@unbrained/pm-cli 2026.11.22 → 2026.11.24
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +1 -1
- package/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.js +11 -11
- 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 +5 -5
- package/dist/cli/expected-revisions.js +1 -1
- package/dist/cli/extension-command-help.js +6 -6
- package/dist/cli/extension-recovery.js +1 -1
- package/dist/cli/help-content.js +5 -5
- package/dist/cli/help-json-payload.js +7 -7
- 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/preflight-warnings.js +3 -3
- 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 +0 -1
- package/dist/cli/register-mutation.js +6 -6
- 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/annotation-option-retry.js +1 -1
- package/dist/cli/runtime/close-fields-retry.js +1 -1
- package/dist/cli/runtime/field-route-retry.js +1 -1
- package/dist/cli/runtime/invocation-options.js +1 -1
- package/dist/cli/runtime/invocation-rewrites.js +1 -1
- package/dist/cli/runtime/projection-retry.js +1 -1
- package/dist/cli/runtime/read-output-mutation-retry.js +1 -1
- package/dist/cli/runtime/refusal-credential-redaction.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.js +4 -4
- package/dist/cli/schema/registration.js +15 -15
- 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 +1 -1
- package/dist/cli-bundle/chunks/chunk-23K6DQQY.js +9 -0
- package/dist/cli-bundle/chunks/chunk-37UDIJ2K.js +3 -0
- package/dist/cli-bundle/chunks/chunk-5DUP4AZA.js +2 -0
- package/dist/cli-bundle/chunks/chunk-6H36ZHMI.js +2 -0
- package/dist/cli-bundle/chunks/chunk-7IROAPWI.js +3 -0
- package/dist/cli-bundle/chunks/chunk-7VRFEURZ.js +33 -0
- package/dist/cli-bundle/chunks/chunk-7X253M6Z.js +3 -0
- package/dist/cli-bundle/chunks/chunk-AA52P34H.js +3 -0
- package/dist/cli-bundle/chunks/chunk-AWB5KBJS.js +2 -0
- package/dist/cli-bundle/chunks/chunk-D6PDUKUG.js +9 -0
- package/dist/cli-bundle/chunks/chunk-DQDRA3SW.js +2 -0
- package/dist/cli-bundle/chunks/chunk-FXJYZBWV.js +113 -0
- package/dist/cli-bundle/chunks/chunk-HNKK2UG6.js +8 -0
- package/dist/cli-bundle/chunks/chunk-HZZLSBIJ.js +2 -0
- package/dist/cli-bundle/chunks/chunk-I2OJ5B4A.js +2 -0
- package/dist/cli-bundle/chunks/chunk-I3BFCKZR.js +2 -0
- package/dist/cli-bundle/chunks/chunk-MXUSC5RS.js +31 -0
- package/dist/cli-bundle/chunks/chunk-PLIUU37C.js +3 -0
- package/dist/cli-bundle/chunks/chunk-PQUBVRV5.js +2 -0
- package/dist/cli-bundle/chunks/chunk-PW7U7WCE.js +3 -0
- package/dist/cli-bundle/chunks/chunk-PZA7QECY.js +1 -0
- package/dist/cli-bundle/chunks/chunk-SLFRSZK6.js +1 -0
- package/dist/cli-bundle/chunks/chunk-SSALO4DB.js +2 -0
- package/dist/cli-bundle/chunks/chunk-STOOTHZZ.js +2 -0
- package/dist/cli-bundle/chunks/chunk-TKRY22SO.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-B76TFRO2.js → chunk-TVIJ2VCU.js} +93 -93
- package/dist/cli-bundle/chunks/chunk-VJSGUXGU.js +3 -0
- package/dist/cli-bundle/chunks/chunk-WWTPNIC2.js +6 -0
- package/dist/cli-bundle/chunks/chunk-XFADNMGD.js +2 -0
- package/dist/cli-bundle/chunks/chunk-YOPTAIBD.js +125 -0
- package/dist/cli-bundle/chunks/chunk-YW2HBHRO.js +70 -0
- package/dist/cli-bundle/chunks/chunk-YYT3MIRF.js +3 -0
- package/dist/cli-bundle/chunks/chunk-Z7MFVRDV.js +2 -0
- package/dist/cli-bundle/chunks/chunk-ZOX4SWRL.js +8 -0
- package/dist/cli-bundle/chunks/chunk-ZYCOM4MS.js +9 -0
- package/dist/cli-bundle/chunks/context-budget-recovery-M5RFUEFG.js +2 -0
- package/dist/cli-bundle/chunks/field-option-collisions-W66HSWMK.js +2 -0
- package/dist/cli-bundle/chunks/indexed-receipt-blobs-BPYKN5Q7.js +4 -0
- package/dist/cli-bundle/{focused-chunks/item-revision-2O6MLPEX.js → chunks/item-revision-D3LSBNIR.js} +2 -2
- package/dist/cli-bundle/chunks/item-transaction-M6NTBYH3.js +2 -0
- package/dist/cli-bundle/chunks/mutation-actor-OKL3CQVX.js +2 -0
- package/dist/cli-bundle/chunks/mutation-admission-EKPEOZMF.js +2 -0
- package/dist/cli-bundle/chunks/{register-list-query-RR5KACJ3.js → register-list-query-3LBV6CS2.js} +11 -11
- package/dist/cli-bundle/chunks/register-mutation-72AGTMNE.js +21 -0
- package/dist/cli-bundle/chunks/register-operations-XERFG2SH.js +2 -0
- package/dist/cli-bundle/chunks/register-setup-W22L34Z4.js +2 -0
- package/dist/cli-bundle/chunks/runtime-schema-JP2KBHBY.js +2 -0
- package/dist/cli-bundle/chunks/settlement-hook-6MR32OOC.js +7 -0
- package/dist/cli-bundle/chunks/stage-T2LKWN7C.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-24VRBNKE.js +26 -0
- package/dist/cli-bundle/focused-chunks/chunk-3ELVASVA.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-3GT4A3ZN.js +44 -0
- package/dist/cli-bundle/focused-chunks/chunk-3OCDKITJ.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-3Z7MCUJM.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-46MP7IZN.js +5 -0
- package/dist/cli-bundle/focused-chunks/chunk-5LDBS6MS.js +91 -0
- package/dist/cli-bundle/focused-chunks/chunk-A6VEMCRR.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-AIDL2ZNT.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-B6BNHKUW.js +78 -0
- package/dist/cli-bundle/focused-chunks/chunk-BKPUUW5O.js +1 -0
- package/dist/cli-bundle/focused-chunks/chunk-BWOVFE5B.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-C7WHWI7K.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-EUQGZPGO.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-FDZPRJXJ.js +27 -0
- package/dist/cli-bundle/focused-chunks/chunk-GXP7Q4XM.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-HL47UQZJ.js +8 -0
- package/dist/cli-bundle/focused-chunks/chunk-IIP6LZ5E.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-K53OIT5J.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-LMFIAQ2V.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-LMU7DDOA.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-OZOCEB2Q.js +8 -0
- package/dist/cli-bundle/focused-chunks/chunk-Q2HY44LV.js +13 -0
- package/dist/cli-bundle/focused-chunks/chunk-REFMQY47.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-RIE3SJSE.js +9 -0
- package/dist/cli-bundle/focused-chunks/chunk-RIQUIHYU.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-RLO2HCZT.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-SMMOZ3H3.js +100 -0
- package/dist/cli-bundle/focused-chunks/chunk-UVTUX54T.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-X6CXWWNB.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-XDBHD4CY.js +8 -0
- package/dist/cli-bundle/focused-chunks/chunk-YD66IRSL.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-Z7W2RQIB.js +2 -0
- package/dist/cli-bundle/focused-chunks/context-budget-recovery-CSJV3TY3.js +2 -0
- package/dist/cli-bundle/focused-chunks/field-option-collisions-UODPSV6W.js +2 -0
- package/dist/cli-bundle/focused-chunks/indexed-receipt-blobs-EGEJMG3G.js +4 -0
- package/dist/cli-bundle/focused-chunks/item-revision-QH7RNBX4.js +2 -0
- package/dist/cli-bundle/focused-chunks/item-transaction-ZO72OINF.js +2 -0
- package/dist/cli-bundle/focused-chunks/mutation-actor-PHVLKG4I.js +2 -0
- package/dist/cli-bundle/focused-chunks/mutation-admission-ZSG5OECH.js +2 -0
- package/dist/cli-bundle/focused-chunks/runtime-schema-6RQMIDTN.js +2 -0
- package/dist/cli-bundle/focused-chunks/settlement-hook-FMLGKG7J.js +7 -0
- package/dist/cli-bundle/focused-chunks/stage-AQMKRVX4.js +2 -0
- package/dist/cli-bundle/main.js +27 -27
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +5 -5
- package/dist/cli-bundle/sdk-core.js +1 -1
- package/dist/cli-bundle/sdk-governance.js +1 -1
- package/dist/cli-bundle/sdk-graph.js +1 -1
- package/dist/cli-bundle/sdk-merge.js +66 -66
- 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 +13 -13
- 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/checkpoint/mutation-context.js +1 -1
- 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 -2
- 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.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/mutation-actor-snapshot.js +1 -1
- package/dist/core/extensions/mutation-actor.js +1 -1
- package/dist/core/extensions/preflight-ownership.js +1 -1
- package/dist/core/extensions/read-output-contract.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/extensions/version-diagnostics.js +1 -1
- package/dist/core/fs/atomic-create.js +1 -1
- package/dist/core/fs/file-glob.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/bridge.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.js +1 -1
- package/dist/core/history/event-classification.js +1 -1
- package/dist/core/history/event-index.js +11 -11
- 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 -2
- package/dist/core/history/stream-summary.js +2 -2
- 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 -2
- package/dist/core/item/actionability.js +1 -1
- package/dist/core/item/deferred-fields.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 +7 -7
- package/dist/core/item/item-record.js +1 -1
- package/dist/core/item/item-type-definition.js +1 -1
- package/dist/core/item/literal-mutation-input.js +1 -1
- package/dist/core/item/parent-reference-policy.js +1 -1
- package/dist/core/item/parse.js +8 -8
- 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-confinement.js +1 -1
- package/dist/core/lock/lock-gc.js +1 -1
- package/dist/core/lock/lock-owner.js +1 -1
- package/dist/core/lock/lock.js +4 -4
- package/dist/core/output/linked-test-projection.js +5 -5
- package/dist/core/output/mutation-projection.js +1 -1
- package/dist/core/output/output-control.js +1 -1
- package/dist/core/output/output.js +19 -19
- package/dist/core/output/query-summary.js +1 -1
- package/dist/core/output/tabular.js +3 -3
- 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.d.ts +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 +4 -4
- 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.d.ts +2 -0
- 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/sentry/sensitive-assignments.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 -5
- package/dist/core/shared/command-line.js +1 -1
- package/dist/core/shared/command-types.js +0 -1
- package/dist/core/shared/conflict-markers.js +1 -1
- package/dist/core/shared/constants.js +1 -1
- package/dist/core/shared/error-details.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/output-unicode.js +1 -1
- package/dist/core/shared/primitives.js +1 -1
- package/dist/core/shared/process-tree.js +2 -2
- package/dist/core/shared/secret-rules.js +5 -5
- 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 -2
- package/dist/core/shared/url-credentials.js +1 -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 +11 -11
- package/dist/core/store/item-metadata-read-work.js +1 -1
- package/dist/core/store/item-mutation-precondition.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-sections.js +2 -2
- package/dist/core/store/settings-validator.js +1 -1
- package/dist/core/store/settings.d.ts +3 -1
- package/dist/core/store/settings.js +6 -6
- package/dist/core/store/sqlite-runtime.js +1 -1
- package/dist/core/store/tracker-preflight.js +1 -1
- package/dist/core/store/transaction-coordinator-scope.js +1 -1
- package/dist/core/telemetry/consent.js +3 -3
- 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 -9
- package/dist/core/test/background-runs.js +4 -4
- 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 +5 -5
- 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/linked-resource-recovery.js +1 -1
- package/dist/sdk/agent/refusal-closure-census.js +2 -2
- package/dist/sdk/agent/refusal-corpus-contracts.js +1 -1
- package/dist/sdk/agent/subcommand-recovery.js +1 -1
- package/dist/sdk/agent-capability-contracts.js +3 -3
- 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/cli-bootstrap.js +1 -1
- package/dist/sdk/cli-contracts/agent-output-contracts.js +5 -5
- 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 -2
- 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 +0 -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 -2
- package/dist/sdk/completion/fish.js +72 -72
- package/dist/sdk/completion/shared.js +1 -1
- package/dist/sdk/completion/zsh.js +75 -75
- package/dist/sdk/completion.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 -6
- 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/dependencies/context-budget-recovery.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/host-environment-errors.js +1 -1
- package/dist/sdk/environment/project-runtime-compatibility.js +2 -2
- 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/command-options.d.ts +26 -1
- package/dist/sdk/extension/command-options.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 +3 -3
- 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/managed-update-status.js +1 -1
- package/dist/sdk/extension/migrations.js +2 -2
- package/dist/sdk/extension/native-command-options.js +1 -1
- 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 -11
- 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 +2 -2
- 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/error-code-catalog-rows.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 +0 -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/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 +2 -2
- package/dist/sdk/governance/extension-host-version.js +1 -1
- package/dist/sdk/governance/gc.js +1 -1
- package/dist/sdk/governance/health/history-drift-remedies.js +1 -1
- package/dist/sdk/governance/health/projection.js +1 -1
- package/dist/sdk/governance/health-merge-evidence.js +1 -1
- package/dist/sdk/governance/health.js +2 -2
- package/dist/sdk/governance/hierarchy-validation.js +1 -1
- package/dist/sdk/governance/in-progress-work-health.js +1 -1
- package/dist/sdk/governance/lifecycle-dependency-cycles.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 -4
- package/dist/sdk/governance/reindex.js +5 -5
- 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-deferred-fields.js +1 -1
- 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 -2
- 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/cardinality-integrity.js +1 -1
- package/dist/sdk/graph/centrality.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/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/guide-topics.js +1 -1
- package/dist/sdk/guide.js +7 -7
- package/dist/sdk/history/append-only-repair.js +4 -4
- package/dist/sdk/history/attestation-command.js +2 -2
- 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/reanchor-refusal.js +1 -1
- package/dist/sdk/history/reseed.js +1 -1
- package/dist/sdk/history/salvage.js +5 -5
- 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.d.ts +1 -1
- package/dist/sdk/init-agent-guidance.js +10 -10
- package/dist/sdk/init.js +14 -14
- 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 +3 -3
- package/dist/sdk/lifecycle/checkpoint-rollback.js +1 -1
- package/dist/sdk/lifecycle/claim.js +1 -1
- package/dist/sdk/lifecycle/cli-input.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/core-field-recovery.js +1 -1
- package/dist/sdk/lifecycle/core-item-fields.js +1 -1
- package/dist/sdk/lifecycle/create-deferrals.js +1 -1
- package/dist/sdk/lifecycle/create.js +1 -1
- package/dist/sdk/lifecycle/delete.js +1 -1
- package/dist/sdk/lifecycle/dependency-removal.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/item-revision.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 +0 -1
- package/dist/sdk/lifecycle/mutation-facet-contracts.js +1 -1
- package/dist/sdk/lifecycle/mutation-option-validation.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/release-handoff.js +1 -1
- package/dist/sdk/lifecycle/reopen.js +1 -1
- package/dist/sdk/lifecycle/repeatable-metadata-parsers.js +2 -2
- package/dist/sdk/lifecycle/repeated-terminal-state.js +1 -1
- package/dist/sdk/lifecycle/restore.js +1 -1
- package/dist/sdk/lifecycle/shared-unset-fields.js +1 -1
- package/dist/sdk/lifecycle/start-blockers.js +1 -1
- package/dist/sdk/lifecycle/structured-mutation-plan.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 -2
- package/dist/sdk/lifecycle/workflow-transition.js +1 -1
- package/dist/sdk/lifecycle-completion.js +1 -1
- package/dist/sdk/lifecycle-policy.js +1 -1
- package/dist/sdk/linked-artifacts.js +2 -2
- package/dist/sdk/mcp/apps.js +5 -5
- package/dist/sdk/mcp/authorization.js +1 -1
- package/dist/sdk/mcp/discovery.js +1 -1
- package/dist/sdk/mcp/executable.js +4 -4
- package/dist/sdk/mcp/interactions.js +1 -1
- package/dist/sdk/mcp/protocol.js +1 -1
- package/dist/sdk/mcp/skills.js +3 -3
- 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 +7 -7
- package/dist/sdk/merge/history-scalar-rebase.js +1 -1
- package/dist/sdk/merge/ignored-artifacts.js +1 -1
- package/dist/sdk/merge/index.js +1 -1
- package/dist/sdk/merge/indexed-receipt-blobs.js +2 -2
- package/dist/sdk/merge/install.js +6 -6
- 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/settlement-hook.js +4 -4
- package/dist/sdk/merge/stage.js +1 -1
- package/dist/sdk/merge/three-way.js +9 -9
- package/dist/sdk/merge/worktree-config.js +2 -2
- 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/fit-envelope.js +1 -1
- package/dist/sdk/output/list-envelope.js +1 -1
- package/dist/sdk/output/table-rows.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 -2
- 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 -5
- 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 -4
- package/dist/sdk/query/complete-list.js +1 -1
- package/dist/sdk/query/context.js +2 -2
- package/dist/sdk/query/declared-blockers.js +1 -1
- package/dist/sdk/query/duplicate-candidates.js +1 -1
- package/dist/sdk/query/get-facet-roots.js +1 -1
- package/dist/sdk/query/get.js +1 -1
- package/dist/sdk/query/history.js +1 -1
- package/dist/sdk/query/item-filter-options.js +0 -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-ranking-policy.js +1 -1
- package/dist/sdk/query/next-ready-budget.js +1 -1
- package/dist/sdk/query/next.js +2 -2
- 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 -2
- 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 -3
- package/dist/sdk/query/search/types.js +0 -1
- package/dist/sdk/query/search-contracts.js +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/window-pagination.js +1 -1
- package/dist/sdk/query/workspace-contracts.js +1 -1
- package/dist/sdk/read-output/continuation.js +1 -1
- package/dist/sdk/read-output/extension.js +1 -1
- package/dist/sdk/read-output/options.js +1 -1
- package/dist/sdk/read-output/positional-rows.js +1 -1
- package/dist/sdk/read-output/provenance.js +1 -1
- package/dist/sdk/read-output/session-result.js +0 -1
- package/dist/sdk/read-output/surfaces.js +1 -1
- package/dist/sdk/read-output/tail-retention.js +1 -1
- package/dist/sdk/read-output-budget.js +1 -1
- package/dist/sdk/read-output-contracts.d.ts +11 -0
- 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 +6 -6
- package/dist/sdk/relationship-kinds/contract.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/mutation-admission.js +1 -1
- package/dist/sdk/runtime/mutation-value-validation.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.d.ts +2 -0
- package/dist/sdk/runtime-input.js +1 -1
- package/dist/sdk/runtime-primitives.js +1 -1
- package/dist/sdk/runtime-public-contracts.js +0 -1
- package/dist/sdk/runtime-stats-options.js +1 -1
- package/dist/sdk/runtime.d.ts +5 -3
- package/dist/sdk/runtime.js +1 -1
- package/dist/sdk/scheduling-shortcuts.js +1 -1
- package/dist/sdk/schema/field-flag-spelling.d.ts +22 -0
- package/dist/sdk/schema/field-flag-spelling.js +2 -0
- package/dist/sdk/schema/field-option-collisions.js +2 -0
- package/dist/sdk/schema-migration.js +4 -4
- package/dist/sdk/schema.js +7 -7
- 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 -4
- package/dist/sdk/templates.js +3 -3
- package/dist/sdk/test/batch.js +2 -2
- package/dist/sdk/test/command-args.js +1 -1
- package/dist/sdk/test/command-resolution.js +2 -2
- package/dist/sdk/test/entry.js +2 -2
- package/dist/sdk/test/execution-receipts.js +2 -2
- package/dist/sdk/test/execution.js +5 -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/prerequisites.js +1 -1
- package/dist/sdk/test/receipt-index-snapshot.js +1 -1
- package/dist/sdk/test/run-phases.js +1 -1
- package/dist/sdk/test/runs.js +1 -1
- package/dist/sdk/test/trust.js +2 -2
- package/dist/sdk/test/update.js +1 -1
- package/dist/sdk/test/workspace-snapshot.js +1 -1
- package/dist/sdk/traceability/runtime-files-lookup.js +1 -1
- package/dist/sdk/traceability/source-traceability.js +2 -2
- package/dist/sdk/tracker-root-discovery.js +1 -1
- package/dist/sdk/transactions/item-finalization.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-snapshot.js +5 -5
- package/dist/sdk/workspace-transaction-gc.js +1 -1
- package/dist/sdk/workspace-transaction.js +2 -2
- package/dist/sdk/workspace.js +6 -6
- package/dist/types/index.js +1 -1
- package/dist/types.js +1 -1
- package/docs/COMMANDS.md +1 -1
- package/docs/EXTENSIONS.md +2 -2
- package/docs/READ_OUTPUT_CONTRACTS.md +2 -0
- package/docs/SDK.md +94 -5
- package/docs/SDK_AUDITED_MUTATIONS.md +11 -0
- package/marketplace.json +1 -1
- package/package.json +2 -1
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-claude/package.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/plugins/pm-codex/package.json +1 -1
- package/plugins/pm-codex/plugin.json +1 -1
- package/runtime-dependencies.json +1 -1
- package/scripts/finalize-build.mjs +63 -24
- package/scripts/prepare-build-cache.mjs +28 -1
- package/dist/cli-bundle/chunks/chunk-3W47ZZ5T.js +0 -9
- package/dist/cli-bundle/chunks/chunk-4TB5D6HL.js +0 -125
- package/dist/cli-bundle/chunks/chunk-5ZMVLWE3.js +0 -2
- package/dist/cli-bundle/chunks/chunk-6BBDEIKC.js +0 -33
- package/dist/cli-bundle/chunks/chunk-AR4NP5HI.js +0 -3
- package/dist/cli-bundle/chunks/chunk-B4PPFOPY.js +0 -3
- package/dist/cli-bundle/chunks/chunk-CAR2L5NW.js +0 -8
- package/dist/cli-bundle/chunks/chunk-DEZPZOQ7.js +0 -2
- package/dist/cli-bundle/chunks/chunk-EIGUKEV6.js +0 -2
- package/dist/cli-bundle/chunks/chunk-GTPCAJMZ.js +0 -8
- package/dist/cli-bundle/chunks/chunk-GYP24M7W.js +0 -2
- package/dist/cli-bundle/chunks/chunk-HC2OPETM.js +0 -2
- package/dist/cli-bundle/chunks/chunk-HKUV74K3.js +0 -2
- package/dist/cli-bundle/chunks/chunk-HXHYDO2R.js +0 -115
- package/dist/cli-bundle/chunks/chunk-IB7UB5TE.js +0 -2
- package/dist/cli-bundle/chunks/chunk-J2LABXBL.js +0 -2
- package/dist/cli-bundle/chunks/chunk-J52BEBSS.js +0 -2
- package/dist/cli-bundle/chunks/chunk-KQIZ34SF.js +0 -3
- package/dist/cli-bundle/chunks/chunk-LQBWLNZJ.js +0 -3
- package/dist/cli-bundle/chunks/chunk-OJTMGDON.js +0 -31
- package/dist/cli-bundle/chunks/chunk-SPPHDVZE.js +0 -2
- package/dist/cli-bundle/chunks/chunk-TC6XLIYO.js +0 -2
- package/dist/cli-bundle/chunks/chunk-U7EL3AYA.js +0 -3
- package/dist/cli-bundle/chunks/chunk-VQFWW4EF.js +0 -6
- package/dist/cli-bundle/chunks/chunk-X6MIWTTT.js +0 -2
- package/dist/cli-bundle/chunks/chunk-XC5Q2ZV7.js +0 -2
- package/dist/cli-bundle/chunks/chunk-XFHPKXAE.js +0 -71
- package/dist/cli-bundle/chunks/chunk-YHVLVSEZ.js +0 -9
- package/dist/cli-bundle/chunks/chunk-YMUSRWV4.js +0 -9
- package/dist/cli-bundle/chunks/chunk-YR2KEBHP.js +0 -2
- package/dist/cli-bundle/chunks/context-budget-recovery-L2WP5S26.js +0 -2
- package/dist/cli-bundle/chunks/indexed-receipt-blobs-ITTXIN4K.js +0 -4
- package/dist/cli-bundle/chunks/item-revision-4QBMZXKX.js +0 -2
- package/dist/cli-bundle/chunks/item-transaction-QY3PUHEI.js +0 -2
- package/dist/cli-bundle/chunks/mutation-actor-FWLYWJ37.js +0 -2
- package/dist/cli-bundle/chunks/mutation-admission-7ZDCK3G2.js +0 -2
- package/dist/cli-bundle/chunks/register-mutation-57AJQWFV.js +0 -21
- package/dist/cli-bundle/chunks/register-operations-RKWST7CU.js +0 -2
- package/dist/cli-bundle/chunks/register-setup-CMI23PC5.js +0 -2
- package/dist/cli-bundle/chunks/settlement-hook-BXN5LEQD.js +0 -7
- package/dist/cli-bundle/chunks/stage-4KDVXC5Z.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-2ZD7275J.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-324AHXJO.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-3IRCYJI5.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-3V53UBHN.js +0 -9
- package/dist/cli-bundle/focused-chunks/chunk-3XSWH6QC.js +0 -91
- package/dist/cli-bundle/focused-chunks/chunk-4JZITIJB.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-4KTFKSS3.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-5C5TK3ET.js +0 -78
- package/dist/cli-bundle/focused-chunks/chunk-AKJYOZZP.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-BRZV7BFV.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-C3O6JJPO.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-CR7CGEB2.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-EGN2HFRU.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-GHQVM6K6.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-HDEKFSOK.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-I5LGPUWH.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-IWOXAUDU.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-ML3JHCC6.js +0 -6
- package/dist/cli-bundle/focused-chunks/chunk-OPGOOP25.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-RE7ZWT7D.js +0 -27
- package/dist/cli-bundle/focused-chunks/chunk-RKQNVYGF.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-RQ252B6V.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-SVOOGGAK.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-URGHTTT3.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-USPYKWQG.js +0 -13
- package/dist/cli-bundle/focused-chunks/chunk-UWS3FC4D.js +0 -102
- package/dist/cli-bundle/focused-chunks/chunk-UXQGFGAT.js +0 -44
- package/dist/cli-bundle/focused-chunks/chunk-WZWXGDYY.js +0 -26
- package/dist/cli-bundle/focused-chunks/chunk-YKSLZPLT.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-ZWJTY4ID.js +0 -2
- package/dist/cli-bundle/focused-chunks/context-budget-recovery-5MKOCGY5.js +0 -2
- package/dist/cli-bundle/focused-chunks/indexed-receipt-blobs-AF4U3F3D.js +0 -4
- package/dist/cli-bundle/focused-chunks/item-transaction-GLACUTPL.js +0 -2
- package/dist/cli-bundle/focused-chunks/mutation-actor-TCYDPUGG.js +0 -2
- package/dist/cli-bundle/focused-chunks/mutation-admission-LY73EJWM.js +0 -2
- package/dist/cli-bundle/focused-chunks/settlement-hook-ARYCZQY4.js +0 -7
- package/dist/cli-bundle/focused-chunks/stage-DQ7RQQ52.js +0 -2
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import{i as wi,n as vi,p as ki}from"./chunk-HNKK2UG6.js";import{f as yi}from"./chunk-D6PDUKUG.js";import{_ as Lt}from"./chunk-ZYCOM4MS.js";import{$a as oi,Ab as _n,Ca as ei,Da as Ne,Ea as at,Fa as ti,Ga as ni,Ha as ie,Ia as Ge,Ja as ri,Ka as ce,R as Lr,Vc as yn,ab as ai,bb as Ae,cb as si,db as ci,ec as ui,hb as di,ia as $e,nb as li,od as mi,qb as Rt,rb as Nt,ub as Le,zb as pi}from"./chunk-YOPTAIBD.js";import{I as ze,a as Xr,b as Yr,d as hn,e as Zr,f as Qr,g as Ee,m as ii,p as he,r as gn,v as A,w as ge}from"./chunk-23K6DQQY.js";import{Ag as Ur,Bg as Gr,Dh as W,Eg as zr,Fa as Rr,Fg as Jr,Mb as te,Ng as qr,Oh as H,Pg as Wr,Qa as Nr,Sg as Re,T as Tr,U as Ir,V as B,a as At,b as xr,ba as M,c as pn,ca as Or,d as un,da as Pe,e as mn,ea as Cr,g as br,gc as Fr,gh as fn,h as Sr,hh as Br,ih as Ct,k as Er,kh as be,mh as Se,nc as q,ph as Hr,r as Ar,rh as Pt,sc as Mr,sh as Kr,ta as K,th as Vr,wg as xe}from"./chunk-FXJYZBWV.js";import{a as fi,b as Je,c as qe,d as hi,e as gi,m as _i,n as wn}from"./chunk-PW7U7WCE.js";import{K as T,n as $r,r as Pr,s as se}from"./chunk-7IROAPWI.js";import{E as O,F as X,H as jr,J as V,K as ee,M as Dr,O as ot,Q as Ot,d as It}from"./chunk-7X253M6Z.js";import{A as h,C as m,E as b,F as Tt,G as ke,H as U,K as fe,a as wr,d as $t,t as ln,v as vr,y as kr}from"./chunk-YYT3MIRF.js";import{AsyncLocalStorage as ec}from"node:async_hooks";import xi from"node:path";var bi=new ec;function Si(e,t){return bi.run({...e,pmRoot:xi.resolve(e.pmRoot)},t)}function yf(e,t){let n=bi.getStore();return n!==void 0&&n.pmRoot===xi.resolve(e)&&n.transactionId===t?n.step:void 0}import{mkdir as tc,readFile as nc}from"node:fs/promises";import $i from"node:path";import{createHash as rc}from"node:crypto";var vn=class extends Error{constructor(t="Workspace transaction interrupted"){super(t),this.name="WorkspaceTransactionInterruptedError"}},Ai="sdk-workspace-transaction",Ti=/^[a-zA-Z0-9._-]+$/,Ii=30,Oi=3e3;function En(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n||!Ti.test(n))throw new TypeError(`${t} must match [a-zA-Z0-9._-]+`);return n}function kn(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 $n(e){return{pmRoot:kn(e.pmRoot,"Transaction pmRoot"),transactionId:En(e.transactionId,"Transaction id"),author:kn(e.author,"Transaction author")}}function Dt(e,t,n){let r=e??t;if(!Number.isInteger(r)||r<=0)throw new TypeError(`${n} must be a positive integer`);return r}function Ci(e,t){return $i.join(e,"transactions","sdk",`${t}.json`)}async function de(e,t){t.updatedAt=T();let n=Ci(e,t.transactionId);await tc($i.dirname(n),{recursive:!0}),await fe(n,`${JSON.stringify(t,null,2)}
|
|
2
|
+
`)}function ic(e){return Number.isInteger(e.attempt)&&typeof e.author=="string"&&typeof e.createdAt=="string"&&typeof e.updatedAt=="string"&&oc(e)}function oc(e){let t=e.abandonment;return t===void 0?e.schemaVersion===1&&e.status!=="abandoned":e.schemaVersion!==2||t===null||typeof t!="object"||e.status==="committed"?!1:typeof t.reason=="string"&&t.reason.trim().length>0&&typeof t.author=="string"&&t.author.trim().length>0&&(t.supersededBy===void 0||typeof t.supersededBy=="string"&&Ti.test(t.supersededBy)&&t.supersededBy!==e.transactionId)}function je(e){return Object.assign(Object.create(null),e)}function Pi(e,t){try{let n=JSON.stringify(e,(r,i)=>{if(typeof i=="number"&&!Number.isFinite(i))throw new TypeError(`${t} contains a non-finite number`);if(i===void 0||typeof i=="function"||typeof i=="symbol")throw new TypeError(`${t} contains a non-JSON value`);return i});return JSON.parse(n)}catch(n){throw new TypeError(`${t} must be JSON serializable`,{cause:n})}}function xn(e,t){return e===void 0?void 0:Pi(e,t)}function bn(e,t,n,r){let i=xn(n,r);i===void 0?delete e[t]:e[t]=i}function Ei(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Sn(e,t){return Array.isArray(e)&&new Set(e).size===e.length&&e.every(n=>typeof n=="string"&&t.includes(n))}function ac(e,t){if(!Sn(e.startedStepIds,t)||!Sn(e.completedStepIds,t)||!Ei(e.results)||!Ei(e.compensationData))return!1;let n=e.startedStepIds,r=new Set(n),i=e.completedStepIds,o=new Set(i);return Object.keys(e.compensationData).some(a=>!r.has(a))||Object.keys(e.results).some(a=>!o.has(a))?!1:e.status==="committed"?t.every(a=>o.has(a)):!["compensated","abandoned"].includes(e.status??"")||o.size===0&&r.size===0}function jt(e,t){return new m(`Workspace transaction ${e} journal is invalid (${t})`,h.CONFLICT,{code:"transaction_journal_invalid",required:"A valid durable journal is required before transaction recovery can continue.",why:"Corrupt journal data cannot establish which steps applied or still require compensation.",nextSteps:["Preserve the journal and inspect its integrity or restore a verified backup before retrying.","Do not switch to a new transaction id to bypass an unreadable journal; previously applied work may remain."]})}function Ri(e){return new m(`Workspace transaction ${e} journal does not match the supplied plan`,h.CONFLICT,{code:"transaction_plan_mismatch",required:"Replay the original plan or safely abandon the interrupted transaction before replacing it.",why:"A journal records the plan it is resuming; applying a different plan under the same id could skip or duplicate steps.",nextSteps:["Re-run with the original document to resume or replay it.","For item batches use client.itemTransactions.status(transactionId), then client.itemTransactions.abandon(transactionId, { reason }) before committing a changed plan with a new transactionId.","Run pm ops gc --scope transactions --dry-run to inspect retention; active and explicitly abandoned journals remain protected."]})}function sc(e,t,n){return n===void 0||e.abandonment!==void 0||e.status==="compensated"||t.length===n.length&&t.every((r,i)=>r===n[i])}function cc(e,t,n){let r;try{r=JSON.parse(e)}catch{throw jt(t,"invalid JSON")}if(!r||typeof r!="object"||Array.isArray(r))throw jt(t,"expected an object");let i=r;if(!((i.schemaVersion===1||i.schemaVersion===2)&&i.transactionId===t))throw jt(t,"schema version or transaction id does not match the journal file");let a=i.stepIds;if(!Array.isArray(a)||!Sn(a,a)||!ac(i,a)||!ic(i)||typeof i.status!="string"||!["applying","compensating","compensated","committed","abandoned"].includes(i.status))throw jt(t,"invalid lifecycle, metadata, status or step ids");if(!sc(i,a,n))throw Ri(t);return{...i,results:je(i.results),compensationData:je(i.compensationData)}}async function dc(e,t,n,r,i){let o=i,a=o!==void 0;if(o?.status==="compensating"&&await An(e,o),o===void 0||o.status==="compensated"){let s=T();o={schemaVersion:1,transactionId:t,author:n,status:"applying",attempt:(o?.attempt??0)+1,createdAt:o?.createdAt??s,updatedAt:s,stepIds:r,startedStepIds:[],completedStepIds:[],results:je(),compensationData:je(),...e.recoveryData===void 0?{}:{recoveryData:Pi(e.recoveryData,"Transaction recovery data")}},await de(e.pmRoot,o),await _e(e,o,"prepared")}return{journal:o,recovered:a}}async function lc(e,t,n){try{await pc(t,e.steps),await de(e.pmRoot,t);let r=new Set(t.completedStepIds),i=new Set(t.startedStepIds);for(let o of e.steps){if(r.has(o.id))continue;let a=await o.inspect(),s=xn(a.result,`Step ${o.id} result`);if(a.state!=="applied"){let c=await o.prepareCompensation?.();bn(t.compensationData,o.id,c,`Step ${o.id} compensation data`),i.add(o.id),t.startedStepIds=e.steps.map(l=>l.id).filter(l=>i.has(l)),await de(e.pmRoot,t);let d=await o.apply();s=xn(d,`Step ${o.id} result`)}await _e(e,t,"step_applied",o.id),r.add(o.id),t.completedStepIds=e.steps.map(c=>c.id).filter(c=>r.has(c)),bn(t.results,o.id,s,`Step ${o.id} result`),await de(e.pmRoot,t),await _e(e,t,"step_recorded",o.id)}return await _e(e,t,"committing"),t.status="committed",await de(e.pmRoot,t),await _e(e,t,"committed"),{transactionId:t.transactionId,status:"committed",recovered:n,results:je(t.results)}}catch(r){if(r instanceof vn||t.status==="committed")throw r;try{await An(e,t)}catch(i){throw new AggregateError([r,i],`Workspace transaction failed and compensation failed: ${String(i)}`,{cause:i})}throw r}}async function Ft(e,t,n){try{return cc(await nc(Ci(e,t),"utf8"),t,n)}catch(r){if(r!==null&&typeof r=="object"&&"code"in r&&ke(r))return;throw r}}async function _e(e,t,n,r){await e.onTransition?.({transactionId:t.transactionId,attempt:t.attempt,transition:n,...r===void 0?{}:{stepId:r}})}async function pc(e,t){let n=new Set,r=je();for(let i of t){let o=await i.inspect();o.state==="applied"&&(n.add(i.id),bn(r,i.id,o.result,`Step ${i.id} result`))}e.results=r,e.completedStepIds=t.map(i=>i.id).filter(i=>n.has(i))}async function An(e,t){t.status="compensating",await de(e.pmRoot,t),await _e(e,t,"compensating");let n=new Set(t.completedStepIds),r=new Set(t.startedStepIds);for(let i of[...e.steps].reverse()){if(!r.has(i.id)&&!n.has(i.id))continue;let o;try{let a=(await i.inspect()).state;o=r.has(i.id)&&(a==="applied"||a==="pending"&&i.compensatePending===!0)}catch{o=r.has(i.id)}o&&(await _e(e,t,"step_compensating",i.id),await Si({pmRoot:e.pmRoot,transactionId:t.transactionId,step:i},()=>i.compensate(t.compensationData[i.id]))),n.delete(i.id),r.delete(i.id),t.completedStepIds=e.steps.map(a=>a.id).filter(a=>n.has(a)),t.startedStepIds=e.steps.map(a=>a.id).filter(a=>r.has(a)),delete t.results[i.id],delete t.compensationData[i.id],await de(e.pmRoot,t),await _e(e,t,"step_compensated",i.id)}t.status="compensated",await de(e.pmRoot,t),await _e(e,t,"compensated")}async function Ni(e){let{pmRoot:t,transactionId:n,author:r}=$n(e),i=Dt(e.lockTtlSeconds,Ii,"Transaction lock TTL"),o=Dt(e.lockWaitMs,Oi,"Transaction lock wait"),a=[...e.steps];if(a.length===0)throw new TypeError("Workspace transaction requires at least one step");let s=a.map(l=>{let p=En(l.id,"Transaction step id");if(p!==l.id)throw new TypeError("Transaction step id must not contain surrounding whitespace");return p});if(new Set(s).size!==s.length)throw new TypeError("Workspace transaction step ids must be unique");let c={...e,pmRoot:t,transactionId:n,author:r,steps:a,lockTtlSeconds:i,lockWaitMs:o},d=await te(t,Ai,i,r,!1,!1,o);try{let l=await Ft(t,n,s);if(l?.status==="abandoned"||l?.abandonment!==void 0)throw Li(l);let p=l!==void 0;if(l?.status==="committed")return{transactionId:n,status:"committed",recovered:!0,results:je(l.results)};let u=await dc(c,n,r,s,l);return await lc(c,u.journal,p||u.recovered)}finally{await d()}}function Li(e){let t=e.status!=="abandoned",n=e.abandonment.supersededBy,r=n===void 0?`Retry abandonment without supersededBy to finish retirement of ${JSON.stringify(e.transactionId)}.`:`Retry abandonment with supersededBy ${JSON.stringify(n)} to finish retirement of ${JSON.stringify(e.transactionId)}.`;return new m(t?`Transaction ${e.transactionId} retirement is incomplete`:`Transaction ${e.transactionId} has been abandoned`,h.CONFLICT,{code:"transaction_abandoned",required:t?r:"Use a new transactionId for the replacement plan.",why:t?"Forward replay is fenced, but the recorded retirement has not finished. Preserve its replacement identity.":"An explicitly retired transaction identity cannot be resumed.",...t?{retirement:{state:"pending",superseded_by:n??null},nextSteps:[r]}:{}})}async function Cf(e,t){let n=$n({pmRoot:e,transactionId:t,author:"reader"});return Ft(n.pmRoot,n.transactionId)}function uc(e){return rc("sha256").update(JSON.stringify(e.stepIds)).digest("hex")}async function Pf(e){let t=$n(e),n=kn(e.reason,"Abandonment reason"),r=e.supersededBy===void 0?void 0:En(e.supersededBy,"Replacement transaction id");if(r===t.transactionId)throw new TypeError("Replacement transaction id must differ from the abandoned id");let i=Dt(e.lockTtlSeconds,Ii,"Transaction lock TTL"),o=Dt(e.lockWaitMs,Oi,"Transaction lock wait"),a=await te(t.pmRoot,Ai,i,t.author,!1,!1,o);try{let s=await Ft(t.pmRoot,t.transactionId);if(s===void 0)throw new m(`Transaction ${t.transactionId} was not found`,h.NOT_FOUND);if(s.status==="committed")throw new m(`Transaction ${t.transactionId} is committed and cannot be abandoned`,h.CONFLICT,{code:"transaction_committed",required:"Plan a separate explicit corrective mutation.",why:"Recovery cannot silently undo committed work."});if(s.abandonment!==void 0&&s.abandonment.supersededBy!==r)throw Li(s);if(s.status==="abandoned")return s;let c=e.resolveSteps(structuredClone(s));if(JSON.stringify(c.map(d=>d.id))!==JSON.stringify(s.stepIds))throw Ri(t.transactionId);if(s.abandonment===void 0){if(r!==void 0&&await Ft(t.pmRoot,r)!==void 0)throw new m(`Replacement transaction ${r} already exists`,h.CONFLICT);s.schemaVersion=2,s.abandonment={reason:n,author:t.author,...r===void 0?{}:{supersededBy:r}},await de(t.pmRoot,s)}return s.status!=="compensated"&&await An({...e,...t,steps:c},s),await mc(s,t.pmRoot,i,o),s.status="abandoned",await de(t.pmRoot,s),s}finally{await a()}}async function mc(e,t,n,r){let i=uc(e);if((await Mr(Yr(t),Xr)).some(s=>s.op==="transaction_abandon"&&s.context?.transaction_id===e.transactionId&&s.context?.attempt===e.attempt&&s.context?.plan_digest===i))return;let a=e.abandonment;await Zr({pmRoot:t,author:a.author,lockTtlSeconds:n,lockWaitMs:r,op:"transaction_abandon",message:a.reason,context:{transaction_id:e.transactionId,attempt:e.attempt,plan_digest:i,...a.supersededBy===void 0?{}:{superseded_by:a.supersededBy}}})}import fc from"node:fs/promises";import hc from"node:path";function Tn(e){return hc.join(e,"extension-migrations.json")}function ji(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 Di(e,t){return`${e.layer}:${e.name}:${t}`}async function gc(e){let t=Tn(e);if(!await b(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(r=>typeof r?.key=="string"&&(r.status==="applied"||r.status==="failed")):[]}}async function _c(e,t){let n=await gc(e),r=new Map(n.entries.map(i=>[i.key,i]));return t.forEach((i,o)=>{let a=ji(i,o),s=r.get(Di(i,a));s&&(i.definition.status=s.status,s.status==="failed"?i.definition.reason=s.error:(delete i.definition.reason,delete i.definition.error,delete i.definition.message))}),n}async function yc(e){let t=await _c(e.pmRoot,e.migrations),n=new Map(t.entries.map(l=>[l.key,l])),r=[],i=!1,o=e.migrations.map((l,p)=>({migration:l,index:p})).filter(({migration:l})=>e.scope===void 0||l.layer===e.scope);for(let{migration:l,index:p}of o){let u=ji(l,p),_=Di(l,u),g=n.get(_),w=String(l.definition.status??"pending").toLowerCase(),f=g?.status??(w==="applied"||w==="failed"?w:"pending");if(f==="applied"){r.push({key:_,layer:l.layer,extension:l.name,id:u,before:f,outcome:"skipped"});continue}if(e.dryRun===!0){r.push({key:_,layer:l.layer,extension:l.name,id:u,before:f,outcome:"pending"});continue}let y=l.runtime_definition?.run??l.definition.run;if(typeof y!="function"){r.push({key:_,layer:l.layer,extension:l.name,id:u,before:f,outcome:"pending"});continue}let v=new Date().toISOString();try{await Promise.resolve(y({id:u,command:"migration",layer:l.layer,extension:l.name,pm_root:e.pmRoot,status:f}));let x={key:_,layer:l.layer,extension:l.name,id:u,status:"applied",attempted_at:v};n.set(_,x),l.definition.status="applied",delete l.definition.reason,delete l.definition.error,delete l.definition.message,r.push({key:_,layer:l.layer,extension:l.name,id:u,before:f,outcome:"applied"}),i=!0}catch(x){let S=x instanceof Error?x.message:String(x),L={key:_,layer:l.layer,extension:l.name,id:u,status:"failed",attempted_at:v,error:S};n.set(_,L),l.definition.status="failed",l.definition.reason=S,r.push({key:_,layer:l.layer,extension:l.name,id:u,before:f,outcome:"failed",error:S}),i=!0}}if(i){let l=await A(e.pmRoot),p={version:1,updated_at:new Date().toISOString(),entries:[...n.values()].sort((u,_)=>u.key.localeCompare(_.key))};await Ee({pmRoot:e.pmRoot,filePath:Tn(e.pmRoot),raw:`${JSON.stringify(p,null,2)}
|
|
3
|
+
`,op:"extension_migrations_apply",author:e.author,lockTtlSeconds:l.locks.ttl_seconds,lockWaitMs:l.locks.wait_ms})}let a=r.filter(l=>l.outcome==="pending").length,s=r.filter(l=>l.outcome==="applied").length,c=r.filter(l=>l.outcome==="skipped").length,d=r.filter(l=>l.outcome==="failed").length;return{ok:d===0,dry_run:e.dryRun===!0,state_path:Tn(e.pmRoot),total:r.length,pending_count:a,applied_count:s,skipped_count:c,failed_count:d,migrations:r}}async function Fi(e){let t=await A(e.resolvedRoots.settings_root),n=await be({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),r=await Se(n);e.warnings.push(...n.warnings,...r.warnings);let i=await yc({pmRoot:e.resolvedRoots.pm_root,migrations:r.registrations.migrations,author:typeof e.global.author=="string"&&e.global.author.trim().length>0?e.global.author.trim():"pm-extension-migration",dryRun:e.options.dryRun===!0,...e.scope==="global"?{scope:"global"}:{}});return e.withResult({migration:i,load_failure_count:n.failed.length,activation_failure_count:r.failed.length},i.ok)}var wc=[["beforeCommand","before_command"],["beforeMutation","before_mutation"],["afterCommand","after_command"],["onWrite","on_write"],["onRead","on_read"],["onIndex","on_index"]];function We(e,t={}){let n=new Set;t.extensionName!==void 0&&n.add(Pt(t.extensionName));for(let f of t.extensionNames??[])n.add(Pt(f));let r=f=>n.size===0||n.has(Pt(f)),i=(f,y)=>Mi(f.filter(v=>r(v.name)).map(y)),o=(f,y)=>Mi(f.filter(v=>r(v.name)).flatMap(y)),{registrations:a,commands:s,parsers:c,preflight:d,services:l,renderers:p,hooks:u}=e,_=o(a.relationship_kinds??[],f=>f.definitions.map(y=>y.kind)),g=p.overrides.filter(f=>r(f.name)&&((f.commands?.length??0)>0||f.resultDiscriminator!==void 0)).map(f=>({format:f.format,commands:[...f.commands??[]],result_discriminator:f.resultDiscriminator!==void 0})).sort((f,y)=>f.format.localeCompare(y.format)),w=i(a.assurance_providers??[],f=>f.definition.id);return{capabilities:Kr(e,t),commands:i(a.commands,f=>f.command),command_overrides:i(s.overrides,f=>f.command),command_handlers:i(s.handlers,f=>f.command),hooks:wc.filter(([f])=>u[f].some(y=>r(y.name))).map(([,f])=>f),flag_commands:i(a.flags,f=>f.target_command),item_types:o(a.item_types,f=>f.types.map(y=>y.name)),item_fields:o(a.item_fields,f=>f.fields.map(y=>y.name)),..._.length>0?{relationship_kinds:_}:{},migrations:o(a.migrations,f=>typeof f.definition.id=="string"?[f.definition.id]:[]),profiles:i(a.profiles,f=>f.profile.name),importers:i(a.importers,f=>f.importer),exporters:i(a.exporters,f=>f.exporter),search_providers:i(a.search_providers,f=>f.definition.name),vector_store_adapters:i(a.vector_store_adapters,f=>f.definition.name),...w.length>0?{assurance_providers:w}:{},parser_overrides:i(c.overrides,f=>f.command),service_overrides:i(l.overrides,f=>f.service),renderer_overrides:i(p.overrides,f=>f.format),...g.length>0?{renderer_ownership:g}:{},preflight_overrides:d.overrides.filter(f=>r(f.name)).length,preflight_ownership:d.overrides.filter(f=>r(f.name)).map(f=>({commands:[...f.commands??[]]}))}}function Mi(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}var st={type:"string",minLength:1,maxLength:128,pattern:"\\S"},Mt={type:"array",minItems:1,maxItems:pn,items:st},Ui={...Mt,items:{...st,pattern:"^(?!(?:.*\\.)?(?:__proto__|constructor|prototype)(?:\\.|$))[a-zA-Z_][a-zA-Z0-9_]*(?:\\.[a-zA-Z_][a-zA-Z0-9_]*){0,7}$"}},vc={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,Mt])),dependency:{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:st,id:st}}}},rule:{oneOf:[{type:"object",additionalProperties:!1,required:["kind","fields"],properties:{kind:{const:"require_fields"},fields:Ui}},{type:"object",additionalProperties:!1,required:["kind","authors"],properties:{kind:{const:"authors"},authors:Mt}},...["field_writers","approval"].map(e=>({type:"object",additionalProperties:!1,required:["kind","fields","authors"],properties:{kind:{const:e},fields:Ui,authors:Mt}})),{type:"object",additionalProperties:!1,required:["kind","allowed"],properties:{kind:{const:"transition"},allowed:{type:"array",maxItems:pn,items:{type:"array",minItems:2,maxItems:2,items:st}}}}]}}},qf={$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:xr,items:vc}}};async function Kf(e,t,n,r){let i=await Ae(e).catch(()=>null);return i===null?{check:{name:"completeness",status:"error",ok:!1,details:{policy_registry_readable:!1,policy_registry_path:"schema/policies.json",remediation_hint:"Repair schema/policies.json, then rerun pm validate."}},warnings:["validate_completeness_policy_registry_unreadable"]}:Gi(i,t,n,r)}function kc(e,t,n){return e===0?"undeclared":t===0?"empty":n===0?"inapplicable":n===t?"covered":"partial"}function Gi(e,t,n=5,r=!1){let i=[],o=new Map,a=e.policies.filter(f=>f.rule.kind==="require_fields"),s=a.filter(f=>f.subject?.operations===void 0),c=new Set,d=0,l=0,p=0,u=0,_=0,g=Er(e);for(let f of t){let y=g({operation:"",author:"",before:f,after:f,completeness_only:!0});d+=+(y.decisions.length>0),l+=y.decisions.length,y.decisions.forEach(S=>c.add(S.policy_id));let v=y.decisions.filter(S=>!S.satisfied);if(v.length===0)continue;u+=1;let x=o.get(f.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"&&(_+=1),i.length<n&&i.push({id:f.id,type:f.type,status:f.status,decision:S});o.set(f.type,x)}let w=r||_>0?"error":p>0?"warn":"ok";return{check:{name:"completeness",status:w,ok:w==="ok",details:{scope:"operation_independent_require_fields",declared_requirement_count:a.length,state_requirement_count:s.length,applicable_requirement_count:c.size,requirement_application_count:l,governed_items:d,ungoverned_items:t.length-d,contract_status:kc(a.length,t.length,d),applied_policy_ids:[...c].sort().slice(0,Math.max(0,n)),applied_policy_ids_truncated:c.size>Math.max(0,n),checked_items:t.length,incomplete_items:u,violation_count:p,refused_violations:_,missing_by_type:Object.fromEntries(o),violations:i,violations_truncated:i.length<p,enforcement:e.enforcement}},warnings:[...p>0?[`validate_completeness_missing_fields:${p}`]:[],...r?["validate_completeness_source_incomplete"]:[]]}}import xc from"node:path";function bc(){return{version:1,enforcement:"advise",policies:[...[["Epic",["goal","objective","body"]],["Story",["description","value","acceptance_criteria"]],["Decision",["body","resolution"]],["Feature",["acceptance_criteria","expected_result"]],["Task",["description"]],["Issue",["repro_steps","expected_result"]],["Chore",["description"]]].map(([t,n])=>({id:`completeness-${t.toLowerCase()}`,effect:"advise",description:`Evidence expected when ${t} work reaches completion.`,subject:{types:[t],statuses:["closed"]},rule:{kind:"require_fields",fields:[...n]}})),{id:"completeness-resolution",effect:"advise",subject:{statuses:["closed"]},rule:{kind:"require_fields",fields:["resolution","expected_result","actual_result"]}}]}}function qi(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{throw new m("Policy definition must be valid JSON.",h.USAGE)}if(typeof t!="object"||t===null||Array.isArray(t))throw new m("Policy definition must be an object.",h.USAGE);return t}async function Sc(e,t){let n=M(process.cwd(),e.path);await ze(n);let r=await A(n);return{pmRoot:n,settings:r,author:q(t,r.author_default)}}function zi(e,t,n,r){if(e==="policy-mode")return mn({...n,enforcement:t});let i=n.policies.filter(s=>s.id!==t);if(e==="policy-remove")return{...n,policies:i};let o=un(r.definition),a=mn({...n,policies:[...i,o].sort((s,c)=>s.id.localeCompare(c.id))});if(Buffer.byteLength(`${JSON.stringify(a,null,2)}
|
|
4
|
+
`)>oi)throw new m("Policy registry exceeds its byte ceiling.",h.USAGE);return a}async function Ji(e,t,n,r){if(n.dryRun)return{policy_result:!0,action:e,changed:!1,result:zi(e,t,await Ae(r.pmRoot),n)};let i=await Qr({pmRoot:r.pmRoot,filePath:xc.join(r.pmRoot,"schema","policies.json"),op:`schema:${e}`,author:r.author,message:n.message,lockTtlSeconds:r.settings.locks.ttl_seconds,lockWaitMs:r.settings.locks.wait_ms,mutate(o){let a=zi(e,t,ai(o),n);return{raw:`${JSON.stringify(a,null,2)}
|
|
5
|
+
`,result:a}}});return{policy_result:!0,action:e,changed:i.changed,result:i.result}}async function Ec(e,t,n){let r,i=await pi({...n,id:e,op:"policy_approve",message:t.message,resolveHistoryContext:()=>({workflow_approval:r}),async mutate(o){let s=(await Ae(n.pmRoot)).policies.find(c=>c.id===t.policy);if(!s||s.rule.kind!=="approval")throw new m("--policy must name an approval rule.",h.USAGE);if(!s.rule.authors.includes(n.author))throw new m("This actor is not a declared approver.",h.CONFLICT);return await si(n.pmRoot,o.metadata.id),r={policy_id:s.id,policy_fingerprint:br(s),content_fingerprint:Sr(s,{...o.metadata,body:o.body})},{changedFields:[]}}});return{policy_result:!0,action:"policy-approve",changed:!0,result:{id:i.item.id,...r,warnings:i.warnings}}}function $c(e,t){let n=qi(t),r=un({...n,id:n.id===void 0?e:n.id});if(e!==void 0&&e.trim()!==r.id)throw new m("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 r}async function dh(e,t,n={},r={}){if(!At.includes(e))throw new m("Unknown workflow policy action.",h.USAGE);if(e==="policy-presets")return{policy_result:!0,action:e,changed:!1,result:bc()};let i=await Sc(r,n.author);if(e==="policies")return{policy_result:!0,action:e,changed:!1,result:await Ae(i.pmRoot)};if(e==="policy-put"){let l=$c(t,n.definition);return Ji(e,l.id,{...n,definition:l},i)}if(!t?.trim())throw new m(`schema ${e} requires an operand.`,h.USAGE);if(["policy-remove","policy-mode"].includes(e))return Ji(e,t,n,i);if(e==="policy-approve"){if(n.dryRun)throw new m("Use policy-check to preview; policy-approve records an approval.",h.USAGE);return Ec(t,n,i)}let o=B(i.settings,W()),a=await Rt(i.pmRoot,t,i.settings.id_prefix,i.settings.item_format,o.type_to_folder);if(!a)throw new m(`Item ${t} not found.`,h.NOT_FOUND);let{document:s}=await Nt(a,{schema:i.settings.schema}),c={...s.metadata,body:s.body},d=n.definition===void 0?c:{...c,...qi(n.definition)};if(d.id!==c.id)throw new m("Policy preview cannot change the item id.",h.USAGE);return{policy_result:!0,action:e,changed:!1,result:await ci(i.pmRoot,await Ae(i.pmRoot),{operation:"update",author:i.author,before:c,after:d,completeness_only:n.definition===void 0})}}import{createHash as Xi}from"node:crypto";import Ve from"node:fs/promises";import Xe from"node:path";var Ac=new Set(It),De=new Set(jr.map(e=>O(e.id)).filter(e=>e.length>0));function Tc(e){let t=new Set;for(let n of e){let r=O(n);r.length>0&&t.add(r)}return[...t].sort((n,r)=>n.localeCompare(r))}function Wi(e){let t=O(e.id);if(t.length===0)throw new Error("Status id must not be empty.");if(De.has(t))throw new Error(`Cannot add-status the built-in status "${t}". Built-in statuses are reserved: ${[...De].join(", ")}.`);let n;if(e.roles!==void 0){n=[];let a=new Set;for(let s of e.roles){let c=typeof s=="string"?s.trim().toLowerCase():"";if(c.length!==0){if(!Ac.has(c))throw new Error(`Invalid status role "${s}". Allowed roles: ${It.join(", ")}.`);a.has(c)||(a.add(c),n.push(c))}}if(n.length===0)throw new Error(`Status role must include at least one lifecycle role. Allowed roles: ${It.join(", ")}.`)}let r=e.aliases===void 0?void 0:Tc(e.aliases).filter(a=>a!==t),i=e.description?.trim(),o=typeof e.order=="number"&&Number.isFinite(e.order)?Math.trunc(e.order):void 0;return{id:t,roles:n,aliases:r,description:i&&i.length>0?i:void 0,order:o}}function Ic(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 Oc(e){let t=Ic(e);if(!t)return[];let n=[];for(let r of t){if(typeof r!="object"||r===null||Array.isArray(r))continue;let i=r;typeof i.id!="string"||i.id.trim().length===0||n.push(i)}return n}function Be(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:Oc(t)}}function He(e){return`${JSON.stringify({statuses:e.statuses},null,2)}
|
|
6
|
+
`}function Bi(e,t,n){let r=e.statuses.slice(),i=r.findIndex(s=>O(s.id)===t.id),o=i>=0?r[i]:n,a={...o,id:t.id};return t.roles!==void 0&&(t.roles.length>0?a.roles=[...t.roles]:a.roles!==void 0&&delete a.roles),t.aliases!==void 0&&(t.aliases.length>0?a.aliases=[...t.aliases]:a.aliases!==void 0&&delete a.aliases),t.description!==void 0&&(a.description=t.description),t.order!==void 0&&(a.order=t.order),i>=0?r[i]=a:r.push(a),{file:{statuses:r},definition:a,replaced:o!==void 0}}function Hi(e,t){let n=O(t);if(n.length===0)throw new Error("Status id must not be empty.");if(De.has(n))throw new Error(`Cannot remove built-in status "${n}". Built-in statuses are reserved: ${[...De].join(", ")}.`);let r=e.statuses.slice(),i=r.findIndex(a=>O(a.id)===n);if(i<0)return{file:{statuses:r},removed:!1};let[o]=r.splice(i,1);return{file:{statuses:r},removed:!0,definition:o}}function In(e,t){let n=[e.id,...e.aliases??[]];for(let r of n){let i=O(r);if(i.length===0)continue;let o=t.get(i);if(o!==void 0&&o!==e.id)throw new Error(`Status token "${i}" already belongs to status "${o}". Choose a different id/alias to avoid shadowing it.`)}}function ye(e,t){if(typeof e!="string"||e.trim().length===0)throw new TypeError(`Schema migration ${t} must be non-empty`);return e.trim()}function Yi(e){let t=ye(e,"migrationId");if(!/^[a-zA-Z0-9._-]+$/.test(t))throw new TypeError("Schema migration migrationId must match [a-zA-Z0-9._-]+");return t}function Zi(e,t){let n=Cn(e),r=ye(t,"migrationScope");return`auto-${Xi("sha256").update(JSON.stringify({scope:r,request:n})).digest("hex").slice(0,20)}`}function Cn(e){let t=e.kind==="rename-type"?{kind:e.kind,from:ye(e.from,"source"),to:ye(e.to,"target")}:e.kind==="rename-field"?{kind:e.kind,from:O(ye(e.from,"source")),to:O(ye(e.to,"target")),...e.type===void 0?{}:{type:ye(e.type,"type")}}:{kind:e.kind,from:O(ye(e.from,"source")),to:O(ye(e.to,"target"))};if(t.from.toLowerCase()===t.to.toLowerCase())throw new TypeError("Schema migration source and target must differ");return t}function Cc(e){return e.kind==="rename-type"?"types":e.kind==="rename-field"?"fields":"statuses"}function Pc(e,t,n){let r=V(t.schema),i=Cc(n);return ee(e,r.files[i],X[i])}function Qi(e,t){return Xe.join(e,"transactions","schema",`${t}-plan.json`)}function Ut(e){return e.length===0?null:JSON.parse(e)}async function Ke(e){let t=await U(e);return{exists:t!==null,raw:t??""}}async function eo(e,t){t.exists?await fe(e,t.raw):await Ve.rm(e,{force:!0})}function Rc(e,t,n){let r=ie(e),i=r.definitions.findIndex(a=>a.name.trim().toLowerCase()===t.from.toLowerCase()),o=r.definitions.findIndex(a=>a.name.trim().toLowerCase()===t.to.toLowerCase());if(n==="stage"){if(o>=0)return ce(r);if(i<0)throw new TypeError(`Unknown custom type "${t.from}".`);r.definitions.push({...r.definitions[i],name:t.to})}else i>=0&&r.definitions.splice(i,1);return ce(r)}function to(e,t){return{...e,key:t,metadata_key:t,front_matter_key:t,cli_flag:t.replaceAll("_","-")}}function Nc(e,t,n){if(t.kind!=="rename-field"||n)return;let r=e.schema.fields.find(i=>O(i.key)===t.from);r!==void 0&&wn(to(r,t.to))}function Lc(e,t,n){let r=Je(e),i=r.fields.findIndex(a=>a.key===t.from),o=r.fields.findIndex(a=>a.key===t.to);if(n==="stage"){if(o>=0)return qe(r);if(i<0)throw new TypeError(`Unknown custom field "${t.from}".`);let a=to(r.fields[i],t.to);wn(a),r.fields.push(a)}else i>=0&&r.fields.splice(i,1);return qe(r)}function jc(e,t,n){let r=Be(e),i=r.statuses.findIndex(a=>a.id===t.from),o=r.statuses.findIndex(a=>a.id===t.to);if(n==="stage"){if(o>=0)return He(r);if(i<0)throw new TypeError(`Unknown custom status "${t.from}".`);r.statuses.push({...r.statuses[i],id:t.to})}else i>=0&&r.statuses.splice(i,1);return He(r)}function Dc(e,t,n){return t.kind==="rename-type"?Rc(e,t,n):t.kind==="rename-field"?Lc(e,t,n):jc(e,t,n)}function Te(e,t){return typeof e=="string"&&e.trim().toLowerCase()===t.from.toLowerCase()?t.to:e}function Pn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function Ye(e){return Array.isArray(e)?e.map(t=>Pn(t)).filter(t=>t!==void 0):[]}function Fc(e,t){for(let n of Ye(e.fields))Array.isArray(n.required_types)&&(n.required_types=n.required_types.map(r=>Te(r,t)));for(let n of Ye(e.type_workflows))n.type=Te(n.type,t)}function Mc(e,t){for(let r of Ye(e.definitions))r.default_status=Te(r.default_status,t);let n=Pn(e.workflow);if(n)for(let[r,i]of Object.entries(n))n[r]=Te(i,t);for(let r of Ye(e.type_workflows))Array.isArray(r.allowed_transitions)&&(r.allowed_transitions=r.allowed_transitions.map(i=>Array.isArray(i)?i.map(o=>Te(o,t)):i))}function Uc(e,t){for(let n of Ye(e.definitions)){for(let r of["required_create_fields","required_create_repeatables"])Array.isArray(n[r])&&(n[r]=n[r].map(i=>Te(i,t)));for(let r of["options","command_option_policies"])for(let i of Ye(n[r])){let o=r==="options"?"key":"option";i[o]=Te(i[o],t)}}}function Gc(e,t){let n=Pn(e.options);if(!n)return;if(t.kind==="rename-field"){if(!Object.prototype.hasOwnProperty.call(n,t.from))return;if(Object.prototype.hasOwnProperty.call(n,t.to))throw new TypeError(`Schema migration collision in saved template "${String(e.name??"unknown")}": target field "${t.to}" already exists.`);n[t.to]=n[t.from],delete n[t.from];return}let r=t.kind==="rename-type"?"type":"status";n[r]=Te(n[r],t)}function On(e,t){let n=JSON.parse(e);if(typeof n!="object"||n===null||Array.isArray(n))return e;let r=n;return t.kind==="rename-type"?Fc(r,t):t.kind==="rename-field"?Uc(r,t):Mc(r,t),Gc(r,t),`${JSON.stringify(r,null,2)}
|
|
7
|
+
`}function no(e,t){if(t.kind==="rename-type"){let r=ie(e).definitions;return{source:r.some(i=>i.name.trim().toLowerCase()===t.from.toLowerCase()),target:r.some(i=>i.name.trim().toLowerCase()===t.to.toLowerCase())}}if(t.kind==="rename-field"){let r=Je(e).fields;return{source:r.some(i=>i.key===t.from),target:r.some(i=>i.key===t.to)}}let n=Be(e).statuses;return{source:n.some(r=>r.id===t.from),target:n.some(r=>r.id===t.to)}}function zc(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 Jc(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 ro(e,t){let n=Cn(t.request),r=t.migrationId===void 0?Zi(n,t.migrationScope??"plan"):Yi(t.migrationId),i=e.map(c=>Jc(c,n)).filter(c=>c!==null).sort((c,d)=>c.id.localeCompare(d.id)),o=Xi("sha256").update(JSON.stringify({migrationId:r,request:n,items:i})).digest("hex"),a=new Set([...t.completedItemIds??[]].map(c=>c.trim()).filter(c=>c.length>0)),s=i.filter(c=>!a.has(c.id));return Object.freeze({migration_id:r,request:n,fingerprint:o,affected_item_count:i.length,pending_item_count:s.length,skipped_completed_count:i.length-s.length,items:Object.freeze(s)})}async function qc(e){let t=B(e.settings,W()),n=[...new Set(Object.values(t.type_to_folder))],r=await li(e.pmRoot,n),i=e.request.kind==="rename-type"?{types:[e.request.from]}:e.request.kind==="remap-status"?{statuses:[e.request.from]}:{metadataKeys:[e.request.from],...e.request.type===void 0?{}:{types:[e.request.type]}},o=r?await di({pmRoot:e.pmRoot,expectedSourceCursor:r.source_cursor,query:i}):null;return o?{items:o.items,selectionSource:"derived_index",typeToFolder:t.type_to_folder}:{items:await Le(e.pmRoot,e.settings.item_format,t.type_to_folder,[],e.settings.schema),selectionSource:"scan",typeToFolder:t.type_to_folder}}async function Wc(e,t){let n=await U(Qi(e,t));if(n===null)return null;try{let r=JSON.parse(n);if(r.schema_version!==1||r.plan.migration_id!==t||!Array.isArray(r.plan.items))throw new TypeError("invalid plan envelope");return r.plan}catch(r){throw new m(`Stored schema migration plan "${t}" is invalid: ${Rr(r)}`,h.GENERIC_FAILURE)}}async function Bc(e,t){let n=Qi(e,t.migration_id);await Ve.mkdir(Xe.dirname(n),{recursive:!0});let r={schema_version:1,plan:t,created_at:new Date().toISOString()};await fe(n,`${JSON.stringify(r,null,2)}
|
|
8
|
+
`)}function Hc(e,t){return JSON.stringify(e)===JSON.stringify(t)}async function Kc(e){let t=await Rt(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!t)throw new m(`Schema migration item "${e.id}" no longer exists.`,h.NOT_FOUND);return(await Nt(t,{schema:e.settings.schema})).document.metadata}function Ki(e,t,n){let r=n==="forward"?t.from:t.to,i=n==="forward"?t.to:t.from;if(t.kind==="rename-type"){if(e.metadata.type.toLowerCase()===i.toLowerCase())return[];if(e.metadata.type.toLowerCase()!==r.toLowerCase())throw new TypeError(`Schema migration expected type "${r}" on item "${e.metadata.id}".`);return e.metadata.type=i,["type"]}if(t.kind==="remap-status"){if(e.metadata.status.toLowerCase()===i.toLowerCase())return[];if(e.metadata.status.toLowerCase()!==r.toLowerCase())throw new TypeError(`Schema migration expected status "${r}" on item "${e.metadata.id}".`);return e.metadata.status=i,["status"]}let o=e.metadata;if(Object.prototype.hasOwnProperty.call(o,i)&&!Object.prototype.hasOwnProperty.call(o,r))return[];if(!Object.prototype.hasOwnProperty.call(o,r)||Object.prototype.hasOwnProperty.call(o,i))throw new TypeError(`Schema migration field state changed concurrently on item "${e.metadata.id}".`);return o[i]=o[r],delete o[r],[r,i]}function Vi(e){return{id:e.id,inspect:async()=>{let t=await Ke(e.filePath),n=no(t.raw,e.request),r=e.phase==="stage"?n.source&&n.target:!n.source&&n.target;return{state:r?"applied":"pending",...r?{result:{phase:e.phase}}:{}}},prepareCompensation:async()=>{let t=await Ke(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await Ke(e.filePath);return await fe(e.filePath,Dc(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 eo(e.filePath,{exists:t.exists,raw:t.raw})}}}function Vc(e){return{id:e.stepId,inspect:async()=>{let t=await Ke(e.filePath);return{state:On(t.raw,e.request)===t.raw?"applied":"pending"}},prepareCompensation:async()=>{let t=await Ke(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await Ke(e.filePath);return await fe(e.filePath,On(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 eo(e.filePath,{exists:t.exists,raw:t.raw})}}}function Xc(e){return{id:`item-${e.id}`,inspect:async()=>{let t=await A(e.pmRoot),n=B(t,W()).type_to_folder,r=await Kc({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id}),i=zc(r,e.request).length===0;return{state:i?"applied":"pending",...i?{result:{item_id:e.id}}:{}}},apply:async()=>{let t=await A(e.pmRoot),n=B(t,W()).type_to_folder,r=await _n({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id,op:`schema_${e.request.kind.replaceAll("-","_")}`,author:e.author,message:`Schema migration ${e.request.kind}: ${e.request.from} -> ${e.request.to}`,force:e.force,skipNoop:!0,mutate(i){return{changedFields:Ki(i,e.request,"forward")}}});return{item_id:e.id,changed_fields:r.changedFields}},compensate:async()=>{let t=await A(e.pmRoot),n=B(t,W()).type_to_folder;await _n({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id,op:`schema_${e.request.kind.replaceAll("-","_")}_compensate`,author:e.author,message:`Compensate schema migration ${e.request.kind}: ${e.request.to} -> ${e.request.from}`,force:!0,skipNoop:!0,mutate(r){return{changedFields:Ki(r,e.request,"reverse")}}})}}}async function Yc(e){let t=await Wc(e.pmRoot,e.migrationId);if(t){if(!Hc(t.request,e.request))throw new m(`Schema migration id "${e.migrationId}" already belongs to a different request.`,h.CONFLICT);return{plan:t,stored:!0}}let n=await qc({pmRoot:e.pmRoot,settings:e.settings,request:e.request});return{plan:{...ro(n.items,{migrationId:e.migrationId,request:e.request}),selection_source:n.selectionSource},stored:!1}}async function Zc(e){let t=no(await U(e.schemaPath)??"",e.request);if(!t.source)throw new m(`Schema migration source "${e.request.from}" is not a custom definition.`,h.NOT_FOUND);if(t.target)throw new m(`Schema migration target "${e.request.to}" already exists.`,h.CONFLICT);await Bc(e.pmRoot,e.plan)}async function Qc(e){let t=V(e.settings.schema),n=[...new Set([["types",X.types],["fields",X.fields],["workflows",X.workflows]].map(([i,o])=>ee(e.pmRoot,t.files[i],o)).filter(i=>i!==e.schemaPath))];try{let i=Xe.join(e.pmRoot,"templates"),o=await Ve.readdir(i,{withFileTypes:!0});n.push(...o.filter(a=>a.isFile()&&a.name.toLowerCase().endsWith(".json")).map(a=>Xe.join(i,a.name)))}catch(i){if(typeof i!="object"||i===null||!("code"in i)||!ke(i))throw i}n.sort((i,o)=>i.localeCompare(o));let r=[];for(let i of n){let o=await U(i);o!==null&&On(o,e.request)!==o&&r.push({filePath:i,beforeRaw:o})}return{paths:n,snapshots:r}}async function ed(e){for(let t of e.snapshots){let n=await Ve.readFile(t.filePath,"utf8"),r=Xe.relative(e.pmRoot,t.filePath).replaceAll("\\","/");await hn({pmRoot:e.pmRoot,author:e.author,documentPath:r,before:Ut(t.beforeRaw),after:Ut(n),op:"schema_migration_reference",idempotencyKey:`${e.plan.migration_id}:${e.plan.fingerprint}:${r}`,message:`${e.request.kind}: ${e.request.from} -> ${e.request.to}`,lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}}async function td(e,t,n){let r=Cn(e),i=M(process.cwd(),n.path);await ze(i);let o=t.migrationId===void 0?Zi(r,await Ve.realpath(i)):Yi(t.migrationId),a=await A(i),s=q(t.author,a.author_default),c=await Yc({pmRoot:i,settings:a,migrationId:o,request:r});Nc(a,r,c.stored);let d=c.plan;if(t.dryRun===!0)return{...d,action:r.kind,applied:!1,recovered:!1,migrated_item_count:0};let l=Pc(i,a,r),p=await U(l)??"";c.stored||await Zc({pmRoot:i,schemaPath:l,request:r,plan:d});let u=await Qc({pmRoot:i,schemaPath:l,settings:a,request:r}),_=[Vi({id:"stage-schema",filePath:l,request:r,phase:"stage"}),...u.paths.map((y,v)=>Vc({filePath:y,request:r,stepId:`reference-${String(v+1).padStart(4,"0")}`})),...d.items.map(y=>Xc({pmRoot:i,id:y.id,request:r,author:s,force:t.force===!0})),Vi({id:"retire-source",filePath:l,request:r,phase:"retire"})],g=await Ni({pmRoot:i,transactionId:`schema-${o}`,author:s,steps:_,lockTtlSeconds:Math.max(a.locks.ttl_seconds,300),lockWaitMs:a.locks.wait_ms}),w=await Ve.readFile(l,"utf8"),{historyPath:f}=await hn({pmRoot:i,author:s,documentPath:Xe.relative(i,l).replaceAll("\\","/"),before:Ut(p),after:Ut(w),op:"schema_migration",idempotencyKey:`${d.migration_id}:${d.fingerprint}`,message:`${r.kind}: ${r.from} -> ${r.to}; affected=${d.affected_item_count}`,lockTtlSeconds:a.locks.ttl_seconds,lockWaitMs:a.locks.wait_ms});return await ed({pmRoot:i,author:s,settings:a,request:r,plan:d,snapshots:u.snapshots}),{...d,action:r.kind,applied:!0,recovered:g.recovered,migrated_item_count:d.affected_item_count,workspace_history_path:f}}function nd(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(`
|
|
9
|
+
`)}import ao from"node:fs/promises";import Fe from"node:path";var Gt=["extensions","docs","examples","assets","prompts"],rd=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 id(e){return Gt.includes(e)}function od(e,t){if(t==null)return[];let n=Array.isArray(t)?t:[t],r=[];for(let i of n){if(typeof i!="string"||i.trim().length===0)throw new m(`Package manifest field pm.${e} must contain string paths.`,h.USAGE);r.push(i.trim())}return[...new Set(r)].sort((i,o)=>i.localeCompare(o))}function ad(e){if(e==null)return{};if(typeof e!="object"||Array.isArray(e))throw new m("Package manifest field pm must be an object.",h.USAGE);let t={},n=e;for(let[r,i]of Object.entries(n)){if(!id(r))continue;let o=od(r,i);o.length>0&&(t[r]=o)}return t}function le(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n.trim():void 0}function Rn(e){if(!Array.isArray(e))return;let t=e.map(n=>typeof n=="string"?n.trim():"").filter(n=>n.length>0);return t.length>0?[...new Set(t)].sort((n,r)=>n.localeCompare(r)):void 0}function io(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 sd(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={docs:le(t,"docs"),npm:le(t,"npm"),repository:le(t,"repository"),report:le(t,"report")};return Object.values(n).some(r=>typeof r=="string")?n:void 0}function cd(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={image:le(t,"image"),video:le(t,"video")};return Object.values(n).some(r=>typeof r=="string")?n:void 0}function dd(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n={display_name:le(t,"display_name")??le(t,"displayName"),category:le(t,"category"),summary:le(t,"summary"),links:sd(t.links),media:cd(t.media),tags:Rn(t.tags)};return Object.values(n).some(r=>r!==void 0)?n:void 0}async function ct(e){let t=Fe.join(e,"package.json");if(!await b(t))return{source:"convention",resources:{}};let n;try{n=JSON.parse(await ao.readFile(t,"utf8"))}catch(s){throw new m(`Failed to parse package manifest at "${t}": ${String(s)}`,h.USAGE)}if(typeof n!="object"||n===null||Array.isArray(n))throw new m(`Package manifest at "${t}" must be a JSON object.`,h.USAGE);let r=n,i=r.pm,o=i!=null,a=typeof i=="object"&&i!==null&&!Array.isArray(i)?i:{};return{source:o?"pm":"convention",package_json_path:t,package_name:typeof r.name=="string"?r.name:void 0,package_version:typeof r.version=="string"?r.version:void 0,package_private:r.private===!0,package_description:typeof r.description=="string"?r.description:void 0,package_keywords:Rn(r.keywords),package_homepage:typeof r.homepage=="string"?r.homepage:void 0,package_repository_url:io(r.repository),package_bugs_url:io(r.bugs),aliases:Rn(a.aliases),resources:ad(i),catalog:dd(a.catalog)}}async function oo(e){if(!await b(e))return[];let t=await ao.readdir(e,{withFileTypes:!0}),n=[];for(let r of t){if(!r.isDirectory())continue;let i=Fe.join(e,r.name);await b(Fe.join(i,"manifest.json"))&&n.push(i)}return n.sort((r,i)=>r.localeCompare(i))}async function zt(e){if(await b(Fe.join(e,"manifest.json")))return[e];let n=(await ct(e)).resources.extensions??[],r=new Set;for(let i of n){if(i.includes("*")||i.startsWith("!"))throw new m(`Package extension entry "${i}" uses a glob/exclusion pattern. pm package installs currently require concrete extension paths or directories.`,h.USAGE);let o=Fe.resolve(e,i);if(!K(e,o))throw new m(`Package extension entry "${i}" resolves outside package root.`,h.USAGE);if(await b(Fe.join(o,"manifest.json"))){r.add(o);continue}for(let a of await oo(o))r.add(a)}if(n.length===0)for(let i of rd.extensions)for(let o of await oo(Fe.join(e,i)))r.add(o);return[...r].sort((i,o)=>i.localeCompare(o))}import{execFile as Rd}from"node:child_process";import C from"node:fs/promises";import zn from"node:os";import $ from"node:path";import{fileURLToPath as Nd}from"node:url";import{promisify as Ld}from"node:util";import jd from"npm-package-arg";import{extract as Dd,list as Fd}from"tar";import bd from"node:fs/promises";import oe from"node:path";import so from"node:fs/promises";import Nn from"node:path";function Q(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function k(e){return e.trim().toLowerCase()}function Jt(e){let t=e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-"),n=0;for(;t[n]==="-";)n+=1;let r=t.length;for(;r>n&&t[r-1]==="-";)r-=1;let i=t.slice(n,r);if(i.length===0)throw new m("Extension manifest name must resolve to a non-empty directory name.",h.USAGE);if(i==="."||i==="..")throw new m('Extension manifest name must not resolve to "." or "..".',h.USAGE);return i}function Ln(e){return qr(e)}async function ld(e){try{let t=JSON.parse(await so.readFile(Nn.join(e,"package.json"),"utf8")),n=typeof t.name=="string"&&/^(?:@[a-z0-9._~-]+\/)?[a-z0-9._~-]+$/iu.test(t.name)?t.name:void 0;return{...n?{package_name:n}:{},has_build_script:["build","prepare","prepack"].some(r=>typeof t.scripts?.[r]=="string")}}catch{return{has_build_script:!1}}}async function pd(e,t,n){if(n.source_kind!=="github"||typeof n.source_root!="string")return new m(`Extension entry file is missing at "${t}".`,h.USAGE);let r=await ld(n.source_root),i=r.package_name?`pm package install npm:${r.package_name}`:void 0,o=n.source_input??n.source_root;return new m(`Extension entry "${e.entry}" is absent from GitHub source "${o}". pm package install copies GitHub repositories without running package scripts${r.has_build_script?", and this package declares a build or publish script":""}. ${i?`Try "${i}" if the package is published, or install a locally built directory.`:"Build the source locally and install that directory, or use its published npm: package."}`,h.USAGE,{code:"github_source_entry_unbuilt",required:"Use a GitHub tree with committed runtime output, a published npm artifact, or a locally built source directory.",why:"GitHub installation is a source copy and never executes untrusted package build scripts.",examples:i?[i,`pm package install ${n.source_root}`]:[`pm package install ${n.source_root}`],nextSteps:i?[`Retry with ${i}.`,"Or build the repository locally, then install its directory."]:["Build the repository locally, then install its directory.","If it is published, retry with pm package install npm:<package-name>."],recovery:{attempted_command:`pm install ${o}`,normalized_args:["install",o],...i?{next_best_command:i}:{}}})}async function Ze(e,t={}){let n=Nn.join(e,"manifest.json");if(!await b(n))throw new m(`Extension manifest is missing at "${n}".`,h.USAGE);let r;try{r=JSON.parse(await so.readFile(n,"utf8"))}catch(a){throw new m(`Failed to parse extension manifest at "${n}": ${ud(a)}`,h.USAGE)}let i=Ln(r);if(!i)throw new m(`Extension manifest at "${n}" is invalid.`,h.USAGE);let o=Nn.resolve(e,i.entry);if(!K(e,o))throw new m(`Extension entry "${i.entry}" resolves outside extension directory "${e}".`,h.USAGE);if(!await b(o))throw await pd(i,o,t);if(!await Br(e,o))throw new m(`Extension entry "${i.entry}" resolves outside extension directory after symlink resolution.`,h.USAGE);return{directory:e,manifest_path:n,entry_path:o,manifest:i}}function ud(e){return e instanceof Error?e.message:String(e)}import jn from"node:fs/promises";import md from"node:path";var fd=".managed-extensions.json",qt=1;function dt(e){return md.join(e,fd)}function hd(){return{version:qt,updated_at:T(),entries:[]}}function lt(e){return[...e].sort((t,n)=>{let r=t.scope.localeCompare(n.scope);if(r!==0)return r;let i=t.name.localeCompare(n.name);return i!==0?i:t.directory.localeCompare(n.directory)})}function co(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 Y(e){return typeof e=="string"?e:void 0}var gd=/^(?:npm_registry|github_remote)_lookup_timed_out$/u;function _d(e,t){let n=Y(t);return n===void 0||e.kind!=="github"||n.trim().length===0||/^[a-z0-9_]+$/u.test(n.trim())?n:"github_remote_lookup_failed"}function lo(e){return typeof e=="string"&&gd.test(e.trim())}function yd(e,t){return lo(e)&&typeof t=="number"&&Number.isSafeInteger(t)&&t>0?{update_check_timeout_ms:t}:{}}function wd(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 vd(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:Y(t.name),package:Y(t.package),version:Y(t.version),repository:Y(t.repository),owner:Y(t.owner),repo:Y(t.repo),ref:Y(t.ref),subpath:Y(t.subpath),commit:Y(t.commit)}}function kd(e){if(typeof e!="object"||e===null)return null;let t=e;if(!wd(t))return null;let n=vd(t.source);if(!n)return null;let r=Ur(t.contributions);return r===null?null:{name:t.name.trim(),directory:t.directory.trim(),scope:t.scope,manifest_version:t.manifest_version,manifest_entry:t.manifest_entry,capabilities:Q(t.capabilities),contributions:r,installed_at:t.installed_at,updated_at:t.updated_at,source:n,last_update_check_at:Y(t.last_update_check_at),last_update_remote_commit:Y(t.last_update_remote_commit),last_update_remote_version:Y(t.last_update_remote_version),update_available:lo(t.update_error)?null:typeof t.update_available=="boolean"||t.update_available===null?t.update_available:void 0,update_error:_d(n,t.update_error),...yd(t.update_error,t.update_check_timeout_ms)}}function xd(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.version!==qt||!Array.isArray(t.entries))return null;let n=[];for(let r of t.entries){let i=kd(r);i&&n.push(i)}return{version:qt,updated_at:Y(t.updated_at)??T(),entries:lt(n)}}async function pe(e){let t=dt(e),n=hd();try{let r=await jn.readFile(t,"utf8"),i=JSON.parse(r),o=xd(i);if(!o)throw new m(`Managed extension state file "${t}" has an invalid schema. Repair or remove it before mutating extension state.`,h.GENERIC_FAILURE);return{path:t,state:o,warnings:[]}}catch(r){if(r instanceof m)throw r;if(typeof r=="object"&&r!==null&&"code"in r&&ke(r))return{path:t,state:n,warnings:[]};throw new m(`Managed extension state file "${t}" could not be read. Repair or remove it before mutating extension state.`,h.GENERIC_FAILURE)}}async function Qe(e,t){let n=dt(e),r={version:qt,updated_at:T(),entries:lt(t.entries)};await jn.mkdir(e,{recursive:!0}),await jn.writeFile(n,`${JSON.stringify(r,null,2)}
|
|
10
|
+
`,"utf8")}function pt(e,t){let n=e.entries.filter(r=>k(r.name)!==k(t.name)&&k(r.directory)!==k(t.directory));return n.push(t),{...e,updated_at:T(),entries:lt(n)}}async function po(e,t,n,r){let i=t.entries.find(a=>k(a.name)===k(n));if(!i)return t;let o=pt(t,{...i,contributions:r});return await Qe(e,o),o}var Sd="PM_CLI_PACKAGE_ROOT",uo={beads:{package_directory:"pm-beads",legacy_extension_directory:"beads"},todos:{package_directory:"pm-todos",legacy_extension_directory:"todos"}},Ed=new Set(["*","all"]);function Dn(){let e=[],t=process.env[Sd];return typeof t=="string"&&t.trim().length>0&&e.push(oe.resolve(t.trim())),e.push(xe(import.meta.url,["../../.."])),[...new Set(e)]}async function ut(e){let t=e.trim().toLowerCase(),n=await fo(t);if(n)return n;let r=uo[t];if(!r)return null;for(let i of Dn()){let o=oe.join(i,".agents","pm","extensions",r.legacy_extension_directory);if(await b(oe.join(o,"manifest.json")))return o}return null}function mo(e){return Ed.has(e.trim().toLowerCase())}function $d(e){return e.replace(/^pm-/i,"").trim().toLowerCase()}async function Ad(e,t){let n=await bd.readdir(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||!r.name.startsWith("pm-"))continue;let i=oe.join(e,r.name);if(!await b(oe.join(i,"package.json")))continue;let o=await ct(i),a=o.aliases&&o.aliases.length>0?o.aliases:[$d(r.name)];for(let s of a){let c=s.trim().toLowerCase();c.length===0||t.has(c)||t.set(c,{alias:c,package_directory:r.name,package_root:i,package_name:o.package_name??null})}}}async function Fn(){let e=new Map;for(let t of Dn()){let n=oe.join(t,"packages");await b(n)&&await Ad(n,e)}for(let[t,n]of Object.entries(uo))if(!e.has(t))for(let r of Dn()){let i=oe.join(r,"packages",n.package_directory);if(await b(oe.join(i,"package.json"))){e.set(t,{alias:t,package_directory:n.package_directory,package_root:i,package_name:null});break}}return[...e.values()].sort((t,n)=>t.alias.localeCompare(n.alias))}async function Wt(){return(await Fn()).map(e=>e.alias)}async function fo(e){let t=e.trim().toLowerCase();return(await Fn()).find(r=>r.alias===t||r.package_directory.toLowerCase()===t||r.package_name?.toLowerCase()===t)?.package_root??null}async function ho(e){let t=await fo(e);return t?(await ct(t)).package_name??null:null}async function go(e){let t=await ut(e);if(!t)return null;try{let n=await zt(t);return n.length!==1?null:(await Ze(n[0])).manifest.name}catch{return null}}function Td(e){return{docs:e.catalog?.links?.docs??e.package_homepage,npm:e.catalog?.links?.npm??(e.package_name&&e.package_private!==!0?`https://www.npmjs.com/package/${encodeURIComponent(e.package_name)}`:void 0),repository:e.catalog?.links?.repository??e.package_repository_url,report:e.catalog?.links?.report??e.package_bugs_url}}function Id(e,t,n,r,i,o){let a=r==="global"?"--global":"--project",s=Object.fromEntries(Gt.filter(c=>c!=="extensions").map(c=>[c,e.resources[c]??[]]).filter(([,c])=>Array.isArray(c)&&c.length>0));return{alias:t.alias,aliases:n,bundled:!0,available:!0,installed:n.some(c=>i.has(c))||o.has(oe.resolve(t.package_root)),install_target:t.alias,install_command:`pm install ${t.alias} ${a}`,package_name:e.package_name,package_version:e.package_version,description:e.catalog?.summary??e.package_description,keywords:e.package_keywords??[],resources:e.resources,installable_resources:{extensions:e.resources.extensions??[]},metadata_only_resources:s,catalog:{display_name:e.catalog?.display_name,category:e.catalog?.category,tags:e.catalog?.tags??e.package_keywords??[],links:Td(e),media:e.catalog?.media}}}async function _o(e,t,n={}){let r=Ct(M(process.cwd(),t.path),process.cwd()),i=e==="global"?r.global:r.project,o=await pe(i),a=new Set(o.state.entries.filter(u=>u.scope===e).filter(u=>u.source.kind!=="builtin").map(u=>oe.resolve(u.source.location))),s=new Set(o.state.entries.filter(u=>u.scope===e&&u.source.kind==="builtin").flatMap(u=>[u.source.name,u.source.input,u.source.location]).filter(u=>typeof u=="string"&&u.trim().length>0).map(u=>u.trim().toLowerCase())),c=[],d=new Map;for(let u of await Fn()){let _=oe.resolve(u.package_root),g=d.get(_)??[];g.push(u),d.set(_,g)}for(let u of d.values()){let _=u[0],g=u.map(f=>f.alias).sort((f,y)=>f.localeCompare(y)),w=await ct(_.package_root);c.push(Id(w,_,g,e,s,a))}let l=Cd(n.fields),p=l?c.map(u=>Pd(u,l)):c;return{total:p.length,scope:e,installable_resource_kinds:["extensions"],metadata_only_resource_kinds:Gt.filter(u=>u!=="extensions"),packages:p}}var Od=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 Cd(e){if(e===void 0)return;let t=mi(e);if(t.length===0)throw new m("Package catalog --fields requires a comma-separated list of field names",h.USAGE);let n=t.filter(r=>!Od.has(r));if(n.length>0)throw new m(`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 Pd(e,t){let n={};for(let r of t)r==="category"?n[r]=e.catalog?.category??null:r==="display_name"?n[r]=e.catalog?.display_name??null:n[r]=e[r]??null;return n}var vo=Ld(Rd),Bt="@unbrained/pm-cli",Md={maxArchiveBytes:64*1024*1024,maxEntries:4096,maxExpandedBytes:256*1024*1024,maxEntryBytes:64*1024*1024},Mn;async function ko(e,t=process.cwd()){let n=e.trim();if(!/^(@[^/\\\s]+\/[^/\\\s]+|[^@/\\\s][^/\\\s]*)$/u.test(n))return null;let r=$.resolve(t);for(;;){let i=$.join(r,"node_modules",...n.split("/")),o=$.join(i,"package.json");if(await b(o))try{let s=JSON.parse(await C.readFile(o,"utf8"));if(s.name===n)return{package:n,...typeof s.version=="string"?{version:s.version}:{},directory:i}}catch{return null}let a=$.dirname(r);if(a===r)return null;r=a}}function Un(e,t,n){let r=e.split("/").map(d=>d.trim()).filter(d=>d.length>0);if(r.length<2)return null;let i=r[0],o=r[1].replace(/\.git$/i,"");if(i.length===0||o.length===0)return null;let a=r.slice(2),s,c;return a[0]==="tree"&&a.length>=2?(s=a[1],c=a.slice(2).join("/")):a.length>0&&(c=a.join("/")),typeof n=="string"&&n.trim().length>0&&(s=n.trim()),{kind:"github",input:t,owner:i,repo:o,repository:`https://github.com/${i}/${o}.git`,ref:s,subpath:c&&c.length>0?c:void 0}}function Ud(e,t,n){let r=e.slice(4).trim();if(r.length===0)throw new m('npm package source must include a package spec after "npm:".',h.USAGE);if(t)throw new m('Options "--gh/--github" cannot be combined with npm: package sources.',h.USAGE);if(n)throw new m('Option "--ref" cannot be combined with npm: package sources.',h.USAGE);return{kind:"npm",input:e,spec:r}}function mt(e,t={}){let n=e.trim();if(n.length===0)throw new m("Extension source is required for --install.",h.USAGE);let r=typeof t.ref=="string"&&t.ref.trim().length>0?t.ref.trim():void 0;if(n.startsWith("npm:"))return Ud(n,t.forceGithub===!0,r);let i=(()=>{try{let a=new URL(n);if(a.hostname!=="github.com")return null;let s=a.pathname.replace(/^\/+/,"");return Un(s,n,r)}catch{return null}})();if(i)return i;let o=n.startsWith("github.com/")?n.slice(11):null;if(o){let a=Un(o,n,r);if(!a)throw new m(`Invalid GitHub source "${n}".`,h.USAGE);return a}if(t.forceGithub){let a=Un(n,n,r);if(!a)throw new m(`Invalid GitHub shorthand "${n}".`,h.USAGE);return a}if(/^https?:\/\//i.test(n))throw new m(`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 yo(e,t=vo,n){try{return((await t("git",e,{encoding:"utf8",timeout:n})).stdout??"").trim()}catch(r){let i=typeof r=="object"&&r!==null&&"stderr"in r?String(r.stderr):"",o=i.trim().length>0?i.trim():r instanceof Error?r.message:String(r);throw new m(`Git command failed: git ${e.join(" ")}
|
|
11
|
+
${o}`,h.GENERIC_FAILURE)}}function Jn(e=process.platform){return e==="win32"?"npm.cmd":"npm"}function qn(e=process.platform){return e==="win32"}async function xo(e,t,n=vo,r=process.platform,i=process.env){let o=Jn(r),a=Object.fromEntries(Object.entries(i).filter(([s])=>s.toLowerCase()!=="npm_config_allow_scripts"));a.NPM_CONFIG_ALLOW_SCRIPTS="";try{return((await n(o,e,{cwd:t,encoding:"utf8",env:a,shell:qn(r)})).stdout??"").trim()}catch(s){let c=typeof s=="object"&&s!==null&&"stderr"in s?String(s.stderr):"",d=c.trim().length>0?c.trim():s instanceof Error?s.message:String(s);throw new m(`npm command failed: ${o} ${e.join(" ")}
|
|
12
|
+
${d}`,h.GENERIC_FAILURE)}}function bo(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 So(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 Gd(e){let n=(e instanceof Error?e.message:String(e)).toLowerCase();return n.includes("npm err! code e404")||n.includes("404 not found")||n.includes("is not in this registry")}function zd(e){let n=(e instanceof Error?e.message:String(e)).toLowerCase();return Gd(e)||n.includes("not found")}function Jd(e){let t=e.trim().toLowerCase();return t.startsWith("@unbrained/pm-")||t.startsWith("pm-")}function qd(e){let t=bo(e),n=Jd(t),r=t.replace(/^.*\//,""),i=n?`github.com/unbraind/${r}`:void 0,o=i?`pm package install --project ${i}`:void 0;return{message:n?`npm package "${e}" was not found in the registry. If this is an unpublished first-party pm package, install its GitHub repository instead.`:`npm package "${e}" was not found in the registry.`,context:{code:"npm_package_not_found",required:"Use an install source that exists, or publish the npm package before installing it with npm:<name>.",why:"Classifying npm 404s avoids repeated registry retries and gives agents a deterministic fallback path.",examples:o?[o,"pm package catalog --project --json"]:[`npm view ${t}`,"pm package catalog --project --json"],nextSteps:o?[`Try ${o} if the repository exists.`,"Use pm package catalog --project --json to inspect bundled package aliases before installing."]:[`Verify ${t} exists in the npm registry and that you have access to it.`,"Use pm package catalog --project --json to inspect bundled package aliases before installing."],recovery:{attempted_command:`pm install --project npm:${e}`,normalized_args:["install","--project",`npm:${e}`],...i&&o?{fallback_candidates:[{source:i,command:o,reason:"canonical first-party GitHub repository fallback for unpublished pm packages"}],next_best_command:o}:{}}}}}function Wd(e,t){if(!zd(t))return null;let n=qd(e);return new m(n.message,h.NOT_FOUND,n.context)}async function Eo(e){if($.isAbsolute(e)||e.startsWith(".")||e.startsWith("..")){let t=$.resolve(process.cwd(),e);return await b(t)?t:null}try{let t=new URL(e);if(t.protocol==="file:"){let n=Nd(t);return await b(n)?n:null}}catch{}if(!/^[a-z][a-z0-9+.-]*:/i.test(e)){let t=$.resolve(process.cwd(),e);if(await b(t))return t}return null}async function Bd(e){let t=await Eo(e);if(t)return t;let n=Hd(e);return n!==e?n:(/^[a-z][a-z0-9+.-]*:/i.test(e),e)}function Hd(e,t=process.cwd()){let n="@file:",r=e.lastIndexOf(n);if(!So(e))return e;let i=e.slice(0,r),o=e.slice(r+n.length);if(o.startsWith("//")&&!o.startsWith("///"))return e;if(!o.startsWith("/"))return`${i}@${$.resolve(t,o)}`;let a;try{a=decodeURIComponent(new URL(`file:${o}`).pathname)}catch{return e}let s=/^\/[A-Za-z]:/.test(a)?a.slice(1):a;return`${i}@${s}`}function wo(e,t){let n=$.resolve(e,t),r=$.relative(e,n);if(r.length===0||r===".."||r.startsWith(`..${$.sep}`)||$.isAbsolute(r))throw new m("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 Kd(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 Vd(e){return(Array.isArray(e)?e.map(n=>({value:n})):typeof e=="object"&&e!==null?Object.entries(e).map(([n,r])=>({key:n,value:r})):[]).flatMap(({key:n,value:r})=>{let i=Kd(r,n);return i?[i]:[]})}function Xd(e,t){let n=t?.trim().toLowerCase(),r=n?e.filter(a=>{let s=a.name?.trim().toLowerCase();return s!==void 0?s===n:a.key?.trim().toLowerCase()===n}):[];if(r.length===1)return r[0];if(e.length!==1)return;let i=e[0],o=i.name??i.key;return n&&o!==void 0&&o.trim().toLowerCase()!==n?void 0:i}function Yd(e,t,n){let r;try{r=JSON.parse(e)}catch{let a=e.split(/\r?\n/).map(s=>s.trim()).filter(s=>s.length>0).at(-1);if(!a)throw new m("npm pack did not report a tarball filename.",h.GENERIC_FAILURE);return{tarball:wo(t,a)}}let i=Vd(r),o=Xd(i,n);if(!o)throw new m("npm pack --json returned an unsupported or ambiguous package receipt.",h.GENERIC_FAILURE,{code:"npm_pack_json_shape_unsupported",required:"Use an npm client that returns an array of package receipts or an object keyed by package name, with exactly one requested package entry containing filename.",why:`Well-formed JSON contained ${i.length} usable package receipt(s), but pm could not select ${n??"one package"} deterministically.`});return{tarball:wo(t,o.filename),package:o.name??o.key,version:o.version}}async function Zd(e){return Qd(e,xo)}async function Qd(e,t){let n=await Eo(e.spec);if(n){if((await C.stat(n)).isFile()&&$o(n))return Gn(n);let a=$.join(n,"package.json"),s=await b(a)?JSON.parse(await C.readFile(a,"utf8")):{};return{directory:await Ht(n,e.input),package:typeof s.name=="string"?s.name:void 0,version:typeof s.version=="string"?s.version:void 0,cleanup:async()=>{}}}let r=await C.mkdtemp($.join(zn.tmpdir(),"pm-npm-package-source-")),i=$.join(r,"pack");await C.mkdir(i,{recursive:!0});try{let o=await Bd(e.spec),a=await t(["pack",o,"--json","--pack-destination",i]),s=Yd(a,i,So(e.spec)?void 0:bo(e.spec));if(!await b(s.tarball))throw new m("npm pack did not create its reported package archive.",h.GENERIC_FAILURE,{code:"npm_package_archive_missing",required:"Retry the npm package install with a healthy registry and writable temporary directory.",why:"The package manager reported a tarball filename that was absent before validation, so pm cannot safely extract or install it."});let c=await Gn(s.tarball);return{directory:c.directory,package:s.package??c.package,version:s.version??c.version,cleanup:async()=>{try{await c.cleanup()}finally{await C.rm(r,{recursive:!0,force:!0})}}}}catch(o){await C.rm(r,{recursive:!0,force:!0});let a=Wd(e.spec,o);throw a||o}}function $o(e){let t=e.toLowerCase();return t.endsWith(".tgz")||t.endsWith(".tar.gz")}function we(e){throw new m(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 el(e,t,n){if(e.meta)return;n.entries+=1,n.entries>t.maxEntries&&we(`Local package archive exceeds the ${t.maxEntries} entry limit.`);let r=e.path,i=r.split("/");(r.includes("\\")||r.startsWith("/")||/^[A-Za-z]:/u.test(r)||i.some(o=>o===".."))&&we(`Local package archive contains an escaping path: "${r}".`),i[0]!=="package"&&we(`Local package archive entry "${r}" is outside the required package/ root.`),(e.type==="SymbolicLink"||e.type==="Link")&&we(`Local package archive link "${r}" is not supported.`),e.type!=="File"&&e.type!=="OldFile"&&e.type!=="Directory"&&we(`Local package archive entry "${r}" uses unsupported type "${e.type}".`),e.size>t.maxEntryBytes&&we(`Local package archive entry "${r}" exceeds the ${t.maxEntryBytes} byte entry limit.`),n.expandedBytes+=e.size,n.expandedBytes>t.maxExpandedBytes&&we(`Local package archive exceeds the ${t.maxExpandedBytes} expanded byte limit.`),r==="package/package.json"&&(n.packageJsonEntries+=1)}async function Gn(e,t=Md){(await C.stat(e)).size>t.maxArchiveBytes&&we(`Local package archive exceeds the ${t.maxArchiveBytes} archive byte limit.`);let r=await C.mkdtemp($.join(zn.tmpdir(),"pm-local-package-archive-")),i=$.join(r,"extract");await C.mkdir(i,{recursive:!0});let o={entries:0,expandedBytes:0,packageJsonEntries:0},a;try{if(await Fd({file:e,strict:!0,maxDecompressionRatio:100,onReadEntry:l=>{if(a===void 0)try{el(l,t,o)}catch(p){a=p}}}),a!==void 0)throw a;o.packageJsonEntries!==1&&we(`Local package archive must contain exactly one package/package.json entry; found ${o.packageJsonEntries}.`),await Dd({file:e,cwd:i,strict:!0,preservePaths:!1,preserveOwner:!1,noMtime:!0,unlink:!0,maxDepth:64,maxDecompressionRatio:100});let s=$.join(i,"package"),c=$.join(s,"package.json"),d=JSON.parse(await C.readFile(c,"utf8"));return await tl(s),{directory:await Ht(s,e),package:typeof d.name=="string"?d.name:void 0,version:typeof d.version=="string"?d.version:void 0,cleanup:async()=>{await C.rm(r,{recursive:!0,force:!0})}}}catch(s){throw await C.rm(r,{recursive:!0,force:!0}),s}}async function tl(e,t=xo){let n=$.join(e,"package.json");if(!await b(n))return;let r;try{r=JSON.parse(await C.readFile(n,"utf8"))}catch{return}if(typeof r!="object"||r===null)return;let i=r,o=sl(i),a=nl(i);if(o.length===0&&!a)return;let s={...r};delete s.devDependencies;let c={...s};rl(c),await C.writeFile(n,`${JSON.stringify(c,null,2)}
|
|
13
|
+
`,"utf8");try{await Promise.all([C.rm($.join(e,"package-lock.json"),{force:!0}),C.rm($.join(e,"npm-shrinkwrap.json"),{force:!0})]),o.length>0&&await t(["install","--ignore-scripts","--no-audit","--fund=false","--package-lock=false","--no-save","--omit=peer","--"],e),a&&await il(e)}finally{await C.writeFile(n,`${JSON.stringify(s,null,2)}
|
|
14
|
+
`,"utf8")}}function nl(e){for(let t of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(typeof t=="object"&&t!==null&&Bt in t)return!0;return!1}function rl(e){for(let t of["dependencies","optionalDependencies","peerDependencies"]){let n=e[t];if(typeof n!="object"||n===null)continue;let r={...n};delete r[Bt],Object.keys(r).length===0?delete e[t]:e[t]=r}}async function il(e){let t=xe(import.meta.url,["../../.."]),[n,r]=Bt.split("/"),i=$.join(e,"node_modules",n),o=$.join(i,r);await C.mkdir(i,{recursive:!0}),await C.rm(o,{recursive:!0,force:!0}),await C.symlink(t,o,ol(process.platform))}function ol(e){return e==="win32"?"junction":"dir"}function al(e,t){if(e.startsWith("-"))throw new m(`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(r=>{let i=r.charCodeAt(0);return i<=31||i===127||"&|;()`\"'".includes(r)}))throw new m(`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{jd.resolve(e,t)}catch{throw new m(`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 sl(e){let t=new Map;for(let n of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(!(typeof n!="object"||n===null))for(let[r,i]of Object.entries(n)){if(r===Bt||typeof i!="string"||i.trim().length===0||t.has(r))continue;let o=i.trim();t.set(r,al(r,o))}return[...t.values()]}async function Ht(e,t){let n=await zt(e);if(n.length===1)return n[0];if(n.length>1){let r=n.map(i=>$.relative(e,i).replaceAll($.sep,"/")).sort((i,o)=>i.localeCompare(o));throw new m(`Package source "${t}" contains multiple extension manifests. Provide an explicit extension path. Candidates: ${r.join(", ")}`,h.USAGE)}throw new m(`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 cl(e,t){let n=[];t.subpath&&(n.push(t.subpath),n.push($.posix.join(".agents/pm/extensions",t.subpath)),n.push($.posix.join(".custom/pm-extensions",t.subpath)),n.push($.posix.join(".custom/pm-extension",t.subpath)));for(let i of n){let o=$.resolve(e,i);if(K(e,o)&&await b($.join(o,"manifest.json")))return{directory:o,resolved_subpath:i}}if(await b($.join(e,"manifest.json")))return{directory:e,resolved_subpath:"."};let r=await Ht(e,t.input);return{directory:r,resolved_subpath:$.relative(e,r).replaceAll($.sep,"/")}}function dl(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 ll(e){let t=`Local extension source does not exist: "${e.absolute_path}".`,n=e.input.trim();if(!dl(n))return new m(t,h.NOT_FOUND);let r=[];try{let o=process.env.PM_CLI_PACKAGE_ROOT,a=typeof o=="string"&&o.trim().length>0?$.resolve(o.trim()):"";Mn?.key!==a&&(Mn={key:a,aliases:await Wt()}),r=Mn.aliases}catch{}let i=[`Retry with pm package install npm:${n} if the package is published to npm.`,`Or inspect bundled packages with pm package catalog --project --json before installing by alias. Known aliases (blank means none found): ${r.join(", ")}`];return new m(`${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 package install npm:${n}`,"pm package catalog --project --json"],nextSteps:i,recovery:{attempted_command:`pm install ${n}`,normalized_args:["install",n],next_best_command:`pm package install npm:${n}`}})}async function Ao(e){if(e.kind==="local"){let r;try{r=await C.stat(e.absolute_path)}catch{throw await ll(e)}if(r.isFile()&&$o(e.absolute_path)){let o=await Gn(e.absolute_path);return{source:e,directory:o.directory,source_root:$.dirname(o.directory),resolved_subpath:$.relative($.dirname(o.directory),o.directory).replaceAll($.sep,"/"),npm_package:o.package,npm_version:o.version,cleanup:o.cleanup}}if(!r.isDirectory())throw new m(`Local extension source must be a directory or npm .tgz/.tar.gz archive: "${e.absolute_path}".`,h.USAGE);let i=await Ht(e.absolute_path,e.input);return{source:e,directory:i,source_root:e.absolute_path}}if(e.kind==="npm"){let r=await Zd(e);return{source:e,directory:r.directory,source_root:$.dirname(r.directory),cleanup:r.cleanup,resolved_subpath:$.relative($.dirname(r.directory),r.directory).replaceAll($.sep,"/"),npm_package:r.package,npm_version:r.version}}let t=await C.mkdtemp($.join(zn.tmpdir(),"pm-extension-source-")),n=["clone","--depth","1"];e.ref&&n.push("--branch",e.ref),n.push(e.repository,t);try{await yo(n);let r=await yo(["-C",t,"rev-parse","HEAD"]),i=await cl(t,e);return{source:e,directory:i.directory,source_root:t,resolved_subpath:i.resolved_subpath,commit:r,cleanup:async()=>{await C.rm(t,{recursive:!0,force:!0})}}}catch(r){throw await C.rm(t,{recursive:!0,force:!0}),r}}async function et(e,t){if(!await b(e)||!await b(t))return!1;let[n,r]=await Promise.all([C.realpath(e),C.realpath(t)]);return n===r}import ft from"node:fs/promises";import ht from"node:path";var Wn=1,Me="2026.6.24",pl=">=22.18.0",ul={fs_read:!1,fs_write:!1,network:!1,env_read:!1,env_write:!1,process_spawn:!1},To=new Set([...Ar.map(e=>e.split("-")[0].toLowerCase()),...Object.keys($r).map(e=>e.toLowerCase()),"scaffold"]),ml="^6.0.0",fl="^22.0.0",Co=["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."," }"," }","}",""],ue=[" } finally {"," await deactivateIfNeeded(ext, deactivated);"," }"];function Io(e,t){return e.map(n=>n===""?n:`${t}${n}`)}function Po(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 Ro(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 hl={compilerOptions:{target:"ES2022",module:"NodeNext",moduleResolution:"NodeNext",strict:!0,esModuleInterop:!0,skipLibCheck:!0,noEmit:!0,allowImportingTsExtensions:!0,resolveJsonModule:!0,types:["node"]},include:["**/*.ts"]},Oo=["commands","hooks","search","importers","schema","profile","renderers","parser","preflight","services"],No={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"]},gl={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"]'},_l={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."},yl={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."},Lo="- `tsconfig.json`: strict type-check-only TypeScript config (`noEmit`) for the `.ts` source the loader runs directly.",wl={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."]},vl={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."]},kl={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`."]},xl={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 jo(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 Do(e,t){return e==="schema"?kl[t]:e==="profile"?xl[t]:vl[t]}function bl(e){let t=e.replace(/-/g," ").trim().split(/\s+/).filter(c=>c.length>0);if(t.length===0)return"starter ping";let n=t[0].toLowerCase(),r=0;for(;t[r]?.toLowerCase()==="starter";)r+=1;let i=t[r]?.toLowerCase(),o=r>0&&(r===t.length||i!==void 0&&To.has(i));return`${(To.has(n)||o?["starter",...t]:t).join(" ")} ping`}function Fo(e){let t=e,n=`${e}s`,r=e.replace(/-/g,""),i=r===t?[]:[r],o=`${e.replace(/-/g,"_")}_owner`,a="reviewing";return[` name: ${JSON.stringify(e)},`,` title: ${JSON.stringify(`${e} archetype`)},`,' summary: "Starter project profile. Replace these dimensions with your own archetype.",'," // Item types the profile upserts into the project schema when applied."," types: ["," {",` name: ${JSON.stringify(t)},`,` folder: ${JSON.stringify(n)},`,` aliases: ${JSON.stringify(i)},`,` description: ${JSON.stringify(`A ${e} work item that flows to done.`)},`," },"," ],"," // Custom statuses upserted into the project status set."," statuses: ["," {",` id: ${JSON.stringify(a)},`,' roles: ["active"],',' aliases: ["in-review"],',' description: "Work is implementation-complete and awaiting review.",'," },"," ],"," // Custom item-metadata fields the archetype tracks."," fields: ["," {",` key: ${JSON.stringify(o)},`,' type: "string",',' commands: ["create", "update", "list"],',' description: "Stakeholder accountable for the item.",'," },"," ],"," // Per-type workflow transition allow-list staged into settings."," workflows: ["," {",` type: ${JSON.stringify(t)},`," allowed_transitions: [",' ["open", "in_progress"],',` ["in_progress", ${JSON.stringify(a)}],`,` [${JSON.stringify(a)}, "in_progress"],`,` [${JSON.stringify(a)}, "closed"],`,' ["in_progress", "blocked"],',' ["blocked", "in_progress"],'," ],"," },"," ],"," // Nested-settings knobs staged when the profile is applied."," config: [",' { key: "search_provider", value: "bm25", summary: "Offline BM25 lexical search needs no embedding service." },',' { key: "search_max_results", value: "20", summary: "Result cap tuned for quick triage." },'," ],"," // Create templates staged into <pmRoot>/templates."," templates: ["," {",` name: ${JSON.stringify(e)},`," options: {",` type: ${JSON.stringify(t)},`,' priority: "2",',` tags: ${JSON.stringify(e)},`,' acceptanceCriteria: "Item delivers the stated outcome with tests and docs updated.",',' body: "## Context\\n\\n## Acceptance\\n- [ ] \\n",'," },"," },"," ],"," // Advisory package recommendations (never auto-installed)."," packages: [",' { spec: "templates", reason: "Reusable create templates for recurring item shapes." },'," ],"]}function Sl(e,t,n){let r=`${e}-search`,i=`${e}-vector`,o=`${e.replace(/-/g," ")} items`,a=[" api.registerCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",'," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,",' message: "Starter extension scaffold is active.",'," }),"," });"];if(n==="commands")return a;if(n==="search")return[...a,""," // Search providers let packages customize how pm ranks and retrieves"," // project context. This starter is deterministic and dependency-free:"," // replace the scoring with your domain retrieval, embedding, or rerank"," // logic as the package grows."," api.registerSearchProvider({",` name: ${JSON.stringify(r)},`," query: async (context) => {"," const needle = context.query.toLowerCase();"," const hits = context.documents"," .filter((document) => {",' const title = String(document.metadata.title ?? "").toLowerCase();'," return title.includes(needle);"," })"," .map((document) => ({"," id: document.metadata.id,"," score: 1,",' matched_fields: ["title"],'," }));"," return { hits };"," },"," embed: async (context) => [context.input.length],"," });",""," // Vector-store adapters let packages own semantic index storage. This"," // starter returns a stable in-memory hit so generated tests can exercise"," // the adapter without external services."," api.registerVectorStoreAdapter({",` name: ${JSON.stringify(i)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),"," });"];if(n==="schema"){let s=e,c=`${e}s`,d=e.replace(/-/g,""),l=d===s?[]:[d],p=`${e.replace(/-/g,"_")}_note`,u=`${e}-0001-init`;return[...a,""," // Schema registrations let a package model its own project domain \u2014 the",' // heart of "project management = context management". Item types and fields'," // are GLOBAL contributions: built-in commands like `pm create <type>` and"," // `pm list --type <type>` must see them, so this package declares no"," // `activation.commands` and pm activates it conservatively for every command."," // The `schema` capability in manifest.json grants all three registrations."," api.registerItemFields(["," {",` name: ${JSON.stringify(p)},`,' type: "string",'," optional: true,"," },"," ]);",""," api.registerItemTypes(["," {",` name: ${JSON.stringify(s)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(c)},`,` aliases: ${JSON.stringify(l)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],"," },"," ]);",""," // Migrations let a package evolve stored items as its schema changes. pm"," // runs each migration ONCE through the preflight gate (not once per item),"," // passing a context that identifies the migration itself: `context.id` is"," // the migration id (not an item id), alongside `context.pm_root` \u2014 iterate"," // the corpus yourself from there. This starter is a deterministic no-op so"," // package tests can invoke it without touching the corpus; replace the body"," // with your real rewrite."," api.registerMigration({",` id: ${JSON.stringify(u)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),"," });"]}return n==="profile"?[...a,""," // A project profile is the broadest customization primitive pm has: one"," // declarative bundle of item types, custom statuses, fields, a per-type"," // workflow, config knobs, create templates, and package recommendations. Once"," // this package is installed the profile resolves by name through `pm profile"," // list`, `pm profile show`, and `pm profile apply`, which stages every dimension"," // idempotently like a core archetype. A profile registration is a schema+config"," // bundle, so the `schema` capability in manifest.json grants it."," api.registerProfile({",...Fo(e).map(s=>` ${s}`)," });"]:n==="importers"?[...a,""," // Importers/exporters are the bridge between pm's context graph and"," // another project-management system. Keep the starter deterministic so"," // package tests can run without touching the network or filesystem; replace"," // these payloads with your adapter's real mapping as the package grows."," api.registerImporter(",` ${JSON.stringify(o)},`," async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${o} 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(o)},`," async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${o} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," },"," );"]:n==="renderers"?[...a,""," // Renderer overrides customize how pm serializes a command's structured",' // result for an output format ("toon" or "json"). Host-enforced ownership'," // prevents unrelated commands from reaching this callback."," // The `renderers` capability in manifest.json grants the registration.",' api.registerRenderer("toon", (context) => {',` return ${JSON.stringify(`${e}: `)} + JSON.stringify(context.result);`,` }, { commands: [${JSON.stringify(t)}] });`]:n==="parser"?[" api.registerCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",'," flags: ["," {",' long: "--shout",',' value_type: "boolean",',' description: "Deprecated alias for --upper; the parser override rewrites it.",'," },"," {",' long: "--upper",',' value_type: "boolean",',' description: "Echo the canonical flag the parser override produces.",'," },"," ],"," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,"," // Surfaces the normalized option so `--shout`/`--upper` is observable."," upper: context.options.upper === true,",' message: "Starter extension scaffold is active.",'," }),"," });",""," // Parser overrides preprocess a command's parsed options BEFORE its handler"," // runs, returning a delta \u2014 only the keys you set are merged over the parsed"," // input. This override is scoped to THIS package's own command. Here it"," // rewrites the deprecated `--shout` boolean alias to the canonical `--upper`"," // flag; replace it with your command's real normalization. The `parser`"," // capability in manifest.json grants the registration.",` api.registerParser(${JSON.stringify(t)}, (context) => {`," const options = { ...context.options };"," if (options.shout === true) {"," options.upper = true;"," }"," delete options.shout;"," return { options };"," });"]:n==="preflight"?[...a,""," // Preflight overrides adjust pm's pre-run gate decision (extension"," // migrations + item-format checks) for the commands it owns. Disjoint"," // packages compose; overlapping or legacy global ownership is diagnosed."," // Return a delta of the keys you want to change"," // (enforce_item_format_gate, run_preflight_item_format_sync,"," // run_extension_migrations, enforce_mandatory_migration_gate); returning"," // context.decision unchanged is a safe no-op so installing the package does"," // not alter gate behavior \u2014 replace it with your policy, e.g."," // `{ run_extension_migrations: false }`. The `preflight` capability in"," // manifest.json grants the registration."," api.registerPreflight({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,"," });"]:n==="services"?[...a,""," // Service overrides replace a built-in pm service. The `output_format`"," // service renders a command's structured result; returning the payload"," // unchanged passes through to pm's default formatting. This override scopes"," // itself to THIS package's own command and passes every other command"," // through, so it never disrupts unrelated output. The `services` capability"," // in manifest.json grants the registration.",' api.registerService("output_format", (context) => {',` if (context.command !== ${JSON.stringify(t)}) {`," return { handled: false };"," }",` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`," });"]:[...a,""," // after_command hooks fire once pm finishes a command, receiving the items"," // it mutated. This is the natural place to react to every change - sync to"," // an external system, emit telemetry, or refresh derived context",' // ("project management = context management"). This starter is a documented'," // no-op on the success path; replace the body with your own reaction."," api.hooks.afterCommand((context) => {"," if (!context.ok) {"," return;"," }"," // `context.affected` lists the items pm mutated (id, status,"," // changed_fields). React here, e.g.:"," // for (const item of context.affected ?? []) { /* ...item.id... */ }"," });"]}function El(e,t,n){let r=n==="hooks",i=n==="search",o=n==="importers",a=n==="schema",s=n==="profile",c=n==="renderers",d=n==="parser",l=n==="preflight",p=n==="services",u=gl[n],_=e,g=`${e}s`,w=`${e.replace(/-/g,"_")}_note`,f=`${e}-0001-init`,y=[" assertExtensionDeactivated,"," createExtensionTestHarness,"],v=r?[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {"," // assertHook throws unless an after_command hook is registered, so"," // reaching the next line already proves the hook is wired."," ext.assertHook({",' kind: "after_command",',` extensionName: ${JSON.stringify(e)},`," });"," // runHook fires the hook through pm's real runner with a synthetic"," // context and returns the warnings it produced; a clean hook returns none."," // Replace the context/assertions as your hook grows."," const warnings = await ext.runHook({",' kind: "after_command",'," context: {",` command: ${JSON.stringify(t)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});",""]:[],x=i?Bn(e,t,"search",u):[],S=o?Bn(e,t,"importers",u):[],L=a?[`test(${JSON.stringify(`${e} registers and runs its custom schema`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {",...Io(Po({extensionName:e,itemTypeName:_,itemTypeFolder:g,fieldName:w,migrationId:f,includeMigrationReplacementHint:!0})," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});",""]:[],F=s?[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {",...Io(Ro(e)," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});",""]:[],j=c?[`test(${JSON.stringify(`${e} registers and invokes its renderer override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {"," // assertRendererOverride throws unless a renderer is registered for the"," // format, so reaching the next line already proves the wiring.",` const override = ext.assertRendererOverride({ name: "toon", extensionName: ${JSON.stringify(e)} });`,' assert.equal(override.format, "toon");',""," // runRendererOverride renders through pm's real runner. The override"," // customizes only THIS package's command output and returns a string the"," // host uses verbatim. Replace the assertions as it grows."," const rendered = await ext.runRendererOverride({",' format: "toon",',` command: ${JSON.stringify(t)},`," result: { ok: true },"," });"," assert.equal(rendered.overridden, true);",` assert.equal(rendered.rendered, ${JSON.stringify(`${e}: `)} + JSON.stringify({ ok: true }));`,""," // Output for any other command passes through to pm's default renderer."," const passthrough = await ext.runRendererOverride({",' format: "toon",',' command: "list",'," result: { ok: true },"," });"," assert.equal(passthrough.overridden, false);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});",""]:[],E=d?[`test(${JSON.stringify(`${e} rewrites command options via its parser override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {"," // assertParserOverride throws unless a parser is registered for the"," // command, so reaching the next line already proves the wiring.",` ext.assertParserOverride({ name: ${JSON.stringify(t)}, extensionName: ${JSON.stringify(e)} });`,""," // runParserOverride runs the override through pm's real parser runner and"," // returns the rewritten context. The starter rewrites the deprecated"," // `shout` alias to the canonical `upper` flag."," const result = await ext.runParserOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: { shout: true },"," global: {},",' pm_root: "",'," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.context.options, { upper: true });",""," // End to end: feed the rewritten options into the command handler to"," // prove `pm <command> --shout` surfaces the normalized `upper` flag in"," // the result.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)}, options: result.context.options });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`," upper: true,",' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});",""]:[],J=l?[`test(${JSON.stringify(`${e} returns a preflight gate decision via its override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {"," // assertPreflightOverride throws unless a preflight override is"," // registered, so reaching the next line already proves the wiring.",` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(e)} });`,""," // runPreflightOverride runs the override through pm's real runner with a"," // synthetic gate decision. The starter echoes the decision unchanged;"," // replace the values/assertions with your real policy."," const decision = {"," enforce_item_format_gate: true,"," run_preflight_item_format_sync: false,"," run_extension_migrations: true,"," enforce_mandatory_migration_gate: false,"," };"," const result = await ext.runPreflightOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: {},"," global: {},",' pm_root: "",'," decision,"," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.decision, decision);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});",""]:[],it=p?[`test(${JSON.stringify(`${e} customizes command output via its service override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {"," // assertServiceOverride throws unless a service override is registered"," // for the service, so reaching the next line proves the wiring.",` ext.assertServiceOverride({ name: "output_format", extensionName: ${JSON.stringify(e)} });`,""," // runServiceOverride runs the override through pm's real service runner."," // The override customizes only THIS package's command output (handled),"," // passing every other command through (not handled)."," const handled = await ext.runServiceOverride({",' service: "output_format",',` command: ${JSON.stringify(t)},`," payload: { ok: true },"," });"," assert.equal(handled.handled, true);",` assert.deepEqual(handled.result, { rendered_by: ${JSON.stringify(e)}, payload: { ok: true } });`,""," // Output for any other command passes through to pm's default formatter."," const passthrough = await ext.runServiceOverride({",' service: "output_format",',' command: "list",'," payload: { ok: true },"," });"," assert.equal(passthrough.handled, false);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});",""]:[];return['import assert from "node:assert/strict";','import { test } from "node:test";',"import {",...y,'} from "@unbrained/pm-cli/sdk/testing";',...i?['import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";']:[],'import extension from "./index.ts";',"",...Co,`test(${JSON.stringify(`${e} registers its starter command`)}, async () => {`," // `capabilities` mirrors manifest.json so the in-memory activation grants"," // the capabilities the entrypoint relies on."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," let deactivated = false;"," try {"," // assertCommandContract is bound to the right activation registry and throws"," // if the command is not registered, so reaching here already proves the"," // wiring; assert on the returned definition to inspect metadata."," const registered = ext.assertCommandContract({",` name: ${JSON.stringify(t)},`,` extensionName: ${JSON.stringify(e)},`," });",' assert.equal(typeof registered.command.description, "string");',""," // runCommand invokes the handler through pm's real dispatch engine, so this"," // asserts behavior - not just that the command is wired. Replace these"," // assertions as you flesh out your command."," const invocation = await ext.runCommand({",` command: ${JSON.stringify(t)},`," });"," assert.equal(invocation.handled, true);"," // The handler result is typed `unknown`, so deep-equality on the whole"," // structured payload keeps the assertion type-safe without a cast."," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`,...d?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});","",...v,...x,...S,...L,...F,...j,...E,...J,...it,`test(${JSON.stringify(`${e} tears down cleanly via deactivate`)}, async () => {`," // createExtensionTestHarness binds teardown to the same name/layer used for"," // activation, so this proves your `deactivate` hook runs without throwing."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${u},`," });"," const teardown = await ext.deactivate();"," // assertExtensionDeactivated throws unless exactly one extension tore down"," // with no failures, so reaching the next line already proves teardown ran."," assertExtensionDeactivated(teardown);"," assert.equal(teardown.deactivated, 1);","});",""].join(`
|
|
15
|
+
`)}function $l(e,t,n){if(n==="schema"||n==="profile")return[];if(n==="importers"){let r=`${e.replace(/-/g," ")} items`;return[t,`${r} import`,`${r} export`]}return[t]}var Al={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"},Tl={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 Il(e,t,n){let r=n==="parser";return["// The starter command, authored with the `defineCommand` builder so its literal","// name is preserved and the handler `context` is inferred. Exporting it lets you","// unit-test the definition in isolation, apart from the blueprint.","export const pingCommand = defineCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",',...r?[" flags: ["," {",' long: "--shout",',' value_type: "boolean",',' description: "Deprecated alias for --upper; the parser override rewrites it.",'," },"," {",' long: "--upper",',' value_type: "boolean",',' description: "Echo the canonical flag the parser override produces.",'," },"," ],"]:[]," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,",...r?[" upper: context.options.upper === true,"]:[],' message: "Starter extension scaffold is active.",'," }),","});"]}function Ol(e,t,n){let r=[],i=[...Il(e,t,n)],o=[" commands: [pingCommand],"],a=`${e}-search`,s=`${e}-vector`,c=`${e.replace(/-/g," ")} items`,d=e,l=`${e}s`,p=e.replace(/-/g,""),u=p===d?[]:[p],_=`${e.replace(/-/g,"_")}_note`,g=`${e}-0001-init`;switch(n){case"commands":break;case"hooks":r.push("defineAfterCommandHook"),i.push("","// after_command hooks fire once pm finishes a command, receiving the items it","// mutated. React here - sync to an external system, emit telemetry, or refresh",'// derived context ("project management = context management"). This starter is a',"// documented no-op on the success path; replace the body with your own reaction.","export const afterCommandHook = defineAfterCommandHook((context) => {"," if (!context.ok) {"," return;"," }"," // `context.affected` lists the items pm mutated (id, status, changed_fields):"," // for (const item of context.affected ?? []) { /* ...item.id... */ }","});"),o.push(" hooks: { afterCommand: [afterCommandHook] },");break;case"search":r.push("defineSearchProvider","defineVectorStoreAdapter"),i.push("","// Search providers let packages customize how pm ranks and retrieves project","// context. This starter is deterministic and dependency-free: replace the scoring","// with your domain retrieval, embedding, or rerank logic as the package grows.","export const searchProvider = defineSearchProvider({",` name: ${JSON.stringify(a)},`," query: async (context) => {"," const needle = context.query.toLowerCase();"," const hits = context.documents"," .filter((document) => {",' const title = String(document.metadata.title ?? "").toLowerCase();'," return title.includes(needle);"," })"," .map((document) => ({"," id: document.metadata.id,"," score: 1,",' matched_fields: ["title"],'," }));"," return { hits };"," },"," embed: async (context) => [context.input.length],","});","","// Vector-store adapters let packages own semantic index storage. This starter","// returns a stable in-memory hit so generated tests can exercise the adapter","// without external services.","export const vectorStoreAdapter = defineVectorStoreAdapter({",` name: ${JSON.stringify(s)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),","});"),o.push(" searchProviders: [searchProvider],"," vectorStoreAdapters: [vectorStoreAdapter],");break;case"importers":r.push("defineExporter","defineImporter"),i.push("","// Importers/exporters are the bridge between pm's context graph and another","// project-management system. Keep the starter deterministic so package tests can","// run without touching the network or filesystem; replace these payloads with","// your adapter's real mapping as the package grows.","export const importer = defineImporter(async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,","}));","","export const exporter = defineExporter(async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,","}));"),o.push(" importers: ["," {",` name: ${JSON.stringify(c)},`," importer,"," options: {",` action: ${JSON.stringify(`${c} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," },"," },"," ],"," exporters: ["," {",` name: ${JSON.stringify(c)},`," exporter,"," options: {",` action: ${JSON.stringify(`${c} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," },"," },"," ],");break;case"schema":r.push("defineItemField","defineItemType","defineMigration"),i.push("","// Schema registrations let a package model its own project domain - the heart of",'// "project management = context management". Item types and fields are GLOBAL',"// contributions, so this package declares no `activation.commands` and pm","// activates it conservatively for every command.","export const noteField = defineItemField({",` name: ${JSON.stringify(_)},`,' type: "string",'," optional: true,","});","","export const itemType = defineItemType({",` name: ${JSON.stringify(d)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(l)},`,` aliases: ${JSON.stringify(u)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],","});","","// Migrations let a package evolve stored items as its schema changes. pm runs each","// migration ONCE through the preflight gate (not once per item), passing a context","// that identifies the migration itself: `context.id` is the migration id (not an","// item id), alongside `context.pm_root`. This starter is a deterministic no-op so","// package tests can invoke it without touching the corpus; replace the body with","// your real rewrite.","export const initMigration = defineMigration({",` id: ${JSON.stringify(g)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),o.push(" itemTypes: [itemType],"," itemFields: [noteField],"," migrations: [initMigration],");break;case"profile":r.push("defineProjectProfile"),i.push("","// A project profile is the broadest customization primitive pm has: one","// declarative bundle of item types, custom statuses, fields, a per-type workflow,","// config knobs, create templates, and package recommendations. Once installed it","// resolves by name through `pm profile list/show/apply`, which stages every","// dimension idempotently like a core archetype. A profile registration is a","// schema+config bundle, so the `schema` capability grants it.","export const starterProfile = defineProjectProfile({",...Fo(e),"});"),o.push(" profiles: [starterProfile],");break;case"renderers":r.push("defineRendererOverride"),i.push("","// Host-enforced command ownership prevents unrelated output from reaching","// this renderer callback; return a string to take over serialization.","export const toonRenderer = defineRendererOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => {",` return ${JSON.stringify(`${e}: `)} + JSON.stringify(context.result);`," },","});"),o.push(" renderers: { toon: toonRenderer },");break;case"parser":r.push("defineParserOverride"),i.push("","// Parser overrides preprocess a command's parsed options BEFORE its handler runs,","// returning a delta - only the keys you set are merged over the parsed input. This","// override is scoped to THIS package's own command; here it rewrites the deprecated","// `--shout` boolean alias to the canonical `--upper` flag.","export const pingParser = defineParserOverride((context) => {"," const options = { ...context.options };"," if (options.shout === true) {"," options.upper = true;"," }"," delete options.shout;"," return { options };","});"),o.push(` parsers: { ${JSON.stringify(t)}: pingParser },`);break;case"preflight":r.push("definePreflightOverride"),i.push("","// Preflight overrides adjust pm's pre-run gate decision (extension migrations +","// item-format checks) for the commands it owns. Scoped ownership composes with","// other packages; overlapping or legacy global ownership is diagnosed.","// Return a delta of the keys you want to change (enforce_item_format_gate,","// run_preflight_item_format_sync, run_extension_migrations,","// enforce_mandatory_migration_gate); returning context.decision unchanged is a","// safe no-op - replace it with your policy, e.g. { run_extension_migrations: false }.","export const preflightOverride = definePreflightOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,","});"),o.push(" preflights: [preflightOverride],");break;case"services":r.push("defineServiceOverride"),i.push("","// Service overrides replace a built-in pm service. The `output_format` service","// renders a command's structured result; returning the payload unchanged passes","// through to pm's default formatting. This override scopes itself to THIS","// package's own command and passes every other command through.","export const outputService = defineServiceOverride((context) => {",` if (context.command !== ${JSON.stringify(t)}) {`," return { handled: false };"," }",` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`,"});"),o.push(" services: { output_format: outputService },");break}return{builderImports:r,definitions:i,blueprintFields:o}}function Cl(e,t,n){let r=Ol(e,t,n);return[`import { ${["composeExtension","defineCommand","defineExtensionBlueprint",...r.builderImports].sort((o,a)=>o.localeCompare(a)).join(", ")} } from "@unbrained/pm-cli/sdk";`,"",...r.definitions,"","// Declarative authoring: describe WHAT the package registers as a blueprint and","// let `composeExtension` generate the `activate` that wires every surface in order,","// instead of hand-writing each `api.register*` call. `defineExtensionBlueprint`","// contract-checks the blueprint where it is authored. Keep `manifest.json`'s","// `capabilities` equal to the set this blueprint derives.","export const blueprint = defineExtensionBlueprint({",...r.blueprintFields," // `deactivate` is the teardown counterpart to the generated `activate`: pm runs"," // it on host shutdown/reload to release anything the package opened (timers,"," // connections, caches). This starter holds none, so it stays a no-op."," deactivate: () => {},","});","","// `composeExtension(blueprint)` is the package's default export \u2014 the runtime","// `ExtensionModule` pm loads. Guard the blueprint with `assertExtensionPreflight`","// in index.test.ts before publishing.","export default composeExtension(blueprint);",""].join(`
|
|
16
|
+
`)}function Bn(e,t,n,r){if(n==="commands")return[];let i=`${e}-search`,o=`${e}-vector`,a=`${e.replace(/-/g," ")} items`,s=e,c=`${e}s`,d=`${e.replace(/-/g,"_")}_note`,l=`${e}-0001-init`,p=[" const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${r},`," });"],u=_=>[...p," let deactivated = false;"," try {",..._.map(g=>g===""?g:` ${g}`)," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue];switch(n){case"hooks":return[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`,...u([" // assertHook throws unless an after_command hook is registered, so reaching the"," // next line already proves the hook is wired.",` ext.assertHook({ kind: "after_command", extensionName: ${JSON.stringify(e)} });`," // runHook fires the hook through pm's real runner with a synthetic context and"," // returns the warnings it produced; a clean hook returns none."," const warnings = await ext.runHook({",' kind: "after_command",'," context: {",` command: ${JSON.stringify(t)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"]),"});",""];case"search":return[`test(${JSON.stringify(`${e} registers and invokes search primitives`)}, async () => {`,...u([` ext.assertSearchProvider({ name: ${JSON.stringify(i)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertVectorStoreAdapter({ name: ${JSON.stringify(o)}, extensionName: ${JSON.stringify(e)} });`,""," // The starter provider reads only document title/id, so `settings` is a minimal"," // typed stub and `documents` carry just the fields it inspects."," const settings = {"," testing: {"," record_results_to_items: false,"," allow_untrusted_linked_tests: false,"," },"," } as PmSettings;"," const query = await ext.runSearchProvider({",` provider: ${JSON.stringify(i)},`,' operation: "query",'," context: {",' query: "sync",',' mode: "semantic",',' tokens: ["sync"],'," options: {},"," settings,"," documents: [",' { metadata: { id: "pm-1", title: "Sync external context" }, body: "" },',' { metadata: { id: "pm-2", title: "Unrelated task" }, body: "" },'," ] as ItemDocument[],"," },"," });",' assert.deepEqual(query, { hits: [{ id: "pm-1", score: 1, matched_fields: ["title"] }] });',""," const embedding = await ext.runSearchProvider({",` provider: ${JSON.stringify(i)},`,' operation: "embed",',' context: { input: "abc", settings, model: "starter-model" },'," });"," assert.deepEqual(embedding, [3]);",""," const vectorHits = await ext.runVectorStoreAdapter({",` adapter: ${JSON.stringify(o)},`,' operation: "query",'," context: { vector: [0.1, 0.2], limit: 2, settings },"," });",' assert.deepEqual(vectorHits, [{ id: "starter-vector-hit", score: 2 }]);']),"});",""];case"importers":return[`test(${JSON.stringify(`${e} registers and invokes import/export primitives`)}, async () => {`,...u([` ext.assertImporter({ name: ${JSON.stringify(a)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertExporter({ name: ${JSON.stringify(a)}, extensionName: ${JSON.stringify(e)} });`,""," const imported = await ext.runImporter({",` importer: ${JSON.stringify(a)},`,' options: { source: "tickets" },',' args: ["batch-1"],'," });"," assert.equal(imported.handled, true);",' assert.deepEqual(imported.result, { imported: 1, source: "tickets", args: ["batch-1"] });',""," const exported = await ext.runExporter({",` exporter: ${JSON.stringify(a)},`,' options: { destination: "archive" },',' args: ["done"],'," });"," assert.equal(exported.handled, true);",' assert.deepEqual(exported.result, { exported: true, destination: "archive", args: ["done"] });']),"});",""];case"schema":return[`test(${JSON.stringify(`${e} registers and runs its custom schema`)}, async () => {`,...u(Po({extensionName:e,itemTypeName:s,itemTypeFolder:c,fieldName:d,migrationId:l})),"});",""];case"profile":return[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`,...u(Ro(e)),"});",""];case"renderers":return[`test(${JSON.stringify(`${e} registers and invokes its renderer override`)}, async () => {`,...u([" // assertRendererOverride throws unless a renderer is registered for the format,"," // so reaching the next line already proves the wiring.",` const override = ext.assertRendererOverride({ name: "toon", extensionName: ${JSON.stringify(e)} });`,' assert.equal(override.format, "toon");',""," // runRendererOverride renders through pm's real runner. The override customizes"," // only THIS package's command output and returns a string the host uses verbatim."," const rendered = await ext.runRendererOverride({",' format: "toon",',` command: ${JSON.stringify(t)},`," result: { ok: true },"," });"," assert.equal(rendered.overridden, true);"," assert.equal(rendered.rendered, JSON.stringify({ ok: true }));",""," // Output for any other command passes through to pm's default renderer."," const passthrough = await ext.runRendererOverride({",' format: "toon",',' command: "list",'," result: { ok: true },"," });"," assert.equal(passthrough.overridden, false);"]),"});",""];case"parser":return[`test(${JSON.stringify(`${e} rewrites command options via its parser override`)}, async () => {`,...u([" // assertParserOverride throws unless a parser is registered for the command, so"," // reaching the next line already proves the wiring.",` ext.assertParserOverride({ name: ${JSON.stringify(t)}, extensionName: ${JSON.stringify(e)} });`,""," // runParserOverride runs the override through pm's real parser runner and returns"," // the rewritten context. The starter rewrites the deprecated `shout` alias to the"," // canonical `upper` flag."," const result = await ext.runParserOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: { shout: true },"," global: {},",' pm_root: "",'," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.context.options, { upper: true });",""," // End to end: feed the rewritten options into the command handler to prove"," // `pm <command> --shout` surfaces the normalized `upper` flag in the result.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)}, options: result.context.options });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`," upper: true,",' message: "Starter extension scaffold is active.",'," });"]),"});",""];case"preflight":return[`test(${JSON.stringify(`${e} returns a preflight gate decision via its override`)}, async () => {`,...u([" // assertPreflightOverride throws unless a preflight override is registered, so"," // reaching the next line already proves the wiring.",` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(e)} });`,""," // runPreflightOverride runs the override through pm's real runner with a synthetic"," // gate decision. The starter echoes the decision unchanged; replace the"," // values/assertions with your real policy."," const decision = {"," enforce_item_format_gate: true,"," run_preflight_item_format_sync: false,"," run_extension_migrations: true,"," enforce_mandatory_migration_gate: false,"," };"," const result = await ext.runPreflightOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: {},"," global: {},",' pm_root: "",'," decision,"," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.decision, decision);"]),"});",""];case"services":return[`test(${JSON.stringify(`${e} customizes command output via its service override`)}, async () => {`,...u([" // assertServiceOverride throws unless a service override is registered for the"," // service, so reaching the next line proves the wiring.",` ext.assertServiceOverride({ name: "output_format", extensionName: ${JSON.stringify(e)} });`,""," // runServiceOverride runs the override through pm's real service runner. The"," // override customizes only THIS package's command output (handled), passing every"," // other command through (not handled)."," const handled = await ext.runServiceOverride({",' service: "output_format",',` command: ${JSON.stringify(t)},`," payload: { ok: true },"," });"," assert.equal(handled.handled, true);",` assert.deepEqual(handled.result, { rendered_by: ${JSON.stringify(e)}, payload: { ok: true } });`,""," // Output for any other command passes through to pm's default formatter."," const passthrough = await ext.runServiceOverride({",' service: "output_format",',' command: "list",'," payload: { ok: true },"," });"," assert.equal(passthrough.handled, false);"]),"});",""]}}function Pl(e,t,n){let r=n==="parser",i=JSON.stringify([...No[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" };',"",...Co,`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(Me)},`," },",` target: { pmVersion: ${JSON.stringify(Me)} },`," });"," // Fail the starter suite whenever the checked-in manifest drifts from the"," // capabilities derived from the blueprint."," assertExtensionManifestMatchesBlueprint(manifest, blueprint);"," // The capability set is DERIVED from the blueprint, never hand-synced. Keep"," // manifest.json's `capabilities` equal to this list (set match, sorted).",` assert.deepEqual(report.capabilities, ${i});`,` assert.deepEqual(report.manifest?.capabilities, ${i});`,"});","",`test(${JSON.stringify(`${e} registers and runs its starter command`)}, async () => {`," // createExtensionTestHarness activates the composed module once and binds the"," // assert*/run*/deactivate helpers to the right activation sub-registry, so you"," // never thread activation.registrations vs activation.commands by hand."," // `capabilities` mirrors manifest.json so the in-memory activation grants what the"," // blueprint needs."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${i},`," });"," let deactivated = false;"," try {"," // assertCommandContract throws unless the command is registered, so reaching"," // the next line already proves the wiring; assert on the returned definition"," // to demonstrate inspecting registered metadata.",` const registered = ext.assertCommandContract({ name: ${JSON.stringify(t)} });`,' assert.equal(typeof registered.command.description, "string");',""," // runCommand invokes the handler through pm's real dispatch engine, so this"," // asserts behavior - not just that the command is wired. Replace these"," // assertions as you flesh out your command.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)} });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`,...r?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," // deactivate runs pm's real teardown engine over the module; exactly one"," // extension tears down with no failures."," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ue,"});","",...Bn(e,t,n,i)].join(`
|
|
17
|
+
`)}function Rl(e,t,n){let r=jo(n,"package"),i=Do(n,"package");return[`# ${e}`,"","Generated by `pm package init --declarative`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",r,`- \`index.ts\`: the TypeScript manifest entry \u2014 a \`defineExtensionBlueprint\` blueprint (${Al[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`.",Lo,"- `.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 ${Tl[n]}. Add more`," fields as the package grows.","- `composeExtension(blueprint)` is the default export \u2014 the runtime module pm"," loads. Its generated `activate` requires exactly the capabilities the blueprint"," derives, so `manifest.json`'s `capabilities` never drift.","","## Validate the Package","`npm install` pulls the peer SDK and TypeScript. `npm test` is the default","validation gate: it type-checks the package, then runs the colocated sample:","```bash","npm install","npm test","```","`index.test.ts` exercises both authoring capstones: `assertExtensionPreflight`","(the author-time lint + manifest synthesis + version-compatibility check over the","exported `blueprint`) and `createExtensionTestHarness` (the runtime fixture whose","`assert*`/`run*`/`deactivate` methods bind to the right activation sub-registry).","`npm run typecheck` is available when you only want the SDK contract check.","`npm run test:runtime` runs just `node --test`, which strips types on load and","executes `index.test.ts` directly against the `@unbrained/pm-cli/sdk/testing`","helpers - no compile step and no extra test runner required.",...i,"","## Compatibility Bounds","`manifest.json` cannot hold comments, so the version-compatibility fields are documented here:",`- \`manifest_version\` (integer): manifest schema generation. Leave at \`${Wn}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${Me}\`. 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(`
|
|
18
|
+
`)}function Nl(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 Ll(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 jl(e,t,n,r){let i=["export const pingCommand = defineCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",',...n==="parser"?[" flags: [",' { long: "--shout", value_type: "boolean", description: "Deprecated alias for --upper." },',' { long: "--upper", value_type: "boolean", description: "Canonical flag the parser produces." },'," ],"," run: (context) => ({ ok: true, command: context.command, upper: context.options.upper === true }),"]:[" run: (context) => ({ ok: true, command: context.command }),"],"});"];return n==="hooks"&&i.push("","export const afterCommandHook = defineAfterCommandHook((context) => {"," if (!context.ok) return;"," // React to context.affected here as your package grows.","});"),n==="search"&&i.push("","export const searchProvider = defineSearchProvider({",` name: ${JSON.stringify(r.searchProviderName)},`," query: async (context) => ({"," hits: context.documents",' .filter((document) => String(document.metadata.title ?? "").toLowerCase().includes(context.query.toLowerCase()))',' .map((document) => ({ id: document.metadata.id, score: 1, matched_fields: ["title"] })),'," }),"," embed: async (context) => [context.input.length],","});","","export const vectorStoreAdapter = defineVectorStoreAdapter({",` name: ${JSON.stringify(r.vectorAdapterName)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),","});"),n==="importers"&&i.push("","export const importer = defineImporter(async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,","}));","","export const exporter = defineExporter(async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,","}));"),n==="schema"&&i.push("",`export const noteField = defineItemField({ name: ${JSON.stringify(r.fieldName)}, type: "string", optional: true });`,"","export const itemType = defineItemType({",` name: ${JSON.stringify(r.itemTypeName)},`,` folder: ${JSON.stringify(r.itemTypeFolder)},`,` aliases: ${JSON.stringify(r.itemTypeAliases)},`," required_create_fields: [],","});","","export const initMigration = defineMigration({",` id: ${JSON.stringify(r.migrationId)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),n==="profile"&&i.push("","export const starterProfile = defineProjectProfile({",` name: ${JSON.stringify(e)},`,` title: ${JSON.stringify(`${e} archetype`)},`,' summary: "Starter project profile. Replace these dimensions with your own archetype.",'," types: [",` { name: ${JSON.stringify(r.itemTypeName)}, folder: ${JSON.stringify(r.itemTypeFolder)} },`," ],"," // ...plus statuses, fields, workflows, config, templates, and packages.","});"),n==="renderers"&&i.push("","export const toonRenderer = defineRendererOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => JSON.stringify(context.result),","});"),n==="parser"&&i.push("","export const pingParser = defineParserOverride((context) => {"," const options = { ...context.options };"," if (options.shout === true) options.upper = true;"," delete options.shout;"," return { options };","});"),n==="preflight"&&i.push("","// Return a delta of the gate-decision keys you want to change; returning","// context.decision unchanged is a safe no-op (e.g. { run_extension_migrations: false }).","export const preflightOverride = definePreflightOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,","});"),n==="services"&&i.push("","export const outputService = defineServiceOverride((context) => {",` if (context.command !== ${JSON.stringify(t)}) return { handled: false };`,` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`,"});"),i}function Dl(e,t,n){let r=[];return t==="renderers"&&r.push(' api.registerRenderer("toon", toonRenderer.run, toonRenderer);'),t==="parser"&&r.push(` api.registerParser(${JSON.stringify(e)}, pingParser);`),t==="preflight"&&r.push(" api.registerPreflight(preflightOverride);"),t==="services"&&r.push(' api.registerService("output_format", outputService);'),t==="hooks"&&r.push(" api.hooks.afterCommand(afterCommandHook);"),t==="search"&&r.push(" api.registerSearchProvider(searchProvider);"," api.registerVectorStoreAdapter(vectorStoreAdapter);"),t==="schema"&&r.push(" api.registerItemFields([noteField]);"," api.registerItemTypes([itemType]);"," api.registerMigration(initMigration);"),t==="profile"&&r.push(" api.registerProfile(starterProfile);"),t==="importers"&&r.push(` api.registerImporter(${JSON.stringify(n.adapterName)}, importer, {`,` action: ${JSON.stringify(`${n.adapterName} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," });",` api.registerExporter(${JSON.stringify(n.adapterName)}, exporter, {`,` action: ${JSON.stringify(`${n.adapterName} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," });"),r}function Fl(e,t,n,r="commands",i=!1){let o=`pm-${e}`,a=No[r],s=$l(e,t,r),c=`${JSON.stringify({name:e,version:"0.1.0",entry:"./index.ts",manifest_version:Wn,pm_min_version:Me,trusted:!0,sandbox_profile:"strict",permissions:{...ul},capabilities:a,...s.length>0?{activation:{commands:s}}:{}},null,2)}
|
|
19
|
+
`,d=['import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"","export function activate(api: ExtensionApi): void {",...Sl(e,t,r),"}","","// `deactivate` is the teardown counterpart to `activate`: pm runs it on host","// shutdown/reload (e.g. the MCP server between requests) to release anything","// `activate` opened - timers, connections, caches. This starter holds no such","// resources, so it stays a documented no-op; add cleanup here as you grow.","export function deactivate(): void {}","","export default {"," activate,"," deactivate,","};",""].join(`
|
|
20
|
+
`),l=`${JSON.stringify(hl,null,2)}
|
|
21
|
+
`,p=_l[r],u=jo(r,"package"),_=`${JSON.stringify({name:o,version:"0.1.0",private:!0,type:"module",keywords:["pm-package"],engines:{node:pl},scripts:{typecheck:"tsc --noEmit","test:runtime":"node --test",test:"npm run typecheck && npm run test:runtime"},peerDependencies:{"@unbrained/pm-cli":`>=${Me}`},devDependencies:{"@types/node":fl,typescript:ml},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)}
|
|
22
|
+
`,g=El(e,t,r),w=yl[r],f=["node_modules/","*.log","*.tsbuildinfo",""].join(`
|
|
23
|
+
`),y=Nl(e),x=["```ts",`import { ${Ll(r)} } from "@unbrained/pm-cli/sdk";`,'import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"",...jl(e,t,r,y),"","export function activate(api: ExtensionApi): void {"," api.registerCommand(pingCommand);",...Dl(t,r,y),"}","","export function deactivate(): void {}","","export default { activate, deactivate };","```"],S=[`# ${o}`,"","Generated by `pm package init` or `pm extension init`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",u,p,w,Lo,"- `.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:",...x,"The builders return their argument unchanged; runtime validation still lives","in `api.register*`, and behavior validation lives in `sdk/testing`.",...wl[r],...Do(r,"package"),"","## Compatibility Bounds",`- \`peerDependencies["@unbrained/pm-cli"]\` uses the stable range \`>=${Me}\`. 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 \`${Wn}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${Me}\`. 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(`
|
|
24
|
+
`);return{"package.json":_,"manifest.json":c,"index.ts":i?Cl(e,t,r):d,"index.test.ts":i?Pl(e,t,r):g,"tsconfig.json":l,".gitignore":f,"README.md":i?Rl(o,t,r):S}}async function Mo(e,t="extension",n="commands",r=!1){let i=n.trim().toLowerCase();if(!Oo.includes(i))throw new m(`Unknown scaffold capability "${n}". Supported capabilities: ${Oo.join(", ")}.`,h.USAGE);let o=i;if(r&&t!=="package")throw new m("--declarative scaffolds a package-mode blueprint starter (composeExtension is a runtime SDK import). Use `pm package init`, not `pm extension init`.",h.USAGE);let a=r?"declarative":"imperative",s=e.trim(),c=ht.resolve(process.cwd(),s),d=Jt(ht.basename(c)).replace(/^(?:pm-)+/u,""),l=bl(d),p=Fl(d,l,t,o,r),u=!1;if(await b(c)){if(!(await ft.stat(c)).isDirectory())throw new m(`Scaffold target "${c}" exists and is not a directory.`,h.CONFLICT)}else await ft.mkdir(c,{recursive:!0}),u=!0;for(let[g,w]of Object.entries(p)){let f=ht.join(c,g);if(!await b(f))continue;if(await ft.readFile(f,"utf8")!==w)throw new m(`Scaffold file "${g}" already exists with different content in "${c}". Choose a new target path or remove conflicting files.`,h.CONFLICT)}let _=[];for(let[g,w]of Object.entries(p)){let f=ht.join(c,g);if(await b(f)){_.push({path:g,status:"unchanged"});continue}await ft.mkdir(ht.dirname(f),{recursive:!0}),await ft.writeFile(f,w,"utf8"),_.push({path:g,status:"created"})}return{extension_name:d,package_name:`pm-${d}`,command_name:l,invocation_command:`pm ${l}`,capability:o,style:a,target_path:c,created_directory:u,files:_}}var Uo=[["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 Hn(e){return"#".repeat(e)}function Go(e){if(!e.includes("`"))return`\`${e}\``;let t=0,n=0;for(let o of e)n=o==="`"?n+1:0,t=Math.max(t,n);let r="`".repeat(t+1),i=e.startsWith("`")||e.endsWith("`")?" ":"";return`${r}${i}${e}${i}${r}`}function Ml(e){return e.length===0?"Capabilities: _none registered_":`Capabilities: ${e.map(Go).join(", ")}`}function Ul(e,t,n){let r=[`${Hn(t)} ${e}`,""];return n.length===0?(r.push("_None._",""),r):(r.push(...n.map(i=>`- ${Go(i)}`),""),r)}function Gl(e,t,n){return e===0&&!n?[]:[`${Hn(t)} Preflight overrides`,"",e>0?`- ${e} registered (this surface carries no per-entry identifier)`:"_None._",""]}function Kn(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 r=Math.min(n+1,6),i=t.includeEmpty===!0,o=t.title??"Extension surfaces",a=[`${Hn(n)} ${o}`,""];(i||e.capabilities.length>0)&&a.push(Ml(e.capabilities),"");for(let[c,d]of Uo){let l=e[c]??[];l.length===0&&!i||a.push(...Ul(d,r,l))}return a.push(...Gl(e.preflight_overrides,r,i)),!(e.preflight_overrides>0||Uo.some(([c])=>(e[c]?.length??0)>0))&&!i&&a.push("_This extension registers no surfaces._",""),`${a.join(`
|
|
25
|
+
`).trimEnd()}
|
|
26
|
+
`}function zo(e,t){return`${e}:${k(t)}`}function zl(e,t){let n=[];for(let[r,i]of[["handler",e.commands.handlers],["override",e.commands.overrides]]){let o=new Map;for(let a of i){let s=o.get(a.command)??[];o.set(a.command,[...s,a])}for(let[a,s]of o){if(t!==null&&!s.some(d=>t.has(k(d.name))))continue;let c=s.at(-1);n.push({command:a,surface:r,policy:"last_activated_wins",collision:s.length>1,claimants:s.map(d=>({name:d.name,layer:d.layer,winner:d===c}))})}}return n.sort((r,i)=>r.command.localeCompare(i.command)||r.surface.localeCompare(i.surface))}function Jo(e,t,n){let r=new Set(n.failed.map(d=>zo(d.layer,d.name))),i=[...t.loaded.map(d=>({name:d.name,layer:d.layer,version:d.version,activation_status:r.has(zo(d.layer,d.name))?"failed":"ok",surfaces:We(n,{extensionName:d.name})})),...t.failed.map(d=>({name:d.name,layer:d.layer,version:"unknown",activation_status:"not_loaded",surfaces:We(n,{extensionName:d.name})}))].sort((d,l)=>d.name.localeCompare(l.name)||d.layer.localeCompare(l.layer)),o=typeof e=="string"?k(e):null,a=o===null?null:new Set(t.loaded.filter(d=>k(d.name)===o||typeof d.source_package=="string"&&k(d.source_package)===o||(d.source_aliases??[]).some(l=>k(l)===o)).map(d=>k(d.name)).concat(o)),s=a===null?i:i.filter(d=>a.has(k(d.name))),c=a===null?{}:{extensionNames:[...a]};return{target:typeof e=="string"?e.trim():null,total:s.length,extensions:s,union:We(n,c),command_ownership:zl(n,a)}}var Jl={ok:"loaded",failed:"activation failed",not_loaded:"not loaded"};function t_(e,t){let r=[`# ${`${t[0].toUpperCase()}${t.slice(1)}`} surface reference`,""];if(r.push(e.target===null?`Scope: all loaded ${t}s`:`Scope: \`${e.target}\``),r.push(`Described: ${e.total} ${t}${e.total===1?"":"s"}`,""),(e.command_ownership?.length??0)>0){r.push("## Command ownership","");for(let i of e.command_ownership){let o=i.claimants.find(s=>s.winner),a=i.claimants.map(s=>`${s.layer}:${s.name}`).join(", ");r.push(`- \`${i.command}\` (${i.surface}): ${o.layer}:${o.name}; policy=${i.policy}; collision=${String(i.collision)}; claimants=${a}`)}r.push("")}if(e.extensions.length===0)return r.push(`_No ${t}s are loaded._`,""),`${r.join(`
|
|
27
|
+
`).trimEnd()}
|
|
28
|
+
`;for(let i of e.extensions){let o=`${i.name} (${i.layer} v${i.version}, ${Jl[i.activation_status]})`;r.push(Kn(i.surfaces,{title:o,headingLevel:2}))}return e.extensions.length>1&&r.push(Kn(e.union,{title:`Union across all described ${t}s`,headingLevel:2})),`${r.join(`
|
|
29
|
+
`).trimEnd()}
|
|
30
|
+
`}import Xt from"node:fs/promises";import Vt from"node:path";import qo from"node:path";function gt(e,t,n,r){let i=qo.relative(e,n);if(i!==""&&!K(e,n)||n===t||K(t,n))return!1;let o=i.split(qo.sep);return o.includes(".git")?!1:r?!o.some(a=>a===".agents"||a==="node_modules"||a.startsWith(".pm-extension-install-backup-")):!0}import{randomUUID as ql}from"node:crypto";import D from"node:fs/promises";import Wl from"node:os";import N from"node:path";var Wo=3,Bl=120,Bo=250,Hl=12e4,Kl=new Set(["EEXIST","ENOTEMPTY","ENOENT"]),Ho=e=>typeof e=="object"&&e!==null&&"code"in e?e.code:void 0,Ko=e=>Kl.has(String(Ho(e))),Kt=(e,t)=>Ho(e)===t,Vo=e=>new Promise(t=>{setTimeout(t,e)}),Xo=async e=>{let t=N.join(e,"package.json");await b(t)||await D.writeFile(t,`${JSON.stringify({type:"module"},null,2)}
|
|
31
|
+
`,"utf8")},Yo=async e=>{let t=xe(import.meta.url,["../../.."]),n=N.join(e,"node_modules","@unbrained"),r=N.join(n,"pm-cli");await D.mkdir(n,{recursive:!0}),await D.rm(r,{recursive:!0,force:!0}),await D.symlink(t,r,process.platform==="win32"?"junction":"dir")},_t=async e=>{let t=N.resolve(e),n=N.dirname(t),r=N.parse(n).root,i=await D.realpath(r).catch(()=>r),o=N.relative(r,n),a=o===""?[]:o.split(N.sep);for(let[s,c]of a.entries()){let d=N.join(i,c);try{i=await D.realpath(d)}catch{i=N.join(i,...a.slice(s));break}}return N.join(i,N.basename(t))},Zo=async(e,t,n,r=Wl.tmpdir())=>Re("extension_install_copy",async()=>{let i=N.resolve(e),o=await D.realpath(i).catch(()=>i),a=await _t(t);if(o===a)return;if(!K(o,a)){await n(o,t,{recursive:!0,force:!0,filter:p=>gt(o,a,N.resolve(p),!1)});return}let s=await D.realpath(N.resolve(r)).catch(()=>_t(r)),c=K(o,s)?N.dirname(o):s;if(K(o,c))throw new m(`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 d=await D.mkdtemp(N.join(c,"pm-extension-copy-")),l=N.join(d,"extension");try{await n(o,l,{recursive:!0,force:!0,filter:p=>gt(o,a,N.resolve(p),!0)}),await n(l,t,{recursive:!0,force:!0})}finally{await D.rm(d,{recursive:!0,force:!0})}}),Qo=async(e,t,n=D.cp)=>{for(let r=1;r<=Wo;r+=1)try{await Re("extension_install_copy",async()=>{await D.rm(t,{recursive:!0,force:!0}),await Zo(e,t,n)});return}catch(i){if(!Ko(i)||r===Wo)throw i;await Vo(Bo)}},Vn=async e=>{let t;try{t=await D.readFile(N.join(e,"owner.json"),"utf8")}catch(i){if(!Tt(i))throw i;return null}let n;try{n=JSON.parse(t)}catch{return null}if(typeof n!="object"||n===null||!("token"in n))return null;let r=n.token;return typeof r=="string"&&r.length>0?r:null},ea=async(e,t)=>await Vn(e)!==t?!1:(await D.rm(e,{recursive:!0,force:!0}),!0),Vl=async(e,t)=>{let n;try{n=await D.stat(e)}catch{return!1}if(Date.now()-n.mtimeMs<=t)return!1;let r=await Vn(e);return r===null?(await D.rm(e,{recursive:!0,force:!0}),!0):ea(e,r)},Xl=(e,t,n)=>{let r=Promise.resolve(),i=setInterval(()=>{r=r.then(async()=>{if(await Vn(e)!==t)return;let o=new Date;await D.utimes(e,o,o)}).catch(()=>{})},n);return i.unref(),async()=>{clearInterval(i),await r}},Yl=async(e,t)=>{await D.mkdir(e);try{await D.writeFile(N.join(e,"owner.json"),`${JSON.stringify(t,null,2)}
|
|
32
|
+
`,"utf8")}catch(n){throw await D.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}},Zl=async(e,t,n,r,i)=>{for(let o=1;o<=n;o+=1)try{return await Yl(e,t),!0}catch(a){if(!Kt(a,"EEXIST"))throw a;await Vl(e,i)?o-=1:await Vo(r)}return!1},Xn=async(e,t,n,r)=>Re("extension_install",async()=>{let i=N.join(e,"runtime","extension-install-locks"),o=N.join(i,"scope.lock");await D.mkdir(i,{recursive:!0});let{attempts:a=Bl,delay_ms:s=Bo,stale_ms:c=Hl,heartbeat_ms:d}=r??{};if(![a,s,c,d].filter(v=>v!==void 0).every(Number.isFinite))throw new m("Extension install lock timings must be finite numbers.",h.USAGE);let l=Math.max(1,Math.floor(a)),p=Math.max(0,Math.floor(s)),u=Math.floor(c),_=Math.floor(d??u/3);if(u<=0||_<=0||_>=u)throw new m("Extension install lock timings require stale_ms > 0 and 0 < heartbeat_ms < stale_ms.",h.USAGE);let g={pid:process.pid,token:ql(),created_at:T(),destination:t};if(!await Zl(o,g,l,p,u))throw new m(`Timed out waiting for extension install lock for "${t}".`,h.CONFLICT);let f=Xl(o,g.token,_),y=!1;try{let v=await n();return y=!0,v}finally{await f(),await ea(o,g.token).catch(v=>{if(y)throw v})}});var Ql=new Set(["node_modules",".git","dist","build","coverage"]);async function ta(e,t,n,r){let i=e.source.kind==="local"?await Xt.stat(e.source.absolute_path):void 0,o=e.source.kind==="local"?i.isDirectory()?"directory":"archive":e.source.kind,a=await ep(e.directory,t,r),s={source_mode:o,...o==="archive"?{archive_bytes:i.size}:{},copy:a},c=e.source_root??e.directory;if(o==="directory"&&(!a.complete||a.development_entries>0||a.bytes>=16*1024*1024)&&await b(Vt.join(c,"package.json"))&&(s.packed_alternative={cwd:c,pack:{command:"npm",args:["pack","--ignore-scripts","--json"]},install:{command:"pm",args:["package","install","<archive-filename>",`--${n}`]},archive_argument:"pack_result[0].filename"}),o==="directory"&&!a.complete){let d=a.stop_reason==="entry_limit"?`${a.max_entries} entries`:`${a.max_depth} directory levels`;throw new m(`Local extension source scan stopped at ${d}; the directory snapshot is incomplete and installation was refused. ${s.packed_alternative?"Pack the package with npm pack --ignore-scripts --json, then install its archive.":"Install a smaller source directory or a packed archive."}`,h.USAGE,{code:"extension_install_incomplete_source_scan",reason:a.stop_reason,nextSteps:s.packed_alternative?[`Run npm pack --ignore-scripts --json from the package root, then pm package install <archive-filename> --${n}.`]:["Choose a smaller source directory or install a packed archive."]})}return s}async function ep(e,t,n={}){let{maxEntries:r=1e4,maxDepth:i=64,signal:o}=n;if(![r,i].every(p=>Number.isSafeInteger(p)&&p>0))throw new m("maxEntries and maxDepth must be positive safe integers.",h.USAGE);o?.throwIfAborted();let a=await Xt.realpath(e),s=await _t(t),c=await et(a,s);o?.throwIfAborted();let d=c?"in_place":K(a,s)?"nested_filtered_snapshot":"directory_snapshot",l={copy_scope:d,source_directory:a,destination_directory:s,files:0,bytes:0,directories:0,symlinks:0,other_entries:0,scanned_entries:0,excluded_entries:0,development_entries:0,complete:!0,stop_reason:"complete",max_entries:r,max_depth:i};return d==="in_place"||await na(a,0,l,o),l}async function na(e,t,n,r){r?.throwIfAborted();let i=await Xt.opendir(e);for await(let o of i){if(r?.throwIfAborted(),n.scanned_entries>=n.max_entries){n.complete=!1,n.stop_reason="entry_limit";return}n.scanned_entries+=1;let a=Vt.join(e,o.name);if(!gt(n.source_directory,n.destination_directory,a,n.copy_scope==="nested_filtered_snapshot")){n.excluded_entries+=1;continue}if(Vt.relative(n.source_directory,a).split(Vt.sep).some(s=>Ql.has(s))&&(n.development_entries+=1),await tp(a,t,n,r),!n.complete)return}}async function tp(e,t,n,r){let i=await Xt.lstat(e);if(r?.throwIfAborted(),i.isDirectory()){if(n.directories+=1,t+1>=n.max_depth){n.complete=!1,n.stop_reason="depth_limit";return}await na(e,t+1,n,r)}else i.isFile()?(n.files+=1,n.bytes+=i.size):i.isSymbolicLink()?n.symlinks+=1:n.other_entries+=1}import np from"node:fs/promises";import rp from"npm-package-arg";async function ip(e,t){if(e.kind!=="local"||e.input.startsWith(".")||e.input.includes("\\")||e.input.includes("/")&&!/^@[a-zA-Z0-9._-]+\/[a-zA-Z0-9._-]+$/u.test(e.input))return e;try{return await np.lstat(e.absolute_path),e}catch(a){if(!ke(a))throw a}let n=e.input.trim(),r=t.filter(a=>a.source.kind==="npm"),o=(r.find(a=>a.name===n)??r.find(a=>a.directory===n)??r.find(a=>a.source.package===n))?.source.package;if(o===void 0)return e;try{let a=rp(o);if(!a.registry||a.name!==o)return e}catch{return e}return mt(`npm:${o}`,{})}async function ra(e,t,n,r=[]){let i=typeof t=="string"?null:await ut(e),o=i===null?null:e.trim().toLowerCase(),a=o===null?null:await ho(o),s=await ip(mt(i??e,{forceGithub:typeof t=="string",ref:n}),r),c=o===null?null:await ko(e);return{bundledAliasName:o,bundledPackageName:a,installSource:s,sourceResolution:{requested:e,selected:{kind:o===null?s.kind:"builtin",input:o??s.input,...a===null?{}:{package:a}},ambiguous:c!==null,precedence:"bundled_alias_before_installed_npm",candidates:[...o===null?[]:[{kind:"builtin",input:o,...a===null?{}:{package:a},command:`pm install ${o}`}],...c===null?[]:[{kind:"npm",input:`npm:${c.package}`,package:c.package,...c.version===void 0?{}:{version:c.version},directory:c.directory,command:`pm install npm:${c.package}`}]]}}}import rt from"node:fs/promises";import re from"node:path";import dp from"node:path";import{mkdir as lp}from"node:fs/promises";var yt=["agile","ops","research"],op={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 Yt(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: ${yt.join(", ")}.`)}function wt(e){return op[e].map(t=>at(t))}var ap=/^([A-Za-z][A-Za-z0-9_-]*?)\s*[-:]\s+\S/;function sp(e){let t=ap.exec(e.trim());if(!t)return;let n=t[1];if(!(n.length<2)&&!/^[A-Za-z]\d+$/.test(n))return n.toLowerCase()}function cp(e){return e.split(/[-_]+/).filter(t=>t.length>0).map(t=>`${t.slice(0,1).toUpperCase()}${t.slice(1).toLowerCase()}`).join("")}function ia(e,t={}){let n=typeof t.minCount=="number"&&t.minCount>0?Math.trunc(t.minCount):10,r=typeof t.maxExamples=="number"&&t.maxExamples>0?Math.trunc(t.maxExamples):3,i=new Map;for(let a of e){let s=typeof a=="string"?a.trim():"";if(s.length===0)continue;let c=sp(s);if(c===void 0)continue;let d=i.get(c)??{count:0,examples:[]};d.count+=1,d.examples.length<r&&d.examples.push(s),i.set(c,d)}let o=[];for(let[a,s]of i.entries()){if(s.count<n)continue;let c=cp(a);o.push({name:c,prefix:a,count:s.count,examples:s.examples,shadows_builtin:ei(c)!==void 0})}return o.sort((a,s)=>s.count-a.count||a.name.localeCompare(s.name)),o}var ly=[...At,"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"],Zt="schema-types",oa="schema-statuses",aa="schema-fields";function Ie(e){return Ee({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 py(e,t,n){let r=M(process.cwd(),n.path);await ve(r);let i;try{i=at({name:e,description:t.description,defaultStatus:t.defaultStatus,folder:t.folder,aliases:t.alias})}catch(_){throw new m(_ instanceof Error?_.message:String(_),h.USAGE)}let o=await A(r),a=V(o.schema),s=ee(r,a.files.types,X.types),c=[],d=q(t.author,o.author_default),l=he(o),p=await te(r,Zt,o.locks.ttl_seconds,d,!!t.force,l.force_required_for_stale_lock,o.locks.wait_ms),u;try{let _=await U(s),g;try{g=ie(_)}catch(w){throw new m(w instanceof Error?w.message:String(w),h.GENERIC_FAILURE)}try{ti(i,g);let w=new Map,f=B(o,W());for(let[y,v]of Object.entries(f.type_to_folder)){let x=v.trim().toLowerCase();x.length>0&&!w.has(x)&&w.set(x,y)}ni(i,g,w)}catch(w){throw new m(w instanceof Error?w.message:String(w),h.USAGE)}u=Ge(g,i),u.replaced&&u.previousName!==void 0&&u.previousName!==u.definition.name&&c.push(`type_recased:${u.previousName}->${u.definition.name}`),await Ie({pmRoot:r,filePath:s,raw:ce(u.file),op:"schema:add-type",author:d,settings:o}),await vt(r,[u.definition],c,"schema:add-type-folder"),c.push(...await H({path:s,scope:"project",op:"schema:add-type"}))}finally{await p()}return await sa(r,c),{action:"add-type",registered:!0,replaced:u.replaced,type:u.definition,file:{path:s,definitions:u.file.definitions.length},warnings:Oe(c),generated_at:T()}}async function ve(e){await ze(e)}async function sa(e,t){try{let n=await vi(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 Oe(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}async function pp(e,t,n,r){let i=B(t,W()),o=r.trim().toLowerCase();return(await Le(e,t.item_format,i.type_to_folder,[],n)).filter(s=>typeof s.type=="string"&&s.type.toLowerCase()===o).length}async function up(e,t,n,r){let i=B(t,W()),o=ot(n),a=O(r);return(await Le(e,t.item_format,i.type_to_folder,[],n)).filter(c=>{let d=typeof c.status=="string"?c.status:"";return(o.alias_to_id.get(O(d))??O(d))===a}).length}async function mp(e,t,n,r,i){if(i.length===0||De.has(i))return;let o=await up(t,n,r,i);o>0&&e.push(`items_using_status:${o}`);let a=ca(r.workflow,i);a.length>0&&e.push(`status_referenced_by_workflow:${a.join(",")}`)}function ca(e,t){return[["draft_status",e.draft_status],["open_status",e.open_status],["in_progress_status",e.in_progress_status],["blocked_status",e.blocked_status],["close_status",e.close_status],["canceled_status",e.canceled_status]].filter(([,r])=>r!==void 0&&O(r)===t).map(([r])=>r)}async function uy(e,t,n){let r=M(process.cwd(),n.path);await ve(r);let i=await A(r),o=V(i.schema),a=ee(r,o.files.types,X.types),s=[],c=q(t.author,i.author_default),d=he(i),l=await te(r,Zt,i.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,i.locks.wait_ms),p;try{let u=await U(a),_;try{_=ie(u)}catch(g){throw new m(g instanceof Error?g.message:String(g),h.GENERIC_FAILURE)}try{p=ri(_,e)}catch(g){throw new m(g instanceof Error?g.message:String(g),h.USAGE)}if(p.removed){let g=(p.definition?.name??e??"").trim();if(g.length>0){let w=await pp(r,i,o,g);w>0&&s.push(`items_using_type:${w}`)}await Ie({pmRoot:r,filePath:a,raw:ce(p.file),op:"schema:remove-type",author:c,settings:i}),s.push(...await H({path:a,scope:"project",op:"schema:remove-type"}))}}finally{await l()}return p.removed&&await sa(r,s),{action:"remove-type",removed:p.removed,...p.definition?{type:p.definition}:{},file:{path:a,definitions:p.file.definitions.length},warnings:Oe(s),generated_at:T()}}function Yn(e,t){return ee(e,t.files.statuses,X.statuses)}function Qt(e,t){return ee(e,t.files.fields,X.fields)}function da(e,t){return ee(e,t.files.types,X.types)}async function vt(e,t,n,r){for(let i of t){let o=Ir(i.folder??Tr(i.name)),a=dp.join(e,o);await b(a)||(await lp(a,{recursive:!0}),n.push(...await H({path:a,scope:"project",op:r})))}}function Zn(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 fp(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 hp(e){let t=new Map;for(let n of e){let r=O(n.id);if(r.length!==0){t.set(r,r);for(let i of Array.isArray(n.aliases)?n.aliases:[]){let o=O(i);o.length>0&&!t.has(o)&&t.set(o,r)}}}return t}async function my(e,t,n){let r=M(process.cwd(),n.path);await ve(r);let i;try{i=Wi({id:e,roles:t.role,aliases:t.alias,description:t.description,order:t.order})}catch(f){throw new m(f instanceof Error?f.message:String(f),h.USAGE)}let o=await A(r),a=V(o.schema),s=Yn(r,a),c=ot(a);try{In(i,c.alias_to_id)}catch(f){throw new m(f instanceof Error?f.message:String(f),h.USAGE)}let d=fp(c.by_id.get(i.id));if((i.roles??d?.roles??[]).length===0)throw new m(`Status "${i.id}" requires at least one lifecycle role. Re-run with --role active, --role blocked, --role draft, or an appropriate terminal/default role.`,h.USAGE,{code:"status_lifecycle_role_required",examples:[`pm schema add-status "${Ne(i.id)}" --role active`,`pm schema add-status "${Ne(i.id)}" --role blocked`]});let p=[],u=q(t.author,o.author_default),_=he(o),g=await te(r,oa,o.locks.ttl_seconds,u,!!t.force,_.force_required_for_stale_lock,o.locks.wait_ms),w;try{let f=await U(s),y;try{y=Be(f)}catch(x){throw new m(x instanceof Error?x.message:String(x),h.GENERIC_FAILURE)}let v=hp(y.statuses);try{In(i,v)}catch(x){throw new m(x instanceof Error?x.message:String(x),h.USAGE)}w=Bi(y,i,d),await Ie({pmRoot:r,filePath:s,raw:He(w.file),op:"schema:add-status",author:u,settings:o}),p.push(...await H({path:s,scope:"project",op:"schema:add-status"}))}finally{await g()}return{action:"add-status",registered:!0,replaced:w.replaced,status:w.definition,file:{path:s,statuses:w.file.statuses.length},warnings:Oe(p),generated_at:T()}}async function fy(e,t,n){let r=M(process.cwd(),n.path);await ve(r);let i=await A(r),o=V(i.schema),a=Yn(r,o),s=[],c=q(t.author,i.author_default),d=he(i),l=await te(r,oa,i.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,i.locks.wait_ms),p;try{let u=await U(a),_;try{_=Be(u)}catch(g){throw new m(g instanceof Error?g.message:String(g),h.GENERIC_FAILURE)}try{p=Hi(_,e)}catch(g){throw new m(g instanceof Error?g.message:String(g),h.USAGE)}if(p.removed){let g=O(p.definition?.id??e);await mp(s,r,i,o,g),await Ie({pmRoot:r,filePath:a,raw:He(p.file),op:"schema:remove-status",author:c,settings:i}),s.push(...await H({path:a,scope:"project",op:"schema:remove-status"}))}}finally{await l()}return{action:"remove-status",removed:p.removed,...p.definition?{status:p.definition}:{},file:{path:a,statuses:p.file.statuses.length},warnings:Oe(s),generated_at:T()}}function la(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 gp(e,t,n){return{...la(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 pa(e){return{id:e.id,source:De.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 ua(e,t,n){let r=e.toLowerCase();return n.has(r)?"extension":t.has(r)?"custom":"builtin"}function _p(){let e=new Map,t=W();for(let n of t?.item_types??[]){let r=n.types;if(Array.isArray(r))for(let i of r){if(typeof i!="object"||i===null||Array.isArray(i))continue;let o=i.name;typeof o=="string"&&o.trim().length>0&&e.set(o.trim().toLowerCase(),{layer:n.layer,name:n.name})}}return e}function yp(e){let t=ot(e),n=[],r=[];for(let i of t.definitions){let o=pa(i);o.source==="builtin"?n.push(o):r.push(o)}return{builtin:n,custom:r}}async function kt(e){let t=M(process.cwd(),e.path);await ve(t);let n=await A(t),r=V(n.schema),i=ee(t,r.files.types,X.types),o=Yn(t,r),a=B(n,W()),s=_p(),c=new Set((n.item_types?.definitions??[]).map(d=>d.name.trim().toLowerCase()).filter(d=>d.length>0&&!s.has(d)));return{pmRoot:t,typesPath:i,statusesPath:o,byType:a.by_type,customNames:c,extensionProvenance:s,schema:r}}async function hy(e){let t=await kt(e),n=[],r=[],i=[];for(let s of Object.values(t.byType).sort((c,d)=>c.name.localeCompare(d.name))){let c=ua(s.name,t.customNames,new Set(t.extensionProvenance.keys())),d=la(s);c==="extension"?i.push(d):c==="custom"?r.push(d):n.push(d)}let o=yp(t.schema),a=Ot(t.schema).definitions.map(Zn);return{action:"list",builtin:n,custom:r,extension:i,counts:{builtin:n.length,custom:r.length,extension:i.length,total:n.length+r.length+i.length},statuses:{builtin:o.builtin,custom:o.custom,counts:{builtin:o.builtin.length,custom:o.custom.length,total:o.builtin.length+o.custom.length}},fields:{custom:a,counts:{total:a.length}},file:{path:t.typesPath},generated_at:T()}}async function gy(e,t){let n=(e??"").trim();if(n.length===0)throw new m("Type name must not be empty.",h.USAGE);let r=await kt(t),i=Object.values(r.byType).find(o=>o.name.toLowerCase()===n.toLowerCase()||o.aliases.some(a=>a.toLowerCase()===n.toLowerCase()));if(!i)throw new m(`Unknown item type "${n}". Run pm schema list to inspect registered types, or pm schema add-type "${Ne(n)}" to register it.`,h.NOT_FOUND,{code:"unknown_item_type"});return{action:"show",type:gp(i,ua(i.name,r.customNames,new Set(r.extensionProvenance.keys())),r.extensionProvenance.get(i.name.toLowerCase())),file:{path:r.typesPath},generated_at:T()}}async function _y(e,t){let n=O(e);if(n.length===0)throw new m("Status id must not be empty.",h.USAGE);let r=await kt(t),i=ot(r.schema),o=i.alias_to_id.get(n)??n,a=i.by_id.get(o);if(!a)throw new m(`Unknown status "${e}". Run pm schema list to inspect registered statuses, or pm schema add-status "${Ne(e??"")}" to register it.`,h.NOT_FOUND,{code:"unknown_status"});return{action:"show-status",status:pa(a),file:{path:r.statusesPath},generated_at:T()}}async function yy(e,t,n){let r=M(process.cwd(),n.path);await ve(r);let i;try{i=fi({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(g){throw new m(g instanceof Error?g.message:String(g),h.USAGE)}_i(i);let o=await A(r),a=V(o.schema),s=Qt(r,a),c=[],d=Lt(i.key);d&&c.push(`custom_field_mcp_input_collision:${d.field}:${d.property}:${d.owner}:use=${d.nested_path}`);let l=q(t.author,o.author_default),p=he(o),u=await te(r,aa,o.locks.ttl_seconds,l,!!t.force,p.force_required_for_stale_lock,o.locks.wait_ms),_;try{let g=await U(s),w;try{w=Je(g)}catch(f){throw new m(f instanceof Error?f.message:String(f),h.GENERIC_FAILURE)}_=hi(w,i),await Ie({pmRoot:r,filePath:s,raw:qe(_.file),op:"schema:add-field",author:l,settings:o}),c.push(...await H({path:s,scope:"project",op:"schema:add-field"}))}finally{await u()}return{action:"add-field",registered:!0,replaced:_.replaced,field:_.definition,file:{path:s,fields:_.file.fields.length},warnings:Oe(c),generated_at:T()}}async function wp(e,t,n,r){let i=B(t,W());return(await Le(e,t.item_format,i.type_to_folder,[],n)).filter(a=>{let s=a[r];return s==null?!1:Array.isArray(s)?s.length>0:typeof s=="string"?s.trim().length>0:!0}).length}async function wy(e,t,n){let r=M(process.cwd(),n.path);await ve(r);let i=await A(r),o=V(i.schema),a=Qt(r,o),s=[],c=q(t.author,i.author_default),d=he(i),l=await te(r,aa,i.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,i.locks.wait_ms),p;try{let u=await U(a),_;try{_=Je(u)}catch(g){throw new m(g instanceof Error?g.message:String(g),h.GENERIC_FAILURE)}try{p=gi(_,e)}catch(g){throw new m(g instanceof Error?g.message:String(g),h.USAGE)}if(p.removed){let g=O(p.definition?.key??e),w=O(p.definition?.metadata_key??p.definition?.front_matter_key??g);if(w.length>0){let f=await wp(r,i,o,w);f>0&&s.push(`items_using_field:${f}`)}await Ie({pmRoot:r,filePath:a,raw:qe(p.file),op:"schema:remove-field",author:c,settings:i}),s.push(...await H({path:a,scope:"project",op:"schema:remove-field"}))}}finally{await l()}return{action:"remove-field",removed:p.removed,...p.definition?{field:p.definition}:{},file:{path:a,fields:p.file.fields.length},warnings:Oe(s),generated_at:T()}}async function vy(e){let t=await kt(e),n=Ot(t.schema).definitions.map(Zn);return{action:"list-fields",fields:n,counts:{total:n.length},file:{path:Qt(t.pmRoot,t.schema)},generated_at:T()}}async function ky(e,t){let n=O(e);if(n.length===0)throw new m("Field key must not be empty.",h.USAGE);let r=await kt(t),i=Ot(r.schema).by_key.get(n);if(!i)throw new m(`Unknown custom field "${e}". Run pm schema list-fields to inspect registered fields, or pm schema add-field "${Ne(e??"")}" to register it.`,h.NOT_FOUND,{code:"unknown_field"});return{action:"show-field",field:Zn(i),file:{path:Qt(r.pmRoot,r.schema)},generated_at:T()}}async function xy(e,t,n){let r=M(process.cwd(),n.path);await ve(r);let i;try{let w=Yt(e);if(w===void 0)throw new Error(`Type preset name is required. Allowed: ${yt.join(", ")}.`);i=w}catch(w){throw new m(w instanceof Error?w.message:String(w),h.USAGE)}let o=await A(r),a=V(o.schema),s=da(r,a),c=[],d=q(t.author,o.author_default),l=he(o),p=[],u=[],_,g=await te(r,Zt,o.locks.ttl_seconds,d,!!t.force,l.force_required_for_stale_lock,o.locks.wait_ms);try{let w=await U(s),f;try{f=ie(w)}catch(v){throw new m(v instanceof Error?v.message:String(v),h.GENERIC_FAILURE)}let y=f;for(let v of wt(i)){let x=Ge(y,v);y=x.file,(x.replaced?u:p).push(x.definition.name)}_=y.definitions.length,await Ie({pmRoot:r,filePath:s,raw:ce(y),op:"schema:apply-preset",author:d,settings:o}),await vt(r,wt(i),c,"schema:apply-preset-folder"),c.push(...await H({path:s,scope:"project",op:"schema:apply-preset"}))}finally{await g()}return{action:"apply-preset",preset:i,registered:p,replaced:u,file:{path:s,definitions:_},warnings:Oe(c),generated_at:T()}}function vp(e){if(e===void 0)return 10;if(!Number.isInteger(e)||e<1)throw new m("--min-count must be a positive integer (>= 1).",h.USAGE);return e}async function by(e,t){let n=M(process.cwd(),t.path);await ve(n);let r=await A(n),i=V(r.schema),o=da(n,i),a=vp(e.minCount),s=B(r,W()),d=(await Le(n,r.item_format,s.type_to_folder,[],i)).map(x=>typeof x.title=="string"?x.title:""),l=ia(d,{minCount:a}),p=[],u=[],_=[],g=[],w;if(!e.apply){let x;try{x=ie(await U(o))}catch(S){throw new m(S instanceof Error?S.message:String(S),h.GENERIC_FAILURE)}return w=x.definitions.length,{action:"infer-types",applied:!1,min_count:a,candidates:l,registered:u,replaced:_,skipped:g,file:{path:o,definitions:w},warnings:p,generated_at:T()}}let f=q(e.author,r.author_default),y=he(r),v=await te(n,Zt,r.locks.ttl_seconds,f,!!e.force,y.force_required_for_stale_lock,r.locks.wait_ms);try{let x=await U(o),S;try{S=ie(x)}catch(F){throw new m(F instanceof Error?F.message:String(F),h.GENERIC_FAILURE)}let L=S;for(let F of l){if(F.shadows_builtin){g.push({name:F.name,reason:"shadows_builtin"});continue}let j;try{j=at({name:F.name})}catch{g.push({name:F.name,reason:"invalid_type_token"});continue}let E=Ge(L,j);L=E.file,(E.replaced?_:u).push(E.definition.name)}w=L.definitions.length,await Ie({pmRoot:n,filePath:o,raw:ce(L),op:"schema:infer-types",author:f,settings:r}),await vt(n,L.definitions.filter(F=>u.includes(F.name)||_.includes(F.name)),p,"schema:infer-types-folder"),p.push(...await H({path:o,scope:"project",op:"schema:infer-types"}))}finally{await v()}return{action:"infer-types",applied:!0,min_count:a,candidates:l,registered:u,replaced:_,skipped:g,file:{path:o,definitions:w},warnings:Oe(p),generated_at:T()}}function Sy(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 "${Ne(e.type.name)}" "<title>"`}function Ey(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 $y(e){let t=e.replaced?"Updated":"Registered",n=e.status.roles&&e.status.roles.length>0?` (roles: ${e.status.roles.join(", ")})`:"",r=e.status.aliases&&e.status.aliases.length>0?` (aliases: ${e.status.aliases.join(", ")})`:"";return`${t} status "${e.status.id}"${n}${r} in ${e.file.path}.`}function Ay(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 Ty(e){let t=[`Schema types: ${e.counts.total} total (${e.counts.builtin} builtin, ${e.counts.custom} custom, ${e.counts.extension} extension)`];for(let[n,r]of[["builtin",e.builtin],["custom",e.custom],["extension",e.extension]])r.length!==0&&t.push(`${n}: ${r.map(i=>i.name).join(", ")}`);t.push(`statuses: ${e.statuses.counts.total} total (${e.statuses.counts.builtin} builtin, ${e.statuses.counts.custom} custom)`);for(let[n,r]of[["builtin statuses",e.statuses.builtin],["custom statuses",e.statuses.custom]])r.length!==0&&t.push(`${n}: ${r.map(i=>i.id).join(", ")}`);return t.push(`custom fields: ${e.fields.counts.total} total`),e.fields.custom.length>0&&t.push(`fields: ${e.fields.custom.map(n=>`${n.key} (${n.type}, ${n.cli_flag})`).join(", ")}`),t.push("Inspect one: pm schema show <Type>"),t.push("Inspect one status: pm schema show-status <status>"),t.push("Inspect one field: pm schema show-field <key>"),t.join(`
|
|
33
|
+
`)}function Iy(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(`
|
|
34
|
+
`)}function Oy(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(`
|
|
35
|
+
`)}function kp(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 Cy(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 Py(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 Ry(e){let t=[`Custom fields: ${e.counts.total} total`];for(let n of e.fields)t.push(` ${kp(n)}`);return t.push("Inspect one: pm schema show-field <key>"),t.join(`
|
|
36
|
+
`)}function Ny(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(`
|
|
37
|
+
`)}function Ly(e){let t=e.registered.length>0?`registered: ${e.registered.join(", ")}`:"",n=e.replaced.length>0?`updated: ${e.replaced.join(", ")}`:"",r=[t,n].filter(i=>i.length>0).join("; ");return`Applied "${e.preset}" type preset to ${e.file.path}${r.length>0?` (${r})`:""}.`}function jy(e){if(e.candidates.length===0)return`No title-prefix conventions found with at least ${e.min_count} items. Lower the threshold with --min-count <n>.`;let t=e.applied?[`Inferred and registered custom types from title prefixes (min-count ${e.min_count}):`]:[`Inferred custom type candidates from title prefixes (min-count ${e.min_count}, dry-run):`];for(let n of e.candidates){let r=n.shadows_builtin?" [shadows built-in, skipped]":"";t.push(` ${n.name} <- "${n.prefix}" (${n.count} items)${r}`)}return e.applied?(e.registered.length>0&&t.push(`registered: ${e.registered.join(", ")}`),e.replaced.length>0&&t.push(`updated: ${e.replaced.join(", ")}`)):t.push("Re-run with --apply to register the non-shadowing candidates."),t.join(`
|
|
38
|
+
`)}var Dy={workflowSlotsReferencing:ca};function ma(e){let t=/^extension_(disabled_)?pm_(min|max)_version_([a-z_]+):(project|global):([^:]+):(.+)$/u.exec(e);if(!t)return;let[,n,r,i,o,a,s]=t,c=s.split(":")[0].replace(r==="min"?"required=":"allowed=",""),d=i==="invalid"?`a valid pm_${r}_version instead of ${c}`:`pm ${r==="min"?">=":"<="} ${c}`;return n?`Package ${a} is disabled and requires ${d} before activation. After satisfying the bound, run ${se(["package","activate",a,`--${o}`])}.`:`Package ${a} requires ${d}. Use a compatible host or package version, or keep it disabled with ${se(["package","deactivate",a,`--${o}`])}.`}function Qn(e){return e.map(({layer:t,name:n,error:r})=>({layer:t,name:n,error:r}))}function en(e,t,n){let r=k(t),i=n.trim();if(r.length===0||i.length===0)return;let o=e.get(r)??new Set;o.add(i),e.set(r,o)}function xp(e){let t=new Map,n=new Map;for(let r of e.registrations.commands)en(t,r.name,r.command),en(n,r.name,r.action);for(let r of e.commands.handlers)en(t,r.name,r.command);for(let r of e.commands.overrides)en(t,r.name,r.command);return{commandPathsByExtension:t,actionPathsByExtension:n}}function fa(e){if(!(!e||e.size===0))return[...e].sort((t,n)=>t.localeCompare(n))}function bp(e){let{enabled:t,normalizedName:n,loadedNames:r,loadFailedNames:i,activationFailedNames:o}=e;return t?i.has(n)||o.has(n)?{runtime_active:!1,activation_status:"failed"}:r.has(n)?{runtime_active:!0,activation_status:"ok"}:{runtime_active:!1,activation_status:"not_loaded"}:{runtime_active:!1,activation_status:"not_loaded"}}function tn(e,t,n){let r=new Set(t.loaded.map(c=>k(c.name))),i=new Set(t.failed.map(c=>k(c.name))),o=new Set(n.failed.map(c=>k(c.name))),{commandPathsByExtension:a,actionPathsByExtension:s}=xp(n);return e.map(c=>{let d=k(c.name),l=fa(a.get(d)),p=fa(s.get(d)),u={...l?{command_paths:l}:{},...p?{action_paths:p}:{}},_=bp({enabled:c.enabled,normalizedName:d,loadedNames:r,loadFailedNames:i,activationFailedNames:o});return{...c,..._,...u}})}function Sp(e){let t=0,n=0,r=0;for(let i of e)if(i.startsWith("extension_policy_")){if(t+=1,i.startsWith("extension_policy_violation_")){n+=1;continue}i.startsWith("extension_policy_blocked_")&&(r+=1)}return{warning_count:t,violation_count:n,blocked_count:r}}function G(e,t){return e.vocabulary==="package"?`pm package --${t}`:`pm extension --${t}`}var _a=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 Ep(e){return _a.has(ba(e))}function ha(e){return e==="project"||e==="global"}function ya(e){let t=e.split(":"),n=t[0];if(!n||!_a.has(n))return null;let r=t.at(-4),i=t.at(-3)?.trim(),o=t.at(-2),a=t.at(-1)?.trim();return!ha(r)||!ha(o)||!i||!a?null:{code:n,surface:t.slice(1,-4).join(":")||"global",winner:{layer:r,name:i},displaced:{layer:o,name:a}}}function $p(e){let t=new Set;for(let n of e){let r=ya(n);r&&(t.add(r.winner.name),t.add(r.displaced.name))}return[...t].sort((n,r)=>n.localeCompare(r))}function Ap(e,t){let n=e.filter(Ep);if(n.length===0)return null;let r=$p(n);return`Extension registration collisions or handler/override overlaps detected.${r.length>0?` Conflicting extensions: ${r.join(", ")}.`:""} Single-winner surfaces can hide earlier package behavior. Deactivate one conflicting package with ${t.deactivate}, or scope registration surfaces in extensions.policy.extension_overrides, then rerun ${t.doctor}.`}function Tp(e,t,n,r){let i=t.map(p=>ya(p)).filter(p=>p!==null).sort((p,u)=>`${p.code}:${p.surface}:${p.winner.name}:${p.displaced.name}`.localeCompare(`${u.code}:${u.surface}:${u.winner.name}:${u.displaced.name}`));if(i.length===0)return;let o=e==="global"?"--global":"--project",a=G(r,"deactivate"),s=`${G(r,"doctor")} ${o} --detail deep --trace`,c=new Map(n.map(p=>[k(p.name),p])),d=new Map;for(let p of i)for(let u of[p.winner.name,p.displaced.name]){let _=k(u);d.set(_,(d.get(_)??0)+1)}let l=[...d.entries()].map(([p,u])=>{let _=c.get(p),g=_?.name??p,w=_?.command_paths??[],f=_?.action_paths??[];return{action:"deactivate",extension:g,command:`${a} ${g} ${o}`,affected_collisions:u,feature_loss:{command_paths:[...w].sort((y,v)=>y.localeCompare(v)),action_paths:[...f].sort((y,v)=>y.localeCompare(v))}}}).sort((p,u)=>{let _=u.affected_collisions-p.affected_collisions;if(_!==0)return _;let g=p.feature_loss.command_paths.length+p.feature_loss.action_paths.length,w=u.feature_loss.command_paths.length+u.feature_loss.action_paths.length;return g!==w?g-w:p.extension.localeCompare(u.extension)});return{status:"conflicts_detected",collision_count:i.length,extension_count:d.size,next_best_command:s,collisions:i,remediation_candidates:l}}function wa(e){let t=[];for(let n of e){let r=n.error.toLowerCase();(r.includes("cannot find package '@unbrained/pm-cli'")||r.includes('cannot find module "@unbrained/pm-cli"')||r.includes("cannot find module '@unbrained/pm-cli'"))&&t.push(`extension_load_failed_sdk_dependency_missing:${n.name}`),(r.includes("cannot use import statement outside a module")||r.includes("to load an es module")||r.includes("must use import to load es module"))&&t.push(`extension_load_failed_module_mode_mismatch:${n.name}`)}return[...new Set(t)].sort((n,r)=>n.localeCompare(r))}function va(e=[]){let t=Array.isArray(e)?e:[],n=[];for(let r of t){if(!r||typeof r.name!="string")continue;let i=r.trace?.missing_capability??r.trace?.capability;typeof i=="string"&&i.trim().length>0&&n.push(`extension_capability_missing:${r.name}:${i.trim().toLowerCase()}`)}return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}function ka(e,t){let n=[];for(let r of Vr(e.loaded,t))for(let i of r.unused)n.push(`extension_capability_unused:${r.layer}:${r.name}:${i}`);return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}var Ip=[{matches:e=>e.some(t=>t.startsWith("extension_manifest_")),build:e=>`Run ${G(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: ${wr.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 ${G(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 ${G(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 ${G(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 ${G(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 ${G(e.options,"doctor")} ${e.scopeFlag}.`},{matches:(e,t)=>t.updateCheckFailedTotal>0,build:e=>`Run ${G(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 Op(e){let{normalizedWarnings:t,options:n,scope:r,scopeFlag:i,updateCheckFailedTotal:o,policyWarningCount:a,unmanagedActionRequiredTotal:s,notCheckedTotal:c,skippedNonGithubTotal:d,updateAvailableTotal:l}=e,p=t.map(ma).filter(_=>_!==void 0),u={options:n,scope:r,scopeFlag:i,updateCheckFailedTotal:o,policyWarningCount:a};if(t.length>0){let _=Ap(t,{deactivate:`${G(n,"deactivate")} <name> ${i}`,doctor:`${G(n,"doctor")} ${i} --detail deep --trace`});_&&p.push(_);for(let g of Ip)g.matches(t,u)&&p.push(g.build(u))}return s>0&&p.push(`Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via ${G(n,"manage")} ${i} --fix-managed-state (or ${G(n,"adopt-all")} ${i}, ${G(n,"adopt")} <name> ${i}, or reinstall via ${G(n,"install")} ${i} <source>).`),d>0&&p.push("Update-check coverage is partial: non-GitHub managed sources were not checked. Inspect their registry or source directly; zero detected updates does not mean these packages are current. Runtime activation health is independent."),c>0&&p.push(`Update-check coverage is partial: some sources have no completed check. Run ${G(n,"manage")} ${i} to request update checks.`),l>0&&p.push(`Update available managed extensions via ${G(n,"install")} ${i} <source>.`),p.length===0&&p.push(`No immediate action required. Re-run ${G(n,"manage")} ${i} after extension changes.`),p}function nn(e,t,n,r={}){let i=[...new Set(t)].sort((E,J)=>E.localeCompare(J)),o=n.filter(E=>E.managed).length,a=n.filter(E=>E.enabled).length,s=n.filter(E=>E.active).length,c=n.filter(E=>E.update_check_status==="checked"&&E.update_available===!0).length,d=n.filter(E=>E.managed===!1),l=d.filter(E=>ga(E)).map(E=>E.name).sort((E,J)=>E.localeCompare(J)),p=d.filter(E=>!ga(E)).map(E=>E.name).sort((E,J)=>E.localeCompare(J)),u={checked:0,skipped_unmanaged:0,skipped_non_github:0,failed:0,not_checked:0};for(let E of n)u[E.update_check_status]+=1;let _=u.failed,g=n.filter(E=>E.update_check_status==="skipped_non_github"&&E.source?.kind!=="builtin").length,w=Object.entries({skipped_unmanaged:p.length,skipped_non_github:g,failed:_,not_checked:u.not_checked}).filter(([,E])=>E>0).map(([E,J])=>`extension_update_health_partial_coverage:${E}:${J}`),f=w.length>0,y=f?"partial":"full",v=[...new Set([...i,...w])].sort((E,J)=>E.localeCompare(J)),x=[...new Set(v.map(E=>ba(E)))].sort((E,J)=>E.localeCompare(J)),S=Sp(v),L=e==="global"?"--global":"--project",F=Tp(e,i,n,r),j=Op({normalizedWarnings:v,options:r,scope:e,scopeFlag:L,updateCheckFailedTotal:_,policyWarningCount:S.warning_count,unmanagedActionRequiredTotal:p.length,notCheckedTotal:u.not_checked,skippedNonGithubTotal:g,updateAvailableTotal:c});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:o,enabled_total:a,active_total:s,update_available_total:c,update_health_coverage:y,update_health_partial:f,unmanaged_loaded_extension_count:d.length,unmanaged_loaded_extensions:d.map(E=>E.name).sort((E,J)=>E.localeCompare(J)),unmanaged_expected_extension_count:l.length,unmanaged_expected_extensions:l,unmanaged_action_required_extension_count:p.length,unmanaged_action_required_extensions:p,update_check_status_totals:u,update_check_failed_total:_,top_warnings:v.slice(0,8),remediation:j,...F?{collision_plan:F}:{}}}function xa(e){if(!e||e.trim().length===0)return"summary";let t=e.trim().toLowerCase();if(t==="summary"||t==="deep")return t;throw new m(`Invalid --detail value "${e}". Expected summary or deep.`,h.USAGE)}function ba(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function Sa(e){let t=new Set,n=[];for(let r of e){let i=(()=>{let o=zr(r);return o?[o]:Jr(r)})();for(let o of i){let a=`${o.layer}:${o.name}:${o.capability}`;t.has(a)||(t.add(a),n.push(o))}}return n}function Ea(){return{version:$t.version,capabilities:[...$t.capabilities],legacy_aliases:{...$t.legacy_aliases}}}function ga(e){let t=k(e.name),n=k(e.directory);return t.startsWith("builtin-")?!0:n==="beads"||n==="todos"}function $a(e,t,n,r,i){if(e!=="project"||i)return{warnings:[],summary:{active_project_count:0,loaded_project_count:0,active_project_names:[],loaded_project_names:[],missing_active_project_names:[]}};let o=[...new Set(t.filter(l=>l.active).map(l=>k(l.name)))].sort((l,p)=>l.localeCompare(p)),a=[...new Set(n.filter(l=>l.layer==="project").map(l=>k(l.name)))].sort((l,p)=>l.localeCompare(p)),s=new Set(r.map(l=>k(l.name))),c=o.filter(l=>!a.includes(l)&&!s.has(l)).sort((l,p)=>l.localeCompare(p));return{warnings:c.length>0?[`extension_doctor_consistency_active_not_loaded:${c.join(",")}`]:[],summary:{active_project_count:o.length,loaded_project_count:a.length,active_project_names:o,loaded_project_names:a,missing_active_project_names:c}}}function Aa(e,t){let n=k(e),r=t.find(i=>k(i.name)===n);return{command_paths:[...r?.command_paths??[]].sort((i,o)=>i.localeCompare(o)),action_paths:[...r?.action_paths??[]].sort((i,o)=>i.localeCompare(o))}}function Ta(e,t){let n=new Set((t?.loaded??[]).flatMap(o=>(o.activation?.commands?.length??0)>0?[`${o.layer}:${k(o.name)}`]:[])),r=e.services.overrides.filter(o=>o.service==="output_format").filter(o=>o.passThrough!==!0).filter(o=>!n.has(`${o.layer}:${k(o.name)}`)).map(o=>`extension_output_service_override_global:${o.service}:${o.layer}:${o.name}`),i=e.renderers.overrides.filter(o=>(o.commands?.length??0)===0&&o.resultDiscriminator===void 0).map(o=>`extension_output_renderer_override_global:${o.format}:${o.layer}:${o.name}`);return[...new Set([...r,...i])].sort((o,a)=>o.localeCompare(a))}var Ia=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=Lt(t.field);return n?[`extension_custom_field_mcp_input_collision:${t.layer}:${t.extension}:${n.field}:${n.property}:${n.owner}:use=${n.nested_path}`]:[]}).filter((t,n,r)=>r.indexOf(t)===n).sort((t,n)=>t.localeCompare(n));import{spawn as Jp}from"node:child_process";import{AsyncLocalStorage as qp}from"node:async_hooks";import{isMainThread as Wp}from"node:worker_threads";import Bp from"npm-package-arg";import{spawn as Cp}from"node:child_process";import{existsSync as rn,readFileSync as Pp}from"node:fs";import Oa from"node:path";var Ca=2e3;function Rp(e,t){let n=new Map;for(let a of e.split(`
|
|
39
|
+
`)){let s=a.trim().split(/\s+/u);if(s.length!==2)continue;let[c,d]=s.map(Number);if(!Number.isSafeInteger(c)||!Number.isSafeInteger(d)||c<=0)continue;let l=n.get(d);l?l.push(c):n.set(d,[c])}let r=new Set([t]),i=[],o=(n.get(t)??[]).map(a=>({pid:a,parent:t}));for(let a=0;a<o.length;a+=1){let s=o[a];if(!r.has(s.pid)){r.add(s.pid),i.push(s);for(let c of n.get(s.pid)??[])o.push({pid:c,parent:s.pid})}}return i.reverse()}function er(e,t=Pa){let n=t(`/proc/${e.pid}/stat`);if(n===void 0)return!rn("/proc/self/stat");let r=n.slice(n.lastIndexOf(")")+1).trim().split(/\s+/u);return Number(r[1])===e.parent}function Np(e=Pa,t=process.platform){let n=e("/proc/self/status");if(n===void 0)return t!=="linux"&&!rn("/proc/self/status");let r=/^NSpid:\s*(.*)$/mu.exec(n)?.[1]?.trim().split(/\s+/u);return r?.length===1&&Number(r[0])===process.pid}function Lp(e,t,n,r=er,i=new Map){let o=[],a=!0;for(let s=e;s!==t;){let c=i.get(s);if(c!==void 0){a=c;break}o.push(s);let d=n.get(s);if(d===void 0||!r({pid:s,parent:d})){a=!1;break}s=d}for(let s of o)i.set(s,a);return a}function Pa(e){try{return Pp(e,"utf8")}catch{return}}var jp=["/bin/ps","/usr/bin/ps"],Dp={PATH:"/usr/bin:/bin",LC_ALL:"C"};function Fp(e=rn){return jp.find(t=>e(t))}var Mp="C:\\Windows";function Up(e=process.env,t=rn){let n=r=>Object.entries(e).find(([i])=>i.toLowerCase()===r)?.[1];return[n("systemroot"),n("windir"),Mp].find(r=>typeof r=="string"&&/^[A-Za-z]:[\\/]/u.test(r)&&t(Oa.win32.join(r,"System32","taskkill.exe")))}function Ra(e){try{process.kill(e,"SIGKILL")}catch{}}function Na(e,t,n,r=Ca){return new Promise(i=>{let o=!1,a="",s;try{s=Cp(e,t,{stdio:["ignore","pipe","ignore"],windowsHide:!0,...n===void 0?{}:{env:n}})}catch{i(void 0);return}let c=r===null?void 0:setTimeout(()=>{d(void 0),s.stdout?.destroy(),s.kill("SIGKILL"),s.unref()},r);function d(l){o||(o=!0,clearTimeout(c),i(l))}if(s.on("error",()=>d(void 0)),!s.stdout){d(void 0);return}s.stdout.setEncoding("utf8"),s.stdout.on("data",l=>{a+=l}),s.on("close",l=>d({code:l,stdout:a}))})}async function La(e,t={kill:()=>Ra(e),alive:()=>!0},n={}){if(!(!Number.isInteger(e)||e<=0)){if(process.platform==="win32"){await Gp(e,t,n.taskkillTimeoutMs===void 0?Ca:n.taskkillTimeoutMs);return}try{process.kill(-e,"SIGKILL");return}catch{}await zp(e,t),t.kill()}}async function Gp(e,t,n){let r=Up();if(r===void 0){t.alive()&&t.kill();return}let i=Oa.win32.join(r,"System32","taskkill.exe");(await Na(i,["/pid",String(e),"/T","/F"],void 0,n))?.code!==0&&t.alive()&&t.kill()}async function zp(e,t){let n=Fp();if(n===void 0||!Np())return;let r=await Na(n,["-A","-o","pid=","-o","ppid="],Dp);if(r?.code!==0||!t.alive())return;let i=Rp(r.stdout,e),o=new Map(i.map(s=>[s.pid,s.parent])),a=new Map;for(let s of i)er(s)&&Lp(s.parent,e,o,er,a)&&Ra(s.pid)}var Hp="PM_EXTENSION_UPDATE_CHECK_TIMEOUT_MS",tr=1e4,Kp=1e3,Vp=25e3,Xp=2e3,Yp="npm_registry_lookup_failed",Zp="npm_registry_lookup_timed_out",Qp="github_remote_lookup_failed",eu="github_remote_lookup_timed_out";function tt(e=process.env){let t=e[Hp]?.trim(),n=t?Number(t):Number.NaN;return Number.isFinite(n)?Math.min(Vp,Math.max(Kp,Math.trunc(n))):tr}var ne=class extends Error{timeout_ms;teardown;constructor(t,n,r){super(t),this.name="UpdateQueryError",this.timeout_ms=n,this.teardown=r}},Fa=new WeakMap;function Ma(e){return Fa.get(e)??Promise.resolve()}function Ua(e,t){let n={checked_at:e,available:null,error:t instanceof Error?t.message:String(t)};return t instanceof ne&&t.timeout_ms!==void 0&&(n.timeout_ms=t.timeout_ms),t instanceof ne&&t.teardown!==void 0&&Fa.set(n,t.teardown),n}var xt=new Set;function ja(){for(let e of xt)e()}var Ga=new qp;async function za(e){let t=new Set;try{return await Ga.run(t,e)}finally{Wp||await Promise.all(t)}}function tu(e){return xt.size===0&&process.on("exit",ja),xt.add(e),()=>{xt.delete(e),xt.size===0&&process.off("exit",ja)}}function nu(e){let t=()=>e.exitCode!==null||e.signalCode!==null,n=()=>{t()||e.kill("SIGKILL")},r=()=>t()||e.pid===void 0?Promise.resolve():new Promise(o=>{let a=setTimeout(()=>{e.unref(),o()},Xp);e.once("exit",()=>{clearTimeout(a),o()})}),i=()=>(n(),e.stdout?.destroy(),r());return{stop:()=>t()||e.pid===void 0?Promise.resolve().then(i):La(e.pid,{kill:n,alive:()=>!t()}).then(i,i),killNow:n}}function Ja(e,t,n,r){return new Promise((i,o)=>{let a;try{a=Jp(e,t,{env:r.env,shell:r.shell,stdio:["ignore","pipe","ignore"]})}catch{o(new ne(r.failed));return}let s=a,c=performance.now()+n,d=!1,l="",p=0,u=nu(s),_=Ga.getStore(),g,w=()=>{let v=tu(u.killNow),x=new Promise(S=>{setTimeout(()=>{u.stop().then(S,S)},0)}).finally(v);return _?.add(x),g=x,x},f=setTimeout(()=>{y(new ne(r.timedOut,n,w()))},n);function y(v){d||(d=!0,clearTimeout(f),performance.now()>=c?o(new ne(r.timedOut,n,g)):v?o(v):i(l.trim()))}if(s.on("error",()=>y(new ne(r.failed))),!s.stdout){y(new ne(r.failed,void 0,w()));return}s.stdout.setEncoding("utf8"),s.stdout.on("data",v=>{if(!d){if(p+=Buffer.byteLength(v),p>r.maxBuffer){y(new ne(r.failed,void 0,w()));return}l+=v}}),s.on("exit",(v,x)=>{v===0&&x===null||(y(new ne(r.failed)),s.stdout.destroy())}),s.on("close",(v,x)=>y(v===0&&x===null?void 0:new ne(r.failed)))})}function Da(e,t,n){if(typeof t=="string")try{let r=Bp.resolve(e,t);if(r.type==="version")return r.fetchSpec}catch{}throw new Error(n)}var ru=(e,t)=>Ja(Jn(),e,t,{env:{...process.env,npm_config_ignore_scripts:"true"},shell:qn(),maxBuffer:64*1024,timedOut:Zp,failed:Yp}),iu=(e,t)=>Ja("git",e,t,{env:{...process.env,GIT_TERMINAL_PROMPT:"0",GCM_INTERACTIVE:"never"},maxBuffer:1024*1024,timedOut:eu,failed:Qp});async function qa(e,t=ru,n=tt()){let r=T();try{if(e.kind!=="npm"||!e.package||!/^(?:@[a-zA-Z0-9._-]+\/)?[a-zA-Z0-9._-]+$/u.test(e.package))throw new Error("missing_or_invalid_npm_package_identity");let i=Da(e.package,e.version,"missing_or_invalid_installed_npm_version"),o=await t(["view",e.package,"dist-tags.latest","--json","--ignore-scripts"],n),a;try{a=JSON.parse(o)}catch{throw new Error("invalid_npm_registry_metadata")}let s=Array.isArray(a)&&a.length===1?a[0]:a,c=Da(e.package,s,"invalid_npm_registry_version");return{checked_at:r,available:c!==i,remote_version:c}}catch(i){return Ua(r,i)}}var ou=(e,t,n)=>{let r=e.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).map(a=>{let[s,c=""]=a.split(/\s+/);return{commit:s,ref:c}}),i=r.find(a=>a.ref.endsWith("^{}"))??r[0];if(!i)return{checked_at:n,available:null,error:"no_remote_reference_found"};let o=t?.trim();return o?{checked_at:n,remote_commit:i.commit,available:i.commit!==o}:{checked_at:n,remote_commit:i.commit,available:null,error:"missing_installed_commit"}},nr=async(e,t=iu,n=tt())=>{let r=T();if(e.kind!=="github"||!e.repository)return{checked_at:r,available:null,error:"not_a_github_managed_source"};try{let i=[e.ref?.trim(),"HEAD"].find(Boolean),o=await t(["ls-remote",e.repository,i,`${i}^{}`],n);return ou(o,e.commit,r)}catch(i){return Ua(r,i)}};var Wa=4;function au(e){let t=e,n=[];return{acquire:()=>t>0?(t-=1,Promise.resolve()):new Promise(r=>n.push(r)),release:()=>{let r=n.shift();r?r():t+=1}}}function Ba(e,t){let{update_check_timeout_ms:n,...r}=e;return t===void 0?r:{...r,update_check_timeout_ms:t}}async function Ha(e,t=!1,n=tt(),r=!0){let i=au(Wa),o=await yn(e.entries,Wa,async a=>{if(!["github","npm"].includes(a.source.kind))return a;if(t)return Ba({...a,last_update_check_at:void 0,last_update_remote_commit:void 0,last_update_remote_version:void 0,update_available:null,update_error:void 0},void 0);await i.acquire();let s=a.source.kind==="github"?await nr(a.source,void 0,n):await qa(a.source,void 0,n);return r?Ma(s).then(i.release):i.release(),Ba({...a,last_update_check_at:s.checked_at,last_update_remote_commit:"remote_commit"in s?s.remote_commit:void 0,last_update_remote_version:"remote_version"in s?s.remote_version:void 0,update_available:s.available,update_error:s.error},s.timeout_ms)});return{...e,entries:lt(o)}}function Ka(e,t){let n=e.filter(r=>r.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:r,result:i})=>{let o=i.details;return{alias:r,ok:i.ok,extension:o.extension,source:o.source,source_resolution:o.source_resolution,install_plan:o.install_plan,dry_run:o.dry_run,destination_path:o.destination_path,activated:o.activated,settings_changed:o.settings_changed,previous_state_preserved:o.previous_state_preserved,rollback:o.rollback,command_paths:o.command_paths,action_paths:o.action_paths,command_discovery:o.command_discovery,verification:o.verification,runtime_activation_status:o.runtime_activation_status,activation_diagnostics:o.activation_diagnostics,warnings:i.warnings}})}}import su from"node:fs/promises";import cu from"node:path";function du(e){return typeof e.name=="string"&&e.name.trim().length>0?e.name.trim():"workspace-manifest"}function lu(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 pu(e){let t=cu.join(e,"manifest.json"),n;try{n=await su.readFile(t,"utf8")}catch(s){if(Tt(s))return{path:t,present:!1,parse_status:"absent",package_metadata_location:"package.json#pm",schema_findings:[],warnings:[],remediation:[]};throw s}let r;try{r=JSON.parse(n)}catch{return{path:t,present:!0,parse_status:"invalid_json",package_metadata_location:"package.json#pm",schema_findings:[],warnings:["extension_author_manifest_invalid_json:manifest.json"],remediation:["Repair manifest.json so it contains one valid JSON object, then rerun pm package doctor --project."]}}if(typeof r!="object"||r===null||Array.isArray(r))return{path:t,present:!0,parse_status:"invalid_shape",package_metadata_location:"package.json#pm",schema_findings:[],warnings:["extension_author_manifest_invalid_shape:manifest.json"],remediation:["Replace manifest.json with one JSON object, then rerun pm package doctor --project."]};let i=r,o=Wr(i),a=du(i);return{path:t,present:!0,parse_status:"valid",package_metadata_location:"package.json#pm",schema_findings:o.findings,warnings:o.findings.map(s=>lu(a,s)),remediation:o.findings.map(s=>s.message)}}function Va(e){return pu(Or(e))}import ae from"node:fs/promises";import nt from"node:path";var rr=async e=>ae.readFile(e).catch(t=>{if(Kt(t,"ENOENT"))return null;throw t}),uu=async(e,t,n,r,i)=>Re("extension_install_backup",async()=>{let o=dt(e),a=Cr(t),[s,c]=await Promise.all([rr(o),rr(a)]);return r&&await ae.cp(n,i,{recursive:!0,force:!0}),{backupDirectory:i,destinationDirectory:n,destinationExists:r,managedStatePath:o,managedStateContents:s,settingsPath:a,settingsContents:c}}),Xa=async e=>Re("extension_install_rollback",async()=>{await ae.rm(e.destinationDirectory,{recursive:!0,force:!0}),e.destinationExists&&await ae.cp(e.backupDirectory,e.destinationDirectory,{recursive:!0,force:!0});for(let[t,n]of[[e.managedStatePath,e.managedStateContents],[e.settingsPath,e.settingsContents]])if(n===null)await ae.rm(t,{force:!0});else if(t===e.settingsPath){let r=nt.dirname(e.settingsPath),i=await A(r);try{await Ee({pmRoot:r,filePath:t,raw:n.toString("utf8"),op:"extension:install:rollback",author:q(void 0,i.author_default),lockTtlSeconds:i.locks.ttl_seconds,lockWaitMs:i.locks.wait_ms})}finally{ii(r)}}else await ae.mkdir(nt.dirname(t),{recursive:!0}),await ae.writeFile(t,n)});async function Ya(e,t){let n=await b(e.destinationDirectory),r=await et(e.sourceDirectory,e.destinationDirectory);await ae.mkdir(e.selectedRoot,{recursive:!0});let i=nt.join(nt.dirname(e.selectedRoot),"runtime","extension-installs");await ae.mkdir(i,{recursive:!0});let o=await ae.mkdtemp(nt.join(i,".pm-extension-install-backup-")),a=nt.join(o,"destination"),s=["package","install",a,`--${e.scope}`],c=se(s),d=!1;try{let l=await uu(e.selectedRoot,e.settingsRoot,e.destinationDirectory,n,a),p;try{p=await t()}catch(u){try{await Xa(l)}catch(_){d=!0;let g=new m(`Extension install failed: ${String(u)}; rollback failed: ${String(_)}`,h.GENERIC_FAILURE,{code:"extension_install_rollback_failed",original_code:u instanceof m?u.code:void 0,required:"Restore the previous package before retrying the replacement. Previous state was not preserved.",nextSteps:[n?c:"Repair the reported metadata write failure, then retry the original install."],...n?{recovery:{suggested_retry:c,suggested_retry_args:s}}:{}});throw Object.defineProperty(g,"cause",{value:u,configurable:!0,writable:!0}),g}throw u}if(p.ok)return p;if(!n||r)return{...p,details:{...p.details,previous_state_preserved:!1}};try{await Xa(l)}catch(u){return d=!0,{...p,details:{...p.details,previous_state_preserved:!1,rollback:{status:"failed",error:String(u),backup_directory:a,recovery_command:c,recovery_args:s}}}}return{...p,details:{...p.details,overwritten:!1,settings_changed:!1,previous_state_preserved:!0,rollback:{status:"restored"}}}}finally{d||await ae.rm(o,{recursive:!0,force:!0}).catch(()=>{})}}var 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"]],mu=ts.map(([,,e])=>e).filter((e,t,n)=>n.indexOf(e)===t).join(", "),fu={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"},hu="__pm_native_output",gu=["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"],_u=["disabled","require_trusted","require_provenance"],rs={mode:"off",trust_mode:"off",require_provenance:!1,trusted_extensions:[],default_sandbox_profile:"none",allowed_extensions:[],blocked_extensions:[],allowed_capabilities:[],blocked_capabilities:[],allowed_surfaces:[],blocked_surfaces:[],allowed_commands:[],blocked_commands:[],allowed_actions:[],blocked_actions:[],allowed_services:[],blocked_services:[],extension_overrides:[]},yu=e=>{let t=e??rs,n={};for(let r of gu)n[r]=Q(t[r]??[]);return n},wu=(e,t)=>{for(let n of ns)t[n].length>0&&(e[n]=t[n]);return e},vu=(e,t)=>{for(let n of _u)t[n]===!0&&(e[n]=!0);return t.sandbox_profile&&(e.sandbox_profile=t.sandbox_profile),e},ku=e=>{let t={};for(let n of ns)t[n]=Q(e[n]??[]);return t},xu=e=>{let t=typeof e.name=="string"?e.name.trim():"";return t.length===0?null:wu(vu({name:t},e),ku(e))},bu=e=>(e??[]).map(t=>xu(t)).filter(t=>t!==null).sort((t,n)=>t.name.localeCompare(n.name)),Su=e=>{let t=Object.assign({},rs,e??{}),n=yu(e),r=bu(t.extension_overrides);return{mode:t.mode,trust_mode:t.trust_mode,require_provenance:t.require_provenance===!0,trusted_extensions:n.trusted_extensions,default_sandbox_profile:t.default_sandbox_profile,allowed_extensions:n.allowed_extensions,blocked_extensions:n.blocked_extensions,allowed_capabilities:n.allowed_capabilities,blocked_capabilities:n.blocked_capabilities,allowed_surfaces:n.allowed_surfaces,blocked_surfaces:n.blocked_surfaces,allowed_commands:n.allowed_commands,blocked_commands:n.blocked_commands,allowed_actions:n.allowed_actions,blocked_actions:n.blocked_actions,allowed_services:n.allowed_services,blocked_services:n.blocked_services,extension_overrides:r}},is=async(e,t)=>{let n=[t],r=await go(t);r&&n.push(r);let i=[...new Set(n.map(o=>k(o)).filter(o=>o.length>0))];for(let o of i){let a=e.find(c=>k(c.name)===o);if(a)return a;let s=e.find(c=>k(c.directory)===o);if(s)return s}},os=(e,t)=>{let n=t.trim(),r=new Set(Q(e.extensions.enabled));return new Set(Q(e.extensions.disabled)).has(n)?!1:r.size===0?!0:r.has(n)},as=(e,t)=>{let n=t.trim(),r=new Set(Q(e.extensions.enabled)),i=new Set(Q(e.extensions.disabled)),o=[...r],a=[...i];return i.delete(n),r.size>0&&r.add(n),e.extensions.enabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...i].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==o.join("\0")||e.extensions.disabled.join("\0")!==a.join("\0")},Eu=(e,t)=>{let n=t.trim(),r=new Set(Q(e.extensions.enabled)),i=new Set(Q(e.extensions.disabled)),o=[...r],a=[...i];return r.delete(n),i.add(n),e.extensions.enabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...i].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==o.join("\0")||e.extensions.disabled.join("\0")!==a.join("\0")},$u=(e,t)=>{let n=t.trim(),r=new Set(Q(e.extensions.enabled)),i=new Set(Q(e.extensions.disabled)),o=[...r],a=[...i];return r.delete(n),i.delete(n),e.extensions.enabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...i].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==o.join("\0")||e.extensions.disabled.join("\0")!==a.join("\0")},Au=e=>{let t=e.trim().toLowerCase(),n=Math.min(2,Math.max(1,Math.ceil(t.length/4))),r=ts.map(([i,o,a])=>({action:o,flag:a,distance:Nr(t,i,n)})).filter(i=>i.distance!==null).sort((i,o)=>i.distance-o.distance)[0];return r?{action:r.action,flag:r.flag}:null},Tu=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",r=Au(e);if(!r)return new m(`One action flag is required. Use one of: ${mu}. Bare \`pm package\` and \`pm extension\` default to --explore.`,h.USAGE);let i=`pm ${n} ${r.flag}`;return Lr({command_path:n,display_name:`${n} lifecycle`,token_kind:"action",token:e,allowed:Object.keys(ss),retry_command:i,message_suffix:`. Did you mean "${r.flag}"?`,fallback_candidates:[{source:"lifecycle_action",command:i,reason:`nearest lifecycle action for "${e}"`}]})},Iu=[["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"},Ou=e=>ss[e]??null,Cu=(e,t)=>{let n=[...new Set(Iu.filter(([r])=>t[r]===!0).map(([,r])=>r))];if(n.length===0){if(e===void 0)return"explore";let r=Ou(e.trim().toLowerCase());if(r)return r;throw Tu(e,t)}if(n.length>1)throw new m("Extension action flags are mutually exclusive.",h.USAGE);return n[0]},Pu=e=>{let t=e.project===!0||e.local===!0,n=e.global===!0;if(t&&n)throw new m('Options "--project/--local" and "--global" are mutually exclusive.',h.USAGE);return n?"global":"project"},Ru=[e=>e?null:{status:"skipped_unmanaged",reason:"extension_not_managed"},e=>e&&!["github","npm"].includes(e.source.kind)?{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 Ru){let n=t(e);if(n)return n}return{status:"not_checked",reason:"no_update_check_recorded"}},ds=(e,t,n,r)=>{let i=n??{};return{name:e.name,directory:e.directory,version:e.version,entry:e.entry,scope:t,active:e.enabled,enabled:e.enabled,runtime_active:null,activation_status:"unknown",contributions:i.contributions,managed:!!n,source:i.source,update_available:i.update_available,last_update_check_at:i.last_update_check_at,last_update_remote_commit:i.last_update_remote_commit,last_update_remote_version:i.last_update_remote_version,update_error:i.update_error,...r.status==="failed"&&i.update_check_timeout_ms!==void 0?{update_check_timeout_ms:i.update_check_timeout_ms}:{},update_check_status:r.status,update_check_reason:r.reason}},Nu=(e,t,n,r)=>{let i=Object.assign({name:e,manifest_version:"unknown",manifest_entry:"unknown"},r),o=r?os(n,r.name):!1;return{warning:`extension_manifest_missing:${t}:${e}`,summary:ds({name:i.name,directory:e,version:i.manifest_version,entry:i.manifest_entry,enabled:o},t,r,cs(r))}},Lu=async(e,t,n,r,i,o)=>{let a=re.join(e,t),s=re.join(a,"manifest.json"),c=o.get(k(t));if(!await b(s))return Nu(t,n,r,c);let d=Symbol("invalid-extension-manifest-json"),l=await rt.readFile(s,"utf8").then(_=>JSON.parse(_)).catch(()=>d);if(l===d)return{warning:`extension_manifest_invalid_json:${n}:${t}`};let p=Ln(l);if(!p)return{warning:`extension_manifest_invalid:${n}:${t}`};let u=i.get(k(p.name))??o.get(k(t));return{summary:ds({name:p.name,directory:t,version:p.version,entry:p.entry,enabled:os(r,p.name)},n,u,cs(u))}},me=async(e,t,n,r)=>{if(!await b(e))return{extensions:[],warnings:[]};let o=(await rt.readdir(e,{withFileTypes:!0})).filter(l=>l.isDirectory()).map(l=>l.name).sort((l,p)=>l.localeCompare(p)),a=new Map(r.entries.map(l=>[k(l.name),l])),s=new Map(r.entries.map(l=>[k(l.directory),l])),c=[],d=[];for(let l of o){let p=await Lu(e,l,t,n,a,s);p.warning&&c.push(p.warning),p.summary&&d.push(p.summary)}return{extensions:d.sort((l,p)=>l.name.localeCompare(p.name)),warnings:c.sort((l,p)=>l.localeCompare(p))}},ju=Hr(),Du=(e,t)=>[t.package,t.kind==="builtin"?t.name:void 0].find(n=>n?.trim())?.trim()??e,Fu=(e,t,n,r)=>{let i=n.command_paths.map(s=>`pm ${s} --help`),o=r?.error.toLowerCase().includes("@unbrained/pm-cli")===!0,a=n.command_paths.length>0?[...i]:["Run pm package doctor --project --detail deep if expected package commands are missing."];return o&&a.unshift("Install @unbrained/pm-cli in the target workspace so declarative package runtime imports resolve, then reinstall the package."),{package_name:Du(e,t),extension_name:e,command_paths:n.command_paths,action_paths:n.action_paths,help_commands:i,next_steps:a,...o?{sdk_dependency_status:"missing"}:{}}},Mu=e=>{let t=e.trace,n={layer:e.layer,name:e.name,entry_path:e.entry_path,error:e.error};return t&&(n.trace=Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0)),t.missing_capability&&(n.missing_capability=t.missing_capability),t.hint&&(n.hint=t.hint)),n},ls=e=>e.map(t=>Mu(t)).sort((t,n)=>`${t.layer}:${t.name}`.localeCompare(`${n.layer}:${n.name}`)),ps=(e,t,n)=>{let r=k(e);return t.find(i=>(n===void 0||i.layer===n)&&k(i.name)===r)},Uu=(e,t,n,r)=>n.find(o=>o.scope===t&&k(o.name)===k(e))?.activation_status??(r?"failed":"unknown"),us=(e,t,n,r,i)=>ju.enqueue(async()=>{let o=process.env.PM_CLI_PACKAGE_ROOT,a=await rt.mkdtemp(re.join(t,".pm-module-graph-"));process.env.PM_CLI_PACKAGE_ROOT=xe(import.meta.url,["../.."]);try{let s=await be({pmRoot:e,settings:n,cwd:process.cwd(),noExtensions:i.noExtensions===!0,reload_token:fn(),cache_bust:!0,module_graph_snapshot_root:a}),c=await Se({...s}),d=[...s.failed.map(p=>({layer:p.layer,name:p.name,entry_path:p.entry_path,error:p.error})),...ls(c.failed)],l=Object.fromEntries(s.loaded.map(p=>[k(p.name),Gr(We(c,{extensionName:p.name}))]));return{installed:tn(r,s,c),warnings:[...s.warnings,...c.warnings],activation_failures:d,extensions_disabled:s.disabled_by_flag,item_type_registrations:c.registrations.item_types,contribution_inventories:l}}finally{await rt.rm(a,{recursive:!0,force:!0}),o===void 0?delete process.env.PM_CLI_PACKAGE_ROOT:process.env.PM_CLI_PACKAGE_ROOT=o}}),or=async(e,t,n,r)=>{let i=n.filter(c=>!c.managed),o=[...i].sort((c,d)=>{let l=c.name.localeCompare(d.name);return l!==0?l:c.directory.localeCompare(d.directory)}),a=r,s=[];for(let c of o){let d=re.join(e,c.directory),l=await Ze(d),p=T(),u={kind:"local",input:c.name,location:d};a=pt(a,{name:l.manifest.name,directory:c.directory,scope:t,manifest_version:l.manifest.version,manifest_entry:l.manifest.entry,capabilities:[...l.manifest.capabilities],contributions:l.manifest.contributions,installed_at:p,updated_at:p,source:u}),s.push({name:l.manifest.name,directory:c.directory,version:l.manifest.version,entry:l.manifest.entry,source:u})}return s.length>0&&await Qe(e,a),{state:a,adopted_entries:s,unmanaged_candidates:o,already_managed_count:n.length-i.length}},Gu=(e,t)=>{let n=M(process.cwd(),t.path),r=Ct(n,process.cwd()),i=e==="global"?Pe(process.cwd()):n,o=e==="global"?r.global:r.project;return{pm_root:n,scope:e,settings_root:i,selected_root:o,roots:r}},on=e=>{let t=[e.gh,e.github].filter(r=>typeof r=="string").map(r=>r.trim()).filter(Boolean),n=[...new Set(t)];if(n.length>1)throw new m('Options "--gh" and "--github" must match when both are provided.',h.USAGE);return n[0]},zu=e=>fu[e],Ju=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",r=e==="install"?"source":"name",i=`${n} ${r}`,o=zu(e),a=`<${r}>`,s=`pm ${n} ${o} ${a}`;throw new m(`Action "${e}" requires ${i} input.`,h.USAGE,{code:"missing_lifecycle_target",required:`Provide a ${r} target for ${e}.`,examples:[`pm ${n} ${e} ${a}`,s,`pm ${n} --help`],recovery:{attempted_command:`pm ${n} ${e}`,suggested_retry:s,fallback_candidates:[{source:"lifecycle_action",command:s,reason:`flag-form ${e} command with required ${r} target`}]}})},an=(e,t,n={})=>{let r=e?.trim();if(r)return r;if(t==="init")throw new m('Action "init" requires a scaffold target path (for example: pm package init ./my-package or pm extension init ./my-extension).',h.USAGE);return Ju(t,n)},qu=(e,t)=>{let n=new Set([...t.registrations.item_types.map(r=>({entry:r,count:r.types.length})),...t.registrations.item_fields.map(r=>({entry:r,count:r.fields.length}))].filter(({count:r})=>r>0).map(({entry:r})=>`${r.layer}:${k(r.name)}`));return e.loaded.filter(r=>(r.activation?.commands??[]).length>0).filter(r=>n.has(`${r.layer}:${k(r.name)}`)).map(r=>`extension_schema_narrow_activation:${r.layer}:${r.name}`).filter((r,i,o)=>o.indexOf(r)===i).sort((r,i)=>r.localeCompare(i))},Wu=(e,t)=>{let r=[{triggered:t.strictExit===!0||t.failOnWarn===!0,allowed:e==="doctor",message:"--strict-exit and --fail-on-warn are only valid with --doctor."},{triggered:t.trace===!0,allowed:e==="doctor",message:"--trace is only valid with --doctor."},{triggered:t.watch===!0,allowed:e==="reload",message:"--watch is only valid with --reload."},{triggered:t.runtimeProbe===!0,allowed:e==="manage",message:"--runtime-probe is only valid with --manage."},{triggered:t.fixManagedState===!0,allowed:e==="manage"||e==="doctor",message:"--fix-managed-state is only valid with --manage or --doctor."},{triggered:t.isolated===!0||t.ignoreGlobal===!0,allowed:e==="doctor",message:"--isolated and --ignore-global are only valid with --doctor."},{triggered:t.capability!==void 0,allowed:e==="init",message:"--capability is only valid with --init/--scaffold."},{triggered:t.declarative===!0,allowed:e==="init",message:"--declarative is only valid with --init/--scaffold."},{triggered:t.dryRun===!0,allowed:e==="migrate"||e==="install",message:"--dry-run is only valid with --migrate or --install."}].find(i=>i.triggered&&!i.allowed);if(r)throw new m(r.message,h.USAGE)},Bu=(e,t,n)=>{let r=String(e??"").trim().toLowerCase(),i=[n.init,n.scaffold].includes(!0);return({doctor:["doctor"],reload:["reload"],catalog:["catalog"],init:i?[]:["init","scaffold"]}[t]??[]).includes(r)?void 0:e},Hu=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},Ku=(e,t,n)=>{let r={ok:n,action:e.action,scope:e.scope,roots:Hu(e),warnings:[...new Set(e.warnings)].sort((i,o)=>i.localeCompare(o)),details:t};return e.action==="doctor"&&Object.defineProperty(r,hu,{value:!0,enumerable:!1,configurable:!1}),r},ar=async(e,t,n)=>{let r=Cu(e,t);Wu(r,t);let i=Bu(e,r,t),o=Pu(t),a=Gu(o,n),c={action:r,normalizedTarget:i,scope:o,resolvedRoots:a,warnings:[],options:t,global:n},l={...c,withResult:(p,u=!0)=>Ku(c,p,u)};return await za(()=>Am(l))},Vu=(e,t)=>{let n=t.vocabulary??"extension",r=e.target_path.replace(/\\/g,"/"),i=Pr(r),o={package:`Install dependencies: cd ${i}, then run "npm install"`,extension:`Install type-check dependencies: cd ${i}, then run "npm install -D typescript @types/node @unbrained/pm-cli"`},a={package:`Validate the package: cd ${i}, then run "npm run typecheck" and "npm test"`,extension:`Type-check the source (optional): cd ${i}, then run "npx tsc --noEmit"`},s=[];return[n==="package",t.declarative===!0].every(Boolean)&&s.push("Ensure the target workspace can resolve @unbrained/pm-cli before installing this declarative package."),[o[n],...s,`Install the scaffold: ${se(n==="package"?["install","--project",r]:["extension","--install","--project",r])}`,`Smoke-test command path: pm ${e.command_name}`,a[n],`Run diagnostics: ${n==="package"?"pm package doctor":"pm extension --doctor"} --project --detail summary`]},Xu=async e=>{let{action:t,normalizedTarget:n,options:r,withResult:i}=e;if([on(r),r.ref].filter(d=>typeof d=="string").map(d=>d.trim()).filter(Boolean).length>0)throw new m('Action "init" does not accept --gh/--github/--ref options.',h.USAGE);let s=an(n,t,r),c=await Mo(s,r.vocabulary??"extension",r.capability,r.declarative===!0);return i({scaffolded:c.created_directory||c.files.some(d=>d.status==="created"),extension:{name:c.extension_name,command:c.command_name},capability:c.capability,style:c.style,target_path:c.target_path,created_directory:c.created_directory,files:c.files,next_steps:Vu(c,r)})},Yu=async e=>{let{normalizedTarget:t,resolvedRoots:n,warnings:r,options:i,global:o,withResult:a}=e;if(t!==void 0)throw new m('Action "reload" does not accept a target argument.',h.USAGE);let s=await A(n.settings_root),c=fn(),d=await be({pmRoot:n.settings_root,settings:s,cwd:process.cwd(),noExtensions:o.noExtensions,reload_token:c,cache_bust:!0});r.push(...d.warnings);let l=await Se(d);r.push(...l.warnings);let p={reload:{token:c,cache_bust:!0,watch:i.watch===!0},loaded_count:d.loaded.length,failed_count:d.failed.length,activated_count:Math.max(0,d.loaded.length-l.failed.length),activation_failed_count:l.failed.length,loaded_extensions:d.loaded.map(u=>({name:u.name,layer:u.layer,version:u.version})),failed_extensions:d.failed.map(u=>({name:u.name,layer:u.layer,error:u.error})),activation_failures:l.failed.map(u=>({name:u.name,layer:u.layer,error:u.error}))};return i.watch===!0&&r.push("extension_reload_watch_hint:watch_mode_requested_non_interactive_single_pass_only"),a(p)},Zu=async e=>{let{normalizedTarget:t,scope:n,options:r,global:i,withResult:o}=e;if(typeof t=="string"&&t.length>0&&t!=="catalog")throw new m('Action "catalog" does not accept a package target.',h.USAGE);return o(await _o(n,i,r))},Qu=(e,t)=>({kind:"builtin",input:e,location:e,name:e,...t===null?{}:{package:t}}),em=e=>({kind:"local",input:e.input,location:e.absolute_path}),tm=(e,t)=>({kind:"npm",input:e.input,location:t.resolved_subpath??".",package:t.npm_package,version:t.npm_version}),nm=(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}),rm=(e,t,n,r)=>e?Qu(e,t):n.kind==="local"?em(n):n.kind==="npm"?tm(n,r):nm(n,r),im=(e,t,n,r)=>e?e.manifest_version!==t?{installed_at:e.installed_at,updated_at:r}:co(e.source,n)?{installed_at:e.installed_at,updated_at:e.updated_at}:{installed_at:e.installed_at,updated_at:r}:{installed_at:r,updated_at:r},om=async(e,t)=>{let{scope:n,resolvedRoots:r,warnings:i}=e,{validated:o,destinationDirectoryName:a}=t,s=await A(r.settings_root),c=await pe(r.selected_root);i.push(...c.warnings);let d=re.join(r.selected_root,a),l=await b(d),p=await et(o.directory,d);await rt.mkdir(r.selected_root,{recursive:!0});let u=rm(t.bundledAliasName,t.bundledPackageName,t.installSource,t.resolvedSource),_=c.state.entries.find(y=>k(y.name)===k(o.manifest.name)),g=im(_,o.manifest.version,u,T()),w=pt(c.state,{name:o.manifest.name,directory:a,scope:n,manifest_version:o.manifest.version,manifest_entry:o.manifest.entry,capabilities:[...o.manifest.capabilities],contributions:o.manifest.contributions,...g,source:u}),f=as(s,o.manifest.name);return p||await Qo(o.directory,d),await Xo(d),await Yo(d),await Qe(r.selected_root,w),f&&await ge(r.settings_root,s,"settings:write"),{settings:s,managedState:w,sourceRecord:u,destinationDirectory:d,destinationExists:l,installInPlace:p,activationChanged:f}},am=async(e,t,n)=>{let r=n.filter(i=>k(i.name)===k(t)).flatMap(i=>i.types.map(o=>({name:o.name,folder:o.folder})));return e.scope==="project"&&r.length>0&&await vt(e.resolvedRoots.pm_root,r,e.warnings,"install:type-folder"),r},sm=(e,t,n,r,i)=>{let o=ps(t,n.activation_failures,e.scope),a=Uu(t,e.scope,n.installed,o),s=[!n.extensions_disabled,a==="ok"].every(Boolean);s||e.warnings.push(`extension_install_activation_failed:${e.scope}:${t}:${a}`);let c={true:{status:"ok",blocking_failure_count:0},false:{status:"degraded",blocking_failure_count:1}};return{activated:s,status:a,failure:o,verification:{status:c[String(s)].status,target_pm_root:e.resolvedRoots.pm_root,activation_status:a,activated:s,registered_commands:r.command_paths,registered_actions:r.action_paths,registered_item_types:i,module_graph_verification:"fresh_in_topology_snapshot",health:c[String(s)]}}},cm=async(e,t)=>{let{scope:n,resolvedRoots:r,warnings:i,global:o,withResult:a}=e,{validated:s,destinationDirectoryName:c}=t;return Ya({selectedRoot:r.selected_root,settingsRoot:r.settings_root,destinationDirectory:re.join(r.selected_root,c),sourceDirectory:s.directory,scope:n},async()=>{let d=await om(e,t),l=await me(r.selected_root,n,d.settings,d.managedState);i.push(...l.warnings);let p=await us(r.pm_root,re.dirname(r.selected_root),d.settings,l.extensions,o);i.push(...p.warnings);let u=await am(e,s.manifest.name,p.item_type_registrations),_=Aa(s.manifest.name,p.installed),g=sm(e,s.manifest.name,p,_,u),w=p.contribution_inventories[k(s.manifest.name)];return w&&(d.managedState=await po(r.selected_root,d.managedState,s.manifest.name,w)),a({extension:{name:s.manifest.name,version:s.manifest.version,entry:s.manifest.entry,capabilities:s.manifest.capabilities,directory:c},source:d.sourceRecord,source_resolution:t.sourceResolution,...t.installPlan?{install_plan:t.installPlan}:{},destination_path:d.destinationDirectory,overwritten:[d.destinationExists,!d.installInPlace].every(Boolean),installed_in_place:d.installInPlace,activated:g.activated,settings_changed:d.activationChanged,runtime_activation_status:g.status,command_paths:_.command_paths,action_paths:_.action_paths,contributions:w,command_discovery:Fu(s.manifest.name,d.sourceRecord,_,g.failure),verification:g.verification,activation_diagnostics:{failed_count:p.activation_failures.length,failed:p.activation_failures,installed_extension_failed:g.failure??null}},g.activated)})},dm=async e=>{let{options:t,global:n,warnings:r,withResult:i}=e;if(typeof t.ref=="string"&&t.ref.trim().length>0)throw new m('Action "install all" does not accept --ref.',h.USAGE);let o=[],a=new Map;for(let s of await Wt()){let c=await ut(s),d=re.resolve(c),l=a.get(d);l===void 0&&(l=await ar(s,{...t,install:!0},n),a.set(d,l)),o.push({alias:s,result:l})}return r.push(...o.flatMap(s=>s.result.warnings)),i(Ka(o,t.dryRun===!0),o.every(s=>s.result.ok))},lm=async(e,t,n)=>{let{resolvedRoots:r}=e,{bundledAliasName:i,bundledPackageName:o,installSource:a,sourceResolution:s}=await ra(t,n,e.options.ref,(await pe(r.selected_root)).state.entries);if(s.ambiguous){let d=s.candidates.find(l=>l.kind==="npm");e.warnings.push(`extension_install_source_ambiguous:${t}:builtin:${i}:npm:${d.package}`)}let c=await Ao(a);try{let d=await Ze(c.directory,{source_kind:a.kind,source_input:a.input,source_root:c.source_root}),l=Jt(d.manifest.name),p=e.options.dryRun===!0||a.kind==="local"&&i===null?await ta(c,re.join(r.selected_root,l),e.scope,e.options.copyPlan):void 0;return e.options.dryRun===!0?e.withResult({dry_run:!0,installed:!1,activated:!1,extension:{name:d.manifest.name,version:d.manifest.version},source_resolution:s,install_plan:p}):await Xn(r.settings_root,l,()=>cm(e,{validated:d,destinationDirectoryName:l,bundledAliasName:i,bundledPackageName:o,sourceResolution:s,installSource:a,resolvedSource:c,installPlan:p}))}finally{c.cleanup&&await c.cleanup()}},pm=async e=>{let t=on(e.options),n=t??an(e.normalizedTarget,e.action,e.options);return[t===void 0,mo(n)].every(Boolean)?dm(e):lm(e,n,t)},um=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:i,options:o,withResult:a}=e;if(t!==void 0)throw new m('Action "adopt-all" does not accept a target argument.',h.USAGE);if(on(o)!==void 0||typeof o.ref=="string"&&o.ref.trim().length>0)throw new m('Action "adopt-all" does not accept --gh/--github/--ref options.',h.USAGE);let c=await A(r.settings_root),d=await pe(r.selected_root);i.push(...d.warnings);let l=await me(r.selected_root,n,c,d.state);i.push(...l.warnings);let p=await or(r.selected_root,n,l.extensions,d.state),u=await me(r.selected_root,n,c,p.state);i.push(...u.warnings);let _=nn(n,i,u.extensions,o);i.push(..._.warnings);let g=new Map(u.extensions.map(y=>[`${k(y.name)}:${k(y.directory)}`,y])),w=new Map(u.extensions.map(y=>[k(y.directory),y])),f=p.adopted_entries.map(y=>{let v=k(y.directory),x=g.get(`${k(y.name)}:${v}`)??w.get(v);return{...y,...ms(x)}});return a({adopted_all:f.length>0,adopted_count:f.length,already_managed_count:p.already_managed_count,extensions:f,triage:_,warning_codes:_.warning_codes,update_health_partial:_.update_health_partial,update_health_coverage:_.update_health_coverage})},ms=e=>({update_check_status:e?.update_check_status??null,update_check_reason:e?.update_check_reason??null}),mm=(e,t,n,r)=>{if(e===void 0)return{kind:"local",input:t,location:n};let i=mt(e,{forceGithub:!0,ref:r});if(i.kind!=="github")throw new m(`Invalid GitHub shorthand "${e}".`,h.USAGE);return{kind:"github",input:i.input,location:i.subpath??".",repository:i.repository,owner:i.owner,repo:i.repo,ref:i.ref,subpath:i.subpath}},fm=async e=>{let{action:t,normalizedTarget:n,scope:r,resolvedRoots:i,warnings:o,options:a,withResult:s}=e,c=an(n,t,a),d=on(a),l=await A(i.settings_root),p=await pe(i.selected_root);o.push(...p.warnings);let u=await me(i.selected_root,r,l,p.state);o.push(...u.warnings);let _=await is(u.extensions,c);if(!_)throw new m(`Installed extension "${c}" was not found in ${r} scope.`,h.NOT_FOUND);if(_.managed)return s({adopted:!1,already_managed:!0,extension:{name:_.name,directory:_.directory}});let g=re.join(i.selected_root,_.directory),w=await Ze(g),f=T(),y=mm(d,c,g,a.ref),v=pt(p.state,{name:w.manifest.name,directory:_.directory,scope:r,manifest_version:w.manifest.version,manifest_entry:w.manifest.entry,capabilities:[...w.manifest.capabilities],contributions:w.manifest.contributions,installed_at:f,updated_at:f,source:y});await Qe(i.selected_root,v);let x=await me(i.selected_root,r,l,v);o.push(...x.warnings);let S=x.extensions.find(L=>k(L.name)===k(w.manifest.name))??x.extensions.find(L=>k(L.directory)===k(_.directory));return s({adopted:!0,extension:{name:w.manifest.name,directory:_.directory,version:w.manifest.version,entry:w.manifest.entry},source:y,...ms(S)})},fs=async e=>{let{action:t,normalizedTarget:n,scope:r,resolvedRoots:i,warnings:o,options:a}=e,s=an(n,t,a),c=await A(i.settings_root),d=await pe(i.selected_root);o.push(...d.warnings);let l=await me(i.selected_root,r,c,d.state);o.push(...l.warnings);let p=await is(l.extensions,s);if(!p)throw new m(`Installed extension "${s}" was not found in ${r} scope.`,h.NOT_FOUND);return{settings:c,managedStateRead:d,candidate:p}},hm=async e=>{let{resolvedRoots:t,withResult:n}=e,{settings:r,managedStateRead:i,candidate:o}=await fs(e),a=re.join(t.selected_root,o.directory);await rt.rm(a,{recursive:!0,force:!0});let s={...i.state,updated_at:T(),entries:i.state.entries.filter(d=>k(d.name)!==k(o.name)&&k(d.directory)!==k(o.directory))};await Qe(t.selected_root,s);let c=$u(r,o.name);return c&&await ge(t.settings_root,r,"settings:write"),n({removed:!0,extension:{name:o.name,directory:o.directory},destination_path:a,settings_changed:c})},Za=async e=>{let{action:t,resolvedRoots:n,warnings:r,global:i,withResult:o}=e,{settings:a,candidate:s}=await fs(e),c=t==="activate"?as(a,s.name):Eu(a,s.name);c&&await ge(n.settings_root,a,"settings:write");let d=t==="activate"?await us(n.pm_root,re.dirname(n.selected_root),a,[s],i).then(l=>(r.push(...l.warnings),ps(s.name,l.activation_failures,e.scope))):void 0;return d&&r.push(`extension_activate_failed:${e.scope}:${s.name}`),o({extension:{name:s.name,directory:s.directory},active:t==="activate"&&d===void 0,runtime_active:t==="activate"&&d===void 0,activation_failure:d??null,settings_changed:c,settings:{enabled:[...a.extensions.enabled],disabled:[...a.extensions.disabled]}},d===void 0)},gm=(e,t,n,r,i,o)=>{let a=r==="package"?"package":"extension",s={package:"doctor",extension:"--doctor"}[a],c=i?.adopted_entries.length??0,d=[[o!==null,o??""],[t>0,`Run pm ${a} explore --project and pm ${a} explore --global to inspect load failures.`],[n>0,`Review activation failures in pm ${a} ${s} --detail deep output.`],[c>0,`Managed-state fix adopted ${c} extension(s).`]];return[...new Set([...e,...d.filter(([l])=>l).map(([,l])=>l)].map(l=>l.trim()).filter(l=>l.length>0))]},ir=e=>e.loaded.some(t=>t.layer==="global")||e.failed.some(t=>t.layer==="global")||e.warnings.some(t=>t.includes(":global:")),_m=(e,t,n,r)=>{if(e!=="project"||t||!ir(r))return null;let i=n==="package"?"package":"extension";return`Global ${i} registrations are included in project diagnostics. For hermetic ${i} smoke tests, rerun pm ${i} doctor --project --isolated --detail deep --trace, or set PM_GLOBAL_PATH to a temporary directory for the whole test process.`},ym=(e,t,n)=>{if(String(e??"").trim().length>0)throw new m('Action "doctor" does not accept a target argument.',h.USAGE);let r=[n.isolated,n.ignoreGlobal].includes(!0);if([r,t==="global"].every(Boolean))throw new m("--isolated and --ignore-global are only valid with project-scope doctor diagnostics.",h.USAGE);let i=xa(n.detail),o=n.trace===!0;if([o,i!=="deep"].every(Boolean))throw new m("--trace requires --detail deep with --doctor.",h.USAGE);return{isolated:r,detailMode:i,includeTrace:o}},wm=async(e,t,n)=>{if(e.options.fixManagedState!==!0)return{state:n,fix:null};let r=await or(e.resolvedRoots.selected_root,e.scope,t,n);return{state:r.state,fix:r}},vm=(e,t,n,r)=>{let i=n==="package"?"package":"extension";if(e!=="project")return{isolated:t,global_extensions_included:!1,global_diagnostics_present:ir(r),rerun_command:null,pm_global_path_recipe:null};let o=`pm ${i} doctor --project --isolated --detail deep --trace`;return{isolated:t,global_extensions_included:!t,global_diagnostics_present:ir(r),rerun_command:t?null:o,pm_global_path_recipe:`PM_GLOBAL_PATH=$(mktemp -d) pm ${i} doctor --project --detail deep --trace`}},km=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:i,options:o,global:a,withResult:s}=e,{isolated:c,detailMode:d,includeTrace:l}=ym(t,n,o),p=await A(r.settings_root),u=await pe(r.selected_root);i.push(...u.warnings);let _=await me(r.selected_root,n,p,u.state);i.push(..._.warnings);let{state:g,fix:w}=await wm(e,_.extensions,u.state),f=await me(r.selected_root,n,p,g);i.push(...f.warnings);let y=await be({pmRoot:r.pm_root,settings:p,cwd:process.cwd(),noExtensions:a.noExtensions===!0,ignoreGlobalExtensions:c}),v=await Se({...y,loaded:y.loaded}),x=await Va(r.pm_root);i.push(...x.warnings,...y.warnings),i.push(...wa(y.failed)),i.push(...v.warnings),i.push(...va(v.failed)),i.push(...ka(y,v)),i.push(...Ta(v,y)),i.push(...qu(y,v)),i.push(...Ia(v));let S=tn(f.extensions,y,v),L=$a(n,S,y.loaded.map(I=>({layer:I.layer,name:I.name})),y.failed.map(I=>({name:I.name})),y.disabled_by_flag);i.push(...L.warnings);let F=S.filter(I=>I.update_check_status==="failed").map(I=>`extension_update_check_failed:${I.name}`);i.push(...F);let j=nn(n,i,S,o);i.push(...j.warnings);let E=[...j.warnings],J={mode:y.policy.mode,trust_mode:y.policy.trust_mode,require_provenance:y.policy.require_provenance,default_sandbox_profile:y.policy.default_sandbox_profile,sandbox_enforcement:"advisory: sandbox_profile/permissions are declaration-based load gates, not runtime isolation (ADR pm-6ef3)",trusted_extensions_count:y.policy.trusted_extensions.length,allowed_extensions_count:y.policy.allowed_extensions.length,blocked_extensions_count:y.policy.blocked_extensions.length,allowed_capabilities_count:y.policy.allowed_capabilities.length,blocked_capabilities_count:y.policy.blocked_capabilities.length,allowed_surfaces_count:y.policy.allowed_surfaces.length,blocked_surfaces_count:y.policy.blocked_surfaces.length,allowed_commands_count:y.policy.allowed_commands.length,blocked_commands_count:y.policy.blocked_commands.length,allowed_actions_count:y.policy.allowed_actions.length,blocked_actions_count:y.policy.blocked_actions.length,allowed_services_count:y.policy.allowed_services.length,blocked_services_count:y.policy.blocked_services.length,extension_override_count:y.policy.extension_overrides.length},it=Sa(E),cn=Ea(),_r=j.warning_codes,Vs=_m(n,c,o.vocabulary,y),Xs=gm(j.remediation,y.failed.length,v.failed.length,o.vocabulary,w,Vs),yr=vm(n,c,o.vocabulary,y),Ys={status:j.status,scope:n,warning_count:j.warning_count,warning_codes:_r,total_extensions:S.length,managed_total:S.filter(I=>I.managed).length,enabled_total:S.filter(I=>I.enabled).length,active_total:S.filter(I=>I.active).length,unmanaged_loaded_extension_count:j.unmanaged_loaded_extension_count,unmanaged_action_required_extension_count:j.unmanaged_action_required_extension_count,unmanaged_expected_extension_count:j.unmanaged_expected_extension_count,runtime_active_total:S.filter(I=>I.runtime_active===!0).length,activation_status_totals:{ok:S.filter(I=>I.activation_status==="ok").length,failed:S.filter(I=>I.activation_status==="failed").length,not_loaded:S.filter(I=>I.activation_status==="not_loaded").length,unknown:S.filter(I=>I.activation_status==="unknown").length},unknown_capability_count:it.length,capability_contract_version:cn.version,update_available_total:j.update_available_total,update_check_status_totals:j.update_check_status_totals,update_health_coverage:j.update_health_coverage,update_health_partial:j.update_health_partial,update_check_failed_total:S.filter(I=>I.update_check_status==="failed").length,load_failure_count:y.failed.length,activation_failure_count:v.failed.length,load_failures:Qn(y.failed),activation_failures:Qn(v.failed),blocking_failure_count:y.failed.length+v.failed.length,has_blocking_failures:y.failed.length+v.failed.length>0,consistency_warning_count:L.warnings.length,trace_enabled:l,isolation:yr,policy:J,remediation:Xs},Zs=w?{requested:!0,applied:w.adopted_entries.length>0,adopted_count:w.adopted_entries.length,already_managed_count:w.already_managed_count,adopted_extensions:w.adopted_entries.map(I=>I.name)}:{requested:!1,applied:!1,adopted_count:0,already_managed_count:f.extensions.filter(I=>I.managed).length,adopted_extensions:[]},dn={mode:d,summary:Ys,triage:j,trace_enabled:l,capability_contract:cn,capability_guidance:it,managed_state_fix:Zs,author_manifest:x,isolation:yr,policy:y.policy};if(d==="deep"){let I=l?v.failed:v.failed.map(R=>{let{trace:hf,...Qs}=R;return Qs});dn.deep={warnings:E,warning_codes:_r,capability_contract:cn,capability_guidance:it,trace_enabled:l,managed_state:{path:u.path,count:g.entries.length,entries:g.entries},installed_extensions:S,load:{roots:y.roots,policy:y.policy,warnings:y.warnings,failed:y.failed,loaded:y.loaded.map(R=>({layer:R.layer,directory:R.directory,name:R.name,version:R.version,entry:R.entry,priority:R.priority}))},activation:{failed:I,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:L.summary},l&&(dn.deep.trace={activation_failures:v.failed.filter(R=>R.trace!==void 0).map(R=>({layer:R.layer,name:R.name,entry_path:R.entry_path,error:R.error,method:R.trace.method,command:R.trace.command,capability:R.trace.capability,missing_capability:R.trace.missing_capability,registration_index:R.trace.registration_index,expected_schema:R.trace.expected_schema,hint:R.trace.hint,received:R.trace.received}))})}return s(dn)},xm=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:i,options:o,global:a,withResult:s}=e,c=await A(r.settings_root),d=await be({pmRoot:r.pm_root,settings:c,cwd:process.cwd(),noExtensions:a.noExtensions===!0}),l=await Se(d);i.push(...d.warnings),i.push(...l.warnings);let p=Jo(t,d,l);if(t!==void 0&&p.extensions.length===0){let u=o.vocabulary==="package"?"package":"extension",_=[...new Set(d.loaded.map(w=>o.vocabulary==="package"&&typeof w.source_package=="string"&&w.source_package.trim().length>0?w.source_package.trim():w.name))].sort((w,f)=>w.localeCompare(f)),g=_.length>0?` Loaded ${u} names: ${_.join(", ")}.`:"";throw new m(`No loaded ${u} named "${t}" was found in ${n} scope.${g} Run pm ${u} explore to list discovered ${u}s.`,h.NOT_FOUND)}return s({target:p.target,total:p.total,extensions:p.extensions,union:p.union,command_ownership:p.command_ownership})},bm=async(e,t,n)=>{let r=n,i=null;if([e.action==="manage",e.options.fixManagedState===!0].every(Boolean)&&(i=await or(e.resolvedRoots.selected_root,e.scope,t,n),r=i.state),e.action==="manage"){let o=e.options.fixManagedState===!0;r=await Ha(r,e.options.offline,o?tr:tt(),!o)}return{state:r,fix:i}},Sm=async(e,t,n)=>{let r=await be({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),i=await Se({...r,loaded:r.loaded});return e.warnings.push(...r.warnings,...i.warnings),{installed:tn(n,r,i),failures:ls(i.failed),summary:{requested:!0,executed:!0,reason:e.action==="explore"?"explore_defaults_to_runtime_probe":e.options.runtimeProbe===!0?"runtime_probe_requested":"manage_defaults_to_runtime_probe",load_failure_count:r.failed.length,activation_failure_count:i.failed.length,warning_count:[...new Set([...r.warnings,...i.warnings])].length,policy:r.policy}}},Em=(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},Qa=async e=>{let{action:t,scope:n,resolvedRoots:r,warnings:i,options:o,withResult:a}=e,s=await A(r.settings_root),c=Su(s.extensions.policy),d=await pe(r.selected_root);i.push(...d.warnings);let l=await me(r.selected_root,n,s,d.state);i.push(...l.warnings);let{state:p,fix:u}=await bm(e,l.extensions,d.state),_=await me(r.selected_root,n,s,p);if(i.push(..._.warnings),t==="manage"&&o.offline===!0)for(let v of _.extensions)v.managed&&["npm","github"].includes(v.source.kind)&&(v.update_check_reason="offline_requested");if(t==="manage"){let v=_.extensions.filter(x=>x.update_check_status==="failed").map(x=>`extension_update_check_failed:${x.name}`);i.push(...v)}let g=await Sm(e,s,_.extensions),w=g.installed,f=nn(n,i,w,o);i.push(...f.warnings);let y={total:w.length,managed_total:w.filter(v=>v.managed).length,enabled_total:w.filter(v=>v.enabled).length,active_total:w.filter(v=>v.active).length,extensions:w,triage:f,policy:c};return g.failures!==void 0&&(y.activation_diagnostics={failed_count:g.failures.length,failed:g.failures}),t==="explore"&&(y.runtime_probe=g.summary),t==="manage"&&(y.runtime_probe=g.summary,y.managed_state_fix=Em(u,w)),a(y)},es={init:Xu,install:pm,uninstall:hm,explore:Qa,manage:Qa,describe:xm,reload:Yu,doctor:km,catalog:Zu,adopt:fm,"adopt-all":um,activate:Za,deactivate:Za,migrate:Fi},$m=e=>[e.action==="uninstall",e.action==="adopt",e.action==="adopt-all",e.action==="activate",e.action==="deactivate",e.action==="migrate",[["doctor","manage"].includes(e.action),e.options.fixManagedState===!0].every(Boolean)].some(Boolean),Am=e=>$m(e)?Xn(e.resolvedRoots.settings_root,`${e.action}-state`,()=>es[e.action](e)):es[e.action](e);import dr from"node:fs/promises";import z from"node:path";import hs from"node:readline/promises";import{stdin as gs,stdout as bt}from"node:process";var _s=["ask","add","skip","status"],Tm=["AGENTS.md","CLAUDE.md"],Im=["pm init","pm context","pm search","pm create","pm claim","pm files","pm docs","pm test --run","pm close","pm release","pm_author"],Om=8,lr=1,Cm="<!-- pm-cli:agent-guidance:start:",Pm=`<!-- pm-cli:agent-guidance:start:v${lr} -->`,sr="<!-- pm-cli:agent-guidance:end -->",Et="Add workflow guidance later: pm init --agent-guidance add",Pv={toPortableRelativePath:Ue,ensureTrailingNewline:cr,detectLineEnding:ws,findGuidanceBlockRange:pr,buildAgentGuidanceBlock:vs,upsertAgentGuidanceBlock:ur,resolveProjectRoot:xs,resolveTargetGuidancePath:bs,parsePromptChoice:Ss,pushUnique:Ce,promptForGuidanceWrite:Es,normalizeAgentGuidanceState:mr,applyAgentGuidanceState:As,writeGuidanceFile:fr,setAgentGuidanceReadlineFactoryForTests:Rm},ys=()=>hs.createInterface({input:gs,output:bt});function Rm(e){ys=e??(()=>hs.createInterface({input:gs,output:bt}))}function Ue(e,t){let n=z.relative(e,t);return n.length===0?z.basename(t):n.split(z.sep).join("/")}function cr(e){return e.endsWith(`
|
|
40
|
+
`)?e:`${e}
|
|
41
|
+
`}function ws(e){return e.includes(`\r
|
|
42
|
+
`)?`\r
|
|
43
|
+
`:`
|
|
44
|
+
`}function pr(e){let t=e.indexOf(Cm);if(t===-1)return null;let n=e.indexOf(sr,t);return n===-1?null:{start_index:t,end_index:n+sr.length}}function Nm(e){return pr(e)!==null}function vs(e,t="<your project test command>"){return[Pm,"## pm Workflow (Agent Quickstart)","",'- Cold start with the measured canonical orientation: `pm context --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: `pm claim <id> --start`, or `pm claim --next --start` to take the next available item in one write.",`- 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.","",sr,""].join(e)}function ur(e,t="<your project test command>"){let n=ws(e),r=vs(n,t),i=pr(e);if(i){let s=e.slice(i.end_index),c=s.startsWith(`\r
|
|
45
|
+
`)?s.slice(2):s.startsWith(`
|
|
46
|
+
`)?s.slice(1):s,d=cr(`${e.slice(0,i.start_index)}${r}${c}`);return{next_content:d,changed:d!==e}}let o=e.length===0?"":e.endsWith(`
|
|
47
|
+
`)?`
|
|
48
|
+
`:`
|
|
49
|
+
|
|
50
|
+
`,a=cr(`${e}${o}${r}`);return{next_content:a,changed:a!==e}}async function ks(e){if(await b(z.join(e,"scripts","run-tests.mjs")))return"node scripts/run-tests.mjs test";let t;try{t=JSON.parse(await dr.readFile(z.join(e,"package.json"),"utf8"))}catch{return"<your project test command>"}let n=Lm(t);if(n===void 0)return"<your project test command>";let r=n.packageManager?.split("@")[0];return r==="pnpm"?"pnpm test":r==="bun"?"bun run test":r==="yarn"?"yarn test":r==="npm"?"npm test":await b(z.join(e,"pnpm-lock.yaml"))?"pnpm test":await b(z.join(e,"bun.lock"))||await b(z.join(e,"bun.lockb"))?"bun run test":await b(z.join(e,"yarn.lock"))?"yarn test":"npm test"}function Lm(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 xs(e,t){let n=z.dirname(e);return z.basename(e)==="pm"&&z.basename(n)===".agents"?z.dirname(n):z.resolve(t,e)}function bs(e,t){let n=e.find(i=>z.basename(i.file_path)==="AGENTS.md"&&i.exists);if(n)return n.file_path;let r=e.find(i=>i.exists);return r?r.file_path:z.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=ys();try{bt.write(`
|
|
51
|
+
Agent guidance check
|
|
52
|
+
`),bt.write(`No AGENTS.md/CLAUDE.md file currently contains compact pm workflow guidance.
|
|
53
|
+
`);let n=await t.question(`Add a compact pm workflow section to ${e}? [Y/n] `);return bt.write(`
|
|
54
|
+
`),Ss(n,!0)}finally{t.close()}}function mr(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:lr,last_checked_files:Array.isArray(t?.last_checked_files)?[...new Set(t.last_checked_files.map(n=>n.trim()).filter(n=>n.length>0))].sort((n,r)=>n.localeCompare(r)):[]}}async function $s(e){let t=[],n=await ks(e);for(let r of Tm){let i=z.join(e,r),o=await b(i);if(!o){t.push({file_path:i,exists:o,has_guidance:!1,has_marker:!1});continue}let a=await dr.readFile(i,"utf8"),s=a.toLowerCase(),c=Im.filter(l=>s.includes(l)),d=Nm(a);t.push({file_path:i,exists:o,has_guidance:d||c.length>=Om,has_marker:d,outdated:d&&ur(a,n).changed})}return t}function Ce(e,t){e.includes(t)||e.push(t)}function As(e,t){let n=mr(e),r=JSON.stringify(n)!==JSON.stringify(t);return r&&(e.agent_guidance=t),{changed:r,state:t}}async function fr(e,t=z.dirname(e)){let r=await b(e)?await dr.readFile(e,"utf8"):"",i=ur(r,await ks(t));return i.changed?(await fe(e,i.next_content),{changed:!0,warnings:await H({path:e,scope:"project",op:"init:agent_guidance_file"})}):{changed:!1,warnings:[]}}function jm(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=>Ue(e.projectRoot,t.file_path)),files_with_guidance:e.scans.filter(t=>t.has_guidance).map(t=>Ue(e.projectRoot,t.file_path)),missing_files:e.scans.filter(t=>!t.exists).map(t=>Ue(e.projectRoot,t.file_path))}}async function Dm(e,t,n){return e?await $s(n):t}function St(e,t,n){e.state={...e.state,...n,template_version:lr,last_checked_files:t}}async function Ts(e,t){if(t.presentBefore)return;let n=await fr(t.targetPath,t.projectRoot);e.warnings.push(...n.warnings),n.changed&&(e.applied=!0,e.warnings.push(`agent_guidance:added:${t.targetRelativePath}`))}function Fm(e,t){t||(e.warnings.push("agent_guidance:missing"),Ce(e.nextSteps,Et))}function Mm(e,t){e.skipped=!0,St(e,t,{prompt_completed:!0,declined:!0,declined_at:e.state.declined_at||new Date().toISOString()}),e.warnings.push("agent_guidance:explicit_skip"),Ce(e.nextSteps,Et)}async function Um(e,t){await Ts(e,t),St(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""})}function Gm(e,t){e.state.declined&&St(e,t,{prompt_completed:!0,declined:!1,declined_at:""})}function zm(e){e.skipped=!0,e.warnings.push("agent_guidance:skipped_declined"),Ce(e.nextSteps,Et)}async function Jm(e,t){if(e.prompted=!0,await Es(t.targetRelativePath)){await Ts(e,t),St(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""});return}e.skipped=!0,St(e,t.checkedFiles,{prompt_completed:!0,declined:!0,declined_at:new Date().toISOString()}),e.warnings.push("agent_guidance:declined"),Ce(e.nextSteps,Et)}function qm(e){e.warnings.push("agent_guidance:missing_non_interactive"),Ce(e.nextSteps,"Inspect workflow guidance: pm init --agent-guidance status"),Ce(e.nextSteps,Et)}async function Wm(e,t){let n={warnings:[],nextSteps:[],prompted:!1,applied:!1,skipped:!1,state:e};return t.mode==="status"?(Fm(n,t.presentBefore),n):t.mode==="skip"?(Mm(n,t.checkedFiles),n):t.mode==="add"?(await Um(n,t),n):t.presentBefore?(Gm(n,t.checkedFiles),n):n.state.prompt_completed&&n.state.declined?(zm(n),n):t.interactive?(await Jm(n,t),n):(qm(n),n)}async function Is(e){let t=xs(e.pm_root,e.cwd),n=await $s(t),r=bs(n,t),i=Ue(t,r),o=n.map(p=>Ue(t,p.file_path)),a=n.some(p=>p.has_guidance),s=await Wm(mr(e.settings),{mode:e.mode,interactive:e.interactive,targetPath:r,targetRelativePath:i,checkedFiles:o,presentBefore:a,projectRoot:t});if(e.mode==="add")for(let p of n.filter(u=>u.outdated)){let u=await fr(p.file_path,t);s.applied||=u.changed,s.warnings.push(...u.warnings)}let c=As(e.settings,s.state);n=await Dm(s.applied,n,t);let d=n.filter(p=>p.outdated).map(p=>Ue(t,p.file_path));return d.length>0&&(s.warnings.push(`agent_guidance_outdated:${d.join(",")}`),Ce(s.nextSteps,"pm init --agent-guidance add")),{summary:jm({mode:e.mode,scans:n,projectRoot:t,targetRelativePath:i,prompted:s.prompted,applied:s.applied,skipped:s.skipped,state:s.state}),warnings:s.warnings,next_steps:s.nextSteps,settings_changed:c.changed}}import Bm from"node:fs/promises";import P from"node:path";import Cs from"node:readline/promises";import{stdin as Ps,stdout as Z}from"node:process";var Hm=Symbol.for("pm.sdk.init-invocation-cwd");function rk(e,t=!1){if(t){let n=e.warnings.filter(i=>!/^(?:already_exists:|updated:|registered_type_preset:)/u.test(i)),r=n.includes("agent_guidance:missing_non_interactive")?e.next_steps.filter(i=>i.includes("--agent-guidance")):[];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:[...r,...e.next_steps.filter(i=>!r.includes(i))].slice(0,3),...n.length>0?{warnings:n.join("; ")}:{},details:`${se(["--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 ik={normalizeInitGovernancePreset:hr,normalizeInitTypePreset:Ns,normalizeOptionalInitAuthor:Ls,normalizeInitAgentGuidanceMode:Fs,isPathLikeInitTarget:sn,resolveInitInvocation:js,resolveInitPrefixInput:Ds,parseYesNoChoice:Ms,applyGovernancePreset:gr,runInitWizard:Ws,setInitReadlineFactoryForTests:Km,summarizeInstalledPackages:Us,buildInitNextSteps:Hs,registerInitTypePreset:Gs,assertExplicitTrackerPathIsNotWorkspaceRoot:Js,isLikelyWorkspaceRoot:zs,installInitMergeFence:Ks},Rs=()=>Cs.createInterface({input:Ps,output:Z});function Km(e){Rs=e??(()=>Cs.createInterface({input:Ps,output:Z}))}function Vm(){return structuredClone(kr)}var Xm=["minimal","default","strict"];function hr(e){if(e===void 0)return;let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new m("--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 m(`Invalid --preset value "${e}". Allowed: ${Xm.join(", ")}`,h.USAGE)}function Ns(e){if(e!==void 0){if(e.trim().length===0)throw new m("--type-preset must not be empty",h.USAGE);try{return Yt(e)}catch{throw new m(`Invalid --type-preset value "${e}". Allowed: ${yt.join(", ")}`,h.USAGE)}}}function Ls(e){if(e===void 0)return;let t=e.trim();if(t.length===0)throw new m("--author must not be empty",h.USAGE);return t}function sn(e){if(e===void 0)return!1;let t=e.trim();return t.length===0?!1:P.isAbsolute(t)||/^[a-z]:/iu.test(t)||t.startsWith(".")||t.includes("/")||t.includes("\\")}function js(e,t,n,r){let i=r?.trim();if(r!==void 0&&i?.length===0)throw new m("--workspace must not be empty",h.USAGE);if(i!==void 0){if(t.path!==void 0||sn(n))throw new m("--workspace cannot be combined with --pm-path/--path or a path-like positional target.",h.USAGE);let d=P.resolve(e,i),l=P.join(d,".agents","pm");return{pmRoot:l,prefixArg:n,target:{mode:"workspace-path",tracker_root:l,workspace_root:d}}}if(t.path===void 0&&sn(n)){let d=P.resolve(e,n.trim());return{pmRoot:d,prefixArg:void 0,target:{mode:"tracker-path",tracker_root:d}}}let o=M(e,t.path),a=P.join(P.resolve(e),".agents","pm"),s=P.dirname(P.dirname(o)),c=P.resolve(o)===a?"current":"ancestor";return{pmRoot:o,prefixArg:n,target:t.path===void 0?{mode:"workspace-discovery",tracker_root:o,workspace_root:s,discovery:c,requested_cwd:P.resolve(e),...c==="ancestor"?{suggested_current_tracker_root:a}:{}}:{mode:"tracker-path",tracker_root:o}}}function Ds(e,t){if(t===void 0)return e;if(t.trim().length===0)throw new m("--id-prefix must not be empty",h.USAGE);if(sn(t))throw new m(`--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 m(`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 m("--agent-guidance must not be empty",h.USAGE);if(t==="ask"||t==="add"||t==="skip"||t==="status")return t;throw new m(`Invalid --agent-guidance value "${e}". Allowed: ${_s.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 gr(e,t){let n=vr[t];e.governance={preset:t,...n},e.validation.parent_reference=n.parent_reference,e.validation.metadata_profile=n.metadata_profile}function Ym(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Us(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(Ym).map(n=>({alias:typeof n.alias=="string"?n.alias:"",ok:n.ok===!0})):[]}}async function Gs(e,t,n){let r=V(t.schema),i=ee(e,r.files.types,X.types),a=ie(await U(i)),s=[],c=[];for(let d of wt(n)){let l=Ge(a,d);a=l.file,(l.replaced?c:s).push(l.definition.name)}return await Ee({pmRoot:e,filePath:i,raw:ce(a),op:"init:type-preset",author:q(void 0,t.author_default),lockTtlSeconds:t.locks.ttl_seconds,lockWaitMs:t.locks.wait_ms}),{name:n,registered:s,updated:c,file:i}}async function zs(e){let t=[".git","package.json","pnpm-workspace.yaml","AGENTS.md",P.join(".agents","pm")];for(let n of t)if(await b(P.join(e,n)))return!0;return!1}async function Js(e,t,n){if(!t||n||await b(P.join(e,"settings.json"))||!await zs(e))return;let r=P.join(e,".agents","pm");throw new m(`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 ${r} init --yes`,"pm init --yes",`pm --pm-path ${e} init --yes --force`],nextSteps:["Use --pm-path <repo>/.agents/pm for repository-local tracker storage.","Use PM_PATH only for sandboxed tests or explicit tracker roots.","Pass --force only when root-level tracker files are intentional."],recovery:{next_best_command:`pm --pm-path ${r} init --yes`}})}async function qs(e,t){let n=[],r=[];for(let i of t){let o=i?P.join(e,i):e,a=await b(o);await Bm.mkdir(o,{recursive:!0}),a?r.push(`already_exists:${o}`):n.push(o),r.push(...await H({path:o,scope:"project",op:"init:ensure_dir"}))}return{createdDirs:n,warnings:r}}async function Ws(e,t){let n=Rs(),r=t===void 0?2:3;try{Z.write(`pm init setup wizard (agent-optimized)
|
|
55
|
+
`),Z.write(`This walkthrough is non-destructive and each choice can be changed later with pm config.
|
|
56
|
+
|
|
57
|
+
`),Z.write(`1/${r} Item ID prefix
|
|
58
|
+
`),Z.write(`Prefix is prepended to generated IDs (for example pm-a1b2).
|
|
59
|
+
`);let i=await n.question(`Item ID prefix [${e}]: `),o=i.trim().length>0?$e(i):e;Z.write(`
|
|
60
|
+
2/${r} Governance preset
|
|
61
|
+
`),Z.write(`minimal: no ownership blocking, progressive create defaults, close validation off.
|
|
62
|
+
`),Z.write(`default: ownership conflict warnings, progressive create defaults, close validation warn.
|
|
63
|
+
`),Z.write(`strict: ownership blocking, strict create defaults, close validation strict.
|
|
64
|
+
`);let a=await n.question("Governance preset [minimal/default/strict] (default: minimal): "),s=a.trim().length>0?a.trim():"minimal",c="minimal";try{c=hr(s)}catch{Z.write(`Unrecognized governance preset "${s}"; using minimal.
|
|
65
|
+
`)}let d;if(t!==void 0){Z.write(`
|
|
66
|
+
3/3 Telemetry
|
|
67
|
+
`),Z.write(`Telemetry helps improve reliability. The choice applies to this CLI install; change it with pm config global set telemetry-tracking.
|
|
68
|
+
`);let l=await n.question(`Enable telemetry for this CLI install? [${t?"Y/n":"y/N"}] `);d=Ms(l,t)}return Z.write(`
|
|
69
|
+
`),{prefix:o,preset:c,telemetry_enabled:d}}finally{n.close()}}function Zm(e){return{presetFromOption:hr(e.preset),useDefaults:e.defaults===!0,authorFromOption:Ls(e.author),installBundledPackages:e.withPackages===!0,agentGuidanceMode:Fs(e.agentGuidance),typePreset:Ns(e.typePreset)}}function Qm(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 ef(e,t,n,r){if(t.length===0||n)return;let i=r.discovery==="ancestor";throw new m(`${i?`No tracker exists in ${r.requested_cwd}; pm init found an ancestor tracker at ${r.tracker_root}. `:""}Refusing to update existing tracker settings at ${e} without --force.`,h.USAGE,{code:"init_existing_settings_requires_force",type:"urn:pm-cli:error:init_existing_settings_requires_force",required:`--force for ${t.join(", ")}`,why:i?"Ancestor discovery is useful for normal commands, but init must make the selected existing workspace explicit before changing its identity or policy settings.":"pm init is safe to rerun, but changing id prefix, governance preset, or default author on an existing tracker can corrupt long-lived project context when an agent meant to initialize a sandbox path.",resolved_path:r.tracker_root,requested_path:r.requested_cwd,suggested_path:r.suggested_current_tracker_root,examples:["pm init --yes","pm init ./sandbox-pm --yes",...i?['pm init <name> --yes --pm-path "$PWD/.agents/pm"']:[],"pm init acme --yes --force"],nextSteps:[...i?['To create a new tracker in the current directory, rerun with --pm-path "$PWD/.agents/pm".']:[],"If you meant to initialize a sandbox tracker, pass a path-like positional such as ./sandbox-pm or /tmp/pm-test.","If you intentionally want to rewrite this existing tracker's init-managed settings, rerun with --force."]})}function tf(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&&(gr(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 nf(e){let t=await A(e.pmRoot);e.warnings.push(`already_exists:${e.settingsPath}`);let n=Qm({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption});return ef(e.settingsPath,n,e.options.force===!0,e.target),tf({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption,warnings:e.warnings})&&await ge(e.pmRoot,t),{settings:t,normalizedPrefix:e.normalizedPrefix,chosenPreset:e.normalizedOptions.presetFromOption,wizardUsed:!1}}async function rf(e){let t=e.normalizedPrefix,n=e.normalizedOptions.presetFromOption,r,i=!1;if(e.normalizedOptions.presetFromOption===void 0&&!e.normalizedOptions.useDefaults&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0){let d=await Ws(t,await of());t=d.prefix,n=d.preset,r=d.telemetry_enabled,i=!0}let o=n??"minimal",a=Vm();a.id_prefix=t,gr(a,o);let s=Fr()?.trim()||void 0;a.author_default=e.normalizedOptions.authorFromOption??s??"";let c=Bs(e.pmRoot);return r!==void 0&&(a.telemetry.enabled=r,a.telemetry.first_run_prompt_completed=!0),await ge(e.pmRoot,a,void 0,c),r!==void 0&&c.omitSections&&await af(r,e.warnings),{settings:a,normalizedPrefix:t,chosenPreset:n,wizardUsed:i}}function Bs(e){return P.resolve(e)===P.resolve(Pe(process.cwd()))?{}:{omitSections:["telemetry"]}}async function of(){let e=await A(Pe(process.cwd()));if(!(ui().telemetry_disabled||e.telemetry.first_run_prompt_completed||gn(e)))return e.telemetry.enabled}async function af(e,t){let n=Pe(process.cwd()),r=await A(n);if(gn(r)){t.push("telemetry_consent_not_recorded:global_settings_unreadable");return}let i=!1;r.telemetry.enabled=e,r.telemetry.first_run_prompt_completed=!0,await ge(n,r,"telemetry:first_run_prompt",{skipIfStored:o=>i=o.telemetry?.first_run_prompt_completed===!0}),i&&t.push("telemetry_consent_kept:recorded_while_prompting")}async function sf(e){let{telemetry:t}=await A(Pe(process.cwd()));return{...e,telemetry:{...e.telemetry,enabled:t.enabled,first_run_prompt_completed:t.first_run_prompt_completed,capture_level:t.capture_level}}}async function Os(e){return e.settingsExists?await nf(e):await rf({pmRoot:e.pmRoot,normalizedPrefix:e.normalizedPrefix,normalizedOptions:e.normalizedOptions,warnings:e.warnings})}async function cf(e){let t=await Is({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 ge(e.pmRoot,e.settings,void 0,Bs(e.pmRoot)),{...t.summary,next_steps:t.next_steps}}async function df(e,t){let n=[],r=[],i=await Dr(e,t.schema);for(let o of i.created_paths)n.push(o),r.push(...await H({path:o,scope:"project",op:"init:runtime_schema_file"}));return{createdDirs:n,warnings:r}}async function lf(e){if(e.typePreset===void 0)return;let t=await Gs(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 pf(e){let n=B(e.settings,W()).folders.filter(i=>!ln.includes(i)),r=await qs(e.pmRoot,n);e.createdDirs.push(...r.createdDirs),e.warnings.push(...r.warnings)}function uf(e){let t=P.resolve(e.tracker_root),n=P.dirname(t);return P.basename(t)==="pm"&&P.basename(n)===".agents"?P.dirname(n):e.workspace_root}async function mf(e,t,n,r){if(!e)return;let i=await ar("all",{install:!0,project:!0},{...t,path:n});r.push(...i.warnings);let o=Us(i),a=o.packages.filter(s=>!s.ok).map(s=>s.alias);if(!o.installed_all||a.length>0)throw new m(`pm init --with-packages did not install all bundled packages successfully${a.length>0?`: ${a.join(", ")}`:"."}`,h.GENERIC_FAILURE);return o}function Hs(e){let t=r=>se([...e.target.mode==="workspace-discovery"?[]:["--pm-path",e.target.tracker_root],...r]),n=[`Create your first item: ${t(["create","--type","Task","--title","<title>"])}`,`List active items: ${t(["list"])}`,`Get agent-friendly project context: ${t(["context"])}`];e.installBundledPackages?n.push(`Explore newly-available commands: ${t(["cal"])}, ${t(["templates"])}, ${t(["guide"])}`):(n.push(`Add optional packages for richer workflows: ${t(["install","calendar","--project"])}, ${t(["install","templates","--project"])}, ${t(["install","guide-shell","--project"])}`),n.push(`Or install everything bundled: ${t(["init","--with-packages"])} (idempotent on re-run)`)),e.registeredTypePreset&&n.push(`Inspect registered preset types: ${t(["schema","list"])}, ${t(["schema","show",e.registeredTypePreset.registered[0]??e.registeredTypePreset.updated[0]])}`),n.push("Supported agent harnesses are attributed automatically; use --author or PM_AUTHOR only when an explicit identity override is required.");for(let r of e.agentGuidanceNextSteps){let i=e.target.mode==="workspace-discovery"?r:r.replace(/\bpm (?=[a-z])/g,()=>`${t([])} `);n.includes(i)||n.push(i)}return n}async function Ks(e,t,n,r=ki){if(t===null){n.push("merge_fence_skipped:not_git_repository:run pm merge install after moving the tracker into a Git repository");return}try{let i=await r({pmRoot:e,workspaceRoot:t});i.gitattributes.changed&&n.push(`updated:merge_fence:${i.gitattributes.path}`)}catch(i){if(!(i instanceof m))throw i;n.push(`merge_fence_skipped:install_failed:${i.context.code??"pm_error"}:${i.message}:run pm merge install after resolving the Git repository error`)}}async function ff(e,t,n,r){if(e==null||n==="status")return;let i=await yi(e,{pmRoot:t});i.changed&&r.push(`updated:gitignore:${i.path}`)}async function ok(e,t,n={}){let r=t[Hm],i=typeof r=="string"?r:process.cwd(),o=js(i,t,e,n.workspace),a=o.pmRoot;e=Ds(o.prefixArg,n.idPrefix);let s=Zm(n);await Js(a,o.target.mode==="tracker-path",n.force===!0);let c=[],d=[],l=P.join(a,"settings.json"),p=await b(l),u;p&&(u=await Os({pmRoot:a,settingsPath:l,settingsExists:p,normalizedPrefix:$e(e),prefixArg:e,options:n,normalizedOptions:s,warnings:d,target:o.target}));let _=await qs(a,ln);c.push(..._.createdDirs),d.push(..._.warnings),u??=await Os({pmRoot:a,settingsPath:l,settingsExists:p,normalizedPrefix:$e(e),prefixArg:e,options:n,normalizedOptions:s,warnings:d,target:o.target});let{settings:g}=u,w=uf(o.target),f=await wi(w??P.dirname(a)),y=w??f,v=await cf({pmRoot:a,cwd:y??i,agentGuidanceMode:s.agentGuidanceMode,settings:g,warnings:d}),x=await df(a,g);c.push(...x.createdDirs),d.push(...x.warnings);let S=await lf({pmRoot:a,settings:g,typePreset:s.typePreset,warnings:d});S&&(g=await A(a)),await pf({pmRoot:a,settings:g,createdDirs:c,warnings:d}),await ff(y,a,s.agentGuidanceMode,d),!p&&n.mergeFence!==!1&&s.agentGuidanceMode!=="status"&&await Ks(a,f,d);let L=await mf(s.installBundledPackages,t,a,d),F=Hs({installBundledPackages:s.installBundledPackages,registeredTypePreset:S,agentGuidanceNextSteps:v.next_steps,target:o.target});return{ok:!0,path:a,target:o.target,settings:await sf(g),created_dirs:c,warnings:d,governance_preset:g.governance.preset,wizard_used:u.wizardUsed,...S?{registered_type_preset:S}:{},...L?{installed_packages:L}:{},next_steps:F,agent_guidance:v}}export{yf as a,vn as b,$n as c,Ni as d,Cf as e,uc as f,Pf as g,Tn as h,gc as i,_c as j,yc as k,Fi as l,op as m,We as n,Wi as o,Be as p,He as q,Bi as r,vc as s,qf as t,Kf as u,Gi as v,bc as w,dh as x,Zi as y,ro as z,td as A,nd as B,ly as C,py as D,uy as E,vt as F,my as G,fy as H,hy as I,gy as J,_y as K,yy as L,wy as M,vy as N,ky as O,xy as P,by as Q,Sy as R,Ey as S,$y as T,Ay as U,Ty as V,Iy as W,Oy as X,Cy as Y,Py as Z,Ry as _,Ny as $,Ly as aa,jy as ba,Dy as ca,Q as da,k as ea,Ln as fa,xd as ga,pe as ha,Gt as ia,rd as ja,ct as ka,zt as la,ko as ma,Oo as na,Kn as oa,Jo as pa,t_ as qa,ma as ra,Ap as sa,Sa as ta,Ea as ua,La as va,ta as wa,ep as xa,pu as ya,ra as za,ar as Aa,_s as Ba,Pv as Ca,Is as Da,Hm as Ea,rk as Fa,ik as Ga,ok as Ha};
|
|
70
|
+
//# sourceMappingURL=chunk-YW2HBHRO.js.map
|