@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,77 +0,0 @@
|
|
|
1
|
-
import{$a as ur,Ae as Er,Ai as le,B as Xt,Bd as A,C as g,Cd as Y,Dd as xr,E as h,Ed as K,Fc as H,Fd as ne,Fe as V,Ge as Q,H as ir,Hb as mr,Hd as Sr,Hf as Ir,Ib as fr,Id as tt,Ji as ae,Kd as xt,Mi as O,Ni as Se,Oa as cr,Oc as W,Pa as dr,Qa as B,Qb as hr,R as I,Rb as gr,Se as $r,Tb as yr,Te as St,Ti as Pr,Vh as tn,Ya as D,Yh as Ge,Za as lr,Zi as Nr,_a as pr,ai as xe,c as x,ca as ar,cj as ze,d as _t,dj as Dr,e as oe,ea as sr,ej as jr,f as q,fa as te,g as he,hc as en,hj as Ce,i as nr,ic as _r,ja as de,jc as wr,kc as bt,l as wt,mc as be,mk as Lr,nj as nn,oc as ke,pa as vt,pn as Et,qa as Qt,qb as Me,ra as Zt,rc as vr,s as rr,si as Tr,tc as kt,ti as Oe,uc as br,ui as nt,vc as kr,vi as Or,w as Yt,wi as Cr,xi as ie,y as or,yf as Ar,yi as Ue,zi as Rr}from"./chunk-QUWFABDM.js";import{mkdir as cs,readFile as ds}from"node:fs/promises";import Jr 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]="6ed4a26f-2ae2-556a-87db-56844108757f")}catch{}})();var rn=class extends Error{constructor(t="Workspace transaction interrupted"){super(t),this.name="WorkspaceTransactionInterruptedError"}},ls="sdk-workspace-transaction",ps=/^[a-zA-Z0-9._-]+$/,us=30,ms=3e3;function Fr(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n||!ps.test(n))throw new TypeError(`${t} must match [a-zA-Z0-9._-]+`);return n}function Mr(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n)throw new TypeError(`${t} must be non-empty`);return n}function Gr(e,t,n){let r=e??t;if(!Number.isInteger(r)||r<=0)throw new TypeError(`${n} must be a positive integer`);return r}function qr(e,t){return Jr.join(e,"transactions","sdk",`${t}.json`)}async function Ee(e,t){t.updatedAt=I();let n=qr(e,t.transactionId);await cs(Jr.dirname(n),{recursive:!0}),await he(n,`${JSON.stringify(t,null,2)}
|
|
2
|
-
`)}function fs(e){return Number.isInteger(e.attempt)&&typeof e.author=="string"&&typeof e.createdAt=="string"&&typeof e.updatedAt=="string"}function Re(e){return Object.assign(Object.create(null),e)}function hs(e,t){try{let n=JSON.stringify(e,(r,o)=>{if(typeof o=="number"&&!Number.isFinite(o))throw new TypeError(`${t} contains a non-finite number`);if(o===void 0||typeof o=="function"||typeof o=="symbol")throw new TypeError(`${t} contains a non-JSON value`);return o});return JSON.parse(n)}catch(n){throw new TypeError(`${t} must be JSON serializable`,{cause:n})}}function on(e,t){return e===void 0?void 0:hs(e,t)}function an(e,t,n,r){let o=on(n,r);o===void 0?delete e[t]:e[t]=o}function Ur(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function zr(e,t){return Array.isArray(e)&&new Set(e).size===e.length&&e.every(n=>typeof n=="string"&&t.includes(n))}function gs(e,t){if(!zr(e.startedStepIds,t)||!zr(e.completedStepIds,t)||!Ur(e.results)||!Ur(e.compensationData))return!1;let n=e.startedStepIds,r=new Set(n),o=e.completedStepIds,i=new Set(o);return Object.keys(e.compensationData).some(a=>!r.has(a))||Object.keys(e.results).some(a=>!i.has(a))?!1:e.status==="committed"?t.every(a=>i.has(a)):e.status!=="compensated"||i.size===0&&r.size===0}function ys(e,t,n){let r;try{r=JSON.parse(e)}catch{throw new TypeError(`Workspace transaction ${t} journal is invalid JSON`)}if(!r||typeof r!="object"||Array.isArray(r))throw new TypeError(`Workspace transaction ${t} journal is invalid`);let o=r,i=o.schemaVersion===1&&o.transactionId===t,a=Array.isArray(o.stepIds)&&o.stepIds.length===n.length&&o.stepIds.every((l,p)=>l===n[p]),s=gs(o,n),c=fs(o),d=["applying","compensating","compensated","committed"].includes(String(o.status));if(!i||!a||!s||!c||!d)throw new TypeError(`Workspace transaction ${t} journal does not match the supplied plan`);return{...o,results:Re(o.results),compensationData:Re(o.compensationData)}}async function _s(e,t,n,r,o){let i=o,a=i!==void 0;if(i?.status==="compensating"&&await Br(e,i),i===void 0||i.status==="compensated"){let s=I();i={schemaVersion:1,transactionId:t,author:n,status:"applying",attempt:(i?.attempt??0)+1,createdAt:i?.createdAt??s,updatedAt:s,stepIds:r,startedStepIds:[],completedStepIds:[],results:Re(),compensationData:Re()},await Ee(e.pmRoot,i),await ge(e,i,"prepared")}return{journal:i,recovered:a}}async function ws(e,t,n){try{await bs(t,e.steps),await Ee(e.pmRoot,t);let r=new Set(t.completedStepIds),o=new Set(t.startedStepIds);for(let i of e.steps){if(r.has(i.id))continue;let a=await i.inspect(),s=on(a.result,`Step ${i.id} result`);if(a.state!=="applied"){let c=await i.prepareCompensation?.();an(t.compensationData,i.id,c,`Step ${i.id} compensation data`),o.add(i.id),t.startedStepIds=e.steps.map(l=>l.id).filter(l=>o.has(l)),await Ee(e.pmRoot,t);let d=await i.apply();s=on(d,`Step ${i.id} result`)}await ge(e,t,"step_applied",i.id),r.add(i.id),t.completedStepIds=e.steps.map(c=>c.id).filter(c=>r.has(c)),an(t.results,i.id,s,`Step ${i.id} result`),await Ee(e.pmRoot,t),await ge(e,t,"step_recorded",i.id)}return await ge(e,t,"committing"),t.status="committed",await Ee(e.pmRoot,t),await ge(e,t,"committed"),{transactionId:t.transactionId,status:"committed",recovered:n,results:Re(t.results)}}catch(r){if(r instanceof rn||t.status==="committed")throw r;try{await Br(e,t)}catch(o){throw new AggregateError([r,o],`Workspace transaction failed and compensation failed: ${String(o)}`,{cause:o})}throw r}}async function vs(e,t,n){try{return ys(await ds(qr(e,t),"utf8"),t,n)}catch(r){if(r!==null&&typeof r=="object"&&"code"in r&&oe(r))return;throw r}}async function ge(e,t,n,r){await e.onTransition?.({transactionId:t.transactionId,attempt:t.attempt,transition:n,...r===void 0?{}:{stepId:r}})}async function bs(e,t){let n=new Set,r=Re();for(let o of t){let i=await o.inspect();i.state==="applied"&&(n.add(o.id),an(r,o.id,i.result,`Step ${o.id} result`))}e.results=r,e.completedStepIds=t.map(o=>o.id).filter(o=>n.has(o))}async function Br(e,t){t.status="compensating",await Ee(e.pmRoot,t),await ge(e,t,"compensating");let n=new Set(t.completedStepIds),r=new Set(t.startedStepIds);for(let o of[...e.steps].reverse()){if(!r.has(o.id)&&!n.has(o.id))continue;let i;try{i=r.has(o.id)&&(await o.inspect()).state==="applied"}catch{i=r.has(o.id)}i&&(await ge(e,t,"step_compensating",o.id),await o.compensate(t.compensationData[o.id])),n.delete(o.id),r.delete(o.id),t.completedStepIds=e.steps.map(a=>a.id).filter(a=>n.has(a)),t.startedStepIds=e.steps.map(a=>a.id).filter(a=>r.has(a)),delete t.results[o.id],delete t.compensationData[o.id],await Ee(e.pmRoot,t),await ge(e,t,"step_compensated",o.id)}t.status="compensated",await Ee(e.pmRoot,t),await ge(e,t,"compensated")}async function Wr(e){let t=Mr(e.pmRoot,"Transaction pmRoot"),n=Fr(e.transactionId,"Transaction id"),r=Mr(e.author,"Transaction author"),o=Gr(e.lockTtlSeconds,us,"Transaction lock TTL"),i=Gr(e.lockWaitMs,ms,"Transaction lock wait"),a=[...e.steps];if(a.length===0)throw new TypeError("Workspace transaction requires at least one step");let s=a.map(l=>{let p=Fr(l.id,"Transaction step id");if(p!==l.id)throw new TypeError("Transaction step id must not contain surrounding whitespace");return p});if(new Set(s).size!==s.length)throw new TypeError("Workspace transaction step ids must be unique");let c={...e,pmRoot:t,transactionId:n,author:r,steps:a,lockTtlSeconds:o,lockWaitMs:i},d=await Q(t,ls,o,r,!1,!1,i);try{let l=await vs(t,n,s),p=l!==void 0;if(l?.status==="committed")return{transactionId:n,status:"committed",recovered:!0,results:Re(l.results)};let u=await _s(c,n,r,s,l);return await ws(c,u.journal,p||u.recovered)}finally{await d()}}import{readFile as ks,writeFile as xs}from"node:fs/promises";import rt 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]="89261a49-97e5-5ffc-a81c-2409f0b529cf")}catch{}})();var Kr="# pm-cli:runtime-cache:start",sn="# pm-cli:runtime-cache:end",Vr=".agents/pm",Ss=["runtime/","search/","locks/","transactions/","checkpoints/"],Es=["search/eval-queries.json"];async function Hr(e){try{return await e()}catch(t){throw t instanceof Error&&"code"in t&&typeof t.code=="string"&&["EACCES","EPERM","EROFS"].includes(t.code)?new h("The workspace .gitignore is not writable.",g.GENERIC_FAILURE,{code:"init_gitignore_unwritable",reason:t.code.toLowerCase(),required:"Grant the current user read and write access to the workspace .gitignore before initialization.",why:"pm init must publish its managed runtime-cache ignore fence without replacing unrelated entries.",nextSteps:["Grant read and write access to the workspace .gitignore and rerun pm init.","If the workspace is intentionally read-only, initialize pm in a writable workspace or clone."]}):t}}function Yr(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/\/+$/,"")}function cn(e){let t=e.replaceAll("\\","/");return rt.isAbsolute(e)||t===".."||t.startsWith("../")}function $s(e=Vr){let t=Yr(e);return[Kr,...Ss.map(n=>n==="search/"?`${t}/${n}*`:`${t}/${n}`),...Es.map(n=>`!${t}/${n}`),sn].join(`
|
|
3
|
-
`)}async function Xr(e,t={}){let n=rt.join(e,".gitignore"),r=Vr;if(t.pmRoot!==void 0){let l=Yr(rt.relative(rt.resolve(e),rt.resolve(t.pmRoot)));if(cn(l))return{path:n,changed:!1};l.length>0&&(r=l)}let o="";try{o=await Hr(()=>ks(n,"utf8"))}catch(l){if(!(l instanceof Error&&"code"in l&&oe(l)))throw l}let i=o.indexOf(Kr),a=o.indexOf(sn),c=(i>=0&&a>=i?`${o.slice(0,i)}${o.slice(a+sn.length)}`:o).trimEnd(),d=`${c.length>0?`${c}
|
|
4
|
-
|
|
5
|
-
`:""}${$s(r)}
|
|
6
|
-
`;return d===o?{path:n,changed:!1}:(await Hr(()=>xs(n,d,"utf8")),{path:n,changed:!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]="2c514907-377f-59f9-bfdd-a184abf7ffb7")}catch{}})();var As=[["beforeCommand","before_command"],["beforeMutation","before_mutation"],["afterCommand","after_command"],["onWrite","on_write"],["onRead","on_read"],["onIndex","on_index"]];function Je(e,t={}){let n=new Set;t.extensionName!==void 0&&n.add(kt(t.extensionName));for(let m of t.extensionNames??[])n.add(kt(m));let r=m=>n.size===0||n.has(kt(m)),o=(m,_)=>Qr(m.filter(v=>r(v.name)).map(_)),i=(m,_)=>Qr(m.filter(v=>r(v.name)).flatMap(_)),{registrations:a,commands:s,parsers:c,preflight:d,services:l,renderers:p,hooks:u}=e,f=i(a.relationship_kinds??[],m=>m.definitions.map(_=>_.kind)),y=p.overrides.filter(m=>r(m.name)&&((m.commands?.length??0)>0||m.resultDiscriminator!==void 0)).map(m=>({format:m.format,commands:[...m.commands??[]],result_discriminator:m.resultDiscriminator!==void 0})).sort((m,_)=>m.format.localeCompare(_.format)),w=o(a.assurance_providers??[],m=>m.definition.id);return{capabilities:br(e,t),commands:o(a.commands,m=>m.command),command_overrides:o(s.overrides,m=>m.command),command_handlers:o(s.handlers,m=>m.command),hooks:As.filter(([m])=>u[m].some(_=>r(_.name))).map(([,m])=>m),flag_commands:o(a.flags,m=>m.target_command),item_types:i(a.item_types,m=>m.types.map(_=>_.name)),item_fields:i(a.item_fields,m=>m.fields.map(_=>_.name)),...f.length>0?{relationship_kinds:f}:{},migrations:i(a.migrations,m=>typeof m.definition.id=="string"?[m.definition.id]:[]),profiles:o(a.profiles,m=>m.profile.name),importers:o(a.importers,m=>m.importer),exporters:o(a.exporters,m=>m.exporter),search_providers:o(a.search_providers,m=>m.definition.name),vector_store_adapters:o(a.vector_store_adapters,m=>m.definition.name),...w.length>0?{assurance_providers:w}:{},parser_overrides:o(c.overrides,m=>m.command),service_overrides:o(l.overrides,m=>m.service),renderer_overrides:o(p.overrides,m=>m.format),...y.length>0?{renderer_ownership:y}:{},preflight_overrides:d.overrides.filter(m=>r(m.name)).length,preflight_ownership:d.overrides.filter(m=>r(m.name)).map(m=>({commands:[...m.commands??[]]}))}}function Qr(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(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]="f97516b2-f75c-5ce0-82dc-f850466284c7")}catch{}})();var Is="PM_SOURCE_CONTEXT_ACCESS",Ts="PM_ALLOW_SOURCE_CONTEXT_WRITES";function Zr(e){let t=e[Is],n=t===void 0||t.trim().toLowerCase()==="write"?"write":"read_only",r=n==="read_only"&&e[Ts]?.trim()==="1";return{access:n,write_override_applied:r,source_writes_allowed:n==="write"||r}}import{readFile as At,realpath as dn,writeFile as Os}from"node:fs/promises";import{execFile as Cs}from"node:child_process";import L from"node:path";import{promisify as Rs}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]="dea4137f-adbd-5dca-bfc7-b56c99c7aa79")}catch{}})();var pn=Rs(Cs),$t="# pm-cli:merge-drivers:start",ro="# pm-cli:merge-drivers:end",qe="# pm-cli:merge-drivers:v2:start",ln="# pm-cli:merge-drivers:v2:end",Ps="merge-fence";function eo(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function oo(){let e=de(import.meta.url,["../../.."]);return`${eo(process.execPath)} ${eo(L.join(e,"dist","cli.js"))}`}var io=[{key:"pm-item-toon",name:"pm field-aware TOON item document merge",artifact:"item",itemPath:"%P"},{key:"pm-item-markdown",name:"pm field-aware JSON-markdown item document merge",artifact:"item",itemPath:"%P"},{key:"pm-history",name:"pm append-only history stream merge",artifact:"history",itemPath:void 0},{key:"pm-relationship",name:"pm append-only relationship event store merge",artifact:"relationship",itemPath:void 0},{key:"pm-json",name:"pm key-level JSON config merge",artifact:"json",itemPath:void 0}];function Ns(e){let t=e.explicitPath?.trim(),n=e.environment.PM_SOURCE_WORKSPACE_ROOT?.trim(),r=e.environment.PM_SOURCE_PM_PATH?.trim(),o=Zr(e.environment),i=!!(n&&r),a=t===void 0&&i&&(e.dryRun||o.source_writes_allowed);if(t!==void 0){let s=D(e.cwd,t);return{pm_root:s,workspace_start:s,source_coordinates_available:i,source_context_selected:!1,source_policy:o}}return a?{pm_root:L.resolve(r),workspace_start:L.resolve(n),source_coordinates_available:!0,source_context_selected:!0,source_policy:o}:{pm_root:i?D(e.cwd,".agents/pm"):D(e.cwd),workspace_start:e.cwd,source_coordinates_available:i,source_context_selected:!1,source_policy:o}}async function un(e){try{let{stdout:t}=await pn("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return await dn(t.trim())}catch{return null}}async function ao(e){let t=await un(e);if(t===null)throw new h("pm merge install requires a git repository (merge drivers are git configuration).",g.USAGE);return t}function mn(e,t){return L.relative(e,t).replaceAll("\\","/")}function pe(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function to(e,t){if(e[t]!=="'")return null;let n="";for(let r=t+1;r<e.length;r+=1){if(e.startsWith(`'"'"'`,r)){n+="'",r+=4;continue}if(e[r]==="'")return{value:n,nextOffset:r+1};n+=e[r]}return null}async function Ds(e,t){let n=to(e,0);if(n===null||e[n.nextOffset]!==" ")return!1;let r=to(e,n.nextOffset+1);if(r===null||e.slice(r.nextOffset)!==t||!/^node(?:\.exe)?$/iu.test(L.basename(n.value))||L.basename(r.value)!=="cli.js"||L.basename(L.dirname(r.value))!=="dist"||!await x(n.value)||!await x(r.value))return!1;try{let o=L.dirname(L.dirname(r.value)),i=JSON.parse(await At(L.join(o,"package.json"),"utf8")),a=typeof i.bin=="object"&&i.bin!==null&&"pm"in i.bin?i.bin.pm:void 0;return i.name==="@unbrained/pm-cli"&&(i.bin==="dist/cli.js"||a==="dist/cli.js")}catch{return!1}}function fn(e,t){let n=e.length>0?`${e}/`:"",r=[`${pe(`${n}**/*.toon`)} merge=pm-item-toon`,`${pe(`${n}**/*.md`)} merge=pm-item-markdown`];for(let o of t)r.push(`${pe(`${n}${o}/*.toon`)} merge=pm-item-toon`),r.push(`${pe(`${n}${o}/*.md`)} merge=pm-item-markdown`);return r.push(`${pe(`${n}**/*.jsonl`)} merge=pm-relationship`),r.push(`${pe(`${n}history/*.jsonl`)} merge=pm-history`),r.push(`${pe(`${n}settings.json`)} merge=pm-json`),r.push(`${pe(`${n}**/*.json`)} merge=pm-json`),r.push(`${pe(`${n}extensions/**`)} -merge`),r.push(`${pe(`${n}extensions/.managed-extensions.json`)} merge=pm-json`),r}function no(e,t,n){let r=e.indexOf(t),o=e.indexOf(n);return r>=0&&o>r?`${e.slice(0,r)}${e.slice(o+n.length)}`:e.replace(t,"").replace(n,"")}async function so(e,t,n){let r=L.join(e,".gitattributes"),o="";try{o=await At(r,"utf8")}catch(d){if(!(d instanceof Error&&"code"in d&&oe(d)))throw d}let i=[qe,...t,ln].join(`
|
|
7
|
-
`),s=no(no(o,qe,ln),$t,ro).trimEnd(),c=`${s.length>0?`${s}
|
|
8
|
-
|
|
9
|
-
`:""}${i}
|
|
10
|
-
`;return c===o?{path:r,changed:!1}:(n||await Os(r,c,"utf8"),{path:r,changed:!0})}function co(e){let t=B(e,null);return[...new Set(Object.values(t.type_to_folder))].sort((n,r)=>n.localeCompare(r))}async function Pm(e,t){let n=L.resolve(e),r=null,o="",i=n;for(let v=0;v<8;v+=1){let k=L.join(i,".gitattributes");try{let C=await At(k,"utf8");if(C.includes(qe)||C.includes($t)){r=i,o=C;break}}catch{}let S=L.dirname(i);if(S===i)break;i=S}if(r===null)return{status:"not_installed",missing_patterns:[],stale_patterns:[],schema_scope:"project"};let a=L.join(r,".gitattributes"),s=o.includes(qe),c=s?qe:$t,d=s?ln:ro,l=o.indexOf(c),p=o.indexOf(d),u=p>l?o.slice(l+c.length,p).split(`
|
|
11
|
-
`).map(v=>v.trim()).filter(v=>v.length>0):[],f=fn(mn(r,n),t),y=new Set(u),w=new Set(f),m=f.filter(v=>!y.has(v)),_=u.filter(v=>!w.has(v));return{status:m.length>0||_.length>0?"drift":"ok",path:a,missing_patterns:m,stale_patterns:_,schema_scope:"project"}}async function Nm(e){let t=oo(),n=[],r=[];for(let o of io){let i=`merge.${o.key}.driver`,a=` merge driver ${o.artifact} "%O" "%A" "%B"${o.itemPath===void 0?"":` --item-path ${o.itemPath}`}`,s=`${t}${a}`;try{let{stdout:c}=await pn("git",["config","--local","--get",i],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),d=c.trim();d!==s&&!await Ds(d,a)&&r.push(i)}catch{n.push(i)}}return{status:n.length>0?"missing":r.length>0?"drift":"ok",missing_keys:n,drifted_keys:r}}async function lo(e){let t;try{t=await ao(L.resolve(e))}catch{return{status:"no_git"}}let n=mn(t,L.resolve(e)),r=await O(e),o=V(void 0,r.author_default),i=await Q(e,Ps,r.locks.ttl_seconds,o,!1,ae(r).force_required_for_stale_lock,r.locks.wait_ms);try{let a=L.join(t,".gitattributes"),s;try{s=await At(a,"utf8")}catch(p){if(p instanceof Error&&"code"in p&&oe(p))return{status:"not_installed",path:a};throw p}if(!s.includes(qe)&&!s.includes($t))return{status:"not_installed",path:a};let c=await O(e),d=co(c),l=await so(t,fn(n,d),!1);return{status:l.changed?"refreshed":"unchanged",path:l.path}}finally{await i()}}async function Dm(e,t){let n=Ns({cwd:process.cwd(),explicitPath:t.path,dryRun:e.dryRun===!0,environment:process.env}),r=n.pm_root;await ze(r);let o=await ao(n.workspace_start);return hn({pmRoot:r,workspaceRoot:o,dryRun:e.dryRun===!0})}async function hn(e){let t=L.resolve(e.pmRoot),n=L.resolve(e.workspaceRoot),r=e.dryRun===!0,o,i;try{[o,i]=await Promise.all([dn(t),dn(n)])}catch(f){throw new h(`Cannot resolve tracker root ${t} or workspace root ${n}: ${String(f)}`,g.NOT_FOUND,{code:"merge_root_not_found",nextSteps:["Initialize the tracker and ensure both paths are accessible.",'Retry "pm merge install" from the repository workspace.']})}let a=mn(i,o);if(cn(a))throw new h(`Tracker root ${t} is outside the git repository ${n}; there is nothing to configure for this repository.`,g.USAGE);let s=await O(o),c=co(s),d=fn(a,c),l=[],p=oo();for(let f of io)l.push({key:`merge.${f.key}.name`,value:f.name}),l.push({key:`merge.${f.key}.driver`,value:`${p} merge driver ${f.artifact} "%O" "%A" "%B"${f.itemPath===void 0?"":` --item-path ${f.itemPath}`}`});if(!r)try{for(let f of l)await pn("git",["config","--local",f.key,f.value],{cwd:i,encoding:"utf8",windowsHide:!0,timeout:1e4})}catch{throw new h(`Cannot install repository-local merge drivers in ${i}. Ensure the repository Git config is writable and no other Git process holds its lock, then retry.`,g.DEPENDENCY_FAILED,{code:"merge_git_config_unwritable",why:"pm merge install must persist clone-local driver commands before publishing their shared .gitattributes mappings.",nextSteps:["Make the repository Git config writable or wait for the process holding its lock to finish.",'Retry "pm merge install"; the operation is idempotent.','Use "pm merge install --dry-run --json" when the workspace is intentionally read-only.']})}let u=await so(i,d,r);return{ok:!0,dry_run:r,workspace_root:i,pm_root:o,gitattributes:{path:u.path,changed:u.changed,patterns:d,schema_scope:"project"},git_config:l,guidance:["Commit .gitattributes so every branch and collaborator shares the merge mapping.",'git config is per-clone: each collaborator (and each fresh worktree/clone) runs "pm merge install" once.','After merging branches, run "pm merge reconcile --dry-run" to inspect the complete receipt and history repair, then apply "pm merge reconcile"; use --force only after explicitly accepting any discarded values.',"Custom item types registered later refresh this fence automatically (pm schema add-type/remove-type); rerun pm merge install only after out-of-band type-folder edits."],generated_at:I()}}import{createHash as So}from"node:crypto";import Ne from"node:fs/promises";import Ye 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]="2b5a573e-1e36-58b9-b93b-4a4088f71e9a")}catch{}})();var js=new Set(Qt),Ls=new Set(Zt),po=new Set([...rr.filter(e=>e!=="severity"),"id","title","type","status","priority","tags","assignee","parent","description","body","created_at","updated_at","closed_at","completed_at","author","deadline","estimate","sprint","release","risk","confidence","reviewer","resolution","expected","actual"]),Fs=["create","update"];function ho(e){if(typeof e!="string")return"";let t=e.trim().toLowerCase().replaceAll(/[\s_]+/g,"-");return t.startsWith("--")?t.slice(2):t}function uo(e){return e.replaceAll("_","-")}function Ms(e,t){let n=new Set;for(let r of e){let o=ho(r);o.length>0&&o!==t&&n.add(o)}return[...n].sort((r,o)=>r.localeCompare(o))}function Gs(e){let t=new Set;for(let n of e??[]){let r=n.trim();r.length>0&&t.add(r)}return[...t].sort((n,r)=>n.localeCompare(r))}function Us(e){let t=new Set,n=[];for(let r of e??[]){let o=r.trim().toLowerCase();if(o.length!==0){if(!Ls.has(o))throw new Error(`Invalid field command "${r}". Allowed: ${Zt.join(", ")}.`);t.has(o)||(t.add(o),n.push(o))}}return e===void 0||n.length===0?[...Fs]:n}function go(e){let t=A(e.key);if(t.length===0)throw new Error("Field key must not be empty.");if(po.has(t))throw new Error(`Cannot define custom field "${t}": custom schema field "${t}" collides with built-in item metadata "${t}". Rename the custom field with a project-specific prefix. Reserved fields: ${[...po].sort((l,p)=>l.localeCompare(p)).join(", ")}.`);let n=typeof e.type=="string"&&e.type.trim().length>0?e.type.trim().toLowerCase():"string";if(!js.has(n))throw new Error(`Invalid field type "${e.type}". Allowed: ${Qt.join(", ")}.`);let r=n,o=Us(e.commands),i=ho(e.cliFlag),a=i.length>0&&i!==uo(t)?i:void 0,s=a??uo(t),c=Ms(e.aliases??[],s),d=e.description?.trim();return{key:t,type:r,commands:o,description:d&&d.length>0?d:void 0,cliFlag:a,cliAliases:c,required:e.required===!0,requiredOnCreate:e.requiredOnCreate===!0,allowUnset:e.allowUnset!==!1,requiredTypes:Gs(e.requiredTypes)}}function zs(e){if(Array.isArray(e))return e;if(typeof e!="object"||e===null)return;let t=e;if(Array.isArray(t.fields))return t.fields;if(Array.isArray(t.definitions))return t.definitions}function Js(e){let t=zs(e);if(!t)return[];let n=[];for(let r of t){if(typeof r!="object"||r===null||Array.isArray(r))continue;let o=r;typeof o.key!="string"||o.key.trim().length===0||n.push(o)}return n}function Be(e){if(e==null||e.trim().length===0)return{fields:[]};let t;try{t=JSON.parse(e)}catch{throw new Error("schema/fields.json contains invalid JSON.")}return{fields:Js(t)}}function We(e){return`${JSON.stringify({fields:e.fields},null,2)}
|
|
12
|
-
`}function yo(e,t){let n=e.fields.find(a=>A(a.key)===t.key),r=n!==void 0,o=e.fields.filter(a=>A(a.key)!==t.key),i={...n,key:t.key,type:t.type,commands:[...t.commands]};return mo(i,"description",t.description),mo(i,"cli_flag",t.cliFlag),t.cliAliases.length>0?i.cli_aliases=[...t.cliAliases]:delete i.cli_aliases,fo(i,"required",t.required),fo(i,"required_on_create",t.requiredOnCreate),t.allowUnset===!1?i.allow_unset=!1:delete i.allow_unset,t.requiredTypes.length>0?i.required_types=[...t.requiredTypes]:delete i.required_types,o.push(i),o.sort((a,s)=>A(a.key).localeCompare(A(s.key))),{file:{fields:o},definition:i,replaced:r}}function _o(e,t){let n=A(t);if(n.length===0)throw new Error("Field key must not be empty.");let r=[],o=e.fields.filter(i=>A(i.key)===n?(r.push(i),!1):!0);return r.length===0?{file:{fields:o},removed:!1}:{file:{fields:o},removed:!0,definition:r[0]}}function mo(e,t,n){let r=e;n!==void 0&&n.length>0?r[t]=n:delete r[t]}function fo(e,t,n){let r=e;n?r[t]=!0:delete r[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]="ec456832-5120-5171-93fd-861ea4125acb")}catch{}})();var qs=new Set(vt),Pe=new Set(xr.map(e=>A(e.id)).filter(e=>e.length>0));function Bs(e){let t=new Set;for(let n of e){let r=A(n);r.length>0&&t.add(r)}return[...t].sort((n,r)=>n.localeCompare(r))}function wo(e){let t=A(e.id);if(t.length===0)throw new Error("Status id must not be empty.");if(Pe.has(t))throw new Error(`Cannot add-status the built-in status "${t}". Built-in statuses are reserved: ${[...Pe].join(", ")}.`);let n;if(e.roles!==void 0){n=[];let a=new Set;for(let s of e.roles){let c=typeof s=="string"?s.trim().toLowerCase():"";if(c.length!==0){if(!qs.has(c))throw new Error(`Invalid status role "${s}". Allowed roles: ${vt.join(", ")}.`);a.has(c)||(a.add(c),n.push(c))}}if(n.length===0)throw new Error(`Status role must include at least one lifecycle role. Allowed roles: ${vt.join(", ")}.`)}let r=e.aliases===void 0?void 0:Bs(e.aliases).filter(a=>a!==t),o=e.description?.trim(),i=typeof e.order=="number"&&Number.isFinite(e.order)?Math.trunc(e.order):void 0;return{id:t,roles:n,aliases:r,description:o&&o.length>0?o:void 0,order:i}}function Ws(e){if(Array.isArray(e))return e;if(typeof e!="object"||e===null)return;let t=e;if(Array.isArray(t.statuses))return t.statuses;if(Array.isArray(t.definitions))return t.definitions}function Hs(e){let t=Ws(e);if(!t)return[];let n=[];for(let r of t){if(typeof r!="object"||r===null||Array.isArray(r))continue;let o=r;typeof o.id!="string"||o.id.trim().length===0||n.push(o)}return n}function He(e){if(e==null||e.trim().length===0)return{statuses:[]};let t;try{t=JSON.parse(e)}catch{throw new Error("schema/statuses.json contains invalid JSON.")}return{statuses:Hs(t)}}function Ke(e){return`${JSON.stringify({statuses:e.statuses},null,2)}
|
|
13
|
-
`}function vo(e,t,n){let r=e.statuses.slice(),o=r.findIndex(s=>A(s.id)===t.id),i=o>=0?r[o]:n,a={...i,id:t.id};return t.roles!==void 0&&(t.roles.length>0?a.roles=[...t.roles]:a.roles!==void 0&&delete a.roles),t.aliases!==void 0&&(t.aliases.length>0?a.aliases=[...t.aliases]:a.aliases!==void 0&&delete a.aliases),t.description!==void 0&&(a.description=t.description),t.order!==void 0&&(a.order=t.order),o>=0?r[o]=a:r.push(a),{file:{statuses:r},definition:a,replaced:i!==void 0}}function bo(e,t){let n=A(t);if(n.length===0)throw new Error("Status id must not be empty.");if(Pe.has(n))throw new Error(`Cannot remove built-in status "${n}". Built-in statuses are reserved: ${[...Pe].join(", ")}.`);let r=e.statuses.slice(),o=r.findIndex(a=>A(a.id)===n);if(o<0)return{file:{statuses:r},removed:!1};let[i]=r.splice(o,1);return{file:{statuses:r},removed:!0,definition:i}}function gn(e,t){let n=[e.id,...e.aliases??[]];for(let r of n){let o=A(r);if(o.length===0)continue;let i=t.get(o);if(i!==void 0&&i!==e.id)throw new Error(`Status token "${o}" already belongs to status "${i}". Choose a different id/alias to avoid shadowing it.`)}}(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]="60738c1f-3b44-5f8a-82c9-99d2b2de1e51")}catch{}})();function ye(e,t){if(typeof e!="string"||e.trim().length===0)throw new TypeError(`Schema migration ${t} must be non-empty`);return e.trim()}function Eo(e){let t=ye(e,"migrationId");if(!/^[a-zA-Z0-9._-]+$/.test(t))throw new TypeError("Schema migration migrationId must match [a-zA-Z0-9._-]+");return t}function $o(e,t){let n=_n(e),r=ye(t,"migrationScope");return`auto-${So("sha256").update(JSON.stringify({scope:r,request:n})).digest("hex").slice(0,20)}`}function _n(e){let t=e.kind==="rename-type"?{kind:e.kind,from:ye(e.from,"source"),to:ye(e.to,"target")}:e.kind==="rename-field"?{kind:e.kind,from:A(ye(e.from,"source")),to:A(ye(e.to,"target")),...e.type===void 0?{}:{type:ye(e.type,"type")}}:{kind:e.kind,from:A(ye(e.from,"source")),to:A(ye(e.to,"target"))};if(t.from.toLowerCase()===t.to.toLowerCase())throw new TypeError("Schema migration source and target must differ");return t}function Ks(e){return e.kind==="rename-type"?"types":e.kind==="rename-field"?"fields":"statuses"}function Vs(e,t,n){let r=K(t.schema),o=Ks(n);return ne(e,r.files[o],Y[o])}function Ao(e,t){return Ye.join(e,"transactions","schema",`${t}-plan.json`)}function It(e){return e.length===0?null:JSON.parse(e)}async function Ve(e){let t=await q(e);return{exists:t!==null,raw:t??""}}async function Io(e,t){t.exists?await he(e,t.raw):await Ne.rm(e,{force:!0})}function Ys(e,t,n){let r=ie(e),o=r.definitions.findIndex(a=>a.name.trim().toLowerCase()===t.from.toLowerCase()),i=r.definitions.findIndex(a=>a.name.trim().toLowerCase()===t.to.toLowerCase());if(n==="stage"){if(i>=0)return le(r);if(o<0)throw new TypeError(`Unknown custom type "${t.from}".`);r.definitions.push({...r.definitions[o],name:t.to})}else o>=0&&r.definitions.splice(o,1);return le(r)}function Xs(e,t,n){let r=Be(e),o=r.fields.findIndex(a=>a.key===t.from),i=r.fields.findIndex(a=>a.key===t.to);if(n==="stage"){if(i>=0)return We(r);if(o<0)throw new TypeError(`Unknown custom field "${t.from}".`);let a=r.fields[o];r.fields.push({...a,key:t.to,metadata_key:t.to,front_matter_key:t.to,cli_flag:t.to.replaceAll("_","-")})}else o>=0&&r.fields.splice(o,1);return We(r)}function Qs(e,t,n){let r=He(e),o=r.statuses.findIndex(a=>a.id===t.from),i=r.statuses.findIndex(a=>a.id===t.to);if(n==="stage"){if(i>=0)return Ke(r);if(o<0)throw new TypeError(`Unknown custom status "${t.from}".`);r.statuses.push({...r.statuses[o],id:t.to})}else o>=0&&r.statuses.splice(o,1);return Ke(r)}function Zs(e,t,n){return t.kind==="rename-type"?Ys(e,t,n):t.kind==="rename-field"?Xs(e,t,n):Qs(e,t,n)}function $e(e,t){return typeof e=="string"&&e.trim().toLowerCase()===t.from.toLowerCase()?t.to:e}function wn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function Xe(e){return Array.isArray(e)?e.map(t=>wn(t)).filter(t=>t!==void 0):[]}function ec(e,t){for(let n of Xe(e.fields))Array.isArray(n.required_types)&&(n.required_types=n.required_types.map(r=>$e(r,t)));for(let n of Xe(e.type_workflows))n.type=$e(n.type,t)}function tc(e,t){for(let r of Xe(e.definitions))r.default_status=$e(r.default_status,t);let n=wn(e.workflow);if(n)for(let[r,o]of Object.entries(n))n[r]=$e(o,t);for(let r of Xe(e.type_workflows))Array.isArray(r.allowed_transitions)&&(r.allowed_transitions=r.allowed_transitions.map(o=>Array.isArray(o)?o.map(i=>$e(i,t)):o))}function nc(e,t){for(let n of Xe(e.definitions)){for(let r of["required_create_fields","required_create_repeatables"])Array.isArray(n[r])&&(n[r]=n[r].map(o=>$e(o,t)));for(let r of["options","command_option_policies"])for(let o of Xe(n[r])){let i=r==="options"?"key":"option";o[i]=$e(o[i],t)}}}function rc(e,t){let n=wn(e.options);if(!n)return;if(t.kind==="rename-field"){if(!Object.prototype.hasOwnProperty.call(n,t.from))return;if(Object.prototype.hasOwnProperty.call(n,t.to))throw new TypeError(`Schema migration collision in saved template "${String(e.name??"unknown")}": target field "${t.to}" already exists.`);n[t.to]=n[t.from],delete n[t.from];return}let r=t.kind==="rename-type"?"type":"status";n[r]=$e(n[r],t)}function yn(e,t){let n=JSON.parse(e);if(typeof n!="object"||n===null||Array.isArray(n))return e;let r=n;return t.kind==="rename-type"?ec(r,t):t.kind==="rename-field"?nc(r,t):tc(r,t),rc(r,t),`${JSON.stringify(r,null,2)}
|
|
14
|
-
`}function To(e,t){if(t.kind==="rename-type"){let r=ie(e).definitions;return{source:r.some(o=>o.name.trim().toLowerCase()===t.from.toLowerCase()),target:r.some(o=>o.name.trim().toLowerCase()===t.to.toLowerCase())}}if(t.kind==="rename-field"){let r=Be(e).fields;return{source:r.some(o=>o.key===t.from),target:r.some(o=>o.key===t.to)}}let n=He(e).statuses;return{source:n.some(r=>r.id===t.from),target:n.some(r=>r.id===t.to)}}function oc(e,t){let n=e;return t.kind==="rename-type"?e.type.toLowerCase()===t.to.toLowerCase()?[]:["type"]:t.kind==="remap-status"?e.status.toLowerCase()===t.to.toLowerCase()?[]:["status"]:Object.prototype.hasOwnProperty.call(n,t.to)&&!Object.prototype.hasOwnProperty.call(n,t.from)?[]:[t.from,t.to]}function ic(e,t){if(t.kind==="rename-type")return e.type.toLowerCase()===t.from.toLowerCase()?{id:e.id,changes:[{field:"type",before:e.type,after:t.to}]}:null;if(t.kind==="remap-status")return e.status.toLowerCase()===t.from.toLowerCase()?{id:e.id,changes:[{field:"status",before:e.status,after:t.to}]}:null;if(t.type!==void 0&&e.type.toLowerCase()!==t.type.toLowerCase())return null;let n=e;if(!Object.prototype.hasOwnProperty.call(n,t.from))return null;if(Object.prototype.hasOwnProperty.call(n,t.to))throw new TypeError(`Schema migration collision on item "${e.id}": target field "${t.to}" already exists.`);return{id:e.id,changes:[{field:t.from,before:n[t.from],after:void 0},{field:t.to,before:void 0,after:n[t.from]}]}}function Oo(e,t){let n=_n(t.request),r=t.migrationId===void 0?$o(n,t.migrationScope??"plan"):Eo(t.migrationId),o=e.map(c=>ic(c,n)).filter(c=>c!==null).sort((c,d)=>c.id.localeCompare(d.id)),i=So("sha256").update(JSON.stringify({migrationId:r,request:n,items:o})).digest("hex"),a=new Set([...t.completedItemIds??[]].map(c=>c.trim()).filter(c=>c.length>0)),s=o.filter(c=>!a.has(c.id));return Object.freeze({migration_id:r,request:n,fingerprint:i,affected_item_count:o.length,pending_item_count:s.length,skipped_completed_count:o.length-s.length,items:Object.freeze(s)})}async function ac(e){let t=B(e.settings,H()),n=[...new Set(Object.values(t.type_to_folder))],r=await Nr(e.pmRoot,n),o=e.request.kind==="rename-type"?{types:[e.request.from]}:e.request.kind==="remap-status"?{statuses:[e.request.from]}:{metadataKeys:[e.request.from],...e.request.type===void 0?{}:{types:[e.request.type]}},i=r?await Pr({pmRoot:e.pmRoot,expectedSourceCursor:r.source_cursor,query:o}):null;return i?{items:i.items,selectionSource:"derived_index",typeToFolder:t.type_to_folder}:{items:await Ce(e.pmRoot,e.settings.item_format,t.type_to_folder,[],e.settings.schema),selectionSource:"scan",typeToFolder:t.type_to_folder}}async function sc(e,t){let n=await q(Ao(e,t));if(n===null)return null;try{let r=JSON.parse(n);if(r.schema_version!==1||r.plan.migration_id!==t||!Array.isArray(r.plan.items))throw new TypeError("invalid plan envelope");return r.plan}catch(r){throw new h(`Stored schema migration plan "${t}" is invalid: ${ir(r)}`,g.GENERIC_FAILURE)}}async function cc(e,t){let n=Ao(e,t.migration_id);await Ne.mkdir(Ye.dirname(n),{recursive:!0});let r={schema_version:1,plan:t,created_at:new Date().toISOString()};await he(n,`${JSON.stringify(r,null,2)}
|
|
15
|
-
`)}function dc(e,t){return JSON.stringify(e)===JSON.stringify(t)}async function lc(e){let t=await Dr(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!t)throw new h(`Schema migration item "${e.id}" no longer exists.`,g.NOT_FOUND);return(await jr(t,{schema:e.settings.schema})).document.metadata}function ko(e,t,n){let r=n==="forward"?t.from:t.to,o=n==="forward"?t.to:t.from;if(t.kind==="rename-type"){if(e.metadata.type.toLowerCase()===o.toLowerCase())return[];if(e.metadata.type.toLowerCase()!==r.toLowerCase())throw new TypeError(`Schema migration expected type "${r}" on item "${e.metadata.id}".`);return e.metadata.type=o,["type"]}if(t.kind==="remap-status"){if(e.metadata.status.toLowerCase()===o.toLowerCase())return[];if(e.metadata.status.toLowerCase()!==r.toLowerCase())throw new TypeError(`Schema migration expected status "${r}" on item "${e.metadata.id}".`);return e.metadata.status=o,["status"]}let i=e.metadata;if(Object.prototype.hasOwnProperty.call(i,o)&&!Object.prototype.hasOwnProperty.call(i,r))return[];if(!Object.prototype.hasOwnProperty.call(i,r)||Object.prototype.hasOwnProperty.call(i,o))throw new TypeError(`Schema migration field state changed concurrently on item "${e.metadata.id}".`);return i[o]=i[r],delete i[r],[r,o]}function xo(e){return{id:e.id,inspect:async()=>{let t=await Ve(e.filePath),n=To(t.raw,e.request),r=e.phase==="stage"?n.source&&n.target:!n.source&&n.target;return{state:r?"applied":"pending",...r?{result:{phase:e.phase}}:{}}},prepareCompensation:async()=>{let t=await Ve(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await Ve(e.filePath);return await he(e.filePath,Zs(t.raw,e.request,e.phase)),{phase:e.phase}},compensate:async t=>{if(typeof t!="object"||t===null||Array.isArray(t)||typeof t.exists!="boolean"||typeof t.raw!="string")throw new TypeError(`Missing schema snapshot for ${e.id} compensation.`);await Io(e.filePath,{exists:t.exists,raw:t.raw})}}}function pc(e){return{id:e.stepId,inspect:async()=>{let t=await Ve(e.filePath);return{state:yn(t.raw,e.request)===t.raw?"applied":"pending"}},prepareCompensation:async()=>{let t=await Ve(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await Ve(e.filePath);return await he(e.filePath,yn(t.raw,e.request)),{file:e.filePath}},compensate:async t=>{if(typeof t!="object"||t===null||Array.isArray(t)||typeof t.exists!="boolean"||typeof t.raw!="string")throw new TypeError(`Missing schema reference snapshot for ${e.stepId} compensation.`);await Io(e.filePath,{exists:t.exists,raw:t.raw})}}}function uc(e){return{id:`item-${e.id}`,inspect:async()=>{let t=await O(e.pmRoot),n=B(t,H()).type_to_folder,r=await lc({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id}),o=oc(r,e.request).length===0;return{state:o?"applied":"pending",...o?{result:{item_id:e.id}}:{}}},apply:async()=>{let t=await O(e.pmRoot),n=B(t,H()).type_to_folder,r=await nn({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id,op:`schema_${e.request.kind.replaceAll("-","_")}`,author:e.author,message:`Schema migration ${e.request.kind}: ${e.request.from} -> ${e.request.to}`,force:e.force,skipNoop:!0,mutate(o){return{changedFields:ko(o,e.request,"forward")}}});return{item_id:e.id,changed_fields:r.changedFields}},compensate:async()=>{let t=await O(e.pmRoot),n=B(t,H()).type_to_folder;await nn({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id,op:`schema_${e.request.kind.replaceAll("-","_")}_compensate`,author:e.author,message:`Compensate schema migration ${e.request.kind}: ${e.request.to} -> ${e.request.from}`,force:!0,skipNoop:!0,mutate(r){return{changedFields:ko(r,e.request,"reverse")}}})}}}async function mc(e){let t=await sc(e.pmRoot,e.migrationId);if(t){if(!dc(t.request,e.request))throw new h(`Schema migration id "${e.migrationId}" already belongs to a different request.`,g.CONFLICT);return{plan:t,stored:!0}}let n=await ac({pmRoot:e.pmRoot,settings:e.settings,request:e.request});return{plan:{...Oo(n.items,{migrationId:e.migrationId,request:e.request}),selection_source:n.selectionSource},stored:!1}}async function fc(e){let t=To(await q(e.schemaPath)??"",e.request);if(!t.source)throw new h(`Schema migration source "${e.request.from}" is not a custom definition.`,g.NOT_FOUND);if(t.target)throw new h(`Schema migration target "${e.request.to}" already exists.`,g.CONFLICT);await cc(e.pmRoot,e.plan)}async function hc(e){let t=K(e.settings.schema),n=[...new Set([["types",Y.types],["fields",Y.fields],["workflows",Y.workflows]].map(([o,i])=>ne(e.pmRoot,t.files[o],i)).filter(o=>o!==e.schemaPath))];try{let o=Ye.join(e.pmRoot,"templates"),i=await Ne.readdir(o,{withFileTypes:!0});n.push(...i.filter(a=>a.isFile()&&a.name.toLowerCase().endsWith(".json")).map(a=>Ye.join(o,a.name)))}catch(o){if(typeof o!="object"||o===null||!("code"in o)||!oe(o))throw o}n.sort((o,i)=>o.localeCompare(i));let r=[];for(let o of n){let i=await q(o);i!==null&&yn(i,e.request)!==i&&r.push({filePath:o,beforeRaw:i})}return{paths:n,snapshots:r}}async function gc(e){for(let t of e.snapshots){let n=await Ne.readFile(t.filePath,"utf8"),r=Ye.relative(e.pmRoot,t.filePath).replaceAll("\\","/");await tn({pmRoot:e.pmRoot,author:e.author,documentPath:r,before:It(t.beforeRaw),after:It(n),op:"schema_migration_reference",idempotencyKey:`${e.plan.migration_id}:${e.plan.fingerprint}:${r}`,message:`${e.request.kind}: ${e.request.from} -> ${e.request.to}`,lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}}async function yc(e,t,n){let r=_n(e),o=D(process.cwd(),n.path);await ze(o);let i=t.migrationId===void 0?$o(r,await Ne.realpath(o)):Eo(t.migrationId),a=await O(o),s=V(t.author,a.author_default),c=await mc({pmRoot:o,settings:a,migrationId:i,request:r}),d=c.plan;if(t.dryRun===!0)return{...d,action:r.kind,applied:!1,recovered:!1,migrated_item_count:0};let l=Vs(o,a,r),p=await Ne.readFile(l,"utf8");c.stored||await fc({pmRoot:o,schemaPath:l,request:r,plan:d});let u=await hc({pmRoot:o,schemaPath:l,settings:a,request:r}),f=[xo({id:"stage-schema",filePath:l,request:r,phase:"stage"}),...u.paths.map((_,v)=>pc({filePath:_,request:r,stepId:`reference-${String(v+1).padStart(4,"0")}`})),...d.items.map(_=>uc({pmRoot:o,id:_.id,request:r,author:s,force:t.force===!0})),xo({id:"retire-source",filePath:l,request:r,phase:"retire"})],y=await Wr({pmRoot:o,transactionId:`schema-${i}`,author:s,steps:f,lockTtlSeconds:Math.max(a.locks.ttl_seconds,300),lockWaitMs:a.locks.wait_ms}),w=await Ne.readFile(l,"utf8"),{historyPath:m}=await tn({pmRoot:o,author:s,documentPath:Ye.relative(o,l).replaceAll("\\","/"),before:It(p),after:It(w),op:"schema_migration",idempotencyKey:`${d.migration_id}:${d.fingerprint}`,message:`${r.kind}: ${r.from} -> ${r.to}; affected=${d.affected_item_count}`,lockTtlSeconds:a.locks.ttl_seconds,lockWaitMs:a.locks.wait_ms});return await gc({pmRoot:o,author:s,settings:a,request:r,plan:d,snapshots:u.snapshots}),{...d,action:r.kind,applied:!0,recovered:y.recovered,migrated_item_count:d.affected_item_count,workspace_history_path:m}}function _c(e){let t=e.applied?"applied":"dry-run",n=e.recovered?" (recovered)":"";return[`${e.action}: ${e.request.from} -> ${e.request.to} [${t}${n}]`,`migration_id: ${e.migration_id}`,`affected: ${e.affected_item_count}`,`pending: ${e.pending_item_count}`,`fingerprint: ${e.fingerprint}`].join(`
|
|
16
|
-
`)}import xc from"node:path";import{mkdir as Sc}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]="e3f016bb-8add-5765-bb1a-a7b22423f8d1")}catch{}})();var ot=["agile","ops","research"],wc={agile:[{name:"Story",description:"User-facing outcome or capability slice expressed from a stakeholder perspective.",defaultStatus:"open",folder:"stories",aliases:["user-story"]},{name:"Spike",description:"Time-boxed investigation used to reduce uncertainty before implementation.",defaultStatus:"open",folder:"spikes",aliases:["research-spike"]}],ops:[{name:"Incident",description:"Operational disruption, degradation, or support escalation with recovery tracking.",defaultStatus:"open",folder:"incidents",aliases:["outage"]},{name:"Runbook",description:"Repeatable operational procedure, diagnostic path, or response playbook.",defaultStatus:"open",folder:"runbooks",aliases:["playbook"]}],research:[{name:"Experiment",description:"Validated-learning activity with hypothesis, method, and outcome tracking.",defaultStatus:"open",folder:"experiments",aliases:["study"]},{name:"Hypothesis",description:"Testable claim or assumption that should be supported, rejected, or refined.",defaultStatus:"open",folder:"hypotheses",aliases:["assumption"]}]};function Tt(e){if(e===void 0)return;let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new Error("Type preset name must not be empty.");if(t==="agile"||t==="ops"||t==="research")return t;throw new Error(`Invalid type preset "${e}". Allowed: ${ot.join(", ")}.`)}function it(e){return wc[e].map(t=>nt(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]="3d53ef97-6dd5-5dea-a5c2-9bc9e62d881c")}catch{}})();var vc=/^([A-Za-z][A-Za-z0-9_-]*?)\s*[-:]\s+\S/;function bc(e){let t=vc.exec(e.trim());if(!t)return;let n=t[1];if(!(n.length<2)&&!/^[A-Za-z]\d+$/.test(n))return n.toLowerCase()}function kc(e){return e.split(/[-_]+/).filter(t=>t.length>0).map(t=>`${t.slice(0,1).toUpperCase()}${t.slice(1).toLowerCase()}`).join("")}function Co(e,t={}){let n=typeof t.minCount=="number"&&t.minCount>0?Math.trunc(t.minCount):10,r=typeof t.maxExamples=="number"&&t.maxExamples>0?Math.trunc(t.maxExamples):3,o=new Map;for(let a of e){let s=typeof a=="string"?a.trim():"";if(s.length===0)continue;let c=bc(s);if(c===void 0)continue;let d=o.get(c)??{count:0,examples:[]};d.count+=1,d.examples.length<r&&d.examples.push(s),o.set(c,d)}let i=[];for(let[a,s]of o.entries()){if(s.count<n)continue;let c=kc(a);i.push({name:c,prefix:a,count:s.count,examples:s.examples,shadows_builtin:Tr(c)!==void 0})}return i.sort((a,s)=>s.count-a.count||a.name.localeCompare(s.name)),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]="264088a5-09d1-52ed-8b12-af00392e1a5f")}catch{}})();var Bf=["add-type","remove-type","add-status","remove-status","add-field","remove-field","list-fields","show-field","apply-preset","list","show","show-status","rename-type","rename-field","remap-status"],Ot="schema-types",Ro="schema-statuses",Po="schema-fields";function Ae(e){return Ge({pmRoot:e.pmRoot,filePath:e.filePath,raw:e.raw,op:e.op,author:e.author,lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}async function Wf(e,t,n){let r=D(process.cwd(),n.path);await _e(r);let o;try{o=nt({name:e,description:t.description,defaultStatus:t.defaultStatus,folder:t.folder,aliases:t.alias})}catch(f){throw new h(f instanceof Error?f.message:String(f),g.USAGE)}let i=await O(r),a=K(i.schema),s=ne(r,a.files.types,Y.types),c=[],d=V(t.author,i.author_default),l=ae(i),p=await Q(r,Ot,i.locks.ttl_seconds,d,!!t.force,l.force_required_for_stale_lock,i.locks.wait_ms),u;try{let f=await q(s),y;try{y=ie(f)}catch(w){throw new h(w instanceof Error?w.message:String(w),g.GENERIC_FAILURE)}try{Or(o,y);let w=new Map,m=B(i,H());for(let[_,v]of Object.entries(m.type_to_folder)){let k=v.trim().toLowerCase();k.length>0&&!w.has(k)&&w.set(k,_)}Cr(o,y,w)}catch(w){throw new h(w instanceof Error?w.message:String(w),g.USAGE)}u=Ue(y,o),u.replaced&&u.previousName!==void 0&&u.previousName!==u.definition.name&&c.push(`type_recased:${u.previousName}->${u.definition.name}`),await Ae({pmRoot:r,filePath:s,raw:le(u.file),op:"schema:add-type",author:d,settings:i}),await at(r,[u.definition],c,"schema:add-type-folder"),c.push(...await W({path:s,scope:"project",op:"schema:add-type"}))}finally{await p()}return await No(r,c),{action:"add-type",registered:!0,replaced:u.replaced,type:u.definition,file:{path:s,definitions:u.file.definitions.length},warnings:Ie(c),generated_at:I()}}async function _e(e){await ze(e)}async function No(e,t){try{let n=await lo(e);n.status==="refreshed"?t.push("merge_fence_refreshed"):n.status==="not_installed"&&t.push('merge_fence_not_installed:type folders lack git merge drivers; run "pm merge install"')}catch{t.push('merge_fence_refresh_failed:run "pm merge install" to reconcile')}}function Ie(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}async function Ec(e,t,n,r){let o=B(t,H()),i=r.trim().toLowerCase();return(await Ce(e,t.item_format,o.type_to_folder,[],n)).filter(s=>typeof s.type=="string"&&s.type.toLowerCase()===i).length}async function $c(e,t,n,r){let o=B(t,H()),i=tt(n),a=A(r);return(await Ce(e,t.item_format,o.type_to_folder,[],n)).filter(c=>{let d=typeof c.status=="string"?c.status:"";return(i.alias_to_id.get(A(d))??A(d))===a}).length}async function Ac(e,t,n,r,o){if(o.length===0||Pe.has(o))return;let i=await $c(t,n,r,o);i>0&&e.push(`items_using_status:${i}`);let a=Do(r.workflow,o);a.length>0&&e.push(`status_referenced_by_workflow:${a.join(",")}`)}function Do(e,t){return[["draft_status",e.draft_status],["open_status",e.open_status],["in_progress_status",e.in_progress_status],["blocked_status",e.blocked_status],["close_status",e.close_status],["canceled_status",e.canceled_status]].filter(([,r])=>r!==void 0&&A(r)===t).map(([r])=>r)}async function Hf(e,t,n){let r=D(process.cwd(),n.path);await _e(r);let o=await O(r),i=K(o.schema),a=ne(r,i.files.types,Y.types),s=[],c=V(t.author,o.author_default),d=ae(o),l=await Q(r,Ot,o.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,o.locks.wait_ms),p;try{let u=await q(a),f;try{f=ie(u)}catch(y){throw new h(y instanceof Error?y.message:String(y),g.GENERIC_FAILURE)}try{p=Rr(f,e)}catch(y){throw new h(y instanceof Error?y.message:String(y),g.USAGE)}if(p.removed){let y=(p.definition?.name??e??"").trim();if(y.length>0){let w=await Ec(r,o,i,y);w>0&&s.push(`items_using_type:${w}`)}await Ae({pmRoot:r,filePath:a,raw:le(p.file),op:"schema:remove-type",author:c,settings:o}),s.push(...await W({path:a,scope:"project",op:"schema:remove-type"}))}}finally{await l()}return p.removed&&await No(r,s),{action:"remove-type",removed:p.removed,...p.definition?{type:p.definition}:{},file:{path:a,definitions:p.file.definitions.length},warnings:Ie(s),generated_at:I()}}function vn(e,t){return ne(e,t.files.statuses,Y.statuses)}function Ct(e,t){return ne(e,t.files.fields,Y.fields)}function jo(e,t){return ne(e,t.files.types,Y.types)}async function at(e,t,n,r){for(let o of t){let i=dr(o.folder??cr(o.name)),a=xc.join(e,i);await x(a)||(await Sc(a,{recursive:!0}),n.push(...await W({path:a,scope:"project",op:r})))}}function bn(e){return{key:e.key,type:e.type,commands:[...e.commands],cli_flag:`--${e.cli_flag}`,cli_aliases:e.cli_aliases.map(t=>`--${t}`),...e.description?{description:e.description}:{},required:e.required,required_on_create:e.required_on_create,allow_unset:e.allow_unset,required_types:[...e.required_types]}}function Ic(e){if(e)return{id:e.id,...e.roles.length>0?{roles:[...e.roles]}:{},...e.aliases.length>0?{aliases:[...e.aliases]}:{},...e.description?{description:e.description}:{},...typeof e.order=="number"?{order:e.order}:{}}}function Tc(e){let t=new Map;for(let n of e){let r=A(n.id);if(r.length!==0){t.set(r,r);for(let o of Array.isArray(n.aliases)?n.aliases:[]){let i=A(o);i.length>0&&!t.has(i)&&t.set(i,r)}}}return t}async function Kf(e,t,n){let r=D(process.cwd(),n.path);await _e(r);let o;try{o=wo({id:e,roles:t.role,aliases:t.alias,description:t.description,order:t.order})}catch(m){throw new h(m instanceof Error?m.message:String(m),g.USAGE)}let i=await O(r),a=K(i.schema),s=vn(r,a),c=tt(a);try{gn(o,c.alias_to_id)}catch(m){throw new h(m instanceof Error?m.message:String(m),g.USAGE)}let d=Ic(c.by_id.get(o.id));if((o.roles??d?.roles??[]).length===0)throw new h(`Status "${o.id}" requires at least one lifecycle role. Re-run with --role active, --role blocked, --role draft, or an appropriate terminal/default role.`,g.USAGE,{code:"status_lifecycle_role_required",examples:[`pm schema add-status "${Oe(o.id)}" --role active`,`pm schema add-status "${Oe(o.id)}" --role blocked`]});let p=[],u=V(t.author,i.author_default),f=ae(i),y=await Q(r,Ro,i.locks.ttl_seconds,u,!!t.force,f.force_required_for_stale_lock,i.locks.wait_ms),w;try{let m=await q(s),_;try{_=He(m)}catch(k){throw new h(k instanceof Error?k.message:String(k),g.GENERIC_FAILURE)}let v=Tc(_.statuses);try{gn(o,v)}catch(k){throw new h(k instanceof Error?k.message:String(k),g.USAGE)}w=vo(_,o,d),await Ae({pmRoot:r,filePath:s,raw:Ke(w.file),op:"schema:add-status",author:u,settings:i}),p.push(...await W({path:s,scope:"project",op:"schema:add-status"}))}finally{await y()}return{action:"add-status",registered:!0,replaced:w.replaced,status:w.definition,file:{path:s,statuses:w.file.statuses.length},warnings:Ie(p),generated_at:I()}}async function Vf(e,t,n){let r=D(process.cwd(),n.path);await _e(r);let o=await O(r),i=K(o.schema),a=vn(r,i),s=[],c=V(t.author,o.author_default),d=ae(o),l=await Q(r,Ro,o.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,o.locks.wait_ms),p;try{let u=await q(a),f;try{f=He(u)}catch(y){throw new h(y instanceof Error?y.message:String(y),g.GENERIC_FAILURE)}try{p=bo(f,e)}catch(y){throw new h(y instanceof Error?y.message:String(y),g.USAGE)}if(p.removed){let y=A(p.definition?.id??e);await Ac(s,r,o,i,y),await Ae({pmRoot:r,filePath:a,raw:Ke(p.file),op:"schema:remove-status",author:c,settings:o}),s.push(...await W({path:a,scope:"project",op:"schema:remove-status"}))}}finally{await l()}return{action:"remove-status",removed:p.removed,...p.definition?{status:p.definition}:{},file:{path:a,statuses:p.file.statuses.length},warnings:Ie(s),generated_at:I()}}function Lo(e){return{name:e.name,folder:e.folder,aliases:Array.isArray(e.aliases)?[...e.aliases]:[],...e.default_status?{default_status:e.default_status}:{},...e.description?{description:e.description}:{}}}function Oc(e,t,n){return{...Lo(e),source:t,...n?{extension:n}:{},required_create_fields:[...e.required_create_fields],required_create_repeatables:[...e.required_create_repeatables],options:structuredClone(e.options),command_option_policies:structuredClone(e.command_option_policies)}}function Fo(e){return{id:e.id,source:Pe.has(e.id)?"builtin":"custom",roles:Array.isArray(e.roles)?[...e.roles]:[],aliases:Array.isArray(e.aliases)?[...e.aliases]:[],...e.description?{description:e.description}:{},...typeof e.order=="number"?{order:e.order}:{}}}function Mo(e,t,n){let r=e.toLowerCase();return n.has(r)?"extension":t.has(r)?"custom":"builtin"}function Cc(){let e=new Map,t=H();for(let n of t?.item_types??[]){let r=n.types;if(Array.isArray(r))for(let o of r){if(typeof o!="object"||o===null||Array.isArray(o))continue;let i=o.name;typeof i=="string"&&i.trim().length>0&&e.set(i.trim().toLowerCase(),{layer:n.layer,name:n.name})}}return e}function Rc(e){let t=tt(e),n=[],r=[];for(let o of t.definitions){let i=Fo(o);i.source==="builtin"?n.push(i):r.push(i)}return{builtin:n,custom:r}}async function st(e){let t=D(process.cwd(),e.path);await _e(t);let n=await O(t),r=K(n.schema),o=ne(t,r.files.types,Y.types),i=vn(t,r),a=B(n,H()),s=Cc(),c=new Set((n.item_types?.definitions??[]).map(d=>d.name.trim().toLowerCase()).filter(d=>d.length>0&&!s.has(d)));return{pmRoot:t,typesPath:o,statusesPath:i,byType:a.by_type,customNames:c,extensionProvenance:s,schema:r}}async function Yf(e){let t=await st(e),n=[],r=[],o=[];for(let s of Object.values(t.byType).sort((c,d)=>c.name.localeCompare(d.name))){let c=Mo(s.name,t.customNames,new Set(t.extensionProvenance.keys())),d=Lo(s);c==="extension"?o.push(d):c==="custom"?r.push(d):n.push(d)}let i=Rc(t.schema),a=xt(t.schema).definitions.map(bn);return{action:"list",builtin:n,custom:r,extension:o,counts:{builtin:n.length,custom:r.length,extension:o.length,total:n.length+r.length+o.length},statuses:{builtin:i.builtin,custom:i.custom,counts:{builtin:i.builtin.length,custom:i.custom.length,total:i.builtin.length+i.custom.length}},fields:{custom:a,counts:{total:a.length}},file:{path:t.typesPath},generated_at:I()}}async function Xf(e,t){let n=(e??"").trim();if(n.length===0)throw new h("Type name must not be empty.",g.USAGE);let r=await st(t),o=Object.values(r.byType).find(i=>i.name.toLowerCase()===n.toLowerCase()||i.aliases.some(a=>a.toLowerCase()===n.toLowerCase()));if(!o)throw new h(`Unknown item type "${n}". Run pm schema list to inspect registered types, or pm schema add-type "${Oe(n)}" to register it.`,g.NOT_FOUND,{code:"unknown_item_type"});return{action:"show",type:Oc(o,Mo(o.name,r.customNames,new Set(r.extensionProvenance.keys())),r.extensionProvenance.get(o.name.toLowerCase())),file:{path:r.typesPath},generated_at:I()}}async function Qf(e,t){let n=A(e);if(n.length===0)throw new h("Status id must not be empty.",g.USAGE);let r=await st(t),o=tt(r.schema),i=o.alias_to_id.get(n)??n,a=o.by_id.get(i);if(!a)throw new h(`Unknown status "${e}". Run pm schema list to inspect registered statuses, or pm schema add-status "${Oe(e??"")}" to register it.`,g.NOT_FOUND,{code:"unknown_status"});return{action:"show-status",status:Fo(a),file:{path:r.statusesPath},generated_at:I()}}async function Zf(e,t,n){let r=D(process.cwd(),n.path);await _e(r);let o;try{o=go({key:e,type:t.type,commands:t.commands,description:t.description,cliFlag:t.cliFlag,aliases:t.alias,required:t.required,requiredOnCreate:t.requiredOnCreate,allowUnset:t.allowUnset,requiredTypes:t.requiredTypes})}catch(y){throw new h(y instanceof Error?y.message:String(y),g.USAGE)}let i=await O(r),a=K(i.schema),s=Ct(r,a),c=[],d=Et(o.key);d&&c.push(`custom_field_mcp_input_collision:${d.field}:${d.property}:${d.owner}:use=${d.nested_path}`);let l=V(t.author,i.author_default),p=ae(i),u=await Q(r,Po,i.locks.ttl_seconds,l,!!t.force,p.force_required_for_stale_lock,i.locks.wait_ms),f;try{let y=await q(s),w;try{w=Be(y)}catch(m){throw new h(m instanceof Error?m.message:String(m),g.GENERIC_FAILURE)}f=yo(w,o),await Ae({pmRoot:r,filePath:s,raw:We(f.file),op:"schema:add-field",author:l,settings:i}),c.push(...await W({path:s,scope:"project",op:"schema:add-field"}))}finally{await u()}return{action:"add-field",registered:!0,replaced:f.replaced,field:f.definition,file:{path:s,fields:f.file.fields.length},warnings:Ie(c),generated_at:I()}}async function Pc(e,t,n,r){let o=B(t,H());return(await Ce(e,t.item_format,o.type_to_folder,[],n)).filter(a=>{let s=a[r];return s==null?!1:Array.isArray(s)?s.length>0:typeof s=="string"?s.trim().length>0:!0}).length}async function eh(e,t,n){let r=D(process.cwd(),n.path);await _e(r);let o=await O(r),i=K(o.schema),a=Ct(r,i),s=[],c=V(t.author,o.author_default),d=ae(o),l=await Q(r,Po,o.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,o.locks.wait_ms),p;try{let u=await q(a),f;try{f=Be(u)}catch(y){throw new h(y instanceof Error?y.message:String(y),g.GENERIC_FAILURE)}try{p=_o(f,e)}catch(y){throw new h(y instanceof Error?y.message:String(y),g.USAGE)}if(p.removed){let y=A(p.definition?.key??e),w=A(p.definition?.metadata_key??p.definition?.front_matter_key??y);if(w.length>0){let m=await Pc(r,o,i,w);m>0&&s.push(`items_using_field:${m}`)}await Ae({pmRoot:r,filePath:a,raw:We(p.file),op:"schema:remove-field",author:c,settings:o}),s.push(...await W({path:a,scope:"project",op:"schema:remove-field"}))}}finally{await l()}return{action:"remove-field",removed:p.removed,...p.definition?{field:p.definition}:{},file:{path:a,fields:p.file.fields.length},warnings:Ie(s),generated_at:I()}}async function th(e){let t=await st(e),n=xt(t.schema).definitions.map(bn);return{action:"list-fields",fields:n,counts:{total:n.length},file:{path:Ct(t.pmRoot,t.schema)},generated_at:I()}}async function nh(e,t){let n=A(e);if(n.length===0)throw new h("Field key must not be empty.",g.USAGE);let r=await st(t),o=xt(r.schema).by_key.get(n);if(!o)throw new h(`Unknown custom field "${e}". Run pm schema list-fields to inspect registered fields, or pm schema add-field "${Oe(e??"")}" to register it.`,g.NOT_FOUND,{code:"unknown_field"});return{action:"show-field",field:bn(o),file:{path:Ct(r.pmRoot,r.schema)},generated_at:I()}}async function rh(e,t,n){let r=D(process.cwd(),n.path);await _e(r);let o;try{let w=Tt(e);if(w===void 0)throw new Error(`Type preset name is required. Allowed: ${ot.join(", ")}.`);o=w}catch(w){throw new h(w instanceof Error?w.message:String(w),g.USAGE)}let i=await O(r),a=K(i.schema),s=jo(r,a),c=[],d=V(t.author,i.author_default),l=ae(i),p=[],u=[],f,y=await Q(r,Ot,i.locks.ttl_seconds,d,!!t.force,l.force_required_for_stale_lock,i.locks.wait_ms);try{let w=await q(s),m;try{m=ie(w)}catch(v){throw new h(v instanceof Error?v.message:String(v),g.GENERIC_FAILURE)}let _=m;for(let v of it(o)){let k=Ue(_,v);_=k.file,(k.replaced?u:p).push(k.definition.name)}f=_.definitions.length,await Ae({pmRoot:r,filePath:s,raw:le(_),op:"schema:apply-preset",author:d,settings:i}),await at(r,it(o),c,"schema:apply-preset-folder"),c.push(...await W({path:s,scope:"project",op:"schema:apply-preset"}))}finally{await y()}return{action:"apply-preset",preset:o,registered:p,replaced:u,file:{path:s,definitions:f},warnings:Ie(c),generated_at:I()}}function Nc(e){if(e===void 0)return 10;if(!Number.isInteger(e)||e<1)throw new h("--min-count must be a positive integer (>= 1).",g.USAGE);return e}async function oh(e,t){let n=D(process.cwd(),t.path);await _e(n);let r=await O(n),o=K(r.schema),i=jo(n,o),a=Nc(e.minCount),s=B(r,H()),d=(await Ce(n,r.item_format,s.type_to_folder,[],o)).map(k=>typeof k.title=="string"?k.title:""),l=Co(d,{minCount:a}),p=[],u=[],f=[],y=[],w;if(!e.apply){let k;try{k=ie(await q(i))}catch(S){throw new h(S instanceof Error?S.message:String(S),g.GENERIC_FAILURE)}return w=k.definitions.length,{action:"infer-types",applied:!1,min_count:a,candidates:l,registered:u,replaced:f,skipped:y,file:{path:i,definitions:w},warnings:p,generated_at:I()}}let m=V(e.author,r.author_default),_=ae(r),v=await Q(n,Ot,r.locks.ttl_seconds,m,!!e.force,_.force_required_for_stale_lock,r.locks.wait_ms);try{let k=await q(i),S;try{S=ie(k)}catch(G){throw new h(G instanceof Error?G.message:String(G),g.GENERIC_FAILURE)}let C=S;for(let G of l){if(G.shadows_builtin){y.push({name:G.name,reason:"shadows_builtin"});continue}let M;try{M=nt({name:G.name})}catch{y.push({name:G.name,reason:"invalid_type_token"});continue}let ce=Ue(C,M);C=ce.file,(ce.replaced?f:u).push(ce.definition.name)}w=C.definitions.length,await Ae({pmRoot:n,filePath:i,raw:le(C),op:"schema:infer-types",author:m,settings:r}),await at(n,C.definitions.filter(G=>u.includes(G.name)||f.includes(G.name)),p,"schema:infer-types-folder"),p.push(...await W({path:i,scope:"project",op:"schema:infer-types"}))}finally{await v()}return{action:"infer-types",applied:!0,min_count:a,candidates:l,registered:u,replaced:f,skipped:y,file:{path:i,definitions:w},warnings:Ie(p),generated_at:I()}}function ih(e){let t=e.replaced?"Updated":"Registered",n=e.type.aliases&&e.type.aliases.length>0?` (aliases: ${e.type.aliases.join(", ")})`:"";return`${t} custom item type "${e.type.name}"${n} in ${e.file.path}. Run: pm create "${Oe(e.type.name)}" "<title>"`}function ah(e){return e.removed?`Removed custom item type "${e.type?.name??"(unknown)"}" from ${e.file.path}.`:`No custom item type matched; nothing removed from ${e.file.path}.`}function sh(e){let t=e.replaced?"Updated":"Registered",n=e.status.roles&&e.status.roles.length>0?` (roles: ${e.status.roles.join(", ")})`:"",r=e.status.aliases&&e.status.aliases.length>0?` (aliases: ${e.status.aliases.join(", ")})`:"";return`${t} status "${e.status.id}"${n}${r} in ${e.file.path}.`}function ch(e){return e.removed?`Removed custom status "${e.status?.id??"(unknown)"}" from ${e.file.path}.`:`No custom status matched; nothing removed from ${e.file.path}.`}function dh(e){let t=[`Schema types: ${e.counts.total} total (${e.counts.builtin} builtin, ${e.counts.custom} custom, ${e.counts.extension} extension)`];for(let[n,r]of[["builtin",e.builtin],["custom",e.custom],["extension",e.extension]])r.length!==0&&t.push(`${n}: ${r.map(o=>o.name).join(", ")}`);t.push(`statuses: ${e.statuses.counts.total} total (${e.statuses.counts.builtin} builtin, ${e.statuses.counts.custom} custom)`);for(let[n,r]of[["builtin statuses",e.statuses.builtin],["custom statuses",e.statuses.custom]])r.length!==0&&t.push(`${n}: ${r.map(o=>o.id).join(", ")}`);return t.push(`custom fields: ${e.fields.counts.total} total`),e.fields.custom.length>0&&t.push(`fields: ${e.fields.custom.map(n=>`${n.key} (${n.type}, ${n.cli_flag})`).join(", ")}`),t.push("Inspect one: pm schema show <Type>"),t.push("Inspect one status: pm schema show-status <status>"),t.push("Inspect one field: pm schema show-field <key>"),t.join(`
|
|
17
|
-
`)}function lh(e){let t=[`type: ${e.type.name}`,`source: ${e.type.source}`,`folder: ${e.type.folder}`];return e.type.default_status&&t.push(`default_status: ${e.type.default_status}`),e.type.aliases.length>0&&t.push(`aliases: ${e.type.aliases.join(", ")}`),e.type.description&&t.push(`description: ${e.type.description}`),e.type.options.length>0&&t.push(`options: ${e.type.options.map(n=>n.key).join(", ")}`),t.join(`
|
|
18
|
-
`)}function ph(e){let t=[`status: ${e.status.id}`,`source: ${e.status.source}`];return e.status.roles.length>0&&t.push(`roles: ${e.status.roles.join(", ")}`),e.status.aliases.length>0&&t.push(`aliases: ${e.status.aliases.join(", ")}`),e.status.description&&t.push(`description: ${e.status.description}`),typeof e.status.order=="number"&&t.push(`order: ${e.status.order}`),t.join(`
|
|
19
|
-
`)}function Dc(e){let t=[];e.required&&t.push("required"),e.required_on_create&&t.push("required_on_create"),e.allow_unset||t.push("no_unset");let n=t.length>0?` [${t.join(", ")}]`:"";return`${e.key} (${e.type}) ${e.cli_flag} commands=${e.commands.join("/")}${n}`}function uh(e){return`${e.replaced?"Updated":"Registered"} custom field "${e.field.key}" in ${e.file.path}. Use it: pm create "<title>" --${(e.field.cli_flag??e.field.key).replaceAll("_","-")} <value>`}function mh(e){return e.removed?`Removed custom field "${e.field?.key??"(unknown)"}" from ${e.file.path}.`:`No custom field matched; nothing removed from ${e.file.path}.`}function fh(e){let t=[`Custom fields: ${e.counts.total} total`];for(let n of e.fields)t.push(` ${Dc(n)}`);return t.push("Inspect one: pm schema show-field <key>"),t.join(`
|
|
20
|
-
`)}function hh(e){let t=e.field,n=[`field: ${t.key}`,`type: ${t.type}`,`cli_flag: ${t.cli_flag}`,`commands: ${t.commands.join(", ")}`];return t.cli_aliases.length>0&&n.push(`cli_aliases: ${t.cli_aliases.join(", ")}`),t.description&&n.push(`description: ${t.description}`),t.required&&n.push("required: true"),t.required_on_create&&n.push("required_on_create: true"),t.allow_unset||n.push("allow_unset: false"),t.required_types.length>0&&n.push(`required_types: ${t.required_types.join(", ")}`),n.join(`
|
|
21
|
-
`)}function gh(e){let t=e.registered.length>0?`registered: ${e.registered.join(", ")}`:"",n=e.replaced.length>0?`updated: ${e.replaced.join(", ")}`:"",r=[t,n].filter(o=>o.length>0).join("; ");return`Applied "${e.preset}" type preset to ${e.file.path}${r.length>0?` (${r})`:""}.`}function yh(e){if(e.candidates.length===0)return`No title-prefix conventions found with at least ${e.min_count} items. Lower the threshold with --min-count <n>.`;let t=e.applied?[`Inferred and registered custom types from title prefixes (min-count ${e.min_count}):`]:[`Inferred custom type candidates from title prefixes (min-count ${e.min_count}, dry-run):`];for(let n of e.candidates){let r=n.shadows_builtin?" [shadows built-in, skipped]":"";t.push(` ${n.name} <- "${n.prefix}" (${n.count} items)${r}`)}return e.applied?(e.registered.length>0&&t.push(`registered: ${e.registered.join(", ")}`),e.replaced.length>0&&t.push(`updated: ${e.replaced.join(", ")}`)):t.push("Re-run with --apply to register the non-shadowing candidates."),t.join(`
|
|
22
|
-
`)}var _h={workflowSlotsReferencing:Do};import zo from"node:fs/promises";import De 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]="6fc24a7c-a359-51fd-a432-4c8037d10e9e")}catch{}})();var Rt=["extensions","docs","examples","assets","prompts"],jc=Object.freeze({extensions:Object.freeze([".agents/pm/extensions","extensions",".custom/pm-extensions",".custom/pm-extension"]),docs:Object.freeze(["docs","documentation"]),examples:Object.freeze(["examples","docs/examples"]),assets:Object.freeze(["assets",".agents/pm/assets"]),prompts:Object.freeze(["prompts",".agents/pm/prompts"])});function Lc(e){return Rt.includes(e)}function Fc(e,t){if(t==null)return[];let n=Array.isArray(t)?t:[t],r=[];for(let o of n){if(typeof o!="string"||o.trim().length===0)throw new h(`Package manifest field pm.${e} must contain string paths.`,g.USAGE);r.push(o.trim())}return[...new Set(r)].sort((o,i)=>o.localeCompare(i))}function Mc(e){if(e==null)return{};if(typeof e!="object"||Array.isArray(e))throw new h("Package manifest field pm must be an object.",g.USAGE);let t={},n=e;for(let[r,o]of Object.entries(n)){if(!Lc(r))continue;let i=Fc(r,o);i.length>0&&(t[r]=i)}return t}function ue(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n.trim():void 0}function kn(e){if(!Array.isArray(e))return;let t=e.map(n=>typeof n=="string"?n.trim():"").filter(n=>n.length>0);return t.length>0?[...new Set(t)].sort((n,r)=>n.localeCompare(r)):void 0}function Go(e){if(typeof e=="string"&&e.trim().length>0)return e.trim();if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let t=e.url;return typeof t=="string"&&t.trim().length>0?t.trim():void 0}}function Gc(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={docs:ue(t,"docs"),npm:ue(t,"npm"),repository:ue(t,"repository"),report:ue(t,"report")};return Object.values(n).some(r=>typeof r=="string")?n:void 0}function Uc(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={image:ue(t,"image"),video:ue(t,"video")};return Object.values(n).some(r=>typeof r=="string")?n:void 0}function zc(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={display_name:ue(t,"display_name")??ue(t,"displayName"),category:ue(t,"category"),summary:ue(t,"summary"),links:Gc(t.links),media:Uc(t.media),tags:kn(t.tags)};return Object.values(n).some(r=>r!==void 0)?n:void 0}async function ct(e){let t=De.join(e,"package.json");if(!await x(t))return{source:"convention",resources:{}};let n;try{n=JSON.parse(await zo.readFile(t,"utf8"))}catch(s){throw new h(`Failed to parse package manifest at "${t}": ${String(s)}`,g.USAGE)}if(typeof n!="object"||n===null||Array.isArray(n))throw new h(`Package manifest at "${t}" must be a JSON object.`,g.USAGE);let r=n,o=r.pm,i=o!=null,a=typeof o=="object"&&o!==null&&!Array.isArray(o)?o:{};return{source:i?"pm":"convention",package_json_path:t,package_name:typeof r.name=="string"?r.name:void 0,package_version:typeof r.version=="string"?r.version:void 0,package_private:r.private===!0,package_description:typeof r.description=="string"?r.description:void 0,package_keywords:kn(r.keywords),package_homepage:typeof r.homepage=="string"?r.homepage:void 0,package_repository_url:Go(r.repository),package_bugs_url:Go(r.bugs),aliases:kn(a.aliases),resources:Mc(o),catalog:zc(a.catalog)}}async function Uo(e){if(!await x(e))return[];let t=await zo.readdir(e,{withFileTypes:!0}),n=[];for(let r of t){if(!r.isDirectory())continue;let o=De.join(e,r.name);await x(De.join(o,"manifest.json"))&&n.push(o)}return n.sort((r,o)=>r.localeCompare(o))}async function Pt(e){if(await x(De.join(e,"manifest.json")))return[e];let n=(await ct(e)).resources.extensions??[],r=new Set;for(let o of n){if(o.includes("*")||o.startsWith("!"))throw new h(`Package extension entry "${o}" uses a glob/exclusion pattern. pm package installs currently require concrete extension paths or directories.`,g.USAGE);let i=De.resolve(e,o);if(!te(e,i))throw new h(`Package extension entry "${o}" resolves outside package root.`,g.USAGE);if(await x(De.join(i,"manifest.json"))){r.add(i);continue}for(let a of await Uo(i))r.add(a)}if(n.length===0)for(let o of jc.extensions)for(let i of await Uo(De.join(e,o)))r.add(i);return[...r].sort((o,i)=>o.localeCompare(i))}import{execFile as dd}from"node:child_process";import R from"node:fs/promises";import Cn from"node:os";import E from"node:path";import{fileURLToPath as ld}from"node:url";import{promisify as pd}from"node:util";import ud from"npm-package-arg";import{extract as md,list as fd}from"tar";import Zc from"node:fs/promises";import se from"node:path";import Jo from"node:fs/promises";import xn 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]="af718efb-d1cf-5adc-9518-c858627e1b54")}catch{}})();function Z(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function b(e){return e.trim().toLowerCase()}function Nt(e){let t=e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-"),n=0;for(;t[n]==="-";)n+=1;let r=t.length;for(;r>n&&t[r-1]==="-";)r-=1;let o=t.slice(n,r);if(o.length===0)throw new h("Extension manifest name must resolve to a non-empty directory name.",g.USAGE);if(o==="."||o==="..")throw new h('Extension manifest name must not resolve to "." or "..".',g.USAGE);return o}function Sn(e){return _r(e)}async function Jc(e){try{let t=JSON.parse(await Jo.readFile(xn.join(e,"package.json"),"utf8")),n=typeof t.name=="string"&&/^(?:@[a-z0-9._~-]+\/)?[a-z0-9._~-]+$/iu.test(t.name)?t.name:void 0;return{...n?{package_name:n}:{},has_build_script:["build","prepare","prepack"].some(r=>typeof t.scripts?.[r]=="string")}}catch{return{has_build_script:!1}}}async function qc(e,t,n){if(n.source_kind!=="github"||typeof n.source_root!="string")return new h(`Extension entry file is missing at "${t}".`,g.USAGE);let r=await Jc(n.source_root),o=r.package_name?`pm install npm:${r.package_name}`:void 0,i=n.source_input??n.source_root;return new h(`Extension entry "${e.entry}" is absent from GitHub source "${i}". pm install copies GitHub repositories without running package scripts${r.has_build_script?", and this package declares a build or publish script":""}. ${o?`Try "${o}" if the package is published, or install a locally built directory.`:"Build the source locally and install that directory, or use its published npm: package."}`,g.USAGE,{code:"github_source_entry_unbuilt",required:"Use a GitHub tree with committed runtime output, a published npm artifact, or a locally built source directory.",why:"GitHub installation is a source copy and never executes untrusted package build scripts.",examples:o?[o,`pm install ${n.source_root}`]:[`pm install ${n.source_root}`],nextSteps:o?[`Retry with ${o}.`,"Or build the repository locally, then install its directory."]:["Build the repository locally, then install its directory.","If it is published, retry with pm install npm:<package-name>."],recovery:{attempted_command:`pm install ${i}`,normalized_args:["install",i],...o?{next_best_command:o}:{}}})}async function Qe(e,t={}){let n=xn.join(e,"manifest.json");if(!await x(n))throw new h(`Extension manifest is missing at "${n}".`,g.USAGE);let r;try{r=JSON.parse(await Jo.readFile(n,"utf8"))}catch(a){throw new h(`Failed to parse extension manifest at "${n}": ${Bc(a)}`,g.USAGE)}let o=Sn(r);if(!o)throw new h(`Extension manifest at "${n}" is invalid.`,g.USAGE);let i=xn.resolve(e,o.entry);if(!te(e,i))throw new h(`Extension entry "${o.entry}" resolves outside extension directory "${e}".`,g.USAGE);if(!await x(i))throw await qc(o,i,t);if(!await wr(e,i))throw new h(`Extension entry "${o.entry}" resolves outside extension directory after symlink resolution.`,g.USAGE);return{directory:e,manifest_path:n,entry_path:i,manifest:o}}function Bc(e){return e instanceof Error?e.message:String(e)}import En from"node:fs/promises";import Wc 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]="159d7bbd-1d2a-503d-b3ce-f32dcc6f6547")}catch{}})();var Hc=".managed-extensions.json",Dt=1;function dt(e){return Wc.join(e,Hc)}function Kc(){return{version:Dt,updated_at:I(),entries:[]}}function lt(e){return[...e].sort((t,n)=>{let r=t.scope.localeCompare(n.scope);if(r!==0)return r;let o=t.name.localeCompare(n.name);return o!==0?o:t.directory.localeCompare(n.directory)})}function qo(e,t){return e.kind!==t.kind||e.input!==t.input||e.location!==t.location?!1:e.kind==="npm"&&t.kind==="npm"?e.package===t.package&&e.version===t.version:e.kind==="github"&&t.kind==="github"?e.repository===t.repository&&e.ref===t.ref&&e.subpath===t.subpath&&e.commit===t.commit:e.kind==="builtin"&&t.kind==="builtin"?e.name===t.name:!0}function ee(e){return typeof e=="string"?e:void 0}function Vc(e){return typeof e.name=="string"&&e.name.trim().length>0&&typeof e.directory=="string"&&e.directory.trim().length>0&&(e.scope==="project"||e.scope==="global")&&typeof e.manifest_version=="string"&&typeof e.manifest_entry=="string"&&Array.isArray(e.capabilities)&&e.capabilities.every(t=>typeof t=="string")&&typeof e.installed_at=="string"&&typeof e.updated_at=="string"}function Yc(e){if(typeof e!="object"||e===null)return null;let t=e;return t.kind!=="local"&&t.kind!=="github"&&t.kind!=="npm"&&t.kind!=="builtin"||typeof t.input!="string"||typeof t.location!="string"?null:{kind:t.kind,input:t.input,location:t.location,name:ee(t.name),package:ee(t.package),version:ee(t.version),repository:ee(t.repository),owner:ee(t.owner),repo:ee(t.repo),ref:ee(t.ref),subpath:ee(t.subpath),commit:ee(t.commit)}}function Xc(e){if(typeof e!="object"||e===null)return null;let t=e;if(!Vc(t))return null;let n=Yc(t.source);if(!n)return null;let r=hr(t.contributions);return r===null?null:{name:t.name.trim(),directory:t.directory.trim(),scope:t.scope,manifest_version:t.manifest_version,manifest_entry:t.manifest_entry,capabilities:Z(t.capabilities),contributions:r,installed_at:t.installed_at,updated_at:t.updated_at,source:n,last_update_check_at:ee(t.last_update_check_at),last_update_remote_commit:ee(t.last_update_remote_commit),update_available:typeof t.update_available=="boolean"||t.update_available===null?t.update_available:void 0,update_error:ee(t.update_error)}}function Qc(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.version!==Dt||!Array.isArray(t.entries))return null;let n=[];for(let r of t.entries){let o=Xc(r);o&&n.push(o)}return{version:Dt,updated_at:ee(t.updated_at)??I(),entries:lt(n)}}async function we(e){let t=dt(e),n=Kc();try{let r=await En.readFile(t,"utf8"),o=JSON.parse(r),i=Qc(o);if(!i)throw new h(`Managed extension state file "${t}" has an invalid schema. Repair or remove it before mutating extension state.`,g.GENERIC_FAILURE);return{path:t,state:i,warnings:[]}}catch(r){if(r instanceof h)throw r;if(typeof r=="object"&&r!==null&&"code"in r&&oe(r))return{path:t,state:n,warnings:[]};throw new h(`Managed extension state file "${t}" could not be read. Repair or remove it before mutating extension state.`,g.GENERIC_FAILURE)}}async function je(e,t){let n=dt(e),r={version:Dt,updated_at:I(),entries:lt(t.entries)};await En.mkdir(e,{recursive:!0}),await En.writeFile(n,`${JSON.stringify(r,null,2)}
|
|
23
|
-
`,"utf8")}function pt(e,t){let n=e.entries.filter(r=>b(r.name)!==b(t.name)&&b(r.directory)!==b(t.directory));return n.push(t),{...e,updated_at:I(),entries:lt(n)}}async function Bo(e,t,n,r){let o=t.entries.find(a=>b(a.name)===b(n));if(!o)return t;let i=pt(t,{...o,contributions:r});return await je(e,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]="259656b0-09b7-52c5-8f54-52ac29eec607")}catch{}})();var ed="PM_CLI_PACKAGE_ROOT",Wo={beads:{package_directory:"pm-beads",legacy_extension_directory:"beads"},todos:{package_directory:"pm-todos",legacy_extension_directory:"todos"}},td=new Set(["*","all"]);function $n(){let e=[],t=process.env[ed];return typeof t=="string"&&t.trim().length>0&&e.push(se.resolve(t.trim())),e.push(de(import.meta.url,["../../.."])),[...new Set(e)]}async function ut(e){let t=e.trim().toLowerCase(),n=await Ko(t);if(n)return n;let r=Wo[t];if(!r)return null;for(let o of $n()){let i=se.join(o,".agents","pm","extensions",r.legacy_extension_directory);if(await x(se.join(i,"manifest.json")))return i}return null}function Ho(e){return td.has(e.trim().toLowerCase())}function nd(e){return e.replace(/^pm-/i,"").trim().toLowerCase()}async function rd(e,t){let n=await Zc.readdir(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||!r.name.startsWith("pm-"))continue;let o=se.join(e,r.name);if(!await x(se.join(o,"package.json")))continue;let i=await ct(o),a=i.aliases&&i.aliases.length>0?i.aliases:[nd(r.name)];for(let s of a){let c=s.trim().toLowerCase();c.length===0||t.has(c)||t.set(c,{alias:c,package_directory:r.name,package_root:o,package_name:i.package_name??null})}}}async function An(){let e=new Map;for(let t of $n()){let n=se.join(t,"packages");await x(n)&&await rd(n,e)}for(let[t,n]of Object.entries(Wo))if(!e.has(t))for(let r of $n()){let o=se.join(r,"packages",n.package_directory);if(await x(se.join(o,"package.json"))){e.set(t,{alias:t,package_directory:n.package_directory,package_root:o,package_name:null});break}}return[...e.values()].sort((t,n)=>t.alias.localeCompare(n.alias))}async function jt(){return(await An()).map(e=>e.alias)}async function Ko(e){let t=e.trim().toLowerCase();return(await An()).find(r=>r.alias===t||r.package_directory.toLowerCase()===t||r.package_name?.toLowerCase()===t)?.package_root??null}async function Vo(e){let t=await Ko(e);return t?(await ct(t)).package_name??null:null}async function Yo(e){let t=await ut(e);if(!t)return null;try{let n=await Pt(t);return n.length!==1?null:(await Qe(n[0])).manifest.name}catch{return null}}function od(e){return{docs:e.catalog?.links?.docs??e.package_homepage,npm:e.catalog?.links?.npm??(e.package_name&&e.package_private!==!0?`https://www.npmjs.com/package/${encodeURIComponent(e.package_name)}`:void 0),repository:e.catalog?.links?.repository??e.package_repository_url,report:e.catalog?.links?.report??e.package_bugs_url}}function id(e,t,n,r,o,i){let a=r==="global"?"--global":"--project",s=Object.fromEntries(Rt.filter(c=>c!=="extensions").map(c=>[c,e.resources[c]??[]]).filter(([,c])=>Array.isArray(c)&&c.length>0));return{alias:t.alias,aliases:n,bundled:!0,available:!0,installed:n.some(c=>o.has(c))||i.has(se.resolve(t.package_root)),install_target:t.alias,install_command:`pm install ${t.alias} ${a}`,package_name:e.package_name,package_version:e.package_version,description:e.catalog?.summary??e.package_description,keywords:e.package_keywords??[],resources:e.resources,installable_resources:{extensions:e.resources.extensions??[]},metadata_only_resources:s,catalog:{display_name:e.catalog?.display_name,category:e.catalog?.category,tags:e.catalog?.tags??e.package_keywords??[],links:od(e),media:e.catalog?.media}}}async function Xo(e,t,n={}){let r=bt(D(process.cwd(),t.path),process.cwd()),o=e==="global"?r.global:r.project,i=await we(o),a=new Set(i.state.entries.filter(u=>u.scope===e).filter(u=>u.source.kind!=="builtin").map(u=>se.resolve(u.source.location))),s=new Set(i.state.entries.filter(u=>u.scope===e&&u.source.kind==="builtin").flatMap(u=>[u.source.name,u.source.input,u.source.location]).filter(u=>typeof u=="string"&&u.trim().length>0).map(u=>u.trim().toLowerCase())),c=[],d=new Map;for(let u of await An()){let f=se.resolve(u.package_root),y=d.get(f)??[];y.push(u),d.set(f,y)}for(let u of d.values()){let f=u[0],y=u.map(m=>m.alias).sort((m,_)=>m.localeCompare(_)),w=await ct(f.package_root);c.push(id(w,f,y,e,s,a))}let l=sd(n.fields),p=l?c.map(u=>cd(u,l)):c;return{total:p.length,scope:e,installable_resource_kinds:["extensions"],metadata_only_resource_kinds:Rt.filter(u=>u!=="extensions"),packages:p}}var ad=new Set(["alias","aliases","bundled","available","installed","install_target","install_command","package_name","package_version","description","keywords","resources","installable_resources","metadata_only_resources","catalog","category","display_name"]);function sd(e){if(e===void 0)return;let t=Lr(e);if(t.length===0)throw new h("Package catalog --fields requires a comma-separated list of field names",g.USAGE);let n=t.filter(r=>!ad.has(r));if(n.length>0)throw new h(`Unknown package catalog --fields value(s): ${n.join(", ")}`,g.USAGE,{examples:["pm package list --project --fields alias,installed,install_command","pm package catalog --project --fields alias,package_name,category"]});return t}function cd(e,t){let n={};for(let r of t)r==="category"?n[r]=e.catalog?.category??null:r==="display_name"?n[r]=e.catalog?.display_name??null:n[r]=e[r]??null;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]="05f56edb-c08d-570c-b8b5-641fc694331e")}catch{}})();var Zo=pd(dd),Ft="@unbrained/pm-cli",hd={maxArchiveBytes:64*1024*1024,maxEntries:4096,maxExpandedBytes:256*1024*1024,maxEntryBytes:64*1024*1024},In;async function ei(e,t=process.cwd()){let n=e.trim();if(!/^(@[^/\\\s]+\/[^/\\\s]+|[^@/\\\s][^/\\\s]*)$/u.test(n))return null;let r=E.resolve(t);for(;;){let o=E.join(r,"node_modules",...n.split("/")),i=E.join(o,"package.json");if(await x(i))try{let s=JSON.parse(await R.readFile(i,"utf8"));if(s.name===n)return{package:n,...typeof s.version=="string"?{version:s.version}:{},directory:o}}catch{return null}let a=E.dirname(r);if(a===r)return null;r=a}}function Tn(e,t,n){let r=e.split("/").map(d=>d.trim()).filter(d=>d.length>0);if(r.length<2)return null;let o=r[0],i=r[1].replace(/\.git$/i,"");if(o.length===0||i.length===0)return null;let a=r.slice(2),s,c;return a[0]==="tree"&&a.length>=2?(s=a[1],c=a.slice(2).join("/")):a.length>0&&(c=a.join("/")),typeof n=="string"&&n.trim().length>0&&(s=n.trim()),{kind:"github",input:t,owner:o,repo:i,repository:`https://github.com/${o}/${i}.git`,ref:s,subpath:c&&c.length>0?c:void 0}}function gd(e,t,n){let r=e.slice(4).trim();if(r.length===0)throw new h('npm package source must include a package spec after "npm:".',g.USAGE);if(t)throw new h('Options "--gh/--github" cannot be combined with npm: package sources.',g.USAGE);if(n)throw new h('Option "--ref" cannot be combined with npm: package sources.',g.USAGE);return{kind:"npm",input:e,spec:r}}function Mt(e,t={}){let n=e.trim();if(n.length===0)throw new h("Extension source is required for --install.",g.USAGE);let r=typeof t.ref=="string"&&t.ref.trim().length>0?t.ref.trim():void 0;if(n.startsWith("npm:"))return gd(n,t.forceGithub===!0,r);let o=(()=>{try{let a=new URL(n);if(a.hostname!=="github.com")return null;let s=a.pathname.replace(/^\/+/,"");return Tn(s,n,r)}catch{return null}})();if(o)return o;let i=n.startsWith("github.com/")?n.slice(11):null;if(i){let a=Tn(i,n,r);if(!a)throw new h(`Invalid GitHub source "${n}".`,g.USAGE);return a}if(t.forceGithub){let a=Tn(n,n,r);if(!a)throw new h(`Invalid GitHub shorthand "${n}".`,g.USAGE);return a}if(/^https?:\/\//i.test(n))throw new h(`Unsupported extension source URL "${n}". Supported remote source host: github.com.`,g.USAGE);return{kind:"local",input:n,absolute_path:E.resolve(process.cwd(),n)}}async function Lt(e,t=Zo,n){try{return((await t("git",e,{encoding:"utf8",timeout:n})).stdout??"").trim()}catch(r){let o=typeof r=="object"&&r!==null&&"stderr"in r?String(r.stderr):"",i=o.trim().length>0?o.trim():r instanceof Error?r.message:String(r);throw new h(`Git command failed: git ${e.join(" ")}
|
|
24
|
-
${i}`,g.GENERIC_FAILURE)}}function yd(e=process.platform){return e==="win32"?"npm.cmd":"npm"}function _d(e=process.platform){return e==="win32"}async function ti(e,t,n=Zo,r=process.platform,o=process.env){let i=yd(r),a=Object.fromEntries(Object.entries(o).filter(([s])=>s.toLowerCase()!=="npm_config_allow_scripts"));a.NPM_CONFIG_ALLOW_SCRIPTS="";try{return((await n(i,e,{cwd:t,encoding:"utf8",env:a,shell:_d(r)})).stdout??"").trim()}catch(s){let c=typeof s=="object"&&s!==null&&"stderr"in s?String(s.stderr):"",d=c.trim().length>0?c.trim():s instanceof Error?s.message:String(s);throw new h(`npm command failed: ${i} ${e.join(" ")}
|
|
25
|
-
${d}`,g.GENERIC_FAILURE)}}function ni(e){let t=e.trim(),n=t.includes("@file:")?t.slice(0,t.lastIndexOf("@file:")):t;return n.startsWith("@")?n.match(/^(@[^/@\s]+\/[^/@\s]+)/)?.[1]??n:n.match(/^([^/@\s]+)/)?.[1]??n}function ri(e){let t="@file:",n=e.lastIndexOf(t);return n>0&&e.slice(0,n).trim().length>0&&e.slice(n+t.length).trim().length>0}function wd(e){let n=(e instanceof Error?e.message:String(e)).toLowerCase();return n.includes("npm err! code e404")||n.includes("404 not found")||n.includes("is not in this registry")}function vd(e){let n=(e instanceof Error?e.message:String(e)).toLowerCase();return wd(e)||n.includes("not found")}function bd(e){let t=e.trim().toLowerCase();return t.startsWith("@unbrained/pm-")||t.startsWith("pm-")}function kd(e){let t=ni(e),n=bd(t),r=t.replace(/^.*\//,""),o=n?`github.com/unbraind/${r}`:void 0,i=o?`pm install --project ${o}`:void 0;return{message:n?`npm package "${e}" was not found in the registry. If this is an unpublished first-party pm package, install its GitHub repository instead.`:`npm package "${e}" was not found in the registry.`,context:{code:"npm_package_not_found",required:"Use an install source that exists, or publish the npm package before installing it with npm:<name>.",why:"Classifying npm 404s avoids repeated registry retries and gives agents a deterministic fallback path.",examples:i?[i,"pm package catalog --project --json"]:[`npm view ${t}`,"pm package catalog --project --json"],nextSteps:i?[`Try ${i} if the repository exists.`,"Use pm package catalog --project --json to inspect bundled package aliases before installing."]:[`Verify ${t} exists in the npm registry and that you have access to it.`,"Use pm package catalog --project --json to inspect bundled package aliases before installing."],recovery:{attempted_command:`pm install --project npm:${e}`,normalized_args:["install","--project",`npm:${e}`],...o&&i?{fallback_candidates:[{source:o,command:i,reason:"canonical first-party GitHub repository fallback for unpublished pm packages"}],next_best_command:i}:{}}}}}function xd(e,t){if(!vd(t))return null;let n=kd(e);return new h(n.message,g.NOT_FOUND,n.context)}async function oi(e){if(E.isAbsolute(e)||e.startsWith(".")||e.startsWith("..")){let t=E.resolve(process.cwd(),e);return await x(t)?t:null}try{let t=new URL(e);if(t.protocol==="file:"){let n=ld(t);return await x(n)?n:null}}catch{}if(!/^[a-z][a-z0-9+.-]*:/i.test(e)){let t=E.resolve(process.cwd(),e);if(await x(t))return t}return null}async function Sd(e){let t=await oi(e);if(t)return t;let n=Ed(e);return n!==e?n:(/^[a-z][a-z0-9+.-]*:/i.test(e),e)}function Ed(e,t=process.cwd()){let n="@file:",r=e.lastIndexOf(n);if(!ri(e))return e;let o=e.slice(0,r),i=e.slice(r+n.length);if(i.startsWith("//")&&!i.startsWith("///"))return e;if(!i.startsWith("/"))return`${o}@${E.resolve(t,i)}`;let a;try{a=decodeURIComponent(new URL(`file:${i}`).pathname)}catch{return e}let s=/^\/[A-Za-z]:/.test(a)?a.slice(1):a;return`${o}@${s}`}function Qo(e,t){let n=E.resolve(e,t),r=E.relative(e,n);if(r.length===0||r===".."||r.startsWith(`..${E.sep}`)||E.isAbsolute(r))throw new h("npm pack reported a package archive outside its isolated destination.",g.GENERIC_FAILURE,{code:"npm_package_archive_unsafe",required:"Retry with a trusted npm client that writes its archive inside the requested pack destination.",why:"pm will not read a package-manager artifact outside the isolated directory created for this install."});return n}function $d(e,t){if(typeof e!="object"||e===null||Array.isArray(e))return;let n=e;if(!(typeof n.filename!="string"||n.filename.trim().length===0))return{...t===void 0?{}:{key:t},filename:n.filename,...typeof n.name=="string"?{name:n.name}:{},...typeof n.version=="string"?{version:n.version}:{}}}function Ad(e){return(Array.isArray(e)?e.map(n=>({value:n})):typeof e=="object"&&e!==null?Object.entries(e).map(([n,r])=>({key:n,value:r})):[]).flatMap(({key:n,value:r})=>{let o=$d(r,n);return o?[o]:[]})}function Id(e,t){let n=t?.trim().toLowerCase(),r=n?e.filter(a=>{let s=a.name?.trim().toLowerCase();return s!==void 0?s===n:a.key?.trim().toLowerCase()===n}):[];if(r.length===1)return r[0];if(e.length!==1)return;let o=e[0],i=o.name??o.key;return n&&i!==void 0&&i.trim().toLowerCase()!==n?void 0:o}function Td(e,t,n){let r;try{r=JSON.parse(e)}catch{let a=e.split(/\r?\n/).map(s=>s.trim()).filter(s=>s.length>0).at(-1);if(!a)throw new h("npm pack did not report a tarball filename.",g.GENERIC_FAILURE);return{tarball:Qo(t,a)}}let o=Ad(r),i=Id(o,n);if(!i)throw new h("npm pack --json returned an unsupported or ambiguous package receipt.",g.GENERIC_FAILURE,{code:"npm_pack_json_shape_unsupported",required:"Use an npm client that returns an array of package receipts or an object keyed by package name, with exactly one requested package entry containing filename.",why:`Well-formed JSON contained ${o.length} usable package receipt(s), but pm could not select ${n??"one package"} deterministically.`});return{tarball:Qo(t,i.filename),package:i.name??i.key,version:i.version}}async function Od(e){return Cd(e,ti)}async function Cd(e,t){let n=await oi(e.spec);if(n){if((await R.stat(n)).isFile()&&ii(n))return On(n);let a=E.join(n,"package.json"),s=await x(a)?JSON.parse(await R.readFile(a,"utf8")):{};return{directory:await Gt(n,e.input),package:typeof s.name=="string"?s.name:void 0,version:typeof s.version=="string"?s.version:void 0,cleanup:async()=>{}}}let r=await R.mkdtemp(E.join(Cn.tmpdir(),"pm-npm-package-source-")),o=E.join(r,"pack");await R.mkdir(o,{recursive:!0});try{let i=await Sd(e.spec),a=await t(["pack",i,"--json","--pack-destination",o]),s=Td(a,o,ri(e.spec)?void 0:ni(e.spec));if(!await x(s.tarball))throw new h("npm pack did not create its reported package archive.",g.GENERIC_FAILURE,{code:"npm_package_archive_missing",required:"Retry the npm package install with a healthy registry and writable temporary directory.",why:"The package manager reported a tarball filename that was absent before validation, so pm cannot safely extract or install it."});let c=await On(s.tarball);return{directory:c.directory,package:s.package??c.package,version:s.version??c.version,cleanup:async()=>{try{await c.cleanup()}finally{await R.rm(r,{recursive:!0,force:!0})}}}}catch(i){await R.rm(r,{recursive:!0,force:!0});let a=xd(e.spec,i);throw a||i}}function ii(e){let t=e.toLowerCase();return t.endsWith(".tgz")||t.endsWith(".tar.gz")}function ve(e){throw new h(e,g.USAGE,{code:"local_package_archive_unsafe",required:"Use a bounded npm .tgz or .tar.gz archive with one package/ root and no links or escaping paths.",why:"Package archives are untrusted input and must be validated before any entry reaches the filesystem."})}function Rd(e,t,n){if(e.meta)return;n.entries+=1,n.entries>t.maxEntries&&ve(`Local package archive exceeds the ${t.maxEntries} entry limit.`);let r=e.path,o=r.split("/");(r.includes("\\")||r.startsWith("/")||/^[A-Za-z]:/u.test(r)||o.some(i=>i===".."))&&ve(`Local package archive contains an escaping path: "${r}".`),o[0]!=="package"&&ve(`Local package archive entry "${r}" is outside the required package/ root.`),(e.type==="SymbolicLink"||e.type==="Link")&&ve(`Local package archive link "${r}" is not supported.`),e.type!=="File"&&e.type!=="OldFile"&&e.type!=="Directory"&&ve(`Local package archive entry "${r}" uses unsupported type "${e.type}".`),e.size>t.maxEntryBytes&&ve(`Local package archive entry "${r}" exceeds the ${t.maxEntryBytes} byte entry limit.`),n.expandedBytes+=e.size,n.expandedBytes>t.maxExpandedBytes&&ve(`Local package archive exceeds the ${t.maxExpandedBytes} expanded byte limit.`),r==="package/package.json"&&(n.packageJsonEntries+=1)}async function On(e,t=hd){(await R.stat(e)).size>t.maxArchiveBytes&&ve(`Local package archive exceeds the ${t.maxArchiveBytes} archive byte limit.`);let r=await R.mkdtemp(E.join(Cn.tmpdir(),"pm-local-package-archive-")),o=E.join(r,"extract");await R.mkdir(o,{recursive:!0});let i={entries:0,expandedBytes:0,packageJsonEntries:0},a;try{if(await fd({file:e,strict:!0,maxDecompressionRatio:100,onReadEntry:l=>{if(a===void 0)try{Rd(l,t,i)}catch(p){a=p}}}),a!==void 0)throw a;i.packageJsonEntries!==1&&ve(`Local package archive must contain exactly one package/package.json entry; found ${i.packageJsonEntries}.`),await md({file:e,cwd:o,strict:!0,preservePaths:!1,preserveOwner:!1,noMtime:!0,unlink:!0,maxDepth:64,maxDecompressionRatio:100});let s=E.join(o,"package"),c=E.join(s,"package.json"),d=JSON.parse(await R.readFile(c,"utf8"));return await Pd(s),{directory:await Gt(s,e),package:typeof d.name=="string"?d.name:void 0,version:typeof d.version=="string"?d.version:void 0,cleanup:async()=>{await R.rm(r,{recursive:!0,force:!0})}}}catch(s){throw await R.rm(r,{recursive:!0,force:!0}),s}}async function Pd(e,t=ti){let n=E.join(e,"package.json");if(!await x(n))return;let r;try{r=JSON.parse(await R.readFile(n,"utf8"))}catch{return}if(typeof r!="object"||r===null)return;let o=r,i=Md(o),a=Nd(o);if(i.length===0&&!a)return;let s={...r};delete s.devDependencies;let c={...s};Dd(c),await R.writeFile(n,`${JSON.stringify(c,null,2)}
|
|
26
|
-
`,"utf8");try{await Promise.all([R.rm(E.join(e,"package-lock.json"),{force:!0}),R.rm(E.join(e,"npm-shrinkwrap.json"),{force:!0})]),i.length>0&&await t(["install","--ignore-scripts","--no-audit","--fund=false","--package-lock=false","--no-save","--omit=peer","--"],e),a&&await jd(e)}finally{await R.writeFile(n,`${JSON.stringify(s,null,2)}
|
|
27
|
-
`,"utf8")}}function Nd(e){for(let t of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(typeof t=="object"&&t!==null&&Ft in t)return!0;return!1}function Dd(e){for(let t of["dependencies","optionalDependencies","peerDependencies"]){let n=e[t];if(typeof n!="object"||n===null)continue;let r={...n};delete r[Ft],Object.keys(r).length===0?delete e[t]:e[t]=r}}async function jd(e){let t=de(import.meta.url,["../../.."]),[n,r]=Ft.split("/"),o=E.join(e,"node_modules",n),i=E.join(o,r);await R.mkdir(o,{recursive:!0}),await R.rm(i,{recursive:!0,force:!0}),await R.symlink(t,i,Ld(process.platform))}function Ld(e){return e==="win32"?"junction":"dir"}function Fd(e,t){if(e.startsWith("-"))throw new h(`Extension runtime dependency name "${e}" is unsafe because npm could interpret it as a command-line option.`,g.USAGE,{code:"extension_dependency_name_unsafe",required:"Use a valid npm package name that does not begin with a dash.",why:"Extension manifests are untrusted input and dependency names must never become npm options."});if([...t].some(r=>{let o=r.charCodeAt(0);return o<=31||o===127||"&|;()`\"'".includes(r)}))throw new h(`Extension runtime dependency "${e}" has an unsafe version specifier.`,g.USAGE,{code:"extension_dependency_version_unsafe",required:"Use an npm version, range, dist-tag, URL, or file specifier without shell metacharacters.",why:"npm.cmd requires a command shell on Windows, so untrusted shell metacharacters cannot be forwarded."});try{ud.resolve(e,t)}catch{throw new h(`Extension runtime dependency "${e}@${t}" is not a valid npm dependency specifier.`,g.USAGE,{code:"extension_dependency_spec_invalid",required:"Use a valid npm package name and npm-supported version, range, dist-tag, URL, or file specifier.",why:"Only grammar-validated dependency specs may be written to the isolated runtime install manifest."})}return`${e}@${t}`}function Md(e){let t=new Map;for(let n of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(!(typeof n!="object"||n===null))for(let[r,o]of Object.entries(n)){if(r===Ft||typeof o!="string"||o.trim().length===0||t.has(r))continue;let i=o.trim();t.set(r,Fd(r,i))}return[...t.values()]}async function Gt(e,t){let n=await Pt(e);if(n.length===1)return n[0];if(n.length>1){let r=n.map(o=>E.relative(e,o).replaceAll(E.sep,"/")).sort((o,i)=>o.localeCompare(i));throw new h(`Package source "${t}" contains multiple extension manifests. Provide an explicit extension path. Candidates: ${r.join(", ")}`,g.USAGE)}throw new h(`Unable to locate a pm extension manifest in package source "${t}". Package installs currently activate only extension resources, so add package.json pm.extensions or an extensions/ directory. Metadata-only resources like pm.docs/pm.examples are catalog metadata and do not activate commands.`,g.USAGE)}async function Gd(e,t){let n=[];t.subpath&&(n.push(t.subpath),n.push(E.posix.join(".agents/pm/extensions",t.subpath)),n.push(E.posix.join(".custom/pm-extensions",t.subpath)),n.push(E.posix.join(".custom/pm-extension",t.subpath)));for(let o of n){let i=E.resolve(e,o);if(te(e,i)&&await x(E.join(i,"manifest.json")))return{directory:i,resolved_subpath:o}}if(await x(E.join(e,"manifest.json")))return{directory:e,resolved_subpath:"."};let r=await Gt(e,t.input);return{directory:r,resolved_subpath:E.relative(e,r).replaceAll(E.sep,"/")}}function Ud(e){let t=e.trim();return t.length===0||t.startsWith(".")||t.startsWith("~")?!1:t.startsWith("@")?t.split("/").length===2:!t.includes("/")&&!t.includes("\\")}async function zd(e){let t=`Local extension source does not exist: "${e.absolute_path}".`,n=e.input.trim();if(!Ud(n))return new h(t,g.NOT_FOUND);let r=[];try{let i=process.env.PM_CLI_PACKAGE_ROOT,a=typeof i=="string"&&i.trim().length>0?E.resolve(i.trim()):"";In?.key!==a&&(In={key:a,aliases:await jt()}),r=In.aliases}catch{}let o=[`Retry with pm install npm:${n} if the package is published to npm.`,`Or inspect bundled packages with pm package catalog --project --json before installing by alias. Known aliases (blank means none found): ${r.join(", ")}`];return new h(`${t} "${n}" did not match a local directory, bundled package alias, or bundled package name; if you meant an npm package, install it as "npm:${n}".`,g.NOT_FOUND,{code:"local_source_not_found_bare_name",required:`Use "npm:${n}" for npm registry packages, a bundled catalog alias, or an existing local directory path.`,why:"Bare names resolve as local paths only after bundled aliases, so unmatched names need an explicit npm: source.",examples:[`pm install npm:${n}`,"pm package catalog --project --json"],nextSteps:o,recovery:{attempted_command:`pm install ${n}`,normalized_args:["install",n],next_best_command:`pm install npm:${n}`}})}async function ai(e){if(e.kind==="local"){let r;try{r=await R.stat(e.absolute_path)}catch{throw await zd(e)}if(r.isFile()&&ii(e.absolute_path)){let i=await On(e.absolute_path);return{source:e,directory:i.directory,source_root:E.dirname(i.directory),resolved_subpath:E.relative(E.dirname(i.directory),i.directory).replaceAll(E.sep,"/"),npm_package:i.package,npm_version:i.version,cleanup:i.cleanup}}if(!r.isDirectory())throw new h(`Local extension source must be a directory or npm .tgz/.tar.gz archive: "${e.absolute_path}".`,g.USAGE);let o=await Gt(e.absolute_path,e.input);return{source:e,directory:o,source_root:e.absolute_path}}if(e.kind==="npm"){let r=await Od(e);return{source:e,directory:r.directory,source_root:E.dirname(r.directory),cleanup:r.cleanup,resolved_subpath:E.relative(E.dirname(r.directory),r.directory).replaceAll(E.sep,"/"),npm_package:r.package,npm_version:r.version}}let t=await R.mkdtemp(E.join(Cn.tmpdir(),"pm-extension-source-")),n=["clone","--depth","1"];e.ref&&n.push("--branch",e.ref),n.push(e.repository,t);try{await Lt(n);let r=await Lt(["-C",t,"rev-parse","HEAD"]),o=await Gd(t,e);return{source:e,directory:o.directory,source_root:t,resolved_subpath:o.resolved_subpath,commit:r,cleanup:async()=>{await R.rm(t,{recursive:!0,force:!0})}}}catch(r){throw await R.rm(t,{recursive:!0,force:!0}),r}}async function si(e,t){if(!await x(e)||!await x(t))return!1;let[n,r]=await Promise.all([R.realpath(e),R.realpath(t)]);return n===r}import mt from"node:fs/promises";import ft 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]="5321d574-4de4-5f94-99db-0c49639673fc")}catch{}})();var Rn=1,Le="2026.6.24",Jd=">=22.18.0",qd={fs_read:!1,fs_write:!1,network:!1,env_read:!1,env_write:!1,process_spawn:!1},ci=new Set([...Ir.map(e=>e.split("-")[0].toLowerCase()),...Object.keys(Ar).map(e=>e.toLowerCase()),"scaffold"]),Bd="^6.0.0",Wd="^22.0.0",pi=["type StarterHarness = Awaited<ReturnType<typeof createExtensionTestHarness>>;","","async function deactivateIfNeeded(ext: StarterHarness, deactivated: boolean): Promise<void> {"," if (!deactivated) {"," try {"," await ext.deactivate();"," } catch {"," // Preserve the original assertion error; cleanup is best effort."," }"," }","}",""],me=[" } finally {"," await deactivateIfNeeded(ext, deactivated);"," }"];function di(e,t){return e.map(n=>n===""?n:`${t}${n}`)}function ui(e){let t=e.includeMigrationReplacementHint===!0?[" // as your migration grows."]:[];return[" // assertItemType/Field/Migration throw unless the registration is present, so"," // reaching each next line already proves the wiring; assert on the returned"," // definitions to demonstrate inspecting registered metadata.",` const itemType = ext.assertItemType({ name: ${JSON.stringify(e.itemTypeName)}, extensionName: ${JSON.stringify(e.extensionName)} });`,` assert.equal(itemType.itemType.folder, ${JSON.stringify(e.itemTypeFolder)});`,` const itemField = ext.assertItemField({ name: ${JSON.stringify(e.fieldName)}, extensionName: ${JSON.stringify(e.extensionName)} });`,' assert.equal(itemField.field.type, "string");',` ext.assertMigration({ name: ${JSON.stringify(e.migrationId)}, extensionName: ${JSON.stringify(e.extensionName)}, mandatory: false });`,""," // runMigration invokes the migration through pm's real runner with a synthetic"," // context and returns its result.",...t,` const migrated = await ext.runMigration({ migration: ${JSON.stringify(e.migrationId)} });`,` assert.deepEqual(migrated, { migrated: true, id: ${JSON.stringify(e.migrationId)} });`]}function mi(e){return[" // assertProfile throws unless the profile is registered, so reaching the next"," // line already proves the wiring; assert on the returned definition to inspect"," // the bundled archetype dimensions.",` const { profile } = ext.assertProfile({ name: ${JSON.stringify(e)}, extensionName: ${JSON.stringify(e)} });`,` assert.equal(profile.title, ${JSON.stringify(`${e} archetype`)});`," assert.equal(profile.types.length, 1);"," assert.equal(profile.workflows.length, 1);"]}var Hd={compilerOptions:{target:"ES2022",module:"NodeNext",moduleResolution:"NodeNext",strict:!0,esModuleInterop:!0,skipLibCheck:!0,noEmit:!0,allowImportingTsExtensions:!0,resolveJsonModule:!0,types:["node"]},include:["**/*.ts"]},li=["commands","hooks","search","importers","schema","profile","renderers","parser","preflight","services"],fi={commands:["commands"],hooks:["commands","hooks"],search:["commands","search"],importers:["commands","schema","importers"],schema:["commands","schema"],profile:["commands","schema"],renderers:["commands","renderers"],parser:["commands","parser","schema"],preflight:["commands","preflight"],services:["commands","services"]},Kd={commands:'["commands"]',hooks:'["commands", "hooks"]',search:'["commands", "search"]',importers:'["commands", "schema", "importers"]',schema:'["commands", "schema"]',profile:'["commands", "schema"]',renderers:'["commands", "renderers"]',parser:'["commands", "parser", "schema"]',preflight:'["commands", "preflight"]',services:'["commands", "services"]'},Vd={commands:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration plus a `deactivate` teardown stub.",hooks:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, an `after_command` lifecycle hook, and a `deactivate` teardown stub.",search:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a search provider, a vector-store adapter, and a `deactivate` teardown stub.",importers:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, importer/exporter command registrations, and a `deactivate` teardown stub.",schema:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a custom item type, a custom item field, a schema migration, and a `deactivate` teardown stub.",profile:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a project profile (item types, statuses, fields, a workflow, config, a template, and package recommendations) registered via `api.registerProfile`, and a `deactivate` teardown stub.",renderers:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a `toon` output renderer override, and a `deactivate` teardown stub.",parser:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a parser override that rewrites the command's parsed options, and a `deactivate` teardown stub.",preflight:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a preflight override over pm's pre-run gate decision, and a `deactivate` teardown stub.",services:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, an `output_format` service override, and a `deactivate` teardown stub."},Yd={commands:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, and teardown via the SDK testing helpers.",hooks:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, the after_command hook, and teardown via the SDK testing helpers.",search:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, search provider/vector adapter invocation, and teardown via the SDK testing helpers.",importers:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, importer/exporter invocation, and teardown via the SDK testing helpers.",schema:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, item type/field/migration registration, migration invocation, and teardown via the SDK testing helpers.",profile:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, project-profile registration (asserting the bundled archetype dimensions), and teardown via the SDK testing helpers.",renderers:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, renderer override registration and invocation (including format pass-through), and teardown via the SDK testing helpers.",parser:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, parser override registration and the option rewrite it produces, and teardown via the SDK testing helpers.",preflight:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, preflight override registration and the gate decision it returns, and teardown via the SDK testing helpers.",services:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, service override registration and invocation (including command pass-through), and teardown via the SDK testing helpers."},hi="- `tsconfig.json`: strict type-check-only TypeScript config (`noEmit`) for the `.ts` source the loader runs directly.",Xd={commands:[],hooks:["","## Lifecycle Hook","`index.ts` registers an `after_command` hook via `api.hooks.afterCommand`.","pm fires it once a command finishes, passing the command outcome and the","items it mutated (`context.affected`). React there to keep external context","in sync - sync records, emit telemetry, or refresh derived state. The","`hooks` capability in `manifest.json` is what grants the hook registration;","remove it (and the hook) if your package only needs commands."],search:["","## Search Provider","`index.ts` registers a deterministic in-memory search provider and","vector-store adapter through `api.registerSearchProvider` and","`api.registerVectorStoreAdapter`. Replace the sample scoring,","embedding, and storage behavior with your project-specific retrieval","logic. The `search` capability in `manifest.json` grants both","registrations."],importers:["","## Importer and Exporter","`index.ts` registers paired project-context import/export commands through","`api.registerImporter` and `api.registerExporter`. Replace the starter","payloads with your domain adapter: GitHub issues, CSV rows, documents,","tickets, or another project-management source of truth. The `importers`","capability grants both registrations, and `schema` grants the example","command flag metadata."],schema:["","## Custom Schema","`index.ts` models a project domain by registering a custom item type, a","custom item field, and a schema migration through `api.registerItemTypes`,","`api.registerItemFields`, and `api.registerMigration`. This is how a package","turns pm into a domain-specific tracker \u2014 `project management = context","management`. Replace the sample type/field/migration with your own domain","model; the `schema` capability in `manifest.json` grants all three","registrations. Once installed, the custom type is usable everywhere, e.g.",'`pm create <type> "<title>"` and `pm list --type <type>`.'],profile:["","## Project Profile","`index.ts` registers a complete project-profile archetype through","`api.registerProfile`. A profile is the broadest customization primitive pm","has \u2014 one declarative bundle of item types, custom statuses, fields, a per-type","workflow, config knobs, create templates, and package recommendations. Once the","package is installed the profile resolves by name through `pm profile list`,","`pm profile show <name>`, and `pm profile apply <name>`, which stages every","dimension idempotently \u2014 exactly like a core archetype (agile/ops/research),","with no consumer code required. Replace the sample archetype with your own","domain; the `schema` capability in `manifest.json` grants the registration (a","profile is a schema+config bundle, so it needs no separate capability)."],renderers:["","## Output Renderer","`index.ts` registers a `toon` output renderer override through","`api.registerRenderer`. Renderer overrides run for every command's output in","that format, so this starter scopes itself to THIS package's own command and","returns `null` (pass-through to pm's default renderer) for everything else.","Return a string to take over rendering. Replace the sample serialization with","your own; the `renderers` capability in `manifest.json` grants the","registration."],parser:["","## Parser Override","`index.ts` registers a parser override for the starter command through","`api.registerParser`. pm runs it on the command's parsed options BEFORE the","handler, merging the delta you return. This starter rewrites a deprecated","`--shout` alias to the canonical `--upper` flag; replace it with your","command's real normalization. The `parser` capability in `manifest.json`","grants the registration."],preflight:["","## Preflight Override","`index.ts` registers a preflight override through `api.registerPreflight`. pm","calls it only for its declared command ownership to compute the migration/format","gate decision. Overlapping or legacy global ownership is diagnosed. Return only","the decision keys you want to","change; this starter echoes the current decision unchanged (a safe no-op) so","installing the package does not alter gate behavior. The `preflight`","capability in `manifest.json` grants the registration."],services:["","## Service Override","`index.ts` overrides the built-in `output_format` service through","`api.registerService`. The service renders a command's structured result;","returning the payload unchanged passes through to pm's default formatting.","This starter scopes itself to THIS package's own command and passes every","other command through, so it never disrupts unrelated output. The `services`","capability in `manifest.json` grants the registration."]},Qd={package:["","## Lazy Activation","`manifest.json` declares `activation.commands`: the exact command paths this","package's `activate` registers. pm imports and activates the package lazily \u2014","only when an invoked command path matches one of these entries \u2014 so unrelated","commands (`pm list`, `pm search`, ...) never pay to load it. Keep this list in","sync with the registrations in `index.ts`: add an entry when you register a new","command, importer, or exporter, and remove one you drop. An omitted or stale","entry means the matching command will not dispatch from the CLI. Globally-scoped","surfaces (hooks, parser/preflight/renderer overrides, and search providers for","built-in search commands) still activate regardless of this list."],extension:["","## Lazy Activation","`manifest.json` declares `activation.commands`: the exact command paths this","extension's `activate` registers. pm imports and activates the extension lazily \u2014","only when an invoked command path matches one of these entries \u2014 so unrelated","commands never pay to load it. Keep this list in sync with the registrations in","`index.ts`: an omitted or stale entry means the matching command will not dispatch","from the CLI. Globally-scoped surfaces (hooks, parser/preflight/renderer overrides,","and search providers for built-in search commands) still activate regardless."]},Zd={package:["","## Activation","This package contributes a GLOBAL custom item type and field, so `manifest.json`","intentionally declares no `activation.commands`. pm activates the package","conservatively \u2014 for every command \u2014 so the custom type is present wherever it is","used: `pm create <type>`, `pm list --type <type>`, `pm validate`, and so on.","Declaring narrow `activation.commands` here would gate activation to only those","commands and silently leave the custom type unregistered for `pm create`. If you","drop the schema registrations and keep only command/hook/search/importer surfaces,","add `activation.commands` back so pm can load the package lazily."],extension:["","## Activation","This extension contributes a GLOBAL custom item type and field, so `manifest.json`","intentionally declares no `activation.commands`. pm activates the extension","conservatively \u2014 for every command \u2014 so the custom type is present wherever it is","used: `pm create <type>`, `pm list --type <type>`, `pm validate`, and so on.","Declaring narrow `activation.commands` here would gate activation to only those","commands and silently leave the custom type unregistered for `pm create`."]},el={package:["","## Activation","This package contributes a project profile resolved by the built-in","`pm profile list`, `pm profile show <name>`, and `pm profile apply <name>`","commands \u2014 commands the package does not own \u2014 so `manifest.json` intentionally","declares no `activation.commands`. pm activates the package conservatively (for","every command, granted by the `schema` capability) so the profile is present","whenever `pm profile` runs. Declaring narrow `activation.commands` here would","gate activation to only the listed commands and silently leave the profile","unregistered for `pm profile`."],extension:["","## Activation","This extension contributes a project profile resolved by the built-in","`pm profile list`, `pm profile show <name>`, and `pm profile apply <name>`","commands, so `manifest.json` intentionally declares no `activation.commands`. pm","activates the extension conservatively (for every command, granted by the","`schema` capability) so the profile is present whenever `pm profile` runs.","Declaring narrow `activation.commands` here would silently leave the profile","unregistered for `pm profile`."]};function gi(e,t){return e==="schema"?`- \`manifest.json\`: ${t} metadata and capabilities (no \`activation.commands\` \u2014 the custom item type activates for every command).`:e==="profile"?`- \`manifest.json\`: ${t} metadata and capabilities (no \`activation.commands\` \u2014 the contributed profile resolves through \`pm profile\` for every command).`:`- \`manifest.json\`: ${t} metadata, capabilities, and \`activation.commands\` (the command paths that lazily activate this ${t}).`}function yi(e,t){return e==="schema"?Zd[t]:e==="profile"?el[t]:Qd[t]}function tl(e){let t=e.replace(/-/g," ").trim().split(/\s+/).filter(c=>c.length>0);if(t.length===0)return"starter ping";let n=t[0].toLowerCase(),r=0;for(;t[r]?.toLowerCase()==="starter";)r+=1;let o=t[r]?.toLowerCase(),i=r>0&&(r===t.length||o!==void 0&&ci.has(o));return`${(ci.has(n)||i?["starter",...t]:t).join(" ")} ping`}function _i(e){let t=e,n=`${e}s`,r=e.replace(/-/g,""),o=r===t?[]:[r],i=`${e.replace(/-/g,"_")}_owner`,a="reviewing";return[` name: ${JSON.stringify(e)},`,` title: ${JSON.stringify(`${e} archetype`)},`,' summary: "Starter project profile. Replace these dimensions with your own archetype.",'," // Item types the profile upserts into the project schema when applied."," types: ["," {",` name: ${JSON.stringify(t)},`,` folder: ${JSON.stringify(n)},`,` aliases: ${JSON.stringify(o)},`,` description: ${JSON.stringify(`A ${e} work item that flows to done.`)},`," },"," ],"," // Custom statuses upserted into the project status set."," statuses: ["," {",` id: ${JSON.stringify(a)},`,' roles: ["active"],',' aliases: ["in-review"],',' description: "Work is implementation-complete and awaiting review.",'," },"," ],"," // Custom item-metadata fields the archetype tracks."," fields: ["," {",` key: ${JSON.stringify(i)},`,' type: "string",',' commands: ["create", "update", "list"],',' description: "Stakeholder accountable for the item.",'," },"," ],"," // Per-type workflow transition allow-list staged into settings."," workflows: ["," {",` type: ${JSON.stringify(t)},`," allowed_transitions: [",' ["open", "in_progress"],',` ["in_progress", ${JSON.stringify(a)}],`,` [${JSON.stringify(a)}, "in_progress"],`,` [${JSON.stringify(a)}, "closed"],`,' ["in_progress", "blocked"],',' ["blocked", "in_progress"],'," ],"," },"," ],"," // Nested-settings knobs staged when the profile is applied."," config: [",' { key: "search_provider", value: "bm25", summary: "Offline BM25 lexical search needs no embedding service." },',' { key: "search_max_results", value: "20", summary: "Result cap tuned for quick triage." },'," ],"," // Create templates staged into <pmRoot>/templates."," templates: ["," {",` name: ${JSON.stringify(e)},`," options: {",` type: ${JSON.stringify(t)},`,' priority: "2",',` tags: ${JSON.stringify(e)},`,' acceptanceCriteria: "Item delivers the stated outcome with tests and docs updated.",',' body: "## Context\\n\\n## Acceptance\\n- [ ] \\n",'," },"," },"," ],"," // Advisory package recommendations (never auto-installed)."," packages: [",' { spec: "templates", reason: "Reusable create templates for recurring item shapes." },'," ],"]}function nl(e,t,n){let r=`${e}-search`,o=`${e}-vector`,i=`${e.replace(/-/g," ")} items`,a=[" api.registerCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",'," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,",' message: "Starter extension scaffold is active.",'," }),"," });"];if(n==="commands")return a;if(n==="search")return[...a,""," // Search providers let packages customize how pm ranks and retrieves"," // project context. This starter is deterministic and dependency-free:"," // replace the scoring with your domain retrieval, embedding, or rerank"," // logic as the package grows."," api.registerSearchProvider({",` name: ${JSON.stringify(r)},`," query: async (context) => {"," const needle = context.query.toLowerCase();"," const hits = context.documents"," .filter((document) => {",' const title = String(document.metadata.title ?? "").toLowerCase();'," return title.includes(needle);"," })"," .map((document) => ({"," id: document.metadata.id,"," score: 1,",' matched_fields: ["title"],'," }));"," return { hits };"," },"," embed: async (context) => [context.input.length],"," });",""," // Vector-store adapters let packages own semantic index storage. This"," // starter returns a stable in-memory hit so generated tests can exercise"," // the adapter without external services."," api.registerVectorStoreAdapter({",` name: ${JSON.stringify(o)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),"," });"];if(n==="schema"){let s=e,c=`${e}s`,d=e.replace(/-/g,""),l=d===s?[]:[d],p=`${e.replace(/-/g,"_")}_note`,u=`${e}-0001-init`;return[...a,""," // Schema registrations let a package model its own project domain \u2014 the",' // heart of "project management = context management". Item types and fields'," // are GLOBAL contributions: built-in commands like `pm create <type>` and"," // `pm list --type <type>` must see them, so this package declares no"," // `activation.commands` and pm activates it conservatively for every command."," // The `schema` capability in manifest.json grants all three registrations."," api.registerItemFields(["," {",` name: ${JSON.stringify(p)},`,' type: "string",'," optional: true,"," },"," ]);",""," api.registerItemTypes(["," {",` name: ${JSON.stringify(s)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(c)},`,` aliases: ${JSON.stringify(l)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],"," },"," ]);",""," // Migrations let a package evolve stored items as its schema changes. pm"," // runs each migration ONCE through the preflight gate (not once per item),"," // passing a context that identifies the migration itself: `context.id` is"," // the migration id (not an item id), alongside `context.pm_root` \u2014 iterate"," // the corpus yourself from there. This starter is a deterministic no-op so"," // package tests can invoke it without touching the corpus; replace the body"," // with your real rewrite."," api.registerMigration({",` id: ${JSON.stringify(u)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),"," });"]}return n==="profile"?[...a,""," // A project profile is the broadest customization primitive pm has: one"," // declarative bundle of item types, custom statuses, fields, a per-type"," // workflow, config knobs, create templates, and package recommendations. Once"," // this package is installed the profile resolves by name through `pm profile"," // list`, `pm profile show`, and `pm profile apply`, which stages every dimension"," // idempotently like a core archetype. A profile registration is a schema+config"," // bundle, so the `schema` capability in manifest.json grants it."," api.registerProfile({",..._i(e).map(s=>` ${s}`)," });"]:n==="importers"?[...a,""," // Importers/exporters are the bridge between pm's context graph and"," // another project-management system. Keep the starter deterministic so"," // package tests can run without touching the network or filesystem; replace"," // these payloads with your adapter's real mapping as the package grows."," api.registerImporter(",` ${JSON.stringify(i)},`," async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${i} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," },"," );",""," api.registerExporter(",` ${JSON.stringify(i)},`," async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${i} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," },"," );"]:n==="renderers"?[...a,""," // Renderer overrides customize how pm serializes a command's structured",' // result for an output format ("toon" or "json"). Host-enforced ownership'," // prevents unrelated commands from reaching this callback."," // The `renderers` capability in manifest.json grants the registration.",' api.registerRenderer("toon", (context) => {',` return ${JSON.stringify(`${e}: `)} + JSON.stringify(context.result);`,` }, { commands: [${JSON.stringify(t)}] });`]:n==="parser"?[" api.registerCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",'," flags: ["," {",' long: "--shout",',' value_type: "boolean",',' description: "Deprecated alias for --upper; the parser override rewrites it.",'," },"," {",' long: "--upper",',' value_type: "boolean",',' description: "Echo the canonical flag the parser override produces.",'," },"," ],"," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,"," // Surfaces the normalized option so `--shout`/`--upper` is observable."," upper: context.options.upper === true,",' message: "Starter extension scaffold is active.",'," }),"," });",""," // Parser overrides preprocess a command's parsed options BEFORE its handler"," // runs, returning a delta \u2014 only the keys you set are merged over the parsed"," // input. This override is scoped to THIS package's own command. Here it"," // rewrites the deprecated `--shout` boolean alias to the canonical `--upper`"," // flag; replace it with your command's real normalization. The `parser`"," // capability in manifest.json grants the registration.",` api.registerParser(${JSON.stringify(t)}, (context) => {`," const options = { ...context.options };"," if (options.shout === true) {"," options.upper = true;"," }"," delete options.shout;"," return { options };"," });"]:n==="preflight"?[...a,""," // Preflight overrides adjust pm's pre-run gate decision (extension"," // migrations + item-format checks) for the commands it owns. Disjoint"," // packages compose; overlapping or legacy global ownership is diagnosed."," // Return a delta of the keys you want to change"," // (enforce_item_format_gate, run_preflight_item_format_sync,"," // run_extension_migrations, enforce_mandatory_migration_gate); returning"," // context.decision unchanged is a safe no-op so installing the package does"," // not alter gate behavior \u2014 replace it with your policy, e.g."," // `{ run_extension_migrations: false }`. The `preflight` capability in"," // manifest.json grants the registration."," api.registerPreflight({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,"," });"]:n==="services"?[...a,""," // Service overrides replace a built-in pm service. The `output_format`"," // service renders a command's structured result; returning the payload"," // unchanged passes through to pm's default formatting. This override scopes"," // itself to THIS package's own command and passes every other command"," // through, so it never disrupts unrelated output. The `services` capability"," // in manifest.json grants the registration.",' api.registerService("output_format", (context) => {',` if (context.command !== ${JSON.stringify(t)}) {`," return { handled: false };"," }",` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`," });"]:[...a,""," // after_command hooks fire once pm finishes a command, receiving the items"," // it mutated. This is the natural place to react to every change - sync to"," // an external system, emit telemetry, or refresh derived context",' // ("project management = context management"). This starter is a documented'," // no-op on the success path; replace the body with your own reaction."," api.hooks.afterCommand((context) => {"," if (!context.ok) {"," return;"," }"," // `context.affected` lists the items pm mutated (id, status,"," // changed_fields). React here, e.g.:"," // for (const item of context.affected ?? []) { /* ...item.id... */ }"," });"]}function rl(e,t,n){let r=n==="hooks",o=n==="search",i=n==="importers",a=n==="schema",s=n==="profile",c=n==="renderers",d=n==="parser",l=n==="preflight",p=n==="services",u=Kd[n],f=e,y=`${e}s`,w=`${e.replace(/-/g,"_")}_note`,m=`${e}-0001-init`,_=[" assertExtensionDeactivated,"," createExtensionTestHarness,"],v=r?[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {"," // assertHook throws unless an after_command hook is registered, so"," // reaching the next line already proves the hook is wired."," ext.assertHook({",' kind: "after_command",',` extensionName: ${JSON.stringify(e)},`," });"," // runHook fires the hook through pm's real runner with a synthetic"," // context and returns the warnings it produced; a clean hook returns none."," // Replace the context/assertions as your hook grows."," const warnings = await ext.runHook({",' kind: "after_command",'," context: {",` command: ${JSON.stringify(t)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...me,"});",""]:[],k=o?Pn(e,t,"search",u):[],S=i?Pn(e,t,"importers",u):[],C=a?[`test(${JSON.stringify(`${e} registers and runs its custom schema`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {",...di(ui({extensionName:e,itemTypeName:f,itemTypeFolder:y,fieldName:w,migrationId:m,includeMigrationReplacementHint:!0})," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...me,"});",""]:[],G=s?[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {",...di(mi(e)," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...me,"});",""]:[],M=c?[`test(${JSON.stringify(`${e} registers and invokes its renderer override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {"," // assertRendererOverride throws unless a renderer is registered for the"," // format, so reaching the next line already proves the wiring.",` const override = ext.assertRendererOverride({ name: "toon", extensionName: ${JSON.stringify(e)} });`,' assert.equal(override.format, "toon");',""," // runRendererOverride renders through pm's real runner. The override"," // customizes only THIS package's command output and returns a string the"," // host uses verbatim. Replace the assertions as it grows."," const rendered = await ext.runRendererOverride({",' format: "toon",',` command: ${JSON.stringify(t)},`," result: { ok: true },"," });"," assert.equal(rendered.overridden, true);",` assert.equal(rendered.rendered, ${JSON.stringify(`${e}: `)} + JSON.stringify({ ok: true }));`,""," // Output for any other command passes through to pm's default renderer."," const passthrough = await ext.runRendererOverride({",' format: "toon",',' command: "list",'," result: { ok: true },"," });"," assert.equal(passthrough.overridden, false);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...me,"});",""]:[],ce=d?[`test(${JSON.stringify(`${e} rewrites command options via its parser override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {"," // assertParserOverride throws unless a parser is registered for the"," // command, so reaching the next line already proves the wiring.",` ext.assertParserOverride({ name: ${JSON.stringify(t)}, extensionName: ${JSON.stringify(e)} });`,""," // runParserOverride runs the override through pm's real parser runner and"," // returns the rewritten context. The starter rewrites the deprecated"," // `shout` alias to the canonical `upper` flag."," const result = await ext.runParserOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: { shout: true },"," global: {},",' pm_root: "",'," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.context.options, { upper: true });",""," // End to end: feed the rewritten options into the command handler to"," // prove `pm <command> --shout` surfaces the normalized `upper` flag in"," // the result.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)}, options: result.context.options });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`," upper: true,",' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...me,"});",""]:[],$=l?[`test(${JSON.stringify(`${e} returns a preflight gate decision via its override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {"," // assertPreflightOverride throws unless a preflight override is"," // registered, so reaching the next line already proves the wiring.",` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(e)} });`,""," // runPreflightOverride runs the override through pm's real runner with a"," // synthetic gate decision. The starter echoes the decision unchanged;"," // replace the values/assertions with your real policy."," const decision = {"," enforce_item_format_gate: true,"," run_preflight_item_format_sync: false,"," run_extension_migrations: true,"," enforce_mandatory_migration_gate: false,"," };"," const result = await ext.runPreflightOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: {},"," global: {},",' pm_root: "",'," decision,"," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.decision, decision);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...me,"});",""]:[],J=p?[`test(${JSON.stringify(`${e} customizes command output via its service override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {"," // assertServiceOverride throws unless a service override is registered"," // for the service, so reaching the next line proves the wiring.",` ext.assertServiceOverride({ name: "output_format", extensionName: ${JSON.stringify(e)} });`,""," // runServiceOverride runs the override through pm's real service runner."," // The override customizes only THIS package's command output (handled),"," // passing every other command through (not handled)."," const handled = await ext.runServiceOverride({",' service: "output_format",',` command: ${JSON.stringify(t)},`," payload: { ok: true },"," });"," assert.equal(handled.handled, true);",` assert.deepEqual(handled.result, { rendered_by: ${JSON.stringify(e)}, payload: { ok: true } });`,""," // Output for any other command passes through to pm's default formatter."," const passthrough = await ext.runServiceOverride({",' service: "output_format",',' command: "list",'," payload: { ok: true },"," });"," assert.equal(passthrough.handled, false);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...me,"});",""]:[];return['import assert from "node:assert/strict";','import { test } from "node:test";',"import {",..._,'} from "@unbrained/pm-cli/sdk/testing";',...o?['import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";']:[],'import extension from "./index.ts";',"",...pi,`test(${JSON.stringify(`${e} registers its starter command`)}, async () => {`," // `capabilities` mirrors manifest.json so the in-memory activation grants"," // the capabilities the entrypoint relies on."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {"," // assertCommandContract is bound to the right activation registry and throws"," // if the command is not registered, so reaching here already proves the"," // wiring; assert on the returned definition to inspect metadata."," const registered = ext.assertCommandContract({",` name: ${JSON.stringify(t)},`,` extensionName: ${JSON.stringify(e)},`," });",' assert.equal(typeof registered.command.description, "string");',""," // runCommand invokes the handler through pm's real dispatch engine, so this"," // asserts behavior - not just that the command is wired. Replace these"," // assertions as you flesh out your command."," const invocation = await ext.runCommand({",` command: ${JSON.stringify(t)},`," });"," assert.equal(invocation.handled, true);"," // The handler result is typed `unknown`, so deep-equality on the whole"," // structured payload keeps the assertion type-safe without a cast."," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`,...d?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...me,"});","",...v,...k,...S,...C,...G,...M,...ce,...$,...J,`test(${JSON.stringify(`${e} tears down cleanly via deactivate`)}, async () => {`," // createExtensionTestHarness binds teardown to the same name/layer used for"," // activation, so this proves your `deactivate` hook runs without throwing."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," const teardown = await ext.deactivate();"," // assertExtensionDeactivated throws unless exactly one extension tore down"," // with no failures, so reaching the next line already proves teardown ran."," assertExtensionDeactivated(teardown);"," assert.equal(teardown.deactivated, 1);","});",""].join(`
|
|
28
|
-
`)}function ol(e,t,n){if(n==="schema"||n==="profile")return[];if(n==="importers"){let r=`${e.replace(/-/g," ")} items`;return[t,`${r} import`,`${r} export`]}return[t]}var il={commands:"starter command",hooks:"starter command and after_command hook",search:"starter command, search provider, and vector-store adapter",importers:"starter command, importer, and exporter",schema:"starter command, custom item type, item field, and migration",profile:"starter command and project profile",renderers:"starter command and toon renderer override",parser:"starter command and parser override",preflight:"starter command and preflight override",services:"starter command and output_format service override"},al={commands:"`commands`",hooks:"`commands` and `hooks.afterCommand`",search:"`commands`, `searchProviders`, and `vectorStoreAdapters`",importers:"`commands`, `importers`, and `exporters`",schema:"`commands`, `itemTypes`, `itemFields`, and `migrations`",profile:"`commands` and `profiles`",renderers:"`commands` and `renderers`",parser:"`commands` and `parsers`",preflight:"`commands` and `preflights`",services:"`commands` and `services`"};function sl(e,t,n){let r=n==="parser";return["// The starter command, authored with the `defineCommand` builder so its literal","// name is preserved and the handler `context` is inferred. Exporting it lets you","// unit-test the definition in isolation, apart from the blueprint.","export const pingCommand = defineCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",',...r?[" flags: ["," {",' long: "--shout",',' value_type: "boolean",',' description: "Deprecated alias for --upper; the parser override rewrites it.",'," },"," {",' long: "--upper",',' value_type: "boolean",',' description: "Echo the canonical flag the parser override produces.",'," },"," ],"]:[]," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,",...r?[" upper: context.options.upper === true,"]:[],' message: "Starter extension scaffold is active.",'," }),","});"]}function cl(e,t,n){let r=[],o=[...sl(e,t,n)],i=[" commands: [pingCommand],"],a=`${e}-search`,s=`${e}-vector`,c=`${e.replace(/-/g," ")} items`,d=e,l=`${e}s`,p=e.replace(/-/g,""),u=p===d?[]:[p],f=`${e.replace(/-/g,"_")}_note`,y=`${e}-0001-init`;switch(n){case"commands":break;case"hooks":r.push("defineAfterCommandHook"),o.push("","// after_command hooks fire once pm finishes a command, receiving the items it","// mutated. React here - sync to an external system, emit telemetry, or refresh",'// derived context ("project management = context management"). This starter is a',"// documented no-op on the success path; replace the body with your own reaction.","export const afterCommandHook = defineAfterCommandHook((context) => {"," if (!context.ok) {"," return;"," }"," // `context.affected` lists the items pm mutated (id, status, changed_fields):"," // for (const item of context.affected ?? []) { /* ...item.id... */ }","});"),i.push(" hooks: { afterCommand: [afterCommandHook] },");break;case"search":r.push("defineSearchProvider","defineVectorStoreAdapter"),o.push("","// Search providers let packages customize how pm ranks and retrieves project","// context. This starter is deterministic and dependency-free: replace the scoring","// with your domain retrieval, embedding, or rerank logic as the package grows.","export const searchProvider = defineSearchProvider({",` name: ${JSON.stringify(a)},`," query: async (context) => {"," const needle = context.query.toLowerCase();"," const hits = context.documents"," .filter((document) => {",' const title = String(document.metadata.title ?? "").toLowerCase();'," return title.includes(needle);"," })"," .map((document) => ({"," id: document.metadata.id,"," score: 1,",' matched_fields: ["title"],'," }));"," return { hits };"," },"," embed: async (context) => [context.input.length],","});","","// Vector-store adapters let packages own semantic index storage. This starter","// returns a stable in-memory hit so generated tests can exercise the adapter","// without external services.","export const vectorStoreAdapter = defineVectorStoreAdapter({",` name: ${JSON.stringify(s)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),","});"),i.push(" searchProviders: [searchProvider],"," vectorStoreAdapters: [vectorStoreAdapter],");break;case"importers":r.push("defineExporter","defineImporter"),o.push("","// Importers/exporters are the bridge between pm's context graph and another","// project-management system. Keep the starter deterministic so package tests can","// run without touching the network or filesystem; replace these payloads with","// your adapter's real mapping as the package grows.","export const importer = defineImporter(async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,","}));","","export const exporter = defineExporter(async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,","}));"),i.push(" importers: ["," {",` name: ${JSON.stringify(c)},`," importer,"," options: {",` action: ${JSON.stringify(`${c} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," },"," },"," ],"," exporters: ["," {",` name: ${JSON.stringify(c)},`," exporter,"," options: {",` action: ${JSON.stringify(`${c} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," },"," },"," ],");break;case"schema":r.push("defineItemField","defineItemType","defineMigration"),o.push("","// Schema registrations let a package model its own project domain - the heart of",'// "project management = context management". Item types and fields are GLOBAL',"// contributions, so this package declares no `activation.commands` and pm","// activates it conservatively for every command.","export const noteField = defineItemField({",` name: ${JSON.stringify(f)},`,' type: "string",'," optional: true,","});","","export const itemType = defineItemType({",` name: ${JSON.stringify(d)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(l)},`,` aliases: ${JSON.stringify(u)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],","});","","// Migrations let a package evolve stored items as its schema changes. pm runs each","// migration ONCE through the preflight gate (not once per item), passing a context","// that identifies the migration itself: `context.id` is the migration id (not an","// item id), alongside `context.pm_root`. This starter is a deterministic no-op so","// package tests can invoke it without touching the corpus; replace the body with","// your real rewrite.","export const initMigration = defineMigration({",` id: ${JSON.stringify(y)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),i.push(" itemTypes: [itemType],"," itemFields: [noteField],"," migrations: [initMigration],");break;case"profile":r.push("defineProjectProfile"),o.push("","// A project profile is the broadest customization primitive pm has: one","// declarative bundle of item types, custom statuses, fields, a per-type workflow,","// config knobs, create templates, and package recommendations. Once installed it","// resolves by name through `pm profile list/show/apply`, which stages every","// dimension idempotently like a core archetype. A profile registration is a","// schema+config bundle, so the `schema` capability grants it.","export const starterProfile = defineProjectProfile({",..._i(e),"});"),i.push(" profiles: [starterProfile],");break;case"renderers":r.push("defineRendererOverride"),o.push("","// Host-enforced command ownership prevents unrelated output from reaching","// this renderer callback; return a string to take over serialization.","export const toonRenderer = defineRendererOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => {",` return ${JSON.stringify(`${e}: `)} + JSON.stringify(context.result);`," },","});"),i.push(" renderers: { toon: toonRenderer },");break;case"parser":r.push("defineParserOverride"),o.push("","// Parser overrides preprocess a command's parsed options BEFORE its handler runs,","// returning a delta - only the keys you set are merged over the parsed input. This","// override is scoped to THIS package's own command; here it rewrites the deprecated","// `--shout` boolean alias to the canonical `--upper` flag.","export const pingParser = defineParserOverride((context) => {"," const options = { ...context.options };"," if (options.shout === true) {"," options.upper = true;"," }"," delete options.shout;"," return { options };","});"),i.push(` parsers: { ${JSON.stringify(t)}: pingParser },`);break;case"preflight":r.push("definePreflightOverride"),o.push("","// Preflight overrides adjust pm's pre-run gate decision (extension migrations +","// item-format checks) for the commands it owns. Scoped ownership composes with","// other packages; overlapping or legacy global ownership is diagnosed.","// Return a delta of the keys you want to change (enforce_item_format_gate,","// run_preflight_item_format_sync, run_extension_migrations,","// enforce_mandatory_migration_gate); returning context.decision unchanged is a","// safe no-op - replace it with your policy, e.g. { run_extension_migrations: false }.","export const preflightOverride = definePreflightOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,","});"),i.push(" preflights: [preflightOverride],");break;case"services":r.push("defineServiceOverride"),o.push("","// Service overrides replace a built-in pm service. The `output_format` service","// renders a command's structured result; returning the payload unchanged passes","// through to pm's default formatting. This override scopes itself to THIS","// package's own command and passes every other command through.","export const outputService = defineServiceOverride((context) => {",` if (context.command !== ${JSON.stringify(t)}) {`," return { handled: false };"," }",` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`,"});"),i.push(" services: { output_format: outputService },");break}return{builderImports:r,definitions:o,blueprintFields:i}}function dl(e,t,n){let r=cl(e,t,n);return[`import { ${["composeExtension","defineCommand","defineExtensionBlueprint",...r.builderImports].sort((i,a)=>i.localeCompare(a)).join(", ")} } from "@unbrained/pm-cli/sdk";`,"",...r.definitions,"","// Declarative authoring: describe WHAT the package registers as a blueprint and","// let `composeExtension` generate the `activate` that wires every surface in order,","// instead of hand-writing each `api.register*` call. `defineExtensionBlueprint`","// contract-checks the blueprint where it is authored. Keep `manifest.json`'s","// `capabilities` equal to the set this blueprint derives.","export const blueprint = defineExtensionBlueprint({",...r.blueprintFields," // `deactivate` is the teardown counterpart to the generated `activate`: pm runs"," // it on host shutdown/reload to release anything the package opened (timers,"," // connections, caches). This starter holds none, so it stays a no-op."," deactivate: () => {},","});","","// `composeExtension(blueprint)` is the package's default export \u2014 the runtime","// `ExtensionModule` pm loads. Guard the blueprint with `assertExtensionPreflight`","// in index.test.ts before publishing.","export default composeExtension(blueprint);",""].join(`
|
|
29
|
-
`)}function Pn(e,t,n,r){if(n==="commands")return[];let o=`${e}-search`,i=`${e}-vector`,a=`${e.replace(/-/g," ")} items`,s=e,c=`${e}s`,d=`${e.replace(/-/g,"_")}_note`,l=`${e}-0001-init`,p=[" const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${r},`," });"],u=f=>[...p," let deactivated = false;"," try {",...f.map(y=>y===""?y:` ${y}`)," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...me];switch(n){case"hooks":return[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`,...u([" // assertHook throws unless an after_command hook is registered, so reaching the"," // next line already proves the hook is wired.",` ext.assertHook({ kind: "after_command", extensionName: ${JSON.stringify(e)} });`," // runHook fires the hook through pm's real runner with a synthetic context and"," // returns the warnings it produced; a clean hook returns none."," const warnings = await ext.runHook({",' kind: "after_command",'," context: {",` command: ${JSON.stringify(t)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"]),"});",""];case"search":return[`test(${JSON.stringify(`${e} registers and invokes search primitives`)}, async () => {`,...u([` ext.assertSearchProvider({ name: ${JSON.stringify(o)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertVectorStoreAdapter({ name: ${JSON.stringify(i)}, extensionName: ${JSON.stringify(e)} });`,""," // The starter provider reads only document title/id, so `settings` is a minimal"," // typed stub and `documents` carry just the fields it inspects."," const settings = {"," testing: {"," record_results_to_items: false,"," allow_untrusted_linked_tests: false,"," },"," } as PmSettings;"," const query = await ext.runSearchProvider({",` provider: ${JSON.stringify(o)},`,' operation: "query",'," context: {",' query: "sync",',' mode: "semantic",',' tokens: ["sync"],'," options: {},"," settings,"," documents: [",' { metadata: { id: "pm-1", title: "Sync external context" }, body: "" },',' { metadata: { id: "pm-2", title: "Unrelated task" }, body: "" },'," ] as ItemDocument[],"," },"," });",' assert.deepEqual(query, { hits: [{ id: "pm-1", score: 1, matched_fields: ["title"] }] });',""," const embedding = await ext.runSearchProvider({",` provider: ${JSON.stringify(o)},`,' operation: "embed",',' context: { input: "abc", settings, model: "starter-model" },'," });"," assert.deepEqual(embedding, [3]);",""," const vectorHits = await ext.runVectorStoreAdapter({",` adapter: ${JSON.stringify(i)},`,' operation: "query",'," context: { vector: [0.1, 0.2], limit: 2, settings },"," });",' assert.deepEqual(vectorHits, [{ id: "starter-vector-hit", score: 2 }]);']),"});",""];case"importers":return[`test(${JSON.stringify(`${e} registers and invokes import/export primitives`)}, async () => {`,...u([` ext.assertImporter({ name: ${JSON.stringify(a)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertExporter({ name: ${JSON.stringify(a)}, extensionName: ${JSON.stringify(e)} });`,""," const imported = await ext.runImporter({",` importer: ${JSON.stringify(a)},`,' options: { source: "tickets" },',' args: ["batch-1"],'," });"," assert.equal(imported.handled, true);",' assert.deepEqual(imported.result, { imported: 1, source: "tickets", args: ["batch-1"] });',""," const exported = await ext.runExporter({",` exporter: ${JSON.stringify(a)},`,' options: { destination: "archive" },',' args: ["done"],'," });"," assert.equal(exported.handled, true);",' assert.deepEqual(exported.result, { exported: true, destination: "archive", args: ["done"] });']),"});",""];case"schema":return[`test(${JSON.stringify(`${e} registers and runs its custom schema`)}, async () => {`,...u(ui({extensionName:e,itemTypeName:s,itemTypeFolder:c,fieldName:d,migrationId:l})),"});",""];case"profile":return[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`,...u(mi(e)),"});",""];case"renderers":return[`test(${JSON.stringify(`${e} registers and invokes its renderer override`)}, async () => {`,...u([" // assertRendererOverride throws unless a renderer is registered for the format,"," // so reaching the next line already proves the wiring.",` const override = ext.assertRendererOverride({ name: "toon", extensionName: ${JSON.stringify(e)} });`,' assert.equal(override.format, "toon");',""," // runRendererOverride renders through pm's real runner. The override customizes"," // only THIS package's command output and returns a string the host uses verbatim."," const rendered = await ext.runRendererOverride({",' format: "toon",',` command: ${JSON.stringify(t)},`," result: { ok: true },"," });"," assert.equal(rendered.overridden, true);"," assert.equal(rendered.rendered, JSON.stringify({ ok: true }));",""," // Output for any other command passes through to pm's default renderer."," const passthrough = await ext.runRendererOverride({",' format: "toon",',' command: "list",'," result: { ok: true },"," });"," assert.equal(passthrough.overridden, false);"]),"});",""];case"parser":return[`test(${JSON.stringify(`${e} rewrites command options via its parser override`)}, async () => {`,...u([" // assertParserOverride throws unless a parser is registered for the command, so"," // reaching the next line already proves the wiring.",` ext.assertParserOverride({ name: ${JSON.stringify(t)}, extensionName: ${JSON.stringify(e)} });`,""," // runParserOverride runs the override through pm's real parser runner and returns"," // the rewritten context. The starter rewrites the deprecated `shout` alias to the"," // canonical `upper` flag."," const result = await ext.runParserOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: { shout: true },"," global: {},",' pm_root: "",'," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.context.options, { upper: true });",""," // End to end: feed the rewritten options into the command handler to prove"," // `pm <command> --shout` surfaces the normalized `upper` flag in the result.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)}, options: result.context.options });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`," upper: true,",' message: "Starter extension scaffold is active.",'," });"]),"});",""];case"preflight":return[`test(${JSON.stringify(`${e} returns a preflight gate decision via its override`)}, async () => {`,...u([" // assertPreflightOverride throws unless a preflight override is registered, so"," // reaching the next line already proves the wiring.",` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(e)} });`,""," // runPreflightOverride runs the override through pm's real runner with a synthetic"," // gate decision. The starter echoes the decision unchanged; replace the"," // values/assertions with your real policy."," const decision = {"," enforce_item_format_gate: true,"," run_preflight_item_format_sync: false,"," run_extension_migrations: true,"," enforce_mandatory_migration_gate: false,"," };"," const result = await ext.runPreflightOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: {},"," global: {},",' pm_root: "",'," decision,"," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.decision, decision);"]),"});",""];case"services":return[`test(${JSON.stringify(`${e} customizes command output via its service override`)}, async () => {`,...u([" // assertServiceOverride throws unless a service override is registered for the"," // service, so reaching the next line proves the wiring.",` ext.assertServiceOverride({ name: "output_format", extensionName: ${JSON.stringify(e)} });`,""," // runServiceOverride runs the override through pm's real service runner. The"," // override customizes only THIS package's command output (handled), passing every"," // other command through (not handled)."," const handled = await ext.runServiceOverride({",' service: "output_format",',` command: ${JSON.stringify(t)},`," payload: { ok: true },"," });"," assert.equal(handled.handled, true);",` assert.deepEqual(handled.result, { rendered_by: ${JSON.stringify(e)}, payload: { ok: true } });`,""," // Output for any other command passes through to pm's default formatter."," const passthrough = await ext.runServiceOverride({",' service: "output_format",',' command: "list",'," payload: { ok: true },"," });"," assert.equal(passthrough.handled, false);"]),"});",""]}}function ll(e,t,n){let r=n==="parser",o=JSON.stringify([...fi[n]].sort());return['import assert from "node:assert/strict";','import { test } from "node:test";','import { assertExtensionDeactivated, assertExtensionManifestMatchesBlueprint, assertExtensionPreflight, createExtensionTestHarness } from "@unbrained/pm-cli/sdk/testing";',...n==="search"?['import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";']:[],'import extension, { blueprint } from "./index.ts";','import manifest from "./manifest.json" with { type: "json" };',"",...pi,`test(${JSON.stringify(`${e} passes author-time preflight`)}, () => {`," // assertExtensionPreflight is the author-time capstone: it lints the blueprint,"," // synthesizes the least-privilege manifest from `identity`, and checks the version"," // bounds against `target` in one call, throwing on any blocking finding. It returns"," // the full report so you can inspect the derived data."," const report = assertExtensionPreflight(blueprint, {"," identity: {",` name: ${JSON.stringify(e)},`,' version: "0.1.0",',' entry: "./index.ts",'," priority: 0,",` pm_min_version: ${JSON.stringify(Le)},`," },",` target: { pmVersion: ${JSON.stringify(Le)} },`," });"," // Fail the starter suite whenever the checked-in manifest drifts from the"," // capabilities derived from the blueprint."," assertExtensionManifestMatchesBlueprint(manifest, blueprint);"," // The capability set is DERIVED from the blueprint, never hand-synced. Keep"," // manifest.json's `capabilities` equal to this list (set match, sorted).",` assert.deepEqual(report.capabilities, ${o});`,` assert.deepEqual(report.manifest?.capabilities, ${o});`,"});","",`test(${JSON.stringify(`${e} registers and runs its starter command`)}, async () => {`," // createExtensionTestHarness activates the composed module once and binds the"," // assert*/run*/deactivate helpers to the right activation sub-registry, so you"," // never thread activation.registrations vs activation.commands by hand."," // `capabilities` mirrors manifest.json so the in-memory activation grants what the"," // blueprint needs."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${o},`," });"," let deactivated = false;"," try {"," // assertCommandContract throws unless the command is registered, so reaching"," // the next line already proves the wiring; assert on the returned definition"," // to demonstrate inspecting registered metadata.",` const registered = ext.assertCommandContract({ name: ${JSON.stringify(t)} });`,' assert.equal(typeof registered.command.description, "string");',""," // runCommand invokes the handler through pm's real dispatch engine, so this"," // asserts behavior - not just that the command is wired. Replace these"," // assertions as you flesh out your command.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)} });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`,...r?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," // deactivate runs pm's real teardown engine over the module; exactly one"," // extension tears down with no failures."," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...me,"});","",...Pn(e,t,n,o)].join(`
|
|
30
|
-
`)}function pl(e,t,n){let r=gi(n,"package"),o=yi(n,"package");return[`# ${e}`,"","Generated by `pm package init --declarative`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",r,`- \`index.ts\`: the TypeScript manifest entry \u2014 a \`defineExtensionBlueprint\` blueprint (${il[n]}) composed into the runtime module by \`composeExtension\`, plus a \`deactivate\` teardown stub.`,"- `index.test.ts`: sample `node:test` suite covering author-time preflight (`assertExtensionPreflight`) and runtime surface invocation/teardown via `createExtensionTestHarness`.",hi,"- `.gitignore`: ignores `node_modules/`, logs, and the TypeScript build cache.","","## Quick Start","This package is authored AND loaded as TypeScript: the manifest `entry` is","`./index.ts` and pm imports it directly via Node's native type stripping","(Node >=22.18), so there is no build step \u2014 install and run:","```bash","npm install","pm install --project <package-path>",`pm ${t}`,"pm package doctor --project --detail summary","```","","## Declarative Authoring","`index.ts` uses the SDK's declarative authoring loop instead of an imperative","`activate` body. You describe WHAT the package registers as an","`ExtensionBlueprint` and `composeExtension` generates the `activate` that wires","every surface in order:","- The `define*` builders author each surface with literal-type preservation and"," contextual handler inference (`defineCommand`, `defineSearchProvider`,"," `defineItemType`, `defineParserOverride`, ...).","- `defineExtensionBlueprint({ ... })` collects the definitions into the blueprint;",` this starter populates ${al[n]}. Add more`," fields as the package grows.","- `composeExtension(blueprint)` is the default export \u2014 the runtime module pm"," loads. Its generated `activate` requires exactly the capabilities the blueprint"," derives, so `manifest.json`'s `capabilities` never drift.","","## Validate the Package","`npm install` pulls the peer SDK and TypeScript. `npm test` is the default","validation gate: it type-checks the package, then runs the colocated sample:","```bash","npm install","npm test","```","`index.test.ts` exercises both authoring capstones: `assertExtensionPreflight`","(the author-time lint + manifest synthesis + version-compatibility check over the","exported `blueprint`) and `createExtensionTestHarness` (the runtime fixture whose","`assert*`/`run*`/`deactivate` methods bind to the right activation sub-registry).","`npm run typecheck` is available when you only want the SDK contract check.","`npm run test:runtime` runs just `node --test`, which strips types on load and","executes `index.test.ts` directly against the `@unbrained/pm-cli/sdk/testing`","helpers - no compile step and no extra test runner required.",...o,"","## Compatibility Bounds","`manifest.json` cannot hold comments, so the version-compatibility fields are documented here:",`- \`manifest_version\` (integer): manifest schema generation. Leave at \`${Rn}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${Le}\`. The loader blocks the package on older CLIs.`,"- `pm_max_version` (string, optional): highest pm CLI version that may load this package. Add it to block CLIs that are newer than the version you have validated against. The loader blocks the package when the CLI exceeds this bound.","","## Policy Metadata",'The starter command is pure compute, so `manifest.json` declares `trusted: true`, `sandbox_profile: "strict"`, and all six permission keys as `false`. Keep that least-privilege shape for pure packages; relax only the specific permission your package actually needs and verify with `pm package doctor --project --detail deep --trace`.',"","## Notes","- Author in `index.ts`; pm loads it directly (no build), so edits take effect on the next install/reload \u2014 there is no `.js` to regenerate.","- Move larger runtimes into sibling or subdirectory `*.ts` modules and import them with their real `.ts` extension; `tsconfig.json` type-checks every `*.ts` in the package (recursively).","- Use `@unbrained/pm-cli/sdk` as the public SDK import for richer package runtimes.",""].join(`
|
|
31
|
-
`)}function ul(e){let t=e,n=e.replace(/-/g,"");return{searchProviderName:`${e}-search`,vectorAdapterName:`${e}-vector`,adapterName:`${e.replace(/-/g," ")} items`,itemTypeName:t,itemTypeFolder:`${e}s`,itemTypeAliases:n===t?[]:[n],fieldName:`${e.replace(/-/g,"_")}_note`,migrationId:`${e}-0001-init`}}function ml(e){return["defineCommand",...e==="hooks"?["defineAfterCommandHook"]:[],...e==="search"?["defineSearchProvider","defineVectorStoreAdapter"]:[],...e==="importers"?["defineImporter","defineExporter"]:[],...e==="schema"?["defineItemType","defineItemField","defineMigration"]:[],...e==="profile"?["defineProjectProfile"]:[],...e==="renderers"?["defineRendererOverride"]:[],...e==="parser"?["defineParserOverride"]:[],...e==="preflight"?["definePreflightOverride"]:[],...e==="services"?["defineServiceOverride"]:[]].join(", ")}function fl(e,t,n,r){let o=["export const pingCommand = defineCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",',...n==="parser"?[" flags: [",' { long: "--shout", value_type: "boolean", description: "Deprecated alias for --upper." },',' { long: "--upper", value_type: "boolean", description: "Canonical flag the parser produces." },'," ],"," run: (context) => ({ ok: true, command: context.command, upper: context.options.upper === true }),"]:[" run: (context) => ({ ok: true, command: context.command }),"],"});"];return n==="hooks"&&o.push("","export const afterCommandHook = defineAfterCommandHook((context) => {"," if (!context.ok) return;"," // React to context.affected here as your package grows.","});"),n==="search"&&o.push("","export const searchProvider = defineSearchProvider({",` name: ${JSON.stringify(r.searchProviderName)},`," query: async (context) => ({"," hits: context.documents",' .filter((document) => String(document.metadata.title ?? "").toLowerCase().includes(context.query.toLowerCase()))',' .map((document) => ({ id: document.metadata.id, score: 1, matched_fields: ["title"] })),'," }),"," embed: async (context) => [context.input.length],","});","","export const vectorStoreAdapter = defineVectorStoreAdapter({",` name: ${JSON.stringify(r.vectorAdapterName)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),","});"),n==="importers"&&o.push("","export const importer = defineImporter(async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,","}));","","export const exporter = defineExporter(async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,","}));"),n==="schema"&&o.push("",`export const noteField = defineItemField({ name: ${JSON.stringify(r.fieldName)}, type: "string", optional: true });`,"","export const itemType = defineItemType({",` name: ${JSON.stringify(r.itemTypeName)},`,` folder: ${JSON.stringify(r.itemTypeFolder)},`,` aliases: ${JSON.stringify(r.itemTypeAliases)},`," required_create_fields: [],","});","","export const initMigration = defineMigration({",` id: ${JSON.stringify(r.migrationId)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),n==="profile"&&o.push("","export const starterProfile = defineProjectProfile({",` name: ${JSON.stringify(e)},`,` title: ${JSON.stringify(`${e} archetype`)},`,' summary: "Starter project profile. Replace these dimensions with your own archetype.",'," types: [",` { name: ${JSON.stringify(r.itemTypeName)}, folder: ${JSON.stringify(r.itemTypeFolder)} },`," ],"," // ...plus statuses, fields, workflows, config, templates, and packages.","});"),n==="renderers"&&o.push("","export const toonRenderer = defineRendererOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => JSON.stringify(context.result),","});"),n==="parser"&&o.push("","export const pingParser = defineParserOverride((context) => {"," const options = { ...context.options };"," if (options.shout === true) options.upper = true;"," delete options.shout;"," return { options };","});"),n==="preflight"&&o.push("","// Return a delta of the gate-decision keys you want to change; returning","// context.decision unchanged is a safe no-op (e.g. { run_extension_migrations: false }).","export const preflightOverride = definePreflightOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,","});"),n==="services"&&o.push("","export const outputService = defineServiceOverride((context) => {",` if (context.command !== ${JSON.stringify(t)}) return { handled: false };`,` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`,"});"),o}function hl(e,t,n){let r=[];return t==="renderers"&&r.push(' api.registerRenderer("toon", toonRenderer.run, toonRenderer);'),t==="parser"&&r.push(` api.registerParser(${JSON.stringify(e)}, pingParser);`),t==="preflight"&&r.push(" api.registerPreflight(preflightOverride);"),t==="services"&&r.push(' api.registerService("output_format", outputService);'),t==="hooks"&&r.push(" api.hooks.afterCommand(afterCommandHook);"),t==="search"&&r.push(" api.registerSearchProvider(searchProvider);"," api.registerVectorStoreAdapter(vectorStoreAdapter);"),t==="schema"&&r.push(" api.registerItemFields([noteField]);"," api.registerItemTypes([itemType]);"," api.registerMigration(initMigration);"),t==="profile"&&r.push(" api.registerProfile(starterProfile);"),t==="importers"&&r.push(` api.registerImporter(${JSON.stringify(n.adapterName)}, importer, {`,` action: ${JSON.stringify(`${n.adapterName} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," });",` api.registerExporter(${JSON.stringify(n.adapterName)}, exporter, {`,` action: ${JSON.stringify(`${n.adapterName} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," });"),r}function gl(e,t,n,r="commands",o=!1){let i=`pm-${e}`,a=fi[r],s=ol(e,t,r),c=`${JSON.stringify({name:e,version:"0.1.0",entry:"./index.ts",manifest_version:Rn,pm_min_version:Le,trusted:!0,sandbox_profile:"strict",permissions:{...qd},capabilities:a,...s.length>0?{activation:{commands:s}}:{}},null,2)}
|
|
32
|
-
`,d=['import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"","export function activate(api: ExtensionApi): void {",...nl(e,t,r),"}","","// `deactivate` is the teardown counterpart to `activate`: pm runs it on host","// shutdown/reload (e.g. the MCP server between requests) to release anything","// `activate` opened - timers, connections, caches. This starter holds no such","// resources, so it stays a documented no-op; add cleanup here as you grow.","export function deactivate(): void {}","","export default {"," activate,"," deactivate,","};",""].join(`
|
|
33
|
-
`),l=`${JSON.stringify(Hd,null,2)}
|
|
34
|
-
`,p=Vd[r],u=gi(r,"package"),f=`${JSON.stringify({name:i,version:"0.1.0",private:!0,type:"module",keywords:["pm-package"],engines:{node:Jd},scripts:{typecheck:"tsc --noEmit","test:runtime":"node --test",test:"npm run typecheck && npm run test:runtime"},peerDependencies:{"@unbrained/pm-cli":`>=${Le}`},devDependencies:{"@types/node":Wd,typescript:Bd},pm:{aliases:[e],extensions:["."],docs:["README.md"],examples:["README.md"],catalog:{display_name:e,category:"workflow",summary:"Starter pm package scaffold.",tags:["starter"]}}},null,2)}
|
|
35
|
-
`,y=rl(e,t,r),w=Yd[r],m=["node_modules/","*.log","*.tsbuildinfo",""].join(`
|
|
36
|
-
`),_=ul(e),k=["```ts",`import { ${ml(r)} } from "@unbrained/pm-cli/sdk";`,'import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"",...fl(e,t,r,_),"","export function activate(api: ExtensionApi): void {"," api.registerCommand(pingCommand);",...hl(t,r,_),"}","","export function deactivate(): void {}","","export default { activate, deactivate };","```"],S=[`# ${i}`,"","Generated by `pm package init` or `pm extension init`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",u,p,w,hi,"- `.gitignore`: ignores `node_modules/`, logs, and the TypeScript build cache.","","## Quick Start","This package is authored AND loaded as TypeScript: the manifest `entry` is","`./index.ts` and pm imports it directly via Node's native type stripping","(Node >=22.18), so there is no build step \u2014 install and run:","```bash","npm install","pm install --project <package-path>",`pm ${t}`,"pm package doctor --project --detail summary","```","","## Validate the Package","`npm install` pulls the peer SDK and TypeScript. `npm test` is the default","validation gate: it type-checks the package, then runs the colocated sample:","```bash","npm install","npm test","```","`npm run typecheck` is available when you only want the SDK contract check.","`npm run test:runtime` runs just `node --test`, which strips types on load and","executes `index.test.ts` directly against the `@unbrained/pm-cli/sdk/testing`","helpers - no compile step and no extra test runner required.","","## Authoring With define* Builders","`index.ts` is authored fully in TypeScript so every registration is checked","against the SDK contracts at author time. Use the public SDK authoring","builders for exported definitions you want literal-type preservation,","contextual handler inference, and direct unit tests for:",...k,"The builders return their argument unchanged; runtime validation still lives","in `api.register*`, and behavior validation lives in `sdk/testing`.",...Xd[r],...yi(r,"package"),"","## Compatibility Bounds",`- \`peerDependencies["@unbrained/pm-cli"]\` uses the stable range \`>=${Le}\`. Keep a normal stable range instead of pinning a date ordinal: SemVer excludes prerelease ordinals such as \`2026.7.24-3\`, while daily stable releases continue to satisfy the range.`,"`manifest.json` cannot hold comments, so the version-compatibility fields are documented here:",`- \`manifest_version\` (integer): manifest schema generation. Leave at \`${Rn}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${Le}\`. The loader blocks the package on older CLIs.`,"- `pm_max_version` (string, optional): highest pm CLI version that may load this package. Add it to block CLIs that are newer than the version you have validated against. The loader blocks the package when the CLI exceeds this bound.","","## Policy Metadata",'The starter command is pure compute, so `manifest.json` declares `trusted: true`, `sandbox_profile: "strict"`, and all six permission keys as `false`. Keep that least-privilege shape for pure packages; relax only the specific permission your package actually needs and verify with `pm package doctor --project --detail deep --trace`.',"","## Notes","- Author in `index.ts`; pm loads it directly (no build), so edits take effect on the next install/reload \u2014 there is no `.js` to regenerate.","- Move larger runtimes into sibling or subdirectory `*.ts` modules and import them with their real `.ts` extension; `tsconfig.json` type-checks every `*.ts` in the package (recursively).","- Add capabilities to the extension manifest only when the entrypoint uses the matching SDK API.","- Use `@unbrained/pm-cli/sdk` as the public SDK import for richer package runtimes.",""].join(`
|
|
37
|
-
`);return{"package.json":f,"manifest.json":c,"index.ts":o?dl(e,t,r):d,"index.test.ts":o?ll(e,t,r):y,"tsconfig.json":l,".gitignore":m,"README.md":o?pl(i,t,r):S}}async function wi(e,t="extension",n="commands",r=!1){let o=n.trim().toLowerCase();if(!li.includes(o))throw new h(`Unknown scaffold capability "${n}". Supported capabilities: ${li.join(", ")}.`,g.USAGE);let i=o;if(r&&t!=="package")throw new h("--declarative scaffolds a package-mode blueprint starter (composeExtension is a runtime SDK import). Use `pm package init`, not `pm extension init`.",g.USAGE);let a=r?"declarative":"imperative",s=e.trim(),c=ft.resolve(process.cwd(),s),d=Nt(ft.basename(c)).replace(/^(?:pm-)+/u,""),l=tl(d),p=gl(d,l,t,i,r),u=!1;if(await x(c)){if(!(await mt.stat(c)).isDirectory())throw new h(`Scaffold target "${c}" exists and is not a directory.`,g.CONFLICT)}else await mt.mkdir(c,{recursive:!0}),u=!0;for(let[y,w]of Object.entries(p)){let m=ft.join(c,y);if(!await x(m))continue;if(await mt.readFile(m,"utf8")!==w)throw new h(`Scaffold file "${y}" already exists with different content in "${c}". Choose a new target path or remove conflicting files.`,g.CONFLICT)}let f=[];for(let[y,w]of Object.entries(p)){let m=ft.join(c,y);if(await x(m)){f.push({path:y,status:"unchanged"});continue}await mt.mkdir(ft.dirname(m),{recursive:!0}),await mt.writeFile(m,w,"utf8"),f.push({path:y,status:"created"})}return{extension_name:d,package_name:`pm-${d}`,command_name:l,invocation_command:`pm ${l}`,capability:i,style:a,target_path:c,created_directory:u,files:f}}(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]="48c3e62a-8085-5215-a692-4c03792022ce")}catch{}})();var vi=1,Nn=6,bi=[["commands","Commands"],["command_overrides","Command overrides"],["flag_commands","Flag commands"],["item_types","Item types"],["item_fields","Item fields"],["migrations","Migrations"],["profiles","Profiles"],["importers","Importers"],["exporters","Exporters"],["search_providers","Search providers"],["vector_store_adapters","Vector store adapters"],["assurance_providers","Assurance measurement providers"],["hooks","Lifecycle hooks"],["parser_overrides","Parser overrides"],["service_overrides","Service overrides"],["renderer_overrides","Renderer overrides"]];function Dn(e){return"#".repeat(e)}function ki(e){if(!e.includes("`"))return`\`${e}\``;let t=0,n=0;for(let i of e)n=i==="`"?n+1:0,t=Math.max(t,n);let r="`".repeat(t+1),o=e.startsWith("`")||e.endsWith("`")?" ":"";return`${r}${o}${e}${o}${r}`}function yl(e){return e.length===0?"Capabilities: _none registered_":`Capabilities: ${e.map(ki).join(", ")}`}function _l(e,t,n){let r=[`${Dn(t)} ${e}`,""];return n.length===0?(r.push("_None._",""),r):(r.push(...n.map(o=>`- ${ki(o)}`),""),r)}function wl(e,t,n){return e===0&&!n?[]:[`${Dn(t)} Preflight overrides`,"",e>0?`- ${e} registered (this surface carries no per-entry identifier)`:"_None._",""]}function jn(e,t={}){let n=t.headingLevel??2;if(!Number.isInteger(n)||n<vi||n>Nn)throw new RangeError(`headingLevel must be an integer in [${vi}, ${Nn}], received ${String(t.headingLevel)}`);let r=Math.min(n+1,Nn),o=t.includeEmpty===!0,i=t.title??"Extension surfaces",a=[`${Dn(n)} ${i}`,""];(o||e.capabilities.length>0)&&a.push(yl(e.capabilities),"");for(let[c,d]of bi){let l=e[c]??[];l.length===0&&!o||a.push(..._l(d,r,l))}return a.push(...wl(e.preflight_overrides,r,o)),!(e.preflight_overrides>0||bi.some(([c])=>(e[c]?.length??0)>0))&&!o&&a.push("_This extension registers no surfaces._",""),`${a.join(`
|
|
38
|
-
`).trimEnd()}
|
|
39
|
-
`}(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]="536ed530-7726-50ab-bb2d-ace030818f1d")}catch{}})();function xi(e,t){return`${e}:${b(t)}`}function vl(e,t){let n=[];for(let[r,o]of[["handler",e.commands.handlers],["override",e.commands.overrides]]){let i=new Map;for(let a of o){let s=i.get(a.command)??[];i.set(a.command,[...s,a])}for(let[a,s]of i){if(t!==null&&!s.some(d=>t.has(b(d.name))))continue;let c=s.at(-1);n.push({command:a,surface:r,policy:"last_activated_wins",collision:s.length>1,claimants:s.map(d=>({name:d.name,layer:d.layer,winner:d===c}))})}}return n.sort((r,o)=>r.command.localeCompare(o.command)||r.surface.localeCompare(o.surface))}function Si(e,t,n){let r=new Set(n.failed.map(d=>xi(d.layer,d.name))),o=[...t.loaded.map(d=>({name:d.name,layer:d.layer,version:d.version,activation_status:r.has(xi(d.layer,d.name))?"failed":"ok",surfaces:Je(n,{extensionName:d.name})})),...t.failed.map(d=>({name:d.name,layer:d.layer,version:"unknown",activation_status:"not_loaded",surfaces:Je(n,{extensionName:d.name})}))].sort((d,l)=>d.name.localeCompare(l.name)||d.layer.localeCompare(l.layer)),i=typeof e=="string"?b(e):null,a=i===null?null:new Set(t.loaded.filter(d=>b(d.name)===i||typeof d.source_package=="string"&&b(d.source_package)===i||(d.source_aliases??[]).some(l=>b(l)===i)).map(d=>b(d.name)).concat(i)),s=a===null?o:o.filter(d=>a.has(b(d.name))),c=a===null?{}:{extensionNames:[...a]};return{target:typeof e=="string"?e.trim():null,total:s.length,extensions:s,union:Je(n,c),command_ownership:vl(n,a)}}var bl={ok:"loaded",failed:"activation failed",not_loaded:"not loaded"};function Pg(e,t){let r=[`# ${`${t[0].toUpperCase()}${t.slice(1)}`} surface reference`,""];if(r.push(e.target===null?`Scope: all loaded ${t}s`:`Scope: \`${e.target}\``),r.push(`Described: ${e.total} ${t}${e.total===1?"":"s"}`,""),(e.command_ownership?.length??0)>0){r.push("## Command ownership","");for(let o of e.command_ownership){let i=o.claimants.find(s=>s.winner),a=o.claimants.map(s=>`${s.layer}:${s.name}`).join(", ");r.push(`- \`${o.command}\` (${o.surface}): ${i.layer}:${i.name}; policy=${o.policy}; collision=${String(o.collision)}; claimants=${a}`)}r.push("")}if(e.extensions.length===0)return r.push(`_No ${t}s are loaded._`,""),`${r.join(`
|
|
40
|
-
`).trimEnd()}
|
|
41
|
-
`;for(let o of e.extensions){let i=`${o.name} (${o.layer} v${o.version}, ${bl[o.activation_status]})`;r.push(jn(o.surfaces,{title:i,headingLevel:2}))}return e.extensions.length>1&&r.push(jn(e.union,{title:`Union across all described ${t}s`,headingLevel:2})),`${r.join(`
|
|
42
|
-
`).trimEnd()}
|
|
43
|
-
`}import kl from"node:fs/promises";import xl 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]="56290db9-933c-590d-8b9f-df62ff45e515")}catch{}})();function Ln(e){return xl.join(e,"extension-migrations.json")}function Ei(e,t){let n=e.definition.id;return typeof n=="string"&&n.trim().length>0?n.trim():`migration-${String(t+1).padStart(3,"0")}`}function $i(e,t){return`${e.layer}:${e.name}:${t}`}async function Sl(e){let t=Ln(e);if(!await x(t))return{version:1,updated_at:"",entries:[]};let n=JSON.parse(await kl.readFile(t,"utf8"));return{version:1,updated_at:typeof n.updated_at=="string"?n.updated_at:"",entries:Array.isArray(n.entries)?n.entries.filter(r=>typeof r?.key=="string"&&(r.status==="applied"||r.status==="failed")):[]}}async function El(e,t){let n=await Sl(e),r=new Map(n.entries.map(o=>[o.key,o]));return t.forEach((o,i)=>{let a=Ei(o,i),s=r.get($i(o,a));s&&(o.definition.status=s.status,s.status==="failed"?o.definition.reason=s.error:(delete o.definition.reason,delete o.definition.error,delete o.definition.message))}),n}async function $l(e){let t=await El(e.pmRoot,e.migrations),n=new Map(t.entries.map(l=>[l.key,l])),r=[],o=!1,i=e.migrations.map((l,p)=>({migration:l,index:p})).filter(({migration:l})=>e.scope===void 0||l.layer===e.scope);for(let{migration:l,index:p}of i){let u=Ei(l,p),f=$i(l,u),y=n.get(f),w=String(l.definition.status??"pending").toLowerCase(),m=y?.status??(w==="applied"||w==="failed"?w:"pending");if(m==="applied"){r.push({key:f,layer:l.layer,extension:l.name,id:u,before:m,outcome:"skipped"});continue}if(e.dryRun===!0){r.push({key:f,layer:l.layer,extension:l.name,id:u,before:m,outcome:"pending"});continue}let _=l.runtime_definition?.run??l.definition.run;if(typeof _!="function"){r.push({key:f,layer:l.layer,extension:l.name,id:u,before:m,outcome:"pending"});continue}let v=new Date().toISOString();try{await Promise.resolve(_({id:u,command:"migration",layer:l.layer,extension:l.name,pm_root:e.pmRoot,status:m}));let k={key:f,layer:l.layer,extension:l.name,id:u,status:"applied",attempted_at:v};n.set(f,k),l.definition.status="applied",delete l.definition.reason,delete l.definition.error,delete l.definition.message,r.push({key:f,layer:l.layer,extension:l.name,id:u,before:m,outcome:"applied"}),o=!0}catch(k){let S=k instanceof Error?k.message:String(k),C={key:f,layer:l.layer,extension:l.name,id:u,status:"failed",attempted_at:v,error:S};n.set(f,C),l.definition.status="failed",l.definition.reason=S,r.push({key:f,layer:l.layer,extension:l.name,id:u,before:m,outcome:"failed",error:S}),o=!0}}if(o){let l=await O(e.pmRoot),p={version:1,updated_at:new Date().toISOString(),entries:[...n.values()].sort((u,f)=>u.key.localeCompare(f.key))};await Ge({pmRoot:e.pmRoot,filePath:Ln(e.pmRoot),raw:`${JSON.stringify(p,null,2)}
|
|
44
|
-
`,op:"extension_migrations_apply",author:e.author,lockTtlSeconds:l.locks.ttl_seconds,lockWaitMs:l.locks.wait_ms})}let a=r.filter(l=>l.outcome==="pending").length,s=r.filter(l=>l.outcome==="applied").length,c=r.filter(l=>l.outcome==="skipped").length,d=r.filter(l=>l.outcome==="failed").length;return{ok:d===0,dry_run:e.dryRun===!0,state_path:Ln(e.pmRoot),total:r.length,pending_count:a,applied_count:s,skipped_count:c,failed_count:d,migrations:r}}async function Ai(e){let t=await O(e.resolvedRoots.settings_root),n=await be({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),r=await ke(n);e.warnings.push(...n.warnings,...r.warnings);let o=await $l({pmRoot:e.resolvedRoots.pm_root,migrations:r.registrations.migrations,author:typeof e.global.author=="string"&&e.global.author.trim().length>0?e.global.author.trim():"pm-extension-migration",dryRun:e.options.dryRun===!0,...e.scope==="global"?{scope:"global"}:{}});return e.withResult({migration:o,load_failure_count:n.failed.length,activation_failure_count:r.failed.length},o.ok)}(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]="39bc7f14-2d32-5b58-97ab-647f9f238273")}catch{}})();async function Ii(e,t,n){let r=typeof t=="string"?null:await ut(e),o=r===null?null:e.trim().toLowerCase(),i=o===null?null:await Vo(o),a=Mt(r??e,{forceGithub:typeof t=="string",ref:n}),s=o===null?null:await ei(e);return{bundledAliasName:o,bundledPackageName:i,installSource:a,sourceResolution:{requested:e,selected:{kind:o===null?a.kind:"builtin",input:o??a.input,...i===null?{}:{package:i}},ambiguous:s!==null,precedence:"bundled_alias_before_installed_npm",candidates:[...o===null?[]:[{kind:"builtin",input:o,...i===null?{}:{package:i},command:`pm install ${o}`}],...s===null?[]:[{kind:"npm",input:`npm:${s.package}`,package:s.package,...s.version===void 0?{}:{version:s.version},directory:s.directory,command:`pm install npm:${s.package}`}]]}}}import Te from"node:fs/promises";import re 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]="54ce5bae-db04-5c19-81df-093802bf41c7")}catch{}})();function Fn(e){return e.map(({layer:t,name:n,error:r})=>({layer:t,name:n,error:r}))}function Ut(e,t,n){let r=b(t),o=n.trim();if(r.length===0||o.length===0)return;let i=e.get(r)??new Set;i.add(o),e.set(r,i)}function Al(e){let t=new Map,n=new Map;for(let r of e.registrations.commands)Ut(t,r.name,r.command),Ut(n,r.name,r.action);for(let r of e.commands.handlers)Ut(t,r.name,r.command);for(let r of e.commands.overrides)Ut(t,r.name,r.command);return{commandPathsByExtension:t,actionPathsByExtension:n}}function Ti(e){if(!(!e||e.size===0))return[...e].sort((t,n)=>t.localeCompare(n))}function Il(e){let{enabled:t,normalizedName:n,loadedNames:r,loadFailedNames:o,activationFailedNames:i}=e;return t?o.has(n)||i.has(n)?{runtime_active:!1,activation_status:"failed"}:r.has(n)?{runtime_active:!0,activation_status:"ok"}:{runtime_active:!1,activation_status:"not_loaded"}:{runtime_active:!1,activation_status:"not_loaded"}}function zt(e,t,n){let r=new Set(t.loaded.map(c=>b(c.name))),o=new Set(t.failed.map(c=>b(c.name))),i=new Set(n.failed.map(c=>b(c.name))),{commandPathsByExtension:a,actionPathsByExtension:s}=Al(n);return e.map(c=>{let d=b(c.name),l=Ti(a.get(d)),p=Ti(s.get(d)),u={...l?{command_paths:l}:{},...p?{action_paths:p}:{}},f=Il({enabled:c.enabled,normalizedName:d,loadedNames:r,loadFailedNames:o,activationFailedNames:i});return{...c,...f,...u}})}function Tl(e){let t=0,n=0,r=0;for(let o of e)if(o.startsWith("extension_policy_")){if(t+=1,o.startsWith("extension_policy_violation_")){n+=1;continue}o.startsWith("extension_policy_blocked_")&&(r+=1)}return{warning_count:t,violation_count:n,blocked_count:r}}function U(e,t){return e.vocabulary==="package"?`pm package --${t}`:`pm extension --${t}`}var Ri=new Set(["extension_command_handler_collision","extension_command_override_collision","extension_command_override_handler_overlap","extension_parser_override_collision","extension_preflight_override_collision","extension_renderer_collision","extension_service_override_collision"]);function Ol(e){return Ri.has(Fi(e))}function Oi(e){return e==="project"||e==="global"}function Pi(e){let t=e.split(":"),n=t[0];if(!n||!Ri.has(n))return null;let r=t.at(-4),o=t.at(-3)?.trim(),i=t.at(-2),a=t.at(-1)?.trim();return!Oi(r)||!Oi(i)||!o||!a?null:{code:n,surface:t.slice(1,-4).join(":")||"global",winner:{layer:r,name:o},displaced:{layer:i,name:a}}}function Cl(e){let t=new Set;for(let n of e){let r=Pi(n);r&&(t.add(r.winner.name),t.add(r.displaced.name))}return[...t].sort((n,r)=>n.localeCompare(r))}function Rl(e,t){let n=e.filter(Ol);if(n.length===0)return null;let r=Cl(n);return`Extension registration collisions or handler/override overlaps detected.${r.length>0?` Conflicting extensions: ${r.join(", ")}.`:""} Single-winner surfaces can hide earlier package behavior. Deactivate one conflicting package with ${t.deactivate}, or scope registration surfaces in extensions.policy.extension_overrides, then rerun ${t.doctor}.`}function Pl(e,t,n,r){let o=t.map(p=>Pi(p)).filter(p=>p!==null).sort((p,u)=>`${p.code}:${p.surface}:${p.winner.name}:${p.displaced.name}`.localeCompare(`${u.code}:${u.surface}:${u.winner.name}:${u.displaced.name}`));if(o.length===0)return;let i=e==="global"?"--global":"--project",a=U(r,"deactivate"),s=`${U(r,"doctor")} ${i} --detail deep --trace`,c=new Map(n.map(p=>[b(p.name),p])),d=new Map;for(let p of o)for(let u of[p.winner.name,p.displaced.name]){let f=b(u);d.set(f,(d.get(f)??0)+1)}let l=[...d.entries()].map(([p,u])=>{let f=c.get(p),y=f?.name??p,w=f?.command_paths??[],m=f?.action_paths??[];return{action:"deactivate",extension:y,command:`${a} ${y} ${i}`,affected_collisions:u,feature_loss:{command_paths:[...w].sort((_,v)=>_.localeCompare(v)),action_paths:[...m].sort((_,v)=>_.localeCompare(v))}}}).sort((p,u)=>{let f=u.affected_collisions-p.affected_collisions;if(f!==0)return f;let y=p.feature_loss.command_paths.length+p.feature_loss.action_paths.length,w=u.feature_loss.command_paths.length+u.feature_loss.action_paths.length;return y!==w?y-w:p.extension.localeCompare(u.extension)});return{status:"conflicts_detected",collision_count:o.length,extension_count:d.size,next_best_command:s,collisions:o,remediation_candidates:l}}function Ni(e){let t=[];for(let n of e){let r=n.error.toLowerCase();(r.includes("cannot find package '@unbrained/pm-cli'")||r.includes('cannot find module "@unbrained/pm-cli"')||r.includes("cannot find module '@unbrained/pm-cli'"))&&t.push(`extension_load_failed_sdk_dependency_missing:${n.name}`),(r.includes("cannot use import statement outside a module")||r.includes("to load an es module")||r.includes("must use import to load es module"))&&t.push(`extension_load_failed_module_mode_mismatch:${n.name}`)}return[...new Set(t)].sort((n,r)=>n.localeCompare(r))}function Di(e=[]){let t=Array.isArray(e)?e:[],n=[];for(let r of t){if(!r||typeof r.name!="string")continue;let o=r.trace?.missing_capability??r.trace?.capability;typeof o=="string"&&o.trim().length>0&&n.push(`extension_capability_missing:${r.name}:${o.trim().toLowerCase()}`)}return[...new Set(n)].sort((r,o)=>r.localeCompare(o))}function ji(e,t){let n=[];for(let r of kr(e.loaded,t))for(let o of r.unused)n.push(`extension_capability_unused:${r.layer}:${r.name}:${o}`);return[...new Set(n)].sort((r,o)=>r.localeCompare(o))}var Nl=[{matches:e=>e.some(t=>t.startsWith("extension_manifest_")),build:e=>`Run ${U(e.options,"explore")} ${e.scopeFlag} to inspect discovered manifests and directories.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_unknown:")),build:()=>`Unknown extension capabilities detected. Allowed capabilities: ${nr.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_legacy_alias:")),build:()=>"Legacy extension capability aliases were auto-remapped to canonical capabilities. Update manifests to canonical names (migration/validation -> schema)."},{matches:e=>e.some(t=>t.startsWith("extension_capability_missing:")),build:e=>`Extension activation failed because code registered a surface missing from manifest capabilities. Run ${U(e.options,"doctor")} ${e.scopeFlag} --detail deep --trace and add the reported missing_capability to manifest.json before publishing.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_unused:")),build:e=>`Extension manifests declare capabilities that are never registered against. Remove each reported unused capability from manifest.json to keep least privilege, or add the matching registration. Run ${U(e.options,"doctor")} ${e.scopeFlag} --detail deep --trace for per-extension registration counts.`},{matches:e=>e.some(t=>t.startsWith("extension_command_definition_legacy_handler_alias:")),build:()=>"Extension command definitions using legacy handler were auto-remapped. Update command definitions to use run: (context) => ... for forward compatibility."},{matches:e=>e.some(t=>t.startsWith("extension_output_service_override_global:")||t.startsWith("extension_output_renderer_override_global:")),build:()=>"Global output service/renderer overrides are active. For output_format, return context.payload/null/undefined unless the extension owns the command. For renderers, return null for unrelated payloads so pm falls back to native rendering."},{matches:e=>e.some(t=>t.startsWith("extension_schema_narrow_activation:")),build:()=>"A package registers custom item types/fields (a GLOBAL schema contribution) but also declares narrow activation.commands, so it never activates for built-in commands like pm create <type> and the custom type silently fails to register. Remove activation.commands from manifest.json so pm activates the package for every command, or \u2014 if the schema is intentionally command-scoped \u2014 knowingly ignore this advisory."},{matches:e=>e.some(t=>t.startsWith("extension_load_failed_sdk_dependency_missing:")),build:e=>`Detected extension load failures caused by missing SDK dependency resolution. Ensure extension package dependencies include "@unbrained/pm-cli" and reinstall dependencies before running ${U(e.options,"doctor")} ${e.scopeFlag}.`},{matches:e=>e.some(t=>t.startsWith("extension_load_failed_module_mode_mismatch:")),build:e=>`Detected extension module-mode mismatches. For ESM-based extension entries/imports, set package.json "type": "module" or use an explicit .mjs entry and rerun ${U(e.options,"doctor")} ${e.scopeFlag}.`},{matches:e=>e.some(t=>t.startsWith("extension_pm_min_version_")||t.startsWith("extension_pm_max_version_")),build:e=>`Extension pm version-bound warnings detected. Align each package manifest's pm_min_version/pm_max_version with the installed pm CLI version (see the warning's required/allowed=...:current=... details), or upgrade/downgrade the pm CLI to satisfy the declared bounds, then rerun ${U(e.options,"doctor")} ${e.scopeFlag}.`},{matches:(e,t)=>t.updateCheckFailedTotal>0,build:e=>`Run ${U(e.options,"manage")} ${e.scopeFlag} after validating network and repository access.`},{matches:e=>e.some(t=>t.startsWith("extension_manager_state_")),build:e=>`Review and repair ${e.scope} managed extension state file if schema/read warnings persist.`},{matches:(e,t)=>t.policyWarningCount>0,build:()=>"Extension governance policy warnings detected. Review settings.extensions.policy mode and allow/block lists to confirm intended capabilities and registration surfaces."}];function Dl(e){let{normalizedWarnings:t,options:n,scope:r,scopeFlag:o,updateCheckFailedTotal:i,policyWarningCount:a,updateHealthPartial:s,skippedUnmanagedTotal:c,skippedNonGithubTotal:d,updateAvailableTotal:l}=e,p=[],u={options:n,scope:r,scopeFlag:o,updateCheckFailedTotal:i,policyWarningCount:a};if(t.length>0){let f=Rl(t,{deactivate:`${U(n,"deactivate")} <name> ${o}`,doctor:`${U(n,"doctor")} ${o} --detail deep --trace`});f&&p.push(f);for(let y of Nl)y.matches(t,u)&&p.push(y.build(u))}return s?p.push(`Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via ${U(n,"manage")} ${o} --fix-managed-state (or ${U(n,"adopt-all")} ${o}, ${U(n,"adopt")} <name> ${o}, or reinstall via ${U(n,"install")} ${o} <source>).`):c>0&&p.push(`Loaded unmanaged extensions are currently treated as informational. Use ${U(n,"manage")} ${o} --fix-managed-state to adopt them for update checks.`),d>0&&p.push("Non-GitHub managed extensions are skipped by update checks. Use doctor output for non-update diagnostics."),l>0&&p.push(`Update available managed extensions via ${U(n,"install")} ${o} <source>.`),p.length===0&&p.push(`No immediate action required. Re-run ${U(n,"manage")} ${o} after extension changes.`),p}function Jt(e,t,n,r={}){let o=[...new Set(t)].sort(($,J)=>$.localeCompare(J)),i=n.filter($=>$.managed).length,a=n.filter($=>$.enabled).length,s=n.filter($=>$.active).length,c=n.filter($=>$.update_available===!0).length,d=n.filter($=>$.managed===!1),l=d.filter($=>Ci($)).map($=>$.name).sort(($,J)=>$.localeCompare(J)),p=d.filter($=>!Ci($)).map($=>$.name).sort(($,J)=>$.localeCompare(J)),u={checked:0,skipped_unmanaged:0,skipped_non_github:0,failed:0,not_checked:0};for(let $ of n)u[$.update_check_status]+=1;let f=u.failed,y=u.skipped_unmanaged,w=u.skipped_non_github,m=p.length>0,_=m?"partial":"full",v=m?[`extension_update_health_partial_coverage:skipped_unmanaged:${p.length}`]:[],k=[...new Set([...o,...v])].sort(($,J)=>$.localeCompare(J)),S=[...new Set(k.map($=>Fi($)))].sort(($,J)=>$.localeCompare(J)),C=Tl(k),G=e==="global"?"--global":"--project",M=Pl(e,o,n,r),ce=Dl({normalizedWarnings:o,options:r,scope:e,scopeFlag:G,updateCheckFailedTotal:f,policyWarningCount:C.warning_count,updateHealthPartial:m,skippedUnmanagedTotal:y,skippedNonGithubTotal:w,updateAvailableTotal:c});return{status:k.length===0?"ok":"warn",warning_count:k.length,warning_codes:S,warnings:k,policy_warning_count:C.warning_count,policy_violation_count:C.violation_count,policy_blocked_count:C.blocked_count,total_extensions:n.length,managed_total:i,enabled_total:a,active_total:s,update_available_total:c,update_health_coverage:_,update_health_partial:m,unmanaged_loaded_extension_count:d.length,unmanaged_loaded_extensions:d.map($=>$.name).sort(($,J)=>$.localeCompare(J)),unmanaged_expected_extension_count:l.length,unmanaged_expected_extensions:l,unmanaged_action_required_extension_count:p.length,unmanaged_action_required_extensions:p,update_check_status_totals:u,update_check_failed_total:f,top_warnings:k.slice(0,8),remediation:ce,...M?{collision_plan:M}:{}}}function Li(e){if(!e||e.trim().length===0)return"summary";let t=e.trim().toLowerCase();if(t==="summary"||t==="deep")return t;throw new h(`Invalid --detail value "${e}". Expected summary or deep.`,g.USAGE)}function Fi(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function Mi(e){let t=new Set,n=[];for(let r of e){let o=(()=>{let i=mr(r);return i?[i]:fr(r)})();for(let i of o){let a=`${i.layer}:${i.name}:${i.capability}`;t.has(a)||(t.add(a),n.push(i))}}return n}function Gi(){return{version:wt.version,capabilities:[...wt.capabilities],legacy_aliases:{...wt.legacy_aliases}}}function Ci(e){let t=b(e.name),n=b(e.directory);return t.startsWith("builtin-")?!0:n==="beads"||n==="todos"}function Ui(e,t,n,r,o){if(e!=="project"||o)return{warnings:[],summary:{active_project_count:0,loaded_project_count:0,active_project_names:[],loaded_project_names:[],missing_active_project_names:[]}};let i=[...new Set(t.filter(l=>l.active).map(l=>b(l.name)))].sort((l,p)=>l.localeCompare(p)),a=[...new Set(n.filter(l=>l.layer==="project").map(l=>b(l.name)))].sort((l,p)=>l.localeCompare(p)),s=new Set(r.map(l=>b(l.name))),c=i.filter(l=>!a.includes(l)&&!s.has(l)).sort((l,p)=>l.localeCompare(p));return{warnings:c.length>0?[`extension_doctor_consistency_active_not_loaded:${c.join(",")}`]:[],summary:{active_project_count:i.length,loaded_project_count:a.length,active_project_names:i,loaded_project_names:a,missing_active_project_names:c}}}import{randomUUID as jl}from"node:crypto";import F from"node:fs/promises";import Ll from"node:os";import P 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]="b100fde9-412b-587b-85ac-532117e2253f")}catch{}})();var zi=3,Fl=120,Ji=250,Ml=12e4,Gl=new Set(["EEXIST","ENOTEMPTY","ENOENT"]),qi=e=>typeof e=="object"&&e!==null&&"code"in e?e.code:void 0,Bi=e=>Gl.has(String(qi(e))),qt=(e,t)=>qi(e)===t,Wi=e=>new Promise(t=>{setTimeout(t,e)}),Hi=async e=>{let t=P.join(e,"package.json");await x(t)||await F.writeFile(t,`${JSON.stringify({type:"module"},null,2)}
|
|
45
|
-
`,"utf8")},Ki=async e=>{let t=de(import.meta.url,["../../.."]),n=P.join(e,"node_modules","@unbrained"),r=P.join(n,"pm-cli");await F.mkdir(n,{recursive:!0}),await F.rm(r,{recursive:!0,force:!0}),await F.symlink(t,r,process.platform==="win32"?"junction":"dir")},Mn=async e=>{let t=P.resolve(e),n=P.dirname(t),r=P.parse(n).root,o=await F.realpath(r).catch(()=>r),i=P.relative(r,n),a=i===""?[]:i.split(P.sep);for(let[s,c]of a.entries()){let d=P.join(o,c);try{o=await F.realpath(d)}catch{o=P.join(o,...a.slice(s));break}}return P.join(o,P.basename(t))},Vi=async(e,t,n,r=Ll.tmpdir())=>Me("extension_install_copy",async()=>{let o=P.resolve(e),i=await F.realpath(o).catch(()=>o),a=await Mn(t);if(i===a)return;if(!te(i,a)){await n(e,t,{recursive:!0,force:!0});return}let s=u=>{let f=P.resolve(u);if(f!==o&&!te(o,f))return!1;let y=P.resolve(i,P.relative(o,f));if(y===a||te(a,y))return!1;let m=P.relative(i,y).split(P.sep);return m.some(_=>_==="node_modules"||_.startsWith(".pm-extension-install-backup-"))?!1:m[0]!==".agents"},c=await F.realpath(P.resolve(r)).catch(()=>Mn(r)),d=te(i,c)?P.dirname(i):c;if(te(i,d))throw new h(`Extension source "${e}" contains its install destination and no external staging directory is available. Install a narrower package directory instead.`,g.USAGE,{code:"extension_install_source_contains_destination"});let l=await F.mkdtemp(P.join(d,"pm-extension-copy-")),p=P.join(l,"extension");try{await n(e,p,{recursive:!0,force:!0,filter:s}),await n(p,t,{recursive:!0,force:!0})}finally{await F.rm(l,{recursive:!0,force:!0})}}),Yi=async(e,t,n=F.cp)=>{for(let r=1;r<=zi;r+=1)try{await Me("extension_install_copy",async()=>{await F.rm(t,{recursive:!0,force:!0}),await Vi(e,t,n)});return}catch(o){if(!Bi(o)||r===zi)throw o;await Wi(Ji)}},Gn=async e=>{let t;try{t=await F.readFile(P.join(e,"owner.json"),"utf8")}catch(o){if(!_t(o))throw o;return null}let n;try{n=JSON.parse(t)}catch{return null}if(typeof n!="object"||n===null||!("token"in n))return null;let r=n.token;return typeof r=="string"&&r.length>0?r:null},Xi=async(e,t)=>await Gn(e)!==t?!1:(await F.rm(e,{recursive:!0,force:!0}),!0),Ul=async(e,t)=>{let n;try{n=await F.stat(e)}catch{return!1}if(Date.now()-n.mtimeMs<=t)return!1;let r=await Gn(e);return r===null?(await F.rm(e,{recursive:!0,force:!0}),!0):Xi(e,r)},zl=(e,t,n)=>{let r=Promise.resolve(),o=setInterval(()=>{r=r.then(async()=>{if(await Gn(e)!==t)return;let i=new Date;await F.utimes(e,i,i)}).catch(()=>{})},n);return o.unref(),async()=>{clearInterval(o),await r}},Jl=async(e,t)=>{await F.mkdir(e);try{await F.writeFile(P.join(e,"owner.json"),`${JSON.stringify(t,null,2)}
|
|
46
|
-
`,"utf8")}catch(n){throw await F.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}},ql=async(e,t,n,r,o)=>{for(let i=1;i<=n;i+=1)try{return await Jl(e,t),!0}catch(a){if(!qt(a,"EEXIST"))throw a;await Ul(e,o)?i-=1:await Wi(r)}return!1},Un=async(e,t,n,r)=>{let o=P.join(e,"runtime","extension-install-locks"),i=P.join(o,"scope.lock");await F.mkdir(o,{recursive:!0});let{attempts:a=Fl,delay_ms:s=Ji,stale_ms:c=Ml,heartbeat_ms:d}=r??{};if(![a,s,c,d].filter(_=>_!==void 0).every(Number.isFinite))throw new h("Extension install lock timings must be finite numbers.",g.USAGE);let l=Math.max(1,Math.floor(a)),p=Math.max(0,Math.floor(s)),u=Math.floor(c),f=Math.floor(d??u/3);if(u<=0||f<=0||f>=u)throw new h("Extension install lock timings require stale_ms > 0 and 0 < heartbeat_ms < stale_ms.",g.USAGE);let y={pid:process.pid,token:jl(),created_at:I(),destination:t};if(!await ql(i,y,l,p,u))throw new h(`Timed out waiting for extension install lock for "${t}".`,g.CONFLICT);let m=zl(i,y.token,f);try{return await n()}finally{await m(),await Xi(i,y.token).catch(()=>!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]="4d3c62e9-9116-5cdc-bbda-48bbd2e39476")}catch{}})();var Qi=async(e,t,n)=>{if(!Number.isInteger(t)||t<1)throw new RangeError("concurrency must be a positive integer");let r=new Array(e.length),o=0,i=Array.from({length:Math.min(t,e.length)},async()=>{for(;o<e.length;){let a=o;o+=1,r[a]=await n(e[a])}});return await Promise.all(i),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]="b17dfc10-9e07-5912-b294-c5663133f192")}catch{}})();function Zi(e,t){let n=b(e),r=t.find(o=>b(o.name)===n);return{command_paths:[...r?.command_paths??[]].sort((o,i)=>o.localeCompare(i)),action_paths:[...r?.action_paths??[]].sort((o,i)=>o.localeCompare(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]="e5a4cea9-ac5d-5bda-9f7c-6cf8cf9e9998")}catch{}})();function ea(e,t){let n=new Set((t?.loaded??[]).flatMap(i=>(i.activation?.commands?.length??0)>0?[`${i.layer}:${b(i.name)}`]:[])),r=e.services.overrides.filter(i=>i.service==="output_format").filter(i=>i.passThrough!==!0).filter(i=>!n.has(`${i.layer}:${b(i.name)}`)).map(i=>`extension_output_service_override_global:${i.service}:${i.layer}:${i.name}`),o=e.renderers.overrides.filter(i=>(i.commands?.length??0)===0&&i.resultDiscriminator===void 0).map(i=>`extension_output_renderer_override_global:${i.format}:${i.layer}:${i.name}`);return[...new Set([...r,...o])].sort((i,a)=>i.localeCompare(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]="17145dd7-3938-5f20-b5b5-49f8d38d3d8d")}catch{}})();var ta=e=>[...e.registrations.item_fields.flatMap(t=>t.fields.map(n=>({layer:t.layer,extension:t.name,field:n.name}))),...e.registrations.profiles.flatMap(t=>t.profile.fields.map(n=>({layer:t.layer,extension:t.name,field:n.key??""})))].flatMap(t=>{let n=Et(t.field);return n?[`extension_custom_field_mcp_input_collision:${t.layer}:${t.extension}:${n.field}:${n.property}:${n.owner}:use=${n.nested_path}`]:[]}).filter((t,n,r)=>r.indexOf(t)===n).sort((t,n)=>t.localeCompare(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]="ccb857a5-045d-57a7-91d2-b761225fe53a")}catch{}})();var Bl=1e4,Wl=(e,t,n)=>{let r=e.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).map(a=>{let[s,c=""]=a.split(/\s+/);return{commit:s,ref:c}}),o=r.find(a=>a.ref.endsWith("^{}"))??r[0];if(!o)return{checked_at:n,available:null,error:"no_remote_reference_found"};let i=t?.trim();return i?{checked_at:n,remote_commit:o.commit,available:o.commit!==i}:{checked_at:n,remote_commit:o.commit,available:null,error:"missing_installed_commit"}},na=async(e,t=Lt)=>{let n=I();if(e.kind!=="github"||!e.repository)return{checked_at:n,available:null,error:"not_a_github_managed_source"};try{let r=[e.ref?.trim(),"HEAD"].find(Boolean),o=await t(["ls-remote",e.repository,r,`${r}^{}`],void 0,Bl);return Wl(o,e.commit,n)}catch(r){return{checked_at:n,available:null,error:r instanceof Error?r.message:String(r)}}};import Hl from"node:fs/promises";import Kl 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]="5755dee7-d2df-5ced-8a94-aeb51762edb7")}catch{}})();function Vl(e){return typeof e.name=="string"&&e.name.trim().length>0?e.name.trim():"workspace-manifest"}function Yl(e,t){return t.code==="manifest_unknown_key"?`extension_manifest_unknown_key:author:${e}:key=${t.path}${t.suggested_key?`:suggested=${t.suggested_key}`:""}`:`extension_manifest_no_version_bounds:author:${e}:suggested=pm_min_version`}async function Xl(e){let t=Kl.join(e,"manifest.json"),n;try{n=await Hl.readFile(t,"utf8")}catch(s){if(_t(s))return{path:t,present:!1,parse_status:"absent",package_metadata_location:"package.json#pm",schema_findings:[],warnings:[],remediation:[]};throw s}let r;try{r=JSON.parse(n)}catch{return{path:t,present:!0,parse_status:"invalid_json",package_metadata_location:"package.json#pm",schema_findings:[],warnings:["extension_author_manifest_invalid_json:manifest.json"],remediation:["Repair manifest.json so it contains one valid JSON object, then rerun pm package doctor --project."]}}if(typeof r!="object"||r===null||Array.isArray(r))return{path:t,present:!0,parse_status:"invalid_shape",package_metadata_location:"package.json#pm",schema_findings:[],warnings:["extension_author_manifest_invalid_shape:manifest.json"],remediation:["Replace manifest.json with one JSON object, then rerun pm package doctor --project."]};let o=r,i=yr(o),a=Vl(o);return{path:t,present:!0,parse_status:"valid",package_metadata_location:"package.json#pm",schema_findings:i.findings,warnings:i.findings.map(s=>Yl(a,s)),remediation:i.findings.map(s=>s.message)}}function ra(e){return Xl(lr(e))}import Fe from"node:fs/promises";import Ql 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]="58ec3f16-267a-5a31-abd2-df46bb82b716")}catch{}})();var zn=async e=>Fe.readFile(e).catch(t=>{if(qt(t,"ENOENT"))return null;throw t}),oa=async(e,t,n,r,o)=>Me("extension_install_backup",async()=>{let i=dt(e),a=ur(t),[s,c]=await Promise.all([zn(i),zn(a)]);return r&&await Fe.cp(n,o,{recursive:!0,force:!0}),{backupDirectory:o,destinationDirectory:n,destinationExists:r,managedStatePath:i,managedStateContents:s,settingsPath:a,settingsContents:c}}),ia=async e=>Me("extension_install_rollback",async()=>{await Fe.rm(e.destinationDirectory,{recursive:!0,force:!0}),e.destinationExists&&await Fe.cp(e.backupDirectory,e.destinationDirectory,{recursive:!0,force:!0});for(let[t,n]of[[e.managedStatePath,e.managedStateContents],[e.settingsPath,e.settingsContents]])n===null?await Fe.rm(t,{force:!0}):(await Fe.mkdir(Ql.dirname(t),{recursive:!0}),await Fe.writeFile(t,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]="8d5ed026-8d61-5083-956c-9281caa0168b")}catch{}})();var Zl=4,da=[["install","install","--install"],["uninstall","uninstall","--uninstall"],["explore","explore","--explore"],["list","explore","--explore"],["manage","manage","--manage"],["describe","describe","--describe"],["reload","reload","--reload"],["doctor","doctor","--doctor"],["catalog","catalog","--catalog"],["init","init","--init"],["scaffold","init","--scaffold"],["adopt","adopt","--adopt"],["adopt-all","adopt-all","--adopt-all"],["activate","activate","--activate"],["deactivate","deactivate","--deactivate"],["migrate","migrate","--migrate"]],ep=da.map(([,,e])=>e).filter((e,t,n)=>n.indexOf(e)===t).join(", "),tp={install:"--install",uninstall:"--uninstall",explore:"--explore",manage:"--manage",describe:"--describe",reload:"--reload",doctor:"--doctor",catalog:"--catalog",adopt:"--adopt","adopt-all":"--adopt-all",activate:"--activate",deactivate:"--deactivate",migrate:"--migrate",init:"--init"},np="__pm_native_output",rp=["trusted_extensions","allowed_extensions","blocked_extensions","allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],la=["allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],op=["disabled","require_trusted","require_provenance"],pa={mode:"off",trust_mode:"off",require_provenance:!1,trusted_extensions:[],default_sandbox_profile:"none",allowed_extensions:[],blocked_extensions:[],allowed_capabilities:[],blocked_capabilities:[],allowed_surfaces:[],blocked_surfaces:[],allowed_commands:[],blocked_commands:[],allowed_actions:[],blocked_actions:[],allowed_services:[],blocked_services:[],extension_overrides:[]},ip=e=>{let t=e??pa,n={};for(let r of rp)n[r]=Z(t[r]??[]);return n},ap=(e,t)=>{for(let n of la)t[n].length>0&&(e[n]=t[n]);return e},sp=(e,t)=>{for(let n of op)t[n]===!0&&(e[n]=!0);return t.sandbox_profile&&(e.sandbox_profile=t.sandbox_profile),e},cp=e=>{let t={};for(let n of la)t[n]=Z(e[n]??[]);return t},dp=e=>{let t=typeof e.name=="string"?e.name.trim():"";return t.length===0?null:ap(sp({name:t},e),cp(e))},lp=e=>(e??[]).map(t=>dp(t)).filter(t=>t!==null).sort((t,n)=>t.name.localeCompare(n.name)),pp=e=>{let t=Object.assign({},pa,e??{}),n=ip(e),r=lp(t.extension_overrides);return{mode:t.mode,trust_mode:t.trust_mode,require_provenance:t.require_provenance===!0,trusted_extensions:n.trusted_extensions,default_sandbox_profile:t.default_sandbox_profile,allowed_extensions:n.allowed_extensions,blocked_extensions:n.blocked_extensions,allowed_capabilities:n.allowed_capabilities,blocked_capabilities:n.blocked_capabilities,allowed_surfaces:n.allowed_surfaces,blocked_surfaces:n.blocked_surfaces,allowed_commands:n.allowed_commands,blocked_commands:n.blocked_commands,allowed_actions:n.allowed_actions,blocked_actions:n.blocked_actions,allowed_services:n.allowed_services,blocked_services:n.blocked_services,extension_overrides:r}},ua=async(e,t)=>{let n=[t],r=await Yo(t);r&&n.push(r);let o=[...new Set(n.map(i=>b(i)).filter(i=>i.length>0))];for(let i of o){let a=e.find(c=>b(c.name)===i);if(a)return a;let s=e.find(c=>b(c.directory)===i);if(s)return s}},ma=(e,t)=>{let n=t.trim(),r=new Set(Z(e.extensions.enabled));return new Set(Z(e.extensions.disabled)).has(n)?!1:r.size===0?!0:r.has(n)},fa=(e,t)=>{let n=t.trim(),r=new Set(Z(e.extensions.enabled)),o=new Set(Z(e.extensions.disabled)),i=[...r],a=[...o];return o.delete(n),r.size>0&&r.add(n),e.extensions.enabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...o].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==i.join("\0")||e.extensions.disabled.join("\0")!==a.join("\0")},up=(e,t)=>{let n=t.trim(),r=new Set(Z(e.extensions.enabled)),o=new Set(Z(e.extensions.disabled)),i=[...r],a=[...o];return r.delete(n),o.add(n),e.extensions.enabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...o].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==i.join("\0")||e.extensions.disabled.join("\0")!==a.join("\0")},mp=(e,t)=>{let n=t.trim(),r=new Set(Z(e.extensions.enabled)),o=new Set(Z(e.extensions.disabled)),i=[...r],a=[...o];return r.delete(n),o.delete(n),e.extensions.enabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...o].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==i.join("\0")||e.extensions.disabled.join("\0")!==a.join("\0")},fp=e=>{let t=e.trim().toLowerCase(),n=Math.min(2,Math.max(1,Math.ceil(t.length/4))),r=da.map(([o,i,a])=>({action:i,flag:a,distance:ar(t,o,n)})).filter(o=>o.distance!==null).sort((o,i)=>o.distance-i.distance)[0];return r?{action:r.action,flag:r.flag}:null},hp=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",r=fp(e);if(!r)return new h(`One action flag is required. Use one of: ${ep}. Bare \`pm package\` and \`pm extension\` default to --explore.`,g.USAGE);let o=`pm ${n} ${r.flag}`;return sr({command_path:n,display_name:`${n} lifecycle`,token_kind:"action",token:e,allowed:Object.keys(ha),retry_command:o,message_suffix:`. Did you mean "${r.flag}"?`,fallback_candidates:[{source:"lifecycle_action",command:o,reason:`nearest lifecycle action for "${e}"`}]})},gp=[["install","install"],["uninstall","uninstall"],["explore","explore"],["manage","manage"],["describe","describe"],["reload","reload"],["doctor","doctor"],["catalog","catalog"],["init","init"],["scaffold","init"],["adopt","adopt"],["adoptAll","adopt-all"],["activate","activate"],["deactivate","deactivate"],["migrate","migrate"]],ha={doctor:"doctor",reload:"reload",catalog:"catalog",init:"init",scaffold:"init",explore:"explore",manage:"manage",migrate:"migrate",list:"explore","":"explore"},yp=e=>ha[e]??null,_p=(e,t)=>{let n=[...new Set(gp.filter(([r])=>t[r]===!0).map(([,r])=>r))];if(n.length===0){if(e===void 0)return"explore";let r=yp(e.trim().toLowerCase());if(r)return r;throw hp(e,t)}if(n.length>1)throw new h("Extension action flags are mutually exclusive.",g.USAGE);return n[0]},wp=e=>{let t=e.project===!0||e.local===!0,n=e.global===!0;if(t&&n)throw new h('Options "--project/--local" and "--global" are mutually exclusive.',g.USAGE);return n?"global":"project"},vp=[e=>e?null:{status:"skipped_unmanaged",reason:"extension_not_managed"},e=>e&&e.source.kind!=="github"?{status:"skipped_non_github",reason:`managed_source_kind_${e.source.kind}`}:null,e=>{let t=typeof e?.update_error=="string"?e.update_error.trim():"";return t.length>0?{status:"failed",reason:t}:null},e=>{let t=e;return(typeof t.last_update_check_at=="string"?t.last_update_check_at.trim():"").length===0?null:{status:"checked",reason:{true:"update_available",false:"up_to_date"}[String(t.update_available)]??"checked_without_commit_baseline"}}],ga=e=>{for(let t of vp){let n=t(e);if(n)return n}return{status:"not_checked",reason:"no_update_check_recorded"}},ya=(e,t,n,r)=>{let o=n??{};return{name:e.name,directory:e.directory,version:e.version,entry:e.entry,scope:t,active:e.enabled,enabled:e.enabled,runtime_active:null,activation_status:"unknown",contributions:o.contributions,managed:!!n,source:o.source,update_available:o.update_available,last_update_check_at:o.last_update_check_at,last_update_remote_commit:o.last_update_remote_commit,update_error:o.update_error,update_check_status:r.status,update_check_reason:r.reason}},bp=(e,t,n,r)=>{let o=Object.assign({name:e,manifest_version:"unknown",manifest_entry:"unknown"},r),i=r?ma(n,r.name):!1;return{warning:`extension_manifest_missing:${t}:${e}`,summary:ya({name:o.name,directory:e,version:o.manifest_version,entry:o.manifest_entry,enabled:i},t,r,ga(r))}},kp=async(e,t,n,r,o,i)=>{let a=re.join(e,t),s=re.join(a,"manifest.json"),c=i.get(b(t));if(!await x(s))return bp(t,n,r,c);let d=Symbol("invalid-extension-manifest-json"),l=await Te.readFile(s,"utf8").then(f=>JSON.parse(f)).catch(()=>d);if(l===d)return{warning:`extension_manifest_invalid_json:${n}:${t}`};let p=Sn(l);if(!p)return{warning:`extension_manifest_invalid:${n}:${t}`};let u=o.get(b(p.name))??i.get(b(t));return{summary:ya({name:p.name,directory:t,version:p.version,entry:p.entry,enabled:ma(r,p.name)},n,u,ga(u))}},fe=async(e,t,n,r)=>{if(!await x(e))return{extensions:[],warnings:[]};let i=(await Te.readdir(e,{withFileTypes:!0})).filter(l=>l.isDirectory()).map(l=>l.name).sort((l,p)=>l.localeCompare(p)),a=new Map(r.entries.map(l=>[b(l.name),l])),s=new Map(r.entries.map(l=>[b(l.directory),l])),c=[],d=[];for(let l of i){let p=await kp(e,l,t,n,a,s);p.warning&&c.push(p.warning),p.summary&&d.push(p.summary)}return{extensions:d.sort((l,p)=>l.name.localeCompare(p.name)),warnings:c.sort((l,p)=>l.localeCompare(p))}},xp=vr(),Sp=(e,t)=>[t.package,t.kind==="builtin"?t.name:void 0].find(n=>n?.trim())?.trim()??e,Ep=(e,t,n,r)=>{let o=n.command_paths.map(s=>`pm ${s} --help`),i=r?.error.toLowerCase().includes("@unbrained/pm-cli")===!0,a=n.command_paths.length>0?[...o]:["Run pm package doctor --project --detail deep if expected package commands are missing."];return i&&a.unshift("Install @unbrained/pm-cli in the target workspace so declarative package runtime imports resolve, then reinstall the package."),{package_name:Sp(e,t),extension_name:e,command_paths:n.command_paths,action_paths:n.action_paths,help_commands:o,next_steps:a,...i?{sdk_dependency_status:"missing"}:{}}},$p=e=>{let t=e.trace,n={layer:e.layer,name:e.name,entry_path:e.entry_path,error:e.error};return t&&(n.trace=Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0)),t.missing_capability&&(n.missing_capability=t.missing_capability),t.hint&&(n.hint=t.hint)),n},_a=e=>e.map(t=>$p(t)).sort((t,n)=>`${t.layer}:${t.name}`.localeCompare(`${n.layer}:${n.name}`)),wa=(e,t,n)=>{let r=b(e);return t.find(o=>(n===void 0||o.layer===n)&&b(o.name)===r)},Ap=(e,t,n,r)=>n.find(i=>i.scope===t&&b(i.name)===b(e))?.activation_status??(r?"failed":"unknown"),va=(e,t,n,r,o)=>xp.enqueue(async()=>{let i=process.env.PM_CLI_PACKAGE_ROOT,a=await Te.mkdtemp(re.join(t,".pm-module-graph-"));process.env.PM_CLI_PACKAGE_ROOT=de(import.meta.url,["../.."]);try{let s=await be({pmRoot:e,settings:n,cwd:process.cwd(),noExtensions:o.noExtensions===!0,reload_token:en(),cache_bust:!0,module_graph_snapshot_root:a}),c=await ke({...s}),d=[...s.failed.map(p=>({layer:p.layer,name:p.name,entry_path:p.entry_path,error:p.error})),..._a(c.failed)],l=Object.fromEntries(s.loaded.map(p=>[b(p.name),gr(Je(c,{extensionName:p.name}))]));return{installed:zt(r,s,c),warnings:[...s.warnings,...c.warnings],activation_failures:d,extensions_disabled:s.disabled_by_flag,item_type_registrations:c.registrations.item_types,contribution_inventories:l}}finally{await Te.rm(a,{recursive:!0,force:!0}),i===void 0?delete process.env.PM_CLI_PACKAGE_ROOT:process.env.PM_CLI_PACKAGE_ROOT=i}}),qn=async(e,t,n,r)=>{let o=n.filter(c=>!c.managed),i=[...o].sort((c,d)=>{let l=c.name.localeCompare(d.name);return l!==0?l:c.directory.localeCompare(d.directory)}),a=r,s=[];for(let c of i){let d=re.join(e,c.directory),l=await Qe(d),p=I(),u={kind:"local",input:c.name,location:d};a=pt(a,{name:l.manifest.name,directory:c.directory,scope:t,manifest_version:l.manifest.version,manifest_entry:l.manifest.entry,capabilities:[...l.manifest.capabilities],contributions:l.manifest.contributions,installed_at:p,updated_at:p,source:u}),s.push({name:l.manifest.name,directory:c.directory,version:l.manifest.version,entry:l.manifest.entry,source:u})}return s.length>0&&await je(e,a),{state:a,adopted_entries:s,unmanaged_candidates:i,already_managed_count:n.length-o.length}},Ip=(e,t)=>{let n=D(process.cwd(),t.path),r=bt(n,process.cwd()),o=e==="global"?pr(process.cwd()):n,i=e==="global"?r.global:r.project;return{pm_root:n,scope:e,settings_root:o,selected_root:i,roots:r}},Bt=e=>{let t=[e.gh,e.github].filter(r=>typeof r=="string").map(r=>r.trim()).filter(Boolean),n=[...new Set(t)];if(n.length>1)throw new h('Options "--gh" and "--github" must match when both are provided.',g.USAGE);return n[0]},Tp=e=>tp[e],Op=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",r=e==="install"?"source":"name",o=`${n} ${r}`,i=Tp(e),a=`<${r}>`,s=`pm ${n} ${i} ${a}`;throw new h(`Action "${e}" requires ${o} input.`,g.USAGE,{code:"missing_lifecycle_target",required:`Provide a ${r} target for ${e}.`,examples:[`pm ${n} ${e} ${a}`,s,`pm ${n} --help`],recovery:{attempted_command:`pm ${n} ${e}`,suggested_retry:s,fallback_candidates:[{source:"lifecycle_action",command:s,reason:`flag-form ${e} command with required ${r} target`}]}})},Wt=(e,t,n={})=>{let r=e?.trim();if(r)return r;if(t==="init")throw new h('Action "init" requires a scaffold target path (for example: pm package init ./my-package or pm extension init ./my-extension).',g.USAGE);return Op(t,n)},Cp=(e,t)=>{let n=new Set([...t.registrations.item_types.map(r=>({entry:r,count:r.types.length})),...t.registrations.item_fields.map(r=>({entry:r,count:r.fields.length}))].filter(({count:r})=>r>0).map(({entry:r})=>`${r.layer}:${b(r.name)}`));return e.loaded.filter(r=>(r.activation?.commands??[]).length>0).filter(r=>n.has(`${r.layer}:${b(r.name)}`)).map(r=>`extension_schema_narrow_activation:${r.layer}:${r.name}`).filter((r,o,i)=>i.indexOf(r)===o).sort((r,o)=>r.localeCompare(o))},Rp=(e,t)=>{let r=[{triggered:t.strictExit===!0||t.failOnWarn===!0,allowed:e==="doctor",message:"--strict-exit and --fail-on-warn are only valid with --doctor."},{triggered:t.trace===!0,allowed:e==="doctor",message:"--trace is only valid with --doctor."},{triggered:t.watch===!0,allowed:e==="reload",message:"--watch is only valid with --reload."},{triggered:t.runtimeProbe===!0,allowed:e==="manage",message:"--runtime-probe is only valid with --manage."},{triggered:t.fixManagedState===!0,allowed:e==="manage"||e==="doctor",message:"--fix-managed-state is only valid with --manage or --doctor."},{triggered:t.isolated===!0||t.ignoreGlobal===!0,allowed:e==="doctor",message:"--isolated and --ignore-global are only valid with --doctor."},{triggered:t.capability!==void 0,allowed:e==="init",message:"--capability is only valid with --init/--scaffold."},{triggered:t.declarative===!0,allowed:e==="init",message:"--declarative is only valid with --init/--scaffold."},{triggered:t.dryRun===!0,allowed:e==="migrate",message:"--dry-run is only valid with --migrate."}].find(o=>o.triggered&&!o.allowed);if(r)throw new h(r.message,g.USAGE)},Pp=(e,t,n)=>{let r=String(e??"").trim().toLowerCase(),o=[n.init,n.scaffold].includes(!0);return({doctor:["doctor"],reload:["reload"],catalog:["catalog"],init:o?[]:["init","scaffold"]}[t]??[]).includes(r)?void 0:e},Np=e=>[e.action==="catalog",typeof e.options.fields=="string",String(e.options.fields).trim().length>0].every(Boolean)?{project:"project",global:"global",selected:e.scope,settings_root:"project"}:{project:e.resolvedRoots.roots.project,global:e.resolvedRoots.roots.global,selected:e.resolvedRoots.selected_root,settings_root:e.resolvedRoots.settings_root},Dp=(e,t,n)=>{let r={ok:n,action:e.action,scope:e.scope,roots:Np(e),warnings:[...new Set(e.warnings)].sort((o,i)=>o.localeCompare(i)),details:t};return e.action==="doctor"&&Object.defineProperty(r,np,{value:!0,enumerable:!1,configurable:!1}),r},Bn=async(e,t,n)=>{let r=_p(e,t);Rp(r,t);let o=Pp(e,r,t),i=wp(t),a=Ip(i,n),c={action:r,normalizedTarget:o,scope:i,resolvedRoots:a,warnings:[],options:t,global:n},l={...c,withResult:(p,u=!0)=>Dp(c,p,u)};return await fu(l)},jp=(e,t)=>{let n=t.vocabulary??"extension",r=e.target_path.replace(/\\/g,"/"),o=$r(r),i={package:`Install dependencies: cd ${o}, then run "npm install"`,extension:`Install type-check dependencies: cd ${o}, then run "npm install -D typescript @types/node @unbrained/pm-cli"`},a={package:`Validate the package: cd ${o}, then run "npm run typecheck" and "npm test"`,extension:`Type-check the source (optional): cd ${o}, then run "npx tsc --noEmit"`},s=[];return[n==="package",t.declarative===!0].every(Boolean)&&s.push("Ensure the target workspace can resolve @unbrained/pm-cli before installing this declarative package."),[i[n],...s,`Install the scaffold: ${St(n==="package"?["install","--project",r]:["extension","--install","--project",r])}`,`Smoke-test command path: pm ${e.command_name}`,a[n],`Run diagnostics: ${n==="package"?"pm package doctor":"pm extension --doctor"} --project --detail summary`]},Lp=async e=>{let{action:t,normalizedTarget:n,options:r,withResult:o}=e;if([Bt(r),r.ref].filter(d=>typeof d=="string").map(d=>d.trim()).filter(Boolean).length>0)throw new h('Action "init" does not accept --gh/--github/--ref options.',g.USAGE);let s=Wt(n,t,r),c=await wi(s,r.vocabulary??"extension",r.capability,r.declarative===!0);return o({scaffolded:c.created_directory||c.files.some(d=>d.status==="created"),extension:{name:c.extension_name,command:c.command_name},capability:c.capability,style:c.style,target_path:c.target_path,created_directory:c.created_directory,files:c.files,next_steps:jp(c,r)})},Fp=async e=>{let{normalizedTarget:t,resolvedRoots:n,warnings:r,options:o,global:i,withResult:a}=e;if(t!==void 0)throw new h('Action "reload" does not accept a target argument.',g.USAGE);let s=await O(n.settings_root),c=en(),d=await be({pmRoot:n.settings_root,settings:s,cwd:process.cwd(),noExtensions:i.noExtensions,reload_token:c,cache_bust:!0});r.push(...d.warnings);let l=await ke(d);r.push(...l.warnings);let p={reload:{token:c,cache_bust:!0,watch:o.watch===!0},loaded_count:d.loaded.length,failed_count:d.failed.length,activated_count:Math.max(0,d.loaded.length-l.failed.length),activation_failed_count:l.failed.length,loaded_extensions:d.loaded.map(u=>({name:u.name,layer:u.layer,version:u.version})),failed_extensions:d.failed.map(u=>({name:u.name,layer:u.layer,error:u.error})),activation_failures:l.failed.map(u=>({name:u.name,layer:u.layer,error:u.error}))};return o.watch===!0&&r.push("extension_reload_watch_hint:watch_mode_requested_non_interactive_single_pass_only"),a(p)},Mp=async e=>{let{normalizedTarget:t,scope:n,options:r,global:o,withResult:i}=e;if(typeof t=="string"&&t.length>0&&t!=="catalog")throw new h('Action "catalog" does not accept a package target.',g.USAGE);return i(await Xo(n,o,r))},Gp=(e,t)=>({kind:"builtin",input:e,location:e,name:e,...t===null?{}:{package:t}}),Up=e=>({kind:"local",input:e.input,location:e.absolute_path}),zp=(e,t)=>({kind:"npm",input:e.input,location:t.resolved_subpath??".",package:t.npm_package,version:t.npm_version}),Jp=(e,t)=>({kind:"github",input:e.input,location:t.resolved_subpath??e.subpath??".",repository:e.repository,owner:e.owner,repo:e.repo,ref:e.ref,subpath:t.resolved_subpath??e.subpath,commit:t.commit}),qp=(e,t,n,r)=>e?Gp(e,t):n.kind==="local"?Up(n):n.kind==="npm"?zp(n,r):Jp(n,r),Bp=(e,t,n,r)=>e?e.manifest_version!==t?{installed_at:e.installed_at,updated_at:r}:qo(e.source,n)?{installed_at:e.installed_at,updated_at:e.updated_at}:{installed_at:e.installed_at,updated_at:r}:{installed_at:r,updated_at:r},Wp=async(e,t)=>{let{scope:n,resolvedRoots:r,warnings:o}=e,{validated:i,destinationDirectoryName:a}=t,s=await O(r.settings_root),c=await we(r.selected_root);o.push(...c.warnings);let d=re.join(r.selected_root,a),l=await x(d),p=await si(i.directory,d);await Te.mkdir(r.selected_root,{recursive:!0});let u=await Te.mkdtemp(re.join(r.selected_root,".pm-extension-install-backup-")),f=re.join(u,"destination");try{let y=await oa(r.selected_root,r.settings_root,d,l,f),w=qp(t.bundledAliasName,t.bundledPackageName,t.installSource,t.resolvedSource),m=c.state.entries.find(S=>b(S.name)===b(i.manifest.name)),_=Bp(m,i.manifest.version,w,I()),v=pt(c.state,{name:i.manifest.name,directory:a,scope:n,manifest_version:i.manifest.version,manifest_entry:i.manifest.entry,capabilities:[...i.manifest.capabilities],contributions:i.manifest.contributions,..._,source:w}),k=fa(s,i.manifest.name);try{p||await Yi(i.directory,d),await Hi(d),await Ki(d),await je(r.selected_root,v),k&&await Se(r.settings_root,s,"settings:write")}catch(S){try{await ia(y)}catch(C){throw new AggregateError([S,C],`Extension install failed: ${String(S)}; rollback failed: ${String(C)}`,{cause:C})}throw S}return{settings:s,managedState:v,sourceRecord:w,destinationDirectory:d,destinationExists:l,installInPlace:p,activationChanged:k}}finally{await Te.rm(u,{recursive:!0,force:!0}).catch(()=>{})}},Hp=async(e,t,n)=>{let r=n.filter(o=>b(o.name)===b(t)).flatMap(o=>o.types.map(i=>({name:i.name,folder:i.folder})));return e.scope==="project"&&r.length>0&&await at(e.resolvedRoots.pm_root,r,e.warnings,"install:type-folder"),r},Kp=(e,t,n,r,o)=>{let i=wa(t,n.activation_failures,e.scope),a=Ap(t,e.scope,n.installed,i),s=[!n.extensions_disabled,a==="ok"].every(Boolean);s||e.warnings.push(`extension_install_activation_failed:${e.scope}:${t}:${a}`);let c={true:{status:"ok",blocking_failure_count:0},false:{status:"degraded",blocking_failure_count:1}};return{activated:s,status:a,failure:i,verification:{status:c[String(s)].status,target_pm_root:e.resolvedRoots.pm_root,activation_status:a,activated:s,registered_commands:r.command_paths,registered_actions:r.action_paths,registered_item_types:o,module_graph_verification:"fresh_in_topology_snapshot",health:c[String(s)]}}},Vp=async(e,t)=>{let{scope:n,resolvedRoots:r,warnings:o,global:i,withResult:a}=e,{validated:s,destinationDirectoryName:c}=t,d=await Wp(e,t),l=await fe(r.selected_root,n,d.settings,d.managedState);o.push(...l.warnings);let p=await va(r.pm_root,re.dirname(r.selected_root),d.settings,l.extensions,i);o.push(...p.warnings);let u=await Hp(e,s.manifest.name,p.item_type_registrations),f=Zi(s.manifest.name,p.installed),y=Kp(e,s.manifest.name,p,f,u),w=p.contribution_inventories[b(s.manifest.name)];return w&&(d.managedState=await Bo(r.selected_root,d.managedState,s.manifest.name,w)),a({extension:{name:s.manifest.name,version:s.manifest.version,entry:s.manifest.entry,capabilities:s.manifest.capabilities,directory:c},source:d.sourceRecord,source_resolution:t.sourceResolution,destination_path:d.destinationDirectory,overwritten:[d.destinationExists,!d.installInPlace].every(Boolean),installed_in_place:d.installInPlace,activated:y.activated,settings_changed:d.activationChanged,runtime_activation_status:y.status,command_paths:f.command_paths,action_paths:f.action_paths,contributions:w,command_discovery:Ep(s.manifest.name,d.sourceRecord,f,y.failure),verification:y.verification,activation_diagnostics:{failed_count:p.activation_failures.length,failed:p.activation_failures,installed_extension_failed:y.failure??null}},y.activated)},Yp=async e=>{let{options:t,global:n,warnings:r,withResult:o}=e;if(typeof t.ref=="string"&&t.ref.trim().length>0)throw new h('Action "install all" does not accept --ref.',g.USAGE);let i=[],a=new Map;for(let c of await jt()){let d=await ut(c),l=re.resolve(d),p=a.get(l);p===void 0&&(p=await Bn(c,{...t,install:!0},n),a.set(l,p)),i.push({alias:c,result:p})}r.push(...i.flatMap(c=>c.result.warnings));let s=i.every(c=>c.result.ok);return o({installed_all:s,installed_count:i.filter(c=>c.result.ok).length,failed_count:i.filter(c=>!c.result.ok).length,packages:i.map(c=>{let d=c.result.details;return{alias:c.alias,ok:c.result.ok,extension:d.extension,source:d.source,source_resolution:d.source_resolution,destination_path:d.destination_path,activated:d.activated,settings_changed:d.settings_changed,command_paths:d.command_paths,action_paths:d.action_paths,command_discovery:d.command_discovery,verification:d.verification,runtime_activation_status:d.runtime_activation_status,activation_diagnostics:d.activation_diagnostics,warnings:c.result.warnings}})},s)},Xp=async(e,t,n)=>{let{resolvedRoots:r}=e,{bundledAliasName:o,bundledPackageName:i,installSource:a,sourceResolution:s}=await Ii(t,n,e.options.ref);if(s.ambiguous){let d=s.candidates.find(l=>l.kind==="npm");e.warnings.push(`extension_install_source_ambiguous:${t}:builtin:${o}:npm:${d.package}`)}let c=await ai(a);try{let d=await Qe(c.directory,{source_kind:a.kind,source_input:a.input,source_root:c.source_root}),l=Nt(d.manifest.name);return await Un(r.settings_root,l,()=>Vp(e,{validated:d,destinationDirectoryName:l,bundledAliasName:o,bundledPackageName:i,sourceResolution:s,installSource:a,resolvedSource:c}))}finally{c.cleanup&&await c.cleanup()}},Qp=async e=>{let t=Bt(e.options),n=t??Wt(e.normalizedTarget,e.action,e.options);return[t===void 0,Ho(n)].every(Boolean)?Yp(e):Xp(e,n,t)},Zp=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:o,options:i,withResult:a}=e;if(t!==void 0)throw new h('Action "adopt-all" does not accept a target argument.',g.USAGE);if(Bt(i)!==void 0||typeof i.ref=="string"&&i.ref.trim().length>0)throw new h('Action "adopt-all" does not accept --gh/--github/--ref options.',g.USAGE);let c=await O(r.settings_root),d=await we(r.selected_root);o.push(...d.warnings);let l=await fe(r.selected_root,n,c,d.state);o.push(...l.warnings);let p=await qn(r.selected_root,n,l.extensions,d.state),u=await fe(r.selected_root,n,c,p.state);o.push(...u.warnings);let f=Jt(n,o,u.extensions,i);o.push(...f.warnings);let y=new Map(u.extensions.map(_=>[`${b(_.name)}:${b(_.directory)}`,_])),w=new Map(u.extensions.map(_=>[b(_.directory),_])),m=p.adopted_entries.map(_=>{let v=b(_.directory),k=y.get(`${b(_.name)}:${v}`)??w.get(v);return{..._,...ba(k)}});return a({adopted_all:m.length>0,adopted_count:m.length,already_managed_count:p.already_managed_count,extensions:m,triage:f,warning_codes:f.warning_codes,update_health_partial:f.update_health_partial,update_health_coverage:f.update_health_coverage})},ba=e=>({update_check_status:e?.update_check_status??null,update_check_reason:e?.update_check_reason??null}),eu=(e,t,n,r)=>{if(e===void 0)return{kind:"local",input:t,location:n};let o=Mt(e,{forceGithub:!0,ref:r});if(o.kind!=="github")throw new h(`Invalid GitHub shorthand "${e}".`,g.USAGE);return{kind:"github",input:o.input,location:o.subpath??".",repository:o.repository,owner:o.owner,repo:o.repo,ref:o.ref,subpath:o.subpath}},tu=async e=>{let{action:t,normalizedTarget:n,scope:r,resolvedRoots:o,warnings:i,options:a,withResult:s}=e,c=Wt(n,t,a),d=Bt(a),l=await O(o.settings_root),p=await we(o.selected_root);i.push(...p.warnings);let u=await fe(o.selected_root,r,l,p.state);i.push(...u.warnings);let f=await ua(u.extensions,c);if(!f)throw new h(`Installed extension "${c}" was not found in ${r} scope.`,g.NOT_FOUND);if(f.managed)return s({adopted:!1,already_managed:!0,extension:{name:f.name,directory:f.directory}});let y=re.join(o.selected_root,f.directory),w=await Qe(y),m=I(),_=eu(d,c,y,a.ref),v=pt(p.state,{name:w.manifest.name,directory:f.directory,scope:r,manifest_version:w.manifest.version,manifest_entry:w.manifest.entry,capabilities:[...w.manifest.capabilities],contributions:w.manifest.contributions,installed_at:m,updated_at:m,source:_});await je(o.selected_root,v);let k=await fe(o.selected_root,r,l,v);i.push(...k.warnings);let S=k.extensions.find(C=>b(C.name)===b(w.manifest.name))??k.extensions.find(C=>b(C.directory)===b(f.directory));return s({adopted:!0,extension:{name:w.manifest.name,directory:f.directory,version:w.manifest.version,entry:w.manifest.entry},source:_,...ba(S)})},ka=async e=>{let{action:t,normalizedTarget:n,scope:r,resolvedRoots:o,warnings:i,options:a}=e,s=Wt(n,t,a),c=await O(o.settings_root),d=await we(o.selected_root);i.push(...d.warnings);let l=await fe(o.selected_root,r,c,d.state);i.push(...l.warnings);let p=await ua(l.extensions,s);if(!p)throw new h(`Installed extension "${s}" was not found in ${r} scope.`,g.NOT_FOUND);return{settings:c,managedStateRead:d,candidate:p}},nu=async e=>{let{resolvedRoots:t,withResult:n}=e,{settings:r,managedStateRead:o,candidate:i}=await ka(e),a=re.join(t.selected_root,i.directory);await Te.rm(a,{recursive:!0,force:!0});let s={...o.state,updated_at:I(),entries:o.state.entries.filter(d=>b(d.name)!==b(i.name)&&b(d.directory)!==b(i.directory))};await je(t.selected_root,s);let c=mp(r,i.name);return c&&await Se(t.settings_root,r,"settings:write"),n({removed:!0,extension:{name:i.name,directory:i.directory},destination_path:a,settings_changed:c})},aa=async e=>{let{action:t,resolvedRoots:n,warnings:r,global:o,withResult:i}=e,{settings:a,candidate:s}=await ka(e),c=t==="activate"?fa(a,s.name):up(a,s.name);c&&await Se(n.settings_root,a,"settings:write");let d=t==="activate"?await va(n.pm_root,re.dirname(n.selected_root),a,[s],o).then(l=>(r.push(...l.warnings),wa(s.name,l.activation_failures,e.scope))):void 0;return d&&r.push(`extension_activate_failed:${e.scope}:${s.name}`),i({extension:{name:s.name,directory:s.directory},active:t==="activate"&&d===void 0,runtime_active:t==="activate"&&d===void 0,activation_failure:d??null,settings_changed:c,settings:{enabled:[...a.extensions.enabled],disabled:[...a.extensions.disabled]}},d===void 0)},ru=(e,t,n,r,o,i)=>{let a=r==="package"?"package":"extension",s={package:"doctor",extension:"--doctor"}[a],c=o?.adopted_entries.length??0,d=[[i!==null,i??""],[t>0,`Run pm ${a} explore --project and pm ${a} explore --global to inspect load failures.`],[n>0,`Review activation failures in pm ${a} ${s} --detail deep output.`],[c>0,`Managed-state fix adopted ${c} extension(s).`]];return[...new Set([...e,...d.filter(([l])=>l).map(([,l])=>l)].map(l=>l.trim()).filter(l=>l.length>0))]},Jn=e=>e.loaded.some(t=>t.layer==="global")||e.failed.some(t=>t.layer==="global")||e.warnings.some(t=>t.includes(":global:")),ou=(e,t,n,r)=>{if(e!=="project"||t||!Jn(r))return null;let o=n==="package"?"package":"extension";return`Global ${o} registrations are included in project diagnostics. For hermetic ${o} smoke tests, rerun pm ${o} doctor --project --isolated --detail deep --trace, or set PM_GLOBAL_PATH to a temporary directory for the whole test process.`},iu=(e,t,n)=>{if(String(e??"").trim().length>0)throw new h('Action "doctor" does not accept a target argument.',g.USAGE);let r=[n.isolated,n.ignoreGlobal].includes(!0);if([r,t==="global"].every(Boolean))throw new h("--isolated and --ignore-global are only valid with project-scope doctor diagnostics.",g.USAGE);let o=Li(n.detail),i=n.trace===!0;if([i,o!=="deep"].every(Boolean))throw new h("--trace requires --detail deep with --doctor.",g.USAGE);return{isolated:r,detailMode:o,includeTrace:i}},au=async(e,t,n)=>{if(e.options.fixManagedState!==!0)return{state:n,fix:null};let r=await qn(e.resolvedRoots.selected_root,e.scope,t,n);return{state:r.state,fix:r}},su=(e,t,n,r)=>{let o=n==="package"?"package":"extension";if(e!=="project")return{isolated:t,global_extensions_included:!1,global_diagnostics_present:Jn(r),rerun_command:null,pm_global_path_recipe:null};let i=`pm ${o} doctor --project --isolated --detail deep --trace`;return{isolated:t,global_extensions_included:!t,global_diagnostics_present:Jn(r),rerun_command:t?null:i,pm_global_path_recipe:`PM_GLOBAL_PATH=$(mktemp -d) pm ${o} doctor --project --detail deep --trace`}},cu=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:o,options:i,global:a,withResult:s}=e,{isolated:c,detailMode:d,includeTrace:l}=iu(t,n,i),p=await O(r.settings_root),u=await we(r.selected_root);o.push(...u.warnings);let f=await fe(r.selected_root,n,p,u.state);o.push(...f.warnings);let{state:y,fix:w}=await au(e,f.extensions,u.state),m=await fe(r.selected_root,n,p,y);o.push(...m.warnings);let _=await be({pmRoot:r.pm_root,settings:p,cwd:process.cwd(),noExtensions:a.noExtensions===!0,ignoreGlobalExtensions:c}),v=await ke({..._,loaded:_.loaded}),k=await ra(r.pm_root);o.push(...k.warnings,..._.warnings),o.push(...Ni(_.failed)),o.push(...v.warnings),o.push(...Di(v.failed)),o.push(...ji(_,v)),o.push(...ea(v,_)),o.push(...Cp(_,v)),o.push(...ta(v));let S=zt(m.extensions,_,v),C=Ui(n,S,_.loaded.map(T=>({layer:T.layer,name:T.name})),_.failed.map(T=>({name:T.name})),_.disabled_by_flag);o.push(...C.warnings);let G=S.filter(T=>T.update_check_status==="failed").map(T=>`extension_update_check_failed:${T.name}`);o.push(...G);let M=Jt(n,o,S,i);o.push(...M.warnings);let ce=[...M.warnings],$={mode:_.policy.mode,trust_mode:_.policy.trust_mode,require_provenance:_.policy.require_provenance,default_sandbox_profile:_.policy.default_sandbox_profile,sandbox_enforcement:"advisory: sandbox_profile/permissions are declaration-based load gates, not runtime isolation (ADR pm-6ef3)",trusted_extensions_count:_.policy.trusted_extensions.length,allowed_extensions_count:_.policy.allowed_extensions.length,blocked_extensions_count:_.policy.blocked_extensions.length,allowed_capabilities_count:_.policy.allowed_capabilities.length,blocked_capabilities_count:_.policy.blocked_capabilities.length,allowed_surfaces_count:_.policy.allowed_surfaces.length,blocked_surfaces_count:_.policy.blocked_surfaces.length,allowed_commands_count:_.policy.allowed_commands.length,blocked_commands_count:_.policy.blocked_commands.length,allowed_actions_count:_.policy.allowed_actions.length,blocked_actions_count:_.policy.blocked_actions.length,allowed_services_count:_.policy.allowed_services.length,blocked_services_count:_.policy.blocked_services.length,extension_override_count:_.policy.extension_overrides.length},J=Mi(ce),Kt=Gi(),er=M.warning_codes,rs=ou(n,c,i.vocabulary,_),os=ru(M.remediation,_.failed.length,v.failed.length,i.vocabulary,w,rs),tr=su(n,c,i.vocabulary,_),is={status:M.status,scope:n,warning_count:M.warning_count,warning_codes:er,total_extensions:S.length,managed_total:S.filter(T=>T.managed).length,enabled_total:S.filter(T=>T.enabled).length,active_total:S.filter(T=>T.active).length,unmanaged_loaded_extension_count:M.unmanaged_loaded_extension_count,unmanaged_action_required_extension_count:M.unmanaged_action_required_extension_count,unmanaged_expected_extension_count:M.unmanaged_expected_extension_count,runtime_active_total:S.filter(T=>T.runtime_active===!0).length,activation_status_totals:{ok:S.filter(T=>T.activation_status==="ok").length,failed:S.filter(T=>T.activation_status==="failed").length,not_loaded:S.filter(T=>T.activation_status==="not_loaded").length,unknown:S.filter(T=>T.activation_status==="unknown").length},unknown_capability_count:J.length,capability_contract_version:Kt.version,update_available_total:S.filter(T=>T.update_available===!0).length,update_health_coverage:M.update_health_coverage,update_health_partial:M.update_health_partial,update_check_failed_total:S.filter(T=>T.update_check_status==="failed").length,load_failure_count:_.failed.length,activation_failure_count:v.failed.length,load_failures:Fn(_.failed),activation_failures:Fn(v.failed),blocking_failure_count:_.failed.length+v.failed.length,has_blocking_failures:_.failed.length+v.failed.length>0,consistency_warning_count:C.warnings.length,trace_enabled:l,isolation:tr,policy:$,remediation:os},as=w?{requested:!0,applied:w.adopted_entries.length>0,adopted_count:w.adopted_entries.length,already_managed_count:w.already_managed_count,adopted_extensions:w.adopted_entries.map(T=>T.name)}:{requested:!1,applied:!1,adopted_count:0,already_managed_count:m.extensions.filter(T=>T.managed).length,adopted_extensions:[]},Vt={mode:d,summary:is,triage:M,trace_enabled:l,capability_contract:Kt,capability_guidance:J,managed_state_fix:as,author_manifest:k,isolation:tr,policy:_.policy};if(d==="deep"){let T=l?v.failed:v.failed.map(N=>{let{trace:Zu,...ss}=N;return ss});Vt.deep={warnings:ce,warning_codes:er,capability_contract:Kt,capability_guidance:J,trace_enabled:l,managed_state:{path:u.path,count:y.entries.length,entries:y.entries},installed_extensions:S,load:{roots:_.roots,policy:_.policy,warnings:_.warnings,failed:_.failed,loaded:_.loaded.map(N=>({layer:N.layer,directory:N.directory,name:N.name,version:N.version,entry:N.entry,priority:N.priority}))},activation:{failed:T,warnings:v.warnings,hook_counts:v.hook_counts,registration_counts:v.registration_counts,parser_override_count:v.parser_override_count,preflight_override_count:v.preflight_override_count,service_override_count:v.service_override_count,renderer_override_count:v.renderer_override_count},consistency:C.summary},l&&(Vt.deep.trace={activation_failures:v.failed.filter(N=>N.trace!==void 0).map(N=>({layer:N.layer,name:N.name,entry_path:N.entry_path,error:N.error,method:N.trace.method,command:N.trace.command,capability:N.trace.capability,missing_capability:N.trace.missing_capability,registration_index:N.trace.registration_index,expected_schema:N.trace.expected_schema,hint:N.trace.hint,received:N.trace.received}))})}return s(Vt)},du=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:o,options:i,global:a,withResult:s}=e,c=await O(r.settings_root),d=await be({pmRoot:r.pm_root,settings:c,cwd:process.cwd(),noExtensions:a.noExtensions===!0}),l=await ke(d);o.push(...d.warnings),o.push(...l.warnings);let p=Si(t,d,l);if(t!==void 0&&p.extensions.length===0){let u=i.vocabulary==="package"?"package":"extension",f=[...new Set(d.loaded.map(w=>i.vocabulary==="package"&&typeof w.source_package=="string"&&w.source_package.trim().length>0?w.source_package.trim():w.name))].sort((w,m)=>w.localeCompare(m)),y=f.length>0?` Loaded ${u} names: ${f.join(", ")}.`:"";throw new h(`No loaded ${u} named "${t}" was found in ${n} scope.${y} Run pm ${u} explore to list discovered ${u}s.`,g.NOT_FOUND)}return s({target:p.target,total:p.total,extensions:p.extensions,union:p.union,command_ownership:p.command_ownership})},lu=async(e,t,n)=>{let r=n,o=null;if([e.action==="manage",e.options.fixManagedState===!0].every(Boolean)&&(o=await qn(e.resolvedRoots.selected_root,e.scope,t,n),r=o.state),e.action==="manage"){let i=await Qi(r.entries,Zl,async a=>{if(a.source.kind!=="github")return a;let s=await na(a.source);return{...a,last_update_check_at:s.checked_at,last_update_remote_commit:s.remote_commit,update_available:s.available,update_error:s.error}});r={...r,updated_at:I(),entries:lt(i)},await je(e.resolvedRoots.selected_root,r)}return{state:r,fix:o}},pu=async(e,t,n)=>{let r=await be({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),o=await ke({...r,loaded:r.loaded});return e.warnings.push(...r.warnings,...o.warnings),{installed:zt(n,r,o),failures:_a(o.failed),summary:{requested:!0,executed:!0,reason:e.action==="explore"?"explore_defaults_to_runtime_probe":e.options.runtimeProbe===!0?"runtime_probe_requested":"manage_defaults_to_runtime_probe",load_failure_count:r.failed.length,activation_failure_count:o.failed.length,warning_count:[...new Set([...r.warnings,...o.warnings])].length,policy:r.policy}}},uu=(e,t)=>e?{requested:!0,applied:e.adopted_entries.length>0,adopted_count:e.adopted_entries.length,adopted_extensions:e.adopted_entries.map(n=>n.name),already_managed_count:e.already_managed_count}:{requested:!1,applied:!1,adopted_count:0,adopted_extensions:[],already_managed_count:t.filter(n=>n.managed).length},sa=async e=>{let{action:t,scope:n,resolvedRoots:r,warnings:o,options:i,withResult:a}=e,s=await O(r.settings_root),c=pp(s.extensions.policy),d=await we(r.selected_root);o.push(...d.warnings);let l=await fe(r.selected_root,n,s,d.state);o.push(...l.warnings);let{state:p,fix:u}=await lu(e,l.extensions,d.state),f=await fe(r.selected_root,n,s,p);if(o.push(...f.warnings),t==="manage"){let v=f.extensions.filter(k=>k.update_check_status==="failed").map(k=>`extension_update_check_failed:${k.name}`);o.push(...v)}let y=await pu(e,s,f.extensions),w=y.installed,m=Jt(n,o,w,i);o.push(...m.warnings);let _={total:w.length,managed_total:w.filter(v=>v.managed).length,enabled_total:w.filter(v=>v.enabled).length,active_total:w.filter(v=>v.active).length,extensions:w,triage:m,policy:c};return y.failures!==void 0&&(_.activation_diagnostics={failed_count:y.failures.length,failed:y.failures}),t==="explore"&&(_.runtime_probe=y.summary),t==="manage"&&(_.runtime_probe=y.summary,_.managed_state_fix=uu(u,w)),a(_)},ca={init:Lp,install:Qp,uninstall:nu,explore:sa,manage:sa,describe:du,reload:Fp,doctor:cu,catalog:Mp,adopt:tu,"adopt-all":Zp,activate:aa,deactivate:aa,migrate:Ai},mu=e=>[e.action==="uninstall",e.action==="manage",e.action==="adopt",e.action==="adopt-all",e.action==="activate",e.action==="deactivate",e.action==="migrate",[e.action==="doctor",e.options.fixManagedState===!0].every(Boolean)].some(Boolean),fu=e=>mu(e)?Un(e.resolvedRoots.settings_root,`${e.action}-state`,()=>ca[e.action](e)):ca[e.action](e);import Kn from"node:fs/promises";import z from"node:path";import xa from"node:readline/promises";import{stdin as Sa,stdout as ht}from"node:process";(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]="542cd5ac-e4a7-51fe-8521-d0bacd9e6a07")}catch{}})();var Ea=["ask","add","skip","status"],hu=["AGENTS.md","CLAUDE.md"],gu=["pm init","pm context","pm search","pm create","pm claim","pm files","pm docs","pm test --run","pm close","pm release","pm_author"],yu=8,Vn=1,_u="<!-- pm-cli:agent-guidance:start:",wu=`<!-- pm-cli:agent-guidance:start:v${Vn} -->`,Wn="<!-- pm-cli:agent-guidance:end -->",yt="Add workflow guidance later: pm init --agent-guidance add",w_={toPortableRelativePath:Ze,ensureTrailingNewline:Hn,detectLineEnding:Aa,findGuidanceBlockRange:Yn,buildAgentGuidanceBlock:Ia,upsertAgentGuidanceBlock:Ta,resolveProjectRoot:Oa,resolveTargetGuidancePath:Ca,parsePromptChoice:Ra,pushUnique:et,promptForGuidanceWrite:Pa,normalizeAgentGuidanceState:Xn,applyAgentGuidanceState:Da,writeGuidanceFile:ja,setAgentGuidanceReadlineFactoryForTests:vu},$a=()=>xa.createInterface({input:Sa,output:ht});function vu(e){$a=e??(()=>xa.createInterface({input:Sa,output:ht}))}function Ze(e,t){let n=z.relative(e,t);return n.length===0?z.basename(t):n.split(z.sep).join("/")}function Hn(e){return e.endsWith(`
|
|
47
|
-
`)?e:`${e}
|
|
48
|
-
`}function Aa(e){return e.includes(`\r
|
|
49
|
-
`)?`\r
|
|
50
|
-
`:`
|
|
51
|
-
`}function Yn(e){let t=e.indexOf(_u);if(t===-1)return null;let n=e.indexOf(Wn,t);return n===-1?null:{start_index:t,end_index:n+Wn.length}}function bu(e){return Yn(e)!==null}function Ia(e,t="<your project test command>"){return[wu,"## pm Workflow (Agent Quickstart)","",'- Cold start with the measured canonical orientation: `pm context --limit 10 --for orient`; before item mutation, also run `pm search "<keywords>" --limit 10`, `pm list --status open --limit 20`, and `pm list --status in_progress --limit 20`.',"- Claim and execute: `pm claim <id>` then `pm update <id> --status in_progress`.",`- Link evidence while coding: \`pm files <id> --add ...\`, \`pm docs <id> --add ...\`, \`pm test <id> --add command="${t}"\`.`,'- Verify and close: `pm test <id> --run --progress`, then atomically record closure evidence with `pm close <id> "<reason>" --resolution "<what changed>" --expected "<expected outcome>" --actual "<observed outcome>" --validate-close warn`, then `pm release <id>`.',"- Author identity is automatic for supported agent harnesses; use `--author` only for an explicit override.","",Wn,""].join(e)}function Ta(e,t="<your project test command>"){let n=Aa(e),r=Ia(n,t),o=Yn(e);if(o){let s=e.slice(o.end_index),c=s.startsWith(`\r
|
|
52
|
-
`)?s.slice(2):s.startsWith(`
|
|
53
|
-
`)?s.slice(1):s,d=Hn(`${e.slice(0,o.start_index)}${r}${c}`);return{next_content:d,changed:d!==e}}let i=e.length===0?"":e.endsWith(`
|
|
54
|
-
`)?`
|
|
55
|
-
`:`
|
|
56
|
-
|
|
57
|
-
`,a=Hn(`${e}${i}${r}`);return{next_content:a,changed:a!==e}}async function ku(e){if(await x(z.join(e,"scripts","run-tests.mjs")))return"node scripts/run-tests.mjs test";let t;try{t=JSON.parse(await Kn.readFile(z.join(e,"package.json"),"utf8"))}catch{return"<your project test command>"}let n=xu(t);if(n===void 0)return"<your project test command>";let r=n.packageManager?.split("@")[0];return r==="pnpm"?"pnpm test":r==="bun"?"bun run test":r==="yarn"?"yarn test":r==="npm"?"npm test":await x(z.join(e,"pnpm-lock.yaml"))?"pnpm test":await x(z.join(e,"bun.lock"))||await x(z.join(e,"bun.lockb"))?"bun run test":await x(z.join(e,"yarn.lock"))?"yarn test":"npm test"}function xu(e){if(typeof e!="object"||e===null||!("scripts"in e))return;let t=e.scripts;if(!(typeof t!="object"||t===null||!("test"in t)||typeof t.test!="string"||t.test.trim().length===0))return{scripts:{test:t.test},..."packageManager"in e&&typeof e.packageManager=="string"?{packageManager:e.packageManager}:{}}}function Oa(e,t){let n=z.dirname(e);return z.basename(e)==="pm"&&z.basename(n)===".agents"?z.dirname(n):z.resolve(t,e)}function Ca(e,t){let n=e.find(o=>z.basename(o.file_path)==="AGENTS.md"&&o.exists);if(n)return n.file_path;let r=e.find(o=>o.exists);return r?r.file_path:z.join(t,"AGENTS.md")}function Ra(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}async function Pa(e){let t=$a();try{ht.write(`
|
|
58
|
-
Agent guidance check
|
|
59
|
-
`),ht.write(`No AGENTS.md/CLAUDE.md file currently contains compact pm workflow guidance.
|
|
60
|
-
`);let n=await t.question(`Add a compact pm workflow section to ${e}? [Y/n] `);return ht.write(`
|
|
61
|
-
`),Ra(n,!0)}finally{t.close()}}function Xn(e){let t=e.agent_guidance;return{prompt_completed:t?.prompt_completed===!0,declined:t?.declined===!0,declined_at:typeof t?.declined_at=="string"?t.declined_at:"",template_version:typeof t?.template_version=="number"&&Number.isInteger(t.template_version)&&t.template_version>0?t.template_version:Vn,last_checked_files:Array.isArray(t?.last_checked_files)?[...new Set(t.last_checked_files.map(n=>n.trim()).filter(n=>n.length>0))].sort((n,r)=>n.localeCompare(r)):[]}}async function Na(e){let t=[];for(let n of hu){let r=z.join(e,n),o=await x(r);if(!o){t.push({file_path:r,exists:o,has_guidance:!1,has_marker:!1});continue}let i=await Kn.readFile(r,"utf8"),a=i.toLowerCase(),s=gu.filter(d=>a.includes(d)),c=bu(i);t.push({file_path:r,exists:o,has_guidance:c||s.length>=yu,has_marker:c})}return t}function et(e,t){e.includes(t)||e.push(t)}function Da(e,t){let n=Xn(e),r=JSON.stringify(n)!==JSON.stringify(t);return r&&(e.agent_guidance=t),{changed:r,state:t}}async function ja(e,t=z.dirname(e)){let r=await x(e)?await Kn.readFile(e,"utf8"):"",o=Ta(r,await ku(t));return o.changed?(await he(e,o.next_content),{changed:!0,warnings:await W({path:e,scope:"project",op:"init:agent_guidance_file"})}):{changed:!1,warnings:[]}}function Su(e){return{mode:e.mode,present:e.scans.some(t=>t.has_guidance),prompted:e.prompted,applied:e.applied,skipped:e.skipped,declined:e.state.declined,prompt_completed:e.state.prompt_completed,template_version:e.state.template_version,target_file:e.targetRelativePath,checked_files:e.scans.map(t=>Ze(e.projectRoot,t.file_path)),files_with_guidance:e.scans.filter(t=>t.has_guidance).map(t=>Ze(e.projectRoot,t.file_path)),missing_files:e.scans.filter(t=>!t.exists).map(t=>Ze(e.projectRoot,t.file_path))}}async function Eu(e,t,n){return e?await Na(n):t}function gt(e,t,n){e.state={...e.state,...n,template_version:Vn,last_checked_files:t}}async function La(e,t){if(t.presentBefore)return;let n=await ja(t.targetPath,t.projectRoot);e.warnings.push(...n.warnings),n.changed&&(e.applied=!0,e.warnings.push(`agent_guidance:added:${t.targetRelativePath}`))}function $u(e,t){t||(e.warnings.push("agent_guidance:missing"),et(e.nextSteps,yt))}function Au(e,t){e.skipped=!0,gt(e,t,{prompt_completed:!0,declined:!0,declined_at:e.state.declined_at||new Date().toISOString()}),e.warnings.push("agent_guidance:explicit_skip"),et(e.nextSteps,yt)}async function Iu(e,t){await La(e,t),gt(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""})}function Tu(e,t){e.state.declined&>(e,t,{prompt_completed:!0,declined:!1,declined_at:""})}function Ou(e){e.skipped=!0,e.warnings.push("agent_guidance:skipped_declined"),et(e.nextSteps,yt)}async function Cu(e,t){if(e.prompted=!0,await Pa(t.targetRelativePath)){await La(e,t),gt(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""});return}e.skipped=!0,gt(e,t.checkedFiles,{prompt_completed:!0,declined:!0,declined_at:new Date().toISOString()}),e.warnings.push("agent_guidance:declined"),et(e.nextSteps,yt)}function Ru(e){e.warnings.push("agent_guidance:missing_non_interactive"),et(e.nextSteps,yt)}async function Pu(e,t){let n={warnings:[],nextSteps:[],prompted:!1,applied:!1,skipped:!1,state:e};return t.mode==="status"?($u(n,t.presentBefore),n):t.mode==="skip"?(Au(n,t.checkedFiles),n):t.mode==="add"?(await Iu(n,t),n):t.presentBefore?(Tu(n,t.checkedFiles),n):n.state.prompt_completed&&n.state.declined?(Ou(n),n):t.interactive?(await Cu(n,t),n):(Ru(n),n)}async function Fa(e){let t=Oa(e.pm_root,e.cwd),n=await Na(t),r=Ca(n,t),o=Ze(t,r),i=n.map(l=>Ze(t,l.file_path)),a=n.some(l=>l.has_guidance),s=await Pu(Xn(e.settings),{mode:e.mode,interactive:e.interactive,targetPath:r,targetRelativePath:o,checkedFiles:i,presentBefore:a,projectRoot:t}),c=Da(e.settings,s.state);return n=await Eu(s.applied,n,t),{summary:Su({mode:e.mode,scans:n,projectRoot:t,targetRelativePath:o,prompted:s.prompted,applied:s.applied,skipped:s.skipped,state:s.state}),warnings:s.warnings,next_steps:s.nextSteps,settings_changed:c.changed}}import Nu from"node:fs/promises";import j from"node:path";import Ga from"node:readline/promises";import{stdin as Ua,stdout as X}from"node:process";(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]="d06d4db7-8ab7-5a9f-84df-508bd305ea23")}catch{}})();var Du=Symbol.for("pm.sdk.init-invocation-cwd");function J_(e){return{ok:e.ok,path:e.path,target:e.target,id_prefix:e.settings.id_prefix,governance_preset:e.governance_preset,telemetry:{enabled:e.settings.telemetry.enabled,capture_level:e.settings.telemetry.capture_level},output_format:e.settings.output.default_format,created_dirs_count:e.created_dirs.length,created_dirs:e.created_dirs,warnings:e.warnings,wizard_used:e.wizard_used,...e.registered_type_preset?{registered_type_preset:e.registered_type_preset}:{},...e.installed_packages?{installed_packages:e.installed_packages}:{},next_steps:e.next_steps,agent_guidance:e.agent_guidance,hint:"Re-run with --verbose for the full settings tree."}}var q_={normalizeInitGovernancePreset:Qn,normalizeInitTypePreset:Ja,normalizeOptionalInitAuthor:qa,normalizeInitAgentGuidanceMode:Ha,isPathLikeInitTarget:Ht,resolveInitInvocation:Ba,resolveInitPrefixInput:Wa,parseYesNoChoice:Ka,applyGovernancePreset:Zn,runInitWizard:es,setInitReadlineFactoryForTests:ju,summarizeInstalledPackages:Va,buildInitNextSteps:ts,registerInitTypePreset:Ya,assertExplicitTrackerPathIsNotWorkspaceRoot:Qa,isLikelyWorkspaceRoot:Xa,installInitMergeFence:ns},za=()=>Ga.createInterface({input:Ua,output:X});function ju(e){za=e??(()=>Ga.createInterface({input:Ua,output:X}))}function Lu(){return structuredClone(Xt)}var Fu=["minimal","default","strict"];function Qn(e){if(e===void 0)return;let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new h("--preset must not be empty",g.USAGE);if(t==="minimal"||t==="default"||t==="strict")return t;if(t==="lite"||t==="minimum")return"minimal";throw new h(`Invalid --preset value "${e}". Allowed: ${Fu.join(", ")}`,g.USAGE)}function Ja(e){if(e!==void 0){if(e.trim().length===0)throw new h("--type-preset must not be empty",g.USAGE);try{return Tt(e)}catch{throw new h(`Invalid --type-preset value "${e}". Allowed: ${ot.join(", ")}`,g.USAGE)}}}function qa(e){if(e===void 0)return;let t=e.trim();if(t.length===0)throw new h("--author must not be empty",g.USAGE);return t}function Ht(e){if(e===void 0)return!1;let t=e.trim();return t.length===0?!1:j.isAbsolute(t)||/^[a-z]:/iu.test(t)||t.startsWith(".")||t.includes("/")||t.includes("\\")}function Ba(e,t,n,r){let o=r?.trim();if(r!==void 0&&o?.length===0)throw new h("--workspace must not be empty",g.USAGE);if(o!==void 0){if(t.path!==void 0||Ht(n))throw new h("--workspace cannot be combined with --pm-path/--path or a path-like positional target.",g.USAGE);let d=j.resolve(e,o),l=j.join(d,".agents","pm");return{pmRoot:l,prefixArg:n,target:{mode:"workspace-path",tracker_root:l,workspace_root:d}}}if(t.path===void 0&&Ht(n)){let d=j.resolve(e,n.trim());return{pmRoot:d,prefixArg:void 0,target:{mode:"tracker-path",tracker_root:d}}}let i=D(e,t.path),a=j.join(j.resolve(e),".agents","pm"),s=j.dirname(j.dirname(i)),c=j.resolve(i)===a?"current":"ancestor";return{pmRoot:i,prefixArg:n,target:t.path===void 0?{mode:"workspace-discovery",tracker_root:i,workspace_root:s,discovery:c,requested_cwd:j.resolve(e),...c==="ancestor"?{suggested_current_tracker_root:a}:{}}:{mode:"tracker-path",tracker_root:i}}}function Wa(e,t){if(t===void 0)return e;if(t.trim().length===0)throw new h("--id-prefix must not be empty",g.USAGE);if(Ht(t))throw new h(`--id-prefix accepts an item ID prefix, not a tracker path: "${t}".`,g.USAGE,{code:"init_id_prefix_path_like",required:"Pass the tracker path positionally or with the global --path option.",examples:[`pm init ${t}`,`pm --path ${t} init`]});if(e!==void 0&&xe(e)!==xe(t))throw new h(`Conflicting id prefixes: positional "${e}" and --id-prefix "${t}".`,g.USAGE,{code:"init_id_prefix_conflict",required:"Use either the positional id prefix or --id-prefix with one value.",examples:[`pm init ${xe(e)}`,`pm init --id-prefix ${xe(t)}`]});return t}function Ha(e){if(e===void 0)return"ask";let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new h("--agent-guidance must not be empty",g.USAGE);if(t==="ask"||t==="add"||t==="skip"||t==="status")return t;throw new h(`Invalid --agent-guidance value "${e}". Allowed: ${Ea.join(", ")}`,g.USAGE)}function Ka(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}function Zn(e,t){let n=or[t];e.governance={preset:t,...n},e.validation.parent_reference=n.parent_reference,e.validation.metadata_profile=n.metadata_profile}function Mu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Va(e){let t=e.details;return{installed_all:t.installed_all===!0,installed_count:typeof t.installed_count=="number"?t.installed_count:0,packages:Array.isArray(t.packages)?t.packages.filter(Mu).map(n=>({alias:typeof n.alias=="string"?n.alias:"",ok:n.ok===!0})):[]}}async function Ya(e,t,n){let r=K(t.schema),o=ne(e,r.files.types,Y.types),a=ie(await q(o)),s=[],c=[];for(let d of it(n)){let l=Ue(a,d);a=l.file,(l.replaced?c:s).push(l.definition.name)}return await Ge({pmRoot:e,filePath:o,raw:le(a),op:"init:type-preset",author:V(void 0,t.author_default),lockTtlSeconds:t.locks.ttl_seconds,lockWaitMs:t.locks.wait_ms}),{name:n,registered:s,updated:c,file:o}}async function Xa(e){let t=[".git","package.json","pnpm-workspace.yaml","AGENTS.md",j.join(".agents","pm")];for(let n of t)if(await x(j.join(e,n)))return!0;return!1}async function Qa(e,t,n){if(!t||n||await x(j.join(e,"settings.json"))||!await Xa(e))return;let r=j.join(e,".agents","pm");throw new h(`Refusing to initialize tracker files directly in workspace root "${e}".`,g.USAGE,{code:"workspace_root_pm_path",type:"urn:pm-cli:error:workspace_root_pm_path",why:"Path-like init targets and --pm-path/--path point at the tracker storage directory itself, not the repository workspace. Point at .agents/pm, use --workspace, or pass --force if you intentionally want root-level tracker files.",examples:[`pm --pm-path ${r} init --yes`,"pm init --yes",`pm --pm-path ${e} init --yes --force`],nextSteps:["Use --pm-path <repo>/.agents/pm for repository-local tracker storage.","Use PM_PATH only for sandboxed tests or explicit tracker roots.","Pass --force only when root-level tracker files are intentional."],recovery:{next_best_command:`pm --pm-path ${r} init --yes`}})}async function Za(e,t){let n=[],r=[];for(let o of t){let i=o?j.join(e,o):e,a=await x(i);await Nu.mkdir(i,{recursive:!0}),a?r.push(`already_exists:${i}`):n.push(i),r.push(...await W({path:i,scope:"project",op:"init:ensure_dir"}))}return{createdDirs:n,warnings:r}}async function es(e,t){let n=za();try{X.write(`pm init setup wizard (agent-optimized)
|
|
62
|
-
`),X.write(`This walkthrough is non-destructive and each choice can be changed later with pm config.
|
|
63
|
-
|
|
64
|
-
`),X.write(`1/3 Item ID prefix
|
|
65
|
-
`),X.write(`Prefix is prepended to generated IDs (for example pm-a1b2).
|
|
66
|
-
`);let r=await n.question(`Item ID prefix [${e}]: `),o=r.trim().length>0?xe(r):e;X.write(`
|
|
67
|
-
2/3 Governance preset
|
|
68
|
-
`),X.write(`minimal: no ownership blocking, progressive create defaults, close validation off.
|
|
69
|
-
`),X.write(`default: ownership conflict warnings, progressive create defaults, close validation warn.
|
|
70
|
-
`),X.write(`strict: ownership blocking, strict create defaults, close validation strict.
|
|
71
|
-
`);let i=await n.question("Governance preset [minimal/default/strict] (default: minimal): "),a=i.trim().length>0?i.trim():"minimal",s="minimal";try{s=Qn(a)}catch{X.write(`Unrecognized governance preset "${a}"; using minimal.
|
|
72
|
-
`)}X.write(`
|
|
73
|
-
3/3 Project telemetry
|
|
74
|
-
`),X.write(`Telemetry helps improve reliability and can be disabled anytime via pm config.
|
|
75
|
-
`);let c=t?"Y/n":"y/N",d=await n.question(`Enable telemetry for this project? [${c}] `),l=Ka(d,t);return X.write(`
|
|
76
|
-
`),{prefix:o,preset:s,telemetry_enabled:l}}finally{n.close()}}function Gu(e){return{presetFromOption:Qn(e.preset),useDefaults:e.defaults===!0,authorFromOption:qa(e.author),installBundledPackages:e.withPackages===!0,agentGuidanceMode:Ha(e.agentGuidance),typePreset:Ja(e.typePreset)}}function Uu(e){let t=[];return e.prefixArg!==void 0&&e.settings.id_prefix!==e.normalizedPrefix&&t.push("id_prefix"),e.presetFromOption!==void 0&&e.settings.governance.preset!==e.presetFromOption&&t.push("governance_preset"),e.authorFromOption!==void 0&&e.settings.author_default!==e.authorFromOption&&t.push("author_default"),t}function zu(e,t,n,r){if(t.length===0||n)return;let o=r.discovery==="ancestor";throw new h(`${o?`No tracker exists in ${r.requested_cwd}; pm init found an ancestor tracker at ${r.tracker_root}. `:""}Refusing to update existing tracker settings at ${e} without --force.`,g.USAGE,{code:"init_existing_settings_requires_force",type:"urn:pm-cli:error:init_existing_settings_requires_force",required:`--force for ${t.join(", ")}`,why:o?"Ancestor discovery is useful for normal commands, but init must make the selected existing workspace explicit before changing its identity or policy settings.":"pm init is safe to rerun, but changing id prefix, governance preset, or default author on an existing tracker can corrupt long-lived project context when an agent meant to initialize a sandbox path.",resolved_path:r.tracker_root,requested_path:r.requested_cwd,suggested_path:r.suggested_current_tracker_root,examples:["pm init --yes","pm init ./sandbox-pm --yes",...o?['pm init <name> --yes --pm-path "$PWD/.agents/pm"']:[],"pm init acme --yes --force"],nextSteps:[...o?['To create a new tracker in the current directory, rerun with --pm-path "$PWD/.agents/pm".']:[],"If you meant to initialize a sandbox tracker, pass a path-like positional such as ./sandbox-pm or /tmp/pm-test.","If you intentionally want to rewrite this existing tracker's init-managed settings, rerun with --force."]})}function Ju(e){let t=!1;return e.prefixArg!==void 0&&e.settings.id_prefix!==e.normalizedPrefix&&(e.settings.id_prefix=e.normalizedPrefix,e.warnings.push(`updated:id_prefix:${e.normalizedPrefix}`),t=!0),e.presetFromOption!==void 0&&e.settings.governance.preset!==e.presetFromOption&&(Zn(e.settings,e.presetFromOption),e.warnings.push(`updated:governance_preset:${e.presetFromOption}`),t=!0),e.authorFromOption!==void 0&&e.settings.author_default!==e.authorFromOption&&(e.settings.author_default=e.authorFromOption,e.warnings.push(`updated:author_default:${e.authorFromOption}`),t=!0),t}async function qu(e){let t=await O(e.pmRoot);e.warnings.push(`already_exists:${e.settingsPath}`);let n=Uu({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption});return zu(e.settingsPath,n,e.options.force===!0,e.target),Ju({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption,warnings:e.warnings})&&await Se(e.pmRoot,t),{settings:t,normalizedPrefix:e.normalizedPrefix,chosenPreset:e.normalizedOptions.presetFromOption,wizardUsed:!1}}async function Bu(e){let t=e.normalizedPrefix,n=e.normalizedOptions.presetFromOption,r,o=!1;if(e.normalizedOptions.presetFromOption===void 0&&!e.normalizedOptions.useDefaults&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0){let c=await es(t,Xt.telemetry.enabled);t=c.prefix,n=c.preset,r=c.telemetry_enabled,o=!0}let i=n??"minimal",a=Lu();a.id_prefix=t,Zn(a,i);let s=Er()?.trim()||void 0;return a.author_default=e.normalizedOptions.authorFromOption??s??"",r!==void 0&&(a.telemetry.enabled=r,a.telemetry.first_run_prompt_completed=!0),await Se(e.pmRoot,a),{settings:a,normalizedPrefix:t,chosenPreset:n,wizardUsed:o}}async function Ma(e){return e.settingsExists?await qu(e):await Bu({pmRoot:e.pmRoot,normalizedPrefix:e.normalizedPrefix,normalizedOptions:e.normalizedOptions})}async function Wu(e){let t=await Fa({pm_root:e.pmRoot,cwd:e.cwd,mode:e.agentGuidanceMode,interactive:process.stdin.isTTY===!0&&process.stdout.isTTY===!0,settings:e.settings});return e.warnings.push(...t.warnings),t.settings_changed&&await Se(e.pmRoot,e.settings),{...t.summary,next_steps:t.next_steps}}async function Hu(e,t){let n=[],r=[],o=await Sr(e,t.schema);for(let i of o.created_paths)n.push(i),r.push(...await W({path:i,scope:"project",op:"init:runtime_schema_file"}));return{createdDirs:n,warnings:r}}async function Ku(e){if(e.typePreset===void 0)return;let t=await Ya(e.pmRoot,e.settings,e.typePreset);return e.warnings.push(`registered_type_preset:${e.typePreset}`),e.warnings.push(...await W({path:t.file,scope:"project",op:"init:type_preset"})),t}async function Vu(e){let n=B(e.settings,H()).folders.filter(o=>!Yt.includes(o)),r=await Za(e.pmRoot,n);e.createdDirs.push(...r.createdDirs),e.warnings.push(...r.warnings)}function Yu(e){let t=j.resolve(e.tracker_root),n=j.dirname(t);return j.basename(t)==="pm"&&j.basename(n)===".agents"?j.dirname(n):e.workspace_root}async function Xu(e,t,n,r){if(!e)return;let o=await Bn("all",{install:!0,project:!0},{...t,path:n});r.push(...o.warnings);let i=Va(o),a=i.packages.filter(s=>!s.ok).map(s=>s.alias);if(!i.installed_all||a.length>0)throw new h(`pm init --with-packages did not install all bundled packages successfully${a.length>0?`: ${a.join(", ")}`:"."}`,g.GENERIC_FAILURE);return i}function ts(e){let t=r=>St([...e.target.mode==="workspace-discovery"?[]:["--pm-path",e.target.tracker_root],...r]),n=[`Create your first item: ${t(["create","--type","Task","--title","<title>"])}`,`List active items: ${t(["list"])}`,`Get agent-friendly project context: ${t(["context"])}`];e.installBundledPackages?n.push(`Explore newly-available commands: ${t(["cal"])}, ${t(["templates"])}, ${t(["guide"])}`):(n.push(`Add optional packages for richer workflows: ${t(["install","calendar","--project"])}, ${t(["install","templates","--project"])}, ${t(["install","guide-shell","--project"])}`),n.push(`Or install everything bundled: ${t(["init","--with-packages"])} (idempotent on re-run)`)),e.registeredTypePreset&&n.push(`Inspect registered preset types: ${t(["schema","list"])}, ${t(["schema","show",e.registeredTypePreset.registered[0]??e.registeredTypePreset.updated[0]])}`),n.push("Supported agent harnesses are attributed automatically; use --author or PM_AUTHOR only when an explicit identity override is required.");for(let r of e.agentGuidanceNextSteps){let o=e.target.mode==="workspace-discovery"?r:r.replace(/\bpm (?=[a-z])/g,()=>`${t([])} `);n.includes(o)||n.push(o)}return n}async function ns(e,t,n,r=hn){if(t===null){n.push("merge_fence_skipped:not_git_repository:run pm merge install after moving the tracker into a Git repository");return}try{let o=await r({pmRoot:e,workspaceRoot:t});o.gitattributes.changed&&n.push(`updated:merge_fence:${o.gitattributes.path}`)}catch(o){if(!(o instanceof h))throw o;n.push(`merge_fence_skipped:install_failed:${o.context.code??"pm_error"}:${o.message}:run pm merge install after resolving the Git repository error`)}}async function Qu(e,t,n,r){if(e==null||n==="status")return;let o=await Xr(e,{pmRoot:t});o.changed&&r.push(`updated:gitignore:${o.path}`)}async function B_(e,t,n={}){let r=t[Du],o=typeof r=="string"?r:process.cwd(),i=Ba(o,t,e,n.workspace),a=i.pmRoot;e=Wa(i.prefixArg,n.idPrefix);let s=Gu(n);await Qa(a,i.target.mode==="tracker-path",n.force===!0);let c=[],d=[],l=j.join(a,"settings.json"),p=await x(l),u;p&&(u=await Ma({pmRoot:a,settingsPath:l,settingsExists:p,normalizedPrefix:xe(e),prefixArg:e,options:n,normalizedOptions:s,warnings:d,target:i.target}));let f=await Za(a,Yt);c.push(...f.createdDirs),d.push(...f.warnings),u??=await Ma({pmRoot:a,settingsPath:l,settingsExists:p,normalizedPrefix:xe(e),prefixArg:e,options:n,normalizedOptions:s,warnings:d,target:i.target});let{settings:y}=u,w=Yu(i.target),m=await un(w??j.dirname(a)),_=w??m,v=await Wu({pmRoot:a,cwd:_??o,agentGuidanceMode:s.agentGuidanceMode,settings:y,warnings:d}),k=await Hu(a,y);c.push(...k.createdDirs),d.push(...k.warnings);let S=await Ku({pmRoot:a,settings:y,typePreset:s.typePreset,warnings:d});S&&(y=await O(a)),await Vu({pmRoot:a,settings:y,createdDirs:c,warnings:d}),await Qu(_,a,s.agentGuidanceMode,d),!p&&n.mergeFence!==!1&&s.agentGuidanceMode!=="status"&&await ns(a,m,d);let C=await Xu(s.installBundledPackages,t,a,d),G=ts({installBundledPackages:s.installBundledPackages,registeredTypePreset:S,agentGuidanceNextSteps:v.next_steps,target:i.target});return{ok:!0,path:a,target:i.target,settings:y,created_dirs:c,warnings:d,governance_preset:y.governance.preset,wizard_used:u.wizardUsed,...S?{registered_type_preset:S}:{},...C?{installed_packages:C}:{},next_steps:G,agent_guidance:v}}export{rn as a,Wr as b,Kr as c,sn as d,Ss as e,$s as f,Xr as g,Je as h,Is as i,Ts as j,Zr as k,$t as l,ro as m,qe as n,ln as o,Ns as p,un as q,fn as r,co as s,Pm as t,Nm as u,lo as v,Dm as w,hn as x,wo as y,He as z,Ke as A,vo as B,go as C,Be as D,We as E,yo as F,wc as G,$o as H,Oo as I,yc as J,_c as K,Bf as L,Wf as M,Hf as N,at as O,Kf as P,Vf as Q,Yf as R,Xf as S,Qf as T,Zf as U,eh as V,th as W,nh as X,rh as Y,oh as Z,ih as _,ah as $,sh as aa,ch as ba,dh as ca,lh as da,ph as ea,uh as fa,mh as ga,fh as ha,hh as ia,gh as ja,yh as ka,_h as la,b as ma,we as na,Rt as oa,jc as pa,ct as qa,Pt as ra,ei as sa,li as ta,jn as ua,Si as va,Pg as wa,Rl as xa,Mi as ya,Gi as za,Qi as Aa,Ln as Ba,Sl as Ca,El as Da,$l as Ea,Ai as Fa,Xl as Ga,Ii as Ha,Bn as Ia,Ea as Ja,w_ as Ka,Fa as La,Du as Ma,J_ as Na,q_ as Oa,B_ as Pa};
|
|
77
|
-
//# sourceMappingURL=chunk-CKOL5U7J.js.map
|