@unbrained/pm-cli 2026.9.6 → 2026.9.8
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/.agents/skills/pm-developer/SKILL.md +12 -4
- package/.agents/skills/pm-developer/references/MULTI_AGENT_MERGE.md +19 -10
- package/.agents/skills/pm-extensions/SKILL.md +6 -0
- package/.agents/skills/pm-sdk/SKILL.md +11 -2
- package/.agents/skills/pm-user/SKILL.md +5 -0
- package/.agents/skills/pm-user/references/ECOSYSTEM_PLANNING.md +95 -0
- package/.claude-plugin/marketplace.json +2 -2
- package/CHANGELOG.md +218 -182
- package/dist/cli/after-command-context-usage.js +1 -48
- package/dist/cli/argv-utils.js +1 -40
- package/dist/cli/bootstrap-args.js +1 -9
- package/dist/cli/bundle-integrity.js +2 -110
- package/dist/cli/commander-usage.js +11 -771
- package/dist/cli/commands/activity.js +1 -9
- package/dist/cli/commands/aggregate.js +1 -5
- package/dist/cli/commands/append.js +1 -5
- package/dist/cli/commands/claim.js +1 -5
- package/dist/cli/commands/close-many.js +1 -5
- package/dist/cli/commands/close.js +1 -9
- package/dist/cli/commands/comments.js +1 -5
- package/dist/cli/commands/config.js +1 -9
- package/dist/cli/commands/context.js +1 -9
- package/dist/cli/commands/contracts.js +1 -5
- package/dist/cli/commands/copy.js +1 -9
- package/dist/cli/commands/create.js +1 -9
- package/dist/cli/commands/delete.js +1 -9
- package/dist/cli/commands/deps.js +1 -9
- package/dist/cli/commands/docs.js +1 -9
- package/dist/cli/commands/duplicates.js +1 -9
- package/dist/cli/commands/eval.js +1 -9
- package/dist/cli/commands/extension/describe.js +1 -5
- package/dist/cli/commands/extension/scaffold.js +1 -5
- package/dist/cli/commands/extension/shared.js +1 -5
- package/dist/cli/commands/extension.js +1 -9
- package/dist/cli/commands/files.js +1 -9
- package/dist/cli/commands/focus.js +1 -9
- package/dist/cli/commands/gc.js +1 -9
- package/dist/cli/commands/get.js +1 -9
- package/dist/cli/commands/graph.js +1 -10
- package/dist/cli/commands/health.js +1 -9
- package/dist/cli/commands/history-compact.js +1 -10
- package/dist/cli/commands/history-redact.js +1 -11
- package/dist/cli/commands/history-repair.js +1 -10
- package/dist/cli/commands/history.js +1 -5
- package/dist/cli/commands/index.js +1 -58
- package/dist/cli/commands/init-agent-guidance.js +1 -9
- package/dist/cli/commands/init.js +1 -9
- package/dist/cli/commands/learnings.js +1 -5
- package/dist/cli/commands/lifecycle-transitions.js +1 -5
- package/dist/cli/commands/list.js +1 -9
- package/dist/cli/commands/merge.js +1 -11
- package/dist/cli/commands/next.js +1 -9
- package/dist/cli/commands/notes.js +1 -5
- package/dist/cli/commands/plan.js +1 -9
- package/dist/cli/commands/profile.js +1 -9
- package/dist/cli/commands/restore.js +1 -9
- package/dist/cli/commands/scheduling-shortcuts.js +1 -9
- package/dist/cli/commands/schema.js +1 -10
- package/dist/cli/commands/search.js +1 -9
- package/dist/cli/commands/stats.js +1 -9
- package/dist/cli/commands/telemetry.js +1 -9
- package/dist/cli/commands/test-all.js +1 -9
- package/dist/cli/commands/test-runs.js +1 -9
- package/dist/cli/commands/test.js +1 -9
- package/dist/cli/commands/update-many.js +1 -5
- package/dist/cli/commands/update.js +1 -9
- package/dist/cli/commands/upgrade.js +1 -5
- package/dist/cli/commands/validate.js +1 -15
- package/dist/cli/context-intent-invocation.js +1 -20
- package/dist/cli/description-stdin.js +1 -17
- package/dist/cli/error-guidance.js +1 -1353
- package/dist/cli/extension-command-help.js +5 -636
- package/dist/cli/extension-command-options.js +1 -427
- package/dist/cli/extension-recovery.js +1 -126
- package/dist/cli/help-content.js +2 -1001
- package/dist/cli/help-json-payload.js +4 -570
- package/dist/cli/main.d.ts +4 -0
- package/dist/cli/main.js +5 -2573
- package/dist/cli/migration-gates.js +1 -289
- package/dist/cli/public.js +1 -20
- package/dist/cli/register-annotations.js +1 -270
- package/dist/cli/register-assurance.js +1 -62
- package/dist/cli/register-files-lookup.js +1 -56
- package/dist/cli/register-history-activity.d.ts +8 -0
- package/dist/cli/register-history-activity.js +2 -0
- package/dist/cli/register-history-author.js +1 -38
- package/dist/cli/register-history-maintenance.d.ts +9 -0
- package/dist/cli/register-history-maintenance.js +2 -0
- package/dist/cli/register-list-query.js +10 -943
- package/dist/cli/register-mutation-options.js +1 -9
- package/dist/cli/register-mutation.js +19 -1893
- package/dist/cli/register-operations.js +1 -920
- package/dist/cli/register-setup.js +1 -716
- package/dist/cli/register-structured-mutation.js +1 -196
- package/dist/cli/registration-helpers.js +1 -5
- package/dist/cli/runtime-compatibility-boundary.js +4 -42
- package/dist/cli/schema-registration-helpers.js +1 -73
- package/dist/cli/search-refresh.js +1 -13
- package/dist/cli/stats-analytics-json.js +1 -68
- package/dist/cli/telemetry-flush.js +1 -10
- package/dist/cli-bundle/bundle-manifest.json +164 -156
- package/dist/cli-bundle/chunks/chunk-3BZZA6A3.js +5 -0
- package/dist/cli-bundle/chunks/chunk-AMRDVX36.js +235 -0
- package/dist/cli-bundle/chunks/chunk-DAM4CBBR.js +2202 -0
- package/dist/cli-bundle/chunks/{chunk-WYRZZ5ZE.js → chunk-DEZPZOQ7.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-FLDWYEND.js +77 -0
- package/dist/cli-bundle/chunks/{chunk-NPN5I67J.js → chunk-G5ADGQ2D.js} +3 -3
- package/dist/cli-bundle/chunks/chunk-JAAEYHUA.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-JX4DH4WC.js → chunk-KR3RP4FH.js} +3 -3
- package/dist/cli-bundle/chunks/chunk-LEZOUXG6.js +2 -0
- package/dist/cli-bundle/chunks/chunk-NSAPNEYH.js +2 -0
- package/dist/cli-bundle/chunks/chunk-QOEKOECV.js +29 -0
- package/dist/cli-bundle/chunks/chunk-RHSFOMHU.js +2 -0
- package/dist/cli-bundle/chunks/chunk-XOD2PCB6.js +20 -0
- package/dist/cli-bundle/chunks/{chunk-JT6XF6GE.js → chunk-YVEQ2AMO.js} +4 -4
- package/dist/cli-bundle/chunks/register-list-query-KSK3R63M.js +11 -0
- package/dist/cli-bundle/chunks/register-mutation-IQ5C7U6O.js +20 -0
- package/dist/cli-bundle/chunks/{register-operations-I5W3KMGB.js → register-operations-DWVHR2NC.js} +2 -2
- package/dist/cli-bundle/chunks/register-setup-BQ5SVD4B.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-3WRPWLA7.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-7MBUII7U.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-COPBO5HW.js +8 -0
- package/dist/cli-bundle/focused-chunks/chunk-DUN4IXYN.js +20 -0
- package/dist/cli-bundle/focused-chunks/{chunk-LIJIA4TY.js → chunk-EE5QSM4Z.js} +3 -3
- package/dist/cli-bundle/focused-chunks/chunk-HJVARYM3.js +6 -0
- package/dist/cli-bundle/focused-chunks/chunk-IAUOUGVR.js +177 -0
- package/dist/cli-bundle/focused-chunks/chunk-KOOMJ54F.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-MZDXX7JY.js +56 -0
- package/dist/cli-bundle/focused-chunks/{chunk-M6PBRFSH.js → chunk-OPFHFGDD.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-QHNETP77.js +9 -0
- package/dist/cli-bundle/focused-chunks/{chunk-3BZEOXLT.js → chunk-RMWES4M6.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-RXT4P5QH.js +10 -0
- package/dist/cli-bundle/focused-chunks/chunk-SDOL6FM2.js +12 -0
- package/dist/cli-bundle/focused-chunks/chunk-SQV4AAUC.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-PEFABF7E.js → chunk-WE3IUNIW.js} +3 -3
- package/dist/cli-bundle/focused-chunks/chunk-YALOUBWJ.js +2 -0
- package/dist/cli-bundle/main.js +20 -20
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +2 -2
- package/dist/cli-bundle/sdk-core.js +29 -29
- 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 +42 -42
- 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 +11 -11
- package/dist/cli.js +1 -104
- package/dist/core/checkpoint/checkpoint-gc.js +1 -169
- package/dist/core/checkpoint/mutation-checkpoint.js +2 -133
- package/dist/core/config/nested-settings.js +1 -534
- package/dist/core/config/positional-value.js +1 -109
- package/dist/core/diagnostics/remediation.js +1 -506
- package/dist/core/extensions/activation-summary-markdown.js +2 -145
- package/dist/core/extensions/activation-summary.js +1 -92
- package/dist/core/extensions/activation-transaction.js +1 -46
- package/dist/core/extensions/capability-usage.js +1 -173
- package/dist/core/extensions/command-hook-context.js +1 -13
- package/dist/core/extensions/command-metadata-contract.js +1 -22
- package/dist/core/extensions/command-visibility-tier.js +1 -29
- package/dist/core/extensions/contribution-inventory.js +1 -173
- package/dist/core/extensions/exporter-output-contract.js +1 -66
- package/dist/core/extensions/extension-candidate.js +1 -18
- package/dist/core/extensions/extension-capability-aliases.js +1 -158
- package/dist/core/extensions/extension-hook-runtime.js +1 -699
- package/dist/core/extensions/extension-policy.js +1 -599
- package/dist/core/extensions/extension-registries.js +1 -62
- package/dist/core/extensions/extension-runtime-helpers.js +1 -33
- package/dist/core/extensions/extension-types.js +1 -102
- package/dist/core/extensions/flag-definition-validation.js +1 -52
- package/dist/core/extensions/flag-value-types.js +1 -64
- package/dist/core/extensions/index.js +1 -526
- package/dist/core/extensions/item-field-types.js +1 -39
- package/dist/core/extensions/item-fields.js +1 -261
- package/dist/core/extensions/loader.js +1 -2223
- package/dist/core/extensions/manifest-schema.js +1 -69
- package/dist/core/extensions/module-graph-snapshot.js +1 -33
- package/dist/core/extensions/preflight-ownership.js +1 -41
- package/dist/core/extensions/registration-validation.js +1 -82
- package/dist/core/extensions/registration-values.js +1 -209
- package/dist/core/extensions/reserved-host-flags.js +1 -36
- package/dist/core/extensions/runtime-registrations.js +1 -67
- package/dist/core/extensions/service-ownership.js +1 -19
- package/dist/core/extensions/version-compat.js +1 -216
- package/dist/core/fs/fs-utils.js +2 -158
- package/dist/core/fs/host-environment-errors.js +1 -141
- package/dist/core/fs/index.js +1 -9
- package/dist/core/fs/path-utils.js +1 -17
- package/dist/core/governance/content-fields.js +1 -160
- package/dist/core/governance/issue-codes.js +1 -151
- package/dist/core/governance/metadata-coverage.js +1 -358
- package/dist/core/history/drift-cache.js +3 -72
- package/dist/core/history/drift-scan.js +1 -342
- package/dist/core/history/event-classification.js +1 -109
- package/dist/core/history/event-index.js +8 -784
- package/dist/core/history/history-compact-bulk.js +1 -104
- package/dist/core/history/history-diff.js +1 -158
- package/dist/core/history/history-rewrite.d.ts +6 -1
- package/dist/core/history/history-rewrite.js +1 -107
- package/dist/core/history/history-storage-stats.js +1 -102
- package/dist/core/history/history-stream-policy.js +1 -62
- package/dist/core/history/history.js +2 -617
- package/dist/core/history/identity.js +1 -30
- package/dist/core/history/index.js +1 -9
- package/dist/core/history/projection.js +1 -196
- package/dist/core/history/read.d.ts +9 -0
- package/dist/core/history/read.js +1 -57
- package/dist/core/history/replay.js +2 -439
- package/dist/core/history/version-address.js +1 -32
- package/dist/core/history/workspace-history.js +2 -433
- package/dist/core/io/body-file.js +1 -62
- package/dist/core/io/bulk-ids-input.js +1 -112
- package/dist/core/item/actionability.js +1 -327
- package/dist/core/item/dependency-reference.js +1 -20
- package/dist/core/item/id.js +1 -112
- package/dist/core/item/index.js +1 -12
- package/dist/core/item/item-format-version.js +1 -78
- package/dist/core/item/item-format.js +5 -1473
- package/dist/core/item/item-record.js +1 -23
- package/dist/core/item/item-type-definition.js +1 -133
- package/dist/core/item/parent-reference-policy.js +1 -57
- package/dist/core/item/parse.js +2 -603
- package/dist/core/item/plan-lifecycle.js +1 -19
- package/dist/core/item/priority.js +1 -61
- package/dist/core/item/sprint-release-format.js +1 -38
- package/dist/core/item/status-filter.js +1 -115
- package/dist/core/item/status.js +1 -43
- package/dist/core/item/toon-decode.js +1 -29
- package/dist/core/item/type-registry.js +1 -715
- package/dist/core/item/type-synonyms.js +1 -38
- package/dist/core/lock/index.js +1 -9
- package/dist/core/lock/lock-gc.js +1 -240
- package/dist/core/lock/lock.js +3 -590
- package/dist/core/output/mutation-projection.js +1 -217
- package/dist/core/output/output-control.js +1 -25
- package/dist/core/output/output.js +11 -494
- package/dist/core/output/query-summary.js +1 -58
- package/dist/core/output/tabular.js +1 -77
- package/dist/core/packages/manifest.js +1 -244
- package/dist/core/packages/root.js +1 -84
- package/dist/core/profile/profile-describe.js +1 -83
- package/dist/core/profile/profile-lint.js +1 -415
- package/dist/core/profile/profile-plan.js +0 -0
- package/dist/core/profile/profile-presets.js +1 -370
- package/dist/core/reproducibility/context.js +1 -82
- package/dist/core/schema/fields-file.js +2 -288
- package/dist/core/schema/item-types-file.js +2 -296
- package/dist/core/schema/runtime-field-filters.js +1 -49
- package/dist/core/schema/runtime-field-values.js +1 -313
- package/dist/core/schema/runtime-schema.js +2 -826
- package/dist/core/schema/status-defs-file.js +2 -227
- package/dist/core/schema/status-token.js +1 -31
- package/dist/core/schema/type-inference.js +1 -95
- package/dist/core/schema/type-presets.js +1 -87
- package/dist/core/schema/type-workflows.js +1 -104
- package/dist/core/search/background-refresh.js +2 -286
- package/dist/core/search/bm25.js +1 -146
- package/dist/core/search/cache.js +2 -534
- package/dist/core/search/corpus.js +1 -311
- package/dist/core/search/embedding-batches.js +1 -163
- package/dist/core/search/eval.js +1 -225
- package/dist/core/search/http-client.js +1 -75
- package/dist/core/search/providers.js +1 -242
- package/dist/core/search/relevance.js +1 -244
- package/dist/core/search/semantic-defaults.js +1 -199
- package/dist/core/search/staleness.js +1 -30
- package/dist/core/search/vector-stores.js +2 -664
- package/dist/core/search/vectorization-metadata.js +1 -81
- package/dist/core/sentry/helpers.js +1 -272
- package/dist/core/sentry/instrument.js +1 -387
- package/dist/core/session/session-state.js +1 -260
- package/dist/core/shared/agent-session-context.js +1 -133
- package/dist/core/shared/author.js +1 -1172
- package/dist/core/shared/command-types.js +1 -4
- package/dist/core/shared/conflict-markers.js +1 -31
- package/dist/core/shared/constants.js +1 -405
- package/dist/core/shared/errors.js +1 -20
- package/dist/core/shared/html-entity-decode.js +1 -131
- package/dist/core/shared/index.js +1 -12
- package/dist/core/shared/item-metadata-contract.js +1 -89
- package/dist/core/shared/lazy-module.js +1 -16
- package/dist/core/shared/levenshtein.js +1 -61
- package/dist/core/shared/memo.js +1 -19
- package/dist/core/shared/numeric-parsers.js +1 -20
- package/dist/core/shared/option-alias-visibility.js +1 -67
- package/dist/core/shared/primitives.js +1 -127
- package/dist/core/shared/serial-queue.js +1 -79
- package/dist/core/shared/serialization.js +1 -210
- package/dist/core/shared/split-comma-list.js +1 -30
- package/dist/core/shared/text-normalization.js +1 -38
- package/dist/core/shared/time.js +1 -306
- package/dist/core/store/index.js +1 -12
- package/dist/core/store/item-format-migration.js +1 -125
- package/dist/core/store/item-metadata-cache.js +1 -1116
- package/dist/core/store/item-metadata-query-index.js +9 -394
- package/dist/core/store/item-metadata-read-work.js +1 -43
- package/dist/core/store/item-store.js +1 -693
- package/dist/core/store/paths.d.ts +1 -1
- package/dist/core/store/paths.js +1 -214
- package/dist/core/store/settings-read-cache.js +1 -85
- package/dist/core/store/settings-validator.js +1 -421
- package/dist/core/store/settings.js +3 -1309
- package/dist/core/store/tracker-preflight.js +1 -141
- package/dist/core/telemetry/consent.js +5 -108
- package/dist/core/telemetry/observability.js +1 -246
- package/dist/core/telemetry/runtime.js +4 -1988
- package/dist/core/test/background-runs.js +4 -945
- package/dist/core/test/item-test-run-tracking.js +1 -63
- package/dist/core/test/run-selectors.js +1 -120
- package/dist/core/validate/estimate-defaults.js +1 -89
- package/dist/core/validate/fix-planning.js +1 -189
- package/dist/core/validate/linked-artifact-reference.js +1 -36
- package/dist/core/validate/missing-by-type.js +1 -34
- package/dist/core/validate/missing-link-owners.js +1 -95
- package/dist/core/validate/stale-file-classification.js +1 -82
- package/dist/mcp/http-server.js +5 -448
- package/dist/mcp/legacy-adapter.js +1 -77
- package/dist/mcp/runtime-capabilities.js +1 -200
- package/dist/mcp/server.js +4 -1233
- package/dist/mcp/tool-definitions.js +1 -804
- package/dist/sdk/actionability.js +1 -13
- package/dist/sdk/agent/closed-domain-contracts.js +1 -161
- package/dist/sdk/agent/command-recovery.js +1 -59
- package/dist/sdk/agent/command-suggestions.js +1 -66
- package/dist/sdk/agent/create-option-policy.js +1 -31
- package/dist/sdk/agent/identity-config.js +1 -106
- package/dist/sdk/agent/item-addressing.js +1 -207
- package/dist/sdk/agent/refusal-closure-census.js +1 -151
- package/dist/sdk/agent/refusal-closure.js +1 -133
- package/dist/sdk/agent/refusal-corpus-contracts.js +1 -193
- package/dist/sdk/agent/refusal-reachability.js +1 -593
- package/dist/sdk/agent/subcommand-recovery.js +1 -83
- package/dist/sdk/agent/task-transcript-contracts.js +1 -197
- package/dist/sdk/agent/tracker-preflight-contracts.js +1 -126
- package/dist/sdk/agent-capability-contracts.js +1 -428
- package/dist/sdk/agent-session-context.js +1 -9
- package/dist/sdk/annotations.js +1 -448
- package/dist/sdk/author-attribution.js +1 -468
- package/dist/sdk/authoring.js +1 -20
- package/dist/sdk/cli-bootstrap.js +1 -838
- package/dist/sdk/cli-contracts/agent-output-contracts.d.ts +1 -1
- package/dist/sdk/cli-contracts/agent-output-contracts.js +4 -476
- package/dist/sdk/cli-contracts/bootstrap-command-scanner.js +1 -79
- package/dist/sdk/cli-contracts/command-aliases.d.ts +4 -0
- package/dist/sdk/cli-contracts/command-aliases.js +1 -107
- package/dist/sdk/cli-contracts/command-exit-contracts.js +1 -151
- package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1081
- package/dist/sdk/cli-contracts/commander-types.js +1 -159
- package/dist/sdk/cli-contracts/completeness.js +1 -393
- package/dist/sdk/cli-contracts/enum-contracts.js +1 -222
- package/dist/sdk/cli-contracts/flag-contracts.js +1 -1947
- package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -347
- package/dist/sdk/cli-contracts/grammar-contracts.js +1 -986
- package/dist/sdk/cli-contracts/registration-helpers.js +7 -990
- package/dist/sdk/cli-contracts/runtime-contracts.d.ts +5 -0
- package/dist/sdk/cli-contracts/runtime-contracts.js +1 -2090
- package/dist/sdk/cli-contracts/schemas/assurance-definition.js +1 -324
- package/dist/sdk/cli-contracts/string-lists.js +1 -16
- package/dist/sdk/cli-contracts/tool-option-contracts.js +1 -461
- package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -2167
- package/dist/sdk/cli-contracts/tool-schema.d.ts +3 -1
- package/dist/sdk/cli-contracts/tool-schema.js +1 -1664
- package/dist/sdk/cli-contracts/typed-action-inputs.js +1 -4
- package/dist/sdk/cli-contracts.d.ts +1 -1
- package/dist/sdk/cli-contracts.js +1 -17
- package/dist/sdk/cli-program.js +1 -49
- package/dist/sdk/command-line.d.ts +2 -5
- package/dist/sdk/command-line.js +1 -78
- package/dist/sdk/comments.js +1 -133
- package/dist/sdk/compile-cache.js +1 -73
- package/dist/sdk/completion.js +157 -837
- package/dist/sdk/compose.js +1 -1090
- package/dist/sdk/config.js +1 -1204
- package/dist/sdk/context/recency.js +1 -33
- package/dist/sdk/context/semantic-session-attribution.js +1 -82
- package/dist/sdk/context/usage-egress.js +1 -29
- package/dist/sdk/context/usage-ledger.js +3 -185
- package/dist/sdk/context-intent-contracts.js +1 -709
- package/dist/sdk/context-intent-runtime.js +1 -115
- package/dist/sdk/context-packing.js +1 -218
- package/dist/sdk/context-relevance.js +1 -503
- package/dist/sdk/context-signal-store.js +2 -426
- package/dist/sdk/context-usage.js +1 -367
- package/dist/sdk/contracts.js +1 -23
- package/dist/sdk/core-governance.js +1 -14
- package/dist/sdk/core.js +1 -14
- package/dist/sdk/corpus-shape.js +1 -401
- package/dist/sdk/define.js +1 -220
- package/dist/sdk/dependencies.js +1 -718
- package/dist/sdk/dependency-flag-validation.js +1 -156
- package/dist/sdk/dependency-provenance.js +1 -135
- package/dist/sdk/docs.js +1 -14
- package/dist/sdk/duplicates.js +1 -40
- package/dist/sdk/environment/agent-environment.js +1 -466
- package/dist/sdk/environment/host-environment-errors.js +1 -8
- package/dist/sdk/environment/project-runtime-compatibility.js +1 -481
- package/dist/sdk/environment/source-context.js +1 -28
- package/dist/sdk/environment/tracker-preflight.js +1 -9
- package/dist/sdk/error-code-catalog.js +1 -153
- package/dist/sdk/error-runtime.js +1 -58
- package/dist/sdk/errors.js +1 -58
- package/dist/sdk/eval.js +1 -190
- package/dist/sdk/extension/author-manifest.js +1 -92
- package/dist/sdk/extension/bundled-catalog.js +1 -332
- package/dist/sdk/extension/concurrency.js +1 -25
- package/dist/sdk/extension/copy-scope.d.ts +2 -0
- package/dist/sdk/extension/copy-scope.js +2 -0
- package/dist/sdk/extension/custom-field-collisions.js +1 -30
- package/dist/sdk/extension/describe.js +3 -189
- package/dist/sdk/extension/doctor.js +1 -606
- package/dist/sdk/extension/install-plan.d.ts +69 -0
- package/dist/sdk/extension/install-plan.js +2 -0
- package/dist/sdk/extension/install-receipts.d.ts +7 -0
- package/dist/sdk/extension/install-receipts.js +2 -0
- package/dist/sdk/extension/install-runtime.js +3 -313
- package/dist/sdk/extension/install-snapshot.js +1 -66
- package/dist/sdk/extension/install-sources.js +5 -1057
- package/dist/sdk/extension/managed-state.js +2 -252
- package/dist/sdk/extension/migrations.js +2 -174
- package/dist/sdk/extension/output-ownership.js +1 -25
- package/dist/sdk/extension/runtime-summary.js +1 -18
- package/dist/sdk/extension/scaffold.js +4 -2308
- package/dist/sdk/extension/shared.js +1 -147
- package/dist/sdk/extension/source-resolution.js +1 -65
- package/dist/sdk/extension/update-check.js +1 -67
- package/dist/sdk/extension-command-context.js +1 -44
- package/dist/sdk/extension-contracts.js +1 -73
- package/dist/sdk/extension.d.ts +7 -2
- package/dist/sdk/extension.js +1 -2196
- package/dist/sdk/files.js +1 -535
- package/dist/sdk/flag-invocation-contracts.d.ts +0 -5
- package/dist/sdk/flag-invocation-contracts.js +1 -344
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -2224
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -2236
- package/dist/sdk/generated-error-code-catalog.js +1 -16
- package/dist/sdk/governance/assurance-action-contracts.js +1 -4
- package/dist/sdk/governance/assurance-action.js +1 -411
- package/dist/sdk/governance/assurance-limits.js +1 -10
- package/dist/sdk/governance/assurance-mutation-error.js +1 -81
- package/dist/sdk/governance/assurance-presets.js +1 -135
- package/dist/sdk/governance/assurance-runtime.js +1 -238
- package/dist/sdk/governance/assurance.js +4 -1182
- package/dist/sdk/governance/boundary-fixtures.js +1 -200
- package/dist/sdk/governance/coverage-assurance.js +1 -60
- package/dist/sdk/governance/defect-recurrence-coverage.js +1 -188
- package/dist/sdk/governance/defect-recurrence-graph.js +1 -120
- package/dist/sdk/governance/defect-recurrence-signals.js +1 -24
- package/dist/sdk/governance/defect-recurrence.js +1 -623
- package/dist/sdk/governance/extension-host-version.js +1 -115
- package/dist/sdk/governance/gc.js +1 -368
- package/dist/sdk/governance/health.js +1 -2367
- package/dist/sdk/governance/hierarchy-validation.js +1 -108
- package/dist/sdk/governance/linked-file-report.js +1 -71
- package/dist/sdk/governance/merge-receipt-history.js +1 -206
- package/dist/sdk/governance/provenance-health.js +1 -282
- package/dist/sdk/governance/reindex.js +4 -761
- package/dist/sdk/governance/stale-work.js +1 -82
- package/dist/sdk/governance/status-role-diagnostics.js +1 -35
- package/dist/sdk/governance/storage-integrity.js +1 -280
- package/dist/sdk/governance/tracked-runtime-cache.js +1 -106
- package/dist/sdk/governance/upgrade.js +2 -327
- package/dist/sdk/governance/validate-history-drift.js +1 -81
- package/dist/sdk/governance/validate-item-reader.js +1 -17
- package/dist/sdk/governance/validate-normalization.js +1 -36
- package/dist/sdk/governance/validate.js +1 -2261
- package/dist/sdk/governance/workspace-position.js +1 -163
- package/dist/sdk/governance.d.ts +1 -0
- package/dist/sdk/governance.js +1 -31
- package/dist/sdk/graph/adapter.js +1 -181
- package/dist/sdk/graph/analytics.js +1 -474
- package/dist/sdk/graph/assembly.js +1 -377
- package/dist/sdk/graph/cache.js +1 -160
- package/dist/sdk/graph/centrality.js +1 -258
- package/dist/sdk/graph/conformance.js +1 -130
- package/dist/sdk/graph/deadline-scheduling.d.ts +90 -0
- package/dist/sdk/graph/deadline-scheduling.js +2 -0
- package/dist/sdk/graph/durable-cache.d.ts +1 -1
- package/dist/sdk/graph/durable-cache.js +1 -361
- package/dist/sdk/graph/governance-contracts.js +1 -34
- package/dist/sdk/graph/governance.d.ts +13 -1
- package/dist/sdk/graph/governance.js +1 -735
- package/dist/sdk/graph/hierarchy-integrity.js +1 -310
- package/dist/sdk/graph/index.d.ts +3 -2
- package/dist/sdk/graph/index.js +1 -26
- package/dist/sdk/graph/lifecycle-coverage.d.ts +32 -0
- package/dist/sdk/graph/lifecycle-coverage.js +2 -0
- package/dist/sdk/graph/mutation-advisory.js +1 -176
- package/dist/sdk/graph/remediation.js +1 -197
- package/dist/sdk/graph/run.d.ts +15 -1
- package/dist/sdk/graph/run.js +1 -768
- package/dist/sdk/graph/scheduling.js +1 -124
- package/dist/sdk/graph/traversal.js +1 -284
- package/dist/sdk/graph/workspace-relationship-kind-registry.js +1 -27
- package/dist/sdk/graph.js +1 -15
- package/dist/sdk/guide-topics.js +1 -707
- package/dist/sdk/guide.js +1 -279
- package/dist/sdk/history/maintenance.d.ts +71 -0
- package/dist/sdk/history/maintenance.js +2 -0
- package/dist/sdk/history/salvage.js +2 -247
- package/dist/sdk/history/subject.d.ts +19 -0
- package/dist/sdk/history/subject.js +2 -0
- package/dist/sdk/history-analytics.js +1 -282
- package/dist/sdk/history-compact.js +1 -527
- package/dist/sdk/history-mcp.js +1 -68
- package/dist/sdk/history-provenance.js +1 -182
- package/dist/sdk/history-read.js +1 -96
- package/dist/sdk/history-redact.d.ts +1 -14
- package/dist/sdk/history-redact.js +1 -643
- package/dist/sdk/history-repair.d.ts +5 -0
- package/dist/sdk/history-repair.js +1 -657
- package/dist/sdk/improvement-ledger-validation.js +1 -62
- package/dist/sdk/improvement-ledger.js +2 -257
- package/dist/sdk/index.d.ts +4 -0
- package/dist/sdk/index.js +1 -183
- package/dist/sdk/init-agent-guidance.js +2 -496
- package/dist/sdk/init.js +2 -820
- package/dist/sdk/invocation-author.js +1 -39
- package/dist/sdk/item-children.js +1 -90
- package/dist/sdk/item-metadata-index.js +1 -15
- package/dist/sdk/item-schedule.js +1 -27
- package/dist/sdk/item-transaction.js +1 -396
- package/dist/sdk/learnings.js +1 -29
- package/dist/sdk/lifecycle/append.js +2 -53
- package/dist/sdk/lifecycle/claim.d.ts +2 -0
- package/dist/sdk/lifecycle/claim.js +1 -242
- package/dist/sdk/lifecycle/close-many.js +1 -438
- package/dist/sdk/lifecycle/close.js +1 -468
- package/dist/sdk/lifecycle/copy.js +1 -212
- package/dist/sdk/lifecycle/create.js +1 -1949
- package/dist/sdk/lifecycle/delete.js +1 -45
- package/dist/sdk/lifecycle/event-validation-messages.js +1 -91
- package/dist/sdk/lifecycle/focus.js +1 -91
- package/dist/sdk/lifecycle/hierarchy-mutation-lock.js +1 -24
- package/dist/sdk/lifecycle/legacy-none-tokens.js +1 -149
- package/dist/sdk/lifecycle/lifecycle-transitions.js +1 -40
- package/dist/sdk/lifecycle/mcp-actions.d.ts +2 -0
- package/dist/sdk/lifecycle/mcp-actions.js +1 -51
- package/dist/sdk/lifecycle/metadata-normalizers.js +1 -46
- package/dist/sdk/lifecycle/mutation-command-options.js +1 -9
- package/dist/sdk/lifecycle/plan.js +1 -1606
- package/dist/sdk/lifecycle/recurrence-parsers.js +1 -147
- package/dist/sdk/lifecycle/reopen.js +1 -68
- package/dist/sdk/lifecycle/repeatable-metadata-parsers.js +1 -143
- package/dist/sdk/lifecycle/restore.d.ts +1 -0
- package/dist/sdk/lifecycle/restore.js +1 -330
- package/dist/sdk/lifecycle/shared-unset-fields.js +1 -295
- package/dist/sdk/lifecycle/update-many.js +1 -861
- package/dist/sdk/lifecycle/update.js +1 -2136
- package/dist/sdk/lifecycle-completion.js +1 -92
- package/dist/sdk/lifecycle-policy.js +1 -120
- package/dist/sdk/linked-artifacts.js +1 -530
- package/dist/sdk/mcp/apps.js +4 -133
- package/dist/sdk/mcp/authorization.js +1 -404
- package/dist/sdk/mcp/discovery.js +1 -494
- package/dist/sdk/mcp/interactions.js +1 -336
- package/dist/sdk/mcp/protocol.d.ts +7 -0
- package/dist/sdk/mcp/protocol.js +1 -184
- package/dist/sdk/mcp/skills.js +1 -389
- package/dist/sdk/mcp/subscriptions.js +1 -211
- package/dist/sdk/mcp/tasks.js +2 -430
- package/dist/sdk/mcp/transport.js +1 -260
- package/dist/sdk/merge/abandoned-receipts.js +1 -46
- package/dist/sdk/merge/driver.js +1 -212
- package/dist/sdk/merge/index.js +1 -16
- package/dist/sdk/merge/install.js +3 -561
- package/dist/sdk/merge/receipt-file-boundary.js +1 -46
- package/dist/sdk/merge/receipt-operation.js +1 -96
- package/dist/sdk/merge/receipt-schema.js +1 -397
- package/dist/sdk/merge/receipts.js +4 -525
- package/dist/sdk/merge/reconcile.js +1 -352
- package/dist/sdk/merge/three-way.js +3 -775
- package/dist/sdk/merge.js +1 -10
- package/dist/sdk/mutation-events.js +1 -292
- package/dist/sdk/mutation-guard.js +1 -216
- package/dist/sdk/notes.js +1 -139
- package/dist/sdk/output-contracts.js +1 -172
- package/dist/sdk/output-projection.js +1 -430
- package/dist/sdk/output-token-accounting.js +1 -140
- package/dist/sdk/output.js +1 -64
- package/dist/sdk/ownership-source.js +1 -21
- package/dist/sdk/package-import-adapters.js +1 -442
- package/dist/sdk/package-migrations.js +1 -20
- package/dist/sdk/package-runtime-options.js +1 -80
- package/dist/sdk/pagination.js +1 -162
- package/dist/sdk/profile.js +1 -454
- package/dist/sdk/provenance.js +1 -258
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/query/activity.js +1 -401
- package/dist/sdk/query/aggregate.d.ts +16 -0
- package/dist/sdk/query/aggregate.js +1 -390
- package/dist/sdk/query/calendar.js +1 -964
- package/dist/sdk/query/complete-list.js +1 -215
- package/dist/sdk/query/context.js +1 -1702
- package/dist/sdk/query/duplicate-candidates.js +1 -70
- package/dist/sdk/query/get.js +1 -450
- package/dist/sdk/query/history.js +1 -186
- package/dist/sdk/query/item-filter-options.js +1 -9
- package/dist/sdk/query/light-metadata.js +1 -18
- package/dist/sdk/query/list-filter-shared.js +1 -81
- package/dist/sdk/query/list.js +1 -1304
- package/dist/sdk/query/multi-value-filters.js +1 -78
- package/dist/sdk/query/next.js +1 -513
- package/dist/sdk/query/parsers.js +1 -44
- package/dist/sdk/query/projection-contracts.js +1 -184
- package/dist/sdk/query/search-contracts.js +1 -230
- package/dist/sdk/query/search-pagination.js +1 -35
- package/dist/sdk/query/search-rendering.js +1 -105
- package/dist/sdk/query/search.js +2 -1987
- package/dist/sdk/query.js +1 -35
- package/dist/sdk/read-output/continuation.js +1 -194
- package/dist/sdk/read-output-budget.js +1 -135
- package/dist/sdk/read-output-contracts.js +1 -1225
- package/dist/sdk/read-output-rows.js +1 -186
- package/dist/sdk/read-output-session.js +1 -208
- package/dist/sdk/relationship-analytics.js +1 -410
- package/dist/sdk/relationship-context.js +1 -284
- package/dist/sdk/relationship-history.js +4 -519
- package/dist/sdk/relationship-kinds/contract.js +1 -22
- package/dist/sdk/relationship-migration.js +1 -77
- package/dist/sdk/relationships.js +1 -579
- package/dist/sdk/reproducibility/process.js +1 -87
- package/dist/sdk/runtime-action-aliases.js +1 -59
- package/dist/sdk/runtime-extended-actions.js +1 -177
- package/dist/sdk/runtime-input.js +1 -614
- package/dist/sdk/runtime-primitives.js +1 -84
- package/dist/sdk/runtime-public-contracts.js +1 -4
- package/dist/sdk/runtime-stats-options.js +1 -38
- package/dist/sdk/runtime.js +1 -1928
- package/dist/sdk/scheduling-shortcuts.js +1 -63
- package/dist/sdk/schema-migration.js +3 -856
- package/dist/sdk/schema.js +1 -1376
- package/dist/sdk/search-refresh-worker.js +1 -18
- package/dist/sdk/similarity-scoring.js +1 -53
- package/dist/sdk/similarity.js +1 -326
- package/dist/sdk/start-task-status.js +1 -14
- package/dist/sdk/stats.js +1 -270
- package/dist/sdk/structured-mutations.js +1 -580
- package/dist/sdk/telemetry-flush.js +1 -13
- package/dist/sdk/telemetry.js +1 -405
- package/dist/sdk/templates.js +2 -292
- package/dist/sdk/test/batch.js +2 -509
- package/dist/sdk/test/entry.js +1 -70
- package/dist/sdk/test/execution.js +6 -2211
- package/dist/sdk/test/linked-command-detection.js +1 -546
- package/dist/sdk/test/measurements.js +1 -91
- package/dist/sdk/test/parsers.js +1 -545
- package/dist/sdk/test/runs.js +1 -193
- package/dist/sdk/test/trust.js +2 -206
- package/dist/sdk/testing.js +4 -1391
- package/dist/sdk/traceability/runtime-files-lookup.js +1 -32
- package/dist/sdk/traceability/source-traceability.js +1 -292
- package/dist/sdk/tracker-root-discovery.js +1 -9
- package/dist/sdk/workspace-contracts-cache.js +1 -28
- package/dist/sdk/workspace-contracts.js +1 -33
- package/dist/sdk/workspace-memory.js +2 -318
- package/dist/sdk/workspace-recipe.js +1 -71
- package/dist/sdk/workspace-snapshot.js +4 -613
- package/dist/sdk/workspace-transaction-gc.js +1 -149
- package/dist/sdk/workspace-transaction.js +2 -363
- package/dist/sdk/workspace.js +3 -127
- package/dist/types/index.js +1 -9
- package/dist/types.js +1 -245
- package/docs/AGENT_GUIDE.md +1 -1
- package/docs/CONTEXT_ALGORITHM_PORTFOLIO.md +167 -0
- package/docs/DIAGNOSTIC_OUTPUT_CONTRACTS.md +9 -3
- package/docs/EXTENSIONS.md +1 -0
- package/docs/HISTORY_MAINTENANCE.md +125 -0
- package/docs/MCP_2026_07_28_CONFORMANCE.md +20 -10
- package/docs/PACKAGE_EVIDENCE.md +92 -0
- package/docs/PLANNING_MEASUREMENTS.md +183 -0
- package/docs/README.md +3 -0
- package/docs/RELEASING.md +1 -0
- package/docs/SCRIPTING.md +21 -0
- package/docs/TESTING.md +23 -0
- package/docs/generated/FLAG_LEXICON_BUDGETS.md +5 -5
- package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +2 -2
- package/marketplace.json +2 -2
- 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-codex/.codex-plugin/plugin.json +1 -1
- package/scripts/finalize-build.mjs +45 -3
- package/dist/cli-bundle/chunks/chunk-AZDFJGH6.js +0 -9
- package/dist/cli-bundle/chunks/chunk-BAX2BYUW.js +0 -2111
- package/dist/cli-bundle/chunks/chunk-CKOL5U7J.js +0 -77
- package/dist/cli-bundle/chunks/chunk-OF76PSDQ.js +0 -5
- package/dist/cli-bundle/chunks/chunk-QUWFABDM.js +0 -232
- package/dist/cli-bundle/chunks/chunk-QWRRFYK3.js +0 -2
- package/dist/cli-bundle/chunks/chunk-RWWBOWJ5.js +0 -2
- package/dist/cli-bundle/chunks/chunk-WGAOYSYH.js +0 -40
- package/dist/cli-bundle/chunks/chunk-WI2AYPA7.js +0 -2
- package/dist/cli-bundle/chunks/register-list-query-5JL52D33.js +0 -11
- package/dist/cli-bundle/chunks/register-mutation-ZPG7KMVP.js +0 -20
- package/dist/cli-bundle/chunks/register-setup-H4SVAVX7.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-AL5ON6K6.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-CHC2IDXA.js +0 -6
- package/dist/cli-bundle/focused-chunks/chunk-CK6QFAPZ.js +0 -20
- package/dist/cli-bundle/focused-chunks/chunk-EZR3GHFE.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-H2WJWK7L.js +0 -56
- package/dist/cli-bundle/focused-chunks/chunk-NTPY5GSO.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-P5O7MP5Y.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-PDMW2E36.js +0 -177
- package/dist/cli-bundle/focused-chunks/chunk-QTVCLMSZ.js +0 -6
- package/dist/cli-bundle/focused-chunks/chunk-QTZRBUYA.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-SGQST3PQ.js +0 -12
- package/dist/cli-bundle/focused-chunks/chunk-UKHASMMP.js +0 -10
- package/dist/cli-bundle/focused-chunks/chunk-ZPEKQHOC.js +0 -2
|
@@ -1,40 +0,0 @@
|
|
|
1
|
-
import{Da as g_,Ga as h_,Pa as Sa,e as s_,i as _r,j as __,na as ba,q as Lt,s as Vi,t as Yi,u as On,xa as p_,ya as ka,za as Ea}from"./chunk-CKOL5U7J.js";import{Cc as A_,Fc as C_,Ha as u_,Ia as wa,J as mr,K as fr,L as Bi,M as xe,Ma as y_,O as Hi,R as Wi,S as o_,U as va,V as a_,Wa as v_,X as c_,Za as w_,_a as pr,bb as b_,bc as T_,cb as k_,cc as I_,db as E_,e as t_,eb as S_,g as n_,h as zi,i as r_,j as i_,oa as d_,pa as l_,rb as x_}from"./chunk-AZDFJGH6.js";import{$a as Ae,$c as Zl,$d as Sn,$f as Eu,$l as nf,A as oi,Aa as Rl,Ab as zt,Ad as iu,Ae as lu,Ag as Tu,Aj as im,Ak as gm,Al as Om,Am as Tf,B as Gt,Ba as Ol,Bf as fu,Bk as hm,Bl as Dm,Bm as If,C as f,Ca as Dl,Cb as Bl,Cf as _u,Ci as $i,Cl as Lm,Cm as Af,Da as Ho,Df as pu,Dh as Tn,Dk as ym,Dl as Nm,Dm as Cf,E as _,Ee as Qo,Ef as gu,Eh as Nu,El as Mm,Em as Rf,Fc as F,Fe as q,Ff as hu,Fi as Ku,Fj as sm,Fl as Pm,Fm as Of,G as re,Gd as bi,Ge as Ct,Gf as yu,Gh as Mu,Gi as zu,Gl as Fm,Gm as Df,H as kl,He as Rt,Hf as tt,Hh as Pu,Hi as Bu,Hj as om,Hl as $m,Hm as Lf,Id as H,If as vu,Ii as Hu,Ik as vm,Il as jm,Im as Nf,Jd as kn,Jh as In,Jk as wm,Jl as Um,Jm as Mf,Kc as Wl,Kd as En,Kh as na,Kj as ia,Kl as qm,Km as Pf,La as Wo,Lc as Vl,Le as uu,Lh as Fu,Li as Wu,Lk as Ui,Ll as Gm,Lm as pa,Ma as ir,Md as ki,Mh as Ri,Mi as C,Mj as am,Mk as bm,Ml as Km,Mm as Ff,N as El,Na as Ie,Nd as su,Nh as Ht,Ni as Vu,Nl as zm,Oc as Me,Od as ou,Of as wu,Oh as Oi,Oi as Yu,Om as ga,Pc as Yl,Pf as bu,Pl as Bm,Pm as $f,Pn as m_,Qa as U,Qc as Ce,Qd as au,Qf as ea,Ql as fa,Qm as jf,R as T,Ra as ut,Rc as Jl,Rd as Ei,Rh as Di,Rl as Hm,Rm as Uf,Rn as f_,S as Sl,Sa as li,Sc as Xl,Sh as pe,Sl as Wm,Sm as qf,T as yn,Ta as vn,Tc as Ql,Te as ft,Th as Wt,Tl as Vm,Tm as Gf,Ua as sr,Ub as D,Ud as Si,Ug as Iu,Uh as $u,Ui as Ju,Ul as Ym,Um as Dt,V as lt,Va as Kt,Vb as mt,Vd as se,Vi as Xu,Vl as Jm,Vm as Kf,Wb as Ne,Wd as Xo,Wh as An,Wl as Xm,Wm as zf,X as fe,Xd as ue,Xf as ku,Xh as Cn,Xl as Qm,Xm as Bf,Ya as R,Yc as It,Yd as Ge,Yh as ju,Yi as Qu,Yl as Zm,Ym as Hf,Za as Ze,Zc as _i,Zd as cu,Ze as mu,Zi as ji,Zl as ef,_a as et,_c as pi,_i as Zu,_l as tf,_m as Wf,ab as Ll,ae as xi,am as rf,b as We,bb as Nl,be as Ti,bm as sf,c as V,cb as Tt,ci as Ot,cj as $,cm as of,cn as Vf,d as hn,db as ui,dd as gi,di as Uu,dj as X,dk as sa,dm as af,dn as qi,e as j,ea as ai,eb as Ml,ed as hi,eg as ta,ej as ge,ek as oa,em as _a,en as Yf,f as Y,fa as zo,fb as Pl,fd as At,fi as Li,fj as em,fk as aa,fl as la,fm as cf,fn as Gi,g as we,gb as Vo,gd as eu,gh as Au,gi as qu,gj as Rn,gk as ca,gl as km,gm as df,gn as Jf,h as pl,hb as Yo,hd as yi,hh as Cu,hi as Ni,hj as Se,hm as lf,hn as ha,i as gl,ib as Fl,id as tu,ii as Mi,ij as _t,ik as cm,im as uf,ja as xl,jb as $l,jd as te,jh as Ii,ji as Pi,jj as tm,jl as Em,jm as mf,jn as Xf,kb as jl,kd as wn,kh as xn,kj as ur,kl as ua,km as ff,kn as Qf,lb as Ul,ld as ar,li as Fi,ll as Vt,lm as _f,mb as ql,mc as mi,md as be,me as du,mj as nm,mk as da,mm as pf,mn as Zf,nb as Gl,nd as nu,nj as me,nl as Sm,nm as gf,nn as Ki,oc as fi,oi as Gu,om as hf,pa as Bo,pd as qe,pe as cr,pj as ra,pk as dm,pm as yf,qb as or,qd as ru,qe as dr,qh as Ai,qj as rm,rd as Bt,rh as Ru,ri as lr,rk as lm,s as hl,sa as rr,sh as Ou,sk as um,sl as ma,t as yl,ta as Ue,td as vi,tk as mm,tm as vf,tn as ya,ua as ci,ud as bn,uk as fm,ul as xm,um as wf,v as vl,va as di,vd as _e,vl as Tm,vm as bf,wa as Tl,wb as Kl,wd as wi,wh as Du,wl as Im,wm as kf,x as wl,xa as Il,xc as Hl,xf as Zo,xg as Su,xl as Am,xm as Ef,xn as e_,ya as Al,yb as zl,yd as Jo,yg as xu,yh as Ci,yk as _m,yl as Cm,ym as Sf,z as bl,za as Cl,zh as Lu,zk as pm,zl as Rm,zm as xf}from"./chunk-QUWFABDM.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d2d5135a-8110-527e-8530-653b25b792a4")}catch{}})();var N=class extends TypeError{constructor(t){super(t),this.name="AssuranceMutationRefusalError"}},Pe=class extends TypeError{context;constructor(t,n={}){super(t),this.name="AssuranceEvaluationRefusalError",this.context=n}},nt=class extends TypeError{measurement_id;source_kind;field;check;constructor(t,n){super(t),this.name="AssuranceSourceResolutionError",this.measurement_id=n.measurement_id,this.source_kind=n.source_kind,this.field=n.field,this.check=n.check}};async function Dn(e){try{return await e()}catch(t){throw t instanceof N?new _(t.message,f.USAGE,{code:"invalid_argument_value",reason:"assurance_mutation_refused"}):t}}async function R_(e){try{return await e()}catch(t){throw t instanceof Pe?new _(t.message,f.USAGE,{code:"invalid_argument_value",reason:"assurance_evaluation_refused",...t.context}):t}}import{createHash as wk}from"node:crypto";import bk from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b911b43d-d14d-5e4f-a35e-5020b1a84542")}catch{}})();var Ln=1e3;(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d4c380ce-031e-5b2d-aaa8-658bb4aa3087")}catch{}})();var D_=1,pt=["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"],gr=["items","dependency_kind","prose_edge_gap","graph","validate","health","history","links","provider","derived"],kk=["ceiling","floor","equals","zero","monotone_nondecreasing","monotone_nonincreasing","subset_of"],Ek=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,Ji=30,Xi=5e3,L_=4,Sk=50;function gt(e,t){if(!Ek.test(e))throw new N(`${t} must be a stable lowercase id`)}function xk(e,t){if(!Number.isFinite(e)||e<0)throw new N(`${t} must be a finite non-negative number`)}function hr(e){let t=kk.filter(i=>e[i]!==void 0);if(t.length!==1)throw new N(`assertion ${e.id} must declare exactly one polarity`);let n=t[0],r=e[n];return{polarity:n,value:n==="zero"?0:r}}function Ta(e,t){return D(e)===D(t)}function N_(e,t){if(t.polarity==="equals")return Ta(e,t.value);if(t.polarity==="subset_of"){if(!Array.isArray(e)||!Array.isArray(t.value))return!1;let r=t.value;return e.every(i=>r.includes(i))}if(typeof e!="number")return!1;let n=t.value;return t.polarity==="ceiling"||t.polarity==="monotone_nonincreasing"?e<=n:t.polarity==="floor"||t.polarity==="monotone_nondecreasing"?e>=n:e===0}function M_(e){let t=hr(e),n=e.negative_control.cases;return n.some(r=>r.expected==="pass")&&n.some(r=>r.expected==="fail")&&n.every(r=>N_(r.observed,t)===(r.expected==="pass"))}function Tk(e,t){if(e.polarity!==t.polarity)return!0;if(typeof e.value=="number"&&typeof t.value=="number")return e.polarity==="ceiling"||e.polarity==="monotone_nonincreasing"?t.value>e.value:e.polarity==="floor"||e.polarity==="monotone_nondecreasing"?t.value<e.value:t.value!==e.value;if(e.polarity==="subset_of"){let n=e.value,r=t.value;return!Array.isArray(n)||!Array.isArray(r)||r.some(i=>!n.includes(i))}return!Ta(e.value,t.value)}function Ik(e,t){if(e.measurement_id!==t.measurement_id||e.owner_item_id!==t.owner_item_id||D(e.scope)!==D(t.scope))return!0;let n={observe:0,warn:1,block:2},r=(e.lifetime??"hold")==="hold"&&(t.lifetime??"hold")==="retire";return Tk(hr(e),hr(t))||n[t.enforcement]<n[e.enforcement]||r}function Ak(e){if(e.state!==void 0&&!(e.state==="present"||e.state==="missing"))throw new N("items source state must be present or missing");let t=Object.hasOwn(e,"equals"),n=e.state!==void 0,r=Number(t)+Number(n);if(e.field!==void 0&&r!==1)throw new N("items source with field requires exactly one of equals or state");if(e.field===void 0&&r!==0)throw new N("items source equals/state requires field")}function Ck(e){if(typeof e.dependency_kind!="string"||e.dependency_kind.trim().length===0)throw new N("dependency_kind source requires dependency_kind");if([e.source_kind,e.source_kind_prefix,e.source_kind_state].filter(n=>n!==void 0).length>1)throw new N("dependency_kind source accepts at most one source_kind predicate");if(e.source_kind!==void 0&&e.source_kind.trim().length===0||e.source_kind_prefix!==void 0&&e.source_kind_prefix.trim().length===0)throw new N("dependency_kind source provenance values must not be empty");if(e.source_kind_state!==void 0&&e.source_kind_state!=="present"&&e.source_kind_state!=="missing")throw new N("dependency_kind source source_kind_state must be present or missing")}function Rk(e){if(e.sample_limit!==void 0&&(!Number.isInteger(e.sample_limit)||e.sample_limit<1))throw new N("prose_edge_gap sample_limit must be a positive integer");for(let t of e.exemptions??[]){if(typeof t.holder_id!="string"||t.holder_id.trim().length===0||typeof t.reason!="string"||t.reason.trim().length===0)throw new N("prose_edge_gap exemptions require holder_id and reason");if(t.target_id!==void 0&&t.target_id.trim().length===0||t.text_contains!==void 0&&t.text_contains.trim().length===0)throw new N("prose_edge_gap exemption selectors must not be empty")}}function Ia(e){gt(e.id,"measurement.id"),e.max_cost!==void 0&&xk(e.max_cost,"measurement.max_cost");let t=e.source;if(Object.prototype.toString.call(t)!=="[object Object]")throw new N(`measurement.source.kind must be one of ${gr.join(", ")}`);let n=Reflect.get(t,"kind");if(!gr.includes(n))throw new N(`measurement.source.kind must be one of ${gr.join(", ")}`);let r=t;if(r.kind==="items"&&Ak(r),r.kind==="dependency_kind"&&Ck(r),r.kind==="prose_edge_gap"&&Rk(r),(r.kind==="graph"||r.kind==="validate"||r.kind==="health")&&(typeof r.field!="string"||r.field.trim().length===0))throw new N(`${r.kind} source requires field`);return r.kind==="provider"&&(gt(r.provider,"provider source provider"),gt(r.key,"provider source key")),e}function Aa(e){if(gt(e.id,"assertion.id"),gt(e.measurement_id,"assertion.measurement_id"),typeof e.owner_item_id!="string"||e.owner_item_id.trim().length===0)throw new N("assertion.owner_item_id is required");let t=hr(e);if(typeof t.value=="number"&&!Number.isFinite(t.value))throw new N(`assertion.${t.polarity} must be a finite number`);if(e.lifetime==="retire"&&(typeof e.retire_reason!="string"||e.retire_reason.trim().length===0))throw new N("retired assertion requires retire_reason");e.scope.kind==="filter"&>(e.scope.measurement_id,"assertion.scope.measurement_id");let n=e.negative_control?.cases;if(!Array.isArray(n)||!n.some(r=>r.expected==="pass")||!n.some(r=>r.expected==="fail"))throw new N("assertion negative control requires pass and fail cases");if(!M_(e))throw new N(`assertion ${e.id} negative control does not prove its bound`);return e}function Ok(e){if(!Array.isArray(e.allowed_providers))throw new N("gate provider_policy.allowed_providers must be an array");for(let t of e.allowed_providers)gt(t,"gate.provider_policy.allowed_provider");if(typeof e.triggers!="object"||e.triggers===null||Array.isArray(e.triggers))throw new N("gate provider_policy.triggers must be an object");for(let[t,n]of Object.entries(e.triggers)){if(!pt.includes(t))throw new N(`gate provider policy has unknown trigger ${t}`);if(typeof n!="object"||n===null||!["low","medium","high"].includes(n.max_cost_class)||typeof n.allow_network!="boolean")throw new N(`gate provider policy trigger ${t} is invalid`)}}function P_(e){if(gt(e.id,"gate.id"),!Array.isArray(e.assertion_ids))throw new N("gate.assertion_ids is required and must be an array");if(e.assertion_ids.length===0)throw new N("gate requires at least one assertion");for(let t of e.assertion_ids)gt(t,"gate.assertion_id");if(!Array.isArray(e.triggers))throw new N(`gate.triggers is required and must be an array of ${pt.join(", ")}`);if(e.triggers.length===0)throw new N("gate requires at least one trigger");for(let t of e.triggers)if(!pt.includes(t))throw new N(`gate trigger must be one of ${pt.join(", ")}`);return e.provider_policy&&Ok(e.provider_policy),e}function Nn(e){if(e.version!==D_)throw new N(`unsupported assurance document version ${String(e.version)}`);let t=new Set;for(let r of e.measurements){if(Ia(r),t.has(`measurement:${r.id}`))throw new N(`duplicate measurement ${r.id}`);t.add(`measurement:${r.id}`)}for(let r of e.assertions){if(Aa(r),t.has(`assertion:${r.id}`))throw new N(`duplicate assertion ${r.id}`);t.add(`assertion:${r.id}`)}for(let r of e.gates){P_(r);let i=r.assertion_ids.filter(s=>!e.assertions.some(o=>o.id===s));if(i.length>0)throw new N(`gate ${r.id} references missing assertions: ${i.join(", ")}`);if(t.has(`gate:${r.id}`))throw new N(`duplicate gate ${r.id}`);t.add(`gate:${r.id}`)}let n=new Set(e.measurements.map(r=>r.id));for(let[r,i]of F_(e))if(!n.has(r))throw new N(`${i.join(", ")} references missing measurement ${r}`);return e}function Ca(e,t){if("measurement"in e){t.push(e.measurement);return}if("operator"in e)for(let n of e.operands)Ca(n,t)}function F_(e){let t=new Map,n=(r,i)=>{let s=t.get(r)??[];s.push(i),t.set(r,s)};for(let r of e.assertions)n(r.measurement_id,`assertion ${r.id}`),r.scope.kind==="filter"&&n(r.scope.measurement_id,`assertion ${r.id} scope`);for(let r of e.measurements){if(r.source.kind!=="derived")continue;let i=[];Ca(r.source.expression,i);for(let s of i)n(s,`derived measurement ${r.id}`)}return t}function Dk(e,t){let n=e.assertion_ids.flatMap(s=>{let o=t.assertions.find(a=>a.id===s);return[o.measurement_id,...o.scope.kind==="filter"?[o.scope.measurement_id]:[]]}),r=new Set,i=new Set;for(;n.length>0;){let s=n.pop();if(r.has(s))continue;r.add(s);let o=t.measurements.find(a=>a.id===s);o.source.kind==="provider"?i.add(o.source.provider):o.source.kind==="derived"&&Ca(o.source.expression,n)}return i}function yr(){return{version:D_,measurements:[],assertions:[],gates:[]}}function Lk(e,t){let n=t.items.filter(r=>(e.statuses===void 0||e.statuses.includes(r.status))&&(e.types===void 0||e.types.includes(r.type))&&(e.tags===void 0||e.tags.every(i=>r.tags?.includes(i)))&&(e.field===void 0||(()=>{let i=r[e.field];if(e.state!==void 0){let s=i==null||i===""||Array.isArray(i)&&i.length===0;return e.state==="missing"?s:!s}return Ta(i,e.equals)})()));return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(r=>r.id)}}function Nk(e,t){return e.source_kind!==void 0?t?.toLowerCase()===e.source_kind.trim().toLowerCase():e.source_kind_prefix!==void 0?t?.toLowerCase().startsWith(e.source_kind_prefix.trim().toLowerCase())===!0:e.source_kind_state==="present"?t!==void 0&&t.length>0:e.source_kind_state==="missing"?t===void 0||t.length===0:!0}function Mk(e,t){let n=[],r=zt(e.dependency_kind)??e.dependency_kind.trim().toLowerCase();for(let i of t.items)for(let s of i.dependencies??[]){let o=zt(s.kind)??s.kind.trim().toLowerCase(),a=s.source_kind?.trim();o===r&&Nk(e,a)&&n.push(`${i.id}->${s.id}${a?`@${a}`:""}`)}return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n}}function Pk(e){let t=[e.description,e.body].filter(n=>typeof n=="string").map(n=>n.trim()).filter(Boolean);for(let n of["comments","notes","learnings"]){let r=e[n];if(Array.isArray(r)){for(let i of r)if(typeof i=="string")t.push(i);else if(typeof i=="object"&&i!==null){let s=Reflect.get(i,"text");typeof s=="string"&&t.push(s)}}}return t}function Fk(e,t,n,r){return e.some(i=>i.holder_id.trim().toLowerCase()===t.toLowerCase()&&(i.target_id===void 0||i.target_id.trim().toLowerCase()===n.toLowerCase())&&(i.text_contains===void 0||r.toLowerCase().includes(i.text_contains.trim().toLowerCase())))}function xa(e,t){return[e.toLowerCase(),t.toLowerCase()].sort().join("\0")}function $k(e){let t=new Map,n=new Set,r=[],i=/\b[a-z][a-z0-9]*-[a-z0-9]+\b/giu,s=0;for(let o of e){t.set(o.id.toLowerCase(),o.id);for(let a of o.dependencies??[])n.add(xa(o.id,a.id));for(let a of[o.parent,o.blocked_by])typeof a=="string"&&n.add(xa(o.id,a));for(let a of Pk(o)){let c=[...a.matchAll(i)].map(d=>d[0]);s+=c.length,r.push({holder_id:o.id,segment:a,mentioned_ids:c})}}return{canonical_ids:t,linked_pairs:n,prose_mentions:r,mention_count:s}}function jk(e,t){let n=$k(t.items),r=new Map;for(let o of n.prose_mentions){let a=o.mentioned_ids.map(d=>n.canonical_ids.get(d.toLowerCase())).filter(d=>d!==void 0&&d!==o.holder_id),c=[...new Set(a)];for(let d of c){let l=xa(o.holder_id,d);if(n.linked_pairs.has(l)||Fk(e.exemptions??[],o.holder_id,d,o.segment))continue;let u=c.some(m=>m!==d);r.get(l)?.explicit===!0&&!u||r.set(l,{contributor:`${o.holder_id}->${d}|subject=${u?"explicit":"implicit"}`,explicit:u})}}let i=[...r.values()],s=i.map(o=>o.contributor).sort();return{value:s.length,population_size:n.canonical_ids.size,cost:t.items.length+n.linked_pairs.size+n.mention_count,contributors:s.slice(0,e.sample_limit??25),partitions:{explicit_subject:i.filter(o=>o.explicit).length,implicit_subject:i.filter(o=>!o.explicit).length}}}function Uk(e,t){return{value:t.history.filter(r=>(e.op===void 0||r.op===e.op)&&(e.author===void 0||r.author===e.author)&&(e.harness===void 0||r.agent_harness===e.harness)&&(e.model===void 0||r.agent_model===e.model)).length,population_size:t.history.length,cost:t.history.length}}function qk(e,t){let n=t.items.filter(r=>{let i=r[e.link],s=Array.isArray(i)&&i.length>0;return e.state==="present"?s:!s});return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(r=>r.id)}}function Gk(e,t){let n=e.source;return n.kind==="items"?Lk(n,t):n.kind==="dependency_kind"?Mk(n,t):n.kind==="prose_edge_gap"?jk(n,t):n.kind==="history"?Uk(n,t):n.kind==="links"?qk(n,t):null}function $_(e,t){return e.reduce((n,r)=>({units:n.units+r.units,items_scanned:n.items_scanned+r.items_scanned,history_entries:n.history_entries+r.history_entries,provider_calls:n.provider_calls+r.provider_calls,duration_ms:t}),{units:0,items_scanned:0,history_entries:0,provider_calls:0,duration_ms:t})}function Kk(e,t){if(t.length===0)throw new TypeError(`derived ${e} requires operands`);if(e==="add")return t.reduce((n,r)=>n+r,0);if(e==="subtract")return t.slice(1).reduce((n,r)=>n-r,t[0]);if(e==="multiply")return t.reduce((n,r)=>n*r,1);if(e==="divide"){if(t.slice(1).includes(0))throw new TypeError("derived divide cannot divide by zero");return t.slice(1).reduce((n,r)=>n/r,t[0])}return e==="min"?Math.min(...t):Math.max(...t)}async function j_(e,t,n){let r=new Array(e.length),i=0,s=Array.from({length:Math.min(t,e.length)},async()=>{for(;i<e.length;){let o=i;i+=1,r[o]=await n(e[o],o)}});return await Promise.all(s),r}async function U_(e,t,n,r,i){if("literal"in e)return{value:e.literal,costs:[],population_size:0,contributors:[]};if("measurement"in e){let o=n.find(d=>d.id===e.measurement);if(!o)throw new TypeError(`derived measurement references missing ${e.measurement}`);let a=await q_(o,t,n,r,i);if(typeof a.value!="number")throw new TypeError(`derived measurement ${o.id} is not numeric`);let c=i.charged.has(o.id)?[]:[a.cost];return i.charged.add(o.id),{value:a.value,costs:c,population_size:a.population_size,contributors:a.contributors}}let s=await j_(e.operands,L_,o=>U_(o,t,n,r,i));return{value:Kk(e.operator,s.map(o=>o.value)),costs:s.flatMap(o=>o.costs),population_size:Math.max(0,...s.map(o=>o.population_size)),contributors:[...new Set(s.flatMap(o=>o.contributors))]}}async function zk(e,t,n,r,i){Ia(e);let s=Date.now(),o,a=[],c=0;if(e.source.kind==="derived"){let u=await U_(e.source.expression,t,n,[...r,e.id],i);o={value:u.value,population_size:u.population_size,cost:0,contributors:u.contributors},a=u.costs}else{let u=Gk(e,t);u!==null?o=u:(o=await t.external(e.source),c=1)}let d={units:o.cost,items_scanned:e.source.kind==="items"||e.source.kind==="dependency_kind"||e.source.kind==="prose_edge_gap"||e.source.kind==="links"?t.items.length:0,history_entries:e.source.kind==="history"?t.history.length:0,provider_calls:c,duration_ms:Date.now()-s},l=$_([...a,d],Date.now()-s);if(e.max_cost!==void 0&&l.units>e.max_cost)throw new Pe(`measurement ${e.id} exceeded cost ceiling ${e.max_cost} with ${l.units}`);return{id:e.id,definition_fingerprint:`sha256:${wk("sha256").update(D(e)).digest("hex")}`,value:o.value,population_size:o.population_size,cost:l,contributors:o.contributors??[],...o.partitions?{partitions:o.partitions}:{}}}function q_(e,t,n,r,i){if(r.includes(e.id))throw new TypeError(`derived measurement cycle: ${[...r,e.id].join(" -> ")}`);let s=i.cache.get(e.id);if(s)return s;let o=zk(e,t,n,r,i).catch(a=>{if(a instanceof nt&&a.measurement_id===void 0){let c={measurement_id:e.id,source_kind:a.source_kind,field:a.field,...a.check?{check:a.check}:{}},d=new nt(a.message,c);throw d.cause=a,d}throw a});return i.cache.set(e.id,o),o}async function Ra(e,t,n=[e]){return q_(e,t,n,[],{cache:new Map,charged:new Set})}function Bk(e,t){return typeof e!="number"||typeof t.value!="number"?null:t.polarity==="ceiling"||t.polarity==="monotone_nonincreasing"?t.value-e:(t.polarity==="floor"||t.polarity==="monotone_nondecreasing",e-t.value)}function Hk(e,t,n={}){Aa(e);let r=hr(e),i=e.lifetime==="retire"&&n.owner_terminal===!0;return{assertion_id:e.id,measurement_id:e.measurement_id,measurement_definition_fingerprint:t.definition_fingerprint,scope:e.scope,population_size:t.population_size,observed:t.value,bound:r,distance:Bk(t.value,r),verdict:i?"retired":N_(t.value,r)?"pass":"fail",enforcement:e.enforcement,negative_control_proven:M_(e),cost:t.cost,contributors:t.contributors,...t.partitions?{partitions:t.partitions}:{}}}function Wk(e,t,n,r){let i=Dk(e,t);if(i.size===0)return;let s=e.provider_policy,o=s?.triggers[r];if(!s||!o)throw new Pe(`assurance gate ${e.id} refuses provider execution at trigger ${r} without an explicit provider policy`);let a=new Set(s.allowed_providers),c={low:0,medium:1,high:2};for(let d of i){if(!a.has(d))throw new Pe(`assurance gate ${e.id} refuses provider ${d}`);let l=n.provider_capabilities?.[d];if(!l)throw new Pe(`assurance provider ${d} has no declared capabilities`);if(c[l.cost_class]>c[o.max_cost_class])throw new Pe(`assurance gate ${e.id} refuses ${l.cost_class}-cost provider ${d} at trigger ${r}`);if(l.network&&!o.allow_network)throw new Pe(`assurance gate ${e.id} refuses network provider ${d} at trigger ${r}`)}}async function O_(e,t,n,r,i){try{return await Ra(n,r,i)}catch(s){if(s instanceof nt){let o=s.check?` check ${s.check}`:"",a=s.measurement_id??n.id,c=new Pe(`assurance gate ${e} assertion ${t} measurement ${a} source ${s.source_kind}${o} field ${s.field} could not resolve: ${s.message}`,{gate_id:e,assertion_id:t,measurement_id:a,source_kind:s.source_kind,field:s.field,...s.check?{check:s.check}:{}});throw c.cause=s,c}throw s}}async function G_(e,t,n,r){Nn(t);let i=t.gates.find(c=>c.id===e);if(!i)throw new Pe(`assurance gate ${e} not found`);if(!i.triggers.includes(r.trigger))throw new Pe(`assurance gate ${e} does not declare trigger ${r.trigger}`);Wk(i,t,n,r.trigger);let s=await j_(i.assertion_ids,L_,async c=>{let d=t.assertions.find(p=>p.id===c),l=t.measurements.find(p=>p.id===d.measurement_id),u=n;if(d.scope.kind==="active"){let p=new Set(n.terminal_statuses??["closed","canceled"]);u={...n,items:n.items.filter(h=>!p.has(h.status))}}else if(d.scope.kind==="filter"){let p=d.scope.measurement_id,h=t.measurements.find(w=>w.id===p),y=await O_(i.id,d.id,h,n,t.measurements),v=new Set(y.contributors);u={...n,items:n.items.filter(w=>v.has(w.id))}}let m=n.items.find(p=>p.id===d.owner_item_id),g=m!==void 0&&new Set(n.terminal_statuses??["closed","canceled"]).has(m.status);return Hk(d,await O_(i.id,d.id,l,u,t.measurements),{owner_terminal:g})}),o=s.some(c=>c.verdict==="fail"&&c.enforcement==="block"),a=s.some(c=>c.verdict==="fail"&&c.enforcement==="warn");return{gate_id:i.id,tree_id:n.tree_id,trigger:r.trigger,dry_run:r.dry_run===!0,evaluated_at:new Date().toISOString(),verdict:o?"block":a?"warn":"pass",exit_code:o?1:0,assertions:s,assertions_total:s.length,row_contract:{row_keys:["assertions"],jq_selector:".assertions[]"},cost:$_(s.map(c=>c.cost),Math.max(0,...s.map(c=>c.cost.duration_ms)))}}function Qi(e){return bk.join(e,"assurance.json")}async function K_(e){let t=await Y(Qi(e));return t===null?yr():Zi(t)}function Zi(e){try{return Nn(JSON.parse(e))}catch(t){throw new _("The assurance registry is invalid. Repair or restore .agents/pm/assurance.json and retry.",f.GENERIC_FAILURE,{code:"assurance_registry_invalid",reason:String(t),nextSteps:["Restore a valid assurance.json from version control or repair its declaration references.","Run pm assurance list measurement after the repair."]})}}function es(e,t){return t==="measurement"?e.measurements:t==="assertion"?e.assertions:e.gates}function Vk(e,t){e==="measurement"?Ia(t):e==="assertion"?Aa(t):P_(t)}async function vr(e,t){let n=structuredClone(es(await K_(e),t));return{items:n,count:n.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function Oa(e,t,n){let r=es(await K_(e),t).find(i=>i.id===n);if(!r)throw new TypeError(`assurance ${t} ${n} not found`);return structuredClone(r)}async function ts(e,t,n,r={}){Vk(t,n);let i=await C(e),s=q(r.author,i.author_default),o=await Cn({pmRoot:e,filePath:Qi(e),op:`assurance:${t}:put`,author:s,message:r.message,lockTtlSeconds:Ji,lockWaitMs:Xi,mutate:a=>{let c=a===null?yr():Zi(a),d=es(c,t),l=d.findIndex(m=>m.id===n.id),u=l<0?"created":"updated";if(t==="assertion"&&l>=0&&Ik(d[l],n)){let m=n.authorization_decision;if(!m||!r.authorized_decision_ids?.includes(m))throw new N(`loosening assertion ${n.id} requires a verified authorization_decision`)}return l<0?d.push(structuredClone(n)):d[l]=structuredClone(n),Nn(c),{raw:`${JSON.stringify(c,null,2)}
|
|
2
|
-
`,result:{changed:!0,action:u,kind:t,id:n.id}}}});return{...o.result,changed:o.changed}}async function Da(e,t,n={}){let r=yr();r.measurements=structuredClone(t.measurements),r.assertions=structuredClone(t.assertions),r.gates=structuredClone(t.gates),Nn(r);let i=await C(e),s=q(n.author,i.author_default),o=await Cn({pmRoot:e,filePath:Qi(e),op:"assurance:bundle:apply",author:s,message:n.message,lockTtlSeconds:Ji,lockWaitMs:Xi,mutate:a=>{let c=a===null?yr():Zi(a),d=[],l=[],u=(m,g,p)=>{for(let h of g){let y=m.find(v=>v.id===h.id);if(!y){m.push(structuredClone(h)),d.push(`${p}:${h.id}`);continue}if(D(y)!==D(h))throw new N(`assurance bundle refuses to replace divergent ${p} ${h.id}`);l.push(`${p}:${h.id}`)}};return u(c.measurements,r.measurements,"measurement"),u(c.assertions,r.assertions,"assertion"),u(c.gates,r.gates,"gate"),Nn(c),{raw:`${JSON.stringify(c,null,2)}
|
|
3
|
-
`,result:{changed:d.length>0,created_ids:d,unchanged_ids:l}}}});return{...o.result,changed:o.changed}}async function z_(e,t,n,r={}){let i=await C(e),s=q(r.author,i.author_default),o=await Cn({pmRoot:e,filePath:Qi(e),op:`assurance:${t}:remove`,author:s,message:r.message,lockTtlSeconds:Ji,lockWaitMs:Xi,mutate:a=>{let c=a===null?yr():Zi(a);if(t==="measurement"){let u=F_(c).get(n);if(u&&u.length>0)throw new N(`assurance measurement ${n} is referenced by ${u.join(", ")}`)}if(t==="assertion"&&c.gates.some(u=>u.assertion_ids.includes(n)))throw new N(`assurance assertion ${n} is referenced by gate`);let d=es(c,t),l=d.findIndex(u=>u.id===n);if(l<0)throw new N(`assurance ${t} ${n} not found`);return d.splice(l,1),Nn(c),{raw:`${JSON.stringify(c,null,2)}
|
|
4
|
-
`,result:{changed:!0,action:"removed",kind:t,id:n}}}});return{...o.result,changed:o.changed}}async function B_(e,t,n={}){if(t.dry_run)throw new TypeError("dry-run assurance verdicts are not persisted");let r=await C(e);await An({pmRoot:e,op:"assurance:gate:verdict",author:q(n.author,r.author_default),context:{assurance_verdict:t},message:n.message??`Assurance gate ${t.gate_id} returned ${t.verdict}`,lockTtlSeconds:Ji,lockWaitMs:Xi})}async function H_(e,t={}){let n=t.limit??Sk;if(!Number.isInteger(n)||n<1||n>Ln)throw new TypeError(`assurance verdict limit must be an integer from 1 through ${Ln}`);return(await Rt(Wt(e),pe)).reverse().filter(i=>i.op==="assurance:gate:verdict").map(i=>i.context?.assurance_verdict).filter(i=>typeof i=="object"&&i!==null&&"gate_id"in i).filter(i=>t.gate_id===void 0||i.gate_id===t.gate_id).slice(0,n)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="05c29627-6763-5aee-8579-71e563a98780")}catch{}})();var wr=["software-delivery","research","agent-evaluation","operations"];function W_(e,t,n,r,i){return{id:e,measurement_id:t,owner_item_id:n,scope:{kind:"active"},ceiling:r,lifetime:"hold",enforcement:i,negative_control:{cases:[{observed:r,expected:"pass"},{observed:r+1,expected:"fail"}]}}}function ns(e,t,n,r,i){let s=`preset-${e}`,o=i.map(c=>({id:`${s}-missing-${c}`,description:`Active items missing ${c} evidence.`,source:{kind:"links",link:c,state:"missing"}})),a=o.map(c=>W_(`${c.id}-zero`,c.id,r,0,"warn"));return{id:e,title:t,description:n,declarations:{measurements:o,assertions:a,gates:[{id:`${s}-readiness`,description:n,assertion_ids:a.map(c=>c.id),triggers:["ci","scheduled"]}]}}}function rs(e,t){return e==="software-delivery"?ns(e,"Software delivery","Warn when active delivery work lacks executable tests or documentation.",t,["tests","docs"]):e==="research"?ns(e,"Research","Warn when active research work lacks reproducibility files or documentation.",t,["files","docs"]):e==="agent-evaluation"?ns(e,"Agent evaluation","Warn when active evaluation work lacks executable scenarios or recorded artifacts.",t,["tests","files"]):ns(e,"Operations","Warn when active operational work lacks runbook documentation or repair evidence.",t,["docs","files"])}function V_(e,t,n,r={}){return Da(e,rs(t,n).declarations,r)}async function Y_(e,t){let n=new Set(e.terminal_statuses??["closed","canceled"]),r={...e,items:e.items.filter(s=>!n.has(s.status))};return await Promise.all(["files","tests","docs"].map(async s=>{let o={id:`derived-active-missing-${s}`,description:`Observed active items missing ${s} evidence.`,source:{kind:"links",link:s,state:"missing"}},c=(await Ra(o,r)).value,d=W_(`${o.id}-ceiling`,o.id,t,c,"observe"),l=`active-missing-${s}`;return{id:l,population_size:r.items.length,scope:{kind:"active"},observed:c,declarations:{measurements:[o],assertions:[d],gates:[{id:`derived-${l}`,description:`Observe the accepted ${s} evidence baseline.`,assertion_ids:[d.id],triggers:["ci","scheduled"]}]}}}))}function J_(e,t,n={}){return Da(e,{measurements:t.flatMap(r=>r.declarations.measurements),assertions:t.flatMap(r=>r.declarations.assertions),gates:t.flatMap(r=>r.declarations.gates)},n)}async function X_(e,t,n,r={}){let i=t.enforcement==="observe"?"warn":"block";if(t.enforcement==="block"||n!==i)throw new TypeError(`assurance assertion ${t.id} promotion must be ${t.enforcement} -> ${i}`);return ts(e,"assertion",{...t,enforcement:n},{...r,message:r.message??`Promote assurance assertion ${t.id} from ${t.enforcement} to ${n}`})}import ep from"node:fs/promises";import{createRequire as Yk}from"node:module";import Fe from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c21b1a94-1d80-57c0-b090-c4831fc505a2")}catch{}})();function Q_(e,t){let n=Fe.relative(t,e);if(n.length>0&&n!==".."&&!n.startsWith(`..${Fe.sep}`)&&!Fe.isAbsolute(n))return n.split(Fe.sep).join("/");let r=Fe.resolve(e),i=0xcbf29ce484222325n;for(let o=0;o<r.length;o+=1)i^=BigInt(r.charCodeAt(o)),i=BigInt.asUintN(64,i*0x100000001b3n);return`<external>/${i.toString(16).padStart(16,"0")}/${Fe.basename(Fe.dirname(e))}/package.json`}function Jk(e){return e.includes(`${Fe.sep}.pnpm${Fe.sep}`)?"pnpm":e.includes(`${Fe.sep}node_modules${Fe.sep}`)?"npm":"other"}async function Z_(e){try{let t=JSON.parse(await ep.readFile(e,"utf8"));return t.name==="@unbrained/pm-cli"&&typeof t.version=="string"&&t.version.trim().length>0?t.version.trim():void 0}catch{return}}async function La(e){try{return await ep.realpath(e)}catch{return Fe.resolve(e)}}async function tp(e,t,n=xl(import.meta.url,["../../.."])){let r=await La(t),i=await La(Fe.join(n,"package.json")),s=await Z_(i),o=new Map;s!==void 0&&o.set(i,{version:s,path:Q_(i,r),layout:"host",consumers:["pm-cli-host"]});for(let d of e)try{let l=Yk(d.entry_path).resolve("@unbrained/pm-cli/package.json"),u=await La(l),m=await Z_(u);if(m===void 0)continue;let g=u,p=o.get(g);if(p){p.consumers.includes(d.name)||(p.consumers.push(d.name),p.consumers.sort((h,y)=>h.localeCompare(y)));continue}o.set(g,{version:m,path:Q_(u,r),layout:Jk(u),consumers:[d.name]})}catch{}let a=[...o.values()].sort((d,l)=>d.path.localeCompare(l.path)),c=s===void 0?[]:a.filter(d=>d.version!==s);return{host_version:s??null,copies:a,mismatches:c,warnings:c.map(d=>`extension_host_pm_cli_version_skew:${s}:${d.version}:${d.consumers.join("+")}`)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d42d5fb1-eebc-5549-ae88-dc923d9d3696")}catch{}})();var Xk=Symbol("pm.mcp-mutation-transport"),Qk=new Set(["activity","aggregate","context","contracts","deps","files-discover","files-lookup","get","graph","health","history","list","next","search","stats","telemetry","validate"]);function Ma(e){return Xk in e}function ss(e,t){return Ma(e)?nu(t):qe(e,t)}function bj(e,t,n=[]){let r=qe(e,{...e,...t});for(let i of n)Reflect.deleteProperty(r,i);return r}function L(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n:void 0}function ie(e,t){let n=e[t];return typeof n=="string"?n.trim().length>0?n:void 0:typeof n=="number"&&Number.isFinite(n)?String(n):void 0}function kj(e,t){let n=e[t];return typeof n=="string"?n:typeof n=="number"&&Number.isFinite(n)?String(n):void 0}function Mn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Fa(e,t){if(typeof e=="number"){if(!Number.isInteger(e))throw new _(`${t} must be a finite integer.`,f.USAGE);return e}if(typeof e=="string"&&e.trim().length>0){let n=Number(e);if(!Number.isInteger(n))throw new _(`${t} must be a finite integer.`,f.USAGE);return n}}function Ej(e,t){return typeof e.limit=="number"&&Number.isFinite(e.limit)?e.limit:typeof t.limit=="number"&&Number.isFinite(t.limit)?t.limit:L(e,"limit")??L(t,"limit")}function Sj(e){let t=L(e,"outputFormat");return{json:!0,quiet:!0,author:L(e,"author"),path:L(e,"path"),noExtensions:e.noExtensions===!0||e.no_extensions===!0,noPager:!0,outputInclude:L(e,"outputInclude"),outputLimit:ie(e,"outputLimit"),outputBudget:ie(e,"outputBudget"),outputSession:L(e,"outputSession"),outputCursor:L(e,"outputCursor"),outputFormat:t==="json"||t==="toon"?t:void 0}}var Zk=new Set(["tags","blockedBy","blocked_by","skills","fields"]),rp=new Set(["comment","note","learning","reminder","event","dep","depRemove","dep_remove","file","doc","test","unset","addGlob","add_glob","migrate","envSet","env_set","envClear","env_clear"]),eE=new Set([...rp].filter(e=>e!=="file")),tE=new Set(["files","files-discover","docs","test","test-all"]),ip=new Set(["comments","notes","learnings"]);function nE(e,t){if(!(!ip.has(e)||!Object.prototype.hasOwnProperty.call(t,"file")))throw new _(`MCP ${e} does not accept options.file. Pass annotation text in options.add instead.`,f.USAGE,{code:"mcp_annotation_file_unavailable",required:"Pass annotation text as JSON data; MCP annotation actions cannot read server-local files."})}var rE=new Set(["claim","release","start-task","pause-task","close-task"]),iE={list:["status","type","tag","priority","limit","offset"],search:["mode","status","type","tag","priority","limit"],create:["title","type","status","description","body","priority","tags","parent","createMode","create_mode","allowMissingParent","allowDuplicate"],update:["parent","allowMissingParent","completedAt"],copy:["allowDuplicate"],close:["duplicateOf","completedAt"],comments:["ifAbsent"],notes:["ifAbsent"],learnings:["ifAbsent"],upgrade:["scope","dryRun","cliOnly","packagesOnly","repair","tag","packageName"],append:["body"]},sE=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor"];function sp(e,t=""){let n={},r=tE.has(t),i=t==="files"||t==="files-discover"||t==="docs",s=ip.has(t)?eE:rp;for(let[o,a]of Object.entries(e)){if(Array.isArray(a)&&Zk.has(o)){n[o]=a.join(",");continue}if(o==="note"&&i){n[o]=a;continue}if(typeof a=="string"&&s.has(o)){n[o]=[a];continue}if(typeof a=="string"&&r&&(o==="add"||o==="remove")){n[o]=[a];continue}n[o]=a}return n}function oE(e,t,n){let r=L(e,"author");return r!==void 0?r:n!==void 0&&rE.has(n)?L(e,"assignee")??L(t,"assignee"):void 0}function aE(e,t){return t!==void 0&&e.author===void 0?{...e,author:t}:e}function xj(e,t){let n=Mn(e.options)?e.options:void 0,r=El(e.options),i={},s=c=>{r[c]!==void 0||e[c]===void 0||(i[c]=e[c])};for(let c of iE[t??""]??[])s(c);for(let c of sE)s(c);t!==void 0&&Ma(e)&&nE(t,r);let o=sp({...i,...r},t),a=Ma(e)?e:n??e;return ss(a,aE(o,oE(e,o,t)))}function Tj(e){if(e.addNote===void 0)return e;let t={...e};return t.note===void 0&&typeof t.addNote=="string"&&(t.note=t.addNote),delete t.addNote,t}function Ij(e){let t={...e};return t.discoveryNote!==void 0&&t.note===void 0&&typeof t.discoveryNote=="string"&&(t.note=t.discoveryNote),delete t.discover,delete t.discoveryNote,t}function cE(e){let t=[],n=!0;for(let r of e.trim().toLowerCase()){if(r>="a"&&r<="z"||r>="0"&&r<="9"){t.push(r),n=!1;continue}n||(t.push("-"),n=!0)}return t.at(-1)==="-"&&t.pop(),t.join("")}function Aj(e){return!Qk.has(cE(e))}function Cj(e){return e.trim().toLowerCase().split(/\s+/).filter(Boolean).join(" ")}function $a(e){return Array.isArray(e)?e.map(t=>String(t)).filter(t=>t.length>0):[]}function Rj(e,t){let n=new Set(["action","args","author","cwd","fullChangedFields","id","options","path","query","reason","target"]),r={};for(let[s,o]of Object.entries(e))n.has(s)||(r[s]=o);let i={...r,...t};return delete i.args,i}function Oj(e,t){let n=ss(t??{},{...t});return{changedFields:e.fullChangedFields===!0?"full":"compact",idOnly:e.idOnly===!0,runnerOptions:n}}function Pa(e){return{type:ie(e,"filterType"),tag:ie(e,"filterTag"),priority:ie(e,"filterPriority"),deadlineBefore:ie(e,"filterDeadlineBefore"),deadlineAfter:ie(e,"filterDeadlineAfter"),updatedAfter:ie(e,"filterUpdatedAfter"),updatedBefore:ie(e,"filterUpdatedBefore"),createdAfter:ie(e,"filterCreatedAfter"),createdBefore:ie(e,"filterCreatedBefore"),ids:Jo(e.ids),assignee:ie(e,"filterAssignee"),assigneeFilter:ie(e,"filterAssigneeFilter")??ie(e,"filterAssignee_filter"),parent:ie(e,"filterParent"),sprint:ie(e,"filterSprint"),release:ie(e,"filterRelease"),limit:ie(e,"limit"),offset:ie(e,"offset")}}function Na(e){if(typeof e=="string"&&e.trim().length>0)return e;if(Array.isArray(e))return $a(e)}function is(e){if(typeof e=="number"&&Number.isFinite(e)||typeof e=="string"&&e.trim().length>0)return e}function Dj(e){let t=Na(e.kind),n=Na(e.exemptIsolate),r=Na(e.exemptIsolateType);return{...t===void 0?{}:{kind:t},maxDepth:is(e.maxDepth),limit:is(e.limit),after:L(e,"after"),direction:L(e,"direction"),maxPaths:is(e.maxPaths),sample:is(e.sample),...n===void 0?{}:{exemptIsolate:n},...r===void 0?{}:{exemptIsolateType:r},saveBaseline:e.saveBaseline===!0,rebuild:e.rebuild===!0,clear:e.clear===!0,summary:e.summary===!0,...e.full===!0?{full:!0}:{}}}function op(e){let t=f_(e);return e.ids!==void 0&&(t.ids=Jo(e.ids)),t}function Lj(e){return{status:L(e,"filterStatus"),list:Mn(e.list)?op(e.list):Pa(e),reason:L(e,"reason"),resolution:L(e,"resolution"),expectedResult:L(e,"expectedResult")??L(e,"expected_result")??L(e,"expected"),actualResult:L(e,"actualResult")??L(e,"actual_result")??L(e,"actual"),validateClose:L(e,"validateClose")??L(e,"validate_close"),author:L(e,"author"),message:L(e,"message"),force:e.force===!0?!0:void 0,dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:L(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}var dE=new Set(["filterStatus","filterType","filterTag","filterPriority","filterDeadlineBefore","filterDeadlineAfter","filterUpdatedAfter","filterUpdatedBefore","filterCreatedAfter","filterCreatedBefore","filterAssignee","filterAssigneeFilter","filterAssignee_filter","filterParent","filterSprint","filterRelease","ids","list","update","limit","offset","dryRun","dry_run","rollback","checkpoint","noCheckpoint","no_checkpoint"]);function np(e){let t={};for(let[n,r]of Object.entries(e))dE.has(n)||(t[n]=r);return ap(t)}function ap(e){let t=sp(e,"update-many");for(let n of Ui)for(let r of n.keys){let i=t[r];typeof i=="number"&&Number.isFinite(i)&&(t[r]=String(i))}return m_(t)}function Nj(e){if(Mn(e.list)||Mn(e.update)){let t=Mn(e.update)?e.update:np(e),n=ss(e,ap(t));return{status:ie(e,"filterStatus"),list:Mn(e.list)?op(e.list):Pa(e),update:ru(t,n),dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:L(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}return{status:ie(e,"filterStatus"),list:Pa(e),update:ss(e,np(e)),dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:L(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}import{createHash as dp}from"node:crypto";import br from"node:fs/promises";import kr from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b389e521-f689-5895-a5f4-08c3866b3ea3")}catch{}})();function Ke(e,t){throw new _(e,f.USAGE,t)}var lE="2026-07-15T06:22:12.276Z",uE=Date.parse(lE),mE=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],cp=e=>typeof e=="string"?e:"",lp=e=>{let t=e??{},n=cp(t.author).trim().toLowerCase(),r=Number(["","unknown"].includes(n)),i=+(Date.parse(cp(t.ts))>=uE);return mE[r][i]};function up(e,t,n=20,r=new Set,i=!1){let s=[],o=[],a={legacy_unknown:0,actionable_unknown:0},c=Math.max(0,n),d=0,l=0,u=0;for(let[m,g]of t.split(/\r?\n/).entries()){let p;try{p=JSON.parse(g)}catch{continue}d+=1;let h=lp(p);if(h!=="attributed"){if(l+=1,h==="actionable_unknown"&&r.has(`${e}:${m+1}`)){u+=1;continue}a[h]+=1,i&&h==="actionable_unknown"&&o.push({item_id:e,line:m+1}),s.length<c&&s.push({item_id:e,line:m+1})}}return{checked_events:d,unknown_event_count:l,legacy_unknown_event_count:a.legacy_unknown,actionable_unknown_event_count:a.actionable_unknown,acknowledged_actionable_event_count:u,samples:s,samples_truncated:a.legacy_unknown+a.actionable_unknown>s.length,actionable_events:o}}var zj=(e,t,n=20,r=new Set)=>up(e,t,n,r);function mp(e){let t=new Set;for(let n of e.split(/\r?\n/)){let r;try{r=JSON.parse(n)}catch{continue}let s=(typeof r=="object"&&r!==null&&typeof r.context=="object"&&r.context!==null?r.context:{}).author_acknowledgment;if(!(typeof s!="object"||s===null||!Array.isArray(s.events)))for(let o of s.events)typeof o=="object"&&o!==null&&typeof o.item_id=="string"&&Number.isSafeInteger(o.line)&&t.add(`${o.item_id}:${String(o.line)}`)}return t}var Er=async(e,t=20,n=!1)=>{let r=kr.join(e,"history"),i;try{i=(await br.readdir(r)).filter(v=>v.endsWith(".jsonl")).sort((v,w)=>v.localeCompare(w))}catch{i=[]}let s=new Set,o=[],a=[],c=0,d=0,l=0,u=0,m=0,g=0,p="_workspace.jsonl",h=new Set;if(i.includes(p))try{h=mp(await br.readFile(kr.join(r,p),"utf8"))}catch{h=new Set}for(let v of i){let w;try{w=await br.readFile(kr.join(r,v),"utf8")}catch{continue}let E=v.slice(0,-6),S=up(E,w,t-o.length,h,n);c+=1,d+=S.checked_events,l+=S.unknown_event_count,u+=S.legacy_unknown_event_count,m+=S.actionable_unknown_event_count,g+=S.acknowledged_actionable_event_count,S.unknown_event_count>0&&s.add(E),o.push(...S.samples),n&&a.push(...S.actionable_events)}let y=u+m;return{checked_streams:c,checked_events:d,unknown_event_count:l,legacy_unknown_event_count:u,actionable_unknown_event_count:m,acknowledged_actionable_event_count:g,affected_item_ids:[...s].sort((v,w)=>v.localeCompare(w)),samples:o,samples_truncated:y>o.length,...n?{actionable_events:a}:{}}};function fE(e){return[...new Map(e.map(t=>[`${t.item_id}:${t.line}`,{item_id:t.item_id,line:t.line}])).values()].sort((t,n)=>t.item_id.localeCompare(n.item_id)||t.line-n.line)}async function _E(e){try{return mp(await br.readFile(kr.join(e,"history","_workspace.jsonl"),"utf8"))}catch{return new Set}}function pE(e){return(e.item_id===pe||/^[a-z0-9][a-z0-9-]*$/iu.test(e.item_id))&&Number.isSafeInteger(e.line)&&e.line>=1}function gE(e,t,n){let r=n[e.line-1]??"",i;try{i=JSON.parse(r)}catch{Ke(`Unknown-author acknowledgment target ${e.item_id}:${e.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}return lp(i)!=="actionable_unknown"&&Ke(`Author acknowledgment target ${e.item_id}:${e.line} is not an actionable unknown-author event.`,{code:"history_author_acknowledge_target_not_actionable"}),{...e,source_event_hash:dp("sha256").update(r).digest("hex"),disposition:t.has(`${e.item_id}:${e.line}`)?"already_acknowledged":"actionable"}}async function fp(e,t,n){let r=t.events??[],i=+(t.all_actionable===!0)+ +(r.length>0);i===0&&Ke("Specify exactly one selector: events or all_actionable.",{code:"history_author_acknowledge_selector_required"}),i>1&&Ke("Author acknowledgment accepts either explicit events or all_actionable, not both.",{code:"history_author_acknowledge_selector_conflict"}),(!Number.isSafeInteger(n)||n<0)&&Ke("Author acknowledgment coordinate_limit must be a non-negative integer.",{code:"history_author_acknowledge_preview_limit_invalid"});let s=fE(t.all_actionable===!0?(await Er(e,0,!0)).actionable_events:r),o=await _E(e),a=new Map;for(let m of s)if(pE(m)||Ke(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"}),!a.has(m.item_id))try{a.set(m.item_id,(await br.readFile(kr.join(e,"history",`${m.item_id}.jsonl`),"utf8")).split(/\r?\n/u))}catch{Ke(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}let c=s.map(m=>gE(m,o,a.get(m.item_id))),d=t.all_actionable===!0?"all_actionable":"events",l=dp("sha256").update(JSON.stringify({version:1,selection:d,coordinates:c})).digest("hex"),u=c.filter(({disposition:m})=>m==="actionable").length;return{plan:{selection:{kind:d},selected_count:c.length,actionable_count:u,already_acknowledged_count:c.length-u,omitted_count:Math.max(0,c.length-n),coordinates:c.slice(0,n),plan_fingerprint:l},completeCoordinates:c}}async function Bj(e,t,n=50){return(await fp(e,t,n)).plan}function hE(e,t){let n=e.length>0;return n&&t&&Ke("Specify exactly one selector: repeat --event or pass --all-actionable.",{code:"history_author_acknowledge_selector_conflict",required:"Exactly one of --event or --all-actionable",examples:['pm history-author-acknowledge --event pm-a1b2:4 --attributed-author agent --reviewer maintainer --reason "Verified provenance"','pm history-author-acknowledge --all-actionable --attributed-author import-agent --reviewer maintainer --reason "Reviewed the complete actionable set"']}),!n&&!t&&Ke("Specify exactly one selector: repeat --event or pass --all-actionable.",{code:"history_author_acknowledge_selector_required",required:"Exactly one of --event or --all-actionable",examples:['pm history-author-acknowledge --event pm-a1b2:4 --attributed-author agent --reviewer maintainer --reason "Verified provenance"','pm history-author-acknowledge --all-actionable --attributed-author import-agent --reviewer maintainer --reason "Reviewed the complete actionable set"']}),{events:yE(e),all_actionable:t}}function yE(e){return e.map(t=>{let n=t.lastIndexOf(":"),r=t.slice(0,n).trim(),i=Number(t.slice(n+1)),s=r===pe||/^[a-z0-9][a-z0-9-]*$/iu.test(r);return(n<1||!s||!Number.isSafeInteger(i)||i<1)&&Ke(`history-author-acknowledge --event expects <item-id>:<one-based-line>, received "${t}".`,{code:"history_author_acknowledge_target_unreadable"}),{item_id:r,line:i}})}function Hj(e,t){let n=hE($a(t.historyEvent),t.allActionable===!0||t.all_actionable===!0);return vE(e,{events:n.events,all_actionable:n.all_actionable,dry_run:t.dryRun===!0||t.dry_run===!0,plan_fingerprint:L(t,"planFingerprint")??L(t,"plan_fingerprint"),coordinate_limit:typeof t.limit=="number"?t.limit:typeof t.limit=="string"?Number(t.limit):void 0,attributed_author:L(t,"attributedAuthor")??L(t,"attributed_author")??void 0,reviewer:L(t,"reviewer"),reason:L(t,"reason")})}async function vE(e,t){let n=t.reviewer?.trim()??"",r=t.attributed_author?.trim()??"",i=t.reason?.trim()??"",s=await fp(e,t,t.coordinate_limit??50);if(t.dry_run===!0)return{dry_run:!0,mutated:!1,acknowledged:0,outcome:"preview",exit_code:f.SUCCESS,plan:s.plan};if([n.length>0,n.toLowerCase()!=="unknown",r.length>0,r.toLowerCase()!=="unknown",i.length>0].includes(!1)&&Ke("Author acknowledgment requires events, reviewer, attributed_author, and reason.",{code:"history_author_acknowledge_required_values_missing"}),t.plan_fingerprint?.trim()||Ke("Author acknowledgment apply requires plan_fingerprint from a fresh dry-run preview.",{code:"history_author_acknowledge_plan_fingerprint_required",recovery:{suggested_retry:"Rerun history-author-acknowledge with --dry-run, then pass --plan-fingerprint <value>."}}),t.plan_fingerprint.trim()!==s.plan.plan_fingerprint)throw new _("Author acknowledgment selection changed after preview; no history was mutated.",f.CONFLICT,{code:"history_author_acknowledge_plan_conflict",recovery:{suggested_retry:"Rerun history-author-acknowledge with --dry-run and apply the fresh plan_fingerprint."}});let a=s.completeCoordinates.filter(({disposition:u})=>s.plan.selection.kind==="events"||u==="actionable").map(({item_id:u,line:m})=>({item_id:u,line:m}));if(a.length===0)return{dry_run:!1,mutated:!1,acknowledged:0,outcome:"no_effect",exit_code:f.NO_EFFECT,plan:s.plan};let c=await C(e),d=await An({pmRoot:e,op:"history:author-acknowledge",author:n,context:{author_acknowledgment:{events:a,attributed_author:r}},message:i,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),l=s.plan.actionable_count>0&&s.plan.already_acknowledged_count>0?{outcome:"partial_effect",exit_code:f.PARTIAL_EFFECT}:{outcome:"effect",exit_code:f.SUCCESS};return{dry_run:!1,mutated:!0,acknowledged:a.length,...l,plan:s.plan,history_path:d.historyPath}}import ja from"node:fs/promises";import Ua from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cb3bf7ee-808f-5ff6-af84-edb034760c54")}catch{}})();var wE=8388608,bE=new Set(["resolved","failed"]),kE=[{kind:"boolean",matches:e=>typeof e=="boolean"||typeof e=="string"&&/^(?:true|false)$/iu.test(e.trim())},{kind:"single_digit",matches:e=>typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=9||typeof e=="string"&&/^\d$/u.test(e.trim())}];function rt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function qa(e){return kE.find(t=>t.matches(e))?.kind}function _p(e){let t=new Map,n=0,r=0;return{entries:e.map(s=>{let o=rt(s.agent_provenance)?s.agent_provenance:void 0;if(o===void 0||!Ru(s).ok)return s;let a={},c=!1;for(let[l,u]of Object.entries(o)){let m=rt(u)?qa(u.value):void 0;if(m===void 0){a[l]=u;continue}c=!0,r+=1;let g=s.agent_harness??"unknown",p=`${g}\0${l}\0${m}`,h=t.get(p)??{harness:g,dimension:l,kind:m,count:0};h.count+=1,t.set(p,h)}if(!c)return s;n+=1;let d={...s};return Object.keys(a).length===0?delete d.agent_provenance:d.agent_provenance=a,Ou(s,d,{retainPriorRecord:!0,retainPriorRecordHash:!1})}),receipt:{changed:n>0,events_changed:n,observations_removed:r,invalid_values:[...t.values()].sort((s,o)=>s.harness.localeCompare(o.harness)||s.dimension.localeCompare(o.dimension)||s.kind.localeCompare(o.kind))}}}async function pp(e){let t=[];for(let n of await gp(e))try{let r=await ja.readFile(Ua.join(e,"history",n),"utf8");for(let i of r.split(`
|
|
5
|
-
`)){if(i.trim().length===0)continue;let s=hp(i);if(s===null||!rt(s.agent_provenance))continue;if(Object.values(s.agent_provenance).some(a=>rt(a)&&qa(a.value)!==void 0)){t.push(n.slice(0,-6));break}}}catch{}return t}async function gp(e){try{return(await ja.readdir(Ua.join(e,"history"))).filter(t=>t.endsWith(".jsonl")).sort()}catch{return[]}}async function EE(e,t,n){let r;try{r=await ja.open(Ua.join(e,"history",t),"r");let i=(await r.stat()).size,s=Math.min(i,Math.max(0,n)),o=Buffer.alloc(s),{bytesRead:a}=await r.read(o,0,s,0),c=o.subarray(0,a).toString("utf8"),d=a>=i,l=c.lastIndexOf(`
|
|
6
|
-
`),u=c;return d||(u=l===-1?"":c.slice(0,l+1)),{content:u,bytesRead:a,complete:d}}catch{return null}finally{await r?.close()}}function hp(e){try{let t=JSON.parse(e);return rt(t)?t:null}catch{return null}}function SE(e,t,n){let r=typeof e.agent_harness=="string"?e.agent_harness:void 0;if(r===void 0)return;let i=rt(e.agent_provenance)?e.agent_provenance:{};if(Object.entries(i).forEach(([o,a])=>{if(!rt(a))return;let c=qa(a.value);if(!c)return;let d=`${r}\0${o}\0${c}`,l=n.get(d)??{harness:r,dimension:o,kind:c,count:0};l.count+=1,n.set(d,l)}),!rt(e.context))return;let s=e.context.agent_provenance_outcomes;rt(s)&&Object.entries(s).forEach(([o,a])=>{if(!rt(a)||typeof a.resolver!="string"||!bE.has(String(a.status)))return;let c=`${r}\0${o}\0${a.resolver}`,d=t.get(c)??{harness:r,dimension:o,resolver:a.resolver,attempts:0,successes:0};d.attempts+=1,a.status==="resolved"&&(d.successes+=1),t.set(c,d)})}function xE(e,t,n,r,i){let s=i;for(let o of e.split(`
|
|
7
|
-
`)){if(o.trim().length===0)continue;if(s>=r)return{eventsRead:s,truncated:!0};s+=1;let a=hp(o);a&&SE(a,t,n)}return{eventsRead:s,truncated:!1}}async function yp(e,t=1e4){let n=new Map,r=new Map,i=0,s=0,o=!1;for(let d of await gp(e)){let l=await EE(e,d,Math.max(0,wE-s));if(l===null)continue;s+=l.bytesRead;let u=xE(l.content,n,r,t,i);if(i=u.eventsRead,u.truncated){o=!0;break}if(!l.complete){o=!0;break}}let a=[...n.values()].sort((d,l)=>d.harness.localeCompare(l.harness)||d.dimension.localeCompare(l.dimension)||d.resolver.localeCompare(l.resolver)),c=[...r.values()].sort((d,l)=>d.harness.localeCompare(l.harness)||d.dimension.localeCompare(l.dimension)||d.kind.localeCompare(l.kind));return{outcomes:a,invalid_values:c,warnings:o?[]:[...a.filter(d=>d.attempts>0&&d.successes===0).map(d=>`provenance_resolver_zero_success:${d.harness}:${d.dimension}:${d.resolver}:${String(d.attempts)}`),...c.map(d=>`provenance_value_domain_invalid:${d.harness}:${d.dimension}:${d.kind}:${String(d.count)}`)],events_read:i,truncated:o}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4d5434c7-544b-5061-89eb-6e4074e58e30")}catch{}})();var TE=Object.freeze({pm_item_scalar_missing:!0});function Pn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.keys(e).length===1&&e.pm_item_scalar_missing===!0}function J(e){return e===void 0?TE:e}function Mt(e){return Ne(D(e===void 0?{pm_item_scalar_presence:"missing"}:{pm_item_scalar_presence:"present",value:e}))}function Ga(e,t){let n=Ge(e);if(n)throw new _(`History merge input (${t}) contains unresolved conflict markers at line ${n.line}. Merge drivers must receive clean per-side versions.`,f.GENERIC_FAILURE);let r=[];for(let[i,s]of e.split(/\r?\n/).entries()){let o=s.trim();if(o)try{let a=JSON.parse(o);if(typeof a!="object"||a===null||Array.isArray(a))throw new TypeError("history entry must be an object");r.push(a)}catch{throw new _(`History merge input (${t}) contains invalid JSON at line ${i+1}.`,f.GENERIC_FAILURE)}}return r}function Nt(e){return D({ts:e.ts,author:e.author,op:e.op,patch:e.patch,message:e.message??null})}function IE(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&Nt(e[r])===Nt(t[r]);)r+=1;return r}function oU(e,t,n){Ga(e,"base");let r=Ga(t,"ours"),i=Ga(n,"theirs"),s=IE(r,i);if(s===r.length&&s===i.length)return{merged:Ht(r),strategy:"identical",common_entries:s,entries_from_ours:0,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(s===i.length)return{merged:Ht(r),strategy:"fast_forward_ours",common_entries:s,entries_from_ours:r.length-s,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(s===r.length)return{merged:Ht(i),strategy:"fast_forward_theirs",common_entries:s,entries_from_ours:0,entries_from_theirs:i.length-s,entries_total:i.length,reanchored:!1};let o=r.slice(s),a=new Set(o.map(Nt)),c=i.slice(s).filter(u=>!a.has(Nt(u))),d=[...o,...c].sort((u,m)=>{let g=lt(u.ts,m.ts);if(g!==0)return g;let p=a.has(Nt(u)),h=a.has(Nt(m));return p!==h?Number(h)-Number(p):Nt(u).localeCompare(Nt(m))}),l=Ri([...r.slice(0,s),...d],void 0,{continuousHashSurface:!0});if(l.skippedOps>0)throw new _(`History union cannot preserve ${l.skippedOps} patch operation(s) after deterministic suffix ordering; leave the file unresolved for manual recovery.`,f.GENERIC_FAILURE);return{merged:Ht(l.entries),strategy:"union_reanchor",common_entries:s,entries_from_ours:o.length,entries_from_theirs:c.length,entries_total:l.entries.length,reanchored:!0}}function Ka(e,t){let n=Ge(e);if(n)throw new _(`Relationship merge input (${t}) contains unresolved conflict markers at line ${n.line}. Merge drivers must receive clean per-side versions.`,f.GENERIC_FAILURE);let r=[];for(let[i,s]of e.split(/\r?\n/).entries()){let o=s.trim();if(!o)continue;let a;try{a=JSON.parse(o)}catch{throw new _(`Relationship merge input (${t}) contains invalid JSON at line ${i+1}.`,f.GENERIC_FAILURE)}if(typeof a!="object"||a===null||Array.isArray(a)||typeof a.eventId!="string"||typeof a.sequence!="number")throw new _(`Relationship merge input (${t}) line ${i+1} is not a relationship event (eventId + sequence required).`,f.GENERIC_FAILURE);r.push(a)}return r}function os(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
|
|
8
|
-
`)}
|
|
9
|
-
`}function AE(e){return e.map((t,n)=>({...t,sequence:n+1}))}function aU(e,t,n){Ka(e,"base");let r=Ka(t,"ours"),i=Ka(n,"theirs"),s=Math.min(r.length,i.length),o=0;for(;o<s&&r[o].eventId===i[o].eventId;)o+=1;if(o===r.length&&o===i.length)return{merged:os(r),strategy:"identical",common_entries:o,entries_from_ours:0,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(o===i.length)return{merged:os(r),strategy:"fast_forward_ours",common_entries:o,entries_from_ours:r.length-o,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(o===r.length)return{merged:os(i),strategy:"fast_forward_theirs",common_entries:o,entries_from_ours:0,entries_from_theirs:i.length-o,entries_total:i.length,reanchored:!1};let a=r.slice(o),c=new Set(a.map(m=>m.eventId)),d=i.slice(o).filter(m=>!c.has(m.eventId)),l=[...a,...d].sort((m,g)=>{if(m.timestamp!==void 0&&g.timestamp!==void 0){let y=lt(m.timestamp,g.timestamp);if(y!==0)return y}else{if(m.timestamp===void 0&&g.timestamp!==void 0)return 1;if(m.timestamp!==void 0)return-1}let p=c.has(m.eventId),h=c.has(g.eventId);return p!==h?Number(h)-Number(p):0}),u=AE([...r.slice(0,o),...l]);return{merged:os(u),strategy:"union_reanchor",common_entries:o,entries_from_ours:a.length,entries_from_theirs:d.length,entries_total:u.length,reanchored:!0}}var CE=["tags","dependencies","comments","notes","learnings","files","tests","test_runs","docs","reminders","events"],RE=["acceptance_criteria"],OE=["updated_at"];function Yt(e,t){return e===void 0||t===void 0?e===void 0&&t===void 0:D(e)===D(t)}function vp(e,t,n){let r=l=>Array.isArray(l)?l:[],i=new Set(r(e).map(l=>D(l))),s=r(t),o=new Set(s.map(l=>D(l))),a=r(n),c=new Set(a.map(l=>D(l))),d=s.filter(l=>{let u=D(l);return!i.has(u)||c.has(u)});for(let l of a){let u=D(l);!o.has(u)&&!i.has(u)&&d.push(l)}return d}function Sr(e){if(typeof e!="object"||e===null||Array.isArray(e))return D(e);let{provenance:t,...n}=e;return D(n)}function DE(e){if(typeof e!="object"||e===null||Array.isArray(e))return e;let t=e;return t.provenance?{...t,provenance:{...t.provenance,source_kind:"merge_union"}}:{...t,provenance:{source_kind:"merge_union"}}}function LE(e,t,n){let r=l=>Array.isArray(l)?l:[],i=new Set(r(e).map(Sr)),s=r(t),o=new Set(s.map(Sr)),a=r(n),c=new Set(a.map(Sr)),d=s.filter(l=>{let u=Sr(l);return!i.has(u)||c.has(u)});for(let l of a){let u=Sr(l);!o.has(u)&&!i.has(u)&&d.push(DE(l))}return d}function NE(e,t){return lt(String(e),String(t))>=0?e:t}function wp(e,t,n,r){return Yt(t,n)?{value:t,from_theirs:!1,conflict:!1}:Yt(e,t)?{value:n,from_theirs:!0,conflict:!1}:Yt(e,n)?{value:t,from_theirs:!1,conflict:!1}:{value:r==="theirs"?n:t,from_theirs:r==="theirs",conflict:!0}}function bp(e,t,n,r,i,s,o){let a=wp(e,t,n,r);if(!a.conflict)return{...a,conflict:!1};if(i==="preferred_side")return{...a,resolution_basis:"requested_preference",retained_side:a.from_theirs?"theirs":"ours"};let c=lt(s,o);if(i==="latest_document_update"&&c!==0){let l=c<0;return{value:l?n:t,from_theirs:l,conflict:!0,resolution_basis:"document_updated_at",retained_side:l?"theirs":"ours"}}let d=D(J(n)).localeCompare(D(J(t)))<0;return{value:d?n:t,from_theirs:d,conflict:!0,resolution_basis:"stable_value_tiebreak",retained_side:d?"theirs":"ours"}}function za(e){return{...e.metadata}}function Ba(e,t,n){try{let r=Ti(Sn(e,n),n),i=Object.entries(r.metadata).find(([,s])=>Pn(s))?.[0];if(i!==void 0)throw new TypeError(`metadata field ${i} uses the reserved missing-scalar evidence marker`);return r}catch(r){throw new _(`Item merge input (${t}) is not a readable item document: ${String(r)}`,f.GENERIC_FAILURE)}}function ME(e){if(!e.unionFieldSet.has(e.field))return!1;let t=e.field==="tests"?LE(e.baseValue,e.oursValue,e.theirsValue):e.field==="acceptance_criteria"?vp(At(e.baseValue),At(e.oursValue),At(e.theirsValue)).join("; "):vp(e.baseValue,e.oursValue,e.theirsValue);return e.accumulator.merged[e.field]=t,Yt(t,e.oursValue)||e.accumulator.unionFields.push(e.field),!0}function PE(e){let t=bp(e.baseValue,e.oursValue,e.theirsValue,e.preferred,e.conflictResolution,e.oursUpdatedAt,e.theirsUpdatedAt);t.value!==void 0&&(e.accumulator.merged[e.field]=t.value),t.conflict?(e.accumulator.conflictFields.push(e.field),e.accumulator.conflictDecisions.push({field:e.field,base:J(e.baseValue),ours:J(e.oursValue),theirs:J(e.theirsValue),retained:J(t.value),discarded:J(t.from_theirs?e.oursValue:e.theirsValue),retained_side:t.retained_side,resolution_basis:t.resolution_basis})):t.from_theirs&&e.accumulator.fieldsFromTheirs.push(e.field)}function FE(e,t,n,r,i,s,o){let a=new Set([...CE,...RE]),c=new Set(OE),d=[...new Set([...Object.keys(t),...Object.keys(n)])].sort((u,m)=>u.localeCompare(m)),l={merged:{},conflictFields:[],fieldsFromTheirs:[],unionFields:[],conflictDecisions:[]};for(let u of d){let m=e[u],g=t[u],p=n[u];if(!ME({field:u,baseValue:m,oursValue:g,theirsValue:p,unionFieldSet:a,accumulator:l})){if(c.has(u)){l.merged[u]=NE(g,p);continue}PE({field:u,baseValue:m,oursValue:g,theirsValue:p,preferred:r,conflictResolution:i,oursUpdatedAt:s,theirsUpdatedAt:o,accumulator:l})}}return l}function cU(e,t,n,r={}){let i=r.preferred??"ours",s=r.conflictResolution??"preferred_side",o=e.trim().length>0,a=Ba(t,"ours",r),c=Ba(n,"theirs",r),d=o?Ba(e,"base",r):a,l=o?za(d):{},u=za(a),m=za(c),{merged:g,conflictFields:p,fieldsFromTheirs:h,unionFields:y,conflictDecisions:v}=FE(l,u,m,i,s,a.metadata.updated_at,c.metadata.updated_at),w=bp(o?d.body:"",a.body,c.body,i,s,a.metadata.updated_at,c.metadata.updated_at);return w.conflict?(p.push("body"),v.push({field:"body",base:J(o?d.body:""),ours:J(a.body),theirs:J(c.body),retained:J(w.value),discarded:J(w.from_theirs?a.body:c.body),retained_side:w.retained_side,resolution_basis:w.resolution_basis})):w.from_theirs&&h.push("body"),{merged:xi({metadata:g,body:w.value},r),conflict_fields:p,fields_from_theirs:h,union_fields:y,conflict_decisions:v,requested_preference:i,requested_preference_applied:s==="preferred_side",conflict_resolution:s}}function Ha(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Wa(e,t){let n=Ge(e);if(n)throw new _(`JSON merge input (${t}) contains unresolved conflict markers at line ${n.line}.`,f.GENERIC_FAILURE);if(e.trim().length!==0)try{return JSON.parse(e)}catch{throw new _(`JSON merge input (${t}) is not valid JSON.`,f.GENERIC_FAILURE)}}function $E(e,t,n){if(!Array.isArray(e)||!Array.isArray(t)||!Array.isArray(n))return null;let r=d=>{let l=new Map;for(let u of d){let m=D(u);l.set(m,(l.get(m)??0)+1)}return l},i=r(e),s=r(t),o=r(n);for(let[d,l]of i)if((s.get(d)??0)<l||(o.get(d)??0)<l)return null;let a=new Map(s),c=[];for(let d of n){let l=D(d),u=a.get(l)??0;u>0?a.set(l,u-1):c.push(d)}return{merged:[...t,...c],acceptedTheirs:c.length>0}}function jE(e,t,n,r,i,s,o){if(!Ha(t)||!Ha(n))return null;let a=Ha(e)?e:{},c={},d=[...new Set([...Object.keys(t),...Object.keys(n)])].sort((l,u)=>l.localeCompare(u));for(let l of d){let u=i.length>0?`${i}.${l}`:l,m=UE(a,t,n,l,r,u,s,o);m!==void 0&&(c[l]=m)}return c}function kp(e,t,n,r,i,s,o){if(Yt(t,n))return t;let a=$E(e,t,n);if(a!==null)return a.acceptedTheirs&&o.push(i),a.merged;let c=jE(e,t,n,r,i,s,o);if(c!==null)return c;let d=wp(e,t,n,r);return d.conflict?s.push(i):d.from_theirs&&o.push(i),d.value}function UE(e,t,n,r,i,s,o,a){let c=Object.prototype.hasOwnProperty.call(t,r),d=Object.prototype.hasOwnProperty.call(n,r),l=Object.prototype.hasOwnProperty.call(e,r);if(c&&d)return kp(e[r],t[r],n[r],i,s,o,a);if(c){if(l&&Yt(e[r],t[r])){a.push(s);return}return l?(o.push(s),i==="theirs"?void 0:t[r]):t[r]}if(!(l&&Yt(e[r],n[r])))return l?(o.push(s),i==="theirs"?n[r]:void 0):(a.push(s),n[r])}function dU(e,t,n,r={}){let i=r.preferred??"ours",s=Wa(e,"base"),o=Wa(t,"ours"),a=Wa(n,"theirs"),c=[],d=[],l=kp(s,o,a,i,"",c,d);return{merged:`${JSON.stringify(l??null,null,2)}
|
|
10
|
-
`,conflict_paths:c,paths_from_theirs:d,preferred:i}}import{execFile as fS}from"node:child_process";import{randomUUID as _S}from"node:crypto";import{readdir as pS,stat as gS}from"node:fs/promises";import Te from"node:path";import{promisify as hS}from"node:util";import{constants as Ep}from"node:fs";import{lstat as qE,open as GE}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6ece0e15-aff5-5e2d-b18a-16ffaa0fe2ea")}catch{}})();var KE={lstat:qE,open:GE};function zE(e){return e.O_NOFOLLOW??0}async function xr(e,t,n=KE){let r=await n.lstat(e);if(r.isSymbolicLink()||!r.isFile()||r.size>t)return null;let i=await n.open(e,Ep.O_RDONLY|zE(Ep));try{let s=await i.stat();if(!s.isFile()||s.size>t)return null;let o=Buffer.alloc(s.size),a=0;for(;a<o.length;){let{bytesRead:d}=await i.read(o,a,o.length-a,a);if(d===0)break;a+=d}return(await i.stat()).size===s.size&&a===s.size?o.toString("utf8",0,a):null}finally{await i.close()}}import as from"node:path";import{execFile as BE}from"node:child_process";import{createHash as HE}from"node:crypto";import{readdir as WE}from"node:fs/promises";import VE from"node:path";import{promisify as YE}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7bef66b4-7131-5998-84bd-07983a25d762")}catch{}})();var Jt=YE(BE),Va=/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u;async function wU(e,t){let n=t.trim(),r=/^(['"])(.*)\1$/su.exec(n)?.[2]??n;for(let i of["rebase-merge","rebase-apply"])try{let{stdout:s}=await Jt("git",["rev-parse","--path-format=absolute","--git-path",`${i}/orig-head`],{cwd:e,timeout:1e4}),o=(await xr(s.trim(),128))?.trim();if(o===void 0||!Va.test(o))continue;let{stdout:a}=await Jt("git",["rev-parse","--verify",`${o}:${r}`],{cwd:e,timeout:1e4}),c=a.trim();return{kind:"rebase",original_head:o,original_blob:c}}catch{}}function Sp(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;return Object.keys(t).length===3&&t.kind==="rebase"&&typeof t.original_head=="string"&&Va.test(t.original_head)&&typeof t.original_blob=="string"&&Va.test(t.original_blob)}async function xp(e,t,n,r){if(r!==void 0&&HE(n.original_blob.length===40?"sha1":"sha256").update(`blob ${Buffer.byteLength(r)}\0`).update(r).digest("hex")!==n.original_blob)return!1;try{let{stdout:i}=await Jt("git",["rev-parse","--absolute-git-dir"],{cwd:e,timeout:1e4}),s=new Set(["rebase-merge","rebase-apply","MERGE_HEAD","CHERRY_PICK_HEAD","REVERT_HEAD"]);if((await WE(i.trim())).some(d=>s.has(d)))return!1;let{stdout:o}=await Jt("git",["rev-parse","HEAD"],{cwd:e,timeout:1e4});if(o.trim()!==n.original_head)return!1;let{stdout:a}=await Jt("git",["rev-parse","--verify",`HEAD:${t}`],{cwd:e,timeout:1e4});if(a.trim()!==n.original_blob)return!1;let{stdout:c}=await Jt("git",["hash-object","--",VE.resolve(e,t)],{cwd:e,timeout:1e4});return c.trim()!==n.original_blob?!1:(await Jt("git",["diff","--cached","--quiet","HEAD","--",t],{cwd:e,timeout:1e4}),!0)}catch{return!1}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1f6aa507-79da-5d11-a580-72141b725947")}catch{}})();var JE=/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/u,XE=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u,ds=2048,QE=64,ZE=1e5,eS=new Set(["version","id","item_path","item_id","requested_preference","requested_preference_applied","preferred","conflict_resolution","fields_from_theirs","union_fields","merged_field_hashes","decisions","state","created_at","reconciled_at","value_availability","value_policy","evidence_source","operation","settlement"]);function ht(e){return JE.test(e)}var tS=new Set(["field","base","ours","theirs","retained","discarded","retained_side","resolution_basis"]),ls="bounded_non_sensitive_scalars_v1",nS=new Set(["open","in_progress","blocked","closed","canceled"]),rS=new Set(["risk","confidence","severity"]),iS=new Set(["low","medium","high","critical"]),Ip=new Map([["priority",new Set([0,1,2,3,4].map(D))],["status",new Set([...nS].map(D))],...[...rS].map(e=>[e,new Set([...iS].map(D))])]);function it(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ap(e,t){return Object.keys(e).every(n=>t.has(n))}function cs(e){return Array.isArray(e)&&e.length<=ds&&e.every(t=>typeof t=="string"&&t.length>0&&t.length<=256)}function Tr(e){let t=[{value:e,depth:0}],n=0;for(;t.length>0;){let r=t.pop();if(n+=1,n>ZE||r.depth>QE)return!1;if(Array.isArray(r.value))for(let i of r.value)t.push({value:i,depth:r.depth+1});else if(it(r.value))for(let i of Object.values(r.value))t.push({value:i,depth:r.depth+1})}return!0}function Cp(e){if(!it(e))return!1;let t=[void 0,"ours","theirs"],n=[void 0,"requested_preference","document_updated_at","stable_value_tiebreak"];return[Ap(e,tS),typeof e.field=="string",typeof e.field=="string"&&e.field.length>0,typeof e.field=="string"&&e.field.length<=256,Object.hasOwn(e,"base"),Object.hasOwn(e,"ours"),Object.hasOwn(e,"theirs"),Object.hasOwn(e,"retained"),Object.hasOwn(e,"discarded"),Tr(e.base),Tr(e.ours),Tr(e.theirs),Tr(e.retained),Tr(e.discarded),t.includes(e.retained_side),n.includes(e.resolution_basis)].every(Boolean)}function sS(e){if(!it(e))return!1;let t=Object.entries(e);return t.length<=ds&&t.every(([n,r])=>n.length>0&&n.length<=256&&typeof r=="string"&&/^[a-f0-9]{64}$/u.test(r))}function oS(e,t){if(typeof e!="string"||e.length===0||e.length>4096||e.includes("\0")||e.includes("\\")||as.posix.isAbsolute(e))return!1;let n=as.posix.normalize(e);return n!==".."&&!n.startsWith("../")&&as.posix.basename(n,as.posix.extname(n))===t}function aS(e){return!cs(e.fields_from_theirs)||!cs(e.union_fields)||!Array.isArray(e.decisions)||e.decisions.length>ds||!e.decisions.every(Cp)?!1:e.merged_field_hashes===void 0||sS(e.merged_field_hashes)}function cS(e){let t=[void 0,"ours","theirs"],n=[void 0,"preferred_side","stable_value_order","latest_document_update"],r=[void 0,"clone_local","hash_only","bounded_inline","mixed"],i=[void 0,"clone_local","durable"];return t.includes(e.requested_preference)&&t.includes(e.preferred)&&(e.requested_preference_applied===void 0||typeof e.requested_preference_applied=="boolean")&&n.includes(e.conflict_resolution)&&(e.state==="pending"||e.state==="reconciled")&&r.includes(e.value_availability)&&(e.value_policy===void 0||e.value_policy===ls)&&i.includes(e.evidence_source)}function dS(e){return typeof e.created_at=="string"&&yn(e.created_at)&&(e.reconciled_at===void 0||typeof e.reconciled_at=="string"&&yn(e.reconciled_at))}function Tp(e,t){if(!it(t)||us(t)===void 0)return!1;let n=Object.keys(t);if(!n.every(s=>s==="pm_value_hash"||s==="pm_value"))return!1;if(!Object.hasOwn(t,"pm_value"))return n.length===1;let r=t.pm_value;return(r===null||Ip.get(e)?.has(D(r))===!0)&&Mt(r)===t.pm_value_hash}function lS(e){if(!e.decisions.every(r=>r.base===null&&r.ours===null&&r.theirs===null&&Tp(r.field,r.retained)&&Tp(r.field,r.discarded)))return!1;let t=e.decisions.reduce((r,i)=>r+(it(i.retained)&&Object.hasOwn(i.retained,"pm_value")?1:0)+(it(i.discarded)&&Object.hasOwn(i.discarded,"pm_value")?1:0),0),n=t===0?"hash_only":t===e.decisions.length*2?"bounded_inline":"mixed";return e.value_availability===n&&(t===0||e.value_policy===ls)}function uS(e){return e.operation!==void 0&&!Sp(e.operation)?!1:e.settlement===void 0||e.settlement==="original_git_state_restored"&&e.state==="reconciled"&&e.operation!==void 0}function mS(e){for(let t of["version","id","item_path","item_id","fields_from_theirs","union_fields","decisions","state","created_at"])if(!Object.hasOwn(e,t))return"required_fields";return e.version!==1||!Ap(e,eS)?"required_fields":typeof e.id!="string"||!ht(e.id)?"receipt_id":typeof e.item_id!="string"||!XE.test(e.item_id)?"item_id":oS(e.item_path,e.item_id)?null:"item_path"}function Ya(e,t){if(!it(e))return"required_fields";let n=mS(e);return n!==null?n:uS(e)?aS(e)?cS(e)?dS(e)?t==="durable"&&!lS(e)?"durable_decisions":null:"timestamps":"enums":"collections":"operation"}function Ja(e){if(!it(e)||e.version!==1||e.value_policy!==void 0||!Array.isArray(e.decisions))return e;let t=(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0,n=(e.requested_preference==="ours"||e.requested_preference==="theirs")&&e.value_availability==="clone_local";return!t&&!n?e:{...e,decisions:e.decisions.map(r=>!it(r)||!Object.hasOwn(r,"retained")||!Object.hasOwn(r,"discarded")?r:{base:J(void 0),ours:J(void 0),theirs:J(void 0),...r})}}function Rp(e){if(!it(e))return;if(!cs(e.fields_from_theirs))return"fields_from_theirs";if(!cs(e.union_fields))return"union_fields";if(!Array.isArray(e.decisions)||e.decisions.length>ds)return"decisions";let t=e.decisions.findIndex(n=>!Cp(n));return t>=0?`decisions[${t}]`:"merged_field_hashes"}function Xa(e,t){return Ya(e,t)===null}function us(e){if(typeof e!="object"||e===null||Array.isArray(e)||!("pm_value_hash"in e))return;let t=e.pm_value_hash;return typeof t=="string"&&/^[a-f0-9]{64}$/u.test(t)?t:void 0}function Qa(e,t){let n=Pn(t),r=Mt(n?void 0:t);return!n&&(t===null||Ip.get(e)?.has(D(t))===!0)?{pm_value_hash:r,pm_value:t}:{pm_value_hash:r}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e7fe0fee-9519-593d-ac72-b3c7fb63563e")}catch{}})();var yS=hS(fS),Lp=16*1024*1024,ms=100;async function Za(e){try{let{stdout:t}=await yS("git",["rev-parse","--path-format=absolute","--git-path","pm-merge-receipts"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return t.trim()}catch{return null}}async function Np(e,t){let n=Te.dirname(Te.resolve(e,t));for(let r=0;r<12;r+=1){if(await V(Te.join(n,"settings.json")))return n;let i=Te.dirname(n);if(i===n)break;n=i}return null}function ec(e){return Te.join(e,"merge-receipts")}function Fn(e){return`${e}.json`}async function Op(e){let t;try{t=e.readReceipt?await e.readReceipt(e.receiptPath):await xr(e.receiptPath,Lp)}catch(s){if(hn(s))return null;throw s}if(t===null)throw new Error(`Receipt ${e.receiptId} settlement source is not a bounded regular file.`);let n;try{n=Ja(JSON.parse(t))}catch{throw new Error(`Receipt ${e.receiptId} settlement source is not valid JSON.`)}if(!Xa(n,e.evidenceSource)||n.id!==e.receiptId||e.settlement!==void 0&&n.operation===void 0||Te.basename(e.receiptPath)!==Fn(n.id))throw new Error(`Receipt ${e.receiptId} settlement source failed schema or identity validation.`);let{evidence_source:r,...i}=n;return{path:e.receiptPath,fingerprints:tc(n),modern:n.value_policy!==void 0,content:`${JSON.stringify({...i,state:"reconciled",reconciled_at:e.reconciledAt,...e.settlement?{settlement:e.settlement}:{}},null,2)}
|
|
11
|
-
`}}function Ir(e,t=!1){return Ne(D({id:e.id,item_id:e.item_id,item_path:e.item_path,created_at:e.created_at,requested_preference:e.requested_preference??e.preferred??"ours",conflict_resolution:e.conflict_resolution??"preferred_side",fields_from_theirs:e.fields_from_theirs,union_fields:e.union_fields,merged_field_hashes:e.merged_field_hashes??null,operation:e.operation??null,decisions:t?e.decisions.map(n=>({field:n.field,retained_hash:Ne(D(J(n.retained))),discarded_hash:Ne(D(J(n.discarded)))})):nc(e).decisions}))}function tc(e){let t=[Ir(e)];return e.value_policy===void 0&&(e.value_availability===void 0||e.value_availability==="clone_local")&&t.push(Ir(e,!0)),t}function vS(e,t){if(e.state==="reconciled"&&t.state==="reconciled"&&e.settlement===t.settlement)return e;let{reconciled_at:n,settlement:r,...i}=e;return{...i,state:"pending"}}function nc(e){return{receipt_id:e.id,item_id:e.item_id,item_path:e.item_path,conflict_fields:e.decisions.map(t=>t.field),fields_from_theirs:e.fields_from_theirs,union_fields:e.union_fields,requested_preference:e.requested_preference??e.preferred??"ours",requested_preference_applied:e.requested_preference_applied??(e.conflict_resolution??"preferred_side")==="preferred_side",conflict_resolution:e.conflict_resolution,decisions:e.decisions.map(t=>({field:t.field,retained_hash:us(t.retained)??Mt(Pn(t.retained)?void 0:t.retained),discarded_hash:us(t.discarded)??Mt(Pn(t.discarded)?void 0:t.discarded)}))}}async function jU(e){let t=await Za(e.cwd);if(t===null)return null;let n=e.itemPath.trim(),r=/^(['"])(.*)\1$/su.exec(n)?.[2]??n,i=Te.basename(r,Te.extname(r)),s={version:1,id:_S(),item_path:r.replaceAll("\\","/"),item_id:i,requested_preference:e.preferred,requested_preference_applied:(e.conflictResolution??"preferred_side")==="preferred_side",conflict_resolution:e.conflictResolution??"preferred_side",fields_from_theirs:[...e.fieldsFromTheirs],union_fields:[...e.unionFields],...e.mergedFieldHashes?{merged_field_hashes:{...e.mergedFieldHashes}}:{},decisions:structuredClone(e.decisions).map(a=>({...a,base:J(a.base),ours:J(a.ours),theirs:J(a.theirs),retained:J(a.retained),discarded:J(a.discarded)})),...e.operation?{operation:e.operation}:{},state:"pending",created_at:T(),value_availability:"clone_local"};await We(t),await we(Te.join(t,Fn(s.id)),`${JSON.stringify(s,null,2)}
|
|
12
|
-
`);let o=await Np(e.cwd,s.item_path);if(o!==null){let a=ec(o),c=s.decisions.map(u=>({field:u.field,base:null,ours:null,theirs:null,retained:Qa(u.field,u.retained),discarded:Qa(u.field,u.discarded),retained_side:u.retained_side,resolution_basis:u.resolution_basis})),d=c.reduce((u,m)=>u+(Object.hasOwn(m.retained,"pm_value")?1:0)+(Object.hasOwn(m.discarded,"pm_value")?1:0),0),l={...s,decisions:c,value_availability:d===0?"hash_only":d===c.length*2?"bounded_inline":"mixed",value_policy:ls};await We(a),await we(Te.join(a,Fn(s.id)),`${JSON.stringify(l,null,2)}
|
|
13
|
-
`)}return s}async function Dp(e,t){let n;try{n=await pS(e)}catch(a){let c=await wS(e,a);return{receipts:[],invalid_evidence_count:c?0:1,invalid_evidence:c?[]:[{evidence_source:t,reason:"directory_unreadable"}],invalid_evidence_truncated:!1}}let r=[],i=0,s=[],o=(a,c)=>{if(i+=1,s.length>=ms)return;let d=a.slice(0,-5);s.push({evidence_source:t,reason:c.reason,...c.validation_path?{validation_path:c.validation_path}:{},...c.validation_error===void 0?{}:{validation_error:c.validation_error},...ht(d)?{receipt_id:d}:{candidate_name_hash:Ne(a)}})};for(let a of n.sort((c,d)=>c.localeCompare(d))){if(!a.endsWith(".json"))continue;let c=await bS(e,a,t);c.receipt!==void 0?r.push(c.receipt):o(a,c)}return{receipts:r,invalid_evidence_count:i,invalid_evidence:s,invalid_evidence_truncated:i>s.length}}async function wS(e,t,n=gS){if(!j(t))return!1;let r=e;for(;;)try{return(await n(r)).isDirectory()}catch(i){if(!j(i))return!1;let s=Te.dirname(r);if(s===r)return!0;r=s}}async function bS(e,t,n){let r;try{r=await xr(Te.join(e,t),Lp)}catch{return{reason:"candidate_unreadable"}}if(r===null)return{reason:"candidate_not_bounded_regular_file"};let i;try{i=Ja(JSON.parse(r))}catch{return{reason:"candidate_invalid_json"}}let s=Ya(i,n);if(s!==null)return{reason:new Set(["receipt_id","item_id","item_path"]).has(s)?"identity_invalid":"schema_invalid",validation_error:s,...s==="collections"?{validation_path:Rp(i)}:{}};let o=i;if(t!==Fn(o.id))return{reason:"identity_invalid",validation_error:"filename"};let{preferred:a,evidence_source:c,...d}=o;return{receipt:{...d,requested_preference:o.requested_preference??a??"ours",requested_preference_applied:o.requested_preference_applied??(o.conflict_resolution??"preferred_side")==="preferred_side",conflict_resolution:o.conflict_resolution??"preferred_side",evidence_source:n}}}async function st(e,t={}){let n=await Za(e),r=n===null?{receipts:[],invalid_evidence_count:0,invalid_evidence:[],invalid_evidence_truncated:!1}:await Dp(n,"clone_local"),i=t.pmRoot??Te.join(e,".agents","pm"),s=await Dp(ec(i),"durable"),o=new Map(s.receipts.map(d=>[d.id,d])),a=0,c=[];for(let d of r.receipts){let l=o.get(d.id);if(l!==void 0&&!(l.value_policy===void 0?tc(d):[Ir(d)]).includes(Ir(l))){o.delete(d.id),a+=1,r.invalid_evidence.length+s.invalid_evidence.length+c.length<ms&&c.push({evidence_source:"clone_local_and_durable",reason:"copy_provenance_mismatch",receipt_id:d.id});continue}o.set(d.id,l===void 0?d:vS(d,l))}return{receipts:[...o.values()].filter(d=>(t.includeReconciled||d.state==="pending")&&(t.includeLossless!==!1||d.decisions.length>0)).sort((d,l)=>d.created_at.localeCompare(l.created_at)),invalid_evidence_count:r.invalid_evidence_count+s.invalid_evidence_count+a,invalid_evidence:[...r.invalid_evidence,...s.invalid_evidence,...c].slice(0,ms),invalid_evidence_truncated:r.invalid_evidence_truncated||s.invalid_evidence_truncated||r.invalid_evidence_count+s.invalid_evidence_count+a>ms,clone_local_evidence_resolved:n!==null}}async function kS(e,t={}){return(await st(e,t)).receipts}function $n(e){let t=[],n=[];for(let r of e)(Array.isArray(r.decisions)&&r.decisions.length>0?t:n).push(r);return{pendingDecisions:t,lossless:n}}async function UU(e,t,n={}){let r=await Za(e);if(r===null){if(n.requireExisting===!0)throw new Error(`Receipt ${t.id} disappeared before settlement.`);return}let i=t.evidence_source??"clone_local";if(!Xa(t,i))throw new Error("Merge receipt trusted settlement input failed schema validation.");let s=T(),o=Te.join(r,Fn(t.id)),a=await Np(e,t.item_path),c=a===null?null:Te.join(ec(a),Fn(t.id)),l=(await Promise.all([Op({receiptPath:o,receiptId:t.id,evidenceSource:"clone_local",reconciledAt:s,settlement:n.settlement}),...c===null?[]:[Op({receiptPath:c,receiptId:t.id,evidenceSource:"durable",reconciledAt:s,settlement:n.settlement})]])).filter(m=>m!==null);if(l.length===0){if(n.requireExisting===!0)throw new Error(`Receipt ${t.id} disappeared before settlement.`);return}if(!(l.some(m=>m.modern)?[Ir(t)]:tc(t)).some(m=>l.every(g=>g.fingerprints.includes(m))))throw new Error(`Receipt ${t.id} settlement copies disagree on immutable merge provenance.`);for(let m of l)await we(m.path,m.content)}async function qU(e){let t=await kS(e.cwd??process.cwd(),{...e,includeLossless:!0});return{ok:!0,count:t.length,receipts:t,generated_at:T()}}async function GU(e){let t=await st(e.cwd??process.cwd(),{...e,includeLossless:!0}),n=t.clone_local_evidence_resolved===!0&&t.invalid_evidence_count===0;return{ok:n,complete:n,count:t.receipts.length,invalid_evidence_count:t.invalid_evidence_count,invalid_evidence:t.invalid_evidence,invalid_evidence_truncated:t.invalid_evidence_truncated,clone_local_evidence_resolved:t.clone_local_evidence_resolved,receipts:t.receipts,generated_at:T()}}import{createHash as ES}from"node:crypto";import fs from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1e73338f-221a-580f-85a8-6f2a488fb89d")}catch{}})();var SS="2026-08-09T16:15:18.000Z",Pp=Symbol("pre-durable-disposition-eligible");function yt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function rc(e){if(!Array.isArray(e)||e.length>256)return!1;let t=new Set;for(let n=0;n<e.length;n+=1){let r=e[n];if(!(n in e)||typeof r!="string"||r.length===0||r.length>256||r.includes("\0")||t.has(r))return!1;t.add(r)}return!0}function Mp(e){return yt(e)?typeof e.field=="string"&&e.field.length>0&&e.field.length<=256&&!e.field.includes("\0")&&typeof e.retained_hash=="string"&&/^[a-f0-9]{64}$/u.test(e.retained_hash)&&typeof e.discarded_hash=="string"&&/^[a-f0-9]{64}$/u.test(e.discarded_hash):!1}function Fp(e,t){if(typeof e!="string")return!1;let n=fs.posix.normalize(e);return e.length<=4096&&!e.includes("\\")&&!e.includes("\0")&&!fs.posix.isAbsolute(e)&&n===e&&!n.startsWith("../")&&(fs.posix.basename(n)===`${t}.toon`||fs.posix.basename(n)===`${t}.md`)}function xS(e,t){return typeof e.receipt_id=="string"&&ht(e.receipt_id)&&(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0&&e.conflict_resolution===void 0&&e.item_id===t&&Fp(e.item_path,t)}function $p(e){let t=e.conflict_fields,n=e.fields_from_theirs,r=e.union_fields,i=e.decisions,s=Array.isArray(i)?new Set(i.flatMap(o=>Mp(o)?[o.field]:[])):new Set;return rc(t)&&rc(n)&&rc(r)&&Array.isArray(i)&&i.length>0&&i.length<=256&&Object.keys(i).length===i.length&&i.every(Mp)&&s.size===i.length&&t.length===s.size&&t.every(o=>s.has(o))}function TS(e,t){return xS(e,t)&&$p(e)}function IS(e,t){return typeof e.receipt_id=="string"&&ht(e.receipt_id)&&(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0&&(e.conflict_resolution==="preferred_side"||e.conflict_resolution==="stable_value_order")&&e.item_id===t&&Fp(e.item_path,t)&&$p(e)}function AS(e){return e[Pp]===!0}function jp(e,t){if(!yt(e)||!yt(e.context))return[];let n=e.context.merge;return!yt(n)||!Array.isArray(n.receipts)?[]:n.receipts.flatMap(r=>!yt(r)||typeof r.receipt_id!="string"||r.receipt_id.trim().length===0?[]:[{receiptId:r.receipt_id,legacySummaryAccepted:TS(r,t),[Pp]:IS(r,t),...typeof e.ts=="string"&&yn(e.ts)?{eventTimestamp:e.ts}:{}}])}function Up(e,t,n){if(!yt(e)||e.op!=="merge_reconcile")return[];if(!yt(e.context)||!yt(e.context.merge))return[];let r=e.context.merge.missing_receipt_dispositions;return!Array.isArray(r)||r.length>256?[]:r.flatMap(i=>!yt(i)||typeof i.receipt_id!="string"||!ht(i.receipt_id)||typeof i.original_history_line!="number"||!Number.isSafeInteger(i.original_history_line)||i.original_history_line<1||typeof i.original_event_ts!="string"||!yn(i.original_event_ts)||i.reason!=="legacy_clone_local_only"?[]:[{itemId:t,receiptId:i.receipt_id,originalHistoryLine:i.original_history_line,originalEventTimestamp:i.original_event_ts,auditHistoryLine:n,reason:i.reason}])}function qp(e,t,n=[]){let r=new Map;for(let o of n){let a=`${o.itemId}\0${o.originalHistoryLine}\0${o.receiptId}\0${o.originalEventTimestamp}`;r.set(a,Math.max(r.get(a)??0,o.auditHistoryLine))}let i=o=>AS(o)&&o.eventTimestamp!==void 0&<(o.eventTimestamp,SS)<0&&(r.get(`${o.itemId}\0${o.line}\0${o.receiptId}\0${o.eventTimestamp}`)??0)>o.line;return{missing:e.filter(o=>!o.legacySummaryAccepted&&!t.has(o.receiptId)&&!i(o)).map(o=>({item_id:o.itemId,history_line:o.line,...ht(o.receiptId)?{receipt_id:o.receiptId}:{receipt_reference_hash:ES("sha256").update(o.receiptId).digest("hex")}})),acceptedLegacyCount:e.filter(o=>o.legacySummaryAccepted).length,acceptedDispositionCount:e.filter(i).length}}import{isUtf8 as CS}from"node:buffer";import{readFile as RS}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="49af8ec4-dd6b-56ef-8833-9c776fa35c85")}catch{}})();function OS(e){let t;try{t=JSON.parse(e)}catch{if(e.trimStart().startsWith("{")&&e.includes("}"))throw new _("History salvage cannot discard a potentially complete record with trailing corruption.",f.CONFLICT,{code:"history_salvage_refused"});return null}if(typeof t!="object"||t===null||Array.isArray(t))throw new _("History salvage would conceal interior corruption or a malformed record.",f.CONFLICT,{code:"history_salvage_refused"});let n=t;if(!Array.isArray(n.patch)||![n.ts,n.author,n.op,n.before_hash,n.after_hash].every(r=>typeof r=="string"))throw new _("History salvage requires complete history records before the invalid tail.",f.CONFLICT,{code:"history_salvage_refused"});return n}function DS(e){if(Ge(e))throw new _("Resolve history merge conflicts before salvage.",f.CONFLICT,{code:"history_salvage_refused"});let t=[],n=0,r,i=0;for(let[o,a]of e.split(`
|
|
14
|
-
`).entries()){if(!a.trim()){n+=a.length+1;continue}let c=OS(a);if(c===null){r===void 0&&(r=n,i=o+1),n+=a.length+1;continue}if(r!==void 0)throw new _("History salvage would discard a record or conceal interior corruption.",f.CONFLICT,{code:"history_salvage_refused",required:"Recover the damaged record from version control or a backup; no bytes were changed."});t.push(c),n+=a.length+1}let s=In(t);if(!s.ok||s.item_hash_version===void 0)throw new _("History salvage requires a nonempty verified prefix.",f.CONFLICT,{code:"history_salvage_refused",verification_errors:s.errors,required:"Recover an intact history prefix from version control or a backup."});return{entries:t,itemHashVersion:s.item_hash_version,prefix:r===void 0?e:e.slice(0,r),receipt:r===void 0?null:{first_invalid_line:i,discarded_bytes:Buffer.byteLength(e.slice(r)),discarded_sha256:Ne(e.slice(r)),retained_entries:t.length}}}async function LS(e,t,n){if(!e.located)return{itemRaw:null,document:n};let r=await em(e.located,{schema:t.schema});return{itemRaw:r.raw,document:r.document??n}}async function Gp(e){let t;try{t=await RS(e)}catch(n){if(j(n))return null;throw n}if(!CS(t))throw new _("History salvage requires UTF-8 input; recover binary corruption from a byte-preserving backup.",f.CONFLICT,{code:"history_salvage_refused"});return t.toString("utf8")}async function Kp(e){let{subject:t,settings:n,options:r,author:i}=e;if([r.normalizeProvenance,r.auditOperation,r.auditContext,r.auditContextById,r.forceAuditEntry,r.mergeReceiptProof,r.mergeReceiptProofById].some(Boolean))throw new _("Tail salvage cannot be combined with other repair modes.",f.USAGE);let s=await Gp(t.historyPath);if(s===null)throw new _(`No history stream exists for ${t.id}.`,f.NOT_FOUND);await Ce({path:t.historyPath,scope:"project"});let o=DS(s),a=t_(o.entries,o.entries.length-1),c=Nu(a);if(typeof a.metadata.id=="string"&&a.metadata.id!==t.id)throw new _("History belongs to another item; salvage refused.",f.CONFLICT,{code:"history_salvage_refused"});let d=await LS(t,n,c),l=n_({itemDocument:d.document,subjectId:t.id,author:i,force:r.force,settings:n}),u=o.itemHashVersion,m=r.dryRun===!0,g=o.receipt!==null;if(g&&!m){let p=await Ct(e.pmRoot,t.id,n.locks.ttl_seconds,i,!!r.force,n.governance.force_required_for_stale_lock,n.locks.wait_ms);try{let h=await Gp(t.historyPath),y=await X(e.pmRoot,t.id,n.id_prefix,n.item_format,e.typeRegistry.type_to_folder),v=y?await Y(y.itemPath):null;if(h!==s||v!==d.itemRaw)throw new _("History or item changed while waiting for salvage lock; retry.",f.CONFLICT);let w=Ai({...Ci({nowIso:T(),author:i,op:"history_salvage",before:c,after:c,message:r.message,context:{history_salvage:o.receipt}}),before_hash:o.entries.at(-1).after_hash,after_hash:o.entries.at(-1).after_hash,item_hash_version:u});await zi({historyPath:t.historyPath,historyRawUnderLock:s,nextHistoryRaw:`${o.prefix}${JSON.stringify(w)}
|
|
15
|
-
`}),l.push(...await Me({path:t.historyPath,scope:"project",op:"history_salvage:history"}))}finally{await p()}}return{id:t.id,dry_run:m,changed:g,history:{path:t.historyPath,entries_scanned:o.entries.length,chain_drift_before:!1,entries_rehashed:0,entries_patch_repaired:0,converted_replace_to_add:0,skipped_ops:0,reconciled_with_item:!1,audit_entry_added:g&&!m,verify_ok:!0,verify_errors:[],item_hash_version_before:u,item_hash_version_after:u,version_disposition:"preserved"},item:{exists:t.located!==null,path:t.located?.itemPath??null,matched_chain_before:null},provenance_normalization:{requested:!1,changed:!1,events_changed:0,observations_removed:0,invalid_values:[]},...o.receipt?{salvage:o.receipt}:{},warnings:l,generated_at:T()}}import{realpath as Xp}from"node:fs/promises";import ic from"node:path";import Qp from"fast-json-patch";import Ar from"node:fs/promises";import{createHash as NS}from"node:crypto";import Bp from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="80648bfe-2436-5b5a-8a16-b9c2875f95fd")}catch{}})();var Hp=10,MS="history-drift-cache.json";function Wp(e){return Bp.join(e,"runtime",MS)}async function PS(e){try{let t=await Ar.readFile(Wp(e),"utf8"),n=JSON.parse(t);return n.version!==Hp||n.history_item_hash_version!==Ii||typeof n.entries!="object"||n.entries===null||Object.values(n.entries).some(r=>typeof r.chain_ok!="boolean"||typeof r.latest_hash_comparable!="boolean"||!xn.includes(r.item_hash_version)&&r.version_skew!==!0||r.chain_ok&&r.version_skew!==!0&&xn.includes(r.item_hash_version)&&!r.latest_hash_comparable)?null:n}catch{return null}}async function FS(e,t,n,r,i){let s=Wt(e),o;try{o=await Ar.stat(s)}catch(d){return j(d)||i.unreadableStreams.push(pe),!1}let a=i.missingStreams.length,c=await Vp({itemId:pe,historyPath:s,stat:o,cached:t[pe],verifyCacheHitByContent:r,accumulator:i});return c.verification?(c.verification.versionSkew&&i.versionSkews.push(pe),c.verification.chainOk||i.chainMismatches.push(pe),n[pe]={mtime_ms:o.mtimeMs,ctime_ms:o.ctimeMs,size:o.size,content_hash:c.verification.contentHash,latest_after_hash:c.verification.latestAfterHash,chain_ok:c.verification.chainOk,version_skew:c.verification.versionSkew,latest_hash_comparable:c.verification.latestHashComparable,item_hash_version:c.verification.itemHashVersion},c.cacheDirty):(i.missingStreams.splice(a),c.cacheDirty)}function $S(e){return NS("sha256").update(e).digest("hex")}async function jS(e){let t=await Ar.readFile(e,"utf8"),n=$S(t);if(t.trim().length===0)return null;let r=[],i=null;for(let u of t.split(/\r?\n/)){let m=u.trim();if(m.length===0)continue;let g=JSON.parse(m);if(typeof g.after_hash!="string"||g.after_hash.trim().length===0)throw new Error("missing after_hash");r.push(g),i=g.after_hash}if(!i)return null;let s=In(r),o=r.some(u=>u.item_hash_version!==void 0&&!xn.includes(u.item_hash_version)),c=r[r.length-1].item_hash_version,d=c!==void 0&&xn.includes(c),l=d?c:s.item_hash_version;return{latestAfterHash:i,identityDiscontinuities:iu(r),chainOk:s.ok,versionSkew:o,latestHashComparable:l!==void 0&&(!o||d||c===void 0),contentHash:n,itemHashVersion:l??Ii}}function US(e,t){return e!==void 0&&e.mtime_ms===t.mtimeMs&&e.ctime_ms===t.ctimeMs&&e.size===t.size}async function zp(e,t,n){try{let r=await jS(t);return r||(n.missingStreams.push(e),null)}catch{return n.unreadableStreams.push(e),null}}async function Vp(e){let t=typeof e.cached?.content_hash=="string"&&e.cached.content_hash.length>0?e.cached.content_hash:void 0;if(!(US(e.cached,e.stat)&&t!==void 0)||!e.cached||!e.cached.chain_ok)return{verification:await zp(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0};if(e.verifyCacheHitByContent){let r=await zp(e.itemId,e.historyPath,e.accumulator);return{verification:r,cacheDirty:r===null||r.contentHash!==t||r.latestAfterHash!==e.cached.latest_after_hash||r.chainOk!==e.cached.chain_ok||r.versionSkew!==(e.cached.version_skew===!0)||r.latestHashComparable!==e.cached.latest_hash_comparable||r.itemHashVersion!==e.cached.item_hash_version}}return{verification:{identityDiscontinuities:[],latestAfterHash:e.cached.latest_after_hash,chainOk:e.cached.chain_ok,versionSkew:e.cached.version_skew===!0,latestHashComparable:e.cached.latest_hash_comparable&&xn.includes(e.cached.item_hash_version),contentHash:t,itemHashVersion:e.cached.item_hash_version},cacheDirty:!1}}async function qS(e,t,n,r){let i=Tt(e,t.id),s;try{s=await Ar.stat(i)}catch(l){return(j(l)?r.missingStreams:r.unreadableStreams).push(t.id),!1}let o=await Vp({itemId:t.id,historyPath:i,stat:s,cached:n.previousEntries[t.id],verifyCacheHitByContent:n.verifyCacheHitByContent,accumulator:r});if(!o.verification)return o.cacheDirty;o.verification.identityDiscontinuities.length>0&&(r.identityDiscontinuities??=[]).push(...o.verification.identityDiscontinuities.map(l=>({...l,item_id:t.id}))),o.verification.versionSkew&&r.versionSkews.push(t.id),o.verification.chainOk||r.chainMismatches.push(t.id),n.nextEntries[t.id]={mtime_ms:s.mtimeMs,ctime_ms:s.ctimeMs,size:s.size,content_hash:o.verification.contentHash,latest_after_hash:o.verification.latestAfterHash,chain_ok:o.verification.chainOk,version_skew:o.verification.versionSkew,latest_hash_comparable:o.verification.latestHashComparable,item_hash_version:o.verification.itemHashVersion};let{body:a,...c}=t;return o.verification.latestHashComparable&&(Du({metadata:c,body:a},o.verification.itemHashVersion).includes(o.verification.latestAfterHash)||r.hashMismatches.push(t.id)),o.cacheDirty}async function GS(e,t){if(!(t.unreadableStreams.includes(pe)||t.chainMismatches.includes(pe)||t.versionSkews.includes(pe)))try{let n=await $u(e);t.workspaceStateMismatches.push(...n.mismatched_documents),t.workspaceStateMissing.push(...n.missing_documents),t.workspaceStateUnreadable.push(...n.unreadable_documents)}catch{t.unreadableStreams.push(pe)}}async function Xt(e,t,n={}){let r={missingStreams:[],unreadableStreams:[],hashMismatches:[],chainMismatches:[],versionSkews:[],workspaceStateMismatches:[],workspaceStateMissing:[],workspaceStateUnreadable:[]},s=(await PS(e))?.entries??{},o={},a=!1,c=n.cacheHitVerification!=="metadata",d={previousEntries:s,nextEntries:o,verifyCacheHitByContent:c};for(let m of t)await qS(e,m,d,r)&&(a=!0);let l=await FS(e,s,o,c,r);if(a||=l,await GS(e,r),a||Object.keys(s).length!==Object.keys(o).length){let m=Wp(e);try{await Ar.mkdir(Bp.dirname(m),{recursive:!0}),await we(m,JSON.stringify({version:Hp,history_item_hash_version:Ii,entries:o}))}catch{}}let u=[...new Set([...r.missingStreams,...r.unreadableStreams,...r.hashMismatches,...r.chainMismatches,...r.versionSkews,...r.workspaceStateMismatches.length>0||r.workspaceStateMissing.length>0||r.workspaceStateUnreadable.length>0?[pe]:[]])].sort((m,g)=>m.localeCompare(g));return{...r,driftedItems:u}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9f91f2ee-cebe-592c-92ee-717301fa96ca")}catch{}})();function Yp(e,t){return t==="body"?e.body:e.metadata[t]}function sc(e,t){if(e===void 0||Object.is(e,t))return!0;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let r=new Set;return e.every(i=>{let s=t.findIndex((o,a)=>!r.has(a)&&sc(i,o));return s<0?!1:(r.add(s),!0)})}if(e===null||t===null||typeof e!="object"||typeof t!="object"||Array.isArray(t))return!1;let n=t;return Object.entries(e).every(([r,i])=>Object.hasOwn(n,r)&&sc(i,n[r]))}function Jp(e,t){let n=new Set(t),r=[];for(let i=e.length-1;i>=0&&n.size>0;i-=1){let s=e[i],o=new Set;for(let c of Pu(s.patch))o.add(Oi(c.path)),c.from&&o.add(Oi(c.from));let a=[...n].filter(c=>o.has(c));if(a.length!==0){for(let c of a)n.delete(c);r.push({index:i+1,ts:s.ts,author:s.author,op:s.op,fields:a.sort((c,d)=>c.localeCompare(d))})}}return r.reverse()}function KS(e,t,n){let r=Qp.compare(t,n);if(r.length===0)return;let i=new Set;for(let p of r)i.add(Oi(p.path));let s=new Set([...i].filter(p=>sc(Yp(t,p),Yp(n,p)))),o=new Set([...i].filter(p=>!s.has(p))),a=Jp(e,o),c=Jp(e,s),d=[...i].sort((p,h)=>p.localeCompare(h)),l=[...o].sort((p,h)=>p.localeCompare(h)),u=[...s].sort((p,h)=>p.localeCompare(h)),m=[...new Set(a.map(p=>p.author))].sort((p,h)=>p.localeCompare(h)),g=[...new Set(c.map(p=>p.author))].sort((p,h)=>p.localeCompare(h));return{reconciled_field_count:i.size,reconciled_fields:d,reverted_field_count:o.size,reverted_fields:l,discarded_events:a,discarded_authors:m,preserved_field_count:s.size,preserved_fields:u,preserved_events:c,preserved_authors:g,recovery_hint:a.length>0?"Reconciliation keeps the on-disk item and overwrites these replayed mutations. To recover one, inspect it with pm history <id> --diff --field <field>, then re-apply the lost value with pm update.":null}}async function zS(e){try{return await Xp(e)}catch{return null}}async function BS(e){if(await zS(ic.resolve(e.gitWorkspaceRoot,e.receipt.item_path))!==e.currentPath)return null;let n=[...new Set([...e.receipt.fields_from_theirs,...e.receipt.union_fields,...e.receipt.decisions.map(a=>a.field)])].sort(),r=e.receipt.merged_field_hashes;if(!r||n.length===0)return null;let i=Object.keys(r).sort();if(n.length!==i.length||n.some((a,c)=>a!==i[c]))return null;let s=e.currentItemReplay.metadata;return n.every(a=>{let c=a==="body"?e.currentItemReplay.body:s[a];return[Mt(c),Ne(D(J(c)))].includes(r[a])})?{receipt:e.receipt,declaredFields:n}:null}async function HS(e){if(e.proof.gitWorkspaceRoot===null)return{trusted:!1,reason:"git_workspace_unavailable",receipt_ids:[]};if(e.itemPath===null||e.currentItemReplay===null)return{trusted:!1,reason:"item_path_unavailable",receipt_ids:[]};let t=e.proof.receipts.filter(o=>o.item_id===e.id);if(t.length===0)return{trusted:!1,reason:"no_item_receipts",receipt_ids:[]};let n=await Xp(e.itemPath),r=[];for(let o of t){let a=await BS({receipt:o,gitWorkspaceRoot:e.proof.gitWorkspaceRoot,currentPath:n,currentItemReplay:e.currentItemReplay});a&&r.push(a)}let i=new Set(r.flatMap(({declaredFields:o})=>o)),s=e.reconciliation?.reconciled_fields;return r.length>0&&(s===void 0||s.length>0&&s.every(o=>i.has(o)))?{trusted:!0,reason:"trusted_merge_driver_hash_evidence",receipt_ids:r.map(({receipt:o})=>o.id)}:{trusted:!1,reason:"no_receipt_set_proves_snapshot",receipt_ids:[]}}async function Zp(e,t,n,r){if(e===void 0)return;let{receipt:i,gitWorkspaceRoot:s}=e,o=t.currentItemPath===null?null:ic.relative(s,t.currentItemPath).split(ic.sep).join("/");if(!n||r.entriesRehashed!==0||r.entriesPatchRepaired!==0||t.matchedChainBefore!==!0||t.currentItemRawBeforeLock===null||o!==i.item_path||i.operation===void 0||!await xp(s,i.item_path,i.operation,t.currentItemRawBeforeLock))throw new _("Restored-origin receipt evidence no longer proves the exact clean item snapshot.",f.CONFLICT,{code:"merge_reconcile_receipt_evidence_untrusted",recovery:{suggested_retry:"pm merge reconcile --dry-run"}})}async function WS(e){let t=new Set(e.options.mergeReceiptProof?.receipts.filter(o=>o.item_id===e.subjectId).map(o=>o.id)??[]),r=(e.options.mergeReceiptProof?await st(e.options.mergeReceiptProof.gitWorkspaceRoot??process.cwd(),{includeReconciled:!0,includeLossless:!0,pmRoot:e.pmRoot}):void 0)?.receipts.filter(o=>o.item_id===e.subjectId&&t.has(o.id))??[],i=e.options.mergeReceiptProof?await HS({proof:{...e.options.mergeReceiptProof,receipts:r},id:e.subjectId,itemPath:e.itemReplayContext.currentItemPath,currentItemReplay:e.itemReplayContext.currentItemReplay,reconciliation:e.reconciliation}):void 0;if(i&&!i.trusted&&e.options.force!==!0)throw new _(`Merge receipt evidence for ${e.subjectId} does not prove the exact item snapshot (${i.reason}).`,f.CONFLICT,{code:"merge_reconcile_receipt_evidence_untrusted",required:"Use authoritative clone-local or durable receipt evidence whose canonical path, declared fields, and merged-value hashes match the current item, or review the mismatch and rerun with --force.",recovery:{suggested_retry:"pm merge reconcile --dry-run"}});let s=i?.trusted?r.filter(o=>i.receipt_ids.includes(o.id)):[];return{mergeReceiptProof:i,effectiveAuditContext:s.length>0&&e.options.force!==!0?{...e.options.auditContext,merge:{receipts:s.map(nc)}}:e.options.auditContext}}async function VS(e,t,n,r){let i=e.located?.itemPath??null,s=e.located?await ge(e.located,{schema:t.schema}):null;if(!s)return{currentItemReplay:null,currentItemPath:i,matchedChainBefore:null,currentItemRawBeforeLock:null,loadedItem:null};let o=Mu(s.document),a=n[n.length-1].after_hash;return{currentItemReplay:o,currentItemPath:i,matchedChainBefore:Tn(o,r).includes(a),currentItemRawBeforeLock:s.raw,loadedItem:s}}function YS(e){return typeof e.message=="string"&&e.message.trim().length>0?e.message:`history-repair re-anchored ${e.entriesRehashed} entr${e.entriesRehashed===1?"y":"ies"}${e.entriesPatchRepaired>0?`, repaired ${e.entriesPatchRepaired} patch(es)`:""}${e.reconcileNeeded?", reconciled chain with on-disk item":""}.`}function JS(e){let t=[...e.reanchorEntries];if(!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let n=e.reconcileNeeded&&e.currentItemReplay?e.currentItemReplay:e.finalReplay,r=Tn(e.finalReplay,e.itemHashVersion),i=e.reanchorEntries[e.reanchorEntries.length-1].after_hash,s=r.indexOf(i),o=Tn(n,e.itemHashVersion),a={ts:T(),author:e.author,op:e.auditOperation,patch:e.reconcileNeeded&&e.currentItemReplay?Qp.compare(e.finalReplay,e.currentItemReplay):[],before_hash:r[s],after_hash:o[s],message:e.message,...e.explicitItemHashVersion?{item_hash_version:e.itemHashVersion}:{},...e.auditContext===void 0?{}:{context:e.auditContext}};return t.push(Ai({...a,event_class:uu(a)})),{rewrittenEntries:t,auditEntryAdded:!0}}function XS(e,t,n){let r=[];return e||r.push("history_repair_no_changes"),t>0&&r.push(`history_repair_skipped_unresolvable_ops:${t}`),n&&n.discarded_events.length>0&&r.push(`history_repair_reconcile_discards_events:${n.discarded_events.length}`,`history_repair_discarded_authors:${n.discarded_authors.join(",")}`),r}async function QS(e){return r_({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.itemReplayContext.currentItemRawBeforeLock,operation:"history-repair",author:e.author,force:e.force,itemDocument:e.itemReplayContext.loadedItem?.document??null,applyRewrite:async({historyRawUnderLock:t})=>{await Zp(e.mergeAbandonmentProof,e.itemReplayContext,e.chainOk,e.reanchor),await zi({historyPath:e.historyPath,nextHistoryRaw:Ht(e.rewrittenEntries),historyRawUnderLock:t})},applyPostRewrite:async()=>Me({path:e.historyPath,scope:"project",op:"history_repair:history"})})}async function oc(e,t,n){let r=R(process.cwd(),n.path);await $(r);let i=await C(r),s=U(i,F()),o=await i_(r,e,i,s.type_to_folder);return t.salvageTail===!0?Kp({pmRoot:r,subject:o,settings:i,typeRegistry:s,options:t,author:q(t.author,i.author_default)}):ex({pmRoot:r,subject:o,settings:i,typeRegistry:s,options:t})}function ZS(e,t){let n=e.mergeAbandonmentProof!==void 0&&e.auditContext!==void 0&&t.some(r=>r.op==="merge_reconcile"&&D(r.context)===D(e.auditContext));return e.forceAuditEntry===!0&&!n}async function ex(e){let{pmRoot:t,subject:n,settings:r,typeRegistry:i,options:s}=e;if(!await V(n.historyPath))throw new _(`No history stream exists for ${n.id}.`,f.NOT_FOUND);let o=await Y(n.historyPath),a=await Rt(n.historyPath,n.id);if(a.length===0)throw new _(`No history entries exist for ${n.id}; nothing to repair.`,f.USAGE);let c=na(a),d=In(a),l=s.normalizeProvenance?_p(a):{entries:a,receipt:{changed:!1,events_changed:0,observations_removed:0,invalid_values:[]}},u=Fu(l.entries),m=new Set(l.entries.map(K=>K.item_hash_version).filter(K=>K!==void 0)),g=Ri(l.entries,u),p=await VS(n,r,a,u);await Zp(s.mergeAbandonmentProof,p,c.ok,g);let h=g.finalDocument,y=Tn(h,u),v=!1;if(p.currentItemReplay!==null){let K=Tn(p.currentItemReplay,u);v=!y.some((oe,ae)=>oe===K[ae])}let w=v&&p.currentItemReplay?KS(g.entries,h,p.currentItemReplay):void 0,{mergeReceiptProof:E,effectiveAuditContext:S}=await WS({options:s,pmRoot:t,subjectId:n.id,itemReplayContext:p,reconciliation:w}),x=[g.entriesRehashed>0,g.entriesPatchRepaired>0,v,ZS(s,a),l.receipt.changed].some(Boolean),I=q(s.author,r.author_default),k=!!s.dryRun,b=YS({message:s.message,entriesRehashed:g.entriesRehashed,entriesPatchRepaired:g.entriesPatchRepaired,reconcileNeeded:v}),{rewrittenEntries:O,auditEntryAdded:W}=JS({reanchorEntries:g.entries,changed:x,reconcileNeeded:v,currentItemReplay:p.currentItemReplay,finalReplay:h,author:I,message:b,auditOperation:s.auditOperation??"history_repair",auditContext:l.receipt.changed?{...S,provenance_normalization:l.receipt}:S,itemHashVersion:u,explicitItemHashVersion:g.explicitItemHashVersion}),P=na(O);if(!P.ok)throw new _(`history-repair produced an invalid rewritten chain (${P.errors.join(", ")}).`,f.GENERIC_FAILURE);let A=XS(x,g.skippedOps,w);return x&&!k&&A.push(...await QS({pmRoot:t,subject:n,settings:r,typeRegistry:i,historyRawBeforeLock:o,itemReplayContext:p,mergeAbandonmentProof:s.mergeAbandonmentProof,chainOk:c.ok,reanchor:g,author:I,force:s.force,historyPath:n.historyPath,rewrittenEntries:O})),{id:n.id,dry_run:k,changed:x,history:{path:n.historyPath,entries_scanned:a.length,chain_drift_before:!c.ok,entries_rehashed:g.entriesRehashed,entries_patch_repaired:g.entriesPatchRepaired,converted_replace_to_add:g.convertedReplaceToAdd,skipped_ops:g.skippedOps,reconciled_with_item:v,audit_entry_added:W,verify_ok:P.ok,verify_errors:P.errors,item_hash_version_before:d.item_hash_version??null,item_hash_version_after:u,version_disposition:m.size>1?"selected_for_ambiguous_stream":"preserved"},item:{exists:p.currentItemPath!==null,path:p.currentItemPath,matched_chain_before:p.matchedChainBefore},provenance_normalization:{requested:s.normalizeProvenance===!0,...l.receipt},...w?{reconciliation:w}:{},...E?{merge_receipt_proof:E}:{},warnings:[...new Set(A)].sort((K,oe)=>K.localeCompare(oe)),generated_at:T()}}function X1(e,t){if(t&&e!==void 0)throw new _("history-repair: <id> and --all are mutually exclusive; pass an item id to repair one stream or --all to repair every drifted stream.",f.USAGE);if(!t&&e===void 0)throw new _("history-repair: provide an item <id> or pass --all to repair every drifted stream.",f.USAGE)}async function Q1(e,t){if(e.salvageTail===!0)throw new _("Tail salvage requires one explicit item ID; --all is not supported.",f.USAGE);let n=R(process.cwd(),t.path);await $(n);let r=await C(n),i=U(r,F()),s=[],o=await _t(n,r.item_format,i.type_to_folder,s,r.schema,{forceSourceScan:!0}),a=await Xt(n,o),c=e.normalizeProvenance?await pp(n):[],d=[...new Set([...a.driftedItems,...c])].sort((g,p)=>g.localeCompare(p)),l=[],u=[],m={repaired:0,skipped_clean:0,failed:0};for(let g of d)try{let p=await oc(g,{...e,auditContext:e.auditContextById?.[g],auditContextById:void 0,mergeReceiptProof:e.mergeReceiptProofById?.[g]??e.mergeReceiptProof,mergeReceiptProofById:void 0},t),h=p.changed?"repaired":"skipped_clean";m[h]+=1,u.push(...p.warnings.map(y=>`${g}:${y}`)),l.push({id:g,outcome:h,entries_rehashed:p.history.entries_rehashed,entries_patch_repaired:p.history.entries_patch_repaired,reconciled_with_item:p.history.reconciled_with_item,...p.reconciliation?{reconciliation:p.reconciliation}:{},...p.merge_receipt_proof?{merge_receipt_proof:p.merge_receipt_proof}:{},warnings:p.warnings})}catch(p){m.failed+=1,l.push({id:g,outcome:"failed",error:p instanceof Error?p.message:String(p)})}return e.dryRun||await Cu(n),{all:!0,dry_run:!!e.dryRun,scanned_streams:o.length,drifted_streams:a.driftedItems.length,provenance_invalid_streams:c.length,streams:l,totals:m,warnings:[...new Set([...s,...u])].sort((g,p)=>g.localeCompare(p)),generated_at:T()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cd7acf28-cb93-516e-9058-54c32625ec26")}catch{}})();function _s(e,t,n=25){let r=e.definitions.filter(o=>o.roles.length===0).map(o=>o.id).sort((o,a)=>o.localeCompare(a)),i=new Set(r),s=t.filter(o=>{let a=kn(o.status,e);return a!==void 0&&i.has(a)}).map(o=>o.id).sort((o,a)=>o.localeCompare(a));return{roleless_status_count:r.length,roleless_statuses:r.slice(0,n),roleless_statuses_truncated:r.length>n,affected_item_count:s.length,affected_item_ids:s.slice(0,n),affected_item_ids_truncated:s.length>n}}function ps(e){return e.roleless_status_count===0?[]:[`schema_status_missing_lifecycle_role:${e.roleless_status_count}`]}import vt from"node:fs/promises";import Re from"node:path";import Cr from"node:fs/promises";import gs from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="79f9ccbd-48d1-5eb3-82ae-3dd62427041c")}catch{}})();function tx(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t,{id:r,owner:i,created_at:s,ttl_seconds:o}=n;return typeof r!="string"||typeof i!="string"||typeof s!="string"||typeof o!="number"||!Number.isFinite(o)?null:{id:r,owner:i,created_at:s,ttl_seconds:o}}function eg(e,t,n){let r=tx(t);if(r===null)return{detail:"unparseable_json",entry:{file:e,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"}};let i=Date.parse(r.created_at);if(!Number.isFinite(i))return{detail:"invalid_timestamp",entry:{file:e,id:r.id,owner:r.owner,created_at:r.created_at,ttl_seconds:r.ttl_seconds,age_seconds:null,stale:!1,reason:"unparseable"}};let s=n-i,o=Math.floor(s/1e3),a=s>r.ttl_seconds*1e3;return{detail:a?"expired":"active",entry:{file:e,id:r.id,owner:r.owner,created_at:r.created_at,ttl_seconds:r.ttl_seconds,age_seconds:o,stale:a,reason:a?"expired":"active"}}}async function tg(e,t){let n=t??Date.now(),r=gs.join(e,"locks"),i={scanned:0,active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0},s;try{s=(await Cr.readdir(r)).filter(a=>a.endsWith(".lock")).sort()}catch(o){if(j(o))return i;throw o}for(let o of s){let a;try{a=await Cr.readFile(gs.join(r,o),"utf8")}catch(d){if(j(d))continue;i.scanned+=1,i.unreadable_lock_count+=1;continue}i.scanned+=1;let{detail:c}=eg(o,a,n);c==="active"?i.active_lock_count+=1:c==="expired"?i.stale_lock_count+=1:i.unparseable_lock_count+=1}return i}async function ng(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),s=gs.join(e,"locks"),o={scanned:0,removed:[],retained:[],warnings:[],entries:[]},a;try{a=(await Cr.readdir(s)).filter(d=>d.endsWith(".lock")).sort()}catch(c){if(j(c))return o;throw c}for(let c of a){o.scanned+=1;let d=gs.join(s,c),l=`locks/${c}`;if(r?.onRead){let g=await r.onRead(d);o.warnings.push(...g)}let u;try{u=await Cr.readFile(d,"utf8")}catch(g){if(j(g)){o.scanned-=1;continue}o.warnings.push(`lock_unreadable:${c}`),o.retained.push(l),o.entries.push({file:c,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let m=eg(c,u,i);if(m.detail==="unparseable_json"){o.warnings.push(`lock_unparseable:${c}`),o.retained.push(l),o.entries.push(m.entry);continue}if(m.detail==="invalid_timestamp"){o.warnings.push(`lock_invalid_timestamp:${c}`),o.retained.push(l),o.entries.push(m.entry);continue}if(m.detail==="active"){o.retained.push(l),o.entries.push(m.entry);continue}if(!n){try{await Cr.unlink(d)}catch(g){if(!j(g)){o.warnings.push(`lock_remove_failed:${c}`),o.retained.push(l),o.entries.push(m.entry);continue}}if(r?.onWrite){let g=await r.onWrite(d);o.warnings.push(...g)}}o.removed.push(l),o.entries.push(m.entry)}return o}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8e57e03e-3c60-5c1b-b455-9318df8027f6")}catch{}})();var nx=Object.freeze([{code:"missing_directory",command:"pm init",summary:"Recreate missing tracker directories (pm init is idempotent and restores the scaffold)."},{code:"settings_read_fs_error",command:"pm config list --json",summary:"settings.json could not be read as a regular file and pm fell back to defaults; repair the reported path or permissions, then re-run."},{code:"settings_read_invalid_json",command:"pm config list --json",summary:"settings.json is not valid JSON and pm fell back to defaults; fix the syntax error in the reported path, then re-run."},{code:"settings_read_invalid_schema",command:"pm config list --json",summary:"settings.json failed schema validation and pm fell back to defaults; correct the reported key in the file, then re-run."},{code:"settings_read_merge_failed",command:"pm config list --json",summary:"Global/project settings could not be merged; reconcile the conflicting keys in the reported settings files."},{code:"settings:id_prefix_empty",command:"pm config list --json",summary:'id_prefix is empty; set a non-empty "id_prefix" in settings.json so generated item ids are well-formed.'},{code:"settings:locks_ttl_non_positive",command:"pm config list --json",summary:'locks.ttl_seconds must be positive; set a positive "locks.ttl_seconds" in settings.json.'},{code:"telemetry_state_invalid_json",command:"pm health --check-telemetry",summary:"Local telemetry state file is corrupt; pm recreates it on the next flush. Advisory only."},{code:"telemetry_queue_invalid_rows",command:"pm health --check-telemetry",summary:"The telemetry queue has unparseable rows; they are skipped on the next flush. Advisory only."},{code:"telemetry_queue_pending",command:"pm health --check-telemetry",summary:"Telemetry events are queued; they flush automatically on the next reachable command. Advisory only."},{code:"telemetry_queue_high_retries",command:"pm telemetry flush",summary:"Some queued telemetry events are near retry exhaustion; flush now and verify endpoint reachability before entries are dropped."},{code:"telemetry_endpoint_probe_failed",command:"pm health --check-telemetry",summary:"The telemetry endpoint is unreachable; events stay queued until it recovers. Advisory only."},{code:"telemetry_endpoint_probe_http_status",command:"pm health --check-telemetry",summary:"The telemetry endpoint returned a non-success status; events stay queued until it recovers. Advisory only."},{code:"telemetry_schema_version_behind",command:"pm health --check-telemetry",summary:"Client schema is behind server; upgrade pm-cli to emit the latest event shape."},{code:"telemetry_otel_export_failing",command:"pm health --check-telemetry",summary:"OTLP trace spans are queued but the traces endpoint export is failing; spans retry automatically on the next reachable command, or set PM_TELEMETRY_OTEL_DISABLED=1 to skip OTLP export. Advisory only."},{code:"integrity_item_unreadable",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file could not be read; restore or repair the file at the reported path."},{code:"integrity_item_parse_failed",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file failed to parse; fix the malformed item metadata at the reported path."},{code:"integrity_item_conflict_marker",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file contains Git conflict markers; resolve the <<<<<<< / >>>>>>> markers at the reported line."},{code:"integrity_history_unreadable",command:"pm history-repair <id>",summary:"A history stream could not be read; re-anchor the affected item's history chain."},{code:"integrity_history_invalid_json",command:"pm history-repair <id>",summary:"A history stream contains invalid JSON; re-anchor the affected item's history chain."},{code:"integrity_history_conflict_marker",command:"pm history-repair <id>",summary:"A history stream contains Git conflict markers; resolve the markers, then re-anchor the chain."},{code:"validate_storage_unreadable_items",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"An on-disk item file cannot be parsed (for example a botched merge resolution with stale TOON count headers); repair or restore the file at the reported path \u2014 list commands silently skip it while pm get hard-errors."},{code:"validate_storage_duplicate_item_ids",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"One item id is claimed by multiple item documents \u2014 usually two branches minting the same id for different items before merging (GH-600). Keep one document, recreate the other item under a fresh id (pm copy, then delete the colliding file), and consider raising ids.token_length for concurrent multi-agent work."},{code:"validate_storage_history_conflict_markers",command:"pm merge driver history <base> <ours> <theirs>",summary:"A history stream contains unresolved Git conflict markers; re-merge it with the pm history merge driver (or resolve the markers by hand), then run pm history-repair for the item."},{code:"validate_storage_unparseable_history",command:"pm history-repair <id>",summary:"A history stream's newest line is not valid JSONL; repair or restore the stream before further mutations."},{code:"validate_storage_resurrected_items",command:"pm delete <id>",summary:"A live item's newest history operation is a delete: a delete/modify merge silently resurrected it. Decide the winner \u2014 re-delete the item, or keep it and append a mutation documenting the revival."},{code:"validate_storage_unparseable_config",command:"pm merge driver json <base> <ours> <theirs>",summary:"settings.json or a schema file cannot be parsed, so pm silently falls back to defaults; re-merge it with the pm JSON merge driver or fix the file by hand, then rerun pm validate."},{code:"validate_merge_fence_drift",command:"pm merge install",summary:"The committed .gitattributes merge fence no longer matches the active schema's type folders or tracker JSONL stores; rerun pm merge install (and commit .gitattributes) so every tracker artifact keeps its field-aware merge driver."},{code:"validate_storage_tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command, commit the index-only removals and managed .gitignore fence, then rerun validation."},{code:"integrity_item_outdated_format_version",command:"pm validate --verbose-diagnostics",summary:"An item predates the current storage format version; a pm storage migration rewrites it. Use --verbose-diagnostics to list the affected items."},{code:"integrity_item_ahead_format_version",command:"npm install -g @unbrained/pm-cli@latest",summary:"An item was written by a newer pm format version than this runtime supports; upgrade pm to read and validate it safely."},{code:"tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command from the integrity check, commit the index-only removals, and keep the managed .gitignore fence."},{code:"merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:"Review the pending merge receipts, re-apply any intended discarded values, then run pm merge reconcile; lossy receipts require explicit --force acceptance."},{code:"merge_receipts_pending",command:"pm merge reconcile",summary:"A lossless merge receipt is still pending; run pm merge reconcile to settle it (optionally preview first with --dry-run) so a green health gate certifies receipt settlement, not only intact data."},{code:"merge_receipt_evidence_invalid",command:"pm merge report --include-reconciled --json",summary:"One or more receipt candidates failed bounded-file, schema, identity, or copy-consistency validation; inspect the report's privacy-safe source, receipt id, and reason before repairing only the named evidence."},{code:"merge_receipt_history_reference_missing",command:"pm merge reconcile --dry-run",summary:"Review the bounded coordinates and recover available evidence first; for exact pre-durable clone-local-only references, rerun with --force so pm appends an audited disposition and proves the health finding is cleared without rewriting history."},{code:"validate_merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:"Review the pending merge receipts before reconciliation; history-repair alone does not settle them, and lossy receipts require explicit --force acceptance."},{code:"history_drift_missing_stream",command:"pm history-repair <id>",summary:"The item has no history stream; re-anchor the chain to rebuild it (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_unreadable_stream",command:"pm history-repair <id>",summary:"The item's history stream is unreadable; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_hash_mismatch",command:"pm history-repair <id>",summary:"The item's content hash no longer matches its history; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_chain_mismatch",command:"pm history-repair <id>",summary:"The item's history chain is broken; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_version_skew",command:"npm install -g @unbrained/pm-cli@latest",summary:"A history stream declares an item hash version this runtime does not support; upgrade pm to verify the chain instead of re-anchoring it."},{code:"history_drift_merge_receipt",command:"pm merge reconcile",summary:"Canonical path, changed-field, and merged-value hash evidence attributes this drift to a pending receipt; run reconciliation (optionally preview first with --dry-run) instead of repairing history directly."},{code:"history_stream_over_compact_threshold",command:"pm history-compact <id>",summary:"The history stream exceeds the configured compaction threshold; compact it (pm history-compact --all-streams sweeps every over-threshold stream in one pass)."},{code:"history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"provenance_value_domain_invalid",command:"pm history-repair --all --normalize-provenance",summary:"Remove invalid bounded provenance observations from affected streams and append privacy-safe aggregate repair receipts."},{code:"validate_history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"locks_stale_count",command:"pm gc --scope locks",summary:"Stale item-claim locks (embedded ttl elapsed) can block mutations; sweep them \u2014 gc retains active and unparseable locks."},{code:"locks_unreadable",command:"pm gc --scope locks --dry-run",summary:"Some lock files could not be read; preview the sweep and inspect the unreadable files manually \u2014 gc never deletes what it cannot read."},{code:"extension_update_health_partial_coverage",command:"pm extension --adopt-all --project",summary:"Update-health coverage is partial because unmanaged extensions were skipped; adopt the existing installs into managed metadata so the update scan covers them (use --global for global-scope extensions, or pm package --adopt-all when working with packages)."},{code:"vectorization_stale_items_remaining",command:"pm health --refresh-vectors",summary:"Some items have stale embeddings; refresh vectors so semantic search results stay current."},{code:"vectorization_embedding_identity_changed",command:"pm reindex --mode semantic",summary:"Embedding provider/model changed since the last index; run a semantic reindex to rebuild vectors."},{code:"validate_metadata_missing_acceptance_criteria",command:'pm update <id> --acceptance-criteria "<criteria>"',summary:"Backfill the missing acceptance criteria on the reported item(s)."},{code:"validate_metadata_missing_estimate",command:'pm update <id> --estimate "<estimate>"',summary:"Backfill the missing estimate on the reported item(s)."},{code:"validate_metadata_missing_close_reason",command:'pm update <id> --close-reason "<reason>"',summary:"Backfill the missing close reason on the reported closed item(s)."},{code:"validate_metadata_missing_reviewer",command:'pm update <id> --reviewer "<name>"',summary:"Backfill the missing reviewer on the reported item(s)."},{code:"validate_metadata_missing_risk",command:'pm update <id> --risk "<level>"',summary:"Backfill the missing risk on the reported item(s)."},{code:"validate_metadata_missing_confidence",command:'pm update <id> --confidence "<level>"',summary:"Backfill the missing confidence on the reported item(s)."},{code:"validate_metadata_missing_sprint",command:'pm update <id> --sprint "<sprint>"',summary:"Backfill the missing sprint on the reported item(s)."},{code:"validate_metadata_missing_release",command:'pm update <id> --release "<release>"',summary:"Backfill the missing release on the reported item(s)."},{code:"validate_metadata_custom_profile_missing_required_fields",command:'pm config set metadata-required-fields --criterion "<field>"',summary:"Config-driven finding: the custom metadata profile has no required fields configured and falls back to core, so configure the fields rather than mutating items."},{code:"validate_metadata_duplicate_issue_codes",command:'pm update <id> --title "<distinct title>"',summary:"Two or more items share one logical issue code (GH-235); give each a distinct title so the derived code is unique, or close the redundant item with pm close <id> --duplicate-of <canonical-id> (closed-as-duplicate items are excluded from the check)."},{code:"validate_resolution_missing_fields",command:'pm update <id> --resolution "<how resolved>"',summary:"Backfill resolution / expected_result / actual_result on the reported closed item(s)."},{code:"validate_lifecycle_active_closure_like_metadata",command:"pm update <id> --unset <closure-like-field>",summary:"Clear the closure-like field the validator flags on this active item \u2014 the detail row names it (resolution / actual-result / blocked-reason) \u2014 or close the item if it is actually done."},{code:"validate_lifecycle_active_terminal_parent",command:"pm update <id> --parent <active-parent-id>",summary:"Reopen the terminal parent or move the active child under a non-terminal parent."},{code:"validate_lifecycle_stale_blockers",command:"pm update <id> --unset blocked-by --unset blocked-reason",summary:"Resolve the stale blocker the validator flags: clear blocked-by/blocked-reason when they linger on a non-blocked item or report a resolved blocker; if instead a blocked item is missing blocker context, add the context or move it out of a blocked status."},{code:"validate_lifecycle_dependency_cycles_error",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_lifecycle_dependency_cycles",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_hierarchy_parent_cycle_error",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_hierarchy_parent_cycle",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_files_missing_linked_paths",command:"pm <files|docs> <id> --remove <path>",summary:"The check spans both item.files and item.docs under one code: restore the missing linked artifact, or unlink it with pm files (linked file) or pm docs (linked doc)."},{code:"validate_files_orphaned_paths",command:"pm <files|docs> <id> --add <path>",summary:"Link the orphaned artifact with pm files (file) or pm docs (doc), or remove it from the workspace."},{code:"validate_files_tracked_all_strict_forces_pm_internals",command:"pm validate --check-files --include-pm-internals",summary:"tracked-all-strict scan flagged pm internals; re-run with --include-pm-internals or a softer --scan-mode."},{code:"validate_history_drift_missing_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items missing a history stream."},{code:"validate_history_drift_unreadable_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with an unreadable history stream."},{code:"validate_history_drift_hash_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items whose content hash drifted."},{code:"validate_history_drift_chain_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with a broken history chain."},{code:"validate_history_drift_version_skews",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more history streams declare an item hash version this runtime does not support; upgrade pm to verify the chains instead of re-anchoring them."},{code:"validate_command_references_stale_pm_ids",command:'pm update <id> --replace-tests --test "command=<corrected-command>" [--test ...]',summary:"Correct the stale pm-ID inside the item's linked test command (the check scans tests[].command, not the body). --replace-tests overwrites the entire tests list, so re-include the item's other linked tests in the same call."},{code:"validate_format_version_outdated_items",command:"pm validate --verbose-diagnostics",summary:"One or more items predate the current storage format version; a pm storage migration rewrites them. Use --verbose-diagnostics to list the affected items."},{code:"validate_format_version_ahead_items",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more items were written by a newer pm format version than this runtime supports; upgrade pm to read and validate them safely."}]);function ac(e){if(typeof e!="string")return;let t=e.trim();for(let n of nx)if(t===n.code||t.startsWith(`${n.code}:`))return n}function cc(e){let t={};for(let n of e){let r=ac(n);r!==void 0&&!Object.prototype.hasOwnProperty.call(t,r.code)&&(t[r.code]=r.command)}return t}function rg(e){return Object.values(cc(e))}import{execFile as rx}from"node:child_process";import{realpath as ix}from"node:fs/promises";import ig from"node:path";import{promisify as sx}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d18b51d7-294a-52da-b1cf-a10f24aefbc9")}catch{}})();var ox=sx(rx),ax=32*1024*1024,cx=1e4,dx=["search/eval-queries.json"];function dc(e){return e.replaceAll("\\","/").replace(/\/+$/,"")}function lx(e){return`'${e.replaceAll("'","'\\''")}'`}async function ux(e,t=ix){return t(e).catch(()=>ig.resolve(e))}async function hs(e){let t=await Lt(e);if(t===null)return{git_workspace_root:null,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let n=await ux(e),r=dc(ig.relative(t,n));if(r.length===0)return{git_workspace_root:t,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let i=s_.map(s=>`${r}/${dc(s)}`);try{let{stdout:s}=await ox("git",["ls-files","-z","--",...i.map(d=>`:(literal)${d}`)],{cwd:t,encoding:"utf8",maxBuffer:ax,windowsHide:!0,timeout:cx}),o=new Set(dx.map(d=>`${r}/${d}`)),a=[...new Set(s.split("\0").filter(d=>d.length>0&&!o.has(dc(d))))].sort((d,l)=>d.localeCompare(l)),c=i.filter(d=>a.some(l=>l===d||l.startsWith(`${d}/`)));return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:a,tracked_path_count:a.length,remediation_command:a.length===0?null:`git rm --cached -r -- ${c.map(d=>lx(`:(literal)${d}`)).join(" ")}`}}catch{return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:[],tracked_path_count:0,remediation_command:null}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cee8abad-51d2-5051-9cb8-81447bf2fd50")}catch{}})();var mx=new Set(mm),og=25,Un=8,Qt=100,fx=Re.join("runtime","telemetry","events.jsonl"),_x=Re.join("runtime","telemetry","state.json"),px=2500,gx=500,ag=um-3,hx=["x-pm-telemetry-max-schema-version","x-pm-telemetry-max-version"];function pc(e,t=!1){return e.startsWith("telemetry_")||e.startsWith("history_stream_over_compact_threshold:")||e.startsWith("integrity_legacy_hierarchy_")||e.startsWith("stale_in_progress_items:")||e.startsWith("provenance_resolver_zero_success:")||e.startsWith("provenance_value_domain_invalid:")||!t&&e.startsWith("merge_driver_configuration_missing:")}function gc(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function qn(e){return e.trim().toLowerCase()}function mc(e,t){let n=qn(e),r=qn(t);return n.startsWith("builtin-")?!0:r==="beads"||r==="todos"}async function hc(e){try{return(await vt.stat(e)).isDirectory()}catch{return!1}}async function yx(e){let t=(await vt.readdir(e,{withFileTypes:!0})).filter(r=>r.isDirectory()),n=await Promise.all(t.map(r=>vt.readdir(Re.join(e,r.name),{withFileTypes:!0})));return new Set(n.flatMap(r=>r.filter(i=>i.isFile()).filter(i=>Kt.some(s=>i.name.endsWith(s))).map(i=>Re.parse(i.name).name)))}async function vx(e,t,n,r){let i=await Ce({path:e,scope:"project"}),s=t!=="_workspace"&&!r.has(t);if(!n.enabled&&!s)return{warnings:i,overThreshold:!1,classification:"live"};let o;try{o=await vt.readFile(e,"utf8")}catch{return{warnings:i,overThreshold:!1,classification:"unreadable"}}let a="live";if(s){let d=o.split(/\r?\n/).map(l=>l.trim()).filter(Boolean).at(-1);try{a=JSON.parse(d??"{}").op==="delete"?"tombstone":"orphaned"}catch{a="orphaned"}}let c=n.enabled?o.split(/\r?\n/).filter(d=>d.trim().length>0).length:0;return{warnings:i,overThreshold:n.enabled&&c>n.max_entries,classification:a}}async function wx(e,t,n){let r=Re.join(e,"history");if(!await hc(r))return{count:0,warnings:[],over_threshold:[],max_entries:null,tombstones:[],orphaned:[]};let i=(await vt.readdir(r)).filter(u=>u.endsWith(".jsonl")).sort((u,m)=>u.localeCompare(m)),o=t.enabled?t.max_entries:null,a=[],c=[],d=[],l=[];for(let u of i){let m=Re.join(r,u),g=u.slice(0,-6),p=await vx(m,g,t,n);a.push(...p.warnings),p.classification==="tombstone"&&d.push(g),p.classification==="orphaned"&&l.push(g),p.overThreshold&&c.push(g)}return{count:i.length,warnings:[...a,...c.map(u=>`history_stream_over_compact_threshold:${u}`),...l.map(u=>`history_orphaned_stream:${u}`)],over_threshold:c,max_entries:o,tombstones:d,orphaned:l}}function fc(e,t){return Re.relative(e,t).replaceAll("\\","/")}async function cg(e,t){let n=[...new Set(Object.values(t))].sort((i,s)=>i.localeCompare(s)),r=[];for(let i of n){let s=Re.join(e,i),o=[];try{o=await vt.readdir(s)}catch(a){if(typeof a=="object"&&a!==null&&"code"in a&&j(a))continue;continue}for(let a of o)Kt.some(c=>a.toLowerCase().endsWith(c))&&r.push(Re.join(s,a))}return r.sort((i,s)=>fc(e,i).localeCompare(fc(e,s))),r}function bx(e){return!(typeof e=="object"&&e!==null&&"code"in e&&j(e))}async function kx(e,t,n){let r=await cg(e,t),i=[],s=[],o=[],a=[],c=It(F());for(let d of r){let l=fc(e,d),u;try{u=await vt.readFile(d,"utf8")}catch{i.push(l);continue}let m=Ge(u);if(m){s.push({path:l,...m});continue}try{let g=Sn(u,{format:Nl(d),schema:n,extensionFieldNames:c});a.push({ref:l,version:Ei(g.metadata)})}catch{o.push(l)}}return{paths:r,unreadable:i,conflictMarkers:s,parseFailures:o,formatVersions:a}}async function Ex(e){let t=Re.join(e,"history"),n=[],r=[],i=[],s=[],o=[],a=[];try{a=(await vt.readdir(t)).filter(c=>c.endsWith(".jsonl")).sort((c,d)=>c.localeCompare(d))}catch(c){bx(c)&&n.push("history")}for(let c of a){let d=c.slice(0,-6),l;try{l=await vt.readFile(Re.join(t,c),"utf8")}catch{n.push(d);continue}let u=Ge(l);if(u){r.push({id:d,...u});continue}l.split(/\r?\n/).forEach((m,g)=>{if(m.trim())try{let p=JSON.parse(m);s.push(...jp(p,d).map(h=>({itemId:d,line:g+1,...h}))),o.push(...Up(p,d,g+1))}catch{i.push({id:d,line:g+1})}})}return{files:a,unreadable:n,conflictMarkers:r,invalidJson:i,mergeReceiptReferences:s,mergeReceiptDispositions:o}}function dg(e){return[...e.cycles.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_cycle:${t.item_ids.join(",")}`:`integrity_hierarchy_cycle:${t.item_ids.join(",")}`),...e.cardinality_violations.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_cardinality:${t.child_id}`:`integrity_hierarchy_cardinality:${t.child_id}`),...e.divergences.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_divergence:${t.child_id}`:`integrity_hierarchy_divergence:${t.child_id}`)]}function Sx(e){let t=[];return e.invalidEvidenceCount>0&&t.push(`merge_receipt_evidence_invalid:${e.invalidEvidenceCount}`),e.missingHistoryReferenceCount>0&&t.push(`merge_receipt_history_reference_missing:${e.missingHistoryReferenceCount}`),t}async function xx(e,t,n,r,i){let s=await kx(e,t,n),o=await Ex(e),a=Si(s.formatVersions),c=H(n),d=Hi(i,b=>ue(b,c),xe()),l=await hs(e),u=await Lt(e),m=u===null?null:await On(u),g=await st(u??e,{includeReconciled:!0,includeLossless:!0,pmRoot:e}),p=new Set(g.receipts.map(b=>b.id)),h=qp(o.mergeReceiptReferences,p,o.mergeReceiptDispositions),y=h.missing,v=g.receipts.filter(b=>b.state==="pending"),{pendingDecisions:w,lossless:E}=$n(v),S=m?.status==="missing"&&m.missing_keys.length===5&&m.drifted_keys.length===0,x=[...s.unreadable.map(b=>`integrity_item_unreadable:${b}`),...s.conflictMarkers.map(b=>`integrity_item_conflict_marker:${b.path}:L${b.line}`),...s.parseFailures.map(b=>`integrity_item_parse_failed:${b}`),...o.unreadable.map(b=>`integrity_history_unreadable:${b}`),...o.conflictMarkers.map(b=>`integrity_history_conflict_marker:${b.id}:L${b.line}`),...o.invalidJson.map(b=>`integrity_history_invalid_json:${b.id}:L${b.line}`),...a.outdated.map(b=>`integrity_item_outdated_format_version:${b}`),...a.ahead.map(b=>`integrity_item_ahead_format_version:${b}`),...dg(d),...l.tracked_path_count>0?[`tracked_runtime_cache_files:${l.tracked_path_count}`]:[],...m!==null&&m.status!=="ok"?[`merge_driver_configuration_${S?"missing":"drift"}:${m.missing_keys.length+m.drifted_keys.length}`]:[],...w.length>0?[`merge_decisions_unreviewed:${w.length}`]:[],...E.length>0?[`merge_receipts_pending:${E.length}`]:[],...Sx({invalidEvidenceCount:g.invalid_evidence_count,missingHistoryReferenceCount:y.length})],I=[...new Set(x)].sort((b,O)=>b.localeCompare(O)),k=I.filter(b=>!b.startsWith("integrity_legacy_hierarchy_"));return{check:{name:"integrity",status:k.length===0?"ok":"warn",ok:k.length===0,details:{checked_item_files:s.paths.length,checked_history_streams:o.files.length,counts:{item_unreadable:s.unreadable.length,item_conflict_markers:s.conflictMarkers.length,item_parse_failures:s.parseFailures.length,history_unreadable:o.unreadable.length,history_conflict_markers:o.conflictMarkers.length,history_invalid_json:o.invalidJson.length,item_outdated_format_version:a.outdated.length,item_ahead_format_version:a.ahead.length,hierarchy_cycles:d.cycles.length,hierarchy_cardinality_violations:d.cardinality_violations.length,hierarchy_parent_divergences:d.divergences.length,tracked_runtime_cache_files:l.tracked_path_count,merge_driver_configuration:m===null||m.status==="ok"?0:m.missing_keys.length+m.drifted_keys.length,pending_merge_decisions:w.length,lossless_merge_receipts:E.length,invalid_merge_receipt_evidence:g.invalid_evidence_count,missing_merge_receipt_history_references:y.length,accepted_legacy_merge_receipt_references:h.acceptedLegacyCount,accepted_missing_merge_receipt_dispositions:h.acceptedDispositionCount},item_unreadable:s.unreadable,item_conflict_markers:s.conflictMarkers,item_parse_failures:s.parseFailures,item_outdated_format_version:a.outdated,item_ahead_format_version:a.ahead,hierarchy_integrity:{...d,relations:ot(d.relations,Un)},history_unreadable:o.unreadable,history_conflict_markers:o.conflictMarkers,history_invalid_json:o.invalidJson,tracked_runtime_cache:{tracker_relative_root:l.tracker_relative_root,tracked_paths:l.tracked_paths,tracked_path_count:l.tracked_path_count,remediation_command:l.remediation_command},merge_driver_configuration:m===null?null:{...m,required:r},pending_merge_decision_items:[...new Set(w.map(b=>b.item_id))].sort((b,O)=>b.localeCompare(O)),lossless_merge_receipt_items:[...new Set(E.map(b=>b.item_id))].sort((b,O)=>b.localeCompare(O)),invalid_merge_receipt_evidence_details:g.invalid_evidence,invalid_merge_receipt_evidence_details_truncated:g.invalid_evidence_truncated,missing_merge_receipt_history_reference_details:y.slice(0,Qt),missing_merge_receipt_history_reference_details_truncated:y.length>Qt}},warnings:I,gitWorkspaceRoot:u,pendingMergeReceipts:v}}function Tx(e){if(typeof e.activate=="function")return!0;let t=e.default;return typeof t!="object"||t===null?!1:typeof t.activate=="function"}function Ix(e){let t={layer:e.layer,directory:e.directory,manifest_path:e.manifest_path,name:e.name,version:e.version,entry:e.entry,priority:e.priority,entry_path:e.entry_path,has_activate:Tx(e.module)};return Array.isArray(e.capabilities)&&(t.capabilities=[...e.capabilities]),t}function Ax(e,t){let n=re(e.id);return n||`migration-${String(t+1).padStart(3,"0")}`}function Cx(e){let n=re(e.status)?.toLowerCase();return n==="failed"?"failed":n==="applied"?"applied":"pending"}function Rx(e){return re(e.reason)??re(e.error)??re(e.message)}function lc(e,t){let n=(e.layer??"").localeCompare(t.layer??"");if(n!==0)return n;let r=(e.name??"").localeCompare(t.name??"");return r!==0?r:(e.id??"").localeCompare(t.id??"")}function Ox(e){let t=[],n=[],r=[];e.forEach((s,o)=>{let a=Ax(s.definition,o),c=Cx(s.definition);if(c==="applied"){t.push({layer:s.layer,name:s.name,id:a,status:c});return}if(c==="failed"){r.push({layer:s.layer,name:s.name,id:a,status:c,reason:Rx(s.definition)});return}n.push({layer:s.layer,name:s.name,id:a,status:c})}),t.sort(lc),n.sort(lc),r.sort(lc);let i=[...r.map(s=>`extension_migration_failed:${s.layer}:${s.name}:${s.id}`),...n.map(s=>`extension_migration_pending:${s.layer}:${s.name}:${s.id}`)];return{summary:{applied:t,pending:n,failed:r,applied_count:t.length,pending_count:n.length,failed_count:r.length},warnings:i}}function lg(e,t,n,r,i,s,o,a,c){let d=[...new Set(e)].sort((y,v)=>y.localeCompare(v)),l=[...new Set(d.map(y=>gc(y)))].sort((y,v)=>y.localeCompare(v)),u=d.filter(y=>y.startsWith("extension_capability_unknown:")).length,m=c.length>0,g=m?"partial":"full",p=[],h=p_(d,{deactivate:"pm extension --deactivate <name> --project/--global",doctor:"pm extension --doctor --project/--global --detail deep --trace"});return h&&p.push(h),t>0&&p.push("Run pm extension --explore --project and pm extension --explore --global to inspect load failures."),n>0&&p.push("Review checks[name=extensions].details.activation.failed in pm health --json for activation error details."),(r.failed_count>0||r.pending_count>0)&&p.push("Resolve pending/failed extension migrations before write commands; use --force only when policy allows."),i>0&&p.push("Run pm extension --manage --project and pm extension --manage --global to refresh managed-state diagnostics."),u>0&&p.push(`Unknown extension capabilities detected. Allowed capabilities: ${gl.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`),d.some(y=>y.startsWith("extension_capability_legacy_alias:"))&&p.push("Legacy extension capability aliases were auto-remapped to canonical capabilities. Update manifests to canonical names (migration/validation -> schema)."),d.some(y=>y.startsWith("extension_command_definition_legacy_handler_alias:"))&&p.push("Extension command definitions using legacy handler were auto-remapped. Update command definitions to use run: (context) => ... for forward compatibility."),m?p.push("Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via pm extension --manage --project/--global --fix-managed-state, pm extension --adopt-all --project/--global, or pm extension --adopt <name>."):o.length>0&&p.push("Loaded unmanaged extensions are currently treated as informational. Use pm extension --manage --project/--global --fix-managed-state to adopt them for update checks."),p.length===0&&p.push("No immediate action required. Re-run pm health after extension configuration changes."),{status:d.length===0?"ok":"warn",warning_count:d.length,warning_codes:l,load_failure_count:t,activation_failure_count:n,migration_failed_count:r.failed_count,migration_pending_count:r.pending_count,managed_state_warning_count:i,managed_extension_entries_count:s,unmanaged_loaded_extension_count:o.length,unmanaged_loaded_extensions:o,unmanaged_expected_extension_count:a.length,unmanaged_expected_extensions:a,unmanaged_action_required_extension_count:c.length,unmanaged_action_required_extensions:c,update_health_coverage:g,update_health_partial:m,unknown_capability_count:u,top_warnings:d.slice(0,8),remediation:p}}async function Dx(e,t,n){let r=await h_(Ze(e)),i=await mi({pmRoot:e,settings:t,cwd:process.cwd(),noExtensions:n}),s=i.loaded.map(k=>Ix(k)),o=await tp(i.loaded,Ze(e)),a=await fi({...i,loaded:i.loaded}),[c,d]=await Promise.all([ba(i.roots.project),ba(i.roots.global)]);await g_(e,a.registrations.migrations);let l=Ox(a.registrations.migrations),u={failed:a.failed,warnings:a.warnings,hook_counts:a.hook_counts,command_override_count:a.command_override_count,command_handler_count:a.command_handler_count,parser_override_count:a.parser_override_count,preflight_override_count:a.preflight_override_count,service_override_count:a.service_override_count,renderer_override_count:a.renderer_override_count,registration_counts:a.registration_counts,registrations:a.registrations,migration_status:l.summary,managed_extensions:{project:{path:c.path,count:c.state.entries.length,entries:c.state.entries},global:{path:d.path,count:d.state.entries.length,entries:d.state.entries}}},m=new Set(c.state.entries.map(k=>qn(k.name))),g=new Set(d.state.entries.map(k=>qn(k.name))),p=[...new Map(i.loaded.filter(k=>!(k.layer==="project"?m:g).has(qn(k.name))).map(k=>[`${k.layer}:${k.name}`,{layer:k.layer,name:k.name,directory:k.directory}])).values()].sort((k,b)=>{let O=`${k.layer}:${k.name}`,W=`${b.layer}:${b.name}`;return O.localeCompare(W)}),h=p.map(k=>`${k.layer}:${k.name}`).sort((k,b)=>k.localeCompare(b)),y=p.filter(k=>mc(k.name,k.directory)).map(k=>`${k.layer}:${k.name}`).sort((k,b)=>k.localeCompare(b)),v=p.filter(k=>!mc(k.name,k.directory)).map(k=>`${k.layer}:${k.name}`).sort((k,b)=>k.localeCompare(b)),w=v.length>0?[`extension_update_health_partial_coverage:skipped_unmanaged:${v.length}`]:[],E=[...r.warnings,...i.warnings,...u.warnings,...l.warnings,...c.warnings,...d.warnings,...w,...o.warnings],S=ka(E),x=Ea(),I=lg(E,i.failed.length,a.failed.length,l.summary,c.warnings.length+d.warnings.length,c.state.entries.length+d.state.entries.length,h,y,v);return{check:{name:"extensions",status:E.length===0?"ok":"warn",ok:E.length===0,details:{...i,loaded:s,warnings:E,activation:u,author_manifest:r,triage:I,...l.summary.pending_count>0?{remediation_map:{extension_migration_pending:"pm extension migrate --project"}}:{},capability_contract:x,capability_guidance:S,host_version_census:o}},warnings:E}}function Lx(e,t){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function ot(e,t){return Array.isArray(e)?{count:e.length,sample:e.slice(0,t),truncated:e.length>t}:{count:0,sample:[],truncated:!1}}function Nx(e){if(typeof e!="object"||e===null||Array.isArray(e))return{};let t=e;return{layer:t.layer,directory:t.directory,name:t.name,version:t.version,enabled:t.enabled,status:t.status,has_activate:t.has_activate,capabilities:t.capabilities}}function ys(e,t){let n=ot(e,t);return{...n,sample:n.sample.map(r=>Nx(r))}}function B(e,t){if(!Array.isArray(e))return{count:0,sample:[],truncated:!1};let n=e.filter(r=>typeof r=="string");return{count:n.length,sample:n.slice(0,t),truncated:n.length>t}}function Mx(e){if(typeof e!="object"||e===null)return null;let t=e;return{applied_count:t.applied_count,pending_count:t.pending_count,failed_count:t.failed_count}}var Px={settings:(e,t)=>({version:e.version,id_prefix:e.id_prefix,locks_ttl_seconds:e.locks_ttl_seconds,warnings:B(e.warnings,t)}),directories:(e,t)=>({required_count:Array.isArray(e.required)?e.required.length:0,optional_count:Array.isArray(e.optional)?e.optional.length:0,missing_required:B(e.missing_required,t),missing_optional:B(e.missing_optional,t),missing:B(e.missing,t),strict_directories:e.strict_directories}),settings_values:(e,t)=>({warnings:B(e.warnings,t)}),telemetry:e=>({enabled:e.enabled,capture_level:e.capture_level,endpoint:e.endpoint,queue_exists:e.queue_exists,queue_entries:e.queue_entries,queue_draining:e.queue_draining,queue_invalid_rows:e.queue_invalid_rows,queue_rows_total:e.queue_rows_total,last_successful_flush_at:e.last_successful_flush_at,last_failed_flush_at:e.last_failed_flush_at,endpoint_probe:e.endpoint_probe,env_overrides:e.env_overrides}),extensions:(e,t)=>{let n=typeof e.activation=="object"&&e.activation!==null?e.activation:{};return{disabled_by_flag:e.disabled_by_flag,discovered:ys(e.discovered,t),effective:ys(e.effective,t),loaded:ys(e.loaded,t),failed:ot(e.failed,t),warnings:B(e.warnings,t),activation:{failed:ot(n.failed,t),warnings:B(n.warnings,t),hook_counts:n.hook_counts,command_handler_count:n.command_handler_count,service_override_count:n.service_override_count,renderer_override_count:n.renderer_override_count,registration_counts:n.registration_counts,migration_status:Mx(n.migration_status)},author_manifest:e.author_manifest,triage:e.triage,capability_contract:e.capability_contract,capability_guidance:ot(e.capability_guidance,t),host_version_census:e.host_version_census}},storage:(e,t)=>{let n=typeof e.author_attribution=="object"&&e.author_attribution!==null?e.author_attribution:void 0;return{...e,...n?{author_attribution:{...n,affected_item_ids:B(n.affected_item_ids,t),samples:ot(n.samples,t)}}:{}}},locks:e=>({active_lock_count:e.active_lock_count,stale_lock_count:e.stale_lock_count,unreadable_lock_count:e.unreadable_lock_count,unparseable_lock_count:e.unparseable_lock_count}),integrity:(e,t)=>{let n=typeof e.tracked_runtime_cache=="object"&&e.tracked_runtime_cache!==null?e.tracked_runtime_cache:void 0;return{checked_item_files:e.checked_item_files,checked_history_streams:e.checked_history_streams,counts:e.counts,item_unreadable:B(e.item_unreadable,t),item_conflict_markers:ot(e.item_conflict_markers,t),item_parse_failures:B(e.item_parse_failures,t),tracked_runtime_cache:n===void 0?e.tracked_runtime_cache:{...n,tracked_paths:B(n.tracked_paths,t)},history_unreadable:B(e.history_unreadable,t),history_conflict_markers:ot(e.history_conflict_markers,t),history_invalid_json:ot(e.history_invalid_json,t),skipped:e.skipped}},history_drift:(e,t)=>{let n=typeof e.cache_confirmation=="object"&&e.cache_confirmation!==null?e.cache_confirmation:void 0;return{checked_items:e.checked_items,cache_hit_verification:e.cache_hit_verification,cache_confirmation:n===void 0?e.cache_confirmation:{...n,candidate_items:B(n.candidate_items,t),confirmed_items:B(n.confirmed_items,t),resolved_false_positive_items:B(n.resolved_false_positive_items,t)},counts:e.counts,drifted_items:B(e.drifted_items,t),merge_receipt_attributed_items:B(e.merge_receipt_attributed_items,t),missing_streams:B(e.missing_streams,t),unreadable_streams:B(e.unreadable_streams,t),hash_mismatches:B(e.hash_mismatches,t),chain_mismatches:B(e.chain_mismatches,t),version_skews:B(e.version_skews,t),workspace_state_mismatches:B(e.workspace_state_mismatches,t),workspace_state_missing:B(e.workspace_state_missing,t),workspace_state_unreadable:B(e.workspace_state_unreadable,t),skipped:e.skipped}},vectorization:(e,t)=>({semantic_runtime_available:e.semantic_runtime_available,compatibility_mode_auto_defaults:e.compatibility_mode_auto_defaults,auto_ollama_defaults_applied:e.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:e.auto_ollama_defaults_skipped_reason,auto_ollama_defaults_remediation:e.auto_ollama_defaults_remediation,refresh_policy:e.refresh_policy,provider_active:e.provider_active,vector_store_active:e.vector_store_active,items:e.items,ledger_entries_before:e.ledger_entries_before,stale_items_before_total:e.stale_items_before_total,stale_items_before:B(e.stale_items_before,t),refresh_attempted:e.refresh_attempted,refresh_skipped_reason:e.refresh_skipped_reason,refresh_result:e.refresh_result,ledger_entries_after:e.ledger_entries_after,stale_items_after_total:e.stale_items_after_total,stale_items_after:B(e.stale_items_after,t),skipped:e.skipped})};function ug(e,t){let n=Px[e.name];return n?n(e.details,t):e.details}function Fx(e){let t=B(e.warnings,Un);return{ok:e.ok,...e.verdict?{verdict:e.verdict}:{},checks:e.checks.map(n=>({name:n.name,status:n.status,ok:n.ok,details:ug(n,Un)})),warnings:t.sample,findings:e.findings.filter(n=>t.sample.includes(n.warning)||e.failed_because.includes(n.warning)),failed_because:e.failed_because,projection:{mode:"brief",warning_count:t.count,warnings_truncated:t.truncated,detail_limit:Un},generated_at:e.generated_at}}function sg(e){return e.details.skipped===!0}function $x(e){let t=B(e.warnings,Un),n=e.checks.filter(sg).map(r=>r.name);return{ok:e.ok,...e.verdict?{verdict:e.verdict}:{},checks:e.checks.filter(r=>!sg(r)).map(r=>({name:r.name,status:r.status,ok:r.ok,details:{}})),warning_count:t.count,warnings:t.sample,findings:e.findings.filter(r=>t.sample.includes(r.warning)||e.failed_because.includes(r.warning)),failed_because:e.failed_because,projection:{mode:"summary",warning_count:t.count,warnings_truncated:t.truncated,detail_limit:Un,omitted_checks:n},generated_at:e.generated_at}}function _c(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=Lx(e,og);return{values:n.values,truncated:n.truncated,total:e.length}}function jn(e){let t=(process.env[e]??"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function jx(){let e=(process.env.PM_TELEMETRY_SOURCE_CONTEXT??"").trim().toLowerCase();return mx.has(e)?e:null}function vs(e){let t=e.trim();if(t.length===0)return"";try{let n=new URL(t);return n.username="",n.password="",n.search="",n.hash="",n.toString()}catch{return t}}function mg(e){let t=0,n=0,r=0,i=0,s=0;for(let o of e.split(`
|
|
16
|
-
`)){let a=o.trim();if(a.length!==0){r+=1;try{let c=JSON.parse(a);if(typeof c=="object"&&c!==null&&typeof c.attempts=="number"&&Number.isFinite(c.attempts)){let d=Math.max(0,Math.trunc(c.attempts));t+=1,s=Math.max(s,d),d>=ag&&(i+=1)}else n+=1}catch{n+=1}}}return{validEntries:t,invalidRows:n,totalRows:r,highRetryEntries:i,maxAttempts:s}}function Ux(){return{validEntries:0,invalidRows:0,totalRows:0,highRetryEntries:0,maxAttempts:0}}function qx(e){if(!e||e.trim().length===0)return{runtimeState:{},stateParseFailed:!1};try{let t=JSON.parse(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)?{runtimeState:t,stateParseFailed:!1}:{runtimeState:{},stateParseFailed:!0}}catch{return{runtimeState:{},stateParseFailed:!0}}}async function Gx(e,t){let n=e.telemetry.endpoint.trim();return!t||!e.telemetry.enabled||n.length===0?void 0:{attempted:!0,...await fg(n)}}function Kx(e,t,n){let r=[];if(t.invalidRows>0&&r.push(`telemetry_queue_invalid_rows:${t.invalidRows}`),!e.telemetry.enabled||t.validEntries===0)return r;let i=n.last_successful_flush_at,s=n.last_failed_flush_at,o=s&&(!i||s>i),a=!i,c=t.validEntries>=gx;return(o||a||c)&&r.push(`telemetry_queue_pending:${t.validEntries}`),t.highRetryEntries>0&&r.push(`telemetry_queue_high_retries:${t.highRetryEntries}`),r}function zx(e){return!e||e.ok!==!1?[]:typeof e.status=="number"?[`telemetry_endpoint_probe_http_status:${e.status}`]:["telemetry_endpoint_probe_failed"]}function Bx(e){let t=Number.parseInt(e?.max_schema_version??"",10);return e?.ok===!0&&Number.isInteger(t)&&t>lm?[`telemetry_schema_version_behind:${t}`]:[]}function Hx(e,t){let n=typeof t.pending_otel_spans=="number"?t.pending_otel_spans:0,r=t.last_otel_success_at,i=t.last_otel_failure_at;return e.telemetry.enabled&&n>0&&!!i&&(!r||i>=r)?[`telemetry_otel_export_failing:${n}`]:[]}function Wx(){return{telemetry_disabled:jn("PM_TELEMETRY_DISABLED")||jn("PM_NO_TELEMETRY"),pm_no_telemetry:jn("PM_NO_TELEMETRY"),telemetry_otel_disabled:jn("PM_TELEMETRY_OTEL_DISABLED"),telemetry_inline_flush:jn("PM_TELEMETRY_INLINE_FLUSH"),telemetry_source_context:jx()}}function Vx(e,t){return e.telemetry.enabled&&t.validEntries>0}function Yx(e,t){return e&&t.every(n=>!n.startsWith("telemetry_queue_pending:")&&!n.startsWith("telemetry_queue_high_retries:"))}async function fg(e){let t=e;try{let n=new URL(e);n.pathname="/healthz",n.search="",n.hash="",t=n.toString()}catch{}try{let n=await fetch(t,{method:"GET",signal:AbortSignal.timeout(px)});return{probe_url:vs(t),ok:n.ok,status:n.status,max_schema_version:(()=>{for(let r of hx){let i=n.headers.get(r)?.trim();if(i&&i.length>0)return i}})()}}catch(n){return{probe_url:vs(t),ok:!1,error:n instanceof Error?n.message:"probe_failed"}}}async function Jx(e,t){let n=et(process.cwd()),r=Re.join(n,fx),i=Re.join(n,_x),s=await Y(r),o=s!==null,a=s?Buffer.byteLength(s,"utf8"):0,c=s?mg(s):Ux(),d=await Y(i),{runtimeState:l,stateParseFailed:u}=qx(d),m=e.telemetry.endpoint.trim(),g=vs(m),p=await Gx(e,t.checkTelemetry),h=[];u&&h.push("telemetry_state_invalid_json"),h.push(...Kx(e,c,l),...zx(p),...Bx(p),...Hx(e,l));let y=Vx(e,c),v=typeof l.pending_otel_spans=="number"?l.pending_otel_spans:0;return{check:{name:"telemetry",status:h.length===0?"ok":"warn",ok:h.length===0,details:{enabled:e.telemetry.enabled,capture_level:e.telemetry.capture_level,endpoint:g,global_pm_root:n,queue_path:r,queue_exists:o,queue_entries:c.validEntries,queue_draining:Yx(y,h),queue_invalid_rows:c.invalidRows,queue_rows_total:c.totalRows,queue_size_bytes:a,queue_high_retry_entries:c.highRetryEntries,queue_high_retry_threshold:ag,queue_max_attempts:c.maxAttempts,runtime_state_path:i,last_attempted_flush_at:l.last_attempted_flush_at??null,last_successful_flush_at:l.last_successful_flush_at??null,last_failed_flush_at:l.last_failed_flush_at??null,last_failed_flush_error:l.last_failed_flush_error??null,pending_otel_spans:v,last_otel_attempt_at:l.last_otel_attempt_at??null,last_otel_success_at:l.last_otel_success_at??null,last_otel_failure_at:l.last_otel_failure_at??null,last_otel_failure_error:l.last_otel_failure_error??null,endpoint_probe:p??{attempted:!1},env_overrides:Wx()}},warnings:h}}async function Xx(e){let t;try{t=await tg(e)}catch(r){let i=r instanceof Error?r.message:String(r);return{check:{name:"locks",status:"warn",ok:!1,details:{active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0,scan_failed:!0,error:i,pm_root:e}},warnings:[`locks_scan_failed:${i}`]}}let n=[];return t.stale_lock_count>0&&n.push(`locks_stale_count:${t.stale_lock_count}`),t.unreadable_lock_count>0&&n.push(`locks_unreadable:${t.unreadable_lock_count}`),{check:{name:"locks",status:n.length===0?"ok":"warn",ok:n.length===0,details:{active_lock_count:t.active_lock_count,stale_lock_count:t.stale_lock_count,unreadable_lock_count:t.unreadable_lock_count,unparseable_lock_count:t.unparseable_lock_count}},warnings:n}}async function Qx(e){let t="metadata",n=e.items,r=await Xt(e.pmRoot,n,{cacheHitVerification:t}),i=[...new Set([...r.hashMismatches,...r.chainMismatches,...r.versionSkews])].sort((v,w)=>v.localeCompare(w)),s=[],o=[];if(i.length>0){n=await _t(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema,{forceSourceScan:!0}),r=await Xt(e.pmRoot,n),s=[...new Set([...r.hashMismatches,...r.chainMismatches,...r.versionSkews])].sort((w,E)=>w.localeCompare(E));let v=new Set(s);o=i.filter(w=>!v.has(w))}let{missingStreams:a,unreadableStreams:c,hashMismatches:d,chainMismatches:l,versionSkews:u,driftedItems:m,workspaceStateMismatches:g,workspaceStateMissing:p,workspaceStateUnreadable:h}=r,y=[...a.map(v=>`history_drift_missing_stream:${v}`),...c.map(v=>`history_drift_unreadable_stream:${v}`),...d.map(v=>`history_drift_hash_mismatch:${v}`),...l.map(v=>`history_drift_chain_mismatch:${v}`),...u.map(v=>`history_drift_version_skew:${v}`),...g.map(v=>`history_drift_workspace_state_mismatch:${v}`),...p.map(v=>`history_drift_workspace_state_missing:${v}`),...h.map(v=>`history_drift_workspace_state_unreadable:${v}`)];return{check:{name:"history_drift",status:y.length===0?"ok":"warn",ok:y.length===0,details:{checked_items:n.length,cache_hit_verification:i.length>0?"metadata_then_content_hash":t,cache_confirmation:{triggered:i.length>0,reason:i.length>0?"cached_corruption_candidate":null,candidate_items:i,confirmed_items:s,resolved_false_positive_items:o,authoritative_item_source:i.length>0},drifted_items:m,counts:{drifted:m.length,missing_streams:a.length,unreadable_streams:c.length,hash_mismatches:d.length,chain_mismatches:l.length,version_skews:u.length,workspace_state_mismatches:g.length,workspace_state_missing:p.length,workspace_state_unreadable:h.length},missing_streams:a,unreadable_streams:c,hash_mismatches:d,chain_mismatches:l,version_skews:u,workspace_state_mismatches:g,workspace_state_missing:p,workspace_state_unreadable:h}},warnings:y}}function Zx(e,t){let n=Yu(e),r=rm(n.settings),i=im(n.settings,t),s=r.active?sm(r.active.name,r.active.model):null;return{runtimeDefaults:n,providerResolution:r,vectorStoreResolution:i,runtimeEmbeddingIdentity:s,semanticRuntimeAvailable:!!(r.active&&i.active)}}function eT(){return{refreshed:[],skipped:[],warnings:[]}}async function tT(e){return!e.refreshPolicy.enabled||!e.snapshot.semanticRuntimeAvailable||e.staleBefore.length===0?eT():am(e.pmRoot,e.staleBefore,{settings:e.snapshot.runtimeDefaults.settings,apply_runtime_defaults:!1})}function nT(e){return e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&!!(e.ledgerBefore.embedding&&e.runtimeEmbeddingIdentity&&om(e.ledgerBefore.embedding,e.runtimeEmbeddingIdentity))}function rT(e){let t=new Set([...e.ledgerBefore.warnings,...e.ledgerAfter.warnings]);if(e.strictVectorizationWarnings)for(let n of e.refreshResult.warnings)t.add(n);return e.embeddingIdentityChanged&&t.add("vectorization_embedding_identity_changed"),e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&e.staleAfter.length>0&&t.add(`vectorization_stale_items_remaining:${e.staleAfter.length}`),[...t].sort((n,r)=>n.localeCompare(r))}function iT(e,t,n){return e.enabled&&t&&n.length>0?null:e.enabled?t?"no_stale_items":"semantic_runtime_unavailable":"refresh_disabled"}function _g(e,t){let n=t.providerResolution.active?.name??null,r=t.vectorStoreResolution.active?.name??null;return{provider_active:n,provider_configured:typeof e.search?.provider=="string"?e.search.provider:null,provider_source:ra(n,e.search?.provider??null),vector_store_active:r,vector_store_configured:typeof e.vector_store?.adapter=="string"?e.vector_store.adapter:null,vector_store_source:ra(r,e.vector_store?.adapter??null)}}function sT(e){return{enabled:e.enabled,check_only:e.checkOnly,no_refresh:e.noRefresh,refresh_vectors:e.refreshVectors}}function oT(e,t,n){return e.enabled&&n.length>0&&t}async function aT(e,t,n,r,i){let s=Zx(t,e),o=await ia(e),a=s.semanticRuntimeAvailable?wa(n,o.entries):[],c=await tT({pmRoot:e,snapshot:s,refreshPolicy:r,staleBefore:a}),d=await ia(e),l=s.semanticRuntimeAvailable?wa(n,d.entries):[],u=!s.runtimeDefaults.auto_ollama_defaults_applied,m=nT({strictVectorizationWarnings:u,semanticRuntimeAvailable:s.semanticRuntimeAvailable,ledgerBefore:o,runtimeEmbeddingIdentity:s.runtimeEmbeddingIdentity}),g=rT({ledgerBefore:o,ledgerAfter:d,refreshResult:c,strictVectorizationWarnings:u,semanticRuntimeAvailable:s.semanticRuntimeAvailable,embeddingIdentityChanged:m,staleAfter:l}),p=_c(a,i),h=_c(l,i),y=oT(r,s.semanticRuntimeAvailable,a);return{check:{name:"vectorization",status:g.length===0?"ok":"warn",ok:g.length===0,details:{semantic_runtime_available:s.semanticRuntimeAvailable,compatibility_mode_auto_defaults:s.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_applied:s.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:s.runtimeDefaults.auto_ollama_defaults_skipped_reason??null,auto_ollama_defaults_remediation:s.runtimeDefaults.auto_ollama_defaults_remediation??null,refresh_policy:sT(r),..._g(t,s),embedding_identity_changed:m,embedding_identity_before:o.embedding??null,embedding_identity_runtime:s.runtimeEmbeddingIdentity??null,items:n.length,ledger_entries_before:Object.keys(o.entries).length,stale_items_detail_mode:i?"full":"summary",stale_items_summary_limit:og,stale_items_before_total:p.total,stale_items_before:p.values,stale_items_before_truncated:p.truncated,refresh_attempted:y,refresh_skipped_reason:iT(r,s.semanticRuntimeAvailable,a),refresh_result:c,ledger_entries_after:Object.keys(d.entries).length,stale_items_after_total:h.total,stale_items_after:h.values,stale_items_after_truncated:h.truncated}},warnings:g}}function cT(e){let t=[];return e.id_prefix.trim().length===0&&t.push("settings:id_prefix_empty"),e.locks.ttl_seconds<=0&&t.push("settings:locks_ttl_non_positive"),t}function pg(e){let t=e.checkOnly===!0,n=e.refreshVectors===!0;if(n&&t)throw new _("--check-only cannot be combined with --refresh-vectors",f.USAGE);if(n&&e.noRefresh===!0)throw new _("--no-refresh cannot be combined with --refresh-vectors",f.USAGE);return{enabled:n,checkOnly:t,noRefresh:!n,refreshVectors:n}}var dT=new Set(["extensions","locks","search"]);function lT(e){let t=new Set(vl.filter(i=>i.length>0)),n=new Set,r=new Set(Object.values(wl));for(let i of e.folders)t.has(i)&&!r.has(i)||(t.delete(i),n.add(i));for(let i of dT)t.delete(i),n.add(i);return{requiredDirs:[...t].sort((i,s)=>i.localeCompare(s)),optionalDirs:[...n].sort((i,s)=>i.localeCompare(s)),optionalDirSet:n}}async function uT(e,t,n){let{requiredDirs:r,optionalDirs:i,optionalDirSet:s}=lT(t),o=[],a=[],c=[];for(let d of[...r,...i]){let l=Re.join(e,d);c.push(...await Ce({path:l,scope:"project"})),!await hc(l)&&(s.has(d)?a.push(d):o.push(d))}return{requiredDirs:r,optionalDirs:i,missingRequiredDirs:o,missingOptionalDirs:a,missingDirs:n?[...o,...a]:[...o],hookWarnings:c}}function gg(e){let t=e.checkOnly===!0&&e.brief!==!0&&e.summary!==!0&&e.full!==!0,n=(e.summary===!0||t)&&e.full!==!0,r=e.checkOnly===!0&&(e.brief===!0||e.summary===!0)&&e.full!==!0;return{summaryMode:n,skipIntegrity:(e.skipIntegrity===!0||r)&&e.full!==!0,skipDrift:(e.skipDrift===!0||r)&&e.full!==!0,skipVectors:(e.skipVectors===!0||r)&&e.full!==!0}}async function mT(e){return e.skipPolicy.skipDrift&&e.skipPolicy.skipVectors?Se(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema):_t(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema)}function uc(e){return{check:{name:e,status:"ok",ok:!0,details:{skipped:!0}},warnings:[]}}function fT(e,t,n){return{name:"settings",status:n.length===0?"ok":"warn",ok:n.length===0,details:{path:e,version:t.version,id_prefix:t.id_prefix,locks_ttl_seconds:t.locks.ttl_seconds,warnings:n}}}function _T(e,t){return{name:"directories",status:e.missingDirs.length===0?"ok":"warn",ok:e.missingDirs.length===0,details:{required:e.requiredDirs,optional:e.optionalDirs,missing_required:e.missingRequiredDirs,missing_optional:e.missingOptionalDirs,missing:e.missingDirs,strict_directories:t}}}function pT(e,t){return{name:"settings_values",status:e.length===0?"ok":"warn",ok:e.length===0,details:{warnings:e,...t.roleless_status_count>0?{lifecycle_status_roles:t}:{}}}}var yc=e=>e.unknown_event_count??0,vc=e=>e.actionable_unknown_event_count??yc(e);function gT(e,t,n,r,i,s,o){let a=yc(r),c=vc(r),d=a>0,l=c>0,u=i.count>0;return{name:"storage",status:n.over_threshold.length===0&&n.orphaned.length===0&&!l&&!u?"ok":"warn",ok:n.over_threshold.length===0&&n.orphaned.length===0&&!l&&!u,details:{items:e.length,history_streams:n.count,tombstones:{retention_policy:"retain_append_only",gc_enabled:!1,count:n.tombstones.length,ids:n.tombstones.slice(0,25),truncated:n.tombstones.length>25},orphaned_history_streams:{count:n.orphaned.length,ids:n.orphaned.slice(0,25),truncated:n.orphaned.length>25},...d?{author_attribution:r}:{},...u?{stale_in_progress:i}:{},...s.length>0?{provenance_resolver_outcomes:s}:{},...o.length>0?{provenance_invalid_values:o}:{},...n.max_entries!==null?{compact_policy:{enabled:t.history.compact_policy.enabled,max_entries:n.max_entries,trigger:t.history.compact_policy.trigger,over_threshold_count:n.over_threshold.length,over_threshold:n.over_threshold}}:{}}}}function hg(e){let t=e.count===0?[]:[`stale_in_progress_items:${e.count}`];return{scan:e,warnings:t}}function hT(e){let t=[...e.directoryState.missingDirs.map(n=>`missing_directory:${n}`),...e.normalizedSettingsReadWarnings,...e.settingWarnings,...e.normalizedItemReadWarnings,...e.telemetryCheck.warnings,...e.extensionCheck.warnings,...e.historyPolicyWarnings,...e.historySummary.warnings,...e.authorAttributionWarnings,...e.staleInProgressWarnings,...e.provenanceWarnings,...e.locksCheck.warnings,...e.integrityCheck.warnings,...e.historyDriftCheck.warnings,...e.vectorizationCheck.warnings,...e.directoryState.hookWarnings];return[...new Set(t)]}function yT(e){let t=e.check.details.counts;return typeof t?.drifted=="number"?t.drifted:0}function vT(e){return{settings:e.normalizedSettingsReadWarnings,directories:e.directoryState.missingDirs.map(t=>`missing_directory:${t}`).concat(e.directoryState.hookWarnings),settings_values:e.settingWarnings,telemetry:e.telemetryCheck.warnings,extensions:e.extensionCheck.warnings,storage:[...e.historyPolicyWarnings,...e.historySummary.warnings,...e.authorAttributionWarnings,...e.staleInProgressWarnings,...e.provenanceWarnings],locks:e.locksCheck.warnings,integrity:[...e.normalizedItemReadWarnings,...e.integrityCheck.warnings],history_drift:e.historyDriftCheck.warnings,vectorization:e.vectorizationCheck.warnings}}function yg(e){let t=new Map;for(let[i,s]of Object.entries(e.remediationSources))for(let o of s)t.has(o)||t.set(o,i);let n=new Map(e.checks.map(i=>[i.name,i]));return e.warnings.map(i=>{let s=t.get(i)??"integrity",o=ac(i)?.code??gc(i),a=n.get(s)?.details,d=(typeof a?.remediation_map=="object"&&a.remediation_map!==null?a.remediation_map:{})[o],l=pc(i,e.requireMergeDrivers)?"advisory":"gate_failing";return{warning:i,code:o,check:s,severity:l,...typeof d=="string"?{remediation:d}:l==="gate_failing"?{disposition:"no_safe_automatic_remediation"}:{}}})}function wT(e){if(e.check.name==="history_drift"&&e.historyDriftedCount>1)for(let t of Object.keys(e.remediationMap))t!=="history_drift_merge_receipt"&&t!=="history_drift_version_skew"&&(e.remediationMap[t]="pm history-repair --all");if(e.check.name==="storage"&&e.overThresholdCount>1)for(let t of Object.keys(e.remediationMap))e.remediationMap[t]="pm history-compact --all-streams"}function bT(e){for(let t of e.checks){let n=cc(e.remediationSources[t.name]);wT({check:t,remediationMap:n,historyDriftedCount:e.historyDriftedCount,overThresholdCount:e.overThresholdCount}),Object.keys(n).length>0&&(t.details={...t.details,remediation_map:n})}}async function kT(e){if(e.gitWorkspaceRoot===null||e.pendingMergeReceipts.length===0)return[];let t=e.historyDriftCheck.check.details,n=Array.isArray(t.hash_mismatches)?t.hash_mismatches.filter(o=>typeof o=="string"):[],r=new Set([t.missing_streams,t.unreadable_streams,t.chain_mismatches].flatMap(o=>Array.isArray(o)?o:[])),i=new Map;for(let o of e.pendingMergeReceipts){if(o.evidence_source!=="clone_local")continue;let a=i.get(o.item_id)??[];a.push(o),i.set(o.item_id,a)}let s=[];for(let o of n){if(r.has(o))continue;let a=i.get(o);if(!(!a||a.length===0))try{await oc(o,{dryRun:!0,mergeReceiptProof:{gitWorkspaceRoot:e.gitWorkspaceRoot,receipts:a}},e.global),s.push(o)}catch{}}return[...new Set(s)].sort((o,a)=>o.localeCompare(a))}function ET(e,t){let n=new Set(t);e.warnings=[...e.warnings.filter(r=>r.startsWith("history_drift_hash_mismatch:")?!n.has(r.slice(r.indexOf(":")+1)):!0),...t.map(r=>`history_drift_merge_receipt:${r}`)].sort((r,i)=>r.localeCompare(i)),e.check.details={...e.check.details,merge_receipt_attributed_items:t}}function vg(e,t,n){let r=e.warning_count??e.warnings.length,i={...e,warning_count:r,warning_limit:Qt,warnings_truncated:r>Qt,warnings:e.warnings.slice(0,Qt),findings:(e.findings??[]).filter(o=>e.warnings.slice(0,Qt).includes(o.warning)||e.failed_because.includes(o.warning))},s=n?$x(i):t.brief===!0?Fx(i):i;return{...s,warning_count:r,warning_limit:Qt,warnings_truncated:r>s.warnings.length,...s.projection?{projection:{...s.projection,warning_count:r,warnings_truncated:r>s.warnings.length}}:{}}}async function wg(e,t={}){let n=R(process.cwd(),e.path);await $(n);let r=Ae(n),{settings:i,warnings:s}=await Wu(n),o=[...new Set(s)],a=U(i,F()),c=t.strictDirectories===!0,d=t.strictExit===!0||t.failOnWarn===!0,l=t.requireMergeDrivers===!0||d,u=pg(t),m=await uT(n,a,c),g=cT(i),p=await Jx(i,{checkTelemetry:t.checkTelemetry===!0}),h=await Dx(n,i,!!e.noExtensions),y=gg(t),v=[],w=await mT({pmRoot:n,settings:i,typeRegistry:a,skipPolicy:y,itemReadWarnings:v}),E=w,S=_s(H(i.schema),w),x=[...g,...ps(S)],I=y.skipDrift?{warnings:[]}:await Di({pmRoot:n,settings:i,itemIds:w.map(le=>le.id),commandLabel:"health"}),k=await wx(n,i.history.compact_policy,await yx(n)),b=await Er(n,20,t.verboseAuthorEvents===!0),O=vc(b),W=O>0?[`history_unknown_author_events:${O}`]:[],P=hg(await cm(n,w,{in_progress_status:i.schema.workflow.in_progress_status,threshold_hours:i.mutation_guard.stale_in_progress_hours})),A=await yp(n),K=A.outcomes,oe=A.invalid_values,ae=A.warnings,ye=await Xx(n),$e=y.skipIntegrity&&!l?{...uc("integrity"),gitWorkspaceRoot:null,pendingMergeReceipts:[]}:await xx(n,a.type_to_folder,i.schema,l,w),Je=y.skipDrift?uc("history_drift"):await Qx({pmRoot:n,items:E,settings:i,typeRegistry:a,itemReadWarnings:v}),xt=[...new Set(v)],dt=await kT({gitWorkspaceRoot:$e.gitWorkspaceRoot,pendingMergeReceipts:$e.pendingMergeReceipts,historyDriftCheck:Je,global:e});ET(Je,dt);let _n=y.skipVectors?uc("vectorization"):await aT(n,i,E,u,t.verboseStaleItems===!0),de=[fT(r,i,o),_T(m,c),pT(x,S),p.check,h.check,gT(w,i,k,b,P.scan,K,oe),ye.check,$e.check,Je.check,_n.check],je=hT({directoryState:m,normalizedSettingsReadWarnings:o,settingWarnings:x,normalizedItemReadWarnings:xt,telemetryCheck:p,extensionCheck:h,historyPolicyWarnings:I.warnings,historySummary:k,authorAttributionWarnings:W,staleInProgressWarnings:P.warnings,provenanceWarnings:ae,locksCheck:ye,integrityCheck:$e,historyDriftCheck:Je,vectorizationCheck:_n}),pn=vT({directoryState:m,normalizedSettingsReadWarnings:o,settingWarnings:x,normalizedItemReadWarnings:xt,telemetryCheck:p,extensionCheck:h,historyPolicyWarnings:I.warnings,historySummary:k,authorAttributionWarnings:W,staleInProgressWarnings:P.warnings,provenanceWarnings:ae,locksCheck:ye,integrityCheck:$e,historyDriftCheck:Je,vectorizationCheck:_n});bT({checks:de,remediationSources:pn,historyDriftedCount:yT(Je),overThresholdCount:k.over_threshold.length});let M=je.filter(le=>!pc(le,l)),ve=yg({warnings:je,checks:de,remediationSources:pn,requireMergeDrivers:l}),He=new Set(ve.filter(le=>le.severity==="gate_failing").map(le=>le.check)),gn=new Set(ve.map(le=>le.check));for(let le of de)le.ok=!He.has(le.name),gn.has(le.name)&&(le.status="warn");let Xe={ok:M.length===0,verdict:{authority:"ok",...d?{strict_exit:!0}:{},...l?{require_merge_drivers:!0}:{},exit_code:d&&M.length>0?f.GENERIC_FAILURE:0},checks:de,warnings:je,findings:ve,failed_because:M,generated_at:T()};return vg(Xe,t,y.summaryMode)}var aG={buildHierarchyIntegrityWarnings:dg,buildExtensionHealthTriageSummary:lg,buildHealthFindings:yg,buildCapabilityContractMetadata:Ea,buildStaleInProgressHealthSummary:hg,buildVectorizationProviderDetails:_g,collectUnknownCapabilityGuidance:ka,isAdvisoryHealthWarning:pc,isDirectory:hc,isExpectedUnmanagedExtension:mc,listItemDocumentPaths:cg,normalizeEndpointForDisplay:vs,normalizeExtensionNameForMatch:qn,parseTelemetryQueue:mg,probeTelemetryEndpointHealth:fg,projectHealthResult:vg,resolveActionableUnknownAuthorEventCount:vc,resolveHealthSkipPolicy:gg,resolveUnknownAuthorEventCount:yc,resolveVectorRefreshPolicy:pg,selectStaleItemDetail:_c,summarizeHealthCheckDetails:ug,summarizeExtensionList:ys,summarizeRecordList:ot,summarizeStringList:B,telemetryEnvFlagEnabled:jn,warningCode:gc};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1a4f19cf-56ba-571a-908c-97278a8284f7")}catch{}})();function ST(e,t){return e==="malformed"||t==="malformed"?"malformed":e==="moved"||t==="moved"?"moved":"deleted"}function bg(e){return`${e.item_id} ${e.link_kind}`}function kg(e,t){let n=new Map;for(let r of e){let i=n.get(r.path);i?(i.classification=ST(i.classification,r.classification),i.owners.set(bg(r),r)):n.set(r.path,{classification:r.classification,owners:new Map([[bg(r),r]])})}return[...n.entries()].sort(([r],[i])=>r.localeCompare(i)).map(([r,i])=>({path:r,classification:i.classification,items:[...i.owners.values()].map(s=>{let o=t(s.item_id);return{id:s.item_id,type:o?.type??"Unknown",title:o?.title??"",status:o?.status??"",field:s.link_kind}}).sort((s,o)=>{let a=s.id.localeCompare(o.id);return a!==0?a:s.field.localeCompare(o.field)})}))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d62bc6ec-c345-5196-93b8-280b5484b18a")}catch{}})();function Eg(e,t,n,r,i=40){let s=i===1/0?1/0:Number.isFinite(i)?Math.max(0,Math.floor(i)):40,o=new Map(t.map(d=>[d.path,d])),a={missing_linked_path_rows_count:0,missing_linked_path_rows:[],missing_linked_path_rows_truncated:!1,missing_linked_links_count:0,active_missing_linked_links_count:0,legacy_closed_missing_linked_links_count:0,legacy_terminal_missing_linked_links_count:0,active_missing_linked_paths_count:0},c=kg(e,n).map(d=>{let l=[],u=[];for(let g of d.items){let p=se(g.status,r)??g.status;r.terminal_statuses.has(p)?(u.push(g),p===r.close_status&&(a.legacy_closed_missing_linked_links_count+=1)):l.push(g)}a.missing_linked_links_count+=d.items.length,a.active_missing_linked_links_count+=l.length,a.legacy_terminal_missing_linked_links_count+=u.length,l.length>0&&(a.active_missing_linked_paths_count+=1);let m=o.get(d.path);return{...d,candidates:m?.candidates??[],candidates_truncated:m?.candidates_truncated??!1,link_count:d.items.length,active_link_count:l.length,items:[...l,...u].slice(0,s),items_truncated:d.items.length>s}});return c.sort((d,l)=>+(l.active_link_count>0)-+(d.active_link_count>0)||d.path.localeCompare(l.path)),a.missing_linked_path_rows_count=c.length,a.missing_linked_path_rows=c.slice(0,s),a.missing_linked_path_rows_truncated=c.length>s,a}import Gn from"node:fs/promises";import Kn from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="59b566d5-1d4f-500b-98e3-004e6f57d2b4")}catch{}})();async function xT(e,t){let n=[...new Set(Object.values(t))],r=[];return await Promise.all(n.map(async i=>{let s;try{s=await Gn.readdir(Kn.join(e,i))}catch{return}for(let o of s)for(let a of Kt)if(o.toLowerCase().endsWith(a)){r.push({relativePath:`${i}/${o}`,id:o.slice(0,-a.length)});break}})),r.sort((i,s)=>i.relativePath.localeCompare(s.relativePath))}function TT(e,t){let{id:n,relativePath:r,liveItemIds:i,out:s}=e,o=Ge(t);if(o){s.conflictMarkers.push({id:n,path:r,line:o.line,detail:`unresolved merge conflict marker ${o.marker}`});return}let a=null,c=t.split(/\r?\n/).map((d,l)=>({content:d.trim(),number:l+1})).filter(d=>d.content.length>0);for(let d of c)try{let l=JSON.parse(d.content);if(typeof l!="object"||l===null||Array.isArray(l))throw new TypeError("history entry must be an object");a=l}catch{s.unparseable.push({id:n,path:r,line:d.number,detail:"history line is not a valid JSON object"});return}a!==null&&(a.op==="delete"&&i.has(n)&&s.resurrected.push({id:n,deleted_at:typeof a.ts=="string"?a.ts:"",deleted_by:typeof a.author=="string"?a.author:""}),a.op==="history_repair"&&Array.isArray(a.patch)&&a.patch.length>0&&(s.repairReconciliations+=1))}function wc(e,t){let n=typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"?t.code:"UNKNOWN";return`${e} could not be read (error code: ${n})`}async function IT(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},r;try{r=await Gn.readdir(Kn.join(e,"history"))}catch{return n}for(let i of r.sort((s,o)=>s.localeCompare(o))){if(!i.endsWith(".jsonl"))continue;n.scanned+=1;let s;try{s=await Gn.readFile(Kn.join(e,"history",i),"utf8")}catch(o){n.unparseable.push({id:i.slice(0,-6),path:`history/${i}`,detail:wc("history stream",o)});continue}TT({id:i.slice(0,-6),relativePath:`history/${i}`,liveItemIds:t,out:n},s)}return n}function Sg(e){let t=Ge(e);if(t)return`unresolved merge conflict marker ${t.marker} at line ${t.line}`;try{return JSON.parse(e),null}catch(n){return`invalid JSON (${String(n)})`}}async function AT(e){let t=[],n=0,r=null;try{r=await Y(Ae(e))}catch(s){n+=1,t.push({path:"settings.json",detail:wc("configuration file",s)})}if(r!==null){n+=1;let s=Sg(r);s!==null&&t.push({path:"settings.json",detail:s})}let i;try{i=await Gn.readdir(Kn.join(e,"schema"))}catch{return{scanned:n,unparseable:t}}for(let s of i.sort((o,a)=>o.localeCompare(a))){if(!s.endsWith(".json"))continue;n+=1;let o;try{o=await Gn.readFile(Kn.join(e,"schema",s),"utf8")}catch(c){t.push({path:`schema/${s}`,detail:wc("configuration file",c)});continue}let a=Sg(o);a!==null&&t.push({path:`schema/${s}`,detail:a})}return{scanned:n,unparseable:t}}async function xg(e,t,n,r={}){let i=await xT(e,n),s=new Set(i.map(u=>u.id)),o=new Map;for(let u of i){let m=o.get(u.id);m===void 0?o.set(u.id,[u.relativePath]):m.push(u.relativePath)}let a=[...o.entries()].filter(([,u])=>u.length>1).map(([u,m])=>({id:u,paths:[...m].sort((g,p)=>g.localeCompare(p))})).sort((u,m)=>u.id.localeCompare(m.id)),c=(await Promise.all(i.map(async u=>{if(!t.has(u.id))return{path:u.relativePath,id:u.id};try{let m=Kn.join(e,u.relativePath);return Sn(await Gn.readFile(m,"utf8"),{format:m.toLowerCase().endsWith(".md")?"json_markdown":"toon",schema:r.schema,extensionFieldNames:r.extensionFieldNames}),null}catch{return{path:u.relativePath,id:u.id}}}))).filter(u=>u!==null),d=await IT(e,s),l=await AT(e);return{item_files_on_disk:i.length,item_ids_on_disk:s.size,parsed_items:t.size,unreadable_item_files:c,duplicate_item_ids:a,history_streams_scanned:d.scanned,history_conflict_marker_streams:d.conflictMarkers,history_unparseable_streams:d.unparseable,resurrected_items:d.resurrected,history_repair_reconciliations:d.repairReconciliations,config_files_scanned:l.scanned,unparseable_config_files:l.unparseable}}import RT from"node:fs/promises";import ze from"node:path";import OT from"fast-glob";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2b9ba0a4-396f-5870-bc89-e7fc789bb49d")}catch{}})();var CT=/^[a-z][a-z0-9+.-]+:\/\//i;function Rr(e){return CT.test(e.trim())}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="accd0229-6974-5950-8cea-74f517706878")}catch{}})();var DT=["path","scope","note"],LT=["pattern","glob","path","scope","note"],NT=["path"],MT=["from","to"],PT=new Set(["note","scope"]);function Ig(e){let t=e??"project";if(!Ue.includes(t))throw new _(`Invalid scope "${e}". Valid scopes: ${Ue.join(", ")} (default: project).`,f.USAGE);return t}function bc(e){if(e.startsWith("```")||e.includes(`
|
|
17
|
-
`)||/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(e))return!0;let t=e.indexOf(","),n=e.slice(0,t>=0?t:e.length),r=n.indexOf("=");return r>=0&&!/\s/u.test(e)&&(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)||/^(?:[A-Za-z]:[\\/]|[\\/]{1,2}|\.\.?(?:[\\/]))/u.test(e)||[e.indexOf("/"),e.indexOf("\\")].some(i=>i>=0&&i<r))?!1:n.includes("=")||wn(e)}function FT(e){let t=0;for(let n of e)if(n==="("&&(t+=1),n===")"&&(t-=1),t<0)return!1;return t===0}function $T(e){if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)&&!bc(e))return{path:e,scope:"project",note:void 0};let t=e.indexOf("](");if(e.startsWith("[")&&t>0&&e.endsWith(")")){let s=e.slice(t+2,-1).trim();if(s.length>0&&FT(s))return{path:s,scope:"project",note:e.slice(1,t).trim()||void 0}}let n=e.indexOf(",");if(n<0)return;let r=e.slice(0,n).trim(),i=e.slice(n+1).trim();if(!(r.length===0||!/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(i)))return{path:i,scope:"project",note:r}}function jT(e,t){return e?e.flatMap(n=>{let r=n.trim();if(t==="doc"){let s=$T(r);if(s!==void 0)return[s]}ar(r,"--add",`${t} path`,bc(r));let i=bc(r)?te(n,"--add"):{path:r};if(be(i,"--add",DT),!i.path)throw new _(`--add requires path=<value> or a bare ${t} path`,f.USAGE);return[{path:i.path,scope:Ig(i.scope),note:i.note?.trim()||void 0}]}):[]}function UT(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new _("--add-glob requires a glob pattern value",f.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?(?:pattern|glob|path)\s*[:=]/i.test(n)||n.startsWith("```")){let r=te(n,"--add-glob");be(r,"--add-glob",LT);let i=r.pattern?.trim()||r.glob?.trim()||r.path?.trim();if(!i)throw new _("--add-glob key/value form requires pattern=<glob>",f.USAGE);return{pattern:i,scope:Ig(r.scope),note:r.note?.trim()||void 0}}return{pattern:n,scope:"project"}}):[]}function qT(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new _("--remove requires a path value",f.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?path\s*[:=]/i.test(n)||n.startsWith("```")){let r=te(n,"--remove"),i=Object.keys(r).filter(s=>PT.has(s.toLowerCase()));if(i.length>0)throw new _(`--remove identifies a linked artifact by path only and does not accept ${i.map(s=>`"${s}"`).join(", ")}. Pass just the path (path=<value>, path:<value>, or a bare path); record removal context with --message "<why removed>".`,f.USAGE);if(be(r,"--remove",NT),!r.path)throw new _("--remove key/value form requires path=<value>",f.USAGE);return r.path}return n}):[]}function GT(e){return e?e.map(t=>{let n=te(t,"--migrate");be(n,"--migrate",MT);let r=n.from?.trim(),i=n.to?.trim();if(!r||!i)throw new _("--migrate requires from=<value> and to=<value>",f.USAGE);return{from:r,to:i}}):[]}function Or(e,t){let n=e;for(let r of t)n.startsWith(r.from)&&(n=`${r.to}${n.slice(r.from.length)}`);return n}function KT(e,t,n=[]){if(e.length===0||t.length===0)return;let r=new Set(e.map(s=>Or(s.path,n))),i=[...new Set(t.map(s=>Or(s,n)).filter(s=>r.has(s)))].sort((s,o)=>s.localeCompare(o));if(i.length!==0)throw new _(`Linked artifact mutation cannot add and remove the same normalized path in one transaction: ${i.join(", ")}. Split the replacement into separate commands so each history event has one unambiguous intent.`,f.USAGE,{code:"linked_artifact_mutation_conflict",reason:"same_path_added_and_removed",required:"Use distinct normalized paths for --add and --remove in one invocation.",why:"Conflicting batch intent cannot be applied deterministically without silently discarding metadata or a removal.",nextSteps:["Run the removal and addition as separate commands with a --message describing each intent."]})}function wt(e){return e.split(ze.sep).join("/")}function kc(e,t,n=process.cwd()){let r=e.trim();if(Rr(r))return r;if(ze.isAbsolute(r)||/^[A-Za-z]:[\\/]/.test(r))return wt(r.replaceAll("\\",ze.sep));let i=ze.relative(t,n);return i.startsWith(`..${ze.sep}`)||i===".."||ze.isAbsolute(i)?wt(ze.normalize(r)):wt(ze.relative(t,ze.resolve(n,r)))}async function zT(e,t=process.cwd(),n=process.cwd()){let r=[];for(let i of e){let s=ze.isAbsolute(i.pattern),o=await OT(i.pattern,{cwd:n,absolute:s,onlyFiles:!0,dot:!0,unique:!0,followSymbolicLinks:!0}),a=[...new Set(o.map(c=>kc(c,t,n)))].sort((c,d)=>c.localeCompare(d));for(let c of a)r.push({path:c,scope:i.scope,note:i.note})}return r}function BT(e,t,n){if(t===void 0)return e;if(!n)throw new _("--note requires --add or --add-glob in the same invocation (the note annotates the links being added)",f.USAGE);let r=t.trim();return r.length===0?e:e.map(i=>i.note===void 0?{...i,note:r}:i)}function HT(e){return`${e.path}::${e.scope}`}function Ec(e){return[...e].sort((t,n)=>{let r=t.path.localeCompare(n.path);return r!==0?r:t.scope.localeCompare(n.scope)})}function Sc(e){return[...new Map(e.map(t=>[HT(t),t])).values()].map(t=>({...t,note:t.note?.trim()||void 0}))}async function WT(e,t=process.cwd()){let n=[...new Set(e)].sort((a,c)=>a.localeCompare(c)),r=[],i=[],s=[],o=[];for(let a of n){if(Rr(a)){o.push(a.trim());continue}let c=ze.isAbsolute(a)?a:ze.resolve(t,a);try{(await RT.stat(c)).isFile()?r.push(a):s.push(a)}catch(d){if(typeof d=="object"&&d!==null&&"code"in d&&hn(d)){i.push(a);continue}s.push(a)}}return{checked:n.length,existing_files:r,missing_paths:i,non_file_paths:s,remote_references:o}}function VT(e,t,n,r){let i=0;for(let o=0;o<e.length;o+=1){let a=Or(e[o].path,r);a!==e[o].path&&(e[o]={...e[o],path:a},i+=1)}return{adds:t.map(o=>{let a=Or(o.path,r);return a!==o.path&&(i+=1),{...o,path:a}}),removes:n.map(o=>Or(o,r)),count:i}}function YT(e,t,n,r){for(let s of t)e.some(o=>o.path===s.path&&o.scope===s.scope)||e.push(s);if(n.length>0)for(let s=e.length-1;s>=0;s-=1)n.includes(e[s].path)&&e.splice(s,1);let i=Sc(e);return r?i:Ec(i)}async function Tg(e){let t=e.artifacts.map(n=>n.path);return{id:e.id,artifacts:e.artifacts,changed:e.changed,count:e.artifacts.length,migrations_applied:e.migrationsApplied&&e.migrationsApplied>0?e.migrationsApplied:void 0,validation:e.options.validatePaths||e.changed?await WT(t,e.workspaceRoot):void 0}}async function ws(e,t,n,r){let{metadataKey:i}=r,s=bn(),o=R(process.cwd(),n.path),a=Ze(o),c=process.cwd();await $(o);let d=await C(o),l=U(d,F()),u=await s.resolveList(t.add,"--add"),m=await s.resolveList(t.addGlob,"--add-glob"),g=await s.resolveList(t.remove,"--remove"),p=await s.resolveList(t.migrate,"--migrate"),h=jT(u,r.bareNoun).map(P=>({...P,path:kc(P.path,a,c)})),y=UT(m),v=await zT(y,a,c),w=BT([...h,...v],t.note,h.length>0||y.length>0),E=qT(g).map(P=>kc(P,a,c)),S=GT(p);if(KT(w,E,S),!(w.length>0||E.length>0||S.length>0)){let P=await X(o,e,d.id_prefix,d.item_format,l.type_to_folder);if(!P)throw new _(`Item ${e} not found`,f.NOT_FOUND);let K=(await ge(P,{schema:d.schema})).document.metadata[i]??[];return Tg({id:P.id,artifacts:K,changed:!1,options:t,workspaceRoot:a})}let I=q(t.author,d.author_default),k=await me({pmRoot:o,settings:d,id:e,op:r.op,author:I,message:t.message,force:t.force,skipNoop:!0,mutate(P){let A=P.metadata,K=A[i]??[],oe=[...K],ae=VT(oe,w,E,S),ye=YT(oe,ae.adds,ae.removes,r.supportsAppendStable&&t.appendStable===!0);ye.length>0?A[i]=ye:delete A[i];let $e=!mt(K,ye);return{changedFields:$e?[i]:[],warnings:$e&&ae.count>0?[`path_migrations_applied:${ae.count}`]:[]}}}),b=k.item[i]??[],O=k.warnings.find(P=>P.startsWith("path_migrations_applied:")),W=O?Number(O.slice(24)):0;return Tg({id:k.item.id,artifacts:b,changed:k.changedFields.includes(i),migrationsApplied:W,options:t,workspaceRoot:a})}function bs(e,t){let n={};for(let[r,i]of Object.entries(e))n[r==="artifacts"?t:r]=i;return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c4c82f8f-7890-5ed2-8f0f-a82ba42cf807")}catch{}})();async function Ag(e,t,n){let r=await ws(e,t,n,{metadataKey:"docs",op:"docs_add",bareNoun:"doc",supportsAppendStable:!1});return bs(r,"docs")}import{execFile as JT}from"node:child_process";import Cg from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b8b3f729-be32-5a77-b08f-f616ee068e0f")}catch{}})();function Rg(e,t){return new Promise((n,r)=>{JT("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:4*1024*1024},(i,s)=>{i?r(i):n(s)})})}function Og(e){if(e&&(!Number.isSafeInteger(e.start)||!Number.isSafeInteger(e.end)||e.start<1||e.end<e.start))throw new RangeError("Source line range must be inclusive positive integers with end >= start.")}function zG(e){let t=/^(\d+):(\d+)$/u.exec(e.trim()),n=t?{start:Number(t[1]),end:Number(t[2])}:void 0;if(Og(n),!n)throw new RangeError("Source line range must use start:end.");return n}function XT(e){let t=new Map;for(let n of e.split(`
|
|
18
|
-
`)){let r=/^([0-9a-f^]{40,64}) \d+ \d+(?: \d+)?$/u.exec(n)?.[1];r&&t.set(r,(t.get(r)??0)+1)}return t}function QT(e){let t=e.split("\0"),n=new Map;for(let r=0;r+1<t.length;r+=2){let i=t[r]?.trim();if(!i)continue;let s=[...new Set(t[r+1]?.match(/\bpm-[a-z0-9][a-z0-9-]{2,63}\b/gu)??[])].sort((o,a)=>o.localeCompare(a));n.set(i,s)}return n}async function ZT(e){let t=Cg.relative(e.workspaceRoot,Cg.resolve(e.workspaceRoot,e.sourcePath)),n=await Rg(e.workspaceRoot,["blame","--line-porcelain","-L",`${e.lineRange.start},${e.lineRange.end}`,"--",t]),r=await Rg(e.workspaceRoot,["log","-n","256","--format=%H%x00%B%x00","--",t]);return{commitLines:XT(n),commitItems:QT(r),available:!0}}function eI(e){let t=e.current.nodes.at(-1),n=e.current.kinds.length+1,r;for(let i of e.graph.incidentEdges(t)){let s=i.source===t,o=s?i.target:i.source;if((e.visitedDepth.get(o)??Number.POSITIVE_INFINITY)<n)continue;e.visitedDepth.set(o,n);let a=e.graph.registry().require(i.kind),c={nodes:[...e.current.nodes,o],kinds:[...e.current.kinds,s?i.kind:a.inverse??i.kind]};e.details.get(o)?.type?.toLowerCase()==="decision"?(r=n,e.found.push(c)):e.queue.push(c)}return r}function tI(e){let t=[{nodes:[e.itemId],kinds:[]}],n=new Map([[e.itemId,0]]),r=[],i;for(;t.length>0;){let s=t.shift(),o=s.kinds.length;i!==void 0&&o>=i||o>=e.maxDepth||(i=eI({current:s,graph:e.graph,details:e.details,visitedDepth:n,queue:t,found:r})??i)}return r.sort((s,o)=>s.nodes.join("\0").localeCompare(o.nodes.join("\0"))),r}function nI(e,t,n){let r=c_(t);if(!r.graph.hasNode(e))return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let i=tI({itemId:e,maxDepth:n,graph:r.graph,details:new Map(r.details.map(a=>[a.id,a]))}),s=i[0];if(!s)return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let o=[...new Set(i.map(a=>a.nodes.at(-1)))];return{status:o.length===1?"found":"ambiguous",nodes:s.nodes,kinds:s.kinds,alternative_decision_ids:o.slice(1)}}async function rI(e){if(!e.lineRange)return{commitLines:new Map,commitItems:new Map,available:!0};try{return await ZT({workspaceRoot:e.workspaceRoot,sourcePath:e.paths[0],lineRange:e.lineRange})}catch{return{commitLines:new Map,commitItems:new Map,available:!1}}}function iI(e){let t=[];return e.hasLineRange&&!e.attributionAvailable&&t.push("git_attribution_unavailable"),e.hasLineRange&&e.contributionLines===0&&t.push("line_attribution_unmapped"),e.decisionStatus==="ambiguous"&&t.push("multiple_governing_decisions"),e.decisionStatus==="not_found"&&t.push("governing_decision_not_found"),t}function sI(e){return[...e.commitLines.keys()].filter(t=>(e.commitItems.get(t)?.length??0)>0)}async function Dg(e){Og(e.lineRange);let t=e.decisionDepth??8;if(!Number.isSafeInteger(t)||t<1||t>32)throw new RangeError("Decision path depth must be an integer from 1 to 32.");let n=await rI(e),r=sI(n),i=new Map;for(let s of e.candidates){let o=[...n.commitLines.entries()].filter(([l])=>n.commitItems.get(l)?.includes(s.item.id)),a=o.reduce((l,[,u])=>l+u,0),c=nI(s.item.id,e.corpus,t),d=iI({hasLineRange:e.lineRange!==void 0,attributionAvailable:n.available,contributionLines:a,decisionStatus:c.status});i.set(s.item.id,{score:a*100+s.files.length*10+Math.max(0,9-Math.floor((Date.now()-Date.parse(s.item.updated_at))/(720*60*60*1e3))),contribution_lines:a,evidence:[...s.files.map(l=>({kind:"linked_file",reference:l.path})),...o.map(([l,u])=>({kind:"git_commit",reference:l.slice(0,12),contribution_lines:u}))],rationale:{value:s.item.value?.trim()||null,why_now:s.item.why_now?.trim()||null,outcome:s.item.outcome?.trim()||null,objective:s.item.objective?.trim()||null},decision_path:c,ambiguities:d})}return{explanations:i,receipt:{line_range:e.lineRange??null,blamed_commit_count:n.commitLines.size,mapped_commit_count:r.length,unmapped_commit_count:n.commitLines.size-r.length,decision_depth:t}}}import Lg from"node:fs/promises";import Be from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ed504f2b-8b78-5fca-a4a7-7b0709a65533")}catch{}})();var oI=32768;function xc(e){return wt(Be.normalize(e))}async function ks(e){try{return await Lg.realpath(e)}catch{return Be.resolve(e)}}function zn(e,t){let n=Be.isAbsolute(e.path)?Be.resolve(e.path):Be.resolve(t,e.path);return`${xc(n)}::${e.scope}`}function Es(e,t,n){if(typeof e=="string"){let r=e.trim();r.length>0&&n.push({field:t,value:r});return}if(Array.isArray(e)){e.forEach((r,i)=>Es(r,`${t}[${i}]`,n));return}if(typeof e=="object"&&e!==null)for(let[r,i]of Object.entries(e))Es(i,t?`${t}.${r}`:r,n)}function aI(e){let t=[];return Es(e.metadata,"metadata",t),Es(e.body,"body",t),t}function cI(e){let t=e.trim();return t=t.replace(/^[`"'<([{]+/u,""),t=t.replace(/[`"'>)\]},;!?]+$/u,""),t=t.replace(/[.]+$/u,""),t=t.replace(/:(?:\d+)(?::\d+)?$/u,""),t=t.replace(/[.]+$/u,""),t}function dI(e){let t=[],n=/(?:[A-Za-z]:[\\/]|\/)[^\s"'`<>()[\]{},;]+/gu,r=/(?:\.{1,2}[\\/])?(?:(?:[A-Za-z0-9_.@-]+[\\/])+[A-Za-z0-9_.@-]+|[A-Za-z0-9_.@-]+\.[A-Za-z0-9][A-Za-z0-9._-]*)/gu;for(let i of e){let s=new Set,o=i.value.slice(0,oI);for(let[a,c]of[[n,i.value],[r,o]]){a.lastIndex=0;for(let d of c.matchAll(a)){let l=cI(d[0]);!l||s.has(l)||(s.add(l),t.push({field:i.field,value:l}))}}}return t}async function lI(e,t,n=t){let r=Be.isAbsolute(e)?Be.resolve(e):Be.resolve(n,e),i;try{i=await Lg.stat(r)}catch{return}if(!i.isFile())return;let[s,o]=await Promise.all([ks(t),ks(r)]);if(zo(s,o)){let a=Be.relative(s,o);return!a||a.startsWith("..")||Be.isAbsolute(a)?void 0:{path:xc(a),scope:"project"}}return{path:xc(r),scope:"global"}}async function uI(e,t,n=t){let r=new Set((e.metadata.files??[]).map(c=>zn(c,t))),i=new Map,s=dI(aI(e)),o=new Map;await Promise.all([...new Set(s.map(c=>c.value))].map(async c=>{o.set(c,await lI(c,t,n))}));let a=s.map(c=>({reference:c,resolved:o.get(c.value)}));for(let{reference:c,resolved:d}of a){if(!d)continue;let l=zn(d,t),u=i.get(l)??{path:d.path,scope:d.scope,sourceFields:new Set,originalPaths:new Set,sourceCount:0};u.sourceFields.add(c.field),u.originalPaths.add(c.value),u.sourceCount+=1,i.set(l,u)}return[...i.entries()].map(([c,d])=>({path:d.path,scope:d.scope,status:r.has(c)?"already_linked":"addable",source_count:d.sourceCount,source_fields:[...d.sourceFields].sort((l,u)=>l.localeCompare(u)),original_paths:[...d.originalPaths].sort((l,u)=>l.localeCompare(u))})).sort((c,d)=>{let l=c.status.localeCompare(d.status);if(l!==0)return l;let u=c.path.localeCompare(d.path);return u!==0?u:c.scope.localeCompare(d.scope)})}async function Ng(e,t,n){let r=await ws(e,t,n,{metadataKey:"files",op:"files_add",bareNoun:"file",supportsAppendStable:!0});return bs(r,"files")}async function mI(e,t){let n=await ks(t),r=await Promise.all(e.map(async s=>{let o=s.trim();if(!o)throw new _("Files lookup paths must not be empty.",f.USAGE);if(!Be.isAbsolute(o))return wt(o);let a=await ks(o);return zo(n,a)?wt(Be.relative(n,a)):wt(a)})),i=[...new Set(r)].sort((s,o)=>s.localeCompare(o));if(i.length===0)throw new _("Files lookup requires at least one path.",f.USAGE);return i}function fI(e){for(let[r,i]of[["limit",e.limit],["offset",e.offset]])if(i!==void 0&&(!Number.isInteger(i)||i<0))throw new _(`Files lookup ${r} must be a non-negative integer.`,f.USAGE);let{offset:t=0,limit:n=50}=e;return{offset:Math.max(0,Math.floor(t)),limit:e.noTruncate?void 0:Math.max(0,Math.floor(n))}}function Mg(e){return{id:e.id,title:e.title,type:e.type,status:e.status,priority:e.priority,updated_at:e.updated_at}}function Pg(e,t){let n=e.item.priority-t.item.priority;if(n!==0)return n;let r=t.item.updated_at.localeCompare(e.item.updated_at);return r===0?e.item.id.localeCompare(t.item.id):r}function _I(e){return e.metadata.map(t=>({item:t,files:(t.files??[]).filter(n=>e.paths.includes(wt(n.path))&&(e.scope===void 0||n.scope===e.scope)).sort((n,r)=>{let i=n.path.localeCompare(r.path);return i===0?n.scope.localeCompare(r.scope):i})})).filter(t=>t.files.length>0).sort(Pg)}async function pI(e){if(e.explain)return Dg({workspaceRoot:e.workspaceRoot,paths:e.paths,candidates:e.matching,corpus:e.metadata,...e.lineRange?{lineRange:e.lineRange}:{},...e.decisionDepth===void 0?{}:{decisionDepth:e.decisionDepth}})}async function gI(e){if([e.strictRead,e.noTruncate,e.explain,Jl()].includes(!0))return null;let t=await ji(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]);return t?Ju({pmRoot:e.pmRoot,expectedSourceCursor:t.source_cursor,paths:e.paths,scope:e.scope,limit:e.limit,offset:e.offset}):null}async function hI(e){let t=[],n=await Rn(e.pmRoot,e.settings.item_format,e.typeToFolder,t,e.settings.schema),r=_I({metadata:n,paths:e.paths,scope:e.scope}),i=t.filter(c=>/^item_list_(?:item|directory)_read_failed:/u.test(c));if(e.strictRead&&i.length>0)throw new _(`Files lookup could not read every item: ${i.join("; ")}`,f.GENERIC_FAILURE);let s=await pI({explain:e.explain,workspaceRoot:e.workspaceRoot,paths:e.paths,matching:r,metadata:n,lineRange:e.lineRange,decisionDepth:e.decisionDepth}),a=(s?[...r].sort((c,d)=>{let l=s.explanations.get(d.item.id).score-s.explanations.get(c.item.id).score;return l!==0?l:Pg(c,d)}):r).slice(e.offset,e.limit===void 0?void 0:e.offset+e.limit);return{paths:e.paths,total:r.length,count:a.length,offset:e.offset,limit:e.limit??null,has_more:e.offset+a.length<r.length,truncated:e.offset+a.length<r.length,completeness:{status:i.length===0?"complete":"partial",source:"source_scan"},warnings:t,matches:a.map(c=>({item:Mg(c.item),files:c.files,...s?{traceability:s.explanations.get(c.item.id)}:{}})),...s?{traceability_receipt:s.receipt}:{}}}async function cK(e,t){let n=R(process.cwd(),t.path),r=Ze(n);await $(n);let i=await mI(e.paths,r);if(e.lineRange&&i.length!==1)throw new _("Files lookup line attribution requires exactly one source path.",f.USAGE);let s=await C(n),o=U(s,F()),{offset:a,limit:c}=fI(e),d=await gI({pmRoot:n,typeToFolder:o.type_to_folder,paths:i,scope:e.scope,limit:c,offset:a,strictRead:e.strictRead===!0,noTruncate:e.noTruncate===!0,explain:e.explain===!0||e.lineRange!==void 0});return d?{paths:i,total:d.total,count:d.matches.length,offset:a,limit:c,has_more:a+d.matches.length<d.total,truncated:a+d.matches.length<d.total,completeness:{status:"unchecked",source:"index"},warnings:[],matches:d.matches.map(l=>({item:Mg(l.item),files:l.files}))}:hI({pmRoot:n,settings:s,typeToFolder:o.type_to_folder,paths:i,scope:e.scope,limit:c,offset:a,strictRead:e.strictRead===!0,workspaceRoot:r,explain:e.explain===!0||e.lineRange!==void 0,lineRange:e.lineRange,decisionDepth:e.decisionDepth})}async function dK(e,t,n){let r=R(process.cwd(),n.path),i=Ze(r);await $(r);let s=await C(r),o=U(s,F()),a=await X(r,e,s.id_prefix,s.item_format,o.type_to_folder);if(!a)throw new _(`Item ${e} not found`,f.NOT_FOUND);let c=await ge(a,{schema:s.schema}),d=await uI(c.document,i,process.cwd()),l=d.filter(b=>b.status==="addable"),u=d.filter(b=>b.status==="already_linked"),m=t.apply===!0,g=t.note?.trim()||"discovered from item text";if(!m||l.length===0){let b=c.document.metadata.files??[];return{id:a.id,files:b,changed:!1,apply:m,count:b.length,candidate_count:d.length,addable_count:l.length,added_count:0,skipped_existing_count:u.length,candidates:d,added:[],skipped_existing:u}}let p=q(t.author,s.author_default),h=l.map(b=>({path:b.path,scope:b.scope,note:g})),y=[],v=new Set,w=await me({pmRoot:r,settings:s,id:e,op:"files_discover",author:p,message:t.message??"Discover referenced file links",force:t.force,mutate(b){let O=[...b.metadata.files??[]],W=new Set(O.map(K=>zn(K,i)));y=[],v.clear();for(let[K,oe]of h.entries()){let ae=zn(oe,i);W.has(ae)||(O.push(oe),W.add(ae),y.push(oe),v.add(K))}let P=Sc(O),A=t.appendStable?P:Ec(P);return A.length>0?b.metadata.files=A:delete b.metadata.files,{changedFields:y.length>0?["files"]:[],warnings:y.length!==h.length?[`files_discover_skipped_existing:${h.length-y.length}`]:[]}}}),E=w.item.files??[],S=new Set(y.map(b=>zn(b,i))),x=E.filter(b=>S.has(zn(b,i))),I=l.filter((b,O)=>!v.has(O)),k=[...u,...I];return{id:w.item.id,files:E,changed:x.length>0,apply:!0,count:E.length,candidate_count:d.length,addable_count:l.length,added_count:x.length,skipped_existing_count:k.length,candidates:d,added:x,skipped_existing:k}}import{readFileSync as yI}from"node:fs";import Ss from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="673a5a26-6214-58d6-af19-baee5a8359f0")}catch{}})();var vI=new Set(["get","history","restore","update","close","delete","append","claim","release","comments","notes","learnings","files","docs","deps","test"]),Tc=new Set(["--pm-path","--path","--author"]),wI={get:new Set(["--depth","--fields","--tree-depth","--tree_depth","--at","--format"]),history:new Set(["--limit","--field","--format"]),restore:new Set(["--message"]),update:new Set(["--title","-t","--description","-d","--body","-b","--status","-s","--close-reason","--close_reason","--priority","-p","--type","--tags","--add-tags","--add_tags","--remove-tags","--remove_tags","--deadline","--estimated-minutes","--estimate","--estimated_minutes","--acceptance-criteria","--ac","--acceptance_criteria","--definition-of-ready","--definition_of_ready","--order","--rank","--goal","--objective","--value","--impact","--outcome","--why-now","--why_now","--message","--assignee","--parent","--reviewer","--risk","--confidence","--sprint","--release","--blocked-by","--blocked_by","--blocked-reason","--blocked_reason","--unblock-note","--unblock_note","--reporter","--severity","--environment","--repro-steps","--repro_steps","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual","--affected-version","--affected_version","--fixed-version","--fixed_version","--component","--regression","--customer-impact","--customer_impact","--dep","--dep-remove","--dep_remove","--comment","--note","--learning","--file","--test","--doc","--reminder","--event","--type-option","--type_option","--field","--unset","--body-file"]),close:new Set(["--reason","-r","--close-reason","--duplicate-of","-d","--message","-m","--validate-close","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual"]),delete:new Set(["--message"]),append:new Set(["--body","--text","--message"]),claim:new Set(["--assignee","--message","--type","--tag","--priority","--assignee-filter","--parent","--sprint","--release","--max-attempts"]),release:new Set(["--assignee","--message"]),comments:new Set(["--add","--body","--comment","--file","--edit","--delete","--limit","--message"]),notes:new Set(["--add","--file","--edit","--delete","--limit","--message"]),learnings:new Set(["--add","--file","--edit","--delete","--limit","--message"]),files:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),docs:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),deps:new Set(["--format","--max-depth","--collapse","--node-limit","--edge-limit","--token-budget","--cursor","--direction","--kind"]),test:new Set(["--add","--add-json","--remove","--match","--only-index","--timeout","--env-set","--env-clear","--pm-context","--message"])},bI=new Set(["-p","--package"]),kI=new Set(["-c","--call"]),Ic=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),Ac=new Set(["-C","--prefix","--userconfig","--cache"]),Fg=new Set(["--cwd"]),$g=new Set(["--cwd"]),EI=new Set(["exec","x"]),jg=new Set(["run","run-script"]),Ug=new Set(["-C","--dir","--cwd","-w","--workspace","--filter"]);function Zt(e){return e.split(/&&|\|\||\||;/).map(t=>t.trim()).filter(t=>t.length>0)}function xs(e,t=process.cwd()){let n=Ts(e.split(" ").filter(o=>o.length>0));if(n.length===0)return null;let[r,...i]=n;if(Dr(r)||Lr(r,t))return i;if(r==="node"&&i[0]&&Lr(i[0],t))return i.slice(1);let s=r==="npx"||r==="bunx"?en(i):r==="pnpm"?As(i):r==="npm"?Cs(i):null;return s&&(Dr(s.command)||Rc(s.command))?s.args:null}var Cc=(e,t="pm")=>{let n=t.trim().toLowerCase(),r=n.length;for(;r>0&&n[r-1]==="-";)r-=1;let i=n.slice(0,r);if(i.length===0)return[];let s=e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase(),o=new Set;for(let a of Zt(s)){let c=xs(a),d=c?Oc(c):null,l=d&&vI.has(d.subcommand)?xI(d.remaining,wI[d.subcommand]):void 0,u=l?.trim().toLowerCase();u?.startsWith(`${i}-`)===!0&&u.length>i.length+1&&o.add(l)}return[...o].sort((a,c)=>a.localeCompare(c))};function Ts(e){let t=0;for(e[t]==="env"&&(t+=1);t<e.length;){let n=e[t];if(/^(?:[a-z_][a-z0-9_]*|\$env:[a-z_][a-z0-9_]*)=.*/.test(n)){t+=1;continue}break}return e.slice(t)}function Is(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(Tc.has(n)){t+=2;continue}t+=1;continue}return n}}function Dr(e){return e==="pm"||e==="pm.cmd"||e==="pm.exe"||e.endsWith("/pm")||e.endsWith("/pm.cmd")||e.endsWith("/pm.exe")}function SI(e){let t=e.trim();if(!t.startsWith("@")){let i=t.indexOf("@");return i===-1?t:t.slice(0,i)}let n=t.indexOf("/");if(n===-1)return t;let r=t.indexOf("@",n+1);return r===-1?t:t.slice(0,r)}function Rc(e){let t=SI(e);return t==="pm-cli"||t.endsWith("/pm-cli")||e==="pm-cli"||e.endsWith("/pm-cli")}function Lr(e,t=process.cwd()){let n=e.replaceAll("\\","/");if(n!=="dist/cli.js"&&n!=="./dist/cli.js"&&!n.endsWith("/dist/cli.js"))return!1;let r=Ss.resolve(t,e);try{return JSON.parse(yI(Ss.join(Ss.dirname(Ss.dirname(r)),"package.json"),"utf8")).name==="@unbrained/pm-cli"}catch{return!1}}function en(e){let t=0;for(;t<e.length;){let r=e[t];if(r==="--"){t+=1;break}if(!r.startsWith("-"))break;let i=/^(?:-c|--call)=(.*)$/.exec(r);if(i){let s=i[1];return s?{command:s,args:e.slice(t+1)}:null}if(kI.has(r)){t+=1;break}t+=bI.has(r)&&!r.includes("=")?2:1}let n=e[t];return n?{command:n,args:e.slice(t+1)}:null}function Pt(e,t){let n=0;for(;n<e.length;){let r=e[n];if(r==="--"){n+=1;continue}if(r.startsWith("-")){if(r.includes("=")){n+=1;continue}if(t.has(r)){n+=2;continue}n+=1;continue}return{subcommand:r,args:e.slice(n+1)}}return null}function As(e){let t=Pt(e,Ic);return t?.subcommand!=="dlx"?null:en(t.args)}function Cs(e){let t=Pt(e,Ac);return!t||!EI.has(t.subcommand)?null:en(t.args)}function Oc(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(Tc.has(n)){t+=2;continue}t+=1;continue}return{subcommand:n,remaining:e.slice(t+1)}}return null}function xI(e,t=new Set){for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="--")return e[n+1];if(!r.startsWith("-"))return r;!r.includes("=")&&(Tc.has(r)||t.has(r))&&(n+=1)}}import{execFile as TI}from"node:child_process";import{readFile as II}from"node:fs/promises";import Gg from"node:path";import{promisify as AI}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="30a61f26-5db8-50ba-af37-1990a4742ce8")}catch{}})();var CI=AI(TI),Dc=1,RI="linked-test-trust.json";function Lc(e){return Gg.join(Ml(e),RI)}function qg(){return{version:Dc,acknowledged:{}}}async function Nc(e){try{let t=JSON.parse(await II(Lc(e),"utf8"));return t.version!==Dc||typeof t.acknowledged!="object"||t.acknowledged===null||Array.isArray(t.acknowledged)?qg():{version:Dc,acknowledged:t.acknowledged}}catch{return qg()}}async function Mr(e=process.cwd()){let t=process.env.GITHUB_HEAD_REF?.trim()||process.env.GITHUB_REF_NAME?.trim();if(t&&t!=="merge")return t;try{let{stdout:n}=await CI("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),r=n.trim();return r.length===0?void 0:r}catch{return}}function Pr(e=process.cwd()){return process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||e}function OI(e){return e===null||typeof e!="object"?!1:typeof e.author=="string"&&e.author.trim().length>0&&typeof e.created_at=="string"&&Sl(e.created_at)&&(e.source_kind==="local_mutation"||e.source_kind==="merge_union")}function Nr(e,t){return{...e?{source_ref:e}:{},...t?{current_source_ref:t}:{}}}function DI(e,t,n,r){return e?.map(i=>i.command&&!i.provenance?{...i,provenance:{author:t,created_at:n,source_kind:"local_mutation",...r?{source_ref:r}:{}}}:i)}async function Bn(e,t,n){if(!e||e.length===0)return e;let r=Pr();return DI(e,t,n,await Mr(r))}function Kg(e){return Ne(D({command:e.command??null,path:e.path??null,scope:e.scope,pm_context_mode:e.pm_context_mode??null,workspace_context_mode:e.workspace_context_mode??null,env_set:e.env_set??null,env_clear:e.env_clear??null,shared_host_safe:e.shared_host_safe??null,provenance:e.provenance??null,provenance_invalid:e.provenance_invalid??null}))}async function Mc(e,t,n){let r=await Nc(e);return zg(t,n,r)}function zg(e,t,n){let r=Kg(e),i=e.provenance?.source_ref;if(e.provenance===void 0&&e.provenance_invalid!==!0)return{fingerprint:r,trusted:!0,reason:"legacy"};let s=Object.hasOwn(n.acknowledged,r);return e.provenance_invalid===!0||!OI(e.provenance)?s?{fingerprint:r,trusted:!0,reason:"acknowledged",...Nr(void 0,t)}:{fingerprint:r,trusted:!1,reason:"invalid_provenance",...Nr(void 0,t)}:e.provenance.source_kind==="local_mutation"&&i===void 0?{fingerprint:r,trusted:!0,reason:"local_mutation",...Nr(void 0,t)}:e.provenance.source_kind==="local_mutation"&&i!==void 0&&i===t?{fingerprint:r,trusted:!0,reason:"local_source_ref",source_ref:i,current_source_ref:t}:s?{fingerprint:r,trusted:!0,reason:"acknowledged",...Nr(i,t)}:{fingerprint:r,trusted:!1,reason:"foreign_source_ref",...Nr(i,t)}}async function Bg(e,t,n){let r=await Nc(e);return t.map(i=>zg(i,n,r))}async function Hg(e,t,n){let r=await Nc(e),i=t.filter(s=>typeof s.command=="string"&&s.command.length>0).map(Kg);for(let s of i)r.acknowledged[s]={acknowledged_at:n};return await We(Gg.dirname(Lc(e))),await we(Lc(e),`${JSON.stringify(r,null,2)}
|
|
19
|
-
`),{acknowledged:i.length,fingerprints:i}}import Wc from"node:fs/promises";import{realpathSync as UI}from"node:fs";import{execFile as qI}from"node:child_process";import Oe from"node:path";import{promisify as GI}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="98a73818-c4ef-5bce-8b23-6c40f7312cc3")}catch{}})();var LI=["metadata","resolution"],Pc=["metadata","resolution","estimates","lifecycle"],NI="completed";function Fc(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function Wg(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function Vg(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let r=Wg(n.close_reason)??NI;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:r,command:`pm update ${n.id} --resolution ${Fc(r)}`,gate:"resolution"})}return t}function Yg(e){let t=[];for(let n of e){let r=Wg(n.resolution);r!==void 0&&t.push({item_id:n.id,check:"metadata",field:"close_reason",kind:"set_close_reason",value:r,command:`pm update ${n.id} --close-reason ${Fc(r)}`,gate:"metadata"})}return t}function Jg(e,t){return e.map(n=>{let r=Hu(n.type,t);return{item_id:n.id,check:"metadata",field:"estimated_minutes",kind:"set_estimate",value:String(r),command:`pm update ${n.id} --estimate ${r}`,gate:"estimates"}})}function Xg(e){return e.map(t=>t.grandparent_id!==void 0&&t.grandparent_active===!0?{item_id:t.id,check:"lifecycle",field:"parent",kind:"reparent",parent_id:t.grandparent_id,command:`pm update ${t.id} --parent ${t.grandparent_id}`,gate:"lifecycle"}:{item_id:t.id,check:"lifecycle",field:"parent",kind:"unset_parent",command:`pm update ${t.id} --unset parent`,gate:"lifecycle"})}function Qg(e){let t=[];for(let n of e){if(n.classification!=="deleted")continue;let r=n.link_kind==="files"?"files":"docs";t.push({item_id:n.item_id,check:"files",field:n.link_kind,kind:n.link_kind==="files"?"prune_file_link":"prune_doc_link",path:n.path,command:`pm ${r} ${n.item_id} --remove ${Fc(n.path)}`})}return t}function Zg(e){let t=(e??[]).flatMap(r=>r.split(",")).map(r=>r.trim()).filter(r=>r.length>0);if(t.length===0){if(e!==void 0&&e.length>0)throw new _(`--fix-scope values must not be empty. Supported values: ${Pc.join(", ")}.`,f.USAGE);return new Set(LI)}let n=new Set;for(let r of t){let i=r.toLowerCase().replaceAll("-","_");if(Pc.includes(i)){n.add(i);continue}throw new _(`Unknown --fix-scope value "${r}". Supported values: ${Pc.join(", ")}.`,f.USAGE)}return n}function eh(e,t){let n=[],r=[];for(let i of e)i.gate!==void 0&&!t.has(i.gate)?r.push(i):n.push(i);return{applicable:n,gated:r}}function Fr(e){return{item_id:e.item_id,check:e.check,field:e.field,command:e.command,...e.gate!==void 0?{gate:e.gate}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8a7fbaf1-917f-5067-b9b6-a9f27c80e291")}catch{}})();var MI=/^([A-Z][A-Z0-9]*-\d+)\b/iu;function PI(e,t={}){if(typeof e!="string")return null;let n=e.trim();if(n.length===0)return null;let r=MI.exec(n);if(!r)return null;let i=r[1],s=i.toUpperCase(),o=i.slice(0,i.lastIndexOf("-")),a=new Set((t.configuredPrefixes??[]).map(m=>m.trim().replace(/-+$/u,"").toUpperCase())),c=n.slice(i.length),d=t.evidenceText?.toUpperCase()??"",l=d.includes(`ISSUE CODE: ${s}`)||d.includes(`ISSUE CODE \`${s}\``)||d.includes(`\`${s}\``)||d.includes(`[${s}]`);return o===o.toUpperCase()||/^\s*(?::|—|–|\])/u.test(c)||a.has(o.toUpperCase())||l?s:null}function th(e){return typeof e=="string"&&e.trim().length>0}function nh(e,t={}){let n=new Map;for(let i of e){if(typeof i.title!="string"||th(i.duplicate_of))continue;let s=PI(i.title,{...t,evidenceText:i.body});if(s===null)continue;let o=n.get(s);o||(o=[],n.set(s,o)),o.some(a=>a.id===i.id)||o.push({id:i.id,title:i.title,parent:th(i.parent)?i.parent.trim():null})}let r=[];for(let[i,s]of n){if(s.length<2)continue;let o=new Set(s.map(d=>d.id.toLowerCase())),a=s.filter(d=>d.parent===null||!o.has(d.parent.toLowerCase()));if(a.length<2)continue;let c=[...a].sort((d,l)=>d.id.localeCompare(l.id));r.push({code:i,count:c.length,ids:c.map(d=>d.id),titles:c.map(d=>d.title)})}return r.sort((i,s)=>i.code.localeCompare(s.code))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1951b0f1-11fa-5728-b516-7458a55b1e29")}catch{}})();function rh(e){let t=new Map;for(let r of e){let i=t.get(r.item_type);i||(i=new Map,t.set(r.item_type,i)),i.set(r.field,(i.get(r.field)??0)+1)}let n={};for(let r of[...t.keys()].sort((i,s)=>i.localeCompare(s))){let i=t.get(r),s={};for(let o of[...i.keys()].sort((a,c)=>a.localeCompare(c)))s[o]=i.get(o);n[r]=s}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="eb4fe9bd-31b5-5ed3-b401-3e3776ec12e9")}catch{}})();var ih=3;function sh(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function oh(e,t,n=ih){let r=Number.isFinite(n)&&n>=1?Math.floor(n):ih,i=new Map;for(let s of t){let o=sh(s);if(o.length===0)continue;let a=i.get(o);a?a.push(s):i.set(o,[s])}return e.map(s=>{if(s.includes(",")||s.replace(/^[a-z]:[\\/]/i,"").includes(":"))return{path:s,classification:"malformed",candidates:[],candidates_truncated:!1};let o=(i.get(sh(s))??[]).filter(a=>a!==s).sort((a,c)=>a.localeCompare(c));return o.length===0?{path:s,classification:"deleted",candidates:[],candidates_truncated:!1}:{path:s,classification:"moved",candidates:o.slice(0,r),candidates_truncated:o.length>r}})}function ah(e){return e.map(t=>t.classification==="moved"?`${t.path}:moved:${t.candidates[0]}`:`${t.path}:${t.classification}`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="01f042d0-7f02-59f5-8894-cf48eb936d99")}catch{}})();async function Rs(e){return e.includeBody?_t(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema,{forceSourceScan:!0}):Rn(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a2c96f3a-fa7a-538f-ae11-7b821e5b7ab2")}catch{}})();var FI=5;async function Os(e,t,n){let r=await Xt(e,t),s=[["validate_history_drift_missing_streams",r.missingStreams.length],["validate_history_drift_unreadable_streams",r.unreadableStreams.length],["validate_history_drift_hash_mismatches",r.hashMismatches.length],["validate_history_drift_chain_mismatches",r.chainMismatches.length],["validate_history_drift_version_skews",r.versionSkews.length],["validate_history_drift_workspace_state_mismatches",r.workspaceStateMismatches.length],["validate_history_drift_workspace_state_missing",r.workspaceStateMissing.length],["validate_history_drift_workspace_state_unreadable",r.workspaceStateUnreadable.length]].filter(([,d])=>d>0).map(([d,l])=>`${d}:${l}`),o=n?Number.POSITIVE_INFINITY:FI,a=r.driftedItems.slice(0,o),c=r.identityDiscontinuities??[];return{check:{name:"history_drift",status:c.length>0?"error":s.length===0?"ok":"warn",ok:c.length===0&&s.length===0,details:{identity_discontinuities:c.slice(0,o),identity_discontinuities_count:c.length,identity_discontinuities_truncated:c.length>o,checked_items:t.length,drifted_items_count:r.driftedItems.length,drifted_items:a,drifted_items_truncated:a.length<r.driftedItems.length,counts:{missing_streams:r.missingStreams.length,unreadable_streams:r.unreadableStreams.length,hash_mismatches:r.hashMismatches.length,chain_mismatches:r.chainMismatches.length,version_skews:r.versionSkews.length,workspace_state_mismatches:r.workspaceStateMismatches.length,workspace_state_missing:r.workspaceStateMissing.length,workspace_state_unreadable:r.workspaceStateUnreadable.length},workspace_state_mismatches:r.workspaceStateMismatches,workspace_state_missing:r.workspaceStateMissing,workspace_state_unreadable:r.workspaceStateUnreadable,version_skews:r.versionSkews.slice(0,o)}},warnings:s}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="77a3c404-bbcd-5a5e-80bf-cb61c45af55d")}catch{}})();function Ds(e,t){let n=e[0];if(e.length===1)return[n,n];let r=new Set(e),i=[n],s=new Set([n]),o=a=>{for(let c of(t.get(a)??[]).filter(d=>r.has(d))){if(c===n&&i.length>1)return i.push(n),!0;if(!s.has(c)){if(s.add(c),i.push(c),o(c))return!0;i.pop(),s.delete(c)}}return!1};return o(n)?[...i]:[...e,n]}function $I(e,t){if(typeof e!="string")return;let n=e.trim().toLowerCase();return n.length>0?t.get(n):void 0}function jI(e,t,n,r){for(let i of e.dependencies??[]){if(typeof i!="object"||i===null||typeof i.id!="string")continue;let s=r.resolve(i.kind);if(!s?.hierarchy)continue;let o=n.get(i.id.toLowerCase());o&&(s.hierarchyDirection==="source_parent"?t.get(o).push(e.id):t.get(e.id).push(o))}}function $c(e,t=xe()){let n=new Map(e.map(i=>[i.id.toLowerCase(),i.id])),r=new Map(e.map(i=>[i.id,[]]));for(let i of[...e].sort((s,o)=>s.id.localeCompare(o.id))){let s=r.get(i.id),o=$I(i.parent,n);o&&s.push(o),jI(i,r,n,t)}for(let[i,s]of r)r.set(i,[...new Set(s)].sort());return r}function jc(e,t,n=xe()){let r=Hi(e,o=>t?ki(o,t):o==="closed"||o==="canceled",n),i=$c(e,n),s=r.cycles.map(o=>o.item_ids);return{cycle_count:s.length,active_cycle_count:r.cycles.filter(o=>!o.legacy_terminal).length,legacy_cycle_count:r.cycles.filter(o=>o.legacy_terminal).length,cycle_item_ids:[...new Set(s.flat())].sort(),cycle_sample_paths:s.map(o=>Ds(o,i).join("->")),cardinality_violation_count:r.cardinality_violations.length,active_cardinality_violation_count:r.cardinality_violations.filter(o=>!o.legacy_terminal).length,legacy_cardinality_violation_count:r.cardinality_violations.filter(o=>o.legacy_terminal).length,cardinality_violation_rows:r.cardinality_violations.map(o=>`${o.child_id}:${o.parent_ids.join(",")}:${o.legacy_terminal?"legacy":"active"}`),parent_divergence_count:r.divergences.length,active_parent_divergence_count:r.divergences.filter(o=>!o.legacy_terminal).length,legacy_parent_divergence_count:r.divergences.filter(o=>o.legacy_terminal).length,parent_divergence_rows:r.divergences.map(o=>`${o.child_id}:scalar=${o.scalar_parent_id}:dependencies=${o.dependency_parent_ids.join(",")}:${o.legacy_terminal?"legacy":"active"}`)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="de2cc648-965a-59c9-b688-0fe12edeec82")}catch{}})();function Ft(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/^\/+/,"")}function Uc(e){return Ft(e).replace(/\/+$/,"")}function Ve(e){let t=re(e);if(!t)return;let n=t.toLowerCase();if(!(n==="none"||n==="null"||n==="n/a"||n==="na"))return t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="898c4c05-70ab-5ea4-851e-9e224a85afc4")}catch{}})();var KI=["src","tests","docs"],zI=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],BI=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),HI=["resolution","expected_result","actual_result"],WI=["default","tracked-all","tracked-all-strict"],ch=["core","strict","custom"],Ms=["off","warn","error"],Kc=["author","acceptance_criteria","estimated_minutes","close_reason"],uh=[...Kc,"reviewer","risk","confidence","sprint","release"],Vc=Array.from(new Set(uh)),VI={author:"author",acceptance_criteria:"acceptance_criteria","acceptance-criteria":"acceptance_criteria",estimated_minutes:"estimated_minutes","estimated-minutes":"estimated_minutes",estimate:"estimated_minutes",close_reason:"close_reason","close-reason":"close_reason",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release"},YI={author:"validate_metadata_missing_author",acceptance_criteria:"validate_metadata_missing_acceptance_criteria",estimated_minutes:"validate_metadata_missing_estimate",close_reason:"validate_metadata_missing_close_reason",reviewer:"validate_metadata_missing_reviewer",risk:"validate_metadata_missing_risk",confidence:"validate_metadata_missing_confidence",sprint:"validate_metadata_missing_sprint",release:"validate_metadata_missing_release"},JI={author:"missing_author",acceptance_criteria:"missing_acceptance_criteria",estimated_minutes:"missing_estimated_minutes",close_reason:"closed_missing_close_reason",reviewer:"missing_reviewer",risk:"missing_risk",confidence:"missing_confidence",sprint:"missing_sprint",release:"missing_release"},XI={author:"missing_author_item_ids",acceptance_criteria:"missing_acceptance_criteria_item_ids",estimated_minutes:"missing_estimated_minutes_item_ids",close_reason:"closed_missing_close_reason_item_ids",reviewer:"missing_reviewer_item_ids",risk:"missing_risk_item_ids",confidence:"missing_confidence_item_ids",sprint:"missing_sprint_item_ids",release:"missing_release_item_ids"},QI={author:"missing_author_truncated",acceptance_criteria:"missing_acceptance_criteria_truncated",estimated_minutes:"missing_estimated_minutes_truncated",close_reason:"closed_missing_close_reason_truncated",reviewer:"missing_reviewer_truncated",risk:"missing_risk_truncated",confidence:"missing_confidence_truncated",sprint:"missing_sprint_truncated",release:"missing_release_truncated"},ZI=32*1024*1024,eA=1e4,zc=40,kt=5,tA=4096,nA=255,rA=GI(qI);function mh(e){let t={};for(let[n,r]of Object.entries(e))Array.isArray(r)||r===!1&&n.endsWith("_truncated")||(t[n]=typeof r=="object"&&r!==null?mh(r):r);return t}function iA(e){return{...e,checks:e.checks.map(t=>({...t,details:mh(t.details)})),...e.fixes?{fixes:{mode:e.fixes.mode,auto_fix:e.fixes.auto_fix,prune_missing:e.fixes.prune_missing,planned_count:e.fixes.planned_count,applied_count:e.fixes.applied_count,gated_count:e.fixes.gated_count,failed_count:e.fixes.failed_count}}:{}}}function Fs(e,t){return se(e,t)??e}function $r(e,t){return t.terminal_statuses.has(Fs(e,t))}function $t(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function Ls(e,t){return e.length!==t.length?!1:e.every((n,r)=>n===t[r])}function sA(e){let t=$t(bl),n={blocked_reason:$t(oi.blocked_reason),resolution:$t(oi.resolution),actual_result:$t(oi.actual_result)},r=$t(e.validation.lifecycle_stale_blocker_reason_patterns),i={blocked_reason:$t(e.validation.lifecycle_closure_like_blocked_reason_patterns),resolution:$t(e.validation.lifecycle_closure_like_resolution_patterns),actual_result:$t(e.validation.lifecycle_closure_like_actual_result_patterns)};return{stale_blocker_reason_patterns:r,stale_blocker_reason_pattern_source:Ls(r,t)?"default":"settings",closure_like_metadata_field_patterns:i,closure_like_metadata_field_pattern_sources:{blocked_reason:Ls(i.blocked_reason,n.blocked_reason)?"default":"settings",resolution:Ls(i.resolution,n.resolution)?"default":"settings",actual_result:Ls(i.actual_result,n.actual_result)?"default":"settings"}}}function fh(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"core";if(ch.includes(t))return t;throw new _(`Unknown --metadata-profile value "${e}". Supported values: ${ch.join(", ")}.`,f.USAGE)}function _h(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(Ms.includes(t))return t;throw new _(`Unknown --dependency-cycle-severity value "${e}". Supported values: ${Ms.join(", ")}.`,f.USAGE)}function ph(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(Ms.includes(t))return t;throw new _(`Unknown --parent-cycle-severity value "${e}". Supported values: ${Ms.join(", ")}.`,f.USAGE)}function oA(e){return[...new Set((e??[]).map(n=>n.trim().toLowerCase().replaceAll("-","_")))].map(n=>VI[n]).filter(n=>n!==void 0).sort((n,r)=>n.localeCompare(r))}function aA(e,t,n){let r=oA(n);return e==="core"?{profile:e,profile_source:t,required_fields:[...Kc],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:e==="strict"?{profile:e,profile_source:t,required_fields:[...uh],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:r.length>0?{profile:e,profile_source:t,required_fields:r,configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:{profile:e,profile_source:t,required_fields:[...Kc],configured_custom_fields:r,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}var cA=new Set(["acceptance_criteria","estimated_minutes"]);function gh(e,t,n,r){return!r&&cA.has(t)&&$r(e.status,n)?!1:t==="author"?!re(e.author):t==="acceptance_criteria"?!re(e.acceptance_criteria):t==="estimated_minutes"?!Number.isFinite(e.estimated_minutes):t==="close_reason"?Fs(e.status,n)===n.close_status&&!re(e.close_reason):t==="reviewer"?!re(e.reviewer):t==="risk"?!re(e.risk):t==="confidence"?typeof e.confidence=="number"?!Number.isFinite(e.confidence):!re(e.confidence):t==="sprint"?!re(e.sprint):!re(e.release)}function hh(e){if(e===void 0)return"default";let t=e.trim().toLowerCase();if(t.length===0||t==="default")return"default";if(t==="tracked-all"||t==="tracked_all")return"tracked-all";if(t==="tracked-all-strict"||t==="tracked_all_strict")return"tracked-all-strict";throw new _(`Unknown --scan-mode value "${e}". Supported values: ${WI.join(", ")}.`,f.USAGE)}function yh(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim();if(t)return Oe.resolve(t);let n=Oe.resolve(e);if(n.replaceAll("\\","/").endsWith("/.agents/pm"))return Oe.dirname(Oe.dirname(n));let i=Oe.resolve(process.cwd()),s=dh(n),o=dh(i),a=Oe.relative(s,o);return a.length===0||!a.startsWith("..")&&!Oe.isAbsolute(a)?n:i}function dh(e){try{return UI.native(e)}catch{return Oe.resolve(e)}}function dA(e,t){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&t.includes(e.code)}async function Yc(e,t,n){let r=t.length>0?Oe.join(e,t):e,i;try{i=await Wc.readdir(r,{withFileTypes:!0})}catch(s){if(j(s))return;throw s}for(let s of i){if(s.name.startsWith("."))continue;let o=t.length>0?Oe.join(t,s.name):s.name;if(s.isDirectory()){if(BI.has(s.name))continue;await Yc(e,o,n);continue}s.isFile()&&n.push(Ft(o))}}async function Bc(e){let t=[];for(let n of KI)await Yc(e,n,t);for(let n of zI){let r=Oe.join(e,n);try{(await Wc.stat(r)).isFile()&&t.push(Ft(n))}catch{}}return[...new Set(t)].sort((n,r)=>n.localeCompare(r))}async function vh(e){try{let{stdout:t}=await rA("git",["ls-files","-z"],{cwd:e,encoding:"utf8",maxBuffer:ZI,windowsHide:!0,timeout:eA}),n=t.split("\0").map(r=>Ft(r)).filter(r=>r.length>0);return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}catch{return null}}function lA(e,t){let n=new Set,r=Uc(yl);r.length>0&&n.add(r);let i=Uc(Oe.relative(t,e));return i.length>0&&!i.startsWith("..")&&n.add(i),[...n].sort((s,o)=>s.localeCompare(o))}function lh(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}async function uA(e,t){if(t==="tracked-all"||t==="tracked-all-strict"){let r=await vh(e);if(r)return{requestedMode:t,appliedMode:t,source:"tracked-git",candidateFiles:r,candidateTotal:r.length,candidateScanned:r.length};let i=await Bc(e);return{requestedMode:t,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:i,candidateTotal:i.length,candidateScanned:i.length}}let n=await Bc(e);return{requestedMode:t,appliedMode:"default",source:"default-curated",candidateFiles:n,candidateTotal:n.length,candidateScanned:n.length}}function ne(e,t=kt){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function tn(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=ne(e,zc);return{values:n.values,truncated:n.truncated,total:e.length}}var mA={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},fA={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function _A(e){let t=e.missing_fields.map(n=>`${mA[n]} "${fA[n]}"`).join(" ");return`pm update ${e.id} ${t} --message "Backfill resolution metadata"`}function wh(e,t){let n=e.details?.missing_resolution_remediation_hints,r=Array.isArray(n)&&n.length>0,i=r?n.filter(o=>typeof o=="string"):rg(t);if(i.length===0)return;let s=r&&e.details?.missing_resolution_remediation_hints_truncated===!0;e.details={...e.details,fix_hints:i,...s?{fix_hints_truncated:!0}:{}}}function bh(e){let t=new Set;return e.checkMetadata&&t.add("metadata"),e.checkResolution&&t.add("resolution"),(e.checkLifecycle||e.checkStaleBlockers)&&t.add("lifecycle"),e.checkFiles&&t.add("files"),e.checkHistoryDrift&&t.add("history_drift"),e.checkCommandReferences&&t.add("command_references"),e.checkStorageIntegrity&&t.add("storage_integrity"),t.size===0?(e.autoFix&&(t.add("metadata"),t.add("resolution"),t.add("lifecycle")),e.pruneMissing&&t.add("files"),t.size===0&&(t.add("metadata"),t.add("resolution"),t.add("lifecycle"),t.add("files"),t.add("command_references"),t.add("history_drift"),t.add("format_version"),t.add("storage_integrity")),t):(e.pruneMissing&&t.add("files"),t)}var pA="validate_metadata_duplicate_issue_codes";function kh(e,t){if(e.length===0)return{rows:[],truncated:!1,warnings:[]};let n=t?e.length:kt,r=e.slice(0,n);return{rows:r.map(s=>({code:s.code,count:s.count,ids:s.ids,titles:s.titles,remediation_hint:`Items ${s.ids.join(", ")} share issue code "${s.code}"; rename or merge so each logical code maps to one item.`})),truncated:r.length<e.length,warnings:[`${pA}:${e.length}`]}}function gA(){return Object.fromEntries(Vc.map(e=>[e,[]]))}function hA(e,t,n){let r=gA();for(let i of e)for(let s of Vc)gh(i,s,t,n)&&r[s].push(i.id);return r}function yA(e,t,n){let r=[...e.warnings];for(let i of e.required_fields){let s=t[i];s.length>0&&r.push(`${YI[i]}:${s.length}`)}return r.push(...n),r}function Eh(e,t){let n={};for(let r of e.required_fields){let i=t[r],s=i?i.length:0,o=JI[r];n[o]=s}return n}function Sh(e,t,n){let r=[];for(let i of e.required_fields){let s=t[i];if(s)for(let o of s){let a=n.get(o)?.type,c=typeof a=="string"&&a.length>0?a:"Unknown";r.push({item_type:c,field:i})}}return r}function vA(e,t,n,r){for(let i of t.required_fields){let s=n[i];if(!s||s.length===0)continue;let o=XI[i],a=QI[i];if(!o||!a)continue;let c=ne(s,r?s.length:kt);e[o]=c.values,e[a]=c.truncated}}function xh(e,t,n){if(!e.required_fields.includes("close_reason"))return[];let r=t.close_reason;return r?r.map(i=>({id:i,resolution:re(n.get(i)?.resolution)})):[]}function Th(e,t,n){if(!e.required_fields.includes("estimated_minutes"))return[];let r=t.estimated_minutes;return r?r.map(i=>({id:i,type:re(n.get(i)?.type)})):[]}function wA(e,t,n,r,i){let s=new Map(e.map(v=>[v.id,v])),o=t.profile==="strict",a=hA(e,n,o),c=nh(e,{configuredPrefixes:i}),d=kh(c,r),l=yA(t,a,d.warnings),u=Eh(t,a),m=Sh(t,a,s),g=rh(m),p={checked_items:e.length,metadata_profile:t.profile,metadata_profile_source:t.profile_source,metadata_profile_fallback_to_core:t.fallback_to_core,required_fields:[...t.required_fields],supported_required_fields:[...Vc],counts:u,missing_by_type:g,duplicate_issue_codes_count:c.length,duplicate_issue_codes:d.rows,duplicate_issue_codes_truncated:d.truncated};t.configured_custom_fields.length>0&&(p.configured_custom_required_fields=[...t.configured_custom_fields]),vA(p,t,a,r);let h=xh(t,a,s),y=Th(t,a,s);return{check:{name:"metadata",status:l.length===0?"ok":"warn",ok:l.length===0,details:p},warnings:l,closeReasonBackfillRows:h,estimateBackfillRows:y}}function bA(e,t,n){let r=new Set(t.terminal_done_statuses);r.add(t.close_status);let i=e.filter(m=>r.has(Fs(m.status,t))),s=[],o=[];for(let m of i){let g=HI.filter(p=>!re(m[p]));g.length!==0&&(s.push({id:m.id,missing_fields:g}),o.push({id:m.id,missing_fields:g,close_reason:re(m.close_reason)}))}let a=s.length>0?[`validate_resolution_missing_fields:${s.length}`]:[],c=n?Number.POSITIVE_INFINITY:kt,d=ne(s.map(m=>`${m.id}:${m.missing_fields.join(",")}`),c),l=s.map(m=>_A(m)),u=ne(l,c);return{check:{name:"resolution",status:a.length===0?"ok":"warn",ok:a.length===0,details:{checked_closed_items:i.length,missing_resolution_items:s.length,missing_resolution_rows:d.values,missing_resolution_rows_truncated:d.truncated,missing_resolution_remediation_hints:u.values,missing_resolution_remediation_hints_truncated:u.truncated}},warnings:a,resolutionBackfillRows:o}}function Ih(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ah(e,t="pm",n=zl()){let r=new Set(e.map(s=>s.id)),i=[...e].sort((s,o)=>s.id.localeCompare(o.id));return new Map(i.map(s=>{let o=new Set,a=Ve(s.blocked_by);a&&r.has(a)&&o.add(a),(s.dependencies??[]).filter(d=>{let l=Ve(d.kind);return l!==void 0&&n.resolve(l)?.ordering===!0}).map(d=>Ve(d.id)).filter(d=>d!==void 0&&r.has(d)).forEach(d=>o.add(d));let c=Ve(s.definition_of_ready);return Rh(c??"",t).filter(d=>r.has(d)).forEach(d=>o.add(d)),[s.id,[...o].sort((d,l)=>d.localeCompare(l))]}))}function Ch(e,t,n){let r=a_(e,n?l=>$r(l,n):void 0),i=r.active.map(l=>`${l.holder_id}:${l.target_id}:${l.kind}`),s=r.legacy_terminal.map(l=>`${l.holder_id}:${l.target_id}:${l.kind}:${l.holder_status}`),o=t?Number.POSITIVE_INFINITY:kt,a=ne(i,o),c=ne(s,o),d=ne(r.active.map(l=>l.source==="parent"?`pm update ${l.holder_id} --unset parent`:l.source==="blocked_by"?`pm update ${l.holder_id} --unset blocked_by`:`pm update ${l.holder_id} --replace-deps '<correct dependency edges>'`),o);return{check:{name:"dependency_references",status:i.length===0?"ok":"warn",ok:i.length===0,details:{checked_items:e.length,dangling_reference_count:i.length+s.length,active_dangling_reference_count:i.length,dangling_reference_rows:a.values,dangling_reference_rows_truncated:a.truncated,legacy_terminal_dangling_reference_count:s.length,legacy_closed_dangling_reference_count:r.legacy_terminal.filter(l=>l.holder_status==="closed").length,legacy_terminal_dangling_reference_rows:c.values,legacy_terminal_dangling_reference_rows_truncated:c.truncated,no_active_blocker_sentinel_count:r.no_active_blocker_sentinels.length,remediation_hints:d.values,remediation_hints_truncated:d.truncated}},warnings:i.length>0?[`validate_dangling_dependency_references:${i.length}`]:[]}}function Rh(e,t="pm"){let n=(t.trim().toLowerCase()||"pm").replace(/-+$/g,""),r=new RegExp(`(?:^|[^a-z0-9-])(${Ih(n)}-[a-z0-9][a-z0-9-]*)`,"gi");return[...new Set([...e.matchAll(r)].map(i=>i[1].toLowerCase()))].sort((i,s)=>i.localeCompare(s))}function Oh(e){let t=0,n=new Map,r=new Map,i=[],s=new Set,o=[],a=l=>{n.set(l,t),r.set(l,t),t+=1,i.push(l),s.add(l);for(let m of e.get(l)??[])n.has(m)?s.has(m)&&r.set(l,Math.min(r.get(l),n.get(m))):(a(m),r.set(l,Math.min(r.get(l),r.get(m))));if(r.get(l)!==n.get(l))return;let u=[];for(;i.length>0;){let m=i.pop();if(s.delete(m),u.push(m),m===l)break}u.sort((m,g)=>m.localeCompare(g)),o.push(u)},c=[...e.keys()].sort((l,u)=>l.localeCompare(u));for(let l of c)n.has(l)||a(l);return o.filter(l=>{if(l.length>1)return!0;let u=l[0];return(e.get(u)??[]).includes(u)}).sort((l,u)=>l[0].localeCompare(u[0])||l.length-u.length||l.join(",").localeCompare(u.join(",")))}function Dh(e,t="pm"){let n=Ah(e,t),r=Oh(n),i=[...new Set(r.flat())].sort((o,a)=>o.localeCompare(a)),s=r.map(o=>Ds(o,n).join("->"));return{cycle_count:r.length,cycle_item_ids:i,cycle_sample_paths:s}}function Lh(e){return e.startsWith("docs/")?"docs_unowned":e.startsWith("tests/")?"tests_unowned":e.startsWith("src/")?"source_unowned":e.endsWith(".md")?"docs_unowned":"unlinked_existing"}function Ps(e){let t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function Nh(e,t){let n=Ps(e).split("/").filter(Boolean),r=Ps(t).split("/").filter(Boolean),i=0;for(;i<n.length&&i<r.length&&n[i]===r[i];)i+=1;return i}function kA(e,t){let n=Ps(t),r=Ps(e),i=t.endsWith("/")?t:`${t}/`,s=e.startsWith(i),o=n.length>0&&n===r,a=Nh(e,t);return!s&&!o&&a===0?null:s?{score:t.length+1e3,confidence:"path_prefix"}:o?{score:a+500,confidence:"same_directory"}:{score:a,confidence:"shared_directory"}}function EA(e,t,n){return e===void 0||n>e.score||n===e.score&&t.id.localeCompare(e.item.id)<0}function SA(e,t,n){let r=t==="docs_unowned"?"docs":"files",i;return n.flatMap(s=>(r==="docs"?s.docs??[]:s.files??[]).map(o=>({item:s,link:o}))).forEach(({item:s,link:o})=>{if(o.scope!=="project")return;let a=Ft(o.path);if(a.length===0||a===e)return;let c=kA(e,a);c!==null&&EA(i,s,c.score)&&(i={item:s,score:c.score,confidence:c.confidence})}),i?{id:i.item.id,type:i.item.type,title:i.item.title,status:i.item.status,confidence:i.confidence}:null}function Mh(e,t){return e.map(n=>{let r=Lh(n),i=r==="docs_unowned"?"docs":"files",s=SA(n,r,t),o=s?.id??"<id>";return{path:n,classification:r,owner_candidate:s,remediation_hint:`pm ${i} ${o} --add path=${n},scope=project,note="<why this artifact belongs to the item>"`}})}function Ph(e){return e.map(t=>`${t.path}:${t.classification} owner_candidate=${t.owner_candidate?.id??"unowned"} hint=${JSON.stringify(t.remediation_hint)}`)}function xA(e,t){return Object.entries(t.closure_like_metadata_field_patterns).filter(([n,r])=>{let i=Ve(e[n]);return i?r.some(s=>i.toLowerCase().includes(s)):!1}).map(([n])=>n).sort((n,r)=>n.localeCompare(r))}function TA(e,t,n,r,i){let s=Ve(t.parent),o=s?n.get(r.get(s.toLowerCase())??s):void 0;return{id:e.id,parent_id:t.id,grandparent_id:o?.id,grandparent_active:o!==void 0&&!$r(o.status,i)}}function IA(e,t,n,r){let i=Ve(e.blocked_by),s=Ve(e.blocked_reason),o=s?.toLowerCase(),a=Fs(e.status,n),c=[];return t.has(a)?(!i&&!s&&c.push("blocked_status_missing_blocker_context"),o?.includes("no active blocker")&&c.push("blocked_status_reason_reports_no_active_blocker"),o&&r.stale_blocker_reason_patterns.some(d=>o.includes(d))&&c.push("blocked_status_reason_matches_stale_pattern"),c):(i&&c.push("non_blocked_status_has_blocked_by"),s&&c.push("non_blocked_status_has_blocked_reason"),c)}function AA(e,t,n,r){let i=new Map(e.map(c=>[c.id,c])),s=new Map(e.map(c=>[c.id.toLowerCase(),c.id])),o=n.blocked_statuses.size>0?n.blocked_statuses:new Set(["blocked"]),a={activeItems:e.filter(c=>!$r(c.status,n)),closureLikeRows:[],terminalParentRows:[],terminalParentFixRows:[],staleBlockerRows:[]};for(let c of a.activeItems){let d=xA(c,r);d.length>0&&a.closureLikeRows.push({id:c.id,fields:d});let l=Ve(c.parent),u=l?i.get(s.get(l.toLowerCase())??l):void 0;if(u&&$r(u.status,n)&&(a.terminalParentRows.push({id:c.id,parent_id:u.id,parent_status:u.status}),a.terminalParentFixRows.push(TA(c,u,i,s,n))),t){let m=IA(c,o,n,r);m.length>0&&a.staleBlockerRows.push({id:c.id,status:c.status,reasons:[...new Set(m)].sort((g,p)=>g.localeCompare(p))})}}return a}function CA(e){e.closureLikeRows.sort((t,n)=>t.id.localeCompare(n.id)),e.terminalParentRows.sort((t,n)=>t.id.localeCompare(n.id)||t.parent_id.localeCompare(n.parent_id)),e.terminalParentFixRows.sort((t,n)=>t.id.localeCompare(n.id)||t.parent_id.localeCompare(n.parent_id)),e.staleBlockerRows.sort((t,n)=>t.id.localeCompare(n.id))}function Ns(e,t,n){return n<=0||t==="off"?null:`${t==="error"?`${e}_error`:e}:${n}`}function qc(e,t,n){return n>0&&t!=="off"?`${e}:${n}`:null}function RA(e,t,n,r,i){let s=[];e.closureLikeRows.length>0&&s.push(`validate_lifecycle_active_closure_like_metadata:${e.closureLikeRows.length}`),e.terminalParentRows.length>0&&s.push(`validate_lifecycle_active_terminal_parent:${e.terminalParentRows.length}`),t&&e.staleBlockerRows.length>0&&s.push(`validate_lifecycle_stale_blockers:${e.staleBlockerRows.length}`);let o=Ns("validate_lifecycle_dependency_cycles",n,i.dependencyCycles),a=Ns("validate_hierarchy_parent_cycle",r,i.activeHierarchyCycles),c=Ns("validate_hierarchy_cardinality_violation",r,i.activeHierarchyCardinality),d=Ns("validate_hierarchy_parent_divergence",r,i.activeHierarchyDivergence),l=qc("validate_legacy_hierarchy_parent_cycle",r,i.legacyHierarchyCycles),u=qc("validate_legacy_hierarchy_cardinality_violation",r,i.legacyHierarchyCardinality),m=qc("validate_legacy_hierarchy_parent_divergence",r,i.legacyHierarchyDivergence);return[...s,...o?[o]:[],...a?[a]:[],...c?[c]:[],...d?[d]:[],...l?[l]:[],...u?[u]:[],...m?[m]:[]]}function Fh(e){let t=Ft(e);return t.length>tA||t.split(/[\\/]/).some(n=>n.length>nA)}async function OA(e,t){let n=Oe.isAbsolute(t)?t:Oe.resolve(e,t);if(Fh(n))return!1;try{let r=await Wc.stat(n);return!r.isFile()&&!r.isDirectory()}catch(r){return dA(r,["ENOENT","ENOTDIR"])}}async function DA(e,t){let n={linkedProjectPaths:new Set,remoteLinkedPaths:new Set,missingLinkedPaths:[],staleLinkRows:[]},r=e.flatMap(i=>[...(i.files??[]).map(s=>({item:i,artifact:s,link_kind:"files"})),...(i.docs??[]).map(s=>({item:i,artifact:s,link_kind:"docs"}))]);for(let{item:i,artifact:s,link_kind:o}of r){if(s.scope!=="project")continue;if(Rr(s.path)){n.remoteLinkedPaths.add(s.path.trim());continue}let a=Ft(s.path);a.length!==0&&(n.linkedProjectPaths.add(a),await OA(t,s.path)&&(n.missingLinkedPaths.push(a),n.staleLinkRows.push({item_id:i.id,path:a,link_kind:o})))}return n}function LA(e,t,n,r,i,s){let o=r==="tracked-all-strict",a=o&&!i,c=i||o,d=c?[]:lA(t,n),l=d.length===0?[]:e.candidateFiles.filter(g=>lh(g,d)),u=d.length===0?e.candidateFiles:e.candidateFiles.filter(g=>!lh(g,d)),m={};if(l.length>0){let g=tn(l,s);m.pm_internals={count:l.length,paths:g.values,paths_truncated:g.truncated,paths_total:g.total}}return{strictTrackedAllMode:o,strictModeForcesPmInternals:a,includePmInternalsEffective:c,pmInternalCandidatePrefixes:d,excludedPmInternalPaths:l,candidateFiles:u,excludedByReason:m}}function $h(e,t,n,r,i,s,o,a="pm"){let c=AA(e,t,i,s);CA(c);let d=Dh(c.activeItems,a),l=jc(e,i),u=_s(i,e,o?Number.POSITIVE_INFINITY:kt),m=[...RA(c,t,n,r,{dependencyCycles:d.cycle_count,activeHierarchyCycles:l.active_cycle_count,activeHierarchyCardinality:l.active_cardinality_violation_count,activeHierarchyDivergence:l.active_parent_divergence_count,legacyHierarchyCycles:l.legacy_cycle_count,legacyHierarchyCardinality:l.legacy_cardinality_violation_count,legacyHierarchyDivergence:l.legacy_parent_divergence_count}),...ps(u)],g=o?Number.POSITIVE_INFINITY:kt,p=ne(c.closureLikeRows.map(b=>`${b.id}:${b.fields.join(",")}`),g),h=ne(c.terminalParentRows.map(b=>`${b.id}:${b.parent_id}:${b.parent_status}`),g),y=ne(c.staleBlockerRows.map(b=>`${b.id}:${b.status}:${b.reasons.join(",")}`),g),v=ne(d.cycle_item_ids,g),w=ne(d.cycle_sample_paths,g),E=ne(l.cycle_item_ids,g),S=ne(l.cycle_sample_paths,g),x=ne(l.cardinality_violation_rows,g),I=ne(l.parent_divergence_rows,g),k=d.cycle_count>0&&n==="error"||(l.active_cycle_count>0||l.active_cardinality_violation_count>0||l.active_parent_divergence_count>0)&&r==="error";return{check:{name:"lifecycle",status:k?"error":m.length===0?"ok":"warn",ok:!k&&m.length===0,details:{checked_active_items:c.activeItems.length,lifecycle_status_roles:u,active_closure_like_metadata_items:c.closureLikeRows.length,active_closure_like_metadata_rows:p.values,active_closure_like_metadata_rows_truncated:p.truncated,active_terminal_parent_items:c.terminalParentRows.length,active_terminal_parent_rows:h.values,active_terminal_parent_rows_truncated:h.truncated,stale_blocker_checks_enabled:t,stale_blocker_items:c.staleBlockerRows.length,stale_blocker_rows:y.values,stale_blocker_rows_truncated:y.truncated,dependency_cycle_severity_policy:n,dependency_cycle_count:d.cycle_count,dependency_cycle_item_count:d.cycle_item_ids.length,dependency_cycle_item_ids:v.values,dependency_cycle_item_ids_truncated:v.truncated,dependency_cycle_sample_paths:w.values,dependency_cycle_sample_paths_truncated:w.truncated,parent_cycle_severity_policy:r,parent_cycle_count:l.cycle_count,active_parent_cycle_count:l.active_cycle_count,legacy_parent_cycle_count:l.legacy_cycle_count,parent_cycle_item_count:l.cycle_item_ids.length,parent_cycle_item_ids:E.values,parent_cycle_item_ids_truncated:E.truncated,parent_cycle_sample_paths:S.values,parent_cycle_sample_paths_truncated:S.truncated,hierarchy_cardinality_violation_count:l.cardinality_violation_count,active_hierarchy_cardinality_violation_count:l.active_cardinality_violation_count,legacy_hierarchy_cardinality_violation_count:l.legacy_cardinality_violation_count,hierarchy_cardinality_violation_rows:x.values,hierarchy_cardinality_violation_rows_truncated:x.truncated,hierarchy_parent_divergence_count:l.parent_divergence_count,active_hierarchy_parent_divergence_count:l.active_parent_divergence_count,legacy_hierarchy_parent_divergence_count:l.legacy_parent_divergence_count,hierarchy_parent_divergence_rows:I.values,hierarchy_parent_divergence_rows_truncated:I.truncated,stale_blocker_reason_patterns:[...s.stale_blocker_reason_patterns],stale_blocker_reason_pattern_source:s.stale_blocker_reason_pattern_source,closure_like_blocked_reason_patterns:[...s.closure_like_metadata_field_patterns.blocked_reason],closure_like_blocked_reason_pattern_source:s.closure_like_metadata_field_pattern_sources.blocked_reason,closure_like_resolution_patterns:[...s.closure_like_metadata_field_patterns.resolution],closure_like_resolution_pattern_source:s.closure_like_metadata_field_pattern_sources.resolution,closure_like_actual_result_patterns:[...s.closure_like_metadata_field_patterns.actual_result],closure_like_actual_result_pattern_source:s.closure_like_metadata_field_pattern_sources.actual_result}},warnings:m,terminalParentFixRows:c.terminalParentFixRows}}async function jh(e,t,n,r,i,s,o=H(Gt.schema)){let a=await DA(e,t),c=new Map(e.map(A=>[A.id,A])),d=[...new Set(a.missingLinkedPaths)].sort((A,K)=>A.localeCompare(K)),l=await uA(t,r),u=LA(l,n,t,r,i,s),m=u.candidateFiles.filter(A=>!a.linkedProjectPaths.has(A)),g=Mh(m,e),p=oh(d,u.candidateFiles),h=new Map(p.map(A=>[A.path,A.classification])),y=p.filter(A=>A.classification==="moved").length,v=a.staleLinkRows.map(A=>({...A,classification:h.get(A.path)??"deleted"})).sort((A,K)=>A.item_id.localeCompare(K.item_id)||A.path.localeCompare(K.path)||A.link_kind.localeCompare(K.link_kind)),w=[];u.strictModeForcesPmInternals&&w.push("validate_files_tracked_all_strict_forces_pm_internals"),m.length>0&&w.push(`validate_files_orphaned_paths:${m.length}`);let E=[...a.remoteLinkedPaths].sort((A,K)=>A.localeCompare(K)),S=tn(E,s),x=tn(d,s),I=tn(m,s),k=tn(g.map(A=>`${A.path}:${A.classification}:owner_candidate=${A.owner_candidate?.id??"unowned"}`),s),b=s?g:tn(Ph(g),!1).values,O=tn(ah(p),s),P=Eg(v,p,A=>c.get(A),o,s?1/0:zc);return P.active_missing_linked_paths_count>0&&w.push(`validate_files_missing_linked_paths:${P.active_missing_linked_paths_count}`),{check:{name:"files",status:w.length===0?"ok":"warn",ok:w.length===0,details:{workspace_root:t,scan_mode_requested:l.requestedMode,scan_mode_applied:l.appliedMode,strict_tracked_all_mode:u.strictTrackedAllMode,strict_mode_forces_pm_internals:u.strictModeForcesPmInternals,strict_mode_forces_pm_internals_notice:u.strictModeForcesPmInternals?"tracked-all-strict force-enables PM internals; pass --include-pm-internals to make inclusion explicit.":null,file_list_detail_mode:s?"full":"summary",file_list_summary_limit:zc,candidate_scan_source:l.source,include_pm_internals:u.includePmInternalsEffective,include_pm_internals_requested:i,pm_internal_candidate_prefixes:u.pmInternalCandidatePrefixes,pm_internal_excluded_count:u.excludedPmInternalPaths.length,excluded_total:u.excludedPmInternalPaths.length,excluded_by_reason:u.excludedByReason,linked_project_paths:a.linkedProjectPaths.size,remote_linked_paths_count:E.length,remote_linked_paths_total:S.total,remote_linked_paths:S.values,remote_linked_paths_truncated:S.truncated,candidate_total_raw:l.candidateTotal,candidate_scanned_raw:l.candidateScanned,candidate_total:u.candidateFiles.length,candidate_scanned:u.candidateFiles.length,scanned_candidate_files:u.candidateFiles.length,missing_linked_paths_count:d.length,missing_linked_paths_total:x.total,missing_linked_paths:x.values,missing_linked_paths_truncated:x.truncated,missing_linked_paths_moved_count:y,missing_linked_paths_deleted_count:p.filter(A=>A.classification==="deleted").length,missing_linked_paths_malformed_count:p.filter(A=>A.classification==="malformed").length,missing_linked_path_classifications:O.values,missing_linked_path_classifications_truncated:O.truncated,...P,orphaned_paths_count:m.length,orphaned_paths_total:I.total,orphaned_paths:I.values,orphaned_paths_truncated:I.truncated,orphaned_path_classifications:k.values,orphaned_path_classifications_truncated:k.truncated,orphaned_path_rows_count:g.length,orphaned_path_rows:b}},warnings:w,staleLinkPruneRows:v}}function Uh(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length>120?`${t.slice(0,117)}...`:t}function NA(e,t,n){return`${e}:${t}:${Uh(n)}`}function MA(e,t){let n=[];return e.forEach(({item:r,linkedTest:i},s)=>{let o=t[s];if(o.trusted)return;let a=Uh(i.command??"");n.push(`${r.id}:${o.source_ref??"unknown"}->${o.current_source_ref??"unknown"}:${a}`)}),n}async function qh(e,t,n,r){let i=new Set(e.map(x=>x.id.toLowerCase())),s=0,o=0,a=new Set,c=[],d=e.flatMap(x=>(x.tests??[]).map(I=>({item:x,linkedTest:I}))),l=await Mr(Pr()),u=await Bg(r,d.map(({linkedTest:x})=>x),l),m=MA(d,u);for(let{item:x,linkedTest:I}of d){if(typeof I.command!="string"||I.command.trim().length===0)continue;s+=1;let k=Cc(I.command,t);if(k.length!==0){o+=k.length;for(let b of k)a.add(b),i.has(b.toLowerCase())||c.push(NA(x.id,b,I.command))}}let g=[...new Set(c)].sort((x,I)=>x.localeCompare(I)),p=[...new Set(g.map(x=>x.split(":")[1]??""))].filter(x=>x.length>0).sort((x,I)=>x.localeCompare(I)),h=[];g.length>0&&h.push(`validate_command_references_stale_pm_ids:${g.length}`),m.length>0&&h.push(`validate_linked_test_trust_unacknowledged:${m.length}`);let y=n?Number.POSITIVE_INFINITY:kt,v=ne(g,y),w=ne(p,y),E=ne([...a].sort((x,I)=>x.localeCompare(I)),y),S=ne(m,y);return{check:{name:"command_references",status:h.length===0?"ok":"warn",ok:h.length===0,details:{checked_items:e.length,linked_commands_scanned:s,referenced_pm_ids_count:o,unique_referenced_pm_ids_count:a.size,unique_referenced_pm_ids:E.values,unique_referenced_pm_ids_truncated:E.truncated,linked_test_trust_current_source_ref:l??null,untrusted_linked_tests_count:m.length,untrusted_linked_tests:S.values,untrusted_linked_tests_truncated:S.truncated,stale_pm_id_references_count:g.length,stale_pm_ids_count:p.length,stale_pm_ids:w.values,stale_pm_ids_truncated:w.truncated,stale_pm_id_reference_rows:v.values,stale_pm_id_reference_rows_truncated:v.truncated}},warnings:h}}function PA(e,t){let n=Si(e.map(c=>({ref:c.id,version:Ei(c)}))),r=[];n.outdated.length>0&&r.push(`validate_format_version_outdated_items:${n.outdated.length}`),n.ahead.length>0&&r.push(`validate_format_version_ahead_items:${n.ahead.length}`);let i=t?Number.POSITIVE_INFINITY:kt,s=ne(n.outdated,i),o=ne(n.ahead,i),a=n.ahead.length>0?"error":n.outdated.length>0?"warn":"ok";return{check:{name:"format_version",status:a,ok:a==="ok",details:{checked_items:e.length,current_format_version:au,outdated_items_count:n.outdated.length,outdated_items:s.values,outdated_items_truncated:s.truncated,ahead_items_count:n.ahead.length,ahead_items:o.values,ahead_items_truncated:o.truncated}},warnings:r}}var Hc="pm validate auto-fix";async function Gh(e,t,n){switch(e.kind){case"set_resolution":case"set_close_reason":case"set_estimate":case"reparent":case"unset_parent":{let r={message:Hc};if(e.kind==="set_resolution"?r.resolution=e.value:e.kind==="set_close_reason"?r.closeReason=e.value:e.kind==="set_estimate"?r.estimatedMinutes=e.value:e.kind==="reparent"?r.parent=e.parent_id:r.unset=["parent"],!n.runUpdate)throw new _("Applying validate metadata/lifecycle fixes requires a runUpdate mutation service.",f.USAGE);await n.runUpdate(e.item_id,r,t);return}case"prune_file_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`);case"prune_doc_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`)}}function Gc(e){return e.kind!=="prune_file_link"&&e.kind!=="prune_doc_link"?null:`${e.kind}:${e.item_id}`}async function Kh(e,t,n){let r=[],i=[],s=new Map;for(let o of e.filter(a=>Gc(a)===null))try{await Gh(o,t,n),r.push(o)}catch(a){i.push({fix:o,error:a})}for(let o of e.filter(a=>Gc(a)!==null)){let a=Gc(o),c=s.get(a);c?c.push(o):s.set(a,[o])}for(let o of s.values()){let a=o[0];if(!a)continue;let c=o.map(d=>d.path).filter(d=>typeof d=="string"&&d.length>0);try{a.kind==="prune_file_link"?await Ng(a.item_id,{remove:c,message:Hc},t):await Ag(a.item_id,{remove:c,message:Hc},t),r.push(...o)}catch(d){i.push(...o.map(l=>({fix:l,error:d})))}}return{applied:r,failed:i}}var Cz={applyValidateFix:Gh,applyValidateFixes:Kh,attachValidateFixHints:wh,buildCommandReferencesCheck:qh,buildDependencyReferencesCheck:Ch,buildCloseReasonBackfillRows:xh,buildFilesCheck:jh,buildLifecycleCheck:$h,buildLifecycleDependencyGraph:Ah,buildLifecycleParentGraph:$c,buildEstimateBackfillRows:Th,buildMetadataCounts:Eh,buildMissingFieldOccurrences:Sh,buildOrphanedPathRows:Mh,classifyOrphanedPath:Lh,collectDefaultProjectFileCandidates:Bc,collectTrackedGitFileCandidates:vh,detectLifecycleDependencyCycles:Dh,detectLifecycleParentCycles:jc,escapeRegExp:Ih,extractItemIds:Rh,findLifecycleDependencyCycleComponents:Oh,isMetadataFieldMissing:gh,linkedArtifactPathExceedsFilesystemLimits:Fh,listFilesRecursive:Yc,resolveDependencyCycleSeverity:_h,resolveParentCycleSeverity:ph,resolveFileScanMode:hh,resolveLifecycleDependencyCycleSamplePath:Ds,resolveRequestedChecks:bh,resolveValidateMetadataProfile:fh,resolveWorkspaceRoot:yh,sharedDirectoryPrefixLength:Nh,summarizeOrphanedPathRows:Ph,summarizeDuplicateIssueCodes:kh,toMeaningfulString:Ve};function FA(e,t){t>0&&e.push(`merge_receipt_evidence_invalid:${t}`)}async function $A(e,t,n,r){let i=await xg(e,new Set(t.map(y=>y.id)),n,{schema:r.schema,extensionFieldNames:It(F())}),s=[];i.unreadable_item_files.length>0&&s.push(`validate_storage_unreadable_items:${i.unreadable_item_files.length}`),i.duplicate_item_ids.length>0&&s.push(`validate_storage_duplicate_item_ids:${i.duplicate_item_ids.length}`),i.history_conflict_marker_streams.length>0&&s.push(`validate_storage_history_conflict_markers:${i.history_conflict_marker_streams.length}`),i.history_unparseable_streams.length>0&&s.push(`validate_storage_unparseable_history:${i.history_unparseable_streams.length}`),i.resurrected_items.length>0&&s.push(`validate_storage_resurrected_items:${i.resurrected_items.length}`),i.unparseable_config_files.length>0&&s.push(`validate_storage_unparseable_config:${i.unparseable_config_files.length}`);let o=s.length,a=await hs(e);a.tracked_path_count>0&&s.push(`validate_storage_tracked_runtime_cache_files:${a.tracked_path_count}`);let c=await Yi(e,Vi(r));c.status==="drift"&&s.push(`validate_merge_fence_drift:${c.missing_patterns.length+c.stale_patterns.length}`);let d=await Lt(e),l=d===null?null:await On(d);l!==null&&l.status!=="ok"&&s.push(`validate_merge_driver_configuration:${l.missing_keys.length+l.drifted_keys.length}`);let u=await st(d??e,{includeLossless:!0,pmRoot:e}),m=u.receipts,{pendingDecisions:g,lossless:p}=$n(m);g.length>0&&s.push(`validate_merge_decisions_unreviewed:${g.length}`),FA(s,u.invalid_evidence_count);let h=o>0?"error":s.length>0?"warn":"ok";return{check:{name:"storage_integrity",status:h,ok:h==="ok",details:{...i,merge_fence:c,merge_driver_configuration:l,pending_merge_decision_count:g.length,pending_merge_decision_items:[...new Set(g.map(y=>y.item_id))].sort((y,v)=>y.localeCompare(v)),lossless_merge_receipt_count:p.length,invalid_merge_receipt_evidence_count:u.invalid_evidence_count,invalid_merge_receipt_evidence_details:u.invalid_evidence,invalid_merge_receipt_evidence_details_truncated:u.invalid_evidence_truncated,lossless_merge_receipt_items:[...new Set(p.map(y=>y.item_id))].sort((y,v)=>y.localeCompare(v)),tracked_runtime_cache:{tracker_relative_root:a.tracker_relative_root,tracked_paths:a.tracked_paths,tracked_path_count:a.tracked_path_count,remediation_command:a.remediation_command}}},warnings:s}}function bt(e,t,n){n&&wh(t.check,t.warnings),e.checks.push(t.check),e.warnings.push(...t.warnings)}async function jA(e){let t={checks:[],warnings:[...e.initialWarnings],closeReasonBackfillRows:[],estimateBackfillRows:[],resolutionBackfillRows:[],terminalParentFixRows:[],staleLinkPruneRows:[]},n=e.options.fixHints===!0,r=e.options.verboseDiagnostics===!0||e.options.allAffectedIds===!0||e.global.json===!0;if(e.requestedChecks.has("metadata")){let i=wA(e.items,e.metadataPolicy,e.statusRegistry,r,[e.settings.id_prefix]);t.closeReasonBackfillRows=i.closeReasonBackfillRows,t.estimateBackfillRows=i.estimateBackfillRows,bt(t,i,n)}if(e.requestedChecks.has("resolution")){let i=bA(e.items,e.statusRegistry,r);t.resolutionBackfillRows=i.resolutionBackfillRows,bt(t,i,n)}if(e.requestedChecks.has("lifecycle")){let i=$h(e.items,!!e.options.checkStaleBlockers,e.dependencyCycleSeverity,e.parentCycleSeverity,e.statusRegistry,e.lifecyclePatternPolicy,r,e.settings.id_prefix);t.terminalParentFixRows=i.terminalParentFixRows,bt(t,i,n),bt(t,Ch(e.items,r,e.statusRegistry),n)}if(e.requestedChecks.has("files")){let i=await jh(e.items,e.workspaceRoot,e.pmRoot,e.fileScanMode,!!e.options.includePmInternals,!!e.options.verboseFileLists,e.statusRegistry);t.staleLinkPruneRows=i.staleLinkPruneRows,bt(t,i,n)}return e.requestedChecks.has("command_references")&&bt(t,await qh(e.items,e.settings.id_prefix,r,e.pmRoot),n),e.requestedChecks.has("history_drift")&&bt(t,await Os(e.pmRoot,e.items,r),n),e.requestedChecks.has("format_version")&&bt(t,PA(e.items,r),n),e.requestedChecks.has("storage_integrity")&&bt(t,await $A(e.pmRoot,e.items,U(e.settings,F()).type_to_folder,e.settings),n),t}function UA(e,t,n){let r=[];return e.autoFix===!0&&(r.push(...Yg(t.closeReasonBackfillRows)),r.push(...Vg(t.resolutionBackfillRows)),r.push(...Jg(t.estimateBackfillRows,n.validation.estimate_defaults_by_type)),r.push(...Xg(t.terminalParentFixRows))),e.pruneMissing===!0&&r.push(...Qg(t.staleLinkPruneRows)),r}async function qA(e,t,n,r,i,s){if(e.autoFix!==!0&&e.pruneMissing!==!0)return;let o=UA(e,t,n),{applicable:a,gated:c}=eh(o,r),d=e.dryRun===!0,l=[],u=[];if(!d){let m=await Kh(a,i,s);l.push(...m.applied.map(Fr)),u.push(...m.failed.map(({fix:g,error:p})=>({...Fr(g),error:p instanceof Error?p.message:String(p)})))}return{mode:d?"dry_run":"apply",auto_fix:e.autoFix===!0,prune_missing:e.pruneMissing===!0,granted_fix_scopes:[...r].sort((m,g)=>m.localeCompare(g)),planned_count:o.length,applied_count:l.length,gated_count:c.length,failed_count:u.length,planned_fixes:o.map(Fr),applied_fixes:l,gated_fixes:c.map(m=>({...Fr(m),gate_hint:`Withheld: re-run with --fix-scope ${m.gate} to apply.`})),failed_fixes:u}}async function zh(e,t,n={}){mu(e.counts===!0,e.full===!0,"--counts");let r=e.autoFix===!0||e.pruneMissing===!0;if(e.dryRun===!0&&!r)throw new _("--dry-run requires --auto-fix or --prune-missing (there is nothing to preview otherwise).",f.USAGE);if(e.fixScope!==void 0&&e.fixScope.length>0&&e.autoFix!==!0)throw new _("--fix-scope requires --auto-fix.",f.USAGE);let i=Zg(e.fixScope),s=R(process.cwd(),t.path);await $(s);let o=await C(s),a=H(o.schema),c=U(o,F()),d=bh(e),l=[],u=await Rs({includeBody:d.has("history_drift")||d.has("metadata"),pmRoot:s,settings:o,typeToFolder:c.type_to_folder,warnings:l});if(d.has("history_drift")){let O=await Er(s);O.actionable_unknown_event_count>0&&l.push(`validate_history_unknown_author_events:${O.actionable_unknown_event_count}`)}let m=typeof e.metadataProfile=="string"?"option":"settings",g=fh(typeof e.metadataProfile=="string"?e.metadataProfile:o.validation.metadata_profile),p=aA(g,m,o.validation.metadata_required_fields),h=sA(o),y=_h(e.dependencyCycleSeverity),v=ph(e.parentCycleSeverity),w=hh(e.scanMode),E=yh(s),S=await jA({requestedChecks:d,options:e,global:t,pmRoot:s,workspaceRoot:E,settings:o,items:u,statusRegistry:a,metadataPolicy:p,lifecyclePatternPolicy:h,dependencyCycleSeverity:y,parentCycleSeverity:v,fileScanMode:w,initialWarnings:[...new Set(l)]}),x=r?await qA(e,S,o,i,t,n):void 0,I=[...new Set(S.warnings)].sort((O,W)=>O.localeCompare(W)),b={ok:!S.checks.some(O=>O.status==="error"),has_warnings:I.length>0,checks:S.checks,warnings:I,...x!==void 0?{fixes:x}:{},generated_at:T(),projection:{mode:"full",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:["diagnostic_rows"]}};return e.counts!==!0?b:{...iA(b),projection:{mode:"counts",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:[]}}}import{execFile as GA}from"node:child_process";import{promisify as KA}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cdf52e5c-86cf-5540-bc08-bfc274a1fdf9")}catch{}})();var zA=KA(GA),BA=16,HA=3e4;function WA(e,t,n){if(!(e.keys[t].value_type==="number"?typeof n.value=="number"&&Number.isFinite(n.value):Array.isArray(n.value)&&n.value.every(s=>typeof s=="string")))throw new TypeError(`assurance provider ${e.id} key ${t} returned the wrong value type`);if(!Number.isInteger(n.population_size)||n.population_size<0||!Number.isFinite(n.cost)||n.cost<0)throw new TypeError(`assurance provider ${e.id} returned an invalid population or cost`);return n}function VA(e,t){let n=e.keys[t.key];if(!n)throw new TypeError(`assurance provider ${e.id} does not declare key ${t.key}`);let r=t.parameters??{},i=n.parameters??{};for(let s of Object.entries(i).filter(([,o])=>o.required===!0).map(([o])=>o))if(!Object.hasOwn(r,s))throw new TypeError(`assurance provider ${e.id} key ${t.key} requires parameter ${s}`);for(let[s,o]of Object.entries(r)){let a=i[s];if(!a)throw new TypeError(`assurance provider ${e.id} key ${t.key} does not declare parameter ${s}`);if(o===null||typeof o!==a.type)throw new TypeError(`assurance provider ${e.id} parameter ${s} must be ${a.type}`)}return{...r}}async function YA(e,t,n,r){let i=VA(e,t),s=Promise.resolve().then(()=>e.resolve({provider:e.id,key:t.key,parameters:i,trigger:r,pm_root:n,...Hl(n)}));s.catch(()=>{});let o;try{let a=await Promise.race([s,new Promise((c,d)=>{o=setTimeout(()=>d(new TypeError(`assurance provider ${e.id} timed out`)),e.timeout_ms??HA),o.unref?.()})]);return WA(e,t.key,a)}finally{clearTimeout(o)}}function Hh(e,t,n,r){let i=e;for(let s of t.split(".")){if(typeof i!="object"||i===null||Array.isArray(i))throw new nt(`assurance field ${t} is not present`,{source_kind:n,field:t,...r?{check:r}:{}});i=i[s]}if(typeof i=="number"&&Number.isFinite(i)||Array.isArray(i)&&i.every(s=>typeof s=="string"))return i;throw new nt(`assurance field ${t} must resolve to a finite number or string array`,{source_kind:n,field:t,...r?{check:r}:{}})}function Bh(e,t,n,r){let i=e.checks.find(o=>o.name===t);if(!i)throw new nt(`assurance check ${t} is not present`,{source_kind:r,field:n,check:t});return{value:n==="status"||n==="ok"?i.ok?0:1:Hh(i.details,n,r,t),population_size:1,cost:e.checks.length}}async function JA(e,t){if(t?.trim())return t.trim();try{let{stdout:n}=await zA("git",["rev-parse","HEAD^{commit}"],{cwd:e,encoding:"utf8",timeout:5e3,windowsHide:!0});return n.trim()}catch{return"working-copy"}}async function XA(e,t){let n=new Array(t.length),r=0,i=Array.from({length:Math.min(BA,t.length)},async()=>{for(;r<t.length;){let s=r;r+=1;let o=t[s],a=await Rt(Tt(e,o.id),o.id);n[s]=a.map(c=>({op:c.op,author:c.author,agent_harness:c.agent_harness,agent_model:c.agent_model}))}});return await Promise.all(i),n.flat()}async function jr(e,t={}){let n=await C(e),r=U(n),i=H(n.schema),o=(t.strict_read===!0?(await x_(void 0,{status:"all",full:!0,noTruncate:!0,strictRead:!0},{path:e})).items:await Rn(e,n.item_format,r.type_to_folder,void 0,n.schema)).map(g=>({...g,id:g.id,status:g.status,type:g.type})),a={path:e},c=F(),d=Object.fromEntries((c?.assurance_providers??[]).map(g=>[g.definition.id,{cost_class:g.runtime_definition.cost_class,network:g.runtime_definition.network}])),l=new Map,u,m;return{tree_id:t.resolve_tree===!1?t.tree_id??"working-copy":await JA(e,t.tree_id),items:o,history:t.include_history===!1?[]:await XA(e,o),terminal_statuses:[...i.terminal_statuses],provider_capabilities:{...d,...t.provider_capabilities},external:async g=>{if(g.kind==="graph"){let y=D({operation:g.operation,parameters:g.parameters??{}}),v=l.get(y);v===void 0&&(v=u_(g.operation,void 0,void 0,{...g.parameters,full:!0},a),l.set(y,v));let w=await v;return{value:Hh(w,g.field,g.kind),population_size:o.length,cost:o.length}}if(g.kind==="validate"){u??=zh({counts:!0},a);let y=await u;return Bh(y,g.check,g.field,g.kind)}if(g.kind==="health"){m??=wg(a,{checkOnly:!0,full:!0});let y=await m;return Bh(y,g.check,g.field,g.kind)}let p=t.providers?.[g.provider];if(p)return p(g);let h=Zl(c,g.provider);if(!h)throw new TypeError(`assurance provider ${g.provider} is not registered`);return YA(h.runtime_definition,g,e,t.trigger??"sdk")}}}import{createHash as QA}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ef2edfdc-7166-5cfc-adf1-fc8c69dfab1c")}catch{}})();function Wh(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new TypeError("recurrence coverage request must be an object");let t=e;if(Object.hasOwn(t,"change"))throw new TypeError("recurrence coverage request does not accept change");if(t.uncoveredOnly!==void 0&&typeof t.uncoveredOnly!="boolean")throw new TypeError("recurrence coverage request.uncoveredOnly must be a boolean");let{policy:n,cursor:r,limit:i}=Ki({...t,change:{}});return{policy:n,...r===void 0?{}:{cursor:r},...i===void 0?{}:{limit:i},...t.uncoveredOnly===void 0?{}:{uncoveredOnly:t.uncoveredOnly}}}function ZA(e,t){if(e===void 0)return 0;let n;try{n=JSON.parse(Buffer.from(e,"base64url").toString("utf8"))}catch{throw new TypeError("recurrence coverage cursor is invalid")}if(typeof n!="object"||n===null||Array.isArray(n))throw new TypeError("recurrence coverage cursor is invalid");let r=n;if(r.fingerprint!==t||typeof r.offset!="number"||!Number.isSafeInteger(r.offset)||r.offset<0)throw new TypeError("recurrence coverage cursor does not match this evidence and filter");return r.offset}function eC(e,t,n,r,i,s){let o=Object.fromEntries(ha.map(g=>[g,0])),a=0,c=0,d=0,l=0,u=[],m=QA("sha256").update(i);for(let g of r){let p=e.membership.get(g),h=n.has(g),y=p.family_ids.length>0;y&&h&&(a+=1),y||(c+=1),h||(d+=1);let v=t.get(g)?.escape_class;v!==void 0&&ha.includes(v)&&(o[v]+=1,l+=1),m.update(D([g,h,t.get(g)??null,p.id,p.family_ids])),(!s||!y||!h)&&u.push(g)}return{classCounts:o,coveredCount:a,uncoveredCount:c,missingCount:d,classifiedCount:l,selected:u,fingerprint:m.digest("hex")}}function Vh(e,t,n={}){Zf(e);let r=n.limit??25;if(!Number.isSafeInteger(r)||r<1||r>100)throw new TypeError("recurrence coverage limit must be an integer from 1 through 100");let i=new Set,s=new Map;for(let S of t){if(i.has(S.id))throw new TypeError(`Duplicate recurrence item ${S.id}`);i.add(S.id);let x=Gi(S);x!==void 0&&s.set(S.id,x)}let o=Jf(e.families,s),a=[...o.membership.keys()].sort(),c=D({policy:e,uncoveredOnly:n.uncoveredOnly===!0}),{classCounts:d,coveredCount:l,uncoveredCount:u,missingCount:m,classifiedCount:g,selected:p,fingerprint:h}=eC(o,s,i,a,c,n.uncoveredOnly===!0),y=ZA(n.cursor,h);if(y>p.length)throw new TypeError("recurrence coverage cursor offset exceeds the selected population");let v=p.slice(y,y+r).map(S=>{let x=o.membership.get(S),I=i.has(S);return{item_id:S,lineage_id:x.id,lineage_item_count:x.item_ids.length,family_ids:x.family_ids,present:I,...I?x.family_ids.length===0?{finding:"unregistered_recurrence_item"}:{}:{finding:"missing_recurrence_item"}}}),w=y+v.length,E=a.length===0?null:d.production_defect/a.length;return{ok:u===0&&m===0,fingerprint:h,items:v,total:p.length,has_more:w<p.length,...w<p.length?{next_cursor:Buffer.from(JSON.stringify({fingerprint:h,offset:w})).toString("base64url")}:{},population:{scope:"all_recorded_recurrence_items",item_count:a.length,lineage_count:o.lineages.length,edge_count:o.edge_count,covered_item_count:l,uncovered_item_count:u,missing_item_count:m,classified_item_count:g,unclassified_item_count:a.length-g,class_counts:d,escape_rate:g===a.length?E:null,escape_rate_lower_bound:E},budget_scope:"registered_families_only",cost:{items_scanned:t.length,edges_scanned:o.edge_count,row_limit:r},row_contract:{row_keys:["items"],jq_selector:".items[]"}}}import{createHash as tC}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="811330eb-207d-5e27-9786-72c1fba7d4c9")}catch{}})();var Jc,Yh=["list","show","put","remove","run","verdicts","presets","apply","derive","promote","risk","lineages"],Xc=["measurement","assertion","gate"];function nC(e){if(Yh.includes(e))return e;throw ai({command_path:"assurance",token:e,allowed:Yh,display_name:"assurance action"})}function Hn(e,t,n){throw new _(t,f.USAGE,{code:"missing_required_argument",required:`Provide the missing assurance operand: ${e}.`,examples:[n],recovery:{missing:[e]}})}function rC(e){if(!e)return Hn("kind",`Assurance declaration kind is required. Expected: ${Xc.join(", ")}`,"pm assurance list measurement");if(Xc.includes(e))return e;throw new _(`Assurance declaration kind is required. Expected: ${Xc.join(", ")}`,f.USAGE)}function Jh(e){if(!e)return Hn("preset",`Assurance preset is required. Expected: ${wr.join(", ")}`,"pm assurance apply software-delivery --owner <pm-item-id>");if(wr.includes(e))return e;throw new _(`Assurance preset is required. Expected: ${wr.join(", ")}`,f.USAGE)}function Qc(e){return e.owner?.trim()?e.owner.trim():Hn("owner","assurance preset and derivation actions require --owner <pm-item-id>","pm assurance apply software-delivery --owner <pm-item-id>")}function iC(e,t){let n=t;if(typeof t=="string")if(!t.trim())n=void 0;else try{n=JSON.parse(t)}catch(r){throw new _("assurance definition must be valid JSON",f.USAGE,{reason:r instanceof Error?r.message:"invalid_json"})}if(typeof n!="object"||n===null||Array.isArray(n))throw new _("assurance put requires a JSON object definition",f.USAGE);return n}async function sC(e){let[t,n,r]=await Promise.all([vr(e,"measurement"),vr(e,"assertion"),vr(e,"gate")]);return{version:1,measurements:t.items,assertions:n.items,gates:r.items}}function Xh(e,t){return t===!0?{id:e.id}:e}async function oC(e,t){let n=t.authorization_decision;if(!n)return[];let r=await jr(e,{include_history:!1,resolve_tree:!1}),i=r.items.find(o=>o.id===n),s=new Set(r.terminal_statuses);if(!i||i.type.toLowerCase()!=="decision"||!s.has(i.status))throw new _(`Assurance authorization ${n} must name a terminal Decision item`,f.USAGE);return[i.id]}async function aC(e,t){let n=Fa(e.limit,"assurance verdict limit");if(n!==void 0&&(n<1||n>Ln))throw new _(`assurance verdict limit must be an integer from 1 through ${Ln}`,f.USAGE);let r=await H_(t,{gate_id:e.id??e.gate,limit:n});return{items:r,count:r.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function cC(e,t,n){if(e==="presets"){if(t.preset??t.id)return rs(Jh(t.preset??t.id),Qc(t));let i=wr.map(s=>{let o=rs(s,"pm-owner");return{id:s,title:o.title,description:o.description}});return{items:i,count:i.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}if(e==="apply")return Dn(()=>V_(n,Jh(t.preset??t.id),Qc(t),{author:t.author,message:t.message}));if(e==="derive"){let i=await Y_(await jr(n,{resolve_tree:!1,trigger:"derive"}),Qc(t)),s=t.apply?await Dn(()=>J_(n,i,{author:t.author,message:t.message??"Accept observation-derived assurance proposals"})):void 0;return{items:i,count:i.length,...s?{applied:s}:{}}}if(!t.id)return Hn("assertion-id","assurance promote requires an assertion id","pm assurance promote <assertion-id> --enforcement warn");if(t.enforcement!=="warn"&&t.enforcement!=="block")throw new _("assurance promote requires --enforcement warn|block",f.USAGE);let r=await Oa(n,"assertion",t.id);return Dn(()=>X_(n,r,t.enforcement,{author:t.author,message:t.message}))}async function dC(e,t,n){if(!e.id)return Hn("gate-id","assurance run requires a gate id","pm assurance run <gate-id> --trigger ci --dry-run");let r=e.id;if(!e.trigger)throw new _("assurance run requires a trigger",f.USAGE);if(!pt.includes(e.trigger))throw new _(`Unknown assurance trigger ${e.trigger}. Expected: ${pt.join(", ")}`,f.USAGE);let i=e.trigger,[s,o]=await Promise.all([sC(t),jr(t,{...n.workspace,tree_id:e.tree,trigger:i})]),a=await R_(()=>G_(r,s,o,{trigger:i,dry_run:e.dry_run===!0}));return a.dry_run||await B_(t,a,{author:e.author,message:e.message}),a}function Qh(e){throw e instanceof _?e:new _(e instanceof Error?e.message:"assurance risk request is invalid",f.USAGE)}function lC(e){if(e.limit!==void 0)throw new _(`assurance ${e.action} does not accept --limit; set limit inside the definition`,f.USAGE);let t=e.definition;if(typeof t=="string")try{t=JSON.parse(t)}catch(n){throw new _(`assurance ${e.action} definition must be valid JSON`,f.USAGE,{reason:n instanceof Error?n.message:"invalid_json"})}try{return e.action==="lineages"?Wh(t):Ki(t)}catch(n){return Qh(n)}}function uC(e,t){let n=new Set;for(let[r,i]of t)e.item_fingerprints.get(r)!==i&&n.add(r);for(let r of e.item_fingerprints.keys())t.has(r)||n.add(r);return n}function mC(e,t,n){let r=D(t.policy),i=Jc?.pm_root===e?Jc:void 0,s=new Map(n.map(d=>[d.id,tC("sha256").update(D([Vf(d),Gi(d)])).digest("hex")])),o=i?.policy_serialized===r?i:void 0,a=o?uC(o,s):new Set,c=Xf(t.policy,o?n.filter(d=>a.has(d.id)):n,o?{previous_index:o.index,changed_item_ids:[...a]}:{});return Jc={pm_root:e,policy_serialized:r,item_fingerprints:s,index:c},c}async function fC(e,t){let n=lC(e),r=await jr(t,{strict_read:!0,include_history:!1,resolve_tree:!1});try{return"change"in n?Qf(mC(t,n,r.items),n.change,{cursor:n.cursor,limit:n.limit}):Vh(n.policy,r.items,n)}catch(i){return Qh(i)}}async function _C(e,t={},n={}){let r=nC(e.action),i=R(process.cwd(),t.path);if(r==="presets"||r==="apply"||r==="derive"||r==="promote")return cC(r,e,i);if(r==="verdicts")return aC(e,i);if(r==="run")return dC(e,i,n);if(["risk","lineages"].includes(r))return fC(e,i);let s=rC(e.kind);if(r==="list")return vr(i,s);if(!e.id)return Hn("id",`assurance ${r} requires an id`,`pm assurance ${r} ${s} <id>`);let o=e.id;if(r==="show")return Oa(i,s,o);if(r==="remove"){let l=await Dn(()=>z_(i,s,o,{author:e.author,message:e.message}));return Xh(l,e.idOnly)}let a=iC(s,e.definition);if(a.id!==o)throw new _(`Assurance definition id ${a.id} does not match requested id ${o}`,f.USAGE);let c={author:e.author,message:e.message,...s==="assertion"?{authorized_decision_ids:await oC(i,a)}:{}},d=await Dn(()=>ts(i,s,a,c));return Xh(d,e.idOnly)}function lB(e,t,n){let r={...e,...t};return _C({action:L(r,"subcommand")??L(r,"assuranceAction")??L(r,"operation")??"",kind:L(r,"kind"),id:L(r,"id"),definition:r.definition,trigger:L(r,"trigger"),tree:L(r,"treeId")??L(r,"tree"),gate:L(r,"gate"),limit:Fa(r.limit,"assurance verdict limit"),dry_run:r.dryRun===!0||r.dry_run===!0,fullChangedFields:r.fullChangedFields===!0,idOnly:r.idOnly===!0,author:L(r,"author"),message:L(r,"message"),preset:L(r,"preset"),owner:L(r,"owner"),apply:r.apply===!0,enforcement:L(r,"enforcement")},n)}import{readFile as pC}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6d20a21c-ac67-5712-9f63-b10ffc0e2c64")}catch{}})();function TB(e){let t={...e,...e.full===!0?{fullHistory:!0}:{}};return delete t.full,qe(e,t)}function Zh(e,t){if(typeof e=="object"&&e!==null&&"format"in e&&e.format==="json")throw new _(`Structured context events are append-only and cannot be ${t}.`,f.USAGE,{code:"structured_event_immutable"})}function gC(e,t){return t===void 0?e:t===0?[]:e.slice(Math.max(0,e.length-t))}function nn(e,t){let n=e[t];return Array.isArray(n)?n:[]}function IB(e,t={}){let n=e.trim();if(!n)return"";let r=/^(?:[-*+]\s*)?text\s*[:=]/i.exec(n);if(t.stripPlainTextPrefix===!0&&r&&!n.startsWith("```"))return n.slice(r[0].length).trim()||n;if(!(/^(?:[-*+]\s*)?text\s*[:=]/im.test(n)||n.startsWith("```")))return n;try{let s=te(n,"--add");return Object.keys(s).map(c=>c.trim().toLowerCase()).some(c=>c!=="text")?n:s.text?.trim()||n}catch{return n}}function hC(e){return typeof e=="object"&&e!==null&&"code"in e}function ey(e,t){if(!Bt(e))throw new _(`${t} cannot read process stdin through the MCP JSON-RPC transport. Pass annotation text in options.add instead.`,f.USAGE,{code:"mcp_stdin_unavailable",required:"Pass annotation text as JSON data; the MCP protocol already owns process stdin."})}async function yC(e,t){if(+(e.add!==void 0)+ +(e.stdin===!0)+ +(typeof e.file=="string")>1)throw new _(`Specify ${t} text using only one input source: --add, --stdin, or --file`,f.USAGE);let r=bn(),i=Bt(e);if(e.add!==void 0)return{value:await r.resolveValue(e.add,"--add",i)??"",rawValue:e.add,emptyFlag:"--add"};if(e.stdin===!0)return ey(e,"--stdin"),{value:await r.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};if(typeof e.file!="string")return;let s=e.file.trim();if(!s)throw new _("--file path cannot be empty",f.USAGE);if(s==="-")return ey(e,"--file -"),{value:await r.resolveValue("-","--file")??"",emptyFlag:"--file"};try{return{value:await pC(s,"utf8"),emptyFlag:"--file"}}catch(o){if(hC(o)&&hn(o))throw new _(`--file path not found: ${s}. Use --file - to read stdin.`,f.USAGE);let a=o instanceof Error?o.message:String(o);throw new _(`Failed to read --file path "${s}": ${a}. Use --file - to read stdin.`,f.USAGE)}}async function AB(e,t){if(e.edit!==void 0&&e.delete!==void 0)throw new _("Specify only one of --edit or --delete",f.USAGE);if(e.delete!==void 0){if(e.add!==void 0||e.stdin===!0||typeof e.file=="string")throw new _("--delete cannot be combined with replacement text",f.USAGE);if(!Number.isInteger(e.delete)||e.delete<1)throw new _("--delete must be a positive integer",f.USAGE);return{mode:"delete",index:e.delete}}if(e.edit!==void 0&&(!Number.isInteger(e.edit)||e.edit<1))throw new _("--edit must be a positive integer",f.USAGE);let n=await yC(e,t);if(e.edit!==void 0){if(!n)throw new _("--edit requires replacement text from --add, --stdin, or --file",f.USAGE);return{mode:"edit",index:e.edit,...n}}return n?{mode:"add",...n}:{mode:"list"}}function Ur(e,t){throw e instanceof _&&e.exitCode===f.CONFLICT&&e.message.includes("is assigned to")&&e.message.includes("Use --force to override")?new _(e.message,e.exitCode,{code:"ownership_conflict",required:t.required,examples:t.examples,nextSteps:t.nextSteps}):e}function ny(e){return e==="comments"?"--stdin":"--add -"}function vC(e,t){if((t.input.emptyFlag??"--add")!=="--add")return;let r=e.trim();if(!/^-{1,2}[A-Za-z][\w-]*(?:=.*)?$/.test(r))return;let i=ny(t.collectionKey),s=t.input.mode==="edit"?`pm ${t.collectionKey} <id> --edit <index>`:`pm ${t.collectionKey} <id>`;throw new _(`--add value "${r}" looks like an option, not annotation text. Use ${i} to read stdin, or use text=${r} for literal dash-leading text.`,f.USAGE,{code:"annotation_flag_like_value",required:`Use ${i} for stdin input, pass plain text, or use text=${r} when the text really starts with "-".`,examples:[`${s} ${i}`,`${s} --add text=${r}`]})}function wC(e,t){if(t.ifAbsent===!0&&!["add","stdin","file"].includes(e.input.mode))throw new _(`--if-absent requires a ${e.collectionKey.replace(/s$/,"")} append`,f.USAGE,{code:"annotation_if_absent_without_append",required:"Combine --if-absent with one append text source; omit it for list, edit, and delete operations."});if(e.input.mode!=="list"||t.message===void 0)return;let n=e.collectionKey.replace(/s$/,"");throw new _(`--message labels a ${n} mutation but does not provide ${n} text. Pass text positionally or with --add, --stdin, or --file.`,f.USAGE,{code:"annotation_message_without_text",required:`Provide ${n} text through a content source; --message only annotates the history entry of a mutation.`,examples:[`pm ${e.collectionKey} <id> --add "text" --message "why"`,`pm ${e.collectionKey} <id> ${ny(e.collectionKey)}`]})}function bC(e,t,n,r,i,s){let o=nn(e.metadata,t),a=i?o.findIndex(c=>c.author===n&&c.text===r):-1;return a>=0?{changedFields:[],entryIndex:a+1}:(o.push(s({created_at:T(),author:n,text:r})),e.metadata[t]=o,{changedFields:[t],entryIndex:o.length})}async function CB(e,t,n,r){wC(r,t);let i=R(process.cwd(),n.path);await $(i);let s=await C(i),o=U(s,F()),a=lr(t.limit);if(r.input.mode==="list"){let p=await X(i,e,s.id_prefix,s.item_format,o.type_to_folder);if(!p)throw new _(`Item ${e} not found`,f.NOT_FOUND);let h=await ge(p,{schema:s.schema}),y=nn(h.document.metadata,r.collectionKey);return $s(p.id,r.collectionKey,y,a,t.includeMeta===!0)}let c=q(t.author,s.author_default);if(r.input.mode==="delete"){let p=r.deleteOp??r.op,h;try{h=await me({pmRoot:i,settings:s,id:e,op:p,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(v){let w=nn(v.metadata,r.collectionKey),E=ty(r.input.index,w.length,r.collectionKey);return Zh(w[E],"deleted"),w.splice(E,1),v.metadata[r.collectionKey]=w,{changedFields:[r.collectionKey]}}})}catch(v){Ur(v,r.conflictGuidance)}let y=nn(h.item,r.collectionKey);return $s(h.item.id,r.collectionKey,y,a,t.includeMeta===!0,{action:"delete",entryIndex:r.input.index},t.fullHistory===!0)}let d=r.input.rawValue??r.input.value??"";vC(d,r);let l=r.parseText(r.input.value??"");if(!l.trim())throw new _(`${r.input.emptyFlag??"--add"} text cannot be empty`,f.USAGE);if(r.input.mode==="edit"){let p=r.editOp??r.op,h;try{h=await me({pmRoot:i,settings:s,id:e,op:p,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(v){let w=nn(v.metadata,r.collectionKey),E=ty(r.input.index,w.length,r.collectionKey),S=w[E];return Zh(S,"edited"),w[E]={...S,text:l,edited_at:T()},v.metadata[r.collectionKey]=w,{changedFields:[r.collectionKey]}}})}catch(v){Ur(v,r.conflictGuidance)}let y=nn(h.item,r.collectionKey);return $s(h.item.id,r.collectionKey,y,a,t.includeMeta===!0,{action:"edit",entryIndex:r.input.index,entry:y[r.input.index-1]},t.fullHistory===!0)}let u,m=0;try{u=await me({pmRoot:i,settings:s,id:e,op:r.op,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,skipNoop:t.ifAbsent===!0,mutate(p){let h=bC(p,r.collectionKey,c,l,t.ifAbsent===!0,r.createEntry);return m=h.entryIndex,{changedFields:h.changedFields}}})}catch(p){Ur(p,r.conflictGuidance)}let g=nn(u.item,r.collectionKey);return $s(u.item.id,r.collectionKey,g,a,t.includeMeta===!0,{action:"add",entryIndex:m,entry:g[m-1],changedCount:t.ifAbsent===!0?Math.min(u.changedFields.length,1):void 0},t.fullHistory===!0)}function ty(e,t,n){if(e===void 0||!Number.isInteger(e)||e<1||e>t){let r=n.replace(/s$/,""),i=`${r.charAt(0).toUpperCase()}${r.slice(1)}`,s=t===1?`1 ${r}`:`${t} ${n}`;throw new _(`${i} index ${e??"(missing)"} out of range (item has ${s})`,f.USAGE)}return e-1}function kC(e,t,n){return t===void 0?{}:{mutation_receipt:{action:t.action,entry_index:t.entryIndex,changed_count:t.changedCount??1,full_history_included:!n},omission_receipt:{has_omissions:n,omitted_field_group_count:n?1:0,omitted_field_groups:n?[{name:`${e}_history`,restore_with:{selector:"full_history",cli_flag:"--full-history",sdk_option:"fullHistory",mcp_option:"full"}}]:[]}}}function $s(e,t,n,r,i,s,o=!1){let a=s===void 0||o?gC(n,s!==void 0&&o?void 0:r):s.entry===void 0?[]:[s.entry],c=s!==void 0&&a.length<n.length;return{id:e,[t]:a,count:a.length,...s?.changedCount===void 0?{}:{changed:s.changedCount===1},...[i,s!==void 0].includes(!0)?{total_count:n.length,returned_count:a.length,has_more:c||a.length<n.length,...r!==void 0?{limit:r}:{}}:{},...kC(t,s,c)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d0579277-f123-5f96-8664-dfe05ade1b24")}catch{}})();async function ry(e,t,n){return[...await Rt(Tt(e,t),t).catch(()=>[])].reverse().find(s=>s.patch.some(o=>o.path==="/metadata/assignee"))?.op==="claim"?`claimed by ${n}`:`assigned to ${n}`}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a4d95016-05b9-5272-8044-2649da644e98")}catch{}})();var iy="no_available_next_item";function EC(e){if(!(e instanceof Error)||e.name!=="PmCliError")return!1;let t=e.context;return typeof t=="object"&&t!==null&&"code"in t&&t.code==="already_claimed_by"}async function SC(e,t,n,r={}){let i=R(process.cwd(),n.path);await $(i);let s=await C(i),o=H(s.schema),a=q(r.author,s.author_default),c=Qo(a),d=null,l=!1,u=[],m=await me({pmRoot:i,settings:s,id:e,op:"claim",author:a,message:r.message,force:t,skipNoop:!0,async mutate(g){let h=g.metadata.assignee??"",y=g.metadata.claim_principal?.trim()||h;if(d=h.trim().length>0?h:null,ki(g.metadata.status,o)&&!t)throw new _(`Cannot claim terminal item ${g.metadata.id} without --force`,f.CONFLICT);if(d!==null&&y!==c){if(r.ifAvailable===!0)return l=!0,u.push(`claim_skipped_held_by:${d}`),{changedFields:[]};if(!t){let w=await ry(i,g.metadata.id,h);throw new _(`Item ${g.metadata.id} is already ${w}. Use --force to take over, or --if-available to skip without failing.`,f.CONFLICT,{code:"already_claimed_by",why:"Claim is an atomic test-and-set so parallel agents never proceed believing they own the same item.",nextSteps:["Run pm next to pick a different unclaimed item.","Re-run with --if-available to treat a held item as a no-op skip.","Re-run with --force only when taking over the item is coordinated."]})}u.push(`claim_takeover:${d}->${a}`)}return g.metadata.assignee=a,g.metadata.claim_principal=c,{changedFields:["assignee","claim_principal"],warnings:u}}});return l||await T_({pmRoot:i,settings:s,principal:c,itemId:m.item.id}),{item:m.item,claimed_by:l&&d!==null?d:a,previous_assignee:d,forced:t,...l?{skipped:!0}:{},...u.length>0?{warnings:u}:{}}}async function UB(e,t,n={},r={}){let i=xC(n.maxAttempts),s=await C(R(process.cwd(),t.path)),o={...n,author:q(n.author,s.author_default)},a=await A_({...r,callerAuthor:o.author,limit:String(i)},t),c=[a.recommended,...a.ready].filter(d=>d!==null).map(d=>({...d,reasons:"reasons"in d?d.reasons:["ranked ready candidate"]}));return TC(c.slice(0,i),e,t,o)}function xC(e){if(e===void 0)return 10;let t=Number(e);if(!Number.isSafeInteger(t)||t<1||t>100)throw new _("--max-attempts must be an integer from 1 to 100",f.USAGE);return t}async function TC(e,t,n,r={},i=SC){let s=0;for(let a of e){s+=1;try{let c=await i(a.id,t,n,r),d={...c,recommendation:a,attempts:s,available:!0};if(!c.skipped)return d}catch(c){if(!EC(c))throw c}}if(r.ifAvailable===!0)return{available:!1,item:null,claimed_by:q(r.author,""),previous_assignee:null,forced:t,skipped:!0,recommendation:null,attempts:s,warnings:[iy]};let o=s===0;throw new _(o?"No actionable items matched the selection filters":"No actionable item remained available to claim",o?f.NOT_FOUND:f.CONFLICT,{code:iy,why:o?"No ready items matched the specified filters or selection criteria.":"Every ranked candidate was claimed by another agent before this atomic selection completed.",nextSteps:[o?"Verify the filters or run pm next to inspect all ready work.":"Run pm claim --next again to refresh the ranked candidate set."]})}async function qB(e,t,n,r={}){let i=R(process.cwd(),n.path);await $(i);let s=await C(i),o=q(r.author,s.author_default),a=Qo(o),c=r.ownershipReleaseBypass===!0,d=null,l;try{l=await me({pmRoot:i,settings:s,id:e,op:"release",author:o,message:r.message,force:t,bypassAssigneeConflict:c,mutate(g){return d=g.metadata.assignee??null,!d&&!g.metadata.claim_principal?{changedFields:[]}:(delete g.metadata.assignee,delete g.metadata.claim_principal,{changedFields:["assignee","claim_principal"]})}})}catch(g){Ur(g,{required:"For approved non-owner handoffs, prefer the ownership-release bypass before considering --force.",examples:['pm release pm-a1b2 --author "reviewer" --force'],nextSteps:["Use the package-provided ownership-release bypass for handoffs that only clear assignee metadata.","Use --force only when an explicit override is approved for broader ownership conflicts."]})}await I_({pmRoot:i,principal:a,itemId:l.item.id});let u=H(s.schema),m=Xo(l.item.status,u)===Xo(u.in_progress_status,u);return{item:l.item,released_by:o,previous_assignee:d,forced:t,...m?{warnings:["released_unclaimed_in_progress"],suggestions:[`${l.item.id} remains ${l.item.status} and unclaimed. If work is paused, run pm pause-task ${l.item.id} to move it to ${u.open_status}.`]}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="89e3f65e-8455-5921-bcc1-45cf572d8585")}catch{}})();var BB=Object.freeze({requireCloseReason:!0,orderingEdges:"preserve"});function IC(e){let t=[{source:"explicit",value:e.explicit},{source:"duplicate",value:e.duplicateOf===void 0?void 0:`Duplicate of ${e.duplicateOf}`},{source:"resolution",value:e.resolution},{source:"message",value:e.message}];for(let n of t){let r=n.value?.trim();if(r)return{closeReason:r,source:n.source}}return{source:"none"}}function oy(e,t){return Zc(e,t,{operation:"close"})}function Zc(e,t,n){let r=IC(e);if(!t||r.closeReason!==void 0)return r;let i=n.operation==="create"?[`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --close-reason "<closing summary>"`,`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --resolution "<resolution summary>"`,"pm create --stdin-json < item.json"]:['pm close <id> "Done: <what changed and why>"','pm close <id> --reason "<closing summary>"','pm close <id> -m "<closing summary>"',"pm close <id> --duplicate-of <canonical-id>"];throw new _("Close reason text is required because governance.require_close_reason is enabled",f.USAGE,{code:"close_reason_required",required:"Provide an author-controlled closing summary as the reason, message, resolution, or duplicate target.",why:"governance.require_close_reason is enabled, so tools must not invent immutable closure evidence.",examples:i,nextSteps:[`Re-run the ${n.operation} operation with a closing summary.`,"To stop requiring reasons, run: pm config set governance-require-close-reason --policy disabled"]})}function ay(e,t){let n=typeof e.blocked_by=="string"?e.blocked_by.trim():"",r=e.blocked_by!==void 0,i=e.dependencies??[],s=i.filter(d=>d.kind==="blocked_by"),o=e.blocked_reason!==void 0,a=[];if(r&&(delete e.blocked_by,a.push("blocked_by")),o&&(delete e.blocked_reason,a.push("blocked_reason")),t.orderingEdges==="remove"&&s.length>0){let d=i.filter(l=>l.kind!=="blocked_by");d.length>0?e.dependencies=d:delete e.dependencies,a.push("dependencies")}let c=[...new Set([...n?[n]:[],...s.map(d=>d.id)])];return c.length===0?{changedFields:a,warnings:[]}:{changedFields:a,warnings:[t.orderingEdges==="preserve"?`closed_preserved_predecessors:${e.id}:${c.join(",")}`:`closed_removed_predecessors:${e.id}:${c.join(",")}`]}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0e166cbb-ef9c-5016-89a6-07f287e00a2e")}catch{}})();var AC=[{key:"resolution",label:"resolution (--resolution)"},{key:"expected_result",label:"expected_result (--expected-result)"},{key:"actual_result",label:"actual_result (--actual-result)"}];function CC(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0||t==="warn")return"warn";if(t==="off"||t==="none"||t==="disabled")return"off";if(t==="strict")return"strict";throw new _(`Invalid --validate-close mode "${e}" (expected "off", "warn", or "strict")`,f.USAGE)}function cy(e){let t=[];for(let n of AC){let r=e[n.key];(typeof r!="string"||r.trim().length===0)&&t.push(n)}return t}function dy(e,t,n={}){let r=cy(e);if(r.length===0)return;let i={resolution:n.resolution,expected_result:n.expectedResult,actual_result:n.actualResult},s=r.map(a=>`--${a.key.replaceAll("_","-")}`),o=["--pm-path",t,"update",e.id,...r.flatMap((a,c)=>[s[c],i[a.key]?.trim()||"<value>"])];return{missing:s,suggested_retry:ft(o),suggested_retry_args:o}}async function RC(e,t,n){let r=new Set,i=t;for(;typeof i=="string"&&i.trim().length>0;){let s=i.trim();if(s===n)return!0;if(r.has(s))return!1;r.add(s),i=(await e(s))?.duplicate_of}return!1}function OC(e){return typeof e!="string"||e.trim().length===0}async function DC(e,t,n,r){let i=n?.trim();if(!i)return;if(i===r)throw new _("An item cannot be closed as a duplicate of itself.",f.USAGE,{code:"duplicate_target_self",why:"--duplicate-of must identify the canonical item that should remain open or already represent the work."});let s=U(t,F()),o=new Map,a=async d=>{if(o.has(d))return o.get(d)??null;let l=await X(e,d,t.id_prefix,t.item_format,s.type_to_folder);if(!l)return o.set(d,null),null;let{document:u}=await ge(l,{schema:t.schema});return o.set(d,u.metadata),u.metadata},c=await a(i);if(!c)throw new _(`Duplicate target "${i}" was not found. Create or locate the canonical item first.`,f.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 ${r} "Duplicate of ${i}" --duplicate-of ${i}`],nextSteps:["Run pm search/list to find the canonical item, then retry with --duplicate-of <id>."]});if(await RC(a,c.duplicate_of,r))throw new _(`Circular duplicate reference detected. Target "${i}" points back to "${r}".`,f.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 c.duplicate_of=="string"&&c.duplicate_of.trim().length>0)throw new _(`Duplicate target "${i}" is already marked as a duplicate of "${c.duplicate_of.trim()}".`,f.USAGE,{code:"duplicate_target_is_duplicate",why:"Duplicate closure should point directly at the canonical item, not another duplicate.",examples:[`pm close ${r} "Duplicate of ${c.duplicate_of.trim()}" --duplicate-of ${c.duplicate_of.trim()}`],nextSteps:["Use the canonical item referenced by duplicate_of as the --duplicate-of target."]});return c.id}function LC(e,t,n){return e.filter(r=>r.parent===t&&!ue(r.status,n)).map(r=>r.id).sort((r,i)=>r.localeCompare(i))}function NC(e,t,n){let r=new Map(e.map(a=>[a.id.trim().toLowerCase(),a])),i=y_(e),s=t.trim().toLowerCase(),o=n.blocked_statuses;return e.filter(a=>o.has(a.status)).map(a=>({item:a,blockerIds:i.get(a.id.trim().toLowerCase())})).filter(({blockerIds:a})=>a.includes(s)).filter(({blockerIds:a})=>a.every(c=>{if(c===s)return!0;let d=r.get(c);return d!==void 0&&ue(d.status,n)})).map(({item:a,blockerIds:c})=>({id:a.id,blocker_ids:c})).sort((a,c)=>a.id.localeCompare(c.id))}async function MC(e,t,n,r,i,s){let o=NC(n,r,s),a=[];for(let c of o)try{let d=await me({pmRoot:e,settings:t,id:c.id,op:"update",author:i,message:`Auto-unblocked after blocker ${r} closed`,mutate(l){let u=l.metadata.dependencies??[],m=u.filter(p=>{let h=p.id.trim().toLowerCase();return p.kind!=="blocked_by"||!c.blocker_ids.includes(h)});l.metadata.status=s.open_status,delete l.metadata.blocked_by,delete l.metadata.blocked_reason,l.metadata.unblock_note=`Auto-unblocked after blocker ${r} closed; all blockers resolved (${c.blocker_ids.join(", ")}).`,m.length>0?l.metadata.dependencies=m:delete l.metadata.dependencies;let g=["status","blocked_by","blocked_reason","unblock_note"];return m.length!==u.length&&g.push("dependencies"),{changedFields:g}}});a.push(`auto_unblocked:${d.item.id}:resolved_blockers=${c.blocker_ids.join(",")}`)}catch(d){let l=d instanceof Error?d.message.replace(/\s+/g," ").trim():"unknown";a.push(`auto_unblock_failed:${c.id}:${l}`)}return a}function PC(e,t){let n=[],r=[{option:t.resolution,key:"resolution"},{option:t.expectedResult,key:"expected_result"},{option:t.actualResult,key:"actual_result"}];for(let{option:i,key:s}of r){if(typeof i!="string")continue;let o=i.trim();o.length!==0&&(e[s]=o,n.push(s))}return n}function FC(e,t){if(t===void 0)return[];e.duplicate_of=t;let n=[],r=[{key:"resolution",value:`Duplicate of ${t}`},{key:"expected_result",value:`Canonical item ${t} tracks the work.`},{key:"actual_result",value:`Closed as duplicate of ${t}.`}];for(let{key:i,value:s}of r)OC(e[i])&&(e[i]=s,n.push(i));return n}function $C(e,t,n,r){let i=[];if(t!=="off"){let s=cy(e);if(s.length>0){let o=s.map(a=>a.label);if(t==="strict"){let a=s.map(d=>`--${d.key.replaceAll("_","-")}`),c=["--pm-path",r,"update",e.id,...a.flatMap(d=>[d,"<value>"])];throw new _(`Cannot close item ${e.id}: missing ${o.join(", ")}. Populate fields or use --validate-close warn.`,f.USAGE,{code:"close_validation_missing_fields",recovery:{missing:a,suggested_retry:ft(c)},nextSteps:["Run the suggested pm update, then retry the original pm close invocation.","Use --validate-close warn only when governance permits an evidenced exception."]})}i.push(`close_validation_missing_fields:${e.id}:${o.join(",")}`)}if(n.length>0){if(t==="strict")throw new _(`Cannot close item ${e.id}: active child items remain open (${n.join(", ")}). Close, cancel, or re-parent them first, or use --validate-close warn.`,f.USAGE);i.push(`close_validation_active_children:${e.id}:${n.join(",")}`)}return i}return n.length>0&&i.push(`closed_with_active_children:${e.id}:${n.join(",")}`),i}function jC(e,t){return t!==void 0?(e.close_reason=t,["close_reason"]):[]}function UC(e){return e.assignee===void 0?[]:(delete e.assignee,["assignee"])}function qC(e,t){if(ue(e.status,t.statusRegistry)&&!t.force)throw new _(`Item ${e.id} is already terminal; use pm update to append acceptance evidence, or --force only for an intentional repeat closure.`,f.CONFLICT,{recovery:dy(e,t.pmRoot,t.options)});let n=PC(e,t.options),r=FC(e,t.duplicateOf),i=$C(e,t.validateCloseMode,t.activeChildIds,t.pmRoot);e.status=t.statusRegistry.close_status,e.closed_at=t.closedAt;let s=t.options.completedAt!==void 0||e.completed_at===void 0;s&&(e.completed_at=t.completedAt);let o=["status","closed_at",...s?["completed_at"]:[],...jC(e,t.closeReason),...n];if(dm(e)&&(e.plan_mode="completed",o.push("plan_mode")),t.duplicateOf!==void 0){o.push("duplicate_of");for(let c of r)o.includes(c)||o.push(c)}o.push(...UC(e));let a=ay(e,t.lifecyclePolicy);return o.push(...a.changedFields),i.push(...a.warnings),{changedFields:o,...i.length>0?{warnings:i}:{}}}async function GC(e,t,n,r){let i=R(process.cwd(),r.path);await $(i);let s=await C(i),o=H(s.schema),a=q(n.author,s.author_default),c=U(s,F()).type_to_folder,d=await X(i,e,s.id_prefix,s.item_format,c);if(!d)throw await ur(i,e,s.id_prefix,c);let l=await DC(i,s,n.duplicateOf,d.id),u={requireCloseReason:n.lifecyclePolicy?.requireCloseReason??s.governance.require_close_reason,orderingEdges:n.lifecyclePolicy?.orderingEdges??"preserve"},m=oy({explicit:t,duplicateOf:l,resolution:n.resolution,message:n.message},u.requireCloseReason).closeReason,g=CC(n.validateClose)??s.governance.close_validation_default,p=await Se(i,s.item_format,c,void 0,s.schema),h=LC(p,d.id,o),y=T(),v=n.completedAt===void 0?y:fe(n.completedAt,new Date(y),"completed-at"),w=await me({pmRoot:i,settings:s,id:d.id,op:"close",author:a,message:n.message,force:n.force,mutate(S){return qC(S.metadata,{pmRoot:i,statusRegistry:o,force:n.force,options:n,duplicateOf:l,validateCloseMode:g,activeChildIds:h,closeReason:m,closedAt:y,completedAt:v,lifecyclePolicy:u})}}),E=g==="warn"?dy(w.item,i):void 0;return{item:w.item,changed_fields:w.changedFields,...E?{recovery:E}:{},warnings:[...w.warnings,...await MC(i,s,p,d.id,a,o)]}}function ly(e,t,n,r){return GC(e,t,n,r)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5bbc21f0-f517-571a-8ecf-45f20f0e793d")}catch{}})();var ed=[{exit_code:f.SUCCESS,outcome:"effect",success:!0,meaning:"The requested operation completed with its intended effect."},{exit_code:f.GENERIC_FAILURE,outcome:"internal_failure",success:!1,meaning:"An unexpected runtime or internal failure prevented completion."},{exit_code:f.USAGE,outcome:"refused_input",success:!1,meaning:"The invocation was refused because its input or composition was invalid."},{exit_code:f.NOT_FOUND,outcome:"refused_tracker_state",success:!1,meaning:"The requested tracker, item, or resource was not present."},{exit_code:f.CONFLICT,outcome:"conflict",success:!1,meaning:"Current state or concurrency prevented the requested effect."},{exit_code:f.DEPENDENCY_FAILED,outcome:"dependency_failed",success:!1,meaning:"A required dependency operation failed."},{exit_code:f.NO_EFFECT,outcome:"no_effect",success:!0,meaning:"The request was valid and completed, but matched nothing to change."},{exit_code:f.PARTIAL_EFFECT,outcome:"partial_effect",success:!0,meaning:"The request completed and changed some, but not all, selected targets."}],uy=[f.SUCCESS,f.GENERIC_FAILURE,f.USAGE,f.NOT_FOUND,f.CONFLICT,f.DEPENDENCY_FAILED],KC=new Set(["close-many","update-many"]),fy=tt.map(e=>({command:e,exit_codes:KC.has(e)?[...uy,f.NO_EFFECT,f.PARTIAL_EFFECT]:[...uy]})),my=new Map(fy.map(e=>[e.command,e])),zC=[f.SUCCESS,f.NO_EFFECT,f.PARTIAL_EFFECT];function rH(e){return zC.includes(e)}function iH(e){return ed.some(t=>t.exit_code===e)}function _y(e){let t=e.trim().toLowerCase().split(/\s+/u).filter(Boolean).join(" ");return my.get(t)??my.get(t.split(" ")[0])}function sH(e,t=tt,n=fy){let r=new Map(n.map(d=>[d.command,d])),i=t.filter(d=>!r.has(d)),s=e.filter(d=>{let l=r.get(d.command)??r.get(d.command.split(" ")[0]);return l===void 0||!l.exit_codes.includes(d.exit_code)}),o=new Set(e.map(d=>d.exit_code)),c=[...new Set(n.flatMap(d=>d.exit_codes))].filter(d=>!o.has(d)).sort((d,l)=>d-l);return{ok:i.length===0&&s.length===0&&c.length===0,missing_commands:i,undeclared_observations:s,unreachable_exit_codes:c}}function oH(e){return e.applied===0&&e.failed>0?{outcome:"dependency_failed",exit_code:f.DEPENDENCY_FAILED}:e.applied===0?{outcome:"no_effect",exit_code:f.NO_EFFECT}:e.skipped>0||e.failed>0||e.unmatched>0?{outcome:"partial_effect",exit_code:f.PARTIAL_EFFECT}:{outcome:"effect",exit_code:f.SUCCESS}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="94e8b95b-35fa-5fc7-843a-481497e09b54")}catch{}})();function py(e){return[...e].sort().join("\0")}function BC(e,t,n){let r=e.successors.get(t);r?r.push(n):e.successors.set(t,[n]);let i=e.predecessors.get(n);i?i.push(t):e.predecessors.set(n,[t])}function gy(e,t,n,r,i){let s=t.resolve(i);if(s?.ordering!==!0)return;let o=o_(r),a=o===void 0?void 0:e.canonicalIds.get(o.toLowerCase());if(a===void 0)return;let c=(s.precedence??"source_before_target")==="source_before_target";BC(e,c?n:a,c?a:n)}function HC(e,t){let n={successors:new Map,predecessors:new Map,canonicalIds:new Map},r=e.filter(i=>typeof i?.id=="string"&&i.id.trim().length>0);for(let i of r){let s=i.id.trim();n.canonicalIds.set(s.toLowerCase(),s)}for(let i of r){let s=i.id.trim();gy(n,t,s,i.blocked_by,"blocked_by");for(let o of i.dependencies??[])typeof o!="object"||o===null||gy(n,t,s,o.id,typeof o.kind=="string"?o.kind:"related")}for(let i of[n.successors,n.predecessors])for(let s of i.values())s.sort();return n}function WC(e,t){let n=new Set([t]),r=[t];for(;r.length>0;){let i=r.pop();for(let s of[e.successors,e.predecessors])for(let o of s.get(i)??[])n.has(o)||(n.add(o),r.push(o))}return n}function VC(e,t){let n=new Map;for(let r of t){let i=(e.successors.get(r)??[]).filter(s=>t.has(s));i.length>0&&n.set(r,i)}return n}function hy(e,t,n){let r=HC(e,t),i=r.canonicalIds.get(n.trim().toLowerCase());if(i===void 0)return{cycles:[],successors:new Map,canonical:n};let s=VC(r,WC(r,i));return{cycles:d_(s).filter(o=>o.includes(i)),successors:s,canonical:i}}function YC(e,t,n){let r=new Set(t),i=r.has(n)?n:t[0];if(e.get(i)?.includes(i))return[i,i];for(let s of e.get(i)??[]){if(!r.has(s))continue;let o=JC(e,r,i,s);if(o)return o}return[...t,t[0]]}function JC(e,t,n,r){let i=[[r]],s=new Set([n,r]);for(;i.length>0;){let o=i.shift(),a=o.at(-1);for(let c of e.get(a)??[]){if(c===n)return[n,...o,n];!t.has(c)||s.has(c)||(s.add(c),i.push([...o,c]))}}}function js(e,t,n){let r=xe(),i=hy(e,r,n),s=hy(t,r,n),o=new Set(i.cycles.map(py)),a=new Set(va(e,void 0,r).map(d=>`${d.holder_id.toLowerCase()}\0${d.target_id.toLowerCase()}\0${d.dependency_kind}`));return[...va(t,void 0,r).filter(d=>d.holder_id.toLowerCase()===n.trim().toLowerCase()&&!a.has(`${d.holder_id.toLowerCase()}\0${d.target_id.toLowerCase()}\0${d.dependency_kind}`)).map(d=>`ordering_storage_contradiction_created:${l_(d)}:remove_contradicting_dependency_row:run_pm_graph_audit`),...s.cycles.filter(d=>!o.has(py(d))).map(d=>`ordering_cycle_created:${YC(s.successors,d,s.canonical).join(" -> ")}:items_will_not_be_ready:run_pm_graph_audit`)]}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d425cf45-5b62-5613-a5ce-78da6b0e201b")}catch{}})();var Us=1e6;function td(e,t=Us,n=.8,r=!1){let i=new Set,s=(l,u)=>{if(i.add(`${l}:${u}`),i.size>t)throw new _(`Duplicate sweep exceeded ${t} candidate pairs; narrow it with statuses or since.`,f.CONFLICT,{code:"duplicate_sweep_cost_limit",required:"Narrow the duplicate query or increase its similarity threshold. No partial result was returned."})};if(r||n===0){for(let l=0;l<e.length;l+=1)for(let u=0;u<l;u+=1)s(u,l);return i}let o=new Map;for(let{prepared:l}of e)for(let u of l.tokens)o.set(u,(o.get(u)??0)+1);let a=new Map,c=new Map,d=new Map;for(let[l,{prepared:u}]of e.entries()){let m=[...u.tokens].sort((h,y)=>o.get(h)-o.get(y)||h.localeCompare(y)),g=m.length-Math.ceil(n*m.length-1e-12)+1,p=[{index:a,keys:[u.normalized],lengthFilter:!1},{index:c,keys:n<=.99?u.issueCodes:[],lengthFilter:!1},{index:d,keys:m.length===0?[""]:m.slice(0,g),lengthFilter:!0}];for(let h of p)XC(e,l,h,n,s)}return i}function XC(e,t,n,r,i){let s=e[t].prepared.tokens.length;for(let o of n.keys){let a=n.index.get(o)??[];for(let c of a){let d=e[c].prepared.tokens.length;n.lengthFilter&&Math.min(d,s)/Math.max(d,s)+1e-12<r||i(c,t)}a.push(t),n.index.set(o,a)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9baf5711-9796-57e8-99e5-8990fd481ef8")}catch{}})();var QC=3,yy=20,ZC=.8,eR=100,vy=1e3;function wy(e){return e===void 0?[]:[`likely_duplicates:${e.result.items.map(t=>t.id).join(",")}`,`likely_duplicate_recovery:${e.recovery.action}:${e.recovery.item_id}`]}async function tR(e,t){let n=e.items[0],r=R(t.cwd??process.cwd(),t.pmRoot),i=H((await C(r)).schema);return ue(n.status,i)?{action:"reopen",item_id:n.id,command:`pm item reopen ${n.id} "<recurrence reason>"`,args:["item","reopen",n.id,"<recurrence reason>"]}:{action:"reuse",item_id:n.id,command:`pm get ${n.id} --full`,args:["get",n.id,"--full"]}}function nd(e){let t=e.limit??QC,n=e.threshold??ZC;if(!Number.isSafeInteger(t)||t<0||t>yy)throw new _(`Similarity limit must be an integer from 0 to ${yy}.`,f.USAGE);if(!Number.isFinite(n)||n<0||n>1)throw new _("Similarity threshold must be a number from 0 to 1.",f.USAGE);return{limit:t,threshold:n}}function by(e){let t=e.limit??eR;if(!Number.isSafeInteger(t)||t<0||t>vy)throw new _(`Duplicate cluster limit must be an integer from 0 to ${vy}.`,f.USAGE);let n=e.since===void 0?void 0:new Date(e.since);if(n&&Number.isNaN(n.getTime()))throw new _("Duplicate cluster --since must be a valid ISO timestamp.",f.USAGE);return{limit:t,since:n}}async function nR(e,t){let n=R(e.cwd??process.cwd(),e.pmRoot),r=await C(n),i=U(r),s=e.statuses?.map(u=>u.trim().toLowerCase()).filter(Boolean);if(e.statuses!==void 0&&s?.length===0)throw new _("Duplicate cluster statuses must include at least one lifecycle status or all.",f.USAGE);let o=H(r.schema),a=s?.map(u=>{if(u==="all")return u;let m=se(u,o);if(!m)throw new _(`Unknown duplicate-cluster status "${u}". Allowed: all, ${o.definitions.map(g=>g.id).join(", ")}.`,f.USAGE);return m}),c=a?.includes("all")===!0;if(c&&a?.some(u=>u!=="all"))throw new _('The "all" status cannot be combined with other statuses.',f.USAGE);let d=c?void 0:a,l=d?new Set(d):void 0;return{items:(await Se(n,r.item_format,i.type_to_folder,void 0,r.schema)).filter(u=>(!l||l.has(u.status))&&(!t||new Date(u.created_at).getTime()>=t.getTime())),statuses:d}}var AH={buildDuplicateClusters:Ey,collectDuplicateCandidatePairs:td,createDuplicateUnionFind:ky};function ky(e){let t=Array.from({length:e},(r,i)=>i);return{parent:t,findRoot:r=>{let i=r;for(;t[i]!==i;)i=t[i];for(;t[r]!==r;){let s=t[r];t[r]=i,r=s}return i}}}function rR(e,t,n,r){let i=[];for(let s of t){let[o,a]=s.split(":").map(u=>Number.parseInt(u,10)),c=ca(e[o].prepared,e[a].prepared);if(c.score<n)continue;let d=r.findRoot(o),l=r.findRoot(a);d!==l&&(r.parent[l]=d),i.push({left_id:e[o].item.id,right_id:e[a].item.id,...c})}return i}function Ey(e,t,n,r){let i=new Map;for(let a of e.keys()){let c=n.findRoot(a),d=i.get(c)??[];d.push(a),i.set(c,d)}let s=new Map(e.map(({item:a},c)=>[a.id,n.findRoot(c)])),o=new Map;for(let a of t){let c=s.get(a.left_id),d=o.get(c)??[];d.push(a),o.set(c,d)}return[...i.values()].filter(a=>a.length>1).map(a=>{let c=(o.get(n.findRoot(a[0]))??[]).sort((d,l)=>l.score-d.score||d.left_id.localeCompare(l.left_id)||d.right_id.localeCompare(l.right_id));return{id:e[a[0]].item.id,items:a.map(d=>{let l=e[d].item;return{id:l.id,title:l.title,status:l.status,type:l.type}}),matches:c,max_score:c[0]?.score??0}}).sort((a,c)=>c.max_score-a.max_score||a.id.localeCompare(c.id)).slice(0,r)}function iR(e,t,n,r,i){return t.filter(s=>!n.has(s.id)).map(s=>({id:s.id,title:s.title,status:s.status,type:s.type,...aa(e,s.title)})).filter(s=>s.score>=r).sort((s,o)=>o.score-s.score||s.id.localeCompare(o.id)).slice(0,i)}async function sR(e,t={}){let n=e.title.trim();if(n.length===0)throw new _("Similarity candidate title must not be empty.",f.USAGE);let{limit:r,threshold:i}=nd(t),s=R(t.cwd??process.cwd(),t.pmRoot),o=await C(s),a=U(o),c=await ji(s,Object.values(a.type_to_folder)),d=sa(n),l=c&&d.length>0?await Xu({pmRoot:s,expectedSourceCursor:c.source_cursor,query:d.map(g=>`"${g.replaceAll('"','""')}"`).join(" OR "),limit:Math.max(r*10,50)}):null,u=l===null?await Se(s,o.item_format,a.type_to_folder,void 0,o.schema):l.items,m=iR(n,u,new Set(e.excludeIds??[]),i,r);return{items:m,count:m.length,threshold:i,source:l?"persistent_index":"metadata_fallback"}}function oR(e,t={}){let{threshold:n}=nd({...t,limit:void 0}),{limit:r}=by(t),i=new Set;for(let l of e){if(!l.id.trim()||i.has(l.id))throw new _("Duplicate analysis requires unique non-empty item ids.",f.USAGE);i.add(l.id)}let s=[...e].sort((l,u)=>l.id.localeCompare(u.id)).map(l=>({item:l,prepared:oa(l.title)})),o=td(s,Us,n,t.exhaustive===!0),a=ky(s.length),c=rR(s,o,n,a),d=Ey(s,c,a,r);return{clusters:d,count:d.length,threshold:n,cost:{item_count:s.length,algorithm:t.exhaustive===!0||n===0?"exhaustive":"prefix_exact",possible_pairs:s.length*(s.length-1)/2,pair_limit:Us,recall_guarantee:"exact",candidate_pairs:o.size,scored_pairs:o.size}}}async function Sy(e={}){nd({...e,limit:void 0});let{since:t}=by(e),{items:n,statuses:r}=await nR(e,t);return{...oR(n,e),source:"metadata_scan",filters:{statuses:r??null,since:e.since??null}}}async function rd(e,t){if(t.mode==="off")return;let n=await sR(e,t);if(n.count===0)return;let r=await tR(n,t),i=t.mode==="strict"&&t.allowDuplicate===!0;if(t.mode==="strict"&&!i){let s=n.items.map(a=>`${a.id} (${a.status}): ${a.title}`).join("; "),o=r.action==="reopen"?"Reopen the canonical item":"Reuse the canonical item";throw new _(`Likely duplicate item(s) found: ${s}. ${o} or pass --allow-duplicate with explicit intent.`,f.CONFLICT,{code:"likely_duplicate",required:`${o}, or explicitly acknowledge the duplicate with --allow-duplicate.`,recovery:{suggested_flags:["--allow-duplicate"],suggested_retry:r.command,suggested_retry_args:r.args}})}return{mode:t.mode,bypassed:i,result:n,recovery:r}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b29e4416-82ab-585c-9456-718e4699566d")}catch{}})();var Et=["command","cmd","path","scope","timeout","timeout_seconds","pm_context_mode","workspace_context_mode","env_set","env_clear","shared_host_safe","assert_stdout_contains","assert_stdout_regex","assert_stderr_contains","assert_stderr_regex","assert_stdout_min_lines","assert_json_field_equals","assert_json_field_gte","note"],aR=new Set(Et);function xy(e){return gi(e,Et)}function qs(e,t){let n={},r=[];for(let[i,s]of Object.entries(e)){let o=i.toLowerCase();if(!aR.has(o)){r.push(i);continue}if(Object.hasOwn(n,o))throw new _(`${t} provides key "${i}" more than once after case normalization`,f.USAGE);n[o]=s}if(r.length>0)throw new _(`${t} does not recognize key${r.length>1?"s":""} ${r.map(i=>`"${i}"`).join(", ")}. Allowed keys: ${Et.join(", ")}.`,f.USAGE);if(n.cmd!==void 0){if(n.command!==void 0&&n.command.trim()!==n.cmd.trim())throw new _(`${t} command and cmd must match when both are provided`,f.USAGE);let{cmd:i,...s}=n;return{...s,command:s.command??i}}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="64adcc3c-3646-5990-9442-4c4374a2dc7d")}catch{}})();var on=new Set(["PM_PATH","PM_GLOBAL_PATH","PM_SOURCE_PM_PATH","PM_SOURCE_WORKSPACE_ROOT",_r,__,"FORCE_COLOR"]),zs=/^[A-Za-z_][A-Za-z0-9_]*$/,sn=["schema","tracker","auto"],Ty=["source","isolated","snapshot"];function qr(e,t){if(!e)return;let n=e.split(/[;\n]/).map(i=>i.trim()).filter(i=>i.length>0);if(n.length===0)throw new _(`${t} env_set must include at least one KEY=VALUE assignment`,f.USAGE);let r=Object.create(null);for(let i of n){let s=i.indexOf("=");if(s<=0)throw new _(`${t} env_set entries must use KEY=VALUE and be separated by semicolons. Example: env_set=PORT=0;PLAYWRIGHT_BASE_URL=http://127.0.0.1:4173`,f.USAGE);let o=i.slice(0,s).trim(),a=i.slice(s+1);if(!zs.test(o))throw new _(`${t} env_set key "${o}" is invalid`,f.USAGE);if(on.has(o.toUpperCase()))throw new _(`${t} env_set key "${o}" is reserved for sandbox safety`,f.USAGE);r[o]=a}return Object.keys(r).length>0?r:void 0}function Gr(e,t){if(!e)return;let n=da(e,{separators:/[;,\n]/});if(n.length===0)throw new _(`${t} env_clear must include at least one environment variable name`,f.USAGE);for(let r of n){if(!zs.test(r))throw new _(`${t} env_clear key "${r}" is invalid`,f.USAGE);if(on.has(r.toUpperCase()))throw new _(`${t} env_clear key "${r}" is reserved for sandbox safety`,f.USAGE)}return n}function Bs(e,t,n){if(!e)return;let r=e.trim().toLowerCase();if(r==="true"||r==="1"||r==="yes")return!0;if(r==="false"||r==="0"||r==="no")return!1;throw new _(`${t} ${n} must be one of true|false|1|0|yes|no`,f.USAGE)}function Hs(e,t){if(!e)return;let n=e.trim().toLowerCase();if(sn.includes(n))return n;throw new _(`${t} pm_context_mode must be one of: ${sn.join(", ")}`,f.USAGE)}function an(e,t){if(!e)return;let n=e.trim().toLowerCase();if(Ty.includes(n))return n;throw new _(`${t} workspace_context_mode must be one of: ${Ty.join(", ")}`,f.USAGE)}function cn(e){if(!e)return;let t=da(e,{separators:/[;\n]/});return t.length>0?t:void 0}function Wn(e,t,n){let r=cn(e);if(!(!r||r.length===0)){for(let i of r)try{new RegExp(i,"m")}catch(s){throw new _(`${t} ${n} includes invalid regex "${i}": ${s instanceof Error?s.message:String(s)}`,f.USAGE)}return r}}function Ws(e,t){if(!e)return;let n=_e(e,"assert_stdout_min_lines");if(!Number.isInteger(n)||n<0)throw new _(`${t} assert_stdout_min_lines must be an integer >= 0`,f.USAGE);return n}function Vs(e,t){if(!e)return;let n=e.split(/[;\n]/).map(i=>i.trim()).filter(i=>i.length>0);if(n.length===0)throw new _(`${t} assert_json_field_equals must include at least one path=value assignment`,f.USAGE);let r=Object.create(null);for(let i of n){let s=i.indexOf("=");if(s<=0)throw new _(`${t} assert_json_field_equals entries must use path=value and be separated by semicolons`,f.USAGE);let o=i.slice(0,s).trim(),a=i.slice(s+1).trim();if(o.length===0||a.length===0)throw new _(`${t} assert_json_field_equals entries must include non-empty path and value`,f.USAGE);r[o]=a}return Object.keys(r).length>0?r:void 0}function Ys(e,t){if(!e)return;let n=e.split(/[;\n]/).map(i=>i.trim()).filter(i=>i.length>0);if(n.length===0)throw new _(`${t} assert_json_field_gte must include at least one path=value assignment`,f.USAGE);let r=Object.create(null);for(let i of n){let s=i.indexOf("=");if(s<=0)throw new _(`${t} assert_json_field_gte entries must use path=value and be separated by semicolons`,f.USAGE);let o=i.slice(0,s).trim(),a=i.slice(s+1).trim();if(o.length===0||a.length===0)throw new _(`${t} assert_json_field_gte entries must include non-empty path and value`,f.USAGE);let c=Number(a);if(!Number.isFinite(c))throw new _(`${t} assert_json_field_gte value for "${o}" must be numeric`,f.USAGE);r[o]=c}return Object.keys(r).length>0?r:void 0}var cR=new Set(Et);function Js(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function dR(e,t){let n={},r=[];for(let[i,s]of Object.entries(e)){let o=i.toLowerCase();if(!cR.has(o)){r.push(i);continue}if(Object.hasOwn(n,o))throw t(`provides key "${i}" more than once after case normalization`);n[o]=s}if(r.length>0)throw t(`does not recognize key${r.length>1?"s":""} ${r.map(i=>`"${i}"`).join(", ")}. Allowed keys: ${Et.join(", ")}.`);return n}function rn(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r!==void 0){if(typeof r!="string")throw n(`field "${t}" must be a JSON string`);return r}}function Gs(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r===void 0)return;let i=typeof r=="string"?[r]:r;if(!Array.isArray(i)||i.some(o=>typeof o!="string"))throw n(`field "${t}" must be a string or an array of strings`);let s=i.filter(o=>o.length>0);return s.length>0?s:void 0}function Iy(e,t,n){let r=Gs(e,t,n);if(r){for(let i of r)try{new RegExp(i,"m")}catch(s){throw n(`field "${t}" includes invalid regex "${i}": ${s instanceof Error?s.message:String(s)}`)}return r}}function Ks(e,t,n){let r=typeof e=="number"?e:typeof e=="string"&&e.trim().length>0?Number(e.trim()):Number.NaN;if(typeof e=="boolean"||!Number.isFinite(r))throw n(`field "${t}" must be a finite number (or numeric string)`);return r}function lR(e,t){let n=e.timeout_seconds,r=e.timeout;if(n===void 0&&r===void 0)return;let i=n===void 0?void 0:Ks(n,"timeout_seconds",t),s=r===void 0?void 0:Ks(r,"timeout",t);if(i!==void 0&&s!==void 0&&i!==s)throw t("timeout and timeout_seconds must match when both are provided");let o=i??s;if(!Number.isInteger(o)||o<=0)throw t("timeout_seconds must be a positive integer");return o}function uR(e,t){let n=rn(e,"scope",t);if(n===void 0)return"project";if(!Ue.includes(n))throw t(`field "scope" must be one of: ${Ue.join(", ")}`);return n}function mR(e,t){if(!Object.hasOwn(e,"env_set"))return;let n=e.env_set;if(n===void 0)return;if(!Js(n))throw t('field "env_set" must be a JSON object mapping environment names to string values');let r=Object.create(null);for(let[i,s]of Object.entries(n)){if(typeof s!="string")throw t(`field "env_set" value for "${i}" must be a string`);if(!zs.test(i))throw t(`field "env_set" key "${i}" is invalid`);if(on.has(i.toUpperCase()))throw t(`field "env_set" key "${i}" is reserved for sandbox safety`);r[i]=s}return Object.keys(r).length>0?r:void 0}function fR(e,t){let n=Gs(e,"env_clear",t);if(n){for(let r of n){if(!zs.test(r))throw t(`field "env_clear" key "${r}" is invalid`);if(on.has(r.toUpperCase()))throw t(`field "env_clear" key "${r}" is reserved for sandbox safety`)}return n}}function _R(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r!==void 0){if(typeof r!="boolean")throw n(`field "${t}" must be a JSON boolean (true or false)`);return r}}function pR(e,t){if(!Object.hasOwn(e,"assert_stdout_min_lines"))return;let n=e.assert_stdout_min_lines;if(n===void 0)return;let r=Ks(n,"assert_stdout_min_lines",t);if(!Number.isInteger(r)||r<0)throw t('field "assert_stdout_min_lines" must be an integer >= 0');return r}function gR(e,t){if(!Object.hasOwn(e,"assert_json_field_equals"))return;let n=e.assert_json_field_equals;if(n===void 0)return;if(!Js(n))throw t('field "assert_json_field_equals" must be a JSON object mapping field paths to expected values');let r=Object.create(null);for(let[i,s]of Object.entries(n)){if(i.trim().length===0)throw t('field "assert_json_field_equals" keys must be non-empty field paths');if(typeof s!="string"&&typeof s!="number"&&typeof s!="boolean")throw t(`field "assert_json_field_equals" value for "${i}" must be a string, number, or boolean`);r[i]=String(s)}return Object.keys(r).length>0?r:void 0}function hR(e,t){if(!Object.hasOwn(e,"assert_json_field_gte"))return;let n=e.assert_json_field_gte;if(n===void 0)return;if(!Js(n))throw t('field "assert_json_field_gte" must be a JSON object mapping field paths to numeric minimums');let r=Object.create(null);for(let[i,s]of Object.entries(n)){if(i.trim().length===0)throw t('field "assert_json_field_gte" keys must be non-empty field paths');r[i]=Ks(s,`assert_json_field_gte.${i}`,t)}return Object.keys(r).length>0?r:void 0}function yR(e,t,n){let r=m=>new _(`${n} ${t} ${m}`,f.USAGE);if(!Js(e))throw r(`must be a JSON object with linked-test fields. Allowed keys: ${Et.join(", ")}.`);let i=dR(e,r),s=rn(i,"command",r),o=rn(i,"cmd",r);if(s!==void 0&&o!==void 0&&s!==o)throw r("command and cmd must match when both are provided");let a=s??o;if(a===void 0||a.trim().length===0)throw r('requires a non-empty "command" string');let c=rn(i,"path",r),d=rn(i,"pm_context_mode",r);if(d!==void 0&&!sn.includes(d))throw r(`field "pm_context_mode" must be one of: ${sn.join(", ")}`);let l=an(rn(i,"workspace_context_mode",r),`${n} ${t}`),u=rn(i,"note",r);return{command:a,path:c!==void 0&&c.length>0?c:void 0,scope:uR(i,r),timeout_seconds:lR(i,r),pm_context_mode:d,workspace_context_mode:l,env_set:mR(i,r),env_clear:fR(i,r),shared_host_safe:_R(i,"shared_host_safe",r),assert_stdout_contains:Gs(i,"assert_stdout_contains",r),assert_stdout_regex:Iy(i,"assert_stdout_regex",r),assert_stderr_contains:Gs(i,"assert_stderr_contains",r),assert_stderr_regex:Iy(i,"assert_stderr_regex",r),assert_stdout_min_lines:pR(i,r),assert_json_field_equals:gR(i,r),assert_json_field_gte:hR(i,r),note:u!==void 0&&u.trim().length>0?u.trim():void 0}}function Ay(e,t){let n=e.trim();if(n.length===0)throw new _(`${t} requires a JSON object or array of objects describing linked-test entries`,f.USAGE);let r;try{r=JSON.parse(n)}catch(s){throw new _(`${t} value is not valid JSON: ${s instanceof Error?s.message:String(s)}. Provide a JSON object or array of objects, e.g. '{"command":"node scripts/check.js --flag value, with commas","timeout_seconds":120}'.`,f.USAGE)}let i=Array.isArray(r)?r:[r];if(i.length===0)throw new _(`${t} array must include at least one linked-test entry object`,f.USAGE);return i.map((s,o)=>yR(s,i.length>1?`entry ${o+1}`:"entry",t))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="002f45a2-edc3-5aa0-9af8-d9b1dfecc097")}catch{}})();var vR={comment:"--clear-comments",dep:"--clear-deps",doc:"--clear-docs",event:"--clear-events",file:"--clear-files",learning:"--clear-learnings",note:"--clear-notes",reminder:"--clear-reminders",test:"--clear-tests",typeOption:"--clear-type-options"};function wR(e){return vR[e]}function id(e){return wR(e)!==void 0}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="39a36d42-29b1-5f0f-a8b2-f3bfc0ef78c2")}catch{}})();var bR="hierarchy-integrity";async function Xs(e){let t=e.required?await Ct(e.pmRoot,bR,e.ttlSeconds,e.author,!1,!1,e.waitMs):async()=>{},n=!1;return async()=>{n||(n=!0,await t())}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="dcbb6070-7457-5454-abf1-fa8153c8efd6")}catch{}})();function Qs(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function Zs(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function eo(e){let t=e.trim().toLowerCase();if(t==="med")return"medium";if(Tl.includes(t))return t;let n=_e(e,"confidence");if(!Number.isInteger(n)||n<0||n>100)throw new _("Confidence must be an integer 0..100 or one of low|med|medium|high",f.USAGE);return n}function to(e){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1;throw new _("Regression must be one of true|false|1|0",f.USAGE)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="afc4f3d5-ba5e-5dd7-abc9-531b319cdb4e")}catch{}})();var kR=new Set(["none","null"]);function no(e={}){return[{optionKey:"dep",clearFlagKey:"clearDeps",valueFlag:"--dep",clearFlag:"--clear-deps",...e.depDisableFlagKey===void 0?{}:{disableFlagKey:e.depDisableFlagKey}},{optionKey:"comment",clearFlagKey:"clearComments",valueFlag:"--comment",clearFlag:"--clear-comments"},{optionKey:"note",clearFlagKey:"clearNotes",valueFlag:"--note",clearFlag:"--clear-notes"},{optionKey:"learning",clearFlagKey:"clearLearnings",valueFlag:"--learning",clearFlag:"--clear-learnings"},{optionKey:"file",clearFlagKey:"clearFiles",valueFlag:"--file",clearFlag:"--clear-files",...e.fileDisableFlagKey===void 0?{}:{disableFlagKey:e.fileDisableFlagKey}},{optionKey:"test",clearFlagKey:"clearTests",valueFlag:"--test",clearFlag:"--clear-tests",...e.testDisableFlagKey===void 0?{}:{disableFlagKey:e.testDisableFlagKey}},{optionKey:"doc",clearFlagKey:"clearDocs",valueFlag:"--doc",clearFlag:"--clear-docs",...e.docDisableFlagKey===void 0?{}:{disableFlagKey:e.docDisableFlagKey}},{optionKey:"reminder",clearFlagKey:"clearReminders",valueFlag:"--reminder",clearFlag:"--clear-reminders"},{optionKey:"event",clearFlagKey:"clearEvents",valueFlag:"--event",clearFlag:"--clear-events"},{optionKey:"typeOption",clearFlagKey:"clearTypeOptions",valueFlag:"--type-option",clearFlag:"--clear-type-options"}]}function Ye(e){return e===void 0?!1:kR.has(e.trim().toLowerCase())}function ro(e,t,n){if(!Ye(e))return;let r=n?` ${n}`:"";throw new _(`${t} no longer accepts "none" or "null".${r}`.trim(),f.USAGE)}function De(e,t,n){if(!e||e.length===0||!e.some(s=>Ye(s)))return;let i=n?` ${n}`:"";throw new _(`${t} no longer accepts "none" or "null".${i}`.trim(),f.USAGE)}function io(e,t){for(let n of t){let r=e[n.optionKey];if(!Array.isArray(r)||r.length===0)continue;if(!r.every(a=>typeof a=="string"))throw new _(`${n.valueFlag} entries must be strings.`,f.USAGE);let i=r;if(!i.some(a=>Ye(a)))continue;if(i.filter(a=>!Ye(a)).length>0)throw new _(`Cannot mix legacy clear token "none"/"null" with concrete ${n.valueFlag} entries. Use ${n.clearFlag} to clear or provide explicit entries.`,f.USAGE);e[n.optionKey]=void 0,e[n.clearFlagKey]=!0,n.disableFlagKey&&(e[n.disableFlagKey]=!1)}return e}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e009d7f9-8d50-519a-9a43-632efd3bf443")}catch{}})();var ER=new Set(["event","meeting","reminder","milestone","decision","adr"]);function Cy(e,t,n,r){if(ER.has(t.trim().toLowerCase())||n!==r.open_status)return;let i=kn("in_progress",r);if(!(i===void 0||i===r.open_status))return{command:`pm start-task ${e}`,to_status:i}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0062e981-158a-5e6a-b028-6c7cef0f59ba")}catch{}})();var sd=[{canonical:"tags",aliases:["tags"],optionKey:"tags",metadataKey:"tags"}],od=[{canonical:"deadline",aliases:["deadline"],optionKey:"deadline",metadataKey:"deadline"},{canonical:"estimate",aliases:["estimate","estimated_minutes","estimated-minutes"],optionKey:"estimatedMinutes",metadataKey:"estimated_minutes"},{canonical:"acceptance-criteria",aliases:["acceptance_criteria","acceptance-criteria","ac"],optionKey:"acceptanceCriteria",metadataKey:"acceptance_criteria"},{canonical:"definition-of-ready",aliases:["definition_of_ready","definition-of-ready"],optionKey:"definitionOfReady",metadataKey:"definition_of_ready"},{canonical:"order",aliases:["order","rank"],optionKey:"order",metadataKey:"order"},{canonical:"goal",aliases:["goal"],optionKey:"goal",metadataKey:"goal"},{canonical:"objective",aliases:["objective"],optionKey:"objective",metadataKey:"objective"},{canonical:"value",aliases:["value"],optionKey:"value",metadataKey:"value"},{canonical:"impact",aliases:["impact"],optionKey:"impact",metadataKey:"impact"},{canonical:"outcome",aliases:["outcome"],optionKey:"outcome",metadataKey:"outcome"},{canonical:"why-now",aliases:["why_now","why-now"],optionKey:"whyNow",metadataKey:"why_now"}],Ry=[...sd,...od],so=[{canonical:"assignee",aliases:["assignee"],optionKey:"assignee",metadataKey:"assignee"},{canonical:"parent",aliases:["parent"],optionKey:"parent",metadataKey:"parent"},{canonical:"reviewer",aliases:["reviewer"],optionKey:"reviewer",metadataKey:"reviewer"},{canonical:"risk",aliases:["risk"],optionKey:"risk",metadataKey:"risk"},{canonical:"confidence",aliases:["confidence"],optionKey:"confidence",metadataKey:"confidence"},{canonical:"sprint",aliases:["sprint"],optionKey:"sprint",metadataKey:"sprint"},{canonical:"release",aliases:["release"],optionKey:"release",metadataKey:"release"},{canonical:"blocked-by",aliases:["blocked_by","blocked-by"],optionKey:"blockedBy",metadataKey:"blocked_by"},{canonical:"blocked-reason",aliases:["blocked_reason","blocked-reason"],optionKey:"blockedReason",metadataKey:"blocked_reason"},{canonical:"unblock-note",aliases:["unblock_note","unblock-note"],optionKey:"unblockNote",metadataKey:"unblock_note"},{canonical:"reporter",aliases:["reporter"],optionKey:"reporter",metadataKey:"reporter"},{canonical:"severity",aliases:["severity"],optionKey:"severity",metadataKey:"severity"},{canonical:"environment",aliases:["environment"],optionKey:"environment",metadataKey:"environment"},{canonical:"repro-steps",aliases:["repro_steps","repro-steps"],optionKey:"reproSteps",metadataKey:"repro_steps"},{canonical:"resolution",aliases:["resolution"],optionKey:"resolution",metadataKey:"resolution"},{canonical:"expected-result",aliases:["expected_result","expected-result"],optionKey:"expectedResult",metadataKey:"expected_result"},{canonical:"actual-result",aliases:["actual_result","actual-result"],optionKey:"actualResult",metadataKey:"actual_result"},{canonical:"affected-version",aliases:["affected_version","affected-version"],optionKey:"affectedVersion",metadataKey:"affected_version"},{canonical:"fixed-version",aliases:["fixed_version","fixed-version"],optionKey:"fixedVersion",metadataKey:"fixed_version"},{canonical:"component",aliases:["component"],optionKey:"component",metadataKey:"component"},{canonical:"regression",aliases:["regression"],optionKey:"regression",metadataKey:"regression"},{canonical:"customer-impact",aliases:["customer_impact","customer-impact"],optionKey:"customerImpact",metadataKey:"customer_impact"}];function oo(e){let t=new Set,n=new Set;if(!e.raw||e.raw.length===0)return{metadataKeys:t,optionKeys:n};for(let r of e.raw){let i=r.trim().toLowerCase();if(!i)throw new _("--unset values must not be empty",f.USAGE);if(Ye(i))throw new _('--unset no longer accepts "none" or "null". Specify concrete field names such as --unset deadline',f.USAGE);let s=e.resolveDefinition(i);if(!s)throw new _(`Unsupported --unset field "${r}". Supported fields: ${e.supportedFields}`,f.USAGE);t.add(s.metadataKey),n.add(s.optionKey)}return{metadataKeys:t,optionKeys:n}}function ao(e,t,n){let r=e.trim().toLowerCase();if(!n)return;let i=n.command_to_fields?.get(t)??[];for(let s of i){if(s.allow_unset===!1)continue;let o=new Set;if(typeof s.key=="string"&&s.key.length>0&&o.add(s.key.toLowerCase()),typeof s.metadata_key=="string"&&s.metadata_key.length>0&&o.add(s.metadata_key.toLowerCase()),typeof s.cli_flag=="string"&&s.cli_flag.length>0&&(o.add(s.cli_flag.replaceAll("-","_").toLowerCase()),o.add(s.cli_flag.toLowerCase())),Array.isArray(s.cli_aliases))for(let a of s.cli_aliases)typeof a!="string"||a.length===0||(o.add(a.replaceAll("-","_").toLowerCase()),o.add(a.toLowerCase()));if(o.has(r))return{optionKey:s.key,metadataKey:s.metadata_key}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2fcfbe50-039b-5031-8b18-a208908a0d87")}catch{}})();function Dy(e,t){let n=e.trim().toLowerCase();if(n==="true"||n==="1"||n==="yes")return!0;if(n==="false"||n==="0"||n==="no")return!1;throw new _(`${t} must be one of true|false|1|0|yes|no`,f.USAGE)}function ad(e){return e?e.split("|").map(t=>t.trim()).filter(t=>t.length>0):[]}function Le(e,t,n){if(!t.includes(e))throw new _(`Invalid ${n} value "${e}". Allowed: ${t.join(", ")}`,f.USAGE);return e}var Ly=["recur_freq","recur_interval","recur_count","recur_until","recur_by_weekday","recur_by_month_day","recur_exdates"];function SR(e,t){return t==="defined"?e!==void 0:!!e}function Oy(e,t,n){if(!SR(e,n))return;let r=_e(e,`event ${t}`);if(!Number.isInteger(r)||r<1)throw new _(`--event ${t} must be an integer >= 1`,f.USAGE);return r}function xR(e,t,n){let r=e?fe(e,n,"event.recur_until"):void 0;if(r&&r<t)throw new _("--event recur_until must be at or after start",f.USAGE);return r}function TR(e){return Array.from(new Set(ad(e).map(t=>Le(t.toLowerCase(),Dl,"event weekday")))).sort((t,n)=>Ho(t)-Ho(n))}function IR(e){return Array.from(new Set(ad(e).map(t=>{let n=_e(t,"event recur_by_month_day");if(!Number.isInteger(n)||n<1||n>31)throw new _("--event recur_by_month_day values must be integers 1..31",f.USAGE);return n}))).sort((t,n)=>t-n)}function AR(e,t){return Array.from(new Set(ad(e).map(n=>fe(n,t,"event.recur_exdates")))).sort((n,r)=>n.localeCompare(r))}function Ny(e,t,n,r){let i=e.recur_freq?.trim(),s=e.recur_interval?.trim(),o=e.recur_count?.trim(),a=e.recur_until?.trim(),c=e.recur_by_weekday?.trim(),d=e.recur_by_month_day?.trim(),l=e.recur_exdates?.trim();if(![i,s,o,a,c,d,l].some(E=>E!==void 0))return;if(!i)throw new _("--event recurrence fields require recur_freq=<daily|weekly|monthly|yearly>",f.USAGE);let m=Le(i.toLowerCase(),Ol,"event recurrence frequency"),g=Oy(s,"recur_interval",r),p=Oy(o,"recur_count",r),h=xR(a,t,n),y=TR(c),v=IR(d),w=AR(l,n);return{freq:m,interval:g,count:p,until:h,by_weekday:y.length>0?y:void 0,by_month_day:v.length>0?v:void 0,exdates:w.length>0?w:void 0}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d6f359cb-2bc9-5f96-8789-db91512d0bd5")}catch{}})();function Kr(e,t,n="--dep"){if(!t&&/[:,=]/.test(e))throw new _(`Invalid ${n} value "${e}". Use a bare item id or id=<id>,kind=<kind>.`,f.USAGE,{code:"dependency_flag_value_invalid",reason:"malformed_dependency_shorthand",flag:n,value:e,required:"Use a bare item id or an explicit id=<id>,kind=<kind> entry."})}function zr(e,t,n=xe()){for(let r of t??[])try{Bl(e,r.id,r.kind,n)}catch(i){throw new _(kl(i),f.USAGE,{code:"dependency_edge_not_allowed",why:`${e} -> ${r.id} (${r.kind}) violates the active relationship-kind policy`})}}async function My(e,t){return(await ge(e,{schema:t})).document.metadata.created_at}async function CR(e,t){if(e.createdAt!==void 0)return e.createdAt;let n=await X(t.pmRoot,e.id,t.idPrefix,t.itemFormat,t.typeToFolder);return n===null?void 0:My(n,t.schema)}function RR(e){let t=e.registry.require(e.dependency.kind);return new _(`${t.kind} requires source ${e.holder.id} to be created after target ${e.dependency.id}`,f.USAGE,{code:"dependency_temporal_order_invalid",reason:"source_not_after_target",required:`${e.holder.id}.created_at must be later than ${e.dependency.id}.created_at for ${t.kind}.`,why:"Chronological recurrence direction must be validated before the relationship is persisted.",source_id:e.holder.id,source_created_at:e.sourceCreatedAt,target_id:e.dependency.id,target_created_at:e.targetCreatedAt,temporal_order:t.temporalOrder})}async function OR(e){let t=e.dependencies.filter(i=>e.registry.resolve(i.kind)?.temporalOrder==="source_after_target"&&!e.missingTargets.includes(i.id));if(t.length===0||e.holders.length===0)return;let n=new Map(e.resolutions.flatMap(({target:i,located:s})=>s===null?[]:[[i,s]])),r=new Map(await Promise.all([...new Set(t.map(({id:i})=>i))].map(async i=>[i,await My(n.get(i),e.context.schema)])));for(let i of e.holders){let s=await CR(i,e.context);if(s!==void 0)for(let o of t){let a=r.get(o.id),c=Date.parse(s),d=Date.parse(a);if(!(Number.isFinite(c)&&Number.isFinite(d)&&c>d))throw RR({holder:i,dependency:o,sourceCreatedAt:s,targetCreatedAt:a,registry:e.registry})}}}async function co(e){let t=e.registry??xe(),n=(e.dependencies??[]).filter(o=>!Yf(o.source_kind)),r=[...new Set(n.map(o=>o.id))],i=await Promise.all(r.map(async o=>({target:o,located:await X(e.pmRoot,o,e.idPrefix,e.itemFormat,e.typeToFolder)}))),s=i.filter(({located:o})=>o===null).map(({target:o})=>o).sort((o,a)=>o<a?-1:1);if(s.length>0&&e.allowUnresolved!==!0)throw new _(`Dependency target${s.length===1?"":"s"} not found: ${s.join(", ")}`,f.NOT_FOUND,{code:"dependency_target_not_found",reason:"unresolved_local_dependency",required:"Every local dependency target must exist before the edge is committed.",why:"Fail-fast target resolution prevents dangling graph nodes and preserves reliable traversal semantics.",unresolved_targets:s,examples:["--dep id=<existing-item-id>,kind=related","--dep id=<external-id>,kind=related,source_kind=external","--allow-unresolved-deps --dep id=<future-item-id>,kind=related"],nextSteps:[`Create or correct ${s.length===1?"the target":"the targets"}, then retry the mutation.`,"Use source_kind=external for a cross-workspace reference.","Use --allow-unresolved-deps only when the dangling local edge is intentional."],recovery:{recovery_mode:"compact",missing:s,suggested_flags:["--allow-unresolved-deps"],suggested_retry:`pm search "${s[0]}" --limit 10`}});return await OR({dependencies:n,missingTargets:s,resolutions:i,holders:e.holders??[],registry:t,context:e}),s.map(o=>`dependency_target_unresolved:${o}`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8248687e-ba97-5e1b-afbf-a322a72eb1aa")}catch{}})();var Py="--event end must be strictly after start. Equal start/end timestamps are treated as an instant event (end is dropped); an end earlier than start is rejected. Omit end for an instant event or set end later than start.",DR="--event end and duration are mutually exclusive; provide only one (use duration=<relative> like duration=2h, duration=30min, or duration=PT30M, or set an explicit end).",LR=/^([+-]?)(\d+)(min|mins|minute|minutes)$/i,NR=/^([+-]?)[Pp][Tt](?:(\d+)[Hh])?(?:(\d+)[Mm])?(?:(\d+)[Ss])?$/,$y=1e3,cd=60*$y,MR=60*cd;function Fy(e,t){let n=new Date(e);if(!Number.isFinite(n.getTime()))throw new _(`Invalid event.duration value "${t}". Duration is out of supported timestamp range.`,f.USAGE);return n.toISOString()}function PR(e,t){let n=new Date(e),r=t.trim(),i=LR.exec(r);if(i){let a=i[1]==="-"?-1:1,c=Number.parseInt(i[2],10)*a;return Fy(n.getTime()+c*cd,r)}let s=NR.exec(r);if(s){let[,a,c,d,l]=s;if(c||d||l){let m=a==="-"?-1:1,g=Number.parseInt(c??"0",10),p=Number.parseInt(d??"0",10),h=Number.parseInt(l??"0",10),y=g*MR+p*cd+h*$y;return Fy(n.getTime()+m*y,r)}}let o=r.startsWith("+")||r.startsWith("-")?r:`+${r}`;return fe(o,n,"event.duration")}function jy(e,t,n,r){if(t&&n)throw new _(DR,f.USAGE);if(n){let s=PR(e,n);if(s<e)throw new _(Py,f.USAGE);return s===e?void 0:s}if(!t)return;let i=fe(t,r,"event.end");if(i<e)throw new _(Py,f.USAGE);if(i!==e)return i}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fd41d2bf-7be0-55ee-9048-a9d5092a9a21")}catch{}})();var FR=["at","date","text","title"],$R=["start","date","end","duration","title","description","location","timezone","all_day",...Ly],jR=["key","value"];function Uy(e,t){return t==="trimmed"?e?.trim():e}function UR(e,t){return t==="defined"?e!==void 0:!!e}function lo(e,t,n){return e.map(r=>{let i=te(r,"--reminder");be(i,"--reminder",FR);let s=Uy(i.at??i.date,n.valueMode),o=Uy(i.text??i.title,n.valueMode);if(!s||!o)throw new _("--reminder requires at=<iso|relative> or date=<iso|relative>, plus text=<value> or title=<value>",f.USAGE);let a=o.trim();if(!a)throw new _("--reminder text must not be empty",f.USAGE);return{at:fe(s,t,"reminder.at"),text:a}})}function uo(e,t,n){return e.map(r=>{let i=te(r,"--event");be(i,"--event",$R);let s=(i.start??i.date)?.trim();if(!s)throw new _("--event requires start=<iso|relative> or date=<iso|relative>",f.USAGE);let o=fe(s,t,"event.start"),a=i.end?.trim(),c=i.duration?.trim(),d=jy(o,a,c,t),l=i.title,u=i.description,m=i.location,g=i.timezone,p=l?.trim(),h=u?.trim(),y=m?.trim(),v=g?.trim(),w=[["title",l,p],["description",u,h],["location",m,y],["timezone",g,v]];for(let[I,k,b]of w)if(k!==void 0&&!b)throw new _(`--event ${I} must not be empty`,f.USAGE);let E=i.all_day?.trim(),S=Ny(i,o,t,n.recurrenceEmptyNumericGuard),x=UR(E,n.allDayEmptyGuard)?Dy(E,"--event all_day"):void 0;return{start_at:o,end_at:d,title:p,description:h,location:y,all_day:x,timezone:v,recurrence:S}})}function mo(e){let t={};for(let n of e){let r=n.trim();if(r.length===0)throw new _("--type-option values must not be empty",f.USAGE);let i,s;if(r.includes(",")||r.includes(`
|
|
20
|
-
`)||r.startsWith("```")||/^(?:[-*+]\s+)?(?:key|value)\s*[:=]/i.test(r)){let a=te(r,"--type-option");be(a,"--type-option",jR),i=a.key?.trim(),s=a.value?.trim()}else{let a=r.indexOf("="),c=r.indexOf(":"),d=a;if(a<=0&&c>0&&(d=c),d<=0||d===r.length-1)throw new _("--type-option requires key=value or key=<name>,value=<value> entries",f.USAGE);i=r.slice(0,d).trim(),s=r.slice(d+1).trim()}if(!i||!s)throw new _("--type-option requires key and value",f.USAGE);t[i]=s}return Object.fromEntries(Object.entries(t).sort((n,r)=>n[0].localeCompare(r[0])))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="44240cea-9996-5f86-acc5-ac0cfa71c586")}catch{}})();var qR=["strict","progressive"],GR=["lightweight"],zy=new Set(["Reminder","Meeting","Event"]),KR=new Set(["author","created_at","text"]),ld=[...Ry,{canonical:"author",aliases:["author"],optionKey:"author",metadataKey:"author"},...so],zR=(()=>{let e=new Map;for(let t of ld)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),fo=new Map(ld.map(e=>[e.optionKey,e.canonical])),BR=ld.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", ");function HR(e,t){let n=se(e,t);if(!n){let r=t.definitions.map(i=>i.id);throw new _(`Invalid status value "${e}". Allowed: ${r.join(", ")}`,f.USAGE)}return n}function WR(e,t){let n=e.default_status;if(n!==void 0){let r=se(n,t);if(r)return r}return t.open_status}function dd(e,t){if(!e||e.trim()===""||e.trim().toLowerCase()==="now")return t;let n=Date.parse(e);if(!Number.isFinite(n))throw new _(`Invalid created_at timestamp "${e}"`,f.USAGE);return new Date(n).toISOString()}var VR=no();function By(e){let t={...e,unset:e.unset?[...e.unset]:void 0},n=i=>{let s=t.unset?[...t.unset]:[];s.includes(i)||s.push(i),t.unset=s};Ye(t.template)&&(t.template=void 0);let r=new Set([...fo.keys(),"rank"]);for(let i of r){let s=t[i];if(typeof s!="string"||!Ye(s))continue;let o=i==="rank"?"order":fo.get(i)??i;n(o),t[i]=void 0}return qe(e,io(t,VR))}function ke(e){if(e!==void 0)return e}function YR(e,t){return oo({raw:e,supportedFields:BR,resolveDefinition:n=>zR.get(n)??ao(n,"create",t)})}var qy=["id","kind","type","author","created_at","source_kind"],_o=["path","scope","note"];function JR(e,t,n,r){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(De(e,"--dep","Use --clear-deps to clear dependencies."),{values:e.map(s=>{let o=s.trim(),a=po(o,qy);Kr(o,a);let c=a?te(s,"--dep"):{id:o,kind:"related"};a&&be(c,"--dep",qy);let d=ke(c.id),l=XR(ke(c.kind??c.type));if(!d||!l)throw new _("--dep requires id and kind, or a bare item id to create a related dependency",f.USAGE);if(d.trim().toLowerCase()==="undefined")throw new _(`--dep id must not use placeholder token "${d}". Use --clear-deps to clear dependencies.`,f.USAGE);let u=mr(ke(c.source_kind)),m=ke(c.author);return{id:fr(d,n,u),kind:Le(l,rr,"dependency kind"),created_at:dd(c.created_at,t),author:m??r,source_kind:u??"cli:create:dep",author_source:m?"asserted":"detected"}}),explicitEmpty:!1})}function XR(e){return typeof e=="string"?zt(e)??e.trim():e}function po(e,t){return gi(e,t)?!0:wn(e)}function ln(e,t,n,r){return!t||t.length===0?{values:void 0,explicitEmpty:!1}:(De(t,e,e==="--comment"?"Use --clear-comments to clear comments.":e==="--note"?"Use --clear-notes to clear notes.":"Use --clear-learnings to clear learnings."),{values:t.map(o=>{let a=o.trim(),c=()=>{if(a.length===0)throw new _(`${e} requires text=<value>`,f.USAGE);return{created_at:n,author:r,text:a}},d;try{d=te(o,e)}catch(m){if(e==="--comment"||e==="--note"||e==="--learning")return c();throw m}if(Object.keys(d).filter(m=>!KR.has(m)).length>0)return{created_at:dd(d.created_at,n),author:ke(d.author)??r,text:a};let u=d.text??"";if(u==="")throw new _(`${e} requires text=<value>`,f.USAGE);return{created_at:dd(d.created_at,n),author:ke(d.author)??r,text:u}}),explicitEmpty:!1})}function ud(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(De(e,"--file","Use --clear-files to clear linked files."),{values:e.map(n=>{let r=n.trim(),i=po(r,_o);ar(r,"--file","file path",i);let s=i?te(n,"--file"):{path:r};if(i&&be(s,"--file",_o),!s.path)throw new _("--file requires path=<value> or a bare file path",f.USAGE);return{path:s.path,scope:Le(s.scope??"project",Ue,"file scope"),note:ke(s.note)}}),explicitEmpty:!1})}function md(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(De(e,"--test","Use --clear-tests to clear linked tests."),{values:e.map(n=>{let r=n.trim(),i=po(r,Et);ar(r,"--test","test command",i);let s=i?qs(te(n,"--test"),"--test"):{command:r},o=ke(s.command),a=ke(s.path);if(!o)throw new _("--test requires command=<value> or a bare command (path=<value> is optional metadata)",f.USAGE);let c=ke(s.timeout_seconds),d=ke(s.timeout);if(c&&d&&c!==d)throw new _("--test timeout and timeout_seconds must match when both are provided",f.USAGE);let l=c??d;return{command:o,path:a,scope:Le(s.scope??"project",Ue,"test scope"),timeout_seconds:l?_e(l,"timeout_seconds"):void 0,pm_context_mode:Hs(s.pm_context_mode,"--test"),workspace_context_mode:an(s.workspace_context_mode,"--test"),env_set:qr(s.env_set,"--test"),env_clear:Gr(s.env_clear,"--test"),shared_host_safe:Bs(s.shared_host_safe,"--test","shared_host_safe"),assert_stdout_contains:cn(s.assert_stdout_contains),assert_stdout_regex:Wn(s.assert_stdout_regex,"--test","assert_stdout_regex"),assert_stderr_contains:cn(s.assert_stderr_contains),assert_stderr_regex:Wn(s.assert_stderr_regex,"--test","assert_stderr_regex"),assert_stdout_min_lines:Ws(s.assert_stdout_min_lines,"--test"),assert_json_field_equals:Vs(s.assert_json_field_equals,"--test"),assert_json_field_gte:Ys(s.assert_json_field_gte,"--test"),note:ke(s.note)}}),explicitEmpty:!1})}function fd(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(De(e,"--doc","Use --clear-docs to clear linked docs."),{values:e.map(n=>{let r=n.trim(),i=po(r,_o),s=i?te(n,"--doc"):{path:r};if(i&&be(s,"--doc",_o),!s.path)throw new _("--doc requires path=<value> or a bare doc path",f.USAGE);return{path:s.path,scope:Le(s.scope??"project",Ue,"doc scope"),note:ke(s.note)}}),explicitEmpty:!1})}function QR(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(De(e,"--reminder","Use --clear-reminders to clear reminders."),{values:lo(e,new Date(t),{valueMode:"raw"}),explicitEmpty:!1})}function ZR(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(De(e,"--event","Use --clear-events to clear linked events."),{values:uo(e,new Date(t),{allDayEmptyGuard:"defined",recurrenceEmptyNumericGuard:"defined"}),explicitEmpty:!1})}function e0(e,t,n,r=[]){let i=[...hl.filter(s=>e[s]!==void 0),...r.filter(s=>e[s]!==void 0),...t.length>0?["body"]:[],...n.map(s=>`unset:${s}`)];return Array.from(new Set(i))}function t0(e,t){let n=e??"";if(t.length===0)return n;let r=`explicit_unset=${t.join(",")}`;return n?`${n} | ${r}`:r}function Gy(e,t,n){let r=ir("create",e);if(!r)throw new _(`Unsupported ${n} entry "${e}" for type "${t}"`,f.CONFLICT);return r}function n0(e){return{scalarValues:{title:e.title,description:e.description,type:e.type,status:e.status,priority:e.priority,tags:e.tags,body:e.body,deadline:e.deadline,estimatedMinutes:e.estimatedMinutes,acceptanceCriteria:e.acceptanceCriteria,definitionOfReady:e.definitionOfReady,order:e.order??e.rank,goal:e.goal,objective:e.objective,value:e.value,impact:e.impact,outcome:e.outcome,whyNow:e.whyNow,author:e.author,message:e.message,assignee:e.assignee,parent:e.parent,reviewer:e.reviewer,risk:e.risk,confidence:e.confidence,sprint:e.sprint,release:e.release,blockedBy:e.blockedBy,blockedReason:e.blockedReason,unblockNote:e.unblockNote,reporter:e.reporter,severity:e.severity,environment:e.environment,reproSteps:e.reproSteps,resolution:e.resolution,expectedResult:e.expectedResult,actualResult:e.actualResult,affectedVersion:e.affectedVersion,fixedVersion:e.fixedVersion,component:e.component,regression:e.regression,customerImpact:e.customerImpact},repeatableValues:{dep:e.dep,comment:e.comment,note:e.note,learning:e.learning,file:e.file,test:e.test,doc:e.doc,reminder:e.reminder,event:e.event,typeOption:e.typeOption,field:e.field},addTags:e.addTags}}function Hy(e,t){if(t==="tags")return e.scalarValues.tags!==void 0||Array.isArray(e.addTags)&&e.addTags.length>0;if(Object.prototype.hasOwnProperty.call(e.scalarValues,t))return e.scalarValues[t]!==void 0;if(Object.prototype.hasOwnProperty.call(e.repeatableValues,t)){let n=e.repeatableValues[t];return Array.isArray(n)&&n.length>0}return!1}function r0(e,t){let n=new Set(["title","type"]);if(t!=="strict")return n;for(let r of e.required_create_fields)n.add(Gy(r,e.name,"required_create_fields"));for(let r of e.required_create_repeatables)n.add(Gy(r,e.name,"required_create_repeatables"));return n}function i0(e,t,n,r){for(let i of e)if(!(!Hy(t,i)&&!n.has(i)))throw new _(`Option ${Ie("create",i)} is disabled for type "${r}" by command_option_policies`,f.USAGE)}function s0(e,t,n){if(t!=="strict")return;let r=e.filter(s=>n.has(s)&&!id(s));if(r.length===0)return;let i=[...new Set(r.map(s=>Ie("create",s)))].sort((s,o)=>s.localeCompare(o));throw new _(`Strict create mode requires concrete values for ${i.join(", ")}; --unset/--clear-* directives cannot satisfy required options`,f.USAGE)}function o0(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(De(e,"--type-option","Use --clear-type-options to clear existing type options."),{values:mo(e),explicitEmpty:!1})}async function a0(e){return await vi(e,[["body","--body"],["description","--description"]],[["dep","--dep"],["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"],["field","--field"]])}async function c0(e){return Bt(e)?await a0(e):e}function d0(e,t){if(e===void 0)return t;let n=e.trim().toLowerCase();if(n.length===0)return t;if(n==="strict"||n==="progressive")return n;throw new _(`Invalid --create-mode value "${e}". Allowed: ${qR.join(", ")}`,f.USAGE)}function l0(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)throw new _("--schedule-preset must not be empty",f.USAGE);if(t==="lightweight"||t==="lite"||t==="schedule-lite")return"lightweight";throw new _(`Invalid --schedule-preset value "${e}". Allowed: ${GR.join(", ")}`,f.USAGE)}function u0(e,t,n){let r=d0(e,n);if(t===void 0)return r;if(typeof e=="string"&&e.trim().length>0&&r==="strict")throw new _("--schedule-preset lightweight cannot be combined with --create-mode strict. Use --create-mode progressive or omit --create-mode.",f.USAGE);return"progressive"}function m0(e,t,n,r){let i=e.name,s=n0(t),o=r0(e,n),a=vn(e,"create",o);if(a.errors.length>0)throw new _(a.errors.join("; "),f.CONFLICT);i0(a.disabled,s,r,i),s0(a.required,n,r);let c=l=>l==="status"&&e.default_status!==void 0||r.has(l)&&id(l)?!0:Hy(s,l),d=a.required.filter(l=>!c(l));return[...new Set(d.map(l=>Ie("create",l)))].sort((l,u)=>l.localeCompare(u))}var Wy=/^Missing required type option "([^"]+)" for type "([^"]+)"$/;function f0(e,t){let n=[];for(let r of e){let i=r.match(Wy);i&&i[2]===t&&n.push(i[1])}return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}function _0(e,t){return e.filter(n=>{let r=n.match(Wy);return!r||r[2]!==t})}function p0(e,t,n,r){let i=_0(e,t);if(i.length===0)return;let s=Vy(n,[],[],r.open_status);throw new _(i.join("; "),f.USAGE,{code:"invalid_argument_value",required:`Provide valid --type-option key/value pairs for type "${t}".`,examples:[s],nextSteps:[`Run "pm create --help --type ${t}" to review allowed type-option keys and values.`]})}function g0(e,t){let r=e.options.find(i=>i.key===t)?.values[0];return typeof r=="string"&&r.trim().length>0?r:"<value>"}function h0(e,t,n){switch(e){case"--title":return["--title",`"${t} example title"`];case"--description":return["--description",`"${t} example description"`];case"--type":return["--type",t];case"--status":return["--status",n];case"--priority":return["--priority","1"];case"--message":return["--message",`"Create ${t} item"`];case"--dep":return["--dep",'"id=pm-xxxx,kind=related,author=maintainer,created_at=now"'];case"--comment":return["--comment",'"author=maintainer,created_at=now,text=Implementation context"'];case"--note":return["--note",'"author=maintainer,created_at=now,text=Design note"'];case"--learning":return["--learning",'"author=maintainer,created_at=now,text=Durable lesson"'];case"--file":return["--file",'"path=src/example.ts,note=implementation file"'];case"--test":return["--test",'"command=node scripts/run-tests.mjs test,timeout_seconds=240"'];case"--doc":return["--doc",'"path=README.md,note=reference doc"'];default:return[e,'"<value>"']}}function Vy(e,t,n,r){let i=["pm","create","--title",`"${e.name} example title"`,"--description",`"${e.name} example description"`,"--type",e.name],s=["--status","--priority","--message"],o=[...new Set([...s,...t])],a=new Set(["--title","--description","--type"]);for(let c of o)a.has(c)||(i.push(...h0(c,e.name,r)),a.add(c));for(let c of n){let d=g0(e,c);i.push("--type-option",`${c}=${d}`)}return i.join(" ")}function _d(e,t){let n=e?.trim();if(!n)throw t==="--title"?e!==void 0?new _("Title cannot be empty or whitespace-only. Retry: pass a non-empty title with --title.",f.USAGE):new _('Missing required option --title. Why required: every item needs a human-readable title for lookup, search, and reporting. Retry: pass the title as the first positional argument (example: pm create "Fix login bug" --type Issue) or with --title.',f.USAGE):new _(`Missing required option ${t}`,f.USAGE);return n}function y0(e,t){let n={};for(let[r,i]of Object.entries(e))n[r]=Array.isArray(i)?[...i]:i;for(let[r,i]of Object.entries(t))i!==void 0&&(n[r]=Array.isArray(i)?[...i]:i);return n}function v0(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function w0(){let e=F();return e?e.commands.some(t=>t.action==="templates-show"||v0(t.command)==="templates show"):!1}function b0(e,t){if(typeof e!="object"||e===null||!("options"in e))throw new _(`Templates package returned invalid payload for template "${t}". Expected an options object.`,f.GENERIC_FAILURE);let n=e.options;if(typeof n!="object"||n===null||Array.isArray(n))throw new _(`Templates package returned invalid options for template "${t}".`,f.GENERIC_FAILURE);let r={};for(let[i,s]of Object.entries(n)){if(typeof s=="string"||typeof s=="number"||typeof s=="boolean"){r[i]=s;continue}if(Array.isArray(s)&&s.every(o=>typeof o=="string")){r[i]=[...s];continue}throw new _(`Templates package returned unsupported option value for "${i}" in template "${t}".`,f.GENERIC_FAILURE)}return r}async function k0(e,t,n){if(!w0())throw new _("--template requires the templates package. Install it first (for example: pm install templates --project).",f.USAGE);let r=await Ql({command:"templates show",args:[e],options:{},global:t,pm_root:n});if(!r.handled){let i=r.warnings.length>0?` (${r.warnings.join(", ")})`:"";throw new _(`Unable to resolve template "${e}" via templates package. Run "pm templates show ${e}" for details.${i}`,f.USAGE)}return b0(r.result,e)}function Q(e,t,n){return e.has(t)||n===void 0?void 0:ke(n)}function dn(e,t,n,r){return e.has(t)||n===void 0?void 0:r(n)}var E0=new Set(["milestone","meeting","reminder","event"]);function Yy(e,t,n,r){let i=t!==void 0,s=n!==void 0&&n.length>0,o=r!==void 0&&r.length>0;return E0.has(e.toLowerCase())&&!i&&!s&&!o}function S0(e,t,n,r,i){let s=[];return e.toLowerCase()==="event"&&(i===void 0||i.length===0)&&s.push(`event_without_schedule:${t}:no_time_set`),Yy(e,n,r,i)&&s.push(`calendar_item_without_schedule:${t}:no_deadline_or_reminder_or_event (hint: set --deadline <ISO> or --reminder "<when>", or link an Event via --event "start=<ISO>,end=<ISO>"; otherwise this item never appears on pm calendar)`),s}async function x0(e,t,n,r){if(e!==void 0||n.has("parent")||t.parent!==void 0)return{parent:e,parentSource:void 0};let i=await du(r);return i===void 0?{parent:e,parentSource:void 0}:{parent:i,parentSource:"focus"}}async function T0(e,t,n,r,i,s){let o=Bi(Li(i),t.id_prefix);if(qi(o))return{parent:o,warnings:[]};if(Mi(r,o,t.id_prefix),await X(e,o,t.id_prefix,t.item_format,n.type_to_folder))return{parent:o,warnings:[]};let c=Ot(o,t.id_prefix);return{parent:o,warnings:Ni(c,s).warnings}}async function I0(e){return e.parent===void 0?{parent:void 0,warnings:[]}:await T0(e.pmRoot,e.settings,e.typeRegistry,e.itemId,e.parent,e.policy)}async function A0(e){if(e.explicitId===void 0)return Uu(e.pmRoot,e.settings.id_prefix,{tokenLength:e.settings.ids.token_length,typeToFolder:e.typeRegistry.type_to_folder,probeExisting:!1});if(typeof e.explicitId!="string")throw new _("--id must be a string",f.USAGE);let t=e.explicitId.trim();if(t.length===0||qu(t))throw new _("--id must not be empty or use a placeholder token",f.USAGE);let n=Ot(t,e.settings.id_prefix);if(!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(n))throw new _("--id must contain only letters, numbers, and dashes after normalization",f.USAGE);return n}function Ky(e,t,n,r,i){let s=Q(e,t,n);if(s===void 0)return{value:void 0,warnings:[]};let o=Fi(r,s,i);return{value:o.value,warnings:o.warnings}}async function C0(e){let{pmRoot:t,settings:n,typeRegistry:r,statusRegistry:i,blockedBy:s,status:o,statusExplicit:a,nowValue:c,author:d}=e,l=e.dependencyValues;if(s===void 0)return{dependencyValues:l,status:o};let u=Ot(s,n.id_prefix),m=await X(t,u,n.id_prefix,n.item_format,r.type_to_folder);if(!m)return{dependencyValues:l,status:o};if((l??[]).some(h=>h.id===m.id&&h.kind==="blocked_by")||(l=[...l??[],{id:m.id,kind:"blocked_by",created_at:c,author:d,source_kind:"cli:create:blocked_by",author_source:"detected"}]),a)return{dependencyValues:l,status:o};let p=i.blocked_statuses.has("blocked")?"blocked":[...i.blocked_statuses].sort((h,y)=>h.localeCompare(y))[0]??i.open_status;return{dependencyValues:l,status:p}}function R0(e,t,n){if(typeof e.createMode=="string"&&e.createMode.trim().toLowerCase()==="strict")return;let i=t.governance.create_default_type?.trim();if(i&&i.length>0&&ut(i,n)){e.type=i;return}ut("Task",n)&&(e.type="Task")}function O0(e,t){return e.options.filter(n=>ir("create",n.key)===void 0).flatMap(n=>{let r=t[n.key];if(r===void 0)return[];if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")return[n];throw new _(`Template custom type option "${n.key}" must be a string, number, or boolean value`,f.USAGE)})}async function D0(e,t,n,r,i){let s=e,o=[];if(s.template!==void 0){let p=s.template.trim();if(p.length===0)throw new _("--template must not be empty. Omit --template to disable template usage.",f.USAGE);let h=await k0(p,t,n);s=By(y0(h,s))}if(s.type===void 0&&R0(s,r,i),s.type===void 0)throw new _("Missing required option --type <value>",f.USAGE);let a=ut(s.type,i);if(!a){let p=Gu(s.type),h=p?ut(p,i):void 0;if(h)o.push(`type_coercion:${s.type.trim()}:${h}`),s.type=h,a=h;else throw new _($i(s.type,i.types,bi(n,r.schema)),f.USAGE)}let c=li(a,i);if(!c)throw new _(`Invalid type value "${s.type}"`,f.USAGE);let d=c.name,l=O0(c,s),u=l.map(p=>`${p.key}=${String(s[p.key])}`);if(u.length>0){s.typeOption=[...u,...s.typeOption??[]];for(let p of l)delete s[p.key]}let m=l0(s.schedulePreset);if(m!==void 0&&!zy.has(d))throw new _(`--schedule-preset ${m} is only supported for Reminder, Meeting, or Event types`,f.USAGE);let g=u0(s.createMode,m,r.governance.create_mode_default);return{resolvedOptions:s,typeDefinition:c,type:d,schedulePreset:m,createMode:g,warnings:o}}function L0(e,t){let n=new Set(t.metadataKeys),r=new Set(t.optionKeys),i=[{enabled:e.clearDeps,optionKey:"dep",clearFlag:"--clear-deps",valueFlag:"--dep",values:e.dep,metadataKey:"dependencies"},{enabled:e.clearComments,optionKey:"comment",clearFlag:"--clear-comments",valueFlag:"--comment",values:e.comment,metadataKey:"comments"},{enabled:e.clearNotes,optionKey:"note",clearFlag:"--clear-notes",valueFlag:"--note",values:e.note,metadataKey:"notes"},{enabled:e.clearLearnings,optionKey:"learning",clearFlag:"--clear-learnings",valueFlag:"--learning",values:e.learning,metadataKey:"learnings"},{enabled:e.clearFiles,optionKey:"file",clearFlag:"--clear-files",valueFlag:"--file",values:e.file,metadataKey:"files"},{enabled:e.clearTests,optionKey:"test",clearFlag:"--clear-tests",valueFlag:"--test",values:e.test,metadataKey:"tests"},{enabled:e.clearDocs,optionKey:"doc",clearFlag:"--clear-docs",valueFlag:"--doc",values:e.doc,metadataKey:"docs"},{enabled:e.clearReminders,optionKey:"reminder",clearFlag:"--clear-reminders",valueFlag:"--reminder",values:e.reminder,metadataKey:"reminders"},{enabled:e.clearEvents,optionKey:"event",clearFlag:"--clear-events",valueFlag:"--event",values:e.event,metadataKey:"events"},{enabled:e.clearTypeOptions,optionKey:"typeOption",clearFlag:"--clear-type-options",valueFlag:"--type-option",values:e.typeOption,metadataKey:"type_options"}];for(let s of i)if(s.enabled){if(s.values&&s.values.length>0)throw new _(`Cannot combine ${s.clearFlag} with ${s.valueFlag}`,f.USAGE);n.add(s.metadataKey),r.add(s.optionKey)}return{explicitUnsets:n,clearOptionKeys:r}}function N0(e,t){let n={tags:e.tags!==void 0,deadline:e.deadline!==void 0,estimatedMinutes:e.estimatedMinutes!==void 0,acceptanceCriteria:e.acceptanceCriteria!==void 0,definitionOfReady:e.definitionOfReady!==void 0,order:e.order!==void 0||e.rank!==void 0,goal:e.goal!==void 0,objective:e.objective!==void 0,value:e.value!==void 0,impact:e.impact!==void 0,outcome:e.outcome!==void 0,whyNow:e.whyNow!==void 0,author:e.author!==void 0,assignee:e.assignee!==void 0,parent:e.parent!==void 0,reviewer:e.reviewer!==void 0,risk:e.risk!==void 0,confidence:e.confidence!==void 0,sprint:e.sprint!==void 0,release:e.release!==void 0,blockedBy:e.blockedBy!==void 0,blockedReason:e.blockedReason!==void 0,unblockNote:e.unblockNote!==void 0,reporter:e.reporter!==void 0,severity:e.severity!==void 0,environment:e.environment!==void 0,reproSteps:e.reproSteps!==void 0,resolution:e.resolution!==void 0,expectedResult:e.expectedResult!==void 0,actualResult:e.actualResult!==void 0,affectedVersion:e.affectedVersion!==void 0,fixedVersion:e.fixedVersion!==void 0,component:e.component!==void 0,regression:e.regression!==void 0,customerImpact:e.customerImpact!==void 0};for(let[r,i]of Object.entries(n)){if(!i||!t.optionKeys.has(r))continue;let s=fo.get(r)??r;throw new _(`Cannot combine --unset ${s} with ${Ie("create",r)}`,f.USAGE)}}function M0(e){let t=(n,r)=>{let i=fo.get(r),s=i?`Use --unset ${i} to clear this field.`:void 0;ro(n,Ie("create",r),s)};t(e.tags,"tags"),t(e.deadline,"deadline"),t(e.estimatedMinutes,"estimatedMinutes"),t(e.acceptanceCriteria,"acceptanceCriteria"),t(e.definitionOfReady,"definitionOfReady"),t(e.order??e.rank,"order"),t(e.goal,"goal"),t(e.objective,"objective"),t(e.value,"value"),t(e.impact,"impact"),t(e.outcome,"outcome"),t(e.whyNow,"whyNow"),t(e.author,"author"),t(e.assignee,"assignee"),t(e.parent,"parent"),t(e.reviewer,"reviewer"),t(e.risk,"risk"),t(e.confidence,"confidence"),t(e.sprint,"sprint"),t(e.release,"release"),t(e.blockedBy,"blockedBy"),t(e.blockedReason,"blockedReason"),t(e.unblockNote,"unblockNote"),t(e.reporter,"reporter"),t(e.severity,"severity"),t(e.environment,"environment"),t(e.reproSteps,"reproSteps"),t(e.resolution,"resolution"),t(e.expectedResult,"expectedResult"),t(e.actualResult,"actualResult"),t(e.affectedVersion,"affectedVersion"),t(e.fixedVersion,"fixedVersion"),t(e.component,"component"),t(e.regression,"regression"),t(e.customerImpact,"customerImpact")}function P0(e,t,n){for(let r of Object.keys(e))if(n.metadataKeys.has(r))throw new _(`Cannot combine --unset ${r.replaceAll("_","-")} with --field ${r}=...`,f.USAGE);for(let r of Object.keys(t.values??{}))if(n.metadataKeys.has(r))throw new _(`Cannot combine --unset ${r.replaceAll("_","-")} with its value flag`,f.USAGE)}var F0={"--comment":"--clear-comments","--dep":"--clear-deps","--doc":"--clear-docs","--event":"--clear-events","--file":"--clear-files","--learning":"--clear-learnings","--note":"--clear-notes","--reminder":"--clear-reminders","--test":"--clear-tests","--type-option":"--clear-type-options"};function $0(e){let{combinedMissingFlags:t,typeDefinition:n,missingRequiredCreateFlags:r,missingRequiredTypeOptionKeys:i,openStatus:s,type:o,createMode:a,missingRequiredRuntimeFields:c}=e;if(t.length===0)return;let d=c.map(p=>{let h=p.type==="boolean"?"<true|false>":p.type==="array"?"<json-array>":p.type==="object"?"<json-object>":p.type==="number"?"<number>":p.type==="string_array"||p.repeatable?"<value>":"<string>";return{example:`--${p.cli_flag} ${h}`,description:`--${p.cli_flag} maps to ${p.metadata_key} (${p.type}${p.repeatable?", repeatable":""})`}}),l=[Vy(n,r,i,s),...d.map(p=>p.example)].join(" "),u=[`Run "pm create --help --type ${o}" for type-aware required option guidance.`,...t.filter(p=>p==="--title").map(()=>'Title can also be passed as the first positional argument (example: pm create "Your title" --type '+o+").")];a==="strict"&&(u.push('For staged onboarding, retry with "--create-mode progressive".'),zy.has(o)&&u.push('For minimal scheduling inputs, try "--schedule-preset lightweight".')),d.length>0&&u.push(`Required custom field formats: ${d.map(p=>p.description).join("; ")}.`);let m=[...new Set(t.flatMap(p=>{let h=p.split(" ",1)[0],y=F0[h];return y?[y]:[]}))];m.length>0&&u.push(`If the truthful value is an empty collection, use ${m.join(", ")} instead of inventing metadata.`);let g=t.length===1?`Missing required option ${t[0]} for type "${o}"`:`Missing required options ${t.join(", ")} for type "${o}"`;throw new _(g,f.USAGE,{code:"missing_required_option",required:`Provide all required create options and type options for type "${o}" in one invocation.`,examples:[...m.map(p=>`pm create --type ${o} ${p} ...`),l],nextSteps:u,recovery:a==="strict"?{recovery_mode:"compact",missing_required_fields:t,suggested_flags:[...m,...t,"--create-mode progressive"]}:void 0})}function j0(e,t){if(e.has("tags")&&Array.isArray(t.addTags)&&t.addTags.length>0)throw new _("Cannot combine --unset tags with --add-tags",f.USAGE);let n=e.has("tags")?[]:t.tags!==void 0?hi(t.tags):[];return yi(n,t.addTags)}function U0(e,t){if(t.order!==void 0&&t.rank!==void 0&&t.order!==t.rank)throw new _("--order and --rank must match when both are provided",f.USAGE);let n=t.order??t.rank,r=dn(e,"order",n,i=>_e(i,"order"));if(r!==void 0&&!Number.isInteger(r))throw new _("Order must be an integer",f.USAGE);return r}function q0(e,t,n,r,i,s){if(r.completedAt!==void 0&&e!==t.close_status)throw new _("--completed-at requires a terminal create status.",f.USAGE);let o=e!==t.close_status?void 0:r.completedAt===void 0?s:fe(r.completedAt,new Date(s),"completed-at");if(e!==t.close_status)return{closeReason:void 0,completedAt:o,warnings:[]};let a=n.governance.require_close_reason?{explicit:r.closeReason??r.message,resolution:i}:{explicit:r.closeReason};return{closeReason:Zc(a,n.governance.require_close_reason,{operation:"create",status:e}).closeReason,completedAt:o,warnings:[]}}async function G0(e){let{pmRoot:t,type:n,id:r,settings:i,typeRegistry:s,author:o,extensionFieldNames:a,afterDocument:c,beforeDocument:d,historyMessage:l,changedFields:u,nowValue:m,similarityCandidate:g,allowDuplicate:p}=e,h=Ll(t,n,r,i.item_format,s.type_to_folder),y=Tt(t,r),v=xe(),w=c.metadata.parent!==void 0||(c.metadata.dependencies??[]).some(I=>v.resolve(I.kind)?.hierarchy),E=await Xs({pmRoot:t,author:o,ttlSeconds:i.locks.ttl_seconds,waitMs:i.locks.wait_ms,required:w}),S=w,x=[];try{let I=await Ct(t,r,i.locks.ttl_seconds,o,!1,i.governance.force_required_for_stale_lock,i.locks.wait_ms);try{let k=c.metadata.parent!==void 0||c.metadata.dependencies!==void 0&&c.metadata.dependencies.length>0?await Se(t,i.item_format,s.type_to_folder,void 0,i.schema):void 0;if(await X(t,r,i.id_prefix,i.item_format,s.type_to_folder))throw new _(`Item "${r}" already exists`,f.CONFLICT);if(k){let P=H(i.schema);Wi(k,[...k,c.metadata],r,A=>ue(A,P),v)}await Yl({pm_root:t,operation:"create",before:null,after:c,changed_fields:u,sdk:tm({pmRoot:t,settings:i,typeToFolder:s.type_to_folder})});let O=await Qu(t,o,{required:i.governance.duplicate_detection_mode==="strict"&&p!==!0}),W=[];try{i.governance.duplicate_detection_mode==="strict"&&p!==!0&&await rd(g,{pmRoot:t,mode:"strict",threshold:i.governance.duplicate_detection_threshold,limit:i.governance.duplicate_detection_limit,allowDuplicate:!1}),await we(h,xi(c,{format:i.item_format,schema:i.schema,extensionFieldNames:a}));try{let P=Ci({nowIso:m,author:o,op:"create",before:d,after:c,message:l});await Lu(y,P)}catch(P){throw await pl(h),P}S&&(await E(),S=!1),W=await Zu({pmRoot:t,preferredFormat:i.item_format,typeToFolder:s.type_to_folder,schema:i.schema,itemPath:h,document:c})}finally{await O()}x=[...k?js(k,[...k,c.metadata],r):[],...W,...await Me({path:h,scope:"project",op:"create",item_id:c.metadata.id,item_type:c.metadata.type,before:d,after:c,changed_fields:u}),...await Me({path:y,scope:"project",op:"create:history",item_id:c.metadata.id,item_type:c.metadata.type,before:d,after:c,changed_fields:u})],Wl({id:c.metadata.id,op:"create",item_type:c.metadata.type,status:c.metadata.status,current:Vl(c.metadata,u),changed_fields:u})}finally{await I()}}finally{S&&await E()}return x}async function pd(e,t){let n=By(await c0(e)),r=R(process.cwd(),t.path);await $(r);let i=await C(r),s=H(i.schema),o=En(i.schema),a=U(i,F()),c=await D0(n,t,r,i,a);n=c.resolvedOptions;let{typeDefinition:d,type:l,createMode:u}=c,m=YR(n.unset,o),{explicitUnsets:g,clearOptionKeys:p}=L0(n,m);N0(n,m),M0(n);let h=m0(d,n,u,p),y=T(),v=q(ke(n.author),i.author_default),w=JR(n.dep,y,i.id_prefix,v),E=ln("--comment",n.comment,y,v),S=ln("--note",n.note,y,v),x=ln("--learning",n.learning,y,v),I=ud(n.file),k=md(n.test);k.values=await Bn(k.values,v,y);let b=fd(n.doc),O=QR(n.reminder,y),W=ZR(n.event,y),P=o0(n.typeOption),A=sr(l,P.values,a),K=F(),oe=It(K),ae=_i(n.field,K),ye=su(n,o,l),$e=new Set(ye.missing_required_flags),Je=o.definitions.filter(ee=>$e.has(`--${ee.cli_flag}`));P0(ae,ye,m);let xt=f0(A.errors,l),dt=xt.map(ee=>`--type-option ${ee}=<value>`),_n=[...new Set([...h,...dt,...ye.missing_required_flags])].sort((ee,Ko)=>ee.localeCompare(Ko));$0({combinedMissingFlags:_n,typeDefinition:d,missingRequiredCreateFlags:h,missingRequiredTypeOptionKeys:xt,openStatus:s.open_status,type:l,createMode:u,missingRequiredRuntimeFields:Je}),p0(A.errors,l,d,s);let de=await A0({pmRoot:r,settings:i,typeRegistry:a,explicitId:n.id}),je=n.status!==void 0?HR(n.status,s):WR(d,s),pn=n.priority!==void 0?Pi(n.priority):2,M=m.metadataKeys,ve=j0(M,n),He=dn(M,"deadline",n.deadline,ee=>fe(ee,new Date(y),"deadline")),gn=dn(M,"estimated_minutes",n.estimatedMinutes,ee=>wi(ee,"estimated-minutes")),Xe=Q(M,"acceptance_criteria",n.acceptanceCriteria),le=Q(M,"definition_of_ready",n.definitionOfReady),Qe=U0(M,n),Fo=Q(M,"goal",n.goal),ri=Q(M,"objective",n.objective),jb=Q(M,"value",n.value),Ub=Q(M,"impact",n.impact),qb=Q(M,"outcome",n.outcome),Gb=Q(M,"why_now",n.whyNow),Kb=Q(M,"assignee",n.assignee),zb=M.has("author")?void 0:ke(n.author)??v,Bb=Q(M,"parent",n.parent),rl=await x0(Bb,n,M,r),$o=rl.parent,Hb=rl.parentSource,Wb=Q(M,"reviewer",n.reviewer),Vb=dn(M,"risk",n.risk,ee=>Le(Qs(ee),ci,"risk")),Yb=dn(M,"confidence",n.confidence,ee=>eo(ee)),Jb=n.allowMissingParent===!0&&i.validation.parent_reference==="strict_error"?"warn":i.validation.parent_reference,il=i.validation.sprint_release_format,qt=[...c.warnings,...S0(l,de,He,O.values,W.values)],sl=await I0({itemId:de,parent:$o,pmRoot:r,settings:i,typeRegistry:a,policy:Jb});$o=sl.parent,qt.push(...sl.warnings);let ol=Ky(M,"sprint",n.sprint,"sprint",il),Xb=ol.value;qt.push(...ol.warnings);let al=Ky(M,"release",n.release,"release",il),Qb=al.value;qt.push(...al.warnings);let cl=Q(M,"blocked_by",n.blockedBy),dl=await C0({pmRoot:r,settings:i,typeRegistry:a,statusRegistry:s,blockedBy:cl,dependencyValues:w.values,status:je,statusExplicit:n.status!==void 0,nowValue:y,author:v}),jo=dl.dependencyValues;zr(de,jo),qt.push(...await co({pmRoot:r,dependencies:jo,idPrefix:i.id_prefix,itemFormat:i.item_format,typeToFolder:a.type_to_folder,allowUnresolved:n.allowUnresolvedDeps,holders:[{id:de,createdAt:y}],schema:i.schema})),je=dl.status;let Zb=Q(M,"blocked_reason",n.blockedReason),ek=Q(M,"unblock_note",n.unblockNote),tk=Q(M,"reporter",n.reporter),nk=dn(M,"severity",n.severity,ee=>Le(Zs(ee),di,"severity")),rk=Q(M,"environment",n.environment),ik=Q(M,"repro_steps",n.reproSteps),ll=Q(M,"resolution",n.resolution),sk=Q(M,"expected_result",n.expectedResult),ok=Q(M,"actual_result",n.actualResult),ak=Q(M,"affected_version",n.affectedVersion),ck=Q(M,"fixed_version",n.fixedVersion),dk=Q(M,"component",n.component),lk=dn(M,"regression",n.regression,ee=>to(ee)),uk=Q(M,"customer_impact",n.customerImpact),Uo=_d(n.title,"--title"),qo=n.description??"",ii=n.body??"",ul=await rd({title:Uo,description:qo,body:ii},{pmRoot:r,mode:i.governance.duplicate_detection_mode,threshold:i.governance.duplicate_detection_threshold,limit:i.governance.duplicate_detection_limit,allowDuplicate:n.allowDuplicate});qt.push(...wy(ul));let Go=q0(je,s,i,n,ll,y),mk=Go.closeReason,fk=je===s.close_status?y:void 0,_k=Go.completedAt;qt.push(...Go.warnings);let si=cu({id:de,title:Uo,description:qo,type:l,type_options:A.normalized,status:je,closed_at:fk,completed_at:_k,close_reason:mk,priority:pn,tags:ve,created_at:y,updated_at:y,deadline:He,assignee:Kb,author:zb,estimated_minutes:gn,acceptance_criteria:Xe,definition_of_ready:le,order:Qe,goal:Fo,objective:ri,value:jb,impact:Ub,outcome:qb,why_now:Gb,parent:$o,reviewer:Wb,risk:Vb,confidence:Yb,sprint:Xb,release:Qb,blocked_by:cl,blocked_reason:Zb,unblock_note:ek,reporter:tk,severity:nk,environment:rk,repro_steps:ik,resolution:ll,expected_result:sk,actual_result:ok,affected_version:ak,fixed_version:ck,component:dk,regression:lk,customer_impact:uk,dependencies:jo,comments:E.values,notes:S.values,learnings:x.values,files:I.values,tests:k.values,docs:b.values,reminders:O.values,events:W.values,...ae,...ye.values});try{pi(si,K)}catch(ee){throw new _(ee instanceof Error?ee.message:"Invalid extension item field values",f.USAGE)}let pk=Ti({metadata:si,body:ii},{schema:i.schema,extensionFieldNames:oe}),gk={metadata:{},body:""},ml=[...g].sort((ee,Ko)=>ee.localeCompare(Ko)),hk=t0(n.message,ml),fl=e0(si,ii,ml,[...Object.keys(ae),...Object.keys(ye.values??{})]),yk=await G0({pmRoot:r,type:l,id:de,settings:i,typeRegistry:a,author:v,extensionFieldNames:oe,afterDocument:pk,beforeDocument:gk,historyMessage:hk,changedFields:fl,nowValue:y,similarityCandidate:{title:Uo,description:qo,body:ii},allowDuplicate:n.allowDuplicate}),_l=structuredClone(si);u==="strict"&&g.has("dependencies")&&(_l.dependencies=[]);let vk=Cy(de,l,je,s);return Yy(l,He,O.values,W.values)&&Au(`[pm] warning: ${l} '${de}' has no deadline/reminder/event \u2014 it will not appear on the calendar. Add one via 'pm update ${de} --deadline <ISO>' or 'pm update ${de} --event "start=<ISO>,end=<ISO>"'.`),{item:_l,changed_fields:fl,warnings:[...qt,...yk],...Object.fromEntries([["parent_source",Hb],["next_transition",vk],["similarity_advisory",ul]].filter(ee=>ee[1]!==void 0))}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5a6614ac-62fd-5680-9eed-447bfb7a167f")}catch{}})();var vd=[...sd,{canonical:"close-reason",aliases:["close_reason","close-reason"],optionKey:"closeReason",metadataKey:"close_reason"},...od,...so],K0=(()=>{let e=new Map;for(let t of vd)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),go=new Map(vd.map(e=>[e.optionKey,e.canonical])),z0=vd.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", "),B0=new Set(["close_reason","assignee","parent","blocked_by","blocked_reason","unblock_note","dependencies","comments","notes","learnings","files","tests","docs","reminders","events"]),H0=no({depDisableFlagKey:"replaceDeps",fileDisableFlagKey:"replaceFiles",testDisableFlagKey:"replaceTests",docDisableFlagKey:"replaceDocs"});function rv(e){let t={...e,unset:e.unset?[...e.unset]:void 0},n=i=>{let s=t.unset?[...t.unset]:[];s.includes(i)||s.push(i),t.unset=s},r=new Set([...go.keys(),"rank"]);for(let i of r){let s=t[i];if(typeof s!="string"||!Ye(s))continue;let o=i==="rank"?"order":go.get(i)??i;n(o),t[i]=void 0}return qe(e,io(t,H0))}function iv(e,t,n=[]){return oo({raw:e,supportedFields:z0,resolveDefinition:r=>{let i=n.find(o=>{let a=o.toLowerCase();return a===r||a.replaceAll("_","-")===r||a.replaceAll("-","_")===r});return K0.get(r)??ao(r,"update",t)??(i?{optionKey:"field",metadataKey:i}:void 0)}})}var Jy=new Map([["--comment",e=>`pm comments ${e} --add "<text>" --force`],["--file",e=>`pm files ${e} --add "path=<path>,scope=<scope>,note=<note>" --force`],["--doc",e=>`pm docs ${e} --add "path=<path>,scope=<scope>,note=<note>" --force`]]);function Xy(e){let t=e.disallowedFlags.flatMap(r=>{let i=Jy.get(r);return i?[i(e.id)]:[]}),n=e.disallowedFlags.flatMap(r=>{let i=Jy.get(r);return i?[`Replace ${r} with: ${i(e.id)}`]:[]});return new _(e.message,f.USAGE,{code:e.code,required:e.required,why:e.why,...t.length>0?{examples:t}:{},nextSteps:[`Re-run without: ${e.disallowedFlags.join(", ")}`,...n]})}function W0(e,t,n){let r=t.ownershipMetadataBypass===!0,i=t.ownershipDependencyBypass===!0;if(!r&&!i)return;if(r&&i)throw new _("Choose only one package-provided ownership bypass mode.",f.USAGE);let s=(c,d,l)=>{c&&l.push(d)};if(i){let c=[];if(s(t.title!==void 0,"--title",c),s(t.description!==void 0,"--description",c),s(t.body!==void 0,"--body",c),s(t.status!==void 0,"--status",c),s(t.closeReason!==void 0,"--close-reason",c),s(t.priority!==void 0,"--priority",c),s(t.type!==void 0,"--type",c),s(t.tags!==void 0,"--tags",c),s(Array.isArray(t.addTags)&&t.addTags.length>0,"--add-tags",c),s(Array.isArray(t.removeTags)&&t.removeTags.length>0,"--remove-tags",c),s(t.deadline!==void 0,"--deadline",c),s(t.estimatedMinutes!==void 0,"--estimate",c),s(t.acceptanceCriteria!==void 0,"--acceptance-criteria",c),s(Array.isArray(t.addAc)&&t.addAc.length>0,"--add-ac",c),s(Array.isArray(t.removeAc)&&t.removeAc.length>0,"--remove-ac",c),s(t.definitionOfReady!==void 0,"--definition-of-ready",c),s(t.order!==void 0||t.rank!==void 0,"--order/--rank",c),s(t.goal!==void 0,"--goal",c),s(t.objective!==void 0,"--objective",c),s(t.value!==void 0,"--value",c),s(t.impact!==void 0,"--impact",c),s(t.outcome!==void 0,"--outcome",c),s(t.whyNow!==void 0,"--why-now",c),s(t.assignee!==void 0,"--assignee",c),s(t.parent!==void 0,"--parent",c),s(t.reviewer!==void 0,"--reviewer",c),s(t.risk!==void 0,"--risk",c),s(t.confidence!==void 0,"--confidence",c),s(t.sprint!==void 0,"--sprint",c),s(t.release!==void 0,"--release",c),s(t.blockedBy!==void 0,"--blocked-by",c),s(t.blockedReason!==void 0,"--blocked-reason",c),s(t.unblockNote!==void 0,"--unblock-note",c),s(t.reporter!==void 0,"--reporter",c),s(t.severity!==void 0,"--severity",c),s(t.environment!==void 0,"--environment",c),s(t.reproSteps!==void 0,"--repro-steps",c),s(t.resolution!==void 0,"--resolution",c),s(t.expectedResult!==void 0,"--expected-result",c),s(t.actualResult!==void 0,"--actual-result",c),s(t.affectedVersion!==void 0,"--affected-version",c),s(t.fixedVersion!==void 0,"--fixed-version",c),s(t.component!==void 0,"--component",c),s(t.regression!==void 0,"--regression",c),s(t.customerImpact!==void 0,"--customer-impact",c),s(t.depRemove!==void 0,"--dep-remove",c),s(t.replaceDeps===!0,"--replace-deps",c),s(t.replaceTests===!0,"--replace-tests",c),s(t.replaceFiles===!0,"--replace-files",c),s(t.replaceDocs===!0,"--replace-docs",c),s(t.comment!==void 0,"--comment",c),s(t.note!==void 0,"--note",c),s(t.learning!==void 0,"--learning",c),s(t.file!==void 0,"--file",c),s(t.test!==void 0,"--test",c),s(t.doc!==void 0,"--doc",c),s(t.reminder!==void 0,"--reminder",c),s(t.event!==void 0,"--event",c),s(t.typeOption!==void 0,"--type-option",c),s(t.clearDeps===!0,"--clear-deps",c),s(t.clearComments===!0,"--clear-comments",c),s(t.clearNotes===!0,"--clear-notes",c),s(t.clearLearnings===!0,"--clear-learnings",c),s(t.clearFiles===!0,"--clear-files",c),s(t.clearTests===!0,"--clear-tests",c),s(t.clearDocs===!0,"--clear-docs",c),s(t.clearReminders===!0,"--clear-reminders",c),s(t.clearEvents===!0,"--clear-events",c),s(t.clearTypeOptions===!0,"--clear-type-options",c),s(t.force===!0,"--force",c),s(n.size>0,"--unset",c),t.dep===void 0||t.dep.length===0)throw new _("The dependency ownership bypass requires at least one --dep value",f.USAGE);if(c.length>0)throw Xy({id:e,code:"ownership_dependency_bypass_restricted_options",message:`The dependency ownership bypass supports append-only dependency additions via --dep. Remove restricted options: ${c.join(", ")}`,required:"Pass only --dep additions (plus --message/--author) with the dependency ownership bypass.",why:"the dependency ownership bypass is a narrow non-owner override scoped to append-only dependency additions; every other mutation keeps its normal ownership rules.",disallowedFlags:c});return}let o=[];s(t.status!==void 0,"--status",o),s(t.closeReason!==void 0,"--close-reason",o),s(t.assignee!==void 0,"--assignee",o),s(t.parent!==void 0,"--parent",o),s(t.blockedBy!==void 0,"--blocked-by",o),s(t.blockedReason!==void 0,"--blocked-reason",o),s(t.unblockNote!==void 0,"--unblock-note",o),s(t.dep!==void 0,"--dep",o),s(t.depRemove!==void 0,"--dep-remove",o),s(t.replaceDeps===!0,"--replace-deps",o),s(t.replaceTests===!0,"--replace-tests",o),s(t.replaceFiles===!0,"--replace-files",o),s(t.replaceDocs===!0,"--replace-docs",o),s(t.note!==void 0,"--note",o),s(t.learning!==void 0,"--learning",o),s(t.test!==void 0,"--test",o),s(t.reminder!==void 0,"--reminder",o),s(t.event!==void 0,"--event",o),s(t.clearDeps===!0,"--clear-deps",o),s(t.clearComments===!0,"--clear-comments",o),s(t.clearNotes===!0,"--clear-notes",o),s(t.clearLearnings===!0,"--clear-learnings",o),s(t.clearFiles===!0,"--clear-files",o),s(t.clearTests===!0,"--clear-tests",o),s(t.clearDocs===!0,"--clear-docs",o),s(t.clearReminders===!0,"--clear-reminders",o),s(t.clearEvents===!0,"--clear-events",o);let a=[...n].filter(c=>B0.has(c)).sort((c,d)=>c.localeCompare(d)).map(c=>`--unset ${c.replaceAll("_","-")}`);if(o.push(...a),o.length>0)throw Xy({id:e,code:"ownership_metadata_bypass_restricted_options",message:`The metadata ownership bypass only supports non-lifecycle metadata fields and evidence appends. Remove restricted options: ${o.join(", ")}`,required:"Limit the metadata ownership bypass to non-lifecycle metadata fields plus append-only --comment/--file/--doc evidence; route restricted appends and lifecycle changes through their dedicated commands.",why:"the metadata ownership bypass is a non-owner override scoped to metadata maintenance and append-only evidence; lifecycle, ownership, dependency mutations, restricted append fields, and clear/replace operations keep their normal ownership rules.",disallowedFlags:o})}function V0(e,t){let n=se(e,t);if(!n){let r=t.definitions.map(i=>i.id);throw new _(`Invalid --status value "${e}". Allowed: ${r.join(", ")}`,f.USAGE)}return n}function Y0(e){if(e.enforcement==="off"||e.typeWorkflows.length===0)return;let t=zu({typeName:e.typeName,fromStatus:e.fromStatus,toStatus:e.toStatus,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry});if(!t.hasRule||t.allowed)return;let n=se(e.fromStatus,e.statusRegistry)??e.fromStatus,r=se(e.toStatus,e.statusRegistry)??e.toStatus,i=`Disallowed transition for type "${e.typeName}": ${n} -> ${r}. Allowed transitions: ${Bu(t.allowedTransitions)}.`;if(e.enforcement==="strict")throw new _(i,f.USAGE);return`workflow_transition_not_allowed: ${i}`}function J0(e,t){return!e||e.trim()===""||e.trim().toLowerCase()==="now"?t:sv(e)}function sv(e){let t=Date.parse(e);if(!Number.isFinite(t))throw new _(`Invalid dependency created_at timestamp "${e}"`,f.USAGE);return new Date(t).toISOString()}function Vn(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}var X0=["id","kind","type","author","created_at","source_kind"],Q0=["id","kind","type","author","created_at","source_kind"];function ov(e){return e.startsWith("```")||e.includes(`
|
|
21
|
-
`)||/^(?:[-*+]\s+)?(?:id|kind|type|author|created_at|source_kind)\s*[:=]/i.test(e)?!0:wn(e)}function av(e){return typeof e=="string"?zt(e)??e.trim():e}function Z0(e,t,n,r){return e?(De(e,"--dep","Use --clear-deps to clear dependencies."),{additions:e.map(s=>{let o=s.trim(),a=ov(o);Kr(o,a);let c=a?te(s,"--dep"):{id:o,kind:"related"};a&&be(c,"--dep",X0);let d=c.id?.trim(),l=av((c.kind??c.type)?.trim());if(!d||!l)throw new _("--dep requires id and kind, or a bare item id to add a related dependency",f.USAGE);if(d.toLowerCase()==="undefined")throw new _(`--dep id must not use placeholder token "${d}". Use --clear-deps to clear dependencies.`,f.USAGE);let u=mr(Vn(c.source_kind)),m=Vn(c.author);return{id:fr(d,t,u),kind:Le(l,rr,"dependency kind"),created_at:J0(c.created_at,n),author:m??r,source_kind:u??"cli:update:dep",author_source:m?"asserted":"detected"}})}):{additions:[]}}function eO(e,t){return e?(De(e,"--dep-remove"),e.map(n=>{let r=n.trim();if(!r)throw new _("--dep-remove requires id or key/value selectors",f.USAGE);let i=ov(r);if(Kr(r,i,"--dep-remove"),i){let s=te(r,"--dep-remove");be(s,"--dep-remove",Q0);let o=s.id?.trim();if(!o)throw new _("--dep-remove key/value form requires id=<value>",f.USAGE);if(o.toLowerCase()==="undefined")throw new _(`--dep-remove id must not use placeholder token "${o}"`,f.USAGE);let a=av(Vn(s.kind??s.type)),c=mr(Vn(s.source_kind)),d=Vn(s.author),l=Vn(s.created_at);return{id:fr(o,t,c),kind:a?Le(a,rr,"dependency kind"):void 0,source_kind:c,author:d,created_at:l?sv(l):void 0}}if(r.toLowerCase()==="undefined")throw new _(`--dep-remove id must not use placeholder token "${r}"`,f.USAGE);return{id:Ot(r,t)}})):[]}function ho(e){let t=e.source_kind?.trim().toLowerCase()??"";return[e.id.trim().toLowerCase(),e.kind,t].join("\0")}function tO(e){let t=e.source_kind?.trim().toLowerCase()??"",n=e.author?.trim().toLowerCase()??"",r=e.created_at?.trim()??"",i=Date.parse(r),s=Number.isFinite(i)?new Date(i).toISOString():r;return[e.id.trim().toLowerCase(),e.kind,t,n,s].join("\0")}function nO(e,t,n,r){let i=[...e??[]],s=!1;if(t===void 0){let o=i.filter(a=>a.kind!=="blocked_by");return o.length!==i.length&&(i=o,s=!0),s?{dependencies:i.length>0?i:void 0,changed:!0}:{dependencies:e,changed:!1}}return i.some(o=>o.kind==="blocked_by"&&o.id===t)||(i.push({id:t,kind:"blocked_by",created_at:n,author:r,source_kind:"cli:update:blocked_by",author_source:"detected"}),s=!0),s?{dependencies:i.length>0?i:void 0,changed:!0}:{dependencies:e,changed:!1}}async function rO(e,t,n,r,i,s){if(e===void 0||t)return{};let o=e.trim();if(o.length===0)return{};let a=await X(n,Ot(o,r),r,i,s);return a?{id:a.id}:{unresolved:o}}function iO(e,t,n,r,i){let s=nO(e.dependencies,t,n,r);s.changed&&(s.dependencies===void 0?delete e.dependencies:e.dependencies=s.dependencies,i.includes("dependencies")||i.push("dependencies"))}function sO(e){return`${e.path}::${e.scope}`}function oO(e){return`${e.path}::${e.scope}`}function aO(e){return`${e.command}::${e.path??""}::${e.scope}::${e.pm_context_mode??""}::${e.workspace_context_mode??""}`}function cv(e,t){return!(e.id.trim().toLowerCase()!==t.id.trim().toLowerCase()||t.kind&&e.kind!==t.kind||t.source_kind!==void 0&&e.source_kind?.trim().toLowerCase()!==t.source_kind.trim().toLowerCase()||t.author!==void 0&&e.author?.trim().toLowerCase()!==t.author.trim().toLowerCase()||t.created_at!==void 0&&(e.created_at===void 0||!Number.isFinite(Date.parse(e.created_at))||new Date(Date.parse(e.created_at)).toISOString()!==t.created_at))}function Qy(e,t){let n=ir("update",e);if(!n)throw new _(`Unsupported command_option_policies option "${e}" for update command on type "${t}"`,f.CONFLICT);return n}function cO(e,t,n){let r=new Set,i=(s,o)=>{o&&r.add(s)};if(i("title",e.title!==void 0),i("description",e.description!==void 0),i("body",e.body!==void 0),i("status",e.status!==void 0),i("closeReason",e.closeReason!==void 0),i("priority",e.priority!==void 0),i("type",e.type!==void 0),i("tags",e.tags!==void 0||Array.isArray(e.addTags)&&e.addTags.length>0||Array.isArray(e.removeTags)&&e.removeTags.length>0),i("deadline",e.deadline!==void 0),i("estimatedMinutes",e.estimatedMinutes!==void 0),i("acceptanceCriteria",e.acceptanceCriteria!==void 0||Array.isArray(e.addAc)&&e.addAc.length>0||Array.isArray(e.removeAc)&&e.removeAc.length>0),i("definitionOfReady",e.definitionOfReady!==void 0),i("order",e.order!==void 0||e.rank!==void 0),i("goal",e.goal!==void 0),i("objective",e.objective!==void 0),i("value",e.value!==void 0),i("impact",e.impact!==void 0),i("outcome",e.outcome!==void 0),i("whyNow",e.whyNow!==void 0),i("author",e.author!==void 0),i("message",e.message!==void 0),i("assignee",e.assignee!==void 0),i("parent",e.parent!==void 0),i("reviewer",e.reviewer!==void 0),i("risk",e.risk!==void 0),i("confidence",e.confidence!==void 0),i("sprint",e.sprint!==void 0),i("release",e.release!==void 0),i("blockedBy",e.blockedBy!==void 0),i("blockedReason",e.blockedReason!==void 0),i("unblockNote",e.unblockNote!==void 0),i("reporter",e.reporter!==void 0),i("severity",e.severity!==void 0),i("environment",e.environment!==void 0),i("reproSteps",e.reproSteps!==void 0),i("resolution",e.resolution!==void 0),i("expectedResult",e.expectedResult!==void 0),i("actualResult",e.actualResult!==void 0),i("affectedVersion",e.affectedVersion!==void 0),i("fixedVersion",e.fixedVersion!==void 0),i("component",e.component!==void 0),i("regression",e.regression!==void 0),i("customerImpact",e.customerImpact!==void 0),i("dep",e.dep!==void 0),i("depRemove",e.depRemove!==void 0),i("dep",e.replaceDeps===!0),i("comment",e.comment!==void 0),i("note",e.note!==void 0),i("learning",e.learning!==void 0),i("file",e.file!==void 0),i("test",e.test!==void 0),i("test",e.replaceTests===!0),i("file",e.replaceFiles===!0),i("doc",e.replaceDocs===!0),i("doc",e.doc!==void 0),i("reminder",e.reminder!==void 0),i("event",e.event!==void 0),i("typeOption",e.typeOption!==void 0),i("field",e.field!==void 0),i("force",e.force===!0),i("ownershipMetadataBypass",e.ownershipMetadataBypass===!0),i("ownershipDependencyBypass",e.ownershipDependencyBypass===!0),i("dep",e.clearDeps===!0),i("comment",e.clearComments===!0),i("note",e.clearNotes===!0),i("learning",e.clearLearnings===!0),i("file",e.clearFiles===!0),i("test",e.clearTests===!0),i("doc",e.clearDocs===!0),i("reminder",e.clearReminders===!0),i("event",e.clearEvents===!0),i("typeOption",e.clearTypeOptions===!0),e.unset&&e.unset.length>0){let s=iv(e.unset,t,n);for(let o of s.optionKeys)i(o,!0)}return r}function dO(e,t,n,r,i){let s=li(e,n);if(!s)throw new _(`Invalid type value "${e}"`,f.USAGE);let o=vn(s,"update",[]);if(o.errors.length>0)throw new _(o.errors.join("; "),f.CONFLICT);let a=cO(t,r,i);for(let c of o.disabled)if(a.has(Qy(c,e)))throw new _(`Option ${Ie("update",c)} is disabled for type "${e}" by command_option_policies`,f.USAGE);for(let c of o.required)if(!a.has(Qy(c,e)))throw new _(`Missing required option ${Ie("update",c)} for type "${e}"`,f.USAGE)}var lO=new Set(["order","rank"]),uO=Wo.filter(e=>!lO.has(e)),dv=["tags","closeReason",...uO],mO=["title","description","body","status","closeReason","completedAt","priority","type",...Wo,"dep","depRemove","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],fO=[{optionKey:"deadline",metadataKey:"deadline",transform:(e,t)=>fe(e,t.nowValue,"deadline")},{optionKey:"estimatedMinutes",metadataKey:"estimated_minutes",transform:e=>wi(e,"estimated-minutes")},{optionKey:"acceptanceCriteria",metadataKey:"acceptance_criteria",transform:e=>e},{optionKey:"definitionOfReady",metadataKey:"definition_of_ready"},{optionKey:"goal",metadataKey:"goal"},{optionKey:"objective",metadataKey:"objective"},{optionKey:"value",metadataKey:"value"},{optionKey:"impact",metadataKey:"impact"},{optionKey:"outcome",metadataKey:"outcome"},{optionKey:"whyNow",metadataKey:"why_now"}],_O=[{optionKey:"reviewer",metadataKey:"reviewer"},{optionKey:"risk",metadataKey:"risk",transform:e=>Le(Qs(e),ci,"risk")},{optionKey:"confidence",metadataKey:"confidence",transform:e=>eo(e)}],pO=[{optionKey:"blockedReason",metadataKey:"blocked_reason"},{optionKey:"unblockNote",metadataKey:"unblock_note"},{optionKey:"reporter",metadataKey:"reporter"},{optionKey:"severity",metadataKey:"severity",transform:e=>Le(Zs(e),di,"severity")},{optionKey:"environment",metadataKey:"environment"},{optionKey:"reproSteps",metadataKey:"repro_steps"},{optionKey:"resolution",metadataKey:"resolution"},{optionKey:"expectedResult",metadataKey:"expected_result"},{optionKey:"actualResult",metadataKey:"actual_result"},{optionKey:"affectedVersion",metadataKey:"affected_version"},{optionKey:"fixedVersion",metadataKey:"fixed_version"},{optionKey:"component",metadataKey:"component"},{optionKey:"regression",metadataKey:"regression",transform:e=>to(e)},{optionKey:"customerImpact",metadataKey:"customer_impact"}];function yd(e,t,n){for(let r of e){let i=t[r.optionKey],s=n.clearItemMetadataKeys.has(r.metadataKey);if(!(i===void 0&&!s)){if(s){delete n.metadataRecord[r.metadataKey],n.changedFields.push(r.metadataKey);continue}if(typeof i!="string")throw new _(`${Ie("update",String(r.optionKey))} must be a string value`,f.USAGE);n.metadataRecord[r.metadataKey]=r.transform?r.transform(i,n):i.trim(),n.changedFields.push(r.metadataKey)}}}async function gO(e){return rv(await vi(e,[["body","--body"],["description","--description"]],[["dep","--dep"],["depRemove","--dep-remove"],["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"],["field","--field"]]))}async function hO(e){return Bt(e)?await gO(e):rv(e)}function yO(e){return[{enabled:e.clearDeps||e.replaceDeps,optionKey:"dep",clearFlag:"--clear-deps",valueFlag:"--dep",values:e.dep,metadataKey:"dependencies"},{enabled:e.clearComments,optionKey:"comment",clearFlag:"--clear-comments",valueFlag:"--comment",values:e.comment,metadataKey:"comments"},{enabled:e.clearNotes,optionKey:"note",clearFlag:"--clear-notes",valueFlag:"--note",values:e.note,metadataKey:"notes"},{enabled:e.clearLearnings,optionKey:"learning",clearFlag:"--clear-learnings",valueFlag:"--learning",values:e.learning,metadataKey:"learnings"},{enabled:e.clearFiles||e.replaceFiles,optionKey:"file",clearFlag:"--clear-files",valueFlag:"--file",values:e.file,metadataKey:"files"},{enabled:e.clearTests||e.replaceTests,optionKey:"test",clearFlag:"--clear-tests",valueFlag:"--test",values:e.test,metadataKey:"tests"},{enabled:e.clearDocs||e.replaceDocs,optionKey:"doc",clearFlag:"--clear-docs",valueFlag:"--doc",values:e.doc,metadataKey:"docs"},{enabled:e.clearReminders,optionKey:"reminder",clearFlag:"--clear-reminders",valueFlag:"--reminder",values:e.reminder,metadataKey:"reminders"},{enabled:e.clearEvents,optionKey:"event",clearFlag:"--clear-events",valueFlag:"--event",values:e.event,metadataKey:"events"},{enabled:e.clearTypeOptions,optionKey:"typeOption",clearFlag:"--clear-type-options",valueFlag:"--type-option",values:e.typeOption,metadataKey:"type_options"}]}function gd(e){if(e.enabled&&(!e.values||e.values.length===0))throw new _(`${e.replaceFlag} requires at least one ${e.valueFlag} entry`,f.USAGE);if(e.enabled&&e.clearEnabled)throw new _(`${e.replaceFlag} cannot be combined with ${e.clearFlag}`,f.USAGE)}function vO(e){let t=(e.addAc?.length??0)>0||(e.removeAc?.length??0)>0;if(e.acceptanceCriteria!==void 0&&t)throw new _("Cannot combine --acceptance-criteria replacement with --add-ac or --remove-ac. Use --remove-ac and --add-ac together for an atomic one-entry repair.",f.USAGE,{code:"acceptance_criteria_mutation_conflict",reason:"replacement_and_additive_mutation_combined",nextSteps:["Use --acceptance-criteria alone to replace the complete list.","Use --remove-ac <old> --add-ac <new> to repair one criterion without replacing unrelated entries."]});if(e.replaceDeps===!0&&(e.dep===void 0||e.dep.length===0))throw new _("--replace-deps requires at least one --dep entry",f.USAGE);if(e.replaceDeps===!0&&e.depRemove!==void 0&&e.depRemove.length>0)throw new _("--replace-deps cannot be combined with --dep-remove",f.USAGE);gd({enabled:e.replaceTests===!0,values:e.test,replaceFlag:"--replace-tests",clearEnabled:e.clearTests===!0,clearFlag:"--clear-tests",valueFlag:"--test"}),gd({enabled:e.replaceFiles===!0,values:e.file,replaceFlag:"--replace-files",clearEnabled:e.clearFiles===!0,clearFlag:"--clear-files",valueFlag:"--file"}),gd({enabled:e.replaceDocs===!0,values:e.doc,replaceFlag:"--replace-docs",clearEnabled:e.clearDocs===!0,clearFlag:"--clear-docs",valueFlag:"--doc"})}function wO(e){for(let t of e.definitions){if(!t.enabled)continue;let n=t.optionKey==="dep"&&e.options.replaceDeps===!0||t.optionKey==="test"&&e.options.replaceTests===!0||t.optionKey==="file"&&e.options.replaceFiles===!0||t.optionKey==="doc"&&e.options.replaceDocs===!0;if(t.values&&t.values.length>0&&!n)throw new _(`Cannot combine ${t.clearFlag} with ${t.valueFlag}`,f.USAGE);e.clearOptionKeys.add(t.optionKey),e.clearItemMetadataKeys.add(t.metadataKey)}}function bO(e){let t={};for(let n of dv)t[String(n)]=e[n]!==void 0;return t.order=e.order!==void 0||e.rank!==void 0,t}function kO(e,t){let n=bO(e);for(let[r,i]of Object.entries(n)){if(!i||!t.optionKeys.has(r))continue;let s=go.get(r)??r;throw new _(`Cannot combine --unset ${s} with ${Ie("update",r)}`,f.USAGE)}if(t.metadataKeys.has("acceptance_criteria")){if(Array.isArray(e.addAc)&&e.addAc.length>0)throw new _("Cannot combine --unset acceptance-criteria with --add-ac",f.USAGE);if(Array.isArray(e.removeAc)&&e.removeAc.length>0)throw new _("Cannot combine --unset acceptance-criteria with --remove-ac",f.USAGE)}if(t.metadataKeys.has("tags")){if(Array.isArray(e.addTags)&&e.addTags.length>0)throw new _("Cannot combine --unset tags with --add-tags",f.USAGE);if(Array.isArray(e.removeTags)&&e.removeTags.length>0)throw new _("Cannot combine --unset tags with --remove-tags",f.USAGE)}}function EO(e){let t=(n,r)=>{let i=go.get(r),s=i?`Use --unset ${i} to clear this field.`:void 0;ro(n,Ie("update",r),s)};for(let n of dv)t(e[n],String(n));t(e.order??e.rank,"order"),De(e.reminder,"--reminder","Use --clear-reminders to clear reminders."),De(e.event,"--event","Use --clear-events to clear linked events.")}function SO(e,t){let n={};for(let r of mO)n[String(r)]=e[r]!==void 0;return n.tags=e.tags!==void 0,n.addTags=Array.isArray(e.addTags)&&e.addTags.length>0,n.removeTags=Array.isArray(e.removeTags)&&e.removeTags.length>0,n.addAc=Array.isArray(e.addAc)&&e.addAc.length>0,n.removeAc=Array.isArray(e.removeAc)&&e.removeAc.length>0,n.order=e.order!==void 0,n.rank=e.rank!==void 0,n.replaceDeps=e.replaceDeps===!0,n.replaceTests=e.replaceTests===!0,n.replaceFiles=e.replaceFiles===!0,n.replaceDocs=e.replaceDocs===!0,n.unset=e.unset!==void 0&&e.unset.length>0,n.clearDeps=e.clearDeps===!0,n.clearComments=e.clearComments===!0,n.clearNotes=e.clearNotes===!0,n.clearLearnings=e.clearLearnings===!0,n.clearFiles=e.clearFiles===!0,n.clearTests=e.clearTests===!0,n.clearDocs=e.clearDocs===!0,n.clearReminders=e.clearReminders===!0,n.clearEvents=e.clearEvents===!0,n.clearTypeOptions=e.clearTypeOptions===!0,n.runtimeFields=Object.keys(t).length>0,n}async function xO(e){let t=await X(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await ur(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await ge(t,{schema:e.settings.schema});return{item:n.metadata,changed_fields:[],warnings:["noop_no_update_fields"]}}async function TO(e){if(!(!e.fieldFlags.dep&&!e.fieldFlags.blockedBy&&!e.fieldFlags.parent&&!e.clearedMetadataKeys.has("parent")))return Se(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}function IO(e){e.before&&Wi(e.before,e.before.map(t=>t.id===e.document.metadata.id?e.document.metadata:t),e.document.metadata.id,t=>ue(t,e.statusRegistry),xe())}function AO(e){if(e.order!==void 0&&e.rank!==void 0&&e.order!==e.rank)throw new _("--order and --rank must match when both are provided",f.USAGE)}async function CO(e){if(e.options.parent===void 0||e.unsetTargets.metadataKeys.has("parent"))return{resolvedParentValue:void 0,warnings:[]};let t=Bi(Li(e.options.parent),e.settings.id_prefix);if(qi(t))return{resolvedParentValue:t,warnings:[]};if(Mi(e.id,t,e.settings.id_prefix),await X(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder))return{resolvedParentValue:t,warnings:[]};let r=Ot(t,e.settings.id_prefix);return{resolvedParentValue:t,warnings:Ni(r,e.parentReferencePolicy).warnings}}function RO(e){return e.unresolved===void 0?[]:[`blocked_by_unresolved:${e.unresolved}`]}async function OO(e){if(e.workflowEnforcement==="off"||e.typeWorkflows.length===0||!e.fieldFlags.status||e.options.status===void 0)return[];let t=await X(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await ur(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await ge(t,{schema:e.settings.schema}),r=e.options.type!==void 0?ut(e.options.type,e.typeRegistry)??e.options.type:n.metadata?.type??"",i=Y0({enforcement:e.workflowEnforcement,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry,typeName:r,fromStatus:n.metadata?.status??"",toStatus:e.options.status});return i?[i]:[]}async function DO(e){if(!e.fieldFlags.status||se(e.options.status,e.statusRegistry)!==e.statusRegistry.close_status)return;let n=Object.entries(e.fieldFlags).filter(([a,c])=>c&&a!=="status"&&a!=="closeReason"&&a!=="completedAt").map(([a])=>a),r=[],i=[];if(n.length>0){let a=qe(e.options,{...e.options,status:void 0,closeReason:void 0,message:void 0}),c=await oD(e.id,a,e.global);i=c.changed_fields,r.push(...c.warnings)}let s=await ly(e.id,e.options.closeReason,{author:e.options.author,message:e.options.message,force:e.options.force,completedAt:e.options.completedAt},e.global),o=[...e.workflowTransitionWarnings,...r,...s.warnings,"auto_routed_from_update_to_close"];return{item:s.item,changed_fields:[...i,...s.changed_fields],warnings:o}}function LO(e,t,n,r){return t.title!==void 0&&(e.metadata.title=_d(t.title,"--title"),r.push("title")),t.description!==void 0&&(e.metadata.description=t.description,r.push("description")),t.body!==void 0&&(e.body=t.body,r.push("body")),se(e.metadata.status,n)??e.metadata.status}var NO=["closed_at","completed_at","close_reason","resolution","expected_result","actual_result","fixed_version"];function MO(e,t){for(let n of NO)e[n]!==void 0&&(delete e[n],t.push(n))}function PO(e,t,n,r,i){let s=V0(n,t.statusRegistry);if(e.metadata.status=s,i.push("status"),s===t.statusRegistry.close_status&&(e.metadata.closed_at===void 0||e.metadata.closed_at===null)){e.metadata.closed_at=t.nowIso,e.metadata.completed_at=t.nowIso,i.push("closed_at","completed_at");return}!ue(s,t.statusRegistry)&&ue(r,t.statusRegistry)&&MO(e.metadata,i)}function FO(e,t,n,r){if(t.options.status!==void 0&&PO(e,t,t.options.status,n,r),t.options.completedAt!==void 0){if(!ue(e.metadata.status,t.statusRegistry))throw new _("--completed-at can only be set on a terminal item",f.USAGE);e.metadata.completed_at=fe(t.options.completedAt,new Date(t.nowIso),"completed-at"),r.push("completed_at")}}function $O(e,t,n,r){if(t.options.closeReason!==void 0||t.clearItemMetadataKeys.has("close_reason")){if(t.clearItemMetadataKeys.has("close_reason"))delete e.metadata.close_reason;else{let i=t.options.closeReason?.trim()??"";if(i.length===0)throw new _("--close-reason must not be empty",f.USAGE);e.metadata.close_reason=i}r.push("close_reason");return}t.options.status!==void 0&&ue(n,t.statusRegistry)&&!ue(e.metadata.status,t.statusRegistry)&&e.metadata.close_reason!==void 0&&(delete e.metadata.close_reason,r.push("close_reason"))}function jO(e,t,n,r){FO(e,t,n,r),$O(e,t,n,r)}function UO(e,t,n){let r=ut(e.metadata.type,t.typeRegistry)??e.metadata.type;if(t.options.priority!==void 0&&(e.metadata.priority=Pi(t.options.priority),n.push("priority")),t.options.type!==void 0){let i=ut(t.options.type,t.typeRegistry);if(!i)throw new _($i(t.options.type,t.typeRegistry.types,bi(t.pmRoot,t.settings.schema)),f.USAGE);e.metadata.type=i,r=i,n.push("type")}return dO(r,t.options,t.typeRegistry,t.runtimeFieldRegistry,t.extensionFieldNames),qO(e,t,r,n),r}function qO(e,t,n,r){if(t.options.typeOption!==void 0||t.clearItemMetadataKeys.has("type_options")){if(t.clearItemMetadataKeys.has("type_options"))delete e.metadata.type_options;else{let s=mo(t.options.typeOption??[]),o=sr(n,s,t.typeRegistry);if(o.errors.length>0)throw new _(o.errors.join("; "),f.USAGE);e.metadata.type_options=o.normalized}r.push("type_options");return}if(t.options.type===void 0||e.metadata.type_options===void 0)return;let i=sr(n,e.metadata.type_options,t.typeRegistry);if(i.errors.length>0)throw new _(`Current type options are incompatible with type "${n}". ${i.errors.join("; ")}. Use --clear-type-options to clear them.`,f.USAGE);e.metadata.type_options=i.normalized}function GO(e,t){let n=new Set(t.map(i=>ho(i))),r=new Set;return e.filter(i=>{if(!n.has(ho(i)))return!0;let s=tO(i);return r.has(s)?!1:(r.add(s),!0)})}function KO(e,t,n){let r=t.filter(i=>!e.some(s=>cv(s,i)));if(r.length!==0)throw new _(`Dependency removal did not match ${r.length===1?"a stored edge":"stored edges"}.`,f.NOT_FOUND,{code:"dependency_remove_no_match",reason:"selector_not_found",unmatched_selectors:r,available_dependencies:e.map(i=>({id:i.id,kind:i.kind,source_kind:i.source_kind,author:i.author,created_at:i.created_at})),why:"Failing on a zero-match selector prevents a mistyped dependency removal from being reported as successful.",nextSteps:[`Inspect the current item with: pm get ${n} --full`,"Retry --dep-remove with the exact id plus any kind, source_kind, author, or created_at selectors needed to identify one stored row."]})}function zO(e,t,n){if(t.options.dep===void 0&&t.options.depRemove===void 0&&!t.clearItemMetadataKeys.has("dependencies"))return;let r=t.clearItemMetadataKeys.has("dependencies")?[]:[...e.metadata.dependencies??[]];if(t.dependencyUpdates.additions.length>0){r=GO(r,t.dependencyUpdates.additions);let i=new Set(r.map(s=>ho(s)));for(let s of t.dependencyUpdates.additions){let o=ho(s);i.has(o)||(r.push(s),i.add(o))}}t.dependencyRemovals.length>0&&(KO(r,t.dependencyRemovals,e.metadata.id),r=r.filter(i=>!t.dependencyRemovals.some(s=>cv(i,s)))),r.length===0?delete e.metadata.dependencies:e.metadata.dependencies=r,n.push("dependencies")}function BO(e,t,n){hd(e,"comments",t.options.comment,t.commentUpdates.values,t.clearItemMetadataKeys,n),hd(e,"notes",t.options.note,t.noteUpdates.values,t.clearItemMetadataKeys,n),hd(e,"learnings",t.options.learning,t.learningUpdates.values,t.clearItemMetadataKeys,n)}function hd(e,t,n,r,i,s){n===void 0&&!i.has(t)||(i.has(t)||!r||r.length===0?delete e.metadata[t]:e.metadata[t]=[...e.metadata[t]??[],...r],s.push(t))}function HO(e,t,n){Zy(e,"files",t.options.file,t.fileUpdates.values,sO,t.options.replaceFiles===!0,t.clearItemMetadataKeys,n),WO(e,t,n),Zy(e,"docs",t.options.doc,t.docUpdates.values,oO,t.options.replaceDocs===!0,t.clearItemMetadataKeys,n)}function Zy(e,t,n,r,i,s,o,a){if(!(n===void 0&&!o.has(t))){if(s)e.metadata[t]=r;else if(o.has(t)||!r||r.length===0)delete e.metadata[t];else{let c=[...e.metadata[t]??[]],d=new Set(c.map(l=>i(l)));for(let l of r){let u=i(l);d.has(u)||(c.push(l),d.add(u))}e.metadata[t]=c}a.push(t)}}function WO(e,t,n){t.options.test===void 0&&!t.clearItemMetadataKeys.has("tests")||(t.clearItemMetadataKeys.has("tests")&&t.options.replaceTests===!0?e.metadata.tests=ev(t.testUpdates.values)??[]:t.clearItemMetadataKeys.has("tests")||!t.testUpdates.values||t.testUpdates.values.length===0?delete e.metadata.tests:e.metadata.tests=ev([...e.metadata.tests??[],...t.testUpdates.values]),e.metadata.tests!==void 0&&e.metadata.tests.length===0&&delete e.metadata.tests,n.push("tests"))}function ev(e){if(!e||e.length===0)return;let t=[],n=new Set;for(let r of e){let i=aO(r);n.has(i)||(t.push(r),n.add(i))}return t}function VO(e,t,n){let r=t.options.addTags,i=t.options.removeTags,s=Array.isArray(r)&&r.length>0||Array.isArray(i)&&i.length>0;if(t.options.tags!==void 0||t.clearItemMetadataKeys.has("tags")||s){let o=t.clearItemMetadataKeys.has("tags")?[]:t.options.tags!==void 0?hi(t.options.tags):Array.isArray(e.metadata.tags)?[...e.metadata.tags]:[];e.metadata.tags=tu(yi(o,r),i),n.changedFields.push("tags")}yd(fO,t.options,n),JO(e,t,n.changedFields)}function YO(e,t,n){let r=t.options.addAc,i=t.options.removeAc;if(!(Array.isArray(r)&&r.length>0)&&!(Array.isArray(i)&&i.length>0))return;let s=eu(At(e.metadata.acceptance_criteria),r,i);if(s.unmatchedRemovals.length>0)throw new _(`Acceptance criteria removal did not match: ${s.unmatchedRemovals.join(", ")}`,f.NOT_FOUND,{code:"acceptance_criteria_remove_unmatched",reason:"exact_match_not_found",field:"acceptance_criteria",unmatched:s.unmatchedRemovals,why:"Lossless removal fails instead of silently applying the remaining mutations when an exact selector is wrong.",nextSteps:["Read the current acceptance_criteria value and retry with the exact criterion text.","Use --acceptance-criteria alone only when replacing the complete list is intentional."]});let o=s.criteria.join("; ");e.metadata.acceptance_criteria!==o&&(o===""&&e.metadata.acceptance_criteria===void 0||(e.metadata.acceptance_criteria=o,n.changedFields.includes("acceptance_criteria")||n.changedFields.push("acceptance_criteria")))}function JO(e,t,n){let r=t.options.order??t.options.rank;if(!(r===void 0&&!t.clearItemMetadataKeys.has("order"))){if(t.clearItemMetadataKeys.has("order"))delete e.metadata.order;else{let i=_e(r??"","order");if(!Number.isInteger(i))throw new _("Order must be an integer",f.USAGE);e.metadata.order=i}n.push("order")}}function XO(e,t,n,r){QO(e,t,n.changedFields),ZO(e,t,n.changedFields),yd(_O,t.options,n),tv(e,t,"sprint",r,n.changedFields),tv(e,t,"release",r,n.changedFields),eD(e,t,n.changedFields),yd(pO,t.options,n)}function QO(e,t,n){if(!(t.options.assignee===void 0&&!t.clearItemMetadataKeys.has("assignee"))){if(t.clearItemMetadataKeys.has("assignee"))delete e.metadata.assignee;else{let r=t.options.assignee?.trim()??"";if(r==="")throw new _("--assignee must not be empty. Use --unset assignee to clear it.",f.USAGE);e.metadata.assignee=r}n.push("assignee")}}function ZO(e,t,n){t.options.parent===void 0&&!t.clearItemMetadataKeys.has("parent")||(t.clearItemMetadataKeys.has("parent")?delete e.metadata.parent:e.metadata.parent=t.resolvedParentValue??"",n.push("parent"))}function tv(e,t,n,r,i){if(!(t.options[n]===void 0&&!t.clearItemMetadataKeys.has(n))){if(t.clearItemMetadataKeys.has(n))delete e.metadata[n];else{let s=Fi(n,t.options[n]??"",t.settings.validation.sprint_release_format);e.metadata[n]=s.value,r.push(...s.warnings)}i.push(n)}}function eD(e,t,n){t.options.blockedBy===void 0&&!t.clearItemMetadataKeys.has("blocked_by")||(t.clearItemMetadataKeys.has("blocked_by")?delete e.metadata.blocked_by:e.metadata.blocked_by=t.options.blockedBy?.trim()??"",n.push("blocked_by"),(t.clearItemMetadataKeys.has("blocked_by")||t.resolvedBlockedByDependencyId!==void 0)&&iO(e.metadata,t.resolvedBlockedByDependencyId,t.nowIso,t.author,n))}function tD(e,t,n){(t.options.reminder!==void 0||t.clearItemMetadataKeys.has("reminders"))&&(t.clearItemMetadataKeys.has("reminders")?delete e.metadata.reminders:e.metadata.reminders=lo(t.options.reminder??[],t.nowValue,{valueMode:"trimmed"}),n.push("reminders")),(t.options.event!==void 0||t.clearItemMetadataKeys.has("events"))&&(t.clearItemMetadataKeys.has("events")?delete e.metadata.events:e.metadata.events=uo(t.options.event??[],t.nowValue,{allDayEmptyGuard:"truthy",recurrenceEmptyNumericGuard:"truthy"}),n.push("events"))}function nD(e,t,n){nv(e,t.runtimeFieldRegistry.definitions.map(i=>i.metadata_key),t.clearItemMetadataKeys,n),nv(e,t.extensionFieldNames,t.clearItemMetadataKeys,n);for(let[i,s]of Object.entries(t.runtimeFieldUpdates)){if(t.clearItemMetadataKeys.has(i)){let o=i.replaceAll("_","-"),c=t.runtimeFieldRegistry.definitions.find(d=>d.metadata_key===i)?.cli_flag??o;throw new _(`Cannot combine --unset ${o} with --${c}`,f.USAGE)}mt(e[i],s)||(e[i]=s,n.push(i))}let r=_i(t.options.field,t.extensionRegistrations);for(let i of Object.keys(r))if(t.clearItemMetadataKeys.has(i))throw new _(`Cannot combine --unset ${i.replaceAll("_","-")} with --field ${i}=...`,f.USAGE);for(let[i,s]of Object.entries(r))mt(e[i],s)||(e[i]=s,n.push(i))}function nv(e,t,n,r){for(let i of t)!n.has(i)||e[i]===void 0||(delete e[i],r.push(i))}function rD(e,t){let n=structuredClone(e.metadata),r=e.body,i=[],s=[],o=LO(e,t.options,t.statusRegistry,i),a=e.metadata,c={metadataRecord:a,clearItemMetadataKeys:t.clearItemMetadataKeys,changedFields:i,nowValue:t.nowValue};jO(e,t,o,i),UO(e,t,i),zO(e,t,i),BO(e,t,i),HO(e,t,i),VO(e,t,c),YO(e,t,c),XO(e,t,c,s),(t.options.dep!==void 0||t.options.depRemove!==void 0||t.options.blockedBy!==void 0||t.clearItemMetadataKeys.has("dependencies")||t.clearItemMetadataKeys.has("blocked_by"))&&zr(e.metadata.id,e.metadata.dependencies),se(e.metadata.status,t.statusRegistry)===t.statusRegistry.canceled_status&&e.metadata.assignee!==void 0&&(delete e.metadata.assignee,i.includes("assignee")||i.push("assignee")),tD(e,t,i),nD(a,t,i);try{pi(a,t.extensionRegistrations,{skipDefaultFields:t.clearItemMetadataKeys})}catch(u){throw new _(u instanceof Error?u.message:"Invalid extension item field values",f.USAGE)}let d=e.metadata,l=[...new Set(i)].filter(u=>u==="body"?e.body!==r:!mt(n[u],d[u]));return t.options.acceptanceCriteria!==void 0&&l.includes("acceptance_criteria")&&s.push(`acceptance_criteria_replaced:${At(n.acceptance_criteria).length}:${At(d.acceptance_criteria).length}`),{changedFields:l,warnings:s}}async function lv(e,t,n,r={}){t=await hO(t);let i=R(process.cwd(),n.path);await $(i);let s=await C(i),o=H(s.schema),a=En(s.schema),c=F(),d=It(c),l=U(s,c),u=s.governance.workflow_enforcement??"off",m=u==="off"?[]:Ku(s.schema),g=[{strict_error:"strict_error",warn:"warn",off:"off"},{strict_error:"warn",warn:"warn",off:"off"}][+(t.allowMissingParent===!0)][s.validation.parent_reference],p=iv(t.unset,a,d),h=new Set(p.optionKeys),y=new Set(p.metadataKeys);vO(t),wO({definitions:yO(t),options:t,clearOptionKeys:h,clearItemMetadataKeys:y}),W0(e,t,y),kO(t,p),EO(t);let v=q(t.author,s.author_default),w=new Date,E=w.toISOString(),S=Z0(t.dep,s.id_prefix,E,v);zr(e,S.additions);let x=await co({pmRoot:i,dependencies:S.additions,idPrefix:s.id_prefix,itemFormat:s.item_format,typeToFolder:l.type_to_folder,allowUnresolved:t.allowUnresolvedDeps,holders:[{id:e}],schema:s.schema}),I=eO(t.depRemove,s.id_prefix),k=ln("--comment",t.comment,E,v),b=t.ownershipMetadataBypass===!0&&k.values?{...k,values:k.values.map(ve=>({...ve,author:v}))}:k,O=ln("--note",t.note,E,v),W=ln("--learning",t.learning,E,v),P=ud(t.file),A=md(t.test);A.values=await Bn(A.values,v,E);let K=fd(t.doc),oe=[],ae=await CO({id:e,options:t,unsetTargets:p,pmRoot:i,settings:s,typeRegistry:l,parentReferencePolicy:g}),ye=await rO(t.blockedBy,y.has("blocked_by"),i,s.id_prefix,s.item_format,l.type_to_folder),$e=ye.id,Je=[...ae.warnings,...RO(ye)],xt=ou(t,a,t.runtimeFieldCommands),dt=SO(t,xt);if(!Object.values(dt).some(Boolean))return xO({pmRoot:i,id:e,settings:s,typeRegistry:l});oe.push(...await OO({options:t,fieldFlags:dt,workflowEnforcement:u,typeWorkflows:m,statusRegistry:o,typeRegistry:l,pmRoot:i,id:e,settings:s}));let de=await DO({options:t,fieldFlags:dt,statusRegistry:o,workflowTransitionWarnings:oe,global:n,id:e});if(de)return de;AO(t);let je=xe(),pn=dt.parent&&!y.has("parent")||S.additions.some(ve=>je.resolve(ve.kind)?.hierarchy),M=await Xs({pmRoot:i,author:v,ttlSeconds:s.locks.ttl_seconds,waitMs:s.locks.wait_ms,required:pn});try{let ve=await TO({fieldFlags:dt,clearedMetadataKeys:y,pmRoot:i,settings:s,typeToFolder:l.type_to_folder}),He,gn,Xe=await nm({pmRoot:i,settings:s,typeToFolder:l.type_to_folder,id:e,op:iD(t,r),author:v,message:t.message,resolveHistoryContext:()=>gn,force:t.force,bypassAssigneeConflict:t.ownershipMetadataBypass===!0||t.ownershipDependencyBypass===!0,extensionFieldNames:d,skipNoop:!0,mutate(Qe){He=sD({document:Qe,recurrenceReason:r.recurrenceReason,requestedStatus:t.status,statusRegistry:o}),gn=He?{recurrence:He}:void 0,ve=ve?.map(ri=>ri.id===Qe.metadata.id?structuredClone(Qe.metadata):ri);let Fo=rD(Qe,{options:t,settings:s,typeRegistry:l,statusRegistry:o,runtimeFieldRegistry:a,extensionRegistrations:c,extensionFieldNames:d,clearItemMetadataKeys:y,dependencyUpdates:S,dependencyRemovals:I,commentUpdates:b,noteUpdates:O,learningUpdates:W,fileUpdates:P,testUpdates:A,docUpdates:K,resolvedParentValue:ae.resolvedParentValue,resolvedBlockedByDependencyId:$e,runtimeFieldUpdates:xt,nowValue:w,nowIso:E,author:v,pmRoot:i});return IO({before:ve,document:Qe,statusRegistry:o}),Fo}});await M();let le=ve?js(ve,ve.map(Qe=>Qe.id===Xe.item.id?Xe.item:Qe),Xe.item.id):[];return{item:Xe.item,changed_fields:Xe.changedFields,warnings:[...oe,...Je,...x,...le,...Xe.warnings],...He===void 0?{}:{lifecycle_transition:He}}}finally{await M()}}function iD(e,t){return e.ownershipMetadataBypass===!0||e.ownershipDependencyBypass===!0?"update_ownership_bypass":t.recurrenceReason===void 0?"update":"reopen"}function sD(e){if(e.recurrenceReason===void 0)return;let t=se(e.document.metadata.status,e.statusRegistry)??e.document.metadata.status;if(!ue(t,e.statusRegistry))throw new _(`Item ${e.document.metadata.id} is already active with status ${t}; recurrence transitions require a terminal item.`,f.CONFLICT,{code:"item_already_active",reason:"recurrence_requires_terminal_item",required:"Use item reopen only for a terminal item whose work has recurred.",why:"Appending a recurrence event to active work would corrupt lifecycle history.",recovery:{suggested_retry:`pm get ${e.document.metadata.id} --full`,suggested_retry_args:["get",e.document.metadata.id,"--full"]},nextSteps:[`Inspect the active item with: pm get ${e.document.metadata.id} --full`,`Continue the existing work with: pm update ${e.document.metadata.id} ...`]});let n=e.requestedStatus??e.statusRegistry.open_status,r=se(n,e.statusRegistry)??n,i=e.document.metadata,s=Object.fromEntries(["close_reason","resolution","expected_result","actual_result","fixed_version"].flatMap(o=>{let a=i[o];return typeof a=="string"?[[o,a]]:[]}));return{reason:e.recurrenceReason,from_status:t,to_status:r,previous_terminal:s}}async function oD(e,t,n){return lv(e,t,n)}async function lV(e,t,n,r){let i=await lv(e,t,n,{recurrenceReason:r});if(i.lifecycle_transition===void 0)throw new _(`Item ${e} did not produce the required recurrence receipt.`,f.GENERIC_FAILURE,{code:"reopen_receipt_missing",reason:"recurrence_transition_not_recorded",required:"A successful reopen must return the terminal-to-active lifecycle transition recorded in immutable history."});return{...i,lifecycle_transition:i.lifecycle_transition}}import wd from"node:fs/promises";import uv from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7df80849-51e1-5efa-b40a-b44088f941a9")}catch{}})();var aD=1440*60*1e3,cD=new Set(["committed","compensated"]);function dD(e){let t;try{t=JSON.parse(e)}catch{return{status:null,updatedAt:null}}if(typeof t!="object"||t===null||Array.isArray(t))return{status:null,updatedAt:null};let n=t;return{status:typeof n.status=="string"?n.status:null,updatedAt:typeof n.updatedAt=="string"?n.updatedAt:null}}function lD(e,t,n,r,i){let s=n===null?Number.NaN:Date.parse(n);if(t===null||!Number.isFinite(s))return{entry:{file:e,status:t,age_seconds:null,stale:!1,reason:"unparseable"},remove:!1};let o=r-s;return cD.has(t)?o>i?{entry:{file:e,status:t,age_seconds:Math.floor(o/1e3),stale:!0},remove:!0}:{entry:{file:e,status:t,age_seconds:Math.floor(o/1e3),stale:!1,reason:"fresh"},remove:!1}:{entry:{file:e,status:t,age_seconds:Math.floor(o/1e3),stale:!1,reason:"active"},remove:!1}}async function uD(e,t,n,r){let i=r.hooks?.onRead?await r.hooks.onRead(e):[],s=dD(await wd.readFile(e,"utf8")),o=lD(t,s.status,s.updatedAt,r.nowMs,r.retentionMs);return o.entry.reason==="unparseable"&&i.push(`transaction_journal_unparseable:${n}`),o.remove&&!r.dryRun&&(await wd.rm(e,{force:!0}),r.hooks?.onWrite&&i.push(...await r.hooks.onWrite(e))),{decision:o,warnings:i}}async function mv(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),s=Math.max(0,t.retentionDays)*aD,o=uv.join(e,"transactions","sdk"),a={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c;try{c=(await wd.readdir(o)).filter(d=>d.endsWith(".json")).sort((d,l)=>d.localeCompare(l))}catch(d){if(j(d))return a;throw d}for(let d of c){let l=uv.join(o,d),u=`transactions/sdk/${d}`,m=await uD(l,u,d,{dryRun:n,hooks:r,nowMs:i,retentionMs:s});a.warnings.push(...m.warnings),a.scanned+=1;let{decision:g}=m;if(!g.remove){a.retained.push(u),a.entries.push(g.entry);continue}a.removed.push(u),a.entries.push(g.entry)}return a}import Yn from"node:fs/promises";import vo from"node:path";import yo from"node:fs/promises";import bd from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b26cf702-330e-5cf5-8371-204220d5c5c9")}catch{}})();var mD=864e5;function fD(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t.created_at;return typeof n=="string"?n:null}async function _D(e,t){let n;try{n=await yo.readdir(e,{withFileTypes:!0})}catch(i){if(j(i))return[];throw i}let r=[];for(let i of n)if(i.isDirectory()){let s=bd.join(e,i.name),o;try{o=await yo.readdir(s)}catch(a){j(a)||t.push(`checkpoint_subdir_unreadable:${i.name}`);continue}for(let a of o)a.endsWith(".json")&&r.push(`${i.name}/${a}`)}else i.name.endsWith(".json")&&r.push(i.name);return r.sort()}async function fv(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),s=Math.max(0,t.retentionDays)*mD,o=bd.join(e,"checkpoints"),a={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c=await _D(o,a.warnings);for(let d of c){let l=bd.join(o,d),u=`checkpoints/${d}`;a.scanned+=1,r?.onRead&&a.warnings.push(...await r.onRead(l));let m;try{m=await yo.readFile(l,"utf8")}catch(v){if(j(v)){a.scanned-=1;continue}a.warnings.push(`checkpoint_unreadable:${d}`),a.retained.push(u),a.entries.push({file:u,created_at:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let g=fD(m),p=g===null?Number.NaN:Date.parse(g);if(!Number.isFinite(p)){a.warnings.push(`checkpoint_unparseable:${d}`),a.retained.push(u),a.entries.push({file:u,created_at:g,age_seconds:null,stale:!1,reason:"unparseable"});continue}let h=i-p,y={file:u,created_at:g,age_seconds:Math.floor(h/1e3),stale:h>s,reason:h>s?"expired":"active"};if(!y.stale){a.retained.push(u),a.entries.push(y);continue}if(!n){try{await yo.unlink(l)}catch(v){if(!j(v)){a.warnings.push(`checkpoint_remove_failed:${d}`),a.retained.push(u),a.entries.push(y);continue}}r?.onWrite&&a.warnings.push(...await r.onWrite(l))}a.removed.push(u),a.entries.push(y)}return a}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="76f8405f-138d-5119-a300-f068354394a5")}catch{}})();var Br=["index","embeddings","runtime","locks","checkpoints","transactions"],pD=1440*60*1e3,gD=[{scope:"index",relativePath:"index/manifest.json",kind:"file"},{scope:"embeddings",relativePath:"search/embeddings.jsonl",kind:"file"},{scope:"embeddings",relativePath:"search/vectorization-status.json",kind:"file"},{scope:"embeddings",relativePath:"search/lancedb",kind:"directory"},{scope:"embeddings",relativePath:"search/pending-refresh.json",kind:"file"},{scope:"embeddings",relativePath:"search/pending-refresh.gate.lock",kind:"directory"},{scope:"runtime",relativePath:"runtime/test-runs",kind:"directory"},{scope:"runtime",relativePath:"runtime/history-drift-cache.json",kind:"file"}];async function hD(e,t,n){let r=t.relativePath,i=vo.join(e,r),s=await Ce({path:i,scope:"project"});try{let o=await Yn.stat(i);if(t.kind==="file"&&!o.isFile())return{removed:!1,warnings:[...s,`not_a_file:${r}`]};if(t.kind==="directory"&&!o.isDirectory())return{removed:!1,warnings:[...s,`not_a_directory:${r}`]};if(n)return{removed:!0,warnings:s};t.kind==="file"?await Yn.unlink(i):await Yn.rm(i,{recursive:!0,force:!0});let a=await Me({path:i,scope:"project",op:"gc:remove"});return{removed:!0,warnings:[...s,...a]}}catch(o){if(j(o))return{removed:!1,warnings:s};throw o}}async function yD(e,t){let n=[{relativePath:"runtime/workspace-snapshots/objects",prefix:".create-"},{relativePath:"runtime/workspace-snapshots/refs",prefix:".ref-"}],r=[],i=[],s=[],o=Date.now()-pD;for(let a of n){let c=vo.join(e,a.relativePath);if(!await V(c))continue;let d=(await Yn.readdir(c)).filter(l=>l.startsWith(a.prefix)).sort();for(let l of d){let u=vo.posix.join(a.relativePath,l),m=vo.join(c,l);s.push(...await Ce({path:m,scope:"project"}));let g=await Yn.stat(m).catch(p=>{if(!j(p))throw p});if(g){if(g.mtimeMs>o){i.push(u);continue}r.push(u),!t&&(await Yn.rm(m,{recursive:!0,force:!0}),s.push(...await Me({path:m,scope:"project",op:"gc:workspace_snapshot_temp_remove"})))}}}return{removed:r,retained:i,warnings:s}}function vD(e){if(!e||e.length===0)return[...Br];let t=e.flatMap(r=>r.split(",")).map(r=>r.trim().toLowerCase()).filter(r=>r.length>0);if(t.length===0)throw new _(`--scope requires at least one value (${Br.join(",")})`,f.USAGE);let n=new Set;for(let r of t){if(!Br.includes(r))throw new _(`Invalid --scope value "${r}". Expected one or more of: ${Br.join(", ")}`,f.USAGE);n.add(r)}return Br.filter(r=>n.has(r))}function wD(e){let t=[];e.dryRun&&t.push("Dry-run preview only: no cache artifacts were deleted.");let n=e.scopes.includes("index")||e.scopes.includes("embeddings"),r=e.removed.some(i=>i==="index/manifest.json"||i==="search/embeddings.jsonl"||i==="search/vectorization-status.json"||i==="search/lancedb"||i==="search/pending-refresh.json"||i==="search/pending-refresh.gate.lock");return n&&r&&t.push('Search artifacts were removed; the semantic index (including any queued background refresh) is invalidated. Run "pm install search-advanced --project" if reindex is unavailable, then "pm reindex --mode keyword" (and "--mode semantic" when semantic search is enabled) before search-heavy workflows.'),e.removed.includes("runtime/history-drift-cache.json")&&t.push('History drift cache was removed; the next "pm health" run performs a full history-drift re-scan.'),!e.dryRun&&e.removed.some(i=>i.startsWith("checkpoints/"))&&t.push('Aged rollback checkpoints were removed; their "pm update-many"/"pm close-many --rollback" windows are no longer recoverable.'),!e.dryRun&&e.removed.some(i=>i.startsWith("transactions/"))&&t.push("Aged terminal workspace-transaction journals were removed; replaying those transactionIds re-executes their idempotent steps instead of short-circuiting."),t}async function LV(e,t={}){let n=R(process.cwd(),e.path);await $(n);let r=await C(n),i=t.dryRun===!0,s=vD(t.scope),o=gD.filter(p=>s.includes(p.scope)),a=[],c=[],d=[];for(let p of o){let h=await hD(n,p,i);h.removed?a.push(p.relativePath):c.push(p.relativePath),d.push(...h.warnings)}if(s.includes("runtime")){let p=await yD(n,i);a.push(...p.removed),c.push(...p.retained),d.push(...p.warnings)}let l;if(s.includes("locks")){let p=await ng(n,{dryRun:i,hooks:{onRead:h=>Ce({path:h,scope:"project"}),onWrite:h=>Me({path:h,scope:"project",op:"gc:lock_remove"})}});a.push(...p.removed),c.push(...p.retained),d.push(...p.warnings),l={scanned:p.scanned,removed:p.removed.length,retained:p.retained.length}}let u;if(s.includes("transactions")){let p=r.checkpoints.retention_days,h=await mv(n,{dryRun:i,retentionDays:p,hooks:{onRead:y=>Ce({path:y,scope:"project"}),onWrite:y=>Me({path:y,scope:"project",op:"gc:transaction_journal_remove"})}});a.push(...h.removed),c.push(...h.retained),d.push(...h.warnings),u={scanned:h.scanned,removed:h.removed.length,retained:h.retained.length,retention_days:p}}let m;if(s.includes("checkpoints")){let p=r.checkpoints.retention_days,h=await fv(n,{dryRun:i,retentionDays:p,hooks:{onRead:y=>Ce({path:y,scope:"project"}),onWrite:y=>Me({path:y,scope:"project",op:"gc:checkpoint_remove"})}});a.push(...h.removed),c.push(...h.retained),d.push(...h.warnings),m={scanned:h.scanned,removed:h.removed.length,retained:h.retained.length,retention_days:p}}d.push(...await Xl({mode:i?"gc:dry-run":"gc",total_items:o.length}));let g=wD({dryRun:i,scopes:s,removed:a});return{ok:d.length===0,dry_run:i,scope:s,removed:a,retained:c,warnings:d,...l?{locks:l}:{},...m?{checkpoints:m}:{},...u?{transactions:u}:{},guidance:g,generated_at:T()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c7c75b13-7317-5089-9869-7e6e22ed95b2")}catch{}})();var bD="1h",kD="now",ED="+1d";function jt(e,t,n){n!==void 0&&e.push(`${t}="${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`)}function _v(e,t,n){let r={type:e,title:t,schedulePreset:"lightweight",parent:n.parent,allowMissingParent:n.allowMissingParent,tags:n.tags,priority:n.priority,body:n.body,description:n.description,author:n.author,message:n.message};return qe(n,r)}async function pv(e,t,n,r){let i=_v(e,t,n),s=[];return jt(s,"start",n.start??kD),n.end!==void 0?jt(s,"end",n.end):jt(s,"duration",n.duration??bD),jt(s,"location",n.location),jt(s,"timezone",n.timezone),n.allDay===!0&&jt(s,"all_day","true"),i.event=[s.join(",")],pd(i,r)}function FV(e,t,n){return pv("Meeting",e,t,n)}function $V(e,t,n){return pv("Event",e,t,n)}function jV(e,t,n){let r=_v("Reminder",e,t),i=[];return jt(i,"at",t.at??ED),jt(i,"text",t.text??e),r.reminder=[i.join(",")],pd(r,n)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8a0d8f6e-f4ff-5a0c-9205-d28e03df72b9")}catch{}})();import Wr from"node:crypto";import{cp as gv,lstat as SD,mkdir as un,readFile as Jn,readdir as Ed,rename as vv,rm as xd,writeFile as wo}from"node:fs/promises";import G from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2580e043-8675-5070-b57e-30cae333228c")}catch{}})();var wv="https://schema.unbrained.dev/pm/workspace-snapshot/v1",t2=["create","list","inspect","restore","delete"],bv=G.join("runtime","workspace-snapshots"),xD=new Set(["checkpoints","locks","runtime","search","transactions"]),TD=/^[a-z0-9][a-z0-9._-]*$/,Hr="sdk-workspace-transaction",kd={capacity:{code:"workspace_snapshot_storage_exhausted"},permission:{code:"workspace_snapshot_permission_denied"},resource:{code:"workspace_snapshot_resource_exhausted"}},kv={renameEntry:vv,removeEntry:async e=>{await xd(e,{recursive:!0,force:!0})}},Sd=class{lockPath;owner;intervalMs;timer;refresh;failure;constructor(t,n,r){this.lockPath=t,this.owner=n,this.intervalMs=Math.max(10,Math.floor(r*1e3/3))}start(){this.scheduleRenewal(),this.timer=setInterval(()=>{this.scheduleRenewal()},this.intervalMs),this.timer.unref()}async refreshNow(){this.scheduleRenewal(),await this.refresh,this.assertHealthy()}assertHealthy(){if(this.failure!==void 0)throw new Error("Workspace snapshot restore lost its writer lock",{cause:this.failure})}async stop(){this.timer!==void 0&&clearInterval(this.timer),await this.refresh,this.assertHealthy()}scheduleRenewal(){this.refresh!==void 0||this.failure!==void 0||(this.refresh=this.renew().catch(t=>{this.failure=t}).finally(()=>{this.refresh=void 0}))}async renew(){let t=JSON.parse(await Jn(this.lockPath,"utf8"));if(typeof t!="object"||t===null||Array.isArray(t))throw new Error("Workspace writer lock has invalid structure");let n=t;if(n.id!==Hr||n.owner!==this.owner||n.pid!==process.pid)throw new Error("Workspace writer lock ownership changed");await we(this.lockPath,`${JSON.stringify({...n,created_at:new Date().toISOString()},null,2)}
|
|
22
|
-
`)}};async function Ev(e,t=""){let n=await Ed(G.join(e,t),{withFileTypes:!0}),r=[];for(let i of n.sort((s,o)=>s.name.localeCompare(o.name))){if(t.length===0&&xD.has(i.name))continue;let s=G.posix.join(t.replaceAll(G.sep,"/"),i.name);if(i.isSymbolicLink())throw new Error(`Workspace snapshots reject symbolic links: ${s}`);if(i.isDirectory())r.push(...await Ev(e,s));else if(i.isFile())r.push(s);else throw new Error(`Workspace snapshots reject unsupported filesystem entries: ${s}`)}return r}async function Sv(e){let t=await Ev(e),n=Wr.createHash("sha256"),r=[],i=0;for(let o of t){let a=await Jn(G.join(e,o));r.push(a),i+=a.byteLength,n.update(o),n.update("\0"),n.update(String(a.byteLength)),n.update("\0"),n.update(a)}let s=n.digest("hex");return{manifest:{schema:wv,fingerprint:s,files:t,bytes:i},contents:r}}function hv(e){return e===void 0||e.byteLength===0?0:e.toString("utf8").split(`
|
|
23
|
-
`).filter(t=>t.trim().length>0).length}async function ID(e,t){let n=new Map;for(let r=0;r<t.length;r+=32){let i=t.slice(r,r+32),s=await Promise.all(i.map(async o=>[o,await Jn(G.join(e,o))]));for(let[o,a]of s)n.set(o,a)}return n}function Td(e){if(!TD.test(e))throw new _("Snapshot names and fingerprints must use lowercase letters, digits, dots, underscores, or hyphens",f.USAGE,{code:"invalid_workspace_snapshot_target",required:"Provide a non-empty lowercase snapshot name or 64-character hexadecimal fingerprint.",why:"Snapshot targets are used as portable reference filenames and content identities.",examples:["pm workspace snapshot list --json","pm workspace snapshot inspect baseline --json"],nextSteps:["List available snapshots, then retry with a returned name or fingerprint."],recovery:{suggested_retry:"pm workspace snapshot list --json"}})}async function xv(e,t){return or(`workspace_snapshot_${e}`,t,{codes:{capacity:kd.capacity.code,permission:kd.permission.code,resource:kd.resource.code},why:"Snapshot create and restore copy authoritative tracker state before activation, so the stage needs capacity and write access up front.",nextSteps:["Reclaim rebuildable tracker cache space with pm gc, then retry."],suggestedRetry:"pm gc --json"})}function mn(e){return G.join(e,bv)}function Tv(e){return new _(`Unknown workspace snapshot: ${e}`,f.NOT_FOUND,{code:"workspace_snapshot_not_found",required:"Use a snapshot name or fingerprint returned by snapshot list.",why:"The requested reference or immutable snapshot object does not exist.",examples:["pm workspace snapshot list --json"],nextSteps:["List available snapshots and retry with an exact target."],recovery:{suggested_retry:"pm workspace snapshot list --json"}})}async function Iv(e,t){try{return JSON.parse(await Jn(e,"utf8"))}catch(n){throw j(n)?Tv(t):n}}async function yv(e,t,n){try{await xd(e,{recursive:n})}catch(r){throw j(r)?Tv(t):r}}async function AD(e,t,n=kv){try{return await n.renameEntry(e,t),!1}catch(r){if(!(r instanceof Error&&"code"in r&&(r.code==="EEXIST"||r.code==="ENOTEMPTY")))throw r;return await n.removeEntry(e),!0}}async function CD(e,t,n,r,i){await r.renameEntry(t,n);try{await r.renameEntry(e,t),await i?.()}catch(s){throw await r.renameEntry(n,t),await r.removeEntry(e),s}await r.removeEntry(n)}async function RD(e,t){return Td(t),/^[a-f0-9]{64}$/.test(t)?t:(await Iv(G.join(mn(e),"refs",`${t}.json`),t)).fingerprint}async function OD(e,t={}){if(t.name!==void 0&&(Td(t.name),/^[a-f0-9]{64}$/.test(t.name)))throw new _("Snapshot names must not be 64-character lowercase hexadecimal fingerprints",f.USAGE,{code:"workspace_snapshot_name_reserved_fingerprint",required:"Choose a human-readable reference name that cannot be mistaken for a content fingerprint.",why:"Exact 64-character hexadecimal values address immutable objects.",examples:["pm workspace snapshot create baseline --json"],nextSteps:["Retry with a shorter descriptive snapshot name."]});let{manifest:n,contents:r}=await Sv(e),i=mn(e),s=G.join(i,"objects",n.fingerprint),o=!1;try{o=(await SD(s)).isDirectory()}catch(a){if(!(a instanceof Error&&"code"in a&&j(a)))throw a}if(!o){let a=G.join(i,"objects",`.create-${process.pid}-${Wr.randomUUID()}`);await xv("create_object",async()=>{await un(G.join(a,"files"),{recursive:!0});for(let[c,d]of n.files.entries()){let l=G.join(a,"files",d);await un(G.dirname(l),{recursive:!0}),await wo(l,r[c])}await wo(G.join(a,"manifest.json"),`${JSON.stringify(n,null,2)}
|
|
24
|
-
`,"utf8"),await un(G.dirname(s),{recursive:!0})}),o=await AD(a,s)}if(t.name!==void 0){let a={name:t.name,fingerprint:n.fingerprint},c=G.join(i,"refs");await un(c,{recursive:!0});let d=G.join(c,`.ref-${process.pid}-${Wr.randomUUID()}`);await wo(d,`${JSON.stringify(a,null,2)}
|
|
25
|
-
`,"utf8"),await vv(d,G.join(c,`${t.name}.json`))}return{manifest:n,...t.name===void 0?{}:{name:t.name},deduplicated:o}}async function Id(e,t){let n=await RD(e,t),r=await Iv(G.join(mn(e),"objects",n,"manifest.json"),t);if(r.schema!==wv||r.fingerprint!==n)throw new _(`Snapshot manifest identity mismatch: ${t}`,f.CONFLICT,{code:"workspace_snapshot_manifest_mismatch",required:"Use an intact snapshot whose manifest fingerprint matches its object path.",why:"Content identity must be verified before snapshot data is trusted.",examples:["pm workspace snapshot list --json"],nextSteps:["Inspect or recreate the snapshot before restoring it."]});return r}async function DD(e){let t=mn(e),n=await Ed(G.join(t,"objects")).catch(i=>{if(i instanceof Error&&"code"in i&&j(i))return[];throw i}),r=await Ed(G.join(t,"refs")).catch(i=>{if(i instanceof Error&&"code"in i&&j(i))return[];throw i});return{objects:await Promise.all(n.filter(i=>/^[a-f0-9]{64}$/.test(i)).sort().map(i=>Id(e,i))),references:await Promise.all(r.filter(i=>i.endsWith(".json")).sort().map(async i=>JSON.parse(await Jn(G.join(t,"refs",i),"utf8"))))}}async function LD(e,t){let n=await Id(e,t),{manifest:r,contents:i}=await Sv(e),s=new Map(r.files.map((u,m)=>[u,i[m]])),o=await ID(G.join(mn(e),"objects",n.fingerprint,"files"),n.files),a=new Set(r.files),c=new Set(n.files),d=new Set([...a,...c]);for(let u of d){let m=s.get(u),g=o.get(u);m!==void 0&&g!==void 0&&m.equals(g)&&d.delete(u)}let l=r.files.filter(u=>u.startsWith("history/")&&u.endsWith(".jsonl")).map(u=>{let m=hv(s.get(u)),g=hv(o.get(u));return{path:u,current_entries:m,target_entries:g,removed_entries:Math.max(0,m-g)}}).filter(u=>u.removed_entries>0).sort((u,m)=>u.path.localeCompare(m.path));return{target_fingerprint:n.fingerprint,current_fingerprint:r.fingerprint,changed_file_count:d.size,removed_file_count:[...a].filter(u=>!c.has(u)).length,added_file_count:[...c].filter(u=>!a.has(u)).length,removed_item_count:[...a].filter(u=>u.endsWith(".toon")&&!c.has(u)).length,affected_history_stream_count:l.length,removed_history_entry_count:l.reduce((u,m)=>u+m.removed_entries,0),affected_history_streams:l,changes_authoritative_state:r.fingerprint!==n.fingerprint}}async function ND(e,t,n={}){if(n.force!==!0)throw new _("Workspace snapshot restore requires explicit force confirmation; inspect the impact with planWorkspaceSnapshotRestore or pm workspace snapshot restore <target> --dry-run, then retry with force",f.USAGE,{code:"workspace_snapshot_force_required",required:"Preview the destructive impact, then explicitly confirm the restore.",why:"A restore replaces the complete authoritative tracker state.",examples:[`pm workspace snapshot restore ${t} --dry-run --json`,`pm workspace snapshot restore ${t} --force --json`],nextSteps:["Review the dry-run counts before retrying with --force."],recovery:{suggested_retry:`pm workspace snapshot restore ${t} --dry-run --json`}});let r=n.author?.trim()||"pm-sdk",i=n.lockTtlSeconds??60,s=n.lockWaitMs??5e3,o=await Ct(e,Hr,i,r,!1,!1,s),a=new Sd(ui(e,Hr),r,i);a.start(),await a.refreshNow();let c,d=!1,l=!1;try{let u=await LD(e,t),m=await Id(e,t),g=await OD(e),p=m.fingerprint,h=mn(e),y=G.join(h,"objects",p,"files"),v=G.dirname(e),w=G.basename(e);c=G.join(v,`.${w}.restore-${Wr.randomUUID()}`);let E=G.join(v,`.${w}.backup-${Wr.randomUUID()}`);await xv("restore_stage",async()=>{await un(c,{recursive:!0}),await gv(y,c,{recursive:!0,force:!1}),await un(G.join(c,"runtime"),{recursive:!0}),await gv(h,G.join(c,bv),{recursive:!0,force:!1})});let S=await An({pmRoot:c,op:"workspace_snapshot_restore",author:r,message:n.message??`Restore workspace snapshot ${p}; recovery snapshot ${g.manifest.fingerprint}`,context:{target_fingerprint:p,pre_restore_fingerprint:g.manifest.fingerprint,changed_file_count:u.changed_file_count,removed_file_count:u.removed_file_count,removed_item_count:u.removed_item_count,affected_history_stream_count:u.affected_history_stream_count,removed_history_entry_count:u.removed_history_entry_count},lockTtlSeconds:i,lockWaitMs:s}),x=G.relative(c,S.historyPath).replaceAll("\\","/");await a.stop(),l=!0;let I=ui(c,Hr);return await un(G.dirname(I),{recursive:!0}),await wo(I,await Jn(ui(e,Hr)),{flag:"wx"}),d=!0,await CD(c,e,E,kv,async()=>{a.start(),l=!1,await a.refreshNow()}),await a.stop(),l=!0,{manifest:m,plan:u,recovery_fingerprint:g.manifest.fingerprint,audit_history_path:x,audit_operation:"workspace_snapshot_restore"}}catch(u){throw c!==void 0&&!d&&await Promise.allSettled([xd(c,{recursive:!0,force:!0})]),u}finally{try{l||await a.stop()}catch{}finally{await o()}}}async function n2(e,t){return(await ND(e,t,{force:!0,message:"Restore requested through the compatibility SDK signature"})).manifest}async function r2(e,t){Td(t);let n=mn(e);if(!/^[a-f0-9]{64}$/.test(t))return await yv(G.join(n,"refs",`${t}.json`),t,!1),{deleted:"reference",target:t};let{references:r}=await DD(e);if(r.some(i=>i.fingerprint===t))throw new Error(`Snapshot object ${t} is still referenced`);return await yv(G.join(n,"objects",t),t,!0),{deleted:"object",target:t}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e900c117-6d8d-55d3-86df-f543dc499930")}catch{}})();function Av(e){return e.invalidEvidenceCount>0?"merge_evidence_invalid":e.historyEvidenceValid?e.pendingDecisionCount>0||e.losslessCount>0?"merge_reconciliation_required":e.driftedItemCount>0?"history_repair_required":e.fence.status!=="ok"||e.drivers===null||e.drivers.status!=="ok"?"merge_fence_unprepared":"ready":"history_evidence_invalid"}function Cv(e,t,n=process.platform){let r=["--pm-path",t];return e==="merge_evidence_invalid"?ft([...r,"merge","report"],n):e==="history_evidence_invalid"?ft([...r,"validate","--check-history-drift","--full"],n):e==="merge_reconciliation_required"?ft([...r,"merge","reconcile"],n):e==="history_repair_required"?ft([...r,"history-repair","--all"],n):e==="merge_fence_unprepared"?ft([...r,"merge","install"],n):null}function Rv(e){let t=Array.isArray(e.drifted_items)?e.drifted_items.filter(r=>typeof r=="string"):[];return{evidence_valid:Array.isArray(e.drifted_items)&&e.drifted_items.every(r=>typeof r=="string")&&typeof e.drifted_items_count=="number"&&Number.isInteger(e.drifted_items_count)&&e.drifted_items_count>=0&&typeof e.drifted_items_truncated=="boolean"&&typeof e.counts=="object"&&e.counts!==null&&!Array.isArray(e.counts),drifted_item_count:typeof e.drifted_items_count=="number"?e.drifted_items_count:t.length,drifted_item_ids:t,drifted_item_ids_truncated:e.drifted_items_truncated===!0,counts:typeof e.counts=="object"&&e.counts!==null?e.counts:{}}}async function g2(e){let t=R(process.cwd(),e.path);await $(t);let n=await C(t),r=U(n,F()),i=[],s=await Rs({includeBody:!0,pmRoot:t,settings:n,typeToFolder:r.type_to_folder,warnings:i}),o=await Lt(t),[a,c,d,l]=await Promise.all([Yi(t,Vi(n)),o===null?Promise.resolve(null):On(o),st(o??t,{includeLossless:!0,pmRoot:t}),Os(t,s,!1)]),{pendingDecisions:u,lossless:m}=$n(d.receipts),g=[...new Set(u.map(v=>v.item_id))].sort((v,w)=>v.localeCompare(w)),p=l.check.details,h=Rv(p),y=Av({invalidEvidenceCount:d.invalid_evidence_count,pendingDecisionCount:u.length,losslessCount:m.length,historyEvidenceValid:h.evidence_valid,driftedItemCount:h.drifted_item_count,fence:a,drivers:c});return{ok:y==="ready",state:y,merge_fence:{committed:a,clone_local_drivers:c},merge_receipts:{pending_decision_count:u.length,pending_item_ids:g.slice(0,25),pending_item_ids_truncated:g.length>25,lossless_count:m.length,invalid_evidence_count:d.invalid_evidence_count},history_drift:h,next_action:{command:Cv(y,t),reason:y},warnings:[...new Set(i)].sort((v,w)=>v.localeCompare(w)),generated_at:T()}}function h2(e){let t=e.next_action.command??"none";return[`workspace_position: ${e.state}`,`merge_fence: ${e.merge_fence.committed.status}`,`clone_local_drivers: ${e.merge_fence.clone_local_drivers?.status??"unavailable"}`,`pending_merge_decisions: ${e.merge_receipts.pending_decision_count}`,`history_drifted_items: ${e.history_drift.drifted_item_count}`,`next_action: ${t}`].join(`
|
|
26
|
-
`)}var y2={commandForWorkspacePositionState:Cv,normalizeWorkspaceHistoryDrift:Rv,selectWorkspacePositionState:Av};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d1930c5a-6849-5f78-8090-a436f61711ae")}catch{}})();function b2(e){return kn("in_progress",e)??e.open_status}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7ef5cc14-ad6b-5cce-a1a1-e5cfac85fbc2")}catch{}})();var MD=Object.freeze({"--body":"Set the item body.","--body-file":"Read the item body from a file, or from stdin when set to -.","--description":"Set the item description.","--stdin":"Read the value from stdin.","--stdin-json":"Read a complete JSON document from stdin."}),PD=new Set(["--add","--body","--comment","--dep","--dep-remove","--description","--doc","--event","--field","--file","--learning","--note","--remove","--reminder","--test","--type-option"]),FD=new Set(["append","comments","create","docs","files","learnings","notes","test","update","update-many"]),$D=new Set(["close-many:--ids","comments:--file","create:--body-file","history-compact:--ids","learnings:--file","notes:--file","update:--body-file","update-many:--ids"]),jD=new Set(["close-many:--ids","history-compact:--ids","update-many:--ids"]),UD=["--allow-","--check-","--dry-run","--explain","--fail-","--fix-","--full","--has-","--include-","--json","--no-","--prune-","--quiet","--refresh-","--require-","--runtime-only","--schema-only","--skip-","--stream","--strict-","--summary","--today","--verbose"],qD=new Set(["--activate","--active-only","--adopt","--adopt-all","--all","--all-actionable","--all-affected-ids","--all-day","--all-streams","--acknowledge-linked-tests","--append-stable","--auto-fix","--auto-pm-context","--availability-only","--background","--brief","--by-assignee","--by-priority","--by-tag","--catalog","--claim","--clear","--clear-comments","--clear-criteria","--clear-deps","--clear-docs","--clear-events","--clear-files","--clear-learnings","--clear-notes","--clear-reminders","--clear-tests","--clear-type-options","--cli-only","--closed","--compact","--completion","--count","--counts","--deactivate","--declarative","--defaults","--describe","--diff","--doctor","--empty-body","--explore","--field-utilization","--filter-empty-body","--flags-only","--follow","--force","--global","--highlight","--hybrid","--id-only","--if-available","--ignore-global","--include_unparented","--infer","--init","--install","--isolated","--lean","--list","--local","--manage","--markdown","--metadata-coverage","--next","--normalize-provenance","--only","--only-last","--output-row-contract","--override-linked-pm-context","--override-linked-workspace-context","--packages-only","--past","--phrase-exact","--profile","--progress","--project","--promote-to-item-dep","--provenance","--provenance-summary","--raw","--ready-only","--ready_only","--rebuild","--recent","--reload","--repair","--replace-deps","--replace-docs","--replace-files","--replace-tests","--required","--required-on-create","--run","--runtime-probe","--save-baseline","--scaffold","--semantic","--shared-host-safe","--storage","--title-exact","--token-accounting","--trace","--tree","--unbounded","--uninstall","--validate-paths","--verify","--watch","--with-packages"]),GD=new Set(["--only-index"]),KD=new Set(["activity:--stream","eval:--fail-under","validate:--fix-scope"]),zD=new Set(["activity:--stream","close:--validate-close","close-many:--validate-close","comments:--author","learnings:--author","notes:--author"]),BD=new Set(["--regression"]);function HD(e,t){return t==="--stdin"||t==="--stdin-json"?["stdin"]:$D.has(`${e}:${t}`)?["argv","file","stdin"]:t.endsWith("-file")?["argv","file"]:PD.has(t)&&FD.has(e)?["argv","stdin"]:["argv"]}function WD(e,t){let n=KD.has(`${e}:${t.flag}`)||t.value_name!==void 0||t.value_type==="string"||t.value_type==="number"||t.list===!0||t.repeatable===!0,r=t.value_type==="boolean"||t.flag==="--stdin"||t.flag==="--stdin-json"||t.flag.startsWith("--filter-")&&(t.flag.endsWith("-missing")||t.flag.startsWith("--filter-has-")||t.flag.startsWith("--filter-no-"))||UD.some(i=>t.flag.startsWith(i));return n||GD.has(t.flag)||!qD.has(t.flag)&&!r}function VD(e,t){let n=WD(e,t),r=HD(e,t.flag),i=t.description??MD[t.flag]??`${n?"Set":"Enable"} ${t.flag.slice(2).replaceAll("-"," ")}.`;return{...t,description:i,takes_value:n,value_required:n&&!BD.has(t.flag)&&!zD.has(`${e}:${t.flag}`),...n?{value_name:t.value_name??"value"}:{},value_type:n?t.value_type??"string":"boolean",required:t.required===!0,repeatable:t.repeatable===!0||t.list===!0,input_sources:r,...r.includes("stdin")&&t.flag!=="--stdin"&&t.flag!=="--stdin-json"?{stdin_token:"-"}:{},...jD.has(`${e}:${t.flag}`)?{file_token_prefix:"@"}:{}}}function Ov(e,t){return t.map(n=>VD(e,n))}function E2(e,t,n){let r=e.trim().toLowerCase(),i=[],s=new Map,o=0;for(let c of n)if(c.command.trim().toLowerCase()===r){if(o+=1,s.has(c.flag)){i.push({code:"duplicate_observation",command:r,flag:c.flag,detail:`${r} ${c.flag} was observed more than once.`});continue}s.set(c.flag,c)}let a=new Set(t.map(({flag:c})=>c));for(let c of t){let d=s.get(c.flag);if(!d){i.push({code:"missing_observation",command:r,flag:c.flag,detail:`${r} ${c.flag} has no executable option observation.`});continue}for(let[l,u]of[["takes_value","takes_value_mismatch"],["value_required","value_required_mismatch"],["repeatable","repeatable_mismatch"]])c[l]!==d[l]&&i.push({code:u,command:r,flag:c.flag,detail:`${r} ${c.flag} declares ${l}=${String(c[l])} but the executable option reports ${String(d[l])}.`})}for(let c of s.values())a.has(c.flag)||i.push({code:"undeclared_observation",command:r,flag:c.flag,detail:`${r} ${c.flag} is executable but absent from invocation contracts.`});return i.sort((c,d)=>c.flag.localeCompare(d.flag)||c.code.localeCompare(d.code)),{ok:i.length===0,declared_count:t.length,observed_count:o,findings:i}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f3f07ca8-7823-536d-b523-6d8f87c35f4a")}catch{}})();var YD=new Set(["claim","close","context","create","get","help","init","list","next","plan","release","search","update","validate"]),JD=new Set(["append","comments","config","contracts","deps","docs","events","files","focus","graph","health","history","learnings","list-all","list-blocked","list-closed","list-in-progress","list-open","notes","profile","schema","test"]),XD=Object.freeze({workspace:new Set(["config","gc","health","init","merge","profile","schema","telemetry","workspace"]),intake:new Set(["copy","create","focus","item","restore"]),context:new Set(["activity","aggregate","context","ctx","duplicates","eval","get","help","list","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","next","search","stats"]),lifecycle:new Set(["claim","close","close-many","close-task","delete","pause-task","item-reopen","release","start-task","update","update-many"]),evidence:new Set(["append","comments","docs","events","files","history","history-author-acknowledge","history-compact","history-redact","history-repair","learnings","notes"]),graph:new Set(["deps","graph","plan"]),quality:new Set(["assurance","contracts","test","test-all","validate"]),automation:new Set(["event","meet","remind"])}),QD=new Set(["extension","install","package","packages","upgrade"]);function ZD(e){let t=e.trim().toLowerCase();for(let[n,r]of Object.entries(XD))if(r.has(t))return n;return QD.has(t)?"extensions":"internal"}var Xn=Object.freeze([...tt.flatMap(e=>e==="item"?["item-reopen"]:[e]).map(e=>({command:e,tier:YD.has(e)?"core":JD.has(e)?"standard":"full",family:ZD(e)})),{command:"completion-statuses",tier:"internal",family:"internal"},{command:"completion-tags",tier:"internal",family:"internal"},{command:"completion-types",tier:"internal",family:"internal"},{command:"test-runs-worker",tier:"internal",family:"internal"}]),eL=Xn,Dv=Object.freeze({max_lines:50,max_utf8_bytes:6e3}),T2=Object.freeze(["-V, --version","--all","--json","--output-include <fields>","--output-limit <count>","--output-budget <tokens|unbounded>","--output-cursor <cursor>","--pm-path <dir>","--no-extensions","--no-pager","--explain","-h, --help"]);function I2(e){let t=e===""?0:e.split(/\r?\n/).length,n=Buffer.byteLength(e,"utf8");return{lines:t,utf8_bytes:n,within_budget:t<=Dv.max_lines&&n<=Dv.max_utf8_bytes}}var Lv={core:0,standard:1,full:2,internal:3},tL=new Map(eL.map(({command:e,tier:t})=>[e,t]));function Nv(e,t="standard"){return tL.get(e.trim().toLowerCase())??t}function A2(e){return Mv(e,Xn)}function Mv(e,t){let n=Lv[e];return t.filter(r=>r.tier!=="internal"&&Lv[r.tier]<=n).map(r=>r.command)}function C2(e){return Pv(e,Xn)}function Pv(e,t){return t.filter(n=>n.family===e).map(n=>n.command)}var nL=["workspace","intake","context","lifecycle","evidence","graph","quality","automation","extensions","internal"],rL=new Set(["ctx","extension","install","item-reopen","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","packages","upgrade"]);function R2(e=Xn){return nL.map(t=>({family:t,commands:Pv(t,e).filter(n=>e.find(r=>r.command===n)?.tier!=="internal"&&!rL.has(n))})).filter(({commands:t})=>t.length>0)}var iL=Object.freeze({pm_append:"append",pm_claim:"claim",pm_close:"close",pm_comments:"comments",pm_config:"config",pm_context:"context",pm_contracts:"contracts",pm_copy:"copy",pm_create:"create",pm_deps:"deps",pm_discover:"help",pm_docs:"docs",pm_events:"history",pm_files:"files",pm_focus:"focus",pm_get:"get",pm_graph:"graph",pm_health:"health",pm_learnings:"learnings",pm_list:"list",pm_mutate:"update",pm_next:"next",pm_notes:"notes",pm_plan:"plan",pm_profile:"profile",pm_release:"release",pm_run:"package",pm_schema:"schema",pm_search:"search",pm_test:"test",pm_update:"update",pm_validate:"validate"});function O2(e,t){return sL(e,t,Xn)}function sL(e,t,n){if(t==="full")return[...e];let r=new Set(Mv(t,n));return e.filter(i=>{let s=iL[i];return s!==void 0&&r.has(s)})}var D2=Object.freeze([{uri:"pm://workspace/context",name:"Workspace context",description:"Bounded project context for orientation, including active hierarchy and progress.",mimeType:"application/json"},{uri:"pm://workspace/focus",name:"Active focus",description:"The session focus that supplies the default create parent.",mimeType:"application/json"},{uri:"pm://workspace/claims",name:"Active claims",description:"Bounded in-progress work and active ownership context.",mimeType:"application/json"},{uri:"pm://workspace/agent-guide",name:"Agent guidance",description:"Repository-local AGENTS.md instructions, bounded for safe host attachment.",mimeType:"text/markdown"}]),L2=Object.freeze([{name:"orient",description:"Build bounded live context, search all statuses, and select canonical work without creating duplicates.",arguments:[{name:"request",description:"The user's requested outcome or topic.",required:!0},{name:"scope",description:"Optional bounded workspace or subsystem scope.",required:!1}],template:"Orient to the live pm workspace for: {{request}}. Scope hint: {{scope}}. Read context, search all statuses, inspect full metadata for relevant items, and select canonical lineage before any mutation."},{name:"claim-and-start",description:"Claim one canonical item and begin implementation with linked context.",arguments:[{name:"id",description:"Canonical pm item id.",required:!0}],template:"Read {{id}} in full, claim it, set it in_progress, then implement only its acceptance scope while linking files, docs, tests, and evidence."},{name:"record-evidence-and-close",description:"Record exact verification evidence, close the item, and release ownership.",arguments:[{name:"id",description:"Canonical pm item id.",required:!0},{name:"evidence",description:"Exact verification and outcome evidence.",required:!0}],template:"For {{id}}, record this evidence: {{evidence}}. Verify linked tests, close only if acceptance is met, then release the claim."}]);function N2(){return oL(Xn)}function oL(e){return["# Generated agent command surface","","This file is generated from `PM_COMMAND_CAPABILITY_CONTRACTS`. Do not edit it manually.","","| Command | Minimum visibility tier | Capability family |","| --- | --- | --- |",...e.map(({command:n,tier:r,family:i})=>`| \`${n}\` | ${r} | ${i} |`),""].join(`
|
|
27
|
-
`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c76fa303-6672-5c1e-9cf5-3a08bd3a7814")}catch{}})();var aL=[{exit_code:1,class:"generic_failure"},{exit_code:2,class:"usage"},{exit_code:3,class:"not_found"},{exit_code:4,class:"conflict"},{exit_code:5,class:"dependency_failed"}],cL=new Map(aL.map(e=>[e.exit_code,e.class]));function bo(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))].sort()}function dL(e){if(!e)return[];let t=new Set,n=new Set;return e.map(r=>{let i=r.state.trim(),s=r.probe_id.trim(),o=bo(r.entrypoints);if(!/^[a-z][a-z0-9_]*$/.test(i)||!/^[a-z][a-z0-9-]*$/.test(s)||o.length===0||t.has(i)||n.has(s))throw new TypeError("Invalid pm refusal state contract");return t.add(i),n.add(s),{state:i,probe_id:s,entrypoints:o,expected_exit_class:r.expected_exit_class}}).sort((r,i)=>r.state.localeCompare(i.state))}function lL(e,t,n,r,i){return![[1,2,3,4,5].includes(e.exit_code),e.meaning.trim().length>0,e.recovery.trim().length>0,t.length>0,n.length>0,/^[a-z][a-z0-9_]*$/.test(r),i.every(s=>/^[a-z][a-z0-9_]*$/.test(s)),cL.get(e.exit_code)===e.class].includes(!1)}function uL(e,t){let n=e,r=new Set;for(;n.canonical_code!==n.code;){if(r.has(n.code))throw new TypeError(`Alias cycle in pm error code catalog: ${e.code}`);r.add(n.code);let i=t.get(n.canonical_code);if(!i)throw new TypeError(`Invalid pm error code contract: ${e.code}`);n=i}return n}function mL(e){let t=new Map(e.map(n=>[n.code,n]));for(let n of e){let r=uL(n,t);if(r.exit_code!==n.exit_code||r.class!==n.class)throw new TypeError(`Alias transport mismatch for pm error code: ${n.code}`);let i=e.filter(s=>s.code!==r.code&&s.canonical_code===r.code).map(s=>s.code).sort();if(n.code===r.code?JSON.stringify(n.aliases)!==JSON.stringify(i):n.aliases.length>0)throw new TypeError(`Invalid pm error code contract: ${n.code}`)}}function $v(e){let t=new Set,n=e.map(r=>{let i=r.code.trim();if(!/^[a-z][a-z0-9_]*$/.test(i))throw new TypeError(`Invalid pm error code: ${JSON.stringify(r.code)}`);if(t.has(i))throw new TypeError(`Duplicate pm error code: ${i}`);t.add(i);let s=bo(r.sources),o=bo(r.emitting_commands),a=(r.canonical_code??i).trim(),c=bo(r.aliases??[]),d=dL(r.owned_states);if(!lL(r,s,o,a,c))throw new TypeError(`Invalid pm error code contract: ${i}`);if(d.some(l=>l.expected_exit_class!==r.class))throw new TypeError(`Invalid pm refusal state exit class: ${i}`);return Object.freeze({...r,code:i,meaning:r.meaning.trim(),recovery:r.recovery.trim(),sources:s,emitting_commands:o,canonical_code:a,aliases:c,owned_states:d})});return mL(n),Object.freeze(n.sort((r,i)=>r.code.localeCompare(i.code)))}function P2(e,t){let n=Fv(e,t);return Fv(n.canonical_code??n.code,t)}function Fv(e,t){let n=e.trim(),r=t.find(i=>i.code===n);if(!r)throw new TypeError(`Unknown pm error code "${n}"`);return r}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="35c194c8-a164-5c90-9baa-9f2fc25c9bfb")}catch{}})();var jv=[{code:"acceptance_criteria_mutation_conflict",meaning:"Acceptance criteria mutation conflict condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/update.ts"],emitting_commands:["update","update-many"],canonical_code:"acceptance_criteria_mutation_conflict",aliases:[]},{code:"acceptance_criteria_remove_unmatched",meaning:"Acceptance criteria remove unmatched condition.",stability:"provisional",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/update-many.ts","sdk/lifecycle/update.ts"],emitting_commands:["update","update-many"],canonical_code:"acceptance_criteria_remove_unmatched",aliases:[]},{code:"acceptance_criteria_semicolon_forbidden",meaning:"Acceptance criteria semicolon forbidden condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/item/parse.ts"],emitting_commands:["*"],canonical_code:"acceptance_criteria_semicolon_forbidden",aliases:[]},{code:"accepted_rejected_value",meaning:"Accepted rejected value condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts"],emitting_commands:["*"],canonical_code:"accepted_rejected_value",aliases:[]},{code:"alias_collision",meaning:"Alias collision condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"],emitting_commands:["*"],canonical_code:"alias_collision",aliases:[]},{code:"alias_target_missing",meaning:"Alias target missing condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/grammar-contracts.ts"],emitting_commands:["*"],canonical_code:"alias_target_missing",aliases:[]},{code:"already_claimed_by",meaning:"Already claimed by condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/claim.ts"],emitting_commands:["claim"],canonical_code:"already_claimed_by",aliases:[]},{code:"ambiguous_option_combination",meaning:"Ambiguous option combination condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"],canonical_code:"ambiguous_option_combination",aliases:[]},{code:"annotation_alias_conflict",meaning:"Annotation alias conflict condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-annotations.ts"],emitting_commands:["*"],canonical_code:"annotation_alias_conflict",aliases:[]},{code:"annotation_flag_like_value",meaning:"Annotation flag like value condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/annotations.ts"],emitting_commands:["*"],canonical_code:"annotation_flag_like_value",aliases:[]},{code:"annotation_if_absent_without_append",meaning:"Annotation if absent without append condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/annotations.ts"],emitting_commands:["*"],canonical_code:"annotation_if_absent_without_append",aliases:[]},{code:"annotation_message_without_text",meaning:"Annotation message without text condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/annotations.ts"],emitting_commands:["*"],canonical_code:"annotation_message_without_text",aliases:[]},{code:"annotation_transposed_subcommand",meaning:"Annotation transposed subcommand condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-annotations.ts"],emitting_commands:["*"],canonical_code:"annotation_transposed_subcommand",aliases:[]},{code:"append_empty_body",meaning:"Append empty body condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/append.ts"],emitting_commands:["append"],canonical_code:"append_empty_body",aliases:[]},{code:"assurance_registry_invalid",meaning:"Assurance registry invalid condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/governance/assurance.ts"],emitting_commands:["*"],canonical_code:"assurance_registry_invalid",aliases:[]},{code:"bare_comma_entry_ambiguous",meaning:"Bare comma entry ambiguous condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/item/parse.ts"],emitting_commands:["*"],canonical_code:"bare_comma_entry_ambiguous",aliases:[]},{code:"body_file_conflicts_with_body",meaning:"Body file conflicts with body condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/io/body-file.ts"],emitting_commands:["*"],canonical_code:"body_file_conflicts_with_body",aliases:[]},{code:"body_file_missing_path",meaning:"Body file missing path condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/io/body-file.ts"],emitting_commands:["*"],canonical_code:"body_file_missing_path",aliases:[]},{code:"body_file_unreadable",meaning:"Body file unreadable condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/io/body-file.ts"],emitting_commands:["*"],canonical_code:"body_file_unreadable",aliases:[]},{code:"budget_exceeded",meaning:"Budget exceeded condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"],emitting_commands:["*"],canonical_code:"budget_exceeded",aliases:[]},{code:"bulk_ids_input_empty",meaning:"Bulk ids input empty condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/io/bulk-ids-input.ts","sdk/history-compact.ts","sdk/history-mcp.ts"],emitting_commands:["*"],canonical_code:"bulk_ids_input_empty",aliases:[],owned_states:[{state:"bulk_ids_stdin_contains_no_nonempty_ids",probe_id:"bulk-ids-stdin-empty",entrypoints:["update-many"],expected_exit_class:"usage"}]},{code:"bulk_ids_input_missing_path",meaning:"Bulk ids input missing path condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/io/bulk-ids-input.ts"],emitting_commands:["*"],canonical_code:"bulk_ids_input_missing_path",aliases:[],owned_states:[{state:"bulk_ids_file_token_omits_its_path",probe_id:"bulk-ids-file-path-missing",entrypoints:["update-many"],expected_exit_class:"usage"}]},{code:"bulk_ids_input_unreadable",meaning:"Bulk ids input unreadable condition.",stability:"provisional",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/io/bulk-ids-input.ts"],emitting_commands:["*"],canonical_code:"bulk_ids_input_unreadable",aliases:[],owned_states:[{state:"bulk_ids_file_path_cannot_be_read",probe_id:"bulk-ids-file-unreadable",entrypoints:["update-many"],expected_exit_class:"not_found"}]},{code:"bundle_integrity_torn_install",meaning:"Bundle integrity torn install condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/bundle-integrity.ts"],emitting_commands:["*"],canonical_code:"bundle_integrity_torn_install",aliases:[]},{code:"capability_undeclared",meaning:"Capability undeclared condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"],canonical_code:"capability_undeclared",aliases:[]},{code:"capability_unused",meaning:"Capability unused condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"],canonical_code:"capability_unused",aliases:[]},{code:"child_projection_item_bound_exceeded",meaning:"Child projection item bound exceeded condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/item-children.ts"],emitting_commands:["*"],canonical_code:"child_projection_item_bound_exceeded",aliases:[]},{code:"close_reason_required",meaning:"Close reason required condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle-policy.ts","sdk/lifecycle/close-many.ts"],emitting_commands:["*","close-many"],canonical_code:"close_reason_required",aliases:[]},{code:"close_through_update",meaning:"Close through update condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/telemetry/observability.ts"],emitting_commands:["*"],canonical_code:"close_through_update",aliases:[]},{code:"close_validation_missing_fields",meaning:"Close validation missing fields condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"],canonical_code:"close_validation_missing_fields",aliases:[]},{code:"collected_zero_items",meaning:"Collected zero items condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution.ts"],emitting_commands:["*"],canonical_code:"collected_zero_items",aliases:[]},{code:"collection_transposed_subcommand",meaning:"Collection transposed subcommand condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"],canonical_code:"collection_transposed_subcommand",aliases:[]},{code:"command_failed",meaning:"Command failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"],canonical_code:"command_failed",aliases:[]},{code:"command_namespace",meaning:"Command namespace condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/runtime-contracts.ts"],emitting_commands:["*"],canonical_code:"command_namespace",aliases:[]},{code:"command_override_conflict",meaning:"Command override conflict condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"],canonical_code:"command_override_conflict",aliases:[]},{code:"config_duplicate",meaning:"Config duplicate condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"config_duplicate",aliases:[]},{code:"config_key_unknown",meaning:"Config key unknown condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"config_key_unknown",aliases:[]},{code:"config_value_invalid",meaning:"Config value invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"config_value_invalid",aliases:[]},{code:"conflicting_lifecycle_owner",meaning:"Conflicting lifecycle owner condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-operations.ts"],emitting_commands:["*"],canonical_code:"conflicting_lifecycle_owner",aliases:[]},{code:"context_signal_store_invalid",meaning:"Context signal store invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/context-signal-store.ts"],emitting_commands:["*"],canonical_code:"context_signal_store_invalid",aliases:[]},{code:"context_signal_store_stale",meaning:"Context signal store stale condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/context-signal-store.ts"],emitting_commands:["*"],canonical_code:"context_signal_store_stale",aliases:[]},{code:"context_signal_store_write_failed",meaning:"Context signal store write failed condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/context-signal-store.ts"],emitting_commands:["*"],canonical_code:"context_signal_store_write_failed",aliases:[]},{code:"context_takes_no_item_argument",meaning:"Context takes no item argument condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"],canonical_code:"context_takes_no_item_argument",aliases:[]},{code:"core_item_field_requires_dedicated_flag",meaning:"Core item field requires dedicated flag condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/item-fields.ts"],emitting_commands:["*"],canonical_code:"core_item_field_requires_dedicated_flag",aliases:[]},{code:"create_positional_type_without_title",meaning:"Create positional type without title condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-mutation.ts"],emitting_commands:["*"],canonical_code:"create_positional_type_without_title",aliases:[]},{code:"dependency_edge_not_allowed",meaning:"Dependency edge not allowed condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/dependency-flag-validation.ts"],emitting_commands:["*"],canonical_code:"dependency_edge_not_allowed",aliases:[]},{code:"dependency_flag_value_invalid",meaning:"Dependency flag value invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/dependency-flag-validation.ts"],emitting_commands:["*"],canonical_code:"dependency_flag_value_invalid",aliases:[]},{code:"dependency_remove_no_match",meaning:"Dependency remove no match condition.",stability:"provisional",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"],canonical_code:"dependency_remove_no_match",aliases:[]},{code:"dependency_target_not_found",meaning:"Dependency target not found condition.",stability:"provisional",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/dependency-flag-validation.ts"],emitting_commands:["*"],canonical_code:"dependency_target_not_found",aliases:[]},{code:"dependency_temporal_order_invalid",meaning:"Dependency temporal order invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/dependency-flag-validation.ts"],emitting_commands:["*"],canonical_code:"dependency_temporal_order_invalid",aliases:[]},{code:"duplicate_canonical_flag",meaning:"Duplicate canonical flag condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"],emitting_commands:["*"],canonical_code:"duplicate_canonical_flag",aliases:[]},{code:"duplicate_command",meaning:"Duplicate command condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"],canonical_code:"duplicate_command",aliases:[]},{code:"duplicate_destination",meaning:"Duplicate destination condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/grammar-contracts.ts"],emitting_commands:["*"],canonical_code:"duplicate_destination",aliases:[]},{code:"duplicate_edge",meaning:"Duplicate edge condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/graph/remediation.ts"],emitting_commands:["*"],canonical_code:"duplicate_edge",aliases:[]},{code:"duplicate_observation",meaning:"Duplicate observation condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/flag-invocation-contracts.ts"],emitting_commands:["*"],canonical_code:"duplicate_observation",aliases:[]},{code:"duplicate_probe",meaning:"Duplicate probe condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts"],emitting_commands:["*"],canonical_code:"duplicate_probe",aliases:[]},{code:"duplicate_sweep_cost_limit",meaning:"Duplicate sweep cost limit condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/query/duplicate-candidates.ts"],emitting_commands:["duplicate-candidates"],canonical_code:"duplicate_sweep_cost_limit",aliases:[]},{code:"duplicate_target_circular",meaning:"Duplicate target circular condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"],canonical_code:"duplicate_target_circular",aliases:[]},{code:"duplicate_target_is_duplicate",meaning:"Duplicate target is duplicate condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"],canonical_code:"duplicate_target_is_duplicate",aliases:[]},{code:"duplicate_target_missing",meaning:"Duplicate target missing condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"],canonical_code:"duplicate_target_missing",aliases:[]},{code:"duplicate_target_self",meaning:"Duplicate target self condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"],canonical_code:"duplicate_target_self",aliases:[]},{code:"empty_corpus",meaning:"Empty corpus condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts"],emitting_commands:["*"],canonical_code:"empty_corpus",aliases:[]},{code:"empty_surface",meaning:"Empty surface condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"],canonical_code:"empty_surface",aliases:[]},{code:"error_code_mismatch",meaning:"Error code mismatch condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts","sdk/agent/tracker-preflight-contracts.ts"],emitting_commands:["*"],canonical_code:"error_code_mismatch",aliases:[]},{code:"event_cursor_query_mismatch",meaning:"Event cursor query mismatch condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-events.ts"],emitting_commands:["*"],canonical_code:"event_cursor_query_mismatch",aliases:[]},{code:"event_index_unavailable",meaning:"Event index unavailable condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-events.ts"],emitting_commands:["*"],canonical_code:"event_index_unavailable",aliases:[]},{code:"exit_code_mismatch",meaning:"Exit code mismatch condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/tracker-preflight-contracts.ts"],emitting_commands:["*"],canonical_code:"exit_code_mismatch",aliases:[]},{code:"extension_command_activation_failed",meaning:"Extension command activation failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/commander-usage.ts"],emitting_commands:["*"],canonical_code:"extension_command_activation_failed",aliases:[]},{code:"extension_dependency_name_unsafe",meaning:"Extension dependency name unsafe condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"],canonical_code:"extension_dependency_name_unsafe",aliases:[]},{code:"extension_dependency_spec_invalid",meaning:"Extension dependency spec invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"],canonical_code:"extension_dependency_spec_invalid",aliases:[]},{code:"extension_dependency_version_unsafe",meaning:"Extension dependency version unsafe condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"],canonical_code:"extension_dependency_version_unsafe",aliases:[]},{code:"extension_install_soft_failed",meaning:"Extension install soft failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-setup.ts"],emitting_commands:["*"],canonical_code:"extension_install_soft_failed",aliases:[]},{code:"extension_install_source_contains_destination",meaning:"Extension install source contains destination condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-runtime.ts"],emitting_commands:["*"],canonical_code:"extension_install_source_contains_destination",aliases:[]},{code:"extension_item_field_reserved",meaning:"Extension item field reserved condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/item-fields.ts"],emitting_commands:["*"],canonical_code:"extension_item_field_reserved",aliases:[]},{code:"extension_item_field_type_conflict",meaning:"Extension item field type conflict condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/item-fields.ts"],emitting_commands:["*"],canonical_code:"extension_item_field_type_conflict",aliases:[]},{code:"extension_item_field_unknown",meaning:"Extension item field unknown condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/item-fields.ts"],emitting_commands:["*"],canonical_code:"extension_item_field_unknown",aliases:[]},{code:"extension_mutation_guard_failed",meaning:"Extension mutation guard failed condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/extension-hook-runtime.ts"],emitting_commands:["*"],canonical_code:"extension_mutation_guard_failed",aliases:[]},{code:"extension_mutation_guard_invalid_decision",meaning:"Extension mutation guard invalid decision condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/extension-hook-runtime.ts"],emitting_commands:["*"],canonical_code:"extension_mutation_guard_invalid_decision",aliases:[]},{code:"extension_mutation_guard_invalid_denial",meaning:"Extension mutation guard invalid denial condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/extension-hook-runtime.ts"],emitting_commands:["*"],canonical_code:"extension_mutation_guard_invalid_denial",aliases:[]},{code:"extension_mutation_guard_timed_out",meaning:"Extension mutation guard timed out condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/extension-hook-runtime.ts"],emitting_commands:["*"],canonical_code:"extension_mutation_guard_timed_out",aliases:[]},{code:"extension_update_health_partial_coverage",meaning:"Extension update health partial coverage condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"extension_update_health_partial_coverage",aliases:[]},{code:"field_duplicate",meaning:"Field duplicate condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"field_duplicate",aliases:[]},{code:"field_invalid",meaning:"Field invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"field_invalid",aliases:[]},{code:"field_mcp_input_collision",meaning:"Field mcp input collision condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"field_mcp_input_collision",aliases:[]},{code:"github_source_entry_unbuilt",meaning:"Github source entry unbuilt condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/shared.ts"],emitting_commands:["*"],canonical_code:"github_source_entry_unbuilt",aliases:[]},{code:"hierarchy_cardinality_created",meaning:"Hierarchy cardinality created condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/graph/hierarchy-integrity.ts"],emitting_commands:["*"],canonical_code:"hierarchy_cardinality_created",aliases:[]},{code:"hierarchy_cycle_created",meaning:"Hierarchy cycle created condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/graph/hierarchy-integrity.ts"],emitting_commands:["*"],canonical_code:"hierarchy_cycle_created",aliases:[]},{code:"hierarchy_parent_divergence_created",meaning:"Hierarchy parent divergence created condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/graph/hierarchy-integrity.ts"],emitting_commands:["*"],canonical_code:"hierarchy_parent_divergence_created",aliases:[]},{code:"history_author_acknowledge_plan_conflict",meaning:"History author acknowledge plan conflict condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/author-attribution.ts"],emitting_commands:["*"],canonical_code:"history_author_acknowledge_plan_conflict",aliases:[]},{code:"history_author_acknowledge_plan_fingerprint_required",meaning:"History author acknowledge plan fingerprint required condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/author-attribution.ts"],emitting_commands:["*"],canonical_code:"history_author_acknowledge_plan_fingerprint_required",aliases:[]},{code:"history_author_acknowledge_preview_limit_invalid",meaning:"History author acknowledge preview limit invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/author-attribution.ts"],emitting_commands:["*"],canonical_code:"history_author_acknowledge_preview_limit_invalid",aliases:[]},{code:"history_author_acknowledge_required_values_missing",meaning:"History author acknowledge required values missing condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/author-attribution.ts"],emitting_commands:["*"],canonical_code:"history_author_acknowledge_required_values_missing",aliases:[]},{code:"history_author_acknowledge_selector_conflict",meaning:"History author acknowledge selector conflict condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/author-attribution.ts"],emitting_commands:["*"],canonical_code:"history_author_acknowledge_selector_conflict",aliases:[]},{code:"history_author_acknowledge_selector_required",meaning:"History author acknowledge selector required condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/author-attribution.ts"],emitting_commands:["*"],canonical_code:"history_author_acknowledge_selector_required",aliases:[]},{code:"history_author_acknowledge_target_not_actionable",meaning:"History author acknowledge target not actionable condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/author-attribution.ts"],emitting_commands:["*"],canonical_code:"history_author_acknowledge_target_not_actionable",aliases:[]},{code:"history_author_acknowledge_target_unreadable",meaning:"History author acknowledge target unreadable condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/author-attribution.ts"],emitting_commands:["*"],canonical_code:"history_author_acknowledge_target_unreadable",aliases:[]},{code:"history_baseline_unavailable",meaning:"History baseline unavailable condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/projection.ts"],emitting_commands:["*"],canonical_code:"history_baseline_unavailable",aliases:[]},{code:"history_drift_chain_mismatch",meaning:"History drift chain mismatch condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_chain_mismatch",aliases:["validate_history_drift_chain_mismatches"]},{code:"history_drift_hash_mismatch",meaning:"History drift hash mismatch condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_hash_mismatch",aliases:["validate_history_drift_hash_mismatches"]},{code:"history_drift_merge_receipt",meaning:"History drift merge receipt condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_merge_receipt",aliases:[]},{code:"history_drift_missing_stream",meaning:"History drift missing stream condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_missing_stream",aliases:["validate_history_drift_missing_streams"]},{code:"history_drift_unreadable_stream",meaning:"History drift unreadable stream condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_unreadable_stream",aliases:["validate_history_drift_unreadable_streams"]},{code:"history_drift_version_skew",meaning:"History drift version skew condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_version_skew",aliases:["validate_history_drift_version_skews"]},{code:"history_json_invalid",meaning:"History json invalid condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/read.ts"],emitting_commands:["*"],canonical_code:"history_json_invalid",aliases:[]},{code:"history_merge_conflict_markers_detected",meaning:"History merge conflict markers detected condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/read.ts"],emitting_commands:["*"],canonical_code:"merge_conflict_markers_detected",aliases:[]},{code:"history_replay_invalid",meaning:"History replay invalid condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/projection.ts"],emitting_commands:["*"],canonical_code:"history_replay_invalid",aliases:[]},{code:"history_salvage_refused",meaning:"History salvage refused condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/history/salvage.ts"],emitting_commands:["*"],canonical_code:"history_salvage_refused",aliases:[]},{code:"history_stream_over_compact_threshold",meaning:"History stream over compact threshold condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_stream_over_compact_threshold",aliases:[]},{code:"history_target_out_of_range",meaning:"History target out of range condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/projection.ts"],emitting_commands:["*"],canonical_code:"history_target_out_of_range",aliases:[]},{code:"history_timestamp_invalid",meaning:"History timestamp invalid condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/event-index.ts","core/history/history.ts"],emitting_commands:["*"],canonical_code:"history_timestamp_invalid",aliases:[]},{code:"history_unknown_author_events",meaning:"History unknown author events condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_unknown_author_events",aliases:["validate_history_unknown_author_events"]},{code:"history_version_mapping_unavailable",meaning:"History version mapping unavailable condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/version-address.ts"],emitting_commands:["*"],canonical_code:"history_version_mapping_unavailable",aliases:[]},{code:"history_version_pruned",meaning:"History version pruned condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/projection.ts"],emitting_commands:["*"],canonical_code:"history_version_pruned",aliases:[]},{code:"host_environment_capacity_fault",meaning:"Host environment capacity fault condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/fs/host-environment-errors.ts"],emitting_commands:["*"],canonical_code:"host_environment_capacity_fault",aliases:[]},{code:"host_environment_operation_invalid",meaning:"Host environment operation invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/fs/host-environment-errors.ts"],emitting_commands:["*"],canonical_code:"host_environment_operation_invalid",aliases:[]},{code:"host_environment_permission_fault",meaning:"Host environment permission fault condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/fs/host-environment-errors.ts"],emitting_commands:["*"],canonical_code:"host_environment_permission_fault",aliases:[]},{code:"host_environment_resource_fault",meaning:"Host environment resource fault condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/fs/host-environment-errors.ts"],emitting_commands:["*"],canonical_code:"host_environment_resource_fault",aliases:[]},{code:"improvement_metric_contract_conflict",meaning:"Improvement metric contract conflict condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/improvement-ledger.ts"],emitting_commands:["*"],canonical_code:"improvement_metric_contract_conflict",aliases:[]},{code:"improvement_observation_conflict",meaning:"Improvement observation conflict condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/improvement-ledger.ts"],emitting_commands:["*"],canonical_code:"improvement_observation_conflict",aliases:[]},{code:"incomplete_allowed_values",meaning:"Incomplete allowed values condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts"],emitting_commands:["*"],canonical_code:"incomplete_allowed_values",aliases:[]},{code:"inconsistent_concept_kind",meaning:"Inconsistent concept kind condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"],emitting_commands:["*"],canonical_code:"inconsistent_concept_kind",aliases:[]},{code:"init_existing_settings_requires_force",meaning:"Init existing settings requires force condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/init.ts"],emitting_commands:["*"],canonical_code:"init_existing_settings_requires_force",aliases:[]},{code:"init_gitignore_unwritable",meaning:"Init gitignore unwritable condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace.ts"],emitting_commands:["*"],canonical_code:"init_gitignore_unwritable",aliases:[]},{code:"init_id_prefix_conflict",meaning:"Init id prefix conflict condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/init.ts"],emitting_commands:["*"],canonical_code:"init_id_prefix_conflict",aliases:[]},{code:"init_id_prefix_path_like",meaning:"Init id prefix path like condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/init.ts"],emitting_commands:["*"],canonical_code:"init_id_prefix_path_like",aliases:[]},{code:"integrity_history_conflict_marker",meaning:"Integrity history conflict marker condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_history_conflict_marker",aliases:["validate_storage_history_conflict_markers"]},{code:"integrity_history_invalid_json",meaning:"Integrity history invalid json condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_history_invalid_json",aliases:[]},{code:"integrity_history_unreadable",meaning:"Integrity history unreadable condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_history_unreadable",aliases:[]},{code:"integrity_item_ahead_format_version",meaning:"Integrity item ahead format version condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_item_ahead_format_version",aliases:["validate_format_version_ahead_items"]},{code:"integrity_item_conflict_marker",meaning:"Integrity item conflict marker condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_item_conflict_marker",aliases:[]},{code:"integrity_item_outdated_format_version",meaning:"Integrity item outdated format version condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_item_outdated_format_version",aliases:["validate_format_version_outdated_items"]},{code:"integrity_item_parse_failed",meaning:"Integrity item parse failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_item_parse_failed",aliases:[]},{code:"integrity_item_unreadable",meaning:"Integrity item unreadable condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_item_unreadable",aliases:[]},{code:"invalid_argument_value",meaning:"Invalid argument value condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts","sdk/context-intent-contracts.ts","sdk/governance/assurance-mutation-error.ts","sdk/lifecycle/create.ts"],emitting_commands:["*","create"],canonical_code:"invalid_argument_value",aliases:[]},{code:"invalid_command_usage",meaning:"Invalid command usage condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts"],emitting_commands:["*"],canonical_code:"invalid_command_usage",aliases:[]},{code:"invalid_event_cursor",meaning:"Invalid event cursor condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-events.ts"],emitting_commands:["*"],canonical_code:"invalid_event_cursor",aliases:[]},{code:"invalid_event_cursor_mode",meaning:"Invalid event cursor mode condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-list-query.ts","sdk/mutation-events.ts","sdk/runtime-extended-actions.ts"],emitting_commands:["*"],canonical_code:"invalid_event_cursor_mode",aliases:[]},{code:"invalid_event_follow_interval",meaning:"Invalid event follow interval condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-events.ts"],emitting_commands:["*"],canonical_code:"invalid_event_follow_interval",aliases:[]},{code:"invalid_event_limit",meaning:"Invalid event limit condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-events.ts"],emitting_commands:["*"],canonical_code:"invalid_event_limit",aliases:[]},{code:"invalid_event_since",meaning:"Invalid event since condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-events.ts"],emitting_commands:["*"],canonical_code:"invalid_event_since",aliases:[]},{code:"invalid_history_analytics_limit",meaning:"Invalid history analytics limit condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/history-analytics.ts"],emitting_commands:["*"],canonical_code:"invalid_history_analytics_limit",aliases:[]},{code:"invalid_history_analytics_minimum_sample",meaning:"Invalid history analytics minimum sample condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/history-analytics.ts"],emitting_commands:["*"],canonical_code:"invalid_history_analytics_minimum_sample",aliases:[]},{code:"invalid_history_analytics_since",meaning:"Invalid history analytics since condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/history-analytics.ts"],emitting_commands:["*"],canonical_code:"invalid_history_analytics_since",aliases:[]},{code:"invalid_improvement_ledger",meaning:"Invalid improvement ledger condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/improvement-ledger-validation.ts"],emitting_commands:["*"],canonical_code:"invalid_improvement_ledger",aliases:[]},{code:"invalid_improvement_metric",meaning:"Invalid improvement metric condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/improvement-ledger.ts"],emitting_commands:["*"],canonical_code:"invalid_improvement_metric",aliases:[]},{code:"invalid_improvement_observation",meaning:"Invalid improvement observation condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/improvement-ledger.ts"],emitting_commands:["*"],canonical_code:"invalid_improvement_observation",aliases:[]},{code:"invalid_improvement_observation_limit",meaning:"Invalid improvement observation limit condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/improvement-ledger.ts"],emitting_commands:["*"],canonical_code:"invalid_improvement_observation_limit",aliases:[]},{code:"invalid_improvement_observation_timestamp",meaning:"Invalid improvement observation timestamp condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/improvement-ledger.ts"],emitting_commands:["*"],canonical_code:"invalid_improvement_observation_timestamp",aliases:[]},{code:"invalid_provenance_predicate",meaning:"Invalid provenance predicate condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/history-provenance.ts"],emitting_commands:["*"],canonical_code:"invalid_provenance_predicate",aliases:[]},{code:"invalid_query_cursor",meaning:"Invalid query cursor condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/pagination.ts"],emitting_commands:["*"],canonical_code:"invalid_query_cursor",aliases:[]},{code:"invalid_read_output_session",meaning:"Invalid read output session condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/read-output-session.ts"],emitting_commands:["*"],canonical_code:"invalid_read_output_session",aliases:[]},{code:"invalid_reproducible_process_environment",meaning:"Invalid reproducible process environment condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/reproducibility/process.ts"],emitting_commands:["*"],canonical_code:"invalid_reproducible_process_environment",aliases:[]},{code:"invalid_workspace_snapshot_target",meaning:"Invalid workspace snapshot target condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"],canonical_code:"invalid_workspace_snapshot_target",aliases:[]},{code:"item_already_active",meaning:"Item already active condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"],canonical_code:"item_already_active",aliases:[]},{code:"item_document_encoding_invalid",meaning:"Item document encoding invalid condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/store/item-store.ts"],emitting_commands:["*"],canonical_code:"item_document_encoding_invalid",aliases:[]},{code:"item_document_invalid",meaning:"Item document invalid condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/item/item-format.ts"],emitting_commands:["*"],canonical_code:"item_document_invalid",aliases:[]},{code:"item_document_roundtrip_failed",meaning:"Item document roundtrip failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/item/item-format.ts"],emitting_commands:["*"],canonical_code:"item_document_roundtrip_failed",aliases:[]},{code:"item_id_collision",meaning:"Item id collision condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/copy.ts"],emitting_commands:["copy"],canonical_code:"item_id_collision",aliases:[]},{code:"item_identity_reserved",meaning:"Item identity reserved condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/history.ts"],emitting_commands:["*"],canonical_code:"item_identity_reserved",aliases:[]},{code:"item_not_found",meaning:"Item not found condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts"],emitting_commands:["*"],canonical_code:"item_not_found",aliases:[]},{code:"likely_duplicate",meaning:"Likely duplicate condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/similarity.ts"],emitting_commands:["*"],canonical_code:"likely_duplicate",aliases:[]},{code:"linked_artifact_mutation_conflict",meaning:"Linked artifact mutation conflict condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/linked-artifacts.ts"],emitting_commands:["*"],canonical_code:"linked_artifact_mutation_conflict",aliases:[]},{code:"linked_test_remove_no_match",meaning:"Linked test remove no match condition.",stability:"provisional",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution.ts"],emitting_commands:["*"],canonical_code:"linked_test_remove_no_match",aliases:[]},{code:"linked_test_value_not_quoted",meaning:"Linked test value not quoted condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"],canonical_code:"linked_test_value_not_quoted",aliases:[]},{code:"list_source_incomplete",meaning:"List source incomplete condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/query/list.ts"],emitting_commands:["list"],canonical_code:"list_source_incomplete",aliases:[]},{code:"local_package_archive_unsafe",meaning:"Local package archive unsafe condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"],canonical_code:"local_package_archive_unsafe",aliases:[]},{code:"local_source_not_found_bare_name",meaning:"Local source not found bare name condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"],canonical_code:"local_source_not_found_bare_name",aliases:[]},{code:"lock_conflict",meaning:"Lock conflict condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/lock/lock.ts","core/telemetry/observability.ts"],emitting_commands:["*"],canonical_code:"lock_conflict",aliases:[]},{code:"locks_stale_count",meaning:"Locks stale count condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"locks_stale_count",aliases:[]},{code:"locks_unreadable",meaning:"Locks unreadable condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"locks_unreadable",aliases:[]},{code:"malformed_plan_step_evidence",meaning:"Malformed plan step evidence condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"],canonical_code:"malformed_plan_step_evidence",aliases:[]},{code:"manifest_capabilities_absent",meaning:"Manifest capabilities absent condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"],canonical_code:"manifest_capabilities_absent",aliases:[]},{code:"manifest_unknown_key",meaning:"Manifest unknown key condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/manifest-schema.ts"],emitting_commands:["*"],canonical_code:"manifest_unknown_key",aliases:[],owned_states:[{state:"author_workspace_manifest_declares_an_unknown_top_level_key",probe_id:"author-manifest-unknown-key",entrypoints:["health"],expected_exit_class:"generic_failure"}]},{code:"mcp_annotation_file_unavailable",meaning:"Mcp annotation file unavailable condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/runtime-input.ts"],emitting_commands:["*"],canonical_code:"mcp_annotation_file_unavailable",aliases:[]},{code:"mcp_stdin_unavailable",meaning:"Mcp stdin unavailable condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/annotations.ts"],emitting_commands:["*"],canonical_code:"mcp_stdin_unavailable",aliases:[]},{code:"mcp_task_not_found_or_not_authorized",meaning:"Mcp task not found or not authorized condition.",stability:"provisional",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mcp/tasks.ts"],emitting_commands:["*"],canonical_code:"mcp_task_not_found_or_not_authorized",aliases:[]},{code:"merge_conflict_markers_detected",meaning:"Merge conflict markers detected condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/item/item-format.ts"],emitting_commands:["*"],canonical_code:"merge_conflict_markers_detected",aliases:["history_merge_conflict_markers_detected"]},{code:"merge_decisions_unreviewed",meaning:"Merge decisions unreviewed condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"merge_decisions_unreviewed",aliases:[]},{code:"merge_git_config_unwritable",meaning:"Merge git config unwritable condition.",stability:"stable",exit_code:5,class:"dependency_failed",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/merge/install.ts"],emitting_commands:["*"],canonical_code:"merge_git_config_unwritable",aliases:[]},{code:"merge_receipt_evidence_invalid",meaning:"Merge receipt evidence invalid condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts","sdk/merge/reconcile.ts"],emitting_commands:["*"],canonical_code:"merge_receipt_evidence_invalid",aliases:[]},{code:"merge_receipt_history_reference_missing",meaning:"Merge receipt history reference missing condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"merge_receipt_history_reference_missing",aliases:[]},{code:"merge_receipts_pending",meaning:"Merge receipts pending condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"merge_receipts_pending",aliases:[]},{code:"merge_reconcile_receipt_evidence_untrusted",meaning:"Merge reconcile receipt evidence untrusted condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/history-repair.ts"],emitting_commands:["*"],canonical_code:"merge_reconcile_receipt_evidence_untrusted",aliases:[]}];(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="aa8f034d-d4b6-595b-af76-f7203d062971")}catch{}})();var Uv=[{code:"merge_root_not_found",meaning:"Merge root not found condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/merge/install.ts"],emitting_commands:["*"],canonical_code:"merge_root_not_found",aliases:[]},{code:"missing_allowed_values",meaning:"Missing allowed values condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts"],emitting_commands:["*"],canonical_code:"missing_allowed_values",aliases:[]},{code:"missing_budget",meaning:"Missing budget condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"],emitting_commands:["*"],canonical_code:"missing_budget",aliases:[]},{code:"missing_cli_flag",meaning:"Missing cli flag condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/tool-option-contracts.ts"],emitting_commands:["*"],canonical_code:"missing_cli_flag",aliases:[]},{code:"missing_destination",meaning:"Missing destination condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/grammar-contracts.ts"],emitting_commands:["*"],canonical_code:"missing_destination",aliases:[]},{code:"missing_directory",meaning:"Missing directory condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"missing_directory",aliases:[]},{code:"missing_init_recovery",meaning:"Missing init recovery condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/tracker-preflight-contracts.ts"],emitting_commands:["*"],canonical_code:"missing_init_recovery",aliases:[]},{code:"missing_lifecycle_target",meaning:"Missing lifecycle target condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension.ts"],emitting_commands:["*"],canonical_code:"missing_lifecycle_target",aliases:[]},{code:"missing_observation",meaning:"Missing observation condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/flag-invocation-contracts.ts"],emitting_commands:["*"],canonical_code:"missing_observation",aliases:[]},{code:"missing_observed_signature",meaning:"Missing observed signature condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/grammar-contracts.ts"],emitting_commands:["*"],canonical_code:"missing_observed_signature",aliases:[]},{code:"missing_parameter_alias",meaning:"Missing parameter alias condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/tool-option-contracts.ts"],emitting_commands:["*"],canonical_code:"missing_parameter_alias",aliases:[]},{code:"missing_positive_execution_receipt",meaning:"Missing positive execution receipt condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution.ts"],emitting_commands:["*"],canonical_code:"missing_positive_execution_receipt",aliases:[]},{code:"missing_probe",meaning:"Missing probe condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/tracker-preflight-contracts.ts"],emitting_commands:["*"],canonical_code:"missing_probe",aliases:[]},{code:"missing_required_argument",meaning:"Missing required argument condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","cli/main.ts","cli/register-mutation.ts","core/telemetry/observability.ts","sdk/governance/assurance-action.ts","sdk/history-redact.ts","sdk/invocation-author.ts"],emitting_commands:["*"],canonical_code:"missing_required_argument",aliases:[]},{code:"missing_required_option",meaning:"Missing required option condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts","sdk/context-intent-contracts.ts","sdk/lifecycle/create.ts","sdk/lifecycle/plan.ts"],emitting_commands:["*","create","plan"],canonical_code:"missing_required_option",aliases:[]},{code:"missing_suggested_retry",meaning:"Missing suggested retry condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts"],emitting_commands:["*"],canonical_code:"missing_suggested_retry",aliases:[]},{code:"missing_suggested_retry_args",meaning:"Missing suggested retry args condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts"],emitting_commands:["*"],canonical_code:"missing_suggested_retry_args",aliases:[]},{code:"module_import_failed",meaning:"Module import failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"],canonical_code:"module_import_failed",aliases:[]},{code:"multi_target_github_install_ambiguous",meaning:"Multi target github install ambiguous condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-setup.ts"],emitting_commands:["*"],canonical_code:"multi_target_github_install_ambiguous",aliases:[]},{code:"mutation_author_required",meaning:"Mutation author required condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-guard.ts"],emitting_commands:["*"],canonical_code:"mutation_author_required",aliases:[]},{code:"mutation_secret_guard_blocked",meaning:"Mutation secret guard blocked condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-guard.ts"],emitting_commands:["*"],canonical_code:"mutation_secret_guard_blocked",aliases:[]},{code:"no_matching_tests",meaning:"No matching tests condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution.ts"],emitting_commands:["*"],canonical_code:"no_matching_tests",aliases:[]},{code:"no_projects_matched_filters",meaning:"No projects matched filters condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution.ts"],emitting_commands:["*"],canonical_code:"no_projects_matched_filters",aliases:[]},{code:"no_test_files_found",meaning:"No test files found condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution.ts"],emitting_commands:["*"],canonical_code:"no_test_files_found",aliases:[]},{code:"no_tests_found",meaning:"No tests found condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution.ts"],emitting_commands:["*"],canonical_code:"no_tests_found",aliases:[]},{code:"no_update_fields",meaning:"No update fields condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts"],emitting_commands:["*"],canonical_code:"no_update_fields",aliases:[]},{code:"no_version_bounds_declared",meaning:"No version bounds declared condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/manifest-schema.ts"],emitting_commands:["*"],canonical_code:"no_version_bounds_declared",aliases:[],owned_states:[{state:"author_workspace_manifest_omits_canonical_pm_version_bounds",probe_id:"author-manifest-version-bounds-missing",entrypoints:["health"],expected_exit_class:"generic_failure"}]},{code:"non_refusal_exit",meaning:"Non refusal exit condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts"],emitting_commands:["*"],canonical_code:"non_refusal_exit",aliases:[]},{code:"npm_pack_json_shape_unsupported",meaning:"Npm pack json shape unsupported condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"],canonical_code:"npm_pack_json_shape_unsupported",aliases:[]},{code:"npm_package_archive_missing",meaning:"Npm package archive missing condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"],canonical_code:"npm_package_archive_missing",aliases:[]},{code:"npm_package_archive_unsafe",meaning:"Npm package archive unsafe condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"],canonical_code:"npm_package_archive_unsafe",aliases:[]},{code:"npm_package_not_found",meaning:"Npm package not found condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"],canonical_code:"npm_package_not_found",aliases:[]},{code:"ownership_conflict",meaning:"Ownership conflict condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts","sdk/annotations.ts"],emitting_commands:["*"],canonical_code:"ownership_conflict",aliases:[]},{code:"ownership_dependency_bypass_restricted_options",meaning:"Ownership dependency bypass restricted options condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"],canonical_code:"ownership_dependency_bypass_restricted_options",aliases:[]},{code:"ownership_metadata_bypass_restricted_options",meaning:"Ownership metadata bypass restricted options condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"],canonical_code:"ownership_metadata_bypass_restricted_options",aliases:[]},{code:"package_spec_empty",meaning:"Package spec empty condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"package_spec_empty",aliases:[]},{code:"package_upgrade_modes_mutually_exclusive",meaning:"Package upgrade modes mutually exclusive condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/governance/upgrade.ts"],emitting_commands:["*"],canonical_code:"package_upgrade_modes_mutually_exclusive",aliases:[]},{code:"positional_shape_budget_exceeded",meaning:"Positional shape budget exceeded condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/grammar-contracts.ts"],emitting_commands:["*"],canonical_code:"positional_shape_budget_exceeded",aliases:[]},{code:"positional_signature_mismatch",meaning:"Positional signature mismatch condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/grammar-contracts.ts"],emitting_commands:["*"],canonical_code:"positional_signature_mismatch",aliases:[]},{code:"profile_name_empty",meaning:"Profile name empty condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"profile_name_empty",aliases:[]},{code:"profile_name_not_normalized",meaning:"Profile name not normalized condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"profile_name_not_normalized",aliases:[]},{code:"profile_summary_empty",meaning:"Profile summary empty condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"profile_summary_empty",aliases:[]},{code:"profile_title_empty",meaning:"Profile title empty condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"profile_title_empty",aliases:[]},{code:"project_runtime_history_epoch_incompatible",meaning:"Project runtime history epoch incompatible condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/environment/project-runtime-compatibility.ts"],emitting_commands:["*"],canonical_code:"project_runtime_history_epoch_incompatible",aliases:[]},{code:"project_runtime_stale_mutation",meaning:"Project runtime stale mutation condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/environment/project-runtime-compatibility.ts"],emitting_commands:["*"],canonical_code:"project_runtime_stale_mutation",aliases:[]},{code:"project_runtime_stale_read",meaning:"Project runtime stale read condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/environment/project-runtime-compatibility.ts"],emitting_commands:["*"],canonical_code:"project_runtime_stale_read",aliases:[]},{code:"projection_options_mutually_exclusive",meaning:"Projection options mutually exclusive condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/query/get.ts","sdk/query/list.ts","sdk/query/search-contracts.ts"],emitting_commands:["get","list","search"],canonical_code:"projection_options_mutually_exclusive",aliases:[]},{code:"provenance_value_domain_invalid",meaning:"Provenance value domain invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"provenance_value_domain_invalid",aliases:[]},{code:"read_output_cursor_command_mismatch",meaning:"Read output cursor command mismatch condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/read-output/continuation.ts"],emitting_commands:["*"],canonical_code:"read_output_cursor_command_mismatch",aliases:[]},{code:"read_output_cursor_invalid",meaning:"Read output cursor invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/read-output/continuation.ts"],emitting_commands:["*"],canonical_code:"read_output_cursor_invalid",aliases:[]},{code:"read_output_cursor_stale",meaning:"Read output cursor stale condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/read-output/continuation.ts"],emitting_commands:["*"],canonical_code:"read_output_cursor_stale",aliases:[]},{code:"recovery_kind_mismatch",meaning:"Recovery kind mismatch condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/tracker-preflight-contracts.ts"],emitting_commands:["*"],canonical_code:"recovery_kind_mismatch",aliases:[]},{code:"redundant_edge",meaning:"Redundant edge condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/graph/remediation.ts"],emitting_commands:["*"],canonical_code:"redundant_edge",aliases:[]},{code:"refusal_allowed_values_mismatch",meaning:"Refusal allowed values mismatch condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-corpus-contracts.ts"],emitting_commands:["*"],canonical_code:"refusal_allowed_values_mismatch",aliases:[]},{code:"refusal_error_code_mismatch",meaning:"Refusal error code mismatch condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-corpus-contracts.ts"],emitting_commands:["*"],canonical_code:"refusal_error_code_mismatch",aliases:[]},{code:"refusal_exit_code_mismatch",meaning:"Refusal exit code mismatch condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-corpus-contracts.ts"],emitting_commands:["*"],canonical_code:"refusal_exit_code_mismatch",aliases:[]},{code:"refusal_mutated_state",meaning:"Refusal mutated state condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-corpus-contracts.ts"],emitting_commands:["*"],canonical_code:"refusal_mutated_state",aliases:[]},{code:"refusal_probe_missing",meaning:"Refusal probe missing condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-corpus-contracts.ts"],emitting_commands:["*"],canonical_code:"refusal_probe_missing",aliases:[]},{code:"refusal_recovery_failed",meaning:"Refusal recovery failed condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-corpus-contracts.ts"],emitting_commands:["*"],canonical_code:"refusal_recovery_failed",aliases:[]},{code:"reindex_already_running",meaning:"Reindex already running condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/governance/reindex.ts"],emitting_commands:["*"],canonical_code:"reindex_already_running",aliases:[]},{code:"removed_canonical_spelling",meaning:"Removed canonical spelling condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"],emitting_commands:["*"],canonical_code:"removed_canonical_spelling",aliases:[]},{code:"removed_compatibility_spelling",meaning:"Removed compatibility spelling condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"],emitting_commands:["*"],canonical_code:"removed_compatibility_spelling",aliases:[]},{code:"reopen_reason_required",meaning:"Reopen reason required condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/reopen.ts"],emitting_commands:["item reopen"],canonical_code:"reopen_reason_required",aliases:[]},{code:"reopen_receipt_missing",meaning:"Reopen receipt missing condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"],canonical_code:"reopen_receipt_missing",aliases:[]},{code:"reopen_target_status_invalid",meaning:"Reopen target status invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/reopen.ts"],emitting_commands:["item reopen"],canonical_code:"reopen_target_status_invalid",aliases:[]},{code:"reported_zero_passes",meaning:"Reported zero passes condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution.ts"],emitting_commands:["*"],canonical_code:"reported_zero_passes",aliases:[]},{code:"reported_zero_tests",meaning:"Reported zero tests condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution.ts"],emitting_commands:["*"],canonical_code:"reported_zero_tests",aliases:[]},{code:"reserved_item_field",meaning:"Reserved item field condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"],canonical_code:"reserved_item_field",aliases:[]},{code:"retry_failed",meaning:"Retry failed condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts","sdk/agent/tracker-preflight-contracts.ts"],emitting_commands:["*"],canonical_code:"retry_failed",aliases:[]},{code:"schema_migration_input_required",meaning:"Schema migration input required condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/migration-gates.ts"],emitting_commands:["*"],canonical_code:"schema_migration_input_required",aliases:[]},{code:"semantic_spelling_collision",meaning:"Semantic spelling collision condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"],emitting_commands:["*"],canonical_code:"semantic_spelling_collision",aliases:[]},{code:"settings_read_fs_error",meaning:"Settings read fs error condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"settings_read_fs_error",aliases:[]},{code:"settings_read_invalid_json",meaning:"Settings read invalid json condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"settings_read_invalid_json",aliases:[]},{code:"settings_read_invalid_schema",meaning:"Settings read invalid schema condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"settings_read_invalid_schema",aliases:[]},{code:"settings_read_merge_failed",meaning:"Settings read merge failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"settings_read_merge_failed",aliases:[]},{code:"stale_budget",meaning:"Stale budget condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"],emitting_commands:["*"],canonical_code:"stale_budget",aliases:[]},{code:"stale_destination",meaning:"Stale destination condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/grammar-contracts.ts"],emitting_commands:["*"],canonical_code:"stale_destination",aliases:[]},{code:"stale_observed_signature",meaning:"Stale observed signature condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/grammar-contracts.ts"],emitting_commands:["*"],canonical_code:"stale_observed_signature",aliases:[]},{code:"status_duplicate",meaning:"Status duplicate condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"status_duplicate",aliases:[]},{code:"status_invalid",meaning:"Status invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"status_invalid",aliases:[]},{code:"status_lifecycle_role_required",meaning:"Status lifecycle role required condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/schema.ts"],emitting_commands:["*"],canonical_code:"status_lifecycle_role_required",aliases:[]},{code:"stdin_json_invalid",meaning:"Stdin json invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/structured-mutations.ts"],emitting_commands:["*"],canonical_code:"stdin_json_invalid",aliases:[]},{code:"stdin_json_unknown_key",meaning:"Stdin json unknown key condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/structured-mutations.ts"],emitting_commands:["*"],canonical_code:"stdin_json_unknown_key",aliases:[]},{code:"structured_event_immutable",meaning:"Structured event immutable condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/annotations.ts"],emitting_commands:["*"],canonical_code:"structured_event_immutable",aliases:[]},{code:"structured_event_input_conflict",meaning:"Structured event input conflict condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/notes.ts"],emitting_commands:["*"],canonical_code:"structured_event_input_conflict",aliases:[]},{code:"structured_event_json_empty",meaning:"Structured event json empty condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/notes.ts"],emitting_commands:["*"],canonical_code:"structured_event_json_empty",aliases:[]},{code:"structured_event_json_invalid",meaning:"Structured event json invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/notes.ts"],emitting_commands:["*"],canonical_code:"structured_event_json_invalid",aliases:[]},{code:"structured_event_since_invalid",meaning:"Structured event since invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/notes.ts"],emitting_commands:["*"],canonical_code:"structured_event_since_invalid",aliases:[]},{code:"suggested_retry_args_mismatch",meaning:"Suggested retry args mismatch condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts"],emitting_commands:["*"],canonical_code:"suggested_retry_args_mismatch",aliases:[]},{code:"telemetry_endpoint_probe_failed",meaning:"Telemetry endpoint probe failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"telemetry_endpoint_probe_failed",aliases:[]},{code:"telemetry_endpoint_probe_http_status",meaning:"Telemetry endpoint probe http status condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"telemetry_endpoint_probe_http_status",aliases:[]},{code:"telemetry_otel_export_failing",meaning:"Telemetry otel export failing condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"telemetry_otel_export_failing",aliases:[]},{code:"telemetry_queue_high_retries",meaning:"Telemetry queue high retries condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"telemetry_queue_high_retries",aliases:[]},{code:"telemetry_queue_invalid_rows",meaning:"Telemetry queue invalid rows condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"telemetry_queue_invalid_rows",aliases:[]},{code:"telemetry_queue_pending",meaning:"Telemetry queue pending condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"telemetry_queue_pending",aliases:[]},{code:"telemetry_schema_version_behind",meaning:"Telemetry schema version behind condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"telemetry_schema_version_behind",aliases:[]},{code:"telemetry_state_invalid_json",meaning:"Telemetry state invalid json condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"telemetry_state_invalid_json",aliases:[]},{code:"template_type_unknown",meaning:"Template type unknown condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"template_type_unknown",aliases:[]},{code:"terminal_plan_mutation",meaning:"Terminal plan mutation condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"],canonical_code:"terminal_plan_mutation",aliases:[]},{code:"terminal_state_conflict",meaning:"Terminal state conflict condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/telemetry/observability.ts"],emitting_commands:["*"],canonical_code:"terminal_state_conflict",aliases:[]},{code:"tracked_runtime_cache_files",meaning:"Tracked runtime cache files condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"tracked_runtime_cache_files",aliases:["validate_storage_tracked_runtime_cache_files"]},{code:"tracker_not_initialized",meaning:"Tracker not initialized condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/store/tracker-preflight.ts","core/telemetry/observability.ts"],emitting_commands:["*"],canonical_code:"tracker_not_initialized",aliases:[],owned_states:[{state:"selected_tracker_root_exists_without_settings",probe_id:"tracker-root-settings-missing",entrypoints:["list"],expected_exit_class:"not_found"}]},{code:"tracker_root_missing",meaning:"Tracker root missing condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/store/tracker-preflight.ts"],emitting_commands:["*"],canonical_code:"tracker_root_missing",aliases:[],owned_states:[{state:"selected_tracker_root_does_not_exist",probe_id:"tracker-root-missing",entrypoints:["list"],expected_exit_class:"not_found"}]},{code:"tracker_root_not_directory",meaning:"Tracker root not directory condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/store/tracker-preflight.ts"],emitting_commands:["*"],canonical_code:"tracker_root_not_directory",aliases:[],owned_states:[{state:"selected_tracker_root_is_a_regular_file",probe_id:"tracker-root-not-directory",entrypoints:["list"],expected_exit_class:"usage"}]},{code:"tracker_root_unreadable",meaning:"Tracker root unreadable condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/store/tracker-preflight.ts"],emitting_commands:["*"],canonical_code:"tracker_root_unreadable",aliases:[],owned_states:[{state:"selected_tracker_root_is_not_readable",probe_id:"tracker-root-unreadable",entrypoints:["list"],expected_exit_class:"generic_failure"}]},{code:"type_duplicate",meaning:"Type duplicate condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"type_duplicate",aliases:[]},{code:"type_invalid",meaning:"Type invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"type_invalid",aliases:[]},{code:"undeclared_observation",meaning:"Undeclared observation condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/flag-invocation-contracts.ts"],emitting_commands:["*"],canonical_code:"undeclared_observation",aliases:[]},{code:"unexpected_refusal_probe",meaning:"Unexpected refusal probe condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-corpus-contracts.ts"],emitting_commands:["*"],canonical_code:"unexpected_refusal_probe",aliases:[]},{code:"unknown_command",meaning:"Unknown command condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts","sdk/cli-contracts/runtime-contracts.ts"],emitting_commands:["*"],canonical_code:"unknown_command",aliases:[]},{code:"unknown_context_intent",meaning:"Unknown context intent condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/context-intent-contracts.ts"],emitting_commands:["*"],canonical_code:"unknown_context_intent",aliases:[]},{code:"unknown_error",meaning:"Unknown error condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"],canonical_code:"unknown_error",aliases:[]},{code:"unknown_field",meaning:"Unknown field condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/schema.ts"],emitting_commands:["*"],canonical_code:"unknown_field",aliases:[]},{code:"unknown_field_projection",meaning:"Unknown field projection condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/query/get.ts","sdk/query/list.ts","sdk/query/search-contracts.ts"],emitting_commands:["get","list","search"],canonical_code:"unknown_field_projection",aliases:[]},{code:"unknown_item_type",meaning:"Unknown item type condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/schema.ts"],emitting_commands:["*"],canonical_code:"unknown_item_type",aliases:[]},{code:"unknown_lifecycle_action",meaning:"Unknown lifecycle action condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/subcommand-recovery.ts"],emitting_commands:["*"],canonical_code:"unknown_subcommand",aliases:[]},{code:"unknown_noun",meaning:"Unknown noun condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/grammar-contracts.ts"],emitting_commands:["*"],canonical_code:"unknown_noun",aliases:[]},{code:"unknown_option",meaning:"Unknown option condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts"],emitting_commands:["*"],canonical_code:"unknown_option",aliases:[],owned_states:[{state:"declared_option_is_rejected_on_the_selected_command_path",probe_id:"cross-command-unknown-option",entrypoints:["deps"],expected_exit_class:"usage"}]},{code:"unknown_plan_template",meaning:"Unknown plan template condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"],canonical_code:"unknown_plan_template",aliases:[]},{code:"unknown_provenance_dimension",meaning:"Unknown provenance dimension condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/history-provenance.ts"],emitting_commands:["*"],canonical_code:"unknown_provenance_dimension",aliases:[]},{code:"unknown_status",meaning:"Unknown status condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/schema.ts"],emitting_commands:["*"],canonical_code:"unknown_status",aliases:[]},{code:"unknown_subcommand",meaning:"Unknown subcommand condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","sdk/agent/subcommand-recovery.ts"],emitting_commands:["*"],canonical_code:"unknown_subcommand",aliases:["unknown_lifecycle_action"],owned_states:[{state:"config_action_token_is_not_declared",probe_id:"config-unknown-action",entrypoints:["config"],expected_exit_class:"usage"},{state:"graph_command_token_is_not_declared",probe_id:"graph-unknown-subcommand",entrypoints:["graph"],expected_exit_class:"usage"},{state:"nested_command_token_is_not_declared_by_its_family",probe_id:"schema-unknown-subcommand",entrypoints:["schema"],expected_exit_class:"usage"},{state:"package_lifecycle_token_is_not_declared",probe_id:"package-unknown-action",entrypoints:["package"],expected_exit_class:"usage"}]},{code:"unsafe_init_recovery",meaning:"Unsafe init recovery condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/tracker-preflight-contracts.ts"],emitting_commands:["*"],canonical_code:"unsafe_init_recovery",aliases:[]},{code:"unsupported_update_option",meaning:"Unsupported update option condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"],canonical_code:"unsupported_update_option",aliases:[]},{code:"validate_command_references_stale_pm_ids",meaning:"Validate command references stale pm ids condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_command_references_stale_pm_ids",aliases:[]},{code:"validate_files_missing_linked_paths",meaning:"Validate files missing linked paths condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_files_missing_linked_paths",aliases:[]},{code:"validate_files_orphaned_paths",meaning:"Validate files orphaned paths condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_files_orphaned_paths",aliases:[]},{code:"validate_files_tracked_all_strict_forces_pm_internals",meaning:"Validate files tracked all strict forces pm internals condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_files_tracked_all_strict_forces_pm_internals",aliases:[]},{code:"validate_format_version_ahead_items",meaning:"Validate format version ahead items condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_item_ahead_format_version",aliases:[]},{code:"validate_format_version_outdated_items",meaning:"Validate format version outdated items condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_item_outdated_format_version",aliases:[]},{code:"validate_hierarchy_parent_cycle",meaning:"Validate hierarchy parent cycle condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_hierarchy_parent_cycle",aliases:[]},{code:"validate_hierarchy_parent_cycle_error",meaning:"Validate hierarchy parent cycle error condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_hierarchy_parent_cycle_error",aliases:[]},{code:"validate_history_drift_chain_mismatches",meaning:"Validate history drift chain mismatches condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_chain_mismatch",aliases:[]},{code:"validate_history_drift_hash_mismatches",meaning:"Validate history drift hash mismatches condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_hash_mismatch",aliases:[]},{code:"validate_history_drift_missing_streams",meaning:"Validate history drift missing streams condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_missing_stream",aliases:[]},{code:"validate_history_drift_unreadable_streams",meaning:"Validate history drift unreadable streams condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_unreadable_stream",aliases:[]},{code:"validate_history_drift_version_skews",meaning:"Validate history drift version skews condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_version_skew",aliases:[]},{code:"validate_history_unknown_author_events",meaning:"Validate history unknown author events condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_unknown_author_events",aliases:[]},{code:"validate_lifecycle_active_closure_like_metadata",meaning:"Validate lifecycle active closure like metadata condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_lifecycle_active_closure_like_metadata",aliases:[]},{code:"validate_lifecycle_active_terminal_parent",meaning:"Validate lifecycle active terminal parent condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_lifecycle_active_terminal_parent",aliases:[]},{code:"validate_lifecycle_dependency_cycles",meaning:"Validate lifecycle dependency cycles condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_lifecycle_dependency_cycles",aliases:[]},{code:"validate_lifecycle_dependency_cycles_error",meaning:"Validate lifecycle dependency cycles error condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_lifecycle_dependency_cycles_error",aliases:[]},{code:"validate_lifecycle_stale_blockers",meaning:"Validate lifecycle stale blockers condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_lifecycle_stale_blockers",aliases:[]},{code:"validate_merge_decisions_unreviewed",meaning:"Validate merge decisions unreviewed condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_merge_decisions_unreviewed",aliases:[]},{code:"validate_merge_fence_drift",meaning:"Validate merge fence drift condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_merge_fence_drift",aliases:[]},{code:"validate_metadata_custom_profile_missing_required_fields",meaning:"Validate metadata custom profile missing required fields condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_metadata_custom_profile_missing_required_fields",aliases:[]},{code:"validate_metadata_duplicate_issue_codes",meaning:"Validate metadata duplicate issue codes condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_metadata_duplicate_issue_codes",aliases:[]},{code:"validate_metadata_missing_acceptance_criteria",meaning:"Validate metadata missing acceptance criteria condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_metadata_missing_acceptance_criteria",aliases:[]},{code:"validate_metadata_missing_close_reason",meaning:"Validate metadata missing close reason condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_metadata_missing_close_reason",aliases:[]},{code:"validate_metadata_missing_confidence",meaning:"Validate metadata missing confidence condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_metadata_missing_confidence",aliases:[]},{code:"validate_metadata_missing_estimate",meaning:"Validate metadata missing estimate condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_metadata_missing_estimate",aliases:[]},{code:"validate_metadata_missing_release",meaning:"Validate metadata missing release condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_metadata_missing_release",aliases:[]},{code:"validate_metadata_missing_reviewer",meaning:"Validate metadata missing reviewer condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_metadata_missing_reviewer",aliases:[]},{code:"validate_metadata_missing_risk",meaning:"Validate metadata missing risk condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_metadata_missing_risk",aliases:[]},{code:"validate_metadata_missing_sprint",meaning:"Validate metadata missing sprint condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_metadata_missing_sprint",aliases:[]},{code:"validate_resolution_missing_fields",meaning:"Validate resolution missing fields condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_resolution_missing_fields",aliases:[]},{code:"validate_storage_duplicate_item_ids",meaning:"Validate storage duplicate item ids condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_storage_duplicate_item_ids",aliases:[]},{code:"validate_storage_history_conflict_markers",meaning:"Validate storage history conflict markers condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_history_conflict_marker",aliases:[]},{code:"validate_storage_resurrected_items",meaning:"Validate storage resurrected items condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_storage_resurrected_items",aliases:[]},{code:"validate_storage_tracked_runtime_cache_files",meaning:"Validate storage tracked runtime cache files condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"tracked_runtime_cache_files",aliases:[]},{code:"validate_storage_unparseable_config",meaning:"Validate storage unparseable config condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_storage_unparseable_config",aliases:[]},{code:"validate_storage_unparseable_history",meaning:"Validate storage unparseable history condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_storage_unparseable_history",aliases:[]},{code:"validate_storage_unreadable_items",meaning:"Validate storage unreadable items condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_storage_unreadable_items",aliases:[]},{code:"vectorization_embedding_identity_changed",meaning:"Vectorization embedding identity changed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"vectorization_embedding_identity_changed",aliases:[]},{code:"vectorization_stale_items_remaining",meaning:"Vectorization stale items remaining condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"vectorization_stale_items_remaining",aliases:[]},{code:"visible_surface_ceiling_exceeded",meaning:"Visible surface ceiling exceeded condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/grammar-contracts.ts"],emitting_commands:["*"],canonical_code:"visible_surface_ceiling_exceeded",aliases:[]},{code:"workflow_duplicate_type",meaning:"Workflow duplicate type condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"workflow_duplicate_type",aliases:[]},{code:"workflow_status_unknown",meaning:"Workflow status unknown condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"workflow_status_unknown",aliases:[]},{code:"workflow_transition_malformed",meaning:"Workflow transition malformed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"workflow_transition_malformed",aliases:[]},{code:"workflow_type_empty",meaning:"Workflow type empty condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"workflow_type_empty",aliases:[]},{code:"workflow_type_unknown",meaning:"Workflow type unknown condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"workflow_type_unknown",aliases:[]},{code:"workspace_history_chain_invalid",meaning:"Workspace history chain invalid condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/workspace-history.ts"],emitting_commands:["*"],canonical_code:"workspace_history_chain_invalid",aliases:[]},{code:"workspace_history_state_conflict",meaning:"Workspace history state conflict condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/workspace-history.ts"],emitting_commands:["*"],canonical_code:"workspace_history_state_conflict",aliases:[]},{code:"workspace_root_pm_path",meaning:"Workspace root pm path condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/init.ts"],emitting_commands:["*"],canonical_code:"workspace_root_pm_path",aliases:[]},{code:"workspace_snapshot_force_required",meaning:"Workspace snapshot force required condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"],canonical_code:"workspace_snapshot_force_required",aliases:[]},{code:"workspace_snapshot_manifest_mismatch",meaning:"Workspace snapshot manifest mismatch condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"],canonical_code:"workspace_snapshot_manifest_mismatch",aliases:[]},{code:"workspace_snapshot_name_reserved_fingerprint",meaning:"Workspace snapshot name reserved fingerprint condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"],canonical_code:"workspace_snapshot_name_reserved_fingerprint",aliases:[]},{code:"workspace_snapshot_not_found",meaning:"Workspace snapshot not found condition.",stability:"provisional",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"],canonical_code:"workspace_snapshot_not_found",aliases:[]},{code:"workspace_snapshot_permission_denied",meaning:"Workspace snapshot permission denied condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"],canonical_code:"workspace_snapshot_permission_denied",aliases:[]},{code:"workspace_snapshot_resource_exhausted",meaning:"Workspace snapshot resource exhausted condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"],canonical_code:"workspace_snapshot_resource_exhausted",aliases:[]},{code:"workspace_snapshot_storage_exhausted",meaning:"Workspace snapshot storage exhausted condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"],canonical_code:"workspace_snapshot_storage_exhausted",aliases:[]},{code:"wrong_item_type",meaning:"Wrong item type condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"],canonical_code:"wrong_item_type",aliases:[]}];(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f617ee39-b463-5482-af64-8dc86fe28e71")}catch{}})();var qv=$v([...jv,...Uv]);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="af86d275-63a8-5205-a8b3-154efdbd8e2a")}catch{}})();var fL=["mutation_receipt","entity","collection","diagnostic","stream"],_L=new Set(["append","claim","close","close-task","copy","create","delete","focus","pause-task","release","restore","start-task","update"]),pL=new Set(["close-many","update-many"]),gL=new Set(["activity","comments","contracts","events","history","learnings","list","notes","search"]),hL=new Set(["aggregate","deps","graph","health","stats","validate"]);function Vr(e){if(e.command.trim().length===0)throw new TypeError("command must be a non-empty command path");if(!fL.includes(e.kind))throw new TypeError(`Unsupported output envelope kind: ${e.kind}`);return e}function Gv(e){let t=e.trim().replace(/\s+/gu," "),[n=t]=t.split(" ");return pL.has(n)?Vr({command:t,kind:"collection",wrapper_key:"rows",cardinality:"many",format_flag:"--json"}):_L.has(n)?Vr({command:t,kind:"mutation_receipt",wrapper_key:null,cardinality:"one",format_flag:"--json"}):gL.has(n)?Vr({command:t,kind:"collection",wrapper_key:n==="contracts"?null:"items",cardinality:"many",format_flag:"--json"}):hL.has(n)?Vr({command:t,kind:"diagnostic",wrapper_key:null,cardinality:"none",format_flag:"--json"}):Vr({command:t,kind:n==="get"?"entity":"diagnostic",wrapper_key:n==="get"?"item":null,cardinality:n==="get"?"one":"none",format_flag:"--json"})}var yL=tt.map(e=>Gv(e)),vL=new Map(yL.map(e=>[e.command,e]));function Kv(e){let t=e.trim().replace(/\s+/gu," ");if(t.length===0)throw new TypeError("command must be a non-empty command path");let[n=t]=t.split(" "),r=vL.get(n);return r?{...r,command:t}:Gv(t)}function wL(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function bL(e){return wL(e)&&typeof e.id=="string"&&e.id.length>0&&typeof e.status=="string"&&e.status.length>0&&Number.isSafeInteger(e.changed_field_count)&&Number(e.changed_field_count)>=0&&(e.close_reason===void 0||typeof e.close_reason=="string")&&(e.deleted===void 0||typeof e.deleted=="boolean")&&(e.previous_status===void 0||typeof e.previous_status=="string")&&(e.warnings===void 0||Array.isArray(e.warnings))}function B2(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch(n){throw new TypeError(`Mutation receipt must be valid JSON: ${String(n)}`,{cause:n})}if(!bL(t))throw new TypeError("Mutation receipt must be a flat object with top-level id, status, and changed_field_count fields");return{id:t.id,status:t.status,changedFieldCount:t.changed_field_count,...typeof t.close_reason=="string"?{closeReason:t.close_reason}:{},...typeof t.deleted=="boolean"?{deleted:t.deleted}:{},...typeof t.previous_status=="string"?{previousStatus:t.previous_status}:{},...Array.isArray(t.warnings)?{warnings:t.warnings}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5ceccf7d-78cb-5750-8e4b-793efa6e716c")}catch{}})();var kL=ya("list").properties.outputSession,EL={outputInclude:{type:"string",minLength:1,description:"Comma-separated fields or sections retained by any built-in read action."},outputLimit:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}],description:"Universal read row ceiling, or unbounded to disable the shared ceiling."},outputBudget:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}],description:"Universal estimated-token ceiling, or unbounded to return the complete read result."},outputFormat:{type:"string",enum:["json","toon"],description:"Universal read-result encoding selector."},outputSession:{...kL},outputCursor:{type:"string",minLength:1,description:"Opaque continuation cursor returned after budget compaction of a declared row collection."}},zv={type:"object",properties:{cwd:{type:"string",description:"Workspace directory to run the native pm operation in. Defaults to the MCP server process cwd."},path:{type:"string",description:"Optional pm data root, equivalent to PM_PATH/global --path. Leave unset for real repository tracking."},author:{type:"string",description:"Optional mutation author override. Otherwise pm uses PM_AUTHOR, project settings, or detected harness identity."},tokenAccounting:{type:"boolean",description:"Attach the same bounded per-section token-cost receipt emitted by CLI --token-accounting."}},additionalProperties:!0},ce={type:"string",description:"pm item id, for example pm-abc1."},SL=`Operation name (one of): ${ea.join(", ")}. Package-owned actions are available dynamically when their provider package is installed.`,xL={status:{type:"string",description:"Alias for options.status."},type:{type:"string",description:"Alias for options.type."},tag:{type:"string",description:"Alias for options.tag."},priority:{type:"string",description:"Alias for options.priority."},limit:{type:["string","number"],description:"Alias for options.limit."},offset:{type:["string","number"],description:"Alias for options.offset."}},TL={mode:{type:"string",description:"Alias for options.mode."},status:{type:"string",description:"Alias for options.status."},type:{type:"string",description:"Alias for options.type."},tag:{type:"string",description:"Alias for options.tag."},priority:{type:"string",description:"Alias for options.priority."},limit:{type:["string","number"],description:"Alias for options.limit."}};function z(e,t=[]){return{...zv,properties:{...zv.properties,...e},required:t}}var IL=[{name:"pm_run",description:"Run any supported pm operation natively through the pm library. Use this for commands not covered by narrower pm_* tools.",inputSchema:z({action:{type:"string",enum:[...ea],description:SL},id:ce,query:{type:"string",description:"Search query for action=search."},reason:{type:"string",description:"Close reason for action=close."},force:{type:"boolean",description:"Force ownership/terminal-state override when supported."},subcommand:{type:"string",description:"Subcommand selector for actions that take one (for example telemetry, or schema \u2014 prefer the dedicated pm_schema tool for schema operations)."},options:{type:"object",description:"Underlying pm command options using camelCase keys."},fullChangedFields:{type:"boolean",description:"For mutation actions, return the full changed_fields array instead of the default changed_field_count."},idOnly:{type:"boolean",description:"For single-item mutation actions, return only id and status."},...EL},["action"])},{name:"pm_discover",description:"Discover the smallest relevant authorized pm tool catalog under an explicit token budget. Ranking is deterministic and returns public lexical, semantic, graph, permission, freshness, and usage signal explanations. Continue with next_cursor; set includeSchema=true only when complete input schemas are needed.",inputSchema:z({query:{type:"string",maxLength:4096,description:"Free-text capability intent. Empty text lists by stable policy order."},family:{type:"string",enum:["workspace","intake","context","lifecycle","evidence","graph","quality","automation","extensions","internal"],description:"Optional stable capability-family filter."},tier:{type:"string",enum:["core","standard","full"],description:"Maximum command visibility tier included in results."},limit:{type:"integer",minimum:1,maximum:100,description:"Maximum result rows; defaults to 10."},cursor:{type:"string",minLength:1,maxLength:4096,description:"Opaque next_cursor from an equivalent discovery request."},includeSchema:{type:"boolean",description:"Include complete tool input schemas; false by default."},outputBudget:{anyOf:[{type:"integer",minimum:128},{const:"unbounded"}],description:"Estimated-token ceiling; defaults to 1200."}})},{name:"pm_context",description:"Return the agent-oriented project context snapshot. Pass options.depth=brief|standard|deep|full (full = every section with no per-section row cap), options.parent='<id>' to scope the snapshot to one item's subtree (the item plus all descendants), options.fields='id,title,priority' to project focus rows to a field subset for low-token reads, or options.section=['hierarchy','progress',...] to pick sections.",inputSchema:z({options:{type:"object"}})},{name:"pm_next",description:"Recommend the next actionable work item: the single highest-priority READY item (active status, no open blockers, no open children; completed containers surface only when no concrete leaf work is ready) plus the ranked ready and blocked queues. The recommended item carries a rationale and each blocked item lists the open blockers gating it. Pass options.parent='<id>' to scope to one subtree, options.limit=N to cap ready rows, options.readyOnly=true to omit the blocked list, or filters (options.type/tag/priority/assignee/sprint/release). The most token-efficient 'what should I do now?' read for agents.",inputSchema:z({options:{type:"object"}})},{name:"pm_search",description:"Search pm items with keyword, semantic, or hybrid search. Defaults to a compact projection for token efficiency. Pass options.mode=keyword|semantic|hybrid, options.limit=N to cap hits, options.status='all' for no lifecycle restriction, options.fields='id,title,score' for a custom projection, or options.full=true for full item bodies (can be large). The result echoes the applied filters and projection mode in query_summary.",inputSchema:z({query:{type:"string"},options:{type:"object"},...TL},["query"])},{name:"pm_list",description:"List pm items with status/type/tag/priority filters. Defaults to compact projection for token efficiency. options.status accepts CSV (all,open,in_progress). Pass options.compact=false or options.includeBody=true for full bodies/comments. Pass options.brief=true for ultra-terse (id/status/type/title only). Pass options.fields='id,title,priority' for custom projection. Pass options.limit=N to cap row count. The result echoes the applied filters and projection mode in query_summary.",inputSchema:z({options:{type:"object"},...xL})},{name:"pm_get",description:"Read one pm item with shared SDK projections. Pass options.depth='brief' or options.fields='id,title,status' for low-token inspection, options.fields='id,schedule.start_at' for schedule context, or options.at='7' / an ISO timestamp for a verified mutation-free historical read. Parent results include bounded child counts, samples, and continuation metadata.",inputSchema:z({id:ce,options:{type:"object",description:"Get options such as depth=brief|standard|deep|full, fields=id,title,status, or at=<version|ISO timestamp>."}},["id"])},{name:"pm_events",description:"Read a bounded, cursor-resumable page of committed mutation events across item history streams. Batch cursors are the token-efficient default; pass cursorMode=row for per-event checkpoints.",inputSchema:z({since:{type:"string",description:"Durable event cursor or ISO timestamp lower bound."},type:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},author:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},item:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},limit:{type:"integer",minimum:0,maximum:1e3},full:{type:"boolean"},cursorMode:{type:"string",enum:["batch","row"],description:"Cursor framing: batch returns one terminal next_cursor (default); row also adds a cursor to every event."}})},{name:"pm_create",description:"Create a pm item natively and write pm history. Output is compact by default (changed_fields replaced with changed_field_count for token efficiency); pass fullChangedFields=true for the full changed_fields array.",inputSchema:z({fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},allowMissingParent:{type:"boolean",description:"Allow unresolved parent references and emit a validation warning."},allowDuplicate:{type:"boolean",description:"Explicitly create when strict similarity governance finds likely duplicates."},options:{type:"object",description:"Create options. title and description are required."}},["options"])},{name:"pm_mutate",description:"Apply an ordered create/update/close/release batch atomically through the public pm SDK. Create rows may declare ref and omit id; @ref forward references resolve deterministically from the stable transactionId. Set dryRun=true to validate and preview without writes.",inputSchema:z({transactionId:{type:"string",description:"Stable idempotency key for this atomic mutation batch."},mutations:{type:"array",minItems:1,description:"Ordered rows shaped as {op:create|update|close|release,id?,ref?,options?,reason?}.",items:{type:"object",properties:{op:{type:"string",enum:["create","update","close","release"]},id:ce,ref:{type:"string",description:"Batch-local create alias; its deterministic id can be referenced as @alias by any row."},reason:{type:"string"},options:{type:"object"}},required:["op"],additionalProperties:!1}},dryRun:{type:"boolean",description:"Validate and preview without writing."},createCompensation:{type:"string",enum:["close","delete"],description:"How a failed batch compensates created items; defaults to close."},lockTtlSeconds:{type:"number"},lockWaitMs:{type:"number"}},["transactionId","mutations"])},{name:"pm_copy",description:"Copy an existing pm item into a new id while resetting lifecycle fields. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:z({id:ce,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object",description:"Copy options such as title override, author, and message."}},["id"])},{name:"pm_focus",description:"Set, clear, or show the session focused item. When focused, pm_create defaults its parent to the focused item (an explicit parent still overrides). Pass id to focus an item, options.clear=true to clear, or neither to show current focus.",inputSchema:z({id:ce,clear:{type:"boolean",description:"Clear the focused item (cannot be combined with id)."},options:{type:"object",description:"Focus options such as clear (boolean)."}},[])},{name:"pm_update",description:"Update pm item metadata/body/dependencies/log seeds natively. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields delta.",inputSchema:z({id:ce,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object"}},["id","options"])},{name:"pm_append",description:"Append markdown text to a pm item body and write pm history. Useful for seeding evidence/log entries before close. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:z({id:ce,body:{type:"string",description:"Markdown text to append to the item body. Required here or as options.body."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object",description:"Append options such as body, author, and message."}},["id"])},{name:"pm_claim",description:"Claim a pm item.",inputSchema:z({id:ce,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_release",description:"Release a pm item claim.",inputSchema:z({id:ce,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_close",description:"Close a pm item with optional close reason and optional close validation (reason requirement follows governance settings). Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:z({id:ce,reason:{type:"string",description:"Close reason text when provided or required by governance settings."},duplicateOf:{type:"string",description:"Canonical item id when closing this item as a duplicate."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object"}},["id"])},{name:"pm_comments",description:"List, add, edit, or delete comments on a pm item. Use options.add to append, options.edit=<1-based index> with replacement text to fix a comment, or options.delete=<1-based index> to remove one. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. List calls default to the most recent 20 comments with total_count/has_more metadata for token efficiency. Pass options.limit=N to choose a page size, options.limit=0 for summary-only metadata, or options.full=true for full history.",inputSchema:z({id:ce,options:{type:"object"}},["id"])},{name:"pm_files",description:"List, add, remove, or validate linked files for a pm item.",inputSchema:z({id:ce,options:{type:"object"}},["id"])},{name:"pm_docs",description:"List, add, or remove linked docs for a pm item.",inputSchema:z({id:ce,options:{type:"object"}},["id"])},{name:"pm_notes",description:"List, add, edit, or delete structured notes on a pm item. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. Omit mutation options to list existing notes.",inputSchema:z({id:ce,options:{type:"object"}},["id"])},{name:"pm_learnings",description:"List, add, edit, or delete learnings on a pm item. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. Omit mutation options to list existing learnings.",inputSchema:z({id:ce,options:{type:"object"}},["id"])},{name:"pm_deps",description:"Read dependency trees/graphs or one bounded explainable relationship context packet. Use options.format=context with direction, kind, depth, node, edge, token, and cursor bounds; context returns a counts-first summary, per-node roles/reasons, root evidence pointers, and enumerated missing references.",inputSchema:z({id:ce,options:{type:"object"}},["id"])},{name:"pm_graph",description:"Run bounded workspace relationship-graph queries: ancestors/descendants (hierarchy), predecessors/successors (ordering), paths, impact (blast radius), analyze (execution + knowledge analytics), audit (governance findings with change-since-baseline deltas), communities (label-propagation clusters), redundancy (transitively implied edges), dominators (structural bottlenecks), slack (critical-path method float per task), centrality (betweenness/closeness/degree with directed fan-in/out), articulation (cut points and bridges \u2014 single points of failure), plan (dry-run remediation proposals derived from the audit), and index (durable cross-process graph index status/rebuild/clear). Traversals, paths, impact, and dominators require id; paths also requires target. Options support kind, maxDepth, limit, after, direction, maxPaths, sample, exemptIsolate, exemptIsolateType, saveBaseline (audit), rebuild/clear (index), and counts-first summary.",inputSchema:z({subcommand:{type:"string",enum:[...vu]},id:ce,target:ce,options:{type:"object"}},["subcommand"])},{name:"pm_test",description:"List, add, remove, or run linked tests for a pm item.",inputSchema:z({id:ce,options:{type:"object"}},["id"])},{name:"pm_validate",description:"Run pm validation checks.",inputSchema:z({options:{type:"object"}})},{name:"pm_health",description:"Run pm health diagnostics. Pass options.brief=true for compact low-token details, options.skipIntegrity=true, options.skipDrift=true, options.skipVectors=true for a fast status-only check, or options.full=true for the complete deep check.",inputSchema:z({options:{type:"object"}})},{name:"pm_contracts",description:"Inspect pm command, flag, schema, and availability contracts.",inputSchema:z({options:{type:"object"}})},{name:"pm_schema",description:"Inspect or modify the workspace item-type/status/field schema (pm schema). subcommand selects the operation; name carries the item type name (show/add-type/remove-type), status id (show-status/add-status/remove-status), or field key (show-field/add-field/remove-field). apply-preset adopts a domain type preset; add-type with infer=true derives types from title-prefix conventions. Schema mutations write workspace config files, not item history.",inputSchema:z({subcommand:{type:"string",enum:["list","show","show-status","add-type","remove-type","add-status","remove-status","add-field","remove-field","list-fields","show-field","apply-preset"],description:"Schema subcommand to run."},name:{type:"string",description:"Item type name (show/add-type/remove-type), status id (show-status/add-status/remove-status), or custom field key (show-field/add-field/remove-field). Required for those subcommands."},description:{type:"string",description:"Custom item type, status, or field description for add-type/add-status/add-field."},defaultStatus:{type:"string",description:"Default status for add-type."},folder:{type:"string",description:"Storage folder for add-type."},alias:{type:"array",items:{type:"string"},description:"Aliases for add-type/add-status, or extra CLI flag aliases for add-field."},role:{type:"array",items:{type:"string",enum:[...Bo]},description:`Lifecycle roles for add-status: ${Bo.join(", ")}.`},order:{type:"number",description:"Display/sort order for add-status."},fieldType:{type:"string",enum:["string","number","boolean","string_array"],description:"Value type for a custom field (add-field)."},commands:{type:"array",items:{type:"string"},description:"Commands a custom field is wired onto (add-field): create, update, update_many, list, search, calendar, context."},cliFlag:{type:"string",description:"Override the auto-derived CLI flag for a custom field (add-field)."},required:{type:"boolean",description:"Mark a custom field as always required (add-field)."},requiredOnCreate:{type:"boolean",description:"Mark a custom field as required at create time (add-field)."},allowUnset:{type:"boolean",description:"Whether a custom field may be cleared via --unset (add-field); defaults to true."},requiredTypes:{type:"array",items:{type:"string"},description:"Restrict a custom field's requirement to specific item types (add-field)."},typePreset:{type:"string",enum:["agile","ops","research"],description:"Domain type preset to adopt (apply-preset)."},infer:{type:"boolean",description:"Infer item types from title-prefix conventions (add-type); previews unless apply is true."},minCount:{type:"number",description:"Minimum items sharing a prefix for add-type inference (default 10)."},apply:{type:"boolean",description:"Register inferred types (add-type infer); without it the call previews only."},force:{type:"boolean",description:"Override removal guardrails for destructive schema changes when supported."},options:{type:"object",description:"Additional schema options using camelCase keys."}},["subcommand"])},{name:"pm_profile",description:"List, show, apply, or lint project profiles (pm profile) \u2014 archetype bundles that stage item types, statuses, fields, per-type workflows, config knobs, create templates, and recommended packages. subcommand selects the operation; name carries the profile name (agile, ops, research) for show/apply/lint. apply stages every dimension idempotently; dryRun previews the diff without writing; lint reports author-time consistency findings (graded error/warning) without touching the tracker. Profile staging writes workspace config/schema files, not item history.",inputSchema:z({subcommand:{type:"string",enum:["list","show","apply","lint"],description:"Profile subcommand to run."},name:{type:"string",description:"Profile name for show/apply/lint. Required for those subcommands. Built-ins are agile, ops, and research; an active extension can contribute additional archetype names that resolve here too."},dryRun:{type:"boolean",description:"Preview the apply diff without writing any files (apply)."},author:{type:"string",description:"Mutation author for apply."},force:{type:"boolean",description:"Force ownership/lock override for apply."},options:{type:"object",description:"Additional profile options using camelCase keys."}},["subcommand"])},{name:"pm_config",description:"Read or write pm workspace configuration (pm config). configAction selects get/set/list/export; key/value address a single setting for get/set. scope chooses the project (default) or global settings file.",inputSchema:z({configAction:{type:"string",enum:["get","set","list","export"],description:"Config operation to perform. get/set require key; list/export dump the resolved settings surface."},key:{type:"string",description:"Settings key for get/set, for example governance-require-close-reason, telemetry-tracking, or a nested leaf such as search_provider (dash and underscore variants accepted; configAction=get without a key lists supported keys in the error)."},value:{type:"string",description:"New value for configAction=set."},scope:{type:"string",enum:["project","global"],description:"Settings scope to read or write. Defaults to project."},options:{type:"object",description:"Additional config options such as criterion, clearCriteria, format, or policy."}},["configAction"])},{name:"pm_plan",description:"Run agent-optimized Plan workflows. options.subcommand selects: create|show|add-step|update-step|complete-step|block-step|reorder-step|remove-step|link|unlink|decision|discovery|validation|resume|approve|materialize. Provide id for all non-create subcommands; provide stepRef for step lifecycle subcommands. Plans store agent-readable steps with dependencies, decisions, discoveries, validation, and resume context.",inputSchema:z({id:{type:"string",description:"Plan id (required for all subcommands except create)."},stepRef:{type:"string",description:"Step id or order for step lifecycle subcommands."},options:{type:"object",description:"Plan options including subcommand, stepRef, stepStatus, link, depth, etc."}})}],AL={pm_append:"append",pm_claim:"claim",pm_close:"close",pm_comments:"comments",pm_config:"config",pm_context:"context",pm_contracts:"contracts",pm_copy:"copy",pm_create:"create",pm_deps:"deps",pm_docs:"docs",pm_events:"events",pm_files:"files",pm_focus:"focus",pm_get:"get",pm_graph:"graph",pm_health:"health",pm_learnings:"learnings",pm_list:"list",pm_next:"next",pm_notes:"notes",pm_plan:"plan",pm_profile:"profile",pm_release:"release",pm_schema:"schema",pm_search:"search",pm_test:"test",pm_update:"update",pm_validate:"validate"},CL=IL.map(e=>{let t=AL[e.name];if(!t)return e;let n=e.inputSchema.properties,r=e.inputSchema.required.map(String);return{...e,inputSchema:ya(t,{properties:n,required:r})}});function Bv(){return CL.map(e=>{let t=e.inputSchema.required,n=Array.isArray(t)?t.map(r=>String(r)).sort((r,i)=>r.localeCompare(i)):[];return{name:e.name,description:e.description,required:n,input_schema:e.inputSchema}}).sort((e,t)=>e.name.localeCompare(t.name))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="188569e7-c809-5f28-a714-d531f57be1d9")}catch{}})();var Hv=new Map([["claim",["--if-available","--next","--type","--priority","--token-budget","--explain-ranking"]],["close",["--reason","--validate-close","--resolution","--expected-result","--actual-result","--message"]],["context",["--limit","--after","--depth","--section","--token-budget","--explain-ranking"]],["contracts",["--command","--flags-only","--summary","--runtime-only","--availability-only","--full"]],["create",["--title","--type","--status","--priority","--dep","--comment"]],["get",["--full","--depth","--fields","--tree","--tree-depth","--format"]],["health",["--check-only","--summary","--brief","--check-telemetry","--strict-exit","--full"]],["list",["--status","--type","--limit","--after","--brief","--fields"]],["next",["--limit","--blocked-limit","--ready-only","--token-budget","--explain-ranking","--format"]],["search",["--mode","--status","--type","--limit","--after","--fields"]],["update",["--status","--message","--dep","--comment","--file","--test"]],["validate",["--check-resolution","--check-history-drift","--check-storage-integrity","--counts","--strict-exit","--fix-hints"]]]),RL=["--limit","--after","--offset","--token-budget","--brief","--summary","--compact","--fields","--full","--format","--since","--until"],nw=new Set(["list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"]),Eo=new Set(["calendar","guide","reindex","completion","test-runs-list","test-runs-status","test-runs-logs","test-runs-stop","test-runs-resume","templates-list","templates-save","templates-show"]),Yr=new Set(["cal","calendar","completion","completion-statuses","completion-tags","completion-types","guide","reindex","templates","templates list","templates save","templates show","test-runs","test-runs list","test-runs status","test-runs logs","test-runs stop","test-runs resume"]),rw=new Map([["cal","calendar"],["calendar","calendar"],["completion","guide-shell"],["completion-statuses","guide-shell"],["completion-tags","guide-shell"],["completion-types","guide-shell"],["guide","guide-shell"],["reindex","search-advanced"],["templates","templates"],["templates list","templates"],["templates save","templates"],["templates show","templates"],["test-runs","linked-test-adapters"],["test-runs list","linked-test-adapters"],["test-runs status","linked-test-adapters"],["test-runs logs","linked-test-adapters"],["test-runs stop","linked-test-adapters"],["test-runs resume","linked-test-adapters"]]),iw=new Map([["calendar","calendar|cal"],["guide","guide"],["reindex","reindex"],["completion","completion"],["test-runs-list","test-runs|test-runs list"],["test-runs-status","test-runs status"],["test-runs-logs","test-runs logs"],["test-runs-stop","test-runs stop"],["test-runs-resume","test-runs resume"],["templates-list","templates|templates list"],["templates-save","templates save"],["templates-show","templates show"]]),sw=new Map([...iw.entries()].flatMap(([e,t])=>St(t).map(n=>[n,e]))),ow=[{canonical:"context",aliases:["ctx"]},{canonical:"package",aliases:["extension","packages"]}],aw=new Map(ow.flatMap(e=>e.aliases.map(t=>[t,e.canonical]))),OL=10,DL=20,Wv=new Map([["activity","Read activity."],["aggregate","Group counts."],["append","Append body."],["assurance","Evaluate assurance."],["assurance derive","Derive checks from evidence."],["assurance risk","Select checks for changes."],["assurance lineages","Measure recurrence coverage."],["beads","Manage Beads interoperability."],["cal","Manage calendar integration."],["calendar","Manage calendar integration."],["changelog","Generate changelog output."],["claim","Claim work."],["close","Close work."],["close-many","Close matching work."],["close-task","Close task work."],["command-kit","Inspect command authoring primitives."],["comments","Manage comments."],["comments-audit","Audit comment governance."],["completion","Generate shell completions."],["config","Manage settings."],["context","Build context."],["contracts","Inspect contracts."],["copy","Copy work."],["create","Create work."],["dedupe-audit","Audit duplicate work."],["dedupe-merge","Merge duplicate work."],["delete","Delete work."],["deps","Manage deps."],["duplicates","Find duplicate clusters."],["docs","Link docs."],["eval","Run evaluations."],["event","Manage events."],["events","Read events."],["files","Link files."],["focus","Manage focus."],["gc","Clean caches."],["get","Read item."],["graph","Query graph."],["guide","Show user guides."],["health","Check health."],["help","Show help."],["history","Inspect history."],["init","Initialize workspace."],["install","Install packages."],["item","Mutate work through typed operations."],["learnings","Manage learnings."],["list","List work."],["list-all","List work across every status."],["list-blocked","List blocked work."],["list-canceled","List canceled work."],["list-closed","List closed work."],["list-draft","List draft work."],["list-in-progress","List in-progress work."],["list-open","List open work."],["meet","Record meeting context."],["merge","Manage tracker merges."],["next","Pick next work."],["notes","Manage notes."],["normalize","Normalize tracker data."],["ops","Run operations."],["package","Manage packages."],["packages","Manage packages."],["pause-task","Pause task work."],["plan","Manage plans."],["profile","Manage profiles."],["reindex","Refresh search index."],["release","Release claim."],["remind","Manage reminders."],["restore","Restore history."],["schema","Customize schema."],["search","Search work."],["search-advanced","Run advanced search."],["start-task","Start task work."],["stats","Show stats."],["telemetry","Manage telemetry."],["templates","Manage work templates."],["test","Run linked tests."],["test-all","Run all linked tests."],["test-runs","Inspect background test runs."],["todos","Manage source-code todos."],["twin","Manage repository twins."],["update","Update work."],["update-many","Update matching work."],["upgrade","Upgrade packages."],["validate","Validate data."],["vcs","Inspect version-control context."],["workspace","Manage portable workspace primitives."],["history-author-acknowledge","Acknowledge reviewed history authors."],["history-compact","Compact history."],["history-redact","Redact sensitive history values."],["history-repair","Repair history integrity."]]),cw=[["init",Bm],["install",Wm],["uninstall",Vm],["explore",Ym],["manage",tf],["describe",Jm],["reload",nf],["doctor",rf],["catalog",sf],["adopt",of],["adopt-all",Xm],["activate",Qm],["deactivate",Zm],["migrate",ef]],LL=[...cw.map(([e,t])=>e==="init"?[e,Hm]:[e,t]),["upgrade",_a]],NL=[...cw.map(([e,t])=>[`extension ${e}`,t]),...LL.flatMap(([e,t])=>[[`package ${e}`,t],[`packages ${e}`,t]]),["init",Gm],["config",Km],["extension",zm],["package",fa],["packages",fa],["install",af],["create",Cf],["item mutate",Rf],["item complete",Of],["item reopen",Df],["copy",Lf],["focus",Nf],["update",Mf],["update-many",Pf],["upgrade",_a],["calendar",pa],["cal",pa],["context",ga],["ctx",ga],["get",$f],["search",zf],["eval",Gf],["workspace",Dt],["workspace position",[]],["workspace snapshot",Dt],["workspace snapshot create",Dt],["workspace snapshot list",Dt],["workspace snapshot inspect",Dt],["workspace snapshot restore",Dt],["workspace snapshot delete",Dt],["next",Kf],["aggregate",Im],["deps",Uf],["graph",qf],["guide",jf],["reindex",cf],["history",Lm],["history-compact",$m],["history-redact",Mm],["history-repair",Pm],["history-author-acknowledge",Fm],["merge",Nm],["schema",jm],["profile",Um],["plan",qm],["restore",ff],["delete",_f],["close",df],["close-many",lf],["append",uf],["claim",mf],["release",pf],["start-task",gf],["pause-task",hf],["close-task",yf],["comments",Am],["notes",Cm],["learnings",Rm],["files",Om],["docs",Dm],["test",vf],["test-all",wf],["telemetry",bf],["test-runs",kf],["gc",Ef],["stats",Sf],["duplicates",xf],["validate",If],["health",Tf],["assurance",Af],...Wf,["contracts",Bf],["completion",Hf],["activity",Ff],...[...nw].map(e=>[e,Tm])],Od=new Map(NL);function ML(e){let t=sw.get(e);return t||(e.startsWith("test-runs ")?`test-runs-${e.slice(10)}`:e.startsWith("templates ")?`templates-${e.slice(10)}`:e)}function Vv(e){return tt.includes(e)?Ee(e):e.startsWith("extension-")?Ee(`extension ${e.slice(10)}`):e.startsWith("package-")?Ee(`package ${e.slice(8)}`):e.startsWith("item-")?Ee(`item ${e.slice(5)}`):e.startsWith("test-runs-")?Ee(`test-runs ${e.slice(10)}`):e.startsWith("templates-")?Ee(`templates ${e.slice(10)}`):Eo.has(e)?iw.get(e)??Ee(e):null}function PL(e,t){return e.command_path===null?!1:St(e.command_path).some(n=>n===t?!0:n.startsWith(`${t} `)||t.startsWith(`${n} `))}function St(e){return e.split("|").map(t=>Ee(t)).filter(t=>t.length>0)}function FL(e,t){let n=new Set(t),r=new Set;for(let i of e)if(i.command_path)for(let s of St(i.command_path)){let o=s.split(" ").filter(a=>a.length>0);if(o.length!==0)for(let a=o.length;a>0;a-=1){let c=o.slice(0,a).join(" ");if(n.has(c)){r.add(c);break}}}return[...r].sort((i,s)=>i.localeCompare(s))}function ko(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function Jr(e){let t=e.oneOf;return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null):[]}function $L(e,t){if(!t)return{...e};let r=Jr(e).filter(i=>{let s=i.properties;if(typeof s!="object"||s===null)return!1;let o=s.action;return typeof o!="object"||o===null?!1:o.const===t});return{...e,oneOf:r}}function Ad(e,t){let r=Jr(e).filter(i=>{let s=i.properties;if(typeof s!="object"||s===null)return!1;let o=s.action;if(typeof o!="object"||o===null)return!1;let a=o.const;return typeof a=="string"&&t.has(a)});return{...e,oneOf:r}}function Ee(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function dw(e){return e.replace(/\s+/g,"-")}function at(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function Yv(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let i=at(r);!i||n.has(i)||(n.add(i),t.push(i))}return t}function Cd(e,t,n){n&&(e[t]=!0)}function Jv(e,t){if(e==null)return null;if(typeof e!="string")throw new TypeError("Expected string for extension flag name.");let n=e.trim();return n.length===0?null:t==="long"?n.startsWith("--")&&n.length>2?n:null:n.startsWith("-")&&!n.startsWith("--")&&n.length>1?n:null}function jL(e){let t=Jv(e.long,"long"),n=Jv(e.short,"short"),r=t??n;if(!r)return null;let i={flag:r};n&&t&&(i.short=n),Cd(i,"required",e.required===!0),Cd(i,"repeatable",e.repeatable===!0),Cd(i,"list",e.list===!0);let s=at(e.description);s&&(i.description=s);let o=at(e.value_name);o&&(i.value_name=o);let a=[at(e.value_type),at(e.type),o?"string":null].find(c=>c==="string"||c==="number"||c==="boolean");return a&&(i.value_type=a),i}function lw(e){let t=new Map;for(let r of e){let i=Ee(r.target_command);if(i.length===0)continue;let s=t.get(i)??{flags:[],sources:[],dedupe:new Set,sourceDedupe:new Set},o=`${r.layer}:${r.name}`;s.sourceDedupe.has(o)||(s.sourceDedupe.add(o),s.sources.push({layer:r.layer,name:r.name}));for(let a of r.flags){let c=jL(a);if(!c)continue;let d=`${c.flag}|${c.short??""}`;s.dedupe.has(d)||(s.dedupe.add(d),s.flags.push(c))}t.set(i,s)}let n=new Map;for(let[r,i]of t.entries())n.set(r,{flags:i.flags,sources:i.sources.sort((s,o)=>{let a=s.layer.localeCompare(o.layer);return a!==0?a:(s.name??"").localeCompare(o.name??"")})});return n}function UL(e){let t=lw(e.flagRegistrations),n=new Map;for(let s of e.commandDefinitions){let o=Ee(s.command);if(o.length===0)continue;let a=at(s.action)??dw(o),c=Array.isArray(s.arguments)?s.arguments.map(d=>{let l=at(d.name);return l?{name:l,required:d.required===!0,variadic:d.variadic===!0,description:at(d.description)}:null}).filter(d=>d!==null):[];n.set(o,{command:o,action:a,source:{layer:s.layer,name:s.name},description:at(s.description),intent:at(s.intent),arguments:c,flags:t.get(o)?.flags??[],examples:Yv(s.examples),failure_hints:Yv(s.failure_hints)})}let r=new Set;for(let s of e.handlers)r.add(Ee(s));for(let s of n.keys())r.add(s);for(let s of t.keys())r.add(s);let i=[];for(let s of[...r].sort((o,a)=>o.localeCompare(a))){let o=n.get(s);i.push(qL(s,o,t.get(s)?.flags??[]))}return i}function qL(e,t,n){return t?{...t,flags:t.flags.length>0?t.flags:n}:{command:e,action:dw(e),source:null,description:null,intent:null,arguments:[],flags:n,examples:[],failure_hints:[]}}function GL(e){let t=e.flag.replace(/^-+/,"").trim();if(t.length===0)return null;let r=t.replace(/-([a-z0-9])/g,(i,s)=>s.toUpperCase()).replace(/[^a-zA-Z0-9]/g,"");return r.length>0?r:null}function KL(e,t){return e.variadic?{type:"array",items:{type:"string"},description:e.description??`Variadic argument '${e.name}' for extension action '${t}'.`}:{type:"string",description:e.description??`Argument '${e.name}' for extension action '${t}'.`}}function zL(e,t){let n=e.value_type??"boolean",r=n==="boolean"?"boolean":n==="number"?["number","string"]:"string",i=e.repeatable===!0||e.list===!0;return{type:i?"array":r,...i?{items:{type:r}}:{},description:e.description??`Extension option '${e.flag}' for action '${t}'.`}}function BL(e){let t=e.command.split("|").map(i=>i.trim()).filter(i=>i.length>0),n={action:{type:"string",const:e.action,description:e.intent??e.description??`Invoke extension command '${e.command}'.`}},r=["action"];for(let i of e.arguments)n[i.name]=KL(i,e.action),i.required&&r.push(i.name);for(let i of e.flags){let s=GL(i);!s||n[s]!==void 0||(n[s]=zL(i,e.action),i.required===!0&&r.push(s))}return{type:"object",properties:n,required:r,additionalProperties:!0,"x-extension-source":e.source,"x-extension-command":t[0]??e.command,"x-extension-commands":t}}function HL(e,t){e.description??=t.description,e.value_name??=t.value_name,e.value_type??=t.value_type,t.required===!0&&(e.required=!0),t.repeatable===!0&&(e.repeatable=!0)}function WL(e){let t=new Map;for(let n of e){let r=t.get(n.action);if(!r){t.set(n.action,{...n,flags:[...n.flags],examples:[...n.examples],failure_hints:[...n.failure_hints]});continue}r.command=[...new Set([r.command,n.command])].sort((s,o)=>s.localeCompare(o)).join("|"),r.arguments=r.arguments.length>=n.arguments.length?r.arguments:n.arguments;let i=new Set(r.flags.map(s=>`${s.flag}|${s.short??""}`));for(let s of n.flags){let o=`${s.flag}|${s.short??""}`;if(!i.has(o))i.add(o),r.flags.push(s);else{let a=r.flags.find(c=>`${c.flag}|${c.short??""}`===o);a&&HL(a,s)}}r.examples=[...new Set([...r.examples,...n.examples])],r.failure_hints=[...new Set([...r.failure_hints,...n.failure_hints])]}return[...t.values()].sort((n,r)=>n.action.localeCompare(r.action))}async function VL(e,t=C){let n={mode:Gt.extensions.policy.mode,trust_mode:Gt.extensions.policy.trust_mode,default_sandbox_profile:Gt.extensions.policy.default_sandbox_profile};if(e.noExtensions)return{handlers:new Set,disabledReason:"extensions_disabled",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};let r=R(process.cwd(),e.path);if(!await V(Ae(r)))return{handlers:new Set,disabledReason:null,commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};try{let i=await t(r),s=await mi({pmRoot:r,settings:i,cwd:process.cwd(),noExtensions:!1}),o=await fi({...s,loaded:s.loaded});return{handlers:new Set(o.commands.handlers.map(c=>Ee(c.command))),disabledReason:null,commandDefinitions:o.registrations.commands,flagRegistrations:o.registrations.flags,registrations:o.registrations,policyState:{mode:s.policy.mode,trust_mode:s.policy.trust_mode,default_sandbox_profile:s.policy.default_sandbox_profile}}}catch{return{handlers:new Set,disabledReason:"extension_runtime_probe_failed",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n}}}function YL(e,t={}){let n=new Map;for(let r of wu){let i=Eo.has(r);if(i&&!t.includePackageOwnedActions)continue;let s=Vv(r);n.set(r,{action:r,provider:i?"extension":"core",requires_extension:i,command_path:s})}if(t.includePackageOwnedActions)for(let r of Eo)n.has(r)||n.set(r,{action:r,provider:"extension",requires_extension:!0,command_path:Vv(r)});for(let r of e)n.has(r.action)||n.set(r.action,{action:r.action,provider:"extension",requires_extension:!0,command_path:Ee(r.command)});return[...n.values()].sort((r,i)=>(r.action??"").localeCompare(i.action??""))}function JL(e,t){if(e.provider==="core"&&!e.requires_extension)return{action:e.action,invocable:!0,available:!0,requires_extension:!1,provider:"core",disabled_reason:null,command_path:e.command_path,cli_exposed:e.command_path!==null};let n=e.command_path?St(e.command_path):[],r=n.some(o=>t.handlers.has(o)),i=n.map(o=>rw.get(o)).find(o=>typeof o=="string"),s=t.disabledReason===null&&r;return{action:e.action,invocable:s,available:s,requires_extension:!0,provider:"extension",disabled_reason:s?null:t.disabledReason??(i?`optional_package_not_installed:${i}`:"extension_command_not_registered"),command_path:e.command_path,cli_exposed:r,policy_state:{mode:t.policyState.mode,trust_mode:t.policyState.trust_mode,default_sandbox_profile:t.policyState.default_sandbox_profile}}}function uw(e){return Od.get(e)??xm}function XL(e){return Yr.has(e)?!1:Od.has(e)}function QL(e){return nw.has(e)?"list":e==="cal"?"calendar":e==="ctx"?"context":e==="update-many"?"update_many":e}function Xv(e){let t=e.trim();return t?t.startsWith("--")?t:t.startsWith("-")?null:`--${t}`:null}function ZL(e){let t=e.trim();return!t||t.startsWith("--")?null:t.startsWith("-")?t:null}function eN(e){let t=new Map;for(let r of e.definitions){let i=Xv(r.cli_flag);if(!i)continue;let s=r.cli_aliases.map(a=>ZL(a)).find(a=>a!==null),o=r.cli_aliases.map(a=>Xv(a)).filter(a=>a!==null&&a!==i);for(let a of r.commands){let c=t.get(a)??{flags:[],seen:new Set},d=s?{flag:i,short:s}:{flag:i},l=`${d.flag}|${d.short??""}`;c.seen.has(l)||(c.seen.add(l),c.flags.push(d));for(let u of o){let m=`${u}|`;c.seen.has(m)||(c.seen.add(m),c.flags.push({flag:u}))}t.set(a,c)}}let n=new Map;for(let[r,i]of t.entries())n.set(r,ma(i.flags));return n}function Qv(e,t){let n=[],r=new Set;for(let i of[...e,...t]){let s=`${i.flag}|${i.short??""}`;r.has(s)||(r.add(s),n.push(i))}return ma(n)}function tN(e,t,n,r){return e.map(i=>{let s=XL(i),o=s?uw(i):[],a=n.get(QL(i))??[],c=t.get(i),d=Qv(o,a),l=Qv(d,c?.flags??[]),u=o.length>0&&(c?.flags.length??0)>0?"mixed":s?"core":"extension";return{command:i,flags:l,...r?{canonical_command:Rd(i),visibility:Nv(Rd(i)),positionals:km(i)?.slots??[],flag_invocations:Ov(i,l)}:{},provider:u,extension_sources:c?.sources}}).sort((i,s)=>i.command.localeCompare(s.command))}function nN(e,t=Zo){let n=new Set(e),r=new Map;for(let i of ow){let s=i.aliases.filter(o=>n.has(o));r.set(i.canonical,{canonical:i.canonical,aliases:s,contracts:[]})}for(let i of t){if(!n.has(i.canonical)||i.registration==="commander"&&!n.has(i.alias))continue;let s=r.get(i.canonical)??{canonical:i.canonical,aliases:[],contracts:[]};s.aliases.includes(i.alias)||s.aliases.push(i.alias),s.contracts.push(i),r.set(i.canonical,s)}return[...r.values()].map(({contracts:i,...s})=>i.length===0?s:{...s,contracts:i}).sort((i,s)=>i.canonical.localeCompare(s.canonical))}function rN(){return{create_string_options:vm,create_repeatable_options:wm,update_string_options:Ui,update_repeatable_options:bm,list_string_options:_m,search_string_options:pm,calendar_string_options:gm,context_string_options:hm,activity_string_options:ym}}function Zv(e,t){let n=new Set(["title","type"]);if(t==="strict"){for(let a of e.required_create_fields)n.add(a);for(let a of e.required_create_repeatables)n.add(a)}let r=vn(e,"create",n),i=[...new Set(r.required)].sort((a,c)=>a.localeCompare(c)),s=[...new Set(i.map(a=>Ie("create",a)))].sort((a,c)=>a.localeCompare(c)),o=[...new Set(e.options.filter(a=>a.required===!0).map(a=>a.key))].sort((a,c)=>a.localeCompare(c));return{required_option_keys:i,required_flags:s,required_type_options:o,policy_errors:[...new Set(r.errors)].sort((a,c)=>a.localeCompare(c))}}function iN(e){let t={},n={};for(let r of[...e.types].sort((i,s)=>i.localeCompare(s))){let i=e.by_type[r];t[r]=Zv(i,"strict"),n[r]=Zv(i,"progressive")}return{default_create_mode:"strict",by_create_mode:{strict:{by_type:t},progressive:{by_type:n}}}}function sN(e,t){let n=Jr(e);if(n.length===0)return e;let r=!1,i=n.map(s=>{let o=s.properties;if(typeof o!="object"||o===null)return s;let a=o.action;return typeof a!="object"||a===null||a.const!=="create"?s:(r=!0,{...s,"x-create-required-options":t})});return r?{...e,oneOf:i}:e}function oN(e){let t=ko(e.action)!==void 0||ko(e.command)!==void 0,n=e.schemaOnly===!0||e.flagsOnly===!0||e.availabilityOnly===!0,r=e.summary===!0||e.full!==!0&&e.runtimeOnly!==!0&&!t&&!n,i=e.schemaOnly===!0,s=e.flagsOnly===!0,o=e.availabilityOnly===!0,a=e.runtimeOnly===!0,c=e.full===!0,d=ko(e.action),l=ko(e.command),u=!r&&!c&&!i&&!s&&!o&&!d&&!l;return{selectedAction:d,selectedCommand:l,summary:r,schemaOnly:i,flagsOnly:s,availabilityOnly:o,runtimeOnly:a,fullOutput:c,omitUnfilteredSchema:u,omitUnfilteredCommandFlags:u,omitUnfilteredCommanderAliases:u||l!==void 0&&!c}}function aN(e){if([e.summary,e.schemaOnly,e.flagsOnly,e.availabilityOnly].filter(n=>n).length>1)throw new _("Choose only one projection flag: --summary, --schema-only, --flags-only, or --availability-only.",f.USAGE)}async function cN(e,t=C){try{return await t(e)}catch{return structuredClone(Gt)}}async function dN(e,t){let n=await cN(t),r=await VL(e),i=U(n,r.registrations??F()),s=En(n.schema),o=UL(r);return{settings:n,runtimeProbe:r,typeRegistry:i,statusRegistry:H(n.schema),runtimeFieldRegistry:s,runtimeFieldFlagMap:eN(s),createRequiredOptionContracts:iN(i),extensionContracts:o,mergedExtensionContracts:WL(o),extensionFlagMap:lw(r.flagRegistrations)}}function ew(e){return e.availabilityOnly&&(e.selectedAction!==void 0&&Eo.has(e.selectedAction)||e.selectedCommand!==void 0&&Yr.has(e.selectedCommand))}function lN(e,t){let n=YL(t,{includePackageOwnedActions:ew(e)});if(e.selectedAction===void 0&&e.selectedCommand===void 0){let r=new Set(bu);return n.filter(i=>!r.has(i.action))}return ew(e)&&e.selectedCommand!==void 0&&Yr.has(e.selectedCommand)&&!n.some(r=>r.command_path===e.selectedCommand)&&n.push({action:ML(e.selectedCommand),provider:"extension",requires_extension:!0,command_path:e.selectedCommand}),n}function uN(e,t){let n=new Set(t.map(r=>r.action));if(e.selectedAction&&!n.has(e.selectedAction))throw new _(`Unknown action: "${e.selectedAction}".`,f.USAGE)}function mN(e,t){return[...new Set([...tt.filter(n=>!Yr.has(n)),...[...Od.keys()].filter(n=>!Yr.has(n)),...e.flatMap(n=>n.command_path?St(n.command_path):[]),...t.flatMap(n=>n.command.split("|"))])].map(n=>Ee(n)).filter(n=>n.length>0).sort((n,r)=>n.localeCompare(r))}function fN(e,t){let n=t.slice(0,OL),r=t.length-n.length,i=r>0?`${n.join(", ")}, and ${r} more`:n.join(", "),s=t.slice(0,DL),o=t.slice(0,5).map(c=>`pm contracts --command "${c}" --flags-only --json`),a=t[0];return new _(`Command "${e}" is a command namespace. Choose a concrete child command: ${i}.`,f.USAGE,{code:"command_namespace",required:"Use a concrete child command path listed under this namespace.",why:"Command groups expose help at the namespace root, but command flag contracts belong to executable child commands.",examples:o,nextSteps:[`Retry with a child command, for example: ${o[0]}`],recovery:{suggested_retry:`pm contracts --command "${a}" --flags-only --json`,fallback_candidates:s.map(c=>({source:"command_namespace",command:`pm contracts --command "${c}" --flags-only --json`,reason:`Child command under ${e}`}))}})}function _N(e,t){return new _(`Unknown command: "${e}". Command "${e}" is provided by the optional "${t}" package. Run "pm install ${t} --project" and retry.`,f.USAGE,{code:"unknown_command",required:`Install the optional "${t}" package, or choose a command from pm contracts --flags-only --json.`,why:"Command contracts include core commands plus commands registered by active packages and extensions.",examples:[`pm install ${t} --project`,`pm contracts --command ${e} --flags-only --json`],nextSteps:[`Install the optional package first: pm install ${t} --project`],recovery:{suggested_retry:`pm install ${t} --project`}})}function pN(e){return new _(`Unknown command: "${e}".`,f.USAGE,{code:"unknown_command",required:"Use a command path listed by pm contracts --flags-only --json.",why:"Command contracts are generated from the active core, package, and extension command registry.",examples:["pm contracts --flags-only --json","pm --help"],nextSteps:["Verify spelling and active packages/extensions, then rerun with a known command path."],recovery:{suggested_retry:"pm contracts --flags-only --json"}})}function gN(e,t){if(!e.selectedCommand||new Set(t).has(e.selectedCommand))return;let r=t.filter(s=>s.startsWith(`${e.selectedCommand} `));if(r.length>0)throw fN(e.selectedCommand,r);let i=rw.get(e.selectedCommand);throw i?_N(e.selectedCommand,i):pN(e.selectedCommand)}function hN(e,t){let n=lN(e,t.mergedExtensionContracts);uN(e,n);let r=mN(n,t.mergedExtensionContracts);gN(e,r);let i=e.selectedCommand?sw.get(e.selectedCommand):void 0,s=e.selectedCommand?n.filter(d=>i?d.action===i:PL(d,e.selectedCommand)):n;if(e.selectedCommand&&e.selectedAction&&!s.some(d=>d.action===e.selectedAction))throw new _(`Action "${e.selectedAction}" is not mapped to command "${e.selectedCommand}" in contracts output.`,f.USAGE);let o=e.selectedAction?s.filter(d=>d.action===e.selectedAction):s,a=[...new Map(o.map(d=>JL(d,t.runtimeProbe)).map(d=>[i?d.action:`${d.action}|${d.command_path??""}`,d])).values()],c=e.runtimeOnly&&!e.selectedAction&&!e.availabilityOnly?a.filter(d=>d.invocable):a;return{actionDescriptors:n,commandCatalog:r,commandScopedDescriptors:s,scopedActionDescriptors:o,selectedPackageOwnedAction:i,actionAvailability:c,actions:[...new Set(c.map(d=>d.action))]}}function yN(e){return new Set(Jr(e).map(t=>{let n=t.properties;if(typeof n!="object"||n===null)return null;let r=n.action;if(typeof r!="object"||r===null)return null;let i=r.const;return typeof i=="string"?i:null}).filter(t=>t!==null))}function vN(e){let t=e_,n=Jr(t),r=yN(t),i=e.filter(s=>!r.has(s.action)).map(s=>BL(s));return i.length>0?{...t,oneOf:[...n,...i]}:t}function tw(e,t,n){let r=new Set(t.actionDescriptors.map(s=>s.action)),i=e.selectedAction?$L(n,e.selectedAction):e.selectedCommand?Ad(n,new Set(t.scopedActionDescriptors.map(s=>s.action))):Ad(n,r);return e.runtimeOnly&&!e.selectedAction?Ad(i,new Set(t.actions)):i}function wN(e,t,n){let r=vN(t.mergedExtensionContracts),s=!e.flagsOnly&&!e.availabilityOnly?sN(tw(e,n,r),t.createRequiredOptionContracts):tw(e,n,r);return{mergedSchema:r,filteredSchema:s}}function bN(e,t){return e.selectedCommand!==void 0?[e.selectedCommand]:e.selectedAction?FL(t.scopedActionDescriptors,t.commandCatalog):t.commandCatalog}function kN(e,t){if(e.selectedCommand!==void 0||e.selectedAction!==void 0)return t;let n=new Set(Zo.filter(r=>r.hidden&&r.lifecycle==="deprecated").map(r=>r.alias));return t.filter(r=>!n.has(r))}function Rd(e){let t=e.split(" ")[0];return t.startsWith("list-")?"list":t.startsWith("history-")?"history":aw.get(t)??t}var EN=new Map([["activate","Activate"],["adopt","Adopt"],["adopt-all","Adopt all"],["catalog","Catalog"],["complete","Complete"],["create","Create"],["deactivate","Deactivate"],["delete","Delete"],["describe","Describe"],["doctor","Diagnose"],["explore","Explore"],["init","Initialize"],["inspect","Inspect"],["install","Install"],["list","List"],["manage","Manage"],["migrate","Migrate"],["mutate","Mutate"],["reload","Reload"],["restore","Restore"],["run","Run"],["snapshot","Manage snapshots for"],["uninstall","Uninstall"],["upgrade","Upgrade"]]),SN=new Map([["extension adopt-all","extensions"],["package adopt-all","packages"],["workspace snapshot list","workspace snapshots"]]);function xN(e,t){let n=Wv.get(e)??(e.includes(" ")?void 0:Wv.get(Rd(e)));if(n!==void 0)return{intent:n,intent_source:"command"};let r=t.find(d=>St(d.command).includes(e));if(r?.intent!==null&&r?.intent!==void 0)return{intent:r.intent,intent_source:"command"};if(r?.description!==null&&r?.description!==void 0)return{intent:r.description,intent_source:"description"};let i=e.split(" "),s=i.at(-1),o=i.slice(0,-1).join(" "),a=EN.get(s),c=SN.get(e)??o;return{intent:a===void 0||o.length===0?`Run ${e}.`:`${a} ${c}.`,intent_source:"generated"}}function TN(e,t=[],n={}){let r=n.includeFormatBudgets??!0,i=n.includeIntentProvenance??!0;return[...new Set(e.map(Ee))].filter(s=>s.length>0).sort((s,o)=>s.localeCompare(o)).map(s=>{let o=ta(s,{generateFallback:!0}),a=s.split(" ")[0],c=aw.get(a)??(a.startsWith("list-")?"list":a.startsWith("history-")?"history":a),d=new Set([...uw(s).map(m=>m.flag),...t.filter(m=>St(m.command).includes(s)).flatMap(m=>m.flags.map(g=>g.flag))]),l=(Hv.get(s)??Hv.get(c)??RL).filter(m=>d.has(m)),u=xN(s,t);return{command:s,intent:u.intent,...i||u.intent_source!=="command"?{intent_source:u.intent_source}:{},...l.length>0?{flags:l}:{},default_max_estimated_tokens:o.default_max_estimated_tokens,...r?{default_max_estimated_tokens_by_format:{...o.default_max_estimated_tokens_by_format}}:{}}})}function IN(e){return e.map(t=>({budget:ta(t,{generateFallback:!0}),envelope:Kv(t)}))}function AN(e){let t=new Map;for(let n of e){let r=_y(n),i=r===void 0?[f.SUCCESS,f.GENERIC_FAILURE,f.USAGE,f.NOT_FOUND,f.CONFLICT,f.DEPENDENCY_FAILED]:r.exit_codes,s=i.join(","),o=t.get(s)??{commands:[],exit_codes:i};o.commands.push(n),t.set(s,o)}return[...t.values()]}function CN(e,t,n){if(e.selectedCommand)return t.extensionContracts.filter(r=>St(r.command).includes(e.selectedCommand));if(e.selectedAction){let r=new Set(n);return t.extensionContracts.filter(i=>St(i.command).some(s=>r.has(s)))}return t.extensionContracts}function RN(e,t,n,r){return{schema_version:typeof t.mergedSchema["x-schema-version"]=="string"?t.mergedSchema["x-schema-version"]:null,schema_id:typeof t.mergedSchema.$id=="string"?t.mergedSchema.$id:null,selected:{action:e.selectedAction??null,command:e.selectedCommand??null,summary:e.summary,schema_only:e.schemaOnly,flags_only:e.flagsOnly,availability_only:e.availabilityOnly,runtime_only:e.runtimeOnly,command_scoped:e.selectedCommand!==void 0},commands:e.summary?[]:r,...!e.summary&&!e.flagsOnly?{actions:n.actions,action_availability:n.actionAvailability}:{}}}function ON(e,t,n){let r=n.selectedCommand;e.runtime_schema={statuses:t.statusRegistry.definitions.map(i=>i.id),open_status:t.statusRegistry.open_status,close_status:t.statusRegistry.close_status,canceled_status:t.statusRegistry.canceled_status,types:[...t.typeRegistry.types],fields_by_command:Object.fromEntries([...t.runtimeFieldRegistry.command_to_fields.entries()].filter(([i])=>r===void 0||i===r).map(([i,s])=>[i,[...new Set(s.map(o=>`--${o.cli_flag}`))].sort((o,a)=>o.localeCompare(a))]))},!(r!==void 0&&!n.fullOutput)&&(e.extension_contracts={capabilities:[...fu],services:[..._u],policy_modes:[...pu],policy_mode_scope:"extensions.policy.mode",policy_surfaces:[...yu],trust_modes:[...gu],trust_mode_scope:"extensions.policy.trust_mode",sandbox_profiles:[...hu],manifest_versions:[1,2],compatibility:{current:"v2",previous:["v1"],breaking_strategy:"versioned_breaking"}},e.governance_contracts={ownership_enforcement_modes:[...Il],create_modes:[...Al],close_validation_modes:[...Cl],workflow_enforcement_modes:[...Rl]},e.relationship_kind_contracts=[...Kl,...(t.runtimeProbe.registrations?.relationship_kinds??[]).flatMap(i=>i.definitions)].sort((i,s)=>i.kind.localeCompare(s.kind)).map(i=>({canonical:i.kind,aliases:[...i.aliases??[]],...i.inverse===void 0?{}:{inverse:i.inverse},ordering:i.ordering,hierarchy:i.hierarchy})))}function DN(e,t,n,r){if(!(t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredSchema){e.schema=n.filteredSchema,e.extension_commands=r;return}e.schema_omitted_reason="unfiltered_default_brief",e.extension_commands=r}}function LN(e,t,n,r,i){if(!(t.schemaOnly||t.availabilityOnly)){if(t.omitUnfilteredCommandFlags)e.command_flags_omitted_reason="unfiltered_default_brief";else{e.command_flags=tN(r,n.extensionFlagMap,n.runtimeFieldFlagMap,t.selectedCommand!==void 0);let s=new Set(r);e.list_projections=Object.entries(S_).filter(([o])=>s.has(o)).map(([o,a])=>({command:o,default:a,brief_fields:[...E_],compact_fields:[...k_]}))}e.command_aliases=i}}function NN(e,t){if(!(t.schemaOnly||t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredCommanderAliases){e.commander_aliases=rN();return}e.commander_aliases_omitted_reason=t.selectedCommand?"command_scoped":"unfiltered_default_brief"}}function MN(e,t,n,r){e.command_summaries=TN(t,n,{includeFormatBudgets:r.includeFormatBudgets,includeIntentProvenance:r.includeIntentProvenance}),e.output_policy={token_estimate:"ceil(utf8_bytes / 4)",degradation_ladder:[...ku],allows_unbounded_opt_out:!0},e.output_projection_contracts={global_ladder_field:"output_policy.degradation_ladder",global_ladder_scope:"union_not_per_command",discovery:"pm contracts --command <command> --summary",...r.includeProjectionModeMatrix?{commands:[...new Set(t.map(Ee))].filter(i=>xu(i)!==void 0).sort((i,s)=>i.localeCompare(s)).map(i=>({command:i,modes:[...Tu(i).keys()]}))}:{}},e.grammar_contracts={nouns:Vt.nouns,shared_verbs:Vt.shared_verbs,scope_before_verb:Vt.scope_before_verb,visible_top_level_ceiling:Vt.visible_top_level_ceiling,ceiling_raise_requires_pm_item:Vt.ceiling_raise_requires_pm_item,positional_shape_budget:Vt.positional_shape_budget,positional_shape_count:new Set(ua.map(({slots:i})=>Sm(i))).size,positional_action_count:la.length,positional_action_parents:[...new Set(la.map(({parent:i})=>i))].sort((i,s)=>i.localeCompare(s)),...r.includePositionalSignatures?{positional_signatures:ua}:{}}}async function f5(e,t){let n=oN(e);aN(n);let r=R(process.cwd(),t.path),i=await dN(t,r),s=hN(n,i),o=wN(n,i,s),a=bN(n,s),c=kN(n,a),d=RN(n,o,s,c),l=CN(n,i,c),u=n.fullOutput||n.selectedCommand!==void 0;if((n.summary||n.fullOutput)&&MN(d,c,l,{includeFormatBudgets:u,includeIntentProvenance:u,includePositionalSignatures:u,includeProjectionModeMatrix:u}),n.summary)return d;let m=nN(s.commandCatalog);return n.flagsOnly&&!n.fullOutput||ON(d,i,n),DN(d,n,o,l),LN(d,n,i,c,m),NN(d,n),(n.selectedCommand==="assurance"||n.fullOutput)&&(d.assurance_contracts={measurement_source_kinds:[...gr],gate_triggers:[...pt]}),n.fullOutput&&d.grammar_contracts&&(d.grammar_contracts.destinations=Em),n.fullOutput&&!n.schemaOnly&&!n.flagsOnly&&!n.availabilityOnly&&(d.mcp_tools=Bv(),d.context_intents=Iu(),d.read_output_dimensions=Su,d.error_codes=qv,d.command_output_contracts=IN(c),d.diagnostic_output_contracts=Eu,d.command_exit_contracts={vocabulary:ed,command_sets:AN(c)}),d}import{createHash as FN}from"node:crypto";import{execFile as $N}from"node:child_process";import _w from"node:path";import{promisify as jN}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="939d5f93-d287-5c1c-bc78-d013f76735f2")}catch{}})();var mw=1;function PN(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.id=="string"&&typeof t.metric=="string"&&typeof t.value=="number"&&Number.isFinite(t.value)&&["higher","lower","target"].includes(String(t.direction))&&typeof t.observed_at=="string"&&typeof t.revision=="string"&&["caller","git","unversioned"].includes(String(t.revision_source))&&typeof t.author=="string"?t.direction!=="target"||typeof t.threshold=="number"&&Number.isFinite(t.threshold):!1}function Dd(e){if(e===null)return{format_version:mw,observations:[]};let t;try{t=JSON.parse(e)}catch{throw new _("Improvement ledger contains invalid JSON.",f.GENERIC_FAILURE,{code:"invalid_improvement_ledger"})}if(typeof t!="object"||t===null||Array.isArray(t)||t.format_version!==mw||!Array.isArray(t.observations))throw new _("Improvement ledger has an unsupported shape or format version.",f.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});let n=t.observations;for(let r of n)if(!PN(r))throw new _("Improvement ledger contains an invalid observation.",f.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});return t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c2e1edc9-c454-5cfa-85c8-e9fb0a76a296")}catch{}})();var UN=jN($N),qN=50,fw=1e3,GN=/^[a-z0-9](?:[a-z0-9._/-]{0,126}[a-z0-9])?$/u;function pw(e){let t=e.trim().toLowerCase();if(!GN.test(t))throw new _(`Invalid metric name "${e}"; use 1-128 lowercase letters, digits, dots, slashes, underscores, or hyphens.`,f.USAGE,{code:"invalid_improvement_metric"});return t}function KN(e){let t=e??"lower";if(!["higher","lower","target"].includes(t))throw new _("Improvement direction must be higher, lower, or target.",f.USAGE,{code:"invalid_improvement_observation"});return t}function Xr(e,t){let n=e?.trim();if(n){if(n.length>256)throw new _(`${t} must not exceed 256 characters.`,f.USAGE,{code:"invalid_improvement_observation"});return n}}function zN(e){let t=e??qN;if(!Number.isSafeInteger(t)||t<0||t>fw)throw new _(`Improvement observation limit must be an integer from 0 to ${fw}.`,f.USAGE,{code:"invalid_improvement_observation_limit"});return t}function gw(e,t){let n=Date.parse(e);if(!Number.isFinite(n))throw new _(`${t} must be an ISO timestamp.`,f.USAGE,{code:"invalid_improvement_observation_timestamp"});return new Date(n).toISOString()}async function BN(e,t,n){if(!Number.isFinite(n.value))throw new _("Improvement observation value must be finite.",f.USAGE,{code:"invalid_improvement_observation"});let r=pw(n.metric),i=KN(n.direction);if(n.threshold!==void 0&&!Number.isFinite(n.threshold)||i==="target"&&n.threshold===void 0)throw new _("Target-directed observations require a finite threshold.",f.USAGE,{code:"invalid_improvement_observation"});let s=await WN(e,n.revision),o=Xr(n.source,"source"),a=Xr(n.itemId,"itemId"),c=Xr(n.unit,"unit"),d=Xr(n.idempotencyKey,"idempotencyKey")??(s.revision_source==="unversioned"?void 0:[s.revision,r,o??"manual",a??"workspace"].join(":")),l={metric:r,value:n.value,direction:i,...c===void 0?{}:{unit:c},...n.threshold===void 0?{}:{threshold:n.threshold},observed_at:gw(n.observedAt??T(),"observedAt"),...s,author:q(n.author,t.author_default),...a===void 0?{}:{item_id:a},...o===void 0?{}:{source:o},...d===void 0?{}:{idempotency_key:d}};return{id:FN("sha256").update(D(l)).digest("hex").slice(0,24),...l}}function HN(e,t){let n=t.idempotency_key?e.observations.find(i=>i.idempotency_key===t.idempotency_key):e.observations.find(i=>i.id===t.id);if(n){if(n.metric!==t.metric||n.value!==t.value||n.direction!==t.direction||n.threshold!==t.threshold||n.unit!==t.unit)throw new _(`Improvement observation retry key already records a different value for ${t.metric}.`,f.CONFLICT,{code:"improvement_observation_conflict"});return n}let r=e.observations.find(i=>i.metric===t.metric);if(r&&(r.direction!==t.direction||r.unit!==t.unit||t.direction==="target"&&r.threshold!==t.threshold))throw new _(`Metric ${t.metric} is already declared with direction ${r.direction} and unit ${r.unit??"<none>"}.`,f.CONFLICT,{code:"improvement_metric_contract_conflict"})}async function WN(e,t){let n=Xr(t,"revision");if(n)return{revision:n,revision_source:"caller"};try{return{revision:(await UN("git",["rev-parse","--verify","HEAD^{commit}"],{cwd:Ze(e),encoding:"utf8",timeout:5e3})).stdout.trim(),revision_source:"git"}}catch{}return{revision:"unversioned",revision_source:"unversioned"}}function VN(e){let t=e[0],n=e[e.length-1],r=n.value-t.value,i=n.direction==="higher"?r>0:n.direction==="lower"?r<0:Math.abs(n.value-n.threshold)<Math.abs(t.value-t.threshold);return{metric:n.metric,direction:n.direction,baseline:t,latest:n,delta:r,improved:i,sample_count:e.length}}async function hw(e,t={}){let n=R(process.cwd(),t.path);await $(n);let r=await C(n),i=await BN(n,r,e),s=_w.join(n,"improvement-ledger.json"),o=await Cn({pmRoot:n,filePath:s,op:"improvement_observe",author:i.author,lockTtlSeconds:r.locks.ttl_seconds,lockWaitMs:r.locks.wait_ms,message:e.message??`Record ${i.metric}=${String(e.value)} improvement observation`,mutate:a=>{let c=Dd(a),d=HN(c,i);return d?{raw:a,result:d}:(c.observations.push(i),c.observations.sort((l,u)=>l.observed_at.localeCompare(u.observed_at)||l.metric.localeCompare(u.metric)||l.id.localeCompare(u.id)),{raw:`${D(c)}
|
|
28
|
-
`,result:i})}});return{changed:o.changed,observation:o.result,ledger_path:"improvement-ledger.json"}}async function yw(e={}){let t=R(e.cwd??process.cwd(),e.pmRoot);await $(t);let n=e.metric===void 0?void 0:pw(e.metric),r=e.since===void 0?void 0:gw(e.since,"since"),i=zN(e.limit),o=Dd(await Y(_w.join(t,"improvement-ledger.json"))).observations.filter(c=>(n===void 0||c.metric===n)&&(e.itemId===void 0||c.item_id===e.itemId)&&(r===void 0||c.observed_at>=r)),a=new Map;for(let c of o){let d=a.get(c.metric)??[];d.push(c),a.set(c.metric,d)}return{observations:[...o].reverse().slice(0,i),total:o.length,truncated:o.length>i,trends:[...a].map(([,c])=>VN(c)).sort((c,d)=>c.metric.localeCompare(d.metric)),source:"audited_workspace_singleton"}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6162845d-f4b4-5d1f-a210-ddef1a5c38f6")}catch{}})();function YN(e){return e.agent_episode!==void 0?{id:e.agent_episode.id,source:"declared"}:{id:e.agent_instance?`inferred:instance:${e.agent_instance}`:`inferred:author:${e.author}:${e.ts.slice(0,13)}`,source:"inferred"}}function JN(e,t,n){let r=t,i=new Set([e.id]);for(;r!==void 0&&!i.has(r.id);)i.add(r.id),r=r.parent_id?n.get(r.parent_id):void 0;return r===void 0}function XN(e){let t=[e];for(;t.length>0;){let n=t.pop();n.sort((r,i)=>r.entries[0].ts.localeCompare(i.entries[0].ts)||r.id.localeCompare(i.id)),t.push(...n.map(r=>r.children))}}function vw(e=dr,t=cr){return t.map(n=>{let r=e.filter(i=>((n==="model"?i.model_environment_keys:i.provenance_environment_keys?.[n])?.length??0)>0||i.provenance_resolvers?.[n]!==void 0).map(i=>i.harness).sort();return{dimension:n,harnesses:r,covered:r.length>0}})}function M5(e,t=1){let n=new Map;for(let r of e){if(!r.agent_harness)continue;let i=n.get(r.agent_harness)??{harness:r.agent_harness,entries:0,observed:0,unavailable:0,legacy_missing:0};i.entries+=1,r.agent_model||r.agent_provenance?.model&&r.agent_provenance.model.value.length>0?i.observed+=1:r.agent_provenance?.model===null?i.unavailable+=1:i.legacy_missing+=1,n.set(r.agent_harness,i)}return[...n.values()].map(r=>{let i=r.observed+r.unavailable;return{...r,coverage:i===0?null:r.observed/i,inert:i>=t&&r.observed===0}}).sort((r,i)=>r.harness.localeCompare(i.harness))}function ww(e,t=cr,n=1){let r=new Map;for(let i of e)if(i.agent_harness)for(let s of t){let o=`${i.agent_harness}\0${s}`,a=r.get(o)??{harness:i.agent_harness,dimension:s,entries:0,observed:0,unavailable:0,legacy_missing:0};a.entries+=1;let c=i.agent_provenance?.[s];c!=null&&c.value.length>0?a.observed+=1:c===null?a.unavailable+=1:a.legacy_missing+=1,r.set(o,a)}return[...r.values()].map(i=>{let s=i.observed+i.unavailable;return{...i,coverage:s===0?null:i.observed/s,inert:s>=n&&i.observed===0}}).sort((i,s)=>i.harness.localeCompare(s.harness)||i.dimension.localeCompare(s.dimension))}function P5(e,t={}){let n=t.minimumCoverage??.8,r=t.minimumEntries??5;if(![Number.isFinite(n),n>=0,n<=1].every(Boolean))throw new RangeError("Semantic attribution minimum coverage must be from 0 to 1.");if(![Number.isSafeInteger(r),r>=1].every(Boolean))throw new RangeError("Semantic attribution minimum entries must be a positive integer.");let i=new Map;for(let c of e)if(c.agent_harness)for(let d of["role","topic"]){let l=`${c.agent_harness}\0${d}`,u=i.get(l)??{harness:c.agent_harness,dimension:d,entries:0,observed:0,by_source:{},coverage:0};u.entries+=1;let m=c.agent_provenance?.[d];m?.value&&(u.observed+=1,u.by_source[m.source]=(u.by_source[m.source]??0)+1),i.set(l,u)}let s=[...i.values()].map(c=>({...c,coverage:c.observed/c.entries,by_source:Object.fromEntries(Object.entries(c.by_source).sort(([d],[l])=>d.localeCompare(l)))})).sort((c,d)=>c.harness.localeCompare(d.harness)||c.dimension.localeCompare(d.dimension)),o=s.filter(c=>c.entries>=r),a=o.filter(c=>c.coverage<n).map(c=>`${c.harness}:${c.dimension}`);return{passed:o.length>0&&a.length===0,minimum_coverage:n,minimum_entries:r,rows:s,failures:a}}function F5(e){let t=[...e].sort((s,o)=>s.ts.localeCompare(o.ts)||s.author.localeCompare(o.author)||s.op.localeCompare(o.op)||s.before_hash.localeCompare(o.before_hash)||s.after_hash.localeCompare(o.after_hash)),n=new Map,r=new Map;for(let s of t){let o=s.agent_episode,a=YN(s),c=`${a.source}:${a.id}`,d=n.get(c);if(d){d.entries.push(s);continue}let l={id:a.id,...o?.label===void 0?{}:{label:o.label},...o?.parent_id===void 0?{}:{parent_id:o.parent_id},source:a.source,entries:[s],children:[]};n.set(c,l),o!==void 0&&r.set(a.id,l)}let i=[];for(let s of n.values()){let o=s.parent_id?r.get(s.parent_id):void 0;o&&JN(s,o,r)?o.children.push(s):i.push(s)}return XN(i),i}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f0e89b0b-ccd1-5dbb-afad-119d5a98590a")}catch{}})();var QN=1e4,bw=1e5,ZN=1e3,eM=30,tM=["append","comment","docs","file","learning","note","test_run"];function nM(e){let t=e??QN;if(!Number.isSafeInteger(t)||t<1||t>bw)throw new _(`History analytics event limit must be an integer from 1 to ${bw}.`,f.USAGE,{code:"invalid_history_analytics_limit"});return t}function kw(e){let t=e??5;if(!Number.isSafeInteger(t)||t<1||t>1e4)throw new _("History analytics minimum sample must be an integer from 1 to 10000.",f.USAGE,{code:"invalid_history_analytics_minimum_sample"});return t}function rM(e){let t=e?.trim();if(!t)return new Date(Date.now()-eM*864e5).toISOString();let n=/^-(\d+)([dh])$/u.exec(t);if(n){let i=Number(n[1]),s=n[2]==="d"?864e5:36e5;if(!Number.isSafeInteger(i)||i<1)throw new _("History analytics --since duration must be positive.",f.USAGE,{code:"invalid_history_analytics_since"});return new Date(Date.now()-i*s).toISOString()}let r=Date.parse(t);if(!Number.isFinite(r))throw new _("History analytics --since must be an ISO timestamp or negative duration such as -30d.",f.USAGE,{code:"invalid_history_analytics_since"});return new Date(r).toISOString()}async function So(e,t){let n=nM(t.eventLimit),r=rM(t.since),i=[],s=r,o=!1;for(;i.length<n;){let a=await C_({pmRoot:e,since:s,limit:Math.min(ZN,n-i.length),full:!0}),c=a.events.map(d=>({item_id:d.item_id,entry:d.entry}));if(i.push(...c),o=a.has_more,s=a.next_cursor,!a.has_more)break}return{events:i,receipt:{since:r,events:i.length,truncated:o,...o?{next_cursor:s}:{},source:"history_event_index"}}}function iM(e,t){return t==="harness"?e.agent_harness:t==="author_source"?e.author_source:e.agent_model??e.agent_provenance?.model?.value}function sM(e){for(let t=e.patch.length-1;t>=0;t-=1){let n=e.patch[t];if(n.path==="/metadata/status"&&"value"in n&&typeof n.value=="string")return n.value}}function oM(e){return tM.some(t=>e.startsWith(t))}function Ew(e,t){let n=e.get(t);if(n)return n;let r={events:0,stateEvents:0,annotationEvents:0,closes:0,reopens:0,defectEscapes:0};return e.set(t,r),r}function aM(e,t,n){let r=new Map,i=new Map,s=new Map;for(let o of t){let a=iM(o.entry,e),c=sM(o.entry),d=i.get(o.item_id)===!0,l=c===void 0?d:n.has(c);if(c!==void 0&&i.set(o.item_id,l),!a)continue;let u=Ew(r,a);u.events+=1,oM(o.entry.op)?u.annotationEvents+=1:u.stateEvents+=1,c!==void 0&&!d&&l?(u.closes+=1,s.set(o.item_id,a)):c!==void 0&&d&&!l&&(u.reopens+=1)}return{buckets:r,lastCloseValue:s}}function cM(e,t,n){for(let r of n){if(r.type!=="Issue")continue;let i=new Set((r.dependencies??[]).filter(s=>s.kind==="discovered_from").map(s=>s.id));for(let s of i){let o=t.get(s);o&&(Ew(e,o).defectEscapes+=1)}}}function dM(e,t,n,r){let i=t.closes>=n?"available":"insufficient";return{value:e,events:t.events,state_events:t.stateEvents,annotation_events:t.annotationEvents,closes:t.closes,reopens:t.reopens,defect_escapes:t.defectEscapes,throughput_per_day:i==="available"?t.closes/r:null,rework_rate:i==="available"?t.reopens/t.closes:null,defect_escape_rate:i==="available"?t.defectEscapes/t.closes:null,sample_status:i}}function lM(e,t,n,r,i,s){let{buckets:o,lastCloseValue:a}=aM(e,t,r);return cM(o,a,n),{dimension:e,status:o.size===0?"unavailable":"available",rows:[...o].map(([c,d])=>dM(c,d,i,s)).sort((c,d)=>d.events-c.events||c.value.localeCompare(d.value))}}function uM(e,t){let n=e[0]?.entry.ts??t,r=e[e.length-1]?.entry.ts??n,i=Date.parse(n),s=Date.parse(r);return!Number.isFinite(i)||!Number.isFinite(s)?1:Math.max(1,(s-i)/864e5)}function mM(e,t,n){let r=vw(t),i=ww(e,cr,n),s=i.filter(a=>a.inert).map(a=>({harness:a.harness,dimension:a.dimension,explicit_samples:a.observed+a.unavailable})),o=r.filter(a=>!a.covered).map(a=>a.dimension);return{descriptors:r,observations:i,inert:s,undeclared:o,warnings:[...s.map(a=>`provenance_dimension_inert:${a.harness}:${a.dimension}:${String(a.explicit_samples)}`),...o.map(a=>`provenance_dimension_undeclared:${a}`)]}}async function z5(e,t=dr,n={}){return Ld(await So(e,n),t,n)}function Ld(e,t=dr,n={}){let r=kw(n.minimumSample);return{...mM(e.events.map(i=>i.entry),t,r),window:e.receipt}}async function B5(e,t,n,r={}){return Nd(await So(e,r),t,n,r)}function Nd(e,t,n,r={}){let i=kw(r.minimumSample),s=uM(e.events,e.receipt.since);return{dimensions:["harness","model","author_source"].map(o=>lM(o,e.events,t,n,i,s)),minimum_sample:i,policy:"observational_only_not_for_authorization_or_routing",window:e.receipt}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6e840281-a386-57db-bee0-c9b93b27deb1")}catch{}})();var fM=32;function _M(e){let t=[];for(let n of e??[]){let r=[];for(let i of n.split(",")){let s=i.slice(0,i.indexOf("=")).trim();r.length>0&&s!=="unit"&&s!=="threshold"&&(t.push(r.join(",")),r=[]),r.push(i)}t.push(r.join(","))}return t}function Qr(e,t){let n=_M(e).map(i=>{let[s,...o]=i.split(","),a=s.indexOf("="),c=s.slice(0,a).trim(),d=s.slice(a+1).trim(),l=Number(d);if(a<=0||c.length===0||d.length===0||!Number.isFinite(l))throw new _(`Invalid --measure "${i}"; expected name=value[,unit=...][,threshold=...]`,f.USAGE);let u,m;for(let g of o){let p=g.indexOf("="),h=g.slice(0,p).trim(),y=g.slice(p+1).trim();if(h==="unit"&&y.length>0)u=y;else if(h==="threshold"&&y.length>0&&Number.isFinite(Number(y)))m=Number(y);else throw new _(`Invalid --measure attribute "${g}"`,f.USAGE)}return{name:c,value:l,unit:u,threshold:m,recorded_at:t}});return[...new Map(n.map(i=>[i.name,i])).values()].sort((i,s)=>i.name.localeCompare(s.name)).slice(0,fM)}function Sw(e,t,n){return e.flatMap(r=>(r.measurements??[]).filter(i=>i.name===t&&i.value<n).map(i=>({...i,run_id:r.run_id})))}function xw(e,t){let n=e.flatMap(s=>s.measurements??[]).filter(s=>s.name===t).sort((s,o)=>o.recorded_at.localeCompare(s.recorded_at)),r=n[0],i=n[1];return{name:t,latest:r?.value??null,previous:i?.value??null,delta:r!==void 0&&i!==void 0?r.value-i.value:null,unit:r?.unit}}import gM from"node:fs/promises";import Iw from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ed44fc89-8b6e-5c83-a4f4-ced4e9031dac")}catch{}})();function xo(e,t,n,r,i,s="min"){let o=i==="min"?e-t:t-e,a=s==="min"?n.localeCompare(r??n):(r??n).localeCompare(n);return o<0||o===0&&r!==null&&a<0}function pM(e,t){let n=Buffer.byteLength(t,"utf8"),r=0,i=null,s=null,o=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY;for(let c of t.split(/\r?\n/)){let d=c.trim();if(d==="")continue;r+=1;let l;try{l=JSON.parse(d)}catch{continue}if(l===null||typeof l!="object"||!("ts"in l)||typeof l.ts!="string")continue;let u=l.ts,m=Date.parse(u);Number.isNaN(m)||(xo(m,o,u,i,"min")&&(o=m,i=u),xo(m,a,u,s,"max","max")&&(a=m,s=u))}return{id:e,bytes:n,lines:r,oldest_ts:i,newest_ts:s}}function Tw(e,t){let n=t?.topN??5,r=Math.max(0,Math.floor(n)),i=e.map(({id:g,raw:p})=>pM(g,p)),s=0,o=0,a=null,c=null,d=Number.POSITIVE_INFINITY,l=Number.NEGATIVE_INFINITY;for(let g of i){if(s+=g.lines,o+=g.bytes,g.oldest_ts!==null){let p=Date.parse(g.oldest_ts);xo(p,d,g.id,a?.id??null,"min")&&(d=p,a={id:g.id,ts:g.oldest_ts})}if(g.newest_ts!==null){let p=Date.parse(g.newest_ts);xo(p,l,g.id,c?.id??null,"max")&&(l=p,c={id:g.id,ts:g.newest_ts})}}let u=r===0?[]:[...i].sort((g,p)=>p.bytes-g.bytes||g.id.localeCompare(p.id)).slice(0,r),m=r===0?[]:[...i].sort((g,p)=>p.lines-g.lines||g.id.localeCompare(p.id)).slice(0,r);return{total_streams:e.length,total_lines:s,total_bytes:o,largest_by_bytes:u,deepest_by_lines:m,oldest_entry:a,newest_entry:c}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b56db1fc-d989-5d18-8b29-336a03f1e525")}catch{}})();function hM(e){return e.reduce((t,n)=>(t[n]=0,t),{})}function yM(e,t,n,r,i){let s=pr(e,"type",r),o=new Set(s.rows.map(m=>m.key)),a=t.filter(m=>!o.has(m)),d=(i?[...s.rows,...a.map(m=>({label:m,key:m,total:0,buckets:{open:0,in_progress:0,blocked:0,draft:0,closed:0,canceled:0,other:0}}))]:s.rows).map(m=>({type:m.key??m.label,total:m.total,open:m.buckets.open,in_progress:m.buckets.in_progress,blocked:m.buckets.blocked,draft:m.buckets.draft,closed:m.buckets.closed,canceled:m.buckets.canceled,other:m.buckets.other})),l=hM([...n]);for(let m of e)l[m.status]+=1;let u=Object.fromEntries(Object.entries(l).filter(([,m])=>i||m>0));return{byType:d,byStatus:u,omitted:i?0:a.length+Object.values(l).filter(m=>m===0).length}}function vM(e){return e.trim().length===0?0:e.split(/\r?\n/u).filter(t=>t.trim().length>0).length}async function wM(e){let t=Iw.join(e,"history");if(!await V(t))return[];await Ce({path:t,scope:"project"});let n=(await gM.readdir(t)).filter(i=>i.endsWith(".jsonl")).sort((i,s)=>i.localeCompare(s)),r=[];for(let i of n){let s=Iw.join(t,i),o=await Y(s);o!==null&&(await Ce({path:s,scope:"project"}),r.push({id:i.slice(0,-6),raw:o}))}return r}async function bM(e,t){let n=[],r=T();for(let i of Qr(t.observe,r))n.push(await hw({metric:i.name,value:i.value,direction:t.direction,unit:i.unit,threshold:i.threshold,source:t.measurementSource,itemId:t.measurementItem,revision:t.measurementRevision,observedAt:r,author:t.author,message:t.message},e));return n}function kM(e,t,n){let r={};return t.byAssignee&&(r.assignee=pr(e,"assignee",n)),t.byTag&&(r.tag=pr(e,"tag",n,{tagPrefix:t.tagPrefix})),t.byPriority&&(r.priority=pr(e,"priority",n)),r}async function EM(e,t,n,r,i){let s={since:i.since,eventLimit:i.eventLimit,minimumSample:i.minimumSample},o=i.provenanceCoverage||i.fleetAttribution?await So(e,s):void 0;return{provenanceCoverage:i.provenanceCoverage&&o?Ld(o,n.agent_identity?.harness_signals,s):void 0,fleetAttribution:i.fleetAttribution&&o?Nd(o,t,r,s):void 0}}function SM(e,t,n,r,i){let s=Object.keys(i.breakdowns).length>0;return{totals:e,by_type:t,by_status:n,omitted_zero_buckets:r,...i.metadataCoverage?{metadata_coverage:i.metadataCoverage}:{},...s?{breakdowns:i.breakdowns}:{},...i.storage?{storage:i.storage}:{},...i.fieldUtilization?{field_utilization:i.fieldUtilization}:{},...i.improvementLedger?{improvement_ledger:i.improvementLedger}:{},...i.recordedObservations.length>0?{recorded_observations:i.recordedObservations}:{},...i.provenanceCoverage?{provenance_coverage:i.provenanceCoverage}:{},...i.fleetAttribution?{fleet_attribution:i.fleetAttribution}:{},generated_at:T()}}async function _8(e,t={}){let n=R(process.cwd(),e.path);await $(n);let r=await C(n),i=await bM(e,t),s=U(r,F()),o=H(r.schema),a=t.fieldUtilization?await _t(n,r.item_format,s.type_to_folder,void 0,r.schema):await Se(n,r.item_format,s.type_to_folder,void 0,r.schema);await Di({pmRoot:n,settings:r,itemIds:a.map(E=>E.id),commandLabel:"stats"});let c=v_(o),d=yM(a,s.types,o.definitions.map(E=>E.id),c,t.includeEmpty===!0),l=await wM(n),u=0;for(let E of l)u+=vM(E.raw);let m=t.storage?Tw(l):void 0,g=t.metadataCoverage?w_(a,c):void 0,p=kM(a,t,c),h=t.fieldUtilization?b_(a):void 0,y=t.measurements===!0||i.length>0?await yw({pmRoot:n,metric:t.metric,itemId:t.measurementItem,limit:t.measurementLimit}):void 0,{provenanceCoverage:v,fleetAttribution:w}=await EM(n,a,r,o.terminal_statuses,t);return SM({items:a.length,history_streams:l.length,history_entries:u},d.byType,d.byStatus,d.omitted,{metadataCoverage:g,breakdowns:p,storage:m,fieldUtilization:h,improvementLedger:y,recordedObservations:i,provenanceCoverage:v,fleetAttribution:w})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="51a84d98-6b3c-55ad-81f8-81928aa6e537")}catch{}})();async function y8(e,t={}){let n=await Sy({pmRoot:R(process.cwd(),e.path),exhaustive:t.exhaustive,...t.status===void 0?{}:{statuses:t.status.flatMap(r=>r.split(",").map(i=>i.trim()).filter(Boolean))},...t.since===void 0?{}:{since:t.since},...t.threshold===void 0?{}:{threshold:t.threshold},...t.limit===void 0?{}:{limit:t.limit}});return{...n,clusters:n.clusters.map(r=>{let i=r.id;return{...r,canonical_id:i,close_command:`pm close <duplicate-id> --duplicate-of ${i}`}}),guidance:{strategy:"review_then_close_duplicate",command:"pm close <duplicate-id> --duplicate-of <canonical-id>"}}}import xM from"node:fs/promises";import Ut from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ad3110ca-e85b-5a7e-b0a1-591796c298eb")}catch{}})();var Dw=Ut.join("runtime","telemetry","events.jsonl"),Lw=Ut.join("runtime","telemetry","state.json"),TM=Ut.join("runtime","telemetry"),IM=20,Aw=["status","flush","stats","clear"],Cw=(e,t)=>{let n=Math.ceil(t*e.length),r=Math.min(e.length-1,Math.max(0,n-1));return e[r]},Md=(e,t)=>typeof e!="string"?t:e.trim().length>0?e:t,Rw=e=>{if(!(typeof e!="number"||!Number.isFinite(e)))return Math.trunc(e)},AM=e=>({command:Md(e.event.command,"<unknown>"),eventType:Md(e.event.event_type,"unknown"),eventSchemaVersion:Rw(e.event.schema_version),clientSchemaVersion:Rw(e.client_schema_version)}),CM=()=>({count:0,max_attempts:0,event_type_counts:{},event_schema_versions:new Set,client_schema_versions:new Set,finish_durations_ms:[],ok_count:0,error_count:0,resolution_counts:{}}),RM=e=>{let t=e?.duration_ms;return typeof t=="number"&&Number.isFinite(t)?t:void 0},OM=e=>{let t=e?.command_resolution;return Md(t,"")||void 0},Nw=(e,t)=>{e[t]=(e[t]??0)+1},DM=(e,t)=>{let n=RM(t);n!==void 0&&e.finish_durations_ms.push(n),t?.ok===!0?e.ok_count+=1:e.error_count+=1;let r=OM(t);r!==void 0&&Nw(e.resolution_counts,r)},LM=e=>Number.isFinite(e)?Math.max(0,Math.trunc(e)):0,Ow=(e,t)=>{t!==void 0&&e.add(t)},NM=(e,t)=>{let n=AM(t),r=e.get(n.command)??CM();r.count+=1,r.max_attempts=Math.max(r.max_attempts,LM(t.attempts)),Nw(r.event_type_counts,n.eventType),Ow(r.event_schema_versions,n.eventSchemaVersion),Ow(r.client_schema_versions,n.clientSchemaVersion),n.eventType==="command_finish"&&DM(r,t.event.payload),e.set(n.command,r)},MM=(e,t)=>{let n=t.ok_count+t.error_count,r=[...t.finish_durations_ms].sort((s,o)=>s-o),i=Object.entries(t.resolution_counts).sort((s,o)=>s[0].localeCompare(o[0]));return{command:e,count:t.count,event_type_counts:Object.fromEntries(Object.entries(t.event_type_counts).sort((s,o)=>s[0].localeCompare(o[0]))),max_attempts:t.max_attempts,event_schema_versions:[...t.event_schema_versions].sort((s,o)=>s-o),client_schema_versions:[...t.client_schema_versions].sort((s,o)=>s-o),...r.length>0?{duration_p50_ms:Cw(r,.5),duration_p95_ms:Cw(r,.95),duration_max_ms:r[r.length-1]}:{},...n>0?{ok_count:t.ok_count,error_count:t.error_count,error_rate:t.error_count/n}:{},...i.length>0?{command_resolution_counts:Object.fromEntries(i)}:{}}},PM=e=>{let t=(e??"status").trim().toLowerCase();if(Aw.includes(t))return t;throw ai({command_path:"telemetry",token:e?.trim()||"<empty>",allowed:Aw,examples:["pm telemetry status","pm telemetry flush","pm telemetry stats --limit 10","pm telemetry clear"]})},Pd=()=>{throw new _("--limit must be a positive integer",f.USAGE)},Mw=e=>[!Number.isFinite(e),!Number.isInteger(e),e<=0].includes(!0)?Pd():e,FM=e=>{let t=e.trim();return[t.length===0,!/^\d+$/.test(t)].includes(!0)?Pd():Mw(Number.parseInt(t,10))},$M=e=>e===void 0?IM:typeof e=="number"?Mw(e):typeof e=="string"?FM(e):Pd(),jM=e=>{if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.attempts=="number"&&typeof t.event=="object"&&t.event!==null},UM=e=>{try{let t=JSON.parse(e);return jM(t)?t:void 0}catch{return}},qM=e=>e===null?[]:e.split(`
|
|
29
|
-
`).map(t=>t.trim()).filter(t=>t.length>0),Pw=e=>{let t=qM(e),n=[],r=0;for(let i of t){let s=UM(i);s===void 0?r+=1:n.push(s)}return{rows_total:t.length,valid_entries:n.length,invalid_rows:r,entries:n}},GM=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),KM=e=>{try{let t=JSON.parse(e);return GM(t)?t:{}}catch{return{}}},zM=async e=>{let t=await Y(e);return t===null||t.trim().length===0?{}:KM(t)},To=e=>e??null,Io=async e=>{let t=await C(e),n=Ut.join(e,Dw),r=Ut.join(e,Lw),i=await Y(n),s=Pw(i),o=await zM(r);return{enabled:t.telemetry.enabled,endpoint:t.telemetry.endpoint,queue_path:n,state_path:r,queue_rows_total:s.rows_total,queue_entries:s.valid_entries,queue_invalid_rows:s.invalid_rows,queue_size_bytes:Buffer.byteLength(i??"","utf8"),last_attempted_flush_at:To(o.last_attempted_flush_at),last_successful_flush_at:To(o.last_successful_flush_at),last_failed_flush_at:To(o.last_failed_flush_at),last_failed_flush_error:To(o.last_failed_flush_error)}},BM=e=>{let t=new Map;for(let n of e)NM(t,n);return[...t.entries()].map(([n,r])=>MM(n,r)).sort((n,r)=>r.count-n.count||n.command.localeCompare(r.command))},HM=async(e,t)=>({action:"telemetry",subcommand:"status",status:await Io(t.globalPmRoot),generated_at:T()}),WM=async(e,t)=>{let n=await Io(t.globalPmRoot);await fm(t.globalPmRoot);let r=await Io(t.globalPmRoot),i=Math.max(0,n.queue_entries-r.queue_entries),s=r.queue_entries===0;return{action:"telemetry",subcommand:"flush",queue_entries_before:n.queue_entries,queue_entries_after:r.queue_entries,queue_entries_drained:i,queue_progressed:i>0,queue_empty:s,queue_drained:s,status:r,generated_at:T()}},VM=async(e,t)=>{let n=$M(e.limit),r=await Y(t.queuePath),i=Pw(r),s=BM(i.entries),o=s.slice(0,n);return{action:"telemetry",subcommand:"stats",limit:n,total_commands:s.length,queue_entries:i.valid_entries,queue_invalid_rows:i.invalid_rows,queue_rows_total:i.rows_total,truncated:s.length>o.length,stats:o,generated_at:T()}},YM=async(e,t)=>{let n=await C(t.globalPmRoot),r=[n.telemetry.enabled!==!1,n.telemetry.installation_id!=="",n.telemetry.first_run_prompt_completed!==!0].includes(!0);n.telemetry.enabled=!1,n.telemetry.first_run_prompt_completed=!0,n.telemetry.installation_id="",r&&await Vu(t.globalPmRoot,n,"telemetry:clear");let i=Ut.join(t.globalPmRoot,TM),s=await V(i);return await xM.rm(i,{recursive:!0,force:!0}),{action:"telemetry",subcommand:"clear",settings_changed:r,runtime_dir_removed:s&&!await V(i),queue_exists_after:await V(t.queuePath),state_exists_after:await V(t.statePath),status:await Io(t.globalPmRoot),generated_at:T()}},JM={status:HM,flush:WM,stats:VM,clear:YM};async function R8(e,t){let n=PM(e.subcommand),r=et(process.cwd());return JM[n](e,{globalPmRoot:r,queuePath:Ut.join(r,Dw),statePath:Ut.join(r,Lw)})}import{spawn as rb}from"node:child_process";import{cp as Ud,mkdir as Do,mkdtemp as ib,open as qd,readdir as Gd,rm as Zr,symlink as sb}from"node:fs/promises";import{tmpdir as ob}from"node:os";import Z from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="62af7c1e-c1c7-529e-ab30-117103ac4607")}catch{}})();var Fw=20;function XM(){let e=process.env.PM_TRACKED_TEST_RUN_HISTORY_LIMIT;if(!e||e.trim().length===0)return Fw;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<=0?Fw:t}function Fd(e){let t=[...e].filter(r=>r.run_id.trim().length>0&&r.started_at.trim().length>0&&r.finished_at.trim().length>0&&r.recorded_at.trim().length>0).sort((r,i)=>{let s=lt(r.recorded_at,i.recorded_at);if(s!==0)return s;let o=r.run_id.localeCompare(i.run_id);return o!==0?o:r.kind.localeCompare(i.kind)}),n=XM();return t.length>n?t.slice(t.length-n):t}async function Ao(e){await me({pmRoot:e.pmRoot,settings:e.settings,id:e.itemId,op:"test_run_track",author:e.author,message:e.message,force:!1,mutate(t){let n=t.metadata.test_runs??[];return t.metadata.test_runs=Fd([...n,e.entry]),{changedFields:["test_runs"]}}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8a6a3402-dae3-56f8-b9ba-a4f6f8a47cda")}catch{}})();var $w=100;function $d(e,t="--only-index"){let n=typeof e=="number"?e:Number(String(e).trim());if(!Number.isInteger(n)||n<1)throw new _(`${t} requires a 1-based integer index into the linked-test list (got "${e}"). Use pm test <id> --list to inspect positions.`,f.USAGE);return n}function QM(e){let n=(e.command??e.path??"<no command>").replaceAll(/\s+/g," ").trim()||"<no command>";return n.length<=$w?n:`${n.slice(0,$w-3)}...`}function jw(e){return e.map((t,n)=>`${n+1}. ${QM(t)}`).join("; ")}function ZM(e){let t=[];return e.match!==void 0&&t.push("match"),e.onlyIndex!==void 0&&t.push("only-index"),e.onlyLast===!0&&t.push("only-last"),t}function eP(e,t){let n=e.command?.toLowerCase()??"",r=e.path?.toLowerCase()??"";return n.includes(t)||r.includes(t)}function Uw(e,t){let n=ZM(t);if(n.length===0)return{selector:null,requested:null,selected:e,selected_indexes:e.map((i,s)=>s+1),selected_count:e.length,skipped_count:0};if(n.length>1)throw new _(`Combine at most one linked-test selector per run: ${n.map(i=>`--${i}`).join(" and ")} were provided. Pick one of --match, --only-index, --only-last.`,f.USAGE);let r=n[0];if(e.length===0)throw new _(`--${r} matched no linked tests because this item has none. Add one first with --add, --command, or --add-json.`,f.USAGE);if(r==="match"){let i=t.match.trim().toLowerCase();if(i.length===0)throw new _("--match requires a non-empty substring to match against linked-test command/path values",f.USAGE);let s=[],o=[];for(let a=0;a<e.length;a+=1)eP(e[a],i)&&(o.push(e[a]),s.push(a+1));if(o.length===0)throw new _(`--match "${t.match}" matched none of the ${e.length} linked test(s). Available entries: ${jw(e)}`,f.USAGE);return{selector:"match",requested:t.match,selected:o,selected_indexes:s,selected_count:o.length,skipped_count:e.length-o.length}}if(r==="only-index"){let i=$d(t.onlyIndex);if(i>e.length)throw new _(`--only-index ${i} is out of range: this item has ${e.length} linked test(s). Available entries: ${jw(e)}`,f.USAGE);return{selector:"only-index",requested:String(i),selected:[e[i-1]],selected_indexes:[i],selected_count:1,skipped_count:e.length-1}}return{selector:"only-last",requested:"last",selected:[e[e.length-1]],selected_indexes:[e.length],selected_count:1,skipped_count:e.length-1}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="03f2f710-3b96-5671-85fa-d8ea4726ee86")}catch{}})();var Oo=20*1024*1024,tP=3e3,nP=1e4,rP=5e3,qw=120,iP=new Set(["locks","extensions","runtime"]),sP=new Set(["history","index","search","extensions","locks","runtime"]),oP=[/eaddrinuse/i,/address already in use/i,/port\s+\d+\s+is already in use/i,/web server[^.\n]*already running/i,/failed to listen on/i],aP=/\b(?:could not|failed to|unable to)\s+acquire\b[^\n.]*\block\b/i,cP=/\b(?:already running|timed?\s*out|timeout|held by another|lock\s+is\s+held)\b/i,dP=new Set(["activity","calendar","context","ctx","deps","get","health","history","list","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","search","stats","test-all","validate"]);function Bd(e,t){let n=process.env[e];if(typeof n!="string"||n.trim().length===0)return t;let r=Number.parseInt(n,10);return!Number.isFinite(r)||r<=0?t:r}function lP(){return Bd("PM_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS",tP)}function uP(){return Bd("PM_LINKED_TEST_HEARTBEAT_INTERVAL_MS",nP)}function mP(){return Bd("PM_LINKED_TEST_PIPE_CLOSE_GRACE_MS",rP)}function fP(e){let t=process.env.PM_BACKGROUND_TEST_RUN_ID?.trim();return t&&t.length>0?t:`${e}-local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function _P(e){let t=0,n=0,r=0;for(let i of e){if(i.status==="passed"){t+=1;continue}if(i.status==="failed"){n+=1;continue}r+=1}return{passed:t,failed:n,skipped:r}}function Hd(e){let t=0,n=0,r=0,i=0;for(let s of e){let o=s.execution_context;!o||o.is_pm_command!==!0||(t+=1,o.is_pm_tracker_read_command===!0&&(n+=1),o.mismatch_detected===!0&&(r+=1),o.auto_pm_context_applied===!0&&(i+=1))}return{checked_pm_commands:t,tracker_read_commands:n,mismatches:r,auto_remediated:i}}function pP(e){let t=e??"project";if(!Ue.includes(t))throw new _(`Invalid scope "${e}"`,f.USAGE);return t}function Lo(e){if(!e)return"schema";let t=e.trim().toLowerCase();if(sn.includes(t))return t;throw new _(`Invalid --pm-context value "${e}". Expected one of: ${sn.join(", ")}`,f.USAGE)}function gP(e){return an(e??"source","--workspace-context")}function ab(e,t,n){return n?t:an(e.workspace_context_mode,"linked test")??t}function cb(e,t,n){return n||typeof e.pm_context_mode!="string"||e.pm_context_mode.trim().length===0?t:Lo(e.pm_context_mode)}function db(e,t){return e==="auto"?t?"tracker":"schema":e}function hP(e){return Object.entries(e).filter(([t])=>t.startsWith("assert_")).some(([,t])=>t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:typeof t=="string"?t.trim().length>0:!0)}function yP(e){let{executionContext:t,runLevelPmContextMode:n,linkedOverridePmContextMode:r}=e;return!t.is_pm_tracker_read_command||!t.mismatch_detected?"":n==="tracker"&&r==="schema"?" Linked test metadata pm_context_mode=schema overrides run-level --pm-context tracker. Set pm_context_mode=tracker (or auto) on the linked test, or remove the override, to run against seeded tracker data.":t.pm_context_mode==="schema"?" Use --auto-pm-context to route PM tracker-read linked commands through seeded tracker data automatically. Alternatively, use --pm-context tracker for the whole run.":""}function vP(e,t){let n={};if(!e)return n;for(let r of e){let i=qr(r,t);if(i)for(let[s,o]of Object.entries(i))n[s]=o}return n}function wP(e,t){if(!e)return[];let n=[];for(let r of e){let i=Gr(r,t);i&&n.push(...i)}return[...new Set(n)]}function bP(e){let t=ei(e);return Zt(t).some(n=>xs(n)!==null)}function lb(e){let t=ei(e);return Zt(t).some(n=>{let r=xs(n);if(!r)return!1;let i=Oc(r);return i?dP.has(i.subcommand):!1})}function Co(e){if(e)return jg.has(e.subcommand)?Pt(e.args,Ug)?.subcommand:e.subcommand}function Gw(e,t){if(e==="npx"||e==="bunx")return en(t)?.command;if(e==="pnpm")return Co(Pt(t,Ic));if(e==="npm")return Co(Pt(t,Ac));if(e==="yarn")return Co(Pt(t,Fg));if(e==="bun")return Co(Pt(t,$g))}function Ro(e){return e?e==="vitest"||e==="test"||e.startsWith("test:"):!1}function jd(e){return!e||!Dr(e.command)&&!Rc(e.command)?!1:Is(e.args)==="test-all"}var ub=new Map([...["sh","bash","dash","zsh"].map(e=>[e,/^(?:-c|-[a-z]*c[a-z]*)$/u]),...["cmd","cmd.exe"].map(e=>[e,/^\/[ck]$/u]),...["powershell","powershell.exe","pwsh","pwsh.exe"].map(e=>[e,/^-(?:c|command)$/u])]),kP=new Set(["npx","bunx"]);function mb(e){let t=e.split(" ").filter(o=>o.length>0),n=Ts(t);if(n.length===0)return!1;let[r,...i]=n,s=ub.get(r);if(s){let o=i.findIndex(a=>s.test(a));return o>=0?mb(i.slice(o+1).join(" ")):!1}return Dr(r)||Lr(r)?Is(i)==="test-all":r==="node"&&i.length>0&&Lr(i[0])?Is(i.slice(1))==="test-all":kP.has(r)?jd(en(i)):r==="pnpm"?jd(As(i)):r==="npm"?jd(Cs(i)):!1}function fb(e){let t=ei(e);return Zt(t).some(n=>mb(n))}function _b(e){if(fb(e))throw new _('Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.',f.USAGE)}function ei(e){return e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase()}function Kw(e){return e.includes("node scripts/run-tests.mjs ")||e.endsWith("node scripts/run-tests.mjs")||e.includes("node ./scripts/run-tests.mjs ")||e.endsWith("node ./scripts/run-tests.mjs")}function Wd(e){let t=e.split(" ").filter(o=>o.length>0),n=Ts(t);if(n.length===0)return!1;let[r,...i]=n,s=ub.get(r);if(s){let o=i.findIndex(a=>s.test(a));return o>=0&&Wd(i.slice(o+1).join(" "))}return r==="vitest"||r.endsWith("/vitest")||r.endsWith("/vitest.mjs")?!0:r==="node"?EP(i):SP(r,i)}function EP(e){return e.includes("--test")||e.some(t=>t==="vitest"||t==="vitest.mjs"||t.endsWith("/vitest")||t.endsWith("/vitest.mjs"))}function SP(e,t){return e==="npx"||e==="bunx"?Ro(en(t)?.command):e==="pnpm"||e==="npm"?Ro((e==="pnpm"?As(t):Cs(t))?.command)||Ro(Gw(e,t)):(e==="yarn"||e==="bun")&&Ro(Gw(e,t))}function f9(e){let t=ei(e),n=Zt(t),r=n.some(s=>!Kw(s)&&Wd(s)),i=n.some(Kw);return{accepted:!0,command_kind:r?"direct_runner":i?"sandbox_runner":"other",tracker_isolation:"runtime_injected",trust_boundary:"provenance",advisory:r?"Accepted with runtime-injected tracker isolation. Prefer the repository sandbox runner when available for reproducible build and coverage setup.":"Accepted with runtime-injected tracker isolation and provenance checks before execution."}}function xP(e){if(fb(e))return'Linked test command skipped: Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.'}function TP(e){return e?e.map(IP):[]}function IP(e){let t=e.trim(),n=xy(t)?qs(te(e,"--add"),"--add"):{command:t},r=he(n.command);if(!r)throw new _("--add requires command=<value> or a bare command (path=<value> is optional metadata)",f.USAGE);return _b(r),{command:r,path:he(n.path),scope:pP(n.scope),timeout_seconds:AP(he(n.timeout_seconds),he(n.timeout)),pm_context_mode:Hs(he(n.pm_context_mode),"--add"),workspace_context_mode:an(he(n.workspace_context_mode),"--add"),env_set:qr(he(n.env_set),"--add"),env_clear:Gr(he(n.env_clear),"--add"),shared_host_safe:Bs(he(n.shared_host_safe),"--add","shared_host_safe"),assert_stdout_contains:cn(he(n.assert_stdout_contains)),assert_stdout_regex:Wn(he(n.assert_stdout_regex),"--add","assert_stdout_regex"),assert_stderr_contains:cn(he(n.assert_stderr_contains)),assert_stderr_regex:Wn(he(n.assert_stderr_regex),"--add","assert_stderr_regex"),assert_stdout_min_lines:Ws(he(n.assert_stdout_min_lines),"--add"),assert_json_field_equals:Vs(he(n.assert_json_field_equals),"--add"),assert_json_field_gte:Ys(he(n.assert_json_field_gte),"--add"),note:he(n.note)}}function he(e){let t=e?.trim();return t&&t.length>0?t:void 0}function AP(e,t){if(e&&t&&e!==t)throw new _("--add timeout and timeout_seconds must match when both are provided",f.USAGE);let n=e??t;if(n===void 0)return;let r=Math.floor(_e(n,"timeout_seconds"));if(r<=0)throw new _("--add timeout_seconds must be a positive integer",f.USAGE);return r}function CP(e){return e?e.flatMap(t=>{let n=Ay(t,"--add-json");for(let r of n){let i=r.command;if(!i)throw new _("--add-json requires a non-empty command string",f.USAGE);_b(i)}return n}):[]}function RP(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new _("--remove requires command or path value",f.USAGE);let r=/^(command|path)\s*=/i.exec(n);if(r){let i=n.slice(r[0].length).trim();if(!i)throw new _("--remove requires a non-empty command=<value> or path=<value>",f.USAGE);return{kind:r[1].toLowerCase(),value:i}}if(/^[A-Za-z_][\w-]*=\S+$/u.test(n))throw new _("--remove structured selectors require command=<value> or path=<value>",f.USAGE);if(/^(?:[-*+]\s+)?(?:path|command)\s*:/i.test(n)||n.startsWith("```")){let i=te(n,"--remove"),s=i.path!==void 0?"path":"command",o=i.path??i.command;if(!o?.trim())throw new _("--remove requires command=<value> and/or path=<value>",f.USAGE);return{kind:s,value:o.trim()}}return{kind:"either",value:n}}):[]}function OP(e){return e?[...new Set(e.map(t=>{let n=typeof t=="number"?t:Number.parseInt(t,10);if(!Number.isInteger(n)||n<1||String(n)!==String(t).trim())throw new _("--remove-index must be a positive integer",f.USAGE);return n}))]:[]}function DP(e){try{e.stdin?.end()}catch{}}function pb(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length<=qw?t:`${t.slice(0,qw-3)}...`}function gb(e){return e==="off"?!1:e==="always"?!0:process.stderr.isTTY===!0}function Kd(e){try{process.stderr.write(`${e}
|
|
30
|
-
`)}catch{}}function LP(e,t){if(!gb(t))return null;let n=pb(e.command),r=Date.now();Kd(`[pm test] linked-test ${e.index}/${e.total} start timeout_ms=${e.timeoutMs} command="${n}"`);let i=setInterval(()=>{let s=Date.now()-r;Kd(`[pm test] linked-test ${e.index}/${e.total} running elapsed_ms=${s} command="${n}"`)},uP());return i.unref?.(),i}function NP(e,t,n,r){if(!gb(r))return;let i=pb(e.command),s=Date.now()-n,a=t.timedOut||t.maxBufferExceeded||t.exitCode!==0?"failed":"passed",c=[];t.timedOut&&c.push("reason=timeout"),t.maxBufferExceeded&&c.push("reason=max_buffer"),t.outputTruncated&&c.push("output=truncated"),t.signal&&c.push(`signal=${t.signal}`);let d=t.exitCode===null?"null":String(t.exitCode),l=c.length>0?` ${c.join(" ")}`:"";Kd(`[pm test] linked-test ${e.index}/${e.total} end status=${a} exit_code=${d} elapsed_ms=${s}${l} command="${i}"`)}async function zw(e){if(!(!Number.isInteger(e)||e<=0)){if(process.platform==="win32"){await new Promise(t=>{let n=rb("taskkill",["/pid",String(e),"/T","/F"],{stdio:"ignore",windowsHide:!0});n.on("error",()=>t()),n.on("close",()=>t())});return}try{process.kill(-e,"SIGKILL");return}catch{}try{process.kill(e,"SIGKILL")}catch{}}}function MP(e){e.heartbeat&&clearInterval(e.heartbeat),e.timedOutTimer&&(clearTimeout(e.timedOutTimer),e.timedOutTimer=null),e.forceKillTimer&&(clearTimeout(e.forceKillTimer),e.forceKillTimer=null)}function PP(e,t){let n=!1;return async()=>{if(n)return;n=!0;let r=e.pid;if(!r||r<=0){try{e.kill("SIGTERM")}catch{}return}if(process.platform==="win32"){await zw(r);return}try{process.kill(-r,"SIGTERM")}catch{try{e.kill("SIGTERM")}catch{}}t.forceKillTimer=setTimeout(()=>{zw(r)},lP()),t.forceKillTimer.unref?.()}}function FP(e){return new Promise(t=>{let n=!1,r=null,i=(s,o=!1)=>{n||(n=!0,r&&(clearTimeout(r),r=null),o&&(e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy()),t(s))};e.on("exit",(s,o)=>{n||(r=setTimeout(()=>{i({code:s,signal:o},!0)},mP()),r.unref?.())}),e.on("close",(s,o)=>{i({code:s,signal:o})})})}function $P(e,t,n,r,i){return rb(e,{cwd:i,env:t,shell:!0,windowsHide:!0,detached:process.platform!=="win32",stdio:["pipe",n,r]})}async function Bw(e){let t=await qd(e,"r");try{let n=(await t.stat()).size,r=Math.min(n,Oo),i=Buffer.alloc(r);return r>0&&await t.read(i,0,r,0),{text:i.toString("utf8"),truncated:n>Oo}}finally{await t.close()}}async function jP(e,t,n,r,i,s=process.cwd()){let o=Date.now(),a=await ib(Z.join(ob(),"pm-linked-test-output-"));try{let c=Z.join(a,"stdout.log"),d=Z.join(a,"stderr.log"),[l,u]=await Promise.all([qd(c,"w"),qd(d,"w")]),m;try{m=$P(e,n,l.fd,u.fd,s)}catch(O){throw await Promise.all([l.close(),u.close()]),O}let g=FP(m),p;m.on("error",O=>{p=O.message}),await Promise.all([l.close(),u.close()]),DP(m);let h={heartbeat:LP(r,i),forceKillTimer:null,timedOutTimer:null},y=PP(m,h),v=!1;h.timedOutTimer=setTimeout(()=>{v=!0,y()},t),h.timedOutTimer.unref?.();let{code:w,signal:E}=await g;MP(h);let[S,x]=await Promise.all([Bw(c),Bw(d)]),I=S.truncated||x.truncated,k=I?`
|
|
31
|
-
[pm linked-test output truncated at ${Oo} bytes per stream; the child process continued to completion]
|
|
32
|
-
`:"",b={stdout:`${S.text}${k}`,stderr:x.text,exitCode:w,signal:E,timedOut:v,maxBufferExceeded:!1,outputTruncated:I,spawnError:p};return NP(r,b,o,i),b}finally{await Zr(a,{recursive:!0,force:!0})}}function UP(e,t){let n=[];e.maxBufferExceeded&&n.push(`Linked test output exceeded maxBuffer=${Oo} bytes. Reduce output volume or split the command.`),e.timedOut&&t>0&&n.push(`Linked test timed out after ${t}ms.`);let r=e.signal?`Linked test command terminated by signal ${e.signal}.`:void 0,i=e.spawnError?.trim()||r||"Linked test command failed.";return n.length===0?i:`${i} ${n.join(" ")}`}function qP(e){let t=[e.spawnError??"",e.stderr,e.stdout].join(`
|
|
33
|
-
`);return oP.some(n=>n.test(t))||t.split(/\r?\n/u).some(n=>aP.test(n)&&cP.test(n))}function GP(e){return qP(e)?"infra_collision":e.timedOut?"timeout":e.maxBufferExceeded?"max_buffer":e.spawnError?"spawn_error":e.signal?"signal":"assertion_failure"}function KP(){return{infra_collision:0,trust_refusal:0,assertion_failure:0,empty_run:0,timeout:0,max_buffer:0,spawn_error:0,signal:0}}function No(e){let t=KP();for(let n of e)n.status!=="failed"||!n.failure_category||(t[n.failure_category]+=1);return t}function Hw(e,t){for(let[n,r]of Object.entries(t.env_set))on.has(n.toUpperCase())||(e[n]=r);for(let n of t.env_clear)on.has(n.toUpperCase())||delete e[n]}function zP(e){e.PORT===void 0&&(e.PORT="0"),e.HOST===void 0&&(e.HOST="127.0.0.1"),e.PM_SHARED_HOST_SAFE===void 0&&(e.PM_SHARED_HOST_SAFE="1"),e.PLAYWRIGHT_HTML_OPEN===void 0&&(e.PLAYWRIGHT_HTML_OPEN="never"),e.PW_TEST_HTML_REPORT_OPEN===void 0&&(e.PW_TEST_HTML_REPORT_OPEN="never")}function BP(e,t){let n={...e.env_set,...t.env_set},r=[...new Set([...e.env_clear,...t.env_clear??[]])],i=t.shared_host_safe??e.shared_host_safe;return{env_set:n,env_clear:r,shared_host_safe:i}}function HP(e,t,n){return{env_set:vP(e,"--env-set"),env_clear:wP(t,"--env-clear"),shared_host_safe:n===!0}}async function Zn(e,t,n=!1,r=Do){if(await V(e))try{await or("seed_linked_test",async()=>{if(await r(Z.dirname(t),{recursive:!0}),n){await Ud(e,t,{recursive:!0,force:!0});return}await Ud(e,t,{force:!0})},{why:"Linked tests need an isolated PM context without mutating the source tracker.",nextSteps:["Reclaim capacity on the filesystem that hosts the linked-test temporary directory."]})}catch(i){if(typeof i=="object"&&i!==null&&"code"in i&&j(i))return;throw i}}async function Ww(e,t,n){await Zn(Ae(n.projectPmRoot),Ae(e)),await Zn(Z.join(n.projectPmRoot,"extensions"),Z.join(e,"extensions"),!0),await Zn(Ae(n.globalPmRoot),Ae(t)),await Zn(Z.join(n.globalPmRoot,"extensions"),Z.join(t,"extensions"),!0)}async function Vw(e,t){if(!await V(e))return;let n=await Gd(e,{withFileTypes:!0});for(let r of n){if(iP.has(r.name))continue;let i=Z.join(e,r.name),s=Z.join(t,r.name);if(r.isDirectory()){await Zn(i,s,!0);continue}r.isFile()&&await Zn(i,s)}}async function Yw(e,t){let n=await Y(Ae(e));if(n===null||await V(Wt(e)))return;let r=await C(t);await Zr(Wt(t),{force:!0}),await Zr(Ae(t),{force:!0}),await ju({pmRoot:t,filePath:Ae(t),raw:n,op:"settings:write",author:q(void 0,r.author_default),lockTtlSeconds:r.locks.ttl_seconds,lockWaitMs:r.locks.wait_ms,recordCreation:!0,message:"Seed linked-test tracker settings history"})}async function Qn(e){if(!await V(e))return 0;let t=0,n=await Gd(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||sP.has(r.name))continue;let i=Z.join(e,r.name),s;try{s=await Gd(i,{withFileTypes:!0})}catch{continue}for(let o of s)o.isFile()&&Kt.some(a=>o.name.toLowerCase().endsWith(a))&&(t+=1)}return t}function WP(e){let t=typeof e.exitCode=="number"?e.exitCode:1;return(e.timedOut||e.maxBufferExceeded)&&t===0?1:t}function VP(e){let t=[],n=e.match(/[^.[\]]+|\[\d+\]/g)??[];for(let r of n){if(r.startsWith("[")&&r.endsWith("]")){let i=Number.parseInt(r.slice(1,-1),10);if(!Number.isInteger(i)||i<0)return[];t.push(i);continue}t.push(r)}return t}function Jw(e,t){let n=t.trim();if(n.length===0)return{found:!1,value:void 0};let r=VP(n);if(r.length===0)return{found:!1,value:void 0};let i=e;for(let s of r){if(typeof s=="number"){if(!Array.isArray(i)||s>=i.length)return{found:!1,value:void 0};i=i[s];continue}if(typeof i!="object"||i===null||!Object.prototype.hasOwnProperty.call(i,s))return{found:!1,value:void 0};i=i[s]}return{found:!0,value:i}}function YP(e){let t=e.trim();if(t==="true")return!0;if(t==="false")return!1;if(t==="null")return null;let n=Number(t);if(t.length>0&&Number.isFinite(n))return n;if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t)}catch{}return t}function JP(e,t){return typeof e=="object"&&e!==null&&typeof t=="object"&&t!==null?mt(e,t):Object.is(e,t)}function XP(e,t,n){let r=[];r.push(...Xw("stdout",t,e.assert_stdout_contains)),r.push(...Qw("stdout",t,e.assert_stdout_regex)),r.push(...Xw("stderr",n,e.assert_stderr_contains)),r.push(...Qw("stderr",n,e.assert_stderr_regex)),r.push(...QP(t,e.assert_stdout_min_lines));let i=e.assert_json_field_equals??{},s=e.assert_json_field_gte??{};if(!(Object.keys(i).length>0||Object.keys(s).length>0))return r;let a;try{a=JSON.parse(t)}catch(c){return r.push(`stdout is not valid JSON for assert_json_field_* checks: ${c instanceof Error?c.message:String(c)}`),r}for(let[c,d]of Object.entries(i)){let l=Jw(a,c);if(!l.found){r.push(`assert_json_field_equals missing path "${c}"`);continue}let u=YP(d);JP(l.value,u)||r.push(`assert_json_field_equals mismatch at "${c}" (expected=${JSON.stringify(u)} actual=${JSON.stringify(l.value)})`)}for(let[c,d]of Object.entries(s)){let l=Jw(a,c);if(!l.found){r.push(`assert_json_field_gte missing path "${c}"`);continue}if(typeof l.value!="number"||!Number.isFinite(l.value)){r.push(`assert_json_field_gte path "${c}" resolved to non-numeric value`);continue}l.value<d&&r.push(`assert_json_field_gte failed at "${c}" (expected >= ${d}, actual ${l.value})`)}return r}function Xw(e,t,n){let r=[];for(let i of n??[])t.includes(i)||r.push(`${e} missing required text: "${i}"`);return r}function Qw(e,t,n){let r=[];for(let i of n??[])try{new RegExp(i,"m").test(t)||r.push(`${e} failed regex assertion: /${i}/m`)}catch(s){r.push(`${e} regex assertion is invalid: /${i}/ (${s instanceof Error?s.message:String(s)})`)}return r}function QP(e,t){if(typeof t!="number")return[];let n=e.split(/\r?\n/).map(r=>r.trim()).filter(r=>r.length>0).length;return n<t?[`stdout line count ${n} is below required minimum ${t}`]:[]}var ZP=[{code:"no_projects_matched_filters",regex:/\bNo projects matched the filters\b/i},{code:"no_test_files_found",regex:/\bNo test files found\b/i},{code:"no_tests_found",regex:/\bNo tests found\b/i},{code:"no_matching_tests",regex:/\bNo matching tests?\b/i},{code:"collected_zero_items",regex:/\bcollected 0 items?\b/i},{code:"reported_zero_passes",regex:/(?:^\s*(?:#|ℹ)?\s*tests\s+0\s*$[\s\S]*^\s*(?:#|ℹ)?\s*pass\s+0\s*$|^\s*(?:#|ℹ)?\s*pass\s+0\s*$[\s\S]*^\s*(?:#|ℹ)?\s*tests\s+0\s*$)/imu},{code:"reported_zero_tests",regex:/^\s*(?:#|ℹ)?\s*tests\s+0\s*$/imu}],eF=[/^\s*(?:#|ℹ)?\s*tests\s+[1-9]\d*\s*$/imu,/^\s*(?:#|ℹ)?\s*pass\s+[1-9]\d*\s*$/imu,/\bTests?\s+[1-9]\d*\s+passed\b/iu,/\b[1-9]\d*\s+passed\b/iu,/\bTests:\s+(?:.*\b)?[1-9]\d*\s+passed\b/iu];function tF(e,t){let n=`${e}
|
|
34
|
-
${t}`;for(let r of ZP)if(r.regex.test(n))return{code:r.code};return null}function nF(e,t){let n=`${e}
|
|
35
|
-
${t}`;return eF.some(r=>r.test(n))}function Zw(e){let t=ei(e);return/(?:^|\s)(?:--test-name-pattern|--testnamepattern)(?:=|\s)/u.test(t)?!0:Zt(t).some(n=>/(?:^|\s)-t(?:=|\s)/u.test(n)&&Wd(n))}function rF(e){return{root:e,schemaProjectPmPath:Z.join(e,"schema","project",".agents","pm"),schemaGlobalPmPath:Z.join(e,"schema","global"),trackerProjectPmPath:Z.join(e,"tracker","project",".agents","pm"),trackerGlobalPmPath:Z.join(e,"tracker","global"),workspaceSnapshotRoot:Z.join(e,"workspace","project"),workspaceIsolatedRoot:Z.join(e,"workspace","isolated")}}function iF(e,t,n){return e.some(r=>ab(r,t,n)==="snapshot")}async function sF(e,t){let n=new Set([".agents",".git",".nyc_output",".turbo","coverage","node_modules"]);await Do(Z.dirname(e.workspaceSnapshotRoot),{recursive:!0}),await Ud(t,e.workspaceSnapshotRoot,{recursive:!0,force:!0,filter(i){let s=Z.relative(t,i);return s?!s.split(Z.sep).some(o=>n.has(o)):!0}});let r=Z.join(t,"node_modules");await V(r)&&await sb(r,Z.join(e.workspaceSnapshotRoot,"node_modules"),process.platform==="win32"?"junction":"dir")}async function oF(e,t){let n=Z.join(e,".agents"),r=Z.join(n,"pm");await Do(n,{recursive:!0}),await Zr(r,{recursive:!0,force:!0}),await sb(t,r,process.platform==="win32"?"junction":"dir")}async function aF(e,t=Sa,n=!0){let r={defaults:!0,agentGuidance:"skip"};await t(void 0,{path:e.schemaProjectPmPath},r),await t(void 0,{path:e.schemaGlobalPmPath},r),n&&(await t(void 0,{path:e.trackerProjectPmPath},r),await t(void 0,{path:e.trackerGlobalPmPath},r))}async function cF(e,t,n){t&&(await Ww(e.schemaProjectPmPath,e.schemaGlobalPmPath,t),n&&(await Ww(e.trackerProjectPmPath,e.trackerGlobalPmPath,t),await Vw(t.projectPmRoot,e.trackerProjectPmPath),await Vw(t.globalPmRoot,e.trackerGlobalPmPath),await Yw(t.projectPmRoot,e.trackerProjectPmPath),await Yw(t.globalPmRoot,e.trackerGlobalPmPath)))}function dF(e,t,n){return e.some(r=>{let i=r.command??"",s=i.length>0&&lb(i),o=n?.autoPmContext===!0&&s?"auto":cb(r,t,n?.overrideLinkedPmContext===!0);return db(o,s)==="tracker"})}async function lF(e,t){return{sourceProjectItemCount:t?await Qn(t.projectPmRoot):0,sourceGlobalItemCount:t?await Qn(t.globalPmRoot):0,schemaProjectItemCount:await Qn(e.schemaProjectPmPath),schemaGlobalItemCount:await Qn(e.schemaGlobalPmPath),trackerProjectItemCount:await Qn(e.trackerProjectPmPath),trackerGlobalItemCount:await Qn(e.trackerGlobalPmPath)}}function uF(e){let t=e.effectivePmContextMode==="tracker",n=t?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath,r=t?e.layout.trackerGlobalPmPath:e.layout.schemaGlobalPmPath,i=t?e.counts.trackerProjectItemCount:e.counts.schemaProjectItemCount,s=t?e.counts.trackerGlobalItemCount:e.counts.schemaGlobalItemCount,o=e.workspaceContextMode==="snapshot"?e.layout.workspaceSnapshotRoot:e.workspaceContextMode==="isolated"?e.layout.workspaceIsolatedRoot:e.sourceWorkspaceRoot,a=e.workspaceContextMode==="isolated"?"":o;return{requested_pm_context_mode:e.requestedPmContextMode,pm_context_mode:e.effectivePmContextMode,auto_pm_context_applied:e.autoPmContextApplied,is_pm_command:e.isPmCommand,is_pm_tracker_read_command:e.isPmTrackerReadCommand,source_project_pm_path:e.sourceRoots?.projectPmRoot??"",sandbox_project_pm_path:n,source_global_pm_path:e.sourceRoots?.globalPmRoot??"",sandbox_global_pm_path:r,source_project_item_count:e.counts.sourceProjectItemCount,sandbox_project_item_count:i,source_global_item_count:e.counts.sourceGlobalItemCount,sandbox_global_item_count:s,mismatch_detected:e.isPmCommand&&(e.counts.sourceProjectItemCount!==i||e.counts.sourceGlobalItemCount!==s),project_extensions_seeded:!!e.sourceRoots,global_extensions_seeded:!!e.sourceRoots,requested_workspace_context_mode:e.requestedWorkspaceContextMode,workspace_context_mode:e.workspaceContextMode,working_directory:o,source_workspace_root:a,trust:e.trust}}async function mF(e){let t=typeof e.linkedTest.pm_context_mode=="string"&&e.linkedTest.pm_context_mode.trim().length>0?Lo(e.linkedTest.pm_context_mode):void 0,n=typeof e.linkedTest.command=="string"&&e.linkedTest.command.length>0?e.linkedTest.command:void 0,r=n?bP(n):!1,i=r&&n?lb(n):!1,s=e.options?.autoPmContext===!0&&i,o=s?"auto":cb(e.linkedTest,e.runLevelPmContextMode,e.options?.overrideLinkedPmContext===!0),a=db(o,i),c=a==="tracker"?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath;e.workspaceContextMode==="snapshot"&&await oF(e.layout.workspaceSnapshotRoot,c);let d=e.options?.pmRoot?await Mc(e.options.pmRoot,e.linkedTest,e.currentSourceRef):await Mc(e.layout.root,e.linkedTest,e.currentSourceRef);return{linkedOverridePmContextMode:t,executionContext:uF({layout:e.layout,counts:e.counts,sourceRoots:e.sourceRoots,isPmCommand:r,isPmTrackerReadCommand:i,requestedPmContextMode:o,effectivePmContextMode:a,autoPmContextApplied:s,requestedWorkspaceContextMode:e.requestedWorkspaceContextMode,workspaceContextMode:e.workspaceContextMode,sourceWorkspaceRoot:e.sourceWorkspaceRoot,trust:d})}}function eb(e,t,n){return{command:e.command,path:e.path,status:"skipped",execution_context:t,error:n}}function zd(e,t,n,r){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"assertion_failure",execution_context:t,...r?{stdout:r.stdout,stderr:r.stderr}:{},error:n}}function fF(e,t,n){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"trust_refusal",execution_context:t,error:n}}function _F(e){if(e.executionContext.trust.trusted)return null;let t=e.options?.allowUntrustedLinkedTests===!0,n=e.options?.untrustedLinkedTestsPolicyEnabled===!0;if(t&&n)return null;let r=n?"Retry with --allow-untrusted-linked-tests for this invocation, or acknowledge the current commands with --acknowledge-linked-tests.":"Set testing.allow_untrusted_linked_tests=true, then retry with --allow-untrusted-linked-tests; alternatively acknowledge the current commands with --acknowledge-linked-tests.";return fF(e.linkedTest,e.executionContext,`Linked test command is not trusted by this clone (source_ref=${e.executionContext.trust.source_ref??"unknown"}, current_ref=${e.executionContext.trust.current_source_ref??"unknown"}). ${r}`)}function pF(e){if(!e.linkedTest.command)return eb(e.linkedTest,e.executionContext,"No command configured for this linked test.");let t=xP(e.linkedTest.command);return t?eb(e.linkedTest,e.executionContext,t):null}function gF(e){let t=pF(e);if(t)return t;let n=_F(e);if(n)return n;let r=e.executionContext.pm_context_mode==="schema"&&e.executionContext.is_pm_tracker_read_command&&e.executionContext.mismatch_detected,i=e.options?.failOnContextMismatch===!0&&e.executionContext.is_pm_command&&e.executionContext.mismatch_detected;if(r||i){let s=yP({executionContext:e.executionContext,runLevelPmContextMode:e.runLevelPmContextMode,linkedOverridePmContextMode:e.linkedOverridePmContextMode}),o=e.options?.checkContext===!0?"Linked test preflight PM context mismatch detected":"Linked test PM context mismatch detected";return zd(e.linkedTest,e.executionContext,`${o} (source_project_items=${e.executionContext.source_project_item_count}, sandbox_project_items=${e.executionContext.sandbox_project_item_count}).${s}`)}return e.options?.requireAssertionsForPm===!0&&e.executionContext.is_pm_command&&!hP(e.linkedTest)?zd(e.linkedTest,e.executionContext,"Linked PM command requires assertions when --require-assertions-for-pm is enabled."):null}function hF(e){let t=BP(e.runtimeDirectives,e.linkedTest),n={...process.env,SENTRY_ENVIRONMENT:"test"};return Hw(n,e.runtimeDirectives),Hw(n,{env_set:e.linkedTest.env_set??{},env_clear:e.linkedTest.env_clear??[]}),t.shared_host_safe&&zP(n),n.FORCE_COLOR="0",n.PM_PATH=e.executionContext.sandbox_project_pm_path,n.PM_GLOBAL_PATH=e.executionContext.sandbox_global_pm_path,e.executionContext.workspace_context_mode==="isolated"?(delete n.PM_SOURCE_WORKSPACE_ROOT,delete n.PM_SOURCE_PM_PATH,delete n[_r]):(n.PM_SOURCE_WORKSPACE_ROOT=e.executionContext.source_workspace_root,n.PM_SOURCE_PM_PATH=e.executionContext.workspace_context_mode==="snapshot"?e.executionContext.sandbox_project_pm_path:e.executionContext.source_project_pm_path,n[_r]="read_only"),n}function yF(e,t,n){return{command:e.command,path:e.path,status:"passed",exit_code:0,execution_context:t,stdout:n.stdout,stderr:n.stderr}}function tb(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:1,failure_category:"empty_run",execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:`Linked test reported an empty test run (${e.emptyRunSignal.code}). Update the test selection so at least one test executes; unfiltered commands may opt out by omitting --fail-on-empty-test-run.`}}function vF(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:WP(e.execution),failure_category:GP(e.execution),execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:UP(e.execution,e.timeoutMs)}}function wF(e){if(e.options?.failOnEmptyTestRun===!0||Zw(e.linkedTest.command??"")){let n=tF(e.execution.stdout,e.execution.stderr);if(n)return tb({...e,emptyRunSignal:n});if(Zw(e.linkedTest.command??"")&&!nF(e.execution.stdout,e.execution.stderr))return tb({...e,emptyRunSignal:{code:"missing_positive_execution_receipt"}})}let t=XP(e.linkedTest,e.execution.stdout,e.execution.stderr);return t.length>0?zd(e.linkedTest,e.executionContext,`Linked test assertion(s) failed: ${t.join("; ")}`,e.execution):yF(e.linkedTest,e.executionContext,e.execution)}async function bF(e){let t=e.linkedTest.command??"",n=(e.linkedTest.timeout_seconds??e.defaultTimeoutSeconds??120)*1e3,r=await jP(t,n,hF(e),{index:e.index+1,total:e.total,timeoutMs:n,command:t},e.progressMode,e.executionContext.working_directory);return r.exitCode===0&&!r.timedOut&&!r.maxBufferExceeded?wF({...e,execution:r}):vF({...e,execution:r,timeoutMs:n})}async function Vd(e,t,n){let r=[],i=await ib(Z.join(ob(),"pm-linked-test-")),s=rF(i),o=Lo(n?.pmContext),a=gP(n?.workspaceContext),c=n?.progress===!0?"always":"auto",d=HP(n?.envSet,n?.envClear,n?.sharedHostSafe),l=n?.sourceRoots,u=Pr(),m=dF(e,o,n),g=iF(e,a,n?.overrideLinkedWorkspaceContext===!0),p=await Mr(u);try{await aF(s,Sa,m),await Do(s.workspaceIsolatedRoot,{recursive:!0}),await cF(s,l,m),g&&await sF(s,u);let h=await lF(s,l);for(let y=0;y<e.length;y+=1){let v=e[y],w=ab(v,a,n?.overrideLinkedWorkspaceContext===!0),E=await mF({linkedTest:v,layout:s,counts:h,sourceRoots:l,runLevelPmContextMode:o,options:n,requestedWorkspaceContextMode:a,workspaceContextMode:w,currentSourceRef:p,sourceWorkspaceRoot:u}),S=gF({linkedTest:v,executionContext:E.executionContext,runLevelPmContextMode:o,linkedOverridePmContextMode:E.linkedOverridePmContextMode,options:n});if(S){r.push(S);continue}r.push(await bF({linkedTest:v,index:y,total:e.length,defaultTimeoutSeconds:t,runtimeDirectives:d,progressMode:c,executionContext:E.executionContext,options:n}))}}finally{await Zr(s.root,{recursive:!0,force:!0,maxRetries:3,retryDelay:100})}return r}async function kF(e){let{id:t,pmRoot:n,settings:r,typeToFolder:i}=e,s=await X(n,t,r.id_prefix,r.item_format,i);if(!s)throw new _(`Item ${t} not found`,f.NOT_FOUND);let o=await ge(s,{schema:r.schema});return{itemId:s.id,tests:o.document.metadata.tests??[],testRuns:o.document.metadata.test_runs??[],changed:!1,removed:0}}function EF(e,t){return e.command===t.command&&e.path===t.path&&e.scope===t.scope&&e.pm_context_mode===t.pm_context_mode&&e.workspace_context_mode===t.workspace_context_mode}function SF(e,t){let n=[...e];for(let r of t)n.some(i=>EF(i,r))||n.push(r);return n}function xF(e,t,n){if(t.length===0&&n.length===0)return{tests:e,removed:0};let r=new Set(n),i=e.filter((s,o)=>r.has(o+1)?!1:!t.some(a=>a.kind==="command"?s.command===a.value:a.kind==="path"?s.path===a.value:s.command===a.value||s.path===a.value));return{tests:i,removed:e.length-i.length}}function TF(e,t,n,r){return xF(SF(e,t),n,r)}function IF(e){return[(e.envSet?.length??0)>0,(e.envClear?.length??0)>0,e.sharedHostSafe===!0,e.pmContext!==void 0,e.overrideLinkedPmContext===!0,e.failOnContextMismatch===!0,e.failOnSkipped===!0,e.failOnEmptyTestRun===!0,e.requireAssertionsForPm===!0,e.checkContext===!0,e.autoPmContext===!0,e.workspaceContext!==void 0,e.overrideLinkedWorkspaceContext===!0,e.allowUntrustedLinkedTests===!0].some(Boolean)}function AF(e){if(IF(e)&&e.run!==!0)throw new _("--env-set, --env-clear, --shared-host-safe, --pm-context, --override-linked-pm-context, --workspace-context, --override-linked-workspace-context, --allow-untrusted-linked-tests, --fail-on-context-mismatch, --fail-on-skipped, --fail-on-empty-test-run, --require-assertions-for-pm, --check-context, and --auto-pm-context require --run",f.USAGE);if(e.acknowledgeLinkedTests===!0&&e.run===!0)throw new _("--acknowledge-linked-tests records trust without executing commands; run it separately before --run",f.USAGE);if((e.match!==void 0||e.onlyIndex!==void 0||e.onlyLast===!0)&&e.run!==!0)throw new _("--match, --only-index, and --only-last require --run",f.USAGE)}async function CF(e){let{id:t,options:n,pmRoot:r,settings:i,typeToFolder:s,adds:o,removes:a,removeIndexes:c}=e;if(o.length===0&&a.length===0&&c.length===0)return kF({id:t,pmRoot:r,settings:i,typeToFolder:s});let d=0,l=await me({pmRoot:r,settings:i,id:t,op:o.length>0?"tests_add":"tests_remove",author:q(n.author,i.author_default),message:n.message,force:n.force,skipNoop:!0,mutate(u){let m=u.metadata.tests??[],g=TF(m,o,a,c);if(d=g.removed,(a.length>0||c.length>0)&&d===0)throw new _("No linked tests matched the requested removal selector",f.NOT_FOUND,{code:"linked_test_remove_no_match",unmatched:[...a.map(p=>`${p.kind}=${p.value}`),...c.map(p=>`index=${p}`)],required:"List linked tests and retry with an exact command/path or a current 1-based --remove-index.",examples:[`pm test ${t} --list`,`pm test ${t} --remove-index 1`]});return u.metadata.tests=g.tests,{changedFields:mt(m,g.tests)?[]:["tests"]}}});return{itemId:l.item.id,tests:l.item.tests??[],testRuns:l.item.test_runs??[],changed:l.changedFields.length>0,removed:d}}function RF(e,t){AF(e);let n={match:e.match,onlyIndex:e.onlyIndex===void 0?void 0:$d(e.onlyIndex),onlyLast:e.onlyLast},r=e.run===!0?Uw(t,n):void 0,i=e.timeout===void 0?void 0:_e(e.timeout,"timeout");if(i!==void 0&&i<=0)throw new _("Test timeout must be a positive number",f.USAGE);return{defaultTimeoutSeconds:i,pmContextMode:Lo(e.pmContext),runSelection:r,testsToRun:r?.selected??t}}async function OF(e){let{options:t,runOptions:n,pmRoot:r}=e;return t.run!==!0?[]:await Vd(n.testsToRun,n.defaultTimeoutSeconds,{progress:t.progress,envSet:t.envSet,envClear:t.envClear,sharedHostSafe:t.sharedHostSafe,pmContext:n.pmContextMode,overrideLinkedPmContext:t.overrideLinkedPmContext,failOnContextMismatch:t.failOnContextMismatch,failOnEmptyTestRun:t.failOnEmptyTestRun,requireAssertionsForPm:t.requireAssertionsForPm,checkContext:t.checkContext,autoPmContext:t.autoPmContext,workspaceContext:t.workspaceContext,overrideLinkedWorkspaceContext:t.overrideLinkedWorkspaceContext,pmRoot:r,allowUntrustedLinkedTests:t.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:e.untrustedLinkedTestsPolicyEnabled,sourceRoots:{projectPmRoot:r,globalPmRoot:et(process.cwd())}})}function DF(e,t,n){let r=[];if(t&&t.selector!==null&&r.push(`linked_test_selection:${t.selector}=${t.requested};selected=${t.selected_count};skipped=${t.skipped_count};indexes=${t.selected_indexes.join(",")}`),e.run===!0&&e.checkContext===!0){let i=Hd(n);r.push(`context_preflight:checked_pm_commands=${i.checked_pm_commands};tracker_read_commands=${i.tracker_read_commands};mismatches=${i.mismatches};auto_remediated=${i.auto_remediated}`)}return r}function LF(e){let t=_P(e.runResults),n=Number.parseInt(process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim()??"",10),r=process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM?.trim(),i=T(),s=Qr(e.options.measure,i);return{run_id:fP("test"),kind:"test",status:t.failed>0||e.failOnSkippedTriggered?"failed":"passed",started_at:e.runStartedAt,finished_at:i,recorded_at:i,attempt:Number.isFinite(n)&&n>=1?n:void 0,resumed_from:r&&r.length>0?r:void 0,passed:t.passed,failed:t.failed,skipped:t.skipped,fail_on_skipped_triggered:e.failOnSkippedTriggered?!0:void 0,measurements:s.length>0?s:void 0,executions:e.runResults.filter(o=>o.command?.trim()).slice(0,32).map(o=>({command:o.command.trim(),requested_pm_context_mode:o.execution_context?.requested_pm_context_mode,pm_context_mode:o.execution_context?.pm_context_mode,workspace_context_mode:o.execution_context?.workspace_context_mode,trust_reason:o.execution_context?.trust.reason}))}}async function NF(e){let{options:t,pmRoot:n,settings:r,itemId:i,runStartedAt:s,runResults:o,failOnSkippedTriggered:a,warnings:c}=e;if(t.run!==!0||!s)return;let d=LF({options:t,runStartedAt:s,runResults:o,failOnSkippedTriggered:a});if(r.testing.record_results_to_items!==!0)return d;try{return await Ao({pmRoot:n,settings:r,itemId:i,author:q(t.author,r.author_default),message:`Track test run summary (${d.run_id})`,entry:d}),d}catch(l){return c.push(`test_result_tracking_failed:${i}:${l instanceof Error?l.message:String(l)}`),d}}function nb(e,t,n){let r;if(e.metricBelow!==void 0){let i=e.metricBelow.indexOf("="),s=e.metricBelow.slice(0,i).trim(),o=e.metricBelow.slice(i+1).trim(),a=Number(o);if(i<=0||s.length===0||o.length===0||!Number.isFinite(a))throw new _("--metric-below must use name=value",f.USAGE);r=Sw(t,s,a)}return{measurements:n?.measurements,metric_below:r,metric_diff:e.metricDiff===void 0?void 0:xw(t,e.metricDiff)}}async function MF(e,t,n){if(e.acknowledgeLinkedTests===!0)return Hg(t,n,T())}async function hb(e,t,n){let r=bn(),i=R(process.cwd(),n.path);await $(i);let s=await C(i);if((t.measure?.length??0)>0&&t.run!==!0)throw new _("--measure requires --run",f.USAGE);Qr(t.measure,"validation"),nb(t,[],void 0);let o=U(s,F()),a=await r.resolveList(t.add,"--add"),c=await r.resolveList(t.addJson,"--add-json"),d=await r.resolveList(t.remove,"--remove"),l=[...TP(a),...CP(c)],u=await Bn(l,q(t.author,s.author_default),T())??[],m=RP(d),g=OP(t.removeIndex),p=await CF({id:e,options:t,pmRoot:i,settings:s,typeToFolder:o.type_to_folder,adds:u,removes:m,removeIndexes:g}),h=RF(t,p.tests),y=await MF(t,i,p.tests),v=t.run===!0?T():void 0,w=await OF({options:t,runOptions:h,pmRoot:i,untrustedLinkedTestsPolicyEnabled:s.testing.allow_untrusted_linked_tests}),E=No(w),S=t.run===!0&&t.failOnSkipped===!0&&w.some(O=>O.status==="skipped"),x=DF(t,h.runSelection,w);y&&x.push(`linked_test_trust_acknowledged:${y.acknowledged}`);let I=await NF({options:t,pmRoot:i,settings:s,itemId:p.itemId,runStartedAt:v,runResults:w,failOnSkippedTriggered:S,warnings:x}),k=I?Fd([...p.testRuns,I]):p.testRuns,b=nb(t,k,I);return{ok:w.every(O=>O.status!=="failed")&&S!==!0,id:p.itemId,tests:p.tests,run_results:w,failure_categories:E,selection:h.runSelection?{selector:h.runSelection.selector,requested:h.runSelection.requested,selected_indexes:h.runSelection.selected_indexes,selected_count:h.runSelection.selected_count,skipped_count:h.runSelection.skipped_count}:void 0,fail_on_skipped_triggered:S?!0:void 0,warnings:x.length>0?x:void 0,changed:p.changed,count:p.tests.length,...p.removed>0?{removed:p.removed}:{},...b}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5d3405c0-14e6-51f5-97a1-355438fd0199")}catch{}})();var PF=(e,t)=>{if(e===void 0)return;let n=se(e,t);if(!n){let r=t.definitions.map(i=>i.id);throw new _(`Invalid --status value "${e}". Allowed: ${r.join(", ")}`,f.USAGE)}return n},FF=e=>{if(e===void 0)return;let t=_e(e,"timeout");if(t<=0)throw new _("timeout must be a positive number",f.USAGE);return t},yb=(e,t)=>{if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<0)throw new _(`${t} must be a non-negative integer`,f.USAGE);return n},$F=e=>e instanceof Error?e.message:String(e),jF=()=>{let e=process.env.PM_BACKGROUND_TEST_RUN_ID?.trim();return e&&e.length>0?e:`test-all-local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`},UF=e=>e.trim().replaceAll(/\s+/g," "),qF=e=>!e||Object.keys(e).length===0?"{}":JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))),GF=e=>!e||e.length===0?"[]":JSON.stringify([...e].sort((t,n)=>t.localeCompare(n))),KF=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"none"},zF=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"source"},Mo=e=>[...new Set(e??[])].sort((t,n)=>t.localeCompare(n)),vb=e=>Object.fromEntries(Object.entries(e??{}).sort(([t],[n])=>t.localeCompare(n))),BF=e=>typeof e=="number"?e:void 0,HF=e=>{let t={assert_stdout_contains:Mo(e.assert_stdout_contains),assert_stdout_regex:Mo(e.assert_stdout_regex),assert_stderr_contains:Mo(e.assert_stderr_contains),assert_stderr_regex:Mo(e.assert_stderr_regex),assert_stdout_min_lines:BF(e.assert_stdout_min_lines),assert_json_field_equals:vb(e.assert_json_field_equals),assert_json_field_gte:vb(e.assert_json_field_gte)};return JSON.stringify(t)},WF=e=>{let t=Yd(e.command);return t!==void 0?`command:${e.scope}:${UF(t)}`:`path:${e.scope}:${Yd(e.path)??""}`},wb=e=>{let t=qF(e.env_set),n=GF(e.env_clear),r=KF(e.pm_context_mode),i=zF(e.workspace_context_mode),s=e.shared_host_safe===!0?"true":"false",o=HF(e);return`${WF(e)}:${t}:${n}:${r}:${i}:${s}:${o}`},VF=(e,t)=>t===void 0?e:e===void 0||t>e?t:e,YF=e=>{let t=0,n=0,r=0;for(let i of e){if(i.status==="passed"){t+=1;continue}if(i.status==="failed"){n+=1;continue}r+=1}return{passed:t,failed:n,skipped:r}},JF=(e,t)=>{for(let[n,r]of Object.entries(t))e[n]+=r},Po=(e,t)=>{if(e.progress===!0)try{process.stderr.write(`[pm test-all] ${t}
|
|
36
|
-
`)}catch{}},XF=async(e,t,n)=>{let r=[],i=0;for(let s of e){let o=await hb(s.id,{run:!1},{...t,path:n});i+=o.tests.length,r.push({item:s,tests:o.tests})}return{itemTests:r,linkedTests:i}},QF=async e=>{let t=H(e.settings.schema),n=U(e.settings,F()),r=PF(e.options.status,t),i=yb(e.options.limit,"--limit"),s=yb(e.options.offset,"--offset")??0,a=(await Se(e.pmRoot,e.settings.item_format,n.type_to_folder,void 0,e.settings.schema)).filter(d=>r?d.status===r:!0).sort((d,l)=>d.id.localeCompare(l.id));return{filteredItems:i===void 0?a.slice(s):a.slice(s,s+i),statusFilter:r,limitFilter:i,offsetFilter:s}},ZF=e=>{let t=new Map;for(let{tests:n}of e)for(let r of n){let i=wb(r);if(!t.has(i)){t.set(i,r.timeout_seconds);continue}t.set(i,VF(t.get(i),r.timeout_seconds))}return t},e$=async(e,t)=>{let n=[],r=e.tests.map(l=>{let u=wb(l),m=t.seenTestKeys.has(u);if(!m){t.seenTestKeys.add(u);let g=t.effectiveTimeoutByKey.get(u);n.push(g===void 0?l:{...l,timeout_seconds:g})}return{test:l,key:u,duplicate:m}}),i=n.length>0?await Vd(n,t.defaultTimeoutSeconds,{progress:t.options.progress,sourceRoots:t.sourceRoots,envSet:t.options.envSet,envClear:t.options.envClear,sharedHostSafe:t.options.sharedHostSafe,pmContext:t.options.pmContext,overrideLinkedPmContext:t.options.overrideLinkedPmContext,failOnContextMismatch:t.options.failOnContextMismatch,failOnEmptyTestRun:t.options.failOnEmptyTestRun,requireAssertionsForPm:t.options.requireAssertionsForPm,checkContext:t.options.checkContext,autoPmContext:t.options.autoPmContext,workspaceContext:t.options.workspaceContext,overrideLinkedWorkspaceContext:t.options.overrideLinkedWorkspaceContext,pmRoot:t.pmRoot,allowUntrustedLinkedTests:t.options.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:t.settings.testing.allow_untrusted_linked_tests}):[],s=0,o=r.map(({test:l,key:u,duplicate:m})=>{if(!m){let g=i[s];return s+=1,g}return{command:l.command,path:l.path,status:"skipped",error:`Duplicate linked test skipped (key=${u}).`}}),a=YF(o),c=No(o),d=await r$(e,a,o,t);return{passed:a.passed,failed:a.failed,skipped:a.skipped,trackingWarnings:d,failureCategories:c,result:{ok:a.failed===0&&!(t.options.failOnSkipped===!0&&a.skipped>0),id:e.item.id,status:e.item.status,test_count:e.tests.length,passed:a.passed,failed:a.failed,skipped:a.skipped,run_results:o,failure_categories:c}}},t$=(e,t)=>[e.failed>0,t.failOnSkipped===!0&&e.skipped>0].includes(!0),n$=e=>e?!0:void 0,r$=async(e,t,n,r)=>{if(!r.trackingEnabled)return[];try{let i=t$(t,r.options);await Ao({pmRoot:r.pmRoot,settings:r.settings,itemId:e.item.id,author:r.trackingAuthor,message:`Track test-all run summary (${r.trackingRunId})`,entry:{run_id:r.trackingRunId,kind:"test-all",status:i?"failed":"passed",started_at:r.runStartedAt,finished_at:T(),recorded_at:T(),attempt:r.trackingAttempt,resumed_from:r.trackingResumedFrom,passed:t.passed,failed:t.failed,skipped:t.skipped,items:1,linked_tests:e.tests.length,fail_on_skipped_triggered:n$(r.options.failOnSkipped===!0&&t.skipped>0),executions:n.filter(s=>s.command?.trim()).slice(0,32).map(s=>({command:s.command.trim(),requested_pm_context_mode:s.execution_context?.requested_pm_context_mode,pm_context_mode:s.execution_context?.pm_context_mode,workspace_context_mode:s.execution_context?.workspace_context_mode,trust_reason:s.execution_context?.trust.reason}))}})}catch(i){return[`test_result_tracking_failed:${e.item.id}:${$F(i)}`]}return[]},i$=()=>{let e=process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim(),t=e?Number.parseInt(e,10):Number.NaN;return Number.isFinite(t)&&t>=1?t:void 0},Yd=e=>{let t=e?.trim();return t&&t.length>0?t:void 0},s$=e=>({pmRoot:e.pmRoot,settings:e.settings,options:e.options,defaultTimeoutSeconds:e.defaultTimeoutSeconds,sourceRoots:{projectPmRoot:e.pmRoot,globalPmRoot:et(process.cwd())},seenTestKeys:new Set,effectiveTimeoutByKey:ZF(e.itemTests),trackingEnabled:e.settings.testing.record_results_to_items===!0,trackingAuthor:q(e.options.author,e.settings.author_default),trackingRunId:jF(),trackingAttempt:i$(),trackingResumedFrom:Yd(process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM),runStartedAt:e.runStartedAt}),o$=(e,t,n)=>{let r={results:[],passed:0,failed:0,skipped:0,failureCategories:No([]),trackingWarnings:[]},i=e.failOnEmptyTestRun===!0&&t===0;return i&&(r.failed+=1,r.failureCategories.empty_run+=1,r.trackingWarnings.push(`empty_linked_test_selection:items=${n.length};linked_tests=0;fail_on_empty_test_run=true`)),{accumulation:r,failOnEmptyTestRunTriggered:i}},a$=async(e,t,n)=>{for(let[r,i]of e.entries()){Po(t.options,`item ${r+1}/${e.length} start id=${i.item.id} linked_tests=${i.tests.length}`);let s=await e$(i,t);JF(n.failureCategories,s.failureCategories),n.passed+=s.passed,n.failed+=s.failed,n.skipped+=s.skipped,n.trackingWarnings.push(...s.trackingWarnings),n.results.push(s.result),Po(t.options,`item ${r+1}/${e.length} end id=${i.item.id} status=${s.failed===0?"passed":"failed"} passed=${s.passed} failed=${s.failed} skipped=${s.skipped}`)}},c$=(e,t)=>{if(e.checkContext!==!0)return;let n=t.results.flatMap(i=>i.run_results),r=Hd(n);t.trackingWarnings.push(`context_preflight:checked_pm_commands=${r.checked_pm_commands};tracker_read_commands=${r.tracker_read_commands};mismatches=${r.mismatches};auto_remediated=${r.auto_remediated}`)},d$=e=>({ok:e.ok,totals:{items:e.filteredItems.length,linked_tests:e.linkedTests,passed:e.accumulation.passed,failed:e.accumulation.failed,skipped:e.accumulation.skipped,failure_categories:e.accumulation.failureCategories},failed:e.accumulation.failed,passed:e.accumulation.passed,skipped:e.accumulation.skipped,fail_on_skipped_triggered:e.failOnSkippedTriggered?!0:void 0,fail_on_empty_test_run_triggered:e.failOnEmptyTestRunTriggered?!0:void 0,warnings:e.accumulation.trackingWarnings.length>0?e.accumulation.trackingWarnings:void 0,results:e.accumulation.results}),l$=e=>[`selection items=${e.filteredItems.length}`,`linked_tests=${e.linkedTests}`,e.statusFilter===void 0?"":`status=${e.statusFilter}`,e.limitFilter===void 0?"":`limit=${e.limitFilter}`,e.offsetFilter>0?`offset=${e.offsetFilter}`:""].filter(t=>t.length>0).join(" "),u$=async(e,t)=>{let n=R(process.cwd(),t.path);await $(n);let r=await C(n),i=await QF({pmRoot:n,settings:r,options:e}),s=FF(e.timeout),o=T(),a=await XF(i.filteredItems,t,n);return Po(e,l$({...i,linkedTests:a.linkedTests})),{pmRoot:n,settings:r,filteredItems:i.filteredItems,itemTests:a.itemTests,linkedTests:a.linkedTests,defaultTimeoutSeconds:s,runStartedAt:o}},m$=e=>{let t=e.options.failOnSkipped===!0&&e.accumulation.skipped>0,n=![e.accumulation.failed>0,t,e.failOnEmptyTestRunTriggered].includes(!0);return{failOnSkippedTriggered:t,ok:n}},O9=async(e,t)=>{let n=await u$(e,t),{accumulation:r,failOnEmptyTestRunTriggered:i}=o$(e,n.linkedTests,n.filteredItems),s=s$({pmRoot:n.pmRoot,settings:n.settings,options:e,itemTests:n.itemTests,defaultTimeoutSeconds:n.defaultTimeoutSeconds,runStartedAt:n.runStartedAt});await a$(n.itemTests,s,r),c$(e,r);let o=m$({options:e,accumulation:r,failOnEmptyTestRunTriggered:i});return Po(e,`end status=${o.ok?"passed":"failed"} items=${n.filteredItems.length} linked_tests=${n.linkedTests} passed=${r.passed} failed=${r.failed} skipped=${r.skipped}`),d$({ok:o.ok,filteredItems:n.filteredItems,linkedTests:n.linkedTests,accumulation:r,failOnSkippedTriggered:o.failOnSkippedTriggered,failOnEmptyTestRunTriggered:i})};import G$ from"node:os";import er from"node:fs/promises";import{spawn as xb}from"node:child_process";import{createHash as f$,randomBytes as _$}from"node:crypto";import ti from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0224a672-e326-5555-a4b4-1fa3550d9e61")}catch{}})();var Tb=new Set(["queued","running"]),Zd=new Set(["passed","failed","stopped","canceled"]),p$=3e3,g$=3e3,h$=3e4,Ib=100,bb=100;function Ab(){return Date.now()}function Cb(e){return e.map(t=>t.trim()).filter(t=>t.length>0)}function y$(e){let t=e.join(" ").replaceAll(/\s+/g," ").trim();return t.length<=180?t:`${t.slice(0,177)}...`}function v$(){let e=Date.now().toString(36),t=_$(3).toString("hex");return`tr-${e}-${t}`}function w$(e,t,n){let r={kind:e,command:Cb(t),pm_root:ti.resolve(n)};return f$("sha256").update(JSON.stringify(r)).digest("hex")}function tr(e){if(!Number.isInteger(e)||!e||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)==="EPERM"}}async function b$(e){await We(Pl(e)),await We(Vo(e)),await We(Fl(e)),await We($l(e)),await We(ql(e))}async function Rb(e,t){try{let n=JSON.parse(e);if(!n||typeof n!="object"||typeof n.id!="string")throw new Error("invalid run record payload");return n}catch(n){throw new _(`Failed to parse background test run record at ${t}: ${n instanceof Error?n.message:String(n)}`,f.GENERIC_FAILURE)}}async function ct(e,t){let n={...t,updated_at:T()};await we(Yo(e,t.id),`${JSON.stringify(n,null,2)}
|
|
37
|
-
`)}async function nr(e,t){let n=Yo(e,t),r=await Y(n);return r?Rb(r,n):null}async function k$(e){let t=Vo(e);return await V(t)?(await er.readdir(t,{withFileTypes:!0})).filter(r=>r.isFile()&&r.name.endsWith(".json")).map(r=>ti.join(t,r.name)).sort((r,i)=>i.localeCompare(r)):[]}function E$(e){let t=e.match(/^VmRSS:\s+(\d+)\s+kB$/m);if(t)return Number.parseInt(t[1],10)*1024}async function S$(e){if(process.platform==="linux")try{let t=await er.readFile(`/proc/${e}/status`,"utf8");return E$(t)}catch{return}}function x$(e){let t=e.lastIndexOf(")");if(t<0)return{};let r=e.slice(t+2).trim().split(/\s+/),i=Number.parseInt(r[11],10),s=Number.parseInt(r[12],10);return!Number.isFinite(i)||!Number.isFinite(s)?{}:{cpu_user_seconds:i/bb,cpu_system_seconds:s/bb}}async function T$(e){if(process.platform!=="linux")return{};try{let t=await er.readFile(`/proc/${e}/stat`,"utf8");return x$(t)}catch{return{}}}async function Xd(e){let t=e.child_pid??e.worker_pid;if(!tr(t))return;let n=await S$(t),r=await T$(t),i=e.started_at?Date.parse(e.started_at):Number.NaN,s=Number.isFinite(i)?Math.max(0,(Ab()-i)/1e3):void 0;return{recorded_at:T(),rss_bytes:n,cpu_user_seconds:r.cpu_user_seconds,cpu_system_seconds:r.cpu_system_seconds,uptime_seconds:s}}function Jd(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function I$(e,t){if(!t||typeof t!="object")return{summary:{passed:0,failed:1,skipped:0},parsedResult:null};let n=t;if(e==="test-all"){let a=n.totals??{};return{summary:{items:typeof a.items=="number"?a.items:void 0,linked_tests:typeof a.linked_tests=="number"?a.linked_tests:void 0,passed:Jd(a.passed),failed:Jd(a.failed),skipped:Jd(a.skipped),fail_on_skipped_triggered:n.fail_on_skipped_triggered===!0?!0:void 0},parsedResult:t}}let r=Array.isArray(n.run_results)?n.run_results:[],i=0,s=0,o=0;for(let a of r){if(!a||typeof a!="object")continue;let c=a.status;if(c==="passed"){i+=1;continue}if(c==="failed"){s+=1;continue}o+=1}return{summary:{passed:i,failed:s,skipped:o,fail_on_skipped_triggered:n.fail_on_skipped_triggered===!0?!0:void 0},parsedResult:t}}function A$(e){let t=e.trim();if(t.length===0)return null;let n=t.match(/\[pm test-all\]\s+item\s+(\d+)\/(\d+)\s+(start|end)\s+id=([^\s]+)/i);if(n){let d=Number.parseInt(n[1],10),l=Number.parseInt(n[2],10);return{item_index:d,item_total:l,item_id:n[4],linked_test_index:void 0,linked_test_total:void 0,current_command:void 0,elapsed_ms:void 0,heartbeat_at:T(),phase:n[3]?.toLowerCase()==="end"?"finished":"running"}}let r=t.match(/\[pm test\]\s+linked-test\s+(\d+)\/(\d+)\s+(start|running|end)(?:.*elapsed_ms=(\d+))?/i);if(!r)return null;let i=Number.parseInt(r[1],10),s=Number.parseInt(r[2],10),o=r[4]?Number.parseInt(r[4],10):void 0,a=t.match(/\scommand="((?:\\.|[^"\\])*)"/),c=a?a[1].replaceAll('\\"','"').replaceAll("\\\\","\\"):void 0;return{linked_test_index:i,linked_test_total:s,current_command:c,elapsed_ms:Number.isFinite(o)?o:void 0,heartbeat_at:T(),phase:r[3]?.toLowerCase()==="end"?"finished":"running"}}function C$(e){return e.split(/\r?\n/).map(t=>t.trimEnd()).filter(t=>t.length>0)}function Qd(e,t){if(t<=0)return[];let n=C$(e);return n.length<=t?n:n.slice(n.length-t)}async function Ob(e){let t=process.env.PM_BACKGROUND_CLI_ENTRY?.trim();if(t&&t.length>0){let i=ti.resolve(e,t);if(await V(i))return i}let n=ti.resolve(e,"dist","cli.js");if(await V(n))return n;let r=process.argv[1]?.trim();if(r&&r.length>0){let i=ti.resolve(e,r);if(await V(i))return i}throw new _("Unable to resolve a CLI entrypoint for background test runs. Build the project or set PM_BACKGROUND_CLI_ENTRY.",f.GENERIC_FAILURE)}async function ni(e,t){if(!Tb.has(t.status)||tr(t.worker_pid)||t.finished_at)return t;let r={...t,status:"failed",finished_at:T(),error:t.error??"Background test run worker exited before writing terminal status."};return await ct(e,r),r}async function el(e){await b$(e.pmRoot);let t=Cb(e.commandArgs);if(t.length===0)throw new _("Background test run requires command arguments.",f.USAGE);let n=w$(e.kind,t,e.pmRoot),r=await nl(e.pmRoot,{});for(let l of r){let u=await ni(e.pmRoot,l);if(u.fingerprint===n&&!(!Tb.has(u.status)||!tr(u.worker_pid)))return{started:!1,run:{...u,duplicate_of:u.id},duplicate_of:u.id}}let i=v$(),s=T(),o=jl(e.pmRoot,i),a=Ul(e.pmRoot,i),c=Gl(e.pmRoot,i);await er.writeFile(o,"","utf8"),await er.writeFile(a,"","utf8");let d={id:i,kind:e.kind,status:"queued",created_at:s,updated_at:s,requested_by:e.requestedBy,fingerprint:n,command_args:t,command_label:y$(t),pm_root:e.pmRoot,global_pm_root:e.globalPmRoot,target_id:e.targetId,status_filter:e.statusFilter,attempt:typeof e.attempt=="number"&&Number.isFinite(e.attempt)&&e.attempt>=1?Math.floor(e.attempt):1,resumed_from:e.resumedFrom,resumed_by:e.resumedBy,stdout_path:o,stderr_path:a,result_path:c,progress:{phase:"queued",message:"Queued for background execution.",heartbeat_at:s}};return await ct(e.pmRoot,d),{started:!0,run:d}}async function tl(e){let t=await nr(e.pmRoot,e.runId);if(!t)throw new _(`Background test run ${e.runId} not found`,f.NOT_FOUND);if(Zd.has(t.status))throw new _(`Background test run ${t.id} is already terminal (${t.status}).`,f.CONFLICT);let n=await Ob(process.cwd()),r=[];e.noExtensions===!0&&r.push("--no-extensions"),r.push("--path",t.pm_root,"test-runs-worker",t.id);let i={...process.env,PM_PATH:t.pm_root,PM_GLOBAL_PATH:t.global_pm_root,PM_BACKGROUND_TEST_RUN_ID:t.id,PM_BACKGROUND_TEST_RUN_ATTEMPT:String(t.attempt),PM_BACKGROUND_TEST_RUN_RESUMED_FROM:t.resumed_from??"",FORCE_COLOR:"0"},s=xb(process.execPath,[n,...r],{cwd:process.cwd(),env:i,detached:!0,stdio:"ignore",windowsHide:!0});s.unref();let o={...t,status:"queued",worker_pid:s.pid,progress:{phase:"queued",message:"Worker process started.",heartbeat_at:T()}};return await ct(e.pmRoot,o),o}async function kb(e,t,n){await e,await er.appendFile(t,n,"utf8")}function Db(e,t){let n=Number.parseInt(process.env[e]??"",10);return Number.isFinite(n)&&n>0?n:t}function R$(e){return{...process.env,PM_PATH:e.pm_root,PM_GLOBAL_PATH:e.global_pm_root,FORCE_COLOR:"0"}}function O$(e,t){return t?["--no-extensions",...e.command_args]:[...e.command_args]}function D$(e,t){let n=Promise.resolve();return{schedule(){n=n.then(async()=>{try{await ct(e,t)}catch{}})},async flush(){await n}}}function Eb(e,t){try{e.kill(t)}catch{}}async function L$(e,t,n,r){if(n.stopRequested)return;n.stopRequested=!0,e.stop_requested_at=T(),e.progress={...e.progress,phase:"stopping",message:"Stop requested for background run.",heartbeat_at:T()},r(),Eb(t,"SIGTERM"),setTimeout(()=>Eb(t,"SIGKILL"),Db("PM_BACKGROUND_RUN_FORCE_KILL_DELAY_MS",g$)).unref?.()}function N$(e,t,n){return{phase:n,message:e,heartbeat_at:T(),item_index:t.item_index,item_total:t.item_total,item_id:t.item_id,linked_test_index:void 0,linked_test_total:void 0,current_command:void 0,elapsed_ms:void 0}}function M$(e,t,n,r){return{phase:r,message:e,heartbeat_at:T(),item_index:n.item_index??t.progress?.item_index,item_total:n.item_total??t.progress?.item_total,item_id:n.item_id??t.progress?.item_id,linked_test_index:n.linked_test_index,linked_test_total:n.linked_test_total,current_command:n.current_command,elapsed_ms:n.elapsed_ms}}function Sb(e,t,n){let r=A$(t);if(!r)return!1;let i=e.progress?.phase==="stopping"?"stopping":"running";return e.progress=r.item_id?N$(t,r,i):M$(t,e,r,i),r.phase==="finished"&&!n&&(e.progress.phase="running"),!0}function P$(e){if(e.trim().length===0)return null;try{return JSON.parse(e)}catch{return null}}function F$(e,t){return t?"stopped":e.exit_code===0&&(e.summary?.failed??0)===0&&e.summary?.fail_on_skipped_triggered!==!0?"passed":"failed"}function $$(e,t){return{phase:"finished",message:t?"Background run stopped.":`Background run finished with status=${e.status}.`,heartbeat_at:T(),item_index:e.progress?.item_index,item_total:e.progress?.item_total,item_id:e.progress?.item_id,linked_test_index:e.progress?.linked_test_index,linked_test_total:e.progress?.linked_test_total,current_command:e.progress?.current_command,elapsed_ms:e.progress?.elapsed_ms}}async function j$(e,t,n){if(t!==null){await we(e.result_path,`${JSON.stringify(t,null,2)}
|
|
38
|
-
`);return}await we(e.result_path,`${JSON.stringify({parse_error:"Background run output was not valid JSON.",stdout_excerpt:Qd(n,Ib)},null,2)}
|
|
39
|
-
`)}async function Lb(e,t,n=!1){let r=await nr(e,t);if(!r)throw new _(`Background test run ${t} not found`,f.NOT_FOUND);let i={...r,status:"running",started_at:r.started_at??T(),worker_pid:process.pid,progress:{phase:"running",message:"Worker started.",heartbeat_at:T()}},s=await Ob(process.cwd()),o=R$(i);await ct(e,i);let a=O$(i,n),c=xb(process.execPath,[s,...a],{cwd:process.cwd(),env:o,detached:!1,stdio:["ignore","pipe","pipe"],windowsHide:!0});i.child_pid=c.pid;let d=D$(e,i),l=d.schedule,u=Promise.resolve(),m=Promise.resolve(),g="",p="",h={stopRequested:!1},y=()=>{L$(i,c,h,l)};process.on("SIGTERM",y),process.on("SIGINT",y);let v=setInterval(()=>{(async()=>(i.resource=await Xd(i),i.progress.heartbeat_at=T(),l()))()},Db("PM_BACKGROUND_RUN_RESOURCE_INTERVAL_MS",p$));v.unref?.(),c.stdout?.on("data",k=>{let b=k.toString("utf8");g+=b,u=kb(u,i.stdout_path,b)}),c.stderr?.on("data",k=>{let b=k.toString("utf8");m=kb(m,i.stderr_path,b),p+=b;let O=p.split(/\r?\n/);p=O.pop();let W=!1;for(let P of O){let A=P.trimEnd();A.length>0&&Sb(i,A,h.stopRequested)&&(W=!0)}W&&l()});let w=null,E=null;try{({code:w,signal:E}=await new Promise(k=>{c.on("close",(b,O)=>{k({code:b,signal:O})})}))}finally{clearInterval(v),process.off("SIGTERM",y),process.off("SIGINT",y)}await u,await m;let S=p.trimEnd();S.length>0&&Sb(i,S,h.stopRequested)&&l(),p="";let x=P$(g),I=I$(i.kind,x);return i.summary=I.summary,i.exit_code=typeof w=="number"?w:void 0,i.signal=E??void 0,i.finished_at=T(),i.status=F$(i,h.stopRequested),i.progress=$$(i,h.stopRequested),i.resource=await Xd(i),await j$(i,x,g),await ct(e,i),await d.flush(),i}async function nl(e,t){let n=await k$(e),r=[];for(let c of n){let d=await Y(c);if(!d)continue;let l=await Rb(d,c);r.push(l)}let i=[];for(let c of r)i.push(await ni(e,c));let o=(t.status?i.filter(c=>c.status===t.status):i).sort((c,d)=>{let l=Date.parse(d.updated_at)-Date.parse(c.updated_at);return Number.isFinite(l)&&l!==0?l:d.id.localeCompare(c.id)}),a=typeof t.limit=="number"&&t.limit>=0?t.limit:void 0;return a===void 0?o:o.slice(0,a)}async function Nb(e,t){let n=await nr(e,t);if(!n)throw new _(`Background test run ${t} not found`,f.NOT_FOUND);let r=await ni(e,n),i=tr(r.worker_pid),s=tr(r.child_pid);r.status==="running"&&!s&&!r.finished_at&&!i&&(r.status="failed",r.finished_at=T(),r.error=r.error??"Background run process exited unexpectedly.",await ct(e,r)),r.status==="running"&&(r.resource=await Xd(r),await ct(e,r));let o=r.progress?.heartbeat_at,a=o?Date.parse(o):Number.NaN,c=Number.isFinite(a)?Math.max(0,Ab()-a):void 0,d=Number.parseInt(process.env.PM_BACKGROUND_RUN_HEARTBEAT_STALE_MS??"",10),l=Number.isFinite(d)&&d>0?d:h$,u=r.status==="running"?c!==void 0&&c>l?"stale":"healthy":"inactive";return{run:r,health:{state:u,last_heartbeat_at:o,heartbeat_lag_ms:c,worker_alive:i,child_alive:s}}}function U$(e,t){let n=t?"SIGKILL":"SIGTERM";if(!tr(e.worker_pid)||!e.worker_pid)return"none";try{return process.kill(e.worker_pid,n),n}catch{return"none"}}function q$(e,t){return{phase:"stopping",message:t==="none"?"Run marked stopped.":`Stop requested via ${t}.`,heartbeat_at:T(),item_index:e.progress?.item_index,item_total:e.progress?.item_total,item_id:e.progress?.item_id,linked_test_index:e.progress?.linked_test_index,linked_test_total:e.progress?.linked_test_total,current_command:e.progress?.current_command,elapsed_ms:e.progress?.elapsed_ms}}async function Mb(e,t,n=!1){let r=await nr(e,t);if(!r)throw new _(`Background test run ${t} not found`,f.NOT_FOUND);let i=await ni(e,r);if(Zd.has(i.status))return{run:i,signal_sent:"none"};let s=U$(i,n);return s==="none"&&(i.status="stopped",i.finished_at=i.finished_at??T()),i.stop_requested_at=T(),i.progress=q$(i,s),await ct(e,i),{run:i,signal_sent:s}}async function Pb(e,t,n,r=!1){let i=await nr(e,t);if(!i)throw new _(`Background test run ${t} not found`,f.NOT_FOUND);let s=await ni(e,i);if(!Zd.has(s.status))throw new _(`Background test run ${t} is not terminal and cannot be resumed.`,f.CONFLICT);let o=await el({pmRoot:s.pm_root,globalPmRoot:s.global_pm_root,kind:s.kind,commandArgs:s.command_args,requestedBy:n,targetId:s.target_id,statusFilter:s.status_filter,resumedFrom:s.id,resumedBy:n,attempt:s.attempt+1});if(!o.started)return o.run;let a=await tl({pmRoot:e,runId:o.run.id,noExtensions:r}),c={...s,resumed_by:a.id};return await ct(e,c),a}async function Fb(e,t,n,r){let i=await nr(e,t);if(!i)throw new _(`Background test run ${t} not found`,f.NOT_FOUND);let s=typeof r=="number"&&Number.isFinite(r)&&r>=0?Math.floor(r):Ib,o=n==="stdout"||n==="both"?await Y(i.stdout_path)??"":"",a=n==="stderr"||n==="both"?await Y(i.stderr_path)??"":"";return{run:i,stream:n,tail:s,stdout:n==="stdout"||n==="both"?Qd(o,s):[],stderr:n==="stderr"||n==="both"?Qd(a,s):[]}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1cbb3565-26d8-5657-b724-602658bec852")}catch{}})();var K$=["queued","running","passed","failed","stopped","canceled"],z$=["stdout","stderr","both"];function B$(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(K$.includes(t))return t;throw new _(`Invalid --status value "${e}"`,f.USAGE)}function H$(e){if(e===void 0||e.trim().length===0)return"stderr";let t=e.trim().toLowerCase();if(z$.includes(t))return t;throw new _(`Invalid --stream value "${e}"`,f.USAGE)}function W$(){try{let e=G$.userInfo().username.trim();if(e.length>0)return e}catch{}}function $b(e,t){let n=[e,lu(),t,process.env.USER,process.env.LOGNAME,process.env.USERNAME,W$()];for(let r of n){if(typeof r!="string")continue;let i=r.trim();if(i.length>0)return i}return"unknown"}async function fn(e){await $(e)}async function Q9(e,t){let n=R(process.cwd(),t.path),r=et(process.cwd());await fn(n);let i=await C(n),s=$b(e.author,i.author_default),o=await el({pmRoot:n,globalPmRoot:r,kind:e.kind,commandArgs:e.commandArgs,requestedBy:s,targetId:e.targetId,statusFilter:e.statusFilter});return o.started?{started:!0,run:await tl({pmRoot:n,runId:o.run.id,noExtensions:e.noExtensions===!0})}:{started:!1,duplicate_of:o.duplicate_of,run:o.run}}async function Z9(e,t){let n=R(process.cwd(),t.path);await fn(n);let r=B$(e.status),i=lr(e.limit,"limit"),s=await nl(n,{status:r,limit:i});return{runs:s,count:s.length,filters:{status:r,limit:i}}}async function e4(e,t){let n=R(process.cwd(),t.path);await fn(n);let r=await Nb(n,e);return{run:r.run,health:r.health}}async function t4(e,t,n){let r=R(process.cwd(),n.path);await fn(r);let i=H$(t.stream),s=lr(t.tail,"tail"),o=await Fb(r,e,i,s);return{run:o.run,stream:o.stream,tail:o.tail,stdout:o.stdout,stderr:o.stderr}}async function n4(e,t,n){let r=R(process.cwd(),n.path);await fn(r);let i=await Mb(r,e,t.force===!0);return{run:i.run,signal_sent:i.signal_sent}}async function r4(e,t,n){let r=R(process.cwd(),n.path);await fn(r);let i=await C(r),s=$b(t.author,i.author_default),o=await Pb(r,e,s,t.noExtensions===!0);return{resumed_from:e,run:o}}async function i4(e,t){let n=R(process.cwd(),t.path);await fn(n);let r=await Lb(n,e,t.noExtensions===!0);return{id:r.id,status:r.status,exit_code:r.exit_code}}export{N as a,Pe as b,nt as c,Dn as d,R_ as e,D_ as f,pt as g,gr as h,Ik as i,Ia as j,Aa as k,P_ as l,Nn as m,yr as n,Ra as o,Hk as p,G_ as q,vr as r,Oa as s,ts as t,Da as u,z_ as v,B_ as w,H_ as x,wr as y,rs as z,V_ as A,Y_ as B,J_ as C,X_ as D,tp as E,bj as F,L as G,ie as H,kj as I,Mn as J,Fa as K,Ej as L,Sj as M,sp as N,xj as O,Tj as P,Ij as Q,cE as R,Aj as S,Cj as T,$a as U,Rj as V,Oj as W,Pa as X,Dj as Y,Lj as Z,ap as _,Nj as $,lE as aa,lp as ba,zj as ca,Er as da,Bj as ea,hE as fa,yE as ga,Hj as ha,vE as ia,_p as ja,pp as ka,yp as la,TE as ma,Pn as na,J as oa,Mt as pa,oU as qa,aU as ra,CE as sa,OE as ta,cU as ua,dU as va,wU as wa,xp as xa,nc as ya,jU as za,st as Aa,kS as Ba,UU as Ca,qU as Da,GU as Ea,SS as Fa,TS as Ga,IS as Ha,AS as Ia,jp as Ja,Up as Ka,qp as La,KS as Ma,oc as Na,X1 as Oa,Q1 as Pa,_s as Qa,ps as Ra,wg as Sa,aG as Ta,Eg as Ua,xg as Va,Ig as Wa,jT as Xa,UT as Ya,qT as Za,GT as _a,Or as $a,KT as ab,wt as bb,zT as cb,BT as db,HT as eb,Ec as fb,Sc as gb,WT as hb,ws as ib,bs as jb,Ag as kb,zG as lb,Dg as mb,Ng as nb,cK as ob,dK as pb,Cc as qb,Mr as rb,Pr as sb,DI as tb,Bn as ub,Kg as vb,Mc as wb,Bg as xb,Hg as yb,iA as zb,Cz as Ab,zh as Bb,jr as Cb,Wh as Db,Vh as Eb,Yh as Fb,Xc as Gb,_C as Hb,lB as Ib,TB as Jb,gC as Kb,nn as Lb,IB as Mb,hC as Nb,ey as Ob,AB as Pb,Ur as Qb,CB as Rb,ty as Sb,ry as Tb,EC as Ub,SC as Vb,UB as Wb,qB as Xb,BB as Yb,IC as Zb,oy as _b,Zc as $b,ay as ac,GC as bc,ly as cc,ed as dc,fy as ec,zC as fc,rH as gc,iH as hc,_y as ic,sH as jc,oH as kc,co as lc,js as mc,wy as nc,AH as oc,sR as pc,oR as qc,Sy as rc,rd as sc,on as tc,zs as uc,sn as vc,Ty as wc,qr as xc,Gr as yc,Bs as zc,Hs as Ac,an as Bc,cn as Cc,Wn as Dc,Ws as Ec,Vs as Fc,Ys as Gc,Ay as Hc,wR as Ic,id as Jc,pd as Kc,Z0 as Lc,hO as Mc,vO as Nc,oD as Oc,lV as Pc,mv as Qc,LV as Rc,FV as Sc,$V as Tc,jV as Uc,wv as Vc,t2 as Wc,OD as Xc,Id as Yc,DD as Zc,LD as _c,ND as $c,n2 as ad,r2 as bd,g2 as cd,h2 as dd,y2 as ed,b2 as fd,VD as gd,Ov as hd,E2 as id,ZD as jd,Xn as kd,eL as ld,T2 as md,I2 as nd,Nv as od,A2 as pd,C2 as qd,R2 as rd,iL as sd,O2 as td,D2 as ud,L2 as vd,N2 as wd,aL as xd,$v as yd,P2 as zd,Fv as Ad,qv as Bd,fL as Cd,Vr as Dd,yL as Ed,Kv as Fd,bL as Gd,B2 as Hd,f5 as Id,hw as Jd,yw as Kd,YN as Ld,vw as Md,M5 as Nd,ww as Od,P5 as Pd,F5 as Qd,So as Rd,mM as Sd,z5 as Td,Ld as Ud,B5 as Vd,Nd as Wd,fM as Xd,Qr as Yd,Sw as Zd,xw as _d,_8 as $d,y8 as ae,Aw as be,R8 as ce,Hd as de,f9 as ee,GP as fe,No as ge,WP as he,Vd as ie,hb as je,O9 as ke,Q9 as le,Z9 as me,e4 as ne,t4 as oe,n4 as pe,r4 as qe,i4 as re};
|
|
40
|
-
//# sourceMappingURL=chunk-WGAOYSYH.js.map
|