@unbrained/pm-cli 2026.10.3 → 2026.10.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +2 -2
- package/CHANGELOG.md +28 -2
- package/dist/cli/after-command-context-usage.js +1 -1
- package/dist/cli/argv-utils.js +1 -1
- package/dist/cli/bootstrap-args.js +1 -1
- package/dist/cli/bundle-integrity.js +2 -2
- package/dist/cli/command-namespaces.js +1 -1
- package/dist/cli/commander-usage.d.ts +1 -1
- package/dist/cli/commander-usage.js +7 -4
- package/dist/cli/commands/annotations/comments.js +1 -1
- package/dist/cli/commands/annotations/docs.js +1 -1
- package/dist/cli/commands/annotations/files.js +1 -1
- package/dist/cli/commands/annotations/learnings.js +1 -1
- package/dist/cli/commands/annotations/notes.js +1 -1
- package/dist/cli/commands/extension/describe.js +1 -1
- package/dist/cli/commands/extension/extension.js +1 -1
- package/dist/cli/commands/extension/scaffold.js +1 -1
- package/dist/cli/commands/extension/shared.js +1 -1
- package/dist/cli/commands/governance/gc.js +1 -1
- package/dist/cli/commands/governance/health.js +1 -1
- package/dist/cli/commands/governance/telemetry.js +1 -1
- package/dist/cli/commands/governance/validate.js +1 -1
- package/dist/cli/commands/history/activity.js +1 -1
- package/dist/cli/commands/history/history-compact.js +1 -1
- package/dist/cli/commands/history/history-redact.js +1 -1
- package/dist/cli/commands/history/history-repair.js +1 -1
- package/dist/cli/commands/history/history.js +1 -1
- package/dist/cli/commands/history/restore.js +1 -1
- package/dist/cli/commands/lifecycle/append.js +1 -1
- package/dist/cli/commands/lifecycle/claim.js +1 -1
- package/dist/cli/commands/lifecycle/close-many.js +1 -1
- package/dist/cli/commands/lifecycle/close.js +1 -1
- package/dist/cli/commands/lifecycle/copy.js +1 -1
- package/dist/cli/commands/lifecycle/create.js +1 -1
- package/dist/cli/commands/lifecycle/delete.js +1 -1
- package/dist/cli/commands/lifecycle/focus.js +1 -1
- package/dist/cli/commands/lifecycle/plan.js +1 -1
- package/dist/cli/commands/lifecycle/update-many.js +1 -1
- package/dist/cli/commands/lifecycle/update.js +1 -1
- package/dist/cli/commands/query/aggregate.js +1 -1
- package/dist/cli/commands/query/context.js +1 -1
- package/dist/cli/commands/query/deps.js +1 -1
- package/dist/cli/commands/query/duplicates.js +1 -1
- package/dist/cli/commands/query/eval.js +1 -1
- package/dist/cli/commands/query/get.js +1 -1
- package/dist/cli/commands/query/graph.js +1 -1
- package/dist/cli/commands/query/list.js +1 -1
- package/dist/cli/commands/query/next.js +1 -1
- package/dist/cli/commands/query/search.js +1 -1
- package/dist/cli/commands/query/stats.js +1 -1
- package/dist/cli/commands/test/test-all.js +1 -1
- package/dist/cli/commands/test/test-runs.js +1 -1
- package/dist/cli/commands/test/test.js +1 -1
- package/dist/cli/commands/workspace/config.js +1 -1
- package/dist/cli/commands/workspace/contracts.js +1 -1
- package/dist/cli/commands/workspace/init.js +1 -1
- package/dist/cli/commands/workspace/merge.js +1 -1
- package/dist/cli/commands/workspace/profile.js +1 -1
- package/dist/cli/commands/workspace/schema.js +1 -1
- package/dist/cli/commands/workspace/upgrade.js +1 -1
- package/dist/cli/context-intent-invocation.js +1 -1
- package/dist/cli/description-stdin.js +1 -1
- package/dist/cli/error-guidance.js +3 -1
- package/dist/cli/extension-command-help.js +5 -3
- package/dist/cli/extension-command-options.js +1 -1
- package/dist/cli/extension-recovery.js +1 -1
- package/dist/cli/help-content.js +5 -2
- package/dist/cli/help-json-payload.js +6 -3
- package/dist/cli/invocation-profile.js +2 -2
- package/dist/cli/main.js +5 -5
- package/dist/cli/migration-gates.js +1 -1
- package/dist/cli/option-values.js +1 -1
- package/dist/cli/public.js +1 -1
- package/dist/cli/register-annotations.js +1 -1
- package/dist/cli/register-assurance.js +1 -1
- package/dist/cli/register-files-lookup.js +1 -1
- package/dist/cli/register-history-activity.js +1 -1
- package/dist/cli/register-history-author.js +1 -1
- package/dist/cli/register-history-maintenance.js +2 -2
- package/dist/cli/register-list-query.js +10 -10
- package/dist/cli/register-mutation-options.js +1 -1
- package/dist/cli/register-mutation.js +2 -2
- package/dist/cli/register-operations.js +1 -1
- package/dist/cli/register-setup.js +1 -1
- package/dist/cli/register-structured-mutation.js +1 -1
- package/dist/cli/registration-helpers.js +1 -1
- package/dist/cli/runtime/activation.js +1 -1
- package/dist/cli/runtime/invocation-options.js +1 -1
- package/dist/cli/runtime/projection-retry.js +1 -1
- package/dist/cli/runtime/selection.js +1 -1
- package/dist/cli/runtime/telemetry-outcome.js +1 -1
- package/dist/cli/runtime-compatibility-boundary.d.ts +1 -1
- package/dist/cli/runtime-compatibility-boundary.js +4 -4
- package/dist/cli/schema/registration.js +2 -2
- package/dist/cli/schema-registration-helpers.js +1 -1
- package/dist/cli/search-refresh.js +1 -1
- package/dist/cli/stats-analytics-json.js +1 -1
- package/dist/cli/telemetry-flush.js +1 -1
- package/dist/cli-bundle/bundle-manifest.json +162 -162
- package/dist/cli-bundle/chunks/chunk-3CYOBJUK.js +3 -0
- package/dist/cli-bundle/chunks/chunk-5MNOWZPN.js +3 -0
- package/dist/cli-bundle/chunks/chunk-AJ7H6XUF.js +20 -0
- package/dist/cli-bundle/chunks/chunk-D332RXZ7.js +80 -0
- package/dist/cli-bundle/chunks/chunk-HRJ6G6ZG.js +31 -0
- package/dist/cli-bundle/chunks/chunk-KRVI56QE.js +6 -0
- package/dist/cli-bundle/chunks/chunk-N4YGSG6F.js +238 -0
- package/dist/cli-bundle/chunks/chunk-OOLYASYJ.js +2 -0
- package/dist/cli-bundle/chunks/chunk-R7CG2DB7.js +2 -0
- package/dist/cli-bundle/chunks/chunk-TGMONGWX.js +2 -0
- package/dist/cli-bundle/chunks/chunk-UZ7BIUCI.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-44UGMMQ6.js → chunk-VZ63DEVJ.js} +3 -3
- package/dist/cli-bundle/chunks/chunk-WFZ4UEOB.js +2 -0
- package/dist/cli-bundle/chunks/chunk-YVBRASXO.js +8 -0
- package/dist/cli-bundle/chunks/{chunk-5XKF5SQV.js → chunk-Z66DWDAU.js} +91 -91
- package/dist/cli-bundle/chunks/{register-list-query-DYCGUQEW.js → register-list-query-75QXHIFH.js} +11 -11
- package/dist/cli-bundle/chunks/register-mutation-YS54SCHG.js +20 -0
- package/dist/cli-bundle/chunks/register-operations-6KHZQSYJ.js +2 -0
- package/dist/cli-bundle/chunks/register-setup-RTATEN2M.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-3BIYG72P.js → chunk-2CVX3KR3.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-5C3IDDW7.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-DBD4W4QP.js → chunk-ABV67XCC.js} +3 -3
- package/dist/cli-bundle/focused-chunks/chunk-B5RSLVE6.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-C224METM.js +20 -0
- package/dist/cli-bundle/focused-chunks/chunk-CLDPTMQY.js +6 -0
- package/dist/cli-bundle/focused-chunks/chunk-DDRN42PB.js +8 -0
- package/dist/cli-bundle/focused-chunks/{chunk-EJN7DY3B.js → chunk-DOVTUKJQ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-ECBOPEJE.js +75 -0
- package/dist/cli-bundle/focused-chunks/chunk-GITOYRUW.js +165 -0
- package/dist/cli-bundle/focused-chunks/chunk-GUIF3WVC.js +30 -0
- package/dist/cli-bundle/focused-chunks/chunk-LE4JUCRR.js +3 -0
- package/dist/cli-bundle/focused-chunks/{chunk-HFAW3FJQ.js → chunk-PSXFFQFT.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-RHIH6XIW.js +12 -0
- package/dist/cli-bundle/focused-chunks/chunk-UDYRVBOZ.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-XV5RV4ZT.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-XRSCIYHR.js → chunk-YMU42COG.js} +2 -2
- package/dist/cli-bundle/main.js +28 -28
- 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 +32 -32
- 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 +55 -55
- 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 +10 -10
- package/dist/cli.js +1 -1
- package/dist/core/checkpoint/checkpoint-gc.js +1 -1
- package/dist/core/checkpoint/mutation-checkpoint.js +2 -2
- package/dist/core/config/nested-settings.js +1 -1
- package/dist/core/config/positional-value.js +1 -1
- package/dist/core/diagnostics/remediation.js +1 -1
- package/dist/core/extensions/activation-summary-markdown.js +2 -1
- package/dist/core/extensions/activation-summary.js +1 -1
- package/dist/core/extensions/activation-transaction.js +1 -1
- package/dist/core/extensions/capability-usage.js +1 -1
- package/dist/core/extensions/command-hook-context.js +1 -1
- package/dist/core/extensions/command-metadata-contract.js +1 -1
- package/dist/core/extensions/command-visibility-tier.js +1 -1
- package/dist/core/extensions/contribution-inventory.js +1 -1
- package/dist/core/extensions/exporter-output-contract.js +1 -1
- package/dist/core/extensions/extension-candidate.js +1 -1
- package/dist/core/extensions/extension-capability-aliases.js +1 -1
- package/dist/core/extensions/extension-hook-runtime.js +1 -1
- package/dist/core/extensions/extension-policy.js +1 -1
- package/dist/core/extensions/extension-registries.js +1 -1
- package/dist/core/extensions/extension-runtime-helpers.js +1 -1
- package/dist/core/extensions/extension-types.d.ts +8 -1
- package/dist/core/extensions/extension-types.js +1 -1
- package/dist/core/extensions/flag-definition-validation.js +1 -1
- package/dist/core/extensions/flag-value-types.js +1 -1
- package/dist/core/extensions/index.js +1 -1
- package/dist/core/extensions/item-field-types.js +1 -1
- package/dist/core/extensions/item-fields.js +1 -1
- package/dist/core/extensions/loader.js +1 -1
- package/dist/core/extensions/manifest-parser.js +1 -1
- package/dist/core/extensions/manifest-schema.js +1 -1
- package/dist/core/extensions/module-graph-snapshot.js +1 -1
- package/dist/core/extensions/preflight-ownership.js +1 -1
- package/dist/core/extensions/registration-contracts.js +1 -1
- package/dist/core/extensions/registration-validation.js +1 -1
- package/dist/core/extensions/registration-values.js +1 -1
- package/dist/core/extensions/reserved-host-flags.js +1 -1
- package/dist/core/extensions/runtime-registrations.js +1 -1
- package/dist/core/extensions/service-ownership.js +1 -1
- package/dist/core/extensions/version-compat.js +1 -1
- package/dist/core/fs/atomic-create.js +1 -1
- package/dist/core/fs/fs-utils.js +2 -2
- package/dist/core/fs/host-environment-errors.js +1 -1
- package/dist/core/fs/index.js +1 -1
- package/dist/core/fs/path-utils.js +1 -1
- package/dist/core/governance/content-fields.js +1 -1
- package/dist/core/governance/issue-codes.js +1 -1
- package/dist/core/governance/metadata-coverage.js +1 -1
- package/dist/core/history/digest.js +1 -1
- package/dist/core/history/drift-cache.js +3 -3
- package/dist/core/history/drift-scan.d.ts +4 -0
- package/dist/core/history/drift-scan.js +1 -1
- package/dist/core/history/event-classification.js +1 -1
- package/dist/core/history/event-index.js +8 -7
- package/dist/core/history/history-compact-bulk.js +1 -1
- package/dist/core/history/history-diff.js +1 -1
- package/dist/core/history/history-rewrite.js +1 -1
- package/dist/core/history/history-storage-stats.js +1 -1
- package/dist/core/history/history-stream-policy.js +1 -1
- package/dist/core/history/history.js +2 -2
- package/dist/core/history/identity.js +1 -1
- package/dist/core/history/index.js +1 -1
- package/dist/core/history/operation-contract.js +1 -1
- package/dist/core/history/projection.js +1 -1
- package/dist/core/history/read.js +1 -1
- package/dist/core/history/replay.js +2 -1
- package/dist/core/history/tombstone.js +1 -1
- package/dist/core/history/version-address.js +1 -1
- package/dist/core/history/workspace-history.js +2 -2
- package/dist/core/io/body-file.js +1 -1
- package/dist/core/io/bulk-ids-input.js +2 -1
- package/dist/core/item/actionability.js +1 -1
- package/dist/core/item/dependency-reference.js +1 -1
- package/dist/core/item/id.js +1 -1
- package/dist/core/item/index.js +1 -1
- package/dist/core/item/item-format-version.js +1 -1
- package/dist/core/item/item-format.js +6 -4
- package/dist/core/item/item-record.js +1 -1
- package/dist/core/item/item-type-definition.js +1 -1
- package/dist/core/item/parent-reference-policy.js +1 -1
- package/dist/core/item/parse.js +8 -2
- package/dist/core/item/plan-lifecycle.js +1 -1
- package/dist/core/item/priority.js +1 -1
- package/dist/core/item/sprint-release-format.js +1 -1
- package/dist/core/item/status-filter.js +1 -1
- package/dist/core/item/status.js +1 -1
- package/dist/core/item/toon-decode.js +1 -1
- package/dist/core/item/type-registry.js +1 -1
- package/dist/core/item/type-synonyms.js +1 -1
- package/dist/core/lock/index.js +1 -1
- package/dist/core/lock/lock-gc.js +1 -1
- package/dist/core/lock/lock.js +3 -3
- package/dist/core/output/mutation-projection.js +1 -1
- package/dist/core/output/output-control.js +1 -1
- package/dist/core/output/output.js +22 -10
- package/dist/core/output/query-summary.js +1 -1
- package/dist/core/output/tabular.js +3 -1
- package/dist/core/packages/manifest.js +1 -1
- package/dist/core/packages/root.js +1 -1
- package/dist/core/policy/workflow-policy-schema.js +1 -1
- package/dist/core/policy/workflow-policy-store.js +1 -1
- package/dist/core/policy/workflow-policy.js +1 -1
- package/dist/core/profile/profile-describe.js +1 -1
- package/dist/core/profile/profile-lint.js +1 -1
- package/dist/core/profile/profile-plan.js +1 -1
- package/dist/core/profile/profile-presets.js +25 -1
- package/dist/core/reproducibility/context.js +1 -1
- package/dist/core/schema/fields-file.js +2 -2
- package/dist/core/schema/item-types-file.js +2 -2
- package/dist/core/schema/runtime-field-filters.js +1 -1
- package/dist/core/schema/runtime-field-values.js +1 -1
- package/dist/core/schema/runtime-schema.js +2 -2
- package/dist/core/schema/status-defs-file.js +2 -2
- package/dist/core/schema/status-token.js +1 -1
- package/dist/core/schema/type-inference.js +1 -1
- package/dist/core/schema/type-presets.js +1 -1
- package/dist/core/schema/type-workflows.js +1 -1
- package/dist/core/search/background-refresh.js +2 -2
- package/dist/core/search/bm25.js +1 -1
- package/dist/core/search/cache.js +2 -2
- package/dist/core/search/corpus.js +1 -1
- package/dist/core/search/embedding-batches.js +1 -1
- package/dist/core/search/eval-thresholds.js +1 -1
- package/dist/core/search/eval.js +1 -1
- package/dist/core/search/http-client.js +1 -1
- package/dist/core/search/providers.js +1 -1
- package/dist/core/search/relevance.js +1 -1
- package/dist/core/search/semantic-defaults.js +1 -1
- package/dist/core/search/staleness.js +1 -1
- package/dist/core/search/vector-stores.js +2 -2
- package/dist/core/search/vectorization-metadata.js +1 -1
- package/dist/core/sentry/helpers.js +1 -1
- package/dist/core/sentry/instrument.js +1 -1
- package/dist/core/session/session-state.js +1 -1
- package/dist/core/shared/agent-session-context.js +1 -1
- package/dist/core/shared/author.js +5 -1
- package/dist/core/shared/command-line.js +1 -1
- package/dist/core/shared/command-types.js +1 -1
- package/dist/core/shared/conflict-markers.js +1 -1
- package/dist/core/shared/constants.js +1 -1
- package/dist/core/shared/errors.js +1 -1
- package/dist/core/shared/html-entity-decode.js +1 -1
- package/dist/core/shared/index.js +1 -1
- package/dist/core/shared/item-metadata-contract.js +1 -1
- package/dist/core/shared/lazy-module.js +1 -1
- package/dist/core/shared/levenshtein.js +1 -1
- package/dist/core/shared/memo.js +1 -1
- package/dist/core/shared/numeric-parsers.js +1 -1
- package/dist/core/shared/option-alias-visibility.js +1 -1
- package/dist/core/shared/primitives.js +1 -1
- package/dist/core/shared/secret-rules.js +1 -1
- package/dist/core/shared/serial-queue.js +1 -1
- package/dist/core/shared/serialization.js +1 -1
- package/dist/core/shared/split-comma-list.js +1 -1
- package/dist/core/shared/text-normalization.js +1 -1
- package/dist/core/shared/time.js +2 -1
- package/dist/core/store/index.js +1 -1
- package/dist/core/store/item-format-migration.js +1 -1
- package/dist/core/store/item-metadata-cache.js +1 -1
- package/dist/core/store/item-metadata-query-index.js +7 -7
- package/dist/core/store/item-metadata-read-work.js +1 -1
- package/dist/core/store/item-store.js +1 -1
- package/dist/core/store/paths.js +1 -1
- package/dist/core/store/settings-concurrency.js +1 -1
- package/dist/core/store/settings-read-cache.js +1 -1
- package/dist/core/store/settings-validator.js +1 -1
- package/dist/core/store/settings.d.ts +11 -2
- package/dist/core/store/settings.js +3 -3
- package/dist/core/store/tracker-preflight.js +1 -1
- package/dist/core/telemetry/consent.js +2 -2
- package/dist/core/telemetry/observability.js +1 -1
- package/dist/core/telemetry/policy.js +1 -1
- package/dist/core/telemetry/read-sampling.js +2 -2
- package/dist/core/telemetry/runtime.js +9 -5
- package/dist/core/test/background-runs.js +3 -3
- package/dist/core/test/item-test-run-tracking.js +1 -1
- package/dist/core/test/run-selectors.js +1 -1
- package/dist/core/validate/estimate-defaults.js +1 -1
- package/dist/core/validate/fix-planning.js +1 -1
- package/dist/core/validate/linked-artifact-reference.js +1 -1
- package/dist/core/validate/missing-by-type.js +1 -1
- package/dist/core/validate/missing-link-owners.js +1 -1
- package/dist/core/validate/stale-file-classification.js +1 -1
- package/dist/mcp/http-server.js +6 -4
- package/dist/mcp/legacy-adapter.js +1 -1
- package/dist/mcp/runtime-capabilities.js +1 -1
- package/dist/mcp/server.js +4 -4
- package/dist/mcp/tool-definitions.js +1 -1
- package/dist/sdk/actionability.js +1 -1
- package/dist/sdk/agent/closed-domain-contracts.js +1 -1
- package/dist/sdk/agent/command-recovery.js +1 -1
- package/dist/sdk/agent/command-suggestions.js +1 -1
- package/dist/sdk/agent/create-option-policy.js +1 -1
- package/dist/sdk/agent/identity-config.js +1 -1
- package/dist/sdk/agent/item-addressing.js +1 -1
- package/dist/sdk/agent/refusal-closure-census.js +2 -1
- package/dist/sdk/agent/refusal-closure.js +1 -1
- package/dist/sdk/agent/refusal-corpus-contracts.js +1 -1
- package/dist/sdk/agent/refusal-reachability.js +3 -1
- package/dist/sdk/agent/subcommand-recovery.js +1 -1
- package/dist/sdk/agent/task-transcript-contracts.js +1 -1
- package/dist/sdk/agent/tracker-preflight-contracts.js +1 -1
- package/dist/sdk/agent-capability-contracts.js +3 -1
- package/dist/sdk/agent-session-context.js +1 -1
- package/dist/sdk/annotations.js +1 -1
- package/dist/sdk/author-attribution.js +1 -1
- package/dist/sdk/authoring.js +1 -1
- package/dist/sdk/cli-bootstrap.js +1 -1
- package/dist/sdk/cli-contracts/agent-output-contracts.js +5 -3
- package/dist/sdk/cli-contracts/bootstrap-command-scanner.js +1 -1
- package/dist/sdk/cli-contracts/command-aliases.js +1 -1
- package/dist/sdk/cli-contracts/command-exit-contracts.js +1 -1
- package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1
- package/dist/sdk/cli-contracts/commander-types.js +1 -1
- package/dist/sdk/cli-contracts/completeness.js +1 -1
- package/dist/sdk/cli-contracts/enum-contracts.js +1 -1
- package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
- package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +2 -1
- package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
- package/dist/sdk/cli-contracts/registration-helpers.js +7 -7
- package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
- package/dist/sdk/cli-contracts/schemas/assurance-definition.js +1 -1
- package/dist/sdk/cli-contracts/string-lists.js +1 -1
- package/dist/sdk/cli-contracts/tool-option-contracts.js +1 -1
- package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
- package/dist/sdk/cli-contracts/tool-schema.js +1 -1
- package/dist/sdk/cli-contracts/typed-action-inputs.js +1 -1
- package/dist/sdk/cli-contracts.js +1 -1
- package/dist/sdk/cli-program.js +1 -1
- package/dist/sdk/command-line.js +1 -1
- package/dist/sdk/comments.js +1 -1
- package/dist/sdk/compile-cache.js +1 -1
- package/dist/sdk/completion/bash.js +2 -1
- package/dist/sdk/completion/fish.js +13 -7
- package/dist/sdk/completion/shared.js +1 -1
- package/dist/sdk/completion/zsh.js +14 -8
- package/dist/sdk/completion.js +1 -1
- package/dist/sdk/compose.js +1 -1
- package/dist/sdk/config.js +1 -1
- package/dist/sdk/context/recency.js +1 -1
- package/dist/sdk/context/semantic-session-attribution.js +1 -1
- package/dist/sdk/context/usage-egress.js +1 -1
- package/dist/sdk/context/usage-ledger.js +6 -3
- package/dist/sdk/context-intent-contracts.js +1 -1
- package/dist/sdk/context-intent-runtime.js +1 -1
- package/dist/sdk/context-packing.js +1 -1
- package/dist/sdk/context-relevance.js +1 -1
- package/dist/sdk/context-signal-store.js +2 -2
- package/dist/sdk/context-usage.js +1 -1
- package/dist/sdk/contracts.js +1 -1
- package/dist/sdk/core-governance.js +1 -1
- package/dist/sdk/core.js +1 -1
- package/dist/sdk/corpus-shape.js +1 -1
- package/dist/sdk/define.js +1 -1
- package/dist/sdk/dependencies.js +1 -1
- package/dist/sdk/dependency-flag-validation.js +1 -1
- package/dist/sdk/dependency-provenance.js +1 -1
- package/dist/sdk/docs.js +1 -1
- package/dist/sdk/duplicates.js +1 -1
- package/dist/sdk/environment/agent-environment.js +1 -1
- package/dist/sdk/environment/host-environment-errors.js +1 -1
- package/dist/sdk/environment/project-runtime-compatibility.js +2 -1
- package/dist/sdk/environment/source-context.js +1 -1
- package/dist/sdk/environment/tracker-preflight.js +1 -1
- package/dist/sdk/error-code-catalog.js +1 -1
- package/dist/sdk/error-runtime.js +1 -1
- package/dist/sdk/errors.js +1 -1
- package/dist/sdk/eval.js +1 -1
- package/dist/sdk/extension/author-manifest.js +1 -1
- package/dist/sdk/extension/bundled-catalog.js +1 -1
- package/dist/sdk/extension/concurrency.js +1 -1
- package/dist/sdk/extension/copy-scope.js +1 -1
- package/dist/sdk/extension/custom-field-collisions.js +1 -1
- package/dist/sdk/extension/describe.js +4 -2
- package/dist/sdk/extension/doctor.js +1 -1
- package/dist/sdk/extension/install-plan.js +1 -1
- package/dist/sdk/extension/install-receipts.js +1 -1
- package/dist/sdk/extension/install-runtime.js +3 -3
- package/dist/sdk/extension/install-snapshot.js +1 -1
- package/dist/sdk/extension/install-sources.js +5 -5
- package/dist/sdk/extension/managed-state.js +2 -2
- package/dist/sdk/extension/migrations.js +2 -2
- package/dist/sdk/extension/output-ownership.js +1 -1
- package/dist/sdk/extension/runtime-summary.js +1 -1
- package/dist/sdk/extension/scaffold.js +11 -4
- package/dist/sdk/extension/shared.js +1 -1
- package/dist/sdk/extension/source-resolution.js +1 -1
- package/dist/sdk/extension/static-inventory.js +1 -1
- package/dist/sdk/extension/update-check.js +1 -1
- package/dist/sdk/extension-command-context.js +1 -1
- package/dist/sdk/extension-contracts.js +1 -1
- package/dist/sdk/extension.js +1 -1
- package/dist/sdk/files.js +1 -1
- package/dist/sdk/flag-invocation-contracts.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
- package/dist/sdk/generated-error-code-catalog.js +1 -1
- package/dist/sdk/governance/assurance-action-contracts.js +1 -1
- package/dist/sdk/governance/assurance-action.js +1 -1
- package/dist/sdk/governance/assurance-limits.js +1 -1
- package/dist/sdk/governance/assurance-mutation-error.js +1 -1
- package/dist/sdk/governance/assurance-presets.js +1 -1
- package/dist/sdk/governance/assurance-runtime.js +1 -1
- package/dist/sdk/governance/assurance.js +4 -4
- package/dist/sdk/governance/boundary-fixtures.js +1 -1
- package/dist/sdk/governance/closure-timestamps.js +1 -1
- package/dist/sdk/governance/coverage-assurance.js +1 -1
- package/dist/sdk/governance/defect-recurrence-coverage.js +1 -1
- package/dist/sdk/governance/defect-recurrence-graph.js +1 -1
- package/dist/sdk/governance/defect-recurrence-signals.js +1 -1
- package/dist/sdk/governance/defect-recurrence.js +1 -1
- package/dist/sdk/governance/extension-host-version.js +1 -1
- package/dist/sdk/governance/gc.js +1 -1
- package/dist/sdk/governance/health-merge-evidence.js +1 -1
- package/dist/sdk/governance/health.js +2 -1
- package/dist/sdk/governance/hierarchy-validation.js +1 -1
- package/dist/sdk/governance/linked-file-report.js +1 -1
- package/dist/sdk/governance/merge-receipt-history.js +1 -1
- package/dist/sdk/governance/provenance-health.js +4 -1
- package/dist/sdk/governance/reindex.js +5 -4
- package/dist/sdk/governance/stale-work.js +1 -1
- package/dist/sdk/governance/status-role-diagnostics.js +1 -1
- package/dist/sdk/governance/storage-integrity.js +1 -1
- package/dist/sdk/governance/tracked-runtime-cache.js +1 -1
- package/dist/sdk/governance/upgrade.js +2 -2
- package/dist/sdk/governance/validate-history-drift.js +1 -1
- package/dist/sdk/governance/validate-item-reader.js +1 -1
- package/dist/sdk/governance/validate-normalization.js +1 -1
- package/dist/sdk/governance/validate.js +1 -1
- package/dist/sdk/governance/workflow-completeness.js +1 -1
- package/dist/sdk/governance/workflow-policy.js +3 -3
- package/dist/sdk/governance/workspace-position.js +2 -1
- package/dist/sdk/governance.js +1 -1
- package/dist/sdk/graph/adapter.js +1 -1
- package/dist/sdk/graph/analytics.js +1 -1
- package/dist/sdk/graph/assembly.js +1 -1
- package/dist/sdk/graph/cache.js +1 -1
- package/dist/sdk/graph/centrality.js +1 -1
- package/dist/sdk/graph/conformance.js +1 -1
- package/dist/sdk/graph/deadline-scheduling.js +1 -1
- package/dist/sdk/graph/durable-cache.js +1 -1
- package/dist/sdk/graph/governance-contracts.js +1 -1
- package/dist/sdk/graph/governance.js +1 -1
- package/dist/sdk/graph/hierarchy-integrity.js +1 -1
- package/dist/sdk/graph/index.js +1 -1
- package/dist/sdk/graph/lifecycle-coverage.js +1 -1
- package/dist/sdk/graph/mutation-advisory.js +1 -1
- package/dist/sdk/graph/query-contracts.js +1 -1
- package/dist/sdk/graph/remediation.js +1 -1
- package/dist/sdk/graph/run.js +1 -1
- package/dist/sdk/graph/scheduling.js +1 -1
- package/dist/sdk/graph/traversal.js +1 -1
- package/dist/sdk/graph/workspace-relationship-kind-registry.js +1 -1
- package/dist/sdk/graph.js +1 -1
- package/dist/sdk/guide-topics.js +1 -1
- package/dist/sdk/guide.js +8 -1
- package/dist/sdk/history/attestation-command.js +1 -1
- package/dist/sdk/history/attestation-contract.js +1 -1
- package/dist/sdk/history/attestation-scan.js +1 -1
- package/dist/sdk/history/attestation.js +1 -1
- package/dist/sdk/history/maintenance.js +1 -1
- package/dist/sdk/history/salvage.js +3 -2
- package/dist/sdk/history/subject.js +1 -1
- package/dist/sdk/history-analytics.js +1 -1
- package/dist/sdk/history-compact.js +1 -1
- package/dist/sdk/history-mcp.js +1 -1
- package/dist/sdk/history-provenance.js +1 -1
- package/dist/sdk/history-read.js +1 -1
- package/dist/sdk/history-redact.js +1 -1
- package/dist/sdk/history-repair.js +1 -1
- package/dist/sdk/improvement-ledger-validation.js +1 -1
- package/dist/sdk/improvement-ledger.js +2 -2
- package/dist/sdk/index.js +1 -1
- package/dist/sdk/init-agent-guidance.js +16 -2
- package/dist/sdk/init.js +16 -2
- package/dist/sdk/invocation-author.js +1 -1
- package/dist/sdk/item-children.js +1 -1
- package/dist/sdk/item-metadata-index.js +1 -1
- package/dist/sdk/item-schedule.js +1 -1
- package/dist/sdk/item-transaction.js +1 -1
- package/dist/sdk/learnings.js +1 -1
- package/dist/sdk/lifecycle/append.js +4 -2
- package/dist/sdk/lifecycle/claim.js +1 -1
- package/dist/sdk/lifecycle/close-many.js +1 -1
- package/dist/sdk/lifecycle/close.js +1 -1
- package/dist/sdk/lifecycle/copy.js +1 -1
- package/dist/sdk/lifecycle/create.js +1 -1
- package/dist/sdk/lifecycle/delete.js +1 -1
- package/dist/sdk/lifecycle/event-validation-messages.js +1 -1
- package/dist/sdk/lifecycle/focus.js +1 -1
- package/dist/sdk/lifecycle/hierarchy-mutation-lock.js +1 -1
- package/dist/sdk/lifecycle/legacy-none-tokens.js +1 -1
- package/dist/sdk/lifecycle/lifecycle-transitions.js +1 -1
- package/dist/sdk/lifecycle/mcp-actions.js +1 -1
- package/dist/sdk/lifecycle/metadata-normalizers.js +1 -1
- package/dist/sdk/lifecycle/mutation-command-options.js +1 -1
- package/dist/sdk/lifecycle/plan-mutation-receipt.js +1 -1
- package/dist/sdk/lifecycle/plan.js +1 -1
- package/dist/sdk/lifecycle/recurrence-parsers.js +1 -1
- package/dist/sdk/lifecycle/reopen.js +1 -1
- package/dist/sdk/lifecycle/repeatable-metadata-parsers.js +2 -1
- package/dist/sdk/lifecycle/restore.js +1 -1
- package/dist/sdk/lifecycle/shared-unset-fields.js +1 -1
- package/dist/sdk/lifecycle/task-composition.js +1 -1
- package/dist/sdk/lifecycle/update-many.js +1 -1
- package/dist/sdk/lifecycle/update.js +2 -1
- package/dist/sdk/lifecycle-completion.js +1 -1
- package/dist/sdk/lifecycle-policy.js +1 -1
- package/dist/sdk/linked-artifacts.js +2 -1
- package/dist/sdk/mcp/apps.js +1 -1
- package/dist/sdk/mcp/authorization.js +1 -1
- package/dist/sdk/mcp/discovery.js +1 -1
- package/dist/sdk/mcp/interactions.js +1 -1
- package/dist/sdk/mcp/protocol.js +1 -1
- package/dist/sdk/mcp/skills.js +3 -1
- package/dist/sdk/mcp/subscriptions.js +1 -1
- package/dist/sdk/mcp/tasks.js +2 -2
- package/dist/sdk/mcp/transport.js +1 -1
- package/dist/sdk/merge/abandoned-receipts.js +1 -1
- package/dist/sdk/merge/driver.js +1 -1
- package/dist/sdk/merge/index.js +1 -1
- package/dist/sdk/merge/install.js +4 -2
- package/dist/sdk/merge/receipt-file-boundary.js +1 -1
- package/dist/sdk/merge/receipt-operation.js +1 -1
- package/dist/sdk/merge/receipt-schema.js +1 -1
- package/dist/sdk/merge/receipts.js +4 -4
- package/dist/sdk/merge/reconcile.js +1 -1
- package/dist/sdk/merge/three-way.js +3 -2
- package/dist/sdk/merge/worktree-config.js +1 -1
- package/dist/sdk/merge.js +1 -1
- package/dist/sdk/mutation-events.js +1 -1
- package/dist/sdk/mutation-guard.js +1 -1
- package/dist/sdk/notes.js +1 -1
- package/dist/sdk/output-contracts.js +1 -1
- package/dist/sdk/output-projection.js +1 -1
- package/dist/sdk/output-token-accounting.js +1 -1
- package/dist/sdk/output.js +2 -1
- package/dist/sdk/ownership-source.js +1 -1
- package/dist/sdk/package-import-adapters.js +1 -1
- package/dist/sdk/package-migrations.js +1 -1
- package/dist/sdk/package-runtime-options.js +1 -1
- package/dist/sdk/pagination.js +1 -1
- package/dist/sdk/profile.js +5 -1
- package/dist/sdk/provenance.js +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/query/activity.js +1 -1
- package/dist/sdk/query/aggregate.js +1 -1
- package/dist/sdk/query/calendar.js +4 -1
- package/dist/sdk/query/complete-list.js +1 -1
- package/dist/sdk/query/context.js +2 -1
- package/dist/sdk/query/duplicate-candidates.js +1 -1
- package/dist/sdk/query/get.d.ts +14 -2
- package/dist/sdk/query/get.js +1 -1
- package/dist/sdk/query/history.js +1 -1
- package/dist/sdk/query/item-filter-options.js +1 -1
- package/dist/sdk/query/light-metadata.js +1 -1
- package/dist/sdk/query/list-filter-shared.js +1 -1
- package/dist/sdk/query/list.js +1 -1
- package/dist/sdk/query/multi-value-filters.js +1 -1
- package/dist/sdk/query/next-ready-budget.js +1 -1
- package/dist/sdk/query/next.js +2 -1
- package/dist/sdk/query/parsers.js +1 -1
- package/dist/sdk/query/projection-contracts.js +1 -1
- package/dist/sdk/query/search/corpus.js +2 -1
- package/dist/sdk/query/search/filters.js +1 -1
- package/dist/sdk/query/search/input.js +1 -1
- package/dist/sdk/query/search/lexical.js +1 -1
- package/dist/sdk/query/search/response.js +1 -1
- package/dist/sdk/query/search/semantic.js +3 -2
- package/dist/sdk/query/search/types.js +1 -1
- package/dist/sdk/query/search-contracts.js +1 -1
- package/dist/sdk/query/search-pagination.d.ts +1 -1
- package/dist/sdk/query/search-pagination.js +1 -1
- package/dist/sdk/query/search-rendering.js +1 -1
- package/dist/sdk/query/search.js +1 -1
- package/dist/sdk/query/workspace-contracts.js +1 -1
- package/dist/sdk/query.js +1 -1
- package/dist/sdk/read-output/continuation.js +1 -1
- package/dist/sdk/read-output/options.js +1 -1
- package/dist/sdk/read-output/provenance.js +1 -1
- package/dist/sdk/read-output-budget.js +1 -1
- package/dist/sdk/read-output-contracts.js +1 -1
- package/dist/sdk/read-output-rows.js +1 -1
- package/dist/sdk/read-output-session.js +1 -1
- package/dist/sdk/relationship-analytics.js +1 -1
- package/dist/sdk/relationship-context.js +1 -1
- package/dist/sdk/relationship-history.js +7 -4
- package/dist/sdk/relationship-kinds/contract.js +1 -1
- package/dist/sdk/relationship-migration.js +1 -1
- package/dist/sdk/relationships.js +1 -1
- package/dist/sdk/reproducibility/process.js +1 -1
- package/dist/sdk/runtime/actions.js +1 -1
- package/dist/sdk/runtime/context.js +1 -1
- package/dist/sdk/runtime/schema-preview.js +1 -1
- package/dist/sdk/runtime/schema.js +1 -1
- package/dist/sdk/runtime-action-aliases.js +1 -1
- package/dist/sdk/runtime-extended-actions.js +1 -1
- package/dist/sdk/runtime-input.js +1 -1
- package/dist/sdk/runtime-primitives.js +1 -1
- package/dist/sdk/runtime-public-contracts.js +1 -1
- package/dist/sdk/runtime-stats-options.js +1 -1
- package/dist/sdk/runtime.js +1 -1
- package/dist/sdk/scheduling-shortcuts.js +1 -1
- package/dist/sdk/schema-migration.js +4 -3
- package/dist/sdk/schema.js +7 -1
- package/dist/sdk/search-refresh-worker.js +1 -1
- package/dist/sdk/similarity-scoring.js +1 -1
- package/dist/sdk/similarity.js +1 -1
- package/dist/sdk/start-task-status.js +1 -1
- package/dist/sdk/stats.js +1 -1
- package/dist/sdk/structured-mutations.js +1 -1
- package/dist/sdk/telemetry-flush.js +1 -1
- package/dist/sdk/telemetry.js +4 -3
- package/dist/sdk/templates.js +26 -2
- package/dist/sdk/test/batch.js +2 -2
- package/dist/sdk/test/entry.js +1 -1
- package/dist/sdk/test/execution.js +6 -5
- package/dist/sdk/test/json-path.js +1 -1
- package/dist/sdk/test/linked-command-detection.js +1 -1
- package/dist/sdk/test/measurements.js +1 -1
- package/dist/sdk/test/parsers.js +1 -1
- package/dist/sdk/test/runs.js +1 -1
- package/dist/sdk/test/trust.js +2 -2
- package/dist/sdk/test/workspace-snapshot.js +1 -1
- package/dist/sdk/testing.js +7 -4
- package/dist/sdk/traceability/runtime-files-lookup.js +1 -1
- package/dist/sdk/traceability/source-traceability.js +2 -1
- package/dist/sdk/tracker-root-discovery.js +1 -1
- package/dist/sdk/workspace-contracts-cache.js +1 -1
- package/dist/sdk/workspace-contracts.js +1 -1
- package/dist/sdk/workspace-memory.js +2 -2
- package/dist/sdk/workspace-recipe.js +1 -1
- package/dist/sdk/workspace-snapshot.js +5 -4
- package/dist/sdk/workspace-transaction-gc.js +1 -1
- package/dist/sdk/workspace-transaction.js +2 -2
- package/dist/sdk/workspace.js +3 -2
- package/dist/types/index.js +1 -1
- package/dist/types.js +1 -1
- package/docs/AGENT_EVIDENCE_CONSISTENCY.md +88 -0
- package/docs/DIAGNOSTIC_OUTPUT_CONTRACTS.md +25 -0
- package/docs/GET_READ_EVIDENCE.md +68 -0
- package/docs/OUTPUT_PROJECTION_CONTRACTS.md +23 -0
- package/docs/README.md +2 -0
- package/docs/SDK_AUDITED_MUTATIONS.md +35 -0
- package/docs/TESTING.md +8 -0
- package/docs/ecosystem-review-2026-09-28.json +2864 -3157
- 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/extensions/vcs/index.ts +4 -2
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-claude/package.json +2 -2
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/plugins/pm-codex/package.json +2 -2
- package/plugins/pm-codex/plugin.json +1 -1
- package/scripts/finalize-build.mjs +3 -2
- package/dist/cli-bundle/chunks/chunk-3AF2R3Y6.js +0 -6
- package/dist/cli-bundle/chunks/chunk-6ST3SCQ6.js +0 -2
- package/dist/cli-bundle/chunks/chunk-6Z4IV2MC.js +0 -8
- package/dist/cli-bundle/chunks/chunk-DEZPZOQ7.js +0 -2
- package/dist/cli-bundle/chunks/chunk-FW5LJXQY.js +0 -31
- package/dist/cli-bundle/chunks/chunk-H2DZW6I6.js +0 -3
- package/dist/cli-bundle/chunks/chunk-H7CXQBGQ.js +0 -2
- package/dist/cli-bundle/chunks/chunk-KP7NBQK3.js +0 -80
- package/dist/cli-bundle/chunks/chunk-MKXBCBAN.js +0 -20
- package/dist/cli-bundle/chunks/chunk-QPKQKSQU.js +0 -238
- package/dist/cli-bundle/chunks/chunk-SGFQQXFD.js +0 -2
- package/dist/cli-bundle/chunks/chunk-YCBGZF3T.js +0 -2
- package/dist/cli-bundle/chunks/chunk-YDWKGUQU.js +0 -3
- package/dist/cli-bundle/chunks/register-mutation-5PT3NW3A.js +0 -20
- package/dist/cli-bundle/chunks/register-operations-QDDQOAAV.js +0 -2
- package/dist/cli-bundle/chunks/register-setup-BBX67YMA.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-4FFPGNCJ.js +0 -6
- package/dist/cli-bundle/focused-chunks/chunk-73DA7ISY.js +0 -75
- package/dist/cli-bundle/focused-chunks/chunk-E754JDLY.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-FKK2HI3S.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-GMYUNHST.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-HIA2ZF64.js +0 -12
- package/dist/cli-bundle/focused-chunks/chunk-UTRSM3ZK.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-VVWYI2X7.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-WAJNX4RN.js +0 -20
- package/dist/cli-bundle/focused-chunks/chunk-WCY6HRZO.js +0 -30
- package/dist/cli-bundle/focused-chunks/chunk-YC32ZSLS.js +0 -165
- package/dist/cli-bundle/focused-chunks/chunk-ZIXFMIUL.js +0 -3
|
@@ -1,80 +0,0 @@
|
|
|
1
|
-
import{$i as De,A as U,Bi as ci,C as ae,Ci as li,Dc as B,Di as Ie,E as V,Ei as di,Fi as pi,Gn as vi,Hb as Bo,I as ue,Jb as Ho,Ld as Dt,Mb as Ne,Mc as K,Md as Qo,N as Po,Nd as Sn,Od as En,Oi as ui,Pd as $n,Qf as Se,Rd as ei,Sa as jo,Sd as ti,Ta as Lo,U as Ro,Ua as z,Ui as mi,Vd as ni,X as Ct,Xi as Lt,Yi as Ft,ab as N,ae as oi,bb as Fo,bd as Zo,bi as In,ca as No,cb as Mo,cd as st,cg as I,db as Go,dg as Q,dh as ai,di as si,eg as ii,ei as He,ej as fi,ff as T,fg as Y,fj as An,gc as xn,gg as ie,ha as wn,hc as Ko,ic as Rt,ig as ri,ih as H,ja as Do,k as Co,kc as ke,kg as ct,li as se,ma as vn,mc as xe,mf as Z,mg as jt,na as h,om as gi,pa as f,pc as Vo,pi as A,pm as je,qi as Ee,qm as lt,rc as Nt,rm as yi,sc as Yo,sm as _i,ta as Pt,tb as Uo,tc as Xo,tm as ce,ua as bn,ub as zo,um as Ke,va as kn,vb as Jo,vm as wi,vo as Mt,wm as me,x,xi as $e,xl as hi,y as Ot,yb as qo,z as pe,zb as Wo}from"./chunk-QPKQKSQU.js";import{mkdir as tc,readFile as nc}from"node:fs/promises";import Ei 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]="d9ef3878-afce-5983-8fe9-8a896f82d0a7")}catch{}})();var Tn=class extends Error{constructor(t="Workspace transaction interrupted"){super(t),this.name="WorkspaceTransactionInterruptedError"}},oc="sdk-workspace-transaction",ic=/^[a-zA-Z0-9._-]+$/,rc=30,ac=3e3;function $i(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n||!ic.test(n))throw new TypeError(`${t} must match [a-zA-Z0-9._-]+`);return n}function bi(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 sc(e){return{pmRoot:bi(e.pmRoot,"Transaction pmRoot"),transactionId:$i(e.transactionId,"Transaction id"),author:bi(e.author,"Transaction author")}}function ki(e,t,n){let o=e??t;if(!Number.isInteger(o)||o<=0)throw new TypeError(`${n} must be a positive integer`);return o}function Ii(e,t){return Ei.join(e,"transactions","sdk",`${t}.json`)}async function Ae(e,t){t.updatedAt=T();let n=Ii(e,t.transactionId);await tc(Ei.dirname(n),{recursive:!0}),await ae(n,`${JSON.stringify(t,null,2)}
|
|
2
|
-
`)}function cc(e){return Number.isInteger(e.attempt)&&typeof e.author=="string"&&typeof e.createdAt=="string"&&typeof e.updatedAt=="string"}function Le(e){return Object.assign(Object.create(null),e)}function lc(e,t){try{let n=JSON.stringify(e,(o,i)=>{if(typeof i=="number"&&!Number.isFinite(i))throw new TypeError(`${t} contains a non-finite number`);if(i===void 0||typeof i=="function"||typeof i=="symbol")throw new TypeError(`${t} contains a non-JSON value`);return i});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:lc(e,t)}function Cn(e,t,n,o){let i=On(n,o);i===void 0?delete e[t]:e[t]=i}function xi(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Si(e,t){return Array.isArray(e)&&new Set(e).size===e.length&&e.every(n=>typeof n=="string"&&t.includes(n))}function dc(e,t){if(!Si(e.startedStepIds,t)||!Si(e.completedStepIds,t)||!xi(e.results)||!xi(e.compensationData))return!1;let n=e.startedStepIds,o=new Set(n),i=e.completedStepIds,r=new Set(i);return Object.keys(e.compensationData).some(a=>!o.has(a))||Object.keys(e.results).some(a=>!r.has(a))?!1:e.status==="committed"?t.every(a=>r.has(a)):e.status!=="compensated"||r.size===0&&o.size===0}function pc(e,t,n){let o;try{o=JSON.parse(e)}catch{throw new TypeError(`Workspace transaction ${t} journal is invalid JSON`)}if(!o||typeof o!="object"||Array.isArray(o))throw new TypeError(`Workspace transaction ${t} journal is invalid`);let i=o,r=i.schemaVersion===1&&i.transactionId===t,a=Array.isArray(i.stepIds)&&i.stepIds.length===n.length&&i.stepIds.every((d,p)=>d===n[p]),s=dc(i,n),c=cc(i),l=["applying","compensating","compensated","committed"].includes(String(i.status));if(!r||!a||!s||!c||!l)throw new TypeError(`Workspace transaction ${t} journal does not match the supplied plan`);return{...i,results:Le(i.results),compensationData:Le(i.compensationData)}}async function uc(e,t,n,o,i){let r=i,a=r!==void 0;if(r?.status==="compensating"&&await Ai(e,r),r===void 0||r.status==="compensated"){let s=T();r={schemaVersion:1,transactionId:t,author:n,status:"applying",attempt:(r?.attempt??0)+1,createdAt:r?.createdAt??s,updatedAt:s,stepIds:o,startedStepIds:[],completedStepIds:[],results:Le(),compensationData:Le()},await Ae(e.pmRoot,r),await ye(e,r,"prepared")}return{journal:r,recovered:a}}async function mc(e,t,n){try{await hc(t,e.steps),await Ae(e.pmRoot,t);let o=new Set(t.completedStepIds),i=new Set(t.startedStepIds);for(let r of e.steps){if(o.has(r.id))continue;let a=await r.inspect(),s=On(a.result,`Step ${r.id} result`);if(a.state!=="applied"){let c=await r.prepareCompensation?.();Cn(t.compensationData,r.id,c,`Step ${r.id} compensation data`),i.add(r.id),t.startedStepIds=e.steps.map(d=>d.id).filter(d=>i.has(d)),await Ae(e.pmRoot,t);let l=await r.apply();s=On(l,`Step ${r.id} result`)}await ye(e,t,"step_applied",r.id),o.add(r.id),t.completedStepIds=e.steps.map(c=>c.id).filter(c=>o.has(c)),Cn(t.results,r.id,s,`Step ${r.id} result`),await Ae(e.pmRoot,t),await ye(e,t,"step_recorded",r.id)}return await ye(e,t,"committing"),t.status="committed",await Ae(e.pmRoot,t),await ye(e,t,"committed"),{transactionId:t.transactionId,status:"committed",recovered:n,results:Le(t.results)}}catch(o){if(o instanceof Tn||t.status==="committed")throw o;try{await Ai(e,t)}catch(i){throw new AggregateError([o,i],`Workspace transaction failed and compensation failed: ${String(i)}`,{cause:i})}throw o}}async function fc(e,t,n){try{return pc(await nc(Ii(e,t),"utf8"),t,n)}catch(o){if(o!==null&&typeof o=="object"&&"code"in o&&pe(o))return;throw o}}async function ye(e,t,n,o){await e.onTransition?.({transactionId:t.transactionId,attempt:t.attempt,transition:n,...o===void 0?{}:{stepId:o}})}async function hc(e,t){let n=new Set,o=Le();for(let i of t){let r=await i.inspect();r.state==="applied"&&(n.add(i.id),Cn(o,i.id,r.result,`Step ${i.id} result`))}e.results=o,e.completedStepIds=t.map(i=>i.id).filter(i=>n.has(i))}async function Ai(e,t){t.status="compensating",await Ae(e.pmRoot,t),await ye(e,t,"compensating");let n=new Set(t.completedStepIds),o=new Set(t.startedStepIds);for(let i of[...e.steps].reverse()){if(!o.has(i.id)&&!n.has(i.id))continue;let r;try{r=o.has(i.id)&&(await i.inspect()).state==="applied"}catch{r=o.has(i.id)}r&&(await ye(e,t,"step_compensating",i.id),await i.compensate(t.compensationData[i.id])),n.delete(i.id),o.delete(i.id),t.completedStepIds=e.steps.map(a=>a.id).filter(a=>n.has(a)),t.startedStepIds=e.steps.map(a=>a.id).filter(a=>o.has(a)),delete t.results[i.id],delete t.compensationData[i.id],await Ae(e.pmRoot,t),await ye(e,t,"step_compensated",i.id)}t.status="compensated",await Ae(e.pmRoot,t),await ye(e,t,"compensated")}async function Ti(e){let{pmRoot:t,transactionId:n,author:o}=sc(e),i=ki(e.lockTtlSeconds,rc,"Transaction lock TTL"),r=ki(e.lockWaitMs,ac,"Transaction lock wait"),a=[...e.steps];if(a.length===0)throw new TypeError("Workspace transaction requires at least one step");let s=a.map(d=>{let p=$i(d.id,"Transaction step id");if(p!==d.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:o,steps:a,lockTtlSeconds:i,lockWaitMs:r},l=await Z(t,oc,i,o,!1,!1,r);try{let d=await fc(t,n,s),p=d!==void 0;if(d?.status==="committed")return{transactionId:n,status:"committed",recovered:!0,results:Le(d.results)};let u=await uc(c,n,o,s,d);return await mc(c,u.journal,p||u.recovered)}finally{await l()}}import gc from"node:fs/promises";import yc 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]="c4dc16d1-672a-5b1c-b681-97a7b3febd69")}catch{}})();function Pn(e){return yc.join(e,"extension-migrations.json")}function Oi(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 Ci(e,t){return`${e.layer}:${e.name}:${t}`}async function _c(e){let t=Pn(e);if(!await x(t))return{version:1,updated_at:"",entries:[]};let n=JSON.parse(await gc.readFile(t,"utf8"));return{version:1,updated_at:typeof n.updated_at=="string"?n.updated_at:"",entries:Array.isArray(n.entries)?n.entries.filter(o=>typeof o?.key=="string"&&(o.status==="applied"||o.status==="failed")):[]}}async function wc(e,t){let n=await _c(e),o=new Map(n.entries.map(i=>[i.key,i]));return t.forEach((i,r)=>{let a=Oi(i,r),s=o.get(Ci(i,a));s&&(i.definition.status=s.status,s.status==="failed"?i.definition.reason=s.error:(delete i.definition.reason,delete i.definition.error,delete i.definition.message))}),n}async function vc(e){let t=await wc(e.pmRoot,e.migrations),n=new Map(t.entries.map(d=>[d.key,d])),o=[],i=!1,r=e.migrations.map((d,p)=>({migration:d,index:p})).filter(({migration:d})=>e.scope===void 0||d.layer===e.scope);for(let{migration:d,index:p}of r){let u=Oi(d,p),g=Ci(d,u),y=n.get(g),w=String(d.definition.status??"pending").toLowerCase(),m=y?.status??(w==="applied"||w==="failed"?w:"pending");if(m==="applied"){o.push({key:g,layer:d.layer,extension:d.name,id:u,before:m,outcome:"skipped"});continue}if(e.dryRun===!0){o.push({key:g,layer:d.layer,extension:d.name,id:u,before:m,outcome:"pending"});continue}let _=d.runtime_definition?.run??d.definition.run;if(typeof _!="function"){o.push({key:g,layer:d.layer,extension:d.name,id:u,before:m,outcome:"pending"});continue}let v=new Date().toISOString();try{await Promise.resolve(_({id:u,command:"migration",layer:d.layer,extension:d.name,pm_root:e.pmRoot,status:m}));let k={key:g,layer:d.layer,extension:d.name,id:u,status:"applied",attempted_at:v};n.set(g,k),d.definition.status="applied",delete d.definition.reason,delete d.definition.error,delete d.definition.message,o.push({key:g,layer:d.layer,extension:d.name,id:u,before:m,outcome:"applied"}),i=!0}catch(k){let S=k instanceof Error?k.message:String(k),R={key:g,layer:d.layer,extension:d.name,id:u,status:"failed",attempted_at:v,error:S};n.set(g,R),d.definition.status="failed",d.definition.reason=S,o.push({key:g,layer:d.layer,extension:d.name,id:u,before:m,outcome:"failed",error:S}),i=!0}}if(i){let d=await A(e.pmRoot),p={version:1,updated_at:new Date().toISOString(),entries:[...n.values()].sort((u,g)=>u.key.localeCompare(g.key))};await He({pmRoot:e.pmRoot,filePath:Pn(e.pmRoot),raw:`${JSON.stringify(p,null,2)}
|
|
3
|
-
`,op:"extension_migrations_apply",author:e.author,lockTtlSeconds:d.locks.ttl_seconds,lockWaitMs:d.locks.wait_ms})}let a=o.filter(d=>d.outcome==="pending").length,s=o.filter(d=>d.outcome==="applied").length,c=o.filter(d=>d.outcome==="skipped").length,l=o.filter(d=>d.outcome==="failed").length;return{ok:l===0,dry_run:e.dryRun===!0,state_path:Pn(e.pmRoot),total:o.length,pending_count:a,applied_count:s,skipped_count:c,failed_count:l,migrations:o}}async function Pi(e){let t=await A(e.resolvedRoots.settings_root),n=await ke({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),o=await xe(n);e.warnings.push(...n.warnings,...o.warnings);let i=await vc({pmRoot:e.resolvedRoots.pm_root,migrations:o.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:i,load_failure_count:n.failed.length,activation_failure_count:o.failed.length},i.ok)}import{readFile as bc,writeFile as kc}from"node:fs/promises";import dt 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]="5b131b40-e139-5a7d-a6ef-633fe2cbee64")}catch{}})();var Ni="# pm-cli:runtime-cache:start",Rn="# pm-cli:runtime-cache:end",Di=".agents/pm",xc=["runtime/","search/","locks/","transactions/","checkpoints/"],Sc=["search/eval-queries.json"];async function Ri(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 f("The workspace .gitignore is not writable.",h.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 ji(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/\/+$/,"")}function Nn(e){let t=e.replaceAll("\\","/");return dt.isAbsolute(e)||t===".."||t.startsWith("../")}function Ec(e=Di){let t=ji(e);return[Ni,...xc.map(n=>n==="search/"?`${t}/${n}*`:`${t}/${n}`),...Sc.map(n=>`!${t}/${n}`),Rn].join(`
|
|
4
|
-
`)}async function Li(e,t={}){let n=dt.join(e,".gitignore"),o=Di;if(t.pmRoot!==void 0){let d=ji(dt.relative(dt.resolve(e),dt.resolve(t.pmRoot)));if(Nn(d))return{path:n,changed:!1};d.length>0&&(o=d)}let i="";try{i=await Ri(()=>bc(n,"utf8"))}catch(d){if(!(d instanceof Error&&"code"in d&&pe(d)))throw d}let r=i.indexOf(Ni),a=i.indexOf(Rn),c=(r>=0&&a>=r?`${i.slice(0,r)}${i.slice(a+Rn.length)}`:i).trimEnd(),l=`${c.length>0?`${c}
|
|
5
|
-
|
|
6
|
-
`:""}${Ec(o)}
|
|
7
|
-
`;return l===i?{path:n,changed:!1}:(await Ri(()=>kc(n,l,"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]="f7999053-cf48-5588-b8c8-570789086dac")}catch{}})();var $c=[["beforeCommand","before_command"],["beforeMutation","before_mutation"],["afterCommand","after_command"],["onWrite","on_write"],["onRead","on_read"],["onIndex","on_index"]];function Ve(e,t={}){let n=new Set;t.extensionName!==void 0&&n.add(Nt(t.extensionName));for(let m of t.extensionNames??[])n.add(Nt(m));let o=m=>n.size===0||n.has(Nt(m)),i=(m,_)=>Fi(m.filter(v=>o(v.name)).map(_)),r=(m,_)=>Fi(m.filter(v=>o(v.name)).flatMap(_)),{registrations:a,commands:s,parsers:c,preflight:l,services:d,renderers:p,hooks:u}=e,g=r(a.relationship_kinds??[],m=>m.definitions.map(_=>_.kind)),y=p.overrides.filter(m=>o(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=i(a.assurance_providers??[],m=>m.definition.id);return{capabilities:Yo(e,t),commands:i(a.commands,m=>m.command),command_overrides:i(s.overrides,m=>m.command),command_handlers:i(s.handlers,m=>m.command),hooks:$c.filter(([m])=>u[m].some(_=>o(_.name))).map(([,m])=>m),flag_commands:i(a.flags,m=>m.target_command),item_types:r(a.item_types,m=>m.types.map(_=>_.name)),item_fields:r(a.item_fields,m=>m.fields.map(_=>_.name)),...g.length>0?{relationship_kinds:g}:{},migrations:r(a.migrations,m=>typeof m.definition.id=="string"?[m.definition.id]:[]),profiles:i(a.profiles,m=>m.profile.name),importers:i(a.importers,m=>m.importer),exporters:i(a.exporters,m=>m.exporter),search_providers:i(a.search_providers,m=>m.definition.name),vector_store_adapters:i(a.vector_store_adapters,m=>m.definition.name),...w.length>0?{assurance_providers:w}:{},parser_overrides:i(c.overrides,m=>m.command),service_overrides:i(d.overrides,m=>m.service),renderer_overrides:i(p.overrides,m=>m.format),...y.length>0?{renderer_ownership:y}:{},preflight_overrides:l.overrides.filter(m=>o(m.name)).length,preflight_ownership:l.overrides.filter(m=>o(m.name)).map(m=>({commands:[...m.commands??[]]}))}}function Fi(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]="8d1a6b35-70e8-5a61-8ce6-3bea9ed8170b")}catch{}})();var Ic="PM_SOURCE_CONTEXT_ACCESS",Ac="PM_ALLOW_SOURCE_CONTEXT_WRITES";function Mi(e){let t=e[Ic],n=t===void 0||t.trim().toLowerCase()==="write"?"write":"read_only",o=n==="read_only"&&e[Ac]?.trim()==="1";return{access:n,write_override_applied:o,source_writes_allowed:n==="write"||o}}import Gi from"node:fs";import Ut from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7ab9180f-dfcb-579d-bc0c-dbba2e4ad77e")}catch{}})();var pt="@unbrained/pm-cli",Tc=new Set(["append","claim","changelog","close","close-many","close-task","comments","config","copy","create","dedupe-merge","delete","deps","docs","extension","event","events","files","focus","gc","history-author-acknowledge","history-compact","history-redact","history-repair","init","install","item","learnings","meet","merge","normalize","notes","package","packages","pause-task","plan","profile","reindex","release","remind","restore","schema","start-task","test","test-all","test-runs","test-runs-worker","telemetry","templates","twin","update","update-many","upgrade","vcs","workspace"]),Ui=new Set(["--author","--output-budget","--output-format","--output-include","--output-limit","--output-session","--path","--pm-path"]),Ln=/\b(\d{4})\.(\d{1,2})\.(\d{1,2})(?:-(\d+))?\b/u,Jt="2026.8.31";function X(e,t){return e.some(n=>t.includes(n.split("=",1)[0]))}function Dn(e,t){return["activate","adopt","adopt-all","deactivate","init","install","migrate","reload","uninstall"].includes(t[0]??"")||X(e,["--activate","--adopt","--adopt-all","--deactivate","--fix-managed-state","--init","--install","--output","--reload","--scaffold","--uninstall"])}var Oc={changelog:(e,t)=>{if(t[0]==="generate")return!X(e,["--check"]);let n=e.indexOf("export");return t[0]==="export"&&(X(e,["--output"])||n>=0&&e[n+1]!==void 0&&!e[n+1].startsWith("-"))},comments:e=>X(e,["--add","--delete","--edit","--file","--stdin"]),config:(e,t)=>(t[0]==="project"||t[0]==="global"?t[1]:t[0])==="set",deps:()=>!1,docs:e=>X(e,["--add","--add-glob","--migrate","--remove"]),duplicates:()=>!1,events:()=>!1,extension:Dn,files:(e,t)=>X(e,["--add","--add-glob","--migrate","--remove"])||t[0]==="discover"&&X(e,["--apply"]),health:e=>!X(e,["--check-only","--no-refresh","--skip-vectors"]),learnings:e=>X(e,["--add","--delete","--edit","--file","--stdin"]),merge:(e,t)=>t[0]!=="report",notes:e=>X(e,["--add","--delete","--edit","--file","--stdin"]),package:Dn,packages:Dn,profile:(e,t)=>t[0]==="apply",schema:(e,t)=>["add-field","add-status","add-type","remove-field","remove-status","remove-type","remap-status","rename-field","rename-type"].includes(t[0]??"")&&!(X(e,["--infer"])&&!X(e,["--apply"])),telemetry:(e,t)=>t.slice(0,2).some(n=>["clear","flush"].includes(n)),templates:(e,t)=>t[0]==="save",test:e=>X(e,["--add","--add-json","--background","--measure","--remove","--resume","--run","--stop"]),validate:e=>X(e,["--auto-fix","--prune-missing"]),vcs:(e,t)=>["abandon","create","merge","propose","ref-create"].includes(t[0]??""),workspace:(e,t)=>t[0]==="snapshot"&&["create","delete","restore"].includes(t[1]??"")};function zt(e){let t=e.match(Ln);return t?[Number(t[1]),Number(t[2]),Number(t[3]),Number(t[4]??0)]:null}function Fe(e,t){let n=zt(e),o=zt(t);if(!n||!o)return null;for(let i=0;i<n.length;i+=1){let r=n[i]-o[i];if(r!==0)return Math.sign(r)}return 0}function Gt(e){return Fe(e,Jt)!==-1?3:2}function Cc(e,t){if(t===3)return e.filter(n=>n.history_epoch_compatible===!1).map(n=>({...n,declaration:n.declaration??n.version})).sort((n,o)=>Fe(n.version,o.version))[0]}function jn(e){try{let t=JSON.parse(Gi.readFileSync(e,"utf8"));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null}catch{return null}}function Pc(e){let t=[...e.matchAll(/(<=|<)\s*v?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/gu)].map(o=>({inclusive:o[1]==="<=",version:o[2]})),n=e.match(/\b\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?\s+-\s+v?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/u);return n?[...t,{inclusive:!0,version:n[1]}]:t}function Rc(e){let t=e.split("||").map(n=>Pc(n));return{bounded:t.some(n=>n.length>0),compatible:t.some(n=>n.every(o=>{let i=Fe(Jt,o.version);return i!==null&&(o.inclusive?i!==1:i===-1)}))}}function Nc(e){return["dependencies","devDependencies","optionalDependencies","peerDependencies"].flatMap(t=>{let n=e[t];if(typeof n!="object"||n===null)return[];let o=n[pt],i=typeof o=="string"?o.trim():"",r=/^[<!]/u.test(i)?void 0:i.match(Ln)?.[0];if(!r)return[];let a=/^(?:=|v)?\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?$/u.test(i),s=Rc(i);return[{version:r,constraint:a?"exact":s.bounded?"range":"minimum",...a?{}:{declaration:i},history_epoch_compatible:a?Fe(r,Jt)!==-1:s.compatible}]})}function Dc(e){let n=jn(Ut.join(e,"package-lock.json"))?.packages;if(typeof n!="object"||n===null)return;let o=n["node_modules/@unbrained/pm-cli"];if(typeof o!="object"||o===null)return;let i=o.version;return typeof i=="string"?i:void 0}function jc(e,t){try{let n=Gi.readFileSync(Ut.join(e,t),"utf8").split(/\r?\n/u),o=n.findIndex(c=>c.includes(pt));if(o<0)return;let i=n[o].match(/^\s*/u)[0].length,r=[n[o]];for(let c=o+1;c<n.length;c+=1){let l=n[c],d=l.trim(),p=l.match(/^\s*/u)[0].length;if(d.length>0&&p<=i)break;r.push(l)}return r.join(`
|
|
8
|
-
`).match(/^\s*version(?::\s*|\s+)["']?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/mu)?.[1]??r[0].match(Ln)?.[0]}catch{return}}function Fn(e){let t=[],n=jn(Ut.join(e,"package.json"));n&&t.push(...Nc(n).map(a=>({...a,source:"package.json"})));let i=jn(Ut.join(e,"node_modules","@unbrained","pm-cli","package.json"))?.version;typeof i=="string"&&zt(i)&&t.push({version:i,source:"installed-package",constraint:"exact",history_epoch_compatible:Gt(i)===3});let r=Dc(e);r&&zt(r)&&t.push({version:r,source:"package-lock.json",constraint:"exact",history_epoch_compatible:Gt(r)===3});for(let a of["pnpm-lock.yaml","yarn.lock"]){let s=jc(e,a);s&&t.push({version:s,source:a,constraint:"exact",history_epoch_compatible:Gt(s)===3})}return t}function zi(e){for(let t=0;t<e.length;t+=1){let n=e[t];if(Ui.has(n)){t+=1;continue}if(!n.startsWith("-"))return{command:n.toLowerCase(),index:t}}}function Lc(e){let t=zi(e);if(!t||X(e,["--help","-h","--dry-run"]))return!1;let{command:n,index:o}=t,i=[];for(let a=o+1;a<e.length;a+=1){let s=e[a];if(Ui.has(s)){a+=1;continue}s.startsWith("-")||i.push(s.toLowerCase())}let r=Oc[n];return r?r(e,i):Tc.has(n)}function Fc(e){let t=zi(e.argv)?.command,n=Lc(e.argv),o=Fn(e.projectRoot).filter(d=>Fe(d.version,e.executingVersion)!==null).sort((d,p)=>Fe(p.version,d.version)),i=o[0],r=i!==void 0&&Fe(e.executingVersion,i.version)===-1,a=Gt(e.executingVersion),s=Cc(o,a),c=n&&s!==void 0,l=r&&!n?{code:"project_runtime_stale_read",executing_version:e.executingVersion,project_version:i.version,source:i.source,message:"This read is using an older pm runtime than the project requires.",next_steps:[`Run the command through the project's installed ${pt} ${i.version}.`,"Install the project dependencies with its declared package manager if the local executable is missing."]}:void 0;return{compatible:!n||!r&&!c||e.allowStale===!0,executing_version:e.executingVersion,...i?{project_version:i.version,source:i.source}:{},...t?{command:t}:{},mutating:n,stale:r,history_epoch_incompatible:c,writer_item_hash_version:a,...s?{incompatible_project_version:s.declaration,incompatible_source:s.source}:{},...l?{warning:l}:{},override_applied:n&&(r||c)&&e.allowStale===!0}}function Vf(e){let t=Fc(e);if(t.compatible)return t;throw t.history_epoch_incompatible?new f(`pm ${t.executing_version} cannot write item-hash epoch ${t.writer_item_hash_version} into a project pinned to pm ${t.incompatible_project_version}.`,h.CONFLICT,{code:"project_runtime_history_epoch_incompatible",reason:t.incompatible_source,why:`The pinned runtime cannot read item_hash_version ${t.writer_item_hash_version}; allowing the write would break its health and validation gates.`,nextSteps:[`Upgrade the project's ${pt} pin to ${Jt} or newer before mutating tracker history.`,"For an intentional coordinated migration only, set PM_ALLOW_STALE_CLI=1 for this invocation and record why.","Read-only commands remain available without an override."]}):new f(`pm ${t.executing_version} cannot mutate a project pinned to newer pm ${t.project_version}.`,h.CONFLICT,{code:"project_runtime_stale_mutation",reason:t.source,why:"An older runtime can write storage, history, and merge contracts it does not understand.",nextSteps:[`Run this command through the project's installed ${pt} ${t.project_version}.`,"For an intentional recovery only, set PM_ALLOW_STALE_CLI=1 for this invocation and record why.","Read-only commands remain available without an override."]})}import{access as zc,readFile as Gn,realpath as Te}from"node:fs/promises";import{constants as Jc}from"node:fs";import{execFile as qc}from"node:child_process";import C from"node:path";import{promisify as Wc}from"node:util";import{execFile as Mc}from"node:child_process";import Gc from"node:path";import{promisify as Uc}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]="725f175b-c548-5700-8e85-ea0b5dce3747")}catch{}})();var Ye=Uc(Mc);function re(){let e={...process.env};for(let t of["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES","GIT_DISCOVERY_ACROSS_FILESYSTEM"])delete e[t];return e}async function Mn(e,t){try{return(await Ye("git",["config","--local",...t==="core.bare"||t==="extensions.worktreeConfig"?["--type=bool"]:[],"--get",t],{cwd:e,env:re(),timeout:1e4})).stdout.trim()}catch(n){if(typeof n=="object"&&n!==null&&"code"in n&&n.code===1)return;throw n}}async function Ji(e){if(await Mn(e,"extensions.worktreeConfig")==="true")return"--worktree";let{stdout:t}=await Ye("git",["rev-parse","--path-format=absolute","--git-dir","--git-common-dir"],{cwd:e,env:re(),timeout:1e4}),[n,o]=t.trim().split(/\r?\n/);if(n===o)return"--local";let i=Gc.join(o,"config.worktree");for(let r of["core.bare","core.worktree"]){let a=await Mn(e,r);a===void 0||r==="core.bare"&&a!=="true"||(await Ye("git",["config","--file",i,r,a],{cwd:e,env:re(),timeout:1e4}),await Ye("git",["config","--local","--unset-all",r],{cwd:e,env:re(),timeout:1e4}))}for(let r of["pm-item-toon","pm-item-markdown","pm-history","pm-relationship","pm-json"])for(let a of["name","driver"]){let s=`merge.${r}.${a}`,c=await Mn(e,s);c!==void 0&&await Ye("git",["config","--file",i,s,c],{cwd:e,env:re(),timeout:1e4})}return await Ye("git",["config","--local","extensions.worktreeConfig","true"],{cwd:e,env:re(),timeout:1e4}),"--worktree"}(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]="22d0a3bd-dd65-5d9a-86bd-e8116d53d94f")}catch{}})();var Xe=Wc(qc),qt="# pm-cli:merge-drivers:start",Bc="# pm-cli:merge-drivers:end",ut="# pm-cli:merge-drivers:v2:start",Bi="# pm-cli:merge-drivers:v2:end",Hc="merge-fence",Kc="merge-attributes";function qi(e){return`'${e.replaceAll("'",`'"'"'`)}'`}async function Vc(e,t){let n=await Te(e);if(/(?:^|[\\/])bun-node-[^\\/]+[\\/]bun(?:\.exe)?$/iu.test(n))return;let{stdout:o}=await Xe(e,["--version"],{encoding:"utf8",windowsHide:!0,timeout:1e4});return o.trim()===t?n:void 0}async function Yc(){let e=ue(import.meta.url,["../../.."]),t=process.execPath,n=!1,o=await Te(process.execPath),i=process.versions.bun,r=(process.env.PATH??"").split(C.delimiter).filter(s=>C.isAbsolute(s)).map(s=>C.join(s,i===void 0?C.basename(process.execPath):process.platform==="win32"?"bun.exe":"bun")),a=i===void 0?r:[process.env.npm_execpath??"",...r,o].filter(s=>C.isAbsolute(s)&&/^(?:bun|bun\.exe)$/iu.test(C.basename(s)));for(let s of a)try{if(await zc(s,Jc.X_OK),i!==void 0){let c=await Vc(s,i);if(c!==void 0){t=c,n=!0;break}continue}if(s!==o&&await Te(s)===o){t=s;break}}catch{}if(i!==void 0&&!n)throw new f("Cannot install Bun merge drivers without a durable executable matching the current Bun version.",h.DEPENDENCY_FAILED,{code:"merge_bun_launcher_unavailable",why:"The current Bun process may be a temporary bunx launcher that Git cannot reuse after this command exits.",nextSteps:["Run with a durable version-matched Bun executable, expose one on an absolute PATH entry, or invoke pm through a Bun runner that publishes an absolute npm_execpath.","Retry pm merge install, then check pm health --strict-exit before merging branches."]});return`${qi(t)} ${qi(C.join(e,"dist","cli.js"))}`}var Hi=[{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 Xc(e){let t=e.explicitPath?.trim(),n=e.environment.PM_SOURCE_WORKSPACE_ROOT?.trim(),o=e.environment.PM_SOURCE_PM_PATH?.trim(),i=Mi(e.environment),r=!!(n&&o),a=t===void 0&&r&&(e.dryRun||i.source_writes_allowed);if(t!==void 0){let s=N(e.cwd,t);return{pm_root:s,workspace_start:s,source_coordinates_available:r,source_context_selected:!1,source_policy:i}}return a?{pm_root:C.resolve(o),workspace_start:C.resolve(n),source_coordinates_available:!0,source_context_selected:!0,source_policy:i}:{pm_root:r?N(e.cwd,".agents/pm"):N(e.cwd),workspace_start:e.cwd,source_coordinates_available:r,source_context_selected:!1,source_policy:i}}async function Wt(e){try{let{stdout:t}=await Xe("git",["rev-parse","--show-toplevel"],{cwd:e,env:re(),encoding:"utf8",windowsHide:!0,timeout:1e4});return await Te(t.trim())}catch{return null}}async function Ki(e){let t=await Wt(e);if(t===null)throw new f("pm merge install requires a git repository (merge drivers are git configuration).",h.USAGE);return t}function Un(e,t){return C.relative(e,t).replaceAll("\\","/")}function le(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function Wi(e,t){if(e[t]!=="'")return null;let n="";for(let o=t+1;o<e.length;o+=1){if(e.startsWith(`'"'"'`,o)){n+="'",o+=4;continue}if(e[o]==="'")return{value:n,nextOffset:o+1};n+=e[o]}return null}async function Zc(e,t,n){if(Fn(t).filter(r=>r.constraint==="exact").some(r=>r.version!==n))return!1;let i=await Wt(e);if(i!==null&&i!==await Te(t)){let r=await Promise.all([i,t].map(async a=>{let s=await Xe("git",["rev-parse","--path-format=absolute","--git-common-dir"],{cwd:a,env:re(),timeout:1e4});return Te(s.stdout.trim())}));if(r[0]===r[1])return!1}return!0}async function Qc(e,t,n){let o=Wi(e,0);if(o===null||e[o.nextOffset]!==" ")return!1;let i=Wi(e,o.nextOffset+1);if(i===null||e.slice(i.nextOffset)!==t||!/^(?:node|bun)(?:\.exe)?$/iu.test(C.basename(o.value))||C.basename(i.value)!=="cli.js"||C.basename(C.dirname(i.value))!=="dist"||!await x(o.value)||!await x(i.value))return!1;try{let r=C.dirname(C.dirname(i.value)),a=JSON.parse(await Gn(C.join(r,"package.json"),"utf8")),s=typeof a.bin=="string"?a.bin:a.bin?.pm;return await Zc(r,n,a.version)?a.name==="@unbrained/pm-cli"&&s==="dist/cli.js":!1}catch{return!1}}function zn(e,t){let n=e.length>0?`${e}/`:"",o=[`${le(`${n}**/*.toon`)} merge=pm-item-toon`,`${le(`${n}**/*.md`)} merge=pm-item-markdown`];for(let i of t)o.push(`${le(`${n}${i}/*.toon`)} merge=pm-item-toon`),o.push(`${le(`${n}${i}/*.md`)} merge=pm-item-markdown`);return o.push(`${le(`${n}**/*.jsonl`)} merge=pm-relationship`),o.push(`${le(`${n}history/*.jsonl`)} merge=pm-history`),o.push(`${le(`${n}settings.json`)} merge=pm-json`),o.push(`${le(`${n}**/*.json`)} merge=pm-json`),o.push(`${le(`${n}extensions/**`)} -merge`),o.push(`${le(`${n}extensions/.managed-extensions.json`)} merge=pm-json`),o}function Vi(e){let t=[],n=0;for(;n<e.length;){let o=e.indexOf(qt,n),i=e.indexOf(ut,n),r=o===-1?i:i===-1?o:Math.min(o,i);if(r===-1)break;let a=r===i,s=a?ut:qt,c=a?Bi:Bc,l=e.indexOf(c,r+s.length),d=l===-1?e.length:l+c.length;t.push({start:r,end:d,closed:l!==-1,lines:e.slice(r+s.length,l===-1?d:l).split(`
|
|
9
|
-
`).map(p=>p.trim()).filter(Boolean)}),n=d}return t}function Yi(e,t,n){let o=new Set(t),i=le(n.length>0?`${n}/`:"").slice(0,-1);return e.some(r=>o.has(r)||r.startsWith(i)&&/^[^/]+\/\*\.(?:toon|md)" merge=pm-item-(?:toon|markdown)$/u.test(r.slice(i.length)))}async function Xi(e,t,n,o){let i=C.join(e,".gitattributes"),r=o?null:(await Xe("git",["rev-parse","--absolute-git-dir"],{cwd:e,env:re(),encoding:"utf8",windowsHide:!0,timeout:1e4})).stdout.trim(),a=r===null?null:await Z(r,Kc,120,"merge-fence",!1,!0,5e3);try{let s=await U(i)??"",c=[ut,...n,Bi].join(`
|
|
10
|
-
`),l=Vi(s),d=l.filter(u=>Yi(u.lines,n,t));d.length===0&&t===".agents/pm"&&l.length===1&&l[0].lines.every(u=>!u.includes(".agents/pm/"))&&d.push(l[0]);let p;if(d.length>0){let u=d[0];p=s;for(let g of d.slice(1).reverse())p=`${p.slice(0,g.start)}${p.slice(g.end)}`;p=`${p.slice(0,u.start)}${c}${p.slice(u.end)}`}else{let u=s.trimEnd();p=`${u.length>0?`${u}
|
|
11
|
-
|
|
12
|
-
`:""}${c}
|
|
13
|
-
`}return p===s?{path:i,changed:!1}:(o||await ae(i,p),{path:i,changed:!0})}finally{await a?.()}}function Zi(e){let t=z(e,null);return[...new Set(Object.values(t.type_to_folder))].sort((n,o)=>n.localeCompare(o))}async function kh(e,t){let n=C.resolve(e),o=null,i="",r=n;for(let m=0;m<8;m+=1){let _=C.join(r,".gitattributes");try{let k=await Gn(_,"utf8");if(k.includes(ut)||k.includes(qt)){o=r,i=k;break}}catch{}let v=C.dirname(r);if(v===r)break;r=v}if(o===null)return{status:"not_installed",missing_patterns:[],stale_patterns:[],schema_scope:"project"};let a=C.join(o,".gitattributes"),s=Un(o,n),c=Vi(i),l=zn(s,t),d=c.filter(m=>Yi(m.lines,l,s)),p=d.flatMap(m=>m.closed?m.lines:[]),u=new Set(p),g=new Set(l),y=l.filter(m=>!u.has(m)),w=p.filter(m=>!g.has(m));return{status:d.length!==1||!d[0].closed||y.length>0||w.length>0?"drift":"ok",path:a,missing_patterns:y,stale_patterns:w,schema_scope:"project"}}async function xh(e){let t=[],n=[];for(let o of Hi){let i=`merge.${o.key}.driver`,r=` merge driver ${o.artifact} "%O" "%A" "%B"${o.itemPath===void 0?"":` --item-path ${o.itemPath}`}`;try{let{stdout:a}=await Xe("git",["config","--get",i],{cwd:e,env:re(),encoding:"utf8",windowsHide:!0,timeout:1e4}),s=a.trim();await Qc(s,r,e)||n.push(i)}catch{t.push(i)}}return{status:t.length>0?"missing":n.length>0?"drift":"ok",missing_keys:t,drifted_keys:n}}async function Qi(e){let t;try{t=await Ki(C.resolve(e))}catch{return{status:"no_git"}}let n=Un(t,C.resolve(e)),o=await A(e),i=H(void 0,o.author_default),r=await Z(e,Hc,o.locks.ttl_seconds,i,!1,se(o).force_required_for_stale_lock,o.locks.wait_ms);try{let a=C.join(t,".gitattributes"),s;try{s=await Gn(a,"utf8")}catch(p){if(p instanceof Error&&"code"in p&&pe(p))return{status:"not_installed",path:a};throw p}if(!s.includes(ut)&&!s.includes(qt))return{status:"not_installed",path:a};let c=await A(e),l=Zi(c),d=await Xi(t,n,zn(n,l),!1);return{status:d.changed?"refreshed":"unchanged",path:d.path}}finally{await r()}}async function Sh(e,t){let n=Xc({cwd:process.cwd(),explicitPath:t.path,dryRun:e.dryRun===!0,environment:process.env}),o=n.pm_root;await Se(o);let i=await Ki(n.workspace_start);return Jn({pmRoot:o,workspaceRoot:i,dryRun:e.dryRun===!0})}async function Jn(e){let t=C.resolve(e.pmRoot),n=C.resolve(e.workspaceRoot),o=e.dryRun===!0,i,r;try{[i,r]=await Promise.all([Te(t),Te(n)])}catch(g){throw new f(`Cannot resolve tracker root ${t} or workspace root ${n}: ${String(g)}`,h.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=Un(r,i);if(Nn(a))throw new f(`Tracker root ${t} is outside the git repository ${n}; there is nothing to configure for this repository.`,h.USAGE);let s=await A(i),c=Zi(s),l=zn(a,c),d=[],p=await Yc();for(let g of Hi)d.push({key:`merge.${g.key}.name`,value:g.name}),d.push({key:`merge.${g.key}.driver`,value:`${p} merge driver ${g.artifact} "%O" "%A" "%B"${g.itemPath===void 0?"":` --item-path ${g.itemPath}`}`});if(!o)try{let g=await Ji(r);for(let y of d)await Xe("git",["config",g,y.key,y.value],{cwd:r,env:re(),encoding:"utf8",windowsHide:!0,timeout:1e4})}catch{throw new f(`Cannot install repository-local merge drivers in ${r}. Ensure the repository Git config is writable and no other Git process holds its lock, then retry.`,h.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 Xi(r,a,l,o);return{ok:!0,dry_run:o,workspace_root:r,pm_root:i,gitattributes:{path:u.path,changed:u.changed,patterns:l,schema_scope:"project"},git_config:d,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: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]="0daf7c89-abc5-5c35-ba3f-9772a50408c0")}catch{}})();var mt={type:"string",minLength:1,maxLength:128,pattern:"\\S"},Bt={type:"array",minItems:1,maxItems:Sn,items:mt},er={...Bt,items:{...mt,pattern:"^(?!(?:.*\\.)?(?:__proto__|constructor|prototype)(?:\\.|$))[a-zA-Z_][a-zA-Z0-9_]*(?:\\.[a-zA-Z_][a-zA-Z0-9_]*){0,7}$"}},el={type:"object",additionalProperties:!1,required:["id","rule"],properties:{id:{type:"string",minLength:1,maxLength:128,pattern:"^[a-zA-Z0-9][a-zA-Z0-9._-]*$"},description:{type:"string",minLength:1,maxLength:500,pattern:"\\S"},effect:{enum:["advise","warn","refuse"]},subject:{type:"object",additionalProperties:!1,properties:{...Object.fromEntries(["types","tags","statuses","operations","parents"].map(e=>[e,Bt])),dependency:{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:mt,id:mt}}}},rule:{oneOf:[{type:"object",additionalProperties:!1,required:["kind","fields"],properties:{kind:{const:"require_fields"},fields:er}},{type:"object",additionalProperties:!1,required:["kind","authors"],properties:{kind:{const:"authors"},authors:Bt}},...["field_writers","approval"].map(e=>({type:"object",additionalProperties:!1,required:["kind","fields","authors"],properties:{kind:{const:e},fields:er,authors:Bt}})),{type:"object",additionalProperties:!1,required:["kind","allowed"],properties:{kind:{const:"transition"},allowed:{type:"array",maxItems:Sn,items:{type:"array",minItems:2,maxItems:2,items:mt}}}}]}}},Ih={$schema:"https://json-schema.org/draft/2020-12/schema",title:"pm workflow policy registry",type:"object",additionalProperties:!1,required:["version","policies"],properties:{version:{const:1},enforcement:{enum:["advise","refuse"],default:"advise"},policies:{type:"array",maxItems:Qo,items:el}}};(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]="42dee0a5-d003-5e44-8b2d-d74a23d3f2ce")}catch{}})();async function Ch(e,t,n,o){let i=await Ie(e).catch(()=>null);return i===null?{check:{name:"completeness",status:"error",ok:!1,details:{policy_registry_readable:!1,policy_registry_path:"schema/policies.json",remediation_hint:"Repair schema/policies.json, then rerun pm validate."}},warnings:["validate_completeness_policy_registry_unreadable"]}:tr(i,t,n,o)}function tl(e,t,n){return e===0?"undeclared":t===0?"empty":n===0?"inapplicable":n===t?"covered":"partial"}function tr(e,t,n=5,o=!1){let i=[],r=new Map,a=e.policies.filter(m=>m.rule.kind==="require_fields"),s=a.filter(m=>m.subject?.operations===void 0),c=new Set,l=0,d=0,p=0,u=0,g=0,y=ni(e);for(let m of t){let _=y({operation:"",author:"",before:m,after:m,completeness_only:!0});l+=+(_.decisions.length>0),d+=_.decisions.length,_.decisions.forEach(S=>c.add(S.policy_id));let v=_.decisions.filter(S=>!S.satisfied);if(v.length===0)continue;u+=1;let k=r.get(m.type)??{items:0,violations:0,missing_fields:0};k.items+=1;for(let S of v)p+=1,k.violations+=1,k.missing_fields+=S.missing_fields.length,S.effect==="refuse"&&(g+=1),i.length<n&&i.push({id:m.id,type:m.type,status:m.status,decision:S});r.set(m.type,k)}let w=o||g>0?"error":p>0?"warn":"ok";return{check:{name:"completeness",status:w,ok:w==="ok",details:{scope:"operation_independent_require_fields",declared_requirement_count:a.length,state_requirement_count:s.length,applicable_requirement_count:c.size,requirement_application_count:d,governed_items:l,ungoverned_items:t.length-l,contract_status:tl(a.length,t.length,l),applied_policy_ids:[...c].sort().slice(0,Math.max(0,n)),applied_policy_ids_truncated:c.size>Math.max(0,n),checked_items:t.length,incomplete_items:u,violation_count:p,refused_violations:g,missing_by_type:Object.fromEntries(r),violations:i,violations_truncated:i.length<p,enforcement:e.enforcement}},warnings:[...p>0?[`validate_completeness_missing_fields:${p}`]:[],...o?["validate_completeness_source_incomplete"]:[]]}}import nl 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]="f54fe358-8f4c-5bf4-ae2a-9c92cd08c953")}catch{}})();function ol(){return{version:1,enforcement:"advise",policies:[...[["Epic",["goal","objective","body"]],["Story",["description","value","acceptance_criteria"]],["Decision",["body","resolution"]],["Feature",["acceptance_criteria","expected_result"]],["Task",["description"]],["Issue",["repro_steps","expected_result"]],["Chore",["description"]]].map(([t,n])=>({id:`completeness-${t.toLowerCase()}`,effect:"advise",description:`Evidence expected when ${t} work reaches completion.`,subject:{types:[t],statuses:["closed"]},rule:{kind:"require_fields",fields:[...n]}})),{id:"completeness-resolution",effect:"advise",subject:{statuses:["closed"]},rule:{kind:"require_fields",fields:["resolution","expected_result","actual_result"]}}]}}function ir(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{throw new f("Policy definition must be valid JSON.",h.USAGE)}if(typeof t!="object"||t===null||Array.isArray(t))throw new f("Policy definition must be an object.",h.USAGE);return t}async function il(e,t){let n=N(process.cwd(),e.path);await Se(n);let o=await A(n);return{pmRoot:n,settings:o,author:H(t,o.author_default)}}function nr(e,t,n,o){if(e==="policy-mode")return $n({...n,enforcement:t});let i=n.policies.filter(s=>s.id!==t);if(e==="policy-remove")return{...n,policies:i};let r=En(o.definition),a=$n({...n,policies:[...i,r].sort((s,c)=>s.id.localeCompare(c.id))});if(Buffer.byteLength(`${JSON.stringify(a,null,2)}
|
|
14
|
-
`)>ci)throw new f("Policy registry exceeds its byte ceiling.",h.USAGE);return a}async function or(e,t,n,o){if(n.dryRun)return{policy_result:!0,action:e,changed:!1,result:nr(e,t,await Ie(o.pmRoot),n)};let i=await si({pmRoot:o.pmRoot,filePath:nl.join(o.pmRoot,"schema","policies.json"),op:`schema:${e}`,author:o.author,message:n.message,lockTtlSeconds:o.settings.locks.ttl_seconds,lockWaitMs:o.settings.locks.wait_ms,mutate(r){let a=nr(e,t,li(r),n);return{raw:`${JSON.stringify(a,null,2)}
|
|
15
|
-
`,result:a}}});return{policy_result:!0,action:e,changed:i.changed,result:i.result}}async function rl(e,t,n){let o,i=await fi({...n,id:e,op:"policy_approve",message:t.message,resolveHistoryContext:()=>({workflow_approval:o}),async mutate(r){let s=(await Ie(n.pmRoot)).policies.find(c=>c.id===t.policy);if(!s||s.rule.kind!=="approval")throw new f("--policy must name an approval rule.",h.USAGE);if(!s.rule.authors.includes(n.author))throw new f("This actor is not a declared approver.",h.CONFLICT);return await di(n.pmRoot,r.metadata.id),o={policy_id:s.id,policy_fingerprint:ei(s),content_fingerprint:ti(s,{...r.metadata,body:r.body})},{changedFields:[]}}});return{policy_result:!0,action:"policy-approve",changed:!0,result:{id:i.item.id,...o,warnings:i.warnings}}}function al(e,t){let n=ir(t),o=En({...n,id:n.id===void 0?e:n.id});if(e!==void 0&&e.trim()!==o.id)throw new f("Policy id operand does not match definition.id.",h.USAGE,{required:"Use the same policy id operand and definition.id, or supply only one of them.",nextSteps:["Omit the policy id operand to use definition.id, or omit definition.id to use the operand."]});return o}async function Kh(e,t,n={},o={}){if(!Dt.includes(e))throw new f("Unknown workflow policy action.",h.USAGE);if(e==="policy-presets")return{policy_result:!0,action:e,changed:!1,result:ol()};let i=await il(o,n.author);if(e==="policies")return{policy_result:!0,action:e,changed:!1,result:await Ie(i.pmRoot)};if(e==="policy-put"){let d=al(t,n.definition);return or(e,d.id,{...n,definition:d},i)}if(!t?.trim())throw new f(`schema ${e} requires an operand.`,h.USAGE);if(["policy-remove","policy-mode"].includes(e))return or(e,t,n,i);if(e==="policy-approve"){if(n.dryRun)throw new f("Use policy-check to preview; policy-approve records an approval.",h.USAGE);return rl(t,n,i)}let r=z(i.settings,B()),a=await Lt(i.pmRoot,t,i.settings.id_prefix,i.settings.item_format,r.type_to_folder);if(!a)throw new f(`Item ${t} not found.`,h.NOT_FOUND);let{document:s}=await Ft(a,{schema:i.settings.schema}),c={...s.metadata,body:s.body},l=n.definition===void 0?c:{...c,...ir(n.definition)};if(l.id!==c.id)throw new f("Policy preview cannot change the item id.",h.USAGE);return{policy_result:!0,action:e,changed:!1,result:await pi(i.pmRoot,await Ie(i.pmRoot),{operation:"update",author:i.author,before:c,after:l,completeness_only:n.definition===void 0})}}import{createHash as _r}from"node:crypto";import Ge from"node:fs/promises";import ot 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]="f9535c02-9214-5d5e-bac0-2dabbe5d395e")}catch{}})();var sl=new Set(bn),cl=new Set(kn),rr=new Set([...No.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"]),ll=["create","update"];function lr(e){if(typeof e!="string")return"";let t=e.trim().toLowerCase().replaceAll(/[\s_]+/g,"-");return t.startsWith("--")?t.slice(2):t}function ar(e){return e.replaceAll("_","-")}function dl(e,t){let n=new Set;for(let o of e){let i=lr(o);i.length>0&&i!==t&&n.add(i)}return[...n].sort((o,i)=>o.localeCompare(i))}function pl(e){let t=new Set;for(let n of e??[]){let o=n.trim();o.length>0&&t.add(o)}return[...t].sort((n,o)=>n.localeCompare(o))}function ul(e){let t=new Set,n=[];for(let o of e??[]){let i=o.trim().toLowerCase();if(i.length!==0){if(!cl.has(i))throw new Error(`Invalid field command "${o}". Allowed: ${kn.join(", ")}.`);t.has(i)||(t.add(i),n.push(i))}}return e===void 0||n.length===0?[...ll]:n}function dr(e){let t=I(e.key);if(t.length===0)throw new Error("Field key must not be empty.");if(rr.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: ${[...rr].sort((d,p)=>d.localeCompare(p)).join(", ")}.`);let n=typeof e.type=="string"&&e.type.trim().length>0?e.type.trim().toLowerCase():"string";if(!sl.has(n))throw new Error(`Invalid field type "${e.type}". Allowed: ${bn.join(", ")}.`);let o=n,i=ul(e.commands),r=lr(e.cliFlag),a=r.length>0&&r!==ar(t)?r:void 0,s=a??ar(t),c=dl(e.aliases??[],s),l=e.description?.trim();return{key:t,type:o,commands:i,description:l&&l.length>0?l:void 0,cliFlag:a,cliAliases:c,required:e.required===!0,requiredOnCreate:e.requiredOnCreate===!0,allowUnset:e.allowUnset!==!1,requiredTypes:pl(e.requiredTypes)}}function ml(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 fl(e){let t=ml(e);if(!t)return[];let n=[];for(let o of t){if(typeof o!="object"||o===null||Array.isArray(o))continue;let i=o;typeof i.key!="string"||i.key.trim().length===0||n.push(i)}return n}function Ze(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:fl(t)}}function Qe(e){return`${JSON.stringify({fields:e.fields},null,2)}
|
|
16
|
-
`}function pr(e,t){let n=e.fields.find(a=>I(a.key)===t.key),o=n!==void 0,i=e.fields.filter(a=>I(a.key)!==t.key),r={...n,key:t.key,type:t.type,commands:[...t.commands]};return sr(r,"description",t.description),sr(r,"cli_flag",t.cliFlag),t.cliAliases.length>0?r.cli_aliases=[...t.cliAliases]:delete r.cli_aliases,cr(r,"required",t.required),cr(r,"required_on_create",t.requiredOnCreate),t.allowUnset===!1?r.allow_unset=!1:delete r.allow_unset,t.requiredTypes.length>0?r.required_types=[...t.requiredTypes]:delete r.required_types,i.push(r),i.sort((a,s)=>I(a.key).localeCompare(I(s.key))),{file:{fields:i},definition:r,replaced:o}}function ur(e,t){let n=I(t);if(n.length===0)throw new Error("Field key must not be empty.");let o=[],i=e.fields.filter(r=>I(r.key)===n?(o.push(r),!1):!0);return o.length===0?{file:{fields:i},removed:!1}:{file:{fields:i},removed:!0,definition:o[0]}}function sr(e,t,n){let o=e;n!==void 0&&n.length>0?o[t]=n:delete o[t]}function cr(e,t,n){let o=e;n?o[t]=!0:delete o[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]="e3a1e65b-55d7-5206-b3e7-cac3ac29745c")}catch{}})();var hl=new Set(Pt),Me=new Set(ii.map(e=>I(e.id)).filter(e=>e.length>0));function gl(e){let t=new Set;for(let n of e){let o=I(n);o.length>0&&t.add(o)}return[...t].sort((n,o)=>n.localeCompare(o))}function mr(e){let t=I(e.id);if(t.length===0)throw new Error("Status id must not be empty.");if(Me.has(t))throw new Error(`Cannot add-status the built-in status "${t}". Built-in statuses are reserved: ${[...Me].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(!hl.has(c))throw new Error(`Invalid status role "${s}". Allowed roles: ${Pt.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: ${Pt.join(", ")}.`)}let o=e.aliases===void 0?void 0:gl(e.aliases).filter(a=>a!==t),i=e.description?.trim(),r=typeof e.order=="number"&&Number.isFinite(e.order)?Math.trunc(e.order):void 0;return{id:t,roles:n,aliases:o,description:i&&i.length>0?i:void 0,order:r}}function yl(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 _l(e){let t=yl(e);if(!t)return[];let n=[];for(let o of t){if(typeof o!="object"||o===null||Array.isArray(o))continue;let i=o;typeof i.id!="string"||i.id.trim().length===0||n.push(i)}return n}function et(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:_l(t)}}function tt(e){return`${JSON.stringify({statuses:e.statuses},null,2)}
|
|
17
|
-
`}function fr(e,t,n){let o=e.statuses.slice(),i=o.findIndex(s=>I(s.id)===t.id),r=i>=0?o[i]:n,a={...r,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),i>=0?o[i]=a:o.push(a),{file:{statuses:o},definition:a,replaced:r!==void 0}}function hr(e,t){let n=I(t);if(n.length===0)throw new Error("Status id must not be empty.");if(Me.has(n))throw new Error(`Cannot remove built-in status "${n}". Built-in statuses are reserved: ${[...Me].join(", ")}.`);let o=e.statuses.slice(),i=o.findIndex(a=>I(a.id)===n);if(i<0)return{file:{statuses:o},removed:!1};let[r]=o.splice(i,1);return{file:{statuses:o},removed:!0,definition:r}}function qn(e,t){let n=[e.id,...e.aliases??[]];for(let o of n){let i=I(o);if(i.length===0)continue;let r=t.get(i);if(r!==void 0&&r!==e.id)throw new Error(`Status token "${i}" already belongs to status "${r}". 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]="9052af10-ff8c-55db-8a35-b45e1e23a901")}catch{}})();function _e(e,t){if(typeof e!="string"||e.trim().length===0)throw new TypeError(`Schema migration ${t} must be non-empty`);return e.trim()}function wr(e){let t=_e(e,"migrationId");if(!/^[a-zA-Z0-9._-]+$/.test(t))throw new TypeError("Schema migration migrationId must match [a-zA-Z0-9._-]+");return t}function vr(e,t){let n=Bn(e),o=_e(t,"migrationScope");return`auto-${_r("sha256").update(JSON.stringify({scope:o,request:n})).digest("hex").slice(0,20)}`}function Bn(e){let t=e.kind==="rename-type"?{kind:e.kind,from:_e(e.from,"source"),to:_e(e.to,"target")}:e.kind==="rename-field"?{kind:e.kind,from:I(_e(e.from,"source")),to:I(_e(e.to,"target")),...e.type===void 0?{}:{type:_e(e.type,"type")}}:{kind:e.kind,from:I(_e(e.from,"source")),to:I(_e(e.to,"target"))};if(t.from.toLowerCase()===t.to.toLowerCase())throw new TypeError("Schema migration source and target must differ");return t}function wl(e){return e.kind==="rename-type"?"types":e.kind==="rename-field"?"fields":"statuses"}function vl(e,t,n){let o=Y(t.schema),i=wl(n);return ie(e,o.files[i],Q[i])}function br(e,t){return ot.join(e,"transactions","schema",`${t}-plan.json`)}function Ht(e){return e.length===0?null:JSON.parse(e)}async function nt(e){let t=await U(e);return{exists:t!==null,raw:t??""}}async function kr(e,t){t.exists?await ae(e,t.raw):await Ge.rm(e,{force:!0})}function bl(e,t,n){let o=ce(e),i=o.definitions.findIndex(a=>a.name.trim().toLowerCase()===t.from.toLowerCase()),r=o.definitions.findIndex(a=>a.name.trim().toLowerCase()===t.to.toLowerCase());if(n==="stage"){if(r>=0)return me(o);if(i<0)throw new TypeError(`Unknown custom type "${t.from}".`);o.definitions.push({...o.definitions[i],name:t.to})}else i>=0&&o.definitions.splice(i,1);return me(o)}function kl(e,t,n){let o=Ze(e),i=o.fields.findIndex(a=>a.key===t.from),r=o.fields.findIndex(a=>a.key===t.to);if(n==="stage"){if(r>=0)return Qe(o);if(i<0)throw new TypeError(`Unknown custom field "${t.from}".`);let a=o.fields[i];o.fields.push({...a,key:t.to,metadata_key:t.to,front_matter_key:t.to,cli_flag:t.to.replaceAll("_","-")})}else i>=0&&o.fields.splice(i,1);return Qe(o)}function xl(e,t,n){let o=et(e),i=o.statuses.findIndex(a=>a.id===t.from),r=o.statuses.findIndex(a=>a.id===t.to);if(n==="stage"){if(r>=0)return tt(o);if(i<0)throw new TypeError(`Unknown custom status "${t.from}".`);o.statuses.push({...o.statuses[i],id:t.to})}else i>=0&&o.statuses.splice(i,1);return tt(o)}function Sl(e,t,n){return t.kind==="rename-type"?bl(e,t,n):t.kind==="rename-field"?kl(e,t,n):xl(e,t,n)}function Oe(e,t){return typeof e=="string"&&e.trim().toLowerCase()===t.from.toLowerCase()?t.to:e}function Hn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function it(e){return Array.isArray(e)?e.map(t=>Hn(t)).filter(t=>t!==void 0):[]}function El(e,t){for(let n of it(e.fields))Array.isArray(n.required_types)&&(n.required_types=n.required_types.map(o=>Oe(o,t)));for(let n of it(e.type_workflows))n.type=Oe(n.type,t)}function $l(e,t){for(let o of it(e.definitions))o.default_status=Oe(o.default_status,t);let n=Hn(e.workflow);if(n)for(let[o,i]of Object.entries(n))n[o]=Oe(i,t);for(let o of it(e.type_workflows))Array.isArray(o.allowed_transitions)&&(o.allowed_transitions=o.allowed_transitions.map(i=>Array.isArray(i)?i.map(r=>Oe(r,t)):i))}function Il(e,t){for(let n of it(e.definitions)){for(let o of["required_create_fields","required_create_repeatables"])Array.isArray(n[o])&&(n[o]=n[o].map(i=>Oe(i,t)));for(let o of["options","command_option_policies"])for(let i of it(n[o])){let r=o==="options"?"key":"option";i[r]=Oe(i[r],t)}}}function Al(e,t){let n=Hn(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 o=t.kind==="rename-type"?"type":"status";n[o]=Oe(n[o],t)}function Wn(e,t){let n=JSON.parse(e);if(typeof n!="object"||n===null||Array.isArray(n))return e;let o=n;return t.kind==="rename-type"?El(o,t):t.kind==="rename-field"?Il(o,t):$l(o,t),Al(o,t),`${JSON.stringify(o,null,2)}
|
|
18
|
-
`}function xr(e,t){if(t.kind==="rename-type"){let o=ce(e).definitions;return{source:o.some(i=>i.name.trim().toLowerCase()===t.from.toLowerCase()),target:o.some(i=>i.name.trim().toLowerCase()===t.to.toLowerCase())}}if(t.kind==="rename-field"){let o=Ze(e).fields;return{source:o.some(i=>i.key===t.from),target:o.some(i=>i.key===t.to)}}let n=et(e).statuses;return{source:n.some(o=>o.id===t.from),target:n.some(o=>o.id===t.to)}}function Tl(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 Ol(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 Sr(e,t){let n=Bn(t.request),o=t.migrationId===void 0?vr(n,t.migrationScope??"plan"):wr(t.migrationId),i=e.map(c=>Ol(c,n)).filter(c=>c!==null).sort((c,l)=>c.id.localeCompare(l.id)),r=_r("sha256").update(JSON.stringify({migrationId:o,request:n,items:i})).digest("hex"),a=new Set([...t.completedItemIds??[]].map(c=>c.trim()).filter(c=>c.length>0)),s=i.filter(c=>!a.has(c.id));return Object.freeze({migration_id:o,request:n,fingerprint:r,affected_item_count:i.length,pending_item_count:s.length,skipped_completed_count:i.length-s.length,items:Object.freeze(s)})}async function Cl(e){let t=z(e.settings,B()),n=[...new Set(Object.values(t.type_to_folder))],o=await mi(e.pmRoot,n),i=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]}},r=o?await ui({pmRoot:e.pmRoot,expectedSourceCursor:o.source_cursor,query:i}):null;return r?{items:r.items,selectionSource:"derived_index",typeToFolder:t.type_to_folder}:{items:await De(e.pmRoot,e.settings.item_format,t.type_to_folder,[],e.settings.schema),selectionSource:"scan",typeToFolder:t.type_to_folder}}async function Pl(e,t){let n=await U(br(e,t));if(n===null)return null;try{let o=JSON.parse(n);if(o.schema_version!==1||o.plan.migration_id!==t||!Array.isArray(o.plan.items))throw new TypeError("invalid plan envelope");return o.plan}catch(o){throw new f(`Stored schema migration plan "${t}" is invalid: ${Po(o)}`,h.GENERIC_FAILURE)}}async function Rl(e,t){let n=br(e,t.migration_id);await Ge.mkdir(ot.dirname(n),{recursive:!0});let o={schema_version:1,plan:t,created_at:new Date().toISOString()};await ae(n,`${JSON.stringify(o,null,2)}
|
|
19
|
-
`)}function Nl(e,t){return JSON.stringify(e)===JSON.stringify(t)}async function Dl(e){let t=await Lt(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!t)throw new f(`Schema migration item "${e.id}" no longer exists.`,h.NOT_FOUND);return(await Ft(t,{schema:e.settings.schema})).document.metadata}function gr(e,t,n){let o=n==="forward"?t.from:t.to,i=n==="forward"?t.to:t.from;if(t.kind==="rename-type"){if(e.metadata.type.toLowerCase()===i.toLowerCase())return[];if(e.metadata.type.toLowerCase()!==o.toLowerCase())throw new TypeError(`Schema migration expected type "${o}" on item "${e.metadata.id}".`);return e.metadata.type=i,["type"]}if(t.kind==="remap-status"){if(e.metadata.status.toLowerCase()===i.toLowerCase())return[];if(e.metadata.status.toLowerCase()!==o.toLowerCase())throw new TypeError(`Schema migration expected status "${o}" on item "${e.metadata.id}".`);return e.metadata.status=i,["status"]}let r=e.metadata;if(Object.prototype.hasOwnProperty.call(r,i)&&!Object.prototype.hasOwnProperty.call(r,o))return[];if(!Object.prototype.hasOwnProperty.call(r,o)||Object.prototype.hasOwnProperty.call(r,i))throw new TypeError(`Schema migration field state changed concurrently on item "${e.metadata.id}".`);return r[i]=r[o],delete r[o],[o,i]}function yr(e){return{id:e.id,inspect:async()=>{let t=await nt(e.filePath),n=xr(t.raw,e.request),o=e.phase==="stage"?n.source&&n.target:!n.source&&n.target;return{state:o?"applied":"pending",...o?{result:{phase:e.phase}}:{}}},prepareCompensation:async()=>{let t=await nt(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await nt(e.filePath);return await ae(e.filePath,Sl(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 kr(e.filePath,{exists:t.exists,raw:t.raw})}}}function jl(e){return{id:e.stepId,inspect:async()=>{let t=await nt(e.filePath);return{state:Wn(t.raw,e.request)===t.raw?"applied":"pending"}},prepareCompensation:async()=>{let t=await nt(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await nt(e.filePath);return await ae(e.filePath,Wn(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 kr(e.filePath,{exists:t.exists,raw:t.raw})}}}function Ll(e){return{id:`item-${e.id}`,inspect:async()=>{let t=await A(e.pmRoot),n=z(t,B()).type_to_folder,o=await Dl({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id}),i=Tl(o,e.request).length===0;return{state:i?"applied":"pending",...i?{result:{item_id:e.id}}:{}}},apply:async()=>{let t=await A(e.pmRoot),n=z(t,B()).type_to_folder,o=await An({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(i){return{changedFields:gr(i,e.request,"forward")}}});return{item_id:e.id,changed_fields:o.changedFields}},compensate:async()=>{let t=await A(e.pmRoot),n=z(t,B()).type_to_folder;await An({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(o){return{changedFields:gr(o,e.request,"reverse")}}})}}}async function Fl(e){let t=await Pl(e.pmRoot,e.migrationId);if(t){if(!Nl(t.request,e.request))throw new f(`Schema migration id "${e.migrationId}" already belongs to a different request.`,h.CONFLICT);return{plan:t,stored:!0}}let n=await Cl({pmRoot:e.pmRoot,settings:e.settings,request:e.request});return{plan:{...Sr(n.items,{migrationId:e.migrationId,request:e.request}),selection_source:n.selectionSource},stored:!1}}async function Ml(e){let t=xr(await U(e.schemaPath)??"",e.request);if(!t.source)throw new f(`Schema migration source "${e.request.from}" is not a custom definition.`,h.NOT_FOUND);if(t.target)throw new f(`Schema migration target "${e.request.to}" already exists.`,h.CONFLICT);await Rl(e.pmRoot,e.plan)}async function Gl(e){let t=Y(e.settings.schema),n=[...new Set([["types",Q.types],["fields",Q.fields],["workflows",Q.workflows]].map(([i,r])=>ie(e.pmRoot,t.files[i],r)).filter(i=>i!==e.schemaPath))];try{let i=ot.join(e.pmRoot,"templates"),r=await Ge.readdir(i,{withFileTypes:!0});n.push(...r.filter(a=>a.isFile()&&a.name.toLowerCase().endsWith(".json")).map(a=>ot.join(i,a.name)))}catch(i){if(typeof i!="object"||i===null||!("code"in i)||!pe(i))throw i}n.sort((i,r)=>i.localeCompare(r));let o=[];for(let i of n){let r=await U(i);r!==null&&Wn(r,e.request)!==r&&o.push({filePath:i,beforeRaw:r})}return{paths:n,snapshots:o}}async function Ul(e){for(let t of e.snapshots){let n=await Ge.readFile(t.filePath,"utf8"),o=ot.relative(e.pmRoot,t.filePath).replaceAll("\\","/");await In({pmRoot:e.pmRoot,author:e.author,documentPath:o,before:Ht(t.beforeRaw),after:Ht(n),op:"schema_migration_reference",idempotencyKey:`${e.plan.migration_id}:${e.plan.fingerprint}:${o}`,message:`${e.request.kind}: ${e.request.from} -> ${e.request.to}`,lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}}async function zl(e,t,n){let o=Bn(e),i=N(process.cwd(),n.path);await Se(i);let r=t.migrationId===void 0?vr(o,await Ge.realpath(i)):wr(t.migrationId),a=await A(i),s=H(t.author,a.author_default),c=await Fl({pmRoot:i,settings:a,migrationId:r,request:o}),l=c.plan;if(t.dryRun===!0)return{...l,action:o.kind,applied:!1,recovered:!1,migrated_item_count:0};let d=vl(i,a,o),p=await Ge.readFile(d,"utf8");c.stored||await Ml({pmRoot:i,schemaPath:d,request:o,plan:l});let u=await Gl({pmRoot:i,schemaPath:d,settings:a,request:o}),g=[yr({id:"stage-schema",filePath:d,request:o,phase:"stage"}),...u.paths.map((_,v)=>jl({filePath:_,request:o,stepId:`reference-${String(v+1).padStart(4,"0")}`})),...l.items.map(_=>Ll({pmRoot:i,id:_.id,request:o,author:s,force:t.force===!0})),yr({id:"retire-source",filePath:d,request:o,phase:"retire"})],y=await Ti({pmRoot:i,transactionId:`schema-${r}`,author:s,steps:g,lockTtlSeconds:Math.max(a.locks.ttl_seconds,300),lockWaitMs:a.locks.wait_ms}),w=await Ge.readFile(d,"utf8"),{historyPath:m}=await In({pmRoot:i,author:s,documentPath:ot.relative(i,d).replaceAll("\\","/"),before:Ht(p),after:Ht(w),op:"schema_migration",idempotencyKey:`${l.migration_id}:${l.fingerprint}`,message:`${o.kind}: ${o.from} -> ${o.to}; affected=${l.affected_item_count}`,lockTtlSeconds:a.locks.ttl_seconds,lockWaitMs:a.locks.wait_ms});return await Ul({pmRoot:i,author:s,settings:a,request:o,plan:l,snapshots:u.snapshots}),{...l,action:o.kind,applied:!0,recovered:y.recovered,migrated_item_count:l.affected_item_count,workspace_history_path:m}}function Jl(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(`
|
|
20
|
-
`)}import Ir from"node:fs/promises";import Ue 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]="8269d712-f438-5f18-8137-ed9a0358e23b")}catch{}})();var Kt=["extensions","docs","examples","assets","prompts"],ql=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 Wl(e){return Kt.includes(e)}function Bl(e,t){if(t==null)return[];let n=Array.isArray(t)?t:[t],o=[];for(let i of n){if(typeof i!="string"||i.trim().length===0)throw new f(`Package manifest field pm.${e} must contain string paths.`,h.USAGE);o.push(i.trim())}return[...new Set(o)].sort((i,r)=>i.localeCompare(r))}function Hl(e){if(e==null)return{};if(typeof e!="object"||Array.isArray(e))throw new f("Package manifest field pm must be an object.",h.USAGE);let t={},n=e;for(let[o,i]of Object.entries(n)){if(!Wl(o))continue;let r=Bl(o,i);r.length>0&&(t[o]=r)}return t}function fe(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,o)=>n.localeCompare(o)):void 0}function Er(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 Kl(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={docs:fe(t,"docs"),npm:fe(t,"npm"),repository:fe(t,"repository"),report:fe(t,"report")};return Object.values(n).some(o=>typeof o=="string")?n:void 0}function Vl(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={image:fe(t,"image"),video:fe(t,"video")};return Object.values(n).some(o=>typeof o=="string")?n:void 0}function Yl(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={display_name:fe(t,"display_name")??fe(t,"displayName"),category:fe(t,"category"),summary:fe(t,"summary"),links:Kl(t.links),media:Vl(t.media),tags:Kn(t.tags)};return Object.values(n).some(o=>o!==void 0)?n:void 0}async function ft(e){let t=Ue.join(e,"package.json");if(!await x(t))return{source:"convention",resources:{}};let n;try{n=JSON.parse(await Ir.readFile(t,"utf8"))}catch(s){throw new f(`Failed to parse package manifest at "${t}": ${String(s)}`,h.USAGE)}if(typeof n!="object"||n===null||Array.isArray(n))throw new f(`Package manifest at "${t}" must be a JSON object.`,h.USAGE);let o=n,i=o.pm,r=i!=null,a=typeof i=="object"&&i!==null&&!Array.isArray(i)?i:{};return{source:r?"pm":"convention",package_json_path:t,package_name:typeof o.name=="string"?o.name:void 0,package_version:typeof o.version=="string"?o.version:void 0,package_private:o.private===!0,package_description:typeof o.description=="string"?o.description:void 0,package_keywords:Kn(o.keywords),package_homepage:typeof o.homepage=="string"?o.homepage:void 0,package_repository_url:Er(o.repository),package_bugs_url:Er(o.bugs),aliases:Kn(a.aliases),resources:Hl(i),catalog:Yl(a.catalog)}}async function $r(e){if(!await x(e))return[];let t=await Ir.readdir(e,{withFileTypes:!0}),n=[];for(let o of t){if(!o.isDirectory())continue;let i=Ue.join(e,o.name);await x(Ue.join(i,"manifest.json"))&&n.push(i)}return n.sort((o,i)=>o.localeCompare(i))}async function Vt(e){if(await x(Ue.join(e,"manifest.json")))return[e];let n=(await ft(e)).resources.extensions??[],o=new Set;for(let i of n){if(i.includes("*")||i.startsWith("!"))throw new f(`Package extension entry "${i}" uses a glob/exclusion pattern. pm package installs currently require concrete extension paths or directories.`,h.USAGE);let r=Ue.resolve(e,i);if(!V(e,r))throw new f(`Package extension entry "${i}" resolves outside package root.`,h.USAGE);if(await x(Ue.join(r,"manifest.json"))){o.add(r);continue}for(let a of await $r(r))o.add(a)}if(n.length===0)for(let i of ql.extensions)for(let r of await $r(Ue.join(e,i)))o.add(r);return[...o].sort((i,r)=>i.localeCompare(r))}import{execFile as yd}from"node:child_process";import P from"node:fs/promises";import oo from"node:os";import $ from"node:path";import{fileURLToPath as _d}from"node:url";import{promisify as wd}from"node:util";import vd from"npm-package-arg";import{extract as bd,list as kd}from"tar";import sd from"node:fs/promises";import de from"node:path";import Ar from"node:fs/promises";import Vn 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]="decec6f3-3795-5353-bf48-75aa61dd79d4")}catch{}})();function te(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 Yt(e){let t=e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-"),n=0;for(;t[n]==="-";)n+=1;let o=t.length;for(;o>n&&t[o-1]==="-";)o-=1;let i=t.slice(n,o);if(i.length===0)throw new f("Extension manifest name must resolve to a non-empty directory name.",h.USAGE);if(i==="."||i==="..")throw new f('Extension manifest name must not resolve to "." or "..".',h.USAGE);return i}function Yn(e){return Bo(e)}async function Xl(e){try{let t=JSON.parse(await Ar.readFile(Vn.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(o=>typeof t.scripts?.[o]=="string")}}catch{return{has_build_script:!1}}}async function Zl(e,t,n){if(n.source_kind!=="github"||typeof n.source_root!="string")return new f(`Extension entry file is missing at "${t}".`,h.USAGE);let o=await Xl(n.source_root),i=o.package_name?`pm install npm:${o.package_name}`:void 0,r=n.source_input??n.source_root;return new f(`Extension entry "${e.entry}" is absent from GitHub source "${r}". pm install copies GitHub repositories without running package scripts${o.has_build_script?", and this package declares a build or publish script":""}. ${i?`Try "${i}" 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."}`,h.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:i?[i,`pm install ${n.source_root}`]:[`pm install ${n.source_root}`],nextSteps:i?[`Retry with ${i}.`,"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 ${r}`,normalized_args:["install",r],...i?{next_best_command:i}:{}}})}async function rt(e,t={}){let n=Vn.join(e,"manifest.json");if(!await x(n))throw new f(`Extension manifest is missing at "${n}".`,h.USAGE);let o;try{o=JSON.parse(await Ar.readFile(n,"utf8"))}catch(a){throw new f(`Failed to parse extension manifest at "${n}": ${Ql(a)}`,h.USAGE)}let i=Yn(o);if(!i)throw new f(`Extension manifest at "${n}" is invalid.`,h.USAGE);let r=Vn.resolve(e,i.entry);if(!V(e,r))throw new f(`Extension entry "${i.entry}" resolves outside extension directory "${e}".`,h.USAGE);if(!await x(r))throw await Zl(i,r,t);if(!await Ko(e,r))throw new f(`Extension entry "${i.entry}" resolves outside extension directory after symlink resolution.`,h.USAGE);return{directory:e,manifest_path:n,entry_path:r,manifest:i}}function Ql(e){return e instanceof Error?e.message:String(e)}import Xn from"node:fs/promises";import ed 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]="33b7f318-cc64-55d6-8b57-19a618efe6c0")}catch{}})();var td=".managed-extensions.json",Xt=1;function ht(e){return ed.join(e,td)}function nd(){return{version:Xt,updated_at:T(),entries:[]}}function gt(e){return[...e].sort((t,n)=>{let o=t.scope.localeCompare(n.scope);if(o!==0)return o;let i=t.name.localeCompare(n.name);return i!==0?i:t.directory.localeCompare(n.directory)})}function Tr(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 ne(e){return typeof e=="string"?e:void 0}function od(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 id(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:ne(t.name),package:ne(t.package),version:ne(t.version),repository:ne(t.repository),owner:ne(t.owner),repo:ne(t.repo),ref:ne(t.ref),subpath:ne(t.subpath),commit:ne(t.commit)}}function rd(e){if(typeof e!="object"||e===null)return null;let t=e;if(!od(t))return null;let n=id(t.source);if(!n)return null;let o=Uo(t.contributions);return o===null?null:{name:t.name.trim(),directory:t.directory.trim(),scope:t.scope,manifest_version:t.manifest_version,manifest_entry:t.manifest_entry,capabilities:te(t.capabilities),contributions:o,installed_at:t.installed_at,updated_at:t.updated_at,source:n,last_update_check_at:ne(t.last_update_check_at),last_update_remote_commit:ne(t.last_update_remote_commit),update_available:typeof t.update_available=="boolean"||t.update_available===null?t.update_available:void 0,update_error:ne(t.update_error)}}function ad(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.version!==Xt||!Array.isArray(t.entries))return null;let n=[];for(let o of t.entries){let i=rd(o);i&&n.push(i)}return{version:Xt,updated_at:ne(t.updated_at)??T(),entries:gt(n)}}async function we(e){let t=ht(e),n=nd();try{let o=await Xn.readFile(t,"utf8"),i=JSON.parse(o),r=ad(i);if(!r)throw new f(`Managed extension state file "${t}" has an invalid schema. Repair or remove it before mutating extension state.`,h.GENERIC_FAILURE);return{path:t,state:r,warnings:[]}}catch(o){if(o instanceof f)throw o;if(typeof o=="object"&&o!==null&&"code"in o&&pe(o))return{path:t,state:n,warnings:[]};throw new f(`Managed extension state file "${t}" could not be read. Repair or remove it before mutating extension state.`,h.GENERIC_FAILURE)}}async function ze(e,t){let n=ht(e),o={version:Xt,updated_at:T(),entries:gt(t.entries)};await Xn.mkdir(e,{recursive:!0}),await Xn.writeFile(n,`${JSON.stringify(o,null,2)}
|
|
21
|
-
`,"utf8")}function yt(e,t){let n=e.entries.filter(o=>b(o.name)!==b(t.name)&&b(o.directory)!==b(t.directory));return n.push(t),{...e,updated_at:T(),entries:gt(n)}}async function Or(e,t,n,o){let i=t.entries.find(a=>b(a.name)===b(n));if(!i)return t;let r=yt(t,{...i,contributions:o});return await ze(e,r),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]="96c5708d-1f4d-5f94-9945-7f8baa337106")}catch{}})();var cd="PM_CLI_PACKAGE_ROOT",Cr={beads:{package_directory:"pm-beads",legacy_extension_directory:"beads"},todos:{package_directory:"pm-todos",legacy_extension_directory:"todos"}},ld=new Set(["*","all"]);function Zn(){let e=[],t=process.env[cd];return typeof t=="string"&&t.trim().length>0&&e.push(de.resolve(t.trim())),e.push(ue(import.meta.url,["../../.."])),[...new Set(e)]}async function _t(e){let t=e.trim().toLowerCase(),n=await Rr(t);if(n)return n;let o=Cr[t];if(!o)return null;for(let i of Zn()){let r=de.join(i,".agents","pm","extensions",o.legacy_extension_directory);if(await x(de.join(r,"manifest.json")))return r}return null}function Pr(e){return ld.has(e.trim().toLowerCase())}function dd(e){return e.replace(/^pm-/i,"").trim().toLowerCase()}async function pd(e,t){let n=await sd.readdir(e,{withFileTypes:!0});for(let o of n){if(!o.isDirectory()||!o.name.startsWith("pm-"))continue;let i=de.join(e,o.name);if(!await x(de.join(i,"package.json")))continue;let r=await ft(i),a=r.aliases&&r.aliases.length>0?r.aliases:[dd(o.name)];for(let s of a){let c=s.trim().toLowerCase();c.length===0||t.has(c)||t.set(c,{alias:c,package_directory:o.name,package_root:i,package_name:r.package_name??null})}}}async function Qn(){let e=new Map;for(let t of Zn()){let n=de.join(t,"packages");await x(n)&&await pd(n,e)}for(let[t,n]of Object.entries(Cr))if(!e.has(t))for(let o of Zn()){let i=de.join(o,"packages",n.package_directory);if(await x(de.join(i,"package.json"))){e.set(t,{alias:t,package_directory:n.package_directory,package_root:i,package_name:null});break}}return[...e.values()].sort((t,n)=>t.alias.localeCompare(n.alias))}async function Zt(){return(await Qn()).map(e=>e.alias)}async function Rr(e){let t=e.trim().toLowerCase();return(await Qn()).find(o=>o.alias===t||o.package_directory.toLowerCase()===t||o.package_name?.toLowerCase()===t)?.package_root??null}async function Nr(e){let t=await Rr(e);return t?(await ft(t)).package_name??null:null}async function Dr(e){let t=await _t(e);if(!t)return null;try{let n=await Vt(t);return n.length!==1?null:(await rt(n[0])).manifest.name}catch{return null}}function ud(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 md(e,t,n,o,i,r){let a=o==="global"?"--global":"--project",s=Object.fromEntries(Kt.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=>i.has(c))||r.has(de.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:ud(e),media:e.catalog?.media}}}async function jr(e,t,n={}){let o=Rt(N(process.cwd(),t.path),process.cwd()),i=e==="global"?o.global:o.project,r=await we(i),a=new Set(r.state.entries.filter(u=>u.scope===e).filter(u=>u.source.kind!=="builtin").map(u=>de.resolve(u.source.location))),s=new Set(r.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=[],l=new Map;for(let u of await Qn()){let g=de.resolve(u.package_root),y=l.get(g)??[];y.push(u),l.set(g,y)}for(let u of l.values()){let g=u[0],y=u.map(m=>m.alias).sort((m,_)=>m.localeCompare(_)),w=await ft(g.package_root);c.push(md(w,g,y,e,s,a))}let d=hd(n.fields),p=d?c.map(u=>gd(u,d)):c;return{total:p.length,scope:e,installable_resource_kinds:["extensions"],metadata_only_resource_kinds:Kt.filter(u=>u!=="extensions"),packages:p}}var fd=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 hd(e){if(e===void 0)return;let t=vi(e);if(t.length===0)throw new f("Package catalog --fields requires a comma-separated list of field names",h.USAGE);let n=t.filter(o=>!fd.has(o));if(n.length>0)throw new f(`Unknown package catalog --fields value(s): ${n.join(", ")}`,h.USAGE,{examples:["pm package list --project --fields alias,installed,install_command","pm package catalog --project --fields alias,package_name,category"]});return t}function gd(e,t){let n={};for(let o of t)o==="category"?n[o]=e.catalog?.category??null:o==="display_name"?n[o]=e.catalog?.display_name??null:n[o]=e[o]??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]="68a37ea1-3571-59ab-b72c-0195efa84e3c")}catch{}})();var Fr=wd(yd),en="@unbrained/pm-cli",xd={maxArchiveBytes:64*1024*1024,maxEntries:4096,maxExpandedBytes:256*1024*1024,maxEntryBytes:64*1024*1024},eo;async function Mr(e,t=process.cwd()){let n=e.trim();if(!/^(@[^/\\\s]+\/[^/\\\s]+|[^@/\\\s][^/\\\s]*)$/u.test(n))return null;let o=$.resolve(t);for(;;){let i=$.join(o,"node_modules",...n.split("/")),r=$.join(i,"package.json");if(await x(r))try{let s=JSON.parse(await P.readFile(r,"utf8"));if(s.name===n)return{package:n,...typeof s.version=="string"?{version:s.version}:{},directory:i}}catch{return null}let a=$.dirname(o);if(a===o)return null;o=a}}function to(e,t,n){let o=e.split("/").map(l=>l.trim()).filter(l=>l.length>0);if(o.length<2)return null;let i=o[0],r=o[1].replace(/\.git$/i,"");if(i.length===0||r.length===0)return null;let a=o.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:i,repo:r,repository:`https://github.com/${i}/${r}.git`,ref:s,subpath:c&&c.length>0?c:void 0}}function Sd(e,t,n){let o=e.slice(4).trim();if(o.length===0)throw new f('npm package source must include a package spec after "npm:".',h.USAGE);if(t)throw new f('Options "--gh/--github" cannot be combined with npm: package sources.',h.USAGE);if(n)throw new f('Option "--ref" cannot be combined with npm: package sources.',h.USAGE);return{kind:"npm",input:e,spec:o}}function tn(e,t={}){let n=e.trim();if(n.length===0)throw new f("Extension source is required for --install.",h.USAGE);let o=typeof t.ref=="string"&&t.ref.trim().length>0?t.ref.trim():void 0;if(n.startsWith("npm:"))return Sd(n,t.forceGithub===!0,o);let i=(()=>{try{let a=new URL(n);if(a.hostname!=="github.com")return null;let s=a.pathname.replace(/^\/+/,"");return to(s,n,o)}catch{return null}})();if(i)return i;let r=n.startsWith("github.com/")?n.slice(11):null;if(r){let a=to(r,n,o);if(!a)throw new f(`Invalid GitHub source "${n}".`,h.USAGE);return a}if(t.forceGithub){let a=to(n,n,o);if(!a)throw new f(`Invalid GitHub shorthand "${n}".`,h.USAGE);return a}if(/^https?:\/\//i.test(n))throw new f(`Unsupported extension source URL "${n}". Supported remote source host: github.com.`,h.USAGE);return{kind:"local",input:n,absolute_path:$.resolve(process.cwd(),n)}}async function Qt(e,t=Fr,n){try{return((await t("git",e,{encoding:"utf8",timeout:n})).stdout??"").trim()}catch(o){let i=typeof o=="object"&&o!==null&&"stderr"in o?String(o.stderr):"",r=i.trim().length>0?i.trim():o instanceof Error?o.message:String(o);throw new f(`Git command failed: git ${e.join(" ")}
|
|
22
|
-
${r}`,h.GENERIC_FAILURE)}}function Ed(e=process.platform){return e==="win32"?"npm.cmd":"npm"}function $d(e=process.platform){return e==="win32"}async function Gr(e,t,n=Fr,o=process.platform,i=process.env){let r=Ed(o),a=Object.fromEntries(Object.entries(i).filter(([s])=>s.toLowerCase()!=="npm_config_allow_scripts"));a.NPM_CONFIG_ALLOW_SCRIPTS="";try{return((await n(r,e,{cwd:t,encoding:"utf8",env:a,shell:$d(o)})).stdout??"").trim()}catch(s){let c=typeof s=="object"&&s!==null&&"stderr"in s?String(s.stderr):"",l=c.trim().length>0?c.trim():s instanceof Error?s.message:String(s);throw new f(`npm command failed: ${r} ${e.join(" ")}
|
|
23
|
-
${l}`,h.GENERIC_FAILURE)}}function Ur(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 zr(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 Id(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 Ad(e){let n=(e instanceof Error?e.message:String(e)).toLowerCase();return Id(e)||n.includes("not found")}function Td(e){let t=e.trim().toLowerCase();return t.startsWith("@unbrained/pm-")||t.startsWith("pm-")}function Od(e){let t=Ur(e),n=Td(t),o=t.replace(/^.*\//,""),i=n?`github.com/unbraind/${o}`:void 0,r=i?`pm install --project ${i}`: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:r?[r,"pm package catalog --project --json"]:[`npm view ${t}`,"pm package catalog --project --json"],nextSteps:r?[`Try ${r} 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}`],...i&&r?{fallback_candidates:[{source:i,command:r,reason:"canonical first-party GitHub repository fallback for unpublished pm packages"}],next_best_command:r}:{}}}}}function Cd(e,t){if(!Ad(t))return null;let n=Od(e);return new f(n.message,h.NOT_FOUND,n.context)}async function Jr(e){if($.isAbsolute(e)||e.startsWith(".")||e.startsWith("..")){let t=$.resolve(process.cwd(),e);return await x(t)?t:null}try{let t=new URL(e);if(t.protocol==="file:"){let n=_d(t);return await x(n)?n:null}}catch{}if(!/^[a-z][a-z0-9+.-]*:/i.test(e)){let t=$.resolve(process.cwd(),e);if(await x(t))return t}return null}async function Pd(e){let t=await Jr(e);if(t)return t;let n=Rd(e);return n!==e?n:(/^[a-z][a-z0-9+.-]*:/i.test(e),e)}function Rd(e,t=process.cwd()){let n="@file:",o=e.lastIndexOf(n);if(!zr(e))return e;let i=e.slice(0,o),r=e.slice(o+n.length);if(r.startsWith("//")&&!r.startsWith("///"))return e;if(!r.startsWith("/"))return`${i}@${$.resolve(t,r)}`;let a;try{a=decodeURIComponent(new URL(`file:${r}`).pathname)}catch{return e}let s=/^\/[A-Za-z]:/.test(a)?a.slice(1):a;return`${i}@${s}`}function Lr(e,t){let n=$.resolve(e,t),o=$.relative(e,n);if(o.length===0||o===".."||o.startsWith(`..${$.sep}`)||$.isAbsolute(o))throw new f("npm pack reported a package archive outside its isolated destination.",h.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 Nd(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 Dd(e){return(Array.isArray(e)?e.map(n=>({value:n})):typeof e=="object"&&e!==null?Object.entries(e).map(([n,o])=>({key:n,value:o})):[]).flatMap(({key:n,value:o})=>{let i=Nd(o,n);return i?[i]:[]})}function jd(e,t){let n=t?.trim().toLowerCase(),o=n?e.filter(a=>{let s=a.name?.trim().toLowerCase();return s!==void 0?s===n:a.key?.trim().toLowerCase()===n}):[];if(o.length===1)return o[0];if(e.length!==1)return;let i=e[0],r=i.name??i.key;return n&&r!==void 0&&r.trim().toLowerCase()!==n?void 0:i}function Ld(e,t,n){let o;try{o=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 f("npm pack did not report a tarball filename.",h.GENERIC_FAILURE);return{tarball:Lr(t,a)}}let i=Dd(o),r=jd(i,n);if(!r)throw new f("npm pack --json returned an unsupported or ambiguous package receipt.",h.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 ${i.length} usable package receipt(s), but pm could not select ${n??"one package"} deterministically.`});return{tarball:Lr(t,r.filename),package:r.name??r.key,version:r.version}}async function Fd(e){return Md(e,Gr)}async function Md(e,t){let n=await Jr(e.spec);if(n){if((await P.stat(n)).isFile()&&qr(n))return no(n);let a=$.join(n,"package.json"),s=await x(a)?JSON.parse(await P.readFile(a,"utf8")):{};return{directory:await nn(n,e.input),package:typeof s.name=="string"?s.name:void 0,version:typeof s.version=="string"?s.version:void 0,cleanup:async()=>{}}}let o=await P.mkdtemp($.join(oo.tmpdir(),"pm-npm-package-source-")),i=$.join(o,"pack");await P.mkdir(i,{recursive:!0});try{let r=await Pd(e.spec),a=await t(["pack",r,"--json","--pack-destination",i]),s=Ld(a,i,zr(e.spec)?void 0:Ur(e.spec));if(!await x(s.tarball))throw new f("npm pack did not create its reported package archive.",h.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 no(s.tarball);return{directory:c.directory,package:s.package??c.package,version:s.version??c.version,cleanup:async()=>{try{await c.cleanup()}finally{await P.rm(o,{recursive:!0,force:!0})}}}}catch(r){await P.rm(o,{recursive:!0,force:!0});let a=Cd(e.spec,r);throw a||r}}function qr(e){let t=e.toLowerCase();return t.endsWith(".tgz")||t.endsWith(".tar.gz")}function ve(e){throw new f(e,h.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 Gd(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 o=e.path,i=o.split("/");(o.includes("\\")||o.startsWith("/")||/^[A-Za-z]:/u.test(o)||i.some(r=>r===".."))&&ve(`Local package archive contains an escaping path: "${o}".`),i[0]!=="package"&&ve(`Local package archive entry "${o}" is outside the required package/ root.`),(e.type==="SymbolicLink"||e.type==="Link")&&ve(`Local package archive link "${o}" is not supported.`),e.type!=="File"&&e.type!=="OldFile"&&e.type!=="Directory"&&ve(`Local package archive entry "${o}" uses unsupported type "${e.type}".`),e.size>t.maxEntryBytes&&ve(`Local package archive entry "${o}" 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.`),o==="package/package.json"&&(n.packageJsonEntries+=1)}async function no(e,t=xd){(await P.stat(e)).size>t.maxArchiveBytes&&ve(`Local package archive exceeds the ${t.maxArchiveBytes} archive byte limit.`);let o=await P.mkdtemp($.join(oo.tmpdir(),"pm-local-package-archive-")),i=$.join(o,"extract");await P.mkdir(i,{recursive:!0});let r={entries:0,expandedBytes:0,packageJsonEntries:0},a;try{if(await kd({file:e,strict:!0,maxDecompressionRatio:100,onReadEntry:d=>{if(a===void 0)try{Gd(d,t,r)}catch(p){a=p}}}),a!==void 0)throw a;r.packageJsonEntries!==1&&ve(`Local package archive must contain exactly one package/package.json entry; found ${r.packageJsonEntries}.`),await bd({file:e,cwd:i,strict:!0,preservePaths:!1,preserveOwner:!1,noMtime:!0,unlink:!0,maxDepth:64,maxDecompressionRatio:100});let s=$.join(i,"package"),c=$.join(s,"package.json"),l=JSON.parse(await P.readFile(c,"utf8"));return await Ud(s),{directory:await nn(s,e),package:typeof l.name=="string"?l.name:void 0,version:typeof l.version=="string"?l.version:void 0,cleanup:async()=>{await P.rm(o,{recursive:!0,force:!0})}}}catch(s){throw await P.rm(o,{recursive:!0,force:!0}),s}}async function Ud(e,t=Gr){let n=$.join(e,"package.json");if(!await x(n))return;let o;try{o=JSON.parse(await P.readFile(n,"utf8"))}catch{return}if(typeof o!="object"||o===null)return;let i=o,r=Hd(i),a=zd(i);if(r.length===0&&!a)return;let s={...o};delete s.devDependencies;let c={...s};Jd(c),await P.writeFile(n,`${JSON.stringify(c,null,2)}
|
|
24
|
-
`,"utf8");try{await Promise.all([P.rm($.join(e,"package-lock.json"),{force:!0}),P.rm($.join(e,"npm-shrinkwrap.json"),{force:!0})]),r.length>0&&await t(["install","--ignore-scripts","--no-audit","--fund=false","--package-lock=false","--no-save","--omit=peer","--"],e),a&&await qd(e)}finally{await P.writeFile(n,`${JSON.stringify(s,null,2)}
|
|
25
|
-
`,"utf8")}}function zd(e){for(let t of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(typeof t=="object"&&t!==null&&en in t)return!0;return!1}function Jd(e){for(let t of["dependencies","optionalDependencies","peerDependencies"]){let n=e[t];if(typeof n!="object"||n===null)continue;let o={...n};delete o[en],Object.keys(o).length===0?delete e[t]:e[t]=o}}async function qd(e){let t=ue(import.meta.url,["../../.."]),[n,o]=en.split("/"),i=$.join(e,"node_modules",n),r=$.join(i,o);await P.mkdir(i,{recursive:!0}),await P.rm(r,{recursive:!0,force:!0}),await P.symlink(t,r,Wd(process.platform))}function Wd(e){return e==="win32"?"junction":"dir"}function Bd(e,t){if(e.startsWith("-"))throw new f(`Extension runtime dependency name "${e}" is unsafe because npm could interpret it as a command-line option.`,h.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(o=>{let i=o.charCodeAt(0);return i<=31||i===127||"&|;()`\"'".includes(o)}))throw new f(`Extension runtime dependency "${e}" has an unsafe version specifier.`,h.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{vd.resolve(e,t)}catch{throw new f(`Extension runtime dependency "${e}@${t}" is not a valid npm dependency specifier.`,h.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 Hd(e){let t=new Map;for(let n of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(!(typeof n!="object"||n===null))for(let[o,i]of Object.entries(n)){if(o===en||typeof i!="string"||i.trim().length===0||t.has(o))continue;let r=i.trim();t.set(o,Bd(o,r))}return[...t.values()]}async function nn(e,t){let n=await Vt(e);if(n.length===1)return n[0];if(n.length>1){let o=n.map(i=>$.relative(e,i).replaceAll($.sep,"/")).sort((i,r)=>i.localeCompare(r));throw new f(`Package source "${t}" contains multiple extension manifests. Provide an explicit extension path. Candidates: ${o.join(", ")}`,h.USAGE)}throw new f(`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.`,h.USAGE)}async function Kd(e,t){let n=[];t.subpath&&(n.push(t.subpath),n.push($.posix.join(".agents/pm/extensions",t.subpath)),n.push($.posix.join(".custom/pm-extensions",t.subpath)),n.push($.posix.join(".custom/pm-extension",t.subpath)));for(let i of n){let r=$.resolve(e,i);if(V(e,r)&&await x($.join(r,"manifest.json")))return{directory:r,resolved_subpath:i}}if(await x($.join(e,"manifest.json")))return{directory:e,resolved_subpath:"."};let o=await nn(e,t.input);return{directory:o,resolved_subpath:$.relative(e,o).replaceAll($.sep,"/")}}function Vd(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 Yd(e){let t=`Local extension source does not exist: "${e.absolute_path}".`,n=e.input.trim();if(!Vd(n))return new f(t,h.NOT_FOUND);let o=[];try{let r=process.env.PM_CLI_PACKAGE_ROOT,a=typeof r=="string"&&r.trim().length>0?$.resolve(r.trim()):"";eo?.key!==a&&(eo={key:a,aliases:await Zt()}),o=eo.aliases}catch{}let i=[`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): ${o.join(", ")}`];return new f(`${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}".`,h.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:i,recovery:{attempted_command:`pm install ${n}`,normalized_args:["install",n],next_best_command:`pm install npm:${n}`}})}async function Wr(e){if(e.kind==="local"){let o;try{o=await P.stat(e.absolute_path)}catch{throw await Yd(e)}if(o.isFile()&&qr(e.absolute_path)){let r=await no(e.absolute_path);return{source:e,directory:r.directory,source_root:$.dirname(r.directory),resolved_subpath:$.relative($.dirname(r.directory),r.directory).replaceAll($.sep,"/"),npm_package:r.package,npm_version:r.version,cleanup:r.cleanup}}if(!o.isDirectory())throw new f(`Local extension source must be a directory or npm .tgz/.tar.gz archive: "${e.absolute_path}".`,h.USAGE);let i=await nn(e.absolute_path,e.input);return{source:e,directory:i,source_root:e.absolute_path}}if(e.kind==="npm"){let o=await Fd(e);return{source:e,directory:o.directory,source_root:$.dirname(o.directory),cleanup:o.cleanup,resolved_subpath:$.relative($.dirname(o.directory),o.directory).replaceAll($.sep,"/"),npm_package:o.package,npm_version:o.version}}let t=await P.mkdtemp($.join(oo.tmpdir(),"pm-extension-source-")),n=["clone","--depth","1"];e.ref&&n.push("--branch",e.ref),n.push(e.repository,t);try{await Qt(n);let o=await Qt(["-C",t,"rev-parse","HEAD"]),i=await Kd(t,e);return{source:e,directory:i.directory,source_root:t,resolved_subpath:i.resolved_subpath,commit:o,cleanup:async()=>{await P.rm(t,{recursive:!0,force:!0})}}}catch(o){throw await P.rm(t,{recursive:!0,force:!0}),o}}async function on(e,t){if(!await x(e)||!await x(t))return!1;let[n,o]=await Promise.all([P.realpath(e),P.realpath(t)]);return n===o}import wt from"node:fs/promises";import vt 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]="60ab864f-43c5-512c-b33f-456de96f8090")}catch{}})();var io=1,Je="2026.6.24",Xd=">=22.18.0",Zd={fs_read:!1,fs_write:!1,network:!1,env_read:!1,env_write:!1,process_spawn:!1},Br=new Set([...oi.map(e=>e.split("-")[0].toLowerCase()),...Object.keys(Co).map(e=>e.toLowerCase()),"scaffold"]),Qd="^6.0.0",ep="^22.0.0",Vr=["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."," }"," }","}",""],he=[" } finally {"," await deactivateIfNeeded(ext, deactivated);"," }"];function Hr(e,t){return e.map(n=>n===""?n:`${t}${n}`)}function Yr(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 Xr(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 tp={compilerOptions:{target:"ES2022",module:"NodeNext",moduleResolution:"NodeNext",strict:!0,esModuleInterop:!0,skipLibCheck:!0,noEmit:!0,allowImportingTsExtensions:!0,resolveJsonModule:!0,types:["node"]},include:["**/*.ts"]},Kr=["commands","hooks","search","importers","schema","profile","renderers","parser","preflight","services"],Zr={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"]},np={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"]'},op={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."},ip={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."},Qr="- `tsconfig.json`: strict type-check-only TypeScript config (`noEmit`) for the `.ts` source the loader runs directly.",rp={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."]},ap={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."]},sp={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`."]},cp={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 ea(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 ta(e,t){return e==="schema"?sp[t]:e==="profile"?cp[t]:ap[t]}function lp(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(),o=0;for(;t[o]?.toLowerCase()==="starter";)o+=1;let i=t[o]?.toLowerCase(),r=o>0&&(o===t.length||i!==void 0&&Br.has(i));return`${(Br.has(n)||r?["starter",...t]:t).join(" ")} ping`}function na(e){let t=e,n=`${e}s`,o=e.replace(/-/g,""),i=o===t?[]:[o],r=`${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(i)},`,` 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(r)},`,' 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 dp(e,t,n){let o=`${e}-search`,i=`${e}-vector`,r=`${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(o)},`," 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(i)},`,' 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`,l=e.replace(/-/g,""),d=l===s?[]:[l],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(d)},`," // 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({",...na(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(r)},`," async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${r} 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(r)},`," async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${r} 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 pp(e,t,n){let o=n==="hooks",i=n==="search",r=n==="importers",a=n==="schema",s=n==="profile",c=n==="renderers",l=n==="parser",d=n==="preflight",p=n==="services",u=np[n],g=e,y=`${e}s`,w=`${e.replace(/-/g,"_")}_note`,m=`${e}-0001-init`,_=[" assertExtensionDeactivated,"," createExtensionTestHarness,"],v=o?[`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;",...he,"});",""]:[],k=i?ro(e,t,"search",u):[],S=r?ro(e,t,"importers",u):[],R=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 {",...Hr(Yr({extensionName:e,itemTypeName:g,itemTypeFolder:y,fieldName:w,migrationId:m,includeMigrationReplacementHint:!0})," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...he,"});",""]:[],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 {",...Hr(Xr(e)," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...he,"});",""]:[],F=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;",...he,"});",""]:[],E=l?[`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;",...he,"});",""]:[],W=d?[`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;",...he,"});",""]:[],at=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;",...he,"});",""]:[];return['import assert from "node:assert/strict";','import { test } from "node:test";',"import {",..._,'} from "@unbrained/pm-cli/sdk/testing";',...i?['import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";']:[],'import extension from "./index.ts";',"",...Vr,`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)},`,...l?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...he,"});","",...v,...k,...S,...R,...G,...F,...E,...W,...at,`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(`
|
|
26
|
-
`)}function up(e,t,n){if(n==="schema"||n==="profile")return[];if(n==="importers"){let o=`${e.replace(/-/g," ")} items`;return[t,`${o} import`,`${o} export`]}return[t]}var mp={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"},fp={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 hp(e,t,n){let o=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.",',...o?[" 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,",...o?[" upper: context.options.upper === true,"]:[],' message: "Starter extension scaffold is active.",'," }),","});"]}function gp(e,t,n){let o=[],i=[...hp(e,t,n)],r=[" commands: [pingCommand],"],a=`${e}-search`,s=`${e}-vector`,c=`${e.replace(/-/g," ")} items`,l=e,d=`${e}s`,p=e.replace(/-/g,""),u=p===l?[]:[p],g=`${e.replace(/-/g,"_")}_note`,y=`${e}-0001-init`;switch(n){case"commands":break;case"hooks":o.push("defineAfterCommandHook"),i.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... */ }","});"),r.push(" hooks: { afterCommand: [afterCommandHook] },");break;case"search":o.push("defineSearchProvider","defineVectorStoreAdapter"),i.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 }),","});"),r.push(" searchProviders: [searchProvider],"," vectorStoreAdapters: [vectorStoreAdapter],");break;case"importers":o.push("defineExporter","defineImporter"),i.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,","}));"),r.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":o.push("defineItemField","defineItemType","defineMigration"),i.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(g)},`,' type: "string",'," optional: true,","});","","export const itemType = defineItemType({",` name: ${JSON.stringify(l)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(d)},`,` 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 }),","});"),r.push(" itemTypes: [itemType],"," itemFields: [noteField],"," migrations: [initMigration],");break;case"profile":o.push("defineProjectProfile"),i.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({",...na(e),"});"),r.push(" profiles: [starterProfile],");break;case"renderers":o.push("defineRendererOverride"),i.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);`," },","});"),r.push(" renderers: { toon: toonRenderer },");break;case"parser":o.push("defineParserOverride"),i.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 };","});"),r.push(` parsers: { ${JSON.stringify(t)}: pingParser },`);break;case"preflight":o.push("definePreflightOverride"),i.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,","});"),r.push(" preflights: [preflightOverride],");break;case"services":o.push("defineServiceOverride"),i.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 };`,"});"),r.push(" services: { output_format: outputService },");break}return{builderImports:o,definitions:i,blueprintFields:r}}function yp(e,t,n){let o=gp(e,t,n);return[`import { ${["composeExtension","defineCommand","defineExtensionBlueprint",...o.builderImports].sort((r,a)=>r.localeCompare(a)).join(", ")} } from "@unbrained/pm-cli/sdk";`,"",...o.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({",...o.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(`
|
|
27
|
-
`)}function ro(e,t,n,o){if(n==="commands")return[];let i=`${e}-search`,r=`${e}-vector`,a=`${e.replace(/-/g," ")} items`,s=e,c=`${e}s`,l=`${e.replace(/-/g,"_")}_note`,d=`${e}-0001-init`,p=[" const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${o},`," });"],u=g=>[...p," let deactivated = false;"," try {",...g.map(y=>y===""?y:` ${y}`)," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...he];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(i)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertVectorStoreAdapter({ name: ${JSON.stringify(r)}, 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(i)},`,' 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(i)},`,' operation: "embed",',' context: { input: "abc", settings, model: "starter-model" },'," });"," assert.deepEqual(embedding, [3]);",""," const vectorHits = await ext.runVectorStoreAdapter({",` adapter: ${JSON.stringify(r)},`,' 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(Yr({extensionName:e,itemTypeName:s,itemTypeFolder:c,fieldName:l,migrationId:d})),"});",""];case"profile":return[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`,...u(Xr(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 _p(e,t,n){let o=n==="parser",i=JSON.stringify([...Zr[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" };',"",...Vr,`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(Je)},`," },",` target: { pmVersion: ${JSON.stringify(Je)} },`," });"," // 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, ${i});`,` assert.deepEqual(report.manifest?.capabilities, ${i});`,"});","",`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: ${i},`," });"," 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)},`,...o?[" 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;",...he,"});","",...ro(e,t,n,i)].join(`
|
|
28
|
-
`)}function wp(e,t,n){let o=ea(n,"package"),i=ta(n,"package");return[`# ${e}`,"","Generated by `pm package init --declarative`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",o,`- \`index.ts\`: the TypeScript manifest entry \u2014 a \`defineExtensionBlueprint\` blueprint (${mp[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`.",Qr,"- `.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 ${fp[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.",...i,"","## Compatibility Bounds","`manifest.json` cannot hold comments, so the version-compatibility fields are documented here:",`- \`manifest_version\` (integer): manifest schema generation. Leave at \`${io}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${Je}\`. 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(`
|
|
29
|
-
`)}function vp(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 bp(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 kp(e,t,n,o){let i=["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"&&i.push("","export const afterCommandHook = defineAfterCommandHook((context) => {"," if (!context.ok) return;"," // React to context.affected here as your package grows.","});"),n==="search"&&i.push("","export const searchProvider = defineSearchProvider({",` name: ${JSON.stringify(o.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(o.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"&&i.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"&&i.push("",`export const noteField = defineItemField({ name: ${JSON.stringify(o.fieldName)}, type: "string", optional: true });`,"","export const itemType = defineItemType({",` name: ${JSON.stringify(o.itemTypeName)},`,` folder: ${JSON.stringify(o.itemTypeFolder)},`,` aliases: ${JSON.stringify(o.itemTypeAliases)},`," required_create_fields: [],","});","","export const initMigration = defineMigration({",` id: ${JSON.stringify(o.migrationId)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),n==="profile"&&i.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(o.itemTypeName)}, folder: ${JSON.stringify(o.itemTypeFolder)} },`," ],"," // ...plus statuses, fields, workflows, config, templates, and packages.","});"),n==="renderers"&&i.push("","export const toonRenderer = defineRendererOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => JSON.stringify(context.result),","});"),n==="parser"&&i.push("","export const pingParser = defineParserOverride((context) => {"," const options = { ...context.options };"," if (options.shout === true) options.upper = true;"," delete options.shout;"," return { options };","});"),n==="preflight"&&i.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"&&i.push("","export const outputService = defineServiceOverride((context) => {",` if (context.command !== ${JSON.stringify(t)}) return { handled: false };`,` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`,"});"),i}function xp(e,t,n){let o=[];return t==="renderers"&&o.push(' api.registerRenderer("toon", toonRenderer.run, toonRenderer);'),t==="parser"&&o.push(` api.registerParser(${JSON.stringify(e)}, pingParser);`),t==="preflight"&&o.push(" api.registerPreflight(preflightOverride);"),t==="services"&&o.push(' api.registerService("output_format", outputService);'),t==="hooks"&&o.push(" api.hooks.afterCommand(afterCommandHook);"),t==="search"&&o.push(" api.registerSearchProvider(searchProvider);"," api.registerVectorStoreAdapter(vectorStoreAdapter);"),t==="schema"&&o.push(" api.registerItemFields([noteField]);"," api.registerItemTypes([itemType]);"," api.registerMigration(initMigration);"),t==="profile"&&o.push(" api.registerProfile(starterProfile);"),t==="importers"&&o.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.",'," },"," ],"," });"),o}function Sp(e,t,n,o="commands",i=!1){let r=`pm-${e}`,a=Zr[o],s=up(e,t,o),c=`${JSON.stringify({name:e,version:"0.1.0",entry:"./index.ts",manifest_version:io,pm_min_version:Je,trusted:!0,sandbox_profile:"strict",permissions:{...Zd},capabilities:a,...s.length>0?{activation:{commands:s}}:{}},null,2)}
|
|
30
|
-
`,l=['import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"","export function activate(api: ExtensionApi): void {",...dp(e,t,o),"}","","// `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(`
|
|
31
|
-
`),d=`${JSON.stringify(tp,null,2)}
|
|
32
|
-
`,p=op[o],u=ea(o,"package"),g=`${JSON.stringify({name:r,version:"0.1.0",private:!0,type:"module",keywords:["pm-package"],engines:{node:Xd},scripts:{typecheck:"tsc --noEmit","test:runtime":"node --test",test:"npm run typecheck && npm run test:runtime"},peerDependencies:{"@unbrained/pm-cli":`>=${Je}`},devDependencies:{"@types/node":ep,typescript:Qd},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)}
|
|
33
|
-
`,y=pp(e,t,o),w=ip[o],m=["node_modules/","*.log","*.tsbuildinfo",""].join(`
|
|
34
|
-
`),_=vp(e),k=["```ts",`import { ${bp(o)} } from "@unbrained/pm-cli/sdk";`,'import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"",...kp(e,t,o,_),"","export function activate(api: ExtensionApi): void {"," api.registerCommand(pingCommand);",...xp(t,o,_),"}","","export function deactivate(): void {}","","export default { activate, deactivate };","```"],S=[`# ${r}`,"","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,Qr,"- `.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`.",...rp[o],...ta(o,"package"),"","## Compatibility Bounds",`- \`peerDependencies["@unbrained/pm-cli"]\` uses the stable range \`>=${Je}\`. 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 \`${io}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${Je}\`. 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(`
|
|
35
|
-
`);return{"package.json":g,"manifest.json":c,"index.ts":i?yp(e,t,o):l,"index.test.ts":i?_p(e,t,o):y,"tsconfig.json":d,".gitignore":m,"README.md":i?wp(r,t,o):S}}async function oa(e,t="extension",n="commands",o=!1){let i=n.trim().toLowerCase();if(!Kr.includes(i))throw new f(`Unknown scaffold capability "${n}". Supported capabilities: ${Kr.join(", ")}.`,h.USAGE);let r=i;if(o&&t!=="package")throw new f("--declarative scaffolds a package-mode blueprint starter (composeExtension is a runtime SDK import). Use `pm package init`, not `pm extension init`.",h.USAGE);let a=o?"declarative":"imperative",s=e.trim(),c=vt.resolve(process.cwd(),s),l=Yt(vt.basename(c)).replace(/^(?:pm-)+/u,""),d=lp(l),p=Sp(l,d,t,r,o),u=!1;if(await x(c)){if(!(await wt.stat(c)).isDirectory())throw new f(`Scaffold target "${c}" exists and is not a directory.`,h.CONFLICT)}else await wt.mkdir(c,{recursive:!0}),u=!0;for(let[y,w]of Object.entries(p)){let m=vt.join(c,y);if(!await x(m))continue;if(await wt.readFile(m,"utf8")!==w)throw new f(`Scaffold file "${y}" already exists with different content in "${c}". Choose a new target path or remove conflicting files.`,h.CONFLICT)}let g=[];for(let[y,w]of Object.entries(p)){let m=vt.join(c,y);if(await x(m)){g.push({path:y,status:"unchanged"});continue}await wt.mkdir(vt.dirname(m),{recursive:!0}),await wt.writeFile(m,w,"utf8"),g.push({path:y,status:"created"})}return{extension_name:l,package_name:`pm-${l}`,command_name:d,invocation_command:`pm ${d}`,capability:r,style:a,target_path:c,created_directory:u,files:g}}(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]="2bc00b8e-0d9f-5af8-9667-d46136ff52b0")}catch{}})();var ia=1,ao=6,ra=[["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 so(e){return"#".repeat(e)}function aa(e){if(!e.includes("`"))return`\`${e}\``;let t=0,n=0;for(let r of e)n=r==="`"?n+1:0,t=Math.max(t,n);let o="`".repeat(t+1),i=e.startsWith("`")||e.endsWith("`")?" ":"";return`${o}${i}${e}${i}${o}`}function Ep(e){return e.length===0?"Capabilities: _none registered_":`Capabilities: ${e.map(aa).join(", ")}`}function $p(e,t,n){let o=[`${so(t)} ${e}`,""];return n.length===0?(o.push("_None._",""),o):(o.push(...n.map(i=>`- ${aa(i)}`),""),o)}function Ip(e,t,n){return e===0&&!n?[]:[`${so(t)} Preflight overrides`,"",e>0?`- ${e} registered (this surface carries no per-entry identifier)`:"_None._",""]}function co(e,t={}){let n=t.headingLevel??2;if(!Number.isInteger(n)||n<ia||n>ao)throw new RangeError(`headingLevel must be an integer in [${ia}, ${ao}], received ${String(t.headingLevel)}`);let o=Math.min(n+1,ao),i=t.includeEmpty===!0,r=t.title??"Extension surfaces",a=[`${so(n)} ${r}`,""];(i||e.capabilities.length>0)&&a.push(Ep(e.capabilities),"");for(let[c,l]of ra){let d=e[c]??[];d.length===0&&!i||a.push(...$p(l,o,d))}return a.push(...Ip(e.preflight_overrides,o,i)),!(e.preflight_overrides>0||ra.some(([c])=>(e[c]?.length??0)>0))&&!i&&a.push("_This extension registers no surfaces._",""),`${a.join(`
|
|
36
|
-
`).trimEnd()}
|
|
37
|
-
`}(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]="6c9e36f8-0f95-5768-8893-bf33bbb4d848")}catch{}})();function sa(e,t){return`${e}:${b(t)}`}function Ap(e,t){let n=[];for(let[o,i]of[["handler",e.commands.handlers],["override",e.commands.overrides]]){let r=new Map;for(let a of i){let s=r.get(a.command)??[];r.set(a.command,[...s,a])}for(let[a,s]of r){if(t!==null&&!s.some(l=>t.has(b(l.name))))continue;let c=s.at(-1);n.push({command:a,surface:o,policy:"last_activated_wins",collision:s.length>1,claimants:s.map(l=>({name:l.name,layer:l.layer,winner:l===c}))})}}return n.sort((o,i)=>o.command.localeCompare(i.command)||o.surface.localeCompare(i.surface))}function ca(e,t,n){let o=new Set(n.failed.map(l=>sa(l.layer,l.name))),i=[...t.loaded.map(l=>({name:l.name,layer:l.layer,version:l.version,activation_status:o.has(sa(l.layer,l.name))?"failed":"ok",surfaces:Ve(n,{extensionName:l.name})})),...t.failed.map(l=>({name:l.name,layer:l.layer,version:"unknown",activation_status:"not_loaded",surfaces:Ve(n,{extensionName:l.name})}))].sort((l,d)=>l.name.localeCompare(d.name)||l.layer.localeCompare(d.layer)),r=typeof e=="string"?b(e):null,a=r===null?null:new Set(t.loaded.filter(l=>b(l.name)===r||typeof l.source_package=="string"&&b(l.source_package)===r||(l.source_aliases??[]).some(d=>b(d)===r)).map(l=>b(l.name)).concat(r)),s=a===null?i:i.filter(l=>a.has(b(l.name))),c=a===null?{}:{extensionNames:[...a]};return{target:typeof e=="string"?e.trim():null,total:s.length,extensions:s,union:Ve(n,c),command_ownership:Ap(n,a)}}var Tp={ok:"loaded",failed:"activation failed",not_loaded:"not loaded"};function zy(e,t){let o=[`# ${`${t[0].toUpperCase()}${t.slice(1)}`} surface reference`,""];if(o.push(e.target===null?`Scope: all loaded ${t}s`:`Scope: \`${e.target}\``),o.push(`Described: ${e.total} ${t}${e.total===1?"":"s"}`,""),(e.command_ownership?.length??0)>0){o.push("## Command ownership","");for(let i of e.command_ownership){let r=i.claimants.find(s=>s.winner),a=i.claimants.map(s=>`${s.layer}:${s.name}`).join(", ");o.push(`- \`${i.command}\` (${i.surface}): ${r.layer}:${r.name}; policy=${i.policy}; collision=${String(i.collision)}; claimants=${a}`)}o.push("")}if(e.extensions.length===0)return o.push(`_No ${t}s are loaded._`,""),`${o.join(`
|
|
38
|
-
`).trimEnd()}
|
|
39
|
-
`;for(let i of e.extensions){let r=`${i.name} (${i.layer} v${i.version}, ${Tp[i.activation_status]})`;o.push(co(i.surfaces,{title:r,headingLevel:2}))}return e.extensions.length>1&&o.push(co(e.union,{title:`Union across all described ${t}s`,headingLevel:2})),`${o.join(`
|
|
40
|
-
`).trimEnd()}
|
|
41
|
-
`}import sn from"node:fs/promises";import an from"node:path";import la 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]="3df6b126-ff8b-55be-8f33-53ec9a2336a8")}catch{}})();function bt(e,t,n,o){let i=la.relative(e,n);if(i!==""&&!V(e,n)||n===t||V(t,n))return!1;let r=i.split(la.sep);return r.includes(".git")?!1:o?!r.some(a=>a===".agents"||a==="node_modules"||a.startsWith(".pm-extension-install-backup-")):!0}import{randomUUID as Op}from"node:crypto";import M from"node:fs/promises";import Cp from"node:os";import j 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]="67bd3c08-81bf-5286-81ee-60126f7f979b")}catch{}})();var da=3,Pp=120,pa=250,Rp=12e4,Np=new Set(["EEXIST","ENOTEMPTY","ENOENT"]),ua=e=>typeof e=="object"&&e!==null&&"code"in e?e.code:void 0,ma=e=>Np.has(String(ua(e))),rn=(e,t)=>ua(e)===t,fa=e=>new Promise(t=>{setTimeout(t,e)}),ha=async e=>{let t=j.join(e,"package.json");await x(t)||await M.writeFile(t,`${JSON.stringify({type:"module"},null,2)}
|
|
42
|
-
`,"utf8")},ga=async e=>{let t=ue(import.meta.url,["../../.."]),n=j.join(e,"node_modules","@unbrained"),o=j.join(n,"pm-cli");await M.mkdir(n,{recursive:!0}),await M.rm(o,{recursive:!0,force:!0}),await M.symlink(t,o,process.platform==="win32"?"junction":"dir")},kt=async e=>{let t=j.resolve(e),n=j.dirname(t),o=j.parse(n).root,i=await M.realpath(o).catch(()=>o),r=j.relative(o,n),a=r===""?[]:r.split(j.sep);for(let[s,c]of a.entries()){let l=j.join(i,c);try{i=await M.realpath(l)}catch{i=j.join(i,...a.slice(s));break}}return j.join(i,j.basename(t))},ya=async(e,t,n,o=Cp.tmpdir())=>Ne("extension_install_copy",async()=>{let i=j.resolve(e),r=await M.realpath(i).catch(()=>i),a=await kt(t);if(r===a)return;if(!V(r,a)){await n(r,t,{recursive:!0,force:!0,filter:p=>bt(r,a,j.resolve(p),!1)});return}let s=await M.realpath(j.resolve(o)).catch(()=>kt(o)),c=V(r,s)?j.dirname(r):s;if(V(r,c))throw new f(`Extension source "${e}" contains its install destination and no external staging directory is available. Install a narrower package directory instead.`,h.USAGE,{code:"extension_install_source_contains_destination"});let l=await M.mkdtemp(j.join(c,"pm-extension-copy-")),d=j.join(l,"extension");try{await n(r,d,{recursive:!0,force:!0,filter:p=>bt(r,a,j.resolve(p),!0)}),await n(d,t,{recursive:!0,force:!0})}finally{await M.rm(l,{recursive:!0,force:!0})}}),_a=async(e,t,n=M.cp)=>{for(let o=1;o<=da;o+=1)try{await Ne("extension_install_copy",async()=>{await M.rm(t,{recursive:!0,force:!0}),await ya(e,t,n)});return}catch(i){if(!ma(i)||o===da)throw i;await fa(pa)}},lo=async e=>{let t;try{t=await M.readFile(j.join(e,"owner.json"),"utf8")}catch(i){if(!Ot(i))throw i;return null}let n;try{n=JSON.parse(t)}catch{return null}if(typeof n!="object"||n===null||!("token"in n))return null;let o=n.token;return typeof o=="string"&&o.length>0?o:null},wa=async(e,t)=>await lo(e)!==t?!1:(await M.rm(e,{recursive:!0,force:!0}),!0),Dp=async(e,t)=>{let n;try{n=await M.stat(e)}catch{return!1}if(Date.now()-n.mtimeMs<=t)return!1;let o=await lo(e);return o===null?(await M.rm(e,{recursive:!0,force:!0}),!0):wa(e,o)},jp=(e,t,n)=>{let o=Promise.resolve(),i=setInterval(()=>{o=o.then(async()=>{if(await lo(e)!==t)return;let r=new Date;await M.utimes(e,r,r)}).catch(()=>{})},n);return i.unref(),async()=>{clearInterval(i),await o}},Lp=async(e,t)=>{await M.mkdir(e);try{await M.writeFile(j.join(e,"owner.json"),`${JSON.stringify(t,null,2)}
|
|
43
|
-
`,"utf8")}catch(n){throw await M.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}},Fp=async(e,t,n,o,i)=>{for(let r=1;r<=n;r+=1)try{return await Lp(e,t),!0}catch(a){if(!rn(a,"EEXIST"))throw a;await Dp(e,i)?r-=1:await fa(o)}return!1},po=async(e,t,n,o)=>Ne("extension_install",async()=>{let i=j.join(e,"runtime","extension-install-locks"),r=j.join(i,"scope.lock");await M.mkdir(i,{recursive:!0});let{attempts:a=Pp,delay_ms:s=pa,stale_ms:c=Rp,heartbeat_ms:l}=o??{};if(![a,s,c,l].filter(v=>v!==void 0).every(Number.isFinite))throw new f("Extension install lock timings must be finite numbers.",h.USAGE);let d=Math.max(1,Math.floor(a)),p=Math.max(0,Math.floor(s)),u=Math.floor(c),g=Math.floor(l??u/3);if(u<=0||g<=0||g>=u)throw new f("Extension install lock timings require stale_ms > 0 and 0 < heartbeat_ms < stale_ms.",h.USAGE);let y={pid:process.pid,token:Op(),created_at:T(),destination:t};if(!await Fp(r,y,d,p,u))throw new f(`Timed out waiting for extension install lock for "${t}".`,h.CONFLICT);let m=jp(r,y.token,g),_=!1;try{let v=await n();return _=!0,v}finally{await m(),await wa(r,y.token).catch(v=>{if(_)throw v})}});(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]="7819cf2a-73dd-5002-9b79-4e099848d0d3")}catch{}})();var Mp=new Set(["node_modules",".git","dist","build","coverage"]);async function va(e,t,n,o){let i=e.source.kind==="local"?await sn.stat(e.source.absolute_path):void 0,r=e.source.kind==="local"?i.isDirectory()?"directory":"archive":e.source.kind,a=await Gp(e.directory,t,o),s={source_mode:r,...r==="archive"?{archive_bytes:i.size}:{},copy:a},c=e.source_root??e.directory;if(r==="directory"&&(!a.complete||a.development_entries>0||a.bytes>=16*1024*1024)&&await x(an.join(c,"package.json"))&&(s.packed_alternative={cwd:c,pack:{command:"npm",args:["pack","--ignore-scripts","--json"]},install:{command:"pm",args:["package","install","<archive-filename>",`--${n}`]},archive_argument:"pack_result[0].filename"}),r==="directory"&&!a.complete){let l=a.stop_reason==="entry_limit"?`${a.max_entries} entries`:`${a.max_depth} directory levels`;throw new f(`Local extension source scan stopped at ${l}; the directory snapshot is incomplete and installation was refused. ${s.packed_alternative?"Pack the package with npm pack --ignore-scripts --json, then install its archive.":"Install a smaller source directory or a packed archive."}`,h.USAGE,{code:"extension_install_incomplete_source_scan",reason:a.stop_reason,nextSteps:s.packed_alternative?[`Run npm pack --ignore-scripts --json from the package root, then pm package install <archive-filename> --${n}.`]:["Choose a smaller source directory or install a packed archive."]})}return s}async function Gp(e,t,n={}){let{maxEntries:o=1e4,maxDepth:i=64,signal:r}=n;if(![o,i].every(p=>Number.isSafeInteger(p)&&p>0))throw new f("maxEntries and maxDepth must be positive safe integers.",h.USAGE);r?.throwIfAborted();let a=await sn.realpath(e),s=await kt(t),c=await on(a,s);r?.throwIfAborted();let l=c?"in_place":V(a,s)?"nested_filtered_snapshot":"directory_snapshot",d={copy_scope:l,source_directory:a,destination_directory:s,files:0,bytes:0,directories:0,symlinks:0,other_entries:0,scanned_entries:0,excluded_entries:0,development_entries:0,complete:!0,stop_reason:"complete",max_entries:o,max_depth:i};return l==="in_place"||await ba(a,0,d,r),d}async function ba(e,t,n,o){o?.throwIfAborted();let i=await sn.opendir(e);for await(let r of i){if(o?.throwIfAborted(),n.scanned_entries>=n.max_entries){n.complete=!1,n.stop_reason="entry_limit";return}n.scanned_entries+=1;let a=an.join(e,r.name);if(!bt(n.source_directory,n.destination_directory,a,n.copy_scope==="nested_filtered_snapshot")){n.excluded_entries+=1;continue}if(an.relative(n.source_directory,a).split(an.sep).some(s=>Mp.has(s))&&(n.development_entries+=1),await Up(a,t,n,o),!n.complete)return}}async function Up(e,t,n,o){let i=await sn.lstat(e);if(o?.throwIfAborted(),i.isDirectory()){if(n.directories+=1,t+1>=n.max_depth){n.complete=!1,n.stop_reason="depth_limit";return}await ba(e,t+1,n,o)}else i.isFile()?(n.files+=1,n.bytes+=i.size):i.isSymbolicLink()?n.symlinks+=1:n.other_entries+=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]="dcdfdabd-8862-502f-8cd1-298c08825985")}catch{}})();async function ka(e,t,n){let o=typeof t=="string"?null:await _t(e),i=o===null?null:e.trim().toLowerCase(),r=i===null?null:await Nr(i),a=tn(o??e,{forceGithub:typeof t=="string",ref:n}),s=i===null?null:await Mr(e);return{bundledAliasName:i,bundledPackageName:r,installSource:a,sourceResolution:{requested:e,selected:{kind:i===null?a.kind:"builtin",input:i??a.input,...r===null?{}:{package:r}},ambiguous:s!==null,precedence:"bundled_alias_before_installed_npm",candidates:[...i===null?[]:[{kind:"builtin",input:i,...r===null?{}:{package:r},command:`pm install ${i}`}],...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 Re from"node:fs/promises";import oe from"node:path";import Bp from"node:path";import{mkdir as Hp}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]="ebcb45a2-996a-5194-8086-efe882dbcacc")}catch{}})();var xt=["agile","ops","research"],zp={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 cn(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: ${xt.join(", ")}.`)}function St(e){return zp[e].map(t=>lt(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]="96cec314-edb6-5c51-abc4-d028bdc4f10c")}catch{}})();var Jp=/^([A-Za-z][A-Za-z0-9_-]*?)\s*[-:]\s+\S/;function qp(e){let t=Jp.exec(e.trim());if(!t)return;let n=t[1];if(!(n.length<2)&&!/^[A-Za-z]\d+$/.test(n))return n.toLowerCase()}function Wp(e){return e.split(/[-_]+/).filter(t=>t.length>0).map(t=>`${t.slice(0,1).toUpperCase()}${t.slice(1).toLowerCase()}`).join("")}function xa(e,t={}){let n=typeof t.minCount=="number"&&t.minCount>0?Math.trunc(t.minCount):10,o=typeof t.maxExamples=="number"&&t.maxExamples>0?Math.trunc(t.maxExamples):3,i=new Map;for(let a of e){let s=typeof a=="string"?a.trim():"";if(s.length===0)continue;let c=qp(s);if(c===void 0)continue;let l=i.get(c)??{count:0,examples:[]};l.count+=1,l.examples.length<o&&l.examples.push(s),i.set(c,l)}let r=[];for(let[a,s]of i.entries()){if(s.count<n)continue;let c=Wp(a);r.push({name:c,prefix:a,count:s.count,examples:s.examples,shadows_builtin:gi(c)!==void 0})}return r.sort((a,s)=>s.count-a.count||a.name.localeCompare(s.name)),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]="1805dfab-5dc5-5be4-ad32-cbd8b3e37f8c")}catch{}})();var H_=[...Dt,"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"],ln="schema-types",Sa="schema-statuses",Ea="schema-fields";function Ce(e){return He({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 Y_(e,t,n){let o=N(process.cwd(),n.path);await be(o);let i;try{i=lt({name:e,description:t.description,defaultStatus:t.defaultStatus,folder:t.folder,aliases:t.alias})}catch(g){throw new f(g instanceof Error?g.message:String(g),h.USAGE)}let r=await A(o),a=Y(r.schema),s=ie(o,a.files.types,Q.types),c=[],l=H(t.author,r.author_default),d=se(r),p=await Z(o,ln,r.locks.ttl_seconds,l,!!t.force,d.force_required_for_stale_lock,r.locks.wait_ms),u;try{let g=await U(s),y;try{y=ce(g)}catch(w){throw new f(w instanceof Error?w.message:String(w),h.GENERIC_FAILURE)}try{yi(i,y);let w=new Map,m=z(r,B());for(let[_,v]of Object.entries(m.type_to_folder)){let k=v.trim().toLowerCase();k.length>0&&!w.has(k)&&w.set(k,_)}_i(i,y,w)}catch(w){throw new f(w instanceof Error?w.message:String(w),h.USAGE)}u=Ke(y,i),u.replaced&&u.previousName!==void 0&&u.previousName!==u.definition.name&&c.push(`type_recased:${u.previousName}->${u.definition.name}`),await Ce({pmRoot:o,filePath:s,raw:me(u.file),op:"schema:add-type",author:l,settings:r}),await Et(o,[u.definition],c,"schema:add-type-folder"),c.push(...await K({path:s,scope:"project",op:"schema:add-type"}))}finally{await p()}return await $a(o,c),{action:"add-type",registered:!0,replaced:u.replaced,type:u.definition,file:{path:s,definitions:u.file.definitions.length},warnings:Pe(c),generated_at:T()}}async function be(e){await Se(e)}async function $a(e,t){try{let n=await Qi(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 Pe(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}async function Kp(e,t,n,o){let i=z(t,B()),r=o.trim().toLowerCase();return(await De(e,t.item_format,i.type_to_folder,[],n)).filter(s=>typeof s.type=="string"&&s.type.toLowerCase()===r).length}async function Vp(e,t,n,o){let i=z(t,B()),r=ct(n),a=I(o);return(await De(e,t.item_format,i.type_to_folder,[],n)).filter(c=>{let l=typeof c.status=="string"?c.status:"";return(r.alias_to_id.get(I(l))??I(l))===a}).length}async function Yp(e,t,n,o,i){if(i.length===0||Me.has(i))return;let r=await Vp(t,n,o,i);r>0&&e.push(`items_using_status:${r}`);let a=Ia(o.workflow,i);a.length>0&&e.push(`status_referenced_by_workflow:${a.join(",")}`)}function Ia(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(([,o])=>o!==void 0&&I(o)===t).map(([o])=>o)}async function X_(e,t,n){let o=N(process.cwd(),n.path);await be(o);let i=await A(o),r=Y(i.schema),a=ie(o,r.files.types,Q.types),s=[],c=H(t.author,i.author_default),l=se(i),d=await Z(o,ln,i.locks.ttl_seconds,c,!!t.force,l.force_required_for_stale_lock,i.locks.wait_ms),p;try{let u=await U(a),g;try{g=ce(u)}catch(y){throw new f(y instanceof Error?y.message:String(y),h.GENERIC_FAILURE)}try{p=wi(g,e)}catch(y){throw new f(y instanceof Error?y.message:String(y),h.USAGE)}if(p.removed){let y=(p.definition?.name??e??"").trim();if(y.length>0){let w=await Kp(o,i,r,y);w>0&&s.push(`items_using_type:${w}`)}await Ce({pmRoot:o,filePath:a,raw:me(p.file),op:"schema:remove-type",author:c,settings:i}),s.push(...await K({path:a,scope:"project",op:"schema:remove-type"}))}}finally{await d()}return p.removed&&await $a(o,s),{action:"remove-type",removed:p.removed,...p.definition?{type:p.definition}:{},file:{path:a,definitions:p.file.definitions.length},warnings:Pe(s),generated_at:T()}}function uo(e,t){return ie(e,t.files.statuses,Q.statuses)}function dn(e,t){return ie(e,t.files.fields,Q.fields)}function Aa(e,t){return ie(e,t.files.types,Q.types)}async function Et(e,t,n,o){for(let i of t){let r=Lo(i.folder??jo(i.name)),a=Bp.join(e,r);await x(a)||(await Hp(a,{recursive:!0}),n.push(...await K({path:a,scope:"project",op:o})))}}function mo(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 Xp(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 Zp(e){let t=new Map;for(let n of e){let o=I(n.id);if(o.length!==0){t.set(o,o);for(let i of Array.isArray(n.aliases)?n.aliases:[]){let r=I(i);r.length>0&&!t.has(r)&&t.set(r,o)}}}return t}async function Z_(e,t,n){let o=N(process.cwd(),n.path);await be(o);let i;try{i=mr({id:e,roles:t.role,aliases:t.alias,description:t.description,order:t.order})}catch(m){throw new f(m instanceof Error?m.message:String(m),h.USAGE)}let r=await A(o),a=Y(r.schema),s=uo(o,a),c=ct(a);try{qn(i,c.alias_to_id)}catch(m){throw new f(m instanceof Error?m.message:String(m),h.USAGE)}let l=Xp(c.by_id.get(i.id));if((i.roles??l?.roles??[]).length===0)throw new f(`Status "${i.id}" requires at least one lifecycle role. Re-run with --role active, --role blocked, --role draft, or an appropriate terminal/default role.`,h.USAGE,{code:"status_lifecycle_role_required",examples:[`pm schema add-status "${je(i.id)}" --role active`,`pm schema add-status "${je(i.id)}" --role blocked`]});let p=[],u=H(t.author,r.author_default),g=se(r),y=await Z(o,Sa,r.locks.ttl_seconds,u,!!t.force,g.force_required_for_stale_lock,r.locks.wait_ms),w;try{let m=await U(s),_;try{_=et(m)}catch(k){throw new f(k instanceof Error?k.message:String(k),h.GENERIC_FAILURE)}let v=Zp(_.statuses);try{qn(i,v)}catch(k){throw new f(k instanceof Error?k.message:String(k),h.USAGE)}w=fr(_,i,l),await Ce({pmRoot:o,filePath:s,raw:tt(w.file),op:"schema:add-status",author:u,settings:r}),p.push(...await K({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:Pe(p),generated_at:T()}}async function Q_(e,t,n){let o=N(process.cwd(),n.path);await be(o);let i=await A(o),r=Y(i.schema),a=uo(o,r),s=[],c=H(t.author,i.author_default),l=se(i),d=await Z(o,Sa,i.locks.ttl_seconds,c,!!t.force,l.force_required_for_stale_lock,i.locks.wait_ms),p;try{let u=await U(a),g;try{g=et(u)}catch(y){throw new f(y instanceof Error?y.message:String(y),h.GENERIC_FAILURE)}try{p=hr(g,e)}catch(y){throw new f(y instanceof Error?y.message:String(y),h.USAGE)}if(p.removed){let y=I(p.definition?.id??e);await Yp(s,o,i,r,y),await Ce({pmRoot:o,filePath:a,raw:tt(p.file),op:"schema:remove-status",author:c,settings:i}),s.push(...await K({path:a,scope:"project",op:"schema:remove-status"}))}}finally{await d()}return{action:"remove-status",removed:p.removed,...p.definition?{status:p.definition}:{},file:{path:a,statuses:p.file.statuses.length},warnings:Pe(s),generated_at:T()}}function Ta(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 Qp(e,t,n){return{...Ta(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 Oa(e){return{id:e.id,source:Me.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 Ca(e,t,n){let o=e.toLowerCase();return n.has(o)?"extension":t.has(o)?"custom":"builtin"}function eu(){let e=new Map,t=B();for(let n of t?.item_types??[]){let o=n.types;if(Array.isArray(o))for(let i of o){if(typeof i!="object"||i===null||Array.isArray(i))continue;let r=i.name;typeof r=="string"&&r.trim().length>0&&e.set(r.trim().toLowerCase(),{layer:n.layer,name:n.name})}}return e}function tu(e){let t=ct(e),n=[],o=[];for(let i of t.definitions){let r=Oa(i);r.source==="builtin"?n.push(r):o.push(r)}return{builtin:n,custom:o}}async function $t(e){let t=N(process.cwd(),e.path);await be(t);let n=await A(t),o=Y(n.schema),i=ie(t,o.files.types,Q.types),r=uo(t,o),a=z(n,B()),s=eu(),c=new Set((n.item_types?.definitions??[]).map(l=>l.name.trim().toLowerCase()).filter(l=>l.length>0&&!s.has(l)));return{pmRoot:t,typesPath:i,statusesPath:r,byType:a.by_type,customNames:c,extensionProvenance:s,schema:o}}async function ew(e){let t=await $t(e),n=[],o=[],i=[];for(let s of Object.values(t.byType).sort((c,l)=>c.name.localeCompare(l.name))){let c=Ca(s.name,t.customNames,new Set(t.extensionProvenance.keys())),l=Ta(s);c==="extension"?i.push(l):c==="custom"?o.push(l):n.push(l)}let r=tu(t.schema),a=jt(t.schema).definitions.map(mo);return{action:"list",builtin:n,custom:o,extension:i,counts:{builtin:n.length,custom:o.length,extension:i.length,total:n.length+o.length+i.length},statuses:{builtin:r.builtin,custom:r.custom,counts:{builtin:r.builtin.length,custom:r.custom.length,total:r.builtin.length+r.custom.length}},fields:{custom:a,counts:{total:a.length}},file:{path:t.typesPath},generated_at:T()}}async function tw(e,t){let n=(e??"").trim();if(n.length===0)throw new f("Type name must not be empty.",h.USAGE);let o=await $t(t),i=Object.values(o.byType).find(r=>r.name.toLowerCase()===n.toLowerCase()||r.aliases.some(a=>a.toLowerCase()===n.toLowerCase()));if(!i)throw new f(`Unknown item type "${n}". Run pm schema list to inspect registered types, or pm schema add-type "${je(n)}" to register it.`,h.NOT_FOUND,{code:"unknown_item_type"});return{action:"show",type:Qp(i,Ca(i.name,o.customNames,new Set(o.extensionProvenance.keys())),o.extensionProvenance.get(i.name.toLowerCase())),file:{path:o.typesPath},generated_at:T()}}async function nw(e,t){let n=I(e);if(n.length===0)throw new f("Status id must not be empty.",h.USAGE);let o=await $t(t),i=ct(o.schema),r=i.alias_to_id.get(n)??n,a=i.by_id.get(r);if(!a)throw new f(`Unknown status "${e}". Run pm schema list to inspect registered statuses, or pm schema add-status "${je(e??"")}" to register it.`,h.NOT_FOUND,{code:"unknown_status"});return{action:"show-status",status:Oa(a),file:{path:o.statusesPath},generated_at:T()}}async function ow(e,t,n){let o=N(process.cwd(),n.path);await be(o);let i;try{i=dr({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 f(y instanceof Error?y.message:String(y),h.USAGE)}let r=await A(o),a=Y(r.schema),s=dn(o,a),c=[],l=Mt(i.key);l&&c.push(`custom_field_mcp_input_collision:${l.field}:${l.property}:${l.owner}:use=${l.nested_path}`);let d=H(t.author,r.author_default),p=se(r),u=await Z(o,Ea,r.locks.ttl_seconds,d,!!t.force,p.force_required_for_stale_lock,r.locks.wait_ms),g;try{let y=await U(s),w;try{w=Ze(y)}catch(m){throw new f(m instanceof Error?m.message:String(m),h.GENERIC_FAILURE)}g=pr(w,i),await Ce({pmRoot:o,filePath:s,raw:Qe(g.file),op:"schema:add-field",author:d,settings:r}),c.push(...await K({path:s,scope:"project",op:"schema:add-field"}))}finally{await u()}return{action:"add-field",registered:!0,replaced:g.replaced,field:g.definition,file:{path:s,fields:g.file.fields.length},warnings:Pe(c),generated_at:T()}}async function nu(e,t,n,o){let i=z(t,B());return(await De(e,t.item_format,i.type_to_folder,[],n)).filter(a=>{let s=a[o];return s==null?!1:Array.isArray(s)?s.length>0:typeof s=="string"?s.trim().length>0:!0}).length}async function iw(e,t,n){let o=N(process.cwd(),n.path);await be(o);let i=await A(o),r=Y(i.schema),a=dn(o,r),s=[],c=H(t.author,i.author_default),l=se(i),d=await Z(o,Ea,i.locks.ttl_seconds,c,!!t.force,l.force_required_for_stale_lock,i.locks.wait_ms),p;try{let u=await U(a),g;try{g=Ze(u)}catch(y){throw new f(y instanceof Error?y.message:String(y),h.GENERIC_FAILURE)}try{p=ur(g,e)}catch(y){throw new f(y instanceof Error?y.message:String(y),h.USAGE)}if(p.removed){let y=I(p.definition?.key??e),w=I(p.definition?.metadata_key??p.definition?.front_matter_key??y);if(w.length>0){let m=await nu(o,i,r,w);m>0&&s.push(`items_using_field:${m}`)}await Ce({pmRoot:o,filePath:a,raw:Qe(p.file),op:"schema:remove-field",author:c,settings:i}),s.push(...await K({path:a,scope:"project",op:"schema:remove-field"}))}}finally{await d()}return{action:"remove-field",removed:p.removed,...p.definition?{field:p.definition}:{},file:{path:a,fields:p.file.fields.length},warnings:Pe(s),generated_at:T()}}async function rw(e){let t=await $t(e),n=jt(t.schema).definitions.map(mo);return{action:"list-fields",fields:n,counts:{total:n.length},file:{path:dn(t.pmRoot,t.schema)},generated_at:T()}}async function aw(e,t){let n=I(e);if(n.length===0)throw new f("Field key must not be empty.",h.USAGE);let o=await $t(t),i=jt(o.schema).by_key.get(n);if(!i)throw new f(`Unknown custom field "${e}". Run pm schema list-fields to inspect registered fields, or pm schema add-field "${je(e??"")}" to register it.`,h.NOT_FOUND,{code:"unknown_field"});return{action:"show-field",field:mo(i),file:{path:dn(o.pmRoot,o.schema)},generated_at:T()}}async function sw(e,t,n){let o=N(process.cwd(),n.path);await be(o);let i;try{let w=cn(e);if(w===void 0)throw new Error(`Type preset name is required. Allowed: ${xt.join(", ")}.`);i=w}catch(w){throw new f(w instanceof Error?w.message:String(w),h.USAGE)}let r=await A(o),a=Y(r.schema),s=Aa(o,a),c=[],l=H(t.author,r.author_default),d=se(r),p=[],u=[],g,y=await Z(o,ln,r.locks.ttl_seconds,l,!!t.force,d.force_required_for_stale_lock,r.locks.wait_ms);try{let w=await U(s),m;try{m=ce(w)}catch(v){throw new f(v instanceof Error?v.message:String(v),h.GENERIC_FAILURE)}let _=m;for(let v of St(i)){let k=Ke(_,v);_=k.file,(k.replaced?u:p).push(k.definition.name)}g=_.definitions.length,await Ce({pmRoot:o,filePath:s,raw:me(_),op:"schema:apply-preset",author:l,settings:r}),await Et(o,St(i),c,"schema:apply-preset-folder"),c.push(...await K({path:s,scope:"project",op:"schema:apply-preset"}))}finally{await y()}return{action:"apply-preset",preset:i,registered:p,replaced:u,file:{path:s,definitions:g},warnings:Pe(c),generated_at:T()}}function ou(e){if(e===void 0)return 10;if(!Number.isInteger(e)||e<1)throw new f("--min-count must be a positive integer (>= 1).",h.USAGE);return e}async function cw(e,t){let n=N(process.cwd(),t.path);await be(n);let o=await A(n),i=Y(o.schema),r=Aa(n,i),a=ou(e.minCount),s=z(o,B()),l=(await De(n,o.item_format,s.type_to_folder,[],i)).map(k=>typeof k.title=="string"?k.title:""),d=xa(l,{minCount:a}),p=[],u=[],g=[],y=[],w;if(!e.apply){let k;try{k=ce(await U(r))}catch(S){throw new f(S instanceof Error?S.message:String(S),h.GENERIC_FAILURE)}return w=k.definitions.length,{action:"infer-types",applied:!1,min_count:a,candidates:d,registered:u,replaced:g,skipped:y,file:{path:r,definitions:w},warnings:p,generated_at:T()}}let m=H(e.author,o.author_default),_=se(o),v=await Z(n,ln,o.locks.ttl_seconds,m,!!e.force,_.force_required_for_stale_lock,o.locks.wait_ms);try{let k=await U(r),S;try{S=ce(k)}catch(G){throw new f(G instanceof Error?G.message:String(G),h.GENERIC_FAILURE)}let R=S;for(let G of d){if(G.shadows_builtin){y.push({name:G.name,reason:"shadows_builtin"});continue}let F;try{F=lt({name:G.name})}catch{y.push({name:G.name,reason:"invalid_type_token"});continue}let E=Ke(R,F);R=E.file,(E.replaced?g:u).push(E.definition.name)}w=R.definitions.length,await Ce({pmRoot:n,filePath:r,raw:me(R),op:"schema:infer-types",author:m,settings:o}),await Et(n,R.definitions.filter(G=>u.includes(G.name)||g.includes(G.name)),p,"schema:infer-types-folder"),p.push(...await K({path:r,scope:"project",op:"schema:infer-types"}))}finally{await v()}return{action:"infer-types",applied:!0,min_count:a,candidates:d,registered:u,replaced:g,skipped:y,file:{path:r,definitions:w},warnings:Pe(p),generated_at:T()}}function lw(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 "${je(e.type.name)}" "<title>"`}function dw(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 pw(e){let t=e.replaced?"Updated":"Registered",n=e.status.roles&&e.status.roles.length>0?` (roles: ${e.status.roles.join(", ")})`:"",o=e.status.aliases&&e.status.aliases.length>0?` (aliases: ${e.status.aliases.join(", ")})`:"";return`${t} status "${e.status.id}"${n}${o} in ${e.file.path}.`}function uw(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 mw(e){let t=[`Schema types: ${e.counts.total} total (${e.counts.builtin} builtin, ${e.counts.custom} custom, ${e.counts.extension} extension)`];for(let[n,o]of[["builtin",e.builtin],["custom",e.custom],["extension",e.extension]])o.length!==0&&t.push(`${n}: ${o.map(i=>i.name).join(", ")}`);t.push(`statuses: ${e.statuses.counts.total} total (${e.statuses.counts.builtin} builtin, ${e.statuses.counts.custom} custom)`);for(let[n,o]of[["builtin statuses",e.statuses.builtin],["custom statuses",e.statuses.custom]])o.length!==0&&t.push(`${n}: ${o.map(i=>i.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(`
|
|
44
|
-
`)}function fw(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(`
|
|
45
|
-
`)}function hw(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(`
|
|
46
|
-
`)}function iu(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 gw(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 yw(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 _w(e){let t=[`Custom fields: ${e.counts.total} total`];for(let n of e.fields)t.push(` ${iu(n)}`);return t.push("Inspect one: pm schema show-field <key>"),t.join(`
|
|
47
|
-
`)}function ww(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(`
|
|
48
|
-
`)}function vw(e){let t=e.registered.length>0?`registered: ${e.registered.join(", ")}`:"",n=e.replaced.length>0?`updated: ${e.replaced.join(", ")}`:"",o=[t,n].filter(i=>i.length>0).join("; ");return`Applied "${e.preset}" type preset to ${e.file.path}${o.length>0?` (${o})`:""}.`}function bw(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 o=n.shadows_builtin?" [shadows built-in, skipped]":"";t.push(` ${n.name} <- "${n.prefix}" (${n.count} items)${o}`)}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(`
|
|
49
|
-
`)}var kw={workflowSlotsReferencing:Ia};(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]="df60255d-fdd6-594a-9e17-547d53f7b3bb")}catch{}})();function fo(e){return e.map(({layer:t,name:n,error:o})=>({layer:t,name:n,error:o}))}function pn(e,t,n){let o=b(t),i=n.trim();if(o.length===0||i.length===0)return;let r=e.get(o)??new Set;r.add(i),e.set(o,r)}function ru(e){let t=new Map,n=new Map;for(let o of e.registrations.commands)pn(t,o.name,o.command),pn(n,o.name,o.action);for(let o of e.commands.handlers)pn(t,o.name,o.command);for(let o of e.commands.overrides)pn(t,o.name,o.command);return{commandPathsByExtension:t,actionPathsByExtension:n}}function Pa(e){if(!(!e||e.size===0))return[...e].sort((t,n)=>t.localeCompare(n))}function au(e){let{enabled:t,normalizedName:n,loadedNames:o,loadFailedNames:i,activationFailedNames:r}=e;return t?i.has(n)||r.has(n)?{runtime_active:!1,activation_status:"failed"}:o.has(n)?{runtime_active:!0,activation_status:"ok"}:{runtime_active:!1,activation_status:"not_loaded"}:{runtime_active:!1,activation_status:"not_loaded"}}function un(e,t,n){let o=new Set(t.loaded.map(c=>b(c.name))),i=new Set(t.failed.map(c=>b(c.name))),r=new Set(n.failed.map(c=>b(c.name))),{commandPathsByExtension:a,actionPathsByExtension:s}=ru(n);return e.map(c=>{let l=b(c.name),d=Pa(a.get(l)),p=Pa(s.get(l)),u={...d?{command_paths:d}:{},...p?{action_paths:p}:{}},g=au({enabled:c.enabled,normalizedName:l,loadedNames:o,loadFailedNames:i,activationFailedNames:r});return{...c,...g,...u}})}function su(e){let t=0,n=0,o=0;for(let i of e)if(i.startsWith("extension_policy_")){if(t+=1,i.startsWith("extension_policy_violation_")){n+=1;continue}i.startsWith("extension_policy_blocked_")&&(o+=1)}return{warning_count:t,violation_count:n,blocked_count:o}}function J(e,t){return e.vocabulary==="package"?`pm package --${t}`:`pm extension --${t}`}var Da=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 cu(e){return Da.has(Ua(e))}function Ra(e){return e==="project"||e==="global"}function ja(e){let t=e.split(":"),n=t[0];if(!n||!Da.has(n))return null;let o=t.at(-4),i=t.at(-3)?.trim(),r=t.at(-2),a=t.at(-1)?.trim();return!Ra(o)||!Ra(r)||!i||!a?null:{code:n,surface:t.slice(1,-4).join(":")||"global",winner:{layer:o,name:i},displaced:{layer:r,name:a}}}function lu(e){let t=new Set;for(let n of e){let o=ja(n);o&&(t.add(o.winner.name),t.add(o.displaced.name))}return[...t].sort((n,o)=>n.localeCompare(o))}function du(e,t){let n=e.filter(cu);if(n.length===0)return null;let o=lu(n);return`Extension registration collisions or handler/override overlaps detected.${o.length>0?` Conflicting extensions: ${o.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 pu(e,t,n,o){let i=t.map(p=>ja(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(i.length===0)return;let r=e==="global"?"--global":"--project",a=J(o,"deactivate"),s=`${J(o,"doctor")} ${r} --detail deep --trace`,c=new Map(n.map(p=>[b(p.name),p])),l=new Map;for(let p of i)for(let u of[p.winner.name,p.displaced.name]){let g=b(u);l.set(g,(l.get(g)??0)+1)}let d=[...l.entries()].map(([p,u])=>{let g=c.get(p),y=g?.name??p,w=g?.command_paths??[],m=g?.action_paths??[];return{action:"deactivate",extension:y,command:`${a} ${y} ${r}`,affected_collisions:u,feature_loss:{command_paths:[...w].sort((_,v)=>_.localeCompare(v)),action_paths:[...m].sort((_,v)=>_.localeCompare(v))}}}).sort((p,u)=>{let g=u.affected_collisions-p.affected_collisions;if(g!==0)return g;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:i.length,extension_count:l.size,next_best_command:s,collisions:i,remediation_candidates:d}}function La(e){let t=[];for(let n of e){let o=n.error.toLowerCase();(o.includes("cannot find package '@unbrained/pm-cli'")||o.includes('cannot find module "@unbrained/pm-cli"')||o.includes("cannot find module '@unbrained/pm-cli'"))&&t.push(`extension_load_failed_sdk_dependency_missing:${n.name}`),(o.includes("cannot use import statement outside a module")||o.includes("to load an es module")||o.includes("must use import to load es module"))&&t.push(`extension_load_failed_module_mode_mismatch:${n.name}`)}return[...new Set(t)].sort((n,o)=>n.localeCompare(o))}function Fa(e=[]){let t=Array.isArray(e)?e:[],n=[];for(let o of t){if(!o||typeof o.name!="string")continue;let i=o.trace?.missing_capability??o.trace?.capability;typeof i=="string"&&i.trim().length>0&&n.push(`extension_capability_missing:${o.name}:${i.trim().toLowerCase()}`)}return[...new Set(n)].sort((o,i)=>o.localeCompare(i))}function Ma(e,t){let n=[];for(let o of Xo(e.loaded,t))for(let i of o.unused)n.push(`extension_capability_unused:${o.layer}:${o.name}:${i}`);return[...new Set(n)].sort((o,i)=>o.localeCompare(i))}var uu=[{matches:e=>e.some(t=>t.startsWith("extension_manifest_")),build:e=>`Run ${J(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: ${Ro.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 ${J(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 ${J(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 ${J(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 ${J(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 ${J(e.options,"doctor")} ${e.scopeFlag}.`},{matches:(e,t)=>t.updateCheckFailedTotal>0,build:e=>`Run ${J(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 mu(e){let{normalizedWarnings:t,options:n,scope:o,scopeFlag:i,updateCheckFailedTotal:r,policyWarningCount:a,unmanagedActionRequiredTotal:s,notCheckedTotal:c,skippedNonGithubTotal:l,updateAvailableTotal:d}=e,p=[],u={options:n,scope:o,scopeFlag:i,updateCheckFailedTotal:r,policyWarningCount:a};if(t.length>0){let g=du(t,{deactivate:`${J(n,"deactivate")} <name> ${i}`,doctor:`${J(n,"doctor")} ${i} --detail deep --trace`});g&&p.push(g);for(let y of uu)y.matches(t,u)&&p.push(y.build(u))}return s>0&&p.push(`Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via ${J(n,"manage")} ${i} --fix-managed-state (or ${J(n,"adopt-all")} ${i}, ${J(n,"adopt")} <name> ${i}, or reinstall via ${J(n,"install")} ${i} <source>).`),l>0&&p.push("Update-check coverage is partial: non-GitHub managed sources were not checked. Inspect their registry or source directly; zero detected updates does not mean these packages are current. Runtime activation health is independent."),c>0&&p.push(`Update-check coverage is partial: some sources have no completed check. Run ${J(n,"manage")} ${i} to request update checks.`),d>0&&p.push(`Update available managed extensions via ${J(n,"install")} ${i} <source>.`),p.length===0&&p.push(`No immediate action required. Re-run ${J(n,"manage")} ${i} after extension changes.`),p}function mn(e,t,n,o={}){let i=[...new Set(t)].sort((E,W)=>E.localeCompare(W)),r=n.filter(E=>E.managed).length,a=n.filter(E=>E.enabled).length,s=n.filter(E=>E.active).length,c=n.filter(E=>E.update_check_status==="checked"&&E.update_available===!0).length,l=n.filter(E=>E.managed===!1),d=l.filter(E=>Na(E)).map(E=>E.name).sort((E,W)=>E.localeCompare(W)),p=l.filter(E=>!Na(E)).map(E=>E.name).sort((E,W)=>E.localeCompare(W)),u={checked:0,skipped_unmanaged:0,skipped_non_github:0,failed:0,not_checked:0};for(let E of n)u[E.update_check_status]+=1;let g=u.failed,y=n.filter(E=>E.update_check_status==="skipped_non_github"&&E.source?.kind!=="builtin").length,w=Object.entries({skipped_unmanaged:p.length,skipped_non_github:y,failed:g,not_checked:u.not_checked}).filter(([,E])=>E>0).map(([E,W])=>`extension_update_health_partial_coverage:${E}:${W}`),m=w.length>0,_=m?"partial":"full",v=[...new Set([...i,...w])].sort((E,W)=>E.localeCompare(W)),k=[...new Set(v.map(E=>Ua(E)))].sort((E,W)=>E.localeCompare(W)),S=su(v),R=e==="global"?"--global":"--project",G=pu(e,i,n,o),F=mu({normalizedWarnings:v,options:o,scope:e,scopeFlag:R,updateCheckFailedTotal:g,policyWarningCount:S.warning_count,unmanagedActionRequiredTotal:p.length,notCheckedTotal:u.not_checked,skippedNonGithubTotal:y,updateAvailableTotal:c});return{status:v.length===0?"ok":"warn",warning_count:v.length,warning_codes:k,warnings:v,policy_warning_count:S.warning_count,policy_violation_count:S.violation_count,policy_blocked_count:S.blocked_count,total_extensions:n.length,managed_total:r,enabled_total:a,active_total:s,update_available_total:c,update_health_coverage:_,update_health_partial:m,unmanaged_loaded_extension_count:l.length,unmanaged_loaded_extensions:l.map(E=>E.name).sort((E,W)=>E.localeCompare(W)),unmanaged_expected_extension_count:d.length,unmanaged_expected_extensions:d,unmanaged_action_required_extension_count:p.length,unmanaged_action_required_extensions:p,update_check_status_totals:u,update_check_failed_total:g,top_warnings:v.slice(0,8),remediation:F,...G?{collision_plan:G}:{}}}function Ga(e){if(!e||e.trim().length===0)return"summary";let t=e.trim().toLowerCase();if(t==="summary"||t==="deep")return t;throw new f(`Invalid --detail value "${e}". Expected summary or deep.`,h.USAGE)}function Ua(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function za(e){let t=new Set,n=[];for(let o of e){let i=(()=>{let r=qo(o);return r?[r]:Wo(o)})();for(let r of i){let a=`${r.layer}:${r.name}:${r.capability}`;t.has(a)||(t.add(a),n.push(r))}}return n}function Ja(){return{version:Ct.version,capabilities:[...Ct.capabilities],legacy_aliases:{...Ct.legacy_aliases}}}function Na(e){let t=b(e.name),n=b(e.directory);return t.startsWith("builtin-")?!0:n==="beads"||n==="todos"}function qa(e,t,n,o,i){if(e!=="project"||i)return{warnings:[],summary:{active_project_count:0,loaded_project_count:0,active_project_names:[],loaded_project_names:[],missing_active_project_names:[]}};let r=[...new Set(t.filter(d=>d.active).map(d=>b(d.name)))].sort((d,p)=>d.localeCompare(p)),a=[...new Set(n.filter(d=>d.layer==="project").map(d=>b(d.name)))].sort((d,p)=>d.localeCompare(p)),s=new Set(o.map(d=>b(d.name))),c=r.filter(d=>!a.includes(d)&&!s.has(d)).sort((d,p)=>d.localeCompare(p));return{warnings:c.length>0?[`extension_doctor_consistency_active_not_loaded:${c.join(",")}`]:[],summary:{active_project_count:r.length,loaded_project_count:a.length,active_project_names:r,loaded_project_names:a,missing_active_project_names:c}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="96a05fa4-b833-56ca-b501-40a427d03201")}catch{}})();var Wa=async(e,t,n)=>{if(!Number.isInteger(t)||t<1)throw new RangeError("concurrency must be a positive integer");let o=new Array(e.length),i=0,r=Array.from({length:Math.min(t,e.length)},async()=>{for(;i<e.length;){let a=i;i+=1,o[a]=await n(e[a])}});return await Promise.all(r),o};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="37f2dced-3b93-5c64-85ae-56e62c95e8eb")}catch{}})();function Ba(e,t){let n=b(e),o=t.find(i=>b(i.name)===n);return{command_paths:[...o?.command_paths??[]].sort((i,r)=>i.localeCompare(r)),action_paths:[...o?.action_paths??[]].sort((i,r)=>i.localeCompare(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]="fcc97434-1ef5-5c47-b491-f00e9d19b2c6")}catch{}})();function Ha(e,t){let n=new Set((t?.loaded??[]).flatMap(r=>(r.activation?.commands?.length??0)>0?[`${r.layer}:${b(r.name)}`]:[])),o=e.services.overrides.filter(r=>r.service==="output_format").filter(r=>r.passThrough!==!0).filter(r=>!n.has(`${r.layer}:${b(r.name)}`)).map(r=>`extension_output_service_override_global:${r.service}:${r.layer}:${r.name}`),i=e.renderers.overrides.filter(r=>(r.commands?.length??0)===0&&r.resultDiscriminator===void 0).map(r=>`extension_output_renderer_override_global:${r.format}:${r.layer}:${r.name}`);return[...new Set([...o,...i])].sort((r,a)=>r.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]="a1803149-25ca-5bb0-a178-afa2d85d2ec9")}catch{}})();var Ka=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=Mt(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,o)=>o.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]="8507f364-e079-5743-a54b-bb3a68ab66d0")}catch{}})();var fu=1e4,hu=(e,t,n)=>{let o=e.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).map(a=>{let[s,c=""]=a.split(/\s+/);return{commit:s,ref:c}}),i=o.find(a=>a.ref.endsWith("^{}"))??o[0];if(!i)return{checked_at:n,available:null,error:"no_remote_reference_found"};let r=t?.trim();return r?{checked_at:n,remote_commit:i.commit,available:i.commit!==r}:{checked_at:n,remote_commit:i.commit,available:null,error:"missing_installed_commit"}},Va=async(e,t=Qt)=>{let n=T();if(e.kind!=="github"||!e.repository)return{checked_at:n,available:null,error:"not_a_github_managed_source"};try{let o=[e.ref?.trim(),"HEAD"].find(Boolean),i=await t(["ls-remote",e.repository,o,`${o}^{}`],void 0,fu);return hu(i,e.commit,n)}catch(o){return{checked_at:n,available:null,error:o instanceof Error?o.message:String(o)}}};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ee1bfa77-6687-578c-9cd6-639fc702c48c")}catch{}})();function Ya(e,t){let n=e.filter(o=>o.result.ok).length;return{installed_all:!t&&n===e.length,installed_count:t?0:n,...t?{dry_run:!0,planned_count:n}:{},failed_count:e.length-n,packages:e.map(({alias:o,result:i})=>{let r=i.details;return{alias:o,ok:i.ok,extension:r.extension,source:r.source,source_resolution:r.source_resolution,install_plan:r.install_plan,dry_run:r.dry_run,destination_path:r.destination_path,activated:r.activated,settings_changed:r.settings_changed,command_paths:r.command_paths,action_paths:r.action_paths,command_discovery:r.command_discovery,verification:r.verification,runtime_activation_status:r.runtime_activation_status,activation_diagnostics:r.activation_diagnostics,warnings:i.warnings}})}}import gu from"node:fs/promises";import yu 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]="b1bf79a0-1f04-590f-b613-45ca1b534d5d")}catch{}})();function _u(e){return typeof e.name=="string"&&e.name.trim().length>0?e.name.trim():"workspace-manifest"}function wu(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 vu(e){let t=yu.join(e,"manifest.json"),n;try{n=await gu.readFile(t,"utf8")}catch(s){if(Ot(s))return{path:t,present:!1,parse_status:"absent",package_metadata_location:"package.json#pm",schema_findings:[],warnings:[],remediation:[]};throw s}let o;try{o=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 o!="object"||o===null||Array.isArray(o))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 i=o,r=Ho(i),a=_u(i);return{path:t,present:!0,parse_status:"valid",package_metadata_location:"package.json#pm",schema_findings:r.findings,warnings:r.findings.map(s=>wu(a,s)),remediation:r.findings.map(s=>s.message)}}function Xa(e){return vu(Fo(e))}import qe from"node:fs/promises";import bu 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]="d7afb9a1-be35-5dfd-a52e-2525598b68d8")}catch{}})();var ho=async e=>qe.readFile(e).catch(t=>{if(rn(t,"ENOENT"))return null;throw t}),Za=async(e,t,n,o,i)=>Ne("extension_install_backup",async()=>{let r=ht(e),a=Go(t),[s,c]=await Promise.all([ho(r),ho(a)]);return o&&await qe.cp(n,i,{recursive:!0,force:!0}),{backupDirectory:i,destinationDirectory:n,destinationExists:o,managedStatePath:r,managedStateContents:s,settingsPath:a,settingsContents:c}}),Qa=async e=>Ne("extension_install_rollback",async()=>{await qe.rm(e.destinationDirectory,{recursive:!0,force:!0}),e.destinationExists&&await qe.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 qe.rm(t,{force:!0}):(await qe.mkdir(bu.dirname(t),{recursive:!0}),await qe.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]="4f8fc1a7-748d-559d-9de8-835d0428c6a7")}catch{}})();var ku=4,os=[["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"]],xu=os.map(([,,e])=>e).filter((e,t,n)=>n.indexOf(e)===t).join(", "),Su={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"},Eu="__pm_native_output",$u=["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"],is=["allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],Iu=["disabled","require_trusted","require_provenance"],rs={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:[]},Au=e=>{let t=e??rs,n={};for(let o of $u)n[o]=te(t[o]??[]);return n},Tu=(e,t)=>{for(let n of is)t[n].length>0&&(e[n]=t[n]);return e},Ou=(e,t)=>{for(let n of Iu)t[n]===!0&&(e[n]=!0);return t.sandbox_profile&&(e.sandbox_profile=t.sandbox_profile),e},Cu=e=>{let t={};for(let n of is)t[n]=te(e[n]??[]);return t},Pu=e=>{let t=typeof e.name=="string"?e.name.trim():"";return t.length===0?null:Tu(Ou({name:t},e),Cu(e))},Ru=e=>(e??[]).map(t=>Pu(t)).filter(t=>t!==null).sort((t,n)=>t.name.localeCompare(n.name)),Nu=e=>{let t=Object.assign({},rs,e??{}),n=Au(e),o=Ru(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:o}},as=async(e,t)=>{let n=[t],o=await Dr(t);o&&n.push(o);let i=[...new Set(n.map(r=>b(r)).filter(r=>r.length>0))];for(let r of i){let a=e.find(c=>b(c.name)===r);if(a)return a;let s=e.find(c=>b(c.directory)===r);if(s)return s}},ss=(e,t)=>{let n=t.trim(),o=new Set(te(e.extensions.enabled));return new Set(te(e.extensions.disabled)).has(n)?!1:o.size===0?!0:o.has(n)},cs=(e,t)=>{let n=t.trim(),o=new Set(te(e.extensions.enabled)),i=new Set(te(e.extensions.disabled)),r=[...o],a=[...i];return i.delete(n),o.size>0&&o.add(n),e.extensions.enabled=[...o].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...i].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==r.join("\0")||e.extensions.disabled.join("\0")!==a.join("\0")},Du=(e,t)=>{let n=t.trim(),o=new Set(te(e.extensions.enabled)),i=new Set(te(e.extensions.disabled)),r=[...o],a=[...i];return o.delete(n),i.add(n),e.extensions.enabled=[...o].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...i].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==r.join("\0")||e.extensions.disabled.join("\0")!==a.join("\0")},ju=(e,t)=>{let n=t.trim(),o=new Set(te(e.extensions.enabled)),i=new Set(te(e.extensions.disabled)),r=[...o],a=[...i];return o.delete(n),i.delete(n),e.extensions.enabled=[...o].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...i].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==r.join("\0")||e.extensions.disabled.join("\0")!==a.join("\0")},Lu=e=>{let t=e.trim().toLowerCase(),n=Math.min(2,Math.max(1,Math.ceil(t.length/4))),o=os.map(([i,r,a])=>({action:r,flag:a,distance:Jo(t,i,n)})).filter(i=>i.distance!==null).sort((i,r)=>i.distance-r.distance)[0];return o?{action:o.action,flag:o.flag}:null},Fu=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",o=Lu(e);if(!o)return new f(`One action flag is required. Use one of: ${xu}. Bare \`pm package\` and \`pm extension\` default to --explore.`,h.USAGE);let i=`pm ${n} ${o.flag}`;return hi({command_path:n,display_name:`${n} lifecycle`,token_kind:"action",token:e,allowed:Object.keys(ls),retry_command:i,message_suffix:`. Did you mean "${o.flag}"?`,fallback_candidates:[{source:"lifecycle_action",command:i,reason:`nearest lifecycle action for "${e}"`}]})},Mu=[["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"]],ls={doctor:"doctor",reload:"reload",catalog:"catalog",init:"init",scaffold:"init",explore:"explore",manage:"manage",migrate:"migrate",list:"explore","":"explore"},Gu=e=>ls[e]??null,Uu=(e,t)=>{let n=[...new Set(Mu.filter(([o])=>t[o]===!0).map(([,o])=>o))];if(n.length===0){if(e===void 0)return"explore";let o=Gu(e.trim().toLowerCase());if(o)return o;throw Fu(e,t)}if(n.length>1)throw new f("Extension action flags are mutually exclusive.",h.USAGE);return n[0]},zu=e=>{let t=e.project===!0||e.local===!0,n=e.global===!0;if(t&&n)throw new f('Options "--project/--local" and "--global" are mutually exclusive.',h.USAGE);return n?"global":"project"},Ju=[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"}}],ds=e=>{for(let t of Ju){let n=t(e);if(n)return n}return{status:"not_checked",reason:"no_update_check_recorded"}},ps=(e,t,n,o)=>{let i=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:i.contributions,managed:!!n,source:i.source,update_available:i.update_available,last_update_check_at:i.last_update_check_at,last_update_remote_commit:i.last_update_remote_commit,update_error:i.update_error,update_check_status:o.status,update_check_reason:o.reason}},qu=(e,t,n,o)=>{let i=Object.assign({name:e,manifest_version:"unknown",manifest_entry:"unknown"},o),r=o?ss(n,o.name):!1;return{warning:`extension_manifest_missing:${t}:${e}`,summary:ps({name:i.name,directory:e,version:i.manifest_version,entry:i.manifest_entry,enabled:r},t,o,ds(o))}},Wu=async(e,t,n,o,i,r)=>{let a=oe.join(e,t),s=oe.join(a,"manifest.json"),c=r.get(b(t));if(!await x(s))return qu(t,n,o,c);let l=Symbol("invalid-extension-manifest-json"),d=await Re.readFile(s,"utf8").then(g=>JSON.parse(g)).catch(()=>l);if(d===l)return{warning:`extension_manifest_invalid_json:${n}:${t}`};let p=Yn(d);if(!p)return{warning:`extension_manifest_invalid:${n}:${t}`};let u=i.get(b(p.name))??r.get(b(t));return{summary:ps({name:p.name,directory:t,version:p.version,entry:p.entry,enabled:ss(o,p.name)},n,u,ds(u))}},ge=async(e,t,n,o)=>{if(!await x(e))return{extensions:[],warnings:[]};let r=(await Re.readdir(e,{withFileTypes:!0})).filter(d=>d.isDirectory()).map(d=>d.name).sort((d,p)=>d.localeCompare(p)),a=new Map(o.entries.map(d=>[b(d.name),d])),s=new Map(o.entries.map(d=>[b(d.directory),d])),c=[],l=[];for(let d of r){let p=await Wu(e,d,t,n,a,s);p.warning&&c.push(p.warning),p.summary&&l.push(p.summary)}return{extensions:l.sort((d,p)=>d.name.localeCompare(p.name)),warnings:c.sort((d,p)=>d.localeCompare(p))}},Bu=Vo(),Hu=(e,t)=>[t.package,t.kind==="builtin"?t.name:void 0].find(n=>n?.trim())?.trim()??e,Ku=(e,t,n,o)=>{let i=n.command_paths.map(s=>`pm ${s} --help`),r=o?.error.toLowerCase().includes("@unbrained/pm-cli")===!0,a=n.command_paths.length>0?[...i]:["Run pm package doctor --project --detail deep if expected package commands are missing."];return r&&a.unshift("Install @unbrained/pm-cli in the target workspace so declarative package runtime imports resolve, then reinstall the package."),{package_name:Hu(e,t),extension_name:e,command_paths:n.command_paths,action_paths:n.action_paths,help_commands:i,next_steps:a,...r?{sdk_dependency_status:"missing"}:{}}},Vu=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(([,o])=>o!==void 0)),t.missing_capability&&(n.missing_capability=t.missing_capability),t.hint&&(n.hint=t.hint)),n},us=e=>e.map(t=>Vu(t)).sort((t,n)=>`${t.layer}:${t.name}`.localeCompare(`${n.layer}:${n.name}`)),ms=(e,t,n)=>{let o=b(e);return t.find(i=>(n===void 0||i.layer===n)&&b(i.name)===o)},Yu=(e,t,n,o)=>n.find(r=>r.scope===t&&b(r.name)===b(e))?.activation_status??(o?"failed":"unknown"),fs=(e,t,n,o,i)=>Bu.enqueue(async()=>{let r=process.env.PM_CLI_PACKAGE_ROOT,a=await Re.mkdtemp(oe.join(t,".pm-module-graph-"));process.env.PM_CLI_PACKAGE_ROOT=ue(import.meta.url,["../.."]);try{let s=await ke({pmRoot:e,settings:n,cwd:process.cwd(),noExtensions:i.noExtensions===!0,reload_token:xn(),cache_bust:!0,module_graph_snapshot_root:a}),c=await xe({...s}),l=[...s.failed.map(p=>({layer:p.layer,name:p.name,entry_path:p.entry_path,error:p.error})),...us(c.failed)],d=Object.fromEntries(s.loaded.map(p=>[b(p.name),zo(Ve(c,{extensionName:p.name}))]));return{installed:un(o,s,c),warnings:[...s.warnings,...c.warnings],activation_failures:l,extensions_disabled:s.disabled_by_flag,item_type_registrations:c.registrations.item_types,contribution_inventories:d}}finally{await Re.rm(a,{recursive:!0,force:!0}),r===void 0?delete process.env.PM_CLI_PACKAGE_ROOT:process.env.PM_CLI_PACKAGE_ROOT=r}}),yo=async(e,t,n,o)=>{let i=n.filter(c=>!c.managed),r=[...i].sort((c,l)=>{let d=c.name.localeCompare(l.name);return d!==0?d:c.directory.localeCompare(l.directory)}),a=o,s=[];for(let c of r){let l=oe.join(e,c.directory),d=await rt(l),p=T(),u={kind:"local",input:c.name,location:l};a=yt(a,{name:d.manifest.name,directory:c.directory,scope:t,manifest_version:d.manifest.version,manifest_entry:d.manifest.entry,capabilities:[...d.manifest.capabilities],contributions:d.manifest.contributions,installed_at:p,updated_at:p,source:u}),s.push({name:d.manifest.name,directory:c.directory,version:d.manifest.version,entry:d.manifest.entry,source:u})}return s.length>0&&await ze(e,a),{state:a,adopted_entries:s,unmanaged_candidates:r,already_managed_count:n.length-i.length}},Xu=(e,t)=>{let n=N(process.cwd(),t.path),o=Rt(n,process.cwd()),i=e==="global"?Mo(process.cwd()):n,r=e==="global"?o.global:o.project;return{pm_root:n,scope:e,settings_root:i,selected_root:r,roots:o}},fn=e=>{let t=[e.gh,e.github].filter(o=>typeof o=="string").map(o=>o.trim()).filter(Boolean),n=[...new Set(t)];if(n.length>1)throw new f('Options "--gh" and "--github" must match when both are provided.',h.USAGE);return n[0]},Zu=e=>Su[e],Qu=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",o=e==="install"?"source":"name",i=`${n} ${o}`,r=Zu(e),a=`<${o}>`,s=`pm ${n} ${r} ${a}`;throw new f(`Action "${e}" requires ${i} input.`,h.USAGE,{code:"missing_lifecycle_target",required:`Provide a ${o} 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 ${o} target`}]}})},hn=(e,t,n={})=>{let o=e?.trim();if(o)return o;if(t==="init")throw new f('Action "init" requires a scaffold target path (for example: pm package init ./my-package or pm extension init ./my-extension).',h.USAGE);return Qu(t,n)},em=(e,t)=>{let n=new Set([...t.registrations.item_types.map(o=>({entry:o,count:o.types.length})),...t.registrations.item_fields.map(o=>({entry:o,count:o.fields.length}))].filter(({count:o})=>o>0).map(({entry:o})=>`${o.layer}:${b(o.name)}`));return e.loaded.filter(o=>(o.activation?.commands??[]).length>0).filter(o=>n.has(`${o.layer}:${b(o.name)}`)).map(o=>`extension_schema_narrow_activation:${o.layer}:${o.name}`).filter((o,i,r)=>r.indexOf(o)===i).sort((o,i)=>o.localeCompare(i))},tm=(e,t)=>{let o=[{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"||e==="install",message:"--dry-run is only valid with --migrate or --install."}].find(i=>i.triggered&&!i.allowed);if(o)throw new f(o.message,h.USAGE)},nm=(e,t,n)=>{let o=String(e??"").trim().toLowerCase(),i=[n.init,n.scaffold].includes(!0);return({doctor:["doctor"],reload:["reload"],catalog:["catalog"],init:i?[]:["init","scaffold"]}[t]??[]).includes(o)?void 0:e},om=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},im=(e,t,n)=>{let o={ok:n,action:e.action,scope:e.scope,roots:om(e),warnings:[...new Set(e.warnings)].sort((i,r)=>i.localeCompare(r)),details:t};return e.action==="doctor"&&Object.defineProperty(o,Eu,{value:!0,enumerable:!1,configurable:!1}),o},_o=async(e,t,n)=>{let o=Uu(e,t);tm(o,t);let i=nm(e,o,t),r=zu(t),a=Xu(r,n),c={action:o,normalizedTarget:i,scope:r,resolvedRoots:a,warnings:[],options:t,global:n},d={...c,withResult:(p,u=!0)=>im(c,p,u)};return await Lm(d)},rm=(e,t)=>{let n=t.vocabulary??"extension",o=e.target_path.replace(/\\/g,"/"),i=Zo(o),r={package:`Install dependencies: cd ${i}, then run "npm install"`,extension:`Install type-check dependencies: cd ${i}, then run "npm install -D typescript @types/node @unbrained/pm-cli"`},a={package:`Validate the package: cd ${i}, then run "npm run typecheck" and "npm test"`,extension:`Type-check the source (optional): cd ${i}, 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."),[r[n],...s,`Install the scaffold: ${st(n==="package"?["install","--project",o]:["extension","--install","--project",o])}`,`Smoke-test command path: pm ${e.command_name}`,a[n],`Run diagnostics: ${n==="package"?"pm package doctor":"pm extension --doctor"} --project --detail summary`]},am=async e=>{let{action:t,normalizedTarget:n,options:o,withResult:i}=e;if([fn(o),o.ref].filter(l=>typeof l=="string").map(l=>l.trim()).filter(Boolean).length>0)throw new f('Action "init" does not accept --gh/--github/--ref options.',h.USAGE);let s=hn(n,t,o),c=await oa(s,o.vocabulary??"extension",o.capability,o.declarative===!0);return i({scaffolded:c.created_directory||c.files.some(l=>l.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:rm(c,o)})},sm=async e=>{let{normalizedTarget:t,resolvedRoots:n,warnings:o,options:i,global:r,withResult:a}=e;if(t!==void 0)throw new f('Action "reload" does not accept a target argument.',h.USAGE);let s=await A(n.settings_root),c=xn(),l=await ke({pmRoot:n.settings_root,settings:s,cwd:process.cwd(),noExtensions:r.noExtensions,reload_token:c,cache_bust:!0});o.push(...l.warnings);let d=await xe(l);o.push(...d.warnings);let p={reload:{token:c,cache_bust:!0,watch:i.watch===!0},loaded_count:l.loaded.length,failed_count:l.failed.length,activated_count:Math.max(0,l.loaded.length-d.failed.length),activation_failed_count:d.failed.length,loaded_extensions:l.loaded.map(u=>({name:u.name,layer:u.layer,version:u.version})),failed_extensions:l.failed.map(u=>({name:u.name,layer:u.layer,error:u.error})),activation_failures:d.failed.map(u=>({name:u.name,layer:u.layer,error:u.error}))};return i.watch===!0&&o.push("extension_reload_watch_hint:watch_mode_requested_non_interactive_single_pass_only"),a(p)},cm=async e=>{let{normalizedTarget:t,scope:n,options:o,global:i,withResult:r}=e;if(typeof t=="string"&&t.length>0&&t!=="catalog")throw new f('Action "catalog" does not accept a package target.',h.USAGE);return r(await jr(n,i,o))},lm=(e,t)=>({kind:"builtin",input:e,location:e,name:e,...t===null?{}:{package:t}}),dm=e=>({kind:"local",input:e.input,location:e.absolute_path}),pm=(e,t)=>({kind:"npm",input:e.input,location:t.resolved_subpath??".",package:t.npm_package,version:t.npm_version}),um=(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}),mm=(e,t,n,o)=>e?lm(e,t):n.kind==="local"?dm(n):n.kind==="npm"?pm(n,o):um(n,o),fm=(e,t,n,o)=>e?e.manifest_version!==t?{installed_at:e.installed_at,updated_at:o}:Tr(e.source,n)?{installed_at:e.installed_at,updated_at:e.updated_at}:{installed_at:e.installed_at,updated_at:o}:{installed_at:o,updated_at:o},hm=async(e,t)=>{let{scope:n,resolvedRoots:o,warnings:i}=e,{validated:r,destinationDirectoryName:a}=t,s=await A(o.settings_root),c=await we(o.selected_root);i.push(...c.warnings);let l=oe.join(o.selected_root,a),d=await x(l),p=await on(r.directory,l);await Re.mkdir(o.selected_root,{recursive:!0});let u=await Re.mkdtemp(oe.join(o.selected_root,".pm-extension-install-backup-")),g=oe.join(u,"destination");try{let y=await Za(o.selected_root,o.settings_root,l,d,g),w=mm(t.bundledAliasName,t.bundledPackageName,t.installSource,t.resolvedSource),m=c.state.entries.find(S=>b(S.name)===b(r.manifest.name)),_=fm(m,r.manifest.version,w,T()),v=yt(c.state,{name:r.manifest.name,directory:a,scope:n,manifest_version:r.manifest.version,manifest_entry:r.manifest.entry,capabilities:[...r.manifest.capabilities],contributions:r.manifest.contributions,..._,source:w}),k=cs(s,r.manifest.name);try{p||await _a(r.directory,l),await ha(l),await ga(l),await ze(o.selected_root,v),k&&await Ee(o.settings_root,s,"settings:write")}catch(S){try{await Qa(y)}catch(R){throw new AggregateError([S,R],`Extension install failed: ${String(S)}; rollback failed: ${String(R)}`,{cause:R})}throw S}return{settings:s,managedState:v,sourceRecord:w,destinationDirectory:l,destinationExists:d,installInPlace:p,activationChanged:k}}finally{await Re.rm(u,{recursive:!0,force:!0}).catch(()=>{})}},gm=async(e,t,n)=>{let o=n.filter(i=>b(i.name)===b(t)).flatMap(i=>i.types.map(r=>({name:r.name,folder:r.folder})));return e.scope==="project"&&o.length>0&&await Et(e.resolvedRoots.pm_root,o,e.warnings,"install:type-folder"),o},ym=(e,t,n,o,i)=>{let r=ms(t,n.activation_failures,e.scope),a=Yu(t,e.scope,n.installed,r),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:r,verification:{status:c[String(s)].status,target_pm_root:e.resolvedRoots.pm_root,activation_status:a,activated:s,registered_commands:o.command_paths,registered_actions:o.action_paths,registered_item_types:i,module_graph_verification:"fresh_in_topology_snapshot",health:c[String(s)]}}},_m=async(e,t)=>{let{scope:n,resolvedRoots:o,warnings:i,global:r,withResult:a}=e,{validated:s,destinationDirectoryName:c}=t,l=await hm(e,t),d=await ge(o.selected_root,n,l.settings,l.managedState);i.push(...d.warnings);let p=await fs(o.pm_root,oe.dirname(o.selected_root),l.settings,d.extensions,r);i.push(...p.warnings);let u=await gm(e,s.manifest.name,p.item_type_registrations),g=Ba(s.manifest.name,p.installed),y=ym(e,s.manifest.name,p,g,u),w=p.contribution_inventories[b(s.manifest.name)];return w&&(l.managedState=await Or(o.selected_root,l.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:l.sourceRecord,source_resolution:t.sourceResolution,...t.installPlan?{install_plan:t.installPlan}:{},destination_path:l.destinationDirectory,overwritten:[l.destinationExists,!l.installInPlace].every(Boolean),installed_in_place:l.installInPlace,activated:y.activated,settings_changed:l.activationChanged,runtime_activation_status:y.status,command_paths:g.command_paths,action_paths:g.action_paths,contributions:w,command_discovery:Ku(s.manifest.name,l.sourceRecord,g,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)},wm=async e=>{let{options:t,global:n,warnings:o,withResult:i}=e;if(typeof t.ref=="string"&&t.ref.trim().length>0)throw new f('Action "install all" does not accept --ref.',h.USAGE);let r=[],a=new Map;for(let s of await Zt()){let c=await _t(s),l=oe.resolve(c),d=a.get(l);d===void 0&&(d=await _o(s,{...t,install:!0},n),a.set(l,d)),r.push({alias:s,result:d})}return o.push(...r.flatMap(s=>s.result.warnings)),i(Ya(r,t.dryRun===!0),r.every(s=>s.result.ok))},vm=async(e,t,n)=>{let{resolvedRoots:o}=e,{bundledAliasName:i,bundledPackageName:r,installSource:a,sourceResolution:s}=await ka(t,n,e.options.ref);if(s.ambiguous){let l=s.candidates.find(d=>d.kind==="npm");e.warnings.push(`extension_install_source_ambiguous:${t}:builtin:${i}:npm:${l.package}`)}let c=await Wr(a);try{let l=await rt(c.directory,{source_kind:a.kind,source_input:a.input,source_root:c.source_root}),d=Yt(l.manifest.name),p=e.options.dryRun===!0||a.kind==="local"&&i===null?await va(c,oe.join(o.selected_root,d),e.scope,e.options.copyPlan):void 0;return e.options.dryRun===!0?e.withResult({dry_run:!0,installed:!1,activated:!1,extension:{name:l.manifest.name,version:l.manifest.version},source_resolution:s,install_plan:p}):await po(o.settings_root,d,()=>_m(e,{validated:l,destinationDirectoryName:d,bundledAliasName:i,bundledPackageName:r,sourceResolution:s,installSource:a,resolvedSource:c,installPlan:p}))}finally{c.cleanup&&await c.cleanup()}},bm=async e=>{let t=fn(e.options),n=t??hn(e.normalizedTarget,e.action,e.options);return[t===void 0,Pr(n)].every(Boolean)?wm(e):vm(e,n,t)},km=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:o,warnings:i,options:r,withResult:a}=e;if(t!==void 0)throw new f('Action "adopt-all" does not accept a target argument.',h.USAGE);if(fn(r)!==void 0||typeof r.ref=="string"&&r.ref.trim().length>0)throw new f('Action "adopt-all" does not accept --gh/--github/--ref options.',h.USAGE);let c=await A(o.settings_root),l=await we(o.selected_root);i.push(...l.warnings);let d=await ge(o.selected_root,n,c,l.state);i.push(...d.warnings);let p=await yo(o.selected_root,n,d.extensions,l.state),u=await ge(o.selected_root,n,c,p.state);i.push(...u.warnings);let g=mn(n,i,u.extensions,r);i.push(...g.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{..._,...hs(k)}});return a({adopted_all:m.length>0,adopted_count:m.length,already_managed_count:p.already_managed_count,extensions:m,triage:g,warning_codes:g.warning_codes,update_health_partial:g.update_health_partial,update_health_coverage:g.update_health_coverage})},hs=e=>({update_check_status:e?.update_check_status??null,update_check_reason:e?.update_check_reason??null}),xm=(e,t,n,o)=>{if(e===void 0)return{kind:"local",input:t,location:n};let i=tn(e,{forceGithub:!0,ref:o});if(i.kind!=="github")throw new f(`Invalid GitHub shorthand "${e}".`,h.USAGE);return{kind:"github",input:i.input,location:i.subpath??".",repository:i.repository,owner:i.owner,repo:i.repo,ref:i.ref,subpath:i.subpath}},Sm=async e=>{let{action:t,normalizedTarget:n,scope:o,resolvedRoots:i,warnings:r,options:a,withResult:s}=e,c=hn(n,t,a),l=fn(a),d=await A(i.settings_root),p=await we(i.selected_root);r.push(...p.warnings);let u=await ge(i.selected_root,o,d,p.state);r.push(...u.warnings);let g=await as(u.extensions,c);if(!g)throw new f(`Installed extension "${c}" was not found in ${o} scope.`,h.NOT_FOUND);if(g.managed)return s({adopted:!1,already_managed:!0,extension:{name:g.name,directory:g.directory}});let y=oe.join(i.selected_root,g.directory),w=await rt(y),m=T(),_=xm(l,c,y,a.ref),v=yt(p.state,{name:w.manifest.name,directory:g.directory,scope:o,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 ze(i.selected_root,v);let k=await ge(i.selected_root,o,d,v);r.push(...k.warnings);let S=k.extensions.find(R=>b(R.name)===b(w.manifest.name))??k.extensions.find(R=>b(R.directory)===b(g.directory));return s({adopted:!0,extension:{name:w.manifest.name,directory:g.directory,version:w.manifest.version,entry:w.manifest.entry},source:_,...hs(S)})},gs=async e=>{let{action:t,normalizedTarget:n,scope:o,resolvedRoots:i,warnings:r,options:a}=e,s=hn(n,t,a),c=await A(i.settings_root),l=await we(i.selected_root);r.push(...l.warnings);let d=await ge(i.selected_root,o,c,l.state);r.push(...d.warnings);let p=await as(d.extensions,s);if(!p)throw new f(`Installed extension "${s}" was not found in ${o} scope.`,h.NOT_FOUND);return{settings:c,managedStateRead:l,candidate:p}},Em=async e=>{let{resolvedRoots:t,withResult:n}=e,{settings:o,managedStateRead:i,candidate:r}=await gs(e),a=oe.join(t.selected_root,r.directory);await Re.rm(a,{recursive:!0,force:!0});let s={...i.state,updated_at:T(),entries:i.state.entries.filter(l=>b(l.name)!==b(r.name)&&b(l.directory)!==b(r.directory))};await ze(t.selected_root,s);let c=ju(o,r.name);return c&&await Ee(t.settings_root,o,"settings:write"),n({removed:!0,extension:{name:r.name,directory:r.directory},destination_path:a,settings_changed:c})},es=async e=>{let{action:t,resolvedRoots:n,warnings:o,global:i,withResult:r}=e,{settings:a,candidate:s}=await gs(e),c=t==="activate"?cs(a,s.name):Du(a,s.name);c&&await Ee(n.settings_root,a,"settings:write");let l=t==="activate"?await fs(n.pm_root,oe.dirname(n.selected_root),a,[s],i).then(d=>(o.push(...d.warnings),ms(s.name,d.activation_failures,e.scope))):void 0;return l&&o.push(`extension_activate_failed:${e.scope}:${s.name}`),r({extension:{name:s.name,directory:s.directory},active:t==="activate"&&l===void 0,runtime_active:t==="activate"&&l===void 0,activation_failure:l??null,settings_changed:c,settings:{enabled:[...a.extensions.enabled],disabled:[...a.extensions.disabled]}},l===void 0)},$m=(e,t,n,o,i,r)=>{let a=o==="package"?"package":"extension",s={package:"doctor",extension:"--doctor"}[a],c=i?.adopted_entries.length??0,l=[[r!==null,r??""],[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,...l.filter(([d])=>d).map(([,d])=>d)].map(d=>d.trim()).filter(d=>d.length>0))]},go=e=>e.loaded.some(t=>t.layer==="global")||e.failed.some(t=>t.layer==="global")||e.warnings.some(t=>t.includes(":global:")),Im=(e,t,n,o)=>{if(e!=="project"||t||!go(o))return null;let i=n==="package"?"package":"extension";return`Global ${i} registrations are included in project diagnostics. For hermetic ${i} smoke tests, rerun pm ${i} doctor --project --isolated --detail deep --trace, or set PM_GLOBAL_PATH to a temporary directory for the whole test process.`},Am=(e,t,n)=>{if(String(e??"").trim().length>0)throw new f('Action "doctor" does not accept a target argument.',h.USAGE);let o=[n.isolated,n.ignoreGlobal].includes(!0);if([o,t==="global"].every(Boolean))throw new f("--isolated and --ignore-global are only valid with project-scope doctor diagnostics.",h.USAGE);let i=Ga(n.detail),r=n.trace===!0;if([r,i!=="deep"].every(Boolean))throw new f("--trace requires --detail deep with --doctor.",h.USAGE);return{isolated:o,detailMode:i,includeTrace:r}},Tm=async(e,t,n)=>{if(e.options.fixManagedState!==!0)return{state:n,fix:null};let o=await yo(e.resolvedRoots.selected_root,e.scope,t,n);return{state:o.state,fix:o}},Om=(e,t,n,o)=>{let i=n==="package"?"package":"extension";if(e!=="project")return{isolated:t,global_extensions_included:!1,global_diagnostics_present:go(o),rerun_command:null,pm_global_path_recipe:null};let r=`pm ${i} doctor --project --isolated --detail deep --trace`;return{isolated:t,global_extensions_included:!t,global_diagnostics_present:go(o),rerun_command:t?null:r,pm_global_path_recipe:`PM_GLOBAL_PATH=$(mktemp -d) pm ${i} doctor --project --detail deep --trace`}},Cm=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:o,warnings:i,options:r,global:a,withResult:s}=e,{isolated:c,detailMode:l,includeTrace:d}=Am(t,n,r),p=await A(o.settings_root),u=await we(o.selected_root);i.push(...u.warnings);let g=await ge(o.selected_root,n,p,u.state);i.push(...g.warnings);let{state:y,fix:w}=await Tm(e,g.extensions,u.state),m=await ge(o.selected_root,n,p,y);i.push(...m.warnings);let _=await ke({pmRoot:o.pm_root,settings:p,cwd:process.cwd(),noExtensions:a.noExtensions===!0,ignoreGlobalExtensions:c}),v=await xe({..._,loaded:_.loaded}),k=await Xa(o.pm_root);i.push(...k.warnings,..._.warnings),i.push(...La(_.failed)),i.push(...v.warnings),i.push(...Fa(v.failed)),i.push(...Ma(_,v)),i.push(...Ha(v,_)),i.push(...em(_,v)),i.push(...Ka(v));let S=un(m.extensions,_,v),R=qa(n,S,_.loaded.map(O=>({layer:O.layer,name:O.name})),_.failed.map(O=>({name:O.name})),_.disabled_by_flag);i.push(...R.warnings);let G=S.filter(O=>O.update_check_status==="failed").map(O=>`extension_update_check_failed:${O.name}`);i.push(...G);let F=mn(n,i,S,r);i.push(...F.warnings);let E=[...F.warnings],W={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},at=za(E),yn=Ja(),To=F.warning_codes,Ys=Im(n,c,r.vocabulary,_),Xs=$m(F.remediation,_.failed.length,v.failed.length,r.vocabulary,w,Ys),Oo=Om(n,c,r.vocabulary,_),Zs={status:F.status,scope:n,warning_count:F.warning_count,warning_codes:To,total_extensions:S.length,managed_total:S.filter(O=>O.managed).length,enabled_total:S.filter(O=>O.enabled).length,active_total:S.filter(O=>O.active).length,unmanaged_loaded_extension_count:F.unmanaged_loaded_extension_count,unmanaged_action_required_extension_count:F.unmanaged_action_required_extension_count,unmanaged_expected_extension_count:F.unmanaged_expected_extension_count,runtime_active_total:S.filter(O=>O.runtime_active===!0).length,activation_status_totals:{ok:S.filter(O=>O.activation_status==="ok").length,failed:S.filter(O=>O.activation_status==="failed").length,not_loaded:S.filter(O=>O.activation_status==="not_loaded").length,unknown:S.filter(O=>O.activation_status==="unknown").length},unknown_capability_count:at.length,capability_contract_version:yn.version,update_available_total:F.update_available_total,update_check_status_totals:F.update_check_status_totals,update_health_coverage:F.update_health_coverage,update_health_partial:F.update_health_partial,update_check_failed_total:S.filter(O=>O.update_check_status==="failed").length,load_failure_count:_.failed.length,activation_failure_count:v.failed.length,load_failures:fo(_.failed),activation_failures:fo(v.failed),blocking_failure_count:_.failed.length+v.failed.length,has_blocking_failures:_.failed.length+v.failed.length>0,consistency_warning_count:R.warnings.length,trace_enabled:d,isolation:Oo,policy:W,remediation:Xs},Qs=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(O=>O.name)}:{requested:!1,applied:!1,adopted_count:0,already_managed_count:m.extensions.filter(O=>O.managed).length,adopted_extensions:[]},_n={mode:l,summary:Zs,triage:F,trace_enabled:d,capability_contract:yn,capability_guidance:at,managed_state_fix:Qs,author_manifest:k,isolation:Oo,policy:_.policy};if(l==="deep"){let O=d?v.failed:v.failed.map(D=>{let{trace:kf,...ec}=D;return ec});_n.deep={warnings:E,warning_codes:To,capability_contract:yn,capability_guidance:at,trace_enabled:d,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(D=>({layer:D.layer,directory:D.directory,name:D.name,version:D.version,entry:D.entry,priority:D.priority}))},activation:{failed:O,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:R.summary},d&&(_n.deep.trace={activation_failures:v.failed.filter(D=>D.trace!==void 0).map(D=>({layer:D.layer,name:D.name,entry_path:D.entry_path,error:D.error,method:D.trace.method,command:D.trace.command,capability:D.trace.capability,missing_capability:D.trace.missing_capability,registration_index:D.trace.registration_index,expected_schema:D.trace.expected_schema,hint:D.trace.hint,received:D.trace.received}))})}return s(_n)},Pm=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:o,warnings:i,options:r,global:a,withResult:s}=e,c=await A(o.settings_root),l=await ke({pmRoot:o.pm_root,settings:c,cwd:process.cwd(),noExtensions:a.noExtensions===!0}),d=await xe(l);i.push(...l.warnings),i.push(...d.warnings);let p=ca(t,l,d);if(t!==void 0&&p.extensions.length===0){let u=r.vocabulary==="package"?"package":"extension",g=[...new Set(l.loaded.map(w=>r.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=g.length>0?` Loaded ${u} names: ${g.join(", ")}.`:"";throw new f(`No loaded ${u} named "${t}" was found in ${n} scope.${y} Run pm ${u} explore to list discovered ${u}s.`,h.NOT_FOUND)}return s({target:p.target,total:p.total,extensions:p.extensions,union:p.union,command_ownership:p.command_ownership})},Rm=async(e,t,n)=>{let o=n,i=null;if([e.action==="manage",e.options.fixManagedState===!0].every(Boolean)&&(i=await yo(e.resolvedRoots.selected_root,e.scope,t,n),o=i.state),e.action==="manage"){let r=await Wa(o.entries,ku,async a=>{if(a.source.kind!=="github")return a;let s=await Va(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}});o={...o,updated_at:T(),entries:gt(r)},await ze(e.resolvedRoots.selected_root,o)}return{state:o,fix:i}},Nm=async(e,t,n)=>{let o=await ke({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),i=await xe({...o,loaded:o.loaded});return e.warnings.push(...o.warnings,...i.warnings),{installed:un(n,o,i),failures:us(i.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:o.failed.length,activation_failure_count:i.failed.length,warning_count:[...new Set([...o.warnings,...i.warnings])].length,policy:o.policy}}},Dm=(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},ts=async e=>{let{action:t,scope:n,resolvedRoots:o,warnings:i,options:r,withResult:a}=e,s=await A(o.settings_root),c=Nu(s.extensions.policy),l=await we(o.selected_root);i.push(...l.warnings);let d=await ge(o.selected_root,n,s,l.state);i.push(...d.warnings);let{state:p,fix:u}=await Rm(e,d.extensions,l.state),g=await ge(o.selected_root,n,s,p);if(i.push(...g.warnings),t==="manage"){let v=g.extensions.filter(k=>k.update_check_status==="failed").map(k=>`extension_update_check_failed:${k.name}`);i.push(...v)}let y=await Nm(e,s,g.extensions),w=y.installed,m=mn(n,i,w,r);i.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=Dm(u,w)),a(_)},ns={init:am,install:bm,uninstall:Em,explore:ts,manage:ts,describe:Pm,reload:sm,doctor:Cm,catalog:cm,adopt:Sm,"adopt-all":km,activate:es,deactivate:es,migrate:Pi},jm=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),Lm=e=>jm(e)?po(e.resolvedRoots.settings_root,`${e.action}-state`,()=>ns[e.action](e)):ns[e.action](e);import bo from"node:fs/promises";import q from"node:path";import ys from"node:readline/promises";import{stdin as _s,stdout as It}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]="f0c60332-623f-52c0-b217-acb15fcd2218")}catch{}})();var ws=["ask","add","skip","status"],Fm=["AGENTS.md","CLAUDE.md"],Mm=["pm init","pm context","pm search","pm create","pm claim","pm files","pm docs","pm test --run","pm close","pm release","pm_author"],Gm=8,ko=1,Um="<!-- pm-cli:agent-guidance:start:",zm=`<!-- pm-cli:agent-guidance:start:v${ko} -->`,wo="<!-- pm-cli:agent-guidance:end -->",Tt="Add workflow guidance later: pm init --agent-guidance add",qv={toPortableRelativePath:We,ensureTrailingNewline:vo,detectLineEnding:bs,findGuidanceBlockRange:xo,buildAgentGuidanceBlock:ks,upsertAgentGuidanceBlock:So,resolveProjectRoot:Ss,resolveTargetGuidancePath:Es,parsePromptChoice:$s,pushUnique:Be,promptForGuidanceWrite:Is,normalizeAgentGuidanceState:Eo,applyAgentGuidanceState:Ts,writeGuidanceFile:$o,setAgentGuidanceReadlineFactoryForTests:Jm},vs=()=>ys.createInterface({input:_s,output:It});function Jm(e){vs=e??(()=>ys.createInterface({input:_s,output:It}))}function We(e,t){let n=q.relative(e,t);return n.length===0?q.basename(t):n.split(q.sep).join("/")}function vo(e){return e.endsWith(`
|
|
50
|
-
`)?e:`${e}
|
|
51
|
-
`}function bs(e){return e.includes(`\r
|
|
52
|
-
`)?`\r
|
|
53
|
-
`:`
|
|
54
|
-
`}function xo(e){let t=e.indexOf(Um);if(t===-1)return null;let n=e.indexOf(wo,t);return n===-1?null:{start_index:t,end_index:n+wo.length}}function qm(e){return xo(e)!==null}function ks(e,t="<your project test command>"){return[zm,"## 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 start atomically: `pm claim <id> --start`.",`- 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.","",wo,""].join(e)}function So(e,t="<your project test command>"){let n=bs(e),o=ks(n,t),i=xo(e);if(i){let s=e.slice(i.end_index),c=s.startsWith(`\r
|
|
55
|
-
`)?s.slice(2):s.startsWith(`
|
|
56
|
-
`)?s.slice(1):s,l=vo(`${e.slice(0,i.start_index)}${o}${c}`);return{next_content:l,changed:l!==e}}let r=e.length===0?"":e.endsWith(`
|
|
57
|
-
`)?`
|
|
58
|
-
`:`
|
|
59
|
-
|
|
60
|
-
`,a=vo(`${e}${r}${o}`);return{next_content:a,changed:a!==e}}async function xs(e){if(await x(q.join(e,"scripts","run-tests.mjs")))return"node scripts/run-tests.mjs test";let t;try{t=JSON.parse(await bo.readFile(q.join(e,"package.json"),"utf8"))}catch{return"<your project test command>"}let n=Wm(t);if(n===void 0)return"<your project test command>";let o=n.packageManager?.split("@")[0];return o==="pnpm"?"pnpm test":o==="bun"?"bun run test":o==="yarn"?"yarn test":o==="npm"?"npm test":await x(q.join(e,"pnpm-lock.yaml"))?"pnpm test":await x(q.join(e,"bun.lock"))||await x(q.join(e,"bun.lockb"))?"bun run test":await x(q.join(e,"yarn.lock"))?"yarn test":"npm test"}function Wm(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 Ss(e,t){let n=q.dirname(e);return q.basename(e)==="pm"&&q.basename(n)===".agents"?q.dirname(n):q.resolve(t,e)}function Es(e,t){let n=e.find(i=>q.basename(i.file_path)==="AGENTS.md"&&i.exists);if(n)return n.file_path;let o=e.find(i=>i.exists);return o?o.file_path:q.join(t,"AGENTS.md")}function $s(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 Is(e){let t=vs();try{It.write(`
|
|
61
|
-
Agent guidance check
|
|
62
|
-
`),It.write(`No AGENTS.md/CLAUDE.md file currently contains compact pm workflow guidance.
|
|
63
|
-
`);let n=await t.question(`Add a compact pm workflow section to ${e}? [Y/n] `);return It.write(`
|
|
64
|
-
`),$s(n,!0)}finally{t.close()}}function Eo(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:ko,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,o)=>n.localeCompare(o)):[]}}async function As(e){let t=[],n=await xs(e);for(let o of Fm){let i=q.join(e,o),r=await x(i);if(!r){t.push({file_path:i,exists:r,has_guidance:!1,has_marker:!1});continue}let a=await bo.readFile(i,"utf8"),s=a.toLowerCase(),c=Mm.filter(d=>s.includes(d)),l=qm(a);t.push({file_path:i,exists:r,has_guidance:l||c.length>=Gm,has_marker:l,outdated:l&&So(a,n).changed})}return t}function Be(e,t){e.includes(t)||e.push(t)}function Ts(e,t){let n=Eo(e),o=JSON.stringify(n)!==JSON.stringify(t);return o&&(e.agent_guidance=t),{changed:o,state:t}}async function $o(e,t=q.dirname(e)){let o=await x(e)?await bo.readFile(e,"utf8"):"",i=So(o,await xs(t));return i.changed?(await ae(e,i.next_content),{changed:!0,warnings:await K({path:e,scope:"project",op:"init:agent_guidance_file"})}):{changed:!1,warnings:[]}}function Bm(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=>We(e.projectRoot,t.file_path)),files_with_guidance:e.scans.filter(t=>t.has_guidance).map(t=>We(e.projectRoot,t.file_path)),missing_files:e.scans.filter(t=>!t.exists).map(t=>We(e.projectRoot,t.file_path))}}async function Hm(e,t,n){return e?await As(n):t}function At(e,t,n){e.state={...e.state,...n,template_version:ko,last_checked_files:t}}async function Os(e,t){if(t.presentBefore)return;let n=await $o(t.targetPath,t.projectRoot);e.warnings.push(...n.warnings),n.changed&&(e.applied=!0,e.warnings.push(`agent_guidance:added:${t.targetRelativePath}`))}function Km(e,t){t||(e.warnings.push("agent_guidance:missing"),Be(e.nextSteps,Tt))}function Vm(e,t){e.skipped=!0,At(e,t,{prompt_completed:!0,declined:!0,declined_at:e.state.declined_at||new Date().toISOString()}),e.warnings.push("agent_guidance:explicit_skip"),Be(e.nextSteps,Tt)}async function Ym(e,t){await Os(e,t),At(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""})}function Xm(e,t){e.state.declined&&At(e,t,{prompt_completed:!0,declined:!1,declined_at:""})}function Zm(e){e.skipped=!0,e.warnings.push("agent_guidance:skipped_declined"),Be(e.nextSteps,Tt)}async function Qm(e,t){if(e.prompted=!0,await Is(t.targetRelativePath)){await Os(e,t),At(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""});return}e.skipped=!0,At(e,t.checkedFiles,{prompt_completed:!0,declined:!0,declined_at:new Date().toISOString()}),e.warnings.push("agent_guidance:declined"),Be(e.nextSteps,Tt)}function ef(e){e.warnings.push("agent_guidance:missing_non_interactive"),Be(e.nextSteps,Tt)}async function tf(e,t){let n={warnings:[],nextSteps:[],prompted:!1,applied:!1,skipped:!1,state:e};return t.mode==="status"?(Km(n,t.presentBefore),n):t.mode==="skip"?(Vm(n,t.checkedFiles),n):t.mode==="add"?(await Ym(n,t),n):t.presentBefore?(Xm(n,t.checkedFiles),n):n.state.prompt_completed&&n.state.declined?(Zm(n),n):t.interactive?(await Qm(n,t),n):(ef(n),n)}async function Cs(e){let t=Ss(e.pm_root,e.cwd),n=await As(t),o=Es(n,t),i=We(t,o),r=n.map(p=>We(t,p.file_path)),a=n.some(p=>p.has_guidance),s=await tf(Eo(e.settings),{mode:e.mode,interactive:e.interactive,targetPath:o,targetRelativePath:i,checkedFiles:r,presentBefore:a,projectRoot:t});if(e.mode==="add")for(let p of n.filter(u=>u.outdated)){let u=await $o(p.file_path,t);s.applied||=u.changed,s.warnings.push(...u.warnings)}let c=Ts(e.settings,s.state);n=await Hm(s.applied,n,t);let l=n.filter(p=>p.outdated).map(p=>We(t,p.file_path));return l.length>0&&(s.warnings.push(`agent_guidance_outdated:${l.join(",")}`),Be(s.nextSteps,"pm init --agent-guidance add")),{summary:Bm({mode:e.mode,scans:n,projectRoot:t,targetRelativePath:i,prompted:s.prompted,applied:s.applied,skipped:s.skipped,state:s.state}),warnings:s.warnings,next_steps:s.nextSteps,settings_changed:c.changed}}import nf from"node:fs/promises";import L from"node:path";import Rs from"node:readline/promises";import{stdin as Ns,stdout as ee}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]="231597cc-2166-5029-9b3a-476587a33941")}catch{}})();var of=Symbol.for("pm.sdk.init-invocation-cwd");function fb(e,t=!1){if(t){let n=e.warnings.filter(o=>!/^(?:already_exists:|updated:|registered_type_preset:)/u.test(o));return{ok:e.ok,path:e.path,governance_preset:e.governance_preset,telemetry:`${e.settings.telemetry.enabled?"enabled":"disabled"} (${e.settings.telemetry.capture_level})`,created_count:e.created_dirs.length,next_steps:e.next_steps.slice(0,3),...n.length>0?{warnings:n.join("; ")}:{},details:`${st(["--pm-path",e.path,"init","--verbose"])} for full setup details and notices (or --json)`}}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 hb={normalizeInitGovernancePreset:Io,normalizeInitTypePreset:js,normalizeOptionalInitAuthor:Ls,normalizeInitAgentGuidanceMode:Gs,isPathLikeInitTarget:gn,resolveInitInvocation:Fs,resolveInitPrefixInput:Ms,parseYesNoChoice:Us,applyGovernancePreset:Ao,runInitWizard:Hs,setInitReadlineFactoryForTests:rf,summarizeInstalledPackages:zs,buildInitNextSteps:Ks,registerInitTypePreset:Js,assertExplicitTrackerPathIsNotWorkspaceRoot:Ws,isLikelyWorkspaceRoot:qs,installInitMergeFence:Vs},Ds=()=>Rs.createInterface({input:Ns,output:ee});function rf(e){Ds=e??(()=>Rs.createInterface({input:Ns,output:ee}))}function af(){return structuredClone(vn)}var sf=["minimal","default","strict"];function Io(e){if(e===void 0)return;let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new f("--preset must not be empty",h.USAGE);if(t==="minimal"||t==="default"||t==="strict")return t;if(t==="lite"||t==="minimum")return"minimal";throw new f(`Invalid --preset value "${e}". Allowed: ${sf.join(", ")}`,h.USAGE)}function js(e){if(e!==void 0){if(e.trim().length===0)throw new f("--type-preset must not be empty",h.USAGE);try{return cn(e)}catch{throw new f(`Invalid --type-preset value "${e}". Allowed: ${xt.join(", ")}`,h.USAGE)}}}function Ls(e){if(e===void 0)return;let t=e.trim();if(t.length===0)throw new f("--author must not be empty",h.USAGE);return t}function gn(e){if(e===void 0)return!1;let t=e.trim();return t.length===0?!1:L.isAbsolute(t)||/^[a-z]:/iu.test(t)||t.startsWith(".")||t.includes("/")||t.includes("\\")}function Fs(e,t,n,o){let i=o?.trim();if(o!==void 0&&i?.length===0)throw new f("--workspace must not be empty",h.USAGE);if(i!==void 0){if(t.path!==void 0||gn(n))throw new f("--workspace cannot be combined with --pm-path/--path or a path-like positional target.",h.USAGE);let l=L.resolve(e,i),d=L.join(l,".agents","pm");return{pmRoot:d,prefixArg:n,target:{mode:"workspace-path",tracker_root:d,workspace_root:l}}}if(t.path===void 0&&gn(n)){let l=L.resolve(e,n.trim());return{pmRoot:l,prefixArg:void 0,target:{mode:"tracker-path",tracker_root:l}}}let r=N(e,t.path),a=L.join(L.resolve(e),".agents","pm"),s=L.dirname(L.dirname(r)),c=L.resolve(r)===a?"current":"ancestor";return{pmRoot:r,prefixArg:n,target:t.path===void 0?{mode:"workspace-discovery",tracker_root:r,workspace_root:s,discovery:c,requested_cwd:L.resolve(e),...c==="ancestor"?{suggested_current_tracker_root:a}:{}}:{mode:"tracker-path",tracker_root:r}}}function Ms(e,t){if(t===void 0)return e;if(t.trim().length===0)throw new f("--id-prefix must not be empty",h.USAGE);if(gn(t))throw new f(`--id-prefix accepts an item ID prefix, not a tracker path: "${t}".`,h.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&&$e(e)!==$e(t))throw new f(`Conflicting id prefixes: positional "${e}" and --id-prefix "${t}".`,h.USAGE,{code:"init_id_prefix_conflict",required:"Use either the positional id prefix or --id-prefix with one value.",examples:[`pm init ${$e(e)}`,`pm init --id-prefix ${$e(t)}`]});return t}function Gs(e){if(e===void 0)return"ask";let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new f("--agent-guidance must not be empty",h.USAGE);if(t==="ask"||t==="add"||t==="skip"||t==="status")return t;throw new f(`Invalid --agent-guidance value "${e}". Allowed: ${ws.join(", ")}`,h.USAGE)}function Us(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}function Ao(e,t){let n=Do[t];e.governance={preset:t,...n},e.validation.parent_reference=n.parent_reference,e.validation.metadata_profile=n.metadata_profile}function cf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function zs(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(cf).map(n=>({alias:typeof n.alias=="string"?n.alias:"",ok:n.ok===!0})):[]}}async function Js(e,t,n){let o=Y(t.schema),i=ie(e,o.files.types,Q.types),a=ce(await U(i)),s=[],c=[];for(let l of St(n)){let d=Ke(a,l);a=d.file,(d.replaced?c:s).push(d.definition.name)}return await He({pmRoot:e,filePath:i,raw:me(a),op:"init:type-preset",author:H(void 0,t.author_default),lockTtlSeconds:t.locks.ttl_seconds,lockWaitMs:t.locks.wait_ms}),{name:n,registered:s,updated:c,file:i}}async function qs(e){let t=[".git","package.json","pnpm-workspace.yaml","AGENTS.md",L.join(".agents","pm")];for(let n of t)if(await x(L.join(e,n)))return!0;return!1}async function Ws(e,t,n){if(!t||n||await x(L.join(e,"settings.json"))||!await qs(e))return;let o=L.join(e,".agents","pm");throw new f(`Refusing to initialize tracker files directly in workspace root "${e}".`,h.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 ${o} 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 ${o} init --yes`}})}async function Bs(e,t){let n=[],o=[];for(let i of t){let r=i?L.join(e,i):e,a=await x(r);await nf.mkdir(r,{recursive:!0}),a?o.push(`already_exists:${r}`):n.push(r),o.push(...await K({path:r,scope:"project",op:"init:ensure_dir"}))}return{createdDirs:n,warnings:o}}async function Hs(e,t){let n=Ds();try{ee.write(`pm init setup wizard (agent-optimized)
|
|
65
|
-
`),ee.write(`This walkthrough is non-destructive and each choice can be changed later with pm config.
|
|
66
|
-
|
|
67
|
-
`),ee.write(`1/3 Item ID prefix
|
|
68
|
-
`),ee.write(`Prefix is prepended to generated IDs (for example pm-a1b2).
|
|
69
|
-
`);let o=await n.question(`Item ID prefix [${e}]: `),i=o.trim().length>0?$e(o):e;ee.write(`
|
|
70
|
-
2/3 Governance preset
|
|
71
|
-
`),ee.write(`minimal: no ownership blocking, progressive create defaults, close validation off.
|
|
72
|
-
`),ee.write(`default: ownership conflict warnings, progressive create defaults, close validation warn.
|
|
73
|
-
`),ee.write(`strict: ownership blocking, strict create defaults, close validation strict.
|
|
74
|
-
`);let r=await n.question("Governance preset [minimal/default/strict] (default: minimal): "),a=r.trim().length>0?r.trim():"minimal",s="minimal";try{s=Io(a)}catch{ee.write(`Unrecognized governance preset "${a}"; using minimal.
|
|
75
|
-
`)}ee.write(`
|
|
76
|
-
3/3 Project telemetry
|
|
77
|
-
`),ee.write(`Telemetry helps improve reliability and can be disabled anytime via pm config.
|
|
78
|
-
`);let c=t?"Y/n":"y/N",l=await n.question(`Enable telemetry for this project? [${c}] `),d=Us(l,t);return ee.write(`
|
|
79
|
-
`),{prefix:i,preset:s,telemetry_enabled:d}}finally{n.close()}}function lf(e){return{presetFromOption:Io(e.preset),useDefaults:e.defaults===!0,authorFromOption:Ls(e.author),installBundledPackages:e.withPackages===!0,agentGuidanceMode:Gs(e.agentGuidance),typePreset:js(e.typePreset)}}function df(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 pf(e,t,n,o){if(t.length===0||n)return;let i=o.discovery==="ancestor";throw new f(`${i?`No tracker exists in ${o.requested_cwd}; pm init found an ancestor tracker at ${o.tracker_root}. `:""}Refusing to update existing tracker settings at ${e} without --force.`,h.USAGE,{code:"init_existing_settings_requires_force",type:"urn:pm-cli:error:init_existing_settings_requires_force",required:`--force for ${t.join(", ")}`,why:i?"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:o.tracker_root,requested_path:o.requested_cwd,suggested_path:o.suggested_current_tracker_root,examples:["pm init --yes","pm init ./sandbox-pm --yes",...i?['pm init <name> --yes --pm-path "$PWD/.agents/pm"']:[],"pm init acme --yes --force"],nextSteps:[...i?['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 uf(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&&(Ao(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 mf(e){let t=await A(e.pmRoot);e.warnings.push(`already_exists:${e.settingsPath}`);let n=df({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption});return pf(e.settingsPath,n,e.options.force===!0,e.target),uf({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption,warnings:e.warnings})&&await Ee(e.pmRoot,t),{settings:t,normalizedPrefix:e.normalizedPrefix,chosenPreset:e.normalizedOptions.presetFromOption,wizardUsed:!1}}async function ff(e){let t=e.normalizedPrefix,n=e.normalizedOptions.presetFromOption,o,i=!1;if(e.normalizedOptions.presetFromOption===void 0&&!e.normalizedOptions.useDefaults&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0){let c=await Hs(t,vn.telemetry.enabled);t=c.prefix,n=c.preset,o=c.telemetry_enabled,i=!0}let r=n??"minimal",a=af();a.id_prefix=t,Ao(a,r);let s=ai()?.trim()||void 0;return a.author_default=e.normalizedOptions.authorFromOption??s??"",o!==void 0&&(a.telemetry.enabled=o,a.telemetry.first_run_prompt_completed=!0),await Ee(e.pmRoot,a),{settings:a,normalizedPrefix:t,chosenPreset:n,wizardUsed:i}}async function Ps(e){return e.settingsExists?await mf(e):await ff({pmRoot:e.pmRoot,normalizedPrefix:e.normalizedPrefix,normalizedOptions:e.normalizedOptions})}async function hf(e){let t=await Cs({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 Ee(e.pmRoot,e.settings),{...t.summary,next_steps:t.next_steps}}async function gf(e,t){let n=[],o=[],i=await ri(e,t.schema);for(let r of i.created_paths)n.push(r),o.push(...await K({path:r,scope:"project",op:"init:runtime_schema_file"}));return{createdDirs:n,warnings:o}}async function yf(e){if(e.typePreset===void 0)return;let t=await Js(e.pmRoot,e.settings,e.typePreset);return e.warnings.push(`registered_type_preset:${e.typePreset}`),e.warnings.push(...await K({path:t.file,scope:"project",op:"init:type_preset"})),t}async function _f(e){let n=z(e.settings,B()).folders.filter(i=>!wn.includes(i)),o=await Bs(e.pmRoot,n);e.createdDirs.push(...o.createdDirs),e.warnings.push(...o.warnings)}function wf(e){let t=L.resolve(e.tracker_root),n=L.dirname(t);return L.basename(t)==="pm"&&L.basename(n)===".agents"?L.dirname(n):e.workspace_root}async function vf(e,t,n,o){if(!e)return;let i=await _o("all",{install:!0,project:!0},{...t,path:n});o.push(...i.warnings);let r=zs(i),a=r.packages.filter(s=>!s.ok).map(s=>s.alias);if(!r.installed_all||a.length>0)throw new f(`pm init --with-packages did not install all bundled packages successfully${a.length>0?`: ${a.join(", ")}`:"."}`,h.GENERIC_FAILURE);return r}function Ks(e){let t=o=>st([...e.target.mode==="workspace-discovery"?[]:["--pm-path",e.target.tracker_root],...o]),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 o of e.agentGuidanceNextSteps){let i=e.target.mode==="workspace-discovery"?o:o.replace(/\bpm (?=[a-z])/g,()=>`${t([])} `);n.includes(i)||n.push(i)}return n}async function Vs(e,t,n,o=Jn){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 i=await o({pmRoot:e,workspaceRoot:t});i.gitattributes.changed&&n.push(`updated:merge_fence:${i.gitattributes.path}`)}catch(i){if(!(i instanceof f))throw i;n.push(`merge_fence_skipped:install_failed:${i.context.code??"pm_error"}:${i.message}:run pm merge install after resolving the Git repository error`)}}async function bf(e,t,n,o){if(e==null||n==="status")return;let i=await Li(e,{pmRoot:t});i.changed&&o.push(`updated:gitignore:${i.path}`)}async function gb(e,t,n={}){let o=t[of],i=typeof o=="string"?o:process.cwd(),r=Fs(i,t,e,n.workspace),a=r.pmRoot;e=Ms(r.prefixArg,n.idPrefix);let s=lf(n);await Ws(a,r.target.mode==="tracker-path",n.force===!0);let c=[],l=[],d=L.join(a,"settings.json"),p=await x(d),u;p&&(u=await Ps({pmRoot:a,settingsPath:d,settingsExists:p,normalizedPrefix:$e(e),prefixArg:e,options:n,normalizedOptions:s,warnings:l,target:r.target}));let g=await Bs(a,wn);c.push(...g.createdDirs),l.push(...g.warnings),u??=await Ps({pmRoot:a,settingsPath:d,settingsExists:p,normalizedPrefix:$e(e),prefixArg:e,options:n,normalizedOptions:s,warnings:l,target:r.target});let{settings:y}=u,w=wf(r.target),m=await Wt(w??L.dirname(a)),_=w??m,v=await hf({pmRoot:a,cwd:_??i,agentGuidanceMode:s.agentGuidanceMode,settings:y,warnings:l}),k=await gf(a,y);c.push(...k.createdDirs),l.push(...k.warnings);let S=await yf({pmRoot:a,settings:y,typePreset:s.typePreset,warnings:l});S&&(y=await A(a)),await _f({pmRoot:a,settings:y,createdDirs:c,warnings:l}),await bf(_,a,s.agentGuidanceMode,l),!p&&n.mergeFence!==!1&&s.agentGuidanceMode!=="status"&&await Vs(a,m,l);let R=await vf(s.installBundledPackages,t,a,l),G=Ks({installBundledPackages:s.installBundledPackages,registeredTypePreset:S,agentGuidanceNextSteps:v.next_steps,target:r.target});return{ok:!0,path:a,target:r.target,settings:y,created_dirs:c,warnings:l,governance_preset:y.governance.preset,wizard_used:u.wizardUsed,...S?{registered_type_preset:S}:{},...R?{installed_packages:R}:{},next_steps:G,agent_guidance:v}}export{Tn as a,sc as b,Ti as c,Pn as d,_c as e,wc as f,vc as g,Pi as h,zp as i,Ni as j,Rn as k,xc as l,Ec as m,Li as n,Ve as o,Ic as p,Ac as q,Mi as r,Jt as s,Fe as t,Gt as u,Fn as v,Lc as w,Fc as x,Vf as y,qt as z,Bc as A,ut as B,Bi as C,Xc as D,Wt as E,zn as F,Zi as G,kh as H,xh as I,Qi as J,Sh as K,Jn as L,mr as M,et as N,tt as O,fr as P,dr as Q,Ze as R,Qe as S,pr as T,el as U,Ih as V,Ch as W,tr as X,ol as Y,Kh as Z,vr as _,Sr as $,zl as aa,Jl as ba,H_ as ca,Y_ as da,X_ as ea,Et as fa,Z_ as ga,Q_ as ha,ew as ia,tw as ja,nw as ka,ow as la,iw as ma,rw as na,aw as oa,sw as pa,cw as qa,lw as ra,dw as sa,pw as ta,uw as ua,mw as va,fw as wa,hw as xa,gw as ya,yw as za,_w as Aa,ww as Ba,vw as Ca,bw as Da,kw as Ea,te as Fa,b as Ga,Yn as Ha,ad as Ia,we as Ja,Kt as Ka,ql as La,ft as Ma,Vt as Na,Mr as Oa,Kr as Pa,co as Qa,ca as Ra,zy as Sa,du as Ta,za as Ua,Ja as Va,Wa,va as Xa,Gp as Ya,vu as Za,ka as _a,_o as $a,ws as ab,qv as bb,Cs as cb,of as db,fb as eb,hb as fb,gb};
|
|
80
|
-
//# sourceMappingURL=chunk-KP7NBQK3.js.map
|