@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
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import{A as G,C as oe,Ci as or,Dc as W,Di as sr,E as K,Ei as Ie,Fi as cr,Gi as lr,Hb as qa,Hn as _r,I as me,Jb as Wa,Ld as Dt,Mb as Ne,Mc as H,Md as Xa,N as Oa,Nd as Sn,Od as En,Pd as $n,Pi as dr,Qf as Se,Rd as Za,Sa as Na,Sd as Qa,Ta as Da,U as Ca,Ua as U,Vd as er,Vi as pr,X as Ct,Yi as Lt,Zi as Ft,ab as N,ae as tr,aj as De,bb as ja,bd as Ya,bi as In,ca as Pa,cb as La,cd as st,cg as I,db as Fa,dg as Z,dh as rr,di as ir,eg as nr,ei as He,ff as T,fg as V,fj as mr,gc as xn,gg as ae,gj as An,ha as wn,hc as Ba,ic as Rt,ig as ar,ih as B,ja as Ra,k as Ta,kc as ke,kg as ct,li as se,ma as vn,mc as xe,mf as X,mg as jt,na as h,pa as f,pc as Ha,pm as fr,qi as A,qm as je,rc as Nt,ri as Ee,rm as lt,sc as Ka,sm as hr,ta as Pt,tb as Ma,tc as Va,tm as gr,ua as bn,ub as Ga,um as ce,va as kn,vb as Ua,vm as Ke,wm as yr,wo as Mt,x as k,xm as ue,y as Ot,yb as za,yi as $e,yl as ur,z as pe,zb as Ja}from"./chunk-N4YGSG6F.js";import{mkdir as Qs,readFile as ec}from"node:fs/promises";import xr 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]="0bd9a904-c076-5c2a-a9d8-42a543625e33")}catch{}})();var Tn=class extends Error{constructor(t="Workspace transaction interrupted"){super(t),this.name="WorkspaceTransactionInterruptedError"}},tc="sdk-workspace-transaction",nc=/^[a-zA-Z0-9._-]+$/,ac=30,rc=3e3;function Sr(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n||!nc.test(n))throw new TypeError(`${t} must match [a-zA-Z0-9._-]+`);return n}function wr(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 ic(e){return{pmRoot:wr(e.pmRoot,"Transaction pmRoot"),transactionId:Sr(e.transactionId,"Transaction id"),author:wr(e.author,"Transaction author")}}function vr(e,t,n){let a=e??t;if(!Number.isInteger(a)||a<=0)throw new TypeError(`${n} must be a positive integer`);return a}function Er(e,t){return xr.join(e,"transactions","sdk",`${t}.json`)}async function Ae(e,t){t.updatedAt=T();let n=Er(e,t.transactionId);await Qs(xr.dirname(n),{recursive:!0}),await oe(n,`${JSON.stringify(t,null,2)}
|
|
2
|
+
`)}function oc(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 sc(e,t){try{let n=JSON.stringify(e,(a,r)=>{if(typeof r=="number"&&!Number.isFinite(r))throw new TypeError(`${t} contains a non-finite number`);if(r===void 0||typeof r=="function"||typeof r=="symbol")throw new TypeError(`${t} contains a non-JSON value`);return r});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:sc(e,t)}function Cn(e,t,n,a){let r=On(n,a);r===void 0?delete e[t]:e[t]=r}function br(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function kr(e,t){return Array.isArray(e)&&new Set(e).size===e.length&&e.every(n=>typeof n=="string"&&t.includes(n))}function cc(e,t){if(!kr(e.startedStepIds,t)||!kr(e.completedStepIds,t)||!br(e.results)||!br(e.compensationData))return!1;let n=e.startedStepIds,a=new Set(n),r=e.completedStepIds,i=new Set(r);return Object.keys(e.compensationData).some(o=>!a.has(o))||Object.keys(e.results).some(o=>!i.has(o))?!1:e.status==="committed"?t.every(o=>i.has(o)):e.status!=="compensated"||i.size===0&&a.size===0}function lc(e,t,n){let a;try{a=JSON.parse(e)}catch{throw new TypeError(`Workspace transaction ${t} journal is invalid JSON`)}if(!a||typeof a!="object"||Array.isArray(a))throw new TypeError(`Workspace transaction ${t} journal is invalid`);let r=a,i=r.schemaVersion===1&&r.transactionId===t,o=Array.isArray(r.stepIds)&&r.stepIds.length===n.length&&r.stepIds.every((d,p)=>d===n[p]),s=cc(r,n),l=oc(r),c=["applying","compensating","compensated","committed"].includes(String(r.status));if(!i||!o||!s||!l||!c)throw new TypeError(`Workspace transaction ${t} journal does not match the supplied plan`);return{...r,results:Le(r.results),compensationData:Le(r.compensationData)}}async function dc(e,t,n,a,r){let i=r,o=i!==void 0;if(i?.status==="compensating"&&await $r(e,i),i===void 0||i.status==="compensated"){let s=T();i={schemaVersion:1,transactionId:t,author:n,status:"applying",attempt:(i?.attempt??0)+1,createdAt:i?.createdAt??s,updatedAt:s,stepIds:a,startedStepIds:[],completedStepIds:[],results:Le(),compensationData:Le()},await Ae(e.pmRoot,i),await ye(e,i,"prepared")}return{journal:i,recovered:o}}async function pc(e,t,n){try{await uc(t,e.steps),await Ae(e.pmRoot,t);let a=new Set(t.completedStepIds),r=new Set(t.startedStepIds);for(let i of e.steps){if(a.has(i.id))continue;let o=await i.inspect(),s=On(o.result,`Step ${i.id} result`);if(o.state!=="applied"){let l=await i.prepareCompensation?.();Cn(t.compensationData,i.id,l,`Step ${i.id} compensation data`),r.add(i.id),t.startedStepIds=e.steps.map(d=>d.id).filter(d=>r.has(d)),await Ae(e.pmRoot,t);let c=await i.apply();s=On(c,`Step ${i.id} result`)}await ye(e,t,"step_applied",i.id),a.add(i.id),t.completedStepIds=e.steps.map(l=>l.id).filter(l=>a.has(l)),Cn(t.results,i.id,s,`Step ${i.id} result`),await Ae(e.pmRoot,t),await ye(e,t,"step_recorded",i.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(a){if(a instanceof Tn||t.status==="committed")throw a;try{await $r(e,t)}catch(r){throw new AggregateError([a,r],`Workspace transaction failed and compensation failed: ${String(r)}`,{cause:r})}throw a}}async function mc(e,t,n){try{return lc(await ec(Er(e,t),"utf8"),t,n)}catch(a){if(a!==null&&typeof a=="object"&&"code"in a&&pe(a))return;throw a}}async function ye(e,t,n,a){await e.onTransition?.({transactionId:t.transactionId,attempt:t.attempt,transition:n,...a===void 0?{}:{stepId:a}})}async function uc(e,t){let n=new Set,a=Le();for(let r of t){let i=await r.inspect();i.state==="applied"&&(n.add(r.id),Cn(a,r.id,i.result,`Step ${r.id} result`))}e.results=a,e.completedStepIds=t.map(r=>r.id).filter(r=>n.has(r))}async function $r(e,t){t.status="compensating",await Ae(e.pmRoot,t),await ye(e,t,"compensating");let n=new Set(t.completedStepIds),a=new Set(t.startedStepIds);for(let r of[...e.steps].reverse()){if(!a.has(r.id)&&!n.has(r.id))continue;let i;try{i=a.has(r.id)&&(await r.inspect()).state==="applied"}catch{i=a.has(r.id)}i&&(await ye(e,t,"step_compensating",r.id),await r.compensate(t.compensationData[r.id])),n.delete(r.id),a.delete(r.id),t.completedStepIds=e.steps.map(o=>o.id).filter(o=>n.has(o)),t.startedStepIds=e.steps.map(o=>o.id).filter(o=>a.has(o)),delete t.results[r.id],delete t.compensationData[r.id],await Ae(e.pmRoot,t),await ye(e,t,"step_compensated",r.id)}t.status="compensated",await Ae(e.pmRoot,t),await ye(e,t,"compensated")}async function Ir(e){let{pmRoot:t,transactionId:n,author:a}=ic(e),r=vr(e.lockTtlSeconds,ac,"Transaction lock TTL"),i=vr(e.lockWaitMs,rc,"Transaction lock wait"),o=[...e.steps];if(o.length===0)throw new TypeError("Workspace transaction requires at least one step");let s=o.map(d=>{let p=Sr(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 l={...e,pmRoot:t,transactionId:n,author:a,steps:o,lockTtlSeconds:r,lockWaitMs:i},c=await X(t,tc,r,a,!1,!1,i);try{let d=await mc(t,n,s),p=d!==void 0;if(d?.status==="committed")return{transactionId:n,status:"committed",recovered:!0,results:Le(d.results)};let m=await dc(l,n,a,s,d);return await pc(l,m.journal,p||m.recovered)}finally{await c()}}import fc from"node:fs/promises";import hc 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]="7be00b26-4a56-5399-94f6-f2f67cc5c1e6")}catch{}})();function Pn(e){return hc.join(e,"extension-migrations.json")}function Ar(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 Tr(e,t){return`${e.layer}:${e.name}:${t}`}async function gc(e){let t=Pn(e);if(!await k(t))return{version:1,updated_at:"",entries:[]};let n=JSON.parse(await fc.readFile(t,"utf8"));return{version:1,updated_at:typeof n.updated_at=="string"?n.updated_at:"",entries:Array.isArray(n.entries)?n.entries.filter(a=>typeof a?.key=="string"&&(a.status==="applied"||a.status==="failed")):[]}}async function yc(e,t){let n=await gc(e),a=new Map(n.entries.map(r=>[r.key,r]));return t.forEach((r,i)=>{let o=Ar(r,i),s=a.get(Tr(r,o));s&&(r.definition.status=s.status,s.status==="failed"?r.definition.reason=s.error:(delete r.definition.reason,delete r.definition.error,delete r.definition.message))}),n}async function _c(e){let t=await yc(e.pmRoot,e.migrations),n=new Map(t.entries.map(d=>[d.key,d])),a=[],r=!1,i=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 i){let m=Ar(d,p),g=Tr(d,m),y=n.get(g),_=String(d.definition.status??"pending").toLowerCase(),u=y?.status??(_==="applied"||_==="failed"?_:"pending");if(u==="applied"){a.push({key:g,layer:d.layer,extension:d.name,id:m,before:u,outcome:"skipped"});continue}if(e.dryRun===!0){a.push({key:g,layer:d.layer,extension:d.name,id:m,before:u,outcome:"pending"});continue}let w=d.runtime_definition?.run??d.definition.run;if(typeof w!="function"){a.push({key:g,layer:d.layer,extension:d.name,id:m,before:u,outcome:"pending"});continue}let v=new Date().toISOString();try{await Promise.resolve(w({id:m,command:"migration",layer:d.layer,extension:d.name,pm_root:e.pmRoot,status:u}));let x={key:g,layer:d.layer,extension:d.name,id:m,status:"applied",attempted_at:v};n.set(g,x),d.definition.status="applied",delete d.definition.reason,delete d.definition.error,delete d.definition.message,a.push({key:g,layer:d.layer,extension:d.name,id:m,before:u,outcome:"applied"}),r=!0}catch(x){let S=x instanceof Error?x.message:String(x),O={key:g,layer:d.layer,extension:d.name,id:m,status:"failed",attempted_at:v,error:S};n.set(g,O),d.definition.status="failed",d.definition.reason=S,a.push({key:g,layer:d.layer,extension:d.name,id:m,before:u,outcome:"failed",error:S}),r=!0}}if(r){let d=await A(e.pmRoot),p={version:1,updated_at:new Date().toISOString(),entries:[...n.values()].sort((m,g)=>m.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 o=a.filter(d=>d.outcome==="pending").length,s=a.filter(d=>d.outcome==="applied").length,l=a.filter(d=>d.outcome==="skipped").length,c=a.filter(d=>d.outcome==="failed").length;return{ok:c===0,dry_run:e.dryRun===!0,state_path:Pn(e.pmRoot),total:a.length,pending_count:o,applied_count:s,skipped_count:l,failed_count:c,migrations:a}}async function Or(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}),a=await xe(n);e.warnings.push(...n.warnings,...a.warnings);let r=await _c({pmRoot:e.resolvedRoots.pm_root,migrations:a.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:r,load_failure_count:n.failed.length,activation_failure_count:a.failed.length},r.ok)}import{readFile as wc,writeFile as vc}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]="1de99e25-e132-5071-833e-37361b4cc7e6")}catch{}})();var Pr="# pm-cli:runtime-cache:start",Rn="# pm-cli:runtime-cache:end",Rr=".agents/pm",bc=["runtime/","search/","locks/","transactions/","checkpoints/"],kc=["search/eval-queries.json"];async function Cr(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 Nr(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/\/+$/,"")}function Nn(e){let t=e.replaceAll("\\","/");return dt.isAbsolute(e)||t===".."||t.startsWith("../")}function xc(e=Rr){let t=Nr(e);return[Pr,...bc.map(n=>n==="search/"?`${t}/${n}*`:`${t}/${n}`),...kc.map(n=>`!${t}/${n}`),Rn].join(`
|
|
4
|
+
`)}async function Dr(e,t={}){let n=dt.join(e,".gitignore"),a=Rr;if(t.pmRoot!==void 0){let c=Nr(dt.relative(dt.resolve(e),dt.resolve(t.pmRoot)));if(Nn(c))return{path:n,changed:!1};c.length>0&&(a=c)}let r="";try{r=await Cr(()=>wc(n,"utf8"))}catch(c){if(!(c instanceof Error&&"code"in c&&pe(c)))throw c}let i=r.indexOf(Pr),o=r.indexOf(Rn),s=(i>=0&&o>=i?`${r.slice(0,i)}${r.slice(o+Rn.length)}`:r).trimEnd(),l=`${s.length>0?`${s}
|
|
5
|
+
|
|
6
|
+
`:""}${xc(a)}
|
|
7
|
+
`;return l===r?{path:n,changed:!1}:(await Cr(()=>vc(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]="184c43e0-a543-5b0b-ac09-9139ba5ded6a")}catch{}})();var Sc=[["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 u of t.extensionNames??[])n.add(Nt(u));let a=u=>n.size===0||n.has(Nt(u)),r=(u,w)=>jr(u.filter(v=>a(v.name)).map(w)),i=(u,w)=>jr(u.filter(v=>a(v.name)).flatMap(w)),{registrations:o,commands:s,parsers:l,preflight:c,services:d,renderers:p,hooks:m}=e,g=i(o.relationship_kinds??[],u=>u.definitions.map(w=>w.kind)),y=p.overrides.filter(u=>a(u.name)&&((u.commands?.length??0)>0||u.resultDiscriminator!==void 0)).map(u=>({format:u.format,commands:[...u.commands??[]],result_discriminator:u.resultDiscriminator!==void 0})).sort((u,w)=>u.format.localeCompare(w.format)),_=r(o.assurance_providers??[],u=>u.definition.id);return{capabilities:Ka(e,t),commands:r(o.commands,u=>u.command),command_overrides:r(s.overrides,u=>u.command),command_handlers:r(s.handlers,u=>u.command),hooks:Sc.filter(([u])=>m[u].some(w=>a(w.name))).map(([,u])=>u),flag_commands:r(o.flags,u=>u.target_command),item_types:i(o.item_types,u=>u.types.map(w=>w.name)),item_fields:i(o.item_fields,u=>u.fields.map(w=>w.name)),...g.length>0?{relationship_kinds:g}:{},migrations:i(o.migrations,u=>typeof u.definition.id=="string"?[u.definition.id]:[]),profiles:r(o.profiles,u=>u.profile.name),importers:r(o.importers,u=>u.importer),exporters:r(o.exporters,u=>u.exporter),search_providers:r(o.search_providers,u=>u.definition.name),vector_store_adapters:r(o.vector_store_adapters,u=>u.definition.name),..._.length>0?{assurance_providers:_}:{},parser_overrides:r(l.overrides,u=>u.command),service_overrides:r(d.overrides,u=>u.service),renderer_overrides:r(p.overrides,u=>u.format),...y.length>0?{renderer_ownership:y}:{},preflight_overrides:c.overrides.filter(u=>a(u.name)).length,preflight_ownership:c.overrides.filter(u=>a(u.name)).map(u=>({commands:[...u.commands??[]]}))}}function jr(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]="6d1f8e03-97b4-5d83-b85c-e47f39c07d48")}catch{}})();var Ec="PM_SOURCE_CONTEXT_ACCESS",$c="PM_ALLOW_SOURCE_CONTEXT_WRITES";function Lr(e){let t=e[Ec],n=t===void 0||t.trim().toLowerCase()==="write"?"write":"read_only",a=n==="read_only"&&e[$c]?.trim()==="1";return{access:n,write_override_applied:a,source_writes_allowed:n==="write"||a}}import Fr 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]="2d40ac36-0627-5636-9679-5669dbacf06b")}catch{}})();var pt="@unbrained/pm-cli",Ic=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"]),Mr=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 Y(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]??"")||Y(e,["--activate","--adopt","--adopt-all","--deactivate","--fix-managed-state","--init","--install","--output","--reload","--scaffold","--uninstall"])}var Ac={changelog:(e,t)=>{if(t[0]==="generate")return!Y(e,["--check"]);let n=e.indexOf("export");return t[0]==="export"&&(Y(e,["--output"])||n>=0&&e[n+1]!==void 0&&!e[n+1].startsWith("-"))},comments:e=>Y(e,["--add","--delete","--edit","--file","--stdin"]),config:(e,t)=>(t[0]==="project"||t[0]==="global"?t[1]:t[0])==="set",deps:()=>!1,docs:e=>Y(e,["--add","--add-glob","--migrate","--remove"]),duplicates:()=>!1,events:()=>!1,extension:Dn,files:(e,t)=>Y(e,["--add","--add-glob","--migrate","--remove"])||t[0]==="discover"&&Y(e,["--apply"]),health:e=>!Y(e,["--check-only","--no-refresh","--skip-vectors"]),learnings:e=>Y(e,["--add","--delete","--edit","--file","--stdin"]),merge:(e,t)=>t[0]!=="report",notes:e=>Y(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]??"")&&!(Y(e,["--infer"])&&!Y(e,["--apply"])),telemetry:(e,t)=>t.slice(0,2).some(n=>["clear","flush"].includes(n)),templates:(e,t)=>t[0]==="save",test:e=>Y(e,["--add","--add-json","--background","--measure","--remove","--resume","--run","--stop"]),validate:e=>Y(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),a=zt(t);if(!n||!a)return null;for(let r=0;r<n.length;r+=1){let i=n[r]-a[r];if(i!==0)return Math.sign(i)}return 0}function Gt(e){return Fe(e,Jt)!==-1?3:2}function Tc(e,t){if(t===3)return e.filter(n=>n.history_epoch_compatible===!1).map(n=>({...n,declaration:n.declaration??n.version})).sort((n,a)=>Fe(n.version,a.version))[0]}function jn(e){try{let t=JSON.parse(Fr.readFileSync(e,"utf8"));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null}catch{return null}}function Oc(e){let t=[...e.matchAll(/(<=|<)\s*v?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/gu)].map(a=>({inclusive:a[1]==="<=",version:a[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 Cc(e){let t=e.split("||").map(n=>Oc(n));return{bounded:t.some(n=>n.length>0),compatible:t.some(n=>n.every(a=>{let r=Fe(Jt,a.version);return r!==null&&(a.inclusive?r!==1:r===-1)}))}}function Pc(e){return["dependencies","devDependencies","optionalDependencies","peerDependencies"].flatMap(t=>{let n=e[t];if(typeof n!="object"||n===null)return[];let a=n[pt],r=typeof a=="string"?a.trim():"",i=/^[<!]/u.test(r)?void 0:r.match(Ln)?.[0];if(!i)return[];let o=/^(?:=|v)?\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?$/u.test(r),s=Cc(r);return[{version:i,constraint:o?"exact":s.bounded?"range":"minimum",...o?{}:{declaration:r},history_epoch_compatible:o?Fe(i,Jt)!==-1:s.compatible}]})}function Rc(e){let t=jn(Ut.join(e,"package-lock.json"))?.packages;if(typeof t!="object"||t===null)return;let n=t["node_modules/@unbrained/pm-cli"];if(typeof n!="object"||n===null)return;let a=n.version;return typeof a=="string"?a:void 0}function Nc(e,t){try{let n=Fr.readFileSync(Ut.join(e,t),"utf8").split(/\r?\n/u),a=n.findIndex(o=>o.includes(pt));if(a<0)return;let r=n[a].match(/^\s*/u)[0].length,i=[n[a]];for(let o=a+1;o<n.length;o+=1){let s=n[o],l=s.trim(),c=s.match(/^\s*/u)[0].length;if(l.length>0&&c<=r)break;i.push(s)}return i.join(`
|
|
8
|
+
`).match(/^\s*version(?::\s*|\s+)["']?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/mu)?.[1]??i[0].match(Ln)?.[0]}catch{return}}function Fn(e){let t=[],n=jn(Ut.join(e,"package.json"));n&&t.push(...Pc(n).map(i=>({...i,source:"package.json"})));let a=jn(Ut.join(e,"node_modules","@unbrained","pm-cli","package.json"))?.version;typeof a=="string"&&zt(a)&&t.push({version:a,source:"installed-package",constraint:"exact",history_epoch_compatible:Gt(a)===3});let r=Rc(e);r&&zt(r)&&t.push({version:r,source:"package-lock.json",constraint:"exact",history_epoch_compatible:Gt(r)===3});for(let i of["pnpm-lock.yaml","yarn.lock"]){let o=Nc(e,i);o&&t.push({version:o,source:i,constraint:"exact",history_epoch_compatible:Gt(o)===3})}return t}function Gr(e){for(let t=0;t<e.length;t+=1){let n=e[t];if(Mr.has(n)){t+=1;continue}if(!n.startsWith("-"))return{command:n.toLowerCase(),index:t}}}function Dc(e){let t=Gr(e);if(!t||Y(e,["--help","-h","--dry-run"]))return!1;let{command:n,index:a}=t,r=[];for(let o=a+1;o<e.length;o+=1){let s=e[o];if(Mr.has(s)){o+=1;continue}s.startsWith("-")||r.push(s.toLowerCase())}let i=Ac[n];return i?i(e,r):Ic.has(n)}function jc(e){let t=Gr(e.argv)?.command,n=Dc(e.argv),a=Fn(e.projectRoot).filter(d=>Fe(d.version,e.executingVersion)!==null).sort((d,p)=>Fe(p.version,d.version)),r=a[0],i=r!==void 0&&Fe(e.executingVersion,r.version)===-1,o=Gt(e.executingVersion),s=Tc(a,o),l=n&&s!==void 0,c=i&&!n?{code:"project_runtime_stale_read",executing_version:e.executingVersion,project_version:r.version,source:r.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} ${r.version}.`,"Install the project dependencies with its declared package manager if the local executable is missing."]}:void 0;return{compatible:!n||!i&&!l||e.allowStale===!0,executing_version:e.executingVersion,...r?{project_version:r.version,source:r.source}:{},...t?{command:t}:{},mutating:n,stale:i,history_epoch_incompatible:l,writer_item_hash_version:o,...s?{incompatible_project_version:s.declaration,incompatible_source:s.source}:{},...c?{warning:c}:{},override_applied:n&&(i||l)&&e.allowStale===!0}}function Hf(e){let t=jc(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 Gc,readFile as Gn,realpath as Te}from"node:fs/promises";import{constants as Uc}from"node:fs";import{execFile as zc}from"node:child_process";import P from"node:path";import{promisify as Jc}from"node:util";import{execFile as Lc}from"node:child_process";import Fc from"node:path";import{promisify as Mc}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]="ed89ee24-d57b-5964-a95b-742c4f4f28a8")}catch{}})();var Ye=Mc(Lc);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 Ur(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,a]=t.trim().split(/\r?\n/);if(n===a)return"--local";let r=Fc.join(a,"config.worktree");for(let i of["core.bare","core.worktree"]){let o=await Mn(e,i);o===void 0||i==="core.bare"&&o!=="true"||(await Ye("git",["config","--file",r,i,o],{cwd:e,env:re(),timeout:1e4}),await Ye("git",["config","--local","--unset-all",i],{cwd:e,env:re(),timeout:1e4}))}for(let i of["pm-item-toon","pm-item-markdown","pm-history","pm-relationship","pm-json"])for(let o of["name","driver"]){let s=`merge.${i}.${o}`,l=await Mn(e,s);l!==void 0&&await Ye("git",["config","--file",r,s,l],{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]="5bcde7f0-1785-530a-91bb-80f2793fb8cf")}catch{}})();var Xe=Jc(zc),qt="# pm-cli:merge-drivers:start",qc="# pm-cli:merge-drivers:end",mt="# pm-cli:merge-drivers:v2:start",qr="# pm-cli:merge-drivers:v2:end",Wc="merge-fence",Bc="merge-attributes";function zr(e){return`'${e.replaceAll("'",`'"'"'`)}'`}async function Hc(e,t){let n=await Te(e);if(/(?:^|[\\/])bun-node-[^\\/]+[\\/]bun(?:\.exe)?$/iu.test(n))return;let{stdout:a}=await Xe(e,["--version"],{encoding:"utf8",windowsHide:!0,timeout:1e4});return a.trim()===t?n:void 0}async function Kc(){let e=me(import.meta.url,["../../.."]),t=process.execPath,n=!1,a=await Te(process.execPath),r=process.versions.bun,i=(process.env.PATH??"").split(P.delimiter).filter(s=>P.isAbsolute(s)).map(s=>P.join(s,r===void 0?P.basename(process.execPath):process.platform==="win32"?"bun.exe":"bun")),o=r===void 0?i:[process.env.npm_execpath??"",...i,a].filter(s=>P.isAbsolute(s)&&/^(?:bun|bun\.exe)$/iu.test(P.basename(s)));for(let s of o)try{if(await Gc(s,Uc.X_OK),r!==void 0){let l=await Hc(s,r);if(l!==void 0){t=l,n=!0;break}continue}if(s!==a&&await Te(s)===a){t=s;break}}catch{}if(r!==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`${zr(t)} ${zr(P.join(e,"dist","cli.js"))}`}var Wr=[{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 Vc(e){let t=e.explicitPath?.trim(),n=e.environment.PM_SOURCE_WORKSPACE_ROOT?.trim(),a=e.environment.PM_SOURCE_PM_PATH?.trim(),r=Lr(e.environment),i=!!(n&&a),o=t===void 0&&i&&(e.dryRun||r.source_writes_allowed);if(t!==void 0){let s=N(e.cwd,t);return{pm_root:s,workspace_start:s,source_coordinates_available:i,source_context_selected:!1,source_policy:r}}return o?{pm_root:P.resolve(a),workspace_start:P.resolve(n),source_coordinates_available:!0,source_context_selected:!0,source_policy:r}:{pm_root:i?N(e.cwd,".agents/pm"):N(e.cwd),workspace_start:e.cwd,source_coordinates_available:i,source_context_selected:!1,source_policy:r}}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 Br(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 P.relative(e,t).replaceAll("\\","/")}function le(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function Jr(e,t){if(e[t]!=="'")return null;let n="";for(let a=t+1;a<e.length;a+=1){if(e.startsWith(`'"'"'`,a)){n+="'",a+=4;continue}if(e[a]==="'")return{value:n,nextOffset:a+1};n+=e[a]}return null}async function Yc(e,t,n){if(Fn(t).filter(r=>r.constraint==="exact").some(r=>r.version!==n))return!1;let a=await Wt(e);if(a!==null&&a!==await Te(t)){let r=await Promise.all([a,t].map(async i=>{let o=await Xe("git",["rev-parse","--path-format=absolute","--git-common-dir"],{cwd:i,env:re(),timeout:1e4});return Te(o.stdout.trim())}));if(r[0]===r[1])return!1}return!0}async function Xc(e,t,n){let a=Jr(e,0);if(a===null||e[a.nextOffset]!==" ")return!1;let r=Jr(e,a.nextOffset+1);if(r===null||e.slice(r.nextOffset)!==t||!/^(?:node|bun)(?:\.exe)?$/iu.test(P.basename(a.value))||P.basename(r.value)!=="cli.js"||P.basename(P.dirname(r.value))!=="dist"||!await k(a.value)||!await k(r.value))return!1;try{let i=P.dirname(P.dirname(r.value)),o=JSON.parse(await Gn(P.join(i,"package.json"),"utf8")),s=typeof o.bin=="string"?o.bin:o.bin?.pm;return await Yc(i,n,o.version)?o.name==="@unbrained/pm-cli"&&s==="dist/cli.js":!1}catch{return!1}}function zn(e,t){let n=e.length>0?`${e}/`:"",a=[`${le(`${n}**/*.toon`)} merge=pm-item-toon`,`${le(`${n}**/*.md`)} merge=pm-item-markdown`];for(let r of t)a.push(`${le(`${n}${r}/*.toon`)} merge=pm-item-toon`),a.push(`${le(`${n}${r}/*.md`)} merge=pm-item-markdown`);return a.push(`${le(`${n}**/*.jsonl`)} merge=pm-relationship`),a.push(`${le(`${n}history/*.jsonl`)} merge=pm-history`),a.push(`${le(`${n}settings.json`)} merge=pm-json`),a.push(`${le(`${n}**/*.json`)} merge=pm-json`),a.push(`${le(`${n}extensions/**`)} -merge`),a.push(`${le(`${n}extensions/.managed-extensions.json`)} merge=pm-json`),a}function Hr(e){let t=[],n=0;for(;n<e.length;){let a=e.indexOf(qt,n),r=e.indexOf(mt,n),i=a===-1?r:r===-1?a:Math.min(a,r);if(i===-1)break;let o=i===r,s=o?mt:qt,l=o?qr:qc,c=e.indexOf(l,i+s.length),d=c===-1?e.length:c+l.length;t.push({start:i,end:d,closed:c!==-1,lines:e.slice(i+s.length,c===-1?d:c).split(`
|
|
9
|
+
`).map(p=>p.trim()).filter(Boolean)}),n=d}return t}function Kr(e,t,n){let a=new Set(t),r=le(n.length>0?`${n}/`:"").slice(0,-1);return e.some(i=>a.has(i)||i.startsWith(r)&&/^[^/]+\/\*\.(?:toon|md)" merge=pm-item-(?:toon|markdown)$/u.test(i.slice(r.length)))}async function Vr(e,t,n,a){let r=P.join(e,".gitattributes"),i=a?null:(await Xe("git",["rev-parse","--absolute-git-dir"],{cwd:e,env:re(),encoding:"utf8",windowsHide:!0,timeout:1e4})).stdout.trim(),o=i===null?null:await X(i,Bc,120,"merge-fence",!1,!0,5e3);try{let s=await G(r)??"",l=[mt,...n,qr].join(`
|
|
10
|
+
`),c=Hr(s),d=c.filter(m=>Kr(m.lines,n,t));d.length===0&&t===".agents/pm"&&c.length===1&&c[0].lines.every(m=>!m.includes(".agents/pm/"))&&d.push(c[0]);let p;if(d.length>0){let m=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,m.start)}${l}${p.slice(m.end)}`}else{let m=s.trimEnd();p=`${m.length>0?`${m}
|
|
11
|
+
|
|
12
|
+
`:""}${l}
|
|
13
|
+
`}return p===s?{path:r,changed:!1}:(a||await oe(r,p),{path:r,changed:!0})}finally{await o?.()}}function Yr(e){let t=U(e,null);return[...new Set(Object.values(t.type_to_folder))].sort((n,a)=>n.localeCompare(a))}async function vh(e,t){let n=P.resolve(e),a=null,r="",i=n;for(let u=0;u<8;u+=1){let w=P.join(i,".gitattributes");try{let x=await Gn(w,"utf8");if(x.includes(mt)||x.includes(qt)){a=i,r=x;break}}catch{}let v=P.dirname(i);if(v===i)break;i=v}if(a===null)return{status:"not_installed",missing_patterns:[],stale_patterns:[],schema_scope:"project"};let o=P.join(a,".gitattributes"),s=Un(a,n),l=Hr(r),c=zn(s,t),d=l.filter(u=>Kr(u.lines,c,s)),p=d.flatMap(u=>u.closed?u.lines:[]),m=new Set(p),g=new Set(c),y=c.filter(u=>!m.has(u)),_=p.filter(u=>!g.has(u));return{status:d.length!==1||!d[0].closed||y.length>0||_.length>0?"drift":"ok",path:o,missing_patterns:y,stale_patterns:_,schema_scope:"project"}}async function bh(e){let t=[],n=[];for(let a of Wr){let r=`merge.${a.key}.driver`,i=` merge driver ${a.artifact} "%O" "%A" "%B"${a.itemPath===void 0?"":` --item-path ${a.itemPath}`}`;try{let{stdout:o}=await Xe("git",["config","--get",r],{cwd:e,env:re(),encoding:"utf8",windowsHide:!0,timeout:1e4}),s=o.trim();await Xc(s,i,e)||n.push(r)}catch{t.push(r)}}return{status:t.length>0?"missing":n.length>0?"drift":"ok",missing_keys:t,drifted_keys:n}}async function Xr(e){let t;try{t=await Br(P.resolve(e))}catch{return{status:"no_git"}}let n=Un(t,P.resolve(e)),a=await A(e),r=B(void 0,a.author_default),i=await X(e,Wc,a.locks.ttl_seconds,r,!1,se(a).force_required_for_stale_lock,a.locks.wait_ms);try{let o=P.join(t,".gitattributes"),s;try{s=await Gn(o,"utf8")}catch(p){if(p instanceof Error&&"code"in p&&pe(p))return{status:"not_installed",path:o};throw p}if(!s.includes(mt)&&!s.includes(qt))return{status:"not_installed",path:o};let l=await A(e),c=Yr(l),d=await Vr(t,n,zn(n,c),!1);return{status:d.changed?"refreshed":"unchanged",path:d.path}}finally{await i()}}async function kh(e,t){let n=Vc({cwd:process.cwd(),explicitPath:t.path,dryRun:e.dryRun===!0,environment:process.env}),a=n.pm_root;await Se(a);let r=await Br(n.workspace_start);return Jn({pmRoot:a,workspaceRoot:r,dryRun:e.dryRun===!0})}async function Jn(e){let t=P.resolve(e.pmRoot),n=P.resolve(e.workspaceRoot),a=e.dryRun===!0,r,i;try{[r,i]=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 o=Un(i,r);if(Nn(o))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(r),l=Yr(s),c=zn(o,l),d=[],p=await Kc();for(let g of Wr)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(!a)try{let g=await Ur(i);for(let y of d)await Xe("git",["config",g,y.key,y.value],{cwd:i,env:re(),encoding:"utf8",windowsHide:!0,timeout:1e4})}catch{throw new f(`Cannot install repository-local merge drivers in ${i}. Ensure the repository Git config is writable and no other Git process holds its lock, then retry.`,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 m=await Vr(i,o,c,a);return{ok:!0,dry_run:a,workspace_root:i,pm_root:r,gitattributes:{path:m.path,changed:m.changed,patterns:c,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]="caa9f916-c7ce-5e74-a00b-dd0fc6a41b5d")}catch{}})();var ut={type:"string",minLength:1,maxLength:128,pattern:"\\S"},Bt={type:"array",minItems:1,maxItems:Sn,items:ut},Zr={...Bt,items:{...ut,pattern:"^(?!(?:.*\\.)?(?:__proto__|constructor|prototype)(?:\\.|$))[a-zA-Z_][a-zA-Z0-9_]*(?:\\.[a-zA-Z_][a-zA-Z0-9_]*){0,7}$"}},Zc={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:ut,id:ut}}}},rule:{oneOf:[{type:"object",additionalProperties:!1,required:["kind","fields"],properties:{kind:{const:"require_fields"},fields:Zr}},{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:Zr,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:ut}}}}]}}},Eh={$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:Xa,items:Zc}}};(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]="808f3bb5-cca5-5f9c-b557-7923c79ae6ce")}catch{}})();async function Th(e,t,n,a){let r=await Ie(e).catch(()=>null);return r===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"]}:Qr(r,t,n,a)}function Qc(e,t,n){return e===0?"undeclared":t===0?"empty":n===0?"inapplicable":n===t?"covered":"partial"}function Qr(e,t,n=5,a=!1){let r=[],i=new Map,o=e.policies.filter(u=>u.rule.kind==="require_fields"),s=o.filter(u=>u.subject?.operations===void 0),l=new Set,c=0,d=0,p=0,m=0,g=0,y=er(e);for(let u of t){let w=y({operation:"",author:"",before:u,after:u,completeness_only:!0});c+=+(w.decisions.length>0),d+=w.decisions.length,w.decisions.forEach(S=>l.add(S.policy_id));let v=w.decisions.filter(S=>!S.satisfied);if(v.length===0)continue;m+=1;let x=i.get(u.type)??{items:0,violations:0,missing_fields:0};x.items+=1;for(let S of v)p+=1,x.violations+=1,x.missing_fields+=S.missing_fields.length,S.effect==="refuse"&&(g+=1),r.length<n&&r.push({id:u.id,type:u.type,status:u.status,decision:S});i.set(u.type,x)}let _=a||g>0?"error":p>0?"warn":"ok";return{check:{name:"completeness",status:_,ok:_==="ok",details:{scope:"operation_independent_require_fields",declared_requirement_count:o.length,state_requirement_count:s.length,applicable_requirement_count:l.size,requirement_application_count:d,governed_items:c,ungoverned_items:t.length-c,contract_status:Qc(o.length,t.length,c),applied_policy_ids:[...l].sort().slice(0,Math.max(0,n)),applied_policy_ids_truncated:l.size>Math.max(0,n),checked_items:t.length,incomplete_items:m,violation_count:p,refused_violations:g,missing_by_type:Object.fromEntries(i),violations:r,violations_truncated:r.length<p,enforcement:e.enforcement}},warnings:[...p>0?[`validate_completeness_missing_fields:${p}`]:[],...a?["validate_completeness_source_incomplete"]:[]]}}import el 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]="0c3bed4d-4a17-5004-a1c5-65f6acec2a9b")}catch{}})();function tl(){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(([e,t])=>({id:`completeness-${e.toLowerCase()}`,effect:"advise",description:`Evidence expected when ${e} work reaches completion.`,subject:{types:[e],statuses:["closed"]},rule:{kind:"require_fields",fields:[...t]}})),{id:"completeness-resolution",effect:"advise",subject:{statuses:["closed"]},rule:{kind:"require_fields",fields:["resolution","expected_result","actual_result"]}}]}}function ni(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 nl(e,t){let n=N(process.cwd(),e.path);await Se(n);let a=await A(n);return{pmRoot:n,settings:a,author:B(t,a.author_default)}}function ei(e,t,n,a){if(e==="policy-mode")return $n({...n,enforcement:t});let r=n.policies.filter(s=>s.id!==t);if(e==="policy-remove")return{...n,policies:r};let i=En(a.definition),o=$n({...n,policies:[...r,i].sort((s,l)=>s.id.localeCompare(l.id))});if(Buffer.byteLength(`${JSON.stringify(o,null,2)}
|
|
14
|
+
`)>or)throw new f("Policy registry exceeds its byte ceiling.",h.USAGE);return o}async function ti(e,t,n,a){if(n.dryRun)return{policy_result:!0,action:e,changed:!1,result:ei(e,t,await Ie(a.pmRoot),n)};let r=await ir({pmRoot:a.pmRoot,filePath:el.join(a.pmRoot,"schema","policies.json"),op:`schema:${e}`,author:a.author,message:n.message,lockTtlSeconds:a.settings.locks.ttl_seconds,lockWaitMs:a.settings.locks.wait_ms,mutate(i){let o=ei(e,t,sr(i),n);return{raw:`${JSON.stringify(o,null,2)}
|
|
15
|
+
`,result:o}}});return{policy_result:!0,action:e,changed:r.changed,result:r.result}}async function al(e,t,n){let a,r=await mr({...n,id:e,op:"policy_approve",message:t.message,resolveHistoryContext:()=>({workflow_approval:a}),async mutate(i){let o=(await Ie(n.pmRoot)).policies.find(s=>s.id===t.policy);if(!o||o.rule.kind!=="approval")throw new f("--policy must name an approval rule.",h.USAGE);if(!o.rule.authors.includes(n.author))throw new f("This actor is not a declared approver.",h.CONFLICT);return await cr(n.pmRoot,i.metadata.id),a={policy_id:o.id,policy_fingerprint:Za(o),content_fingerprint:Qa(o,{...i.metadata,body:i.body})},{changedFields:[]}}});return{policy_result:!0,action:"policy-approve",changed:!0,result:{id:r.item.id,...a,warnings:r.warnings}}}function rl(e,t){let n=ni(t),a=En({...n,id:n.id===void 0?e:n.id});if(e!==void 0&&e.trim()!==a.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 a}async function Bh(e,t,n={},a={}){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:tl()};let r=await nl(a,n.author);if(e==="policies")return{policy_result:!0,action:e,changed:!1,result:await Ie(r.pmRoot)};if(e==="policy-put"){let d=rl(t,n.definition);return ti(e,d.id,{...n,definition:d},r)}if(!t?.trim())throw new f(`schema ${e} requires an operand.`,h.USAGE);if(["policy-remove","policy-mode"].includes(e))return ti(e,t,n,r);if(e==="policy-approve"){if(n.dryRun)throw new f("Use policy-check to preview; policy-approve records an approval.",h.USAGE);return al(t,n,r)}let i=U(r.settings,W()),o=await Lt(r.pmRoot,t,r.settings.id_prefix,r.settings.item_format,i.type_to_folder);if(!o)throw new f(`Item ${t} not found.`,h.NOT_FOUND);let{document:s}=await Ft(o,{schema:r.settings.schema}),l={...s.metadata,body:s.body},c=n.definition===void 0?l:{...l,...ni(n.definition)};if(c.id!==l.id)throw new f("Policy preview cannot change the item id.",h.USAGE);return{policy_result:!0,action:e,changed:!1,result:await lr(r.pmRoot,await Ie(r.pmRoot),{operation:"update",author:r.author,before:l,after:c,completeness_only:n.definition===void 0})}}import{createHash as gi}from"node:crypto";import Ge from"node:fs/promises";import at 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]="68be16cc-4cb4-5df6-90f0-897d4fe82339")}catch{}})();var il=new Set(bn),ol=new Set(kn),ai=new Set([...Pa.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"]),sl=["create","update"];function si(e){if(typeof e!="string")return"";let t=e.trim().toLowerCase().replaceAll(/[\s_]+/g,"-");return t.startsWith("--")?t.slice(2):t}function ri(e){return e.replaceAll("_","-")}function cl(e,t){let n=new Set;for(let a of e){let r=si(a);r.length>0&&r!==t&&n.add(r)}return[...n].sort((a,r)=>a.localeCompare(r))}function ll(e){let t=new Set;for(let n of e??[]){let a=n.trim();a.length>0&&t.add(a)}return[...t].sort((n,a)=>n.localeCompare(a))}function dl(e){let t=new Set,n=[];for(let a of e??[]){let r=a.trim().toLowerCase();if(r.length!==0){if(!ol.has(r))throw new Error(`Invalid field command "${a}". Allowed: ${kn.join(", ")}.`);t.has(r)||(t.add(r),n.push(r))}}return e===void 0||n.length===0?[...sl]:n}function ci(e){let t=I(e.key);if(t.length===0)throw new Error("Field key must not be empty.");if(ai.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: ${[...ai].sort((d,p)=>d.localeCompare(p)).join(", ")}.`);let n=typeof e.type=="string"&&e.type.trim().length>0?e.type.trim().toLowerCase():"string";if(!il.has(n))throw new Error(`Invalid field type "${e.type}". Allowed: ${bn.join(", ")}.`);let a=n,r=dl(e.commands),i=si(e.cliFlag),o=i.length>0&&i!==ri(t)?i:void 0,s=o??ri(t),l=cl(e.aliases??[],s),c=e.description?.trim();return{key:t,type:a,commands:r,description:c&&c.length>0?c:void 0,cliFlag:o,cliAliases:l,required:e.required===!0,requiredOnCreate:e.requiredOnCreate===!0,allowUnset:e.allowUnset!==!1,requiredTypes:ll(e.requiredTypes)}}function pl(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 ml(e){let t=pl(e);if(!t)return[];let n=[];for(let a of t){if(typeof a!="object"||a===null||Array.isArray(a))continue;let r=a;typeof r.key!="string"||r.key.trim().length===0||n.push(r)}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:ml(t)}}function Qe(e){return`${JSON.stringify({fields:e.fields},null,2)}
|
|
16
|
+
`}function li(e,t){let n=e.fields.find(o=>I(o.key)===t.key),a=n!==void 0,r=e.fields.filter(o=>I(o.key)!==t.key),i={...n,key:t.key,type:t.type,commands:[...t.commands]};return ii(i,"description",t.description),ii(i,"cli_flag",t.cliFlag),t.cliAliases.length>0?i.cli_aliases=[...t.cliAliases]:delete i.cli_aliases,oi(i,"required",t.required),oi(i,"required_on_create",t.requiredOnCreate),t.allowUnset===!1?i.allow_unset=!1:delete i.allow_unset,t.requiredTypes.length>0?i.required_types=[...t.requiredTypes]:delete i.required_types,r.push(i),r.sort((o,s)=>I(o.key).localeCompare(I(s.key))),{file:{fields:r},definition:i,replaced:a}}function di(e,t){let n=I(t);if(n.length===0)throw new Error("Field key must not be empty.");let a=[],r=e.fields.filter(i=>I(i.key)===n?(a.push(i),!1):!0);return a.length===0?{file:{fields:r},removed:!1}:{file:{fields:r},removed:!0,definition:a[0]}}function ii(e,t,n){let a=e;n!==void 0&&n.length>0?a[t]=n:delete a[t]}function oi(e,t,n){let a=e;n?a[t]=!0:delete a[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]="b1e4c04e-0ade-5d24-95e3-b8dca3832c5a")}catch{}})();var ul=new Set(Pt),Me=new Set(nr.map(e=>I(e.id)).filter(e=>e.length>0));function fl(e){let t=new Set;for(let n of e){let a=I(n);a.length>0&&t.add(a)}return[...t].sort((n,a)=>n.localeCompare(a))}function pi(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 o=new Set;for(let s of e.roles){let l=typeof s=="string"?s.trim().toLowerCase():"";if(l.length!==0){if(!ul.has(l))throw new Error(`Invalid status role "${s}". Allowed roles: ${Pt.join(", ")}.`);o.has(l)||(o.add(l),n.push(l))}}if(n.length===0)throw new Error(`Status role must include at least one lifecycle role. Allowed roles: ${Pt.join(", ")}.`)}let a=e.aliases===void 0?void 0:fl(e.aliases).filter(o=>o!==t),r=e.description?.trim(),i=typeof e.order=="number"&&Number.isFinite(e.order)?Math.trunc(e.order):void 0;return{id:t,roles:n,aliases:a,description:r&&r.length>0?r:void 0,order:i}}function hl(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 gl(e){let t=hl(e);if(!t)return[];let n=[];for(let a of t){if(typeof a!="object"||a===null||Array.isArray(a))continue;let r=a;typeof r.id!="string"||r.id.trim().length===0||n.push(r)}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:gl(t)}}function tt(e){return`${JSON.stringify({statuses:e.statuses},null,2)}
|
|
17
|
+
`}function mi(e,t,n){let a=e.statuses.slice(),r=a.findIndex(s=>I(s.id)===t.id),i=r>=0?a[r]:n,o={...i,id:t.id};return t.roles!==void 0&&(t.roles.length>0?o.roles=[...t.roles]:o.roles!==void 0&&delete o.roles),t.aliases!==void 0&&(t.aliases.length>0?o.aliases=[...t.aliases]:o.aliases!==void 0&&delete o.aliases),t.description!==void 0&&(o.description=t.description),t.order!==void 0&&(o.order=t.order),r>=0?a[r]=o:a.push(o),{file:{statuses:a},definition:o,replaced:i!==void 0}}function ui(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 a=e.statuses.slice(),r=a.findIndex(o=>I(o.id)===n);if(r<0)return{file:{statuses:a},removed:!1};let[i]=a.splice(r,1);return{file:{statuses:a},removed:!0,definition:i}}function qn(e,t){let n=[e.id,...e.aliases??[]];for(let a of n){let r=I(a);if(r.length===0)continue;let i=t.get(r);if(i!==void 0&&i!==e.id)throw new Error(`Status token "${r}" already belongs to status "${i}". Choose a different id/alias to avoid shadowing it.`)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8d04c087-62e4-51d3-8832-6cbcfd3ed993")}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 yi(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 _i(e,t){let n=Bn(e),a=_e(t,"migrationScope");return`auto-${gi("sha256").update(JSON.stringify({scope:a,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 yl(e){return e.kind==="rename-type"?"types":e.kind==="rename-field"?"fields":"statuses"}function _l(e,t,n){let a=V(t.schema),r=yl(n);return ae(e,a.files[r],Z[r])}function wi(e,t){return at.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 G(e);return{exists:t!==null,raw:t??""}}async function vi(e,t){t.exists?await oe(e,t.raw):await Ge.rm(e,{force:!0})}function wl(e,t,n){let a=ce(e),r=a.definitions.findIndex(o=>o.name.trim().toLowerCase()===t.from.toLowerCase()),i=a.definitions.findIndex(o=>o.name.trim().toLowerCase()===t.to.toLowerCase());if(n==="stage"){if(i>=0)return ue(a);if(r<0)throw new TypeError(`Unknown custom type "${t.from}".`);a.definitions.push({...a.definitions[r],name:t.to})}else r>=0&&a.definitions.splice(r,1);return ue(a)}function vl(e,t,n){let a=Ze(e),r=a.fields.findIndex(o=>o.key===t.from),i=a.fields.findIndex(o=>o.key===t.to);if(n==="stage"){if(i>=0)return Qe(a);if(r<0)throw new TypeError(`Unknown custom field "${t.from}".`);let o=a.fields[r];a.fields.push({...o,key:t.to,metadata_key:t.to,front_matter_key:t.to,cli_flag:t.to.replaceAll("_","-")})}else r>=0&&a.fields.splice(r,1);return Qe(a)}function bl(e,t,n){let a=et(e),r=a.statuses.findIndex(o=>o.id===t.from),i=a.statuses.findIndex(o=>o.id===t.to);if(n==="stage"){if(i>=0)return tt(a);if(r<0)throw new TypeError(`Unknown custom status "${t.from}".`);a.statuses.push({...a.statuses[r],id:t.to})}else r>=0&&a.statuses.splice(r,1);return tt(a)}function kl(e,t,n){return t.kind==="rename-type"?wl(e,t,n):t.kind==="rename-field"?vl(e,t,n):bl(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 rt(e){return Array.isArray(e)?e.map(t=>Hn(t)).filter(t=>t!==void 0):[]}function xl(e,t){for(let n of rt(e.fields))Array.isArray(n.required_types)&&(n.required_types=n.required_types.map(a=>Oe(a,t)));for(let n of rt(e.type_workflows))n.type=Oe(n.type,t)}function Sl(e,t){for(let a of rt(e.definitions))a.default_status=Oe(a.default_status,t);let n=Hn(e.workflow);if(n)for(let[a,r]of Object.entries(n))n[a]=Oe(r,t);for(let a of rt(e.type_workflows))Array.isArray(a.allowed_transitions)&&(a.allowed_transitions=a.allowed_transitions.map(r=>Array.isArray(r)?r.map(i=>Oe(i,t)):r))}function El(e,t){for(let n of rt(e.definitions)){for(let a of["required_create_fields","required_create_repeatables"])Array.isArray(n[a])&&(n[a]=n[a].map(r=>Oe(r,t)));for(let a of["options","command_option_policies"])for(let r of rt(n[a])){let i=a==="options"?"key":"option";r[i]=Oe(r[i],t)}}}function $l(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 a=t.kind==="rename-type"?"type":"status";n[a]=Oe(n[a],t)}function Wn(e,t){let n=JSON.parse(e);if(typeof n!="object"||n===null||Array.isArray(n))return e;let a=n;return t.kind==="rename-type"?xl(a,t):t.kind==="rename-field"?El(a,t):Sl(a,t),$l(a,t),`${JSON.stringify(a,null,2)}
|
|
18
|
+
`}function bi(e,t){if(t.kind==="rename-type"){let a=ce(e).definitions;return{source:a.some(r=>r.name.trim().toLowerCase()===t.from.toLowerCase()),target:a.some(r=>r.name.trim().toLowerCase()===t.to.toLowerCase())}}if(t.kind==="rename-field"){let a=Ze(e).fields;return{source:a.some(r=>r.key===t.from),target:a.some(r=>r.key===t.to)}}let n=et(e).statuses;return{source:n.some(a=>a.id===t.from),target:n.some(a=>a.id===t.to)}}function Il(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 Al(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 ki(e,t){let n=Bn(t.request),a=t.migrationId===void 0?_i(n,t.migrationScope??"plan"):yi(t.migrationId),r=e.map(l=>Al(l,n)).filter(l=>l!==null).sort((l,c)=>l.id.localeCompare(c.id)),i=gi("sha256").update(JSON.stringify({migrationId:a,request:n,items:r})).digest("hex"),o=new Set([...t.completedItemIds??[]].map(l=>l.trim()).filter(l=>l.length>0)),s=r.filter(l=>!o.has(l.id));return Object.freeze({migration_id:a,request:n,fingerprint:i,affected_item_count:r.length,pending_item_count:s.length,skipped_completed_count:r.length-s.length,items:Object.freeze(s)})}async function Tl(e){let t=U(e.settings,W()),n=[...new Set(Object.values(t.type_to_folder))],a=await pr(e.pmRoot,n),r=e.request.kind==="rename-type"?{types:[e.request.from]}:e.request.kind==="remap-status"?{statuses:[e.request.from]}:{metadataKeys:[e.request.from],...e.request.type===void 0?{}:{types:[e.request.type]}},i=a?await dr({pmRoot:e.pmRoot,expectedSourceCursor:a.source_cursor,query:r}):null;return i?{items:i.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 Ol(e,t){let n=await G(wi(e,t));if(n===null)return null;try{let a=JSON.parse(n);if(a.schema_version!==1||a.plan.migration_id!==t||!Array.isArray(a.plan.items))throw new TypeError("invalid plan envelope");return a.plan}catch(a){throw new f(`Stored schema migration plan "${t}" is invalid: ${Oa(a)}`,h.GENERIC_FAILURE)}}async function Cl(e,t){let n=wi(e,t.migration_id);await Ge.mkdir(at.dirname(n),{recursive:!0});let a={schema_version:1,plan:t,created_at:new Date().toISOString()};await oe(n,`${JSON.stringify(a,null,2)}
|
|
19
|
+
`)}function Pl(e,t){return JSON.stringify(e)===JSON.stringify(t)}async function Rl(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 fi(e,t,n){let a=n==="forward"?t.from:t.to,r=n==="forward"?t.to:t.from;if(t.kind==="rename-type"){if(e.metadata.type.toLowerCase()===r.toLowerCase())return[];if(e.metadata.type.toLowerCase()!==a.toLowerCase())throw new TypeError(`Schema migration expected type "${a}" on item "${e.metadata.id}".`);return e.metadata.type=r,["type"]}if(t.kind==="remap-status"){if(e.metadata.status.toLowerCase()===r.toLowerCase())return[];if(e.metadata.status.toLowerCase()!==a.toLowerCase())throw new TypeError(`Schema migration expected status "${a}" on item "${e.metadata.id}".`);return e.metadata.status=r,["status"]}let i=e.metadata;if(Object.prototype.hasOwnProperty.call(i,r)&&!Object.prototype.hasOwnProperty.call(i,a))return[];if(!Object.prototype.hasOwnProperty.call(i,a)||Object.prototype.hasOwnProperty.call(i,r))throw new TypeError(`Schema migration field state changed concurrently on item "${e.metadata.id}".`);return i[r]=i[a],delete i[a],[a,r]}function hi(e){return{id:e.id,inspect:async()=>{let t=await nt(e.filePath),n=bi(t.raw,e.request),a=e.phase==="stage"?n.source&&n.target:!n.source&&n.target;return{state:a?"applied":"pending",...a?{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 oe(e.filePath,kl(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 vi(e.filePath,{exists:t.exists,raw:t.raw})}}}function Nl(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 oe(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 vi(e.filePath,{exists:t.exists,raw:t.raw})}}}function Dl(e){return{id:`item-${e.id}`,inspect:async()=>{let t=await A(e.pmRoot),n=U(t,W()).type_to_folder,a=await Rl({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id}),r=Il(a,e.request).length===0;return{state:r?"applied":"pending",...r?{result:{item_id:e.id}}:{}}},apply:async()=>{let t=await A(e.pmRoot),n=U(t,W()).type_to_folder,a=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(r){return{changedFields:fi(r,e.request,"forward")}}});return{item_id:e.id,changed_fields:a.changedFields}},compensate:async()=>{let t=await A(e.pmRoot),n=U(t,W()).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(a){return{changedFields:fi(a,e.request,"reverse")}}})}}}async function jl(e){let t=await Ol(e.pmRoot,e.migrationId);if(t){if(!Pl(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 Tl({pmRoot:e.pmRoot,settings:e.settings,request:e.request});return{plan:{...ki(n.items,{migrationId:e.migrationId,request:e.request}),selection_source:n.selectionSource},stored:!1}}async function Ll(e){let t=bi(await G(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 Cl(e.pmRoot,e.plan)}async function Fl(e){let t=V(e.settings.schema),n=[...new Set([["types",Z.types],["fields",Z.fields],["workflows",Z.workflows]].map(([r,i])=>ae(e.pmRoot,t.files[r],i)).filter(r=>r!==e.schemaPath))];try{let r=at.join(e.pmRoot,"templates"),i=await Ge.readdir(r,{withFileTypes:!0});n.push(...i.filter(o=>o.isFile()&&o.name.toLowerCase().endsWith(".json")).map(o=>at.join(r,o.name)))}catch(r){if(typeof r!="object"||r===null||!("code"in r)||!pe(r))throw r}n.sort((r,i)=>r.localeCompare(i));let a=[];for(let r of n){let i=await G(r);i!==null&&Wn(i,e.request)!==i&&a.push({filePath:r,beforeRaw:i})}return{paths:n,snapshots:a}}async function Ml(e){for(let t of e.snapshots){let n=await Ge.readFile(t.filePath,"utf8"),a=at.relative(e.pmRoot,t.filePath).replaceAll("\\","/");await In({pmRoot:e.pmRoot,author:e.author,documentPath:a,before:Ht(t.beforeRaw),after:Ht(n),op:"schema_migration_reference",idempotencyKey:`${e.plan.migration_id}:${e.plan.fingerprint}:${a}`,message:`${e.request.kind}: ${e.request.from} -> ${e.request.to}`,lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}}async function Gl(e,t,n){let a=Bn(e),r=N(process.cwd(),n.path);await Se(r);let i=t.migrationId===void 0?_i(a,await Ge.realpath(r)):yi(t.migrationId),o=await A(r),s=B(t.author,o.author_default),l=await jl({pmRoot:r,settings:o,migrationId:i,request:a}),c=l.plan;if(t.dryRun===!0)return{...c,action:a.kind,applied:!1,recovered:!1,migrated_item_count:0};let d=_l(r,o,a),p=await Ge.readFile(d,"utf8");l.stored||await Ll({pmRoot:r,schemaPath:d,request:a,plan:c});let m=await Fl({pmRoot:r,schemaPath:d,settings:o,request:a}),g=[hi({id:"stage-schema",filePath:d,request:a,phase:"stage"}),...m.paths.map((w,v)=>Nl({filePath:w,request:a,stepId:`reference-${String(v+1).padStart(4,"0")}`})),...c.items.map(w=>Dl({pmRoot:r,id:w.id,request:a,author:s,force:t.force===!0})),hi({id:"retire-source",filePath:d,request:a,phase:"retire"})],y=await Ir({pmRoot:r,transactionId:`schema-${i}`,author:s,steps:g,lockTtlSeconds:Math.max(o.locks.ttl_seconds,300),lockWaitMs:o.locks.wait_ms}),_=await Ge.readFile(d,"utf8"),{historyPath:u}=await In({pmRoot:r,author:s,documentPath:at.relative(r,d).replaceAll("\\","/"),before:Ht(p),after:Ht(_),op:"schema_migration",idempotencyKey:`${c.migration_id}:${c.fingerprint}`,message:`${a.kind}: ${a.from} -> ${a.to}; affected=${c.affected_item_count}`,lockTtlSeconds:o.locks.ttl_seconds,lockWaitMs:o.locks.wait_ms});return await Ml({pmRoot:r,author:s,settings:o,request:a,plan:c,snapshots:m.snapshots}),{...c,action:a.kind,applied:!0,recovered:y.recovered,migrated_item_count:c.affected_item_count,workspace_history_path:u}}function Ul(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 Ei 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]="74b72dd8-0877-55a4-9c80-d043f19e1f96")}catch{}})();var Kt=["extensions","docs","examples","assets","prompts"],zl=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 Jl(e){return Kt.includes(e)}function ql(e,t){if(t==null)return[];let n=Array.isArray(t)?t:[t],a=[];for(let r of n){if(typeof r!="string"||r.trim().length===0)throw new f(`Package manifest field pm.${e} must contain string paths.`,h.USAGE);a.push(r.trim())}return[...new Set(a)].sort((r,i)=>r.localeCompare(i))}function Wl(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[a,r]of Object.entries(n)){if(!Jl(a))continue;let i=ql(a,r);i.length>0&&(t[a]=i)}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,a)=>n.localeCompare(a)):void 0}function xi(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 Bl(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(a=>typeof a=="string")?n:void 0}function Hl(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(a=>typeof a=="string")?n:void 0}function Kl(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:Bl(t.links),media:Hl(t.media),tags:Kn(t.tags)};return Object.values(n).some(a=>a!==void 0)?n:void 0}async function ft(e){let t=Ue.join(e,"package.json");if(!await k(t))return{source:"convention",resources:{}};let n;try{n=JSON.parse(await Ei.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 a=n,r=a.pm,i=r!=null,o=typeof r=="object"&&r!==null&&!Array.isArray(r)?r:{};return{source:i?"pm":"convention",package_json_path:t,package_name:typeof a.name=="string"?a.name:void 0,package_version:typeof a.version=="string"?a.version:void 0,package_private:a.private===!0,package_description:typeof a.description=="string"?a.description:void 0,package_keywords:Kn(a.keywords),package_homepage:typeof a.homepage=="string"?a.homepage:void 0,package_repository_url:xi(a.repository),package_bugs_url:xi(a.bugs),aliases:Kn(o.aliases),resources:Wl(r),catalog:Kl(o.catalog)}}async function Si(e){if(!await k(e))return[];let t=await Ei.readdir(e,{withFileTypes:!0}),n=[];for(let a of t){if(!a.isDirectory())continue;let r=Ue.join(e,a.name);await k(Ue.join(r,"manifest.json"))&&n.push(r)}return n.sort((a,r)=>a.localeCompare(r))}async function Vt(e){if(await k(Ue.join(e,"manifest.json")))return[e];let t=(await ft(e)).resources.extensions??[],n=new Set;for(let a of t){if(a.includes("*")||a.startsWith("!"))throw new f(`Package extension entry "${a}" uses a glob/exclusion pattern. pm package installs currently require concrete extension paths or directories.`,h.USAGE);let r=Ue.resolve(e,a);if(!K(e,r))throw new f(`Package extension entry "${a}" resolves outside package root.`,h.USAGE);if(await k(Ue.join(r,"manifest.json"))){n.add(r);continue}for(let i of await Si(r))n.add(i)}if(t.length===0)for(let a of zl.extensions)for(let r of await Si(Ue.join(e,a)))n.add(r);return[...n].sort((a,r)=>a.localeCompare(r))}import{execFile as hd}from"node:child_process";import R from"node:fs/promises";import aa from"node:os";import $ from"node:path";import{fileURLToPath as gd}from"node:url";import{promisify as yd}from"node:util";import _d from"npm-package-arg";import{extract as wd,list as vd}from"tar";import id from"node:fs/promises";import de from"node:path";import $i 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]="cf1403b0-7b07-5f00-9523-87bc727dd7fa")}catch{}})();function ee(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 a=t.length;for(;a>n&&t[a-1]==="-";)a-=1;let r=t.slice(n,a);if(r.length===0)throw new f("Extension manifest name must resolve to a non-empty directory name.",h.USAGE);if(r==="."||r==="..")throw new f('Extension manifest name must not resolve to "." or "..".',h.USAGE);return r}function Yn(e){return qa(e)}async function Vl(e){try{let t=JSON.parse(await $i.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(a=>typeof t.scripts?.[a]=="string")}}catch{return{has_build_script:!1}}}async function Yl(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 a=await Vl(n.source_root),r=a.package_name?`pm install npm:${a.package_name}`:void 0,i=n.source_input??n.source_root;return new f(`Extension entry "${e.entry}" is absent from GitHub source "${i}". pm install copies GitHub repositories without running package scripts${a.has_build_script?", and this package declares a build or publish script":""}. ${r?`Try "${r}" 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:r?[r,`pm install ${n.source_root}`]:[`pm install ${n.source_root}`],nextSteps:r?[`Retry with ${r}.`,"Or build the repository locally, then install its directory."]:["Build the repository locally, then install its directory.","If it is published, retry with pm install npm:<package-name>."],recovery:{attempted_command:`pm install ${i}`,normalized_args:["install",i],...r?{next_best_command:r}:{}}})}async function it(e,t={}){let n=Vn.join(e,"manifest.json");if(!await k(n))throw new f(`Extension manifest is missing at "${n}".`,h.USAGE);let a;try{a=JSON.parse(await $i.readFile(n,"utf8"))}catch(o){throw new f(`Failed to parse extension manifest at "${n}": ${Xl(o)}`,h.USAGE)}let r=Yn(a);if(!r)throw new f(`Extension manifest at "${n}" is invalid.`,h.USAGE);let i=Vn.resolve(e,r.entry);if(!K(e,i))throw new f(`Extension entry "${r.entry}" resolves outside extension directory "${e}".`,h.USAGE);if(!await k(i))throw await Yl(r,i,t);if(!await Ba(e,i))throw new f(`Extension entry "${r.entry}" resolves outside extension directory after symlink resolution.`,h.USAGE);return{directory:e,manifest_path:n,entry_path:i,manifest:r}}function Xl(e){return e instanceof Error?e.message:String(e)}import Xn from"node:fs/promises";import Zl 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]="57d830e7-a4e2-56f5-a89b-ae4403e256ce")}catch{}})();var Ql=".managed-extensions.json",Xt=1;function ht(e){return Zl.join(e,Ql)}function ed(){return{version:Xt,updated_at:T(),entries:[]}}function gt(e){return[...e].sort((t,n)=>{let a=t.scope.localeCompare(n.scope);if(a!==0)return a;let r=t.name.localeCompare(n.name);return r!==0?r:t.directory.localeCompare(n.directory)})}function Ii(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 te(e){return typeof e=="string"?e:void 0}function td(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 nd(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:te(t.name),package:te(t.package),version:te(t.version),repository:te(t.repository),owner:te(t.owner),repo:te(t.repo),ref:te(t.ref),subpath:te(t.subpath),commit:te(t.commit)}}function ad(e){if(typeof e!="object"||e===null)return null;let t=e;if(!td(t))return null;let n=nd(t.source);if(!n)return null;let a=Ma(t.contributions);return a===null?null:{name:t.name.trim(),directory:t.directory.trim(),scope:t.scope,manifest_version:t.manifest_version,manifest_entry:t.manifest_entry,capabilities:ee(t.capabilities),contributions:a,installed_at:t.installed_at,updated_at:t.updated_at,source:n,last_update_check_at:te(t.last_update_check_at),last_update_remote_commit:te(t.last_update_remote_commit),update_available:typeof t.update_available=="boolean"||t.update_available===null?t.update_available:void 0,update_error:te(t.update_error)}}function rd(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 a of t.entries){let r=ad(a);r&&n.push(r)}return{version:Xt,updated_at:te(t.updated_at)??T(),entries:gt(n)}}async function we(e){let t=ht(e),n=ed();try{let a=await Xn.readFile(t,"utf8"),r=JSON.parse(a),i=rd(r);if(!i)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:i,warnings:[]}}catch(a){if(a instanceof f)throw a;if(typeof a=="object"&&a!==null&&"code"in a&&pe(a))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),a={version:Xt,updated_at:T(),entries:gt(t.entries)};await Xn.mkdir(e,{recursive:!0}),await Xn.writeFile(n,`${JSON.stringify(a,null,2)}
|
|
21
|
+
`,"utf8")}function yt(e,t){let n=e.entries.filter(a=>b(a.name)!==b(t.name)&&b(a.directory)!==b(t.directory));return n.push(t),{...e,updated_at:T(),entries:gt(n)}}async function Ai(e,t,n,a){let r=t.entries.find(o=>b(o.name)===b(n));if(!r)return t;let i=yt(t,{...r,contributions:a});return await ze(e,i),i}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c9a362e5-6eb5-52dc-aa74-6c6c0df2c291")}catch{}})();var od="PM_CLI_PACKAGE_ROOT",Ti={beads:{package_directory:"pm-beads",legacy_extension_directory:"beads"},todos:{package_directory:"pm-todos",legacy_extension_directory:"todos"}},sd=new Set(["*","all"]);function Zn(){let e=[],t=process.env[od];return typeof t=="string"&&t.trim().length>0&&e.push(de.resolve(t.trim())),e.push(me(import.meta.url,["../../.."])),[...new Set(e)]}async function _t(e){let t=e.trim().toLowerCase(),n=await Ci(t);if(n)return n;let a=Ti[t];if(!a)return null;for(let r of Zn()){let i=de.join(r,".agents","pm","extensions",a.legacy_extension_directory);if(await k(de.join(i,"manifest.json")))return i}return null}function Oi(e){return sd.has(e.trim().toLowerCase())}function cd(e){return e.replace(/^pm-/i,"").trim().toLowerCase()}async function ld(e,t){let n=await id.readdir(e,{withFileTypes:!0});for(let a of n){if(!a.isDirectory()||!a.name.startsWith("pm-"))continue;let r=de.join(e,a.name);if(!await k(de.join(r,"package.json")))continue;let i=await ft(r),o=i.aliases&&i.aliases.length>0?i.aliases:[cd(a.name)];for(let s of o){let l=s.trim().toLowerCase();l.length===0||t.has(l)||t.set(l,{alias:l,package_directory:a.name,package_root:r,package_name:i.package_name??null})}}}async function Qn(){let e=new Map;for(let t of Zn()){let n=de.join(t,"packages");await k(n)&&await ld(n,e)}for(let[t,n]of Object.entries(Ti))if(!e.has(t))for(let a of Zn()){let r=de.join(a,"packages",n.package_directory);if(await k(de.join(r,"package.json"))){e.set(t,{alias:t,package_directory:n.package_directory,package_root:r,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 Ci(e){let t=e.trim().toLowerCase();return(await Qn()).find(n=>n.alias===t||n.package_directory.toLowerCase()===t||n.package_name?.toLowerCase()===t)?.package_root??null}async function Pi(e){let t=await Ci(e);return t?(await ft(t)).package_name??null:null}async function Ri(e){let t=await _t(e);if(!t)return null;try{let n=await Vt(t);return n.length!==1?null:(await it(n[0])).manifest.name}catch{return null}}function dd(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 pd(e,t,n,a,r,i){let o=a==="global"?"--global":"--project",s=Object.fromEntries(Kt.filter(l=>l!=="extensions").map(l=>[l,e.resources[l]??[]]).filter(([,l])=>Array.isArray(l)&&l.length>0));return{alias:t.alias,aliases:n,bundled:!0,available:!0,installed:n.some(l=>r.has(l))||i.has(de.resolve(t.package_root)),install_target:t.alias,install_command:`pm install ${t.alias} ${o}`,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:dd(e),media:e.catalog?.media}}}async function Ni(e,t,n={}){let a=Rt(N(process.cwd(),t.path),process.cwd()),r=e==="global"?a.global:a.project,i=await we(r),o=new Set(i.state.entries.filter(m=>m.scope===e).filter(m=>m.source.kind!=="builtin").map(m=>de.resolve(m.source.location))),s=new Set(i.state.entries.filter(m=>m.scope===e&&m.source.kind==="builtin").flatMap(m=>[m.source.name,m.source.input,m.source.location]).filter(m=>typeof m=="string"&&m.trim().length>0).map(m=>m.trim().toLowerCase())),l=[],c=new Map;for(let m of await Qn()){let g=de.resolve(m.package_root),y=c.get(g)??[];y.push(m),c.set(g,y)}for(let m of c.values()){let g=m[0],y=m.map(u=>u.alias).sort((u,w)=>u.localeCompare(w)),_=await ft(g.package_root);l.push(pd(_,g,y,e,s,o))}let d=ud(n.fields),p=d?l.map(m=>fd(m,d)):l;return{total:p.length,scope:e,installable_resource_kinds:["extensions"],metadata_only_resource_kinds:Kt.filter(m=>m!=="extensions"),packages:p}}var md=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 ud(e){if(e===void 0)return;let t=_r(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(a=>!md.has(a));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 fd(e,t){let n={};for(let a of t)a==="category"?n[a]=e.catalog?.category??null:a==="display_name"?n[a]=e.catalog?.display_name??null:n[a]=e[a]??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]="db10bb85-f21c-58b1-8b78-8ce1024b3e08")}catch{}})();var ji=yd(hd),en="@unbrained/pm-cli",bd={maxArchiveBytes:64*1024*1024,maxEntries:4096,maxExpandedBytes:256*1024*1024,maxEntryBytes:64*1024*1024},ea;async function Li(e,t=process.cwd()){let n=e.trim();if(!/^(@[^/\\\s]+\/[^/\\\s]+|[^@/\\\s][^/\\\s]*)$/u.test(n))return null;let a=$.resolve(t);for(;;){let r=$.join(a,"node_modules",...n.split("/")),i=$.join(r,"package.json");if(await k(i))try{let s=JSON.parse(await R.readFile(i,"utf8"));if(s.name===n)return{package:n,...typeof s.version=="string"?{version:s.version}:{},directory:r}}catch{return null}let o=$.dirname(a);if(o===a)return null;a=o}}function ta(e,t,n){let a=e.split("/").map(c=>c.trim()).filter(c=>c.length>0);if(a.length<2)return null;let r=a[0],i=a[1].replace(/\.git$/i,"");if(r.length===0||i.length===0)return null;let o=a.slice(2),s,l;return o[0]==="tree"&&o.length>=2?(s=o[1],l=o.slice(2).join("/")):o.length>0&&(l=o.join("/")),typeof n=="string"&&n.trim().length>0&&(s=n.trim()),{kind:"github",input:t,owner:r,repo:i,repository:`https://github.com/${r}/${i}.git`,ref:s,subpath:l&&l.length>0?l:void 0}}function kd(e,t,n){let a=e.slice(4).trim();if(a.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:a}}function tn(e,t={}){let n=e.trim();if(n.length===0)throw new f("Extension source is required for --install.",h.USAGE);let a=typeof t.ref=="string"&&t.ref.trim().length>0?t.ref.trim():void 0;if(n.startsWith("npm:"))return kd(n,t.forceGithub===!0,a);let r=(()=>{try{let o=new URL(n);if(o.hostname!=="github.com")return null;let s=o.pathname.replace(/^\/+/,"");return ta(s,n,a)}catch{return null}})();if(r)return r;let i=n.startsWith("github.com/")?n.slice(11):null;if(i){let o=ta(i,n,a);if(!o)throw new f(`Invalid GitHub source "${n}".`,h.USAGE);return o}if(t.forceGithub){let o=ta(n,n,a);if(!o)throw new f(`Invalid GitHub shorthand "${n}".`,h.USAGE);return o}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=ji,n){try{return((await t("git",e,{encoding:"utf8",timeout:n})).stdout??"").trim()}catch(a){let r=typeof a=="object"&&a!==null&&"stderr"in a?String(a.stderr):"",i=r.trim().length>0?r.trim():a instanceof Error?a.message:String(a);throw new f(`Git command failed: git ${e.join(" ")}
|
|
22
|
+
${i}`,h.GENERIC_FAILURE)}}function xd(e=process.platform){return e==="win32"?"npm.cmd":"npm"}function Sd(e=process.platform){return e==="win32"}async function Fi(e,t,n=ji,a=process.platform,r=process.env){let i=xd(a),o=Object.fromEntries(Object.entries(r).filter(([s])=>s.toLowerCase()!=="npm_config_allow_scripts"));o.NPM_CONFIG_ALLOW_SCRIPTS="";try{return((await n(i,e,{cwd:t,encoding:"utf8",env:o,shell:Sd(a)})).stdout??"").trim()}catch(s){let l=typeof s=="object"&&s!==null&&"stderr"in s?String(s.stderr):"",c=l.trim().length>0?l.trim():s instanceof Error?s.message:String(s);throw new f(`npm command failed: ${i} ${e.join(" ")}
|
|
23
|
+
${c}`,h.GENERIC_FAILURE)}}function Mi(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 Gi(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 Ed(e){let t=(e instanceof Error?e.message:String(e)).toLowerCase();return t.includes("npm err! code e404")||t.includes("404 not found")||t.includes("is not in this registry")}function $d(e){let t=(e instanceof Error?e.message:String(e)).toLowerCase();return Ed(e)||t.includes("not found")}function Id(e){let t=e.trim().toLowerCase();return t.startsWith("@unbrained/pm-")||t.startsWith("pm-")}function Ad(e){let t=Mi(e),n=Id(t),a=t.replace(/^.*\//,""),r=n?`github.com/unbraind/${a}`:void 0,i=r?`pm install --project ${r}`:void 0;return{message:n?`npm package "${e}" was not found in the registry. If this is an unpublished first-party pm package, install its GitHub repository instead.`:`npm package "${e}" was not found in the registry.`,context:{code:"npm_package_not_found",required:"Use an install source that exists, or publish the npm package before installing it with npm:<name>.",why:"Classifying npm 404s avoids repeated registry retries and gives agents a deterministic fallback path.",examples:i?[i,"pm package catalog --project --json"]:[`npm view ${t}`,"pm package catalog --project --json"],nextSteps:i?[`Try ${i} if the repository exists.`,"Use pm package catalog --project --json to inspect bundled package aliases before installing."]:[`Verify ${t} exists in the npm registry and that you have access to it.`,"Use pm package catalog --project --json to inspect bundled package aliases before installing."],recovery:{attempted_command:`pm install --project npm:${e}`,normalized_args:["install","--project",`npm:${e}`],...r&&i?{fallback_candidates:[{source:r,command:i,reason:"canonical first-party GitHub repository fallback for unpublished pm packages"}],next_best_command:i}:{}}}}}function Td(e,t){if(!$d(t))return null;let n=Ad(e);return new f(n.message,h.NOT_FOUND,n.context)}async function Ui(e){if($.isAbsolute(e)||e.startsWith(".")||e.startsWith("..")){let t=$.resolve(process.cwd(),e);return await k(t)?t:null}try{let t=new URL(e);if(t.protocol==="file:"){let n=gd(t);return await k(n)?n:null}}catch{}if(!/^[a-z][a-z0-9+.-]*:/i.test(e)){let t=$.resolve(process.cwd(),e);if(await k(t))return t}return null}async function Od(e){let t=await Ui(e);if(t)return t;let n=Cd(e);return n!==e?n:(/^[a-z][a-z0-9+.-]*:/i.test(e),e)}function Cd(e,t=process.cwd()){let n="@file:",a=e.lastIndexOf(n);if(!Gi(e))return e;let r=e.slice(0,a),i=e.slice(a+n.length);if(i.startsWith("//")&&!i.startsWith("///"))return e;if(!i.startsWith("/"))return`${r}@${$.resolve(t,i)}`;let o;try{o=decodeURIComponent(new URL(`file:${i}`).pathname)}catch{return e}let s=/^\/[A-Za-z]:/.test(o)?o.slice(1):o;return`${r}@${s}`}function Di(e,t){let n=$.resolve(e,t),a=$.relative(e,n);if(a.length===0||a===".."||a.startsWith(`..${$.sep}`)||$.isAbsolute(a))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 Pd(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 Rd(e){return(Array.isArray(e)?e.map(t=>({value:t})):typeof e=="object"&&e!==null?Object.entries(e).map(([t,n])=>({key:t,value:n})):[]).flatMap(({key:t,value:n})=>{let a=Pd(n,t);return a?[a]:[]})}function Nd(e,t){let n=t?.trim().toLowerCase(),a=n?e.filter(o=>{let s=o.name?.trim().toLowerCase();return s!==void 0?s===n:o.key?.trim().toLowerCase()===n}):[];if(a.length===1)return a[0];if(e.length!==1)return;let r=e[0],i=r.name??r.key;return n&&i!==void 0&&i.trim().toLowerCase()!==n?void 0:r}function Dd(e,t,n){let a;try{a=JSON.parse(e)}catch{let o=e.split(/\r?\n/).map(s=>s.trim()).filter(s=>s.length>0).at(-1);if(!o)throw new f("npm pack did not report a tarball filename.",h.GENERIC_FAILURE);return{tarball:Di(t,o)}}let r=Rd(a),i=Nd(r,n);if(!i)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 ${r.length} usable package receipt(s), but pm could not select ${n??"one package"} deterministically.`});return{tarball:Di(t,i.filename),package:i.name??i.key,version:i.version}}async function jd(e){return Ld(e,Fi)}async function Ld(e,t){let n=await Ui(e.spec);if(n){if((await R.stat(n)).isFile()&&zi(n))return na(n);let i=$.join(n,"package.json"),o=await k(i)?JSON.parse(await R.readFile(i,"utf8")):{};return{directory:await nn(n,e.input),package:typeof o.name=="string"?o.name:void 0,version:typeof o.version=="string"?o.version:void 0,cleanup:async()=>{}}}let a=await R.mkdtemp($.join(aa.tmpdir(),"pm-npm-package-source-")),r=$.join(a,"pack");await R.mkdir(r,{recursive:!0});try{let i=await Od(e.spec),o=await t(["pack",i,"--json","--pack-destination",r]),s=Dd(o,r,Gi(e.spec)?void 0:Mi(e.spec));if(!await k(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 l=await na(s.tarball);return{directory:l.directory,package:s.package??l.package,version:s.version??l.version,cleanup:async()=>{try{await l.cleanup()}finally{await R.rm(a,{recursive:!0,force:!0})}}}}catch(i){throw await R.rm(a,{recursive:!0,force:!0}),Td(e.spec,i)||i}}function zi(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 Fd(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 a=e.path,r=a.split("/");(a.includes("\\")||a.startsWith("/")||/^[A-Za-z]:/u.test(a)||r.some(i=>i===".."))&&ve(`Local package archive contains an escaping path: "${a}".`),r[0]!=="package"&&ve(`Local package archive entry "${a}" is outside the required package/ root.`),(e.type==="SymbolicLink"||e.type==="Link")&&ve(`Local package archive link "${a}" is not supported.`),e.type!=="File"&&e.type!=="OldFile"&&e.type!=="Directory"&&ve(`Local package archive entry "${a}" uses unsupported type "${e.type}".`),e.size>t.maxEntryBytes&&ve(`Local package archive entry "${a}" 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.`),a==="package/package.json"&&(n.packageJsonEntries+=1)}async function na(e,t=bd){(await R.stat(e)).size>t.maxArchiveBytes&&ve(`Local package archive exceeds the ${t.maxArchiveBytes} archive byte limit.`);let n=await R.mkdtemp($.join(aa.tmpdir(),"pm-local-package-archive-")),a=$.join(n,"extract");await R.mkdir(a,{recursive:!0});let r={entries:0,expandedBytes:0,packageJsonEntries:0},i;try{if(await vd({file:e,strict:!0,maxDecompressionRatio:100,onReadEntry:c=>{if(i===void 0)try{Fd(c,t,r)}catch(d){i=d}}}),i!==void 0)throw i;r.packageJsonEntries!==1&&ve(`Local package archive must contain exactly one package/package.json entry; found ${r.packageJsonEntries}.`),await wd({file:e,cwd:a,strict:!0,preservePaths:!1,preserveOwner:!1,noMtime:!0,unlink:!0,maxDepth:64,maxDecompressionRatio:100});let o=$.join(a,"package"),s=$.join(o,"package.json"),l=JSON.parse(await R.readFile(s,"utf8"));return await Md(o),{directory:await nn(o,e),package:typeof l.name=="string"?l.name:void 0,version:typeof l.version=="string"?l.version:void 0,cleanup:async()=>{await R.rm(n,{recursive:!0,force:!0})}}}catch(o){throw await R.rm(n,{recursive:!0,force:!0}),o}}async function Md(e,t=Fi){let n=$.join(e,"package.json");if(!await k(n))return;let a;try{a=JSON.parse(await R.readFile(n,"utf8"))}catch{return}if(typeof a!="object"||a===null)return;let r=a,i=Wd(r),o=Gd(r);if(i.length===0&&!o)return;let s={...a};delete s.devDependencies;let l={...s};Ud(l),await R.writeFile(n,`${JSON.stringify(l,null,2)}
|
|
24
|
+
`,"utf8");try{await Promise.all([R.rm($.join(e,"package-lock.json"),{force:!0}),R.rm($.join(e,"npm-shrinkwrap.json"),{force:!0})]),i.length>0&&await t(["install","--ignore-scripts","--no-audit","--fund=false","--package-lock=false","--no-save","--omit=peer","--"],e),o&&await zd(e)}finally{await R.writeFile(n,`${JSON.stringify(s,null,2)}
|
|
25
|
+
`,"utf8")}}function Gd(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 Ud(e){for(let t of["dependencies","optionalDependencies","peerDependencies"]){let n=e[t];if(typeof n!="object"||n===null)continue;let a={...n};delete a[en],Object.keys(a).length===0?delete e[t]:e[t]=a}}async function zd(e){let t=me(import.meta.url,["../../.."]),[n,a]=en.split("/"),r=$.join(e,"node_modules",n),i=$.join(r,a);await R.mkdir(r,{recursive:!0}),await R.rm(i,{recursive:!0,force:!0}),await R.symlink(t,i,Jd(process.platform))}function Jd(e){return e==="win32"?"junction":"dir"}function qd(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(n=>{let a=n.charCodeAt(0);return a<=31||a===127||"&|;()`\"'".includes(n)}))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{_d.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 Wd(e){let t=new Map;for(let n of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(!(typeof n!="object"||n===null))for(let[a,r]of Object.entries(n)){if(a===en||typeof r!="string"||r.trim().length===0||t.has(a))continue;let i=r.trim();t.set(a,qd(a,i))}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 a=n.map(r=>$.relative(e,r).replaceAll($.sep,"/")).sort((r,i)=>r.localeCompare(i));throw new f(`Package source "${t}" contains multiple extension manifests. Provide an explicit extension path. Candidates: ${a.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 Bd(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 r of n){let i=$.resolve(e,r);if(K(e,i)&&await k($.join(i,"manifest.json")))return{directory:i,resolved_subpath:r}}if(await k($.join(e,"manifest.json")))return{directory:e,resolved_subpath:"."};let a=await nn(e,t.input);return{directory:a,resolved_subpath:$.relative(e,a).replaceAll($.sep,"/")}}function Hd(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 Kd(e){let t=`Local extension source does not exist: "${e.absolute_path}".`,n=e.input.trim();if(!Hd(n))return new f(t,h.NOT_FOUND);let a=[];try{let i=process.env.PM_CLI_PACKAGE_ROOT,o=typeof i=="string"&&i.trim().length>0?$.resolve(i.trim()):"";ea?.key!==o&&(ea={key:o,aliases:await Zt()}),a=ea.aliases}catch{}let r=[`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): ${a.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:r,recovery:{attempted_command:`pm install ${n}`,normalized_args:["install",n],next_best_command:`pm install npm:${n}`}})}async function Ji(e){if(e.kind==="local"){let a;try{a=await R.stat(e.absolute_path)}catch{throw await Kd(e)}if(a.isFile()&&zi(e.absolute_path)){let i=await na(e.absolute_path);return{source:e,directory:i.directory,source_root:$.dirname(i.directory),resolved_subpath:$.relative($.dirname(i.directory),i.directory).replaceAll($.sep,"/"),npm_package:i.package,npm_version:i.version,cleanup:i.cleanup}}if(!a.isDirectory())throw new f(`Local extension source must be a directory or npm .tgz/.tar.gz archive: "${e.absolute_path}".`,h.USAGE);let r=await nn(e.absolute_path,e.input);return{source:e,directory:r,source_root:e.absolute_path}}if(e.kind==="npm"){let a=await jd(e);return{source:e,directory:a.directory,source_root:$.dirname(a.directory),cleanup:a.cleanup,resolved_subpath:$.relative($.dirname(a.directory),a.directory).replaceAll($.sep,"/"),npm_package:a.package,npm_version:a.version}}let t=await R.mkdtemp($.join(aa.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 a=await Qt(["-C",t,"rev-parse","HEAD"]),r=await Bd(t,e);return{source:e,directory:r.directory,source_root:t,resolved_subpath:r.resolved_subpath,commit:a,cleanup:async()=>{await R.rm(t,{recursive:!0,force:!0})}}}catch(a){throw await R.rm(t,{recursive:!0,force:!0}),a}}async function an(e,t){if(!await k(e)||!await k(t))return!1;let[n,a]=await Promise.all([R.realpath(e),R.realpath(t)]);return n===a}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]="ceca3e62-35a7-51eb-b478-5309ba430cc8")}catch{}})();var ra=1,Je="2026.6.24",Vd=">=22.18.0",Yd={fs_read:!1,fs_write:!1,network:!1,env_read:!1,env_write:!1,process_spawn:!1},qi=new Set([...tr.map(e=>e.split("-")[0].toLowerCase()),...Object.keys(Ta).map(e=>e.toLowerCase()),"scaffold"]),Xd="^6.0.0",Zd="^22.0.0",Hi=["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 Wi(e,t){return e.map(n=>n===""?n:`${t}${n}`)}function Ki(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 Vi(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 Qd={compilerOptions:{target:"ES2022",module:"NodeNext",moduleResolution:"NodeNext",strict:!0,esModuleInterop:!0,skipLibCheck:!0,noEmit:!0,allowImportingTsExtensions:!0,resolveJsonModule:!0,types:["node"]},include:["**/*.ts"]},Bi=["commands","hooks","search","importers","schema","profile","renderers","parser","preflight","services"],Yi={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"]},ep={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"]'},tp={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."},np={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."},Xi="- `tsconfig.json`: strict type-check-only TypeScript config (`noEmit`) for the `.ts` source the loader runs directly.",ap={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."]},rp={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."]},ip={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`."]},op={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 Zi(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 Qi(e,t){return e==="schema"?ip[t]:e==="profile"?op[t]:rp[t]}function sp(e){let t=e.replace(/-/g," ").trim().split(/\s+/).filter(o=>o.length>0);if(t.length===0)return"starter ping";let n=t[0].toLowerCase(),a=0;for(;t[a]?.toLowerCase()==="starter";)a+=1;let r=t[a]?.toLowerCase(),i=a>0&&(a===t.length||r!==void 0&&qi.has(r));return`${(qi.has(n)||i?["starter",...t]:t).join(" ")} ping`}function eo(e){let t=e,n=`${e}s`,a=e.replace(/-/g,""),r=a===t?[]:[a],i=`${e.replace(/-/g,"_")}_owner`,o="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(r)},`,` description: ${JSON.stringify(`A ${e} work item that flows to done.`)},`," },"," ],"," // Custom statuses upserted into the project status set."," statuses: ["," {",` id: ${JSON.stringify(o)},`,' roles: ["active"],',' aliases: ["in-review"],',' description: "Work is implementation-complete and awaiting review.",'," },"," ],"," // Custom item-metadata fields the archetype tracks."," fields: ["," {",` key: ${JSON.stringify(i)},`,' type: "string",',' commands: ["create", "update", "list"],',' description: "Stakeholder accountable for the item.",'," },"," ],"," // Per-type workflow transition allow-list staged into settings."," workflows: ["," {",` type: ${JSON.stringify(t)},`," allowed_transitions: [",' ["open", "in_progress"],',` ["in_progress", ${JSON.stringify(o)}],`,` [${JSON.stringify(o)}, "in_progress"],`,` [${JSON.stringify(o)}, "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 cp(e,t,n){let a=`${e}-search`,r=`${e}-vector`,i=`${e.replace(/-/g," ")} items`,o=[" 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 o;if(n==="search")return[...o,""," // 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(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."," api.registerVectorStoreAdapter({",` name: ${JSON.stringify(r)},`,' 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,l=`${e}s`,c=e.replace(/-/g,""),d=c===s?[]:[c],p=`${e.replace(/-/g,"_")}_note`,m=`${e}-0001-init`;return[...o,""," // 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(l)},`,` 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(m)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),"," });"]}return n==="profile"?[...o,""," // 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({",...eo(e).map(s=>` ${s}`)," });"]:n==="importers"?[...o,""," // Importers/exporters are the bridge between pm's context graph and"," // another project-management system. Keep the starter deterministic so"," // package tests can run without touching the network or filesystem; replace"," // these payloads with your adapter's real mapping as the package grows."," api.registerImporter(",` ${JSON.stringify(i)},`," async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${i} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," },"," );",""," api.registerExporter(",` ${JSON.stringify(i)},`," async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${i} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," },"," );"]:n==="renderers"?[...o,""," // 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"?[...o,""," // 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"?[...o,""," // 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 };`," });"]:[...o,""," // 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 lp(e,t,n){let a=n==="hooks",r=n==="search",i=n==="importers",o=n==="schema",s=n==="profile",l=n==="renderers",c=n==="parser",d=n==="preflight",p=n==="services",m=ep[n],g=e,y=`${e}s`,_=`${e.replace(/-/g,"_")}_note`,u=`${e}-0001-init`,w=[" assertExtensionDeactivated,"," createExtensionTestHarness,"],v=a?[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," 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,"});",""]:[],x=r?ia(e,t,"search",m):[],S=i?ia(e,t,"importers",m):[],O=o?[`test(${JSON.stringify(`${e} registers and runs its custom schema`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {",...Wi(Ki({extensionName:e,itemTypeName:g,itemTypeFolder:y,fieldName:_,migrationId:u,includeMigrationReplacementHint:!0})," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...he,"});",""]:[],ie=s?[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {",...Wi(Vi(e)," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...he,"});",""]:[],L=l?[`test(${JSON.stringify(`${e} registers and invokes its renderer override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," 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=c?[`test(${JSON.stringify(`${e} rewrites command options via its parser override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," 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,"});",""]:[],q=d?[`test(${JSON.stringify(`${e} returns a preflight gate decision via its override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," 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,"});",""]:[],ot=p?[`test(${JSON.stringify(`${e} customizes command output via its service override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," 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 {",...w,'} from "@unbrained/pm-cli/sdk/testing";',...r?['import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";']:[],'import extension from "./index.ts";',"",...Hi,`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: ${m},`," });"," 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)},`,...c?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...he,"});","",...v,...x,...S,...O,...ie,...L,...E,...q,...ot,`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: ${m},`," });"," 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 dp(e,t,n){if(n==="schema"||n==="profile")return[];if(n==="importers"){let a=`${e.replace(/-/g," ")} items`;return[t,`${a} import`,`${a} export`]}return[t]}var pp={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"},mp={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 up(e,t,n){let a=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.",',...a?[" 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,",...a?[" upper: context.options.upper === true,"]:[],' message: "Starter extension scaffold is active.",'," }),","});"]}function fp(e,t,n){let a=[],r=[...up(e,t,n)],i=[" commands: [pingCommand],"],o=`${e}-search`,s=`${e}-vector`,l=`${e.replace(/-/g," ")} items`,c=e,d=`${e}s`,p=e.replace(/-/g,""),m=p===c?[]:[p],g=`${e.replace(/-/g,"_")}_note`,y=`${e}-0001-init`;switch(n){case"commands":break;case"hooks":a.push("defineAfterCommandHook"),r.push("","// after_command hooks fire once pm finishes a command, receiving the items it","// mutated. React here - sync to an external system, emit telemetry, or refresh",'// derived context ("project management = context management"). This starter is a',"// documented no-op on the success path; replace the body with your own reaction.","export const afterCommandHook = defineAfterCommandHook((context) => {"," if (!context.ok) {"," return;"," }"," // `context.affected` lists the items pm mutated (id, status, changed_fields):"," // for (const item of context.affected ?? []) { /* ...item.id... */ }","});"),i.push(" hooks: { afterCommand: [afterCommandHook] },");break;case"search":a.push("defineSearchProvider","defineVectorStoreAdapter"),r.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(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.","export const vectorStoreAdapter = defineVectorStoreAdapter({",` name: ${JSON.stringify(s)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),","});"),i.push(" searchProviders: [searchProvider],"," vectorStoreAdapters: [vectorStoreAdapter],");break;case"importers":a.push("defineExporter","defineImporter"),r.push("","// Importers/exporters are the bridge between pm's context graph and another","// project-management system. Keep the starter deterministic so package tests can","// run without touching the network or filesystem; replace these payloads with","// your adapter's real mapping as the package grows.","export const importer = defineImporter(async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,","}));","","export const exporter = defineExporter(async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,","}));"),i.push(" importers: ["," {",` name: ${JSON.stringify(l)},`," importer,"," options: {",` action: ${JSON.stringify(`${l} 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(l)},`," exporter,"," options: {",` action: ${JSON.stringify(`${l} 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":a.push("defineItemField","defineItemType","defineMigration"),r.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(c)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(d)},`,` aliases: ${JSON.stringify(m)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],","});","","// Migrations let a package evolve stored items as its schema changes. pm runs each","// migration ONCE through the preflight gate (not once per item), passing a context","// that identifies the migration itself: `context.id` is the migration id (not an","// item id), alongside `context.pm_root`. This starter is a deterministic no-op so","// package tests can invoke it without touching the corpus; replace the body with","// your real rewrite.","export const initMigration = defineMigration({",` id: ${JSON.stringify(y)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),i.push(" itemTypes: [itemType],"," itemFields: [noteField],"," migrations: [initMigration],");break;case"profile":a.push("defineProjectProfile"),r.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({",...eo(e),"});"),i.push(" profiles: [starterProfile],");break;case"renderers":a.push("defineRendererOverride"),r.push("","// Host-enforced command ownership prevents unrelated output from reaching","// this renderer callback; return a string to take over serialization.","export const toonRenderer = defineRendererOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => {",` return ${JSON.stringify(`${e}: `)} + JSON.stringify(context.result);`," },","});"),i.push(" renderers: { toon: toonRenderer },");break;case"parser":a.push("defineParserOverride"),r.push("","// Parser overrides preprocess a command's parsed options BEFORE its handler runs,","// returning a delta - only the keys you set are merged over the parsed input. This","// override is scoped to THIS package's own command; here it rewrites the deprecated","// `--shout` boolean alias to the canonical `--upper` flag.","export const pingParser = defineParserOverride((context) => {"," const options = { ...context.options };"," if (options.shout === true) {"," options.upper = true;"," }"," delete options.shout;"," return { options };","});"),i.push(` parsers: { ${JSON.stringify(t)}: pingParser },`);break;case"preflight":a.push("definePreflightOverride"),r.push("","// Preflight overrides adjust pm's pre-run gate decision (extension migrations +","// item-format checks) for the commands it owns. Scoped ownership composes with","// other packages; overlapping or legacy global ownership is diagnosed.","// Return a delta of the keys you want to change (enforce_item_format_gate,","// run_preflight_item_format_sync, run_extension_migrations,","// enforce_mandatory_migration_gate); returning context.decision unchanged is a","// safe no-op - replace it with your policy, e.g. { run_extension_migrations: false }.","export const preflightOverride = definePreflightOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,","});"),i.push(" preflights: [preflightOverride],");break;case"services":a.push("defineServiceOverride"),r.push("","// Service overrides replace a built-in pm service. The `output_format` service","// renders a command's structured result; returning the payload unchanged passes","// through to pm's default formatting. This override scopes itself to THIS","// package's own command and passes every other command through.","export const outputService = defineServiceOverride((context) => {",` if (context.command !== ${JSON.stringify(t)}) {`," return { handled: false };"," }",` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`,"});"),i.push(" services: { output_format: outputService },");break}return{builderImports:a,definitions:r,blueprintFields:i}}function hp(e,t,n){let a=fp(e,t,n);return[`import { ${["composeExtension","defineCommand","defineExtensionBlueprint",...a.builderImports].sort((r,i)=>r.localeCompare(i)).join(", ")} } from "@unbrained/pm-cli/sdk";`,"",...a.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({",...a.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 ia(e,t,n,a){if(n==="commands")return[];let r=`${e}-search`,i=`${e}-vector`,o=`${e.replace(/-/g," ")} items`,s=e,l=`${e}s`,c=`${e.replace(/-/g,"_")}_note`,d=`${e}-0001-init`,p=[" const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${a},`," });"],m=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 () => {`,...m([" // 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 () => {`,...m([` ext.assertSearchProvider({ name: ${JSON.stringify(r)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertVectorStoreAdapter({ name: ${JSON.stringify(i)}, extensionName: ${JSON.stringify(e)} });`,""," // The starter provider reads only document title/id, so `settings` is a minimal"," // typed stub and `documents` carry just the fields it inspects."," const settings = {"," testing: {"," record_results_to_items: false,"," allow_untrusted_linked_tests: false,"," },"," } as PmSettings;"," const query = await ext.runSearchProvider({",` provider: ${JSON.stringify(r)},`,' 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(r)},`,' operation: "embed",',' context: { input: "abc", settings, model: "starter-model" },'," });"," assert.deepEqual(embedding, [3]);",""," const vectorHits = await ext.runVectorStoreAdapter({",` adapter: ${JSON.stringify(i)},`,' operation: "query",'," context: { vector: [0.1, 0.2], limit: 2, settings },"," });",' assert.deepEqual(vectorHits, [{ id: "starter-vector-hit", score: 2 }]);']),"});",""];case"importers":return[`test(${JSON.stringify(`${e} registers and invokes import/export primitives`)}, async () => {`,...m([` ext.assertImporter({ name: ${JSON.stringify(o)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertExporter({ name: ${JSON.stringify(o)}, extensionName: ${JSON.stringify(e)} });`,""," const imported = await ext.runImporter({",` importer: ${JSON.stringify(o)},`,' 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(o)},`,' 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 () => {`,...m(Ki({extensionName:e,itemTypeName:s,itemTypeFolder:l,fieldName:c,migrationId:d})),"});",""];case"profile":return[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`,...m(Vi(e)),"});",""];case"renderers":return[`test(${JSON.stringify(`${e} registers and invokes its renderer override`)}, async () => {`,...m([" // 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 () => {`,...m([" // 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 () => {`,...m([" // 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 () => {`,...m([" // 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 gp(e,t,n){let a=n==="parser",r=JSON.stringify([...Yi[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" };',"",...Hi,`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, ${r});`,` assert.deepEqual(report.manifest?.capabilities, ${r});`,"});","",`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: ${r},`," });"," 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)},`,...a?[" 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,"});","",...ia(e,t,n,r)].join(`
|
|
28
|
+
`)}function yp(e,t,n){let a=Zi(n,"package"),r=Qi(n,"package");return[`# ${e}`,"","Generated by `pm package init --declarative`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",a,`- \`index.ts\`: the TypeScript manifest entry \u2014 a \`defineExtensionBlueprint\` blueprint (${pp[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`.",Xi,"- `.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 ${mp[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.",...r,"","## Compatibility Bounds","`manifest.json` cannot hold comments, so the version-compatibility fields are documented here:",`- \`manifest_version\` (integer): manifest schema generation. Leave at \`${ra}\` 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 _p(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 wp(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 vp(e,t,n,a){let r=["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"&&r.push("","export const afterCommandHook = defineAfterCommandHook((context) => {"," if (!context.ok) return;"," // React to context.affected here as your package grows.","});"),n==="search"&&r.push("","export const searchProvider = defineSearchProvider({",` name: ${JSON.stringify(a.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(a.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"&&r.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"&&r.push("",`export const noteField = defineItemField({ name: ${JSON.stringify(a.fieldName)}, type: "string", optional: true });`,"","export const itemType = defineItemType({",` name: ${JSON.stringify(a.itemTypeName)},`,` folder: ${JSON.stringify(a.itemTypeFolder)},`,` aliases: ${JSON.stringify(a.itemTypeAliases)},`," required_create_fields: [],","});","","export const initMigration = defineMigration({",` id: ${JSON.stringify(a.migrationId)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),n==="profile"&&r.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(a.itemTypeName)}, folder: ${JSON.stringify(a.itemTypeFolder)} },`," ],"," // ...plus statuses, fields, workflows, config, templates, and packages.","});"),n==="renderers"&&r.push("","export const toonRenderer = defineRendererOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => JSON.stringify(context.result),","});"),n==="parser"&&r.push("","export const pingParser = defineParserOverride((context) => {"," const options = { ...context.options };"," if (options.shout === true) options.upper = true;"," delete options.shout;"," return { options };","});"),n==="preflight"&&r.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"&&r.push("","export const outputService = defineServiceOverride((context) => {",` if (context.command !== ${JSON.stringify(t)}) return { handled: false };`,` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`,"});"),r}function bp(e,t,n){let a=[];return t==="renderers"&&a.push(' api.registerRenderer("toon", toonRenderer.run, toonRenderer);'),t==="parser"&&a.push(` api.registerParser(${JSON.stringify(e)}, pingParser);`),t==="preflight"&&a.push(" api.registerPreflight(preflightOverride);"),t==="services"&&a.push(' api.registerService("output_format", outputService);'),t==="hooks"&&a.push(" api.hooks.afterCommand(afterCommandHook);"),t==="search"&&a.push(" api.registerSearchProvider(searchProvider);"," api.registerVectorStoreAdapter(vectorStoreAdapter);"),t==="schema"&&a.push(" api.registerItemFields([noteField]);"," api.registerItemTypes([itemType]);"," api.registerMigration(initMigration);"),t==="profile"&&a.push(" api.registerProfile(starterProfile);"),t==="importers"&&a.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.",'," },"," ],"," });"),a}function kp(e,t,n,a="commands",r=!1){let i=`pm-${e}`,o=Yi[a],s=dp(e,t,a),l=`${JSON.stringify({name:e,version:"0.1.0",entry:"./index.ts",manifest_version:ra,pm_min_version:Je,trusted:!0,sandbox_profile:"strict",permissions:{...Yd},capabilities:o,...s.length>0?{activation:{commands:s}}:{}},null,2)}
|
|
30
|
+
`,c=['import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"","export function activate(api: ExtensionApi): void {",...cp(e,t,a),"}","","// `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(Qd,null,2)}
|
|
32
|
+
`,p=tp[a],m=Zi(a,"package"),g=`${JSON.stringify({name:i,version:"0.1.0",private:!0,type:"module",keywords:["pm-package"],engines:{node:Vd},scripts:{typecheck:"tsc --noEmit","test:runtime":"node --test",test:"npm run typecheck && npm run test:runtime"},peerDependencies:{"@unbrained/pm-cli":`>=${Je}`},devDependencies:{"@types/node":Zd,typescript:Xd},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=lp(e,t,a),_=np[a],u=["node_modules/","*.log","*.tsbuildinfo",""].join(`
|
|
34
|
+
`),w=_p(e),v=["```ts",`import { ${wp(a)} } from "@unbrained/pm-cli/sdk";`,'import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"",...vp(e,t,a,w),"","export function activate(api: ExtensionApi): void {"," api.registerCommand(pingCommand);",...bp(t,a,w),"}","","export function deactivate(): void {}","","export default { activate, deactivate };","```"],x=[`# ${i}`,"","Generated by `pm package init` or `pm extension init`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",m,p,_,Xi,"- `.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:",...v,"The builders return their argument unchanged; runtime validation still lives","in `api.register*`, and behavior validation lives in `sdk/testing`.",...ap[a],...Qi(a,"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 \`${ra}\` 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":l,"index.ts":r?hp(e,t,a):c,"index.test.ts":r?gp(e,t,a):y,"tsconfig.json":d,".gitignore":u,"README.md":r?yp(i,t,a):x}}async function to(e,t="extension",n="commands",a=!1){let r=n.trim().toLowerCase();if(!Bi.includes(r))throw new f(`Unknown scaffold capability "${n}". Supported capabilities: ${Bi.join(", ")}.`,h.USAGE);let i=r;if(a&&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 o=a?"declarative":"imperative",s=e.trim(),l=vt.resolve(process.cwd(),s),c=Yt(vt.basename(l)).replace(/^(?:pm-)+/u,""),d=sp(c),p=kp(c,d,t,i,a),m=!1;if(await k(l)){if(!(await wt.stat(l)).isDirectory())throw new f(`Scaffold target "${l}" exists and is not a directory.`,h.CONFLICT)}else await wt.mkdir(l,{recursive:!0}),m=!0;for(let[y,_]of Object.entries(p)){let u=vt.join(l,y);if(await k(u)&&await wt.readFile(u,"utf8")!==_)throw new f(`Scaffold file "${y}" already exists with different content in "${l}". Choose a new target path or remove conflicting files.`,h.CONFLICT)}let g=[];for(let[y,_]of Object.entries(p)){let u=vt.join(l,y);if(await k(u)){g.push({path:y,status:"unchanged"});continue}await wt.mkdir(vt.dirname(u),{recursive:!0}),await wt.writeFile(u,_,"utf8"),g.push({path:y,status:"created"})}return{extension_name:c,package_name:`pm-${c}`,command_name:d,invocation_command:`pm ${d}`,capability:i,style:o,target_path:l,created_directory:m,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]="3984f1ef-1703-5a83-a4fa-ec1cdc738572")}catch{}})();var no=[["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 oa(e){return"#".repeat(e)}function ao(e){if(!e.includes("`"))return`\`${e}\``;let t=0,n=0;for(let i of e)n=i==="`"?n+1:0,t=Math.max(t,n);let a="`".repeat(t+1),r=e.startsWith("`")||e.endsWith("`")?" ":"";return`${a}${r}${e}${r}${a}`}function xp(e){return e.length===0?"Capabilities: _none registered_":`Capabilities: ${e.map(ao).join(", ")}`}function Sp(e,t,n){let a=[`${oa(t)} ${e}`,""];return n.length===0?(a.push("_None._",""),a):(a.push(...n.map(r=>`- ${ao(r)}`),""),a)}function Ep(e,t,n){return e===0&&!n?[]:[`${oa(t)} Preflight overrides`,"",e>0?`- ${e} registered (this surface carries no per-entry identifier)`:"_None._",""]}function sa(e,t={}){let n=t.headingLevel??2;if(!Number.isInteger(n)||n<1||n>6)throw new RangeError(`headingLevel must be an integer in [1, 6], received ${String(t.headingLevel)}`);let a=Math.min(n+1,6),r=t.includeEmpty===!0,i=t.title??"Extension surfaces",o=[`${oa(n)} ${i}`,""];(r||e.capabilities.length>0)&&o.push(xp(e.capabilities),"");for(let[s,l]of no){let c=e[s]??[];c.length===0&&!r||o.push(...Sp(l,a,c))}return o.push(...Ep(e.preflight_overrides,a,r)),!(e.preflight_overrides>0||no.some(([s])=>(e[s]?.length??0)>0))&&!r&&o.push("_This extension registers no surfaces._",""),`${o.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]="6d50733c-ced5-5ec8-b82e-2391a974ad0f")}catch{}})();function ro(e,t){return`${e}:${b(t)}`}function $p(e,t){let n=[];for(let[a,r]of[["handler",e.commands.handlers],["override",e.commands.overrides]]){let i=new Map;for(let o of r){let s=i.get(o.command)??[];i.set(o.command,[...s,o])}for(let[o,s]of i){if(t!==null&&!s.some(c=>t.has(b(c.name))))continue;let l=s.at(-1);n.push({command:o,surface:a,policy:"last_activated_wins",collision:s.length>1,claimants:s.map(c=>({name:c.name,layer:c.layer,winner:c===l}))})}}return n.sort((a,r)=>a.command.localeCompare(r.command)||a.surface.localeCompare(r.surface))}function io(e,t,n){let a=new Set(n.failed.map(c=>ro(c.layer,c.name))),r=[...t.loaded.map(c=>({name:c.name,layer:c.layer,version:c.version,activation_status:a.has(ro(c.layer,c.name))?"failed":"ok",surfaces:Ve(n,{extensionName:c.name})})),...t.failed.map(c=>({name:c.name,layer:c.layer,version:"unknown",activation_status:"not_loaded",surfaces:Ve(n,{extensionName:c.name})}))].sort((c,d)=>c.name.localeCompare(d.name)||c.layer.localeCompare(d.layer)),i=typeof e=="string"?b(e):null,o=i===null?null:new Set(t.loaded.filter(c=>b(c.name)===i||typeof c.source_package=="string"&&b(c.source_package)===i||(c.source_aliases??[]).some(d=>b(d)===i)).map(c=>b(c.name)).concat(i)),s=o===null?r:r.filter(c=>o.has(b(c.name))),l=o===null?{}:{extensionNames:[...o]};return{target:typeof e=="string"?e.trim():null,total:s.length,extensions:s,union:Ve(n,l),command_ownership:$p(n,o)}}var Ip={ok:"loaded",failed:"activation failed",not_loaded:"not loaded"};function Gy(e,t){let n=[`# ${`${t[0].toUpperCase()}${t.slice(1)}`} surface reference`,""];if(n.push(e.target===null?`Scope: all loaded ${t}s`:`Scope: \`${e.target}\``),n.push(`Described: ${e.total} ${t}${e.total===1?"":"s"}`,""),(e.command_ownership?.length??0)>0){n.push("## Command ownership","");for(let a of e.command_ownership){let r=a.claimants.find(o=>o.winner),i=a.claimants.map(o=>`${o.layer}:${o.name}`).join(", ");n.push(`- \`${a.command}\` (${a.surface}): ${r.layer}:${r.name}; policy=${a.policy}; collision=${String(a.collision)}; claimants=${i}`)}n.push("")}if(e.extensions.length===0)return n.push(`_No ${t}s are loaded._`,""),`${n.join(`
|
|
38
|
+
`).trimEnd()}
|
|
39
|
+
`;for(let a of e.extensions){let r=`${a.name} (${a.layer} v${a.version}, ${Ip[a.activation_status]})`;n.push(sa(a.surfaces,{title:r,headingLevel:2}))}return e.extensions.length>1&&n.push(sa(e.union,{title:`Union across all described ${t}s`,headingLevel:2})),`${n.join(`
|
|
40
|
+
`).trimEnd()}
|
|
41
|
+
`}import sn from"node:fs/promises";import on from"node:path";import oo 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]="147fb29e-ad06-5850-b0b1-f643e32e9b1f")}catch{}})();function bt(e,t,n,a){let r=oo.relative(e,n);if(r!==""&&!K(e,n)||n===t||K(t,n))return!1;let i=r.split(oo.sep);return i.includes(".git")?!1:a?!i.some(o=>o===".agents"||o==="node_modules"||o.startsWith(".pm-extension-install-backup-")):!0}import{randomUUID as Ap}from"node:crypto";import M from"node:fs/promises";import Tp 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]="cefb224d-a18f-599a-9cf9-3d3a22616440")}catch{}})();var so=3,Op=120,co=250,Cp=12e4,Pp=new Set(["EEXIST","ENOTEMPTY","ENOENT"]),lo=e=>typeof e=="object"&&e!==null&&"code"in e?e.code:void 0,po=e=>Pp.has(String(lo(e))),rn=(e,t)=>lo(e)===t,mo=e=>new Promise(t=>{setTimeout(t,e)}),uo=async e=>{let t=j.join(e,"package.json");await k(t)||await M.writeFile(t,`${JSON.stringify({type:"module"},null,2)}
|
|
42
|
+
`,"utf8")},fo=async e=>{let t=me(import.meta.url,["../../.."]),n=j.join(e,"node_modules","@unbrained"),a=j.join(n,"pm-cli");await M.mkdir(n,{recursive:!0}),await M.rm(a,{recursive:!0,force:!0}),await M.symlink(t,a,process.platform==="win32"?"junction":"dir")},kt=async e=>{let t=j.resolve(e),n=j.dirname(t),a=j.parse(n).root,r=await M.realpath(a).catch(()=>a),i=j.relative(a,n),o=i===""?[]:i.split(j.sep);for(let[s,l]of o.entries()){let c=j.join(r,l);try{r=await M.realpath(c)}catch{r=j.join(r,...o.slice(s));break}}return j.join(r,j.basename(t))},ho=async(e,t,n,a=Tp.tmpdir())=>Ne("extension_install_copy",async()=>{let r=j.resolve(e),i=await M.realpath(r).catch(()=>r),o=await kt(t);if(i===o)return;if(!K(i,o)){await n(i,t,{recursive:!0,force:!0,filter:p=>bt(i,o,j.resolve(p),!1)});return}let s=await M.realpath(j.resolve(a)).catch(()=>kt(a)),l=K(i,s)?j.dirname(i):s;if(K(i,l))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 c=await M.mkdtemp(j.join(l,"pm-extension-copy-")),d=j.join(c,"extension");try{await n(i,d,{recursive:!0,force:!0,filter:p=>bt(i,o,j.resolve(p),!0)}),await n(d,t,{recursive:!0,force:!0})}finally{await M.rm(c,{recursive:!0,force:!0})}}),go=async(e,t,n=M.cp)=>{for(let a=1;a<=so;a+=1)try{await Ne("extension_install_copy",async()=>{await M.rm(t,{recursive:!0,force:!0}),await ho(e,t,n)});return}catch(r){if(!po(r)||a===so)throw r;await mo(co)}},ca=async e=>{let t;try{t=await M.readFile(j.join(e,"owner.json"),"utf8")}catch(r){if(!Ot(r))throw r;return null}let n;try{n=JSON.parse(t)}catch{return null}if(typeof n!="object"||n===null||!("token"in n))return null;let a=n.token;return typeof a=="string"&&a.length>0?a:null},yo=async(e,t)=>await ca(e)!==t?!1:(await M.rm(e,{recursive:!0,force:!0}),!0),Rp=async(e,t)=>{let n;try{n=await M.stat(e)}catch{return!1}if(Date.now()-n.mtimeMs<=t)return!1;let a=await ca(e);return a===null?(await M.rm(e,{recursive:!0,force:!0}),!0):yo(e,a)},Np=(e,t,n)=>{let a=Promise.resolve(),r=setInterval(()=>{a=a.then(async()=>{if(await ca(e)!==t)return;let i=new Date;await M.utimes(e,i,i)}).catch(()=>{})},n);return r.unref(),async()=>{clearInterval(r),await a}},Dp=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}},jp=async(e,t,n,a,r)=>{for(let i=1;i<=n;i+=1)try{return await Dp(e,t),!0}catch(o){if(!rn(o,"EEXIST"))throw o;await Rp(e,r)?i-=1:await mo(a)}return!1},la=async(e,t,n,a)=>Ne("extension_install",async()=>{let r=j.join(e,"runtime","extension-install-locks"),i=j.join(r,"scope.lock");await M.mkdir(r,{recursive:!0});let{attempts:o=Op,delay_ms:s=co,stale_ms:l=Cp,heartbeat_ms:c}=a??{};if(![o,s,l,c].filter(w=>w!==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(o)),p=Math.max(0,Math.floor(s)),m=Math.floor(l),g=Math.floor(c??m/3);if(m<=0||g<=0||g>=m)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:Ap(),created_at:T(),destination:t};if(!await jp(i,y,d,p,m))throw new f(`Timed out waiting for extension install lock for "${t}".`,h.CONFLICT);let _=Np(i,y.token,g),u=!1;try{let w=await n();return u=!0,w}finally{await _(),await yo(i,y.token).catch(w=>{if(u)throw w})}});(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="18bf1015-c2c8-5530-a3ce-1531a8a1d0e2")}catch{}})();var Lp=new Set(["node_modules",".git","dist","build","coverage"]);async function _o(e,t,n,a){let r=e.source.kind==="local"?await sn.stat(e.source.absolute_path):void 0,i=e.source.kind==="local"?r.isDirectory()?"directory":"archive":e.source.kind,o=await Fp(e.directory,t,a),s={source_mode:i,...i==="archive"?{archive_bytes:r.size}:{},copy:o},l=e.source_root??e.directory;if(i==="directory"&&(!o.complete||o.development_entries>0||o.bytes>=16*1024*1024)&&await k(on.join(l,"package.json"))&&(s.packed_alternative={cwd:l,pack:{command:"npm",args:["pack","--ignore-scripts","--json"]},install:{command:"pm",args:["package","install","<archive-filename>",`--${n}`]},archive_argument:"pack_result[0].filename"}),i==="directory"&&!o.complete){let c=o.stop_reason==="entry_limit"?`${o.max_entries} entries`:`${o.max_depth} directory levels`;throw new f(`Local extension source scan stopped at ${c}; 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:o.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 Fp(e,t,n={}){let{maxEntries:a=1e4,maxDepth:r=64,signal:i}=n;if(![a,r].every(p=>Number.isSafeInteger(p)&&p>0))throw new f("maxEntries and maxDepth must be positive safe integers.",h.USAGE);i?.throwIfAborted();let o=await sn.realpath(e),s=await kt(t),l=await an(o,s);i?.throwIfAborted();let c=l?"in_place":K(o,s)?"nested_filtered_snapshot":"directory_snapshot",d={copy_scope:c,source_directory:o,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:a,max_depth:r};return c==="in_place"||await wo(o,0,d,i),d}async function wo(e,t,n,a){a?.throwIfAborted();let r=await sn.opendir(e);for await(let i of r){if(a?.throwIfAborted(),n.scanned_entries>=n.max_entries){n.complete=!1,n.stop_reason="entry_limit";return}n.scanned_entries+=1;let o=on.join(e,i.name);if(!bt(n.source_directory,n.destination_directory,o,n.copy_scope==="nested_filtered_snapshot")){n.excluded_entries+=1;continue}if(on.relative(n.source_directory,o).split(on.sep).some(s=>Lp.has(s))&&(n.development_entries+=1),await Mp(o,t,n,a),!n.complete)return}}async function Mp(e,t,n,a){let r=await sn.lstat(e);if(a?.throwIfAborted(),r.isDirectory()){if(n.directories+=1,t+1>=n.max_depth){n.complete=!1,n.stop_reason="depth_limit";return}await wo(e,t+1,n,a)}else r.isFile()?(n.files+=1,n.bytes+=r.size):r.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]="7bda052f-809f-5c09-bb28-ccb56a7f22b7")}catch{}})();async function vo(e,t,n){let a=typeof t=="string"?null:await _t(e),r=a===null?null:e.trim().toLowerCase(),i=r===null?null:await Pi(r),o=tn(a??e,{forceGithub:typeof t=="string",ref:n}),s=r===null?null:await Li(e);return{bundledAliasName:r,bundledPackageName:i,installSource:o,sourceResolution:{requested:e,selected:{kind:r===null?o.kind:"builtin",input:r??o.input,...i===null?{}:{package:i}},ambiguous:s!==null,precedence:"bundled_alias_before_installed_npm",candidates:[...r===null?[]:[{kind:"builtin",input:r,...i===null?{}:{package:i},command:`pm install ${r}`}],...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 ne from"node:path";import qp from"node:path";import{mkdir as Wp}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]="abb182c9-6d6c-5be4-a2ad-c91b00a098d0")}catch{}})();var xt=["agile","ops","research"],Gp={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 Gp[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]="4d01ffa0-2cdb-5d22-834e-d23d31403ad6")}catch{}})();var Up=/^([A-Za-z][A-Za-z0-9_-]*?)\s*[-:]\s+\S/;function zp(e){let t=Up.exec(e.trim());if(!t)return;let n=t[1];if(!(n.length<2)&&!/^[A-Za-z]\d+$/.test(n))return n.toLowerCase()}function Jp(e){return e.split(/[-_]+/).filter(t=>t.length>0).map(t=>`${t.slice(0,1).toUpperCase()}${t.slice(1).toLowerCase()}`).join("")}function bo(e,t={}){let n=typeof t.minCount=="number"&&t.minCount>0?Math.trunc(t.minCount):10,a=typeof t.maxExamples=="number"&&t.maxExamples>0?Math.trunc(t.maxExamples):3,r=new Map;for(let o of e){let s=typeof o=="string"?o.trim():"";if(s.length===0)continue;let l=zp(s);if(l===void 0)continue;let c=r.get(l)??{count:0,examples:[]};c.count+=1,c.examples.length<a&&c.examples.push(s),r.set(l,c)}let i=[];for(let[o,s]of r.entries()){if(s.count<n)continue;let l=Jp(o);i.push({name:l,prefix:o,count:s.count,examples:s.examples,shadows_builtin:fr(l)!==void 0})}return i.sort((o,s)=>s.count-o.count||o.name.localeCompare(s.name)),i}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7a59f90b-0497-530c-93e1-c93cfc8a0016")}catch{}})();var W_=[...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",ko="schema-statuses",xo="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 K_(e,t,n){let a=N(process.cwd(),n.path);await be(a);let r;try{r=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 i=await A(a),o=V(i.schema),s=ae(a,o.files.types,Z.types),l=[],c=B(t.author,i.author_default),d=se(i),p=await X(a,ln,i.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,i.locks.wait_ms),m;try{let g=await G(s),y;try{y=ce(g)}catch(_){throw new f(_ instanceof Error?_.message:String(_),h.GENERIC_FAILURE)}try{hr(r,y);let _=new Map,u=U(i,W());for(let[w,v]of Object.entries(u.type_to_folder)){let x=v.trim().toLowerCase();x.length>0&&!_.has(x)&&_.set(x,w)}gr(r,y,_)}catch(_){throw new f(_ instanceof Error?_.message:String(_),h.USAGE)}m=Ke(y,r),m.replaced&&m.previousName!==void 0&&m.previousName!==m.definition.name&&l.push(`type_recased:${m.previousName}->${m.definition.name}`),await Ce({pmRoot:a,filePath:s,raw:ue(m.file),op:"schema:add-type",author:c,settings:i}),await Et(a,[m.definition],l,"schema:add-type-folder"),l.push(...await H({path:s,scope:"project",op:"schema:add-type"}))}finally{await p()}return await So(a,l),{action:"add-type",registered:!0,replaced:m.replaced,type:m.definition,file:{path:s,definitions:m.file.definitions.length},warnings:Pe(l),generated_at:T()}}async function be(e){await Se(e)}async function So(e,t){try{let n=await Xr(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 Bp(e,t,n,a){let r=U(t,W()),i=a.trim().toLowerCase();return(await De(e,t.item_format,r.type_to_folder,[],n)).filter(o=>typeof o.type=="string"&&o.type.toLowerCase()===i).length}async function Hp(e,t,n,a){let r=U(t,W()),i=ct(n),o=I(a);return(await De(e,t.item_format,r.type_to_folder,[],n)).filter(s=>{let l=typeof s.status=="string"?s.status:"";return(i.alias_to_id.get(I(l))??I(l))===o}).length}async function Kp(e,t,n,a,r){if(r.length===0||Me.has(r))return;let i=await Hp(t,n,a,r);i>0&&e.push(`items_using_status:${i}`);let o=Eo(a.workflow,r);o.length>0&&e.push(`status_referenced_by_workflow:${o.join(",")}`)}function Eo(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(([,n])=>n!==void 0&&I(n)===t).map(([n])=>n)}async function V_(e,t,n){let a=N(process.cwd(),n.path);await be(a);let r=await A(a),i=V(r.schema),o=ae(a,i.files.types,Z.types),s=[],l=B(t.author,r.author_default),c=se(r),d=await X(a,ln,r.locks.ttl_seconds,l,!!t.force,c.force_required_for_stale_lock,r.locks.wait_ms),p;try{let m=await G(o),g;try{g=ce(m)}catch(y){throw new f(y instanceof Error?y.message:String(y),h.GENERIC_FAILURE)}try{p=yr(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 _=await Bp(a,r,i,y);_>0&&s.push(`items_using_type:${_}`)}await Ce({pmRoot:a,filePath:o,raw:ue(p.file),op:"schema:remove-type",author:l,settings:r}),s.push(...await H({path:o,scope:"project",op:"schema:remove-type"}))}}finally{await d()}return p.removed&&await So(a,s),{action:"remove-type",removed:p.removed,...p.definition?{type:p.definition}:{},file:{path:o,definitions:p.file.definitions.length},warnings:Pe(s),generated_at:T()}}function da(e,t){return ae(e,t.files.statuses,Z.statuses)}function dn(e,t){return ae(e,t.files.fields,Z.fields)}function $o(e,t){return ae(e,t.files.types,Z.types)}async function Et(e,t,n,a){for(let r of t){let i=Da(r.folder??Na(r.name)),o=qp.join(e,i);await k(o)||(await Wp(o,{recursive:!0}),n.push(...await H({path:o,scope:"project",op:a})))}}function pa(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 Vp(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 Yp(e){let t=new Map;for(let n of e){let a=I(n.id);if(a.length!==0){t.set(a,a);for(let r of Array.isArray(n.aliases)?n.aliases:[]){let i=I(r);i.length>0&&!t.has(i)&&t.set(i,a)}}}return t}async function Y_(e,t,n){let a=N(process.cwd(),n.path);await be(a);let r;try{r=pi({id:e,roles:t.role,aliases:t.alias,description:t.description,order:t.order})}catch(_){throw new f(_ instanceof Error?_.message:String(_),h.USAGE)}let i=await A(a),o=V(i.schema),s=da(a,o),l=ct(o);try{qn(r,l.alias_to_id)}catch(_){throw new f(_ instanceof Error?_.message:String(_),h.USAGE)}let c=Vp(l.by_id.get(r.id));if((r.roles??c?.roles??[]).length===0)throw new f(`Status "${r.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(r.id)}" --role active`,`pm schema add-status "${je(r.id)}" --role blocked`]});let d=[],p=B(t.author,i.author_default),m=se(i),g=await X(a,ko,i.locks.ttl_seconds,p,!!t.force,m.force_required_for_stale_lock,i.locks.wait_ms),y;try{let _=await G(s),u;try{u=et(_)}catch(v){throw new f(v instanceof Error?v.message:String(v),h.GENERIC_FAILURE)}let w=Yp(u.statuses);try{qn(r,w)}catch(v){throw new f(v instanceof Error?v.message:String(v),h.USAGE)}y=mi(u,r,c),await Ce({pmRoot:a,filePath:s,raw:tt(y.file),op:"schema:add-status",author:p,settings:i}),d.push(...await H({path:s,scope:"project",op:"schema:add-status"}))}finally{await g()}return{action:"add-status",registered:!0,replaced:y.replaced,status:y.definition,file:{path:s,statuses:y.file.statuses.length},warnings:Pe(d),generated_at:T()}}async function X_(e,t,n){let a=N(process.cwd(),n.path);await be(a);let r=await A(a),i=V(r.schema),o=da(a,i),s=[],l=B(t.author,r.author_default),c=se(r),d=await X(a,ko,r.locks.ttl_seconds,l,!!t.force,c.force_required_for_stale_lock,r.locks.wait_ms),p;try{let m=await G(o),g;try{g=et(m)}catch(y){throw new f(y instanceof Error?y.message:String(y),h.GENERIC_FAILURE)}try{p=ui(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 Kp(s,a,r,i,y),await Ce({pmRoot:a,filePath:o,raw:tt(p.file),op:"schema:remove-status",author:l,settings:r}),s.push(...await H({path:o,scope:"project",op:"schema:remove-status"}))}}finally{await d()}return{action:"remove-status",removed:p.removed,...p.definition?{status:p.definition}:{},file:{path:o,statuses:p.file.statuses.length},warnings:Pe(s),generated_at:T()}}function Io(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 Xp(e,t,n){return{...Io(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 Ao(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 To(e,t,n){let a=e.toLowerCase();return n.has(a)?"extension":t.has(a)?"custom":"builtin"}function Zp(){let e=new Map,t=W();for(let n of t?.item_types??[]){let a=n.types;if(Array.isArray(a))for(let r of a){if(typeof r!="object"||r===null||Array.isArray(r))continue;let i=r.name;typeof i=="string"&&i.trim().length>0&&e.set(i.trim().toLowerCase(),{layer:n.layer,name:n.name})}}return e}function Qp(e){let t=ct(e),n=[],a=[];for(let r of t.definitions){let i=Ao(r);i.source==="builtin"?n.push(i):a.push(i)}return{builtin:n,custom:a}}async function $t(e){let t=N(process.cwd(),e.path);await be(t);let n=await A(t),a=V(n.schema),r=ae(t,a.files.types,Z.types),i=da(t,a),o=U(n,W()),s=Zp(),l=new Set((n.item_types?.definitions??[]).map(c=>c.name.trim().toLowerCase()).filter(c=>c.length>0&&!s.has(c)));return{pmRoot:t,typesPath:r,statusesPath:i,byType:o.by_type,customNames:l,extensionProvenance:s,schema:a}}async function Z_(e){let t=await $t(e),n=[],a=[],r=[];for(let s of Object.values(t.byType).sort((l,c)=>l.name.localeCompare(c.name))){let l=To(s.name,t.customNames,new Set(t.extensionProvenance.keys())),c=Io(s);l==="extension"?r.push(c):l==="custom"?a.push(c):n.push(c)}let i=Qp(t.schema),o=jt(t.schema).definitions.map(pa);return{action:"list",builtin:n,custom:a,extension:r,counts:{builtin:n.length,custom:a.length,extension:r.length,total:n.length+a.length+r.length},statuses:{builtin:i.builtin,custom:i.custom,counts:{builtin:i.builtin.length,custom:i.custom.length,total:i.builtin.length+i.custom.length}},fields:{custom:o,counts:{total:o.length}},file:{path:t.typesPath},generated_at:T()}}async function Q_(e,t){let n=(e??"").trim();if(n.length===0)throw new f("Type name must not be empty.",h.USAGE);let a=await $t(t),r=Object.values(a.byType).find(i=>i.name.toLowerCase()===n.toLowerCase()||i.aliases.some(o=>o.toLowerCase()===n.toLowerCase()));if(!r)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:Xp(r,To(r.name,a.customNames,new Set(a.extensionProvenance.keys())),a.extensionProvenance.get(r.name.toLowerCase())),file:{path:a.typesPath},generated_at:T()}}async function ew(e,t){let n=I(e);if(n.length===0)throw new f("Status id must not be empty.",h.USAGE);let a=await $t(t),r=ct(a.schema),i=r.alias_to_id.get(n)??n,o=r.by_id.get(i);if(!o)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:Ao(o),file:{path:a.statusesPath},generated_at:T()}}async function tw(e,t,n){let a=N(process.cwd(),n.path);await be(a);let r;try{r=ci({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 i=await A(a),o=V(i.schema),s=dn(a,o),l=[],c=Mt(r.key);c&&l.push(`custom_field_mcp_input_collision:${c.field}:${c.property}:${c.owner}:use=${c.nested_path}`);let d=B(t.author,i.author_default),p=se(i),m=await X(a,xo,i.locks.ttl_seconds,d,!!t.force,p.force_required_for_stale_lock,i.locks.wait_ms),g;try{let y=await G(s),_;try{_=Ze(y)}catch(u){throw new f(u instanceof Error?u.message:String(u),h.GENERIC_FAILURE)}g=li(_,r),await Ce({pmRoot:a,filePath:s,raw:Qe(g.file),op:"schema:add-field",author:d,settings:i}),l.push(...await H({path:s,scope:"project",op:"schema:add-field"}))}finally{await m()}return{action:"add-field",registered:!0,replaced:g.replaced,field:g.definition,file:{path:s,fields:g.file.fields.length},warnings:Pe(l),generated_at:T()}}async function em(e,t,n,a){let r=U(t,W());return(await De(e,t.item_format,r.type_to_folder,[],n)).filter(i=>{let o=i[a];return o==null?!1:Array.isArray(o)?o.length>0:typeof o=="string"?o.trim().length>0:!0}).length}async function nw(e,t,n){let a=N(process.cwd(),n.path);await be(a);let r=await A(a),i=V(r.schema),o=dn(a,i),s=[],l=B(t.author,r.author_default),c=se(r),d=await X(a,xo,r.locks.ttl_seconds,l,!!t.force,c.force_required_for_stale_lock,r.locks.wait_ms),p;try{let m=await G(o),g;try{g=Ze(m)}catch(y){throw new f(y instanceof Error?y.message:String(y),h.GENERIC_FAILURE)}try{p=di(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),_=I(p.definition?.metadata_key??p.definition?.front_matter_key??y);if(_.length>0){let u=await em(a,r,i,_);u>0&&s.push(`items_using_field:${u}`)}await Ce({pmRoot:a,filePath:o,raw:Qe(p.file),op:"schema:remove-field",author:l,settings:r}),s.push(...await H({path:o,scope:"project",op:"schema:remove-field"}))}}finally{await d()}return{action:"remove-field",removed:p.removed,...p.definition?{field:p.definition}:{},file:{path:o,fields:p.file.fields.length},warnings:Pe(s),generated_at:T()}}async function aw(e){let t=await $t(e),n=jt(t.schema).definitions.map(pa);return{action:"list-fields",fields:n,counts:{total:n.length},file:{path:dn(t.pmRoot,t.schema)},generated_at:T()}}async function rw(e,t){let n=I(e);if(n.length===0)throw new f("Field key must not be empty.",h.USAGE);let a=await $t(t),r=jt(a.schema).by_key.get(n);if(!r)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:pa(r),file:{path:dn(a.pmRoot,a.schema)},generated_at:T()}}async function iw(e,t,n){let a=N(process.cwd(),n.path);await be(a);let r;try{let _=cn(e);if(_===void 0)throw new Error(`Type preset name is required. Allowed: ${xt.join(", ")}.`);r=_}catch(_){throw new f(_ instanceof Error?_.message:String(_),h.USAGE)}let i=await A(a),o=V(i.schema),s=$o(a,o),l=[],c=B(t.author,i.author_default),d=se(i),p=[],m=[],g,y=await X(a,ln,i.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,i.locks.wait_ms);try{let _=await G(s),u;try{u=ce(_)}catch(v){throw new f(v instanceof Error?v.message:String(v),h.GENERIC_FAILURE)}let w=u;for(let v of St(r)){let x=Ke(w,v);w=x.file,(x.replaced?m:p).push(x.definition.name)}g=w.definitions.length,await Ce({pmRoot:a,filePath:s,raw:ue(w),op:"schema:apply-preset",author:c,settings:i}),await Et(a,St(r),l,"schema:apply-preset-folder"),l.push(...await H({path:s,scope:"project",op:"schema:apply-preset"}))}finally{await y()}return{action:"apply-preset",preset:r,registered:p,replaced:m,file:{path:s,definitions:g},warnings:Pe(l),generated_at:T()}}function tm(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 ow(e,t){let n=N(process.cwd(),t.path);await be(n);let a=await A(n),r=V(a.schema),i=$o(n,r),o=tm(e.minCount),s=U(a,W()),l=(await De(n,a.item_format,s.type_to_folder,[],r)).map(v=>typeof v.title=="string"?v.title:""),c=bo(l,{minCount:o}),d=[],p=[],m=[],g=[],y;if(!e.apply){let v;try{v=ce(await G(i))}catch(x){throw new f(x instanceof Error?x.message:String(x),h.GENERIC_FAILURE)}return y=v.definitions.length,{action:"infer-types",applied:!1,min_count:o,candidates:c,registered:p,replaced:m,skipped:g,file:{path:i,definitions:y},warnings:d,generated_at:T()}}let _=B(e.author,a.author_default),u=se(a),w=await X(n,ln,a.locks.ttl_seconds,_,!!e.force,u.force_required_for_stale_lock,a.locks.wait_ms);try{let v=await G(i),x;try{x=ce(v)}catch(O){throw new f(O instanceof Error?O.message:String(O),h.GENERIC_FAILURE)}let S=x;for(let O of c){if(O.shadows_builtin){g.push({name:O.name,reason:"shadows_builtin"});continue}let ie;try{ie=lt({name:O.name})}catch{g.push({name:O.name,reason:"invalid_type_token"});continue}let L=Ke(S,ie);S=L.file,(L.replaced?m:p).push(L.definition.name)}y=S.definitions.length,await Ce({pmRoot:n,filePath:i,raw:ue(S),op:"schema:infer-types",author:_,settings:a}),await Et(n,S.definitions.filter(O=>p.includes(O.name)||m.includes(O.name)),d,"schema:infer-types-folder"),d.push(...await H({path:i,scope:"project",op:"schema:infer-types"}))}finally{await w()}return{action:"infer-types",applied:!0,min_count:o,candidates:c,registered:p,replaced:m,skipped:g,file:{path:i,definitions:y},warnings:Pe(d),generated_at:T()}}function sw(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 cw(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 lw(e){let t=e.replaced?"Updated":"Registered",n=e.status.roles&&e.status.roles.length>0?` (roles: ${e.status.roles.join(", ")})`:"",a=e.status.aliases&&e.status.aliases.length>0?` (aliases: ${e.status.aliases.join(", ")})`:"";return`${t} status "${e.status.id}"${n}${a} in ${e.file.path}.`}function dw(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 pw(e){let t=[`Schema types: ${e.counts.total} total (${e.counts.builtin} builtin, ${e.counts.custom} custom, ${e.counts.extension} extension)`];for(let[n,a]of[["builtin",e.builtin],["custom",e.custom],["extension",e.extension]])a.length!==0&&t.push(`${n}: ${a.map(r=>r.name).join(", ")}`);t.push(`statuses: ${e.statuses.counts.total} total (${e.statuses.counts.builtin} builtin, ${e.statuses.counts.custom} custom)`);for(let[n,a]of[["builtin statuses",e.statuses.builtin],["custom statuses",e.statuses.custom]])a.length!==0&&t.push(`${n}: ${a.map(r=>r.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 mw(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 uw(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 nm(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 fw(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 hw(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 gw(e){let t=[`Custom fields: ${e.counts.total} total`];for(let n of e.fields)t.push(` ${nm(n)}`);return t.push("Inspect one: pm schema show-field <key>"),t.join(`
|
|
47
|
+
`)}function yw(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 _w(e){let t=e.registered.length>0?`registered: ${e.registered.join(", ")}`:"",n=e.replaced.length>0?`updated: ${e.replaced.join(", ")}`:"",a=[t,n].filter(r=>r.length>0).join("; ");return`Applied "${e.preset}" type preset to ${e.file.path}${a.length>0?` (${a})`:""}.`}function ww(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 a=n.shadows_builtin?" [shadows built-in, skipped]":"";t.push(` ${n.name} <- "${n.prefix}" (${n.count} items)${a}`)}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 vw={workflowSlotsReferencing:Eo};(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]="1e6087f2-01b5-59c3-a471-433c722316b0")}catch{}})();function ma(e){return e.map(({layer:t,name:n,error:a})=>({layer:t,name:n,error:a}))}function pn(e,t,n){let a=b(t),r=n.trim();if(a.length===0||r.length===0)return;let i=e.get(a)??new Set;i.add(r),e.set(a,i)}function am(e){let t=new Map,n=new Map;for(let a of e.registrations.commands)pn(t,a.name,a.command),pn(n,a.name,a.action);for(let a of e.commands.handlers)pn(t,a.name,a.command);for(let a of e.commands.overrides)pn(t,a.name,a.command);return{commandPathsByExtension:t,actionPathsByExtension:n}}function Oo(e){if(!(!e||e.size===0))return[...e].sort((t,n)=>t.localeCompare(n))}function rm(e){let{enabled:t,normalizedName:n,loadedNames:a,loadFailedNames:r,activationFailedNames:i}=e;return t?r.has(n)||i.has(n)?{runtime_active:!1,activation_status:"failed"}:a.has(n)?{runtime_active:!0,activation_status:"ok"}:{runtime_active:!1,activation_status:"not_loaded"}:{runtime_active:!1,activation_status:"not_loaded"}}function mn(e,t,n){let a=new Set(t.loaded.map(l=>b(l.name))),r=new Set(t.failed.map(l=>b(l.name))),i=new Set(n.failed.map(l=>b(l.name))),{commandPathsByExtension:o,actionPathsByExtension:s}=am(n);return e.map(l=>{let c=b(l.name),d=Oo(o.get(c)),p=Oo(s.get(c)),m={...d?{command_paths:d}:{},...p?{action_paths:p}:{}},g=rm({enabled:l.enabled,normalizedName:c,loadedNames:a,loadFailedNames:r,activationFailedNames:i});return{...l,...g,...m}})}function im(e){let t=0,n=0,a=0;for(let r of e)if(r.startsWith("extension_policy_")){if(t+=1,r.startsWith("extension_policy_violation_")){n+=1;continue}r.startsWith("extension_policy_blocked_")&&(a+=1)}return{warning_count:t,violation_count:n,blocked_count:a}}function z(e,t){return e.vocabulary==="package"?`pm package --${t}`:`pm extension --${t}`}var Ro=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 om(e){return Ro.has(Mo(e))}function Co(e){return e==="project"||e==="global"}function No(e){let t=e.split(":"),n=t[0];if(!n||!Ro.has(n))return null;let a=t.at(-4),r=t.at(-3)?.trim(),i=t.at(-2),o=t.at(-1)?.trim();return!Co(a)||!Co(i)||!r||!o?null:{code:n,surface:t.slice(1,-4).join(":")||"global",winner:{layer:a,name:r},displaced:{layer:i,name:o}}}function sm(e){let t=new Set;for(let n of e){let a=No(n);a&&(t.add(a.winner.name),t.add(a.displaced.name))}return[...t].sort((n,a)=>n.localeCompare(a))}function cm(e,t){let n=e.filter(om);if(n.length===0)return null;let a=sm(n);return`Extension registration collisions or handler/override overlaps detected.${a.length>0?` Conflicting extensions: ${a.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 lm(e,t,n,a){let r=t.map(p=>No(p)).filter(p=>p!==null).sort((p,m)=>`${p.code}:${p.surface}:${p.winner.name}:${p.displaced.name}`.localeCompare(`${m.code}:${m.surface}:${m.winner.name}:${m.displaced.name}`));if(r.length===0)return;let i=e==="global"?"--global":"--project",o=z(a,"deactivate"),s=`${z(a,"doctor")} ${i} --detail deep --trace`,l=new Map(n.map(p=>[b(p.name),p])),c=new Map;for(let p of r)for(let m of[p.winner.name,p.displaced.name]){let g=b(m);c.set(g,(c.get(g)??0)+1)}let d=[...c.entries()].map(([p,m])=>{let g=l.get(p),y=g?.name??p,_=g?.command_paths??[],u=g?.action_paths??[];return{action:"deactivate",extension:y,command:`${o} ${y} ${i}`,affected_collisions:m,feature_loss:{command_paths:[..._].sort((w,v)=>w.localeCompare(v)),action_paths:[...u].sort((w,v)=>w.localeCompare(v))}}}).sort((p,m)=>{let g=m.affected_collisions-p.affected_collisions;if(g!==0)return g;let y=p.feature_loss.command_paths.length+p.feature_loss.action_paths.length,_=m.feature_loss.command_paths.length+m.feature_loss.action_paths.length;return y!==_?y-_:p.extension.localeCompare(m.extension)});return{status:"conflicts_detected",collision_count:r.length,extension_count:c.size,next_best_command:s,collisions:r,remediation_candidates:d}}function Do(e){let t=[];for(let n of e){let a=n.error.toLowerCase();(a.includes("cannot find package '@unbrained/pm-cli'")||a.includes('cannot find module "@unbrained/pm-cli"')||a.includes("cannot find module '@unbrained/pm-cli'"))&&t.push(`extension_load_failed_sdk_dependency_missing:${n.name}`),(a.includes("cannot use import statement outside a module")||a.includes("to load an es module")||a.includes("must use import to load es module"))&&t.push(`extension_load_failed_module_mode_mismatch:${n.name}`)}return[...new Set(t)].sort((n,a)=>n.localeCompare(a))}function jo(e=[]){let t=Array.isArray(e)?e:[],n=[];for(let a of t){if(!a||typeof a.name!="string")continue;let r=a.trace?.missing_capability??a.trace?.capability;typeof r=="string"&&r.trim().length>0&&n.push(`extension_capability_missing:${a.name}:${r.trim().toLowerCase()}`)}return[...new Set(n)].sort((a,r)=>a.localeCompare(r))}function Lo(e,t){let n=[];for(let a of Va(e.loaded,t))for(let r of a.unused)n.push(`extension_capability_unused:${a.layer}:${a.name}:${r}`);return[...new Set(n)].sort((a,r)=>a.localeCompare(r))}var dm=[{matches:e=>e.some(t=>t.startsWith("extension_manifest_")),build:e=>`Run ${z(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: ${Ca.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 ${z(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 ${z(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 ${z(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 ${z(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 ${z(e.options,"doctor")} ${e.scopeFlag}.`},{matches:(e,t)=>t.updateCheckFailedTotal>0,build:e=>`Run ${z(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 pm(e){let{normalizedWarnings:t,options:n,scope:a,scopeFlag:r,updateCheckFailedTotal:i,policyWarningCount:o,unmanagedActionRequiredTotal:s,notCheckedTotal:l,skippedNonGithubTotal:c,updateAvailableTotal:d}=e,p=[],m={options:n,scope:a,scopeFlag:r,updateCheckFailedTotal:i,policyWarningCount:o};if(t.length>0){let g=cm(t,{deactivate:`${z(n,"deactivate")} <name> ${r}`,doctor:`${z(n,"doctor")} ${r} --detail deep --trace`});g&&p.push(g);for(let y of dm)y.matches(t,m)&&p.push(y.build(m))}return s>0&&p.push(`Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via ${z(n,"manage")} ${r} --fix-managed-state (or ${z(n,"adopt-all")} ${r}, ${z(n,"adopt")} <name> ${r}, or reinstall via ${z(n,"install")} ${r} <source>).`),c>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."),l>0&&p.push(`Update-check coverage is partial: some sources have no completed check. Run ${z(n,"manage")} ${r} to request update checks.`),d>0&&p.push(`Update available managed extensions via ${z(n,"install")} ${r} <source>.`),p.length===0&&p.push(`No immediate action required. Re-run ${z(n,"manage")} ${r} after extension changes.`),p}function un(e,t,n,a={}){let r=[...new Set(t)].sort((E,q)=>E.localeCompare(q)),i=n.filter(E=>E.managed).length,o=n.filter(E=>E.enabled).length,s=n.filter(E=>E.active).length,l=n.filter(E=>E.update_check_status==="checked"&&E.update_available===!0).length,c=n.filter(E=>E.managed===!1),d=c.filter(E=>Po(E)).map(E=>E.name).sort((E,q)=>E.localeCompare(q)),p=c.filter(E=>!Po(E)).map(E=>E.name).sort((E,q)=>E.localeCompare(q)),m={checked:0,skipped_unmanaged:0,skipped_non_github:0,failed:0,not_checked:0};for(let E of n)m[E.update_check_status]+=1;let g=m.failed,y=n.filter(E=>E.update_check_status==="skipped_non_github"&&E.source?.kind!=="builtin").length,_=Object.entries({skipped_unmanaged:p.length,skipped_non_github:y,failed:g,not_checked:m.not_checked}).filter(([,E])=>E>0).map(([E,q])=>`extension_update_health_partial_coverage:${E}:${q}`),u=_.length>0,w=u?"partial":"full",v=[...new Set([...r,..._])].sort((E,q)=>E.localeCompare(q)),x=[...new Set(v.map(E=>Mo(E)))].sort((E,q)=>E.localeCompare(q)),S=im(v),O=e==="global"?"--global":"--project",ie=lm(e,r,n,a),L=pm({normalizedWarnings:v,options:a,scope:e,scopeFlag:O,updateCheckFailedTotal:g,policyWarningCount:S.warning_count,unmanagedActionRequiredTotal:p.length,notCheckedTotal:m.not_checked,skippedNonGithubTotal:y,updateAvailableTotal:l});return{status:v.length===0?"ok":"warn",warning_count:v.length,warning_codes:x,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:i,enabled_total:o,active_total:s,update_available_total:l,update_health_coverage:w,update_health_partial:u,unmanaged_loaded_extension_count:c.length,unmanaged_loaded_extensions:c.map(E=>E.name).sort((E,q)=>E.localeCompare(q)),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:m,update_check_failed_total:g,top_warnings:v.slice(0,8),remediation:L,...ie?{collision_plan:ie}:{}}}function Fo(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 Mo(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function Go(e){let t=new Set,n=[];for(let a of e){let r=(()=>{let i=za(a);return i?[i]:Ja(a)})();for(let i of r){let o=`${i.layer}:${i.name}:${i.capability}`;t.has(o)||(t.add(o),n.push(i))}}return n}function Uo(){return{version:Ct.version,capabilities:[...Ct.capabilities],legacy_aliases:{...Ct.legacy_aliases}}}function Po(e){let t=b(e.name),n=b(e.directory);return t.startsWith("builtin-")?!0:n==="beads"||n==="todos"}function zo(e,t,n,a,r){if(e!=="project"||r)return{warnings:[],summary:{active_project_count:0,loaded_project_count:0,active_project_names:[],loaded_project_names:[],missing_active_project_names:[]}};let i=[...new Set(t.filter(c=>c.active).map(c=>b(c.name)))].sort((c,d)=>c.localeCompare(d)),o=[...new Set(n.filter(c=>c.layer==="project").map(c=>b(c.name)))].sort((c,d)=>c.localeCompare(d)),s=new Set(a.map(c=>b(c.name))),l=i.filter(c=>!o.includes(c)&&!s.has(c)).sort((c,d)=>c.localeCompare(d));return{warnings:l.length>0?[`extension_doctor_consistency_active_not_loaded:${l.join(",")}`]:[],summary:{active_project_count:i.length,loaded_project_count:o.length,active_project_names:i,loaded_project_names:o,missing_active_project_names:l}}}(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]="eb830963-f036-5f98-ab26-786240b3e0fd")}catch{}})();var Jo=async(e,t,n)=>{if(!Number.isInteger(t)||t<1)throw new RangeError("concurrency must be a positive integer");let a=new Array(e.length),r=0,i=Array.from({length:Math.min(t,e.length)},async()=>{for(;r<e.length;){let o=r;r+=1,a[o]=await n(e[o])}});return await Promise.all(i),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]="accde468-de04-51b6-81ad-5c5ea218a87b")}catch{}})();function qo(e,t){let n=b(e),a=t.find(r=>b(r.name)===n);return{command_paths:[...a?.command_paths??[]].sort((r,i)=>r.localeCompare(i)),action_paths:[...a?.action_paths??[]].sort((r,i)=>r.localeCompare(i))}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f2cac210-bba0-5c7f-867b-8b59f8d36e11")}catch{}})();function Wo(e,t){let n=new Set((t?.loaded??[]).flatMap(i=>(i.activation?.commands?.length??0)>0?[`${i.layer}:${b(i.name)}`]:[])),a=e.services.overrides.filter(i=>i.service==="output_format").filter(i=>i.passThrough!==!0).filter(i=>!n.has(`${i.layer}:${b(i.name)}`)).map(i=>`extension_output_service_override_global:${i.service}:${i.layer}:${i.name}`),r=e.renderers.overrides.filter(i=>(i.commands?.length??0)===0&&i.resultDiscriminator===void 0).map(i=>`extension_output_renderer_override_global:${i.format}:${i.layer}:${i.name}`);return[...new Set([...a,...r])].sort((i,o)=>i.localeCompare(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]="a1803149-25ca-5bb0-a178-afa2d85d2ec9")}catch{}})();var Bo=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,a)=>a.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]="eb2ad9e2-8e60-5cac-8874-ab9300621402")}catch{}})();var mm=1e4,um=(e,t,n)=>{let a=e.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).map(o=>{let[s,l=""]=o.split(/\s+/);return{commit:s,ref:l}}),r=a.find(o=>o.ref.endsWith("^{}"))??a[0];if(!r)return{checked_at:n,available:null,error:"no_remote_reference_found"};let i=t?.trim();return i?{checked_at:n,remote_commit:r.commit,available:r.commit!==i}:{checked_at:n,remote_commit:r.commit,available:null,error:"missing_installed_commit"}},Ho=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 a=[e.ref?.trim(),"HEAD"].find(Boolean),r=await t(["ls-remote",e.repository,a,`${a}^{}`],void 0,mm);return um(r,e.commit,n)}catch(a){return{checked_at:n,available:null,error:a instanceof Error?a.message:String(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]="fcf7df06-e3b8-5476-a76a-cd391839c13d")}catch{}})();function Ko(e,t){let n=e.filter(a=>a.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:a,result:r})=>{let i=r.details;return{alias:a,ok:r.ok,extension:i.extension,source:i.source,source_resolution:i.source_resolution,install_plan:i.install_plan,dry_run:i.dry_run,destination_path:i.destination_path,activated:i.activated,settings_changed:i.settings_changed,command_paths:i.command_paths,action_paths:i.action_paths,command_discovery:i.command_discovery,verification:i.verification,runtime_activation_status:i.runtime_activation_status,activation_diagnostics:i.activation_diagnostics,warnings:r.warnings}})}}import fm from"node:fs/promises";import hm 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]="955d33c5-8c96-5ed6-bbd1-fc8a26801df4")}catch{}})();function gm(e){return typeof e.name=="string"&&e.name.trim().length>0?e.name.trim():"workspace-manifest"}function ym(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 _m(e){let t=hm.join(e,"manifest.json"),n;try{n=await fm.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 a;try{a=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 a!="object"||a===null||Array.isArray(a))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 r=a,i=Wa(r),o=gm(r);return{path:t,present:!0,parse_status:"valid",package_metadata_location:"package.json#pm",schema_findings:i.findings,warnings:i.findings.map(s=>ym(o,s)),remediation:i.findings.map(s=>s.message)}}function Vo(e){return _m(ja(e))}import qe from"node:fs/promises";import wm 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]="776854e4-6df4-507e-b21b-a4d320946642")}catch{}})();var ua=async e=>qe.readFile(e).catch(t=>{if(rn(t,"ENOENT"))return null;throw t}),Yo=async(e,t,n,a,r)=>Ne("extension_install_backup",async()=>{let i=ht(e),o=Fa(t),[s,l]=await Promise.all([ua(i),ua(o)]);return a&&await qe.cp(n,r,{recursive:!0,force:!0}),{backupDirectory:r,destinationDirectory:n,destinationExists:a,managedStatePath:i,managedStateContents:s,settingsPath:o,settingsContents:l}}),Xo=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(wm.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]="f34e0f7f-952c-5673-82b2-6bf87c10c7be")}catch{}})();var vm=4,ts=[["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"]],bm=ts.map(([,,e])=>e).filter((e,t,n)=>n.indexOf(e)===t).join(", "),km={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"},xm="__pm_native_output",Sm=["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"],ns=["allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],Em=["disabled","require_trusted","require_provenance"],as={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:[]},$m=e=>{let t=e??as,n={};for(let a of Sm)n[a]=ee(t[a]??[]);return n},Im=(e,t)=>{for(let n of ns)t[n].length>0&&(e[n]=t[n]);return e},Am=(e,t)=>{for(let n of Em)t[n]===!0&&(e[n]=!0);return t.sandbox_profile&&(e.sandbox_profile=t.sandbox_profile),e},Tm=e=>{let t={};for(let n of ns)t[n]=ee(e[n]??[]);return t},Om=e=>{let t=typeof e.name=="string"?e.name.trim():"";return t.length===0?null:Im(Am({name:t},e),Tm(e))},Cm=e=>(e??[]).map(t=>Om(t)).filter(t=>t!==null).sort((t,n)=>t.name.localeCompare(n.name)),Pm=e=>{let t=Object.assign({},as,e??{}),n=$m(e),a=Cm(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:a}},rs=async(e,t)=>{let n=[t],a=await Ri(t);a&&n.push(a);let r=[...new Set(n.map(i=>b(i)).filter(i=>i.length>0))];for(let i of r){let o=e.find(l=>b(l.name)===i);if(o)return o;let s=e.find(l=>b(l.directory)===i);if(s)return s}},is=(e,t)=>{let n=t.trim(),a=new Set(ee(e.extensions.enabled));return new Set(ee(e.extensions.disabled)).has(n)?!1:a.size===0?!0:a.has(n)},os=(e,t)=>{let n=t.trim(),a=new Set(ee(e.extensions.enabled)),r=new Set(ee(e.extensions.disabled)),i=[...a],o=[...r];return r.delete(n),a.size>0&&a.add(n),e.extensions.enabled=[...a].sort((s,l)=>s.localeCompare(l)),e.extensions.disabled=[...r].sort((s,l)=>s.localeCompare(l)),e.extensions.enabled.join("\0")!==i.join("\0")||e.extensions.disabled.join("\0")!==o.join("\0")},Rm=(e,t)=>{let n=t.trim(),a=new Set(ee(e.extensions.enabled)),r=new Set(ee(e.extensions.disabled)),i=[...a],o=[...r];return a.delete(n),r.add(n),e.extensions.enabled=[...a].sort((s,l)=>s.localeCompare(l)),e.extensions.disabled=[...r].sort((s,l)=>s.localeCompare(l)),e.extensions.enabled.join("\0")!==i.join("\0")||e.extensions.disabled.join("\0")!==o.join("\0")},Nm=(e,t)=>{let n=t.trim(),a=new Set(ee(e.extensions.enabled)),r=new Set(ee(e.extensions.disabled)),i=[...a],o=[...r];return a.delete(n),r.delete(n),e.extensions.enabled=[...a].sort((s,l)=>s.localeCompare(l)),e.extensions.disabled=[...r].sort((s,l)=>s.localeCompare(l)),e.extensions.enabled.join("\0")!==i.join("\0")||e.extensions.disabled.join("\0")!==o.join("\0")},Dm=e=>{let t=e.trim().toLowerCase(),n=Math.min(2,Math.max(1,Math.ceil(t.length/4))),a=ts.map(([r,i,o])=>({action:i,flag:o,distance:Ua(t,r,n)})).filter(r=>r.distance!==null).sort((r,i)=>r.distance-i.distance)[0];return a?{action:a.action,flag:a.flag}:null},jm=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",a=Dm(e);if(!a)return new f(`One action flag is required. Use one of: ${bm}. Bare \`pm package\` and \`pm extension\` default to --explore.`,h.USAGE);let r=`pm ${n} ${a.flag}`;return ur({command_path:n,display_name:`${n} lifecycle`,token_kind:"action",token:e,allowed:Object.keys(ss),retry_command:r,message_suffix:`. Did you mean "${a.flag}"?`,fallback_candidates:[{source:"lifecycle_action",command:r,reason:`nearest lifecycle action for "${e}"`}]})},Lm=[["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"]],ss={doctor:"doctor",reload:"reload",catalog:"catalog",init:"init",scaffold:"init",explore:"explore",manage:"manage",migrate:"migrate",list:"explore","":"explore"},Fm=e=>ss[e]??null,Mm=(e,t)=>{let n=[...new Set(Lm.filter(([a])=>t[a]===!0).map(([,a])=>a))];if(n.length===0){if(e===void 0)return"explore";let a=Fm(e.trim().toLowerCase());if(a)return a;throw jm(e,t)}if(n.length>1)throw new f("Extension action flags are mutually exclusive.",h.USAGE);return n[0]},Gm=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"},Um=[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"}}],cs=e=>{for(let t of Um){let n=t(e);if(n)return n}return{status:"not_checked",reason:"no_update_check_recorded"}},ls=(e,t,n,a)=>{let r=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:r.contributions,managed:!!n,source:r.source,update_available:r.update_available,last_update_check_at:r.last_update_check_at,last_update_remote_commit:r.last_update_remote_commit,update_error:r.update_error,update_check_status:a.status,update_check_reason:a.reason}},zm=(e,t,n,a)=>{let r=Object.assign({name:e,manifest_version:"unknown",manifest_entry:"unknown"},a),i=a?is(n,a.name):!1;return{warning:`extension_manifest_missing:${t}:${e}`,summary:ls({name:r.name,directory:e,version:r.manifest_version,entry:r.manifest_entry,enabled:i},t,a,cs(a))}},Jm=async(e,t,n,a,r,i)=>{let o=ne.join(e,t),s=ne.join(o,"manifest.json"),l=i.get(b(t));if(!await k(s))return zm(t,n,a,l);let c=Symbol("invalid-extension-manifest-json"),d=await Re.readFile(s,"utf8").then(g=>JSON.parse(g)).catch(()=>c);if(d===c)return{warning:`extension_manifest_invalid_json:${n}:${t}`};let p=Yn(d);if(!p)return{warning:`extension_manifest_invalid:${n}:${t}`};let m=r.get(b(p.name))??i.get(b(t));return{summary:ls({name:p.name,directory:t,version:p.version,entry:p.entry,enabled:is(a,p.name)},n,m,cs(m))}},ge=async(e,t,n,a)=>{if(!await k(e))return{extensions:[],warnings:[]};let r=(await Re.readdir(e,{withFileTypes:!0})).filter(c=>c.isDirectory()).map(c=>c.name).sort((c,d)=>c.localeCompare(d)),i=new Map(a.entries.map(c=>[b(c.name),c])),o=new Map(a.entries.map(c=>[b(c.directory),c])),s=[],l=[];for(let c of r){let d=await Jm(e,c,t,n,i,o);d.warning&&s.push(d.warning),d.summary&&l.push(d.summary)}return{extensions:l.sort((c,d)=>c.name.localeCompare(d.name)),warnings:s.sort((c,d)=>c.localeCompare(d))}},qm=Ha(),Wm=(e,t)=>[t.package,t.kind==="builtin"?t.name:void 0].find(n=>n?.trim())?.trim()??e,Bm=(e,t,n,a)=>{let r=n.command_paths.map(s=>`pm ${s} --help`),i=a?.error.toLowerCase().includes("@unbrained/pm-cli")===!0,o=n.command_paths.length>0?[...r]:["Run pm package doctor --project --detail deep if expected package commands are missing."];return i&&o.unshift("Install @unbrained/pm-cli in the target workspace so declarative package runtime imports resolve, then reinstall the package."),{package_name:Wm(e,t),extension_name:e,command_paths:n.command_paths,action_paths:n.action_paths,help_commands:r,next_steps:o,...i?{sdk_dependency_status:"missing"}:{}}},Hm=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(([,a])=>a!==void 0)),t.missing_capability&&(n.missing_capability=t.missing_capability),t.hint&&(n.hint=t.hint)),n},ds=e=>e.map(t=>Hm(t)).sort((t,n)=>`${t.layer}:${t.name}`.localeCompare(`${n.layer}:${n.name}`)),ps=(e,t,n)=>{let a=b(e);return t.find(r=>(n===void 0||r.layer===n)&&b(r.name)===a)},Km=(e,t,n,a)=>n.find(r=>r.scope===t&&b(r.name)===b(e))?.activation_status??(a?"failed":"unknown"),ms=(e,t,n,a,r)=>qm.enqueue(async()=>{let i=process.env.PM_CLI_PACKAGE_ROOT,o=await Re.mkdtemp(ne.join(t,".pm-module-graph-"));process.env.PM_CLI_PACKAGE_ROOT=me(import.meta.url,["../.."]);try{let s=await ke({pmRoot:e,settings:n,cwd:process.cwd(),noExtensions:r.noExtensions===!0,reload_token:xn(),cache_bust:!0,module_graph_snapshot_root:o}),l=await xe({...s}),c=[...s.failed.map(p=>({layer:p.layer,name:p.name,entry_path:p.entry_path,error:p.error})),...ds(l.failed)],d=Object.fromEntries(s.loaded.map(p=>[b(p.name),Ga(Ve(l,{extensionName:p.name}))]));return{installed:mn(a,s,l),warnings:[...s.warnings,...l.warnings],activation_failures:c,extensions_disabled:s.disabled_by_flag,item_type_registrations:l.registrations.item_types,contribution_inventories:d}}finally{await Re.rm(o,{recursive:!0,force:!0}),i===void 0?delete process.env.PM_CLI_PACKAGE_ROOT:process.env.PM_CLI_PACKAGE_ROOT=i}}),ha=async(e,t,n,a)=>{let r=n.filter(l=>!l.managed),i=[...r].sort((l,c)=>{let d=l.name.localeCompare(c.name);return d!==0?d:l.directory.localeCompare(c.directory)}),o=a,s=[];for(let l of i){let c=ne.join(e,l.directory),d=await it(c),p=T(),m={kind:"local",input:l.name,location:c};o=yt(o,{name:d.manifest.name,directory:l.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:m}),s.push({name:d.manifest.name,directory:l.directory,version:d.manifest.version,entry:d.manifest.entry,source:m})}return s.length>0&&await ze(e,o),{state:o,adopted_entries:s,unmanaged_candidates:i,already_managed_count:n.length-r.length}},Vm=(e,t)=>{let n=N(process.cwd(),t.path),a=Rt(n,process.cwd()),r=e==="global"?La(process.cwd()):n,i=e==="global"?a.global:a.project;return{pm_root:n,scope:e,settings_root:r,selected_root:i,roots:a}},fn=e=>{let t=[e.gh,e.github].filter(a=>typeof a=="string").map(a=>a.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]},Ym=e=>km[e],Xm=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",a=e==="install"?"source":"name",r=`${n} ${a}`,i=Ym(e),o=`<${a}>`,s=`pm ${n} ${i} ${o}`;throw new f(`Action "${e}" requires ${r} input.`,h.USAGE,{code:"missing_lifecycle_target",required:`Provide a ${a} target for ${e}.`,examples:[`pm ${n} ${e} ${o}`,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 ${a} target`}]}})},hn=(e,t,n={})=>{let a=e?.trim();if(a)return a;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 Xm(t,n)},Zm=(e,t)=>{let n=new Set([...t.registrations.item_types.map(a=>({entry:a,count:a.types.length})),...t.registrations.item_fields.map(a=>({entry:a,count:a.fields.length}))].filter(({count:a})=>a>0).map(({entry:a})=>`${a.layer}:${b(a.name)}`));return e.loaded.filter(a=>(a.activation?.commands??[]).length>0).filter(a=>n.has(`${a.layer}:${b(a.name)}`)).map(a=>`extension_schema_narrow_activation:${a.layer}:${a.name}`).filter((a,r,i)=>i.indexOf(a)===r).sort((a,r)=>a.localeCompare(r))},Qm=(e,t)=>{let n=[{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(a=>a.triggered&&!a.allowed);if(n)throw new f(n.message,h.USAGE)},eu=(e,t,n)=>{let a=String(e??"").trim().toLowerCase(),r=[n.init,n.scaffold].includes(!0);return({doctor:["doctor"],reload:["reload"],catalog:["catalog"],init:r?[]:["init","scaffold"]}[t]??[]).includes(a)?void 0:e},tu=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},nu=(e,t,n)=>{let a={ok:n,action:e.action,scope:e.scope,roots:tu(e),warnings:[...new Set(e.warnings)].sort((r,i)=>r.localeCompare(i)),details:t};return e.action==="doctor"&&Object.defineProperty(a,xm,{value:!0,enumerable:!1,configurable:!1}),a},ga=async(e,t,n)=>{let a=Mm(e,t);Qm(a,t);let r=eu(e,a,t),i=Gm(t),o=Vm(i,n),s={action:a,normalizedTarget:r,scope:i,resolvedRoots:o,warnings:[],options:t,global:n},l={...s,withResult:(c,d=!0)=>nu(s,c,d)};return await Du(l)},au=(e,t)=>{let n=t.vocabulary??"extension",a=e.target_path.replace(/\\/g,"/"),r=Ya(a),i={package:`Install dependencies: cd ${r}, then run "npm install"`,extension:`Install type-check dependencies: cd ${r}, then run "npm install -D typescript @types/node @unbrained/pm-cli"`},o={package:`Validate the package: cd ${r}, then run "npm run typecheck" and "npm test"`,extension:`Type-check the source (optional): cd ${r}, then run "npx tsc --noEmit"`},s=[];return[n==="package",t.declarative===!0].every(Boolean)&&s.push("Ensure the target workspace can resolve @unbrained/pm-cli before installing this declarative package."),[i[n],...s,`Install the scaffold: ${st(n==="package"?["install","--project",a]:["extension","--install","--project",a])}`,`Smoke-test command path: pm ${e.command_name}`,o[n],`Run diagnostics: ${n==="package"?"pm package doctor":"pm extension --doctor"} --project --detail summary`]},ru=async e=>{let{action:t,normalizedTarget:n,options:a,withResult:r}=e;if([fn(a),a.ref].filter(s=>typeof s=="string").map(s=>s.trim()).filter(Boolean).length>0)throw new f('Action "init" does not accept --gh/--github/--ref options.',h.USAGE);let i=hn(n,t,a),o=await to(i,a.vocabulary??"extension",a.capability,a.declarative===!0);return r({scaffolded:o.created_directory||o.files.some(s=>s.status==="created"),extension:{name:o.extension_name,command:o.command_name},capability:o.capability,style:o.style,target_path:o.target_path,created_directory:o.created_directory,files:o.files,next_steps:au(o,a)})},iu=async e=>{let{normalizedTarget:t,resolvedRoots:n,warnings:a,options:r,global:i,withResult:o}=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),l=xn(),c=await ke({pmRoot:n.settings_root,settings:s,cwd:process.cwd(),noExtensions:i.noExtensions,reload_token:l,cache_bust:!0});a.push(...c.warnings);let d=await xe(c);a.push(...d.warnings);let p={reload:{token:l,cache_bust:!0,watch:r.watch===!0},loaded_count:c.loaded.length,failed_count:c.failed.length,activated_count:Math.max(0,c.loaded.length-d.failed.length),activation_failed_count:d.failed.length,loaded_extensions:c.loaded.map(m=>({name:m.name,layer:m.layer,version:m.version})),failed_extensions:c.failed.map(m=>({name:m.name,layer:m.layer,error:m.error})),activation_failures:d.failed.map(m=>({name:m.name,layer:m.layer,error:m.error}))};return r.watch===!0&&a.push("extension_reload_watch_hint:watch_mode_requested_non_interactive_single_pass_only"),o(p)},ou=async e=>{let{normalizedTarget:t,scope:n,options:a,global:r,withResult:i}=e;if(typeof t=="string"&&t.length>0&&t!=="catalog")throw new f('Action "catalog" does not accept a package target.',h.USAGE);return i(await Ni(n,r,a))},su=(e,t)=>({kind:"builtin",input:e,location:e,name:e,...t===null?{}:{package:t}}),cu=e=>({kind:"local",input:e.input,location:e.absolute_path}),lu=(e,t)=>({kind:"npm",input:e.input,location:t.resolved_subpath??".",package:t.npm_package,version:t.npm_version}),du=(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}),pu=(e,t,n,a)=>e?su(e,t):n.kind==="local"?cu(n):n.kind==="npm"?lu(n,a):du(n,a),mu=(e,t,n,a)=>e?e.manifest_version!==t?{installed_at:e.installed_at,updated_at:a}:Ii(e.source,n)?{installed_at:e.installed_at,updated_at:e.updated_at}:{installed_at:e.installed_at,updated_at:a}:{installed_at:a,updated_at:a},uu=async(e,t)=>{let{scope:n,resolvedRoots:a,warnings:r}=e,{validated:i,destinationDirectoryName:o}=t,s=await A(a.settings_root),l=await we(a.selected_root);r.push(...l.warnings);let c=ne.join(a.selected_root,o),d=await k(c),p=await an(i.directory,c);await Re.mkdir(a.selected_root,{recursive:!0});let m=await Re.mkdtemp(ne.join(a.selected_root,".pm-extension-install-backup-")),g=ne.join(m,"destination");try{let y=await Yo(a.selected_root,a.settings_root,c,d,g),_=pu(t.bundledAliasName,t.bundledPackageName,t.installSource,t.resolvedSource),u=l.state.entries.find(S=>b(S.name)===b(i.manifest.name)),w=mu(u,i.manifest.version,_,T()),v=yt(l.state,{name:i.manifest.name,directory:o,scope:n,manifest_version:i.manifest.version,manifest_entry:i.manifest.entry,capabilities:[...i.manifest.capabilities],contributions:i.manifest.contributions,...w,source:_}),x=os(s,i.manifest.name);try{p||await go(i.directory,c),await uo(c),await fo(c),await ze(a.selected_root,v),x&&await Ee(a.settings_root,s,"settings:write")}catch(S){try{await Xo(y)}catch(O){throw new AggregateError([S,O],`Extension install failed: ${String(S)}; rollback failed: ${String(O)}`,{cause:O})}throw S}return{settings:s,managedState:v,sourceRecord:_,destinationDirectory:c,destinationExists:d,installInPlace:p,activationChanged:x}}finally{await Re.rm(m,{recursive:!0,force:!0}).catch(()=>{})}},fu=async(e,t,n)=>{let a=n.filter(r=>b(r.name)===b(t)).flatMap(r=>r.types.map(i=>({name:i.name,folder:i.folder})));return e.scope==="project"&&a.length>0&&await Et(e.resolvedRoots.pm_root,a,e.warnings,"install:type-folder"),a},hu=(e,t,n,a,r)=>{let i=ps(t,n.activation_failures,e.scope),o=Km(t,e.scope,n.installed,i),s=[!n.extensions_disabled,o==="ok"].every(Boolean);s||e.warnings.push(`extension_install_activation_failed:${e.scope}:${t}:${o}`);let l={true:{status:"ok",blocking_failure_count:0},false:{status:"degraded",blocking_failure_count:1}};return{activated:s,status:o,failure:i,verification:{status:l[String(s)].status,target_pm_root:e.resolvedRoots.pm_root,activation_status:o,activated:s,registered_commands:a.command_paths,registered_actions:a.action_paths,registered_item_types:r,module_graph_verification:"fresh_in_topology_snapshot",health:l[String(s)]}}},gu=async(e,t)=>{let{scope:n,resolvedRoots:a,warnings:r,global:i,withResult:o}=e,{validated:s,destinationDirectoryName:l}=t,c=await uu(e,t),d=await ge(a.selected_root,n,c.settings,c.managedState);r.push(...d.warnings);let p=await ms(a.pm_root,ne.dirname(a.selected_root),c.settings,d.extensions,i);r.push(...p.warnings);let m=await fu(e,s.manifest.name,p.item_type_registrations),g=qo(s.manifest.name,p.installed),y=hu(e,s.manifest.name,p,g,m),_=p.contribution_inventories[b(s.manifest.name)];return _&&(c.managedState=await Ai(a.selected_root,c.managedState,s.manifest.name,_)),o({extension:{name:s.manifest.name,version:s.manifest.version,entry:s.manifest.entry,capabilities:s.manifest.capabilities,directory:l},source:c.sourceRecord,source_resolution:t.sourceResolution,...t.installPlan?{install_plan:t.installPlan}:{},destination_path:c.destinationDirectory,overwritten:[c.destinationExists,!c.installInPlace].every(Boolean),installed_in_place:c.installInPlace,activated:y.activated,settings_changed:c.activationChanged,runtime_activation_status:y.status,command_paths:g.command_paths,action_paths:g.action_paths,contributions:_,command_discovery:Bm(s.manifest.name,c.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)},yu=async e=>{let{options:t,global:n,warnings:a,withResult:r}=e;if(typeof t.ref=="string"&&t.ref.trim().length>0)throw new f('Action "install all" does not accept --ref.',h.USAGE);let i=[],o=new Map;for(let s of await Zt()){let l=await _t(s),c=ne.resolve(l),d=o.get(c);d===void 0&&(d=await ga(s,{...t,install:!0},n),o.set(c,d)),i.push({alias:s,result:d})}return a.push(...i.flatMap(s=>s.result.warnings)),r(Ko(i,t.dryRun===!0),i.every(s=>s.result.ok))},_u=async(e,t,n)=>{let{resolvedRoots:a}=e,{bundledAliasName:r,bundledPackageName:i,installSource:o,sourceResolution:s}=await vo(t,n,e.options.ref);if(s.ambiguous){let c=s.candidates.find(d=>d.kind==="npm");e.warnings.push(`extension_install_source_ambiguous:${t}:builtin:${r}:npm:${c.package}`)}let l=await Ji(o);try{let c=await it(l.directory,{source_kind:o.kind,source_input:o.input,source_root:l.source_root}),d=Yt(c.manifest.name),p=e.options.dryRun===!0||o.kind==="local"&&r===null?await _o(l,ne.join(a.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:c.manifest.name,version:c.manifest.version},source_resolution:s,install_plan:p}):await la(a.settings_root,d,()=>gu(e,{validated:c,destinationDirectoryName:d,bundledAliasName:r,bundledPackageName:i,sourceResolution:s,installSource:o,resolvedSource:l,installPlan:p}))}finally{l.cleanup&&await l.cleanup()}},wu=async e=>{let t=fn(e.options),n=t??hn(e.normalizedTarget,e.action,e.options);return[t===void 0,Oi(n)].every(Boolean)?yu(e):_u(e,n,t)},vu=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:a,warnings:r,options:i,withResult:o}=e;if(t!==void 0)throw new f('Action "adopt-all" does not accept a target argument.',h.USAGE);if(fn(i)!==void 0||typeof i.ref=="string"&&i.ref.trim().length>0)throw new f('Action "adopt-all" does not accept --gh/--github/--ref options.',h.USAGE);let s=await A(a.settings_root),l=await we(a.selected_root);r.push(...l.warnings);let c=await ge(a.selected_root,n,s,l.state);r.push(...c.warnings);let d=await ha(a.selected_root,n,c.extensions,l.state),p=await ge(a.selected_root,n,s,d.state);r.push(...p.warnings);let m=un(n,r,p.extensions,i);r.push(...m.warnings);let g=new Map(p.extensions.map(u=>[`${b(u.name)}:${b(u.directory)}`,u])),y=new Map(p.extensions.map(u=>[b(u.directory),u])),_=d.adopted_entries.map(u=>{let w=b(u.directory),v=g.get(`${b(u.name)}:${w}`)??y.get(w);return{...u,...us(v)}});return o({adopted_all:_.length>0,adopted_count:_.length,already_managed_count:d.already_managed_count,extensions:_,triage:m,warning_codes:m.warning_codes,update_health_partial:m.update_health_partial,update_health_coverage:m.update_health_coverage})},us=e=>({update_check_status:e?.update_check_status??null,update_check_reason:e?.update_check_reason??null}),bu=(e,t,n,a)=>{if(e===void 0)return{kind:"local",input:t,location:n};let r=tn(e,{forceGithub:!0,ref:a});if(r.kind!=="github")throw new f(`Invalid GitHub shorthand "${e}".`,h.USAGE);return{kind:"github",input:r.input,location:r.subpath??".",repository:r.repository,owner:r.owner,repo:r.repo,ref:r.ref,subpath:r.subpath}},ku=async e=>{let{action:t,normalizedTarget:n,scope:a,resolvedRoots:r,warnings:i,options:o,withResult:s}=e,l=hn(n,t,o),c=fn(o),d=await A(r.settings_root),p=await we(r.selected_root);i.push(...p.warnings);let m=await ge(r.selected_root,a,d,p.state);i.push(...m.warnings);let g=await rs(m.extensions,l);if(!g)throw new f(`Installed extension "${l}" was not found in ${a} scope.`,h.NOT_FOUND);if(g.managed)return s({adopted:!1,already_managed:!0,extension:{name:g.name,directory:g.directory}});let y=ne.join(r.selected_root,g.directory),_=await it(y),u=T(),w=bu(c,l,y,o.ref),v=yt(p.state,{name:_.manifest.name,directory:g.directory,scope:a,manifest_version:_.manifest.version,manifest_entry:_.manifest.entry,capabilities:[..._.manifest.capabilities],contributions:_.manifest.contributions,installed_at:u,updated_at:u,source:w});await ze(r.selected_root,v);let x=await ge(r.selected_root,a,d,v);i.push(...x.warnings);let S=x.extensions.find(O=>b(O.name)===b(_.manifest.name))??x.extensions.find(O=>b(O.directory)===b(g.directory));return s({adopted:!0,extension:{name:_.manifest.name,directory:g.directory,version:_.manifest.version,entry:_.manifest.entry},source:w,...us(S)})},fs=async e=>{let{action:t,normalizedTarget:n,scope:a,resolvedRoots:r,warnings:i,options:o}=e,s=hn(n,t,o),l=await A(r.settings_root),c=await we(r.selected_root);i.push(...c.warnings);let d=await ge(r.selected_root,a,l,c.state);i.push(...d.warnings);let p=await rs(d.extensions,s);if(!p)throw new f(`Installed extension "${s}" was not found in ${a} scope.`,h.NOT_FOUND);return{settings:l,managedStateRead:c,candidate:p}},xu=async e=>{let{resolvedRoots:t,withResult:n}=e,{settings:a,managedStateRead:r,candidate:i}=await fs(e),o=ne.join(t.selected_root,i.directory);await Re.rm(o,{recursive:!0,force:!0});let s={...r.state,updated_at:T(),entries:r.state.entries.filter(c=>b(c.name)!==b(i.name)&&b(c.directory)!==b(i.directory))};await ze(t.selected_root,s);let l=Nm(a,i.name);return l&&await Ee(t.settings_root,a,"settings:write"),n({removed:!0,extension:{name:i.name,directory:i.directory},destination_path:o,settings_changed:l})},Zo=async e=>{let{action:t,resolvedRoots:n,warnings:a,global:r,withResult:i}=e,{settings:o,candidate:s}=await fs(e),l=t==="activate"?os(o,s.name):Rm(o,s.name);l&&await Ee(n.settings_root,o,"settings:write");let c=t==="activate"?await ms(n.pm_root,ne.dirname(n.selected_root),o,[s],r).then(d=>(a.push(...d.warnings),ps(s.name,d.activation_failures,e.scope))):void 0;return c&&a.push(`extension_activate_failed:${e.scope}:${s.name}`),i({extension:{name:s.name,directory:s.directory},active:t==="activate"&&c===void 0,runtime_active:t==="activate"&&c===void 0,activation_failure:c??null,settings_changed:l,settings:{enabled:[...o.extensions.enabled],disabled:[...o.extensions.disabled]}},c===void 0)},Su=(e,t,n,a,r,i)=>{let o=a==="package"?"package":"extension",s={package:"doctor",extension:"--doctor"}[o],l=r?.adopted_entries.length??0,c=[[i!==null,i??""],[t>0,`Run pm ${o} explore --project and pm ${o} explore --global to inspect load failures.`],[n>0,`Review activation failures in pm ${o} ${s} --detail deep output.`],[l>0,`Managed-state fix adopted ${l} extension(s).`]];return[...new Set([...e,...c.filter(([d])=>d).map(([,d])=>d)].map(d=>d.trim()).filter(d=>d.length>0))]},fa=e=>e.loaded.some(t=>t.layer==="global")||e.failed.some(t=>t.layer==="global")||e.warnings.some(t=>t.includes(":global:")),Eu=(e,t,n,a)=>{if(e!=="project"||t||!fa(a))return null;let r=n==="package"?"package":"extension";return`Global ${r} registrations are included in project diagnostics. For hermetic ${r} smoke tests, rerun pm ${r} doctor --project --isolated --detail deep --trace, or set PM_GLOBAL_PATH to a temporary directory for the whole test process.`},$u=(e,t,n)=>{if(String(e??"").trim().length>0)throw new f('Action "doctor" does not accept a target argument.',h.USAGE);let a=[n.isolated,n.ignoreGlobal].includes(!0);if([a,t==="global"].every(Boolean))throw new f("--isolated and --ignore-global are only valid with project-scope doctor diagnostics.",h.USAGE);let r=Fo(n.detail),i=n.trace===!0;if([i,r!=="deep"].every(Boolean))throw new f("--trace requires --detail deep with --doctor.",h.USAGE);return{isolated:a,detailMode:r,includeTrace:i}},Iu=async(e,t,n)=>{if(e.options.fixManagedState!==!0)return{state:n,fix:null};let a=await ha(e.resolvedRoots.selected_root,e.scope,t,n);return{state:a.state,fix:a}},Au=(e,t,n,a)=>{let r=n==="package"?"package":"extension";if(e!=="project")return{isolated:t,global_extensions_included:!1,global_diagnostics_present:fa(a),rerun_command:null,pm_global_path_recipe:null};let i=`pm ${r} doctor --project --isolated --detail deep --trace`;return{isolated:t,global_extensions_included:!t,global_diagnostics_present:fa(a),rerun_command:t?null:i,pm_global_path_recipe:`PM_GLOBAL_PATH=$(mktemp -d) pm ${r} doctor --project --detail deep --trace`}},Tu=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:a,warnings:r,options:i,global:o,withResult:s}=e,{isolated:l,detailMode:c,includeTrace:d}=$u(t,n,i),p=await A(a.settings_root),m=await we(a.selected_root);r.push(...m.warnings);let g=await ge(a.selected_root,n,p,m.state);r.push(...g.warnings);let{state:y,fix:_}=await Iu(e,g.extensions,m.state),u=await ge(a.selected_root,n,p,y);r.push(...u.warnings);let w=await ke({pmRoot:a.pm_root,settings:p,cwd:process.cwd(),noExtensions:o.noExtensions===!0,ignoreGlobalExtensions:l}),v=await xe({...w,loaded:w.loaded}),x=await Vo(a.pm_root);r.push(...x.warnings,...w.warnings),r.push(...Do(w.failed)),r.push(...v.warnings),r.push(...jo(v.failed)),r.push(...Lo(w,v)),r.push(...Wo(v,w)),r.push(...Zm(w,v)),r.push(...Bo(v));let S=mn(u.extensions,w,v),O=zo(n,S,w.loaded.map(C=>({layer:C.layer,name:C.name})),w.failed.map(C=>({name:C.name})),w.disabled_by_flag);r.push(...O.warnings);let ie=S.filter(C=>C.update_check_status==="failed").map(C=>`extension_update_check_failed:${C.name}`);r.push(...ie);let L=un(n,r,S,i);r.push(...L.warnings);let E=[...L.warnings],q={mode:w.policy.mode,trust_mode:w.policy.trust_mode,require_provenance:w.policy.require_provenance,default_sandbox_profile:w.policy.default_sandbox_profile,sandbox_enforcement:"advisory: sandbox_profile/permissions are declaration-based load gates, not runtime isolation (ADR pm-6ef3)",trusted_extensions_count:w.policy.trusted_extensions.length,allowed_extensions_count:w.policy.allowed_extensions.length,blocked_extensions_count:w.policy.blocked_extensions.length,allowed_capabilities_count:w.policy.allowed_capabilities.length,blocked_capabilities_count:w.policy.blocked_capabilities.length,allowed_surfaces_count:w.policy.allowed_surfaces.length,blocked_surfaces_count:w.policy.blocked_surfaces.length,allowed_commands_count:w.policy.allowed_commands.length,blocked_commands_count:w.policy.blocked_commands.length,allowed_actions_count:w.policy.allowed_actions.length,blocked_actions_count:w.policy.blocked_actions.length,allowed_services_count:w.policy.allowed_services.length,blocked_services_count:w.policy.blocked_services.length,extension_override_count:w.policy.extension_overrides.length},ot=Go(E),yn=Uo(),Ia=L.warning_codes,Ks=Eu(n,l,i.vocabulary,w),Vs=Su(L.remediation,w.failed.length,v.failed.length,i.vocabulary,_,Ks),Aa=Au(n,l,i.vocabulary,w),Ys={status:L.status,scope:n,warning_count:L.warning_count,warning_codes:Ia,total_extensions:S.length,managed_total:S.filter(C=>C.managed).length,enabled_total:S.filter(C=>C.enabled).length,active_total:S.filter(C=>C.active).length,unmanaged_loaded_extension_count:L.unmanaged_loaded_extension_count,unmanaged_action_required_extension_count:L.unmanaged_action_required_extension_count,unmanaged_expected_extension_count:L.unmanaged_expected_extension_count,runtime_active_total:S.filter(C=>C.runtime_active===!0).length,activation_status_totals:{ok:S.filter(C=>C.activation_status==="ok").length,failed:S.filter(C=>C.activation_status==="failed").length,not_loaded:S.filter(C=>C.activation_status==="not_loaded").length,unknown:S.filter(C=>C.activation_status==="unknown").length},unknown_capability_count:ot.length,capability_contract_version:yn.version,update_available_total:L.update_available_total,update_check_status_totals:L.update_check_status_totals,update_health_coverage:L.update_health_coverage,update_health_partial:L.update_health_partial,update_check_failed_total:S.filter(C=>C.update_check_status==="failed").length,load_failure_count:w.failed.length,activation_failure_count:v.failed.length,load_failures:ma(w.failed),activation_failures:ma(v.failed),blocking_failure_count:w.failed.length+v.failed.length,has_blocking_failures:w.failed.length+v.failed.length>0,consistency_warning_count:O.warnings.length,trace_enabled:d,isolation:Aa,policy:q,remediation:Vs},Xs=_?{requested:!0,applied:_.adopted_entries.length>0,adopted_count:_.adopted_entries.length,already_managed_count:_.already_managed_count,adopted_extensions:_.adopted_entries.map(C=>C.name)}:{requested:!1,applied:!1,adopted_count:0,already_managed_count:u.extensions.filter(C=>C.managed).length,adopted_extensions:[]},_n={mode:c,summary:Ys,triage:L,trace_enabled:d,capability_contract:yn,capability_guidance:ot,managed_state_fix:Xs,author_manifest:x,isolation:Aa,policy:w.policy};if(c==="deep"){let C=d?v.failed:v.failed.map(D=>{let{trace:vf,...Zs}=D;return Zs});_n.deep={warnings:E,warning_codes:Ia,capability_contract:yn,capability_guidance:ot,trace_enabled:d,managed_state:{path:m.path,count:y.entries.length,entries:y.entries},installed_extensions:S,load:{roots:w.roots,policy:w.policy,warnings:w.warnings,failed:w.failed,loaded:w.loaded.map(D=>({layer:D.layer,directory:D.directory,name:D.name,version:D.version,entry:D.entry,priority:D.priority}))},activation:{failed:C,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:O.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)},Ou=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:a,warnings:r,options:i,global:o,withResult:s}=e,l=await A(a.settings_root),c=await ke({pmRoot:a.pm_root,settings:l,cwd:process.cwd(),noExtensions:o.noExtensions===!0}),d=await xe(c);r.push(...c.warnings),r.push(...d.warnings);let p=io(t,c,d);if(t!==void 0&&p.extensions.length===0){let m=i.vocabulary==="package"?"package":"extension",g=[...new Set(c.loaded.map(_=>i.vocabulary==="package"&&typeof _.source_package=="string"&&_.source_package.trim().length>0?_.source_package.trim():_.name))].sort((_,u)=>_.localeCompare(u)),y=g.length>0?` Loaded ${m} names: ${g.join(", ")}.`:"";throw new f(`No loaded ${m} named "${t}" was found in ${n} scope.${y} Run pm ${m} explore to list discovered ${m}s.`,h.NOT_FOUND)}return s({target:p.target,total:p.total,extensions:p.extensions,union:p.union,command_ownership:p.command_ownership})},Cu=async(e,t,n)=>{let a=n,r=null;if([e.action==="manage",e.options.fixManagedState===!0].every(Boolean)&&(r=await ha(e.resolvedRoots.selected_root,e.scope,t,n),a=r.state),e.action==="manage"){let i=await Jo(a.entries,vm,async o=>{if(o.source.kind!=="github")return o;let s=await Ho(o.source);return{...o,last_update_check_at:s.checked_at,last_update_remote_commit:s.remote_commit,update_available:s.available,update_error:s.error}});a={...a,updated_at:T(),entries:gt(i)},await ze(e.resolvedRoots.selected_root,a)}return{state:a,fix:r}},Pu=async(e,t,n)=>{let a=await ke({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),r=await xe({...a,loaded:a.loaded});return e.warnings.push(...a.warnings,...r.warnings),{installed:mn(n,a,r),failures:ds(r.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:a.failed.length,activation_failure_count:r.failed.length,warning_count:[...new Set([...a.warnings,...r.warnings])].length,policy:a.policy}}},Ru=(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},Qo=async e=>{let{action:t,scope:n,resolvedRoots:a,warnings:r,options:i,withResult:o}=e,s=await A(a.settings_root),l=Pm(s.extensions.policy),c=await we(a.selected_root);r.push(...c.warnings);let d=await ge(a.selected_root,n,s,c.state);r.push(...d.warnings);let{state:p,fix:m}=await Cu(e,d.extensions,c.state),g=await ge(a.selected_root,n,s,p);if(r.push(...g.warnings),t==="manage"){let v=g.extensions.filter(x=>x.update_check_status==="failed").map(x=>`extension_update_check_failed:${x.name}`);r.push(...v)}let y=await Pu(e,s,g.extensions),_=y.installed,u=un(n,r,_,i);r.push(...u.warnings);let w={total:_.length,managed_total:_.filter(v=>v.managed).length,enabled_total:_.filter(v=>v.enabled).length,active_total:_.filter(v=>v.active).length,extensions:_,triage:u,policy:l};return y.failures!==void 0&&(w.activation_diagnostics={failed_count:y.failures.length,failed:y.failures}),t==="explore"&&(w.runtime_probe=y.summary),t==="manage"&&(w.runtime_probe=y.summary,w.managed_state_fix=Ru(m,_)),o(w)},es={init:ru,install:wu,uninstall:xu,explore:Qo,manage:Qo,describe:Ou,reload:iu,doctor:Tu,catalog:ou,adopt:ku,"adopt-all":vu,activate:Zo,deactivate:Zo,migrate:Or},Nu=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),Du=e=>Nu(e)?la(e.resolvedRoots.settings_root,`${e.action}-state`,()=>es[e.action](e)):es[e.action](e);import wa from"node:fs/promises";import J from"node:path";import hs from"node:readline/promises";import{stdin as gs,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]="04a94059-e242-58a6-9138-bc48a24e267e")}catch{}})();var ys=["ask","add","skip","status"],ju=["AGENTS.md","CLAUDE.md"],Lu=["pm init","pm context","pm search","pm create","pm claim","pm files","pm docs","pm test --run","pm close","pm release","pm_author"],Fu=8,va=1,Mu="<!-- pm-cli:agent-guidance:start:",Gu=`<!-- pm-cli:agent-guidance:start:v${va} -->`,ya="<!-- pm-cli:agent-guidance:end -->",Tt="Add workflow guidance later: pm init --agent-guidance add",zv={toPortableRelativePath:We,ensureTrailingNewline:_a,detectLineEnding:ws,findGuidanceBlockRange:ba,buildAgentGuidanceBlock:vs,upsertAgentGuidanceBlock:ka,resolveProjectRoot:ks,resolveTargetGuidancePath:xs,parsePromptChoice:Ss,pushUnique:Be,promptForGuidanceWrite:Es,normalizeAgentGuidanceState:xa,applyAgentGuidanceState:Is,writeGuidanceFile:Sa,setAgentGuidanceReadlineFactoryForTests:Uu},_s=()=>hs.createInterface({input:gs,output:It});function Uu(e){_s=e??(()=>hs.createInterface({input:gs,output:It}))}function We(e,t){let n=J.relative(e,t);return n.length===0?J.basename(t):n.split(J.sep).join("/")}function _a(e){return e.endsWith(`
|
|
50
|
+
`)?e:`${e}
|
|
51
|
+
`}function ws(e){return e.includes(`\r
|
|
52
|
+
`)?`\r
|
|
53
|
+
`:`
|
|
54
|
+
`}function ba(e){let t=e.indexOf(Mu);if(t===-1)return null;let n=e.indexOf(ya,t);return n===-1?null:{start_index:t,end_index:n+ya.length}}function zu(e){return ba(e)!==null}function vs(e,t="<your project test command>"){return[Gu,"## 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.","",ya,""].join(e)}function ka(e,t="<your project test command>"){let n=ws(e),a=vs(n,t),r=ba(e);if(r){let s=e.slice(r.end_index),l=s.startsWith(`\r
|
|
55
|
+
`)?s.slice(2):s.startsWith(`
|
|
56
|
+
`)?s.slice(1):s,c=_a(`${e.slice(0,r.start_index)}${a}${l}`);return{next_content:c,changed:c!==e}}let i=e.length===0?"":e.endsWith(`
|
|
57
|
+
`)?`
|
|
58
|
+
`:`
|
|
59
|
+
|
|
60
|
+
`,o=_a(`${e}${i}${a}`);return{next_content:o,changed:o!==e}}async function bs(e){if(await k(J.join(e,"scripts","run-tests.mjs")))return"node scripts/run-tests.mjs test";let t;try{t=JSON.parse(await wa.readFile(J.join(e,"package.json"),"utf8"))}catch{return"<your project test command>"}let n=Ju(t);if(n===void 0)return"<your project test command>";let a=n.packageManager?.split("@")[0];return a==="pnpm"?"pnpm test":a==="bun"?"bun run test":a==="yarn"?"yarn test":a==="npm"?"npm test":await k(J.join(e,"pnpm-lock.yaml"))?"pnpm test":await k(J.join(e,"bun.lock"))||await k(J.join(e,"bun.lockb"))?"bun run test":await k(J.join(e,"yarn.lock"))?"yarn test":"npm test"}function Ju(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 ks(e,t){let n=J.dirname(e);return J.basename(e)==="pm"&&J.basename(n)===".agents"?J.dirname(n):J.resolve(t,e)}function xs(e,t){let n=e.find(r=>J.basename(r.file_path)==="AGENTS.md"&&r.exists);if(n)return n.file_path;let a=e.find(r=>r.exists);return a?a.file_path:J.join(t,"AGENTS.md")}function Ss(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 Es(e){let t=_s();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
|
+
`),Ss(n,!0)}finally{t.close()}}function xa(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:va,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,a)=>n.localeCompare(a)):[]}}async function $s(e){let t=[],n=await bs(e);for(let a of ju){let r=J.join(e,a),i=await k(r);if(!i){t.push({file_path:r,exists:i,has_guidance:!1,has_marker:!1});continue}let o=await wa.readFile(r,"utf8"),s=o.toLowerCase(),l=Lu.filter(d=>s.includes(d)),c=zu(o);t.push({file_path:r,exists:i,has_guidance:c||l.length>=Fu,has_marker:c,outdated:c&&ka(o,n).changed})}return t}function Be(e,t){e.includes(t)||e.push(t)}function Is(e,t){let n=xa(e),a=JSON.stringify(n)!==JSON.stringify(t);return a&&(e.agent_guidance=t),{changed:a,state:t}}async function Sa(e,t=J.dirname(e)){let n=await k(e)?await wa.readFile(e,"utf8"):"",a=ka(n,await bs(t));return a.changed?(await oe(e,a.next_content),{changed:!0,warnings:await H({path:e,scope:"project",op:"init:agent_guidance_file"})}):{changed:!1,warnings:[]}}function qu(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 Wu(e,t,n){return e?await $s(n):t}function At(e,t,n){e.state={...e.state,...n,template_version:va,last_checked_files:t}}async function As(e,t){if(t.presentBefore)return;let n=await Sa(t.targetPath,t.projectRoot);e.warnings.push(...n.warnings),n.changed&&(e.applied=!0,e.warnings.push(`agent_guidance:added:${t.targetRelativePath}`))}function Bu(e,t){t||(e.warnings.push("agent_guidance:missing"),Be(e.nextSteps,Tt))}function Hu(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 Ku(e,t){await As(e,t),At(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""})}function Vu(e,t){e.state.declined&&At(e,t,{prompt_completed:!0,declined:!1,declined_at:""})}function Yu(e){e.skipped=!0,e.warnings.push("agent_guidance:skipped_declined"),Be(e.nextSteps,Tt)}async function Xu(e,t){if(e.prompted=!0,await Es(t.targetRelativePath)){await As(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 Zu(e){e.warnings.push("agent_guidance:missing_non_interactive"),Be(e.nextSteps,Tt)}async function Qu(e,t){let n={warnings:[],nextSteps:[],prompted:!1,applied:!1,skipped:!1,state:e};return t.mode==="status"?(Bu(n,t.presentBefore),n):t.mode==="skip"?(Hu(n,t.checkedFiles),n):t.mode==="add"?(await Ku(n,t),n):t.presentBefore?(Vu(n,t.checkedFiles),n):n.state.prompt_completed&&n.state.declined?(Yu(n),n):t.interactive?(await Xu(n,t),n):(Zu(n),n)}async function Ts(e){let t=ks(e.pm_root,e.cwd),n=await $s(t),a=xs(n,t),r=We(t,a),i=n.map(d=>We(t,d.file_path)),o=n.some(d=>d.has_guidance),s=await Qu(xa(e.settings),{mode:e.mode,interactive:e.interactive,targetPath:a,targetRelativePath:r,checkedFiles:i,presentBefore:o,projectRoot:t});if(e.mode==="add")for(let d of n.filter(p=>p.outdated)){let p=await Sa(d.file_path,t);s.applied||=p.changed,s.warnings.push(...p.warnings)}let l=Is(e.settings,s.state);n=await Wu(s.applied,n,t);let c=n.filter(d=>d.outdated).map(d=>We(t,d.file_path));return c.length>0&&(s.warnings.push(`agent_guidance_outdated:${c.join(",")}`),Be(s.nextSteps,"pm init --agent-guidance add")),{summary:qu({mode:e.mode,scans:n,projectRoot:t,targetRelativePath:r,prompted:s.prompted,applied:s.applied,skipped:s.skipped,state:s.state}),warnings:s.warnings,next_steps:s.nextSteps,settings_changed:l.changed}}import ef from"node:fs/promises";import F from"node:path";import Cs from"node:readline/promises";import{stdin as Ps,stdout as Q}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]="95053097-fc76-5587-ab41-8cb05b9d3cd9")}catch{}})();var tf=Symbol.for("pm.sdk.init-invocation-cwd");function mb(e,t=!1){if(t){let n=e.warnings.filter(a=>!/^(?:already_exists:|updated:|registered_type_preset:)/u.test(a));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 ub={normalizeInitGovernancePreset:Ea,normalizeInitTypePreset:Ns,normalizeOptionalInitAuthor:Ds,normalizeInitAgentGuidanceMode:Fs,isPathLikeInitTarget:gn,resolveInitInvocation:js,resolveInitPrefixInput:Ls,parseYesNoChoice:Ms,applyGovernancePreset:$a,runInitWizard:Ws,setInitReadlineFactoryForTests:nf,summarizeInstalledPackages:Gs,buildInitNextSteps:Bs,registerInitTypePreset:Us,assertExplicitTrackerPathIsNotWorkspaceRoot:Js,isLikelyWorkspaceRoot:zs,installInitMergeFence:Hs},Rs=()=>Cs.createInterface({input:Ps,output:Q});function nf(e){Rs=e??(()=>Cs.createInterface({input:Ps,output:Q}))}function af(){return structuredClone(vn)}var rf=["minimal","default","strict"];function Ea(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: ${rf.join(", ")}`,h.USAGE)}function Ns(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 Ds(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:F.isAbsolute(t)||/^[a-z]:/iu.test(t)||t.startsWith(".")||t.includes("/")||t.includes("\\")}function js(e,t,n,a){let r=a?.trim();if(a!==void 0&&r?.length===0)throw new f("--workspace must not be empty",h.USAGE);if(r!==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 c=F.resolve(e,r),d=F.join(c,".agents","pm");return{pmRoot:d,prefixArg:n,target:{mode:"workspace-path",tracker_root:d,workspace_root:c}}}if(t.path===void 0&&gn(n)){let c=F.resolve(e,n.trim());return{pmRoot:c,prefixArg:void 0,target:{mode:"tracker-path",tracker_root:c}}}let i=N(e,t.path),o=F.join(F.resolve(e),".agents","pm"),s=F.dirname(F.dirname(i)),l=F.resolve(i)===o?"current":"ancestor";return{pmRoot:i,prefixArg:n,target:t.path===void 0?{mode:"workspace-discovery",tracker_root:i,workspace_root:s,discovery:l,requested_cwd:F.resolve(e),...l==="ancestor"?{suggested_current_tracker_root:o}:{}}:{mode:"tracker-path",tracker_root:i}}}function Ls(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 Fs(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: ${ys.join(", ")}`,h.USAGE)}function Ms(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}function $a(e,t){let n=Ra[t];e.governance={preset:t,...n},e.validation.parent_reference=n.parent_reference,e.validation.metadata_profile=n.metadata_profile}function of(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Gs(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(of).map(n=>({alias:typeof n.alias=="string"?n.alias:"",ok:n.ok===!0})):[]}}async function Us(e,t,n){let a=V(t.schema),r=ae(e,a.files.types,Z.types),i=ce(await G(r)),o=[],s=[];for(let l of St(n)){let c=Ke(i,l);i=c.file,(c.replaced?s:o).push(c.definition.name)}return await He({pmRoot:e,filePath:r,raw:ue(i),op:"init:type-preset",author:B(void 0,t.author_default),lockTtlSeconds:t.locks.ttl_seconds,lockWaitMs:t.locks.wait_ms}),{name:n,registered:o,updated:s,file:r}}async function zs(e){let t=[".git","package.json","pnpm-workspace.yaml","AGENTS.md",F.join(".agents","pm")];for(let n of t)if(await k(F.join(e,n)))return!0;return!1}async function Js(e,t,n){if(!t||n||await k(F.join(e,"settings.json"))||!await zs(e))return;let a=F.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 ${a} 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 ${a} init --yes`}})}async function qs(e,t){let n=[],a=[];for(let r of t){let i=r?F.join(e,r):e,o=await k(i);await ef.mkdir(i,{recursive:!0}),o?a.push(`already_exists:${i}`):n.push(i),a.push(...await H({path:i,scope:"project",op:"init:ensure_dir"}))}return{createdDirs:n,warnings:a}}async function Ws(e,t){let n=Rs();try{Q.write(`pm init setup wizard (agent-optimized)
|
|
65
|
+
`),Q.write(`This walkthrough is non-destructive and each choice can be changed later with pm config.
|
|
66
|
+
|
|
67
|
+
`),Q.write(`1/3 Item ID prefix
|
|
68
|
+
`),Q.write(`Prefix is prepended to generated IDs (for example pm-a1b2).
|
|
69
|
+
`);let a=await n.question(`Item ID prefix [${e}]: `),r=a.trim().length>0?$e(a):e;Q.write(`
|
|
70
|
+
2/3 Governance preset
|
|
71
|
+
`),Q.write(`minimal: no ownership blocking, progressive create defaults, close validation off.
|
|
72
|
+
`),Q.write(`default: ownership conflict warnings, progressive create defaults, close validation warn.
|
|
73
|
+
`),Q.write(`strict: ownership blocking, strict create defaults, close validation strict.
|
|
74
|
+
`);let i=await n.question("Governance preset [minimal/default/strict] (default: minimal): "),o=i.trim().length>0?i.trim():"minimal",s="minimal";try{s=Ea(o)}catch{Q.write(`Unrecognized governance preset "${o}"; using minimal.
|
|
75
|
+
`)}Q.write(`
|
|
76
|
+
3/3 Project telemetry
|
|
77
|
+
`),Q.write(`Telemetry helps improve reliability and can be disabled anytime via pm config.
|
|
78
|
+
`);let l=t?"Y/n":"y/N",c=await n.question(`Enable telemetry for this project? [${l}] `),d=Ms(c,t);return Q.write(`
|
|
79
|
+
`),{prefix:r,preset:s,telemetry_enabled:d}}finally{n.close()}}function sf(e){return{presetFromOption:Ea(e.preset),useDefaults:e.defaults===!0,authorFromOption:Ds(e.author),installBundledPackages:e.withPackages===!0,agentGuidanceMode:Fs(e.agentGuidance),typePreset:Ns(e.typePreset)}}function cf(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 lf(e,t,n,a){if(t.length===0||n)return;let r=a.discovery==="ancestor";throw new f(`${r?`No tracker exists in ${a.requested_cwd}; pm init found an ancestor tracker at ${a.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:r?"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:a.tracker_root,requested_path:a.requested_cwd,suggested_path:a.suggested_current_tracker_root,examples:["pm init --yes","pm init ./sandbox-pm --yes",...r?['pm init <name> --yes --pm-path "$PWD/.agents/pm"']:[],"pm init acme --yes --force"],nextSteps:[...r?['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 df(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&&($a(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 pf(e){let t=await A(e.pmRoot);e.warnings.push(`already_exists:${e.settingsPath}`);let n=cf({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption});return lf(e.settingsPath,n,e.options.force===!0,e.target),df({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 mf(e){let t=e.normalizedPrefix,n=e.normalizedOptions.presetFromOption,a,r=!1;if(e.normalizedOptions.presetFromOption===void 0&&!e.normalizedOptions.useDefaults&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0){let l=await Ws(t,vn.telemetry.enabled);t=l.prefix,n=l.preset,a=l.telemetry_enabled,r=!0}let i=n??"minimal",o=af();o.id_prefix=t,$a(o,i);let s=rr()?.trim()||void 0;return o.author_default=e.normalizedOptions.authorFromOption??s??"",a!==void 0&&(o.telemetry.enabled=a,o.telemetry.first_run_prompt_completed=!0),await Ee(e.pmRoot,o),{settings:o,normalizedPrefix:t,chosenPreset:n,wizardUsed:r}}async function Os(e){return e.settingsExists?await pf(e):await mf({pmRoot:e.pmRoot,normalizedPrefix:e.normalizedPrefix,normalizedOptions:e.normalizedOptions})}async function uf(e){let t=await Ts({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 ff(e,t){let n=[],a=[],r=await ar(e,t.schema);for(let i of r.created_paths)n.push(i),a.push(...await H({path:i,scope:"project",op:"init:runtime_schema_file"}));return{createdDirs:n,warnings:a}}async function hf(e){if(e.typePreset===void 0)return;let t=await Us(e.pmRoot,e.settings,e.typePreset);return e.warnings.push(`registered_type_preset:${e.typePreset}`),e.warnings.push(...await H({path:t.file,scope:"project",op:"init:type_preset"})),t}async function gf(e){let t=U(e.settings,W()).folders.filter(a=>!wn.includes(a)),n=await qs(e.pmRoot,t);e.createdDirs.push(...n.createdDirs),e.warnings.push(...n.warnings)}function yf(e){let t=F.resolve(e.tracker_root),n=F.dirname(t);return F.basename(t)==="pm"&&F.basename(n)===".agents"?F.dirname(n):e.workspace_root}async function _f(e,t,n,a){if(!e)return;let r=await ga("all",{install:!0,project:!0},{...t,path:n});a.push(...r.warnings);let i=Gs(r),o=i.packages.filter(s=>!s.ok).map(s=>s.alias);if(!i.installed_all||o.length>0)throw new f(`pm init --with-packages did not install all bundled packages successfully${o.length>0?`: ${o.join(", ")}`:"."}`,h.GENERIC_FAILURE);return i}function Bs(e){let t=a=>st([...e.target.mode==="workspace-discovery"?[]:["--pm-path",e.target.tracker_root],...a]),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 a of e.agentGuidanceNextSteps){let r=e.target.mode==="workspace-discovery"?a:a.replace(/\bpm (?=[a-z])/g,()=>`${t([])} `);n.includes(r)||n.push(r)}return n}async function Hs(e,t,n,a=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 r=await a({pmRoot:e,workspaceRoot:t});r.gitattributes.changed&&n.push(`updated:merge_fence:${r.gitattributes.path}`)}catch(r){if(!(r instanceof f))throw r;n.push(`merge_fence_skipped:install_failed:${r.context.code??"pm_error"}:${r.message}:run pm merge install after resolving the Git repository error`)}}async function wf(e,t,n,a){if(e==null||n==="status")return;let r=await Dr(e,{pmRoot:t});r.changed&&a.push(`updated:gitignore:${r.path}`)}async function fb(e,t,n={}){let a=t[tf],r=typeof a=="string"?a:process.cwd(),i=js(r,t,e,n.workspace),o=i.pmRoot;e=Ls(i.prefixArg,n.idPrefix);let s=sf(n);await Js(o,i.target.mode==="tracker-path",n.force===!0);let l=[],c=[],d=F.join(o,"settings.json"),p=await k(d),m;p&&(m=await Os({pmRoot:o,settingsPath:d,settingsExists:p,normalizedPrefix:$e(e),prefixArg:e,options:n,normalizedOptions:s,warnings:c,target:i.target}));let g=await qs(o,wn);l.push(...g.createdDirs),c.push(...g.warnings),m??=await Os({pmRoot:o,settingsPath:d,settingsExists:p,normalizedPrefix:$e(e),prefixArg:e,options:n,normalizedOptions:s,warnings:c,target:i.target});let{settings:y}=m,_=yf(i.target),u=await Wt(_??F.dirname(o)),w=_??u,v=await uf({pmRoot:o,cwd:w??r,agentGuidanceMode:s.agentGuidanceMode,settings:y,warnings:c}),x=await ff(o,y);l.push(...x.createdDirs),c.push(...x.warnings);let S=await hf({pmRoot:o,settings:y,typePreset:s.typePreset,warnings:c});S&&(y=await A(o)),await gf({pmRoot:o,settings:y,createdDirs:l,warnings:c}),await wf(w,o,s.agentGuidanceMode,c),!p&&n.mergeFence!==!1&&s.agentGuidanceMode!=="status"&&await Hs(o,u,c);let O=await _f(s.installBundledPackages,t,o,c),ie=Bs({installBundledPackages:s.installBundledPackages,registeredTypePreset:S,agentGuidanceNextSteps:v.next_steps,target:i.target});return{ok:!0,path:o,target:i.target,settings:y,created_dirs:l,warnings:c,governance_preset:y.governance.preset,wizard_used:m.wizardUsed,...S?{registered_type_preset:S}:{},...O?{installed_packages:O}:{},next_steps:ie,agent_guidance:v}}export{Tn as a,ic as b,Ir as c,Pn as d,gc as e,yc as f,_c as g,Or as h,Gp as i,Pr as j,Rn as k,bc as l,xc as m,Dr as n,Ve as o,Ec as p,$c as q,Lr as r,Jt as s,Fe as t,Gt as u,Fn as v,Dc as w,jc as x,Hf as y,qt as z,qc as A,mt as B,qr as C,Vc as D,Wt as E,zn as F,Yr as G,vh as H,bh as I,Xr as J,kh as K,Jn as L,pi as M,et as N,tt as O,mi as P,ci as Q,Ze as R,Qe as S,li as T,Zc as U,Eh as V,Th as W,Qr as X,tl as Y,Bh as Z,_i as _,ki as $,Gl as aa,Ul as ba,W_ as ca,K_ as da,V_ as ea,Et as fa,Y_ as ga,X_ as ha,Z_ as ia,Q_ as ja,ew as ka,tw as la,nw as ma,aw as na,rw as oa,iw as pa,ow as qa,sw as ra,cw as sa,lw as ta,dw as ua,pw as va,mw as wa,uw as xa,fw as ya,hw as za,gw as Aa,yw as Ba,_w as Ca,ww as Da,vw as Ea,ee as Fa,b as Ga,Yn as Ha,rd as Ia,we as Ja,Kt as Ka,zl as La,ft as Ma,Vt as Na,Li as Oa,Bi as Pa,sa as Qa,io as Ra,Gy as Sa,cm as Ta,Go as Ua,Uo as Va,Jo as Wa,_o as Xa,Fp as Ya,_m as Za,vo as _a,ga as $a,ys as ab,zv as bb,Ts as cb,tf as db,mb as eb,ub as fb,fb as gb};
|
|
80
|
+
//# sourceMappingURL=chunk-D332RXZ7.js.map
|