@unbrained/pm-cli 2026.11.22 → 2026.11.23
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-2UQU7HRR.js +9 -0
- package/dist/cli-bundle/chunks/chunk-5DUP4AZA.js +2 -0
- package/dist/cli-bundle/chunks/chunk-5WZZ5XEN.js +3 -0
- package/dist/cli-bundle/chunks/chunk-6H36ZHMI.js +2 -0
- package/dist/cli-bundle/chunks/chunk-6MYJLOSG.js +2 -0
- package/dist/cli-bundle/chunks/chunk-AA52P34H.js +3 -0
- package/dist/cli-bundle/chunks/{chunk-B76TFRO2.js → chunk-AEOHUSUI.js} +101 -101
- package/dist/cli-bundle/chunks/chunk-BSRIVYTM.js +8 -0
- package/dist/cli-bundle/chunks/chunk-CFWLQFJM.js +71 -0
- package/dist/cli-bundle/chunks/chunk-D6PDUKUG.js +9 -0
- package/dist/cli-bundle/chunks/chunk-ENKXRSFZ.js +31 -0
- package/dist/cli-bundle/chunks/chunk-F2Z6XLZB.js +3 -0
- package/dist/cli-bundle/chunks/chunk-FJOEL75F.js +2 -0
- package/dist/cli-bundle/chunks/chunk-GDXCAC52.js +2 -0
- package/dist/cli-bundle/chunks/chunk-H7JEXRIN.js +6 -0
- package/dist/cli-bundle/chunks/chunk-J2PDAVBC.js +2 -0
- package/dist/cli-bundle/chunks/chunk-KE7HMBEW.js +2 -0
- package/dist/cli-bundle/chunks/chunk-KZHIBEJL.js +33 -0
- package/dist/cli-bundle/chunks/chunk-NGJ5ERBF.js +115 -0
- package/dist/cli-bundle/chunks/chunk-NQ54T7T2.js +2 -0
- package/dist/cli-bundle/chunks/chunk-O7JHS64G.js +3 -0
- package/dist/cli-bundle/chunks/chunk-OKEZF7HU.js +2 -0
- package/dist/cli-bundle/chunks/chunk-OKIKF4FD.js +2 -0
- package/dist/cli-bundle/chunks/chunk-OPJF254V.js +9 -0
- package/dist/cli-bundle/chunks/chunk-PZA7QECY.js +1 -0
- package/dist/cli-bundle/chunks/chunk-RWA5YZ5X.js +2 -0
- package/dist/cli-bundle/chunks/chunk-S32NGRQM.js +2 -0
- package/dist/cli-bundle/chunks/chunk-SLFRSZK6.js +1 -0
- package/dist/cli-bundle/chunks/chunk-TZY5MVJF.js +125 -0
- package/dist/cli-bundle/chunks/chunk-YYT3MIRF.js +3 -0
- package/dist/cli-bundle/chunks/chunk-ZPS4B6SI.js +8 -0
- package/dist/cli-bundle/chunks/context-budget-recovery-M5RFUEFG.js +2 -0
- package/dist/cli-bundle/chunks/indexed-receipt-blobs-BPYKN5Q7.js +4 -0
- package/dist/cli-bundle/chunks/{item-revision-4QBMZXKX.js → item-revision-FMD4KWBB.js} +2 -2
- package/dist/cli-bundle/chunks/item-transaction-SEHTH7N2.js +2 -0
- package/dist/cli-bundle/chunks/mutation-actor-SFGYIRPW.js +2 -0
- package/dist/cli-bundle/chunks/mutation-admission-57LBSKQI.js +2 -0
- package/dist/cli-bundle/chunks/{register-list-query-RR5KACJ3.js → register-list-query-L4IBU64P.js} +11 -11
- package/dist/cli-bundle/chunks/register-mutation-6NUOPHZ3.js +21 -0
- package/dist/cli-bundle/chunks/register-operations-JGYVORNN.js +2 -0
- package/dist/cli-bundle/chunks/register-setup-C44SIXEH.js +2 -0
- package/dist/cli-bundle/chunks/settlement-hook-6MR32OOC.js +7 -0
- package/dist/cli-bundle/chunks/stage-PQ7AB63N.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-6LKTEKHS.js +6 -0
- package/dist/cli-bundle/focused-chunks/chunk-6LPXMFLM.js +2 -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-BKPUUW5O.js +1 -0
- package/dist/cli-bundle/focused-chunks/chunk-BWOVFE5B.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-HMDQDRV2.js +8 -0
- package/dist/cli-bundle/focused-chunks/chunk-I66IKYKP.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-IIP6LZ5E.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-IR2J3NOT.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-IROZDIDX.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-ITKDHSBR.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-K53OIT5J.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-LQYYPXUK.js +26 -0
- package/dist/cli-bundle/focused-chunks/chunk-NQTEE66P.js +13 -0
- package/dist/cli-bundle/focused-chunks/chunk-O7Z73ALG.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-OTMMOKPM.js +91 -0
- package/dist/cli-bundle/focused-chunks/chunk-OXOCZJC6.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-QLAHEDT6.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-QQIIMMFU.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-RIE3SJSE.js +9 -0
- package/dist/cli-bundle/focused-chunks/chunk-TD544C74.js +8 -0
- package/dist/cli-bundle/focused-chunks/chunk-UFTUNBMY.js +27 -0
- package/dist/cli-bundle/focused-chunks/chunk-X6CXWWNB.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-XRS3VNC6.js +44 -0
- package/dist/cli-bundle/focused-chunks/chunk-XYPEZGTR.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-Y2ESLKCF.js +8 -0
- package/dist/cli-bundle/focused-chunks/chunk-YSJKQLFR.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-Z2X7HH3C.js +102 -0
- package/dist/cli-bundle/focused-chunks/chunk-ZHWPCVQL.js +78 -0
- package/dist/cli-bundle/focused-chunks/context-budget-recovery-CSJV3TY3.js +2 -0
- package/dist/cli-bundle/focused-chunks/indexed-receipt-blobs-EGEJMG3G.js +4 -0
- package/dist/cli-bundle/focused-chunks/{item-revision-2O6MLPEX.js → item-revision-YDACCDVY.js} +2 -2
- package/dist/cli-bundle/focused-chunks/item-transaction-UKEQCTKB.js +2 -0
- package/dist/cli-bundle/focused-chunks/mutation-actor-AS465LRX.js +2 -0
- package/dist/cli-bundle/focused-chunks/mutation-admission-E5UHJZFE.js +2 -0
- package/dist/cli-bundle/focused-chunks/settlement-hook-FMLGKG7J.js +7 -0
- package/dist/cli-bundle/focused-chunks/stage-36J7YLGI.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 +12 -12
- 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.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.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/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.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-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 +1 -1
- package/docs/SDK.md +74 -4
- 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-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,31 @@
|
|
|
1
|
+
import{a as Uh}from"./chunk-5DUP4AZA.js";import{J as yh,a as Ai,b as Lr,c as Ci,d as $e,e as Ti,f as ph,g as _h,h as Ri,i as $r,j as hh,k as gh,l as Sc,m as Ec,n as Nr,r as Mr,t as Ii,u as te,y as Ac}from"./chunk-FJOEL75F.js";import{Aa as Lh,Ba as Ic,C as Oh,Ca as Oc,Da as Lc,Ga as $h,La as Nh,Pa as $c,j as wp,pa as Tc,y as Ih,za as Rc}from"./chunk-CFWLQFJM.js";import{a as jr,b as Ch,i as Pt,k as Fn,l as Dn,m as jn}from"./chunk-BSRIVYTM.js";import{c as Ah}from"./chunk-D6PDUKUG.js";import{A as Pn,B as de,D as Oi,G as Li,H as bh,Ha as Fh,Ia as Dh,J as Cc,Ja as Ur,K as xh,Ka as Nc,M as Sh,Na as jh,Nc as Kh,Qc as zh,U as Eh,_a as Gr,bb as Un,eb as Gn,l as wh,lb as $i,o as vh,oa as Mh,p as Pr,pa as Ph,pb as Gh,qb as qh,s as kh,wb as Wh,y as Fr,z as Dr}from"./chunk-KZHIBEJL.js";import{a as yp}from"./chunk-S32NGRQM.js";import{$ as hc,$a as G_,$b as Si,Aa as w_,Ab as rh,B as pc,Bb as sh,C as _c,D as Ap,E as xi,Ea as v_,F as Cp,Fa as k_,G as Tp,Ga as b_,H as Rp,Ha as x_,I as Ip,Ia as S_,J as Op,Ja as E_,K as Lp,Ka as A_,L as $p,La as C_,M as Np,Ma as T_,N as Mp,Na as R_,O as Pp,Oa as I_,P as Fp,Pa as O_,Q as Dp,Qa as L_,R as jp,Ra as $_,S as Up,Sa as N_,T as Gp,Ta as M_,U as qp,Ua as P_,V as Wp,Va as F_,W as Kp,Wa as yc,X as zp,Xa as D_,Y as Bp,Ya as j_,Za as wc,_ as Hp,_a as U_,_b as ih,aa as Vp,ab as q_,ac as oh,b as vp,ba as Yp,bb as W_,bc,c as kp,ca as Jp,cb as K_,d as bp,da as Xp,db as Mt,dc as ah,ea as Qp,eb as z_,ec as ch,fa as Zp,fb as B_,ga as e_,gb as H_,gc as dh,ha as t_,hb as V_,hc as lh,ia as n_,ic as Ei,ja as r_,jb as Y_,jc as uh,ka as s_,la as i_,lb as Or,ma as o_,na as a_,nb as J_,o as mc,oa as c_,ob as X_,p as xp,pa as gc,pb as Q_,pc as xc,qa as d_,qb as Z_,ra as l_,s as Sp,sa as u_,sb as eh,t as fc,ta as m_,tc as mh,u as nn,ua as f_,va as p_,w as Ep,wa as __,wb as vc,wc as fh,xa as h_,xb as th,ya as g_,yb as nh,za as y_,zb as kc}from"./chunk-OPJF254V.js";import{d as fp,j as pp,r as _p,s as tn,t as hp,w as gp}from"./chunk-6MYJLOSG.js";import{$b as np,A as Tn,Ab as he,B as we,Ba as Rr,C as Gs,Cb as ic,D as Ya,Db as Xf,Dd as bi,E as wr,Ed as mp,F as vr,G as kr,H as gt,I as Lm,J as Vs,La as yi,Nb as Qf,Oa as Mn,Pa as Ff,Qa as Df,R as Qs,Ra as qf,Rc as ac,Sb as Zf,Sc as cc,T as Ot,Tc as dc,U as li,Ub as ep,Uc as lc,V as ui,Xb as oc,Y as $f,Ya as Wf,Zb as tp,ac as $t,bc as rp,c as at,cc as Nt,dc as Ir,e as ct,eb as Kf,ec as en,f as An,g as ja,ga as mi,gc as sp,h as am,i as Fs,ib as Bf,j as Ds,jb as Hf,jd as ap,k as cm,ka as Ze,l as js,la as Nf,m as dm,mb as Vf,n as lm,na as fi,nb as wi,o as ee,oa as Mf,ob as Yf,od as uc,p as Cn,pa as pi,pc as ip,q as hr,qa as _i,qb as Y,r as be,ra as hi,rb as fe,rd as cp,tb as vi,tc as op,ub as Ae,v as dt,va as gi,vb as wt,wb as Jf,wd as dp,x as Bt,xb as Zt,xd as lp,ya as Pf,yd as ki,z as Us,zb as Lt,zd as up}from"./chunk-TZY5MVJF.js";import{C as zf,I as j,a as Qt,b as Tr,e as $n,f as Nn,g as sc,l as jf,u as Uf,v as C,w as Gf}from"./chunk-2UQU7HRR.js";import{$a as bm,$b as Mm,$c as _e,$h as bf,Ac as Zs,Ad as oi,Af as mf,Aj as yt,B as Qu,Bb as $m,Bd as ai,C as Zu,D as em,Db as Vt,Dc as z,Dj as Rf,E as tm,Ec as Qe,Ei as Cr,Ej as He,F as nm,Fa as Wa,Fc as Yt,Ff as rc,Fh as yf,G as rm,Ga as gr,Gh as wf,Gj as If,H as ot,Ha as Ie,Hc as It,Hh as vf,Hj as Of,I as sm,Ic as jm,Id as sf,Ij as Lf,Jb as ie,Jc as Qa,Ka as D,Kc as Um,La as _t,Lc as Za,Ld as xr,Ma as Ks,Mb as Ys,Mc as Gm,Md as Sr,Mh as Er,Na as In,Nc as ei,O as im,Oa as yr,P as om,Pa as Ht,Pc as qm,Q as Da,Qc as Wm,Qe as cf,Qg as hf,Rc as Km,Re as df,Rh as kf,Sa as I,Sc as ti,Ta as lt,Tc as br,Ua as Xe,Va as Oe,Vc as ni,Wa as wm,Wd as of,Xa as vm,Ya as ht,Yb as O,Yc as ri,Yi as ci,Za as zs,Zb as Nm,Zc as ce,_a as km,_b as Ja,_c as Jt,_i as di,a as Z,ab as Ka,ac as Js,ad as ec,ae as nc,af as lf,b as Ue,bb as za,bd as tc,be as G,bi as xf,c as Ju,cb as xm,cc as me,cd as zm,cg as ff,db as Sm,dc as Pm,dg as pf,di as Ar,e as Xu,eb as Em,ec as On,ed as si,fa as Ua,fb as Am,fc as Xa,fi as Sf,gb as Cm,gc as Xs,gd as Bm,ge as Xt,hb as Tm,hd as Ln,hg as _f,hj as Af,ib as Ba,id as Hm,ii as Ef,ja as Ga,jd as Vm,ka as Be,kb as Rm,kd as Ym,la as qs,lb as L,ld as Jm,ma as Ws,mc as Fm,mh as gf,na as mm,nd as ii,ne as af,ob as Bs,od as Xm,pa as fm,pb as Ha,pd as Qm,pj as F,qa as pm,qb as Im,ra as _m,rb as Hs,sa as hm,sb as Om,t as it,tb as Va,ua as gm,v as K,va as ym,vc as Dm,vd as Zm,w as Ps,wa as qa,wd as ef,wf as uf,wj as Cf,x as zt,xd as tf,xj as Tf,yb as Le,yd as nf,zd as rf}from"./chunk-NGJ5ERBF.js";import{c as Th}from"./chunk-AA52P34H.js";import{a as Rh}from"./chunk-6H36ZHMI.js";import{A as m,C as p,D as Rt,E as se,F as Rn,G as U,H as Q,K as Ge,M as um,a as Ku,m as zu,p as Bu,s as Hu,u as Vu,w as Yu,x as Ms,y as Kt}from"./chunk-YYT3MIRF.js";var UE=Object.freeze({"--body":"Set the item body.","--body-file":"Read the item body from a file, or from stdin when set to -.","--description":"Set the item description.","--stdin":"Read the value from stdin.","--stdin-json":"Read a complete JSON document from stdin."}),GE=new Set(["--add","--body","--comment","--dep","--dep-remove","--description","--doc","--event","--field","--file","--learning","--note","--remove","--reminder","--test","--type-option"]),qE=new Set(["append","comments","create","docs","files","learnings","notes","test","update","update-many"]),WE=new Set(["close-many:--ids","comments:--file","create:--body-file","history-compact:--ids","learnings:--file","notes:--file","update:--body-file","update-many:--ids"]),KE=new Set(["close-many:--ids","history-compact:--ids","update-many:--ids"]),zE=["--allow-","--check-","--dry-run","--explain","--fail-","--fix-","--full","--has-","--include-","--json","--no-","--prune-","--quiet","--refresh-","--require-","--runtime-only","--schema-only","--skip-","--stream","--strict-","--summary","--today","--verbose"],BE=new Set(["--activate","--active-only","--adopt","--adopt-all","--all","--all-actionable","--all-affected-ids","--all-day","--all-streams","--acknowledge-linked-tests","--append-stable","--auto-fix","--auto-pm-context","--availability-only","--background","--brief","--by-assignee","--by-priority","--by-tag","--catalog","--claim","--clear","--clear-comments","--clear-criteria","--clear-deps","--clear-docs","--clear-events","--clear-files","--clear-learnings","--clear-notes","--clear-reminders","--clear-tests","--clear-type-options","--cli-only","--closed","--compact","--completion","--count","--counts","--deactivate","--declarative","--defaults","--describe","--diff","--doctor","--empty-body","--explore","--field-utilization","--filter-empty-body","--flags-only","--follow","--force","--global","--highlight","--hybrid","--id-only","--if-available","--ignore-global","--include_unparented","--infer","--init","--install","--isolated","--lean","--list","--local","--manage","--markdown","--metadata-coverage","--next","--normalize-provenance","--only","--only-last","--output-row-contract","--override-linked-pm-context","--override-linked-workspace-context","--packages-only","--past","--phrase-exact","--profile","--progress","--project","--promote-to-item-dep","--provenance","--provenance-summary","--raw","--ready-only","--ready_only","--rebuild","--recent","--reload","--repair","--replace-deps","--replace-docs","--replace-files","--replace-tests","--required","--required-on-create","--run","--runtime-probe","--save-baseline","--scaffold","--semantic","--shared-host-safe","--storage","--takeover-stale","--title-exact","--token-accounting","--trace","--tree","--unbounded","--uninstall","--validate-paths","--verify","--watch","--with-packages"]),HE=new Set(["--only-index"]),VE=new Set(["activity:--stream","eval:--fail-under","validate:--fix-scope"]),YE=new Set(["activity:--stream","close:--validate-close","close-many:--validate-close","comments:--author","learnings:--author","notes:--author"]),JE=new Set(["--regression"]);function XE(e,t){return t==="--stdin"||t==="--stdin-json"?["stdin"]:WE.has(`${e}:${t}`)?["argv","file","stdin"]:t.endsWith("-file")?["argv","file"]:GE.has(t)&&qE.has(e)?["argv","stdin"]:["argv"]}function QE(e,t){let n=VE.has(`${e}:${t.flag}`)||t.value_name!==void 0||t.value_type==="string"||t.value_type==="number"||t.list===!0||t.repeatable===!0,r=t.value_type==="boolean"||t.flag==="--stdin"||t.flag==="--stdin-json"||t.flag.startsWith("--filter-")&&(t.flag.endsWith("-missing")||t.flag.startsWith("--filter-has-")||t.flag.startsWith("--filter-no-"))||zE.some(s=>t.flag.startsWith(s));return n||HE.has(t.flag)||!BE.has(t.flag)&&!r}function ZE(e,t){return t.value_arity!==void 0?t.value_arity:QE(e,t)?JE.has(t.flag)||YE.has(`${e}:${t.flag}`)?"optional":"required":"none"}function eA(e,t){let n=Ps(e),r=ZE(n,t),s=r!=="none",i=XE(n,t.flag),o=t.description??UE[t.flag]??`${s?"Set":"Enable"} ${t.flag.slice(2).replaceAll("-"," ")}.`;return{...t,description:o,takes_value:s,value_required:r==="required",...s?{value_name:t.value_name??"value"}:{},value_type:s?t.value_type??"string":"boolean",required:t.required===!0,repeatable:t.repeatable===!0||t.list===!0,input_sources:i,...i.includes("stdin")&&t.flag!=="--stdin"&&t.flag!=="--stdin-json"?{stdin_token:"-"}:{},...KE.has(`${n}:${t.flag}`)?{file_token_prefix:"@"}:{}}}function Bh(e,t){return t.map(n=>eA(e,n))}function pq(e,t,n){let r=e.trim().toLowerCase(),s=[],i=new Map,o=0;for(let c of n)if(c.command.trim().toLowerCase()===r){if(o+=1,i.has(c.flag)){s.push({code:"duplicate_observation",command:r,flag:c.flag,detail:`${r} ${c.flag} was observed more than once.`});continue}i.set(c.flag,c)}let a=new Set(t.map(({flag:c})=>c));for(let c of t){let d=i.get(c.flag);if(!d){s.push({code:"missing_observation",command:r,flag:c.flag,detail:`${r} ${c.flag} has no executable option observation.`});continue}for(let[l,u]of[["takes_value","takes_value_mismatch"],["value_required","value_required_mismatch"],["repeatable","repeatable_mismatch"]])c[l]!==d[l]&&s.push({code:u,command:r,flag:c.flag,detail:`${r} ${c.flag} declares ${l}=${String(c[l])} but the executable option reports ${String(d[l])}.`})}for(let c of i.values())a.has(c.flag)||s.push({code:"undeclared_observation",command:r,flag:c.flag,detail:`${r} ${c.flag} is executable but absent from invocation contracts.`});return s.sort((c,d)=>c.flag.localeCompare(d.flag)||c.code.localeCompare(d.code)),{ok:s.length===0,declared_count:t.length,observed_count:o,findings:s}}import{readFile as tA}from"node:fs/promises";function Nq(e){let t={...e,...e.full===!0?{fullHistory:!0}:{}};return delete t.full,dt(e,t)}function Qh(e){return Object.prototype.toString.call(e)==="[object Object]"}function nA(e,t,n,r){let s=O();if(!Qh(e))return{...r({created_at:s,author:n,text:t}),text:t,edited_at:s};let i=o=>typeof o=="string"&&o!=="";return{...e,...i(e.created_at)?{}:{created_at:s},...i(e.author)?{}:{author:n},text:t,edited_at:s}}function Hh(e,t){if(typeof e=="object"&&e!==null&&"format"in e&&e.format==="json")throw new p(`Structured context events are append-only and cannot be ${t}.`,m.USAGE,{code:"structured_event_immutable"})}function rA(e,t){return t===void 0?e:t===0?[]:e.slice(Math.max(0,e.length-t))}function rn(e,t){let n=e[t];return Array.isArray(n)?n:[]}function Mq(e,t={}){let n=e.trim();if(!n)return"";let r=/^(?:[-*+]\s*)?text\s*[:=]/i.exec(n);if(t.stripPlainTextPrefix===!0&&r&&!n.startsWith("```"))return n.slice(r[0].length).trim()||n;if(!(/^(?:[-*+]\s*)?text\s*[:=]/im.test(n)||n.startsWith("```")))return n;try{let i=ee(n,"--add");return Object.keys(i).map(c=>c.trim().toLowerCase()).some(c=>c!=="text")?n:i.text?.trim()||n}catch{return n}}function sA(e){return typeof e=="object"&&e!==null&&"code"in e}function Vh(e,t){if(!Bt(e))throw new p(`${t} cannot read process stdin through the MCP JSON-RPC transport. Pass annotation text in options.add instead.`,m.USAGE,{code:"mcp_stdin_unavailable",required:"Pass annotation text as JSON data; the MCP protocol already owns process stdin."})}async function iA(e,t){if(+(e.add!==void 0)+ +(e.stdin===!0)+ +(typeof e.file=="string")>1)throw new p(`Specify ${t} text using only one input source: --add, --stdin, or --file`,m.USAGE);let r=Tn(),s=Bt(e);if(e.add!==void 0)return{value:await r.resolveValue(e.add,"--add",s)??"",rawValue:e.add,emptyFlag:"--add"};if(e.stdin===!0)return Vh(e,"--stdin"),{value:await r.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};if(typeof e.file!="string")return;let i=e.file.trim();if(!i)throw new p("--file path cannot be empty",m.USAGE);if(i==="-")return Vh(e,"--file -"),{value:await r.resolveValue("-","--file")??"",emptyFlag:"--file"};try{return{value:await tA(i,"utf8"),emptyFlag:"--file"}}catch(o){if(sA(o)&&Rn(o))throw new p(`--file path not found: ${i}. Use --file - to read stdin.`,m.USAGE);let a=o instanceof Error?o.message:String(o);throw new p(`Failed to read --file path "${i}": ${a}. Use --file - to read stdin.`,m.USAGE)}}async function Pq(e,t){if(e.edit!==void 0&&e.delete!==void 0)throw new p("Specify only one of --edit or --delete",m.USAGE);if(e.delete!==void 0){if(e.add!==void 0||e.stdin===!0||typeof e.file=="string")throw new p("--delete cannot be combined with replacement text",m.USAGE);if(!Number.isInteger(e.delete)||e.delete<1)throw new p("--delete must be a positive integer",m.USAGE);return{mode:"delete",index:e.delete}}if(e.edit!==void 0&&(!Number.isInteger(e.edit)||e.edit<1))throw new p("--edit must be a positive integer",m.USAGE);let n=await iA(e,t);if(e.edit!==void 0){if(!n)throw new p("--edit requires replacement text from --add, --stdin, or --file",m.USAGE);return{mode:"edit",index:e.edit,...n}}return n?{mode:"add",...n}:{mode:"list"}}function qr(e,t){throw e instanceof p&&e.exitCode===m.CONFLICT&&e.message.includes("is assigned to")&&e.message.includes("Use --force to override")?new p(e.message,e.exitCode,{code:"ownership_conflict",required:t.required,examples:t.examples,nextSteps:t.nextSteps}):e}function Zh(e){return e==="comments"?"--stdin":"--add -"}var Fq="annotation_flag_like_value";function oA(e){return/^-{1,2}[A-Za-z][\w-]*(?:=.*)?$/.test(e.trim())}function aA(e){return e==="--file"?"--file <path>":e.startsWith("--file=")?e:e==="--stdin"?"--stdin":void 0}function cA(e){let t=e.value.trim(),n=e.collectionKey.replace(/s$/,""),r=aA(t),s=Zh(e.collectionKey),i=e.retryArgs===void 0?{}:{field:e.textFlag,recovery:{suggested_flags:[t],suggested_retry:L(e.retryArgs),suggested_retry_args:[...e.retryArgs]}};if(r!==void 0){let o=r.split(/[ =]/,1)[0],a=o==="--file"?"that file":"stdin",c=e.conflictingOperand===void 0?"":` "${e.conflictingOperand}" was read as positional text, which ${o} cannot be combined with: drop it, or pass it as the text without ${o}.`;return new p(`${e.textFlag} value "${t}" looks like an option, not annotation text: ${e.textFlag} took ${o} as its value. Drop ${e.textFlag} and pass ${r} on its own.${c}`,m.USAGE,{code:"annotation_flag_like_value",required:`Drop ${e.textFlag}: ${r} reads the ${n} text from ${a} by itself. Use ${e.textFlag} text=${t} only when the text really is "${t}".`,examples:[`${e.commandPrefix} ${r}`,`${e.commandPrefix} ${e.textFlag} text=${t}`],...i})}return new p(`${e.textFlag} value "${t}" looks like an option, not annotation text. Use ${s} to read stdin, or use text=${t} for literal dash-leading text.`,m.USAGE,{code:"annotation_flag_like_value",required:`Use ${s} for stdin input, pass plain text, or use text=${t} when the text really starts with "-".`,examples:[`${e.commandPrefix} ${s}`,`${e.commandPrefix} ${e.textFlag} text=${t}`],...i})}function dA(e,t){if(!((t.input.emptyFlag??"--add")!=="--add"||!oA(e)))throw cA({collectionKey:t.collectionKey,textFlag:"--add",value:e,commandPrefix:t.input.mode==="edit"?`pm ${t.collectionKey} <id> --edit <index>`:`pm ${t.collectionKey} <id>`})}function lA(e,t,n,r,s){if(n.input.mode!=="edit")return;let i=df(t);if(i===void 0)return;let o=n.collectionKey.replace(/s$/,""),a=n.input.index,c=Le(r)[0]==="--pm-path"?["--pm-path",s]:[];throw new p(`Replacement text for ${o} ${a} on ${e} ends with the read-output compaction marker, so it was copied from a compacted read that left out ${i} characters. Nothing was written.`,m.USAGE,{code:"annotation_text_compacted",item_id:e,details:{collection:n.collectionKey,entry_index:a,omitted_characters:i},required:`Read the whole ${o} with --output-budget unbounded, apply the change to the full text, and retry the edit without the trailing marker.`,why:"A budgeted read shortens long entries to a prefix plus a marker naming how many characters it left out; editing from that text would replace the stored entry with the shortened prefix.",examples:[L([...c,n.collectionKey,e,"--output-budget","unbounded","--json"]),`${L([...c,n.collectionKey,e,"--edit",String(a),"--file"])} <full-text-file>`]})}function uA(e,t){if(t.ifAbsent===!0&&!["add","stdin","file"].includes(e.input.mode))throw new p(`--if-absent requires a ${e.collectionKey.replace(/s$/,"")} append`,m.USAGE,{code:"annotation_if_absent_without_append",required:"Combine --if-absent with one append text source; omit it for list, edit, and delete operations."});if(mA(e,t),e.input.mode!=="list"||t.message===void 0)return;let n=e.collectionKey.replace(/s$/,"");throw new p(`--message labels a ${n} mutation but does not provide ${n} text. Pass text positionally or with --add, --stdin, or --file.`,m.USAGE,{code:"annotation_message_without_text",required:`Provide ${n} text through a content source; --message only annotates the history entry of a mutation.`,examples:[`pm ${e.collectionKey} <id> --add "text" --message "why"`,`pm ${e.collectionKey} <id> ${Zh(e.collectionKey)}`]})}function mA(e,t){if(t.expectAt!==void 0){if(e.input.mode!=="edit"&&e.input.mode!=="delete")throw new p(`--expect-at guards an --edit or --delete of one ${e.collectionKey.replace(/s$/,"")}`,m.USAGE,{code:"annotation_expectation_without_target",required:"Combine --expect-at with --edit <index> or --delete <index>; omit it for list and append operations.",examples:[`pm ${e.collectionKey} <id> --edit <index> --expect-at <created_at> --add "<text>"`,`pm ${e.collectionKey} <id> --delete <index> --expect-at <created_at>`]});if(typeof t.expectAt!="string"||t.expectAt.trim().length===0)throw new p("--expect-at must be the non-empty created_at timestamp of the entry you read",m.USAGE,{code:"annotation_expectation_invalid",required:"Pass the created_at value of the row you read at that index, as a string."})}}function Yh(e,t,n,r,s){if(s===void 0)return;let i=t[n]?.created_at,o=typeof i=="string"?i:null;if(o===s)return;let a=t.flatMap((f,_)=>f?.created_at===s?[_+1]:[]),c=r.collectionKey.replace(/s$/,""),d=r.input.mode==="delete"?"--delete":"--edit",l=n+1,u=a.length===1?` The ${c} created at ${s} is at index ${a[0]}.`:a.length>1?` ${a.length} ${r.collectionKey} were created at ${s}: indexes ${a.join(", ")}.`:` No ${c} on ${e} was created at ${s}.`;throw new p(`${c.charAt(0).toUpperCase()}${c.slice(1)} ${l} on ${e} was created at ${o||"an unrecorded time (malformed entry)"}, not ${s}; refusing ${d} of an entry the caller did not read. Nothing was written.${u}`,m.CONFLICT,{code:"annotation_entry_mismatch",item_id:e,details:{collection:r.collectionKey,entry_index:l,expected_created_at:s,actual_created_at:o,matching_indexes:a},required:`Address the ${c} by the index its listing row reports and keep --expect-at set to that row's created_at. When several indexes share the timestamp, inspect those rows before retrying, because the guard compares timestamps, not entry identities.`,why:"A listing page's position or count is not an entry address; only the row's index is, and the expectation checks that the entry at that index still carries the created_at that was read.",examples:[`pm ${r.collectionKey} ${e} --limit 5`,`pm ${r.collectionKey} ${e} ${d} ${a.length===1?a[0]:"<index>"} --expect-at ${s}${d==="--edit"?' --add "<text>"':""}`]})}function fA(e,t,n,r,s,i){let o=rn(e.metadata,t),a=s?o.findIndex(c=>Qh(c)&&c.author===n&&c.text===r):-1;return a>=0?{changedFields:[],written:o,position:a}:(o.push(i({created_at:O(),author:n,text:r})),e.metadata[t]=o,{changedFields:[t],written:o,position:o.length-1})}function Jh(e,t,n){return Hm.has(e)?t.map((s,i)=>i).sort((s,i)=>Vm(t[s],t[i])||s-i).indexOf(n)+1:n+1}async function Dq(e,t,n,r){uA(r,t);let s=I(process.cwd(),n.path);await j(s);let i=await C(s),o=D(i,F()),a=Rr(t.limit);if(r.input.mode==="list"){let h=await Y(s,e,i.id_prefix,i.item_format,o.type_to_folder);if(!h)throw new p(`Item ${e} not found`,m.NOT_FOUND);let g=await fe(h,{schema:i.schema}),y=rn(g.document.metadata,r.collectionKey);return Ni(h.id,r.collectionKey,y,a,t.includeMeta===!0)}let c=G(t.author,i.author_default);if(r.input.mode==="delete"){let h=r.deleteOp??r.op,g;try{g=await he({pmRoot:s,settings:i,id:e,op:h,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(w){let v=rn(w.metadata,r.collectionKey),S=Xh(r.input.index,v.length,r.collectionKey);return Yh(e,v,S,r,t.expectAt),Hh(v[S],"deleted"),v.splice(S,1),w.metadata[r.collectionKey]=v,{changedFields:[r.collectionKey]}}})}catch(w){qr(w,r.conflictGuidance)}let y=rn(g.item,r.collectionKey);return Ni(g.item.id,r.collectionKey,y,a,t.includeMeta===!0,{action:"delete",entryIndex:r.input.index},t.fullHistory===!0)}let d=r.input.rawValue??r.input.value??"";dA(d,r);let l=r.parseText(r.input.value??"");if(!l.trim())throw new p(`${r.input.emptyFlag??"--add"} text cannot be empty`,m.USAGE);if(lA(e,l,r,n,s),r.input.mode==="edit"){let h=r.editOp??r.op,g,y=0;try{g=await he({pmRoot:s,settings:i,id:e,op:h,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(S){let b=rn(S.metadata,r.collectionKey),k=Xh(r.input.index,b.length,r.collectionKey);Yh(e,b,k,r,t.expectAt);let A=b[k];return Hh(A,"edited"),b[k]=nA(A,l,c,r.createEntry),y=Jh(r.collectionKey,b,k),S.metadata[r.collectionKey]=b,{changedFields:[r.collectionKey]}}})}catch(S){qr(S,r.conflictGuidance)}let w=rn(g.item,r.collectionKey),v=y;return Ni(g.item.id,r.collectionKey,w,a,t.includeMeta===!0,{action:"edit",entryIndex:v,entry:w[v-1]},t.fullHistory===!0)}let u,f=0;try{u=await he({pmRoot:s,settings:i,id:e,op:r.op,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,skipNoop:t.ifAbsent===!0,mutate(h){let g=fA(h,r.collectionKey,c,l,t.ifAbsent===!0,r.createEntry);return f=Jh(r.collectionKey,g.written,g.position),{changedFields:g.changedFields}}})}catch(h){qr(h,r.conflictGuidance)}let _=rn(u.item,r.collectionKey);return Ni(u.item.id,r.collectionKey,_,a,t.includeMeta===!0,{action:"add",entryIndex:f,entry:_[f-1],changedCount:t.ifAbsent===!0?Math.min(u.changedFields.length,1):void 0},t.fullHistory===!0)}function Xh(e,t,n){if(e===void 0||!Number.isInteger(e)||e<1||e>t){let r=n.replace(/s$/,""),s=`${r.charAt(0).toUpperCase()}${r.slice(1)}`,i=t===1?`1 ${r}`:`${t} ${n}`;throw new p(`${s} index ${e??"(missing)"} out of range (item has ${i})`,m.USAGE)}return e-1}function pA(e,t,n){return t===void 0?{}:{mutation_receipt:{action:t.action,entry_index:t.entryIndex,changed_count:t.changedCount??1,full_history_included:!n},omission_receipt:{has_omissions:n,omitted_field_group_count:n?1:0,omitted_field_groups:n?[{name:`${e}_history`,restore_with:{selector:"full_history",cli_flag:"--full-history",sdk_option:"fullHistory",mcp_option:"full"}}]:[]}}}function eg(e,t){if(Object.prototype.toString.call(e)!=="[object Object]")return e;let n={index:t,...e};return n.index=t,n}function _A(e,t){let n=e.length-t.length;return t.map((r,s)=>eg(r,n+s+1))}function Ni(e,t,n,r,s,i,o=!1){let a=i===void 0||o?_A(n,rA(n,i!==void 0&&o?void 0:r)):i.entry===void 0?[]:[eg(i.entry,i.entryIndex)],c=i!==void 0&&a.length<n.length;return{id:e,[t]:a,count:a.length,...i?.changedCount===void 0?{}:{changed:i.changedCount===1},...[s,i!==void 0].includes(!0)?{total_count:n.length,returned_count:a.length,has_more:c||a.length<n.length,...r!==void 0?{limit:r}:{}}:{},...pA(t,i,c)}}import{isDeepStrictEqual as ig}from"node:util";var hA=new Set(["__proto__","prototype","constructor"]),Pc=Symbol("looseOptionOccurrences");function Ft(e){return e.trim().toLowerCase().replaceAll(/-([a-z0-9])/g,(n,r)=>r.toUpperCase())}function gA(e,t,n){let r=e[t];if(r===void 0){e[t]=n;return}if(Array.isArray(r)){r.push(n),e[t]=r;return}e[t]=[r,n]}function Fc(e,t){let n=e[t];if(!n.startsWith("-")||n==="-"||n==="--")return null;if(!n.startsWith("--")){let o=n.indexOf("=");if(o>=0)return{consumed:1,key:n.slice(1,o).trim(),value:n.slice(o+1),attached:!0};let a=n.slice(1).trim(),c=e[t+1];return typeof c=="string"&&!c.startsWith("-")?{consumed:2,key:a,value:c}:{consumed:1,key:a,value:!0}}let r=n.indexOf("=");if(r>=0)return{consumed:1,key:n.slice(2,r).trim(),value:n.slice(r+1),attached:!0};if(n.startsWith("--no-"))return{consumed:1,key:n.slice(5).trim(),value:!1};let s=n.slice(2).trim(),i=e[t+1];return typeof i=="string"&&!i.startsWith("-")?{consumed:2,key:s,value:i}:{consumed:1,key:s,value:!0}}function Pi(e){return hA.has(e)}function Fi(e){let t=(typeof e.value_type=="string"?e.value_type:void 0)??(typeof e.type=="string"?e.type:void 0);return Pm(t)}function Wr(e){let t=[],n=Vt(e.long)??"",r=typeof e.short=="string"?e.short.trim():"";if(n.startsWith("--")){let s=Ft(n.slice(2));s.length>0&&!Pi(s)&&t.push(s)}if(r.startsWith("-")&&!r.startsWith("--")){let s=Ft(r.slice(1));s.length>0&&!Pi(s)&&t.push(s)}return[...new Set(t)]}function Kq(e){let t=new Set;for(let n of e)for(let r of Wr(n))t.add(r);return t}function qn(e){let t=Vt(e.long)??"";if(t.startsWith("--")){let n=Ft(t.slice(2));if(n.length>0&&!Pi(n))return n}return Wr(e)[0]??null}function Wn(e){let t=Vt(e.long)??"";if(t.startsWith("--")&&t.length>2)return t;let n=typeof e.short=="string"?e.short.trim():"";return n.startsWith("-")&&!n.startsWith("--")&&n.length>1?n:null}function og(e,t){return[...(t.definitions??e).map(r=>Wn(r)).filter(r=>r!==null),...t.inheritedFlags??[]]}function zq(e,t,n,r={}){if(t.length===0)return;let s=new Set,i=new Map,o=[],a=og(t,r);for(let c of t){let d=Wr(c),l=Wn(c);for(let u of d)s.add(u),c.enabled===!1&&i.set(u,l);c.required===!0&&c.enabled!==!1&&d.length>0&&o.push({keys:d,label:l,definition:c})}for(let c of Object.keys(e)){s.has(c)||ag(`--${c}`,`--${c}`,n,a);let d=i.get(c);d&&cg(d,n)}for(let c of o){let d=l=>Object.hasOwn(e,l)&&(c.definition.list!==!0||ug(c.definition,e[l]));c.keys.some(d)||dg(c.definition,c.keys[0],c.label,n)}}function ag(e,t,n,r){let s=r.length>0?` Expected one of: ${[...new Set(r)].join(", ")}.`:"";throw new p(`Unknown option '${e}' for extension command '${n}'.${s}`,m.USAGE,{code:"unknown_option",flag:t,required:`Use a flag the command accepts; run pm contracts --command ${n} --flags-only --json to list them.`})}function cg(e,t){throw new p(`Option '${e}' is disabled for extension command '${t}'.`,m.USAGE,{code:"extension_option_disabled",flag:e,required:`Remove ${e}; the command declares it with enabled: false.`,why:"A disabled declaration keeps the flag in the contract while refusing every value for it.",examples:[`pm ${t} --help`],nextSteps:[`Run pm contracts --command ${t} --flags-only --json to list the flags this command accepts.`]})}function dg(e,t,n,r){let s=On(e),i=s.value_arity==="none"?n:s.value_arity==="optional"?`${n} [${s.value_name}]`:`${n} <${s.value_name}>`;throw new p(`Missing required option '${n}' for extension command '${r}'.`,m.USAGE,{code:"missing_required_option",flag:n,field:t,required:`Pass ${i}.`,why:"The command declares this flag as required, so pm refuses the invocation before the extension handler runs.",examples:[`pm ${r} ${i}`],nextSteps:[`Run pm contracts --command ${r} --flags-only --json to read each flag's sdk_option key.`],recovery:{missing:[n]}})}function yA(e){return typeof e=="string"||e==null?e:String(e)}function wA(e){if(typeof e=="number")return e;if(typeof e=="string"&&e.trim().length>0){let t=Number(e);return Number.isFinite(t)?t:e}return e}function lg(e){if(typeof e=="boolean")return e;if(typeof e=="string"){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1}return e}var vA={string:yA,number:wA,boolean:lg};function sn(e,t){return Array.isArray(e)?e.map(n=>sn(n,t)):vA[t](e)}function Dc(e,t,n){let r=n?(Array.isArray(e)?e.flat(1/0):[e]).filter(s=>s!=null&&s!==""):Xa(e);return t?r.map(s=>sn(s,t)):r}function ug(e,t){return Dc(t,null,e.repeatable===!0).length>0}function kA(e,t,n,r){return n?Dc(e,t,r):t?sn(e,t):e}function bA(e,t,n){let r=fg(e,t);return r.length===0?n:r.map(s=>s.value)}function mg(e){return On(e).value_arity==="none"}function jc(e,t,n,r,s){let i=Wn(e),o=s?` for extension command '${s}'`:"",a=n===!0?"no value":JSON.stringify(n);throw new p(`Option '${i}'${o} expects ${r}; received ${a}.`,m.USAGE,{code:"extension_flag_value_invalid",flag:i,required:`Pass ${i} ${t==="number"?"<number>":"<true|false|1|0>"}.`,why:`The flag declares value_type ${t} with value_validation strict, so a malformed token is refused before the extension handler runs.`,nextSteps:[`Re-run with a valid ${t} value for ${i}.`,`Run pm ${s??"<command>"} --help to review the declared flag contract.`]})}function Uc(e,t){return e.value_validation==="strict"&&t!=="string"}function fg(e,t){let n=e[Pc];if(!n)return[];let r=new Set(t);return n.filter(s=>r.has(s.key))}function xA(e,t,n,r){if(mg(e))for(let s of fg(n,t)){if(s.attached!==!0)continue;let i=e.list===!0&&e.repeatable!==!0?Xa(s.value):[s.value];for(let o of i){let a=Xs(sn(o,"boolean"),"boolean");a!==null&&jc(e,"boolean",o,a.expected,r)}}}function SA(e,t,n,r,s){let i=Array.isArray(n)?n.flat(1/0):[n],o=r?i:i.flatMap(a=>typeof a=="string"?a.split(","):[a]);for(let a of o)if(typeof a=="string"&&a.trim().length===0){let c=Xs(a,t);jc(e,t,a,c.expected,s)}}function Gc(e,t,n,r){if(!Uc(e,n))return t;let s=n==="boolean"&&mg(e),i=o=>{let a=Xs(o,n);return a===null?o:s&&typeof o=="string"?!0:jc(e,n,o,a.expected,r)};return Array.isArray(t)?t.map(i):i(t)}function EA(e,t,n,r){for(let s of n)if(!(s===t||!Object.hasOwn(e,s))){if(Object.hasOwn(e,t)){if(r){let i=e[t],o=e[s];e[t]=[...Array.isArray(i)?i:[i],...Array.isArray(o)?o:[o]].filter(a=>a!=null)}delete e[s];continue}e[t]=e[s],delete e[s]}}function pg(e,t,n=e,r){if(t.length===0)return e;let s=Object.create(null);for(let[o,a]of Object.entries(e))s[o]=a;let i=new Set(t.map(o=>qn(o)).filter(o=>o!==null));for(let o of t){let a=qn(o);if(a){let c=Wr(o).filter(d=>d===a||!i.has(d));AA(s,o,a,c,n,r)}}return s}function AA(e,t,n,r,s,i){let o=t.list===!0,a=Fi(t);a&&!o&&CA(e,t,n,r,a,i),EA(e,n,r,o);let c=t.repeatable===!0;if(!Object.hasOwn(e,n)){t.default!==void 0&&(e[n]=kA(t.default,a,o,c));return}if(a==="boolean"&&Uc(t,a)&&xA(t,r,s,i),o){e[n]=TA(t,r,s,e[n],a,c,i);return}a&&(e[n]=Gc(t,sn(e[n],a),a,i))}function CA(e,t,n,r,s,i){for(let o of r)o!==n&&Object.hasOwn(e,o)&&Gc(t,sn(e[o],s),s,i)}function TA(e,t,n,r,s,i,o){let a=bA(n,t,r);s&&Uc(e,s)&&SA(e,s,a,i,o);let c=Dc(a,s,i);return s?Gc(e,c,s,o):c}function Bq(e){let t=Object.create(null),n=[];Object.defineProperty(t,Pc,{value:n});let r=0;for(;r<e.length;){let s=Fc(e,r);if(!s){r+=1;continue}let i=Ft(s.key);if(i.length===0||Pi(i)){r+=s.consumed;continue}gA(t,i,s.value),n.push({...s,key:i}),r+=s.consumed}return t}function Hq(e){let t=[],n=0;for(;n<e.length;){if(e[n]==="--"){t.push(...e.slice(n+1));break}let r=Fc(e,n);if(r){n+=Math.max(1,r.consumed);continue}t.push(e[n]),n+=1}return t}function Vq(e,t){if(t.length===0)return[...e];let n=new Set,r=new Set;for(let o of t){let a=Fi(o);for(let c of Wr(o))n.add(c),a==="boolean"&&r.add(c)}if(n.size===0)return[...e];let s=[],i=0;for(;i<e.length;){if(e[i]==="--"){s.push(...e.slice(i+1));break}let o=Fc(e,i);if(o){let a=Ft(o.key);if(n.has(a)){let c=e[i],d=r.has(a)&&!c.includes("=")?1:o.consumed;i+=d;continue}}s.push(e[i]),i+=1}return s}function qc(e){return qn(e)}function tg(e){return e.trim().toLowerCase().split(/\s+/u).filter(t=>t.length>0).join(" ")}function Yq(e,t){let n=tg(t);if(n.length===0)return[];let r=K(n);return e.flags.filter(s=>K(tg(s.target_command))===r).flatMap(s=>[...s.flags])}function _g(e,t,n,r){let s=Wn(e),[i,o]=n;throw new p(`Options '${i}' and '${o}' both set ${s} for extension command '${r}' with different values.`,m.USAGE,{code:"extension_option_spelling_conflict",required:`Pass ${s} once, under the handler key '${t}'.`,why:`'${i}' and '${o}' are spellings of the same declared flag, and pm refuses to choose between two different values.`,nextSteps:[`Remove '${i}' or '${o}' and pass one value as '${t}'.`,`Run pm contracts --command ${r} --flags-only --json to read each flag's sdk_option key.`]})}function Jq(e,t,n,r={}){if(t.length===0)return e;let s=t.map(l=>l.repeatable===!0&&l.list!==!0?{...l,list:!0}:l),i=LA(s),o=MA(e,i,n),a=new Set([...i.long.values()].map(({handlerKey:l})=>l)),c=Object.create(null),d=Object.create(null);for(let[l,u]of Object.entries(o))a.has(l)?c[l]=u:u===void 0||r.undeclaredKeys==="pass"||IA(l)?d[l]=u:ag(l,OA(l),n,og(s,{}));return gg(c,s,n),Object.assign(d,pg(c,s,hg(c,i),n))}function hg(e,t){let n=new Set([...t.long.values()].map(({handlerKey:i})=>i)),r=Object.entries(e).filter(([i])=>n.has(i)).flatMap(([i,o])=>(Array.isArray(o)?o.flat(1/0):[o]).map(a=>({consumed:1,key:i,value:a,attached:!0}))),s=Object.create(null);return Object.defineProperty(s,Pc,{value:r}),s}function gg(e,t,n){for(let r of t){let s=qn(r);if(s===null)continue;let i=Wn(r),o=e[s],a=Object.hasOwn(e,s);r.enabled===!1&&a&&cg(i,n);let c=a&&(r.list!==!0||ug(r,o));r.required===!0&&r.enabled!==!1&&!c&&dg(r,s,i,n),r.list!==!0&&Array.isArray(o)&&RA(i,n)}}function RA(e,t){throw new p(`Option '${e}' for extension command '${t}' takes one value; received an array.`,m.USAGE,{code:"extension_flag_value_invalid",flag:e,required:`Pass one value for ${e}, or ask the package to declare it with list: true or repeatable: true.`,why:"The flag is not declared list or repeatable, so pm refuses an array before the extension handler runs instead of handing it a value of the wrong shape.",nextSteps:[`Run pm contracts --command ${t} --flags-only --json to read each flag's value contract.`]})}var ng=new Set([...[...$m].flatMap(e=>{let t=e.replace(/^--/u,"");return[t,...t.startsWith("no-")?[t.slice(3)]:[]].flatMap(r=>[Ft(r),r.replaceAll("-","_")])}),"force","subcommand","inputResponses","requestState"]);function IA(e){return ng.has(e)||ng.has(Ft(e.replace(/^-{1,2}/u,"")))}function OA(e){return`--${e.replace(/^-+/u,"").replace(/([a-z0-9])([A-Z])/gu,"$1-$2").replaceAll("_","-").toLowerCase()}`}function LA(e){let t={long:new Map,short:new Map},n=(r,s,i)=>{s.length>0&&!r.has(s)&&r.set(s,i)};for(let r of e){let s=qn(r);if(s===null)continue;let i={handlerKey:s,definition:r};n(t.long,s,i);let o=typeof r.short=="string"?r.short.trim():"";o.startsWith("-")&&!o.startsWith("--")&&n(t.short,o.slice(1),i)}return t}function Mc(e,t){return e.long.get(t)??e.short.get(t.replace(/^-(?!-)/u,""))??e.long.get(Ft(t.replace(/^-{1,2}/u,"")))}function $A(e,t,n,r){let s=/^(?:--)?no-(.+)$/u.exec(t)?.[1];if(s===void 0||Mc(e,t)!==void 0)return{spelling:t,value:n};let i=Mc(e,s);return i===void 0||Fi(i.definition)!=="boolean"?{spelling:t,value:n}:(i.definition.list===!0||i.definition.repeatable===!0)&&Array.isArray(n)?{spelling:s,value:n.flat(1/0).map(o=>rg(t,i.definition,o,r))}:i.definition.list===!0&&n!==void 0?{spelling:s,value:rg(t,i.definition,n,r)}:{spelling:s,value:n===void 0?n:Mi(t,i.definition,n,r)}}function rg(e,t,n,r){let s=i=>i.trim().length===0?i:String(Mi(e,t,i.trim(),r));return n==null?n:typeof n!="string"?Mi(e,t,n,r):n.trim().length===0?n:t.repeatable===!0||!n.includes(",")?Mi(e,t,n,r):n.split(",").map(s).join(",")}function Mi(e,t,n,r){let s=lg(n);return typeof s=="boolean"?!s:NA(e,t,n,r)}function NA(e,t,n,r){let s=Wn(t);throw new p(`Option '${e}' for extension command '${r}' negates ${s} and expects true, false, 1, or 0; received ${JSON.stringify(n)}.`,m.USAGE,{code:"extension_flag_value_invalid",flag:s,required:`Pass ${s} as true or false, or '${e}' as true.`,why:`'${e}' is the negated spelling of the boolean ${s}, so only a boolean value can be inverted before the extension handler runs.`,nextSteps:[`Run pm contracts --command ${r} --flags-only --json to read each flag's value contract.`]})}function MA(e,t,n){let r=Object.create(null),s=new Map;for(let[i,o]of Object.entries(e)){let{spelling:a,value:c}=$A(t,i,o,n),d=Mc(t,a);if(d===void 0)r[a]=c;else if(c!==void 0){let l=s.get(d.handlerKey);l===void 0?(s.set(d.handlerKey,a),r[d.handlerKey]=c):ig(sg(d.definition,d.handlerKey,r[d.handlerKey],t,n),sg(d.definition,d.handlerKey,c,t,n))||_g(d.definition,d.handlerKey,[l,a],n)}}return r}function sg(e,t,n,r,s){let i={[t]:n};return gg(i,[e],s),pg(i,[e],hg(i,r),s)[t]}function PA(e){let t=new Map;for(let n of e){let r=qn(n);if(r===null)continue;let s={definition:n,handlerKey:r,kind:Fi(n),arity:On(n).value_arity,scalar:n.list!==!0},i=[Vt(n.long),typeof n.short=="string"?n.short.trim():""];for(let o of i.filter(a=>a?.startsWith("-")===!0))t.has(o)||t.set(o,s)}return t}function FA(e,t,n){let r=e.optionOf(n),s=t.get(n),i=s?.scalar===!0?s:void 0;if(r!==void 0){let o={arity:r.arity,...r.variadic===!0?{variadic:!0}:{}};if(i?.handlerKey===r.key)return{...o,declared:i};let a=s===void 0&&n.startsWith("--no-")?t.get(`--${n.slice(5)}`):void 0;return a?.scalar===!0&&a.kind==="boolean"&&a.handlerKey===r.key?{...o,declared:a,negates:!0}:o}if(!(!e.includesLooseFlags||s===void 0))return i===void 0?{arity:s.arity,loose:!0}:{arity:s.arity,declared:i,loose:!0}}function Wc(e){return e.length>1&&e.startsWith("-")}var yg=/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/u;function DA(e,t,n){let{tokens:r}=e,s=0,i,o=!1,a=!1;for(;s<r.length||i!==void 0;){let c=i??r[s++];if(c==="--")return;if(a&&i===void 0&&jA(e,c))continue;let d=Wc(c)?GA(e,c,r[s],t,n):{consumedByCommander:!1,consumed:0};if(s+=d.consumed,i=d.group,a=d.variadic===!0,!d.consumedByCommander){if(UA(e.stop,c,o))return;o=!0}}}function jA(e,t){return!Wc(t)||e.negativeNumbersAreValues&&yg.test(t)}function UA(e,t,n){return e!==void 0&&(e.atFirstUnrecognized||!n&&e.atSubcommand(t))}function GA(e,t,n,r,s){let i=qA(t,n,r);if(i!==void 0)return s(i.spelling,i.entry,i.value),{consumedByCommander:!1,consumed:i.consumed};let o=r(t);if(o!==void 0){let a=o.arity==="required"||o.arity==="optional"&&n!==void 0&&(!Wc(n)||e.negativeNumbersAreValues&&yg.test(n));return s(t,o,o.negates===!0?!1:a?n:!0),{consumedByCommander:!0,consumed:a?1:0,variadic:o.variadic===!0}}return t[1]!=="-"?{consumed:0,...WA(t,r,s)}:{consumedByCommander:KA(t,r,s,e.includesLooseFlags?s:()=>{}),consumed:0}}function qA(e,t,n){let r=e.indexOf("="),s=r>1?e.slice(0,r):e,i=n(s);if(i?.loose===!0)return r>1?{spelling:s,entry:i,value:e.slice(r+1),consumed:0}:t!==void 0&&!t.startsWith("-")?{spelling:s,entry:i,value:t,consumed:1}:{spelling:s,entry:i,value:!0,consumed:0};let o=r<0&&e.startsWith("--no-")?n(`--${e.slice(5)}`):void 0;return o?.loose===!0&&o.declared?.kind==="boolean"?{spelling:e,entry:o,value:!1,consumed:0}:void 0}function WA(e,t,n){let r=e.slice(0,2),s=e.length>2?t(r):void 0;return s===void 0||s.loose===!0?{consumedByCommander:!1}:s.arity!=="none"?(n(r,s,e.slice(2)),{consumedByCommander:!0}):(n(r,s,!0),{consumedByCommander:!0,group:`-${e.slice(2)}`})}function KA(e,t,n,r){let s=e.indexOf("=");if(s>2){let o=e.slice(0,s),a=t(o);return a!==void 0&&a.arity!=="none"?(n(o,a,e.slice(s+1)),!0):(a?.declared?.kind==="boolean"&&r(o,a,e.slice(s+1)),!1)}let i=e.startsWith("--no-")?t(`--${e.slice(5)}`):void 0;return i?.declared?.kind==="boolean"&&r(e,i,!1),!1}function Xq(e,t,n){let r=PA(t),s=new Map;for(let i of e)DA(i,o=>FA(i,r,o),(o,a,c)=>{a.declared!==void 0&&zA(s,a.declared,o,c,n)})}function zA(e,t,n,r,s){let{definition:i,handlerKey:o,kind:a}=t,c=a?sn(r,a):r,d=e.get(o)??new Map,l=[...d].find(([u,f])=>u!==n&&!ig(f,c));l!==void 0&&_g(i,o,[l[0],n],s),d.set(n,c),e.set(o,d)}var BA=new Set(["claim","close","context","create","get","help","init","list","next","plan","release","search","update","validate","workspace"]),HA=new Set(["append","comments","config","contracts","deps","docs","events","files","focus","graph","health","history","learnings","list-all","list-blocked","list-closed","list-in-progress","list-open","notes","profile","schema","test"]),VA=Object.freeze({workspace:new Set(["config","gc","health","init","merge","profile","schema","telemetry","workspace"]),intake:new Set(["copy","create","focus","item","restore"]),context:new Set(["activity","aggregate","context","ctx","duplicates","eval","get","help","list","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","next","search","stats"]),lifecycle:new Set(["claim","close","close-many","close-task","delete","pause-task","item-reopen","release","start-task","update","update-many"]),evidence:new Set(["append","comments","docs","events","files","history","history-attest","history-author-acknowledge","history-compact","history-redact","history-repair","learnings","notes"]),graph:new Set(["deps","graph","plan"]),quality:new Set(["assurance","contracts","test","test-all","validate"]),automation:new Set(["event","meet","remind"])}),YA=new Set(["extension","install","package","packages","upgrade"]);function JA(e){let t=K(e.trim().toLowerCase());if(t==="ops")return"quality";for(let[n,r]of Object.entries(VA))if(r.has(t))return n;return YA.has(t)?"extensions":"internal"}var Kn=Object.freeze([...ot.flatMap(e=>e==="item"?["item","item-reopen"]:[e,...it.filter(t=>t.alias===e).map(t=>t.canonical)]).map(e=>({command:e,tier:BA.has(K(e))?"core":HA.has(K(e))?"standard":"full",family:JA(e)})),{command:"ops",tier:"core",family:"quality"},{command:"completion-statuses",tier:"internal",family:"internal"},{command:"completion-tags",tier:"internal",family:"internal"},{command:"completion-types",tier:"internal",family:"internal"},{command:"test-runs-worker",tier:"internal",family:"internal"},{command:"item test worker",tier:"internal",family:"internal"}]),XA=Kn,wg=Object.freeze({max_lines:50,max_utf8_bytes:6e3}),tW=Object.freeze(["-V, --version","--all","--json","--output-include <fields>","--output-limit <count>","--output-budget <tokens|unbounded>","--output-cursor <cursor>","--pm-path <dir>","--no-extensions","--no-pager","--explain","-h, --help"]);function nW(e){let t=e===""?0:e.split(/\r?\n/).length,n=Buffer.byteLength(e,"utf8");return{lines:t,utf8_bytes:n,within_budget:t<=wg.max_lines&&n<=wg.max_utf8_bytes}}var vg={core:0,standard:1,full:2,internal:3},kg=new Map(XA.map(({command:e,tier:t})=>[e,t]));function Kc(e,t="standard"){return kg.get(e.trim().toLowerCase())??kg.get(K(e.trim().toLowerCase()))??t}function rW(e){return bg(e,Kn)}function bg(e,t){let n=vg[e];return t.filter(r=>r.tier!=="internal"&&vg[r.tier]<=n).map(r=>r.command)}function sW(e){return xg(e,Kn)}function xg(e,t){return t.filter(n=>n.family===e).map(n=>n.command)}var QA=["workspace","intake","context","lifecycle","evidence","graph","quality","automation","extensions","internal"],ZA=new Set([...zt.filter(e=>e.hidden).map(e=>e.alias),"ctx","extension","install","item-reopen","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","packages","upgrade"]);function iW(e=Kn){return QA.map(t=>({family:t,commands:xg(t,e).filter(n=>e.find(r=>r.command===n)?.tier!=="internal"&&!ZA.has(n))})).filter(({commands:t})=>t.length>0)}var eC=Object.freeze({pm_append:"append",pm_claim:"claim",pm_close:"close",pm_comments:"comments",pm_config:"config",pm_context:"context",pm_contracts:"contracts",pm_copy:"copy",pm_create:"create",pm_deps:"deps",pm_discover:"help",pm_docs:"docs",pm_events:"history",pm_files:"files",pm_focus:"focus",pm_get:"get",pm_graph:"graph",pm_health:"health",pm_learnings:"learnings",pm_list:"list",pm_mutate:"update",pm_next:"next",pm_notes:"notes",pm_plan:"plan",pm_profile:"profile",pm_release:"release",pm_run:"package",pm_schema:"schema",pm_search:"search",pm_test:"test",pm_update:"update",pm_validate:"validate"});function oW(e,t){return tC(e,t,Kn)}function tC(e,t,n){if(t==="full")return[...e];let r=new Set(bg(t,n));return e.filter(s=>{let i=eC[s];return i!==void 0&&r.has(i)})}var aW=Object.freeze([{uri:"pm://workspace/context",name:"Workspace context",description:"Bounded project context for orientation, including active hierarchy and progress.",mimeType:"application/json"},{uri:"pm://workspace/focus",name:"Active focus",description:"The session focus that supplies the default create parent.",mimeType:"application/json"},{uri:"pm://workspace/claims",name:"Active claims",description:"Bounded in-progress work and active ownership context.",mimeType:"application/json"},{uri:"pm://workspace/agent-guide",name:"Agent guidance",description:"Repository-local AGENTS.md instructions, bounded for safe host attachment.",mimeType:"text/markdown"}]),cW=Object.freeze([{name:"orient",description:"Build bounded live context, search all statuses, and select canonical work without creating duplicates.",arguments:[{name:"request",description:"The user's requested outcome or topic.",required:!0},{name:"scope",description:"Optional bounded workspace or subsystem scope.",required:!1}],template:"Orient to the live pm workspace for: {{request}}. Scope hint: {{scope}}. Read context, search all statuses, inspect full metadata for relevant items, and select canonical lineage before any mutation."},{name:"claim-and-start",description:"Claim one canonical item and begin implementation with linked context.",arguments:[{name:"id",description:"Canonical pm item id.",required:!0}],template:"Read {{id}} in full, claim it, set it in_progress, then implement only its acceptance scope while linking files, docs, tests, and evidence."},{name:"record-evidence-and-close",description:"Record exact verification evidence, close the item, and release ownership.",arguments:[{name:"id",description:"Canonical pm item id.",required:!0},{name:"evidence",description:"Exact verification and outcome evidence.",required:!0}],template:"For {{id}}, record this evidence: {{evidence}}. Verify linked tests, close only if acceptance is met, then release the claim."}]);function dW(){return nC(Kn)}function nC(e){return["# Generated agent command surface","","This file is generated from `PM_COMMAND_CAPABILITY_CONTRACTS`. Do not edit it manually.","","| Command | Minimum visibility tier | Capability family |","| --- | --- | --- |",...e.map(({command:n,tier:r,family:s})=>`| \`${n}\` | ${r} | ${s} |`),""].join(`
|
|
2
|
+
`)}var zc=[{exit_code:1,class:"generic_failure"},{exit_code:2,class:"usage"},{exit_code:3,class:"not_found"},{exit_code:4,class:"conflict"},{exit_code:5,class:"dependency_failed"}],rC=new Map(zc.map(e=>[e.exit_code,e.class]));function Di(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))].sort()}function sC(e){if(!e)return[];let t=new Set,n=new Set;return e.map(r=>{let s=r.state.trim(),i=r.probe_id.trim(),o=Di(r.entrypoints);if(!/^[a-z][a-z0-9_]*$/.test(s)||!/^[a-z][a-z0-9-]*$/.test(i)||o.length===0||t.has(s)||n.has(i))throw new TypeError("Invalid pm refusal state contract");return t.add(s),n.add(i),{state:s,probe_id:i,entrypoints:o,expected_exit_class:r.expected_exit_class}}).sort((r,s)=>r.state.localeCompare(s.state))}function iC(e,t,n,r,s){return![[1,2,3,4,5].includes(e.exit_code),e.meaning.trim().length>0,e.recovery.trim().length>0,t.length>0,n.length>0,/^[a-z][a-z0-9_]*$/.test(r),s.every(i=>/^[a-z][a-z0-9_]*$/.test(i)),rC.get(e.exit_code)===e.class].includes(!1)}function oC(e,t){let n=e,r=new Set;for(;n.canonical_code!==n.code;){if(r.has(n.code))throw new TypeError(`Alias cycle in pm error code catalog: ${e.code}`);r.add(n.code);let s=t.get(n.canonical_code);if(!s)throw new TypeError(`Invalid pm error code contract: ${e.code}`);n=s}return n}function aC(e){let t=new Map(e.map(n=>[n.code,n]));for(let n of e){let r=oC(n,t);if(r.exit_code!==n.exit_code||r.class!==n.class)throw new TypeError(`Alias transport mismatch for pm error code: ${n.code}`);let s=e.filter(i=>i.code!==r.code&&i.canonical_code===r.code).map(i=>i.code).sort();if(n.code===r.code?JSON.stringify(n.aliases)!==JSON.stringify(s):n.aliases.length>0)throw new TypeError(`Invalid pm error code contract: ${n.code}`)}}function Eg(e){let t=new Set,n=e.map(r=>{let s=r.code.trim();if(!/^[a-z][a-z0-9_]*$/.test(s))throw new TypeError(`Invalid pm error code: ${JSON.stringify(r.code)}`);if(t.has(s))throw new TypeError(`Duplicate pm error code: ${s}`);t.add(s);let i=Di(r.sources),o=Di(r.emitting_commands),a=(r.canonical_code??s).trim(),c=Di(r.aliases??[]),d=sC(r.owned_states);if(!iC(r,i,o,a,c))throw new TypeError(`Invalid pm error code contract: ${s}`);if(d.some(l=>l.expected_exit_class!==r.class))throw new TypeError(`Invalid pm refusal state exit class: ${s}`);return Object.freeze({...r,code:s,meaning:r.meaning.trim(),recovery:r.recovery.trim(),sources:i,emitting_commands:o,canonical_code:a,aliases:c,owned_states:d})});return aC(n),Object.freeze(n.sort((r,s)=>r.code.localeCompare(s.code)))}function uW(e,t){let n=Sg(e,t);return Sg(n.canonical_code??n.code,t)}function Sg(e,t){let n=e.trim(),r=t.find(s=>s.code===n);if(!r)throw new TypeError(`Unknown pm error code "${n}"`);return r}var cC="Inspect the structured error guidance, then retry the suggested command when one is present.",dC=new Map(zc.map(e=>[e.exit_code,e.class]));function Ag(e){return e.map(t=>{let n=`${t.code.replaceAll("_"," ")} condition.`,r={code:t.code,meaning:`${n.charAt(0).toUpperCase()}${n.slice(1)}`,stability:t.stable?"stable":"provisional",exit_code:t.exit_code,class:dC.get(t.exit_code),recovery:cC,sources:t.sources,emitting_commands:t.emitting_commands??["*"],canonical_code:t.canonical_code??t.code,aliases:t.aliases??[]};return t.owned_states&&(r.owned_states=t.owned_states),r})}var Cg=[{code:"acceptance_criteria_mutation_conflict",exit_code:2,sources:["sdk/lifecycle/update.ts"],emitting_commands:["update","update-many"]},{code:"acceptance_criteria_remove_unmatched",exit_code:3,sources:["sdk/lifecycle/update-many.ts","sdk/lifecycle/update.ts"],emitting_commands:["update","update-many"]},{code:"acceptance_criteria_semicolon_forbidden",exit_code:2,stable:!0,sources:["core/item/parse.ts"]},{code:"accepted_rejected_value",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"alias_collision",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"alias_target_missing",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"already_claimed_by",exit_code:4,stable:!0,sources:["sdk/lifecycle/claim.ts"],emitting_commands:["claim"]},{code:"ambiguous_option_combination",exit_code:2,stable:!0,sources:["sdk/lifecycle/claim.ts","sdk/lifecycle/plan.ts"],emitting_commands:["claim","plan"]},{code:"annotation_alias_conflict",exit_code:2,sources:["cli/register-annotations.ts"]},{code:"annotation_entry_mismatch",exit_code:4,sources:["sdk/annotations.ts"]},{code:"annotation_expectation_invalid",exit_code:2,sources:["sdk/annotations.ts"]},{code:"annotation_expectation_without_target",exit_code:2,sources:["sdk/annotations.ts"]},{code:"annotation_flag_like_value",exit_code:2,stable:!0,sources:["sdk/annotations.ts"]},{code:"annotation_if_absent_without_append",exit_code:2,sources:["sdk/annotations.ts"]},{code:"annotation_message_without_text",exit_code:2,stable:!0,sources:["sdk/annotations.ts"]},{code:"annotation_text_compacted",exit_code:2,sources:["sdk/annotations.ts"]},{code:"annotation_text_source_conflict",exit_code:2,sources:["sdk/runtime-input.ts"]},{code:"annotation_transposed_subcommand",exit_code:2,sources:["cli/register-annotations.ts"]},{code:"append_empty_body",exit_code:2,stable:!0,sources:["sdk/lifecycle/append.ts"],emitting_commands:["append"]},{code:"assurance_registry_invalid",exit_code:1,sources:["sdk/governance/assurance.ts"]},{code:"bare_comma_entry_ambiguous",exit_code:2,sources:["core/item/parse.ts"]},{code:"blocker_identity_read_failed",exit_code:1,sources:["sdk/query/declared-blockers.ts"]},{code:"body_file_conflicts_with_body",exit_code:2,stable:!0,sources:["core/io/body-file.ts"]},{code:"body_file_missing_path",exit_code:2,stable:!0,sources:["core/io/body-file.ts"]},{code:"body_file_unreadable",exit_code:3,stable:!0,sources:["core/io/body-file.ts"]},{code:"budget_exceeded",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"bulk_create_route",exit_code:2,sources:["cli/register-mutation.ts"]},{code:"bulk_ids_input_empty",exit_code:2,sources:["core/io/bulk-ids-input.ts","sdk/history-compact.ts","sdk/history-mcp.ts"],owned_states:[{state:"bulk_ids_stdin_contains_no_nonempty_ids",probe_id:"bulk-ids-stdin-empty",entrypoints:["update-many"],expected_exit_class:"usage"}]},{code:"bulk_ids_input_missing_path",exit_code:2,sources:["core/io/bulk-ids-input.ts"],owned_states:[{state:"bulk_ids_file_token_omits_its_path",probe_id:"bulk-ids-file-path-missing",entrypoints:["update-many"],expected_exit_class:"usage"}]},{code:"bulk_ids_input_unreadable",exit_code:3,sources:["core/io/bulk-ids-input.ts"],owned_states:[{state:"bulk_ids_file_path_cannot_be_read",probe_id:"bulk-ids-file-unreadable",entrypoints:["update-many"],expected_exit_class:"not_found"}]},{code:"bundle_integrity_torn_install",exit_code:1,stable:!0,sources:["cli/bundle-integrity.ts"]},{code:"capability_undeclared",exit_code:1,stable:!0,sources:["sdk/compose.ts"]},{code:"capability_unused",exit_code:1,stable:!0,sources:["sdk/compose.ts"]},{code:"child_projection_item_bound_exceeded",exit_code:1,stable:!0,sources:["sdk/item-children.ts"]},{code:"close_reason_required",exit_code:2,stable:!0,sources:["sdk/lifecycle-policy.ts","sdk/lifecycle/close-many.ts"],emitting_commands:["*","close-many"]},{code:"close_through_update",exit_code:1,stable:!0,sources:["core/telemetry/observability.ts"]},{code:"close_validation_deferred_fields",exit_code:2,sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"]},{code:"close_validation_missing_fields",exit_code:2,stable:!0,sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"]},{code:"collected_zero_items",exit_code:1,stable:!0,sources:["sdk/test/execution-receipts.ts"]},{code:"collection_transposed_subcommand",exit_code:2,sources:["cli/error-guidance.ts"]},{code:"command_failed",exit_code:1,stable:!0,sources:["cli/error-guidance.ts"]},{code:"command_namespace",exit_code:2,stable:!0,sources:["sdk/cli-contracts/runtime-contracts.ts"]},{code:"command_override_conflict",exit_code:4,stable:!0,sources:["sdk/compose.ts"]},{code:"config_duplicate",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"config_key_unknown",exit_code:2,stable:!0,sources:["core/profile/profile-lint.ts","sdk/config.ts"]},{code:"config_value_invalid",exit_code:2,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"conflicting_lifecycle_owner",exit_code:2,stable:!0,sources:["cli/register-operations.ts"]},{code:"context_evaluation_read_incomplete",exit_code:2,sources:["sdk/context-relevance.ts"]},{code:"context_signal_store_invalid",exit_code:2,sources:["sdk/context-signal-store.ts"]},{code:"context_signal_store_stale",exit_code:1,sources:["sdk/context-signal-store.ts"]},{code:"context_signal_store_write_failed",exit_code:1,sources:["sdk/context-signal-store.ts"]},{code:"context_takes_no_item_argument",exit_code:1,stable:!0,sources:["cli/error-guidance.ts"]},{code:"core_item_field_requires_dedicated_flag",exit_code:2,stable:!0,sources:["core/extensions/item-fields.ts"]},{code:"create_deferral_conflict",exit_code:2,sources:["sdk/lifecycle/create-deferrals.ts"],emitting_commands:["create"]},{code:"create_deferral_field_unsupported",exit_code:2,sources:["sdk/lifecycle/create-deferrals.ts"],emitting_commands:["create"]},{code:"create_deferral_fields_required",exit_code:2,sources:["sdk/lifecycle/create-deferrals.ts"],emitting_commands:["create"]},{code:"create_deferral_reason_required",exit_code:2,sources:["sdk/lifecycle/create-deferrals.ts"],emitting_commands:["create"]},{code:"create_positional_type_without_title",exit_code:2,stable:!0,sources:["cli/register-mutation.ts"]},{code:"dependency_cardinality_created",exit_code:2,sources:["sdk/graph/cardinality-integrity.ts"]},{code:"dependency_edge_not_allowed",exit_code:2,stable:!0,sources:["sdk/dependency-flag-validation.ts"]},{code:"dependency_flag_value_invalid",exit_code:2,sources:["sdk/dependency-flag-validation.ts"]},{code:"dependency_remove_no_match",exit_code:3,sources:["sdk/lifecycle/dependency-removal.ts"],emitting_commands:["update"]},{code:"dependency_target_not_found",exit_code:3,sources:["sdk/dependency-flag-validation.ts"]},{code:"dependency_temporal_order_invalid",exit_code:2,sources:["sdk/dependency-flag-validation.ts"]},{code:"duplicate_canonical_flag",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"duplicate_command",exit_code:1,stable:!0,sources:["sdk/compose.ts"]},{code:"duplicate_destination",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"duplicate_edge",exit_code:1,stable:!0,sources:["sdk/graph/remediation.ts"]},{code:"duplicate_observation",exit_code:1,sources:["sdk/flag-invocation-contracts.ts"]},{code:"duplicate_probe",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"duplicate_sweep_cost_limit",exit_code:4,stable:!0,sources:["sdk/query/duplicate-candidates.ts"],emitting_commands:["duplicate-candidates"]},{code:"duplicate_target_circular",exit_code:2,stable:!0,sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"]},{code:"duplicate_target_is_duplicate",exit_code:2,stable:!0,sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"]},{code:"duplicate_target_missing",exit_code:2,stable:!0,sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"]},{code:"duplicate_target_self",exit_code:2,stable:!0,sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"]},{code:"empty_corpus",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"empty_surface",exit_code:1,stable:!0,sources:["sdk/compose.ts"]},{code:"error_code_mismatch",exit_code:1,sources:["sdk/agent/refusal-closure.ts","sdk/agent/tracker-preflight-contracts.ts"]},{code:"event_cursor_query_mismatch",exit_code:2,stable:!0,sources:["sdk/mutation-events.ts"]},{code:"event_history_integrity_failed",exit_code:1,sources:["core/history/event-index.ts"]},{code:"event_index_unavailable",exit_code:1,stable:!0,sources:["sdk/mutation-events.ts"]},{code:"exit_code_mismatch",exit_code:1,sources:["sdk/agent/tracker-preflight-contracts.ts"]},{code:"expect_hash_background_unsupported",exit_code:2,sources:["sdk/lifecycle/item-revision.ts"]},{code:"expect_hash_invalid",exit_code:2,sources:["sdk/lifecycle/item-revision.ts"]},{code:"expect_hash_invocation_rewritten",exit_code:2,sources:["sdk/lifecycle/item-revision.ts"]},{code:"expect_hash_requires_mutation",exit_code:2,sources:["sdk/lifecycle/item-revision.ts"]},{code:"expect_hash_target_required",exit_code:2,sources:["sdk/lifecycle/item-revision.ts"]},{code:"expected_revision_duplicate",exit_code:2,sources:["core/store/item-mutation-precondition.ts"]},{code:"expected_revision_scope_conflict",exit_code:2,sources:["core/store/item-mutation-precondition.ts"]},{code:"extension_command_activation_failed",exit_code:1,stable:!0,sources:["cli/commander-usage.ts"]},{code:"extension_dependency_name_unsafe",exit_code:2,stable:!0,sources:["sdk/extension/install-sources.ts"]},{code:"extension_dependency_spec_invalid",exit_code:2,stable:!0,sources:["sdk/extension/install-sources.ts"]},{code:"extension_dependency_version_unsafe",exit_code:2,stable:!0,sources:["sdk/extension/install-sources.ts"]},{code:"extension_flag_value_invalid",exit_code:2,sources:["sdk/extension/command-options.ts"]},{code:"extension_install_incomplete_source_scan",exit_code:2,sources:["sdk/extension/install-plan.ts"]},{code:"extension_install_rollback_failed",exit_code:1,sources:["sdk/extension/install-snapshot.ts"]},{code:"extension_install_soft_failed",exit_code:1,stable:!0,sources:["cli/register-setup.ts"]},{code:"extension_install_source_contains_destination",exit_code:2,stable:!0,sources:["sdk/extension/install-runtime.ts"]},{code:"extension_item_field_reserved",exit_code:2,stable:!0,sources:["core/extensions/item-fields.ts"]},{code:"extension_item_field_type_conflict",exit_code:2,stable:!0,sources:["core/extensions/item-fields.ts"]},{code:"extension_item_field_unknown",exit_code:2,stable:!0,sources:["core/extensions/item-fields.ts"]},{code:"extension_mutation_guard_failed",exit_code:4,stable:!0,sources:["core/extensions/extension-hook-runtime.ts"]},{code:"extension_mutation_guard_invalid_decision",exit_code:4,stable:!0,sources:["core/extensions/extension-hook-runtime.ts"]},{code:"extension_mutation_guard_invalid_denial",exit_code:4,stable:!0,sources:["core/extensions/extension-hook-runtime.ts"]},{code:"extension_mutation_guard_timed_out",exit_code:4,stable:!0,sources:["core/extensions/extension-hook-runtime.ts"]},{code:"extension_option_disabled",exit_code:2,sources:["sdk/extension/command-options.ts"]},{code:"extension_option_spelling_conflict",exit_code:2,sources:["sdk/extension/command-options.ts"]},{code:"extension_read_output_invalid",exit_code:2,sources:["sdk/read-output/extension.ts"]},{code:"extension_update_health_partial_coverage",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"extensions_unreadable",exit_code:1,sources:["sdk/extension/static-inventory.ts"]},{code:"field_duplicate",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"field_invalid",exit_code:2,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"field_mcp_input_collision",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"field_option_collision",exit_code:1,sources:["core/profile/profile-lint.ts"]},{code:"finalization_invalid_document",exit_code:2,sources:["sdk/transactions/item-finalization.ts"]},{code:"github_source_entry_unbuilt",exit_code:2,stable:!0,sources:["sdk/extension/shared.ts"]},{code:"hierarchy_cardinality_created",exit_code:4,sources:["sdk/graph/hierarchy-integrity.ts"]},{code:"hierarchy_cycle_created",exit_code:4,sources:["sdk/graph/hierarchy-integrity.ts"]},{code:"hierarchy_parent_divergence_created",exit_code:4,sources:["sdk/graph/hierarchy-integrity.ts"]},{code:"history_append_only_repair_unavailable",exit_code:4,sources:["sdk/history/append-only-repair.ts"]},{code:"history_author_acknowledge_plan_conflict",exit_code:4,sources:["sdk/author-attribution.ts"]},{code:"history_author_acknowledge_plan_fingerprint_required",exit_code:2,sources:["sdk/author-attribution.ts"]},{code:"history_author_acknowledge_preview_limit_invalid",exit_code:2,sources:["sdk/author-attribution.ts"]},{code:"history_author_acknowledge_required_values_missing",exit_code:2,sources:["sdk/author-attribution.ts"]},{code:"history_author_acknowledge_selector_conflict",exit_code:2,sources:["sdk/author-attribution.ts"]},{code:"history_author_acknowledge_selector_required",exit_code:2,stable:!0,sources:["sdk/author-attribution.ts"]},{code:"history_author_acknowledge_target_not_actionable",exit_code:2,sources:["sdk/author-attribution.ts"]},{code:"history_author_acknowledge_target_unreadable",exit_code:2,sources:["sdk/author-attribution.ts"]},{code:"history_baseline_unavailable",exit_code:1,sources:["core/history/projection.ts"]},{code:"history_compact_boundary_bridged",exit_code:2,sources:["sdk/history-compact.ts"]},{code:"history_drift_chain_mismatch",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_history_drift_chain_mismatches"]},{code:"history_drift_chain_unbridgeable",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"history_drift_hash_mismatch",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_history_drift_hash_mismatches"]},{code:"history_drift_merge_receipt",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"history_drift_missing_stream",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_history_drift_missing_streams"]},{code:"history_drift_unreadable_stream",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_history_drift_unreadable_streams"]},{code:"history_drift_unrepairable_stream",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"history_drift_version_skew",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_history_drift_version_skews"]},{code:"history_json_invalid",exit_code:1,sources:["core/history/read.ts"]},{code:"history_merge_conflict_markers_detected",exit_code:1,stable:!0,sources:["core/history/read.ts"],canonical_code:"merge_conflict_markers_detected"},{code:"history_record_integrity_invalid",exit_code:4,sources:["sdk/history/reanchor-refusal.ts"]},{code:"history_record_invalid",exit_code:1,sources:["core/history/read.ts"]},{code:"history_record_version_unsupported",exit_code:4,sources:["sdk/history/reanchor-refusal.ts"]},{code:"history_redact_bridge_unlocated",exit_code:1,sources:["sdk/history-redact.ts"]},{code:"history_replay_invalid",exit_code:1,sources:["core/history/projection.ts","core/history/tombstone.ts"]},{code:"history_salvage_refused",exit_code:4,sources:["sdk/history/salvage.ts"]},{code:"history_stream_over_compact_threshold",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"history_target_out_of_range",exit_code:1,stable:!0,sources:["core/history/projection.ts"]},{code:"history_timestamp_invalid",exit_code:1,sources:["core/history/event-index.ts","core/history/history.ts"]},{code:"history_union_rebase_conflict",exit_code:4,sources:["sdk/merge/history-scalar-rebase.ts"]},{code:"history_unknown_author_events",exit_code:2,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_history_unknown_author_events"]},{code:"history_version_mapping_unavailable",exit_code:2,sources:["core/history/version-address.ts"]},{code:"history_version_pruned",exit_code:2,sources:["core/history/projection.ts"]},{code:"history_version_unreconstructable",exit_code:2,sources:["core/history/projection.ts"]},{code:"host_environment_capacity_fault",exit_code:1,sources:["core/fs/host-environment-errors.ts"]},{code:"host_environment_operation_invalid",exit_code:2,sources:["core/fs/host-environment-errors.ts"]},{code:"host_environment_permission_fault",exit_code:1,sources:["core/fs/host-environment-errors.ts"]},{code:"host_environment_resource_fault",exit_code:1,sources:["core/fs/host-environment-errors.ts"]},{code:"improvement_metric_contract_conflict",exit_code:4,sources:["sdk/improvement-ledger.ts"]},{code:"improvement_observation_conflict",exit_code:4,sources:["sdk/improvement-ledger.ts"]},{code:"in_progress_idle",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"in_progress_unowned",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"incomplete_allowed_values",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"inconsistent_concept_kind",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"init_existing_settings_requires_force",exit_code:2,stable:!0,sources:["sdk/init.ts"]},{code:"init_gitignore_unwritable",exit_code:1,stable:!0,sources:["sdk/workspace.ts"]},{code:"init_id_prefix_conflict",exit_code:2,stable:!0,sources:["sdk/init.ts"]},{code:"init_id_prefix_path_like",exit_code:2,stable:!0,sources:["sdk/init.ts"]},{code:"integrity_history_conflict_marker",exit_code:4,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_storage_history_conflict_markers"]},{code:"integrity_history_invalid_json",exit_code:2,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"integrity_history_unreadable",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"integrity_item_ahead_format_version",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_format_version_ahead_items"]},{code:"integrity_item_conflict_marker",exit_code:4,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"integrity_item_outdated_format_version",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_format_version_outdated_items"]},{code:"integrity_item_parse_failed",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"integrity_item_unreadable",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"invalid_argument_value",exit_code:2,stable:!0,sources:["cli/error-guidance.ts","core/item/priority.ts","core/shared/url-credentials.ts","core/telemetry/observability.ts","sdk/config.ts","sdk/context-intent-contracts.ts","sdk/dependencies.ts","sdk/governance/assurance-mutation-error.ts","sdk/history-redact.ts","sdk/lifecycle/create.ts","sdk/lifecycle/task-composition.ts","sdk/lifecycle/update-many.ts","sdk/lifecycle/update.ts","sdk/linked-artifacts.ts","sdk/query/next.ts","sdk/runtime-input.ts","sdk/runtime.ts","sdk/runtime/mutation-admission.ts","sdk/runtime/mutation-value-validation.ts","sdk/runtime/schema-preview.ts","sdk/test/run-phases.ts","sdk/workspace.ts"],emitting_commands:["*","create","next","task-composition","update","update-many"]},{code:"invalid_command_usage",exit_code:2,stable:!0,sources:["cli/error-guidance.ts","core/telemetry/observability.ts"]},{code:"invalid_event_cursor",exit_code:2,stable:!0,sources:["sdk/mutation-events.ts"]},{code:"invalid_event_cursor_mode",exit_code:2,sources:["cli/register-list-query.ts","sdk/mutation-events.ts","sdk/runtime-extended-actions.ts"]},{code:"invalid_event_follow_interval",exit_code:2,stable:!0,sources:["sdk/mutation-events.ts"]},{code:"invalid_event_limit",exit_code:2,stable:!0,sources:["sdk/mutation-events.ts"]},{code:"invalid_event_since",exit_code:2,stable:!0,sources:["sdk/mutation-events.ts"]},{code:"invalid_history_analytics_limit",exit_code:2,sources:["sdk/history-analytics.ts"]},{code:"invalid_history_analytics_minimum_sample",exit_code:2,sources:["sdk/history-analytics.ts"]},{code:"invalid_history_analytics_since",exit_code:2,sources:["sdk/history-analytics.ts"]},{code:"invalid_improvement_ledger",exit_code:1,sources:["sdk/improvement-ledger-validation.ts"]},{code:"invalid_improvement_metric",exit_code:2,sources:["sdk/improvement-ledger.ts"]},{code:"invalid_improvement_observation",exit_code:2,sources:["sdk/improvement-ledger.ts"]},{code:"invalid_improvement_observation_limit",exit_code:2,sources:["sdk/improvement-ledger.ts"]},{code:"invalid_improvement_observation_timestamp",exit_code:2,sources:["sdk/improvement-ledger.ts"]},{code:"invalid_provenance_predicate",exit_code:2,stable:!0,sources:["sdk/history-provenance.ts"]},{code:"invalid_query_cursor",exit_code:2,stable:!0,sources:["sdk/pagination.ts","sdk/query/window-pagination.ts"]},{code:"invalid_read_output_session",exit_code:2,sources:["sdk/read-output-session.ts"]},{code:"invalid_reproducible_process_environment",exit_code:2,sources:["sdk/reproducibility/process.ts"]},{code:"invalid_workspace_snapshot_target",exit_code:2,sources:["sdk/workspace-snapshot.ts"]},{code:"item_already_active",exit_code:4,sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"]},{code:"item_already_exists",exit_code:4,stable:!0,sources:["sdk/lifecycle/create.ts"],emitting_commands:["create"]},{code:"item_deleted",exit_code:3,sources:["core/history/tombstone.ts"]},{code:"item_document_encoding_invalid",exit_code:4,sources:["core/store/item-store.ts"]},{code:"item_document_invalid",exit_code:1,stable:!0,sources:["core/item/item-format.ts"]},{code:"item_document_roundtrip_failed",exit_code:1,stable:!0,sources:["core/item/item-format.ts"]},{code:"item_format_version_unsupported",exit_code:4,sources:["core/item/item-format.ts"]},{code:"item_id_collision",exit_code:4,stable:!0,sources:["sdk/lifecycle/copy.ts"],emitting_commands:["copy"]},{code:"item_identity_ambiguous",exit_code:4,sources:["core/store/item-store.ts"]},{code:"item_identity_conflict",exit_code:4,sources:["sdk/governance/validate-history-drift.ts","sdk/lifecycle/item-revision.ts","sdk/merge/three-way.ts","sdk/query/declared-blockers.ts"]},{code:"item_identity_reserved",exit_code:4,sources:["core/history/history.ts"]},{code:"item_not_found",exit_code:3,stable:!0,sources:["cli/error-guidance.ts","core/store/item-store.ts","core/telemetry/observability.ts","sdk/governance/validate-history-drift.ts"]},{code:"item_revision_conflict",exit_code:4,sources:["core/store/item-mutation-precondition.ts"]},{code:"likely_duplicate",exit_code:4,stable:!0,sources:["sdk/similarity.ts"]},{code:"linked_artifact_mutation_conflict",exit_code:2,sources:["sdk/linked-artifacts.ts"]},{code:"linked_artifact_note_conflict",exit_code:4,sources:["sdk/linked-artifacts.ts"]},{code:"linked_artifact_note_key_misread",exit_code:2,sources:["sdk/linked-artifacts.ts"]},{code:"linked_resource_positional_value",exit_code:2,sources:["cli/error-guidance.ts"]},{code:"linked_test_command_immutable",exit_code:2,sources:["sdk/test/update.ts"]},{code:"linked_test_command_not_executable",exit_code:2,sources:["sdk/test/entry.ts"]},{code:"linked_test_context_invalid",exit_code:2,sources:["sdk/test/entry.ts"]},{code:"linked_test_patch_fields_unsupported",exit_code:2,sources:["sdk/test/update.ts"]},{code:"linked_test_remove_no_match",exit_code:3,sources:["sdk/test/execution.ts"]},{code:"linked_test_update_ambiguous",exit_code:2,sources:["sdk/test/update.ts"]},{code:"linked_test_update_no_match",exit_code:3,sources:["sdk/test/update.ts"]},{code:"linked_test_value_not_quoted",exit_code:1,stable:!0,sources:["cli/error-guidance.ts"]},{code:"list_source_incomplete",exit_code:1,stable:!0,sources:["sdk/query/list.ts"],emitting_commands:["list"]},{code:"local_package_archive_unsafe",exit_code:2,stable:!0,sources:["sdk/extension/install-sources.ts"]},{code:"local_source_not_found_bare_name",exit_code:3,stable:!0,sources:["sdk/extension/install-sources.ts"]},{code:"lock_conflict",exit_code:4,stable:!0,sources:["cli/error-guidance.ts","core/lock/lock.ts","core/telemetry/observability.ts"]},{code:"lock_lost",exit_code:4,sources:["core/lock/lock.ts"]},{code:"lock_path_unsafe",exit_code:4,sources:["core/lock/lock-confinement.ts"]},{code:"locks_stale_count",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"locks_unreadable",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"malformed_plan_step_evidence",exit_code:2,stable:!0,sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"]},{code:"managed_state_invalid",exit_code:2,sources:["sdk/extension/static-inventory.ts"]},{code:"managed_state_unreadable",exit_code:1,sources:["sdk/extension/static-inventory.ts"]},{code:"manifest_capabilities_absent",exit_code:1,stable:!0,sources:["sdk/compose.ts"]},{code:"manifest_invalid",exit_code:2,sources:["sdk/extension/static-inventory.ts"]},{code:"manifest_unknown_key",exit_code:1,sources:["core/extensions/manifest-schema.ts"],owned_states:[{state:"author_workspace_manifest_declares_an_unknown_top_level_key",probe_id:"author-manifest-unknown-key",entrypoints:["health"],expected_exit_class:"generic_failure"}]},{code:"manifest_unreadable",exit_code:1,sources:["sdk/extension/static-inventory.ts"]},{code:"mcp_annotation_file_unavailable",exit_code:2,sources:["sdk/runtime-input.ts"]},{code:"mcp_stdin_unavailable",exit_code:2,sources:["sdk/annotations.ts"]},{code:"mcp_task_not_found_or_not_authorized",exit_code:3,sources:["sdk/mcp/tasks.ts"]},{code:"merge_artifacts_ignored",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"merge_bun_launcher_unavailable",exit_code:5,sources:["sdk/merge/install.ts"]},{code:"merge_conflict_markers_detected",exit_code:1,stable:!0,sources:["core/item/item-format.ts"],aliases:["history_merge_conflict_markers_detected"]},{code:"merge_decisions_unreviewed",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"merge_driver_configuration_drift",exit_code:1,sources:["core/diagnostics/remediation.ts"]}];var Tg=[{code:"merge_driver_configuration_missing",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"merge_fence_drift",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"merge_fence_missing",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"merge_git_config_unwritable",exit_code:5,stable:!0,sources:["sdk/merge/install.ts"]},{code:"merge_receipt_evidence_invalid",exit_code:4,sources:["core/diagnostics/remediation.ts","sdk/merge/reconcile.ts"]},{code:"merge_receipt_history_reference_missing",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"merge_receipt_not_portable",exit_code:4,sources:["sdk/merge/receipts.ts"]},{code:"merge_receipts_pending",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"merge_reconcile_receipt_evidence_untrusted",exit_code:4,sources:["sdk/history-repair.ts"]},{code:"merge_root_not_found",exit_code:3,stable:!0,sources:["sdk/merge/install.ts"]},{code:"merge_settlement_hook_conflict",exit_code:4,sources:["sdk/merge/settlement-hook.ts"]},{code:"merge_settlement_review_required",exit_code:4,sources:["sdk/merge/ignored-artifacts.ts","sdk/merge/reconcile.ts","sdk/merge/stage.ts"]},{code:"missing_allowed_values",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"missing_budget",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"missing_cli_flag",exit_code:1,sources:["sdk/cli-contracts/tool-option-contracts.ts"]},{code:"missing_destination",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"missing_directory",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"missing_init_recovery",exit_code:1,sources:["sdk/agent/tracker-preflight-contracts.ts"]},{code:"missing_lifecycle_target",exit_code:2,stable:!0,sources:["sdk/extension.ts"]},{code:"missing_observation",exit_code:1,sources:["sdk/flag-invocation-contracts.ts"]},{code:"missing_observed_signature",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"missing_parameter_alias",exit_code:1,sources:["sdk/cli-contracts/tool-option-contracts.ts"]},{code:"missing_positive_execution_receipt",exit_code:1,sources:["sdk/test/execution.ts"]},{code:"missing_probe",exit_code:1,sources:["sdk/agent/tracker-preflight-contracts.ts"]},{code:"missing_required_argument",exit_code:2,stable:!0,sources:["cli/error-guidance.ts","cli/main.ts","cli/register-mutation.ts","cli/schema/registration.ts","core/telemetry/observability.ts","sdk/governance/assurance-action.ts","sdk/history-redact.ts","sdk/invocation-author.ts","sdk/lifecycle/claim.ts","sdk/linked-artifacts.ts"],emitting_commands:["*","claim"]},{code:"missing_required_option",exit_code:2,stable:!0,sources:["cli/error-guidance.ts","core/telemetry/observability.ts","sdk/context-intent-contracts.ts","sdk/extension/command-options.ts","sdk/lifecycle/create.ts","sdk/lifecycle/plan.ts"],emitting_commands:["*","create","plan"]},{code:"missing_suggested_retry",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"missing_suggested_retry_args",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"module_import_failed",exit_code:1,stable:!0,sources:["cli/error-guidance.ts"]},{code:"multi_target_github_install_ambiguous",exit_code:2,stable:!0,sources:["cli/register-setup.ts"]},{code:"mutation_author_required",exit_code:2,stable:!0,sources:["sdk/mutation-guard.ts"]},{code:"mutation_document_unreadable",exit_code:2,sources:["cli/register-structured-mutation.ts"]},{code:"mutation_option_value_invalid",exit_code:2,sources:["sdk/lifecycle/mutation-option-validation.ts"],emitting_commands:["item mutate"]},{code:"mutation_secret_guard_blocked",exit_code:4,stable:!0,sources:["sdk/mutation-guard.ts"]},{code:"no_matching_tests",exit_code:1,stable:!0,sources:["sdk/test/execution-receipts.ts"]},{code:"no_projects_matched_filters",exit_code:1,stable:!0,sources:["sdk/test/execution-receipts.ts"]},{code:"no_test_files_found",exit_code:1,stable:!0,sources:["sdk/test/execution-receipts.ts"]},{code:"no_tests_found",exit_code:1,stable:!0,sources:["sdk/test/execution-receipts.ts"]},{code:"no_update_fields",exit_code:1,stable:!0,sources:["cli/error-guidance.ts","core/telemetry/observability.ts"]},{code:"no_version_bounds_declared",exit_code:1,sources:["core/extensions/manifest-schema.ts"],owned_states:[{state:"author_workspace_manifest_omits_canonical_pm_version_bounds",probe_id:"author-manifest-version-bounds-missing",entrypoints:["health"],expected_exit_class:"generic_failure"}]},{code:"non_refusal_exit",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"npm_pack_json_shape_unsupported",exit_code:1,sources:["sdk/extension/install-sources.ts"]},{code:"npm_package_archive_missing",exit_code:1,sources:["sdk/extension/install-sources.ts"]},{code:"npm_package_archive_unsafe",exit_code:1,sources:["sdk/extension/install-sources.ts"]},{code:"npm_package_not_found",exit_code:3,stable:!0,sources:["sdk/extension/install-sources.ts"]},{code:"output_budget_exceeded",exit_code:2,sources:["sdk/testing.ts"]},{code:"ownership_conflict",exit_code:4,stable:!0,sources:["cli/error-guidance.ts","core/telemetry/observability.ts","sdk/annotations.ts"]},{code:"ownership_dependency_bypass_restricted_options",exit_code:1,stable:!0,sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"]},{code:"ownership_metadata_bypass_restricted_options",exit_code:1,stable:!0,sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"]},{code:"package_spec_empty",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"package_upgrade_modes_mutually_exclusive",exit_code:2,sources:["sdk/governance/upgrade.ts"]},{code:"positional_shape_budget_exceeded",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"positional_signature_mismatch",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"profile_name_empty",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"profile_name_not_normalized",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"profile_summary_empty",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"profile_title_empty",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"project_runtime_history_epoch_incompatible",exit_code:4,sources:["sdk/environment/project-runtime-compatibility.ts"]},{code:"project_runtime_item_format_incompatible",exit_code:4,sources:["sdk/environment/project-runtime-compatibility.ts"]},{code:"project_runtime_stale_mutation",exit_code:4,sources:["sdk/environment/project-runtime-compatibility.ts"]},{code:"project_runtime_stale_read",exit_code:1,sources:["sdk/environment/project-runtime-compatibility.ts"]},{code:"project_schema_field_requires_declared_flag",exit_code:2,sources:["core/extensions/item-fields.ts"]},{code:"projection_options_mutually_exclusive",exit_code:2,sources:["sdk/query/get.ts","sdk/query/list.ts","sdk/query/search-contracts.ts"],emitting_commands:["get","list","search"]},{code:"provenance_value_domain_invalid",exit_code:2,sources:["core/diagnostics/remediation.ts"]},{code:"read_output_cursor_command_mismatch",exit_code:2,sources:["sdk/read-output/continuation.ts"]},{code:"read_output_cursor_invalid",exit_code:2,sources:["sdk/read-output/continuation.ts"]},{code:"read_output_cursor_stale",exit_code:2,sources:["sdk/read-output/continuation.ts"]},{code:"read_output_mutation_conflict",exit_code:2,sources:["sdk/read-output-contracts.ts"]},{code:"recovery_kind_mismatch",exit_code:1,sources:["sdk/agent/tracker-preflight-contracts.ts"]},{code:"redundant_edge",exit_code:1,stable:!0,sources:["sdk/graph/remediation.ts"]},{code:"refusal_allowed_values_mismatch",exit_code:1,sources:["sdk/agent/refusal-corpus-contracts.ts"]},{code:"refusal_error_code_mismatch",exit_code:1,sources:["sdk/agent/refusal-corpus-contracts.ts"]},{code:"refusal_exit_code_mismatch",exit_code:1,sources:["sdk/agent/refusal-corpus-contracts.ts"]},{code:"refusal_mutated_state",exit_code:1,sources:["sdk/agent/refusal-corpus-contracts.ts"]},{code:"refusal_probe_missing",exit_code:1,sources:["sdk/agent/refusal-corpus-contracts.ts"]},{code:"refusal_recovery_failed",exit_code:1,sources:["sdk/agent/refusal-corpus-contracts.ts"]},{code:"reindex_already_running",exit_code:4,stable:!0,sources:["sdk/governance/reindex.ts"]},{code:"removed_canonical_spelling",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"removed_compatibility_spelling",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"reopen_reason_required",exit_code:2,sources:["sdk/lifecycle/reopen.ts"],emitting_commands:["item reopen"]},{code:"reopen_receipt_missing",exit_code:1,sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"]},{code:"reopen_target_status_invalid",exit_code:2,sources:["sdk/lifecycle/reopen.ts"],emitting_commands:["item reopen"]},{code:"reported_zero_passes",exit_code:1,sources:["sdk/test/execution-receipts.ts"]},{code:"reported_zero_tests",exit_code:1,sources:["sdk/test/execution-receipts.ts"]},{code:"reserved_item_field",exit_code:1,stable:!0,sources:["sdk/compose.ts"]},{code:"retry_failed",exit_code:1,sources:["sdk/agent/refusal-closure.ts","sdk/agent/tracker-preflight-contracts.ts"]},{code:"schema_field_option_collision",exit_code:2,sources:["sdk/schema/field-option-collisions.ts"]},{code:"schema_migration_input_required",exit_code:2,stable:!0,sources:["cli/migration-gates.ts"]},{code:"semantic_spelling_collision",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"settings_invalid",exit_code:2,sources:["sdk/extension/static-inventory.ts"]},{code:"settings_read_fs_error",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"settings_read_invalid_json",exit_code:2,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"settings_read_invalid_schema",exit_code:2,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"settings_read_merge_failed",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"settings_section_document_malformed",exit_code:2,sources:["core/store/settings-sections.ts"]},{code:"settings_section_document_missing",exit_code:3,sources:["core/store/settings-sections.ts"]},{code:"settings_section_invalid",exit_code:2,sources:["core/store/settings-sections.ts"]},{code:"settings_section_name_invalid",exit_code:2,sources:["core/store/settings-sections.ts"]},{code:"settings_section_reserved",exit_code:2,sources:["core/store/settings-sections.ts"]},{code:"settings_section_revision_conflict",exit_code:4,sources:["core/store/settings-sections.ts"]},{code:"settings_unreadable",exit_code:1,sources:["sdk/extension/static-inventory.ts"]},{code:"settings_write_assigned_path_invalid",exit_code:2,sources:["core/store/settings.ts"]},{code:"settings_write_invalid_existing_json",exit_code:2,sources:["core/store/settings.ts"]},{code:"settings_write_invalid_existing_schema",exit_code:2,sources:["core/store/settings.ts"]},{code:"stale_budget",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"stale_claim_takeover_refused",exit_code:4,sources:["sdk/lifecycle/claim.ts"],emitting_commands:["claim"]},{code:"stale_destination",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"stale_in_progress_items",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"stale_lock_requires_override",exit_code:4,sources:["core/lock/lock.ts"]},{code:"stale_observed_signature",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"stale_revision",exit_code:4,sources:["core/store/item-store.ts"]},{code:"start_blocked_by_open_dependency",exit_code:4,sources:["sdk/lifecycle/start-blockers.ts"],emitting_commands:["claim","start-task","update"]},{code:"status_duplicate",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"status_invalid",exit_code:2,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"status_lifecycle_role_required",exit_code:2,sources:["sdk/schema.ts"]},{code:"stdin_json_invalid",exit_code:2,stable:!0,sources:["sdk/structured-mutations.ts"]},{code:"stdin_json_persisted_annotation_changed",exit_code:2,sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"]},{code:"stdin_json_unknown_key",exit_code:2,stable:!0,sources:["sdk/structured-mutations.ts"]},{code:"structured_entry_key_repeated",exit_code:2,sources:["core/item/parse.ts"]},{code:"structured_event_immutable",exit_code:2,stable:!0,sources:["sdk/annotations.ts"]},{code:"structured_event_input_conflict",exit_code:2,stable:!0,sources:["sdk/notes.ts"]},{code:"structured_event_json_empty",exit_code:2,stable:!0,sources:["sdk/notes.ts"]},{code:"structured_event_json_invalid",exit_code:2,stable:!0,sources:["sdk/notes.ts"]},{code:"structured_event_since_invalid",exit_code:2,stable:!0,sources:["sdk/notes.ts"]},{code:"suggested_retry_args_mismatch",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"telemetry_endpoint_probe_failed",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"telemetry_endpoint_probe_http_status",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"telemetry_otel_export_failing",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"telemetry_queue_high_retries",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"telemetry_queue_invalid_rows",exit_code:2,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"telemetry_queue_pending",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"telemetry_schema_version_behind",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"telemetry_state_invalid_json",exit_code:2,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"template_type_unknown",exit_code:2,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"terminal_plan_mutation",exit_code:4,stable:!0,sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"]},{code:"terminal_state_conflict",exit_code:4,stable:!0,sources:["core/telemetry/observability.ts","sdk/lifecycle/claim.ts"],emitting_commands:["*","claim"]},{code:"test_measure_requires_execution",exit_code:2,sources:["sdk/test/prerequisites.ts"]},{code:"test_measure_requires_run",exit_code:2,sources:["sdk/test/prerequisites.ts"]},{code:"text_unpaired_surrogate",exit_code:2,sources:["core/item/item-format.ts","core/shared/output-unicode.ts"]},{code:"tracked_runtime_cache_files",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_storage_tracked_runtime_cache_files"]},{code:"tracker_not_initialized",exit_code:3,stable:!0,sources:["cli/error-guidance.ts","core/store/tracker-preflight.ts","core/telemetry/observability.ts"],owned_states:[{state:"selected_tracker_root_exists_without_settings",probe_id:"tracker-root-settings-missing",entrypoints:["list"],expected_exit_class:"not_found"}]},{code:"tracker_root_missing",exit_code:3,stable:!0,sources:["core/store/tracker-preflight.ts"],owned_states:[{state:"selected_tracker_root_does_not_exist",probe_id:"tracker-root-missing",entrypoints:["list"],expected_exit_class:"not_found"}]},{code:"tracker_root_not_directory",exit_code:2,stable:!0,sources:["core/store/tracker-preflight.ts"],owned_states:[{state:"selected_tracker_root_is_a_regular_file",probe_id:"tracker-root-not-directory",entrypoints:["list"],expected_exit_class:"usage"}]},{code:"tracker_root_unreadable",exit_code:1,sources:["core/store/tracker-preflight.ts"],owned_states:[{state:"selected_tracker_root_is_not_readable",probe_id:"tracker-root-unreadable",entrypoints:["list"],expected_exit_class:"generic_failure"}]},{code:"transaction_abandoned",exit_code:4,sources:["sdk/workspace-transaction.ts"]},{code:"transaction_committed",exit_code:4,sources:["sdk/workspace-transaction.ts"]},{code:"transaction_create_compensated",exit_code:4,sources:["sdk/item-transaction.ts"]},{code:"transaction_journal_invalid",exit_code:4,sources:["sdk/workspace-transaction.ts"]},{code:"transaction_partial_mutation",exit_code:4,sources:["sdk/item-transaction.ts"]},{code:"transaction_plan_mismatch",exit_code:4,sources:["sdk/workspace-transaction.ts"]},{code:"transaction_preview_external_schema",exit_code:2,sources:["sdk/item-transaction.ts"]},{code:"transaction_preview_non_regular_file",exit_code:2,sources:["core/fs/fs-utils.ts"]},{code:"transaction_preview_snapshot_changed",exit_code:4,sources:["sdk/item-transaction.ts"]},{code:"transaction_recovery_plan_missing",exit_code:4,sources:["sdk/item-transaction.ts"]},{code:"type_duplicate",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"type_invalid",exit_code:2,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"undeclared_observation",exit_code:1,sources:["sdk/flag-invocation-contracts.ts"]},{code:"unexpected_refusal_probe",exit_code:1,sources:["sdk/agent/refusal-corpus-contracts.ts"]},{code:"unknown_command",exit_code:2,stable:!0,sources:["cli/error-guidance.ts","core/telemetry/observability.ts","sdk/cli-contracts/runtime-contracts.ts"]},{code:"unknown_context_intent",exit_code:2,stable:!0,sources:["sdk/context-intent-contracts.ts"]},{code:"unknown_error",exit_code:1,stable:!0,sources:["cli/error-guidance.ts"]},{code:"unknown_field",exit_code:3,stable:!0,sources:["sdk/schema.ts"]},{code:"unknown_field_projection",exit_code:2,stable:!0,sources:["sdk/query/get.ts","sdk/query/list.ts","sdk/query/search-contracts.ts"],emitting_commands:["get","list","search"]},{code:"unknown_item_type",exit_code:3,stable:!0,sources:["sdk/schema.ts"]},{code:"unknown_lifecycle_action",exit_code:2,stable:!0,sources:["sdk/agent/subcommand-recovery.ts"],canonical_code:"unknown_subcommand"},{code:"unknown_noun",exit_code:2,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"unknown_option",exit_code:2,stable:!0,sources:["cli/error-guidance.ts","cli/runtime/invocation-options.ts","core/telemetry/observability.ts","sdk/extension/command-options.ts"],owned_states:[{state:"declared_option_is_rejected_on_the_selected_command_path",probe_id:"cross-command-unknown-option",entrypoints:["deps"],expected_exit_class:"usage"}]},{code:"unknown_plan_template",exit_code:2,stable:!0,sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"]},{code:"unknown_provenance_dimension",exit_code:2,stable:!0,sources:["sdk/history-provenance.ts"]},{code:"unknown_status",exit_code:3,stable:!0,sources:["sdk/schema.ts"]},{code:"unknown_subcommand",exit_code:2,stable:!0,sources:["cli/error-guidance.ts","sdk/agent/subcommand-recovery.ts"],aliases:["unknown_lifecycle_action"],owned_states:[{state:"config_action_token_is_not_declared",probe_id:"config-unknown-action",entrypoints:["config"],expected_exit_class:"usage"},{state:"graph_command_token_is_not_declared",probe_id:"graph-unknown-subcommand",entrypoints:["graph"],expected_exit_class:"usage"},{state:"nested_command_token_is_not_declared_by_its_family",probe_id:"schema-unknown-subcommand",entrypoints:["schema"],expected_exit_class:"usage"},{state:"package_lifecycle_token_is_not_declared",probe_id:"package-unknown-action",entrypoints:["package"],expected_exit_class:"usage"}]},{code:"unsafe_init_recovery",exit_code:1,sources:["sdk/agent/tracker-preflight-contracts.ts"]},{code:"unsupported_update_option",exit_code:1,stable:!0,sources:["cli/error-guidance.ts"]},{code:"upsert_key_ambiguous",exit_code:4,sources:["sdk/structured-mutations.ts"]},{code:"upsert_key_conflict",exit_code:4,sources:["sdk/item-transaction.ts"]},{code:"upsert_key_duplicate",exit_code:2,sources:["sdk/item-transaction.ts","sdk/structured-mutations.ts"]},{code:"upsert_key_missing",exit_code:2,sources:["sdk/structured-mutations.ts"]},{code:"upsert_match_changed",exit_code:4,sources:["sdk/item-transaction.ts"]},{code:"validate_command_references_stale_pm_ids",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_files_missing_linked_paths",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_files_orphaned_paths",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_files_tracked_all_strict_forces_pm_internals",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_format_version_ahead_items",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"integrity_item_ahead_format_version"},{code:"validate_format_version_outdated_items",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"integrity_item_outdated_format_version"},{code:"validate_hierarchy_parent_cycle",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_hierarchy_parent_cycle_error",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_history_drift_chain_mismatches",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"history_drift_chain_mismatch"},{code:"validate_history_drift_hash_mismatches",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"history_drift_hash_mismatch"},{code:"validate_history_drift_missing_streams",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"history_drift_missing_stream"},{code:"validate_history_drift_unreadable_streams",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"history_drift_unreadable_stream"},{code:"validate_history_drift_version_skews",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"history_drift_version_skew"},{code:"validate_history_unknown_author_events",exit_code:2,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"history_unknown_author_events"},{code:"validate_lifecycle_active_closure_like_metadata",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_lifecycle_active_terminal_parent",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_lifecycle_dependency_cycles",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_lifecycle_dependency_cycles_error",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_lifecycle_stale_blockers",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_merge_decisions_unreviewed",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"validate_merge_driver_configuration",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"validate_merge_fence_drift",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_custom_profile_missing_required_fields",exit_code:2,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_duplicate_issue_codes",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_acceptance_criteria",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_close_reason",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_closed_at",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_confidence",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_estimate",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_release",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_reviewer",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_risk",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_sprint",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_resolution_missing_fields",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_schema_field_option_collision",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"validate_storage_duplicate_item_ids",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_storage_history_conflict_markers",exit_code:4,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"integrity_history_conflict_marker"},{code:"validate_storage_resurrected_items",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_storage_tracked_runtime_cache_files",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"tracked_runtime_cache_files"},{code:"validate_storage_unparseable_config",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_storage_unparseable_history",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_storage_unreadable_items",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"vectorization_embedding_identity_changed",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"vectorization_stale_items_remaining",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"visible_surface_ceiling_exceeded",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"workflow_duplicate_type",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"workflow_policy_approval_history_invalid",exit_code:4,sources:["core/policy/workflow-policy-store.ts"]},{code:"workflow_policy_audit_failed",exit_code:4,sources:["core/policy/workflow-policy-store.ts"]},{code:"workflow_policy_input_unreadable",exit_code:4,sources:["core/policy/workflow-policy-store.ts"]},{code:"workflow_policy_invalid",exit_code:2,sources:["core/policy/workflow-policy.ts"]},{code:"workflow_policy_refused",exit_code:4,sources:["core/policy/workflow-policy-store.ts"]},{code:"workflow_policy_registry_invalid",exit_code:4,sources:["core/policy/workflow-policy-store.ts"]},{code:"workflow_status_unknown",exit_code:2,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"workflow_transition_malformed",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"workflow_type_empty",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"workflow_type_unknown",exit_code:2,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"workspace_history_chain_invalid",exit_code:4,sources:["core/history/workspace-history.ts"]},{code:"workspace_history_state_conflict",exit_code:4,stable:!0,sources:["core/history/workspace-history.ts"]},{code:"workspace_root_pm_path",exit_code:2,stable:!0,sources:["sdk/init.ts"]},{code:"workspace_snapshot_force_required",exit_code:2,sources:["sdk/workspace-snapshot.ts"]},{code:"workspace_snapshot_manifest_mismatch",exit_code:4,sources:["sdk/workspace-snapshot.ts"]},{code:"workspace_snapshot_name_reserved_fingerprint",exit_code:2,sources:["sdk/workspace-snapshot.ts"]},{code:"workspace_snapshot_not_found",exit_code:3,sources:["sdk/workspace-snapshot.ts"]},{code:"workspace_snapshot_permission_denied",exit_code:1,sources:["sdk/workspace-snapshot.ts"]},{code:"workspace_snapshot_resource_exhausted",exit_code:1,sources:["sdk/workspace-snapshot.ts"]},{code:"workspace_snapshot_storage_exhausted",exit_code:1,sources:["sdk/workspace-snapshot.ts"]},{code:"wrong_item_type",exit_code:2,stable:!0,sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"]}];var Rg=Eg(Ag([...Cg,...Tg]));var lC=["mutation_receipt","entity","collection","diagnostic","stream"],uC=new Set(["append","claim","close","close-task","copy","create","delete","focus","pause-task","release","restore","start-task","update"]),mC=new Set(["close-many","update-many"]),fC=new Set(["activity","comments","contracts","events","history","learnings","list","notes","search"]),pC=new Set(["aggregate","deps","graph","health","history-redact","history-repair","history-compact","stats","validate"]);function Kr(e){if(e.command.trim().length===0)throw new TypeError("command must be a non-empty command path");if(!lC.includes(e.kind))throw new TypeError(`Unsupported output envelope kind: ${e.kind}`);return e}function Ig(e){let t=e.trim().replace(/\s+/gu," "),[n=t]=t.split(" ");return mC.has(n)?Kr({command:t,kind:"collection",wrapper_key:"rows",cardinality:"many",format_flag:"--json"}):uC.has(n)?Kr({command:t,kind:"mutation_receipt",wrapper_key:null,cardinality:"one",format_flag:"--json"}):fC.has(n)?Kr({command:t,kind:"collection",wrapper_key:n==="contracts"?null:"items",cardinality:"many",format_flag:"--json"}):pC.has(n)?Kr({command:t,kind:"diagnostic",wrapper_key:null,cardinality:"none",format_flag:"--json"}):Kr({command:t,kind:n==="get"?"entity":"diagnostic",wrapper_key:n==="get"?"item":null,cardinality:n==="get"?"one":"none",format_flag:"--json"})}var _C=ot.map(e=>Ig(e)),hC=new Map(_C.map(e=>[e.command,e]));function Og(e){let t=e.trim().replace(/\s+/gu," ");if(t.length===0)throw new TypeError("command must be a non-empty command path");let[n=t]=Ps(t).split(" "),r=hC.get(n);return r?{...r,command:t}:Ig(t)}function gC(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function yC(e){return gC(e)&&typeof e.id=="string"&&e.id.length>0&&typeof e.status=="string"&&e.status.length>0&&Number.isSafeInteger(e.changed_field_count)&&Number(e.changed_field_count)>=0&&(e.close_reason===void 0||typeof e.close_reason=="string")&&(e.deleted===void 0||typeof e.deleted=="boolean")&&(e.previous_status===void 0||typeof e.previous_status=="string")&&(e.warnings===void 0||Array.isArray(e.warnings))}function SW(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch(n){throw new TypeError(`Mutation receipt must be valid JSON: ${String(n)}`,{cause:n})}if(!yC(t))throw new TypeError("Mutation receipt must be a flat object with top-level id, status, and changed_field_count fields");return{id:t.id,status:t.status,changedFieldCount:t.changed_field_count,...typeof t.close_reason=="string"?{closeReason:t.close_reason}:{},...typeof t.deleted=="boolean"?{deleted:t.deleted}:{},...typeof t.previous_status=="string"?{previousStatus:t.previous_status}:{},...Array.isArray(t.warnings)?{warnings:t.warnings}:{}}}var Bc=[{exit_code:m.SUCCESS,outcome:"effect",success:!0,meaning:"The requested operation completed with its intended effect."},{exit_code:m.GENERIC_FAILURE,outcome:"internal_failure",success:!1,meaning:"An unexpected runtime or internal failure prevented completion."},{exit_code:m.USAGE,outcome:"refused_input",success:!1,meaning:"The invocation was refused because its input or composition was invalid."},{exit_code:m.NOT_FOUND,outcome:"refused_tracker_state",success:!1,meaning:"The requested tracker, item, or resource was not present."},{exit_code:m.CONFLICT,outcome:"conflict",success:!1,meaning:"Current state or concurrency prevented the requested effect."},{exit_code:m.DEPENDENCY_FAILED,outcome:"dependency_failed",success:!1,meaning:"A required dependency operation failed."},{exit_code:m.NO_EFFECT,outcome:"no_effect",success:!0,meaning:"The request was valid and completed, but matched nothing to change."},{exit_code:m.PARTIAL_EFFECT,outcome:"partial_effect",success:!0,meaning:"The request completed and changed some, but not all, selected targets."}],Lg=[m.SUCCESS,m.GENERIC_FAILURE,m.USAGE,m.NOT_FOUND,m.CONFLICT,m.DEPENDENCY_FAILED],wC=new Set(["close-many","update-many"]),Ng=ot.map(e=>({command:e,exit_codes:wC.has(e)?[...Lg,m.NO_EFFECT,m.PARTIAL_EFFECT]:[...Lg]})),$g=new Map(Ng.map(e=>[e.command,e])),vC=[m.SUCCESS,m.NO_EFFECT,m.PARTIAL_EFFECT];function TW(e){return vC.includes(e)}function RW(e){return Bc.some(t=>t.exit_code===e)}function Mg(e){let t=e.trim().toLowerCase().split(/\s+/u).filter(Boolean).join(" ");return $g.get(t)??$g.get(t.split(" ")[0])}function IW(e,t=ot,n=Ng){let r=new Map(n.map(d=>[d.command,d])),s=t.filter(d=>!r.has(d)),i=e.filter(d=>{let l=r.get(d.command)??r.get(d.command.split(" ")[0]);return l===void 0||!l.exit_codes.includes(d.exit_code)}),o=new Set(e.map(d=>d.exit_code)),c=[...new Set(n.flatMap(d=>d.exit_codes))].filter(d=>!o.has(d)).sort((d,l)=>d-l);return{ok:s.length===0&&i.length===0&&c.length===0,missing_commands:s,undeclared_observations:i,unreachable_exit_codes:c}}function OW(e){return e.applied===0&&e.failed>0?{outcome:"dependency_failed",exit_code:m.DEPENDENCY_FAILED}:e.applied===0?{outcome:"no_effect",exit_code:m.NO_EFFECT}:e.skipped>0||e.failed>0||e.unmatched>0?{outcome:"partial_effect",exit_code:m.PARTIAL_EFFECT}:{outcome:"effect",exit_code:m.SUCCESS}}var M=class extends TypeError{constructor(t){super(t),this.name="AssuranceMutationRefusalError"}},Ne=class extends TypeError{context;constructor(t,n={}){super(t),this.name="AssuranceEvaluationRefusalError",this.context=n}},ut=class extends TypeError{measurement_id;source_kind;field;check;constructor(t,n){super(t),this.name="AssuranceSourceResolutionError",this.measurement_id=n.measurement_id,this.source_kind=n.source_kind,this.field=n.field,this.check=n.check}};async function zn(e){try{return await e()}catch(t){throw t instanceof M?new p(t.message,m.USAGE,{code:"invalid_argument_value",reason:"assurance_mutation_refused"}):t}}async function Hc(e){try{return await e()}catch(t){throw t instanceof Ne?new p(t.message,m.USAGE,{code:"invalid_argument_value",reason:"assurance_evaluation_refused",...t.context}):t}}import{createHash as kC}from"node:crypto";import bC from"node:path";var Fg=1,vt=["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"],zr=["items","dependency_kind","prose_edge_gap","graph","validate","health","history","links","provider","derived"],xC=["ceiling","floor","equals","zero","monotone_nondecreasing","monotone_nonincreasing","subset_of"],SC=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,ji=30,Ui=5e3,Dg=4,EC=50;function kt(e,t){if(!SC.test(e))throw new M(`${t} must be a stable lowercase id`)}function AC(e,t){if(!Number.isFinite(e)||e<0)throw new M(`${t} must be a finite non-negative number`)}function Hr(e){let t=xC.filter(s=>e[s]!==void 0);if(t.length!==1)throw new M(`assertion ${e.id} must declare exactly one polarity`);let n=t[0],r=e[n];return{polarity:n,value:n==="zero"?0:r}}function Yc(e,t){return Z(e)===Z(t)}function jg(e,t){if(t.polarity==="equals")return Yc(e,t.value);if(t.polarity==="subset_of"){if(!Array.isArray(e)||!Array.isArray(t.value))return!1;let r=t.value;return e.every(s=>r.includes(s))}if(typeof e!="number")return!1;let n=t.value;return t.polarity==="ceiling"||t.polarity==="monotone_nonincreasing"?e<=n:t.polarity==="floor"||t.polarity==="monotone_nondecreasing"?e>=n:e===0}function Ug(e){let t=Hr(e),n=e.negative_control.cases;return n.some(r=>r.expected==="pass")&&n.some(r=>r.expected==="fail")&&n.every(r=>jg(r.observed,t)===(r.expected==="pass"))}function CC(e,t){if(e.polarity!==t.polarity)return!0;if(typeof e.value=="number"&&typeof t.value=="number")return e.polarity==="ceiling"||e.polarity==="monotone_nonincreasing"?t.value>e.value:e.polarity==="floor"||e.polarity==="monotone_nondecreasing"?t.value<e.value:t.value!==e.value;if(e.polarity==="subset_of"){let n=e.value,r=t.value;return!Array.isArray(n)||!Array.isArray(r)||r.some(s=>!n.includes(s))}return!Yc(e.value,t.value)}function TC(e,t){if(e.measurement_id!==t.measurement_id||e.owner_item_id!==t.owner_item_id||Z(e.scope)!==Z(t.scope))return!0;let n={observe:0,warn:1,block:2},r=(e.lifetime??"hold")==="hold"&&(t.lifetime??"hold")==="retire";return CC(Hr(e),Hr(t))||n[t.enforcement]<n[e.enforcement]||r}function RC(e){if(e.state!==void 0&&!(e.state==="present"||e.state==="missing"))throw new M("items source state must be present or missing");let t=Object.hasOwn(e,"equals"),n=e.state!==void 0,r=Number(t)+Number(n);if(e.field!==void 0&&r!==1)throw new M("items source with field requires exactly one of equals or state");if(e.field===void 0&&r!==0)throw new M("items source equals/state requires field")}function IC(e){if(typeof e.dependency_kind!="string"||e.dependency_kind.trim().length===0)throw new M("dependency_kind source requires dependency_kind");if([e.source_kind,e.source_kind_prefix,e.source_kind_state].filter(n=>n!==void 0).length>1)throw new M("dependency_kind source accepts at most one source_kind predicate");if(e.source_kind!==void 0&&e.source_kind.trim().length===0||e.source_kind_prefix!==void 0&&e.source_kind_prefix.trim().length===0)throw new M("dependency_kind source provenance values must not be empty");if(e.source_kind_state!==void 0&&e.source_kind_state!=="present"&&e.source_kind_state!=="missing")throw new M("dependency_kind source source_kind_state must be present or missing")}function OC(e){if(e.sample_limit!==void 0&&(!Number.isInteger(e.sample_limit)||e.sample_limit<1))throw new M("prose_edge_gap sample_limit must be a positive integer");for(let t of e.exemptions??[]){if(typeof t.holder_id!="string"||t.holder_id.trim().length===0||typeof t.reason!="string"||t.reason.trim().length===0)throw new M("prose_edge_gap exemptions require holder_id and reason");if(t.target_id!==void 0&&t.target_id.trim().length===0||t.text_contains!==void 0&&t.text_contains.trim().length===0)throw new M("prose_edge_gap exemption selectors must not be empty")}}function Jc(e){kt(e.id,"measurement.id"),e.max_cost!==void 0&&AC(e.max_cost,"measurement.max_cost");let t=e.source;if(Object.prototype.toString.call(t)!=="[object Object]")throw new M(`measurement.source.kind must be one of ${zr.join(", ")}`);let n=Reflect.get(t,"kind");if(!zr.includes(n))throw new M(`measurement.source.kind must be one of ${zr.join(", ")}`);let r=t;if(r.kind==="items"&&RC(r),r.kind==="dependency_kind"&&IC(r),r.kind==="prose_edge_gap"&&OC(r),(r.kind==="graph"||r.kind==="validate"||r.kind==="health")&&(typeof r.field!="string"||r.field.trim().length===0))throw new M(`${r.kind} source requires field`);return r.kind==="provider"&&(kt(r.provider,"provider source provider"),kt(r.key,"provider source key")),e}function Xc(e){if(kt(e.id,"assertion.id"),kt(e.measurement_id,"assertion.measurement_id"),typeof e.owner_item_id!="string"||e.owner_item_id.trim().length===0)throw new M("assertion.owner_item_id is required");let t=Hr(e);if(typeof t.value=="number"&&!Number.isFinite(t.value))throw new M(`assertion.${t.polarity} must be a finite number`);if(e.lifetime==="retire"&&(typeof e.retire_reason!="string"||e.retire_reason.trim().length===0))throw new M("retired assertion requires retire_reason");e.scope.kind==="filter"&&kt(e.scope.measurement_id,"assertion.scope.measurement_id");let n=e.negative_control?.cases;if(!Array.isArray(n)||!n.some(r=>r.expected==="pass")||!n.some(r=>r.expected==="fail"))throw new M("assertion negative control requires pass and fail cases");if(!Ug(e))throw new M(`assertion ${e.id} negative control does not prove its bound`);return e}function LC(e){if(!Array.isArray(e.allowed_providers))throw new M("gate provider_policy.allowed_providers must be an array");for(let t of e.allowed_providers)kt(t,"gate.provider_policy.allowed_provider");if(typeof e.triggers!="object"||e.triggers===null||Array.isArray(e.triggers))throw new M("gate provider_policy.triggers must be an object");for(let[t,n]of Object.entries(e.triggers)){if(!vt.includes(t))throw new M(`gate provider policy has unknown trigger ${t}`);if(typeof n!="object"||n===null||!["low","medium","high"].includes(n.max_cost_class)||typeof n.allow_network!="boolean")throw new M(`gate provider policy trigger ${t} is invalid`)}}function Gg(e){if(kt(e.id,"gate.id"),!Array.isArray(e.assertion_ids))throw new M("gate.assertion_ids is required and must be an array");if(e.assertion_ids.length===0)throw new M("gate requires at least one assertion");for(let t of e.assertion_ids)kt(t,"gate.assertion_id");if(!Array.isArray(e.triggers))throw new M(`gate.triggers is required and must be an array of ${vt.join(", ")}`);if(e.triggers.length===0)throw new M("gate requires at least one trigger");for(let t of e.triggers)if(!vt.includes(t))throw new M(`gate trigger must be one of ${vt.join(", ")}`);return e.provider_policy&&LC(e.provider_policy),e}function Bn(e){if(e.version!==Fg)throw new M(`unsupported assurance document version ${String(e.version)}`);let t=new Set;for(let r of e.measurements){if(Jc(r),t.has(`measurement:${r.id}`))throw new M(`duplicate measurement ${r.id}`);t.add(`measurement:${r.id}`)}for(let r of e.assertions){if(Xc(r),t.has(`assertion:${r.id}`))throw new M(`duplicate assertion ${r.id}`);t.add(`assertion:${r.id}`)}for(let r of e.gates){Gg(r);let s=r.assertion_ids.filter(i=>!e.assertions.some(o=>o.id===i));if(s.length>0)throw new M(`gate ${r.id} references missing assertions: ${s.join(", ")}`);if(t.has(`gate:${r.id}`))throw new M(`duplicate gate ${r.id}`);t.add(`gate:${r.id}`)}let n=new Set(e.measurements.map(r=>r.id));for(let[r,s]of qg(e))if(!n.has(r))throw new M(`${s.join(", ")} references missing measurement ${r}`);return e}function Qc(e,t){if("measurement"in e){t.push(e.measurement);return}if("operator"in e)for(let n of e.operands)Qc(n,t)}function qg(e){let t=new Map,n=(r,s)=>{let i=t.get(r)??[];i.push(s),t.set(r,i)};for(let r of e.assertions)n(r.measurement_id,`assertion ${r.id}`),r.scope.kind==="filter"&&n(r.scope.measurement_id,`assertion ${r.id} scope`);for(let r of e.measurements){if(r.source.kind!=="derived")continue;let s=[];Qc(r.source.expression,s);for(let i of s)n(i,`derived measurement ${r.id}`)}return t}function $C(e,t){let n=e.assertion_ids.flatMap(i=>{let o=t.assertions.find(a=>a.id===i);return[o.measurement_id,...o.scope.kind==="filter"?[o.scope.measurement_id]:[]]}),r=new Set,s=new Set;for(;n.length>0;){let i=n.pop();if(r.has(i))continue;r.add(i);let o=t.measurements.find(a=>a.id===i);o.source.kind==="provider"?s.add(o.source.provider):o.source.kind==="derived"&&Qc(o.source.expression,n)}return s}function Vr(){return{version:Fg,measurements:[],assertions:[],gates:[]}}function NC(e,t){let n=t.items.filter(r=>(e.statuses===void 0||e.statuses.includes(r.status))&&(e.types===void 0||e.types.includes(r.type))&&(e.tags===void 0||e.tags.every(s=>r.tags?.includes(s)))&&(e.field===void 0||(()=>{let s=r[e.field];if(e.state!==void 0){let i=s==null||s===""||Array.isArray(s)&&s.length===0;return e.state==="missing"?i:!i}return Yc(s,e.equals)})()));return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(r=>r.id)}}function MC(e,t){return e.source_kind!==void 0?t?.toLowerCase()===e.source_kind.trim().toLowerCase():e.source_kind_prefix!==void 0?t?.toLowerCase().startsWith(e.source_kind_prefix.trim().toLowerCase())===!0:e.source_kind_state==="present"?t!==void 0&&t.length>0:e.source_kind_state==="missing"?t===void 0||t.length===0:!0}function PC(e,t){let n=[],r=Ar(e.dependency_kind)??e.dependency_kind.trim().toLowerCase();for(let s of t.items)for(let i of s.dependencies??[]){let o=Ar(i.kind)??i.kind.trim().toLowerCase(),a=i.source_kind?.trim();o===r&&MC(e,a)&&n.push(`${s.id}->${i.id}${a?`@${a}`:""}`)}return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n}}function FC(e){let t=[e.description,e.body].filter(n=>typeof n=="string").map(n=>n.trim()).filter(Boolean);for(let n of["comments","notes","learnings"]){let r=e[n];if(Array.isArray(r)){for(let s of r)if(typeof s=="string")t.push(s);else if(typeof s=="object"&&s!==null){let i=Reflect.get(s,"text");typeof i=="string"&&t.push(i)}}}return t}function DC(e,t,n,r){return e.some(s=>s.holder_id.trim().toLowerCase()===t.toLowerCase()&&(s.target_id===void 0||s.target_id.trim().toLowerCase()===n.toLowerCase())&&(s.text_contains===void 0||r.toLowerCase().includes(s.text_contains.trim().toLowerCase())))}function Vc(e,t){return[e.toLowerCase(),t.toLowerCase()].sort().join("\0")}function jC(e){let t=new Map,n=new Set,r=[],s=/(?<![\w-])[a-z0-9]+(?:-+[a-z0-9]+)+(?![\w-])/giu,i=0;for(let o of e){t.set(o.id.toLowerCase(),o.id);for(let a of o.dependencies??[])n.add(Vc(o.id,a.id));for(let a of[o.parent,o.blocked_by])typeof a=="string"&&n.add(Vc(o.id,a));for(let a of FC(o)){let c=[...a.matchAll(s)].map(d=>d[0]);i+=c.length,r.push({holder_id:o.id,segment:a,mentioned_ids:c})}}return{canonical_ids:t,linked_pairs:n,prose_mentions:r,mention_count:i}}function UC(e,t){let n=jC(t.items),r=new Map;for(let o of n.prose_mentions){let a=o.mentioned_ids.map(d=>n.canonical_ids.get(d.toLowerCase())).filter(d=>d!==void 0&&d!==o.holder_id),c=[...new Set(a)];for(let d of c){let l=Vc(o.holder_id,d);if(n.linked_pairs.has(l)||DC(e.exemptions??[],o.holder_id,d,o.segment))continue;let u=c.some(f=>f!==d);r.get(l)?.explicit===!0&&!u||r.set(l,{contributor:`${o.holder_id}->${d}|subject=${u?"explicit":"implicit"}`,explicit:u})}}let s=[...r.values()],i=s.map(o=>o.contributor).sort();return{value:i.length,population_size:n.canonical_ids.size,cost:t.items.length+n.linked_pairs.size+n.mention_count,contributors:i.slice(0,e.sample_limit??25),partitions:{explicit_subject:s.filter(o=>o.explicit).length,implicit_subject:s.filter(o=>!o.explicit).length}}}function GC(e,t){return{value:t.history.filter(r=>(e.op===void 0||r.op===e.op)&&(e.author===void 0||r.author===e.author)&&(e.harness===void 0||r.agent_harness===e.harness)&&(e.model===void 0||r.agent_model===e.model)).length,population_size:t.history.length,cost:t.history.length}}function qC(e,t){let n=t.items.filter(r=>{let s=r[e.link],i=Array.isArray(s)&&s.length>0;return e.state==="present"?i:!i});return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(r=>r.id)}}function WC(e,t){let n=e.source;return n.kind==="items"?NC(n,t):n.kind==="dependency_kind"?PC(n,t):n.kind==="prose_edge_gap"?UC(n,t):n.kind==="history"?GC(n,t):n.kind==="links"?qC(n,t):null}function Wg(e,t){return e.reduce((n,r)=>({units:n.units+r.units,items_scanned:n.items_scanned+r.items_scanned,history_entries:n.history_entries+r.history_entries,provider_calls:n.provider_calls+r.provider_calls,duration_ms:t}),{units:0,items_scanned:0,history_entries:0,provider_calls:0,duration_ms:t})}function KC(e,t){if(t.length===0)throw new TypeError(`derived ${e} requires operands`);if(e==="add")return t.reduce((n,r)=>n+r,0);if(e==="subtract")return t.slice(1).reduce((n,r)=>n-r,t[0]);if(e==="multiply")return t.reduce((n,r)=>n*r,1);if(e==="divide"){if(t.slice(1).includes(0))throw new TypeError("derived divide cannot divide by zero");return t.slice(1).reduce((n,r)=>n/r,t[0])}return e==="min"?Math.min(...t):Math.max(...t)}async function Kg(e,t,n){let r=new Array(e.length),s=0,i=Array.from({length:Math.min(t,e.length)},async()=>{for(;s<e.length;){let o=s;s+=1,r[o]=await n(e[o],o)}});return await Promise.all(i),r}async function zg(e,t,n,r,s){if("literal"in e)return{value:e.literal,costs:[],population_size:0,contributors:[]};if("measurement"in e){let o=n.find(d=>d.id===e.measurement);if(!o)throw new TypeError(`derived measurement references missing ${e.measurement}`);let a=await Bg(o,t,n,r,s);if(typeof a.value!="number")throw new TypeError(`derived measurement ${o.id} is not numeric`);let c=s.charged.has(o.id)?[]:[a.cost];return s.charged.add(o.id),{value:a.value,costs:c,population_size:a.population_size,contributors:a.contributors}}let i=await Kg(e.operands,Dg,o=>zg(o,t,n,r,s));return{value:KC(e.operator,i.map(o=>o.value)),costs:i.flatMap(o=>o.costs),population_size:Math.max(0,...i.map(o=>o.population_size)),contributors:[...new Set(i.flatMap(o=>o.contributors))]}}async function zC(e,t,n,r,s){Jc(e);let i=Date.now(),o,a=[],c=0;if(e.source.kind==="derived"){let u=await zg(e.source.expression,t,n,[...r,e.id],s);o={value:u.value,population_size:u.population_size,cost:0,contributors:u.contributors},a=u.costs}else{let u=WC(e,t);u!==null?o=u:(o=await t.external(e.source),c=1)}let d={units:o.cost,items_scanned:e.source.kind==="items"||e.source.kind==="dependency_kind"||e.source.kind==="prose_edge_gap"||e.source.kind==="links"?t.items.length:0,history_entries:e.source.kind==="history"?t.history.length:0,provider_calls:c,duration_ms:Date.now()-i},l=Wg([...a,d],Date.now()-i);if(e.max_cost!==void 0&&l.units>e.max_cost)throw new Ne(`measurement ${e.id} exceeded cost ceiling ${e.max_cost} with ${l.units}`);return{id:e.id,definition_fingerprint:`sha256:${kC("sha256").update(Z(e)).digest("hex")}`,value:o.value,population_size:o.population_size,cost:l,contributors:o.contributors??[],...o.partitions?{partitions:o.partitions}:{}}}function Bg(e,t,n,r,s){if(r.includes(e.id))throw new TypeError(`derived measurement cycle: ${[...r,e.id].join(" -> ")}`);let i=s.cache.get(e.id);if(i)return i;let o=zC(e,t,n,r,s).catch(a=>{if(a instanceof ut&&a.measurement_id===void 0){let c={measurement_id:e.id,source_kind:a.source_kind,field:a.field,...a.check?{check:a.check}:{}},d=new ut(a.message,c);throw d.cause=a,d}throw a});return s.cache.set(e.id,o),o}async function Zc(e,t,n=[e]){return Bg(e,t,n,[],{cache:new Map,charged:new Set})}function BC(e,t){return typeof e!="number"||typeof t.value!="number"?null:t.polarity==="ceiling"||t.polarity==="monotone_nonincreasing"?t.value-e:(t.polarity==="floor"||t.polarity==="monotone_nondecreasing",e-t.value)}function HC(e,t,n={}){Xc(e);let r=Hr(e),s=e.lifetime==="retire"&&n.owner_terminal===!0;return{assertion_id:e.id,measurement_id:e.measurement_id,measurement_definition_fingerprint:t.definition_fingerprint,scope:e.scope,population_size:t.population_size,observed:t.value,bound:r,distance:BC(t.value,r),verdict:s?"retired":jg(t.value,r)?"pass":"fail",enforcement:e.enforcement,negative_control_proven:Ug(e),cost:t.cost,contributors:t.contributors,...t.partitions?{partitions:t.partitions}:{}}}function VC(e,t,n,r){let s=$C(e,t);if(s.size===0)return;let i=e.provider_policy,o=i?.triggers[r];if(!i||!o)throw new Ne(`assurance gate ${e.id} refuses provider execution at trigger ${r} without an explicit provider policy`);let a=new Set(i.allowed_providers),c={low:0,medium:1,high:2};for(let d of s){if(!a.has(d))throw new Ne(`assurance gate ${e.id} refuses provider ${d}`);let l=n.provider_capabilities?.[d];if(!l)throw new Ne(`assurance provider ${d} has no declared capabilities`);if(c[l.cost_class]>c[o.max_cost_class])throw new Ne(`assurance gate ${e.id} refuses ${l.cost_class}-cost provider ${d} at trigger ${r}`);if(l.network&&!o.allow_network)throw new Ne(`assurance gate ${e.id} refuses network provider ${d} at trigger ${r}`)}}async function Pg(e,t,n,r,s){try{return await Zc(n,r,s)}catch(i){if(i instanceof ut){let o=i.check?` check ${i.check}`:"",a=i.measurement_id??n.id,c=new Ne(`assurance gate ${e} assertion ${t} measurement ${a} source ${i.source_kind}${o} field ${i.field} could not resolve: ${i.message}`,{gate_id:e,assertion_id:t,measurement_id:a,source_kind:i.source_kind,field:i.field,...i.check?{check:i.check}:{}});throw c.cause=i,c}throw i}}async function Hg(e,t,n,r){Bn(t);let s=t.gates.find(c=>c.id===e);if(!s)throw new Ne(`assurance gate ${e} not found`);if(!s.triggers.includes(r.trigger))throw new Ne(`assurance gate ${e} does not declare trigger ${r.trigger}`);VC(s,t,n,r.trigger);let i=await Kg(s.assertion_ids,Dg,async c=>{let d=t.assertions.find(h=>h.id===c),l=t.measurements.find(h=>h.id===d.measurement_id),u=n;if(d.scope.kind==="active"){let h=new Set(n.terminal_statuses??["closed","canceled"]);u={...n,items:n.items.filter(g=>!h.has(g.status))}}else if(d.scope.kind==="filter"){let h=d.scope.measurement_id,g=t.measurements.find(v=>v.id===h),y=await Pg(s.id,d.id,g,n,t.measurements),w=new Set(y.contributors);u={...n,items:n.items.filter(v=>w.has(v.id))}}let f=n.items.find(h=>h.id===d.owner_item_id),_=f!==void 0&&new Set(n.terminal_statuses??["closed","canceled"]).has(f.status);return HC(d,await Pg(s.id,d.id,l,u,t.measurements),{owner_terminal:_})}),o=i.some(c=>c.verdict==="fail"&&c.enforcement==="block"),a=i.some(c=>c.verdict==="fail"&&c.enforcement==="warn");return{gate_id:s.id,tree_id:n.tree_id,trigger:r.trigger,dry_run:r.dry_run===!0,evaluated_at:new Date().toISOString(),verdict:o?"block":a?"warn":"pass",exit_code:o?1:0,assertions:i,assertions_total:i.length,row_contract:{row_keys:["assertions"],jq_selector:".assertions[]"},cost:Wg(i.map(c=>c.cost),Math.max(0,...i.map(c=>c.cost.duration_ms)))}}function Gi(e){return bC.join(e,"assurance.json")}async function Vg(e){let t=await Q(Gi(e));return t===null?Vr():qi(t)}function qi(e){try{return Bn(JSON.parse(e))}catch(t){throw new p("The assurance registry is invalid. Repair or restore .agents/pm/assurance.json and retry.",m.GENERIC_FAILURE,{code:"assurance_registry_invalid",reason:String(t),nextSteps:["Restore a valid assurance.json from version control or repair its declaration references.","Run pm assurance list measurement after the repair."]})}}function Wi(e,t){return t==="measurement"?e.measurements:t==="assertion"?e.assertions:e.gates}function YC(e,t){e==="measurement"?Jc(t):e==="assertion"?Xc(t):Gg(t)}async function Yr(e,t){let n=structuredClone(Wi(await Vg(e),t));return{items:n,count:n.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function Yg(e,t,n){let r=Wi(await Vg(e),t).find(s=>s.id===n);if(!r)throw new Ne(`assurance ${t} ${n} not found`);return structuredClone(r)}async function Ki(e,t,n,r={}){YC(t,n);let s=await C(e),i=G(r.author,s.author_default),o=await Nn({pmRoot:e,filePath:Gi(e),op:`assurance:${t}:put`,author:i,message:r.message,lockTtlSeconds:ji,lockWaitMs:Ui,mutate:a=>{let c=a===null?Vr():qi(a),d=Wi(c,t),l=d.findIndex(f=>f.id===n.id),u=l<0?"created":"updated";if(t==="assertion"&&l>=0&&TC(d[l],n)){let f=n.authorization_decision;if(!f||!r.authorized_decision_ids?.includes(f))throw new M(`loosening assertion ${n.id} requires a verified authorization_decision`)}return l<0?d.push(structuredClone(n)):d[l]=structuredClone(n),Bn(c),{raw:`${JSON.stringify(c,null,2)}
|
|
3
|
+
`,result:{changed:!0,action:u,kind:t,id:n.id}}}});return{...o.result,changed:o.changed}}async function ed(e,t,n={}){let r=Vr();r.measurements=structuredClone(t.measurements),r.assertions=structuredClone(t.assertions),r.gates=structuredClone(t.gates),Bn(r);let s=await C(e),i=G(n.author,s.author_default),o=await Nn({pmRoot:e,filePath:Gi(e),op:"assurance:bundle:apply",author:i,message:n.message,lockTtlSeconds:ji,lockWaitMs:Ui,mutate:a=>{let c=a===null?Vr():qi(a),d=[],l=[],u=(f,_,h)=>{for(let g of _){let y=f.find(w=>w.id===g.id);if(!y){f.push(structuredClone(g)),d.push(`${h}:${g.id}`);continue}if(Z(y)!==Z(g))throw new M(`assurance bundle refuses to replace divergent ${h} ${g.id}`);l.push(`${h}:${g.id}`)}};return u(c.measurements,r.measurements,"measurement"),u(c.assertions,r.assertions,"assertion"),u(c.gates,r.gates,"gate"),Bn(c),{raw:`${JSON.stringify(c,null,2)}
|
|
4
|
+
`,result:{changed:d.length>0,created_ids:d,unchanged_ids:l}}}});return{...o.result,changed:o.changed}}async function Jg(e,t,n,r={}){let s=await C(e),i=G(r.author,s.author_default),o=await Nn({pmRoot:e,filePath:Gi(e),op:`assurance:${t}:remove`,author:i,message:r.message,lockTtlSeconds:ji,lockWaitMs:Ui,mutate:a=>{let c=a===null?Vr():qi(a);if(t==="measurement"){let u=qg(c).get(n);if(u&&u.length>0)throw new M(`assurance measurement ${n} is referenced by ${u.join(", ")}`)}if(t==="assertion"&&c.gates.some(u=>u.assertion_ids.includes(n)))throw new M(`assurance assertion ${n} is referenced by gate`);let d=Wi(c,t),l=d.findIndex(u=>u.id===n);if(l<0)throw new M(`assurance ${t} ${n} not found`);return d.splice(l,1),Bn(c),{raw:`${JSON.stringify(c,null,2)}
|
|
5
|
+
`,result:{changed:!0,action:"removed",kind:t,id:n}}}});return{...o.result,changed:o.changed}}async function Xg(e,t,n={}){if(t.dry_run)throw new TypeError("dry-run assurance verdicts are not persisted");let r=await C(e);await $n({pmRoot:e,op:"assurance:gate:verdict",author:G(n.author,r.author_default),context:{assurance_verdict:t},message:n.message??`Assurance gate ${t.gate_id} returned ${t.verdict}`,lockTtlSeconds:ji,lockWaitMs:Ui})}async function Qg(e,t={}){let n=t.limit??EC;if(!Number.isInteger(n)||n<1||n>1e3)throw new TypeError(`assurance verdict limit must be an integer from 1 through ${1e3}`);return(await Xt(Tr(e),Qt)).reverse().filter(s=>s.op==="assurance:gate:verdict").map(s=>s.context?.assurance_verdict).filter(s=>typeof s=="object"&&s!==null&&"gate_id"in s).filter(s=>t.gate_id===void 0||s.gate_id===t.gate_id).slice(0,n)}var JC=xc("list").properties.outputSession,XC={outputInclude:{type:"string",minLength:1,description:"Comma-separated fields or sections retained by any built-in read action."},outputLimit:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}],description:"Universal read row ceiling, or unbounded to disable the shared ceiling."},outputBudget:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}],description:"Universal estimated-token ceiling, or unbounded to return the complete read result."},outputFormat:{type:"string",enum:["json","toon"],description:"Universal read-result encoding selector."},outputSession:{...JC},outputCursor:{type:"string",minLength:1,description:"Opaque continuation cursor returned after budget compaction of a declared row collection."}},Zg={definition:{anyOf:[{type:"object"},{type:"string"}],description:"Policy declaration for policy-put, or proposed metadata for policy-check; structured JSON or JSON text."},policy:{type:"string",description:"Approval policy id for policy-approve."},message:{type:"string",description:"History explanation for policy mutations and approvals."},dryRun:{type:"boolean",description:"Preview registry changes without writing; policy-approve rejects previews."}},ey={type:"object",properties:{cwd:{type:"string",description:"Workspace directory to run the native pm operation in. Defaults to the MCP server process cwd."},path:{type:"string",description:"Optional pm data root, equivalent to PM_PATH/global --path. Leave unset for real repository tracking."},author:{type:"string",description:"Optional mutation author override. Otherwise pm uses PM_AUTHOR, project settings, or detected harness identity."},tokenAccounting:{type:"boolean",description:"Attach the same bounded per-section token-cost receipt emitted by CLI --token-accounting."}},additionalProperties:!0},pe={type:"string",description:"pm item id, for example pm-abc1."},QC=`Operation name (one of): ${Da.join(", ")}. Package-owned actions are available dynamically when their provider package is installed.`,ZC={status:{type:"string",description:"Alias for options.status."},type:{type:"string",description:"Alias for options.type."},tag:{type:"string",description:"Alias for options.tag."},priority:{type:"string",description:"Alias for options.priority."},limit:{type:["string","number"],description:"Alias for options.limit."},offset:{type:["string","number"],description:"Alias for options.offset."}},eT={mode:{type:"string",description:"Alias for options.mode."},status:{type:"string",description:"Alias for options.status."},type:{type:"string",description:"Alias for options.type."},tag:{type:"string",description:"Alias for options.tag."},priority:{type:"string",description:"Alias for options.priority."},limit:{type:["string","number"],description:"Alias for options.limit."}};function B(e,t=[]){return{...ey,properties:{...ey.properties,...e},required:t}}var tT=[{name:"pm_run",description:"Run any supported pm operation natively through the pm library. Use this for commands not covered by narrower pm_* tools.",inputSchema:B({action:{type:"string",enum:[...Da],description:QC},id:pe,query:{type:"string",description:"Search query for action=search."},reason:{type:"string",description:"Close reason for action=close."},force:{type:"boolean",description:"Force ownership/terminal-state override when supported."},subcommand:{type:"string",description:"Subcommand selector for actions that take one (for example telemetry, or schema \u2014 prefer the dedicated pm_schema tool for schema operations)."},options:{type:"object",description:"Underlying pm command options using camelCase keys."},fullChangedFields:{type:"boolean",description:"For mutation actions, return the full changed_fields array instead of the default changed_field_count."},idOnly:{type:"boolean",description:"For single-item mutation actions, return only id and status."},...XC},["action"])},{name:"pm_discover",description:"Discover the smallest relevant authorized pm tool catalog under an explicit token budget. Ranking is deterministic and returns public lexical, semantic, graph, permission, freshness, and usage signal explanations. Continue with next_cursor; set includeSchema=true only when complete input schemas are needed.",inputSchema:B({query:{type:"string",maxLength:4096,description:"Free-text capability intent. Empty text lists by stable policy order."},family:{type:"string",enum:["workspace","intake","context","lifecycle","evidence","graph","quality","automation","extensions","internal"],description:"Optional stable capability-family filter."},tier:{type:"string",enum:["core","standard","full"],description:"Maximum command visibility tier included in results."},limit:{type:"integer",minimum:1,maximum:100,description:"Maximum result rows; defaults to 10."},cursor:{type:"string",minLength:1,maxLength:4096,description:"Opaque next_cursor from an equivalent discovery request."},includeSchema:{type:"boolean",description:"Include complete tool input schemas; false by default."},outputBudget:{anyOf:[{type:"integer",minimum:128},{const:"unbounded"}],description:"Estimated-token ceiling; defaults to 1200."}})},{name:"pm_context",description:"Return the agent-oriented project context snapshot. Pass options.depth=brief|standard|deep|full (full = every section with no per-section row cap), options.parent='<id>' to scope the snapshot to one item's subtree (the item plus all descendants), options.fields='id,title,priority' to project focus rows to a field subset for low-token reads, or options.section=['hierarchy','progress',...] to pick sections.",inputSchema:B({options:{type:"object"}})},{name:"pm_next",description:"Recommend the next actionable work item: the single highest-priority READY item (active status, no open blockers, no open children; completed containers surface only when no concrete leaf work is ready) plus the ranked ready and blocked queues. The recommended item carries a rationale and each blocked item lists the open blockers gating it. Pass options.parent='<id>' to scope to one subtree, options.limit=N to cap ready rows, options.readyOnly=true to omit the blocked list, or filters (options.type/tag/priority/assignee/sprint/release). The most token-efficient 'what should I do now?' read for agents.",inputSchema:B({options:{type:"object"}})},{name:"pm_search",description:"Search pm items with keyword, semantic, or hybrid search. Defaults to a compact projection for token efficiency. Pass options.mode=keyword|semantic|hybrid (default follows search.default_mode: auto runs hybrid when semantic search is configured and runnable, else keyword; the result reports mode_source), options.limit=N to cap hits, options.status='all' for no lifecycle restriction, options.fields='id,title,score' for a custom projection, or options.full=true for full item bodies (can be large). The result echoes the applied filters and projection mode in query_summary.",inputSchema:B({query:{type:"string"},options:{type:"object"},...eT},["query"])},{name:"pm_list",description:"List pm items with status/type/tag/priority filters. Defaults to compact projection for token efficiency. options.status accepts CSV (all,open,in_progress). Pass options.compact=false or options.includeBody=true for full bodies/comments. Pass options.brief=true for ultra-terse (id/status/type/title only). Pass options.fields='id,title,priority' for custom projection. Pass options.limit=N to cap row count. The result echoes the applied filters and projection mode in query_summary.",inputSchema:B({options:{type:"object"},...ZC})},{name:"pm_get",description:"Read one pm item with shared SDK projections. Pass options.depth='brief' or options.fields='id,title,status' for low-token inspection, options.fields='id,schedule.start_at' for schedule context, or options.at='7' / an ISO timestamp for a verified mutation-free historical read. Parent results include bounded child counts, samples, and continuation metadata.",inputSchema:B({id:pe,options:{type:"object",description:"Get options such as depth=brief|standard|deep|full, fields=id,title,status, or at=<version|ISO timestamp>."}},["id"])},{name:"pm_events",description:"Read a bounded, cursor-resumable page of committed mutation events across item history streams. Batch cursors are the token-efficient default; pass cursorMode=row for per-event checkpoints.",inputSchema:B({verify:{type:"boolean",description:"Verify complete selected authoritative history chains."},since:{type:"string",description:"Durable event cursor or ISO timestamp lower bound."},type:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},author:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},item:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},limit:{type:"integer",minimum:0,maximum:1e3},full:{type:"boolean"},cursorMode:{type:"string",enum:["batch","row"],description:"Cursor framing: batch returns one terminal next_cursor (default); row also adds a cursor to every event."}})},{name:"pm_create",description:"Create a pm item natively and write pm history. Output is compact by default (changed_fields replaced with changed_field_count for token efficiency); pass fullChangedFields=true for the full changed_fields array.",inputSchema:B({fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},allowMissingParent:{type:"boolean",description:"Allow unresolved parent references and emit a validation warning."},allowDuplicate:{type:"boolean",description:"Explicitly create when strict similarity governance finds likely duplicates."},options:{type:"object",description:"Create options. title and description are required."}},["options"])},{name:"pm_mutate",description:"Apply an ordered create/update/close/release batch atomically through the public pm SDK. Create rows may declare ref and omit id; @ref forward references resolve deterministically from the stable transactionId, which is derived from the batch when omitted. Bulk creation: rows shaped as {item:{title,type,...}} are create documents using pm create field names; upsertKey updates the existing item whose field matches instead of creating a duplicate. Set dryRun=true to validate and preview without writes.",inputSchema:B({transactionId:{type:"string",description:"Stable idempotency key for this atomic mutation batch; derived from the batch content when omitted."},mutations:{type:"array",minItems:1,description:"Ordered rows shaped as {op:create|update|close|release,id?,ref?,options?,reason?} or create documents {ref?,item:{...}}.",items:{type:"object",properties:{op:{type:"string",enum:["create","update","close","release"],description:"Operation; omitted rows carrying item are creates."},id:pe,ref:{type:"string",description:"Batch-local create alias; its deterministic id can be referenced as @alias by any row."},reason:{type:"string"},options:{type:"object"},item:{type:"object",description:"Create document using pm create field names (title, type, description, body, tags, parent, custom fields)."},unique:{type:"object",description:"Create-only guard {key,value} re-checked under the writer lock; keyed upsert sets it on rows that matched nothing at planning time."},match:{type:"object",description:"Update-only guard {key,value} re-read under the writer lock; keyed upsert sets it on rows it converted into updates of a matched item."}},additionalProperties:!1}},upsertKey:{type:"string",description:"Item field whose value identifies an existing item to update instead of creating a duplicate."},dryRun:{type:"boolean",description:"Validate and preview without writing."},createCompensation:{type:"string",enum:["close","delete"],description:"How a failed batch compensates created items; defaults to close."},lockTtlSeconds:{type:"number"},lockWaitMs:{type:"number"}},["mutations"])},{name:"pm_copy",description:"Copy an existing pm item into a new id while resetting lifecycle fields. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:B({id:pe,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object",description:"Copy options such as title override, author, and message."}},["id"])},{name:"pm_focus",description:"Set, clear, or show the session focused item. When focused, pm_create defaults its parent to the focused item (an explicit parent still overrides). Pass id to focus an item, options.clear=true to clear, or neither to show current focus.",inputSchema:B({id:pe,clear:{type:"boolean",description:"Clear the focused item (cannot be combined with id)."},options:{type:"object",description:"Focus options such as clear (boolean)."}},[])},{name:"pm_update",description:"Update pm item metadata/body/dependencies/log seeds natively. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields delta.",inputSchema:B({id:pe,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object"}},["id","options"])},{name:"pm_append",description:"Append markdown text to a pm item body and write pm history. Useful for seeding evidence/log entries before close. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:B({id:pe,body:{type:"string",description:"Markdown text to append to the item body. Required here or as options.body."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object",description:"Append options such as body, author, and message."}},["id"])},{name:"pm_claim",description:"Claim a pm item.",inputSchema:B({id:pe,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_release",description:"Release a pm item claim.",inputSchema:B({id:pe,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_close",description:"Close a pm item with optional close reason and optional close validation (reason requirement follows governance settings). Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:B({id:pe,reason:{type:"string",description:"Close reason text when provided or required by governance settings."},duplicateOf:{type:"string",description:"Canonical item id when closing this item as a duplicate."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object"}},["id"])},{name:"pm_comments",description:'List, add, edit, or delete comments on a pm item. Use options.add to append, options.edit=<1-based index> with replacement text to fix a comment, or options.delete=<1-based index> to remove one. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. List calls return the newest comments that fit the output budget, with total_count/has_more metadata and a next_cursor that pages back to older comments through outputCursor; without options.limit or outputLimit, outputBudget "unbounded" returns the complete listing at once. Pass options.limit=N for only the newest N comments (next_cursor pages within that window when the budget trims it; has_more reports older comments beyond it without a cursor) or options.limit=0 for summary-only metadata; options.full=true returns the complete history after a write. Rows carry their absolute index; pair edit/delete with options.expectAt to refuse a different entry.',inputSchema:B({id:pe,options:{type:"object"}},["id"])},{name:"pm_files",description:"List, add, remove, or validate linked files for a pm item.",inputSchema:B({id:pe,options:{type:"object"}},["id"])},{name:"pm_docs",description:"List, add, or remove linked docs for a pm item.",inputSchema:B({id:pe,options:{type:"object"}},["id"])},{name:"pm_notes",description:"List, add, edit, or delete structured notes on a pm item. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. Omit mutation options to list existing notes; rows carry their absolute index, and options.expectAt guards edit/delete.",inputSchema:B({id:pe,options:{type:"object"}},["id"])},{name:"pm_learnings",description:"List, add, edit, or delete learnings on a pm item. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. Omit mutation options to list existing learnings; rows carry their absolute index, and options.expectAt guards edit/delete.",inputSchema:B({id:pe,options:{type:"object"}},["id"])},{name:"pm_deps",description:"Read dependency trees/graphs or one bounded explainable relationship context packet. Use options.format=context with direction, kind, depth, node, edge, token, and cursor bounds; context returns a counts-first summary, per-node roles/reasons, root evidence pointers, and enumerated missing references.",inputSchema:B({id:pe,options:{type:"object"}},["id"])},{name:"pm_graph",description:"Run bounded workspace relationship-graph queries: ancestors/descendants (hierarchy), predecessors/successors (ordering), paths, impact (blast radius), analyze (execution + knowledge analytics), audit (governance findings with change-since-baseline deltas), communities (label-propagation clusters), redundancy (transitively implied edges), dominators (structural bottlenecks), slack (critical-path method float per task), centrality (betweenness/closeness/degree with directed fan-in/out), articulation (cut points and bridges \u2014 single points of failure), plan (dry-run remediation proposals derived from the audit), and index (durable cross-process graph index status/rebuild/clear). Traversals, paths, impact, and dominators require id; paths also requires target. Options support kind, maxDepth, limit, after, direction, maxPaths, sample, exemptIsolate, exemptIsolateType, saveBaseline (audit), rebuild/clear (index), and counts-first summary.",inputSchema:B({subcommand:{type:"string",enum:[...sm]},id:pe,target:pe,options:{type:"object"}},["subcommand"])},{name:"pm_test",description:"List, add, remove, or run linked tests for a pm item.",inputSchema:B({id:pe,options:{type:"object"}},["id"])},{name:"pm_validate",description:"Run pm validation checks.",inputSchema:B({options:{type:"object"}})},{name:"pm_health",description:"Run pm health diagnostics. Pass options.brief=true for compact low-token details, options.skipIntegrity=true, options.skipDrift=true, options.skipVectors=true for a fast status-only check, or options.full=true for the complete deep check.",inputSchema:B({options:{type:"object"}})},{name:"pm_contracts",description:"Inspect pm command, flag, schema, and availability contracts.",inputSchema:B({options:{type:"object"}})},{name:"pm_schema",description:"Inspect or modify the workspace item-type/status/field schema (pm schema). subcommand selects the operation; name carries the item type name (show/add-type/remove-type), status id (show-status/add-status/remove-status), or field key (show-field/add-field/remove-field). apply-preset adopts a domain type preset; add-type with infer=true derives types from title-prefix conventions. Policy verbs author declarations, preview changes, set enforcement, and record content-bound approvals. Registry mutations write workspace history; approvals write item history.",inputSchema:B({...Zg,subcommand:{type:"string",enum:["list","show","show-status","add-type","remove-type","add-status","remove-status","add-field","remove-field","list-fields","show-field","apply-preset",...Xu],description:"Schema subcommand to run."},name:{type:"string",description:"Item type name, status id, field key, policy id, or item id for the selected schema verb; policy-mode requires advise|refuse."},description:{type:"string",description:"Custom item type, status, or field description for add-type/add-status/add-field."},defaultStatus:{type:"string",description:"Default status for add-type."},folder:{type:"string",description:"Storage folder for add-type."},alias:{type:"array",items:{type:"string"},description:"Aliases for add-type/add-status, or extra CLI flag aliases for add-field."},role:{type:"array",items:{type:"string",enum:[...Ua]},description:`Lifecycle roles for add-status: ${Ua.join(", ")}.`},order:{type:"number",description:"Display/sort order for add-status."},fieldType:{type:"string",enum:["string","number","boolean","string_array"],description:"Value type for a custom field (add-field)."},commands:{type:"array",items:{type:"string"},description:"Commands a custom field is wired onto (add-field): create, update, update_many, list, search, calendar, context."},cliFlag:{type:"string",description:"Override the auto-derived CLI flag for a custom field (add-field)."},required:{type:"boolean",description:"Mark a custom field as always required (add-field)."},requiredOnCreate:{type:"boolean",description:"Mark a custom field as required at create time (add-field)."},allowUnset:{type:"boolean",description:"Whether a custom field may be cleared via --unset (add-field); defaults to true."},requiredTypes:{type:"array",items:{type:"string"},description:"Restrict a custom field's requirement to specific item types (add-field)."},typePreset:{type:"string",enum:["agile","ops","research"],description:"Domain type preset to adopt (apply-preset)."},infer:{type:"boolean",description:"Infer item types from title-prefix conventions (add-type); previews unless apply is true."},minCount:{type:"number",description:"Minimum items sharing a prefix for add-type inference (default 10)."},apply:{type:"boolean",description:"Register inferred types (add-type infer); without it the call previews only."},force:{type:"boolean",description:"Override removal guardrails for destructive schema changes when supported."},options:{type:"object",description:"Additional schema options using camelCase keys.",properties:Zg}},["subcommand"])},{name:"pm_profile",description:"List, show, apply, or lint project profiles (pm profile) \u2014 archetype bundles that stage item types, statuses, fields, per-type workflows, config knobs, create templates, and recommended packages. subcommand selects the operation; name carries the profile name (agile, ops, research) for show/apply/lint. apply stages every dimension idempotently; dryRun previews the diff without writing; lint reports author-time consistency findings (graded error/warning) without touching the tracker. Profile staging writes workspace config/schema files, not item history.",inputSchema:B({subcommand:{type:"string",enum:["list","show","apply","lint"],description:"Profile subcommand to run."},name:{type:"string",description:"Profile name for show/apply/lint. Required for those subcommands. Built-ins are agile, ops, and research; an active extension can contribute additional archetype names that resolve here too."},dryRun:{type:"boolean",description:"Preview the apply diff without writing any files (apply)."},author:{type:"string",description:"Mutation author for apply."},force:{type:"boolean",description:"Force ownership/lock override for apply."},options:{type:"object",description:"Additional profile options using camelCase keys."}},["subcommand"])},{name:"pm_config",description:"Read or write pm workspace configuration (pm config). configAction selects get/set/list/export; key/value address a single setting for get/set. scope chooses the project (default) or global settings file.",inputSchema:B({configAction:{type:"string",enum:["get","set","list","export"],description:"Config operation to perform. get/set require key; list/export dump the resolved settings surface."},key:{type:"string",description:"Settings key for get/set, for example governance-require-close-reason, telemetry-tracking, or a nested leaf such as search_provider (dash and underscore variants accepted; configAction=get without a key lists supported keys in the error)."},value:{type:"string",description:"New value for configAction=set."},scope:{type:"string",enum:["project","global"],description:"Settings scope to read or write. Defaults to project."},options:{type:"object",description:"Additional config options such as criterion, clearCriteria, format, or policy."}},["configAction"])},{name:"pm_plan",description:"Run agent-optimized Plan workflows. options.subcommand selects: create|show|add-step|update-step|complete-step|block-step|reorder-step|remove-step|link|unlink|decision|discovery|validation|resume|approve|materialize. Provide id for all non-create subcommands; provide stepRef for step lifecycle subcommands. Plans store agent-readable steps with dependencies, decisions, discoveries, validation, and resume context.",inputSchema:B({id:{type:"string",description:"Plan id (required for all subcommands except create)."},stepRef:{type:"string",description:"Step id or order for step lifecycle subcommands."},options:{type:"object",description:"Plan options including subcommand, stepRef, stepStatus, link, depth, etc."}})}],nT={pm_append:"append",pm_claim:"claim",pm_close:"close",pm_comments:"comments",pm_config:"config",pm_context:"context",pm_contracts:"contracts",pm_copy:"copy",pm_create:"create",pm_deps:"deps",pm_docs:"docs",pm_events:"events",pm_files:"files",pm_focus:"focus",pm_get:"get",pm_graph:"graph",pm_health:"health",pm_learnings:"learnings",pm_list:"list",pm_next:"next",pm_notes:"notes",pm_plan:"plan",pm_profile:"profile",pm_release:"release",pm_schema:"schema",pm_search:"search",pm_test:"test",pm_update:"update",pm_validate:"validate"},rT=tT.map(e=>{let t=nT[e.name];if(!t)return e;let n=e.inputSchema.properties,r=e.inputSchema.required.map(String);return{...e,inputSchema:xc(t,{properties:n,required:r})}});function ty(){return rT.map(e=>{let t=e.inputSchema.required,n=Array.isArray(t)?t.map(r=>String(r)).sort((r,s)=>r.localeCompare(s)):[];return{name:e.name,description:e.description,required:n,input_schema:e.inputSchema}}).sort((e,t)=>e.name.localeCompare(t.name))}var ny=new Map([["activity",["--limit","--after","--full"]],["claim",["--if-available","--next","--type","--priority","--token-budget","--explain-ranking"]],["close",["--reason","--validate-close","--resolution","--expected-result","--actual-result","--message"]],["context",["--limit","--after","--depth","--section","--token-budget","--explain-ranking"]],["contracts",["--command","--flags-only","--summary","--runtime-only","--availability-only","--full"]],["create",["--title","--type","--status","--priority","--dep","--comment"]],["get",["--full","--depth","--fields","--tree","--tree-depth","--format"]],["health",["--check-only","--summary","--brief","--check-telemetry","--strict-exit","--full"]],["list",["--status","--type","--limit","--after","--brief","--fields"]],["next",["--limit","--blocked-limit","--ready-only","--token-budget","--explain-ranking","--format"]],["search",["--mode","--status","--type","--limit","--after","--fields"]],["update",["--status","--message","--dep","--comment","--file","--test"]],["validate",["--check-resolution","--check-history-drift","--check-storage-integrity","--counts","--strict-exit","--fix-hints"]]]),sT=["--limit","--after","--offset","--token-budget","--brief","--summary","--compact","--fields","--full","--format","--since","--until"],my=new Set(["list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"]),Bi=new Set(["calendar","guide","reindex","completion","test-runs-list","test-runs-status","test-runs-logs","test-runs-stop","test-runs-resume","templates-list","templates-save","templates-show"]),on=new Set(["meet","event","remind","search-advanced","dedupe-audit","dedupe-merge","comments-audit","cal","calendar","completion","completion-statuses","completion-tags","completion-types","guide","reindex","normalize","templates","templates list","templates save","templates show","test-runs","test-runs list","test-runs status","test-runs logs","test-runs stop","test-runs resume"]),fy=new Map([["meet","calendar"],["event","calendar"],["remind","calendar"],["search-advanced","search-advanced"],["dedupe-audit","governance-audit"],["dedupe-merge","governance-audit"],["comments-audit","governance-audit"],["cal","calendar"],["calendar","calendar"],["completion","guide-shell"],["completion-statuses","guide-shell"],["completion-tags","guide-shell"],["completion-types","guide-shell"],["guide","guide-shell"],["reindex","search-advanced"],["normalize","governance-audit"],["templates","templates"],["templates list","templates"],["templates save","templates"],["templates show","templates"],["test-runs","linked-test-adapters"],["test-runs list","linked-test-adapters"],["test-runs status","linked-test-adapters"],["test-runs logs","linked-test-adapters"],["test-runs stop","linked-test-adapters"],["test-runs resume","linked-test-adapters"]]),py=new Map([["calendar","calendar|cal"],["guide","guide"],["reindex","reindex"],["completion","completion"],["test-runs-list","test-runs|test-runs list"],["test-runs-status","test-runs status"],["test-runs-logs","test-runs logs"],["test-runs-stop","test-runs stop"],["test-runs-resume","test-runs resume"],["templates-list","templates|templates list"],["templates-save","templates save"],["templates-show","templates show"]]),_y=new Map([...py.entries()].flatMap(([e,t])=>bt(t).map(n=>[n,e]))),hy=[{canonical:"context",aliases:["ctx"]},{canonical:"package",aliases:["extension","packages"]}],rd=new Map(hy.flatMap(e=>e.aliases.map(t=>[t,e.canonical]))),iT=10,oT=20,ry=new Map([["activity","Read activity."],["aggregate","Group counts."],["append","Append body."],["assurance","Evaluate assurance."],["assurance derive","Derive checks."],["assurance risk","Select checks for changes."],["assurance lineages","Measure recurrence coverage."],["beads","Manage Beads interoperability."],["cal","Manage calendar integration."],["calendar","Manage calendar integration."],["changelog","Generate changelog output."],["claim","Claim work."],["close","Close work."],["close-many","Close matching work."],["close-task","Close task work."],["command-kit","Inspect command authoring primitives."],["comments","Manage comments."],["comments-audit","Audit comment governance."],["completion","Generate shell completions."],["config","Manage settings."],["context","Build context."],["contracts","Inspect contracts."],["copy","Copy work."],["create","Create work."],["dedupe-audit","Audit duplicate work."],["dedupe-merge","Merge duplicate work."],["delete","Delete work."],["deps","Manage deps."],["duplicates","Find duplicate clusters."],["docs","Link docs."],["eval","Run evaluations."],["event","Manage events."],["events","Read events."],["files","Link files."],["focus","Manage focus."],["gc","Clean caches."],["get","Read item."],["graph","Query graph."],["guide","Show user guides."],["health","Check health."],["help","Show help."],["history","Inspect history."],["init","Initialize workspace."],["install","Install packages."],["item","Mutate items."],["learnings","Manage learnings."],["list","List work."],["list-all","List work across every status."],["list-blocked","List blocked work."],["list-canceled","List canceled work."],["list-closed","List closed work."],["list-draft","List draft work."],["list-in-progress","List in-progress work."],["list-open","List open work."],["meet","Record meeting context."],["merge","Manage tracker merges."],["next","Pick next work."],["notes","Manage notes."],["normalize","Normalize tracker data."],["ops","Run operations."],["package","Manage packages."],["packages","Manage packages."],["pause-task","Pause task work."],["plan","Manage plans."],["profile","Manage profiles."],["reindex","Refresh search index."],["release","Release claim."],["remind","Manage reminders."],["restore","Restore history."],["schema","Customize schema."],["search","Search work."],["search-advanced","Run advanced search."],["start-task","Start task work."],["stats","Show stats."],["telemetry","Manage telemetry."],["templates","Manage work templates."],["test","Run linked tests."],["test-all","Run all linked tests."],["test-runs","Inspect background test runs."],["todos","Manage source-code todos."],["twin","Manage repository twins."],["update","Update work."],["update-many","Update matching work."],["upgrade","Upgrade packages."],["validate","Validate data."],["vcs","Inspect version-control context."],["workspace","Manage workspaces."],["history-author-acknowledge","Acknowledge reviewed history authors."],["history-compact","Compact history."],["history-attest","Export or verify detached history proof."],["history-redact","Redact sensitive history values."],["history-repair","Repair history integrity."]]),gy=[["init",Hp],["install",Yp],["uninstall",Jp],["explore",Xp],["manage",r_],["describe",Qp],["reload",s_],["doctor",i_],["catalog",o_],["adopt",a_],["adopt-all",Zp],["activate",e_],["deactivate",t_],["migrate",n_]],aT=[...gy.map(([e,t])=>e==="init"?[e,Vp]:[e,t]),["upgrade",gc]],cT=[...gy.map(([e,t])=>[`extension ${e}`,t]),...aT.flatMap(([e,t])=>[[`package ${e}`,t],[`packages ${e}`,t]]),["init",Kp],["config",zp],["extension",Bp],["package",hc],["packages",hc],["install",c_],["create",I_],["item mutate",O_],["item complete",L_],["item reopen",$_],["copy",N_],["focus",M_],["update",P_],["update-many",F_],["upgrade",gc],["calendar",yc],["cal",yc],["context",wc],["ctx",wc],["get",U_],["search",B_],["eval",K_],["events",j_],["workspace",Mt],["workspace position",[]],["workspace snapshot",Mt],["workspace snapshot create",Mt],["workspace snapshot list",Mt],["workspace snapshot inspect",Mt],["workspace snapshot restore",Mt],["workspace snapshot delete",Mt],["next",z_],["aggregate",Tp],["deps",q_],["graph",W_],["guide",G_],["reindex",d_],["history",Np],["history-compact",jp],["history-attest",Up],["history-redact",Pp],["history-repair",Fp],["history-author-acknowledge",Dp],["merge",Mp],["schema",Gp],["profile",qp],["plan",Wp],["restore",p_],["delete",__],["close",l_],["close-many",u_],["append",m_],["claim",f_],["release",h_],["start-task",g_],["pause-task",y_],["close-task",w_],["comments",Rp],["notes",Ip],["learnings",Op],["files",Lp],["docs",$p],["test",v_],["test-runs-worker",[]],["test-all",k_],["telemetry",b_],["test-runs",x_],["gc",S_],["stats",E_],["ops",[]],["duplicates",A_],["validate",T_],["health",C_],["assurance",R_],...Y_,["contracts",H_],["completion",V_],["activity",D_],...[...my].map(e=>[e,Cp])],Jr=new Map(cT);for(let{alias:e,canonical:t}of it){let n=Jr.get(e);n!==void 0&&Jr.set(t,n)}function dT(e){let t=_y.get(e);return t||(e.startsWith("test-runs ")?`test-runs-${e.slice(10)}`:e.startsWith("templates ")?`templates-${e.slice(10)}`:e)}function sy(e){let t=it.find(n=>n.alias===e);return t?`${t.canonical}|${t.alias}`:ot.includes(e)?xe(e):e.startsWith("extension-")?xe(`extension ${e.slice(10)}`):e.startsWith("package-")?xe(`package ${e.slice(8)}`):e.startsWith("item-")?xe(`item ${e.slice(5)}`):e.startsWith("test-runs-")?xe(`test-runs ${e.slice(10)}`):e.startsWith("templates-")?xe(`templates ${e.slice(10)}`):Bi.has(e)?py.get(e)??xe(e):null}function lT(e,t){let n=K(t);return n!==t||it.some(r=>r.alias===t)?e.action===n:e.command_path===null?!1:bt(e.command_path).some(r=>r===t?!0:r.startsWith(`${t} `)||t.startsWith(`${r} `))}function bt(e){return e.split("|").map(t=>xe(t)).filter(t=>t.length>0)}function uT(e,t){let n=new Set(t),r=new Set;for(let s of e)if(s.command_path)for(let i of bt(s.command_path)){let o=i.split(" ").filter(a=>a.length>0);if(o.length!==0)for(let a=o.length;a>0;a-=1){let c=o.slice(0,a).join(" ");if(n.has(c)){r.add(c);break}}}return[...r].sort((s,i)=>s.localeCompare(i))}function zi(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function Xr(e){let t=e.oneOf;return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null):[]}function mT(e,t){if(!t)return{...e};let r=Xr(e).filter(s=>{let i=s.properties;if(typeof i!="object"||i===null)return!1;let o=i.action;return typeof o!="object"||o===null?!1:o.const===t});return{...e,oneOf:r}}function td(e,t){let r=Xr(e).filter(s=>{let i=s.properties;if(typeof i!="object"||i===null)return!1;let o=i.action;if(typeof o!="object"||o===null)return!1;let a=o.const;return typeof a=="string"&&t.has(a)});return{...e,oneOf:r}}function xe(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function yy(e){return e.replace(/\s+/g,"-")}function Dt(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function iy(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let s=Dt(r);!s||n.has(s)||(n.add(s),t.push(s))}return t}function nd(e,t,n){n&&(e[t]=!0)}function oy(e,t){if(e==null)return null;if(typeof e!="string")throw new TypeError("Expected string for extension flag name.");let n=e.trim();return n.length===0?null:t==="long"?n.startsWith("--")&&n.length>2?Vt(n):null:n.startsWith("-")&&!n.startsWith("--")&&n.length>1?n:null}function fT(e){let t=oy(e.long,"long"),n=oy(e.short,"short"),r=t??n;if(!r)return null;let s={flag:r};n&&t&&(s.short=n),nd(s,"required",e.required===!0),nd(s,"repeatable",e.repeatable===!0),nd(s,"list",e.list===!0),e.default!==void 0&&(s.default=e.default);let i=Dt(e.description);i&&(s.description=i);let o=On(e);s.value_arity=o.value_arity;let a=Dt(e.value_name)??o.value_name;a&&(s.value_name=a);let c=o.value_type??(o.value_name?"string":null);return c&&(s.value_type=c),s}function wy(e){let t=new Map;for(let r of e){let s=xe(r.target_command);if(s.length===0)continue;let i=t.get(s)??{flags:[],sources:[],dedupe:new Set,sourceDedupe:new Set},o=`${r.layer}:${r.name}`;i.sourceDedupe.has(o)||(i.sourceDedupe.add(o),i.sources.push({layer:r.layer,name:r.name}));for(let a of r.flags){let c=fT(a);if(!c)continue;let d=`${c.flag}|${c.short??""}`;i.dedupe.has(d)||(i.dedupe.add(d),i.flags.push(c))}t.set(s,i)}let n=new Map;for(let[r,s]of t.entries())n.set(r,{flags:s.flags,sources:s.sources.sort((i,o)=>{let a=i.layer.localeCompare(o.layer);return a!==0?a:(i.name??"").localeCompare(o.name??"")})});return n}function pT(e,t){return e.read_output===void 0?{flags:t}:{read_output:e.read_output,flags:[...t,..._c.filter(({flag:n})=>n.startsWith("--output-"))]}}function _T(e){let t=wy(e.flagRegistrations),n=new Map;for(let i of e.commandDefinitions){let o=xe(i.command);if(o.length===0)continue;let a=Dt(i.action)??yy(o),c=Array.isArray(i.arguments)?i.arguments.map(d=>{let l=Dt(d.name);return l?{name:l,required:d.required===!0,variadic:d.variadic===!0,description:Dt(d.description)}:null}).filter(d=>d!==null):[];n.set(o,{...i.tier===void 0?{}:{tier:i.tier},...pT(i,t.get(o)?.flags??[]),command:o,action:a,source:{layer:i.layer,name:i.name},description:Dt(i.description),intent:Dt(i.intent),arguments:c,examples:iy(i.examples),failure_hints:iy(i.failure_hints)})}let r=new Set;for(let i of e.handlers)r.add(xe(i));for(let i of n.keys())r.add(i);for(let i of t.keys())r.add(i);let s=[];for(let i of[...r].sort((o,a)=>o.localeCompare(a))){let o=n.get(i);s.push(hT(i,o,t.get(i)?.flags??[]))}return s}function hT(e,t,n){return t?{...t,flags:t.flags.length>0?t.flags:n}:{command:e,action:yy(e),source:null,description:null,intent:null,arguments:[],flags:n,examples:[],failure_hints:[]}}function gT(e){let t=e.flag.startsWith("--")?e.flag:void 0,n=qc({long:t,short:t===void 0?e.flag:void 0});return n!==null&&/[a-z0-9]/iu.test(n)?n:null}function yT(e,t){return e.variadic?{type:"array",items:{type:"string"},description:e.description??`Variadic argument '${e.name}' for extension action '${t}'.`}:{type:"string",description:e.description??`Argument '${e.name}' for extension action '${t}'.`}}function wT(e,t){let n=e.value_type??"boolean",r=n==="boolean"?"boolean":n==="number"?["number","string"]:"string",s=e.repeatable===!0||e.list===!0;return{type:s?"array":r,...s?{items:{type:r}}:{},...e.default!==void 0?{default:e.default}:{},description:e.description??`Extension option '${e.flag}' for action '${t}'.`}}function vT(e){let t=e.command.split("|").map(s=>s.trim()).filter(s=>s.length>0),n={action:{type:"string",const:e.action,description:e.intent??e.description??`Invoke extension command '${e.command}'.`}},r=["action"];for(let s of e.arguments)n[s.name]=yT(s,e.action),s.required&&r.push(s.name);for(let s of e.flags){let i=gT(s);!i||n[i]!==void 0||(n[i]=_c.some(o=>o.flag===s.flag&&o.flag.startsWith("--output-"))?uh[i]:wT(s,e.action),s.required===!0&&r.push(i))}return{type:"object",properties:n,required:r,additionalProperties:!0,"x-extension-source":e.source,"x-extension-command":t[0]??e.command,"x-extension-commands":t}}function kT(e,t){e.description??=t.description,e.value_name??=t.value_name,e.value_type??=t.value_type,t.required===!0&&(e.required=!0),t.repeatable===!0&&(e.repeatable=!0)}function bT(e){let t=new Map;for(let n of e){let r=t.get(n.action);if(!r){t.set(n.action,{...n,flags:[...n.flags],examples:[...n.examples],failure_hints:[...n.failure_hints]});continue}r.command=[...new Set([r.command,n.command])].sort((i,o)=>i.localeCompare(o)).join("|"),r.arguments=r.arguments.length>=n.arguments.length?r.arguments:n.arguments;let s=new Set(r.flags.map(i=>`${i.flag}|${i.short??""}`));for(let i of n.flags){let o=`${i.flag}|${i.short??""}`;if(!s.has(o))s.add(o),r.flags.push(i);else{let a=r.flags.find(c=>`${c.flag}|${c.short??""}`===o);a&&kT(a,i)}}r.examples=[...new Set([...r.examples,...n.examples])],r.failure_hints=[...new Set([...r.failure_hints,...n.failure_hints])]}return[...t.values()].sort((n,r)=>n.action.localeCompare(r.action))}async function xT(e,t=C){let n={mode:Kt.extensions.policy.mode,trust_mode:Kt.extensions.policy.trust_mode,default_sandbox_profile:Kt.extensions.policy.default_sandbox_profile};if(e.noExtensions)return{handlers:new Set,disabledReason:"extensions_disabled",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};let r=I(process.cwd(),e.path);if(!await se(Oe(r)))return{handlers:new Set,disabledReason:null,commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};try{let s=await t(r),i=await ci({pmRoot:r,settings:s,cwd:process.cwd(),noExtensions:!1}),o=await di({...i,loaded:i.loaded});return{handlers:new Set(o.commands.handlers.map(c=>xe(c.command))),disabledReason:null,commandDefinitions:o.registrations.commands,flagRegistrations:o.registrations.flags,registrations:o.registrations,policyState:{mode:i.policy.mode,trust_mode:i.policy.trust_mode,default_sandbox_profile:i.policy.default_sandbox_profile}}}catch{return{handlers:new Set,disabledReason:"extension_runtime_probe_failed",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n}}}function ST(e,t={}){let n=new Map;for(let r of im){let s=Bi.has(r);if(s&&!t.includePackageOwnedActions)continue;let i=sy(r);n.set(r,{action:r,provider:s?"extension":"core",requires_extension:s,command_path:i})}if(t.includePackageOwnedActions)for(let r of Bi)n.has(r)||n.set(r,{action:r,provider:"extension",requires_extension:!0,command_path:sy(r)});for(let r of e)n.has(r.action)||n.set(r.action,{action:r.action,provider:"extension",requires_extension:!0,command_path:it.find(s=>s.alias===r.command)?.canonical??xe(r.command)});return[...n.values()].sort((r,s)=>(r.action??"").localeCompare(s.action??""))}function ET(e,t){if(e.provider==="core"&&!e.requires_extension)return{action:e.action,invocable:!0,available:!0,requires_extension:!1,provider:"core",disabled_reason:null,command_path:e.command_path,cli_exposed:e.command_path!==null&&(!on.has(e.action)||t.handlers.has(e.action))};let n=e.command_path?bt(e.command_path):[],r=n.some(o=>t.handlers.has(o)||t.handlers.has(K(o))),s=n.map(o=>fy.get(K(o))).find(o=>typeof o=="string"),i=t.disabledReason===null&&r;return{action:e.action,invocable:i,available:i,requires_extension:!0,provider:"extension",disabled_reason:i?null:t.disabledReason??(s?`optional_package_not_installed:${s}`:"extension_command_not_registered"),command_path:e.command_path,cli_exposed:r,policy_state:{mode:t.policyState.mode,trust_mode:t.policyState.trust_mode,default_sandbox_profile:t.policyState.default_sandbox_profile}}}function vy(e){let t=Jr.get(e)??xi,n=Or(e).find(r=>r.flag==="--output-format"&&r.aliases?.includes("--format"));return n?[...t,n]:t}function AT(e){return on.has(K(e))?!1:Jr.has(e)}function CT(e){return my.has(e)?"list":e==="cal"?"calendar":e==="ctx"?"context":e==="update-many"?"update_many":e}function ay(e){let t=e.trim();return t?t.startsWith("--")?t:t.startsWith("-")?null:`--${t}`:null}function TT(e){let t=e.trim();return!t||t.startsWith("--")?null:t.startsWith("-")?t:null}function RT(e){let t=new Map;for(let r of e.definitions){let s=ay(r.cli_flag);if(!s)continue;let i=r.cli_aliases.map(a=>TT(a)).find(a=>a!==null),o=r.cli_aliases.map(a=>ay(a)).filter(a=>a!==null&&a!==s);for(let a of r.commands){let c=t.get(a)??{flags:[],seen:new Set},d=i?{flag:s,short:i}:{flag:s},l=`${d.flag}|${d.short??""}`;c.seen.has(l)||(c.seen.add(l),c.flags.push(d));for(let u of o){let f=`${u}|`;c.seen.has(f)||(c.seen.add(f),c.flags.push({flag:u}))}t.set(a,c)}}let n=new Map;for(let[r,s]of t.entries())n.set(r,pc(s.flags));return n}function cy(e,t){let n=[],r=new Set;for(let s of[...e,...t]){let i=`${s.flag}|${s.short??""}`;r.has(i)||(r.add(i),n.push(s))}return pc(n)}function IT(e){let t=qc(e.flag.startsWith("--")?{long:e.flag}:{short:e.flag});return{...e,owner:"extension",...t===null?{}:{sdk_option:t}}}function OT(e,t,n,r){let s=(n??[]).map(IT),i=t==="extension"&&(n!==void 0||LT(e,r));return{flags:s,inherited:i?{inherited_flags:Ap({readOutput:$T(e,r)})}:{}}}function ky(e,t){let n=K(e);return t.find(r=>K(r.command)===n)}function LT(e,t){return ky(e,t)!==void 0}function $T(e,t){return ky(e,t)?.read_output!==void 0}function NT(e,t,n,r,s){let i=new Map(t);for(let{alias:o,canonical:a}of it){let c=t.get(a)??t.get(o);c&&(i.set(o,c),i.set(a,c))}return e.map(o=>{let a=AT(o),c=a?vy(o):[],d=n.get(CT(o))??[],l=i.get(o),u=cy(c,d),f=c.length>0&&(l?.flags.length??0)>0?"mixed":a?"core":"extension",_=OT(o,f,l?.flags,s),h=cy(u,_.flags);return{command:o,flags:h,..._.inherited,...r?{canonical_command:xy(o),visibility:by(o,s),positionals:xp(o)?.slots??[],flag_invocations:Bh(o,h)}:{},provider:f,extension_sources:l?.sources}}).sort((o,a)=>o.command.localeCompare(a.command))}function MT(e,t=zt){let n=new Set(e),r=new Map;for(let s of hy){let i=s.aliases.filter(o=>n.has(o));r.set(s.canonical,{canonical:s.canonical,aliases:i,contracts:[]})}for(let s of t){if(!n.has(s.canonical)||s.registration==="commander"&&!n.has(s.alias))continue;let i=r.get(s.canonical)??{canonical:s.canonical,aliases:[],contracts:[]};i.aliases.includes(s.alias)||i.aliases.push(s.alias),i.contracts.push(s),r.set(s.canonical,i)}return[...r.values()].map(({contracts:s,...i})=>s.length===0?i:{...i,contracts:s}).sort((s,i)=>s.canonical.localeCompare(i.canonical))}function PT(){return{create_string_options:th,create_repeatable_options:nh,update_string_options:rh,update_repeatable_options:sh,list_string_options:J_,search_string_options:X_,calendar_string_options:Q_,context_string_options:Z_,activity_string_options:eh}}function dy(e,t){let n=new Set(["title","type"]);if(t==="strict"){for(let a of e.required_create_fields)n.add(a);for(let a of e.required_create_repeatables)n.add(a)}let r=In(e,"create",n),s=[...new Set(r.required)].sort((a,c)=>a.localeCompare(c)),i=[...new Set(s.map(a=>Ie("create",a)))].sort((a,c)=>a.localeCompare(c)),o=[...new Set(e.options.filter(a=>a.required===!0).map(a=>a.key))].sort((a,c)=>a.localeCompare(c));return{required_option_keys:s,required_flags:i,required_type_options:o,policy_errors:[...new Set(r.errors)].sort((a,c)=>a.localeCompare(c))}}function FT(e){let t={},n={};for(let r of[...e.types].sort((s,i)=>s.localeCompare(i))){let s=e.by_type[r];t[r]=dy(s,"strict"),n[r]=dy(s,"progressive")}return{default_create_mode:"strict",by_create_mode:{strict:{by_type:t},progressive:{by_type:n}}}}function DT(e,t){let n=Xr(e);if(n.length===0)return e;let r=!1,s=n.map(i=>{let o=i.properties;if(typeof o!="object"||o===null)return i;let a=o.action;return typeof a!="object"||a===null||a.const!=="create"?i:(r=!0,{...i,"x-create-required-options":t})});return r?{...e,oneOf:s}:e}function jT(e){let t=zi(e.action)!==void 0||zi(e.command)!==void 0,n=e.schemaOnly===!0||e.flagsOnly===!0||e.availabilityOnly===!0,r=e.summary===!0||e.full!==!0&&e.runtimeOnly!==!0&&!t&&!n,s=e.schemaOnly===!0,i=e.flagsOnly===!0,o=e.availabilityOnly===!0,a=e.runtimeOnly===!0,c=e.full===!0,d=zi(e.action),l=zi(e.command),u=!r&&!c&&!s&&!i&&!o&&!d&&!l;return{selectedAction:d,selectedCommand:l,summary:r,schemaOnly:s,flagsOnly:i,availabilityOnly:o,runtimeOnly:a,fullOutput:c,omitUnfilteredSchema:u,omitUnfilteredCommandFlags:u,omitUnfilteredCommanderAliases:u||l!==void 0&&!c}}function UT(e){if([e.summary,e.schemaOnly,e.flagsOnly,e.availabilityOnly].filter(n=>n).length>1)throw new p("Choose only one projection flag: --summary, --schema-only, --flags-only, or --availability-only.",m.USAGE)}async function GT(e,t=C){try{return await t(e)}catch{return structuredClone(Kt)}}async function qT(e,t,n){let r=await GT(t),s=await xT(e),i=D(r,s.registrations??F()),o=Yt(r.schema),a=_T(s);return{settings:r,runtimeProbe:s,typeRegistry:i,statusRegistry:z(r.schema),runtimeFieldRegistry:o,runtimeFieldFlagMap:RT(o),createRequiredOptionContracts:FT(i),extensionContracts:a,mergedExtensionContracts:bT(a.filter(c=>Hi(n,c.command,a))),extensionFlagMap:wy(s.flagRegistrations)}}function ly(e){return e.availabilityOnly&&(e.selectedAction!==void 0&&Bi.has(e.selectedAction)||e.selectedCommand!==void 0&&on.has(K(e.selectedCommand)))}function WT(e,t){let n=ST(t,{includePackageOwnedActions:ly(e)});if(e.selectedAction===void 0&&e.selectedCommand===void 0){let r=new Set(om);return n.filter(s=>!r.has(s.action)&&(e.fullOutput||(t.find(i=>i.action===s.action)?.tier??Kc(s.action))!=="internal"))}return ly(e)&&e.selectedCommand!==void 0&&on.has(K(e.selectedCommand))&&!n.some(r=>r.command_path===e.selectedCommand)&&n.push({action:dT(K(e.selectedCommand)),provider:"extension",requires_extension:!0,command_path:e.selectedCommand}),n}function KT(e,t){let n=new Set(t.map(r=>r.action));if(e.selectedAction&&!n.has(e.selectedAction))throw new p(`Unknown action: "${e.selectedAction}".`,m.USAGE)}function zT(e,t){return[...new Set([...ot.filter(n=>!on.has(K(n))),...[...Jr.keys()].filter(n=>!on.has(K(n))),...e.flatMap(n=>n.command_path?bt(n.command_path).filter(r=>n.provider==="extension"||!on.has(K(r))||t.some(s=>s.action===n.action)):[]),...t.flatMap(n=>n.command.split("|").flatMap(r=>{let s=it.find(i=>i.alias===r||i.canonical===r);return s===void 0?[r]:[s.alias,s.canonical]}))])].map(n=>xe(n)).filter(n=>n.length>0).sort((n,r)=>n.localeCompare(r))}function BT(e,t){let n=t.slice(0,iT),r=t.length-n.length,s=r>0?`${n.join(", ")}, and ${r} more`:n.join(", "),i=t.slice(0,oT),o=t.slice(0,5).map(c=>`pm contracts --command "${c}" --flags-only --json`),a=t[0];return new p(`Command "${e}" is a command namespace. Choose a concrete child command: ${s}.`,m.USAGE,{code:"command_namespace",required:"Use a concrete child command path listed under this namespace.",why:"Command groups expose help at the namespace root, but command flag contracts belong to executable child commands.",examples:o,nextSteps:[`Retry with a child command, for example: ${o[0]}`],recovery:{suggested_retry:`pm contracts --command "${a}" --flags-only --json`,fallback_candidates:i.map(c=>({source:"command_namespace",command:`pm contracts --command "${c}" --flags-only --json`,reason:`Child command under ${e}`}))}})}function HT(e,t){return new p(`Unknown command: "${e}". Command "${e}" is provided by the optional "${t}" package. Run "pm package install ${t} --project" and retry.`,m.USAGE,{code:"unknown_command",required:`Install the optional "${t}" package, or choose a command from pm contracts --flags-only --json.`,why:"Command contracts include core commands plus commands registered by active packages and extensions.",examples:[`pm package install ${t} --project`,`pm contracts --command ${e} --flags-only --json`],nextSteps:[`Install the optional package first: pm package install ${t} --project`],recovery:{suggested_retry:`pm package install ${t} --project`}})}function VT(e){return new p(`Unknown command: "${e}".`,m.USAGE,{code:"unknown_command",required:"Use a command path listed by pm contracts --flags-only --json.",why:"Command contracts are generated from the active core, package, and extension command registry.",examples:["pm contracts --flags-only --json","pm --help"],nextSteps:["Verify spelling and active packages/extensions, then rerun with a known command path."],recovery:{suggested_retry:"pm contracts --flags-only --json"}})}function YT(e,t){if(!e.selectedCommand||new Set(t).has(e.selectedCommand))return;let r=t.filter(i=>i.startsWith(`${e.selectedCommand} `));if(r.length>0)throw BT(e.selectedCommand,r);let s=fy.get(K(e.selectedCommand));throw s?HT(e.selectedCommand,s):VT(e.selectedCommand)}function JT(e,t){let n=WT(e,t.mergedExtensionContracts);KT(e,n);let r=zT(n,t.mergedExtensionContracts);YT(e,r);let s=e.selectedCommand?_y.get(K(e.selectedCommand)):void 0,i=e.selectedCommand?n.filter(d=>s?d.action===s:lT(d,e.selectedCommand)):n;if(e.selectedCommand&&e.selectedAction&&!i.some(d=>d.action===e.selectedAction))throw new p(`Action "${e.selectedAction}" is not mapped to command "${e.selectedCommand}" in contracts output.`,m.USAGE);let o=e.selectedAction?i.filter(d=>d.action===e.selectedAction):i,a=[...new Map(o.map(d=>ET(d,t.runtimeProbe)).map(d=>[s?d.action:`${d.action}|${d.command_path??""}`,d])).values()],c=e.runtimeOnly&&!e.selectedAction&&!e.availabilityOnly?a.filter(d=>d.invocable):a;return{actionDescriptors:n,commandCatalog:r,commandScopedDescriptors:i,scopedActionDescriptors:o,selectedPackageOwnedAction:s,actionAvailability:c,actions:[...new Set(c.map(d=>d.action))]}}function XT(e){return new Set(Xr(e).map(t=>{let n=t.properties;if(typeof n!="object"||n===null)return null;let r=n.action;if(typeof r!="object"||r===null)return null;let s=r.const;return typeof s=="string"?s:null}).filter(t=>t!==null))}function QT(e){let t=mh,n=Xr(t),r=XT(t),s=e.filter(i=>!r.has(i.action)).map(i=>vT(i));return s.length>0?{...t,oneOf:[...n,...s]}:t}function uy(e,t,n){let r=new Set(t.actionDescriptors.map(i=>i.action)),s=e.selectedAction?mT(n,e.selectedAction):e.selectedCommand?td(n,new Set(t.scopedActionDescriptors.map(i=>i.action))):td(n,r);return e.runtimeOnly&&!e.selectedAction?td(s,new Set(t.actions)):s}function ZT(e,t,n){let r=QT(t.mergedExtensionContracts),i=!e.flagsOnly&&!e.availabilityOnly?DT(uy(e,n,r),t.createRequiredOptionContracts):uy(e,n,r);return{mergedSchema:r,filteredSchema:i}}function eR(e,t){return e.selectedCommand!==void 0?[e.selectedCommand]:e.selectedAction?uT(t.scopedActionDescriptors,t.commandCatalog):t.commandCatalog}function by(e,t){return t.find(n=>K(n.command)===K(e))?.tier??Kc(e)}function Hi(e,t,n){return e.fullOutput||e.selectedCommand!==void 0||e.selectedAction!==void 0||by(t,n)!=="internal"}function tR(e,t,n){if(e.selectedCommand!==void 0||e.selectedAction!==void 0)return t;let r=new Set(zt.filter(s=>s.hidden&&(s.lifecycle==="deprecated"||!e.fullOutput&&!e.availabilityOnly)).map(s=>s.alias));if(e.summary&&!e.fullOutput)for(let s of rd.keys())r.add(s);return t.filter(s=>!r.has(s)&&Hi(e,s,n))}function xy(e){let t=it.find(r=>r.alias===e||r.canonical===e);if(t)return t.canonical;let n=e.split(" ")[0];return n.startsWith("list-")?"list":rd.get(n)??n}var nR=new Map([["activate","Activate"],["adopt","Adopt"],["adopt-all","Adopt all"],["catalog","Catalog"],["complete","Complete"],["create","Create"],["deactivate","Deactivate"],["delete","Delete"],["describe","Describe"],["doctor","Diagnose"],["explore","Explore"],["init","Initialize"],["inspect","Inspect"],["install","Install"],["list","List"],["manage","Manage"],["migrate","Migrate"],["mutate","Mutate"],["reload","Reload"],["restore","Restore"],["run","Run"],["snapshot","Manage snapshots for"],["uninstall","Uninstall"],["upgrade","Upgrade"]]),rR=new Map([["extension adopt-all","extensions"],["package adopt-all","packages"],["workspace snapshot list","workspace snapshots"]]);function sR(e,t){let n=ry.get(K(e))??(e.includes(" ")?void 0:ry.get(xy(e)));if(n!==void 0)return{intent:n,intent_source:"command"};let r=t.find(d=>bt(d.command).some(l=>K(l)===K(e)));if(r?.intent!==null&&r?.intent!==void 0)return{intent:r.intent,intent_source:"command"};if(r?.description!==null&&r?.description!==void 0)return{intent:r.description,intent_source:"description"};let s=e.split(" "),i=s.at(-1),o=s.slice(0,-1).join(" "),a=nR.get(i),c=rR.get(e)??o;return{intent:a===void 0||o.length===0?`Run ${e}.`:`${a} ${c}.`,intent_source:"generated"}}function iR(e,t=[],n={}){let r=n.includeFormatBudgets??!0,s=n.includeIntentProvenance??!0;return[...new Set(e.map(xe))].filter(i=>i.length>0).sort((i,o)=>i.localeCompare(o)).map(i=>{let o=rc(i,{generateFallback:!0}),a=i.split(" ")[0],c=rd.get(a)??(a.startsWith("list-")?"list":a.startsWith("history-")?"history":a),d=new Set([...vy(i).map(f=>f.flag),...t.filter(f=>bt(f.command).some(_=>K(_)===K(i))).flatMap(f=>f.flags.map(_=>_.flag))]),l=(ny.get(K(i))??ny.get(c)??sT).filter(f=>d.has(f)),u=sR(i,t);return{command:i,intent:u.intent,...s||u.intent_source!=="command"?{intent_source:u.intent_source}:{},...l.length>0?{flags:l}:{},default_max_estimated_tokens:o.default_max_estimated_tokens,...r?{default_max_estimated_tokens_by_format:{...o.default_max_estimated_tokens_by_format}}:{}}})}function oR(e){return e.map(t=>({budget:rc(t,{generateFallback:!0}),envelope:Og(t)}))}function aR(e){let t=new Map;for(let n of e){let r=Mg(n),s=r===void 0?[m.SUCCESS,m.GENERIC_FAILURE,m.USAGE,m.NOT_FOUND,m.CONFLICT,m.DEPENDENCY_FAILED]:r.exit_codes,i=s.join(","),o=t.get(i)??{commands:[],exit_codes:s};o.commands.push(n),t.set(i,o)}return[...t.values()]}function cR(e,t,n){if(e.selectedCommand)return t.extensionContracts.filter(r=>bt(r.command).some(s=>K(s)===K(e.selectedCommand)));if(e.selectedAction){let r=new Set(n);return t.extensionContracts.filter(s=>bt(s.command).some(i=>r.has(i)))}return t.extensionContracts.filter(r=>Hi(e,r.command,t.extensionContracts))}function dR(e,t,n,r){return{schema_version:typeof t.mergedSchema["x-schema-version"]=="string"?t.mergedSchema["x-schema-version"]:null,schema_id:typeof t.mergedSchema.$id=="string"?t.mergedSchema.$id:null,selected:{action:e.selectedAction??null,command:e.selectedCommand??null,summary:e.summary,schema_only:e.schemaOnly,flags_only:e.flagsOnly,availability_only:e.availabilityOnly,runtime_only:e.runtimeOnly,command_scoped:e.selectedCommand!==void 0},commands:e.summary?[]:r,...!e.summary&&!e.flagsOnly?{actions:n.actions,action_availability:n.actionAvailability}:{}}}function lR(e,t,n){(n.selectedCommand==="history"||n.fullOutput)&&!n.flagsOnly&&!n.schemaOnly&&!n.availabilityOnly&&(e.history_operations=Fm);let r=n.selectedCommand;e.runtime_schema={statuses:t.statusRegistry.definitions.map(s=>s.id),open_status:t.statusRegistry.open_status,close_status:t.statusRegistry.close_status,canceled_status:t.statusRegistry.canceled_status,types:[...t.typeRegistry.types],fields_by_command:Object.fromEntries([...t.runtimeFieldRegistry.command_to_fields.entries()].filter(([s])=>r===void 0||s===r).map(([s,i])=>[s,[...new Set(i.map(o=>`--${o.cli_flag}`))].sort((o,a)=>o.localeCompare(a))]))},!(r!==void 0&&!n.fullOutput)&&(e.extension_contracts={capabilities:[...Qu],services:[...Zu],policy_modes:[...em],policy_mode_scope:"extensions.policy.mode",policy_surfaces:[...rm],trust_modes:[...tm],trust_mode_scope:"extensions.policy.trust_mode",sandbox_profiles:[...nm],manifest_versions:[1,2],compatibility:{current:"v2",previous:["v1"],breaking_strategy:"versioned_breaking"}},e.governance_contracts={ownership_enforcement_modes:[...fm],create_modes:[...pm],close_validation_modes:[..._m],workflow_enforcement_modes:[...hm]},e.relationship_kind_contracts=[...bf,...(t.runtimeProbe.registrations?.relationship_kinds??[]).flatMap(s=>s.definitions)].sort((s,i)=>s.kind.localeCompare(i.kind)).map(s=>({canonical:s.kind,aliases:[...s.aliases??[]],...s.inverse===void 0?{}:{inverse:s.inverse},ordering:s.ordering,hierarchy:s.hierarchy})))}function uR(e,t,n,r){if(!(t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredSchema){e.schema=n.filteredSchema,e.extension_commands=r;return}e.schema_omitted_reason="unfiltered_default_brief",e.extension_commands=r}}function mR(e,t,n,r,s){if(!(t.schemaOnly||t.availabilityOnly)){if(t.omitUnfilteredCommandFlags)e.command_flags_omitted_reason="unfiltered_default_brief";else{e.command_flags=NT(r,n.extensionFlagMap,n.runtimeFieldFlagMap,t.selectedCommand!==void 0,n.extensionContracts);let i=new Set(r);e.list_projections=Object.entries(bp).filter(([o])=>i.has(o)).map(([o,a])=>({command:o,default:a,brief_fields:[...kp,"priority"],compact_fields:[...vp]}))}e.command_aliases=t.fullOutput?s:s.map(({canonical:i,aliases:o})=>({canonical:i,aliases:o})),t.fullOutput||(e.command_alias_contracts_omitted_reason="compact_projection; restore with --full")}}function fR(e,t){if(!(t.schemaOnly||t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredCommanderAliases){e.commander_aliases=PT();return}e.commander_aliases_omitted_reason=t.selectedCommand?"command_scoped":"unfiltered_default_brief"}}function pR(e,t,n,r){e.command_summaries=iR(t,n,{includeFormatBudgets:r.includeFormatBudgets,includeIntentProvenance:r.includeIntentProvenance}),e.output_policy={token_estimate:"ceil(utf8_bytes / 4)",degradation_ladder:[...uf],allows_unbounded_opt_out:!0},e.output_projection_contracts={global_ladder_field:"output_policy.degradation_ladder",global_ladder_scope:"union_not_per_command",discovery:"pm contracts --command <command> --summary",...r.includeProjectionModeMatrix?{commands:[...new Set(t.map(xe))].filter(s=>pf(s)!==void 0).sort((s,i)=>s.localeCompare(i)).map(s=>({command:s,modes:[..._f(s).keys()]}))}:{}},e.grammar_contracts={nouns:nn.nouns,shared_verbs:nn.shared_verbs,scope_before_verb:nn.scope_before_verb,visible_top_level_ceiling:nn.visible_top_level_ceiling,ceiling_raise_requires_pm_item:nn.ceiling_raise_requires_pm_item,positional_shape_budget:nn.positional_shape_budget,positional_shape_count:new Set(fc.map(({slots:s})=>Ep(s))).size,positional_action_count:mc.length,positional_action_parents:[...new Set(mc.map(({parent:s})=>s))].sort((s,i)=>s.localeCompare(i)),...r.includePositionalSignatures?{positional_signatures:fc}:{}}}async function hK(e,t){let n=jT(e);UT(n);let r=I(process.cwd(),t.path),s=await qT(t,r,n),i=JT(n,s),o=ZT(n,s,i),a=eR(n,i),c=tR(n,a,s.extensionContracts),d=dR(n,o,i,c),l=cR(n,s,c),u=n.fullOutput||n.selectedCommand!==void 0;if((n.summary||n.fullOutput)&&pR(d,c,l,{includeFormatBudgets:u,includeIntentProvenance:u,includePositionalSignatures:u,includeProjectionModeMatrix:u}),n.summary)return d;let f=MT(i.commandCatalog.filter(_=>Hi(n,_,s.extensionContracts)));return n.flagsOnly&&!n.fullOutput||lR(d,s,n),uR(d,n,o,l),mR(d,n,s,c,f),fR(d,n),(n.selectedCommand==="assurance"||n.fullOutput)&&(d.assurance_contracts={measurement_source_kinds:[...zr],gate_triggers:[...vt]}),n.fullOutput&&d.grammar_contracts&&(d.grammar_contracts.destinations=Sp.map(_=>({..._,reason:_.reason??""}))),n.fullOutput&&!n.schemaOnly&&!n.flagsOnly&&!n.availabilityOnly&&(d.mcp_tools=ty(),d.context_intents=hf(),d.read_output_dimensions=ff,d.error_codes=Rg,d.command_output_contracts=oR(c),d.diagnostic_output_contracts=mf,d.command_exit_contracts={vocabulary:Bc,command_sets:aR(c)}),d}import{createHash as Ey}from"node:crypto";import Qr from"node:fs/promises";import Zr from"node:path";function Ve(e,t){throw new p(e,m.USAGE,t)}var _R="2026-07-15T06:22:12.276Z",hR=Date.parse(_R),gR=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],Sy=e=>typeof e=="string"?e:"",Ay=e=>{let t=e??{},n=Sy(t.author).trim().toLowerCase(),r=Number(["","unknown"].includes(n)),s=+(Date.parse(Sy(t.ts))>=hR);return gR[r][s]};function Cy(e,t,n=20,r=new Set,s=!1){let i=[],o=[],a={legacy_unknown:0,actionable_unknown:0},c=Math.max(0,n),d=0,l=0,u=0;for(let[f,_]of t.split(/\r?\n/).entries()){let h;try{h=JSON.parse(_)}catch{continue}d+=1;let g=Ay(h);if(g!=="attributed"){if(l+=1,g==="actionable_unknown"&&r.has(`${e}:${f+1}`)){u+=1;continue}a[g]+=1,s&&g==="actionable_unknown"&&o.push({item_id:e,line:f+1}),i.length<c&&i.push({item_id:e,line:f+1})}}return{checked_events:d,unknown_event_count:l,legacy_unknown_event_count:a.legacy_unknown,actionable_unknown_event_count:a.actionable_unknown,acknowledged_actionable_event_count:u,samples:i,samples_truncated:a.legacy_unknown+a.actionable_unknown>i.length,actionable_events:o}}var AK=(e,t,n=20,r=new Set)=>Cy(e,t,n,r);function Ty(e){let t=new Set;for(let n of e.split(/\r?\n/)){let r;try{r=JSON.parse(n)}catch{continue}let i=(typeof r=="object"&&r!==null&&typeof r.context=="object"&&r.context!==null?r.context:{}).author_acknowledgment;if(!(typeof i!="object"||i===null||!Array.isArray(i.events)))for(let o of i.events)typeof o=="object"&&o!==null&&typeof o.item_id=="string"&&Number.isSafeInteger(o.line)&&t.add(`${o.item_id}:${String(o.line)}`)}return t}var es=async(e,t=20,n=!1)=>{let r=Zr.join(e,"history"),s;try{s=(await Qr.readdir(r)).filter(w=>w.endsWith(".jsonl")).sort((w,v)=>w.localeCompare(v))}catch{s=[]}let i=new Set,o=[],a=[],c=0,d=0,l=0,u=0,f=0,_=0,h="_workspace.jsonl",g=new Set;if(s.includes(h))try{g=Ty(await Qr.readFile(Zr.join(r,h),"utf8"))}catch{g=new Set}for(let w of s){let v;try{v=await Qr.readFile(Zr.join(r,w),"utf8")}catch{continue}let S=w.slice(0,-6),b=Cy(S,v,t-o.length,g,n);c+=1,d+=b.checked_events,l+=b.unknown_event_count,u+=b.legacy_unknown_event_count,f+=b.actionable_unknown_event_count,_+=b.acknowledged_actionable_event_count,b.unknown_event_count>0&&i.add(S),o.push(...b.samples),n&&a.push(...b.actionable_events)}let y=u+f;return{checked_streams:c,checked_events:d,unknown_event_count:l,legacy_unknown_event_count:u,actionable_unknown_event_count:f,acknowledged_actionable_event_count:_,affected_item_ids:[...i].sort((w,v)=>w.localeCompare(v)),samples:o,samples_truncated:y>o.length,...n?{actionable_events:a}:{}}};function yR(e){return[...new Map(e.map(t=>[`${t.item_id}:${t.line}`,{item_id:t.item_id,line:t.line}])).values()].sort((t,n)=>t.item_id.localeCompare(n.item_id)||t.line-n.line)}async function wR(e){try{return Ty(await Qr.readFile(Zr.join(e,"history","_workspace.jsonl"),"utf8"))}catch{return new Set}}function vR(e){return(e.item_id===Qt||/^[a-z0-9][a-z0-9-]*$/iu.test(e.item_id))&&Number.isSafeInteger(e.line)&&e.line>=1}function kR(e,t,n){let r=n[e.line-1]??"",s;try{s=JSON.parse(r)}catch{Ve(`Unknown-author acknowledgment target ${e.item_id}:${e.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}return Ay(s)!=="actionable_unknown"&&Ve(`Author acknowledgment target ${e.item_id}:${e.line} is not an actionable unknown-author event.`,{code:"history_author_acknowledge_target_not_actionable"}),{...e,source_event_hash:Ey("sha256").update(r).digest("hex"),disposition:t.has(`${e.item_id}:${e.line}`)?"already_acknowledged":"actionable"}}async function Ry(e,t,n){let r=t.events??[],s=+(t.all_actionable===!0)+ +(r.length>0);s===0&&Ve("Specify exactly one selector: events or all_actionable.",{code:"history_author_acknowledge_selector_required"}),s>1&&Ve("Author acknowledgment accepts either explicit events or all_actionable, not both.",{code:"history_author_acknowledge_selector_conflict"}),(!Number.isSafeInteger(n)||n<0)&&Ve("Author acknowledgment coordinate_limit must be a non-negative integer.",{code:"history_author_acknowledge_preview_limit_invalid"});let i=yR(t.all_actionable===!0?(await es(e,0,!0)).actionable_events:r),o=await wR(e),a=new Map;for(let f of i)if(vR(f)||Ve(`Unknown-author acknowledgment target ${f.item_id}:${f.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"}),!a.has(f.item_id))try{a.set(f.item_id,(await Qr.readFile(Zr.join(e,"history",`${f.item_id}.jsonl`),"utf8")).split(/\r?\n/u))}catch{Ve(`Unknown-author acknowledgment target ${f.item_id}:${f.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}let c=i.map(f=>kR(f,o,a.get(f.item_id))),d=t.all_actionable===!0?"all_actionable":"events",l=Ey("sha256").update(JSON.stringify({version:1,selection:d,coordinates:c})).digest("hex"),u=c.filter(({disposition:f})=>f==="actionable").length;return{plan:{selection:{kind:d},selected_count:c.length,actionable_count:u,already_acknowledged_count:c.length-u,omitted_count:Math.max(0,c.length-n),coordinates:c.slice(0,n),plan_fingerprint:l},completeCoordinates:c}}async function CK(e,t,n=50){return(await Ry(e,t,n)).plan}function bR(e,t){let n=e.length>0;return n&&t&&Ve("Specify exactly one selector: repeat --event or pass --all-actionable.",{code:"history_author_acknowledge_selector_conflict",required:"Exactly one of --event or --all-actionable",examples:['pm history-author-acknowledge --event pm-a1b2:4 --attributed-author agent --reviewer maintainer --reason "Verified provenance"','pm history-author-acknowledge --all-actionable --attributed-author import-agent --reviewer maintainer --reason "Reviewed the complete actionable set"']}),!n&&!t&&Ve("Specify exactly one selector: repeat --event or pass --all-actionable.",{code:"history_author_acknowledge_selector_required",required:"Exactly one of --event or --all-actionable",examples:['pm history-author-acknowledge --event pm-a1b2:4 --attributed-author agent --reviewer maintainer --reason "Verified provenance"','pm history-author-acknowledge --all-actionable --attributed-author import-agent --reviewer maintainer --reason "Reviewed the complete actionable set"']}),{events:xR(e),all_actionable:t}}function xR(e){return e.map(t=>{let n=t.lastIndexOf(":"),r=t.slice(0,n).trim(),s=Number(t.slice(n+1)),i=r===Qt||/^[a-z0-9][a-z0-9-]*$/iu.test(r);return(n<1||!i||!Number.isSafeInteger(s)||s<1)&&Ve(`history-author-acknowledge --event expects <item-id>:<one-based-line>, received "${t}".`,{code:"history_author_acknowledge_target_unreadable"}),{item_id:r,line:s}})}function TK(e,t){let n=bR(yh(t.historyEvent),t.allActionable===!0||t.all_actionable===!0);return SR(e,{events:n.events,all_actionable:n.all_actionable,dry_run:t.dryRun===!0||t.dry_run===!0,plan_fingerprint:te(t,"planFingerprint")??te(t,"plan_fingerprint"),coordinate_limit:typeof t.limit=="number"?t.limit:typeof t.limit=="string"?Number(t.limit):void 0,attributed_author:te(t,"attributedAuthor")??te(t,"attributed_author")??void 0,reviewer:te(t,"reviewer"),reason:te(t,"reason")})}async function SR(e,t){let n=t.reviewer?.trim()??"",r=t.attributed_author?.trim()??"",s=t.reason?.trim()??"",i=await Ry(e,t,t.coordinate_limit??50);if(t.dry_run===!0)return{dry_run:!0,mutated:!1,acknowledged:0,outcome:"preview",exit_code:m.SUCCESS,plan:i.plan};if([n.length>0,n.toLowerCase()!=="unknown",r.length>0,r.toLowerCase()!=="unknown",s.length>0].includes(!1)&&Ve("Author acknowledgment requires events, reviewer, attributed_author, and reason.",{code:"history_author_acknowledge_required_values_missing"}),t.plan_fingerprint?.trim()||Ve("Author acknowledgment apply requires plan_fingerprint from a fresh dry-run preview.",{code:"history_author_acknowledge_plan_fingerprint_required",recovery:{suggested_retry:"Rerun history-author-acknowledge with --dry-run, then pass --plan-fingerprint <value>."}}),t.plan_fingerprint.trim()!==i.plan.plan_fingerprint)throw new p("Author acknowledgment selection changed after preview; no history was mutated.",m.CONFLICT,{code:"history_author_acknowledge_plan_conflict",recovery:{suggested_retry:"Rerun history-author-acknowledge with --dry-run and apply the fresh plan_fingerprint."}});let a=i.completeCoordinates.filter(({disposition:u})=>i.plan.selection.kind==="events"||u==="actionable").map(({item_id:u,line:f})=>({item_id:u,line:f}));if(a.length===0)return{dry_run:!1,mutated:!1,acknowledged:0,outcome:"no_effect",exit_code:m.NO_EFFECT,plan:i.plan};let c=await C(e),d=await $n({pmRoot:e,op:"history:author-acknowledge",author:n,context:{author_acknowledgment:{events:a,attributed_author:r}},message:s,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),l=i.plan.actionable_count>0&&i.plan.already_acknowledged_count>0?{outcome:"partial_effect",exit_code:m.PARTIAL_EFFECT}:{outcome:"effect",exit_code:m.SUCCESS};return{dry_run:!1,mutated:!0,acknowledged:a.length,...l,plan:i.plan,history_path:d.historyPath}}import YR from"node:fs/promises";import qe from"node:path";import{readdir as Ly,realpath as $y,stat as Ny}from"node:fs/promises";import Ce from"node:path";var ER=4096,AR=32,CR=1e3,TR=5e4,RR={nodes:1e4,edges:4e4,stateIds:2e6},cn=47,Hn=class extends Error{},IR=new Map(Object.entries({alnum:[[48,57],[65,90],[97,122]],alpha:[[65,90],[97,122]],ascii:[[0,127]],blank:[[9,9],[32,32]],cntrl:[[0,31],[127,127]],digit:[[48,57]],graph:[[33,126]],lower:[[97,122]],print:[[32,126]],punct:[[33,47],[58,64],[91,96],[123,126]],space:[[9,13],[32,32]],upper:[[65,90]],word:[[48,57],[65,90],[95,95],[97,122]],xdigit:[[48,57],[65,70],[97,102]]}));function My(){return new p("--add-glob does not support negated patterns (a leading ! or !(...)); list the files or patterns to link instead",m.USAGE)}function OR(e,t){let n=t+1;for((e[n]==="!"||e[n]==="^")&&(n+=1),e[n]==="]"&&(n+=1);n<e.length;){let r=e[n];if(r==="\\")n+=2;else if(r==="["&&e[n+1]===":"){let s=e.indexOf(":",n+2);s===-1||e[s+1]!=="]"?n+=1:n=s+2}else{if(r==="]")return n+1;n+=1}}return-1}function LR(e,t,n){let r=e[t];if(r==="{")return{index:t,kind:"{"};if(r!=="(")return;let s=e[t-1];return s!==void 0&&"@?*+!".includes(s)&&!Py(e,t-1)?{index:t-1,kind:"("}:n.some(i=>i.kind==="(")?{index:t,kind:"plain"}:void 0}function $R(e,t,n,r,s){let i=e[t],o=n.at(-1);if(i===")"&&o?.kind==="plain"){n.pop(),s.set(o.index,t);return}let a=i==="}"?"{":i===")"?"(":void 0;if(!(a===void 0||o?.kind!==a)&&(n.pop(),r.set(o.index,t),e[o.index]==="!"))throw My()}function NR(e){let t=new Map,n=new Map,r=new Map,s=[],i=0;for(;i<e.length;){if(e[i]==="\\"){i+=2;continue}let o=e[i]==="["?OR(e,i):-1;if(o!==-1){n.set(i,o),i=o;continue}let a=LR(e,i,s);if(a!==void 0?s.push(a):$R(e,i,s,t,r),s.length>AR)throw new Hn;i+=1}return{closers:t,brackets:n,groups:r}}function Py(e,t){let n=0;for(let r=t-1;r>=0&&e[r]==="\\";r-=1)n+=1;return n%2===1}function an(e){return Array.from(e,t=>({kind:"char",value:t.codePointAt(0)}))}function MR(e){let t=/^(-?(?:0|[1-9]\d{0,8}))\.\.(-?(?:0|[1-9]\d{0,8}))$/u.exec(e),n=/^([A-Za-z])\.\.([A-Za-z])$/u.exec(e);if(t===null&&n===null)return;let[r,s]=t!==null?[Number(t[1]),Number(t[2])]:[n[1].codePointAt(0),n[2].codePointAt(0)];if(Math.abs(s-r)+1>CR)throw new Hn;let i=r<=s?1:-1,o=[];for(let a=r;a!==s+i;a+=i)o.push(t!==null?String(a):String.fromCodePoint(a));return o}function PR(e,t){if(e[t]!=="["||e[t+1]!==":")return;let n=e.indexOf(":",t+2);if(!(n===-1||e[n+1]!=="]"))return{ranges:IR.get(e.slice(t+2,n).join(""))??[],next:n+2}}function Iy(e,t,n){let r=e[t]==="\\"&&t+1<n;return{codePoint:e[r?t+1:t].codePointAt(0),next:t+(r?2:1)}}function FR(e,t,n){let r=[];for(let s=t;s<n;s+=1)e[s]==="\\"&&s+1<n&&(s+=1),r.push(e[s].codePointAt(0));return r}function DR(e,t,n){let r=t+1,s=e[r]==="!"||e[r]==="^";s&&(r+=1);let i=[],o=n-1;for(;r<o;){let a=PR(e,r);if(a!==void 0){i.push(...a.ranges),r=a.next;continue}let c=Iy(e,r,o);if(r=c.next,e[r]!=="-"||r+1>=o){i.push([c.codePoint,c.codePoint]);continue}let d=Iy(e,r+1,o);r=d.next,c.codePoint<=d.codePoint&&i.push([c.codePoint,d.codePoint])}return{kind:"class",negated:s,ranges:i,literal:FR(e,t,n)}}var sd=class{chars;closers;brackets;groups;constructor(t,n){this.chars=t,this.closers=n.closers,this.brackets=n.brackets,this.groups=n.groups}alternatives(t,n,r){let s=[],i=t;for(;;){let{nodes:o,stop:a}=this.sequence(i,n,r);if(s.push(o),a>=n)return s;i=a+1}}sequence(t,n,r){let s=[],i=t;for(;i<n;){if(this.chars[i]===r)return{nodes:s,stop:i};let o=this.token(i,n);s.push(...o.nodes),i=o.next}return{nodes:s,stop:n}}token(t,n){let r=this.chars[t];if(r==="\\")return{nodes:an(t+1<n?this.chars[t+1]:"\\"),next:t+2};let s=this.closers.get(t);if(s!==void 0)return{nodes:r==="{"?this.brace(t,s):this.extglob(r,t,s),next:s+1};let i=this.groups.get(t);if(i!==void 0)return{nodes:[...an("("),...this.sequence(t+1,i,void 0).nodes,...an(")")],next:i+1};let o=this.brackets.get(t);return o!==void 0?{nodes:[DR(this.chars,t,o)],next:o}:r==="*"?this.stars(t,n):{nodes:r==="?"?[{kind:"any"}]:an(r),next:t+1}}extglob(t,n,r){let s=this.alternatives(n+2,r,"|");return[t==="@"?{kind:"alt",options:s}:{kind:"repeat",optional:t!=="+",many:t!=="?",options:s}]}brace(t,n){let r=this.alternatives(t+1,n,",");if(r.length>1)return[{kind:"alt",options:r}];let s=MR(this.chars.slice(t+1,n).join(""));return s!==void 0?[{kind:"alt",options:s.map(an)}]:[...an("{"),...r[0],...an("}")]}stars(t,n){let r=1;for(;this.chars[t+r]==="*"&&t+r<n&&!this.closers.has(t+r);)r+=1;if(r!==2)return{nodes:[{kind:"star"}],next:t+r};let s=t+r<n&&this.chars[t+r]==="/";return{nodes:[{kind:"globstar",slash:s}],next:t+r+(s?1:0)}}},id=["segment","inside"],Vi={kind:"any"};function od(e){return id.flatMap(t=>e[t]===void 0?[]:[e[t]])}var ad=class{states=[];add(){if(this.states.length>=TR)throw new Hn;return this.states.push({epsilon:[],syntactic:[],edges:[]}),this.states.length-1}epsilon(t,n,r=!0){this.states[t].epsilon.push(n),r&&this.states[t].syntactic.push(n)}consume(t,n,r){let s=this.add();for(let i of od(t))this.states[i].edges.push({test:n,to:s});return{[r]:s}}join(t){let n={};for(let r of id){let s=t.flatMap(i=>i[r]===void 0?[]:[i[r]]);if(s.length===1&&(n[r]=s[0]),s.length>1){let i=this.add();for(let o of s)this.epsilon(o,i);n[r]=i}}return n}feed(t,n){for(let r of id)t[r]!==void 0&&this.epsilon(t[r],n[r])}build(t,n){let r=n;for(let s of t)r=this.node(s,r);return r}alternation(t,n){return this.join(t.map(r=>this.build(r,n)))}star(t){let n=this.add();for(let r of od(t))this.epsilon(r,n,!1);return this.states[n].edges.push({test:Vi,to:n}),{inside:n}}segments(t){let n=this.add();this.epsilon(t,n,!1);let r=this.add();return this.states[n].edges.push({test:Vi,to:r}),this.states[r].edges.push({test:Vi,to:r},{test:{kind:"char",value:cn},to:n}),n}globstar(t,n){if(n){let s=[];return t.segment!==void 0&&s.push({segment:this.segments(t.segment)}),t.inside!==void 0&&s.push(this.consume(this.star({inside:t.inside}),{kind:"char",value:cn},"segment")),this.join(s)}let r=this.star(t);return t.segment!==void 0&&this.globstars.push({continuation:r.inside,entry:t.segment}),r}globstars=[];syntacticClosure(t){let n=new Set(t),r=[...t];for(;r.length>0;)for(let s of this.states[r.pop()].syntactic)n.has(s)||(n.add(s),r.push(s));return n}resolveGlobstars(t){for(let{continuation:n,entry:r}of this.globstars){let s=this.syntacticClosure([n]);if(s.has(t)){let a=this.add();this.epsilon(r,a,!1),this.states[a].edges.push({test:{kind:"all"},to:a}),this.epsilon(a,t,!1)}let i=new Set;for(let a of s)for(let{test:c,to:d}of this.states[a].edges)Fy(c,cn)&&i.add(d);if(i.size===0)continue;let o=this.segments(r);for(let a of i)this.epsilon(o,a,!1)}}repeat(t,n){if(!t.many)return this.join([n,this.alternation(t.options,n)]);let r={segment:this.add(),inside:this.add()};return this.feed(t.optional?n:this.alternation(t.options,n),r),this.feed(this.alternation(t.options,r),r),r}node(t,n){switch(t.kind){case"char":return this.consume(n,{kind:"char",value:t.value},t.value===cn?"segment":"inside");case"any":return this.consume(n,Vi,"inside");case"star":return this.star(n);case"globstar":return this.globstar(n,t.slash);case"class":return this.join([this.consume(n,{kind:"class",negated:t.negated,ranges:t.ranges},"inside"),this.build(t.literal.map(r=>({kind:"char",value:r})),n)]);case"alt":return this.alternation(t.options,n);case"repeat":return this.repeat(t,n)}}};function Fy(e,t){switch(e.kind){case"char":return e.value===t;case"any":return t!==cn;case"all":return!0;case"class":return t!==cn&&e.ranges.some(([n,r])=>t>=n&&t<=r)!==e.negated}}var cd=class{generation=0;nextId=0;nodes=new Map;edges=new Map;stateIds=0;nfa;acceptState;limits;start;constructor(t,n,r,s){this.nfa=t,this.acceptState=r,this.limits=s,this.start=this.node(this.closure([n]))}retained(){return{nodes:this.nodes.size,edges:this.edges.size,stateIds:this.stateIds}}reset(){this.generation+=1,this.nodes=new Map,this.edges=new Map,this.stateIds=0}closure(t){let n=new Set(t),r=[...t];for(;r.length>0;)for(let s of this.nfa.states[r.pop()].epsilon)n.has(s)||(n.add(s),r.push(s));return[...n].sort((s,i)=>s-i)}node(t){let n=t.join(","),r=this.nodes.get(n);if(r!==void 0)return r;(this.nodes.size>=this.limits.nodes||this.stateIds+t.length>this.limits.stateIds)&&this.reset();let s={id:this.nextId,generation:this.generation,states:t,accepting:t.includes(this.acceptState)};return this.nextId+=1,this.nodes.set(n,s),this.stateIds+=t.length,s}step(t,n){let r=`${t.id}:${n}`,s=t.generation===this.generation?this.edges.get(r):void 0;if(s!==void 0)return s;let i=[];for(let a of t.states)for(let{test:c,to:d}of this.nfa.states[a].edges)Fy(c,n)&&i.push(d);let o=this.node(this.closure(i));return this.edges.size>=this.limits.edges&&this.reset(),t.generation===this.generation&&this.edges.set(r,o),o}advance(t,n){let r=t;for(let s of n){if(r.states.length===0)return r;r=this.step(r,s.codePointAt(0))}return r}};function jR(e,t=RR){let n=Array.from(e),r=new sd(n,NR(n)).sequence(0,n.length,void 0).nodes,s=new ad,i=s.add(),o=s.add();for(let a of od(s.build(r,{segment:i})))s.epsilon(a,o);return s.resolveGlobstars(o),new cd(s,i,o,t)}function UR(e){return!/[*?[\]{}()!@+\\]/u.test(e)}function Oy(e){return e.isFile()?"file":e.isDirectory()?"directory":"other"}async function GR(e,t,n){if(!n.isSymbolicLink())return{kind:Oy(n),real:Ce.join(t,n.name)};try{let r=await $y(Ce.join(e,n.name));return{kind:Oy(await Ny(r)),real:r}}catch{return}}async function Dy(e,t,n,r,s,i,o){let a;try{a=await Ly(t,{withFileTypes:!0})}catch{return}for(let c of a){let d=e.advance(s,c.name);if(d.states.length===0)continue;let l=await GR(t,n,c);if(l===void 0)continue;let u=Ce.posix.join(r,c.name);if(l.kind==="file"&&d.accepting&&o.push(u),l.kind!=="directory")continue;let f=e.step(d,cn);f.states.length===0||i.has(l.real)||(i.add(l.real),await Dy(e,Ce.join(t,c.name),l.real,u,f,i,o),i.delete(l.real))}}function qR(e){let t=Ce.posix.normalize(e);return/^\/\/[^/]/u.test(e)?`/${t}`:t}function WR(e){let t=e;for(;t.length>1&&t.endsWith("/")&&!Py(t,t.length-1);)t=t.slice(0,-1);return t}async function jy(e,t){return(await Ly(e).catch(()=>[])).includes(t)}async function Uy(e,t){let n=e,r=0;for(;t[r]==="..";)n=Ce.dirname(n),r+=1;for(;r<t.length;r+=1){if(!await jy(n,t[r]))return!1;n=Ce.join(n,t[r])}return!0}function Gy(e,t=process.platform){return e.startsWith("/")||t==="win32"&&/^[A-Za-z]:\//u.test(e)}async function KR(e,t){let n=Ce.resolve(t,e),r=await Ny(n).catch(()=>{});if(r===void 0||!r.isFile())return[];let s=Gy(e);return(s?await jy(Ce.dirname(n),Ce.basename(n)):await Uy(t,e.split("/")))?[s?n.replaceAll("\\","/"):Ce.posix.normalize(e)]:[]}function zR(e,t){let n=e.split("/"),r=0;for(;r<n.length&&UR(n[r]);)r+=1;if(r===n.length)return;let s=r===0?"":`${n.slice(0,r).join("/")}/`,i=Ce.resolve(t,s),o=n.slice(r).join("/");if(Gy(e))return{root:i,base:i.replaceAll("\\","/"),rest:o,prefix:[]};let a=Ce.posix.normalize(s===""?".":s).replace(/\/$/u,"");return{root:i,base:a==="."?"":a,rest:o,prefix:n.slice(0,r)}}function BR(e){try{return jR(e)}catch(t){if(t instanceof Hn)return;throw t}}async function qy(e,t){if(e.startsWith("!"))throw My();if(Array.from(e).length>ER)return[];let n=WR(qR(e)),r=zR(n,t);if(r===void 0)return KR(n,t);let s=BR(r.rest);if(s===void 0||!await Uy(t,r.prefix))return[];let i=await $y(r.root).catch(()=>{});if(i===void 0)return[];let o=[];return await Dy(s,r.root,i,"",s.start,new Set([i]),o),o.map(a=>HR(r.base,a))}function HR(e,t){return e.startsWith("//")?`/${Ce.posix.join(e.slice(1),t)}`:Ce.posix.join(e,t)}var VR=/^[a-z][a-z0-9+.-]+:\/\//i;function ts(e){return VR.test(e.trim())}var dd=["refuse","replace","append"],ud="; ";function JR(e,t){if(e===void 0)return"refuse";let n=e.trim().toLowerCase();if(!dd.some(r=>r===n))throw new p(`--note-conflict must be one of ${dd.join(", ")}; got "${e}"`,m.USAGE,{code:"invalid_argument_value",flag:"--note-conflict",value:e,required:`Pass --note-conflict ${dd.join("|")}.`});if(!t)throw new p("--note-conflict requires --add or --add-glob in the same invocation (it decides how those links treat an existing note)",m.USAGE,{code:"missing_required_argument",flag:"--note-conflict",required:"Pass --add or --add-glob with --note-conflict."});return n}function XR(e,t,n){if(t===void 0||t===e)return{note:e,outcome:"unchanged",conflict:!1};if(e===void 0)return{note:t,outcome:"note_added",conflict:!1};if(n==="replace")return{note:t,outcome:"note_replaced",conflict:!1};if(n==="append"){let r=ud;return`${r}${e}${r}`.includes(`${r}${t}${r}`)?{note:e,outcome:"unchanged",conflict:!1}:{note:`${e}${ud}${t}`,outcome:"note_appended",conflict:!1}}return{note:e,outcome:"unchanged",conflict:!0}}function QR(e){let t=e.conflicts[0],n=e.conflicts.length>1?` and ${e.conflicts.length-1} more`:"",r=e.retryArgs("append"),s=e.retryArgs("replace"),i=t.source==="stored"?`${e.itemId} already links ${e.noun} ${t.path} with the note "${t.existing_note}"${n}; the add was refused so that note is kept`:`The add names ${e.noun} ${t.path} on ${e.itemId} with two notes, "${t.existing_note}" and then "${t.requested_note}"${n}; the add was refused because they disagree`;return new p(i,m.CONFLICT,{code:"linked_artifact_note_conflict",item_id:e.itemId,why:"A different stored note is usually another agent's rationale, so --add never overwrites it silently.",required:"Re-run with --note-conflict append to keep both notes, or --note-conflict replace to overwrite the stored note.",...r===void 0||s===void 0?{}:{nextSteps:[e.render(r),e.render(s)],recovery:{suggested_retry:e.render(r),suggested_retry_args:r}},details:{conflicts:e.conflicts.map(o=>({...o}))}})}var md=["path","scope","note"],ZR=["pattern","glob","path","scope","note"],eI=["path"],tI=["from","to"],nI=new Set(["note","scope"]);function Wy(e){return JSON.parse(JSON.stringify(e))}function hd(e,t){let n=e.map(Wy);return t.filter(r=>{let s=Wy(r),i=n.findIndex(o=>Ue(o,s));return i>=0&&n.splice(i,1),i<0})}function ns(e){let t=e.fullHistory?[...e.stored]:[...e.written],n=t.length<e.stored.length;return{entries:t,total_count:e.stored.length,returned_count:t.length,has_more:n,mutation_receipt:{changed_count:e.written.length,removed_count:e.removedCount,full_history_included:!n,...e.linkOutcomes&&e.linkOutcomes.length>0?{link_outcomes:[...e.linkOutcomes]}:{}},omission_receipt:{has_omissions:n,omitted_field_group_count:n?1:0,omitted_field_groups:n?[{name:`${e.collectionKey}_history`,restore_with:{selector:"full_history",cli_flag:"--full-history",sdk_option:"fullHistory",mcp_option:"full"}}]:[]}}}function Ky(e){let t=e??"project";if(!Be.includes(t))throw new p(`Invalid scope "${e}". Valid scopes: ${Be.join(", ")} (default: project).`,m.USAGE);return t}function fd(e){if(e.startsWith("```")||e.includes(`
|
|
6
|
+
`)||/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(e))return!0;let t=e.indexOf(","),n=e.slice(0,t>=0?t:e.length),r=n.indexOf("=");return r>=0&&!/\s/u.test(e)&&(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)||/^(?:[A-Za-z]:[\\/]|[\\/]{1,2}|\.\.?(?:[\\/]))/u.test(e)||[e.indexOf("/"),e.indexOf("\\")].some(s=>s>=0&&s<r))?!1:n.includes("=")||Cn(e)}function rI(e){let t=0;for(let n of e)if(n==="("&&(t+=1),n===")"&&(t-=1),t<0)return!1;return t===0}function sI(e){if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)&&!fd(e))return{path:e,scope:"project",note:void 0};let t=e.indexOf("](");if(e.startsWith("[")&&t>0&&e.endsWith(")")){let i=e.slice(t+2,-1).trim();if(i.length>0&&rI(i))return{path:i,scope:"project",note:e.slice(1,t).trim()||void 0}}let n=e.indexOf(",");if(n<0)return;let r=e.slice(0,n).trim(),s=e.slice(n+1).trim();if(!(r.length===0||!/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(s)))return{path:s,scope:"project",note:r}}function gd(e,t){return e?e.flatMap(n=>{let r=n.trim();if(t==="doc"){let i=sI(r);if(i!==void 0)return[i]}hr(r,"--add",`${t} path`,fd(r));let s=fd(r)?ee(n,"--add"):{path:r};if(be(s,"--add",md),!s.path)throw new p(`--add requires path=<value> or a bare ${t} path`,m.USAGE);return[{path:s.path,scope:Ky(s.scope),note:s.note?.trim()||void 0}]}):[]}function iI(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new p("--add-glob requires a glob pattern value",m.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?(?:pattern|glob|path)\s*[:=]/i.test(n)||n.startsWith("```")){let r=ee(n,"--add-glob");be(r,"--add-glob",ZR);let s=r.pattern?.trim()||r.glob?.trim()||r.path?.trim();if(!s)throw new p("--add-glob key/value form requires pattern=<glob>",m.USAGE);return{pattern:s,scope:Ky(r.scope),note:r.note?.trim()||void 0}}return{pattern:n,scope:"project"}}):[]}function oI(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new p("--remove requires a path value",m.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?path\s*[:=]/i.test(n)||n.startsWith("```")){let r=ee(n,"--remove"),s=Object.keys(r).filter(i=>nI.has(i.toLowerCase()));if(s.length>0)throw new p(`--remove identifies a linked artifact by path only and does not accept ${s.map(i=>`"${i}"`).join(", ")}. Pass just the path (path=<value>, path:<value>, or a bare path); record removal context with --message "<why removed>".`,m.USAGE);if(be(r,"--remove",eI),!r.path)throw new p("--remove key/value form requires path=<value>",m.USAGE);return r.path}return n}):[]}function aI(e){return e?e.map(t=>{let n=ee(t,"--migrate");be(n,"--migrate",tI);let r=n.from?.trim(),s=n.to?.trim();if(!r||!s)throw new p("--migrate requires from=<value> and to=<value>",m.USAGE);return{from:r,to:s}}):[]}function Vn(e,t){let n=e;for(let r of t)n.startsWith(r.from)&&(n=`${r.to}${n.slice(r.from.length)}`);return n}function cI(e,t,n=[]){if(e.length===0||t.length===0)return;let r=new Set(e.map(i=>jt(Vn(i.path,n)))),s=[...new Set(t.map(i=>jt(Vn(i,n))).filter(i=>r.has(i)))].sort((i,o)=>i.localeCompare(o));if(s.length!==0)throw new p(`Linked artifact mutation cannot add and remove the same normalized path in one transaction: ${s.join(", ")}. Split the replacement into separate commands so each history event has one unambiguous intent.`,m.USAGE,{code:"linked_artifact_mutation_conflict",reason:"same_path_added_and_removed",required:"Use distinct normalized paths for --add and --remove in one invocation.",why:"Conflicting batch intent cannot be applied deterministically without silently discarding metadata or a removal.",nextSteps:["Run the removal and addition as separate commands with a --message describing each intent."]})}function xt(e){return e.split(qe.sep).join("/")}function pd(e,t,n=process.cwd()){let r=e.trim();if(ts(r))return r;if(qe.isAbsolute(r)||/^[A-Za-z]:[\\/]/.test(r))return xt(r.replaceAll("\\",qe.sep));let s=qe.relative(t,n);return s.startsWith(`..${qe.sep}`)||s===".."||qe.isAbsolute(s)?xt(qe.normalize(r)):xt(qe.relative(t,qe.resolve(n,r)))}async function dI(e,t=process.cwd(),n=process.cwd()){let r=[];for(let s of e){if(qe.resolve(n,s.pattern)===qe.resolve(n))continue;let i=await qy(s.pattern,n),o=[...new Set(i.map(a=>pd(a,t,n)))].sort((a,c)=>a.localeCompare(c));for(let a of o)r.push({path:a,scope:s.scope,note:s.note})}return r}function lI(e,t,n){if(t===void 0)return e;if(!n)throw new p("--note requires --add or --add-glob in the same invocation (the note annotates the links being added)",m.USAGE);let r=t.trim();return r.length===0?e:e.map(s=>s.note===void 0?{...s,note:r}:s)}function _d(e){return`${e.path}::${e.scope}`}function yd(e){return[...e].sort((t,n)=>{let r=t.path.localeCompare(n.path);return r!==0?r:t.scope.localeCompare(n.scope)})}function wd(e){return[...new Map(e.map(t=>[_d(t),t])).values()].map(t=>({...t,note:t.note?.trim()||void 0}))}async function uI(e,t=process.cwd()){let n=[...new Set(e)].sort((a,c)=>a.localeCompare(c)),r=[],s=[],i=[],o=[];for(let a of n){if(ts(a)){o.push(a.trim());continue}let c=qe.isAbsolute(a)?a:qe.resolve(t,a);try{(await YR.stat(c)).isFile()?r.push(a):i.push(a)}catch(d){if(typeof d=="object"&&d!==null&&"code"in d&&Rn(d)){s.push(a);continue}i.push(a)}}return{checked:n.length,existing_files:r,missing_paths:s,non_file_paths:i,remote_references:o}}function mI(e,t,n,r){let s=0;for(let o=0;o<e.length;o+=1){let a=Vn(e[o].path,r);a!==e[o].path&&(s+=1);let c=jt(a);c!==e[o].path&&(e[o]={...e[o],path:c})}return{adds:t.map(o=>{let a=Vn(o.path,r);return a!==o.path&&(s+=1),{...o,path:jt(a)}}),removes:n.map(o=>jt(Vn(o,r))),count:s}}function jt(e){return e.replaceAll("\\","/")}function ld(e){return`${e.scope}\0${jt(e.path)}`}function fI(e,t,n){let r=new Map(e.map(o=>[ld(o),o.note])),s=new Map(t.map(o=>[ld(o),o.note])),i=new Map;for(let o of n){let a=ld(o);i.has(a)||i.set(a,{path:jt(o.path),scope:o.scope,outcome:pI(r.has(a),r.get(a),s.get(a))})}return[...i.values()]}function pI(e,t,n){return e?n===t?"unchanged":t===void 0?"note_added":n?.startsWith(`${t}${ud}`)?"note_appended":"note_replaced":"added"}function _I(e,t,n){let r=e.merged.findIndex(o=>o.path===t.path&&o.scope===t.scope),s=e.merged[r];if(s===void 0){e.merged.push(t),t.note!==void 0&&e.notedHere.add(t);return}let i=XR(s.note,t.note,n);if(i.conflict)e.conflicts.push({path:t.path,scope:t.scope,existing_note:s.note,requested_note:t.note,source:e.notedHere.has(s)?"this_write":"stored"});else if(i.note!==s.note){let o={...s,note:i.note};e.merged[r]=o,e.notedHere.add(o)}}function hI(e,t,n,r,s){let i=wd(e),o={merged:[...i],notedHere:new Set,conflicts:[]};for(let d of t)_I(o,d,s);let{merged:a}=o,c=fI(i,a,t);if(n.length>0)for(let d=a.length-1;d>=0;d-=1)n.includes(a[d].path)&&a.splice(d,1);return{entries:r?a:yd(a),outcomes:c,conflicts:o.conflicts}}async function zy(e){let t=e.mutation?.entries??e.artifacts,n=e.options.validatePaths?e.artifacts:t,{counts:r,receipts:s}=Ji(e.mutation);return{id:e.id,artifacts:t,changed:e.changed,count:t.length,...r,migrations_applied:e.migrationsApplied&&e.migrationsApplied>0?e.migrationsApplied:void 0,validation:e.options.validatePaths||e.changed&&n.length>0?await uI(n.map(i=>i.path),e.workspaceRoot):void 0,...s}}function gI(e,t,n){let r=new Map;for(let i of t){let o=_d(i);r.set(o,(r.get(o)??0)+1)}let s=0;for(let i of e){let o=_d({...i,path:jt(Vn(i.path,n))}),a=r.get(o)??0;a>0?r.set(o,a-1):s+=1}return s}function yI(e,t){let n=/[\n\r]|^\s*[-*+`]/u.test(e)?[]:lm(e),r=n.findIndex(l=>l.key?.toLowerCase()==="note");if(r<0)return;let s=n.slice(0,r).map(l=>l.raw.trim()),i=new Set(n.slice(0,r).map(l=>l.key?.toLowerCase())),o=[n[r].value],a;for(let l of n.slice(r+1)){let u=l.key?.toLowerCase();if((u==="path"||u==="scope")&&!i.has(u)){s.push(l.raw.trim()),i.add(u);continue}a??=l.key===void 0?void 0:{segment:l.text.trim(),key:l.key},o.push(l.text)}if(a===void 0)return;let c=o.join(",").trim(),d=[...s,`note=${JSON.stringify(c)}`].join(",");try{gd([d],t)}catch{return}return{entry:d,note:c,...a}}function wI(e,t){return e.findIndex(n=>{try{return gd([n],t),!1}catch{return!0}})+1}function Yi(e,t,n){return(t??[]).flatMap(r=>[e,n!==void 0&&r.trim()==="-"?`${n}=-`:r])}function By(e){let{options:t}=e,n=e.noteConflict??t.noteConflict;return[...Le(e.global),...e.guards.map(r=>`--expect-hash=${r}`),e.config.metadataKey,e.id,...Yi("--add",e.entries.map((r,s)=>s===e.position-1?e.rewritten:r),"path"),...Yi("--add-glob",e.resolved.addGlob,"pattern"),...Yi("--remove",e.resolved.remove,"path"),...Yi("--migrate",e.resolved.migrate),...t.note===void 0?[]:["--note",t.note],...n===void 0?[]:["--note-conflict",n],...e.config.supportsAppendStable&&t.appendStable===!0?["--append-stable"]:[],...t.validatePaths===!0?["--validate-paths"]:[],...t.fullHistory===!0?["--full-history"]:[],...t.author?["--author",t.author]:[],...t.message?["--message",t.message]:[],...t.force===!0?["--force"]:[]]}function vI(e){return md.some(t=>t===e.toLowerCase())?`If "${e}" was meant as a key, give it once per entry.`:`If "${e}" was meant as a key, it is not one of: ${md.join(", ")}.`}function kI(e){try{return gd(e.entries,e.config.bareNoun)}catch(t){let n=e.entries,r=t,s=wI(n,e.config.bareNoun),i=yI(n[s-1],e.config.bareNoun);if(i===void 0)throw t;let o=Er(e.pmRoot),a=o===void 0?void 0:By({...e,entries:n,position:s,rewritten:i.entry,guards:o});throw new p(`--add read the note segment "${i.segment}" as a new key "${i.key}", so the ${e.config.bareNoun} link was refused (${r.message})`,m.USAGE,{code:"linked_artifact_note_key_misread",flag:"--add",value:n[s-1],required:`Retry with the note quoted so its commas stay prose (${a===void 0?`as ${i.entry}; its revision guards cannot be replayed as typed, so no executable retry is offered`:"recovery.suggested_retry_args replays the whole invocation that way"}), or pass the prose through --note in a single-entry call. ${vI(i.key)}`,why:"After a comma, an identifier followed by = or : opens a new key, so that a typo such as lable=main is refused instead of being stored as note text (GH-258).",...a===void 0?{}:{nextSteps:[L(a)]},details:{entry_index:s,misread_segment:i.segment,misread_key:i.key,note:i.note,rewritten_entry:i.entry,cause:r.context.code??"invalid_argument_value"},...a===void 0?{}:{recovery:{suggested_retry:L(a),suggested_retry_args:a}}})}}function Ji(e){return e===void 0?{counts:{},receipts:{}}:{counts:{total_count:e.total_count,returned_count:e.returned_count,has_more:e.has_more},receipts:{mutation_receipt:e.mutation_receipt,omission_receipt:e.omission_receipt}}}async function bI(e){let{settings:t,config:n}=e,r=await Y(e.pmRoot,e.id,t.id_prefix,t.item_format,e.typeToFolder);if(!r)throw new p(`Item ${e.id} not found`,m.NOT_FOUND);let i=(await fe(r,{schema:t.schema})).document.metadata[n.metadataKey]??[],o=e.writeRequested?ns({collectionKey:n.metadataKey,stored:i,written:[],removedCount:0,fullHistory:e.options.fullHistory===!0}):void 0;return zy({id:r.id,artifacts:i,changed:!1,options:e.options,workspaceRoot:e.workspaceRoot,mutation:o})}async function Xi(e,t,n,r){let{metadataKey:s}=r,i=Tn(),o=I(process.cwd(),n.path),a=lt(o),c=process.cwd();await j(o);let d=await C(o),l=D(d,F()),u=await i.resolveList(t.add,"--add"),f=await i.resolveList(t.addGlob,"--add-glob"),_=await i.resolveList(t.remove,"--remove"),h=await i.resolveList(t.migrate,"--migrate"),g=kI({id:e,pmRoot:o,entries:u,resolved:{addGlob:f,remove:_,migrate:h},options:t,global:n,config:r}).map(oe=>({...oe,path:pd(oe.path,a,c)})),y=iI(f),w=await dI(y,a,c),v=g.length>0||y.length>0,S=lI([...g,...w],t.note,v),b=JR(t.noteConflict,v),k=oI(_).map(oe=>pd(oe,a,c)),A=aI(h);if(cI(S,k,A),!(S.length>0||k.length>0||A.length>0))return bI({id:e,pmRoot:o,settings:d,typeToFolder:l.type_to_folder,options:t,workspaceRoot:a,config:r,writeRequested:y.length>0});let E=G(t.author,d.author_default),$=[],P=0,R=[],T=await he({pmRoot:o,settings:d,id:e,op:r.op,author:E,message:t.message,force:t.force,skipNoop:!0,mutate(oe){let ze=oe.metadata,Fe=ze[s]??[],ye=[...Fe],Se=mI(ye,S,k,A),re=hI(ye,Se.adds,Se.removes,r.supportsAppendStable&&t.appendStable===!0,b);if(re.conflicts.length>0){let st=Er(o);throw QR({itemId:oe.metadata.id,noun:r.bareNoun,conflicts:re.conflicts,retryArgs:ue=>st===void 0?void 0:By({id:oe.metadata.id,entries:u??[],position:0,rewritten:"",resolved:{addGlob:f,remove:_,migrate:h},options:t,global:n,config:r,guards:st,noteConflict:ue}),render:L})}let Je=re.entries;R=re.outcomes,Je.length>0?ze[s]=Je:delete ze[s];let pt=!Ue(Fe,Je);return $=Fe,P=gI(Fe,Je,A),{changedFields:pt?[s]:[],warnings:pt&&Se.count>0?[`path_migrations_applied:${Se.count}`]:[]}}}),q=T.item[s]??[],Pe=T.warnings.find(oe=>oe.startsWith("path_migrations_applied:")),ke=Pe?Number(Pe.slice(24)):0;return zy({id:T.item.id,artifacts:q,changed:T.changedFields.includes(s),migrationsApplied:ke,options:t,workspaceRoot:a,mutation:ns({collectionKey:s,stored:q,written:hd($,q),removedCount:P,fullHistory:t.fullHistory===!0,linkOutcomes:R})})}function Qi(e,t){let n={};for(let[r,s]of Object.entries(e))n[r==="artifacts"?t:r]=s;return n}async function Hy(e,t,n){let r=await Xi(e,t,n,{metadataKey:"docs",op:"docs_add",bareNoun:"doc",supportsAppendStable:!1});return Qi(r,"docs")}var Zi=1e6;function vd(e,t=Zi,n=.8,r=!1){let s=new Set,i=(l,u)=>{if(s.add(`${l}:${u}`),s.size>t)throw new p(`Duplicate sweep exceeded ${t} candidate pairs; narrow it with statuses or since.`,m.CONFLICT,{code:"duplicate_sweep_cost_limit",required:"Narrow the duplicate query or increase its similarity threshold. No partial result was returned."})};if(r||n===0){for(let l=0;l<e.length;l+=1)for(let u=0;u<l;u+=1)i(u,l);return s}let o=new Map;for(let{prepared:l}of e)for(let u of l.tokens)o.set(u,(o.get(u)??0)+1);let a=new Map,c=new Map,d=new Map;for(let[l,{prepared:u}]of e.entries()){let f=[...u.tokens].sort((g,y)=>o.get(g)-o.get(y)||g.localeCompare(y)),_=f.length-Math.ceil(n*f.length-1e-12)+1,h=[{index:a,keys:[u.normalized],lengthFilter:!1},{index:c,keys:n<=.99?u.issueCodes:[],lengthFilter:!1},{index:d,keys:f.length===0?[""]:f.slice(0,_),lengthFilter:!0}];for(let g of h)xI(e,l,g,n,i)}return s}function xI(e,t,n,r,s){let i=e[t].prepared.tokens.length;for(let o of n.keys){let a=n.index.get(o)??[];for(let c of a){let d=e[c].prepared.tokens.length;n.lengthFilter&&Math.min(d,i)/Math.max(d,i)+1e-12<r||s(c,t)}a.push(t),n.index.set(o,a)}}var SI=3,Vy=20,EI=.8,AI=100,Yy=1e3;function Jy(e){return e===void 0?[]:[`likely_duplicates:${e.result.items.map(t=>t.id).join(",")}`,`likely_duplicate_recovery:${e.recovery.action}:${e.recovery.item_id}`]}async function CI(e,t){let n=e.items[0],r=I(t.cwd??process.cwd(),t.pmRoot),s=z((await C(r)).schema);return _e(n.status,s)?{action:"reopen",item_id:n.id,command:`pm item reopen ${n.id} "<recurrence reason>"`,args:["item","reopen",n.id,"<recurrence reason>"]}:{action:"reuse",item_id:n.id,command:`pm get ${n.id} --full`,args:["get",n.id,"--full"]}}function kd(e){let t=e.limit??SI,n=e.threshold??EI;if(!Number.isSafeInteger(t)||t<0||t>Vy)throw new p(`Similarity limit must be an integer from 0 to ${Vy}.`,m.USAGE);if(!Number.isFinite(n)||n<0||n>1)throw new p("Similarity threshold must be a number from 0 to 1.",m.USAGE);return{limit:t,threshold:n}}function Xy(e){let t=e.limit??AI;if(!Number.isSafeInteger(t)||t<0||t>Yy)throw new p(`Duplicate cluster limit must be an integer from 0 to ${Yy}.`,m.USAGE);let n=e.since===void 0?void 0:new Date(e.since);if(n&&Number.isNaN(n.getTime()))throw new p("Duplicate cluster --since must be a valid ISO timestamp.",m.USAGE);return{limit:t,since:n}}async function TI(e,t){let n=I(e.cwd??process.cwd(),e.pmRoot),r=await C(n),s=D(r),i=e.statuses?.map(u=>u.trim().toLowerCase()).filter(Boolean);if(e.statuses!==void 0&&i?.length===0)throw new p("Duplicate cluster statuses must include at least one lifecycle status or all.",m.USAGE);let o=z(r.schema),a=i?.map(u=>{if(u==="all")return u;let f=ce(u,o);if(!f)throw new p(`Unknown duplicate-cluster status "${u}". Allowed: all, ${o.definitions.map(_=>_.id).join(", ")}.`,m.USAGE);return f}),c=a?.includes("all")===!0;if(c&&a?.some(u=>u!=="all"))throw new p('The "all" status cannot be combined with other statuses.',m.USAGE);let d=c?void 0:a,l=d?new Set(d):void 0;return{items:(await Ae(n,r.item_format,s.type_to_folder,void 0,r.schema)).filter(u=>(!l||l.has(u.status))&&(!t||new Date(u.created_at).getTime()>=t.getTime())),statuses:d}}var kz={buildDuplicateClusters:Zy,collectDuplicateCandidatePairs:vd,createDuplicateUnionFind:Qy};function Qy(e){let t=Array.from({length:e},(r,s)=>s);return{parent:t,findRoot:r=>{let s=r;for(;t[s]!==s;)s=t[s];for(;t[r]!==r;){let i=t[r];t[r]=s,r=i}return s}}}function RI(e,t,n,r){let s=[];for(let i of t){let[o,a]=i.split(":").map(u=>Number.parseInt(u,10)),c=lc(e[o].prepared,e[a].prepared);if(c.score<n)continue;let d=r.findRoot(o),l=r.findRoot(a);d!==l&&(r.parent[l]=d),s.push({left_id:e[o].item.id,right_id:e[a].item.id,...c})}return s}function Zy(e,t,n,r){let s=new Map;for(let a of e.keys()){let c=n.findRoot(a),d=s.get(c)??[];d.push(a),s.set(c,d)}let i=new Map(e.map(({item:a},c)=>[a.id,n.findRoot(c)])),o=new Map;for(let a of t){let c=i.get(a.left_id),d=o.get(c)??[];d.push(a),o.set(c,d)}return[...s.values()].filter(a=>a.length>1).map(a=>{let c=(o.get(n.findRoot(a[0]))??[]).sort((d,l)=>l.score-d.score||d.left_id.localeCompare(l.left_id)||d.right_id.localeCompare(l.right_id));return{id:e[a[0]].item.id,items:a.map(d=>{let l=e[d].item;return{id:l.id,title:l.title,status:l.status,type:l.type}}),matches:c,max_score:c[0]?.score??0}}).sort((a,c)=>c.max_score-a.max_score||a.id.localeCompare(c.id)).slice(0,r)}function II(e,t,n,r,s){return t.filter(i=>!n.has(i.id)).map(i=>({id:i.id,title:i.title,status:i.status,type:i.type,...dc(e,i.title)})).filter(i=>i.score>=r).sort((i,o)=>o.score-i.score||i.id.localeCompare(o.id)).slice(0,s)}async function OI(e,t={}){let n=e.title.trim();if(n.length===0)throw new p("Similarity candidate title must not be empty.",m.USAGE);let{limit:r,threshold:s}=kd(t),i=I(t.cwd??process.cwd(),t.pmRoot),o=await C(i),a=D(o),c=await wi(i,Object.values(a.type_to_folder)),d=ac(n),l=c&&d.length>0?await Hf({pmRoot:i,expectedSourceCursor:c.source_cursor,query:d.map(_=>`"${_.replaceAll('"','""')}"`).join(" OR "),limit:Math.max(r*10,50)}):null,u=l===null?await Ae(i,o.item_format,a.type_to_folder,void 0,o.schema):l.items,f=II(n,u,new Set(e.excludeIds??[]),s,r);return{items:f,count:f.length,threshold:s,source:l?"persistent_index":"metadata_fallback"}}function LI(e,t={}){let{threshold:n}=kd({...t,limit:void 0}),{limit:r}=Xy(t),s=new Set;for(let l of e){if(!l.id.trim()||s.has(l.id))throw new p("Duplicate analysis requires unique non-empty item ids.",m.USAGE);s.add(l.id)}let i=[...e].sort((l,u)=>l.id.localeCompare(u.id)).map(l=>({item:l,prepared:cc(l.title)})),o=vd(i,Zi,n,t.exhaustive===!0),a=Qy(i.length),c=RI(i,o,n,a),d=Zy(i,c,a,r);return{clusters:d,count:d.length,threshold:n,cost:{item_count:i.length,algorithm:t.exhaustive===!0||n===0?"exhaustive":"prefix_exact",possible_pairs:i.length*(i.length-1)/2,pair_limit:Zi,recall_guarantee:"exact",candidate_pairs:o.size,scored_pairs:o.size}}}async function ew(e={}){kd({...e,limit:void 0});let{since:t}=Xy(e),{items:n,statuses:r}=await TI(e,t);return{...LI(n,e),source:"metadata_scan",filters:{statuses:r??null,since:e.since??null}}}async function bd(e,t){if(t.mode==="off")return;let n=await OI(e,t);if(n.count===0)return;let r=await CI(n,t),s=t.mode==="strict"&&t.allowDuplicate===!0;if(t.mode==="strict"&&!s){let i=n.items.map(a=>`${a.id} (${a.status}): ${a.title}`).join("; "),o=r.action==="reopen"?"Reopen the canonical item":"Reuse the canonical item";throw new p(`Likely duplicate item(s) found: ${i}. ${o} or pass --allow-duplicate with explicit intent.`,m.CONFLICT,{code:"likely_duplicate",required:`${o}, or explicitly acknowledge the duplicate with --allow-duplicate.`,recovery:{suggested_flags:["--allow-duplicate"],suggested_retry:r.command,suggested_retry_args:r.args}})}return{mode:t.mode,bypassed:s,result:n,recovery:r}}async function Az(e,t={}){let n=await ew({pmRoot:I(process.cwd(),e.path),exhaustive:t.exhaustive,...t.status===void 0?{}:{statuses:t.status.flatMap(r=>r.split(",").map(s=>s.trim()).filter(Boolean))},...t.since===void 0?{}:{since:t.since},...t.threshold===void 0?{}:{threshold:t.threshold},...t.limit===void 0?{}:{limit:t.limit}});return{...n,clusters:n.clusters.map(r=>{let s=r.id;return{...r,canonical_id:s,close_command:`pm close <duplicate-id> --duplicate-of ${s}`}}),guidance:{strategy:"review_then_close_duplicate",command:"pm close <duplicate-id> --duplicate-of <canonical-id>"}}}import{execFile as $I}from"node:child_process";import tw from"node:path";function nw(e,t){return new Promise((n,r)=>{$I("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:4*1024*1024},(s,i)=>{s?r(s):n(i)})})}function rw(e){if(e&&(!Number.isSafeInteger(e.start)||!Number.isSafeInteger(e.end)||e.start<1||e.end<e.start))throw new RangeError("Source line range must be inclusive positive integers with end >= start.")}function Oz(e){let t=/^(\d+):(\d+)$/u.exec(e.trim()),n=t?{start:Number(t[1]),end:Number(t[2])}:void 0;if(rw(n),!n)throw new RangeError("Source line range must use start:end.");return n}function NI(e){let t=new Map;for(let n of e.split(`
|
|
7
|
+
`)){let r=/^([0-9a-f^]{40,64}) \d+ \d+(?: \d+)?$/u.exec(n)?.[1];r&&t.set(r,(t.get(r)??0)+1)}return t}function MI(e){let t=e.split("\0"),n=new Map;for(let r=0;r+1<t.length;r+=2){let s=t[r]?.trim();if(!s)continue;let i=[...new Set(t[r+1]?.match(/\bpm-[a-z0-9][a-z0-9-]{2,63}\b/gu)??[])].sort((o,a)=>o.localeCompare(a));n.set(s,i)}return n}async function PI(e){let t=tw.relative(e.workspaceRoot,tw.resolve(e.workspaceRoot,e.sourcePath)),n=await nw(e.workspaceRoot,["blame","--line-porcelain","-L",`${e.lineRange.start},${e.lineRange.end}`,"--",t]),r=await nw(e.workspaceRoot,["log","-n","256","--format=%H%x00%B%x00","--",t]);return{commitLines:NI(n),commitItems:MI(r),available:!0}}function FI(e){let t=e.current.nodes.at(-1),n=e.current.kinds.length+1,r;for(let s of e.graph.incidentEdges(t)){let i=s.source===t,o=i?s.target:s.source;if((e.visitedDepth.get(o)??Number.POSITIVE_INFINITY)<n)continue;e.visitedDepth.set(o,n);let a=e.graph.registry().require(s.kind),c={nodes:[...e.current.nodes,o],kinds:[...e.current.kinds,i?s.kind:a.inverse??s.kind]};e.details.get(o)?.type?.toLowerCase()==="decision"?(r=n,e.found.push(c)):e.queue.push(c)}return r}function DI(e){let t=[{nodes:[e.itemId],kinds:[]}],n=new Map([[e.itemId,0]]),r=[],s;for(;t.length>0;){let i=t.shift(),o=i.kinds.length;s!==void 0&&o>=s||o>=e.maxDepth||(s=FI({current:i,graph:e.graph,details:e.details,visitedDepth:n,queue:t,found:r})??s)}return r.sort((i,o)=>i.nodes.join("\0").localeCompare(o.nodes.join("\0"))),r}function jI(e,t,n){let r=Sh(t);if(!r.graph.hasNode(e))return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let s=DI({itemId:e,maxDepth:n,graph:r.graph,details:new Map(r.details.map(a=>[a.id,a]))}),i=s[0];if(!i)return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let o=[...new Set(s.map(a=>a.nodes.at(-1)))];return{status:o.length===1?"found":"ambiguous",nodes:i.nodes,kinds:i.kinds,alternative_decision_ids:o.slice(1)}}async function UI(e){if(!e.lineRange)return{commitLines:new Map,commitItems:new Map,available:!0};try{return await PI({workspaceRoot:e.workspaceRoot,sourcePath:e.paths[0],lineRange:e.lineRange})}catch{return{commitLines:new Map,commitItems:new Map,available:!1}}}function GI(e){let t=[];return e.hasLineRange&&!e.attributionAvailable&&t.push("git_attribution_unavailable"),e.hasLineRange&&e.contributionLines===0&&t.push("line_attribution_unmapped"),e.decisionStatus==="ambiguous"&&t.push("multiple_governing_decisions"),e.decisionStatus==="not_found"&&t.push("governing_decision_not_found"),t}function qI(e){return[...e.commitLines.keys()].filter(t=>(e.commitItems.get(t)?.length??0)>0)}async function sw(e){rw(e.lineRange);let t=e.decisionDepth??8;if(!Number.isSafeInteger(t)||t<1||t>32)throw new RangeError("Decision path depth must be an integer from 1 to 32.");let n=await UI(e),r=qI(n),s=new Map;for(let i of e.candidates){let o=[...n.commitLines.entries()].filter(([l])=>n.commitItems.get(l)?.includes(i.item.id)),a=o.reduce((l,[,u])=>l+u,0),c=jI(i.item.id,e.corpus,t),d=GI({hasLineRange:e.lineRange!==void 0,attributionAvailable:n.available,contributionLines:a,decisionStatus:c.status});s.set(i.item.id,{score:a*100+i.files.length*10+Math.max(0,9-Math.floor((Date.now()-Date.parse(i.item.updated_at))/(720*60*60*1e3))),contribution_lines:a,evidence:[...i.files.map(l=>({kind:"linked_file",reference:l.path})),...o.map(([l,u])=>({kind:"git_commit",reference:l.slice(0,12),contribution_lines:u}))],rationale:{value:i.item.value?.trim()||null,why_now:i.item.why_now?.trim()||null,outcome:i.item.outcome?.trim()||null,objective:i.item.objective?.trim()||null},decision_path:c,ambiguities:d})}return{explanations:s,receipt:{line_range:e.lineRange??null,blamed_commit_count:n.commitLines.size,mapped_commit_count:r.length,unmapped_commit_count:n.commitLines.size-r.length,decision_depth:t}}}import iw from"node:fs/promises";import Ye from"node:path";var WI=32768;function xd(e){return xt(Ye.normalize(e))}async function eo(e){try{return await iw.realpath(e)}catch{return Ye.resolve(e)}}function Yn(e,t){let n=Ye.isAbsolute(e.path)?Ye.resolve(e.path):Ye.resolve(t,e.path);return`${xd(n)}::${e.scope}`}function to(e,t,n){if(typeof e=="string"){let r=e.trim();r.length>0&&n.push({field:t,value:r});return}if(Array.isArray(e)){e.forEach((r,s)=>to(r,`${t}[${s}]`,n));return}if(typeof e=="object"&&e!==null)for(let[r,s]of Object.entries(e))to(s,t?`${t}.${r}`:r,n)}function KI(e){let t=[];return to(e.metadata,"metadata",t),to(e.body,"body",t),t}function zI(e){let t=e.trim();return t=t.replace(/^[`"'<([{]+/u,""),t=t.replace(/[`"'>)\]},;!?]+$/u,""),t=t.replace(/[.]+$/u,""),t=t.replace(/:(?:\d+)(?::\d+)?$/u,""),t=t.replace(/[.]+$/u,""),t}function BI(e){let t=[],n=/(?:[A-Za-z]:[\\/]|\/)[^\s"'`<>()[\]{},;]+/gu,r=/(?:\.{1,2}[\\/])?(?:(?:[A-Za-z0-9_.@-]+[\\/])+[A-Za-z0-9_.@-]+|[A-Za-z0-9_.@-]+\.[A-Za-z0-9][A-Za-z0-9._-]*)/gu;for(let s of e){let i=new Set,o=s.value.slice(0,WI);for(let[a,c]of[[n,s.value],[r,o]]){a.lastIndex=0;for(let d of c.matchAll(a)){let l=zI(d[0]);!l||i.has(l)||(i.add(l),t.push({field:s.field,value:l}))}}}return t}async function HI(e,t,n=t){let r=Ye.isAbsolute(e)?Ye.resolve(e):Ye.resolve(n,e),s;try{s=await iw.stat(r)}catch{return}if(!s.isFile())return;let[i,o]=await Promise.all([eo(t),eo(r)]);if(Ba(i,o)){let a=Ye.relative(i,o);return!a||a.startsWith("..")||Ye.isAbsolute(a)?void 0:{path:xd(a),scope:"project"}}return{path:xd(r),scope:"global"}}async function VI(e,t,n=t){let r=new Set((e.metadata.files??[]).map(c=>Yn(c,t))),s=new Map,i=BI(KI(e)),o=new Map;await Promise.all([...new Set(i.map(c=>c.value))].map(async c=>{o.set(c,await HI(c,t,n))}));let a=i.map(c=>({reference:c,resolved:o.get(c.value)}));for(let{reference:c,resolved:d}of a){if(!d)continue;let l=Yn(d,t),u=s.get(l)??{path:d.path,scope:d.scope,sourceFields:new Set,originalPaths:new Set,sourceCount:0};u.sourceFields.add(c.field),u.originalPaths.add(c.value),u.sourceCount+=1,s.set(l,u)}return[...s.entries()].map(([c,d])=>({path:d.path,scope:d.scope,status:r.has(c)?"already_linked":"addable",source_count:d.sourceCount,source_fields:[...d.sourceFields].sort((l,u)=>l.localeCompare(u)),original_paths:[...d.originalPaths].sort((l,u)=>l.localeCompare(u))})).sort((c,d)=>{let l=c.status.localeCompare(d.status);if(l!==0)return l;let u=c.path.localeCompare(d.path);return u!==0?u:c.scope.localeCompare(d.scope)})}async function ow(e,t,n){let r=await Xi(e,t,n,{metadataKey:"files",op:"files_add",bareNoun:"file",supportsAppendStable:!0});return Qi(r,"files")}async function YI(e,t){let n=await eo(t),r=await Promise.all(e.map(async i=>{let o=i.trim();if(!o)throw new p("Files lookup paths must not be empty.",m.USAGE);if(!Ye.isAbsolute(o))return xt(o);let a=await eo(o);return Ba(n,a)?xt(Ye.relative(n,a)):xt(a)})),s=[...new Set(r)].sort((i,o)=>i.localeCompare(o));if(s.length===0)throw new p("Files lookup requires at least one path.",m.USAGE);return s}function JI(e){for(let[r,s]of[["limit",e.limit],["offset",e.offset]])if(s!==void 0&&(!Number.isInteger(s)||s<0))throw new p(`Files lookup ${r} must be a non-negative integer.`,m.USAGE);let{offset:t=0,limit:n=50}=e;return{offset:Math.max(0,Math.floor(t)),limit:e.noTruncate?void 0:Math.max(0,Math.floor(n))}}function aw(e){return{id:e.id,title:e.title,type:e.type,status:e.status,priority:e.priority,updated_at:e.updated_at}}function cw(e,t){let n=e.item.priority-t.item.priority;if(n!==0)return n;let r=t.item.updated_at.localeCompare(e.item.updated_at);return r===0?e.item.id.localeCompare(t.item.id):r}function XI(e){return e.metadata.map(t=>({item:t,files:(t.files??[]).filter(n=>e.paths.includes(xt(n.path))&&(e.scope===void 0||n.scope===e.scope)).sort((n,r)=>{let s=n.path.localeCompare(r.path);return s===0?n.scope.localeCompare(r.scope):s})})).filter(t=>t.files.length>0).sort(cw)}async function QI(e){if(e.explain)return sw({workspaceRoot:e.workspaceRoot,paths:e.paths,candidates:e.matching,corpus:e.metadata,...e.lineRange?{lineRange:e.lineRange}:{},...e.decisionDepth===void 0?{}:{decisionDepth:e.decisionDepth}})}async function ZI(e){if([e.strictRead,e.noTruncate,e.explain,If()].includes(!0))return null;let t=await wi(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]);return t?Bf({pmRoot:e.pmRoot,expectedSourceCursor:t.source_cursor,paths:e.paths,scope:e.scope,limit:e.limit,offset:e.offset}):null}async function eO(e){let t=[],n=await vi(e.pmRoot,e.settings.item_format,e.typeToFolder,t,e.settings.schema),r=XI({metadata:n,paths:e.paths,scope:e.scope}),s=t.filter(c=>/^item_list_(?:item|directory)_read_failed:/u.test(c));if(e.strictRead&&s.length>0)throw new p(`Files lookup could not read every item: ${s.join("; ")}`,m.GENERIC_FAILURE);let i=await QI({explain:e.explain,workspaceRoot:e.workspaceRoot,paths:e.paths,matching:r,metadata:n,lineRange:e.lineRange,decisionDepth:e.decisionDepth}),a=(i?[...r].sort((c,d)=>{let l=i.explanations.get(d.item.id).score-i.explanations.get(c.item.id).score;return l!==0?l:cw(c,d)}):r).slice(e.offset,e.limit===void 0?void 0:e.offset+e.limit);return{paths:e.paths,total:r.length,count:a.length,offset:e.offset,limit:e.limit??null,has_more:e.offset+a.length<r.length,truncated:e.offset+a.length<r.length,completeness:{status:s.length===0?"complete":"partial",source:"source_scan"},warnings:t,matches:a.map(c=>({item:aw(c.item),files:c.files,...i?{traceability:i.explanations.get(c.item.id)}:{}})),...i?{traceability_receipt:i.receipt}:{}}}async function Yz(e,t){let n=I(process.cwd(),t.path),r=lt(n);await j(n);let s=await YI(e.paths,r);if(e.lineRange&&s.length!==1)throw new p("Files lookup line attribution requires exactly one source path.",m.USAGE);let i=await C(n),o=D(i,F()),{offset:a,limit:c}=JI(e),d=await ZI({pmRoot:n,typeToFolder:o.type_to_folder,paths:s,scope:e.scope,limit:c,offset:a,strictRead:e.strictRead===!0,noTruncate:e.noTruncate===!0,explain:e.explain===!0||e.lineRange!==void 0});return d?{paths:s,total:d.total,count:d.matches.length,offset:a,limit:c,has_more:a+d.matches.length<d.total,truncated:a+d.matches.length<d.total,completeness:{status:"unchecked",source:"index"},warnings:[],matches:d.matches.map(l=>({item:aw(l.item),files:l.files}))}:eO({pmRoot:n,settings:i,typeToFolder:o.type_to_folder,paths:s,scope:e.scope,limit:c,offset:a,strictRead:e.strictRead===!0,workspaceRoot:r,explain:e.explain===!0||e.lineRange!==void 0,lineRange:e.lineRange,decisionDepth:e.decisionDepth})}async function Jz(e,t,n){let r=I(process.cwd(),n.path),s=lt(r);await j(r);let i=await C(r),o=D(i,F()),a=await Y(r,e,i.id_prefix,i.item_format,o.type_to_folder);if(!a)throw new p(`Item ${e} not found`,m.NOT_FOUND);let c=await fe(a,{schema:i.schema}),d=await VI(c.document,s,process.cwd()),l=d.filter(E=>E.status==="addable"),u=d.filter(E=>E.status==="already_linked"),f=t.apply===!0,_=t.note?.trim()||"discovered from item text";if(!f||l.length===0){let E=c.document.metadata.files??[];return{id:a.id,files:E,changed:!1,apply:f,count:E.length,candidate_count:d.length,addable_count:l.length,added_count:0,skipped_existing_count:u.length,candidates:d,added:[],skipped_existing:u}}let h=G(t.author,i.author_default),g=l.map(E=>({path:E.path,scope:E.scope,note:_})),y=[],w=new Set,v=await he({pmRoot:r,settings:i,id:e,op:"files_discover",author:h,message:t.message??"Discover referenced file links",force:t.force,mutate(E){let $=[...E.metadata.files??[]],P=new Set($.map(q=>Yn(q,s)));y=[],w.clear();for(let[q,Pe]of g.entries()){let ke=Yn(Pe,s);P.has(ke)||($.push(Pe),P.add(ke),y.push(Pe),w.add(q))}let R=wd($),T=t.appendStable?R:yd(R);return T.length>0?E.metadata.files=T:delete E.metadata.files,{changedFields:y.length>0?["files"]:[],warnings:y.length!==g.length?[`files_discover_skipped_existing:${g.length-y.length}`]:[]}}}),S=v.item.files??[],b=new Set(y.map(E=>Yn(E,s))),k=S.filter(E=>b.has(Yn(E,s))),A=l.filter((E,$)=>!w.has($)),x=[...u,...A];return{id:v.item.id,files:S,changed:k.length>0,apply:!0,count:S.length,candidate_count:d.length,addable_count:l.length,added_count:k.length,skipped_existing_count:x.length,candidates:d,added:k,skipped_existing:x}}var rs=["software-delivery","research","agent-evaluation","operations"];function dw(e,t,n,r,s){return{id:e,measurement_id:t,owner_item_id:n,scope:{kind:"active"},ceiling:r,lifetime:"hold",enforcement:s,negative_control:{cases:[{observed:r,expected:"pass"},{observed:r+1,expected:"fail"}]}}}function no(e,t,n,r,s){let i=`preset-${e}`,o=s.map(c=>({id:`${i}-missing-${c}`,description:`Active items missing ${c} evidence.`,source:{kind:"links",link:c,state:"missing"}})),a=o.map(c=>dw(`${c.id}-zero`,c.id,r,0,"warn"));return{id:e,title:t,description:n,declarations:{measurements:o,assertions:a,gates:[{id:`${i}-readiness`,description:n,assertion_ids:a.map(c=>c.id),triggers:["ci","scheduled"]}]}}}function ro(e,t){return e==="software-delivery"?no(e,"Software delivery","Warn when active delivery work lacks executable tests or documentation.",t,["tests","docs"]):e==="research"?no(e,"Research","Warn when active research work lacks reproducibility files or documentation.",t,["files","docs"]):e==="agent-evaluation"?no(e,"Agent evaluation","Warn when active evaluation work lacks executable scenarios or recorded artifacts.",t,["tests","files"]):no(e,"Operations","Warn when active operational work lacks runbook documentation or repair evidence.",t,["docs","files"])}function lw(e,t,n,r={}){return ed(e,ro(t,n).declarations,r)}async function uw(e,t){let n=new Set(e.terminal_statuses??["closed","canceled"]),r={...e,items:e.items.filter(i=>!n.has(i.status))};return await Promise.all(["files","tests","docs"].map(async i=>{let o={id:`derived-active-missing-${i}`,description:`Observed active items missing ${i} evidence.`,source:{kind:"links",link:i,state:"missing"}},c=(await Zc(o,r)).value,d=dw(`${o.id}-ceiling`,o.id,t,c,"observe"),l=`active-missing-${i}`;return{id:l,population_size:r.items.length,scope:{kind:"active"},observed:c,declarations:{measurements:[o],assertions:[d],gates:[{id:`derived-${l}`,description:`Observe the accepted ${i} evidence baseline.`,assertion_ids:[d.id],triggers:["ci","scheduled"]}]}}}))}function mw(e,t,n={}){return ed(e,{measurements:t.flatMap(r=>r.declarations.measurements),assertions:t.flatMap(r=>r.declarations.assertions),gates:t.flatMap(r=>r.declarations.gates)},n)}async function fw(e,t,n,r={}){let s=t.enforcement==="observe"?"warn":"block";if(t.enforcement==="block"||n!==s)throw new TypeError(`assurance assertion ${t.id} promotion must be ${t.enforcement} -> ${s}`);return Ki(e,"assertion",{...t,enforcement:n},{...r,message:r.message??`Promote assurance assertion ${t.id} from ${t.enforcement} to ${n}`})}import hw from"node:fs/promises";import{createRequire as tO}from"node:module";import We from"node:path";function pw(e,t){let n=We.relative(t,e);if(n.length>0&&n!==".."&&!n.startsWith(`..${We.sep}`)&&!We.isAbsolute(n))return n.split(We.sep).join("/");let r=We.resolve(e),s=0xcbf29ce484222325n;for(let o=0;o<r.length;o+=1)s^=BigInt(r.charCodeAt(o)),s=BigInt.asUintN(64,s*0x100000001b3n);return`<external>/${s.toString(16).padStart(16,"0")}/${We.basename(We.dirname(e))}/package.json`}function nO(e){return e.includes(`${We.sep}.pnpm${We.sep}`)?"pnpm":e.includes(`${We.sep}node_modules${We.sep}`)?"npm":"other"}async function _w(e){try{let t=JSON.parse(await hw.readFile(e,"utf8"));return t.name==="@unbrained/pm-cli"&&typeof t.version=="string"&&t.version.trim().length>0?t.version.trim():void 0}catch{return}}async function Sd(e){try{return await hw.realpath(e)}catch{return We.resolve(e)}}async function gw(e,t,n=Ef(import.meta.url,["../../.."])){let r=await Sd(t),s=await Sd(We.join(n,"package.json")),i=await _w(s),o=new Map;i!==void 0&&o.set(s,{version:i,path:pw(s,r),layout:"host",consumers:["pm-cli-host"]});for(let d of e)try{let l=tO(d.entry_path).resolve("@unbrained/pm-cli/package.json"),u=await Sd(l),f=await _w(u);if(f===void 0)continue;let _=u,h=o.get(_);if(h){h.consumers.includes(d.name)||(h.consumers.push(d.name),h.consumers.sort((g,y)=>g.localeCompare(y)));continue}o.set(_,{version:f,path:pw(u,r),layout:nO(u),consumers:[d.name]})}catch{}let a=[...o.values()].sort((d,l)=>d.path.localeCompare(l.path)),c=i===void 0?[]:a.filter(d=>d.version!==i);return{host_version:i??null,copies:a,mismatches:c,warnings:c.map(d=>`extension_host_pm_cli_version_skew:${i}:${d.version}:${d.consumers.join("+")}`)}}var yw=25;function rO(e,t,n=[]){let r=["list","--status",e,...n],s=["--assignee-filter","unassigned"],i=["--updated-before",`-${t}h`];return{unowned:L([...r,...s]),idle:L([...r,...i]),stale:L([...r,...s,...i])}}function ww(e,t){let n=e.items.length>yw;return{count:e.count,items:e.items.slice(0,yw),...n?{truncated:!0}:{},sweep:t}}function vw(e,t,n=[]){let r=rO(t.in_progress,e.threshold_hours,n),s=(o,...a)=>`pm ${o} <id>${[...a,...n].map(c=>` ${Rm(c)}`).join("")}`,i=[...e.unowned.count>0?[`in_progress_unowned:${e.unowned.count}`]:[],...e.idle.count>0?[`in_progress_idle:${e.idle.count}`]:[]];return{warnings:i,details:i.length===0?void 0:{threshold_hours:e.threshold_hours,threshold_setting:"mutation_guard.stale_in_progress_hours",unowned:ww(e.unowned,r.unowned),idle:ww(e.idle,r.idle),item_remedies:{claim:s("claim"),take_over_idle:s("claim","--takeover-stale"),return_to_open:s("update","--status",t.open)}},remediation:{stale_in_progress_items:r.stale,in_progress_unowned:r.unowned,in_progress_idle:r.idle}}}import{createHash as sO}from"node:crypto";import so from"node:path";var iO="2026-08-09T16:15:18.000Z",bw=Symbol("pre-durable-disposition-eligible");function St(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ed(e){if(!Array.isArray(e)||e.length>256)return!1;let t=new Set;for(let n=0;n<e.length;n+=1){let r=e[n];if(!(n in e)||typeof r!="string"||r.length===0||r.length>256||r.includes("\0")||t.has(r))return!1;t.add(r)}return!0}function kw(e){return St(e)?typeof e.field=="string"&&e.field.length>0&&e.field.length<=256&&!e.field.includes("\0")&&typeof e.retained_hash=="string"&&/^[a-f0-9]{64}$/u.test(e.retained_hash)&&typeof e.discarded_hash=="string"&&/^[a-f0-9]{64}$/u.test(e.discarded_hash):!1}function xw(e,t){if(typeof e!="string")return!1;let n=so.posix.normalize(e);return e.length<=4096&&!e.includes("\\")&&!e.includes("\0")&&!so.posix.isAbsolute(e)&&n===e&&!n.startsWith("../")&&(so.posix.basename(n)===`${t}.toon`||so.posix.basename(n)===`${t}.md`)}function oO(e,t){return typeof e.receipt_id=="string"&&Gr(e.receipt_id)&&(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0&&e.conflict_resolution===void 0&&e.item_id===t&&xw(e.item_path,t)}function Sw(e){let t=e.conflict_fields,n=e.fields_from_theirs,r=e.union_fields,s=e.decisions,i=Array.isArray(s)?new Set(s.flatMap(o=>kw(o)?[o.field]:[])):new Set;return Ed(t)&&Ed(n)&&Ed(r)&&Array.isArray(s)&&s.length>0&&s.length<=256&&Object.keys(s).length===s.length&&s.every(kw)&&i.size===s.length&&t.length===i.size&&t.every(o=>i.has(o))}function aO(e,t){return oO(e,t)&&Sw(e)}function cO(e,t){return typeof e.receipt_id=="string"&&Gr(e.receipt_id)&&(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0&&(e.conflict_resolution==="preferred_side"||e.conflict_resolution==="stable_value_order")&&e.item_id===t&&xw(e.item_path,t)&&Sw(e)}function dO(e){return e[bw]===!0}function Ew(e,t){if(!St(e)||!St(e.context))return[];let n=e.context.merge;return!St(n)||!Array.isArray(n.receipts)?[]:n.receipts.flatMap(r=>!St(r)||typeof r.receipt_id!="string"||r.receipt_id.trim().length===0?[]:[{receiptId:r.receipt_id,legacySummaryAccepted:aO(r,t),[bw]:cO(r,t),...typeof e.ts=="string"&&Ja(e.ts)?{eventTimestamp:e.ts}:{}}])}function Aw(e,t,n){if(!St(e)||e.op!=="merge_reconcile")return[];if(!St(e.context)||!St(e.context.merge))return[];let r=e.context.merge.missing_receipt_dispositions;return!Array.isArray(r)||r.length>256?[]:r.flatMap(s=>!St(s)||typeof s.receipt_id!="string"||!Gr(s.receipt_id)||typeof s.original_history_line!="number"||!Number.isSafeInteger(s.original_history_line)||s.original_history_line<1||typeof s.original_event_ts!="string"||!Ja(s.original_event_ts)||s.reason!=="legacy_clone_local_only"?[]:[{itemId:t,receiptId:s.receipt_id,originalHistoryLine:s.original_history_line,originalEventTimestamp:s.original_event_ts,auditHistoryLine:n,reason:s.reason}])}function Cw(e,t,n=[]){let r=new Map;for(let o of n){let a=`${o.itemId}\0${o.originalHistoryLine}\0${o.receiptId}\0${o.originalEventTimestamp}`;r.set(a,Math.max(r.get(a)??0,o.auditHistoryLine))}let s=o=>dO(o)&&o.eventTimestamp!==void 0&&Js(o.eventTimestamp,iO)<0&&(r.get(`${o.itemId}\0${o.line}\0${o.receiptId}\0${o.eventTimestamp}`)??0)>o.line;return{missing:e.filter(o=>!o.legacySummaryAccepted&&!t.has(o.receiptId)&&!s(o)).map(o=>({item_id:o.itemId,history_line:o.line,...Gr(o.receiptId)?{receipt_id:o.receiptId}:{receipt_reference_hash:sO("sha256").update(o.receiptId).digest("hex")}})),acceptedLegacyCount:e.filter(o=>o.legacySummaryAccepted).length,acceptedDispositionCount:e.filter(s).length}}function io(e,t,n=25){let r=e.definitions.filter(o=>o.roles.length===0).map(o=>o.id).sort((o,a)=>o.localeCompare(a)),s=new Set(r),i=t.filter(o=>{let a=Qe(o.status,e);return a!==void 0&&s.has(a)}).map(o=>o.id).sort((o,a)=>o.localeCompare(a));return{roleless_status_count:r.length,roleless_statuses:r.slice(0,n),roleless_statuses_truncated:r.length>n,affected_item_count:i.length,affected_item_ids:i.slice(0,n),affected_item_ids_truncated:i.length>n}}function oo(e){return e.roleless_status_count===0?[]:[`schema_status_missing_lifecycle_role:${e.roleless_status_count}`]}function Rw(e,t){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function et(e,t){return Array.isArray(e)?{count:e.length,sample:e.slice(0,t),truncated:e.length>t}:{count:0,sample:[],truncated:!1}}function lO(e){if(typeof e!="object"||e===null||Array.isArray(e))return{};let t=e;return{layer:t.layer,directory:t.directory,name:t.name,version:t.version,enabled:t.enabled,status:t.status,has_activate:t.has_activate,capabilities:t.capabilities}}function ss(e,t){let n=et(e,t);return{...n,sample:n.sample.map(r=>lO(r))}}function H(e,t){if(!Array.isArray(e))return{count:0,sample:[],truncated:!1};let n=e.filter(r=>typeof r=="string");return{count:n.length,sample:n.slice(0,t),truncated:n.length>t}}function uO(e){if(typeof e!="object"||e===null)return null;let t=e;return{applied_count:t.applied_count,pending_count:t.pending_count,failed_count:t.failed_count}}var mO={settings:(e,t)=>({version:e.version,id_prefix:e.id_prefix,locks_ttl_seconds:e.locks_ttl_seconds,warnings:H(e.warnings,t)}),directories:(e,t)=>({required_count:Array.isArray(e.required)?e.required.length:0,optional_count:Array.isArray(e.optional)?e.optional.length:0,missing_required:H(e.missing_required,t),missing_optional:H(e.missing_optional,t),missing:H(e.missing,t),strict_directories:e.strict_directories}),settings_values:(e,t)=>({warnings:H(e.warnings,t)}),telemetry:e=>({enabled:e.enabled,capture_level:e.capture_level,endpoint:e.endpoint,queue_exists:e.queue_exists,queue_entries:e.queue_entries,queue_draining:e.queue_draining,queue_invalid_rows:e.queue_invalid_rows,queue_rows_total:e.queue_rows_total,last_successful_flush_at:e.last_successful_flush_at,last_failed_flush_at:e.last_failed_flush_at,endpoint_probe:e.endpoint_probe,env_overrides:e.env_overrides}),extensions:(e,t)=>{let n=typeof e.activation=="object"&&e.activation!==null?e.activation:{};return{disabled_by_flag:e.disabled_by_flag,discovered:ss(e.discovered,t),effective:ss(e.effective,t),loaded:ss(e.loaded,t),failed:et(e.failed,t),warnings:H(e.warnings,t),activation:{failed:et(n.failed,t),warnings:H(n.warnings,t),hook_counts:n.hook_counts,command_handler_count:n.command_handler_count,service_override_count:n.service_override_count,renderer_override_count:n.renderer_override_count,registration_counts:n.registration_counts,migration_status:uO(n.migration_status)},author_manifest:e.author_manifest,triage:e.triage,capability_contract:e.capability_contract,capability_guidance:et(e.capability_guidance,t),host_version_census:e.host_version_census}},storage:(e,t)=>{let n=typeof e.author_attribution=="object"&&e.author_attribution!==null?e.author_attribution:void 0;return{...e,...n?{author_attribution:{...n,affected_item_ids:H(n.affected_item_ids,t),samples:et(n.samples,t)}}:{}}},locks:e=>({active_lock_count:e.active_lock_count,stale_lock_count:e.stale_lock_count,unreadable_lock_count:e.unreadable_lock_count,unparseable_lock_count:e.unparseable_lock_count}),integrity:(e,t)=>{let n=typeof e.tracked_runtime_cache=="object"&&e.tracked_runtime_cache!==null?e.tracked_runtime_cache:void 0;return{checked_item_files:e.checked_item_files,checked_history_streams:e.checked_history_streams,counts:e.counts,item_unreadable:H(e.item_unreadable,t),item_conflict_markers:et(e.item_conflict_markers,t),item_parse_failures:H(e.item_parse_failures,t),tracked_runtime_cache:n===void 0?e.tracked_runtime_cache:{...n,tracked_paths:H(n.tracked_paths,t)},history_unreadable:H(e.history_unreadable,t),history_conflict_markers:et(e.history_conflict_markers,t),history_invalid_json:et(e.history_invalid_json,t),skipped:e.skipped}},history_drift:(e,t)=>{let n=typeof e.cache_confirmation=="object"&&e.cache_confirmation!==null?e.cache_confirmation:void 0;return{checked_items:e.checked_items,cache_hit_verification:e.cache_hit_verification,cache_confirmation:n===void 0?e.cache_confirmation:{...n,candidate_items:H(n.candidate_items,t),confirmed_items:H(n.confirmed_items,t),resolved_false_positive_items:H(n.resolved_false_positive_items,t)},counts:e.counts,drifted_items:H(e.drifted_items,t),merge_receipt_attributed_items:H(e.merge_receipt_attributed_items,t),missing_streams:H(e.missing_streams,t),unreadable_streams:H(e.unreadable_streams,t),hash_mismatches:H(e.hash_mismatches,t),chain_mismatches:H(e.chain_mismatches,t),version_skews:H(e.version_skews,t),workspace_state_mismatches:H(e.workspace_state_mismatches,t),workspace_state_missing:H(e.workspace_state_missing,t),workspace_state_unreadable:H(e.workspace_state_unreadable,t),skipped:e.skipped}},vectorization:(e,t)=>({semantic_runtime_available:e.semantic_runtime_available,compatibility_mode_auto_defaults:e.compatibility_mode_auto_defaults,auto_ollama_defaults_applied:e.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:e.auto_ollama_defaults_skipped_reason,auto_ollama_defaults_remediation:e.auto_ollama_defaults_remediation,refresh_policy:e.refresh_policy,provider_active:e.provider_active,vector_store_active:e.vector_store_active,items:e.items,ledger_entries_before:e.ledger_entries_before,stale_items_before_total:e.stale_items_before_total,stale_items_before:H(e.stale_items_before,t),refresh_attempted:e.refresh_attempted,refresh_skipped_reason:e.refresh_skipped_reason,refresh_result:e.refresh_result,ledger_entries_after:e.ledger_entries_after,stale_items_after_total:e.stale_items_after_total,stale_items_after:H(e.stale_items_after,t),skipped:e.skipped})};function Ad(e,t){let n=mO[e.name];return n?n(e.details,t):e.details}function Iw(e){return{disabled_by_flag:e.details.disabled_by_flag,loaded_count:Array.isArray(e.details.loaded)?e.details.loaded.length:0,failed_count:0,warning_count:0,restore_with:"pm health --full"}}function fO(e){if(e.name==="extensions"&&e.status==="ok")return Iw(e);let t=Ad(e,8);return Buffer.byteLength(JSON.stringify(t))<Buffer.byteLength(JSON.stringify(e.details))?t:e.details}function Cd(e,t){let n=new Set([...t,...e.failed_because]);return(e.findings??[]).filter(r=>n.has(r.warning))}function pO(e){let t=H(e.warnings,8);return{ok:e.ok,...e.verdict?{verdict:e.verdict}:{},checks:e.checks.map(n=>({name:n.name,status:n.status,ok:n.ok,details:fO(n)})),warnings:t.sample,findings:Cd(e,t.sample),failed_because:e.failed_because,projection:{mode:"brief",warning_count:t.count,warnings_truncated:t.truncated,detail_limit:8},generated_at:e.generated_at}}function Tw(e){return e.details.skipped===!0}function _O(e){let t=H(e.warnings,8),n=e.checks.filter(Tw).map(r=>r.name);return{ok:e.ok,...e.verdict?{verdict:e.verdict}:{},checks:e.checks.filter(r=>!Tw(r)).map(r=>({name:r.name,status:r.status,ok:r.ok,details:{}})),warning_count:t.count,warnings:t.sample,findings:Cd(e,t.sample),failed_because:e.failed_because,projection:{mode:"summary",warning_count:t.count,warnings_truncated:t.truncated,detail_limit:8,omitted_checks:n},generated_at:e.generated_at}}function hO(e,t,n){return n?_O(e):t.brief===!0?pO(e):t.full===!0?e:{...e,checks:e.checks.map(r=>r.name==="extensions"&&r.status==="ok"?{...r,details:Iw(r)}:r),projection:{mode:"standard",warning_count:e.warning_count,warnings_truncated:e.warnings_truncated===!0,detail_limit:8}}}function Td(e,t,n){let r=e.warning_count??e.warnings.length,s=e.warnings.slice(0,100),i={...e,warning_count:r,warning_limit:100,warnings_truncated:r>100,warnings:s,findings:Cd(e,s)},o=hO(i,t,n);return{...o,warning_count:r,warning_limit:100,warnings_truncated:r>o.warnings.length,...o.projection?{projection:{...o.projection,warning_count:r,warnings_truncated:r>o.warnings.length}}:{}}}import Et from"node:fs/promises";import ge from"node:path";import Jn from"node:fs/promises";import is from"node:path";function Ow(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t,{id:r,owner:s,created_at:i,ttl_seconds:o}=n;return typeof r!="string"||typeof s!="string"||typeof i!="string"||typeof o!="number"||!Number.isFinite(o)?null:{id:r,owner:s,created_at:i,ttl_seconds:o,pid:n.pid,host_identity:n.host_identity,process_start_identity:n.process_start_identity}}function gO(e,t,n){let r=Ow(t);if(r===null)return{detail:"unparseable_json",entry:{file:e,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"}};let s=Date.parse(r.created_at);if(!Number.isFinite(s))return{detail:"invalid_timestamp",entry:{file:e,id:r.id,owner:r.owner,created_at:r.created_at,ttl_seconds:r.ttl_seconds,age_seconds:null,stale:!1,reason:"unparseable"}};let i=n-s,o=Math.floor(i/1e3),a=i>r.ttl_seconds*1e3;return{detail:a?"expired":"active",entry:{file:e,id:r.id,owner:r.owner,created_at:r.created_at,ttl_seconds:r.ttl_seconds,age_seconds:o,stale:a,reason:a?"expired":"active"}}}async function Lw(e,t,n){let r=gO(e,t,n);if(r.detail!=="active")return r;let s=Ow(t),i=await ef(s);return i==="unknown"?r:{detail:i==="dead"?"owner_dead":"active",entry:{...r.entry,owner_state:i,pid:s.pid,...i==="dead"?{stale:!0,reason:"owner_dead"}:{}}}}async function yO(e,t,n){let r=await nf(e,"gc");if(r===null)return!1;try{let s;try{s=await Jn.readFile(e,"utf8")}catch(i){if(U(i))return!0;throw i}if(s!==t)return!1;n&&await rf(e,t);try{await Jn.unlink(e)}catch(i){if(!U(i))throw i}return!0}finally{await r()}}function wO(e,t,n){t==="owner_dead"&&(e.owner_dead_lock_samples??=[],e.owner_dead_lock_samples.length<20&&e.owner_dead_lock_samples.push(n)),t==="active"?e.active_lock_count+=1:t==="expired"||t==="owner_dead"?e.stale_lock_count+=1:e.unparseable_lock_count+=1}async function $w(e,t){let n=t??Date.now(),r=is.join(e,"locks"),s={scanned:0,active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0},i;try{i=(await Jn.readdir(r)).filter(a=>a.endsWith(".lock")).sort()}catch(o){if(U(o))return s;throw o}for(let o of i){let a;try{a=await Jn.readFile(is.join(r,o),"utf8")}catch(l){if(U(l))continue;s.scanned+=1,s.unreadable_lock_count+=1;continue}s.scanned+=1;let{detail:c,entry:d}=await Lw(o,a,n);wO(s,c,d)}return s}async function vO(e,t,n,r,s,i,o){if(!t.dryRun){try{if(!await yO(n,i,o.reason==="owner_dead")){e.warnings.push(`lock_changed_or_busy:${s}`),e.retained.push(r),e.entries.push(o);return}}catch{e.warnings.push(`lock_remove_failed:${s}`),e.retained.push(r),e.entries.push(o);return}if(t.hooks?.onWrite){let a=await t.hooks.onWrite(n);e.warnings.push(...a)}}e.removed.push(r),e.entries.push(o)}async function Nw(e,t){let{hooks:n}=t,r=t.now??Date.now(),s=is.join(e,"locks"),i={scanned:0,removed:[],retained:[],warnings:[],entries:[]};await Zm(e,is.join(s,"gc.lock"),"gc");let o;try{o=(await Jn.readdir(s)).filter(c=>c.endsWith(".lock")).sort()}catch(a){if(U(a))return i;throw a}for(let a of o){i.scanned+=1;let c=is.join(s,a),d=`locks/${a}`;if(n?.onRead){let f=await n.onRead(c);i.warnings.push(...f)}let l;try{l=await Jn.readFile(c,"utf8")}catch(f){if(U(f)){i.scanned-=1;continue}i.warnings.push(`lock_unreadable:${a}`),i.retained.push(d),i.entries.push({file:a,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let u=await Lw(a,l,r);if(u.detail==="unparseable_json"){i.warnings.push(`lock_unparseable:${a}`),i.retained.push(d),i.entries.push(u.entry);continue}if(u.detail==="invalid_timestamp"){i.warnings.push(`lock_invalid_timestamp:${a}`),i.retained.push(d),i.entries.push(u.entry);continue}if(u.detail==="active"){i.retained.push(d),i.entries.push(u.entry);continue}await vO(i,t,c,d,a,l,u.entry)}return i}var kO=Object.freeze([{code:"missing_directory",command:"pm init",summary:"Recreate missing tracker directories (pm init is idempotent and restores the scaffold)."},{code:"settings_read_fs_error",command:"pm config list --json",summary:"settings.json could not be read as a regular file and pm fell back to defaults; repair the reported path or permissions, then re-run."},{code:"settings_read_invalid_json",command:"pm config list --json",summary:"settings.json is not valid JSON and pm fell back to defaults; fix the syntax error in the reported path, then re-run."},{code:"settings_read_invalid_schema",command:"pm config list --json",summary:"settings.json failed schema validation and pm fell back to defaults; correct the reported key in the file, then re-run."},{code:"settings_read_merge_failed",command:"pm config list --json",summary:"Global/project settings could not be merged; reconcile the conflicting keys in the reported settings files."},{code:"settings:id_prefix_empty",command:"pm config list --json",summary:'id_prefix is empty; set a non-empty "id_prefix" in settings.json so generated item ids are well-formed.'},{code:"settings:locks_ttl_non_positive",command:"pm config list --json",summary:'locks.ttl_seconds must be positive; set a positive "locks.ttl_seconds" in settings.json.'},{code:"telemetry_state_invalid_json",command:"pm health --check-telemetry",summary:"Local telemetry state file is corrupt; pm recreates it on the next flush. Advisory only."},{code:"telemetry_queue_invalid_rows",command:"pm health --check-telemetry",summary:"The telemetry queue has unparseable rows; they are skipped on the next flush. Advisory only."},{code:"telemetry_queue_pending",command:"pm health --check-telemetry",summary:"Telemetry events are queued; they flush automatically on the next reachable command. Advisory only."},{code:"telemetry_queue_high_retries",command:"pm telemetry flush",summary:"Some queued telemetry events are near retry exhaustion; flush now and verify endpoint reachability before entries are dropped."},{code:"telemetry_endpoint_probe_failed",command:"pm health --check-telemetry",summary:"The telemetry endpoint is unreachable; events stay queued until it recovers. Advisory only."},{code:"telemetry_endpoint_probe_http_status",command:"pm health --check-telemetry",summary:"The telemetry endpoint returned a non-success status; events stay queued until it recovers. Advisory only."},{code:"telemetry_schema_version_behind",command:"pm health --check-telemetry",summary:"Client schema is behind server; upgrade pm-cli to emit the latest event shape."},{code:"telemetry_otel_export_failing",command:"pm health --check-telemetry",summary:"OTLP trace spans are queued but the traces endpoint export is failing; spans retry automatically on the next reachable command, or set PM_TELEMETRY_OTEL_DISABLED=1 to skip OTLP export. Advisory only."},{code:"merge_driver_configuration_missing",command:"pm merge install",summary:"Install the clone-local Git drivers required by the tracker merge fence."},{code:"merge_driver_configuration_drift",command:"pm merge install",summary:"Reinstall clone-local Git drivers after runtime or package paths change."},{code:"merge_fence_missing",command:"pm merge install",summary:"Install the active tracker's committed Git merge attributes."},{code:"merge_fence_drift",command:"pm merge install",summary:"Restore the active tracker's merge mappings while retaining sibling tracker fences."},{code:"validate_merge_driver_configuration",command:"pm merge install",summary:"Restore missing or drifted clone-local Git merge driver commands."},{code:"integrity_item_unreadable",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file could not be read; restore or repair the file at the reported path."},{code:"integrity_item_parse_failed",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file failed to parse; fix the malformed item metadata at the reported path."},{code:"integrity_item_conflict_marker",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file contains Git conflict markers; resolve the <<<<<<< / >>>>>>> markers at the reported line."},{code:"integrity_history_unreadable",command:"pm history-repair <id>",summary:"A history stream could not be read; re-anchor the affected item's history chain."},{code:"integrity_history_invalid_json",command:"pm history-repair <id>",summary:"A history stream contains invalid JSON; re-anchor the affected item's history chain."},{code:"integrity_history_conflict_marker",command:"pm history-repair <id>",summary:"A history stream contains Git conflict markers; resolve the markers, then re-anchor the chain."},{code:"validate_storage_unreadable_items",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"An on-disk item file cannot be parsed (for example a botched merge resolution with stale TOON count headers); repair or restore the file at the reported path \u2014 list commands silently skip it while pm get hard-errors."},{code:"validate_storage_duplicate_item_ids",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"One item id is claimed by multiple item documents \u2014 usually two branches minting the same id for different items before merging (GH-600). Keep one document, recreate the other item under a fresh id (pm copy, then delete the colliding file), and consider raising ids.token_length for concurrent multi-agent work."},{code:"validate_storage_history_conflict_markers",command:"pm merge driver history <base> <ours> <theirs>",summary:"A history stream contains unresolved Git conflict markers; re-merge it with the pm history merge driver (or resolve the markers by hand), then run pm history-repair for the item."},{code:"validate_storage_unparseable_history",command:"pm history-repair <id>",summary:"A history stream's newest line is not valid JSONL; repair or restore the stream before further mutations."},{code:"validate_storage_resurrected_items",command:"pm delete <id>",summary:"A live item's newest history operation is a delete: a delete/modify merge silently resurrected it. Decide the winner \u2014 re-delete the item, or keep it and append a mutation documenting the revival."},{code:"validate_storage_unparseable_config",command:"pm merge driver json <base> <ours> <theirs>",summary:"settings.json or a schema file cannot be parsed, so pm silently falls back to defaults; re-merge it with the pm JSON merge driver or fix the file by hand, then rerun pm validate."},{code:"validate_merge_fence_drift",command:"pm merge install",summary:"The committed .gitattributes merge fence no longer matches the active schema's type folders or tracker JSONL stores; rerun pm merge install (and commit .gitattributes) so every tracker artifact keeps its field-aware merge driver."},{code:"validate_storage_tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command, commit the index-only removals and managed .gitignore fence, then rerun validation."},{code:"integrity_item_outdated_format_version",command:"pm validate --verbose-diagnostics",summary:"An item predates the current storage format version; a pm storage migration rewrites it. Use --verbose-diagnostics to list the affected items."},{code:"integrity_item_ahead_format_version",command:"npm install -g @unbrained/pm-cli@latest",summary:"An item was written by a newer pm format version than this runtime supports; upgrade pm to read and validate it safely."},{code:"tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command from the integrity check, commit the index-only removals, and keep the managed .gitignore fence."},{code:"merge_artifacts_ignored",command:"pm health --check-only --full",summary:"Remove or narrow the owning ignore rules listed in integrity.ignored_merge_artifacts. Merge receipts must be committed with their audit history; preserve those files, then preview pm merge reconcile --stage --dry-run before applying settlement."},{code:"merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:'Review pending receipt summaries, re-apply intended discarded values, then run pm merge reconcile. If proof is unavailable or receipt decisions are lossy, explicit review authority is required for pm merge reconcile --force --message "<reviewed receipt disposition and rationale>"; this records acceptance rather than restoring discarded values.'},{code:"merge_receipts_pending",command:"pm merge reconcile",summary:'A lossless receipt is pending; preview with pm merge reconcile --dry-run, then apply. If no receipt set proves the snapshot, review the summaries and only with explicit authority run pm merge reconcile --force --message "<reviewed receipt disposition and rationale>" to record an audited acceptance.'},{code:"merge_receipt_evidence_invalid",command:"pm merge report --include-reconciled --json",summary:"One or more receipt candidates failed bounded-file, schema, identity, or copy-consistency validation; inspect the report's privacy-safe source, receipt id, and reason before repairing only the named evidence."},{code:"merge_receipt_history_reference_missing",command:"pm merge reconcile --dry-run",summary:"Review the bounded coordinates and recover available evidence first; for exact pre-durable clone-local-only references, rerun with --force so pm appends an audited disposition and proves the health finding is cleared without rewriting history."},{code:"validate_merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:"Review the pending merge receipts before reconciliation; history-repair alone does not settle them, and lossy receipts require explicit --force acceptance."},{code:"history_drift_missing_stream",command:"pm history-repair <id>",summary:"The item has no history record; the repair rebuilds the stream as one audited baseline from the on-disk item, and earlier versions stay unrecorded. When the stream was deleted by mistake, restore it from version control first (pm history-repair --all, with or without --append-only, rebuilds every missing stream in one pass)."},{code:"history_drift_unreadable_stream",command:"pm history-repair <id> --salvage-tail --dry-run",summary:"The item's history stream cannot be read; preview salvage, which removes lines that cannot hold a record and an invalid tail after a verified prefix, then apply it without --dry-run. Salvage refuses interior corruption, which needs recovery from version control, and a permission error needs the file's access fixed."},{code:"history_drift_hash_mismatch",command:"pm history-repair <id>",summary:"The item's content hash no longer matches its history; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_chain_mismatch",command:"pm history-repair <id> --append-only",summary:"The item's history chain is broken; append one record that bridges every break in the stream and keeps every recorded line byte-identical (pm history-repair <id> re-anchors the recorded entries instead). pm health previews the bridge for every chain mismatch, so a break a bridge cannot repair is reported as history_drift_chain_unbridgeable, and a stream no repair can keep as history_drift_unrepairable_stream, instead."},{code:"history_drift_chain_unbridgeable",command:"pm history-repair <id>",summary:"The item's history chain is broken in a way an append-only bridge cannot repair, for example a recorded patch that applies only on top of the unrecorded change (details.repair_refusals names the refusal reason); re-anchor the recorded entries instead (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_unrepairable_stream",command:"pm history <id> --verify --full",summary:"Neither history repair can keep this stream (details.repair_refusals names both refusal reasons). Inspect it: a record that no longer matches its seal, or a malformed chain, needs the item's own stream restored from version control or a backup; a stream entry that is a link (reason stream_not_regular_file) needs the item's own stream restored as a regular file. Then run pm history <id> --verify --strict-exit."},{code:"history_drift_version_skew",command:"npm install -g @unbrained/pm-cli@latest",summary:"A history stream declares an item hash version this runtime does not support; upgrade pm to verify the chain instead of re-anchoring it."},{code:"history_drift_merge_receipt",command:"pm merge reconcile",summary:"Canonical path, changed-field, and merged-value hash evidence attributes this drift to a pending receipt; run reconciliation (optionally preview first with --dry-run) instead of repairing history directly."},{code:"history_stream_over_compact_threshold",command:"pm history-compact <id>",summary:"The history stream exceeds the configured compaction threshold; compact it (pm history-compact --all-streams sweeps every over-threshold stream in one pass)."},{code:"stale_in_progress_items",command:"pm list --status in_progress --assignee-filter unassigned --updated-before -72h",summary:"List unowned in-progress candidates idle past mutation_guard.stale_in_progress_hours by metadata time (pm health substitutes the configured status id and threshold); claim each with pm claim <id> or return it to open with pm update <id> --status open."},{code:"in_progress_unowned",command:"pm list --status in_progress --assignee-filter unassigned",summary:"List in-progress items nobody holds (pm health substitutes the configured status id); claim each with pm claim <id> or return it to open with pm update <id> --status open."},{code:"in_progress_idle",command:"pm list --status in_progress --updated-before -72h",summary:"List in-progress candidates not updated within mutation_guard.stale_in_progress_hours (pm health substitutes the configured status id and threshold; a restored item can appear although its history is recent); resume, release or return each one, or take another holder's with pm claim <id> --takeover-stale, which re-judges under the item lock."},{code:"history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"provenance_value_domain_invalid",command:"pm history-repair --all --normalize-provenance",summary:"Remove invalid bounded provenance observations from affected streams and append privacy-safe aggregate repair receipts."},{code:"validate_history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"locks_stale_count",command:"pm gc --scope locks",summary:"Stale item-claim locks (embedded ttl elapsed) can block mutations; sweep them \u2014 gc retains active and unparseable locks."},{code:"locks_unreadable",command:"pm gc --scope locks --dry-run",summary:"Some lock files could not be read; preview the sweep and inspect the unreadable files manually \u2014 gc never deletes what it cannot read."},{code:"extension_update_health_partial_coverage",command:"pm extension --adopt-all --project",summary:"Update-health coverage is partial because unmanaged extensions were skipped; adopt the existing installs into managed metadata so the update scan covers them (use --global for global-scope extensions, or pm package --adopt-all when working with packages)."},{code:"vectorization_stale_items_remaining",command:"pm health --refresh-vectors",summary:"Some items have stale embeddings; refresh vectors so semantic search results stay current."},{code:"vectorization_embedding_identity_changed",command:"pm reindex --mode semantic",summary:"Embedding provider/model changed since the last index; run a semantic reindex to rebuild vectors."},{code:"validate_metadata_missing_closed_at",command:"pm validate --check-metadata --auto-fix --fix-scope timestamps --dry-run",summary:"Preview closure dates proven by verified lifecycle history; inspect residuals and omit --dry-run to apply only proven dates."},{code:"validate_metadata_missing_acceptance_criteria",command:'pm update <id> --acceptance-criteria "<criteria>"',summary:"Backfill the missing acceptance criteria on the reported item(s)."},{code:"validate_schema_field_option_collision",command:"pm schema rename-field <key> --to <new-key>",summary:"A custom field shadows a built-in option of a command it is registered for; rename it (item values move with it), or re-register the same key with another flag or a narrower --commands list."},{code:"validate_metadata_missing_estimate",command:'pm update <id> --estimate "<estimate>"',summary:"Backfill the missing estimate on the reported item(s)."},{code:"validate_metadata_missing_close_reason",command:'pm update <id> --close-reason "<reason>"',summary:"Backfill the missing close reason on the reported closed item(s)."},{code:"validate_metadata_missing_reviewer",command:'pm update <id> --reviewer "<name>"',summary:"Backfill the missing reviewer on the reported item(s)."},{code:"validate_metadata_missing_risk",command:'pm update <id> --risk "<level>"',summary:"Backfill the missing risk on the reported item(s)."},{code:"validate_metadata_missing_confidence",command:'pm update <id> --confidence "<level>"',summary:"Backfill the missing confidence on the reported item(s)."},{code:"validate_metadata_missing_sprint",command:'pm update <id> --sprint "<sprint>"',summary:"Backfill the missing sprint on the reported item(s)."},{code:"validate_metadata_missing_release",command:'pm update <id> --release "<release>"',summary:"Backfill the missing release on the reported item(s)."},{code:"validate_metadata_custom_profile_missing_required_fields",command:'pm config set metadata-required-fields --criterion "<field>"',summary:"Config-driven finding: the custom metadata profile has no required fields configured and falls back to core, so configure the fields rather than mutating items."},{code:"validate_metadata_duplicate_issue_codes",command:'pm update <id> --title "<distinct title>"',summary:"Two or more items share one logical issue code (GH-235); give each a distinct title so the derived code is unique, or close the redundant item with pm close <id> --duplicate-of <canonical-id> (closed-as-duplicate items are excluded from the check)."},{code:"validate_resolution_missing_fields",command:'pm update <id> --resolution "<how resolved>"',summary:"Backfill resolution / expected_result / actual_result on the reported closed item(s)."},{code:"validate_lifecycle_active_closure_like_metadata",command:"pm update <id> --unset <closure-like-field>",summary:"Clear the closure-like field the validator flags on this active item \u2014 the detail row names it (resolution / actual-result / blocked-reason) \u2014 or close the item if it is actually done."},{code:"validate_lifecycle_active_terminal_parent",command:"pm update <id> --parent <active-parent-id>",summary:"Reopen the terminal parent or move the active child under a non-terminal parent."},{code:"validate_lifecycle_stale_blockers",command:"pm update <id> --unset blocked-by --unset blocked-reason",summary:"Resolve the stale blocker the validator flags: clear blocked-by/blocked-reason when they linger on a non-blocked item or report a resolved blocker; if instead a blocked item is missing blocker context, add the context or move it out of a blocked status."},{code:"validate_lifecycle_dependency_cycles_error",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_lifecycle_dependency_cycles",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_hierarchy_parent_cycle_error",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_hierarchy_parent_cycle",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_files_missing_linked_paths",command:"pm <files|docs> <id> --remove <path>",summary:"The check spans both item.files and item.docs under one code: restore the missing linked artifact, or unlink it with pm files (linked file) or pm docs (linked doc)."},{code:"validate_files_orphaned_paths",command:"pm <files|docs> <id> --add <path>",summary:"Link the orphaned artifact with pm files (file) or pm docs (doc), or remove it from the workspace."},{code:"validate_files_tracked_all_strict_forces_pm_internals",command:"pm validate --check-files --include-pm-internals",summary:"tracked-all-strict scan flagged pm internals; re-run with --include-pm-internals or a softer --scan-mode."},{code:"validate_history_drift_missing_streams",command:"pm history-repair <id>",summary:"Rebuild the history streams of the items without a history record as one audited baseline from each on-disk item."},{code:"validate_history_drift_unreadable_streams",command:"pm history-repair <id> --salvage-tail --dry-run",summary:"Preview salvage of the unreadable history streams, then apply it without --dry-run; interior corruption needs recovery from version control."},{code:"validate_history_drift_hash_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items whose content hash drifted."},{code:"validate_history_drift_chain_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with a broken history chain."},{code:"validate_history_drift_version_skews",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more history streams declare an item hash version this runtime does not support; upgrade pm to verify the chains instead of re-anchoring them."},{code:"validate_command_references_stale_pm_ids",command:'pm update <id> --replace-tests --test "command=<corrected-command>" [--test ...]',summary:"Correct the stale pm-ID inside the item's linked test command (the check scans tests[].command, not the body). --replace-tests overwrites the entire tests list, so re-include the item's other linked tests in the same call."},{code:"validate_format_version_outdated_items",command:"pm validate --verbose-diagnostics",summary:"One or more items predate the current storage format version; a pm storage migration rewrites them. Use --verbose-diagnostics to list the affected items."},{code:"validate_format_version_ahead_items",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more items were written by a newer pm format version than this runtime supports; upgrade pm to read and validate them safely."}]);function Rd(e){if(typeof e!="string")return;let t=e.trim();for(let n of kO)if(t===n.code||t.startsWith(`${n.code}:`))return n}function Id(e){let t={};for(let n of e){let r=Rd(n);r!==void 0&&!Object.prototype.hasOwnProperty.call(t,r.code)&&(t[r.code]=r.command)}return t}function Mw(e){return Object.values(Id(e))}import{execFile as bO}from"node:child_process";import{realpath as xO}from"node:fs/promises";import Pw from"node:path";import{promisify as SO}from"node:util";var EO=SO(bO),AO=32*1024*1024,CO=1e4,TO=["search/eval-queries.json"];function Od(e){return e.replaceAll("\\","/").replace(/\/+$/,"")}function RO(e){return`'${e.replaceAll("'","'\\''")}'`}async function IO(e,t=xO){return t(e).catch(()=>Pw.resolve(e))}async function ao(e){let t=await Pt(e);if(t===null)return{git_workspace_root:null,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let n=await IO(e),r=Od(Pw.relative(t,n));if(r.length===0)return{git_workspace_root:t,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let s=Ah.map(i=>`${r}/${Od(i)}`);try{let{stdout:i}=await EO("git",["ls-files","-z","--",...s.map(d=>`:(literal)${d}`)],{cwd:t,encoding:"utf8",maxBuffer:AO,windowsHide:!0,timeout:CO}),o=new Set(TO.map(d=>`${r}/${d}`)),a=[...new Set(i.split("\0").filter(d=>d.length>0&&!o.has(Od(d))))].sort((d,l)=>d.localeCompare(l)),c=s.filter(d=>a.some(l=>l===d||l.startsWith(`${d}/`)));return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:a,tracked_path_count:a.length,remediation_command:a.length===0?null:`git rm --cached -r -- ${c.map(d=>RO(`:(literal)${d}`)).join(" ")}`}}catch{return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:[],tracked_path_count:0,remediation_command:null}}}import Fw from"node:path";import{realpath as OO}from"node:fs/promises";async function Dw(e,t){let n=t===null?[]:await Uh(t,[Fw.relative(t,Fw.join(await OO(e),"merge-receipts","00000000-0000-4000-8000-000000000000.json")).replaceAll("\\","/")]);return{rules:n,warnings:n.length>0?[`merge_artifacts_ignored:${n.length}`]:[]}}async function jw(e,t,n,r){if(t===null)return{audit:null,count:0,warnings:[]};let s=await Dn(e,Fn(n),{gitWorkspaceRoot:t});if(s.status==="ok")return{audit:s,count:0,warnings:[]};let i=Math.max(1,s.missing_patterns.length+s.stale_patterns.length);return{audit:s,count:i,warnings:r?[`merge_fence_${s.status==="not_installed"?"missing":"drift"}:${i}`]:[]}}function Uw(e){let t=[];return e.invalidEvidenceCount>0&&t.push(`merge_receipt_evidence_invalid:${e.invalidEvidenceCount}`),e.missingHistoryReferenceCount>0&&t.push(`merge_receipt_history_reference_missing:${e.missingHistoryReferenceCount}`),t}import{lstat as LO}from"node:fs/promises";var Ld="history_drift_chain_mismatch",$O="history_drift_chain_unbridgeable",Ww="history_drift_unrepairable_stream",Gw="history_drift_hash_mismatch",Kw="history_drift_missing_stream",NO=["history_drift_unreadable_stream",Ww,"history_drift_version_skew","history_drift_merge_receipt"],MO=new Set([Ld,Kw]);function co(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function PO(e,t){return e instanceof p?typeof e.context.reason=="string"?e.context.reason:e.code??t:t}async function qw(e,t,n){try{await $i(e,{appendOnly:t,dryRun:!0},n);return}catch(r){return PO(r,t?"append_only_preview_failed":"rewrite_preview_failed")}}async function FO(e,t){let n=[];for(let r of co(e.check.details.missing_streams)){let[s]=await Promise.allSettled([LO(ht(t,r))]);s.status==="fulfilled"&&s.value.isSymbolicLink()&&n.push({id:r,reason:"stream_not_regular_file",rewrite_refusal:"stream_not_regular_file"})}return n}async function zw(e,t,n){let r=[],s=new Set(co(e.check.details.version_skews));for(let i of co(e.check.details.chain_mismatches)){if(s.has(i))continue;let o=await qw(i,!0,t);if(o===void 0)continue;let a=await qw(i,!1,t);r.push({id:i,reason:o,...a===void 0?{}:{rewrite_refusal:a}})}return[...r,...await FO(e,n)]}function DO(e,t,n){for(let r of[Ld,Kw]){if(!e.startsWith(`${r}:`))continue;let s=e.slice(r.length+1),i=t.get(s);return i===null?[]:[i===void 0?e:`${i}:${s}`]}return e.startsWith(`${Gw}:`)?n.has(e.slice(Gw.length+1))?[]:[e]:[e]}function Bw(e,t){let n=co(e.check.details.version_skews),r=new Map([...n.map(i=>[i,null]),...t.map(i=>[i.id,i.rewrite_refusal===void 0?$O:Ww])]),s=new Set([...n,...t.filter(i=>i.rewrite_refusal!==void 0).map(i=>i.id)]);e.warnings=e.warnings.flatMap(i=>DO(i,r,s)).sort((i,o)=>i.localeCompare(o)),t.length!==0&&(e.check.details={...e.check.details,repair_refusals:t})}function Hw(e){if(NO.some(r=>Object.hasOwn(e,r)))return;let t=Object.keys(e),n=t.every(r=>MO.has(r));for(let r of t)n?e[r]="pm history-repair --all --append-only":r!==Ld&&(e[r]="pm history-repair --all")}var jO=5;function lo(e,t){let n=[],r={};for(let i of e){let o=si(i);if(o.length!==0){for(let a of o)r[a.field]=(r[a.field]??0)+1;n.push({id:i.id,fields:o.map(a=>a.field),reasons:[...new Set(o.map(a=>a.reason))]})}}if(n.length===0)return;n.sort((i,o)=>i.id.localeCompare(o.id));let s=t?n.length:jO;return{details:{items:n.length,by_field:Object.fromEntries(Object.entries(r).sort(([i],[o])=>i.localeCompare(o))),rows:n.slice(0,s),truncated:n.length>s},warning:`validate_metadata_deferred_fields:${n.length}`}}var Xw=25,GO=ge.join("runtime","telemetry","events.jsonl"),qO=ge.join("runtime","telemetry","state.json"),WO=2500,KO=500,Qw=lp-3,zO=["x-pm-telemetry-max-schema-version","x-pm-telemetry-max-version"];function Dd(e,t=!1){return e.startsWith("agent_guidance_")||e.startsWith("telemetry_")||e.startsWith("extension_disabled_pm_")||e.startsWith("history_stream_over_compact_threshold:")||e.startsWith("integrity_legacy_hierarchy_")||e.startsWith("stale_in_progress_items:")||e.startsWith("in_progress_unowned:")||e.startsWith("in_progress_idle:")||e.startsWith("provenance_resolver_zero_success:")||e.startsWith("provenance_value_domain_invalid:")||!t&&e.startsWith("merge_driver_configuration_missing:")}function jd(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function Xn(e){return e.trim().toLowerCase()}function Md(e,t){let n=Xn(e),r=Xn(t);return n.startsWith("builtin-")?!0:r==="beads"||r==="todos"}async function Ud(e){try{return(await Et.stat(e)).isDirectory()}catch{return!1}}async function BO(e){let t=(await Et.readdir(e,{withFileTypes:!0})).filter(r=>r.isDirectory()),n=await Promise.all(t.map(r=>Et.readdir(ge.join(e,r.name),{withFileTypes:!0})));return new Set(n.flatMap(r=>r.filter(s=>s.isFile()).filter(s=>Ht.some(i=>s.name.endsWith(i))).map(s=>ge.parse(s.name).name)))}async function HO(e,t,n,r){let s=await He({path:e,scope:"project"}),i=t!=="_workspace"&&!r.has(t);if(!n.enabled&&!i)return{warnings:s,overThreshold:!1,classification:"live"};let o;try{o=await Et.readFile(e,"utf8")}catch{return{warnings:s,overThreshold:!1,classification:"unreadable"}}let a="live";if(i){let d=o.split(/\r?\n/).map(l=>l.trim()).filter(Boolean).at(-1);try{a=JSON.parse(d??"{}").op==="delete"?"tombstone":"orphaned"}catch{a="orphaned"}}let c=n.enabled?o.split(/\r?\n/).filter(d=>d.trim().length>0).length:0;return{warnings:s,overThreshold:n.enabled&&c>n.max_entries,classification:a}}async function VO(e,t,n){let r=ge.join(e,"history");if(!await Ud(r))return{count:0,warnings:[],over_threshold:[],max_entries:null,tombstones:[],orphaned:[]};let s=(await Et.readdir(r)).filter(u=>u.endsWith(".jsonl")).sort((u,f)=>u.localeCompare(f)),o=t.enabled?t.max_entries:null,a=[],c=[],d=[],l=[];for(let u of s){let f=ge.join(r,u),_=u.slice(0,-6),h=await HO(f,_,t,n);a.push(...h.warnings),h.classification==="tombstone"&&d.push(_),h.classification==="orphaned"&&l.push(_),h.overThreshold&&c.push(_)}return{count:s.length,warnings:[...a,...c.map(u=>`history_stream_over_compact_threshold:${u}`),...l.map(u=>`history_orphaned_stream:${u}`)],over_threshold:c,max_entries:o,tombstones:d,orphaned:l}}function Pd(e,t){return ge.relative(e,t).replaceAll("\\","/")}async function Zw(e,t){let n=[...new Set(Object.values(t))].sort((s,i)=>s.localeCompare(i)),r=[];for(let s of n){let i=ge.join(e,s),o=[];try{o=await Et.readdir(i)}catch(a){if(typeof a=="object"&&a!==null&&"code"in a&&U(a))continue;continue}for(let a of o)Ht.some(c=>a.toLowerCase().endsWith(c))&&r.push(ge.join(i,a))}return r.sort((s,i)=>Pd(e,s).localeCompare(Pd(e,i))),r}function YO(e){return!(typeof e=="object"&&e!==null&&"code"in e&&U(e))}function JO(e){let t=lo(e,!1);return t===void 0?{}:{curation:{deferred_fields:t.details}}}async function XO(e,t,n){let r=await Zw(e,t),s=[],i=[],o=[],a=[],c=Ot(F());for(let d of r){let l=Pd(e,d),u;try{u=await Et.readFile(d,"utf8")}catch{s.push(l);continue}let f=Ln(u);if(f){i.push({path:l,...f});continue}try{let _=ii(u,{format:vm(d),schema:n,extensionFieldNames:c});a.push({ref:l,version:ni(_.metadata)})}catch{o.push(l)}}return{paths:r,unreadable:s,conflictMarkers:i,parseFailures:o,formatVersions:a}}async function QO(e){let t=ge.join(e,"history"),n=[],r=[],s=[],i=[],o=[],a=[];try{a=(await Et.readdir(t)).filter(c=>c.endsWith(".jsonl")).sort((c,d)=>c.localeCompare(d))}catch(c){YO(c)&&n.push("history")}for(let c of a){let d=c.slice(0,-6),l;try{l=await Et.readFile(ge.join(t,c),"utf8")}catch{n.push(d);continue}let u=Ln(l);if(u){r.push({id:d,...u});continue}l.split(/\r?\n/).forEach((f,_)=>{if(f.trim())try{let h=JSON.parse(f);i.push(...Ew(h,d).map(g=>({itemId:d,line:_+1,...g}))),o.push(...Aw(h,d,_+1))}catch{s.push({id:d,line:_+1})}})}return{files:a,unreadable:n,conflictMarkers:r,invalidJson:s,mergeReceiptReferences:i,mergeReceiptDispositions:o}}function ev(e){return[...e.cycles.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_cycle:${t.item_ids.join(",")}`:`integrity_hierarchy_cycle:${t.item_ids.join(",")}`),...e.cardinality_violations.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_cardinality:${t.child_id}`:`integrity_hierarchy_cardinality:${t.child_id}`),...e.divergences.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_divergence:${t.child_id}`:`integrity_hierarchy_divergence:${t.child_id}`)]}async function ZO(e,t,n,r,s,i){let o=await XO(e,t,n),a=await QO(e),c=ri(o.formatVersions,4,1),d=z(n),l=Oi(i,R=>_e(R,d),de()),u=await ao(e),f=await Pt(e),_=await Dw(e,f),h=await jw(e,f,r,s),g=f===null?null:await jn(f),y=await Un(f??e,{includeReconciled:!0,includeLossless:!0,pmRoot:e}),w=new Set(y.durable_receipt_ids),v=Cw(a.mergeReceiptReferences,w,a.mergeReceiptDispositions),S=v.missing,b=y.receipts.filter(R=>R.state==="pending"),{pendingDecisions:k,lossless:A}=Gn(b),x=g?.status==="missing"&&g.missing_keys.length===5&&g.drifted_keys.length===0,E=[...o.unreadable.map(R=>`integrity_item_unreadable:${R}`),...o.conflictMarkers.map(R=>`integrity_item_conflict_marker:${R.path}:L${R.line}`),...o.parseFailures.map(R=>`integrity_item_parse_failed:${R}`),...a.unreadable.map(R=>`integrity_history_unreadable:${R}`),...a.conflictMarkers.map(R=>`integrity_history_conflict_marker:${R.id}:L${R.line}`),...a.invalidJson.map(R=>`integrity_history_invalid_json:${R.id}:L${R.line}`),...c.outdated.map(R=>`integrity_item_outdated_format_version:${R}`),...c.ahead.map(R=>`integrity_item_ahead_format_version:${R}`),...ev(l),...u.tracked_path_count>0?[`tracked_runtime_cache_files:${u.tracked_path_count}`]:[],...g!==null&&g.status!=="ok"?[`merge_driver_configuration_${x?"missing":"drift"}:${g.missing_keys.length+g.drifted_keys.length}`]:[],...h.warnings,..._.warnings,...k.length>0?[`merge_decisions_unreviewed:${k.length}`]:[],...A.length>0?[`merge_receipts_pending:${A.length}`]:[],...Uw({invalidEvidenceCount:y.invalid_evidence_count,missingHistoryReferenceCount:S.length})],$=[...new Set(E)].sort((R,T)=>R.localeCompare(T)),P=$.filter(R=>!R.startsWith("integrity_legacy_hierarchy_"));return{check:{name:"integrity",status:P.length===0?"ok":"warn",ok:P.length===0,details:{checked_item_files:o.paths.length,checked_history_streams:a.files.length,counts:{item_unreadable:o.unreadable.length,item_conflict_markers:o.conflictMarkers.length,item_parse_failures:o.parseFailures.length,history_unreadable:a.unreadable.length,history_conflict_markers:a.conflictMarkers.length,history_invalid_json:a.invalidJson.length,item_outdated_format_version:c.outdated.length,item_ahead_format_version:c.ahead.length,hierarchy_cycles:l.cycles.length,hierarchy_cardinality_violations:l.cardinality_violations.length,hierarchy_parent_divergences:l.divergences.length,tracked_runtime_cache_files:u.tracked_path_count,merge_driver_configuration:g===null||g.status==="ok"?0:g.missing_keys.length+g.drifted_keys.length,merge_fence:h.count,ignored_merge_artifacts:_.rules.length,pending_merge_decisions:k.length,lossless_merge_receipts:A.length,invalid_merge_receipt_evidence:y.invalid_evidence_count,missing_merge_receipt_history_references:S.length,accepted_legacy_merge_receipt_references:v.acceptedLegacyCount,accepted_missing_merge_receipt_dispositions:v.acceptedDispositionCount},item_unreadable:o.unreadable,item_conflict_markers:o.conflictMarkers,item_parse_failures:o.parseFailures,item_outdated_format_version:c.outdated,item_ahead_format_version:c.ahead,...JO(i),hierarchy_integrity:{...l,relations:et(l.relations,8)},history_unreadable:a.unreadable,history_conflict_markers:a.conflictMarkers,history_invalid_json:a.invalidJson,tracked_runtime_cache:{tracker_relative_root:u.tracker_relative_root,tracked_paths:u.tracked_paths,tracked_path_count:u.tracked_path_count,remediation_command:u.remediation_command},merge_driver_configuration:g===null?null:{...g,required:s},merge_fence:h.audit,ignored_merge_artifacts:_.rules,pending_merge_decision_items:[...new Set(k.map(R=>R.item_id))].sort((R,T)=>R.localeCompare(T)),lossless_merge_receipt_items:[...new Set(A.map(R=>R.item_id))].sort((R,T)=>R.localeCompare(T)),invalid_merge_receipt_evidence_details:y.invalid_evidence,invalid_merge_receipt_evidence_details_truncated:y.invalid_evidence_truncated,missing_merge_receipt_history_reference_details:S.slice(0,100),missing_merge_receipt_history_reference_details_truncated:S.length>100}},warnings:$,gitWorkspaceRoot:f,pendingMergeReceipts:b}}function e0(e){if(typeof e.activate=="function")return!0;let t=e.default;return typeof t!="object"||t===null?!1:typeof t.activate=="function"}function t0(e){let t={layer:e.layer,directory:e.directory,manifest_path:e.manifest_path,name:e.name,version:e.version,entry:e.entry,priority:e.priority,entry_path:e.entry_path,has_activate:e0(e.module)};return Array.isArray(e.capabilities)&&(t.capabilities=[...e.capabilities]),t}function n0(e,t){let n=ie(e.id);return n||`migration-${String(t+1).padStart(3,"0")}`}function r0(e){let n=ie(e.status)?.toLowerCase();return n==="failed"?"failed":n==="applied"?"applied":"pending"}function s0(e){return ie(e.reason)??ie(e.error)??ie(e.message)}function $d(e,t){let n=(e.layer??"").localeCompare(t.layer??"");if(n!==0)return n;let r=(e.name??"").localeCompare(t.name??"");return r!==0?r:(e.id??"").localeCompare(t.id??"")}function i0(e){let t=[],n=[],r=[];e.forEach((i,o)=>{let a=n0(i.definition,o),c=r0(i.definition);if(c==="applied"){t.push({layer:i.layer,name:i.name,id:a,status:c});return}if(c==="failed"){r.push({layer:i.layer,name:i.name,id:a,status:c,reason:s0(i.definition)});return}n.push({layer:i.layer,name:i.name,id:a,status:c})}),t.sort($d),n.sort($d),r.sort($d);let s=[...r.map(i=>`extension_migration_failed:${i.layer}:${i.name}:${i.id}`),...n.map(i=>`extension_migration_pending:${i.layer}:${i.name}:${i.id}`)];return{summary:{applied:t,pending:n,failed:r,applied_count:t.length,pending_count:n.length,failed_count:r.length},warnings:s}}function tv(e,t,n,r,s,i,o,a,c){let d=[...new Set(e)].sort((y,w)=>y.localeCompare(w)),l=[...new Set(d.map(y=>jd(y)))].sort((y,w)=>y.localeCompare(w)),u=d.filter(y=>y.startsWith("extension_capability_unknown:")).length,f=c.length>0,_=f?"partial":"full",h=d.map(Rc).filter(y=>y!==void 0),g=Lh(d,{deactivate:"pm extension --deactivate <name> --project/--global",doctor:"pm extension --doctor --project/--global --detail deep --trace"});return g&&h.push(g),t>0&&h.push("Run pm extension --explore --project and pm extension --explore --global to inspect load failures."),n>0&&h.push("Review checks[name=extensions].details.activation.failed in pm health --json for activation error details."),(r.failed_count>0||r.pending_count>0)&&h.push("Resolve pending/failed extension migrations before write commands; use --force only when policy allows."),s>0&&h.push("Run pm extension --manage --project and pm extension --manage --global to refresh managed-state diagnostics."),u>0&&h.push(`Unknown extension capabilities detected. Allowed capabilities: ${Ku.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`),d.some(y=>y.startsWith("extension_capability_legacy_alias:"))&&h.push("Legacy extension capability aliases were auto-remapped to canonical capabilities. Update manifests to canonical names (migration/validation -> schema)."),d.some(y=>y.startsWith("extension_command_definition_legacy_handler_alias:"))&&h.push("Extension command definitions using legacy handler were auto-remapped. Update command definitions to use run: (context) => ... for forward compatibility."),f?h.push("Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via pm extension --manage --project/--global --fix-managed-state, pm extension --adopt-all --project/--global, or pm extension --adopt <name>."):o.length>0&&h.push("Loaded unmanaged extensions are currently treated as informational. Use pm extension --manage --project/--global --fix-managed-state to adopt them for update checks."),h.length===0&&h.push("No immediate action required. Re-run pm health after extension configuration changes."),{status:d.length===0?"ok":"warn",warning_count:d.length,warning_codes:l,load_failure_count:t,activation_failure_count:n,migration_failed_count:r.failed_count,migration_pending_count:r.pending_count,managed_state_warning_count:s,managed_extension_entries_count:i,unmanaged_loaded_extension_count:o.length,unmanaged_loaded_extensions:o,unmanaged_expected_extension_count:a.length,unmanaged_expected_extensions:a,unmanaged_action_required_extension_count:c.length,unmanaged_action_required_extensions:c,update_health_coverage:_,update_health_partial:f,unknown_capability_count:u,top_warnings:d.slice(0,8),remediation:h}}async function o0(e,t,n){let r=await $h(lt(e)),s=await ci({pmRoot:e,settings:t,cwd:process.cwd(),noExtensions:n}),i=s.loaded.map(x=>t0(x)),o=await gw(s.loaded,lt(e)),a=await di({...s,loaded:s.loaded}),[c,d]=await Promise.all([Tc(s.roots.project),Tc(s.roots.global)]);await wp(e,a.registrations.migrations);let l=i0(a.registrations.migrations),u={failed:a.failed,warnings:a.warnings,hook_counts:a.hook_counts,command_override_count:a.command_override_count,command_handler_count:a.command_handler_count,parser_override_count:a.parser_override_count,preflight_override_count:a.preflight_override_count,service_override_count:a.service_override_count,renderer_override_count:a.renderer_override_count,registration_counts:a.registration_counts,registrations:a.registrations,migration_status:l.summary,managed_extensions:{project:{path:c.path,count:c.state.entries.length,entries:c.state.entries},global:{path:d.path,count:d.state.entries.length,entries:d.state.entries}}},f=new Set(c.state.entries.map(x=>Xn(x.name))),_=new Set(d.state.entries.map(x=>Xn(x.name))),h=[...new Map(s.loaded.filter(x=>!(x.layer==="project"?f:_).has(Xn(x.name))).map(x=>[`${x.layer}:${x.name}`,{layer:x.layer,name:x.name,directory:x.directory}])).values()].sort((x,E)=>{let $=`${x.layer}:${x.name}`,P=`${E.layer}:${E.name}`;return $.localeCompare(P)}),g=h.map(x=>`${x.layer}:${x.name}`).sort((x,E)=>x.localeCompare(E)),y=h.filter(x=>Md(x.name,x.directory)).map(x=>`${x.layer}:${x.name}`).sort((x,E)=>x.localeCompare(E)),w=h.filter(x=>!Md(x.name,x.directory)).map(x=>`${x.layer}:${x.name}`).sort((x,E)=>x.localeCompare(E)),v=w.length>0?[`extension_update_health_partial_coverage:skipped_unmanaged:${w.length}`]:[],S=[...r.warnings,...s.warnings,...u.warnings,...l.warnings,...c.warnings,...d.warnings,...v,...o.warnings],b=Ic(S),k=Oc(),A=tv(S,s.failed.length,a.failed.length,l.summary,c.warnings.length+d.warnings.length,c.state.entries.length+d.state.entries.length,g,y,w);return{check:{name:"extensions",status:S.length===0?"ok":"warn",ok:S.length===0,details:{...s,loaded:i,warnings:S,activation:u,author_manifest:r,triage:A,...l.summary.pending_count>0?{remediation_map:{extension_migration_pending:"pm extension migrate --project"}}:{},capability_contract:k,capability_guidance:b,host_version_census:o}},warnings:S}}function Fd(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=Rw(e,Xw);return{values:n.values,truncated:n.truncated,total:e.length}}function uo(e){let t=(process.env[e]??"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function a0(){let e=np();return e.source_context_source==="env_override"?e.source_context:null}function nv(e){let t=0,n=0,r=0,s=0,i=0;for(let o of e.split(`
|
|
8
|
+
`)){let a=o.trim();if(a.length!==0){r+=1;try{let c=JSON.parse(a);if(typeof c=="object"&&c!==null&&typeof c.attempts=="number"&&Number.isFinite(c.attempts)){let d=Math.max(0,Math.trunc(c.attempts));t+=1,i=Math.max(i,d),d>=Qw&&(s+=1)}else n+=1}catch{n+=1}}}return{validEntries:t,invalidRows:n,totalRows:r,highRetryEntries:s,maxAttempts:i}}function c0(){return{validEntries:0,invalidRows:0,totalRows:0,highRetryEntries:0,maxAttempts:0}}function Yw(e){if(!e||e.trim().length===0)return{runtimeState:{},stateParseFailed:!1};try{let t=JSON.parse(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)?{runtimeState:t,stateParseFailed:!1}:{runtimeState:{},stateParseFailed:!0}}catch{return{runtimeState:{},stateParseFailed:!0}}}async function d0(e,t){let n=Ir(e.telemetry.endpoint).trim();return!t||!e.telemetry.enabled||n.length===0||en().telemetry_disabled?void 0:{attempted:!0,...await rv(n)}}function l0(e,t,n){let r=[];if(t.invalidRows>0&&r.push(`telemetry_queue_invalid_rows:${t.invalidRows}`),!e.telemetry.enabled||t.validEntries===0)return r;let s=n.last_successful_flush_at,i=n.last_failed_flush_at,o=i&&(!s||i>s),a=!s,c=t.validEntries>=KO;return(o||a||c)&&r.push(`telemetry_queue_pending:${t.validEntries}`),t.highRetryEntries>0&&r.push(`telemetry_queue_high_retries:${t.highRetryEntries}`),r}function u0(e){return!e||e.ok!==!1?[]:typeof e.status=="number"?[`telemetry_endpoint_probe_http_status:${e.status}`]:["telemetry_endpoint_probe_failed"]}function m0(e){let t=Number.parseInt(e?.max_schema_version??"",10);return e?.ok===!0&&Number.isInteger(t)&&t>dp?[`telemetry_schema_version_behind:${t}`]:[]}function f0(e,t){let n=typeof t.pending_otel_spans=="number"?t.pending_otel_spans:0,r=t.last_otel_success_at,s=t.last_otel_failure_at;return e.telemetry.enabled&&n>0&&!!s&&(!r||s>=r)?[`telemetry_otel_export_failing:${n}`]:[]}function p0(){return{...en(),pm_no_telemetry:uo("PM_NO_TELEMETRY"),telemetry_otel_disabled:uo("PM_TELEMETRY_OTEL_DISABLED"),telemetry_inline_flush:uo("PM_TELEMETRY_INLINE_FLUSH"),telemetry_source_context:a0()}}function _0(e,t){return e.telemetry.enabled&&t.validEntries>0}function h0(e,t){return e&&t.every(n=>!n.startsWith("telemetry_queue_pending:")&&!n.startsWith("telemetry_queue_high_retries:"))}function Jw(e){try{return decodeURIComponent(e)}catch{return e}}async function rv(e){let t=e,n={};try{let r=new URL(e);r.pathname="/healthz",r.search="",r.hash="",(r.username.length>0||r.password.length>0)&&(n.authorization=`Basic ${Buffer.from(`${Jw(r.username)}:${Jw(r.password)}`).toString("base64")}`,r.username="",r.password=""),t=r.toString()}catch{}try{let r=await fetch(t,{method:"GET",headers:n,signal:AbortSignal.timeout(WO)});return{probe_url:Nt(t),ok:r.ok,status:r.status,max_schema_version:(()=>{for(let s of zO){let i=r.headers.get(s)?.trim();if(i&&i.length>0)return i}})()}}catch(r){return{probe_url:Nt(t),ok:!1,error:r instanceof Error?rp(r.message.replaceAll(t,Nt(t))):"probe_failed"}}}async function g0(e,t){let n=Yw(await Q(e)),r=e===t?n:Yw(await Q(t));return{runtimeState:n.runtimeState,spanState:r.runtimeState,stateParseFailed:n.stateParseFailed||r.stateParseFailed}}async function y0(e){let t=Xe(process.cwd()),n=await C(t),r=ge.join(ge.dirname(ge.join(t,GO)),$t("events.jsonl")),s=ge.join(t,qO),i=ge.join(ge.dirname(s),$t("state.json")),o=await Q(r),a=o!==null,c=o?Buffer.byteLength(o,"utf8"):0,d=o?nv(o):c0(),{runtimeState:l,spanState:u,stateParseFailed:f}=await g0(i,s),_=Ir(n.telemetry.endpoint).trim(),h=Nt(_),g=await d0(n,e.checkTelemetry),y=[];f&&y.push("telemetry_state_invalid_json"),y.push(...l0(n,d,l),...u0(g),...m0(g),...f0(n,u));let w=_0(n,d),v=typeof u.pending_otel_spans=="number"?u.pending_otel_spans:0;return{check:{name:"telemetry",status:y.length===0?"ok":"warn",ok:y.length===0,details:{enabled:n.telemetry.enabled,capture_level:n.telemetry.capture_level,endpoint:h,global_pm_root:t,queue_path:r,queue_exists:a,queue_entries:d.validEntries,queue_draining:h0(w,y),queue_invalid_rows:d.invalidRows,queue_rows_total:d.totalRows,queue_size_bytes:c,queue_high_retry_entries:d.highRetryEntries,queue_high_retry_threshold:Qw,queue_max_attempts:d.maxAttempts,runtime_state_path:i,last_attempted_flush_at:l.last_attempted_flush_at??null,last_successful_flush_at:l.last_successful_flush_at??null,last_failed_flush_at:l.last_failed_flush_at??null,last_failed_flush_error:l.last_failed_flush_error??null,pending_otel_spans:v,last_otel_attempt_at:u.last_otel_attempt_at??null,last_otel_success_at:u.last_otel_success_at??null,last_otel_failure_at:u.last_otel_failure_at??null,last_otel_failure_error:u.last_otel_failure_error??null,endpoint_probe:g??{attempted:!1},env_overrides:p0()}},warnings:y}}async function w0(e){let t;try{t=await $w(e)}catch(r){let s=r instanceof Error?r.message:String(r);return{check:{name:"locks",status:"warn",ok:!1,details:{active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0,scan_failed:!0,error:s,pm_root:e}},warnings:[`locks_scan_failed:${s}`]}}let n=[];return t.stale_lock_count>0&&n.push(`locks_stale_count:${t.stale_lock_count}`),t.unreadable_lock_count>0&&n.push(`locks_unreadable:${t.unreadable_lock_count}`),{check:{name:"locks",status:n.length===0?"ok":"warn",ok:n.length===0,details:{active_lock_count:t.active_lock_count,stale_lock_count:t.stale_lock_count,...t.owner_dead_lock_samples?{owner_dead_lock_samples:t.owner_dead_lock_samples,recovery_command:"pm gc --scope locks"}:{},unreadable_lock_count:t.unreadable_lock_count,unparseable_lock_count:t.unparseable_lock_count}},warnings:n}}async function v0(e){let t="metadata",n=e.items,r=await Ur(e.pmRoot,n,{cacheHitVerification:t}),s=[...new Set([...r.hashMismatches,...r.chainMismatches,...r.versionSkews])].sort((w,v)=>w.localeCompare(v)),i=[],o=[];if(s.length>0){n=await wt(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema,{forceSourceScan:!0}),r=await Ur(e.pmRoot,n),i=[...new Set([...r.hashMismatches,...r.chainMismatches,...r.versionSkews])].sort((v,S)=>v.localeCompare(S));let w=new Set(i);o=s.filter(v=>!w.has(v))}let{missingStreams:a,unreadableStreams:c,hashMismatches:d,chainMismatches:l,versionSkews:u,driftedItems:f,workspaceStateMismatches:_,workspaceStateMissing:h,workspaceStateUnreadable:g}=r,y=[...a.map(w=>`history_drift_missing_stream:${w}`),...c.map(w=>`history_drift_unreadable_stream:${w}`),...d.map(w=>`history_drift_hash_mismatch:${w}`),...l.map(w=>`history_drift_chain_mismatch:${w}`),...u.map(w=>`history_drift_version_skew:${w}`),..._.map(w=>`history_drift_workspace_state_mismatch:${w}`),...h.map(w=>`history_drift_workspace_state_missing:${w}`),...g.map(w=>`history_drift_workspace_state_unreadable:${w}`)];return{check:{name:"history_drift",status:y.length===0?"ok":"warn",ok:y.length===0,details:{checked_items:n.length,cache_hit_verification:s.length>0?"metadata_then_content_hash":t,cache_confirmation:{triggered:s.length>0,reason:s.length>0?"cached_corruption_candidate":null,candidate_items:s,confirmed_items:i,resolved_false_positive_items:o,authoritative_item_source:s.length>0},drifted_items:f,counts:{drifted:f.length,missing_streams:a.length,unreadable_streams:c.length,hash_mismatches:d.length,chain_mismatches:l.length,version_skews:u.length,workspace_state_mismatches:_.length,workspace_state_missing:h.length,workspace_state_unreadable:g.length},missing_streams:a,unreadable_streams:c,hash_mismatches:d,chain_mismatches:l,version_skews:u,workspace_state_mismatches:_,workspace_state_missing:h,workspace_state_unreadable:g}},warnings:y}}function k0(e,t){let n=qf(e),r=Xf(n.settings),s=Qf(n.settings,t),i=r.active?Zf(r.active.name,r.active.model):null;return{runtimeDefaults:n,providerResolution:r,vectorStoreResolution:s,runtimeEmbeddingIdentity:i,semanticRuntimeAvailable:!!(r.active&&s.active)}}function b0(){return{refreshed:[],skipped:[],warnings:[]}}async function x0(e){return!e.refreshPolicy.enabled||!e.snapshot.semanticRuntimeAvailable||e.staleBefore.length===0?b0():tp(e.pmRoot,e.staleBefore,{settings:e.snapshot.runtimeDefaults.settings,apply_runtime_defaults:!1})}function S0(e){return e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&!!(e.ledgerBefore.embedding&&e.runtimeEmbeddingIdentity&&ep(e.ledgerBefore.embedding,e.runtimeEmbeddingIdentity))}function E0(e){let t=new Set([...e.ledgerBefore.warnings,...e.ledgerAfter.warnings]);if(e.strictVectorizationWarnings)for(let n of e.refreshResult.warnings)t.add(n);return e.embeddingIdentityChanged&&t.add("vectorization_embedding_identity_changed"),e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&e.staleAfter.length>0&&t.add(`vectorization_stale_items_remaining:${e.staleAfter.length}`),[...t].sort((n,r)=>n.localeCompare(r))}function A0(e,t,n){return e.enabled&&t&&n.length>0?null:e.enabled?t?"no_stale_items":"semantic_runtime_unavailable":"refresh_disabled"}function sv(e,t){let n=t.providerResolution.active?.name??null,r=t.vectorStoreResolution.active?.name??null;return{provider_active:n,provider_configured:typeof e.search?.provider=="string"?e.search.provider:null,provider_source:ic(n,e.search?.provider??null),vector_store_active:r,vector_store_configured:typeof e.vector_store?.adapter=="string"?e.vector_store.adapter:null,vector_store_source:ic(r,e.vector_store?.adapter??null)}}function C0(e){return{enabled:e.enabled,check_only:e.checkOnly,no_refresh:e.noRefresh,refresh_vectors:e.refreshVectors}}function T0(e,t,n){return e.enabled&&n.length>0&&t}async function R0(e,t,n,r,s){let i=k0(t,e),o=await oc(e),a=i.semanticRuntimeAvailable?Nc(n,o.entries):[],c=await x0({pmRoot:e,snapshot:i,refreshPolicy:r,staleBefore:a}),d=await oc(e),l=i.semanticRuntimeAvailable?Nc(n,d.entries):[],u=!i.runtimeDefaults.auto_ollama_defaults_applied,f=S0({strictVectorizationWarnings:u,semanticRuntimeAvailable:i.semanticRuntimeAvailable,ledgerBefore:o,runtimeEmbeddingIdentity:i.runtimeEmbeddingIdentity}),_=E0({ledgerBefore:o,ledgerAfter:d,refreshResult:c,strictVectorizationWarnings:u,semanticRuntimeAvailable:i.semanticRuntimeAvailable,embeddingIdentityChanged:f,staleAfter:l}),h=Fd(a,s),g=Fd(l,s),y=T0(r,i.semanticRuntimeAvailable,a);return{check:{name:"vectorization",status:_.length===0?"ok":"warn",ok:_.length===0,details:{semantic_runtime_available:i.semanticRuntimeAvailable,compatibility_mode_auto_defaults:i.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_applied:i.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:i.runtimeDefaults.auto_ollama_defaults_skipped_reason??null,auto_ollama_defaults_remediation:i.runtimeDefaults.auto_ollama_defaults_remediation??null,refresh_policy:C0(r),...sv(t,i),embedding_identity_changed:f,embedding_identity_before:o.embedding??null,embedding_identity_runtime:i.runtimeEmbeddingIdentity??null,items:n.length,ledger_entries_before:Object.keys(o.entries).length,stale_items_detail_mode:s?"full":"summary",stale_items_summary_limit:Xw,stale_items_before_total:h.total,stale_items_before:h.values,stale_items_before_truncated:h.truncated,refresh_attempted:y,refresh_skipped_reason:A0(r,i.semanticRuntimeAvailable,a),refresh_result:c,ledger_entries_after:Object.keys(d.entries).length,stale_items_after_total:g.total,stale_items_after:g.values,stale_items_after_truncated:g.truncated}},warnings:_}}function I0(e){let t=[];return e.id_prefix.trim().length===0&&t.push("settings:id_prefix_empty"),e.locks.ttl_seconds<=0&&t.push("settings:locks_ttl_non_positive"),t}function iv(e){let t=e.checkOnly===!0,n=e.refreshVectors===!0;if(n&&t)throw new p("--check-only cannot be combined with --refresh-vectors",m.USAGE);if(n&&e.noRefresh===!0)throw new p("--no-refresh cannot be combined with --refresh-vectors",m.USAGE);return{enabled:n,checkOnly:t,noRefresh:!n,refreshVectors:n}}var O0=new Set(["extensions","locks","search"]);function L0(e){let t=new Set(Hu.filter(s=>s.length>0)),n=new Set,r=new Set(Object.values(Vu));for(let s of e.folders)t.has(s)&&!r.has(s)||(t.delete(s),n.add(s));for(let s of O0)t.delete(s),n.add(s);return{requiredDirs:[...t].sort((s,i)=>s.localeCompare(i)),optionalDirs:[...n].sort((s,i)=>s.localeCompare(i)),optionalDirSet:n}}async function $0(e,t,n){let{requiredDirs:r,optionalDirs:s,optionalDirSet:i}=L0(t),o=[],a=[],c=[];for(let d of[...r,...s]){let l=ge.join(e,d);c.push(...await He({path:l,scope:"project"})),!await Ud(l)&&(i.has(d)?a.push(d):o.push(d))}return{requiredDirs:r,optionalDirs:s,missingRequiredDirs:o,missingOptionalDirs:a,missingDirs:n?[...o,...a]:[...o],hookWarnings:c}}function ov(e){let t=e.checkOnly===!0&&e.brief!==!0&&e.summary!==!0&&e.full!==!0,n=e.summary===!0||t,r=e.checkOnly===!0&&(e.brief===!0||e.summary===!0)&&e.full!==!0;return{summaryMode:n,skipIntegrity:(e.skipIntegrity===!0||r)&&e.full!==!0,skipDrift:(e.skipDrift===!0||r)&&e.full!==!0,skipVectors:(e.skipVectors===!0||r)&&e.full!==!0}}async function N0(e){return e.skipPolicy.skipDrift&&e.skipPolicy.skipVectors?Ae(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema):wt(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema)}function Nd(e){return{check:{name:e,status:"ok",ok:!0,details:{skipped:!0}},warnings:[]}}function M0(e,t,n){return{name:"settings",status:n.length===0?"ok":"warn",ok:n.length===0,details:{path:e,version:t.version,id_prefix:t.id_prefix,locks_ttl_seconds:t.locks.ttl_seconds,warnings:n}}}function P0(e,t){return{name:"directories",status:e.missingDirs.length===0?"ok":"warn",ok:e.missingDirs.length===0,details:{required:e.requiredDirs,optional:e.optionalDirs,missing_required:e.missingRequiredDirs,missing_optional:e.missingOptionalDirs,missing:e.missingDirs,strict_directories:t}}}function F0(e,t){return{name:"settings_values",status:e.length===0?"ok":"warn",ok:e.length===0,details:{warnings:e,...t.roleless_status_count>0?{lifecycle_status_roles:t}:{}}}}var Gd=e=>e.unknown_event_count??0,qd=e=>e.actionable_unknown_event_count??Gd(e);function D0(e,t,n,r,s,i,o){let a=Gd(r),c=qd(r),d=a>0,l=c>0,u=s.count>0||o!==void 0;return{name:"storage",status:n.over_threshold.length===0&&n.orphaned.length===0&&!l&&!u?"ok":"warn",ok:n.over_threshold.length===0&&n.orphaned.length===0&&!l&&!u,details:{items:e.length,history_streams:n.count,tombstones:{retention_policy:"retain_append_only",gc_enabled:!1,count:n.tombstones.length,ids:n.tombstones.slice(0,25),truncated:n.tombstones.length>25},orphaned_history_streams:{count:n.orphaned.length,ids:n.orphaned.slice(0,25),truncated:n.orphaned.length>25},...d?{author_attribution:r}:{},...s.count>0?{stale_in_progress:s}:{},...o===void 0?{}:{in_progress_work:o},...i.outcomes.length>0?{provenance_resolver_outcomes:i.outcomes}:{},...i.invalid_values.length>0?{provenance_invalid_values:i.invalid_values}:{},provenance_sample:i.sample,...n.max_entries!==null?{compact_policy:{enabled:t.history.compact_policy.enabled,max_entries:n.max_entries,trigger:t.history.compact_policy.trigger,over_threshold_count:n.over_threshold.length,over_threshold:n.over_threshold}}:{}}}}function av(e){let t=e.count===0?[]:[`stale_in_progress_items:${e.count}`];return{scan:e,warnings:t}}function j0(e){let t=[...e.directoryState.missingDirs.map(n=>`missing_directory:${n}`),...e.normalizedSettingsReadWarnings,...e.settingWarnings,...e.normalizedItemReadWarnings,...e.telemetryCheck.warnings,...e.extensionCheck.warnings,...e.historyPolicyWarnings,...e.historySummary.warnings,...e.authorAttributionWarnings,...e.staleInProgressWarnings,...e.provenanceWarnings,...e.locksCheck.warnings,...e.integrityCheck.warnings,...e.historyDriftCheck.warnings,...e.vectorizationCheck.warnings,...e.directoryState.hookWarnings];return[...new Set(t)]}function U0(e){let t=e.check.details.counts;return typeof t?.drifted=="number"?t.drifted:0}function G0(e){return{settings:e.normalizedSettingsReadWarnings,directories:e.directoryState.missingDirs.map(t=>`missing_directory:${t}`).concat(e.directoryState.hookWarnings),settings_values:e.settingWarnings,telemetry:e.telemetryCheck.warnings,extensions:e.extensionCheck.warnings,storage:[...e.historyPolicyWarnings,...e.historySummary.warnings,...e.authorAttributionWarnings,...e.staleInProgressWarnings,...e.provenanceWarnings],locks:e.locksCheck.warnings,integrity:[...e.normalizedItemReadWarnings,...e.integrityCheck.warnings],history_drift:e.historyDriftCheck.warnings,vectorization:e.vectorizationCheck.warnings}}function cv(e){let t=new Map;for(let[s,i]of Object.entries(e.remediationSources))for(let o of i)t.has(o)||t.set(o,s);let n=new Map(e.checks.map(s=>[s.name,s]));return e.warnings.map(s=>{let i=t.get(s)??"integrity",o=Rd(s)?.code??jd(s),a=n.get(i)?.details,c=typeof a?.remediation_map=="object"&&a.remediation_map!==null?a.remediation_map:{},d=Rc(s)??(o==="agent_guidance_outdated"?"pm init --agent-guidance add":o==="agent_guidance_unreadable"?"Check AGENTS.md and CLAUDE.md read permissions and file types, then retry pm health.":c[o]),l=Dd(s,e.requireMergeDrivers)?"advisory":"gate_failing";return{warning:s,code:o,check:i,severity:l,...typeof d=="string"?{remediation:d}:l==="gate_failing"?{disposition:"no_safe_automatic_remediation"}:{}}})}function q0(e){if(e.check.name==="history_drift"&&e.historyDriftedCount>1&&Hw(e.remediationMap),e.check.name==="storage"&&e.overThresholdCount>1)for(let t of Object.keys(e.remediationMap))e.remediationMap[t]="pm history-compact --all-streams"}function W0(e){for(let t of e.checks){let n=Id(e.remediationSources[t.name]);q0({check:t,remediationMap:n,historyDriftedCount:e.historyDriftedCount,overThresholdCount:e.overThresholdCount});for(let[r,s]of Object.entries(t.name==="storage"?e.storageRemediation:{}))Object.hasOwn(n,r)&&(n[r]=s);Object.keys(n).length>0&&(t.details={...t.details,remediation_map:n})}}async function K0(e){if(e.gitWorkspaceRoot===null||e.pendingMergeReceipts.length===0)return[];let t=e.historyDriftCheck.check.details,n=Array.isArray(t.hash_mismatches)?t.hash_mismatches.filter(o=>typeof o=="string"):[],r=new Set([t.missing_streams,t.unreadable_streams,t.chain_mismatches].flatMap(o=>Array.isArray(o)?o:[])),s=new Map;for(let o of e.pendingMergeReceipts){let a=s.get(o.item_id)??[];a.push(o),s.set(o.item_id,a)}let i=[];for(let o of n){if(r.has(o))continue;let a=s.get(o);if(!(!a||a.length===0))try{await $i(o,{dryRun:!0,mergeReceiptProof:{gitWorkspaceRoot:e.gitWorkspaceRoot,receipts:a}},e.global),i.push(o)}catch{}}return[...new Set(i)].sort((o,a)=>o.localeCompare(a))}function z0(e,t){let n=new Set(t);e.warnings=[...e.warnings.filter(r=>r.startsWith("history_drift_hash_mismatch:")?!n.has(r.slice(r.indexOf(":")+1)):!0),...t.map(r=>`history_drift_merge_receipt:${r}`)].sort((r,s)=>r.localeCompare(s)),e.check.details={...e.check.details,merge_receipt_attributed_items:t}}async function dv(e,t={}){let n=I(process.cwd(),e.path);await j(n);let r=Oe(n),{settings:s,warnings:i}=await Uf(n),o=[...new Set(i)],a=D(s,F()),c=t.strictDirectories===!0,d=t.strictExit===!0||t.failOnWarn===!0,l=t.requireMergeDrivers===!0||d,u=iv(t),f=await $0(n,a,c),_=I0(s),h=await y0({checkTelemetry:t.checkTelemetry===!0}),g=await o0(n,s,!!e.noExtensions),y=ov(t),w=[],v=await N0({pmRoot:n,settings:s,typeRegistry:a,skipPolicy:y,itemReadWarnings:w}),S=v,b=io(z(s.schema),v),A=[...(await Nh({pm_root:n,cwd:process.cwd(),mode:"status",interactive:!1,settings:s}).catch(()=>({warnings:["agent_guidance_unreadable:AGENTS.md,CLAUDE.md"]}))).warnings.filter(ae=>ae.startsWith("agent_guidance_")),..._,...oo(b)],x=y.skipDrift?{warnings:[]}:await mi({pmRoot:n,settings:s,itemIds:v.map(ae=>ae.id),commandLabel:"health"}),E=await VO(n,s.history.compact_policy,await BO(n)),$=await es(n,20,t.verboseAuthorEvents===!0),P=qd($),R=P>0?[`history_unknown_author_events:${P}`]:[],T=z(s.schema),q=await ap(n,v,{in_progress_status:T.in_progress_status,status_registry:T,threshold_hours:s.mutation_guard.stale_in_progress_hours}),Pe=av(q.stale),ke=vw(q,{in_progress:T.in_progress_status,open:T.open_status},Le(e)),oe=[...Pe.warnings,...ke.warnings],ze=await jh(n),Fe=ze.warnings,ye=await w0(n),Se=y.skipIntegrity&&!l?{...Nd("integrity"),gitWorkspaceRoot:null,pendingMergeReceipts:[]}:await ZO(n,a.type_to_folder,s.schema,s,l,v),re=y.skipDrift?Nd("history_drift"):await v0({pmRoot:n,items:S,settings:s,typeRegistry:a,itemReadWarnings:w}),Je=[...new Set(w)],pt=await K0({gitWorkspaceRoot:Se.gitWorkspaceRoot,pendingMergeReceipts:Se.pendingMergeReceipts,historyDriftCheck:re,global:e});z0(re,pt),Bw(re,await zw(re,e,n));let st=y.skipVectors?Nd("vectorization"):await R0(n,s,S,u,t.verboseStaleItems===!0),ue=[M0(r,s,o),P0(f,c),F0(A,b),h.check,g.check,D0(v,s,E,$,Pe.scan,ze,ke.details),ye.check,Se.check,re.check,st.check],De=j0({directoryState:f,normalizedSettingsReadWarnings:o,settingWarnings:A,normalizedItemReadWarnings:Je,telemetryCheck:h,extensionCheck:g,historyPolicyWarnings:x.warnings,historySummary:E,authorAttributionWarnings:R,staleInProgressWarnings:oe,provenanceWarnings:Fe,locksCheck:ye,integrityCheck:Se,historyDriftCheck:re,vectorizationCheck:st}),Ee=G0({directoryState:f,normalizedSettingsReadWarnings:o,settingWarnings:A,normalizedItemReadWarnings:Je,telemetryCheck:h,extensionCheck:g,historyPolicyWarnings:x.warnings,historySummary:E,authorAttributionWarnings:R,staleInProgressWarnings:oe,provenanceWarnings:Fe,locksCheck:ye,integrityCheck:Se,historyDriftCheck:re,vectorizationCheck:st});W0({checks:ue,remediationSources:Ee,historyDriftedCount:U0(re),overThresholdCount:E.over_threshold.length,storageRemediation:ke.remediation});let N=De.filter(ae=>!Dd(ae,l)),Tt=cv({warnings:De,checks:ue,remediationSources:Ee,requireMergeDrivers:l}),je=new Set(Tt.filter(ae=>ae.severity==="gate_failing").map(ae=>ae.check)),_r=new Set(Tt.map(ae=>ae.check));for(let ae of ue)ae.ok=!je.has(ae.name),_r.has(ae.name)&&(ae.status="warn");let Re={ok:N.length===0,verdict:{authority:"ok",...d?{strict_exit:!0}:{},...l?{require_merge_drivers:!0}:{},exit_code:d&&N.length>0?m.GENERIC_FAILURE:0},checks:ue,warnings:De,findings:Tt,failed_because:N,generated_at:O()};return Td(Re,t,y.summaryMode)}var KH={buildHierarchyIntegrityWarnings:ev,buildExtensionHealthTriageSummary:tv,buildHealthFindings:cv,buildCapabilityContractMetadata:Oc,buildStaleInProgressHealthSummary:av,buildVectorizationProviderDetails:sv,collectUnknownCapabilityGuidance:Ic,isAdvisoryHealthWarning:Dd,isDirectory:Ud,isExpectedUnmanagedExtension:Md,listItemDocumentPaths:Zw,normalizeEndpointForDisplay:Nt,normalizeExtensionNameForMatch:Xn,parseTelemetryQueue:nv,probeTelemetryEndpointHealth:rv,projectHealthResult:Td,resolveActionableUnknownAuthorEventCount:qd,resolveHealthSkipPolicy:ov,resolveUnknownAuthorEventCount:Gd,resolveVectorRefreshPolicy:iv,selectStaleItemDetail:Fd,summarizeHealthCheckDetails:Ad,summarizeExtensionList:ss,summarizeRecordList:et,summarizeStringList:H,telemetryEnvFlagEnabled:uo,warningCode:jd};function lv(e,t,n){if(!n.has(t.metadata.status))return{reason:"not_terminal"};if(e.length===0)return{reason:"missing_history"};if(!yp(e,t).ok)return{reason:"unverified_history"};let r=af(),s={reason:"no_proven_transition"};for(let[i,o]of e.entries()){let a=n.has(String(r.metadata.status));r=Wf(r,o.patch,i+1,o.op),n.has(String(r.metadata.status))?a||(s=["create","close","cancel","update","update_audit"].includes(o.op)&&Mm(o.ts)?{timestamp:o.ts,source_index:i+1}:{reason:"no_proven_transition"}):s={reason:"no_proven_transition"}}return s}function uv(e){return new Set([...e.terminal_statuses,...[...e.alias_to_id].filter(([,t])=>e.terminal_statuses.has(t)).map(([t])=>t)])}async function mv(e,t,n,r,s){let i=uv(n),o=t.filter(d=>i.has(d.status)&&!d.closed_at),a=[],c=[];for(let d of r?o:[]){let l;try{let u=await Xt(ht(e,d.id),d.id),{body:f,..._}=d;l=lv(u,{metadata:_,body:f},i)}catch{c.push({id:d.id,reason:"unreadable_history"});continue}if("reason"in l){c.push({id:d.id,reason:l.reason});continue}a.push({item_id:d.id,check:"metadata",field:"closed_at",kind:"set_closed_at",value:l.timestamp,gate:"timestamps",command:"pm validate --check-metadata --auto-fix --fix-scope timestamps"})}return{details:{missing_closed_at_count:o.length,missing_closed_at_item_ids:o.slice(0,s).map(d=>d.id),missing_closed_at_item_ids_truncated:o.length>s,closure_history_inspected:r,closure_timestamp_derivable_count:a.length,closure_timestamp_residual_count:c.length,closure_timestamp_residual:c.slice(0,s),closure_timestamp_residual_truncated:c.length>s,...o.length>0?{closure_timestamp_fix_hint:"pm validate --check-metadata --auto-fix --fix-scope timestamps --dry-run"}:{}},fixes:a,warnings:o.length>0?[`validate_metadata_missing_closed_at:${o.length}`]:[]}}async function fv(e,t){let n=I(process.cwd(),t.path),r=await C(n),s=z(r.schema);await he({pmRoot:n,settings:r,id:e.item_id,op:"update",author:G(t.author,r.author_default),message:"Backfill closed_at from verified lifecycle history",skipNoop:!0,async mutate(i){if(i.metadata.closed_at)return{changedFields:[]};let o=await Xt(ht(n,i.metadata.id),i.metadata.id),a=uv(s),c=lv(o,i,a);if(!("timestamp"in c)||c.timestamp!==e.value)throw new p("Closure timestamp evidence changed or cannot be verified; rerun the timestamp repair preview.",m.GENERIC_FAILURE);return i.metadata.closed_at=c.timestamp,{changedFields:["closed_at"]}}})}function B0(e,t){return e==="malformed"||t==="malformed"?"malformed":e==="moved"||t==="moved"?"moved":"deleted"}function pv(e){return`${e.item_id} ${e.link_kind}`}function _v(e,t){let n=new Map;for(let r of e){let s=n.get(r.path);s?(s.classification=B0(s.classification,r.classification),s.owners.set(pv(r),r)):n.set(r.path,{classification:r.classification,owners:new Map([[pv(r),r]])})}return[...n.entries()].sort(([r],[s])=>r.localeCompare(s)).map(([r,s])=>({path:r,classification:s.classification,items:[...s.owners.values()].map(i=>{let o=t(i.item_id);return{id:i.item_id,type:o?.type??"Unknown",title:o?.title??"",status:o?.status??"",field:i.link_kind}}).sort((i,o)=>{let a=i.id.localeCompare(o.id);return a!==0?a:i.field.localeCompare(o.field)})}))}function hv(e,t,n,r,s=40){let i=s===1/0?1/0:Number.isFinite(s)?Math.max(0,Math.floor(s)):40,o=new Map(t.map(d=>[d.path,d])),a={missing_linked_path_rows_count:0,missing_linked_path_rows:[],missing_linked_path_rows_truncated:!1,missing_linked_links_count:0,active_missing_linked_links_count:0,legacy_closed_missing_linked_links_count:0,legacy_terminal_missing_linked_links_count:0,active_missing_linked_paths_count:0},c=_v(e,n).map(d=>{let l=[],u=[];for(let _ of d.items){let h=ce(_.status,r)??_.status;r.terminal_statuses.has(h)?(u.push(_),h===r.close_status&&(a.legacy_closed_missing_linked_links_count+=1)):l.push(_)}a.missing_linked_links_count+=d.items.length,a.active_missing_linked_links_count+=l.length,a.legacy_terminal_missing_linked_links_count+=u.length,l.length>0&&(a.active_missing_linked_paths_count+=1);let f=o.get(d.path);return{...d,candidates:f?.candidates??[],candidates_truncated:f?.candidates_truncated??!1,link_count:d.items.length,active_link_count:l.length,items:[...l,...u].slice(0,i),items_truncated:d.items.length>i}});return c.sort((d,l)=>+(l.active_link_count>0)-+(d.active_link_count>0)||d.path.localeCompare(l.path)),a.missing_linked_path_rows_count=c.length,a.missing_linked_path_rows=c.slice(0,i),a.missing_linked_path_rows_truncated=c.length>i,a}import Qn from"node:fs/promises";import Zn from"node:path";async function H0(e,t){let n=[...new Set(Object.values(t))],r=[];return await Promise.all(n.map(async s=>{let i;try{i=await Qn.readdir(Zn.join(e,s))}catch{return}for(let o of i)for(let a of Ht)if(o.toLowerCase().endsWith(a)){r.push({relativePath:`${s}/${o}`,id:o.slice(0,-a.length)});break}})),r.sort((s,i)=>s.relativePath.localeCompare(i.relativePath))}function V0(e,t){let{id:n,relativePath:r,liveItemIds:s,out:i}=e,o=Ln(t);if(o){i.conflictMarkers.push({id:n,path:r,line:o.line,detail:`unresolved merge conflict marker ${o.marker}`});return}let a=Y0(e,t);a!==null&&(a.op==="delete"&&s.has(n)&&i.resurrected.push({id:n,deleted_at:typeof a.ts=="string"?a.ts:"",deleted_by:typeof a.author=="string"?a.author:""}),a.op==="history_repair"&&Array.isArray(a.patch)&&a.patch.length>0&&(i.repairReconciliations+=1))}function Y0(e,t){let{id:n,relativePath:r,out:s}=e,i=null,o=!1,a=t.split(/\r?\n/).map((c,d)=>({content:c.trim(),number:d+1})).filter(c=>c.content.length>0);for(let c of a){try{let d=JSON.parse(c.content);if(typeof d!="object"||d===null||Array.isArray(d))throw new TypeError("history entry must be an object");i=d}catch{return s.unparseable.push({id:n,path:r,line:c.number,detail:"history line is not a valid JSON object"}),null}if(i.op==="create"){if(o)return s.unparseable.push({id:n,path:r,line:c.number,detail:"duplicate item identity: more than one create event in one history stream"}),null;o=!0}}return i}function Wd(e,t){let n=typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"?t.code:"UNKNOWN";return`${e} could not be read (error code: ${n})`}async function J0(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},r;try{r=await Qn.readdir(Zn.join(e,"history"))}catch{return n}for(let s of r.sort((i,o)=>i.localeCompare(o))){if(!s.endsWith(".jsonl"))continue;n.scanned+=1;let i;try{i=await Qn.readFile(Zn.join(e,"history",s),"utf8")}catch(o){n.unparseable.push({id:s.slice(0,-6),path:`history/${s}`,detail:Wd("history stream",o)});continue}V0({id:s.slice(0,-6),relativePath:`history/${s}`,liveItemIds:t,out:n},i)}return n}function gv(e){let t=Ln(e);if(t)return`unresolved merge conflict marker ${t.marker} at line ${t.line}`;try{return JSON.parse(e),null}catch(n){return`invalid JSON (${String(n)})`}}async function X0(e){let t=[],n=0,r=null;try{r=await Q(Oe(e))}catch(i){n+=1,t.push({path:"settings.json",detail:Wd("configuration file",i)})}if(r!==null){n+=1;let i=gv(r);i!==null&&t.push({path:"settings.json",detail:i})}let s;try{s=await Qn.readdir(Zn.join(e,"schema"))}catch{return{scanned:n,unparseable:t}}for(let i of s.sort((o,a)=>o.localeCompare(a))){if(!i.endsWith(".json"))continue;n+=1;let o;try{o=await Qn.readFile(Zn.join(e,"schema",i),"utf8")}catch(c){t.push({path:`schema/${i}`,detail:Wd("configuration file",c)});continue}let a=gv(o);a!==null&&t.push({path:`schema/${i}`,detail:a})}return{scanned:n,unparseable:t}}async function yv(e,t,n,r={}){let s=await H0(e,n),i=new Set(s.map(u=>u.id)),o=new Map;for(let u of s){let f=o.get(u.id);f===void 0?o.set(u.id,[u.relativePath]):f.push(u.relativePath)}let a=[...o.entries()].filter(([,u])=>u.length>1).map(([u,f])=>({id:u,paths:[...f].sort((_,h)=>_.localeCompare(h))})).sort((u,f)=>u.id.localeCompare(f.id)),c=(await Promise.all(s.map(async u=>{if(!t.has(u.id))return{path:u.relativePath,id:u.id};try{let f=Zn.join(e,u.relativePath);return ii(await Qn.readFile(f,"utf8"),{format:f.toLowerCase().endsWith(".md")?"json_markdown":"toon",schema:r.schema,extensionFieldNames:r.extensionFieldNames}),null}catch{return{path:u.relativePath,id:u.id}}}))).filter(u=>u!==null),d=await J0(e,i),l=await X0(e);return{item_files_on_disk:s.length,item_ids_on_disk:i.size,parsed_items:t.size,unreadable_item_files:c,duplicate_item_ids:a,history_streams_scanned:d.scanned,history_conflict_marker_streams:d.conflictMarkers,history_unparseable_streams:d.unparseable,resurrected_items:d.resurrected,history_repair_reconciliations:d.repairReconciliations,config_files_scanned:l.scanned,unparseable_config_files:l.unparseable}}import{readFileSync as Q0}from"node:fs";import mo from"node:path";var Z0=new Set(["get","history","restore","update","close","delete","append","claim","release","comments","notes","learnings","files","docs","deps","test"]),Bd=new Set(["--pm-path","--path","--author","--expect-hash"]),eL={get:new Set(["--depth","--fields","--tree-depth","--tree_depth","--at","--format"]),history:new Set(["--limit","--field","--format"]),restore:new Set(["--message"]),update:new Set(["--title","-t","--description","-d","--body","-b","--status","-s","--close-reason","--close_reason","--priority","-p","--type","--tags","--add-tags","--add_tags","--remove-tags","--remove_tags","--deadline","--estimated-minutes","--estimate","--estimated_minutes","--acceptance-criteria","--ac","--acceptance_criteria","--definition-of-ready","--definition_of_ready","--order","--rank","--goal","--objective","--value","--impact","--outcome","--why-now","--why_now","--message","--assignee","--parent","--reviewer","--risk","--confidence","--sprint","--release","--blocked-by","--blocked_by","--blocked-reason","--blocked_reason","--unblock-note","--unblock_note","--reporter","--severity","--environment","--repro-steps","--repro_steps","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual","--affected-version","--affected_version","--fixed-version","--fixed_version","--component","--regression","--customer-impact","--customer_impact","--dep","--dep-remove","--dep_remove","--comment","--note","--learning","--file","--test","--doc","--reminder","--event","--type-option","--type_option","--field","--unset","--body-file"]),close:new Set(["--reason","-r","--close-reason","--duplicate-of","-d","--message","-m","--validate-close","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual"]),delete:new Set(["--message"]),append:new Set(["--body","--text","--message"]),claim:new Set(["--assignee","--message","--type","--tag","--priority","--assignee-filter","--parent","--sprint","--release","--max-attempts"]),release:new Set(["--assignee","--message"]),comments:new Set(["--add","--body","--comment","--file","--edit","--delete","--limit","--message"]),notes:new Set(["--add","--file","--edit","--delete","--limit","--message"]),learnings:new Set(["--add","--file","--edit","--delete","--limit","--message"]),files:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),docs:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),deps:new Set(["--format","--max-depth","--collapse","--node-limit","--edge-limit","--token-budget","--cursor","--direction","--kind"]),test:new Set(["--add","--add-json","--remove","--match","--only-index","--timeout","--env-set","--env-clear","--pm-context","--message"])},tL=new Set(["-p","--package"]),nL=new Set(["-c","--call"]),Hd=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),Vd=new Set(["-C","--prefix","--userconfig","--cache"]),wv=new Set(["--cwd"]),vv=new Set(["--cwd"]),rL=new Set(["exec","x"]),kv=new Set(["run","run-script"]),bv=new Set(["-C","--dir","--cwd","-w","--workspace","--filter"]);function dn(e){return e.split(/&&|\|\||\||;/).map(t=>t.trim()).filter(t=>t.length>0)}function _o(e,t=process.cwd()){let n=ho(e.split(" ").filter(o=>o.length>0));if(n.length===0)return null;let[r,...s]=n;if(fo(r)||po(r,t))return s;if(r==="node"&&s[0]&&po(s[0],t))return s.slice(1);let i=r==="npx"||r==="bunx"?ln(s):r==="pnpm"?go(s):r==="npm"?yo(s):null;return i&&(fo(i.command)||xv(i.command))?i.args:null}var Yd=(e,t="pm")=>{let n=t.trim().toLowerCase(),r=n.length;for(;r>0&&n[r-1]==="-";)r-=1;let s=n.slice(0,r);if(s.length===0)return[];let i=e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase(),o=new Set;for(let a of dn(i)){let c=_o(a),d=c?Jd(c):null,l=d&&Z0.has(d.subcommand)?iL(d.remaining,eL[d.subcommand]):void 0,u=l?.trim().toLowerCase();u?.startsWith(`${s}-`)===!0&&u.length>s.length+1&&o.add(l)}return[...o].sort((a,c)=>a.localeCompare(c))};function ho(e){let t=0;for(e[t]==="env"&&(t+=1);t<e.length;){let n=e[t];if(/^(?:[a-z_][a-z0-9_]*|\$env:[a-z_][a-z0-9_]*)=.*/.test(n)){t+=1;continue}break}return e.slice(t)}function zd(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(Bd.has(n)){t+=2;continue}t+=1;continue}return n}}function fo(e){return e==="pm"||e==="pm.cmd"||e==="pm.exe"||e.endsWith("/pm")||e.endsWith("/pm.cmd")||e.endsWith("/pm.exe")}function sL(e){let t=e.trim();if(!t.startsWith("@")){let s=t.indexOf("@");return s===-1?t:t.slice(0,s)}let n=t.indexOf("/");if(n===-1)return t;let r=t.indexOf("@",n+1);return r===-1?t:t.slice(0,r)}function xv(e){let t=sL(e);return t==="pm-cli"||t.endsWith("/pm-cli")||e==="pm-cli"||e.endsWith("/pm-cli")}function po(e,t=process.cwd()){let n=e.replaceAll("\\","/");if(n!=="dist/cli.js"&&n!=="./dist/cli.js"&&!n.endsWith("/dist/cli.js"))return!1;let r=mo.resolve(t,e);try{return JSON.parse(Q0(mo.join(mo.dirname(mo.dirname(r)),"package.json"),"utf8")).name==="@unbrained/pm-cli"}catch{return!1}}function ln(e){let t=0;for(;t<e.length;){let r=e[t];if(r==="--"){t+=1;break}if(!r.startsWith("-"))break;let s=/^(?:-c|--call)=(.*)$/.exec(r);if(s){let i=s[1];return i?{command:i,args:e.slice(t+1)}:null}if(nL.has(r)){t+=1;break}t+=tL.has(r)&&!r.includes("=")?2:1}let n=e[t];return n?{command:n,args:e.slice(t+1)}:null}function Ut(e,t){let n=0;for(;n<e.length;){let r=e[n];if(r==="--"){n+=1;continue}if(r.startsWith("-")){if(r.includes("=")){n+=1;continue}if(t.has(r)){n+=2;continue}n+=1;continue}return{subcommand:r,args:e.slice(n+1)}}return null}function go(e){let t=Ut(e,Hd);return t?.subcommand!=="dlx"?null:ln(t.args)}function yo(e){let t=Ut(e,Vd);return!t||!rL.has(t.subcommand)?null:ln(t.args)}function Jd(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(Bd.has(n)){t+=2;continue}t+=1;continue}return{subcommand:n,remaining:e.slice(t+1)}}return null}function iL(e,t=new Set){for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="--")return e[n+1];if(!r.startsWith("-"))return r;!r.includes("=")&&(Bd.has(r)||t.has(r))&&(n+=1)}}function Kd(e){return!e||!fo(e.command)&&!xv(e.command)?!1:zd(e.args)==="test-all"}var Xd=new Map([...["sh","bash","dash","zsh"].map(e=>[e,/^(?:-c|-[a-z]*c[a-z]*)$/u]),...["cmd","cmd.exe"].map(e=>[e,/^\/[ck]$/u]),...["powershell","powershell.exe","pwsh","pwsh.exe"].map(e=>[e,/^-(?:c|command)$/u])]),oL=new Set(["npx","bunx"]);function Qd(e){let t=e.split(" ").filter(o=>o.length>0),n=ho(t);if(n.length===0)return!1;let[r,...s]=n,i=Xd.get(r);if(i){let o=s.findIndex(a=>i.test(a));return o>=0?Qd(s.slice(o+1).join(" ")):!1}return fo(r)||po(r)?zd(s)==="test-all":r==="node"&&s.length>0&&po(s[0])?zd(s.slice(1))==="test-all":oL.has(r)?Kd(ln(s)):r==="pnpm"?Kd(go(s)):r==="npm"?Kd(yo(s)):!1}function Zd(e){let t=er(e);return dn(t).some(n=>Qd(n))}function os(e){if(Zd(e))throw new p('Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.',m.USAGE)}function er(e){return e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase()}import{execFile as aL}from"node:child_process";import{readFile as cL}from"node:fs/promises";import Ev from"node:path";import{promisify as dL}from"node:util";var lL=dL(aL),el=1,uL="linked-test-trust.json";function tl(e){return Ev.join(km(e),uL)}function Sv(){return{version:el,acknowledged:{}}}async function nl(e){try{let t=JSON.parse(await cL(tl(e),"utf8"));return t.version!==el||typeof t.acknowledged!="object"||t.acknowledged===null||Array.isArray(t.acknowledged)?Sv():{version:el,acknowledged:t.acknowledged}}catch{return Sv()}}async function cs(e=process.cwd()){let t=process.env.GITHUB_HEAD_REF?.trim()||process.env.GITHUB_REF_NAME?.trim();if(t&&t!=="merge")return t;try{let{stdout:n}=await lL("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),r=n.trim();return r.length===0?void 0:r}catch{return}}function ds(e=process.cwd()){return process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||e}function mL(e){return e===null||typeof e!="object"?!1:typeof e.author=="string"&&e.author.trim().length>0&&typeof e.created_at=="string"&&Nm(e.created_at)&&(e.source_kind==="local_mutation"||e.source_kind==="merge_union")}function as(e,t){return{...e?{source_ref:e}:{},...t?{current_source_ref:t}:{}}}function fL(e,t,n,r){return e?.map(s=>s.command&&!s.provenance?{...s,provenance:{author:t,created_at:n,source_kind:"local_mutation",...r?{source_ref:r}:{}}}:s)}async function tr(e,t,n){if(!e||e.length===0)return e;for(let s of e)vr(s);let r=ds();return fL(e,t,n,await cs(r))}function Av(e){return Ju(Z({command:e.command??null,path:e.path??null,scope:e.scope,pm_context_mode:e.pm_context_mode??null,workspace_context_mode:e.workspace_context_mode??null,env_set:e.env_set??null,env_clear:e.env_clear??null,shared_host_safe:e.shared_host_safe??null,provenance:e.provenance??null,provenance_invalid:e.provenance_invalid??null}))}async function rl(e,t,n){let r=await nl(e);return Cv(t,n,r)}function Cv(e,t,n){let r=Av(e),s=e.provenance?.source_ref;if(e.provenance===void 0&&e.provenance_invalid!==!0)return{fingerprint:r,trusted:!0,reason:"legacy"};let i=Object.hasOwn(n.acknowledged,r);return e.provenance_invalid===!0||!mL(e.provenance)?i?{fingerprint:r,trusted:!0,reason:"acknowledged",...as(void 0,t)}:{fingerprint:r,trusted:!1,reason:"invalid_provenance",...as(void 0,t)}:e.provenance.source_kind==="local_mutation"&&s===void 0?{fingerprint:r,trusted:!0,reason:"local_mutation",...as(void 0,t)}:e.provenance.source_kind==="local_mutation"&&s!==void 0&&s===t?{fingerprint:r,trusted:!0,reason:"local_source_ref",source_ref:s,current_source_ref:t}:i?{fingerprint:r,trusted:!0,reason:"acknowledged",...as(s,t)}:{fingerprint:r,trusted:!1,reason:"foreign_source_ref",...as(s,t)}}async function Tv(e,t,n){let r=await nl(e);return t.map(s=>Cv(s,n,r))}async function Rv(e,t,n){let r=await nl(e),s=t.filter(i=>typeof i.command=="string"&&i.command.length>0).map(Av);for(let i of s)r.acknowledged[i]={acknowledged_at:n};return await Rt(Ev.dirname(tl(e))),await Ge(tl(e),`${JSON.stringify(r,null,2)}
|
|
9
|
+
`),{acknowledged:s.length,fingerprints:s}}import yl from"node:fs/promises";import{realpathSync as xL}from"node:fs";import{execFile as SL}from"node:child_process";import Me from"node:path";import{promisify as EL}from"node:util";var pL=["metadata","resolution"],sl=["metadata","resolution","estimates","timestamps","lifecycle"],_L="completed";function il(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function Iv(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function Ov(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let r=Iv(n.close_reason)??_L;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:r,command:`pm update ${n.id} --resolution ${il(r)}`,gate:"resolution"})}return t}function Lv(e){let t=[];for(let n of e){let r=Iv(n.resolution);r!==void 0&&t.push({item_id:n.id,check:"metadata",field:"close_reason",kind:"set_close_reason",value:r,command:`pm update ${n.id} --close-reason ${il(r)}`,gate:"metadata"})}return t}function $v(e,t){return e.map(n=>{let r=jf(n.type,t);return{item_id:n.id,check:"metadata",field:"estimated_minutes",kind:"set_estimate",value:String(r),command:`pm update ${n.id} --estimate ${r}`,gate:"estimates"}})}function Nv(e){return e.map(t=>t.grandparent_id!==void 0&&t.grandparent_active===!0?{item_id:t.id,check:"lifecycle",field:"parent",kind:"reparent",parent_id:t.grandparent_id,command:`pm update ${t.id} --parent ${t.grandparent_id}`,gate:"lifecycle"}:{item_id:t.id,check:"lifecycle",field:"parent",kind:"unset_parent",command:`pm update ${t.id} --unset parent`,gate:"lifecycle"})}function Mv(e){let t=[];for(let n of e){if(n.classification!=="deleted")continue;let r=n.link_kind==="files"?"files":"docs";t.push({item_id:n.item_id,check:"files",field:n.link_kind,kind:n.link_kind==="files"?"prune_file_link":"prune_doc_link",path:n.path,command:`pm ${r} ${n.item_id} --remove ${il(n.path)}`})}return t}function Pv(e){let t=(e??[]).flatMap(r=>r.split(",")).map(r=>r.trim()).filter(r=>r.length>0);if(t.length===0){if(e!==void 0&&e.length>0)throw new p(`--fix-scope values must not be empty. Supported values: ${sl.join(", ")}.`,m.USAGE);return new Set(pL)}let n=new Set;for(let r of t){let s=r.toLowerCase().replaceAll("-","_");if(sl.includes(s)){n.add(s);continue}throw new p(`Unknown --fix-scope value "${r}". Supported values: ${sl.join(", ")}.`,m.USAGE)}return n}function Fv(e,t){let n=[],r=[];for(let s of e)s.gate!==void 0&&!t.has(s.gate)?r.push(s):n.push(s);return{applicable:n,gated:r}}function ls(e){return{item_id:e.item_id,check:e.check,field:e.field,command:e.command,...e.gate!==void 0?{gate:e.gate}:{}}}var hL=/^([A-Z][A-Z0-9]*-\d+)\b/iu;function gL(e,t={}){if(typeof e!="string")return null;let n=e.trim();if(n.length===0)return null;let r=hL.exec(n);if(!r)return null;let s=r[1],i=s.toUpperCase(),o=s.slice(0,s.lastIndexOf("-")),a=new Set((t.configuredPrefixes??[]).map(f=>f.trim().replace(/-+$/u,"").toUpperCase())),c=n.slice(s.length),d=t.evidenceText?.toUpperCase()??"",l=d.includes(`ISSUE CODE: ${i}`)||d.includes(`ISSUE CODE \`${i}\``)||d.includes(`\`${i}\``)||d.includes(`[${i}]`);return o===o.toUpperCase()||/^\s*(?::|—|–|\])/u.test(c)||a.has(o.toUpperCase())||l?i:null}function Dv(e){return typeof e=="string"&&e.trim().length>0}function yL(e){let t=new Set(e.map(a=>a.id.toLowerCase())),n=new Map,r=new Map;for(let a of e){let c=a.id.toLowerCase(),d=new Set([...a.parent===null?[]:[a.parent.toLowerCase()],...a.derivations].filter(l=>l!==c&&t.has(l)));n.set(c,d);for(let l of d){let u=r.get(l)??[];u.push(c),r.set(l,u)}}let i=[...[...n].filter(([,a])=>a.size===0).map(([a])=>a)],o=new Set;for(let a=0;a<i.length;a+=1)for(let c of r.get(i[a])??[]){let d=n.get(c);d.delete(i[a]),d.size===0&&(o.add(c),i.push(c))}return e.filter(a=>!o.has(a.id.toLowerCase()))}function jv(e,t={}){let n=new Map;for(let s of e){if(typeof s.title!="string"||Dv(s.duplicate_of))continue;let i=gL(s.title,{...t,evidenceText:s.body});if(i===null)continue;let o=n.get(i);o||(o=[],n.set(i,o)),o.some(a=>a.id===s.id)||o.push({id:s.id,title:s.title,parent:Dv(s.parent)?s.parent.trim():null,derivations:(s.dependencies??[]).filter(a=>["discovered_from","supersedes","incident_from"].includes(a.kind)).map(a=>a.id.trim().toLowerCase()).filter(a=>a!==s.id.toLowerCase())})}let r=[];for(let[s,i]of n){if(i.length<2)continue;let o=yL(i);if(o.length<2)continue;let a=[...o].sort((c,d)=>c.id.localeCompare(d.id));r.push({code:s,count:a.length,ids:a.map(c=>c.id),titles:a.map(c=>c.title)})}return r.sort((s,i)=>s.code.localeCompare(i.code))}function Uv(e){let t=new Map;for(let r of e){let s=t.get(r.item_type);s||(s=new Map,t.set(r.item_type,s)),s.set(r.field,(s.get(r.field)??0)+1)}let n={};for(let r of[...t.keys()].sort((s,i)=>s.localeCompare(i))){let s=t.get(r),i={};for(let o of[...s.keys()].sort((a,c)=>a.localeCompare(c)))i[o]=s.get(o);n[r]=i}return n}function Gv(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function qv(e,t,n=3){let r=Number.isFinite(n)&&n>=1?Math.floor(n):3,s=new Map;for(let i of t){let o=Gv(i);if(o.length===0)continue;let a=s.get(o);a?a.push(i):s.set(o,[i])}return e.map(i=>{if(i.includes(",")||i.replace(/^[a-z]:[\\/]/i,"").includes(":"))return{path:i,classification:"malformed",candidates:[],candidates_truncated:!1};let o=(s.get(Gv(i))??[]).filter(a=>a!==i).sort((a,c)=>a.localeCompare(c));return o.length===0?{path:i,classification:"deleted",candidates:[],candidates_truncated:!1}:{path:i,classification:"moved",candidates:o.slice(0,r),candidates_truncated:o.length>r}})}function Wv(e){return e.map(t=>t.classification==="moved"?`${t.path}:moved:${t.candidates[0]}`:`${t.path}:${t.classification}`)}async function wo(e){return e.includeBody?wt(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema,{forceSourceScan:!0}):vi(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema)}var wL=5;async function vL(e,t){let n=t.hashMismatches.filter(i=>i!==Qt);if(n.length===0)return;let r=await C(e),s=D(r,F());for(let i of n){let o=await oi(e,i,r.locks.ttl_seconds,"history-drift-read",!1,!0,r.locks.wait_ms);try{let a=await Y(e,i,r.id_prefix,r.item_format,s.type_to_folder);if(a===null)throw new p(`Item ${i} not found`,m.NOT_FOUND,{code:"item_not_found",required:"Repeat validation after writers finish; each item-hash discrepancy requires readable canonical source."});let{document:c}=await fe(a,{schema:r.schema});if(c.metadata.id!==i)throw new p(`Item identity changed while validating ${i}`,m.CONFLICT,{code:"item_identity_conflict",required:"Restore the canonical item identity and validate storage integrity before retrying history validation."});let d=await Dh(e,{...c.metadata,body:c.body});for(let u of["missingStreams","unreadableStreams","hashMismatches","chainMismatches","versionSkews","driftedItems"])t[u]=[...t[u].filter(f=>f!==i),...d[u].filter(f=>f===i)].sort((f,_)=>f.localeCompare(_));let l=[...(t.identityDiscontinuities??[]).filter(u=>u.item_id!==i),...(d.identityDiscontinuities??[]).filter(u=>u.item_id===i)];l.length>0?t.identityDiscontinuities=l:delete t.identityDiscontinuities}finally{await o()}}}async function vo(e,t,n){let r=await Ur(e,t);await vL(e,r);let i=[["validate_history_drift_missing_streams",r.missingStreams.length],["validate_history_drift_unreadable_streams",r.unreadableStreams.length],["validate_history_drift_hash_mismatches",r.hashMismatches.length],["validate_history_drift_chain_mismatches",r.chainMismatches.length],["validate_history_drift_version_skews",r.versionSkews.length],["validate_history_drift_workspace_state_mismatches",r.workspaceStateMismatches.length],["validate_history_drift_workspace_state_missing",r.workspaceStateMissing.length],["validate_history_drift_workspace_state_unreadable",r.workspaceStateUnreadable.length]].filter(([,d])=>d>0).map(([d,l])=>`${d}:${l}`),o=n?Number.POSITIVE_INFINITY:wL,a=r.driftedItems.slice(0,o),c=r.identityDiscontinuities??[];return{check:{name:"history_drift",status:c.length>0?"error":i.length===0?"ok":"warn",ok:c.length===0&&i.length===0,details:{identity_discontinuities:c.slice(0,o),identity_discontinuities_count:c.length,identity_discontinuities_truncated:c.length>o,checked_items:t.length,drifted_items_count:r.driftedItems.length,drifted_items:a,drifted_items_truncated:a.length<r.driftedItems.length,counts:{missing_streams:r.missingStreams.length,unreadable_streams:r.unreadableStreams.length,hash_mismatches:r.hashMismatches.length,chain_mismatches:r.chainMismatches.length,version_skews:r.versionSkews.length,workspace_state_mismatches:r.workspaceStateMismatches.length,workspace_state_missing:r.workspaceStateMissing.length,workspace_state_unreadable:r.workspaceStateUnreadable.length},workspace_state_mismatches:r.workspaceStateMismatches,workspace_state_missing:r.workspaceStateMissing,workspace_state_unreadable:r.workspaceStateUnreadable,version_skews:r.versionSkews.slice(0,o)}},warnings:i}}function ol(e){let t=0,n=new Map,r=new Map,s=[],i=new Set,o=[],a=l=>{n.set(l,t),r.set(l,t),t+=1,s.push(l),i.add(l);for(let f of e.get(l)??[])n.has(f)?i.has(f)&&r.set(l,Math.min(r.get(l),n.get(f))):(a(f),r.set(l,Math.min(r.get(l),r.get(f))));if(r.get(l)!==n.get(l))return;let u=[];for(;s.length>0;){let f=s.pop();if(i.delete(f),u.push(f),f===l)break}u.sort((f,_)=>f.localeCompare(_)),o.push(u)},c=[...e.keys()].sort((l,u)=>l.localeCompare(u));for(let l of c)n.has(l)||a(l);return o.filter(l=>{if(l.length>1)return!0;let u=l[0];return(e.get(u)??[]).includes(u)}).sort((l,u)=>l[0].localeCompare(u[0])||l.length-u.length||l.join(",").localeCompare(u.join(",")))}function ko(e,t){let n=e[0];if(e.length===1)return[n,n];let r=new Set(e),s=[n],i=new Set([n]),o=a=>{for(let c of(t.get(a)??[]).filter(d=>r.has(d))){if(c===n&&s.length>1)return s.push(n),!0;if(!i.has(c)){if(i.add(c),s.push(c),o(c))return!0;s.pop(),i.delete(c)}}return!1};return o(n)?[...s]:[...e,n]}function kL(e,t){if(typeof e!="string")return;let n=e.trim().toLowerCase();return n.length>0?t.get(n):void 0}function bL(e,t,n,r){for(let s of e.dependencies??[]){if(typeof s!="object"||s===null||typeof s.id!="string")continue;let i=r.resolve(s.kind);if(!i?.hierarchy)continue;let o=n.get(s.id.toLowerCase());o&&(i.hierarchyDirection==="source_parent"?t.get(o).push(e.id):t.get(e.id).push(o))}}function al(e,t=de()){let n=new Map(e.map(s=>[s.id.toLowerCase(),s.id])),r=new Map(e.map(s=>[s.id,[]]));for(let s of[...e].sort((i,o)=>i.id.localeCompare(o.id))){let i=r.get(s.id),o=kL(s.parent,n);o&&i.push(o),bL(s,r,n,t)}for(let[s,i]of r)r.set(s,[...new Set(i)].sort());return r}function cl(e,t,n=de()){let r=Oi(e,o=>t?It(o,t):o==="closed"||o==="canceled",n),s=al(e,n),i=r.cycles.map(o=>o.item_ids);return{cycle_count:i.length,active_cycle_count:r.cycles.filter(o=>!o.legacy_terminal).length,legacy_cycle_count:r.cycles.filter(o=>o.legacy_terminal).length,cycle_item_ids:[...new Set(i.flat())].sort(),cycle_sample_paths:i.map(o=>ko(o,s).join("->")),cardinality_violation_count:r.cardinality_violations.length,active_cardinality_violation_count:r.cardinality_violations.filter(o=>!o.legacy_terminal).length,legacy_cardinality_violation_count:r.cardinality_violations.filter(o=>o.legacy_terminal).length,cardinality_violation_rows:r.cardinality_violations.map(o=>`${o.child_id}:${o.parent_ids.join(",")}:${o.legacy_terminal?"legacy":"active"}`),parent_divergence_count:r.divergences.length,active_parent_divergence_count:r.divergences.filter(o=>!o.legacy_terminal).length,legacy_parent_divergence_count:r.divergences.filter(o=>o.legacy_terminal).length,parent_divergence_rows:r.divergences.map(o=>`${o.child_id}:scalar=${o.scalar_parent_id}:dependencies=${o.dependency_parent_ids.join(",")}:${o.legacy_terminal?"legacy":"active"}`)}}function Gt(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/^\/+/,"")}function dl(e){return Gt(e).replace(/\/+$/,"")}function tt(e){let t=ie(e);if(!t)return;let n=t.toLowerCase();if(!(n==="none"||n==="null"||n==="n/a"||n==="na"))return t}function ll(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length>120?`${t.slice(0,117)}...`:t}var AL=["src","tests","docs"],CL=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],TL=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),RL=["resolution","expected_result","actual_result"],IL=["default","tracked-all","tracked-all-strict"],Kv=["core","strict","custom"],So=["off","warn","error"],fl=["author","acceptance_criteria","estimated_minutes","close_reason"],Hv=[...fl,"reviewer","risk","confidence","sprint","release"],pl=Array.from(new Set(Hv)),OL={author:"author",acceptance_criteria:"acceptance_criteria","acceptance-criteria":"acceptance_criteria",estimated_minutes:"estimated_minutes","estimated-minutes":"estimated_minutes",estimate:"estimated_minutes",close_reason:"close_reason","close-reason":"close_reason",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release"},LL={author:"validate_metadata_missing_author",acceptance_criteria:"validate_metadata_missing_acceptance_criteria",estimated_minutes:"validate_metadata_missing_estimate",close_reason:"validate_metadata_missing_close_reason",reviewer:"validate_metadata_missing_reviewer",risk:"validate_metadata_missing_risk",confidence:"validate_metadata_missing_confidence",sprint:"validate_metadata_missing_sprint",release:"validate_metadata_missing_release"},$L={author:"missing_author",acceptance_criteria:"missing_acceptance_criteria",estimated_minutes:"missing_estimated_minutes",close_reason:"closed_missing_close_reason",reviewer:"missing_reviewer",risk:"missing_risk",confidence:"missing_confidence",sprint:"missing_sprint",release:"missing_release"},NL={author:"missing_author_item_ids",acceptance_criteria:"missing_acceptance_criteria_item_ids",estimated_minutes:"missing_estimated_minutes_item_ids",close_reason:"closed_missing_close_reason_item_ids",reviewer:"missing_reviewer_item_ids",risk:"missing_risk_item_ids",confidence:"missing_confidence_item_ids",sprint:"missing_sprint_item_ids",release:"missing_release_item_ids"},ML={author:"missing_author_truncated",acceptance_criteria:"missing_acceptance_criteria_truncated",estimated_minutes:"missing_estimated_minutes_truncated",close_reason:"closed_missing_close_reason_truncated",reviewer:"missing_reviewer_truncated",risk:"missing_risk_truncated",confidence:"missing_confidence_truncated",sprint:"missing_sprint_truncated",release:"missing_release_truncated"},PL=32*1024*1024,FL=1e4,_l=40,nt=5,DL=4096,jL=255,UL=EL(SL);function Vv(e){let t={};for(let[n,r]of Object.entries(e))Array.isArray(r)||r===!1&&n.endsWith("_truncated")||(t[n]=typeof r=="object"&&r!==null?Vv(r):r);return t}function GL(e){return{...e,checks:e.checks.map(t=>({...t,details:Vv(t.details)})),...e.fixes?{fixes:{mode:e.fixes.mode,auto_fix:e.fixes.auto_fix,prune_missing:e.fixes.prune_missing,planned_count:e.fixes.planned_count,applied_count:e.fixes.applied_count,gated_count:e.fixes.gated_count,failed_count:e.fixes.failed_count}}:{}}}function Ao(e,t){return ce(e,t)??e}function us(e,t){return t.terminal_statuses.has(Ao(e,t))}function qt(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function bo(e,t){return e.length!==t.length?!1:e.every((n,r)=>n===t[r])}function qL(e){let t=qt(Yu),n={blocked_reason:qt(Ms.blocked_reason),resolution:qt(Ms.resolution),actual_result:qt(Ms.actual_result)},r=qt(e.validation.lifecycle_stale_blocker_reason_patterns),s={blocked_reason:qt(e.validation.lifecycle_closure_like_blocked_reason_patterns),resolution:qt(e.validation.lifecycle_closure_like_resolution_patterns),actual_result:qt(e.validation.lifecycle_closure_like_actual_result_patterns)};return{stale_blocker_reason_patterns:r,stale_blocker_reason_pattern_source:bo(r,t)?"default":"settings",closure_like_metadata_field_patterns:s,closure_like_metadata_field_pattern_sources:{blocked_reason:bo(s.blocked_reason,n.blocked_reason)?"default":"settings",resolution:bo(s.resolution,n.resolution)?"default":"settings",actual_result:bo(s.actual_result,n.actual_result)?"default":"settings"}}}function Yv(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"core";if(Kv.includes(t))return t;throw new p(`Unknown --metadata-profile value "${e}". Supported values: ${Kv.join(", ")}.`,m.USAGE)}function Jv(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(So.includes(t))return t;throw new p(`Unknown --dependency-cycle-severity value "${e}". Supported values: ${So.join(", ")}.`,m.USAGE)}function Xv(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(So.includes(t))return t;throw new p(`Unknown --parent-cycle-severity value "${e}". Supported values: ${So.join(", ")}.`,m.USAGE)}function WL(e){return[...new Set((e??[]).map(n=>n.trim().toLowerCase().replaceAll("-","_")))].map(n=>OL[n]).filter(n=>n!==void 0).sort((n,r)=>n.localeCompare(r))}function KL(e,t,n){let r=WL(n);return e==="core"?{profile:e,profile_source:t,required_fields:[...fl],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:e==="strict"?{profile:e,profile_source:t,required_fields:[...Hv],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:r.length>0?{profile:e,profile_source:t,required_fields:r,configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:{profile:e,profile_source:t,required_fields:[...fl],configured_custom_fields:r,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}var zL=new Set(["acceptance_criteria","estimated_minutes"]);function Qv(e,t,n,r){return!r&&zL.has(t)&&us(e.status,n)?!1:t==="author"?!ie(e.author):t==="acceptance_criteria"?!ie(e.acceptance_criteria):t==="estimated_minutes"?!Number.isFinite(e.estimated_minutes):t==="close_reason"?Ao(e.status,n)===n.close_status&&!ie(e.close_reason):t==="reviewer"?!ie(e.reviewer):t==="risk"?!ie(e.risk):t==="confidence"?typeof e.confidence=="number"?!Number.isFinite(e.confidence):!ie(e.confidence):t==="sprint"?!ie(e.sprint):!ie(e.release)}function Zv(e){if(e===void 0)return"default";let t=e.trim().toLowerCase();if(t.length===0||t==="default")return"default";if(t==="tracked-all"||t==="tracked_all")return"tracked-all";if(t==="tracked-all-strict"||t==="tracked_all_strict")return"tracked-all-strict";throw new p(`Unknown --scan-mode value "${e}". Supported values: ${IL.join(", ")}.`,m.USAGE)}function ek(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim();if(t)return Me.resolve(t);let n=Me.resolve(e);if(n.replaceAll("\\","/").endsWith("/.agents/pm"))return Me.dirname(Me.dirname(n));let s=Me.resolve(process.cwd()),i=zv(n),o=zv(s),a=Me.relative(i,o);return a.length===0||!a.startsWith("..")&&!Me.isAbsolute(a)?n:s}function zv(e){try{return xL.native(e)}catch{return Me.resolve(e)}}function BL(e,t){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&t.includes(e.code)}async function wl(e,t,n){let r=t.length>0?Me.join(e,t):e,s;try{s=await yl.readdir(r,{withFileTypes:!0})}catch(i){if(U(i))return;throw i}for(let i of s){if(i.name.startsWith("."))continue;let o=t.length>0?Me.join(t,i.name):i.name;if(i.isDirectory()){if(TL.has(i.name))continue;await wl(e,o,n);continue}i.isFile()&&n.push(Gt(o))}}async function hl(e){let t=[];for(let n of AL)await wl(e,n,t);for(let n of CL){let r=Me.join(e,n);try{(await yl.stat(r)).isFile()&&t.push(Gt(n))}catch{}}return[...new Set(t)].sort((n,r)=>n.localeCompare(r))}async function tk(e){try{let{stdout:t}=await UL("git",["ls-files","-z"],{cwd:e,encoding:"utf8",maxBuffer:PL,windowsHide:!0,timeout:FL}),n=t.split("\0").map(r=>Gt(r)).filter(r=>r.length>0);return[...new Set(n)].sort((r,s)=>r.localeCompare(s))}catch{return null}}function HL(e,t){let n=new Set,r=dl(Bu);r.length>0&&n.add(r);let s=dl(Me.relative(t,e));return s.length>0&&!s.startsWith("..")&&n.add(s),[...n].sort((i,o)=>i.localeCompare(o))}function Bv(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}async function VL(e,t){if(t==="tracked-all"||t==="tracked-all-strict"){let r=await tk(e);if(r)return{requestedMode:t,appliedMode:t,source:"tracked-git",candidateFiles:r,candidateTotal:r.length,candidateScanned:r.length};let s=await hl(e);return{requestedMode:t,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:s,candidateTotal:s.length,candidateScanned:s.length}}let n=await hl(e);return{requestedMode:t,appliedMode:"default",source:"default-curated",candidateFiles:n,candidateTotal:n.length,candidateScanned:n.length}}function ne(e,t=nt){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function un(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=ne(e,_l);return{values:n.values,truncated:n.truncated,total:e.length}}var YL={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},JL={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function XL(e){let t=e.missing_fields.map(n=>`${YL[n]} "${JL[n]}"`).join(" ");return`pm update ${e.id} ${t} --message "Backfill resolution metadata"`}function nk(e,t){let n=e.details?.missing_resolution_remediation_hints,r=Array.isArray(n)&&n.length>0,s=r?n.filter(o=>typeof o=="string"):Mw(t);if(s.length===0)return;let i=r&&e.details?.missing_resolution_remediation_hints_truncated===!0;e.details={...e.details,fix_hints:s,...i?{fix_hints_truncated:!0}:{}}}function rk(e){let t=new Set;return e.checkCompleteness&&t.add("completeness"),e.checkMetadata&&t.add("metadata"),e.checkResolution&&t.add("resolution"),(e.checkLifecycle||e.checkStaleBlockers)&&t.add("lifecycle"),e.checkFiles&&t.add("files"),e.checkHistoryDrift&&t.add("history_drift"),e.checkCommandReferences&&t.add("command_references"),e.checkStorageIntegrity&&t.add("storage_integrity"),t.size===0?(e.autoFix&&(t.add("metadata"),t.add("resolution"),t.add("lifecycle")),e.pruneMissing&&t.add("files"),t.size===0&&(t.add("metadata"),t.add("resolution"),t.add("lifecycle"),t.add("files"),t.add("command_references"),t.add("history_drift"),t.add("format_version"),t.add("completeness"),t.add("storage_integrity")),t):(e.pruneMissing&&t.add("files"),t)}var QL="validate_metadata_duplicate_issue_codes";function sk(e,t){if(e.length===0)return{rows:[],truncated:!1,warnings:[]};let n=t?e.length:nt,r=e.slice(0,n);return{rows:r.map(i=>({code:i.code,count:i.count,ids:i.ids,titles:i.titles,remediation_hint:`Items ${i.ids.join(", ")} share issue code "${i.code}"; rename or merge so each logical code maps to one item.`})),truncated:r.length<e.length,warnings:[`${QL}:${e.length}`]}}function ZL(e,t,n){let r=Object.fromEntries(pl.map(s=>[s,[]]));for(let s of e)for(let i of pl)Qv(s,i,t,n)&&r[i].push(s.id);return r}function e$(e,t,n){let r=[...e.warnings];for(let s of e.required_fields){let i=t[s];i.length>0&&r.push(`${LL[s]}:${i.length}`)}return r.push(...n),r}function ik(e,t){let n={};for(let r of e.required_fields){let s=t[r],i=s?s.length:0,o=$L[r];n[o]=i}return n}function ok(e,t,n){let r=[];for(let s of e.required_fields){let i=t[s];if(i)for(let o of i){let a=n.get(o)?.type,c=typeof a=="string"&&a.length>0?a:"Unknown";r.push({item_type:c,field:s})}}return r}function t$(e,t,n,r){for(let s of t.required_fields){let i=n[s];if(!i||i.length===0)continue;let o=NL[s],a=ML[s];if(!o||!a)continue;let c=ne(i,r?i.length:nt);e[o]=c.values,e[a]=c.truncated}}function ak(e,t,n){if(!e.required_fields.includes("close_reason"))return[];let r=t.close_reason;return r?r.map(s=>({id:s,resolution:ie(n.get(s)?.resolution)})):[]}function ck(e,t,n){if(!e.required_fields.includes("estimated_minutes"))return[];let r=t.estimated_minutes;return r?r.map(s=>({id:s,type:ie(n.get(s)?.type)})):[]}function n$(e,t,n,r,s){let i=new Map(e.map(v=>[v.id,v])),o=t.profile==="strict",a=ZL(e,n,o),c=jv(e,{configuredPrefixes:s}),d=sk(c,r),l=e$(t,a,d.warnings),u=ik(t,a),f=ok(t,a,i),_=Uv(f),h={checked_items:e.length,metadata_profile:t.profile,metadata_profile_source:t.profile_source,metadata_profile_fallback_to_core:t.fallback_to_core,required_fields:[...t.required_fields],supported_required_fields:[...pl],counts:u,missing_by_type:_,duplicate_issue_codes_count:c.length,duplicate_issue_codes:d.rows,duplicate_issue_codes_truncated:d.truncated};t.configured_custom_fields.length>0&&(h.configured_custom_required_fields=[...t.configured_custom_fields]);let g=lo(e,r);g!==void 0&&(h.deferred_fields=g.details,l.push(g.warning)),t$(h,t,a,r);let y=ak(t,a,i),w=ck(t,a,i);return{check:{name:"metadata",status:l.length===0?"ok":"warn",ok:l.length===0,details:h},warnings:l,closeReasonBackfillRows:y,estimateBackfillRows:w}}function r$(e,t,n){let r=new Set(t.terminal_done_statuses);r.add(t.close_status);let s=e.filter(f=>r.has(Ao(f.status,t))),i=[],o=[];for(let f of s){let _=RL.filter(h=>!ie(f[h]));_.length!==0&&(i.push({id:f.id,missing_fields:_}),o.push({id:f.id,missing_fields:_,close_reason:ie(f.close_reason)}))}let a=i.length>0?[`validate_resolution_missing_fields:${i.length}`]:[],c=n?Number.POSITIVE_INFINITY:nt,d=ne(i.map(f=>`${f.id}:${f.missing_fields.join(",")}`),c),l=i.map(f=>XL(f)),u=ne(l,c);return{check:{name:"resolution",status:a.length===0?"ok":"warn",ok:a.length===0,details:{checked_closed_items:s.length,missing_resolution_items:i.length,missing_resolution_rows:d.values,missing_resolution_rows_truncated:d.truncated,missing_resolution_remediation_hints:u.values,missing_resolution_remediation_hints_truncated:u.truncated}},warnings:a,resolutionBackfillRows:o}}function dk(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function lk(e,t="pm",n=xf()){let r=new Set(e.map(i=>i.id)),s=[...e].sort((i,o)=>i.id.localeCompare(o.id));return new Map(s.map(i=>{let o=new Set,a=tt(i.blocked_by);a&&r.has(a)&&o.add(a),(i.dependencies??[]).filter(d=>{let l=tt(d.kind);return l!==void 0&&n.resolve(l)?.ordering===!0}).map(d=>tt(d.id)).filter(d=>d!==void 0&&r.has(d)).forEach(d=>o.add(d));let c=tt(i.definition_of_ready);return mk(c??"",t).filter(d=>r.has(d)).forEach(d=>o.add(d)),[i.id,[...o].sort((d,l)=>d.localeCompare(l))]}))}function uk(e,t,n){let r=xh(e,n?l=>us(l,n):void 0),s=r.active.map(l=>`${l.holder_id}:${l.target_id}:${l.kind}`),i=r.legacy_terminal.map(l=>`${l.holder_id}:${l.target_id}:${l.kind}:${l.holder_status}`),o=t?Number.POSITIVE_INFINITY:nt,a=ne(s,o),c=ne(i,o),d=ne(r.active.map(l=>l.source==="parent"?`pm update ${l.holder_id} --unset parent`:l.source==="blocked_by"?`pm update ${l.holder_id} --unset blocked_by`:`pm update ${l.holder_id} --replace-deps '<correct dependency edges>'`),o);return{check:{name:"dependency_references",status:s.length===0?"ok":"warn",ok:s.length===0,details:{checked_items:e.length,dangling_reference_count:s.length+i.length,active_dangling_reference_count:s.length,dangling_reference_rows:a.values,dangling_reference_rows_truncated:a.truncated,legacy_terminal_dangling_reference_count:i.length,legacy_closed_dangling_reference_count:r.legacy_terminal.filter(l=>l.holder_status==="closed").length,legacy_terminal_dangling_reference_rows:c.values,legacy_terminal_dangling_reference_rows_truncated:c.truncated,no_active_blocker_sentinel_count:r.no_active_blocker_sentinels.length,remediation_hints:d.values,remediation_hints_truncated:d.truncated}},warnings:s.length>0?[`validate_dangling_dependency_references:${s.length}`]:[]}}function mk(e,t="pm"){let n=(t.trim().toLowerCase()||"pm").replace(/-+$/g,""),r=new RegExp(`(?:^|[^a-z0-9-])(${dk(n)}-[a-z0-9][a-z0-9-]*)`,"gi");return[...new Set([...e.matchAll(r)].map(s=>s[1].toLowerCase()))].sort((s,i)=>s.localeCompare(i))}function fk(e,t="pm"){let n=lk(e,t),r=ol(n),s=[...new Set(r.flat())].sort((o,a)=>o.localeCompare(a)),i=r.map(o=>ko(o,n).join("->"));return{cycle_count:r.length,cycle_item_ids:s,cycle_sample_paths:i}}function pk(e){return e.startsWith("docs/")?"docs_unowned":e.startsWith("tests/")?"tests_unowned":e.startsWith("src/")?"source_unowned":e.endsWith(".md")?"docs_unowned":"unlinked_existing"}function Eo(e){let t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function _k(e,t){let n=Eo(e).split("/").filter(Boolean),r=Eo(t).split("/").filter(Boolean),s=0;for(;s<n.length&&s<r.length&&n[s]===r[s];)s+=1;return s}function s$(e,t){let n=Eo(t),r=Eo(e),s=t.endsWith("/")?t:`${t}/`,i=e.startsWith(s),o=n.length>0&&n===r,a=_k(e,t);return!i&&!o&&a===0?null:i?{score:t.length+1e3,confidence:"path_prefix"}:o?{score:a+500,confidence:"same_directory"}:{score:a,confidence:"shared_directory"}}function i$(e,t,n){return e===void 0||n>e.score||n===e.score&&t.id.localeCompare(e.item.id)<0}function o$(e,t,n){let r=t==="docs_unowned"?"docs":"files",s;return n.flatMap(i=>(r==="docs"?i.docs??[]:i.files??[]).map(o=>({item:i,link:o}))).forEach(({item:i,link:o})=>{if(o.scope!=="project")return;let a=Gt(o.path);if(a.length===0||a===e)return;let c=s$(e,a);c!==null&&i$(s,i,c.score)&&(s={item:i,score:c.score,confidence:c.confidence})}),s?{id:s.item.id,type:s.item.type,title:s.item.title,status:s.item.status,confidence:s.confidence}:null}function hk(e,t){return e.map(n=>{let r=pk(n),s=r==="docs_unowned"?"docs":"files",i=o$(n,r,t),o=i?.id??"<id>";return{path:n,classification:r,owner_candidate:i,remediation_hint:`pm ${s} ${o} --add path=${n},scope=project,note="<why this artifact belongs to the item>"`}})}function gk(e){return e.map(t=>`${t.path}:${t.classification} owner_candidate=${t.owner_candidate?.id??"unowned"} hint=${JSON.stringify(t.remediation_hint)}`)}function a$(e,t){return Object.entries(t.closure_like_metadata_field_patterns).filter(([n,r])=>{let s=tt(e[n]);return s?r.some(i=>s.toLowerCase().includes(i)):!1}).map(([n])=>n).sort((n,r)=>n.localeCompare(r))}function c$(e,t,n,r,s){let i=tt(t.parent),o=i?n.get(r.get(i.toLowerCase())??i):void 0;return{id:e.id,parent_id:t.id,grandparent_id:o?.id,grandparent_active:o!==void 0&&!us(o.status,s)}}function d$(e,t,n,r){let s=tt(e.blocked_by),i=tt(e.blocked_reason),o=i?.toLowerCase(),a=Ao(e.status,n),c=[];return t.has(a)?(!s&&!i&&c.push("blocked_status_missing_blocker_context"),o?.includes("no active blocker")&&c.push("blocked_status_reason_reports_no_active_blocker"),o&&r.stale_blocker_reason_patterns.some(d=>o.includes(d))&&c.push("blocked_status_reason_matches_stale_pattern"),c):(s&&c.push("non_blocked_status_has_blocked_by"),i&&c.push("non_blocked_status_has_blocked_reason"),c)}function l$(e,t,n,r){let s=new Map(e.map(c=>[c.id,c])),i=new Map(e.map(c=>[c.id.toLowerCase(),c.id])),o=n.blocked_statuses.size>0?n.blocked_statuses:new Set(["blocked"]),a={activeItems:e.filter(c=>!us(c.status,n)),closureLikeRows:[],terminalParentRows:[],terminalParentFixRows:[],staleBlockerRows:[]};for(let c of a.activeItems){let d=a$(c,r);d.length>0&&a.closureLikeRows.push({id:c.id,fields:d});let l=tt(c.parent),u=l?s.get(i.get(l.toLowerCase())??l):void 0;if(u&&us(u.status,n)&&(a.terminalParentRows.push({id:c.id,parent_id:u.id,parent_status:u.status}),a.terminalParentFixRows.push(c$(c,u,s,i,n))),t){let f=d$(c,o,n,r);f.length>0&&a.staleBlockerRows.push({id:c.id,status:c.status,reasons:[...new Set(f)].sort((_,h)=>_.localeCompare(h))})}}return a}function u$(e){e.closureLikeRows.sort((t,n)=>t.id.localeCompare(n.id)),e.terminalParentRows.sort((t,n)=>t.id.localeCompare(n.id)||t.parent_id.localeCompare(n.parent_id)),e.terminalParentFixRows.sort((t,n)=>t.id.localeCompare(n.id)||t.parent_id.localeCompare(n.parent_id)),e.staleBlockerRows.sort((t,n)=>t.id.localeCompare(n.id))}function xo(e,t,n){return n<=0||t==="off"?null:`${t==="error"?`${e}_error`:e}:${n}`}function ul(e,t,n){return n>0&&t!=="off"?`${e}:${n}`:null}function m$(e,t,n,r,s){let i=[];e.closureLikeRows.length>0&&i.push(`validate_lifecycle_active_closure_like_metadata:${e.closureLikeRows.length}`),e.terminalParentRows.length>0&&i.push(`validate_lifecycle_active_terminal_parent:${e.terminalParentRows.length}`),t&&e.staleBlockerRows.length>0&&i.push(`validate_lifecycle_stale_blockers:${e.staleBlockerRows.length}`);let o=xo("validate_lifecycle_dependency_cycles",n,s.dependencyCycles),a=xo("validate_hierarchy_parent_cycle",r,s.activeHierarchyCycles),c=xo("validate_hierarchy_cardinality_violation",r,s.activeHierarchyCardinality),d=xo("validate_hierarchy_parent_divergence",r,s.activeHierarchyDivergence),l=ul("validate_legacy_hierarchy_parent_cycle",r,s.legacyHierarchyCycles),u=ul("validate_legacy_hierarchy_cardinality_violation",r,s.legacyHierarchyCardinality),f=ul("validate_legacy_hierarchy_parent_divergence",r,s.legacyHierarchyDivergence);return[...i,...o?[o]:[],...a?[a]:[],...c?[c]:[],...d?[d]:[],...l?[l]:[],...u?[u]:[],...f?[f]:[]]}function yk(e){let t=Gt(e);return t.length>DL||t.split(/[\\/]/).some(n=>n.length>jL)}async function f$(e,t){let n=Me.isAbsolute(t)?t:Me.resolve(e,t);if(yk(n))return!1;try{let r=await yl.stat(n);return!r.isFile()&&!r.isDirectory()}catch(r){return BL(r,["ENOENT","ENOTDIR"])}}async function p$(e,t){let n={linkedProjectPaths:new Set,remoteLinkedPaths:new Set,missingLinkedPaths:[],staleLinkRows:[]},r=e.flatMap(s=>[...(s.files??[]).map(i=>({item:s,artifact:i,link_kind:"files"})),...(s.docs??[]).map(i=>({item:s,artifact:i,link_kind:"docs"}))]);for(let{item:s,artifact:i,link_kind:o}of r){if(i.scope!=="project")continue;if(ts(i.path)){n.remoteLinkedPaths.add(i.path.trim());continue}let a=Gt(i.path);a.length!==0&&(n.linkedProjectPaths.add(a),await f$(t,i.path)&&(n.missingLinkedPaths.push(a),n.staleLinkRows.push({item_id:s.id,path:a,link_kind:o})))}return n}function _$(e,t,n,r,s,i){let o=r==="tracked-all-strict",a=o&&!s,c=s||o,d=c?[]:HL(t,n),l=d.length===0?[]:e.candidateFiles.filter(_=>Bv(_,d)),u=d.length===0?e.candidateFiles:e.candidateFiles.filter(_=>!Bv(_,d)),f={};if(l.length>0){let _=un(l,i);f.pm_internals={count:l.length,paths:_.values,paths_truncated:_.truncated,paths_total:_.total}}return{strictTrackedAllMode:o,strictModeForcesPmInternals:a,includePmInternalsEffective:c,pmInternalCandidatePrefixes:d,excludedPmInternalPaths:l,candidateFiles:u,excludedByReason:f}}function wk(e,t,n,r,s,i,o,a="pm"){let c=l$(e,t,s,i);u$(c);let d=fk(c.activeItems,a),l=cl(e,s),u=io(s,e,o?Number.POSITIVE_INFINITY:nt),f=[...m$(c,t,n,r,{dependencyCycles:d.cycle_count,activeHierarchyCycles:l.active_cycle_count,activeHierarchyCardinality:l.active_cardinality_violation_count,activeHierarchyDivergence:l.active_parent_divergence_count,legacyHierarchyCycles:l.legacy_cycle_count,legacyHierarchyCardinality:l.legacy_cardinality_violation_count,legacyHierarchyDivergence:l.legacy_parent_divergence_count}),...oo(u)],_=o?Number.POSITIVE_INFINITY:nt,h=ne(c.closureLikeRows.map(E=>`${E.id}:${E.fields.join(",")}`),_),g=ne(c.terminalParentRows.map(E=>`${E.id}:${E.parent_id}:${E.parent_status}`),_),y=ne(c.staleBlockerRows.map(E=>`${E.id}:${E.status}:${E.reasons.join(",")}`),_),w=ne(d.cycle_item_ids,_),v=ne(d.cycle_sample_paths,_),S=ne(l.cycle_item_ids,_),b=ne(l.cycle_sample_paths,_),k=ne(l.cardinality_violation_rows,_),A=ne(l.parent_divergence_rows,_),x=d.cycle_count>0&&n==="error"||(l.active_cycle_count>0||l.active_cardinality_violation_count>0||l.active_parent_divergence_count>0)&&r==="error";return{check:{name:"lifecycle",status:x?"error":f.length===0?"ok":"warn",ok:!x&&f.length===0,details:{checked_active_items:c.activeItems.length,lifecycle_status_roles:u,active_closure_like_metadata_items:c.closureLikeRows.length,active_closure_like_metadata_rows:h.values,active_closure_like_metadata_rows_truncated:h.truncated,active_terminal_parent_items:c.terminalParentRows.length,active_terminal_parent_rows:g.values,active_terminal_parent_rows_truncated:g.truncated,stale_blocker_checks_enabled:t,stale_blocker_items:c.staleBlockerRows.length,stale_blocker_rows:y.values,stale_blocker_rows_truncated:y.truncated,dependency_cycle_severity_policy:n,dependency_cycle_count:d.cycle_count,dependency_cycle_item_count:d.cycle_item_ids.length,dependency_cycle_item_ids:w.values,dependency_cycle_item_ids_truncated:w.truncated,dependency_cycle_sample_paths:v.values,dependency_cycle_sample_paths_truncated:v.truncated,parent_cycle_severity_policy:r,parent_cycle_count:l.cycle_count,active_parent_cycle_count:l.active_cycle_count,legacy_parent_cycle_count:l.legacy_cycle_count,parent_cycle_item_count:l.cycle_item_ids.length,parent_cycle_item_ids:S.values,parent_cycle_item_ids_truncated:S.truncated,parent_cycle_sample_paths:b.values,parent_cycle_sample_paths_truncated:b.truncated,hierarchy_cardinality_violation_count:l.cardinality_violation_count,active_hierarchy_cardinality_violation_count:l.active_cardinality_violation_count,legacy_hierarchy_cardinality_violation_count:l.legacy_cardinality_violation_count,hierarchy_cardinality_violation_rows:k.values,hierarchy_cardinality_violation_rows_truncated:k.truncated,hierarchy_parent_divergence_count:l.parent_divergence_count,active_hierarchy_parent_divergence_count:l.active_parent_divergence_count,legacy_hierarchy_parent_divergence_count:l.legacy_parent_divergence_count,hierarchy_parent_divergence_rows:A.values,hierarchy_parent_divergence_rows_truncated:A.truncated,stale_blocker_reason_patterns:[...i.stale_blocker_reason_patterns],stale_blocker_reason_pattern_source:i.stale_blocker_reason_pattern_source,closure_like_blocked_reason_patterns:[...i.closure_like_metadata_field_patterns.blocked_reason],closure_like_blocked_reason_pattern_source:i.closure_like_metadata_field_pattern_sources.blocked_reason,closure_like_resolution_patterns:[...i.closure_like_metadata_field_patterns.resolution],closure_like_resolution_pattern_source:i.closure_like_metadata_field_pattern_sources.resolution,closure_like_actual_result_patterns:[...i.closure_like_metadata_field_patterns.actual_result],closure_like_actual_result_pattern_source:i.closure_like_metadata_field_pattern_sources.actual_result}},warnings:f,terminalParentFixRows:c.terminalParentFixRows}}async function vk(e,t,n,r,s,i,o=z(Kt.schema)){let a=await p$(e,t),c=new Map(e.map(T=>[T.id,T])),d=[...new Set(a.missingLinkedPaths)].sort((T,q)=>T.localeCompare(q)),l=await VL(t,r),u=_$(l,n,t,r,s,i),f=u.candidateFiles.filter(T=>!a.linkedProjectPaths.has(T)),_=hk(f,e),h=qv(d,u.candidateFiles),g=new Map(h.map(T=>[T.path,T.classification])),y=h.filter(T=>T.classification==="moved").length,w=a.staleLinkRows.map(T=>({...T,classification:g.get(T.path)??"deleted"})).sort((T,q)=>T.item_id.localeCompare(q.item_id)||T.path.localeCompare(q.path)||T.link_kind.localeCompare(q.link_kind)),v=[];u.strictModeForcesPmInternals&&v.push("validate_files_tracked_all_strict_forces_pm_internals"),f.length>0&&v.push(`validate_files_orphaned_paths:${f.length}`);let S=[...a.remoteLinkedPaths].sort((T,q)=>T.localeCompare(q)),b=un(S,i),k=un(d,i),A=un(f,i),x=un(_.map(T=>`${T.path}:${T.classification}:owner_candidate=${T.owner_candidate?.id??"unowned"}`),i),E=i?_:un(gk(_),!1).values,$=un(Wv(h),i),R=hv(w,h,T=>c.get(T),o,i?1/0:_l);return R.active_missing_linked_paths_count>0&&v.push(`validate_files_missing_linked_paths:${R.active_missing_linked_paths_count}`),{check:{name:"files",status:v.length===0?"ok":"warn",ok:v.length===0,details:{workspace_root:t,scan_mode_requested:l.requestedMode,scan_mode_applied:l.appliedMode,strict_tracked_all_mode:u.strictTrackedAllMode,strict_mode_forces_pm_internals:u.strictModeForcesPmInternals,strict_mode_forces_pm_internals_notice:u.strictModeForcesPmInternals?"tracked-all-strict force-enables PM internals; pass --include-pm-internals to make inclusion explicit.":null,file_list_detail_mode:i?"full":"summary",file_list_summary_limit:_l,candidate_scan_source:l.source,include_pm_internals:u.includePmInternalsEffective,include_pm_internals_requested:s,pm_internal_candidate_prefixes:u.pmInternalCandidatePrefixes,pm_internal_excluded_count:u.excludedPmInternalPaths.length,excluded_total:u.excludedPmInternalPaths.length,excluded_by_reason:u.excludedByReason,linked_project_paths:a.linkedProjectPaths.size,remote_linked_paths_count:S.length,remote_linked_paths_total:b.total,remote_linked_paths:b.values,remote_linked_paths_truncated:b.truncated,candidate_total_raw:l.candidateTotal,candidate_scanned_raw:l.candidateScanned,candidate_total:u.candidateFiles.length,candidate_scanned:u.candidateFiles.length,scanned_candidate_files:u.candidateFiles.length,missing_linked_paths_count:d.length,missing_linked_paths_total:k.total,missing_linked_paths:k.values,missing_linked_paths_truncated:k.truncated,missing_linked_paths_moved_count:y,missing_linked_paths_deleted_count:h.filter(T=>T.classification==="deleted").length,missing_linked_paths_malformed_count:h.filter(T=>T.classification==="malformed").length,missing_linked_path_classifications:$.values,missing_linked_path_classifications_truncated:$.truncated,...R,orphaned_paths_count:f.length,orphaned_paths_total:A.total,orphaned_paths:A.values,orphaned_paths_truncated:A.truncated,orphaned_path_classifications:x.values,orphaned_path_classifications_truncated:x.truncated,orphaned_path_rows_count:_.length,orphaned_path_rows:E}},warnings:v,staleLinkPruneRows:w}}function h$(e,t){let n=[];return e.forEach(({item:r,linkedTest:s},i)=>{let o=t[i];if(o.trusted)return;let a=ll(s.command??"");n.push(`${r.id}:${o.source_ref??"unknown"}->${o.current_source_ref??"unknown"}:${a}`)}),n}async function kk(e,t,n,r){let s=new Set(e.map(k=>k.id.toLowerCase())),i=0,o=0,a=new Set,c=[],d=e.flatMap(k=>(k.tests??[]).map(A=>({item:k,linkedTest:A}))),l=await cs(ds()),u=await Tv(r,d.map(({linkedTest:k})=>k),l),f=h$(d,u);for(let{item:k,linkedTest:A}of d){if(typeof A.command!="string"||A.command.trim().length===0)continue;i+=1;let x=Yd(A.command,t);if(x.length!==0){o+=x.length;for(let E of x)a.add(E),s.has(E.toLowerCase())||c.push(`${k.id}:${E}:${ll(A.command)}`)}}let _=[...new Set(c)].sort((k,A)=>k.localeCompare(A)),h=[...new Set(_.map(k=>k.split(":")[1]??""))].filter(k=>k.length>0).sort((k,A)=>k.localeCompare(A)),g=[];_.length>0&&g.push(`validate_command_references_stale_pm_ids:${_.length}`),f.length>0&&g.push(`validate_linked_test_trust_unacknowledged:${f.length}`);let y=n?Number.POSITIVE_INFINITY:nt,w=ne(_,y),v=ne(h,y),S=ne([...a].sort((k,A)=>k.localeCompare(A)),y),b=ne(f,y);return{check:{name:"command_references",status:g.length===0?"ok":"warn",ok:g.length===0,details:{checked_items:e.length,linked_commands_scanned:i,referenced_pm_ids_count:o,unique_referenced_pm_ids_count:a.size,unique_referenced_pm_ids:S.values,unique_referenced_pm_ids_truncated:S.truncated,linked_test_trust_current_source_ref:l??null,untrusted_linked_tests_count:f.length,untrusted_linked_tests:b.values,untrusted_linked_tests_truncated:b.truncated,stale_pm_id_references_count:_.length,stale_pm_ids_count:h.length,stale_pm_ids:v.values,stale_pm_ids_truncated:v.truncated,stale_pm_id_reference_rows:w.values,stale_pm_id_reference_rows_truncated:w.truncated}},warnings:g}}function g$(e,t){let n=ri(e.map(c=>({ref:c.id,version:ni(c)})),4,1),r=[];n.outdated.length>0&&r.push(`validate_format_version_outdated_items:${n.outdated.length}`),n.ahead.length>0&&r.push(`validate_format_version_ahead_items:${n.ahead.length}`);let s=t?Number.POSITIVE_INFINITY:nt,i=ne(n.outdated,s),o=ne(n.ahead,s),a=n.ahead.length>0?"error":n.outdated.length>0?"warn":"ok";return{check:{name:"format_version",status:a,ok:a==="ok",details:{checked_items:e.length,current_format_version:4,outdated_items_count:n.outdated.length,outdated_items:i.values,outdated_items_truncated:i.truncated,ahead_items_count:n.ahead.length,ahead_items:o.values,ahead_items_truncated:o.truncated}},warnings:r}}var gl="pm validate auto-fix";async function bk(e,t,n){switch(e.kind){case"set_closed_at":await fv(e,t);return;case"set_resolution":case"set_close_reason":case"set_estimate":case"reparent":case"unset_parent":{let r={message:gl};if(e.kind==="set_resolution"?r.resolution=e.value:e.kind==="set_close_reason"?r.closeReason=e.value:e.kind==="set_estimate"?r.estimatedMinutes=e.value:e.kind==="reparent"?r.parent=e.parent_id:r.unset=["parent"],!n.runUpdate)throw new p("Applying validate metadata/lifecycle fixes requires a runUpdate mutation service.",m.USAGE);await n.runUpdate(e.item_id,r,t);return}case"prune_file_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`);case"prune_doc_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`)}}function ml(e){return e.kind!=="prune_file_link"&&e.kind!=="prune_doc_link"?null:`${e.kind}:${e.item_id}`}async function xk(e,t,n){let r=[],s=[],i=new Map;for(let o of e.filter(a=>ml(a)===null))try{await bk(o,t,n),r.push(o)}catch(a){s.push({fix:o,error:a})}for(let o of e.filter(a=>ml(a)!==null)){let a=ml(o),c=i.get(a);c?c.push(o):i.set(a,[o])}for(let o of i.values()){let a=o[0];if(!a)continue;let c=o.map(d=>d.path).filter(d=>typeof d=="string"&&d.length>0);try{a.kind==="prune_file_link"?await ow(a.item_id,{remove:c,message:gl},t):await Hy(a.item_id,{remove:c,message:gl},t),r.push(...o)}catch(d){s.push(...o.map(l=>({fix:l,error:d})))}}return hp(s.map(o=>o.error)),{applied:r,failed:s}}var J2={applyValidateFix:bk,applyValidateFixes:xk,attachValidateFixHints:nk,buildCommandReferencesCheck:kk,buildDependencyReferencesCheck:uk,buildCloseReasonBackfillRows:ak,buildFilesCheck:vk,buildLifecycleCheck:wk,buildLifecycleDependencyGraph:lk,buildLifecycleParentGraph:al,buildEstimateBackfillRows:ck,buildMetadataCounts:ik,buildMissingFieldOccurrences:ok,buildOrphanedPathRows:hk,classifyOrphanedPath:pk,collectDefaultProjectFileCandidates:hl,collectTrackedGitFileCandidates:tk,detectLifecycleDependencyCycles:fk,detectLifecycleParentCycles:cl,escapeRegExp:dk,extractItemIds:mk,findLifecycleDependencyCycleComponents:ol,isMetadataFieldMissing:Qv,linkedArtifactPathExceedsFilesystemLimits:yk,listFilesRecursive:wl,resolveDependencyCycleSeverity:Jv,resolveParentCycleSeverity:Xv,resolveFileScanMode:Zv,resolveLifecycleDependencyCycleSamplePath:ko,resolveRequestedChecks:rk,resolveValidateMetadataProfile:Yv,resolveWorkspaceRoot:ek,sharedDirectoryPrefixLength:_k,summarizeOrphanedPathRows:gk,summarizeDuplicateIssueCodes:sk,toMeaningfulString:tt};function y$(e,t){t>0&&e.push(`merge_receipt_evidence_invalid:${t}`)}async function w$(e,t,n,r){let s=await yv(e,new Set(t.map(y=>y.id)),n,{schema:r.schema,extensionFieldNames:Ot(F())}),i=[];s.unreadable_item_files.length>0&&i.push(`validate_storage_unreadable_items:${s.unreadable_item_files.length}`),s.duplicate_item_ids.length>0&&i.push(`validate_storage_duplicate_item_ids:${s.duplicate_item_ids.length}`),s.history_conflict_marker_streams.length>0&&i.push(`validate_storage_history_conflict_markers:${s.history_conflict_marker_streams.length}`),s.history_unparseable_streams.length>0&&i.push(`validate_storage_unparseable_history:${s.history_unparseable_streams.length}`),s.resurrected_items.length>0&&i.push(`validate_storage_resurrected_items:${s.resurrected_items.length}`),s.unparseable_config_files.length>0&&i.push(`validate_storage_unparseable_config:${s.unparseable_config_files.length}`);let o=i.length,a=await ao(e);a.tracked_path_count>0&&i.push(`validate_storage_tracked_runtime_cache_files:${a.tracked_path_count}`);let c=await Pt(e),d=await Dn(e,Fn(r),{gitWorkspaceRoot:c});d.status==="drift"&&i.push(`validate_merge_fence_drift:${d.missing_patterns.length+d.stale_patterns.length}`);let l=c===null?null:await jn(c);l!==null&&l.status!=="ok"&&i.push(`validate_merge_driver_configuration:${l.missing_keys.length+l.drifted_keys.length}`);let u=await Un(c??e,{includeLossless:!0,pmRoot:e}),f=u.receipts,{pendingDecisions:_,lossless:h}=Gn(f);_.length>0&&i.push(`validate_merge_decisions_unreviewed:${_.length}`),y$(i,u.invalid_evidence_count);let g=o>0?"error":i.length>0?"warn":"ok";return{check:{name:"storage_integrity",status:g,ok:g==="ok",details:{...s,merge_fence:d,merge_driver_configuration:l,pending_merge_decision_count:_.length,pending_merge_decision_items:[...new Set(_.map(y=>y.item_id))].sort((y,w)=>y.localeCompare(w)),lossless_merge_receipt_count:h.length,invalid_merge_receipt_evidence_count:u.invalid_evidence_count,invalid_merge_receipt_evidence_details:u.invalid_evidence,invalid_merge_receipt_evidence_details_truncated:u.invalid_evidence_truncated,lossless_merge_receipt_items:[...new Set(h.map(y=>y.item_id))].sort((y,w)=>y.localeCompare(w)),tracked_runtime_cache:{tracker_relative_root:a.tracker_relative_root,tracked_paths:a.tracked_paths,tracked_path_count:a.tracked_path_count,remediation_command:a.remediation_command}}},warnings:i}}function mt(e,t,n){n&&nk(t.check,t.warnings),e.checks.push(t.check),e.warnings.push(...t.warnings)}async function v$(e){let t={closureTimestampFixes:[],checks:[],warnings:[...e.initialWarnings],closeReasonBackfillRows:[],estimateBackfillRows:[],resolutionBackfillRows:[],terminalParentFixRows:[],staleLinkPruneRows:[]},n=e.options.fixHints===!0,r=e.options.verboseDiagnostics===!0||e.options.allAffectedIds===!0||e.global.json===!0;if(e.requestedChecks.has("completeness")){let s=await Oh(e.pmRoot,e.items,r?1/0:nt,e.sourceIncomplete);mt(t,s,n)}if(e.requestedChecks.has("metadata")){let s=n$(e.items,e.metadataPolicy,e.statusRegistry,r,[e.settings.id_prefix]);t.closeReasonBackfillRows=s.closeReasonBackfillRows,t.estimateBackfillRows=s.estimateBackfillRows;let i=r?1/0:nt,o=await mv(e.pmRoot,e.items,e.statusRegistry,e.options.autoFix===!0||n,i);t.closureTimestampFixes=o.fixes,Object.assign(s.check.details,o.details),s.warnings.push(...o.warnings);let a=Ih(e.settings.schema,i);Object.assign(s.check.details,a.details),s.warnings.push(...a.warnings),s.check.ok=s.warnings.length===0,s.check.status=s.check.ok?"ok":"warn",mt(t,s,n)}if(e.requestedChecks.has("resolution")){let s=r$(e.items,e.statusRegistry,r);t.resolutionBackfillRows=s.resolutionBackfillRows,mt(t,s,n)}if(e.requestedChecks.has("lifecycle")){let s=wk(e.items,!!e.options.checkStaleBlockers,e.dependencyCycleSeverity,e.parentCycleSeverity,e.statusRegistry,e.lifecyclePatternPolicy,r,e.settings.id_prefix);t.terminalParentFixRows=s.terminalParentFixRows,mt(t,s,n),mt(t,uk(e.items,r,e.statusRegistry),n)}if(e.requestedChecks.has("files")){let s=await vk(e.items,e.workspaceRoot,e.pmRoot,e.fileScanMode,!!e.options.includePmInternals,!!e.options.verboseFileLists,e.statusRegistry);t.staleLinkPruneRows=s.staleLinkPruneRows,mt(t,s,n)}return e.requestedChecks.has("command_references")&&mt(t,await kk(e.items,e.settings.id_prefix,r,e.pmRoot),n),e.requestedChecks.has("history_drift")&&mt(t,await vo(e.pmRoot,e.items,r),n),e.requestedChecks.has("format_version")&&mt(t,g$(e.items,r),n),e.requestedChecks.has("storage_integrity")&&mt(t,await w$(e.pmRoot,e.items,D(e.settings,F()).type_to_folder,e.settings),n),t}function k$(e,t,n){let r=[];return e.autoFix===!0&&(r.push(...t.closureTimestampFixes),r.push(...Lv(t.closeReasonBackfillRows)),r.push(...Ov(t.resolutionBackfillRows)),r.push(...$v(t.estimateBackfillRows,n.validation.estimate_defaults_by_type)),r.push(...Nv(t.terminalParentFixRows))),e.pruneMissing===!0&&r.push(...Mv(t.staleLinkPruneRows)),r}async function b$(e,t,n,r,s,i){if(e.autoFix!==!0&&e.pruneMissing!==!0)return;let o=k$(e,t,n),{applicable:a,gated:c}=Fv(o,r),d=e.dryRun===!0,l=[],u=[];if(!d){let f=await xk(a,s,i);l.push(...f.applied.map(ls)),u.push(...f.failed.map(({fix:_,error:h})=>({...ls(_),error:h instanceof Error?h.message:String(h)})))}return{mode:d?"dry_run":"apply",auto_fix:e.autoFix===!0,prune_missing:e.pruneMissing===!0,granted_fix_scopes:[...r].sort((f,_)=>f.localeCompare(_)),planned_count:o.length,applied_count:l.length,gated_count:c.length,failed_count:u.length,planned_fixes:o.map(ls),applied_fixes:l,gated_fixes:c.map(f=>({...ls(f),gate_hint:`Withheld: re-run with --fix-scope ${f.gate} to apply.`})),failed_fixes:u}}async function Sk(e,t,n={}){lf(e.counts===!0,e.full===!0,"--counts");let r=e.autoFix===!0||e.pruneMissing===!0;if(e.dryRun===!0&&!r)throw new p("--dry-run requires --auto-fix or --prune-missing (there is nothing to preview otherwise).",m.USAGE);if(e.fixScope!==void 0&&e.fixScope.length>0&&e.autoFix!==!0)throw new p("--fix-scope requires --auto-fix.",m.USAGE);let s=Pv(e.fixScope),i=I(process.cwd(),t.path);await j(i);let o=await C(i),a=z(o.schema),c=D(o,F()),d=rk(e),l=[],u=await wo({includeBody:["history_drift","metadata","completeness"].some(P=>d.has(P)),pmRoot:i,settings:o,typeToFolder:c.type_to_folder,warnings:l}),f=l.length>0;if(d.has("history_drift")){let P=await es(i);P.actionable_unknown_event_count>0&&l.push(`validate_history_unknown_author_events:${P.actionable_unknown_event_count}`)}let _=typeof e.metadataProfile=="string"?"option":"settings",h=Yv(typeof e.metadataProfile=="string"?e.metadataProfile:o.validation.metadata_profile),g=KL(h,_,o.validation.metadata_required_fields),y=qL(o),w=Jv(e.dependencyCycleSeverity),v=Xv(e.parentCycleSeverity),S=Zv(e.scanMode),b=ek(i),k=await v$({requestedChecks:d,options:e,global:t,pmRoot:i,workspaceRoot:b,settings:o,items:u,statusRegistry:a,metadataPolicy:g,lifecyclePatternPolicy:y,dependencyCycleSeverity:w,parentCycleSeverity:v,fileScanMode:S,initialWarnings:[...new Set(l)],sourceIncomplete:f}),A=r?await b$(e,k,o,s,t,n):void 0,x=[...new Set(k.warnings)].sort((P,R)=>P.localeCompare(R)),$={ok:!k.checks.some(P=>P.status==="error"),has_warnings:x.length>0,checks:k.checks,warnings:x,...A!==void 0?{fixes:A}:{},generated_at:O(),projection:{mode:"full",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:["diagnostic_rows"]}};return e.counts!==!0?$:{...GL($),projection:{mode:"counts",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:[]}}}import{execFile as x$}from"node:child_process";import{promisify as S$}from"node:util";var E$=S$(x$),A$=16,C$=3e4;function T$(e,t,n){if(!(e.keys[t].value_type==="number"?typeof n.value=="number"&&Number.isFinite(n.value):Array.isArray(n.value)&&n.value.every(i=>typeof i=="string")))throw new TypeError(`assurance provider ${e.id} key ${t} returned the wrong value type`);if(!Number.isInteger(n.population_size)||n.population_size<0||!Number.isFinite(n.cost)||n.cost<0)throw new TypeError(`assurance provider ${e.id} returned an invalid population or cost`);return n}function R$(e,t){let n=e.keys[t.key];if(!n)throw new TypeError(`assurance provider ${e.id} does not declare key ${t.key}`);let r=t.parameters??{},s=n.parameters??{};for(let i of Object.entries(s).filter(([,o])=>o.required===!0).map(([o])=>o))if(!Object.hasOwn(r,i))throw new TypeError(`assurance provider ${e.id} key ${t.key} requires parameter ${i}`);for(let[i,o]of Object.entries(r)){let a=s[i];if(!a)throw new TypeError(`assurance provider ${e.id} key ${t.key} does not declare parameter ${i}`);if(o===null||typeof o!==a.type)throw new TypeError(`assurance provider ${e.id} parameter ${i} must be ${a.type}`)}return{...r}}async function I$(e,t,n,r){let s=R$(e,t),i=Promise.resolve().then(()=>e.resolve({provider:e.id,key:t.key,parameters:s,trigger:r,pm_root:n,...Af(n)}));i.catch(()=>{});let o;try{let a=await Promise.race([i,new Promise((c,d)=>{o=setTimeout(()=>d(new TypeError(`assurance provider ${e.id} timed out`)),e.timeout_ms??C$),o.unref?.()})]);return T$(e,t.key,a)}finally{clearTimeout(o)}}function Ak(e,t,n,r){let s=e;for(let i of t.split(".")){if(typeof s!="object"||s===null||Array.isArray(s))throw new ut(`assurance field ${t} is not present`,{source_kind:n,field:t,...r?{check:r}:{}});s=s[i]}if(typeof s=="number"&&Number.isFinite(s)||Array.isArray(s)&&s.every(i=>typeof i=="string"))return s;throw new ut(`assurance field ${t} must resolve to a finite number or string array`,{source_kind:n,field:t,...r?{check:r}:{}})}function Ek(e,t,n,r){let s=e.checks.find(o=>o.name===t);if(!s)throw new ut(`assurance check ${t} is not present`,{source_kind:r,field:n,check:t});return{value:n==="status"||n==="ok"?s.ok?0:1:Ak(s.details,n,r,t),population_size:1,cost:e.checks.length}}async function O$(e,t){if(t?.trim())return t.trim();try{let{stdout:n}=await E$("git",["rev-parse","HEAD^{commit}"],{cwd:e,encoding:"utf8",timeout:5e3,windowsHide:!0});return n.trim()}catch{return"working-copy"}}async function L$(e,t){let n=new Array(t.length),r=0,s=Array.from({length:Math.min(A$,t.length)},async()=>{for(;r<t.length;){let i=r;r+=1;let o=t[i],a=await Xt(ht(e,o.id),o.id);n[i]=a.map(c=>({op:c.op,author:c.author,agent_harness:c.agent_harness,agent_model:c.agent_model}))}});return await Promise.all(s),n.flat()}async function ms(e,t={}){let n=await C(e),r=D(n),s=z(n.schema),o=(t.strict_read===!0?(await Eh(void 0,{status:"all",full:!0,includeBody:!0,noTruncate:!0,strictRead:!0},{path:e})).items:await wt(e,n.item_format,r.type_to_folder,void 0,n.schema)).map(_=>({..._,id:_.id,status:_.status,type:_.type})),a={path:e},c=F(),d=Object.fromEntries((c?.assurance_providers??[]).map(_=>[_.definition.id,{cost_class:_.runtime_definition.cost_class,network:_.runtime_definition.network}])),l=new Map,u,f;return{tree_id:t.resolve_tree===!1?t.tree_id??"working-copy":await O$(e,t.tree_id),items:o,history:t.include_history===!1?[]:await L$(e,o),terminal_statuses:[...s.terminal_statuses],provider_capabilities:{...d,...t.provider_capabilities},external:async _=>{if(_.kind==="graph"){let y=Z({operation:_.operation,parameters:_.parameters??{}}),w=l.get(y);w===void 0&&(w=Fh(_.operation,void 0,void 0,{..._.parameters,full:!0},a),l.set(y,w));let v=await w;return{value:Ak(v,_.field,_.kind),population_size:o.length,cost:o.length}}if(_.kind==="validate"){u??=Sk({counts:!0},a);let y=await u;return Ek(y,_.check,_.field,_.kind)}if(_.kind==="health"){f??=dv(a,{checkOnly:!0,full:!0});let y=await f;return Ek(y,_.check,_.field,_.kind)}let h=t.providers?.[_.provider];if(h)return h(_);let g=$f(c,_.provider);if(!g)throw new TypeError(`assurance provider ${_.provider} is not registered`);return I$(g.runtime_definition,_,e,t.trigger??"sdk")}}}import{createHash as $$}from"node:crypto";function Ck(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new TypeError("recurrence coverage request must be an object");let t=e;if(Object.hasOwn(t,"change"))throw new TypeError("recurrence coverage request does not accept change");if(t.uncoveredOnly!==void 0&&typeof t.uncoveredOnly!="boolean")throw new TypeError("recurrence coverage request.uncoveredOnly must be a boolean");let{policy:n,cursor:r,limit:s}=Ei({...t,change:{}});return{policy:n,...r===void 0?{}:{cursor:r},...s===void 0?{}:{limit:s},...t.uncoveredOnly===void 0?{}:{uncoveredOnly:t.uncoveredOnly}}}function N$(e,t){if(e===void 0)return 0;let n;try{n=JSON.parse(Buffer.from(e,"base64url").toString("utf8"))}catch{throw new TypeError("recurrence coverage cursor is invalid")}if(typeof n!="object"||n===null||Array.isArray(n))throw new TypeError("recurrence coverage cursor is invalid");let r=n;if(r.fingerprint!==t||typeof r.offset!="number"||!Number.isSafeInteger(r.offset)||r.offset<0)throw new TypeError("recurrence coverage cursor does not match this evidence and filter");return r.offset}function M$(e,t,n,r,s,i){let o=Object.fromEntries(bc.map(_=>[_,0])),a=0,c=0,d=0,l=0,u=[],f=$$("sha256").update(s);for(let _ of r){let h=e.membership.get(_),g=n.has(_),y=h.family_ids.length>0;y&&g&&(a+=1),y||(c+=1),g||(d+=1);let w=t.get(_)?.escape_class;w!==void 0&&bc.includes(w)&&(o[w]+=1,l+=1),f.update(Z([_,g,t.get(_)??null,h.id,h.family_ids])),(!i||!y||!g)&&u.push(_)}return{classCounts:o,coveredCount:a,uncoveredCount:c,missingCount:d,classifiedCount:l,selected:u,fingerprint:f.digest("hex")}}function Tk(e,t,n={}){lh(e);let r=n.limit??25;if(!Number.isSafeInteger(r)||r<1||r>100)throw new TypeError("recurrence coverage limit must be an integer from 1 through 100");let s=new Set,i=new Map;for(let b of t){if(s.has(b.id))throw new TypeError(`Duplicate recurrence item ${b.id}`);s.add(b.id);let k=Si(b);k!==void 0&&i.set(b.id,k)}let o=oh(e.families,i),a=[...o.membership.keys()].sort(),c=Z({policy:e,uncoveredOnly:n.uncoveredOnly===!0}),{classCounts:d,coveredCount:l,uncoveredCount:u,missingCount:f,classifiedCount:_,selected:h,fingerprint:g}=M$(o,i,s,a,c,n.uncoveredOnly===!0),y=N$(n.cursor,g);if(y>h.length)throw new TypeError("recurrence coverage cursor offset exceeds the selected population");let w=h.slice(y,y+r).map(b=>{let k=o.membership.get(b),A=s.has(b);return{item_id:b,lineage_id:k.id,lineage_item_count:k.item_ids.length,family_ids:k.family_ids,present:A,...A?k.family_ids.length===0?{finding:"unregistered_recurrence_item"}:{}:{finding:"missing_recurrence_item"}}}),v=y+w.length,S=a.length===0?null:d.production_defect/a.length;return{ok:u===0&&f===0,fingerprint:g,items:w,total:h.length,has_more:v<h.length,...v<h.length?{next_cursor:Buffer.from(JSON.stringify({fingerprint:g,offset:v})).toString("base64url")}:{},population:{scope:"all_recorded_recurrence_items",item_count:a.length,lineage_count:o.lineages.length,edge_count:o.edge_count,covered_item_count:l,uncovered_item_count:u,missing_item_count:f,classified_item_count:_,unclassified_item_count:a.length-_,class_counts:d,escape_rate:_===a.length?S:null,escape_rate_lower_bound:S},budget_scope:"registered_families_only",cost:{items_scanned:t.length,edges_scanned:o.edge_count,row_limit:r},row_contract:{row_keys:["items"],jq_selector:".items[]"}}}import{createHash as P$}from"node:crypto";var vl,Rk=["list","show","put","remove","run","verdicts","presets","apply","derive","promote","risk","lineages"],kl=["measurement","assertion","gate"];function F$(e){if(Rk.includes(e))return e;throw Qs({command_path:"assurance",token:e,allowed:Rk,display_name:"assurance action"})}function nr(e,t,n){throw new p(t,m.USAGE,{code:"missing_required_argument",required:`Provide the missing assurance operand: ${e}.`,examples:[n],recovery:{missing:[e]}})}function D$(e){if(!e)return nr("kind",`Assurance declaration kind is required. Expected: ${kl.join(", ")}`,"pm assurance list measurement");if(kl.includes(e))return e;throw new p(`Assurance declaration kind is required. Expected: ${kl.join(", ")}`,m.USAGE)}function Ik(e){if(!e)return nr("preset",`Assurance preset is required. Expected: ${rs.join(", ")}`,"pm assurance apply software-delivery --owner <pm-item-id>");if(rs.includes(e))return e;throw new p(`Assurance preset is required. Expected: ${rs.join(", ")}`,m.USAGE)}function bl(e){return e.owner?.trim()?e.owner.trim():nr("owner","assurance preset and derivation actions require --owner <pm-item-id>","pm assurance apply software-delivery --owner <pm-item-id>")}function j$(e,t){let n=t;if(typeof t=="string")if(!t.trim())n=void 0;else try{n=JSON.parse(t)}catch(r){throw new p("assurance definition must be valid JSON",m.USAGE,{reason:r instanceof Error?r.message:"invalid_json"})}if(typeof n!="object"||n===null||Array.isArray(n))throw new p("assurance put requires a JSON object definition",m.USAGE);return n}async function U$(e){let[t,n,r]=await Promise.all([Yr(e,"measurement"),Yr(e,"assertion"),Yr(e,"gate")]);return{version:1,measurements:t.items,assertions:n.items,gates:r.items}}function Ok(e,t){return t===!0?{id:e.id}:e}async function G$(e,t){let n=t.authorization_decision;if(!n)return[];let r=await ms(e,{include_history:!1,resolve_tree:!1}),s=r.items.find(o=>o.id===n),i=new Set(r.terminal_statuses);if(!s||s.type.toLowerCase()!=="decision"||!i.has(s.status))throw new p(`Assurance authorization ${n} must name a terminal Decision item`,m.USAGE);return[s.id]}async function q$(e,t){let n=Ac(e.limit,"assurance verdict limit");if(n!==void 0&&(n<1||n>1e3))throw new p(`assurance verdict limit must be an integer from 1 through ${1e3}`,m.USAGE);let r=await Qg(t,{gate_id:e.id??e.gate,limit:n});return{items:r,count:r.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function Lk(e,t,n){try{return await Hc(()=>Yg(e,t,n))}catch(r){if(!(r instanceof p)||r.context.reason!=="assurance_evaluation_refused")throw r;let s=["--pm-path",e,"assurance","list",t,"--output-budget","2000","--json"],i=L(s);throw Object.assign(r.context,{changed:!1,value:n,required:`Choose a configured ${t} declaration ID using the bounded discovery command.`,why:`The requested ${t} declaration does not exist. The registry and history were not changed.`,examples:[i],recovery:{next_best_command:i,suggested_retry:i,suggested_retry_args:s}}),r}}async function W$(e,t,n){if(e==="presets"){if(t.preset??t.id)return ro(Ik(t.preset??t.id),bl(t));let s=rs.map(i=>{let o=ro(i,"pm-owner");return{id:i,title:o.title,description:o.description}});return{items:s,count:s.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}if(e==="apply")return zn(()=>lw(n,Ik(t.preset??t.id),bl(t),{author:t.author,message:t.message}));if(e==="derive"){let s=await uw(await ms(n,{resolve_tree:!1,trigger:"derive"}),bl(t)),i=t.apply?await zn(()=>mw(n,s,{author:t.author,message:t.message??"Accept observation-derived assurance proposals"})):void 0;return{items:s,count:s.length,...i?{applied:i}:{}}}if(!t.id)return nr("assertion-id","assurance promote requires an assertion id","pm assurance promote <assertion-id> --enforcement warn");if(t.enforcement!=="warn"&&t.enforcement!=="block")throw new p("assurance promote requires --enforcement warn|block",m.USAGE);let r=await Lk(n,"assertion",t.id);return zn(()=>fw(n,r,t.enforcement,{author:t.author,message:t.message}))}async function K$(e,t,n){if(!e.id)return nr("gate-id","assurance run requires a gate id","pm assurance run <gate-id> --trigger ci --dry-run");let r=e.id;if(!e.trigger)throw new p("assurance run requires a trigger",m.USAGE);if(!vt.includes(e.trigger))throw new p(`Unknown assurance trigger ${e.trigger}. Expected: ${vt.join(", ")}`,m.USAGE);let s=e.trigger,[i,o]=await Promise.all([U$(t),ms(t,{...n.workspace,tree_id:e.tree,trigger:s})]),a=await Hc(()=>Hg(r,i,o,{trigger:s,dry_run:e.dry_run===!0}));return a.dry_run||await Xg(t,a,{author:e.author,message:e.message}),a}function $k(e){throw e instanceof p?e:new p(e instanceof Error?e.message:"assurance risk request is invalid",m.USAGE)}function z$(e){if(e.limit!==void 0)throw new p(`assurance ${e.action} does not accept --limit; set limit inside the definition`,m.USAGE);let t=e.definition;if(typeof t=="string")try{t=JSON.parse(t)}catch(n){throw new p(`assurance ${e.action} definition must be valid JSON`,m.USAGE,{reason:n instanceof Error?n.message:"invalid_json"})}try{return e.action==="lineages"?Ck(t):Ei(t)}catch(n){if(e.action==="risk"&&n instanceof dh)throw new p(n.message,m.USAGE,{required:"Supply definition.policy with the project's declared recurrence policy and definition.change with the proposed change; no policy is inferred.",recovery:{suggested_retry:`pm assurance ${e.action} --help`,suggested_retry_args:["assurance",e.action,"--help"]}});return $k(n)}}function B$(e,t){let n=new Set;for(let[r,s]of t)e.item_fingerprints.get(r)!==s&&n.add(r);for(let r of e.item_fingerprints.keys())t.has(r)||n.add(r);return n}function H$(e,t,n){let r=Z(t.policy),s=vl?.pm_root===e?vl:void 0,i=new Map(n.map(d=>[d.id,P$("sha256").update(Z([ih(d),Si(d)])).digest("hex")])),o=s?.policy_serialized===r?s:void 0,a=o?B$(o,i):new Set,c=ah(t.policy,o?n.filter(d=>a.has(d.id)):n,o?{previous_index:o.index,changed_item_ids:[...a]}:{});return vl={pm_root:e,policy_serialized:r,item_fingerprints:i,index:c},c}async function V$(e,t){let n=z$(e),r=await ms(t,{strict_read:!0,include_history:!1,resolve_tree:!1});try{return"change"in n?ch(H$(t,n,r.items),n.change,{cursor:n.cursor,limit:n.limit}):Tk(n.policy,r.items,n)}catch(s){return $k(s)}}async function Y$(e,t={},n={}){let r=F$(e.action),s=I(process.cwd(),t.path);if(r==="presets"||r==="apply"||r==="derive"||r==="promote")return W$(r,e,s);if(r==="verdicts")return q$(e,s);if(r==="run")return K$(e,s,n);if(["risk","lineages"].includes(r))return V$(e,s);let i=D$(e.kind);if(r==="list")return Yr(s,i);if(!e.id)return nr("id",`assurance ${r} requires an id`,`pm assurance ${r} ${i} <id>`);let o=e.id;if(r==="show")return Lk(s,i,o);if(r==="remove"){let l=await zn(()=>Jg(s,i,o,{author:e.author,message:e.message}));return Ok(l,e.idOnly)}let a=j$(i,e.definition);if(a.id!==o)throw new p(`Assurance definition id ${a.id} does not match requested id ${o}`,m.USAGE);let c={author:e.author,message:e.message,...i==="assertion"?{authorized_decision_ids:await G$(s,a)}:{}},d=await zn(()=>Ki(s,i,a,c));return Ok(d,e.idOnly)}function $Y(e,t,n){let r={...e,...t};return Y$({action:te(r,"subcommand")??te(r,"assuranceAction")??te(r,"operation")??"",kind:te(r,"kind"),id:te(r,"id"),definition:r.definition,trigger:te(r,"trigger"),tree:te(r,"treeId")??te(r,"tree"),gate:te(r,"gate"),limit:Ac(r.limit,"assurance verdict limit"),dry_run:r.dryRun===!0||r.dry_run===!0,fullChangedFields:r.fullChangedFields===!0,idOnly:r.idOnly===!0,author:te(r,"author"),message:te(r,"message"),preset:te(r,"preset"),owner:te(r,"owner"),apply:r.apply===!0,enforcement:te(r,"enforcement")},n)}import xl from"node:fs/promises";import Nk from"node:path";var J$=1440*60*1e3,X$=new Set(["committed","compensated"]);function Q$(e){let t;try{t=JSON.parse(e)}catch{return{status:null,updatedAt:null}}if(typeof t!="object"||t===null||Array.isArray(t))return{status:null,updatedAt:null};let n=t;return{status:n.abandonment!==void 0?"abandoned":typeof n.status=="string"?n.status:null,updatedAt:typeof n.updatedAt=="string"?n.updatedAt:null}}function Z$(e,t,n,r,s){let i=n===null?Number.NaN:Date.parse(n);if(t===null||!Number.isFinite(i))return{entry:{file:e,status:t,age_seconds:null,stale:!1,reason:"unparseable"},remove:!1};let o=r-i;return X$.has(t)?o>s?{entry:{file:e,status:t,age_seconds:Math.floor(o/1e3),stale:!0},remove:!0}:{entry:{file:e,status:t,age_seconds:Math.floor(o/1e3),stale:!1,reason:"fresh"},remove:!1}:{entry:{file:e,status:t,age_seconds:Math.floor(o/1e3),stale:!1,reason:"active"},remove:!1}}async function eN(e,t,n,r){let s=r.hooks?.onRead?await r.hooks.onRead(e):[],i=Q$(await xl.readFile(e,"utf8")),o=Z$(t,i.status,i.updatedAt,r.nowMs,r.retentionMs);return o.entry.reason==="unparseable"&&s.push(`transaction_journal_unparseable:${n}`),o.remove&&!r.dryRun&&(await xl.rm(e,{force:!0}),r.hooks?.onWrite&&s.push(...await r.hooks.onWrite(e))),{decision:o,warnings:s}}async function Mk(e,t){let{dryRun:n,hooks:r}=t,s=t.now??Date.now(),i=Math.max(0,t.retentionDays)*J$,o=Nk.join(e,"transactions","sdk"),a={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c;try{c=(await xl.readdir(o)).filter(d=>d.endsWith(".json")).sort((d,l)=>d.localeCompare(l))}catch(d){if(U(d))return a;throw d}for(let d of c){let l=Nk.join(o,d),u=`transactions/sdk/${d}`,f=await eN(l,u,d,{dryRun:n,hooks:r,nowMs:s,retentionMs:i});a.warnings.push(...f.warnings),a.scanned+=1;let{decision:_}=f;if(!_.remove){a.retained.push(u),a.entries.push(_.entry);continue}a.removed.push(u),a.entries.push(_.entry)}return a}import mn from"node:fs/promises";import ps from"node:path";import Co from"node:fs/promises";import Sl from"node:path";var tN=864e5;function nN(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t.created_at;return typeof n=="string"?n:null}async function rN(e,t){let n;try{n=await Co.readdir(e,{withFileTypes:!0})}catch(s){if(U(s))return[];throw s}let r=[];for(let s of n)if(s.isDirectory()){let i=Sl.join(e,s.name),o;try{o=await Co.readdir(i)}catch(a){U(a)||t.push(`checkpoint_subdir_unreadable:${s.name}`);continue}for(let a of o)a.endsWith(".json")&&r.push(`${s.name}/${a}`)}else s.name.endsWith(".json")&&r.push(s.name);return r.sort()}async function Pk(e,t){let{dryRun:n,hooks:r}=t,s=t.now??Date.now(),i=Math.max(0,t.retentionDays)*tN,o=Sl.join(e,"checkpoints"),a={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c=await rN(o,a.warnings);for(let d of c){let l=Sl.join(o,d),u=`checkpoints/${d}`;a.scanned+=1,r?.onRead&&a.warnings.push(...await r.onRead(l));let f;try{f=await Co.readFile(l,"utf8")}catch(w){if(U(w)){a.scanned-=1;continue}a.warnings.push(`checkpoint_unreadable:${d}`),a.retained.push(u),a.entries.push({file:u,created_at:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let _=nN(f),h=_===null?Number.NaN:Date.parse(_);if(!Number.isFinite(h)){a.warnings.push(`checkpoint_unparseable:${d}`),a.retained.push(u),a.entries.push({file:u,created_at:_,age_seconds:null,stale:!1,reason:"unparseable"});continue}let g=s-h,y={file:u,created_at:_,age_seconds:Math.floor(g/1e3),stale:g>i,reason:g>i?"expired":"active"};if(!y.stale){a.retained.push(u),a.entries.push(y);continue}if(!n){try{await Co.unlink(l)}catch(w){if(!U(w)){a.warnings.push(`checkpoint_remove_failed:${d}`),a.retained.push(u),a.entries.push(y);continue}}r?.onWrite&&a.warnings.push(...await r.onWrite(l))}a.removed.push(u),a.entries.push(y)}return a}var fs=["index","embeddings","runtime","locks","checkpoints","transactions"],sN=1440*60*1e3,Fk=[{scope:"index",relativePath:"index/manifest.json",kind:"file"},{scope:"embeddings",relativePath:"search/embeddings.jsonl",kind:"file"},{scope:"embeddings",relativePath:"search/vectorization-status.json",kind:"file"},{scope:"embeddings",relativePath:"search/lancedb",kind:"directory"},{scope:"embeddings",relativePath:"search/pending-refresh.json",kind:"file"},{scope:"embeddings",relativePath:"search/pending-refresh.gate.lock",kind:"directory"},{scope:"runtime",relativePath:"runtime/test-runs",kind:"directory"},{scope:"runtime",relativePath:"runtime/history-drift-cache.json",kind:"file"},{scope:"runtime",relativePath:"runtime/history-stream-summary.json",kind:"file"}];async function iN(e,t,n){let r=t.relativePath,s=ps.join(e,r),i=await He({path:s,scope:"project"});if(t.scope==="runtime"&&await Dk(e))return{removed:!1,redirected:!0,warnings:i};try{let o=await mn.lstat(s);if(t.kind==="file"&&!o.isFile())return{removed:!1,warnings:[...i,`not_a_file:${r}`]};if(t.kind==="directory"&&!o.isDirectory())return{removed:!1,warnings:[...i,`not_a_directory:${r}`]};if(n)return{removed:!0,warnings:i};t.kind==="file"?await mn.unlink(s):await mn.rm(s,{recursive:!0,force:!0});let a=await yt({path:s,scope:"project",op:"gc:remove"});return{removed:!0,warnings:[...i,...a]}}catch(o){if(U(o))return{removed:!1,warnings:i};throw o}}async function oN(e,t,n){let r=[],s=[],i=[],o=!1;for(let a of Fk.filter(c=>t.includes(c.scope))){if(a.scope==="runtime"&&o){s.push(a.relativePath);continue}let c=await iN(e,a,n);o||=c.redirected===!0,(c.removed?r:s).push(a.relativePath),i.push(...c.warnings)}if(t.includes("runtime")&&!o&&(o=await Dk(e)),o)i.push("redirected_runtime_directory:runtime");else if(t.includes("runtime")){let a=await aN(e,n);r.push(...a.removed),s.push(...a.retained),i.push(...a.warnings)}return{removed:r,retained:s,warnings:i}}async function Dk(e){try{return!(await mn.lstat(ps.join(e,"runtime"))).isDirectory()}catch(t){if(U(t))return!1;throw t}}async function aN(e,t){let n=[{relativePath:"runtime/workspace-snapshots/objects",prefix:".create-"},{relativePath:"runtime/workspace-snapshots/refs",prefix:".ref-"}],r=[],s=[],i=[],o=Date.now()-sN;for(let a of n){let c=ps.join(e,a.relativePath);if(!await se(c))continue;let d=(await mn.readdir(c)).filter(l=>l.startsWith(a.prefix)).sort();for(let l of d){let u=ps.posix.join(a.relativePath,l),f=ps.join(c,l);i.push(...await He({path:f,scope:"project"}));let _=await mn.stat(f).catch(h=>{if(!U(h))throw h});if(_){if(_.mtimeMs>o){s.push(u);continue}r.push(u),!t&&(await mn.rm(f,{recursive:!0,force:!0}),i.push(...await yt({path:f,scope:"project",op:"gc:workspace_snapshot_temp_remove"})))}}}return{removed:r,retained:s,warnings:i}}function cN(e){if(!e||e.length===0)return[...fs];let t=e.flatMap(r=>r.split(",")).map(r=>r.trim().toLowerCase()).filter(r=>r.length>0);if(t.length===0)throw new p(`--scope requires at least one value (${fs.join(",")})`,m.USAGE);let n=new Set;for(let r of t){if(!fs.includes(r))throw new p(`Invalid --scope value "${r}". Expected one or more of: ${fs.join(", ")}`,m.USAGE);n.add(r)}return fs.filter(r=>n.has(r))}function dN(e){let t=[];e.dryRun&&t.push("Dry-run preview only: no cache artifacts were deleted.");let n=e.scopes.includes("index")||e.scopes.includes("embeddings"),r=e.removed.some(s=>s==="index/manifest.json"||s==="search/embeddings.jsonl"||s==="search/vectorization-status.json"||s==="search/lancedb"||s==="search/pending-refresh.json"||s==="search/pending-refresh.gate.lock");return n&&r&&t.push('Search artifacts were removed; the semantic index (including any queued background refresh) is invalidated. Run "pm install search-advanced --project" if reindex is unavailable, then "pm reindex --mode keyword" (and "--mode semantic" when semantic search is enabled) before search-heavy workflows.'),e.removed.includes("runtime/history-drift-cache.json")&&t.push('History drift cache was removed; the next "pm health" run performs a full history-drift re-scan.'),e.removed.includes("runtime/history-stream-summary.json")&&t.push('History stream summary was removed; the next "pm activity" or "pm context" read parses every history stream once to rebuild it.'),!e.dryRun&&e.removed.some(s=>s.startsWith("checkpoints/"))&&t.push('Aged rollback checkpoints were removed; their "pm update-many"/"pm close-many --rollback" windows are no longer recoverable.'),!e.dryRun&&e.removed.some(s=>s.startsWith("transactions/"))&&t.push("Aged terminal workspace-transaction journals were removed; replaying those transactionIds re-executes their idempotent steps instead of short-circuiting."),t}async function nJ(e,t={}){let n=I(process.cwd(),e.path);await j(n);let r=await C(n),s=t.dryRun===!0,i=cN(t.scope),{removed:o,retained:a,warnings:c}=await oN(n,i,s),d;if(i.includes("locks")){let _=await Nw(n,{dryRun:s,hooks:{onRead:h=>He({path:h,scope:"project"}),onWrite:h=>yt({path:h,scope:"project",op:"gc:lock_remove"})}});o.push(..._.removed),a.push(..._.retained),c.push(..._.warnings),d={scanned:_.scanned,removed:_.removed.length,retained:_.retained.length}}let l;if(i.includes("transactions")){let _=r.checkpoints.retention_days,h=await Mk(n,{dryRun:s,retentionDays:_,hooks:{onRead:g=>He({path:g,scope:"project"}),onWrite:g=>yt({path:g,scope:"project",op:"gc:transaction_journal_remove"})}});o.push(...h.removed),a.push(...h.retained),c.push(...h.warnings),l={scanned:h.scanned,removed:h.removed.length,retained:h.retained.length,retention_days:_}}let u;if(i.includes("checkpoints")){let _=r.checkpoints.retention_days,h=await Pk(n,{dryRun:s,retentionDays:_,hooks:{onRead:g=>He({path:g,scope:"project"}),onWrite:g=>yt({path:g,scope:"project",op:"gc:checkpoint_remove"})}});o.push(...h.removed),a.push(...h.retained),c.push(...h.warnings),u={scanned:h.scanned,removed:h.removed.length,retained:h.retained.length,retention_days:_}}c.push(...await Of({mode:s?"gc:dry-run":"gc",total_items:Fk.filter(_=>i.includes(_.scope)).length}));let f=dN({dryRun:s,scopes:i,removed:o});return{ok:c.length===0,dry_run:s,scope:i,removed:o,retained:a,warnings:c,...d?{locks:d}:{},...u?{checkpoints:u}:{},...l?{transactions:l}:{},guidance:f,generated_at:O()}}var oJ=Object.freeze({requireCloseReason:!0,orderingEdges:"preserve"});function lN(e){let t=[{source:"explicit",value:e.explicit},{source:"duplicate",value:e.duplicateOf===void 0?void 0:`Duplicate of ${e.duplicateOf}`},{source:"resolution",value:e.resolution},{source:"message",value:e.message}];for(let n of t){let r=n.value?.trim();if(r)return{closeReason:r,source:n.source}}return{source:"none"}}function To(e,t){return El(e,t,{operation:"close"})}function El(e,t,n){let r=lN(e);if(!t||r.closeReason!==void 0)return r;let s=n.operation==="create"?[`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --close-reason "<closing summary>"`,`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --resolution "<resolution summary>"`,"pm create --stdin-json < item.json"]:['pm close <id> "Done: <what changed and why>"','pm close <id> --reason "<closing summary>"','pm close <id> -m "<closing summary>"',"pm close <id> --duplicate-of <canonical-id>"];throw new p("Close reason text is required because governance.require_close_reason is enabled",m.USAGE,{code:"close_reason_required",required:"Provide an author-controlled closing summary as the reason, message, resolution, or duplicate target.",why:"governance.require_close_reason is enabled, so tools must not invent immutable closure evidence.",examples:s,nextSteps:[`Re-run the ${n.operation} operation with a closing summary.`,"To stop requiring reasons, run: pm config set governance-require-close-reason --policy disabled"]})}function jk(e,t){let n=typeof e.blocked_by=="string"?e.blocked_by.trim():"",r=e.blocked_by!==void 0,s=e.dependencies??[],i=s.filter(d=>d.kind==="blocked_by"),o=e.blocked_reason!==void 0,a=[];if(r&&(delete e.blocked_by,a.push("blocked_by")),o&&(delete e.blocked_reason,a.push("blocked_reason")),t.orderingEdges==="remove"&&i.length>0){let d=new Set(i),l=s.filter(u=>!d.has(u));l.length>0?e.dependencies=l:delete e.dependencies,a.push("dependencies")}if(t.orderingEdges==="remove")return{changedFields:a,warnings:[...n?[`closed_cleared_blocked_by:${e.id}:${n}`]:[],...i.length>0?[`closed_removed_predecessors:${e.id}:${i.map(d=>d.id).join(",")}`,`closed_removed_predecessors_count:${e.id}:${i.length}`]:[]]};let c=[...new Set([...n?[n]:[],...i.map(d=>d.id)])];return c.length===0?{changedFields:a,warnings:[]}:{changedFields:a,warnings:[`closed_preserved_predecessors:${e.id}:${c.join(",")}`]}}var uN=[{key:"resolution",label:"resolution (--resolution)"},{key:"expected_result",label:"expected_result (--expected-result)"},{key:"actual_result",label:"actual_result (--actual-result)"}];function mN(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0||t==="warn")return"warn";if(t==="off"||t==="none"||t==="disabled")return"off";if(t==="strict")return"strict";throw new p(`Invalid --validate-close mode "${e}" (expected "off", "warn", or "strict")`,m.USAGE)}function Gk(e){let t=[];for(let n of uN){let r=e[n.key];(typeof r!="string"||r.trim().length===0)&&t.push(n)}return t}function qk(e,t,n={}){let r=Gk(e);if(r.length===0)return;let s={resolution:n.resolution,expected_result:n.expectedResult,actual_result:n.actualResult},i=r.map(a=>`--${a.key.replaceAll("_","-")}`),o=[...t,"update",e.id,...r.flatMap((a,c)=>[i[c],s[a.key]?.trim()||"<value>"])];return{missing:i,suggested_retry:L(o),suggested_retry_args:o}}async function fN(e,t,n){let r=new Set,s=t;for(;typeof s=="string"&&s.trim().length>0;){let i=s.trim();if(i===n)return!0;if(r.has(i))return!1;r.add(i),s=(await e(i))?.duplicate_of}return!1}function pN(e){return typeof e!="string"||e.trim().length===0}async function _N(e,t,n,r){let s=n?.trim();if(!s)return;if(s===r)throw new p("An item cannot be closed as a duplicate of itself.",m.USAGE,{code:"duplicate_target_self",why:"--duplicate-of must identify the canonical item that should remain open or already represent the work."});let i=D(t,F()),o=new Map,a=async d=>{if(o.has(d))return o.get(d)??null;let l=await Y(e,d,t.id_prefix,t.item_format,i.type_to_folder);if(!l)return o.set(d,null),null;let{document:u}=await fe(l,{schema:t.schema});return o.set(d,u.metadata),u.metadata},c=await a(s);if(!c)throw new p(`Duplicate target "${s}" was not found. Create or locate the canonical item first.`,m.USAGE,{code:"duplicate_target_missing",why:"Duplicate closure should point at a real canonical pm item so future dedupe and changelog tooling can trace the relationship.",examples:[`pm close ${r} "Duplicate of ${s}" --duplicate-of ${s}`],nextSteps:["Run pm search/list to find the canonical item, then retry with --duplicate-of <id>."]});if(await fN(a,c.duplicate_of,r))throw new p(`Circular duplicate reference detected. Target "${s}" points back to "${r}".`,m.USAGE,{code:"duplicate_target_circular",why:"Circular duplicate relationships create loops for dedupe and status propagation tooling.",nextSteps:["Choose the existing canonical item, or clear the target duplicate_of metadata before closing this item as a duplicate."]});if(typeof c.duplicate_of=="string"&&c.duplicate_of.trim().length>0)throw new p(`Duplicate target "${s}" is already marked as a duplicate of "${c.duplicate_of.trim()}".`,m.USAGE,{code:"duplicate_target_is_duplicate",why:"Duplicate closure should point directly at the canonical item, not another duplicate.",examples:[`pm close ${r} "Duplicate of ${c.duplicate_of.trim()}" --duplicate-of ${c.duplicate_of.trim()}`],nextSteps:["Use the canonical item referenced by duplicate_of as the --duplicate-of target."]});return c.id}function hN(e,t,n){return e.filter(r=>r.parent===t&&!_e(r.status,n)).map(r=>r.id).sort((r,s)=>r.localeCompare(s))}function gN(e,t,n){let r=new Map(e.map(a=>[a.id.trim().toLowerCase(),a])),s=fp(e),i=t.trim().toLowerCase(),o=n.blocked_statuses;return e.filter(a=>o.has(a.status)).map(a=>({item:a,blockerIds:s.get(a.id.trim().toLowerCase())})).filter(({blockerIds:a})=>a.includes(i)).filter(({blockerIds:a})=>a.every(c=>{if(c===i)return!0;let d=r.get(c);return d!==void 0&&_e(d.status,n)})).map(({item:a,blockerIds:c})=>({id:a.id,blocker_ids:c})).sort((a,c)=>a.id.localeCompare(c.id))}async function yN(e,t,n,r,s,i,o){let a=gN(n,r,i),c=[],d=[],l=[],u=[],f;for(let _ of a)try{let h=await he({pmRoot:e,settings:t,id:_.id,op:"update",author:s,message:`Auto-unblocked after blocker ${r} closed`,mutate(g){let y=g.metadata.dependencies??[],w=y.filter(S=>{let b=S.id.trim().toLowerCase();return S.kind!=="blocked_by"||!_.blocker_ids.includes(b)});g.metadata.status=i.open_status,delete g.metadata.blocked_by,delete g.metadata.blocked_reason,g.metadata.unblock_note=`Auto-unblocked after blocker ${r} closed; all blockers resolved (${_.blocker_ids.join(", ")}).`,w.length>0?g.metadata.dependencies=w:delete g.metadata.dependencies;let v=["status","blocked_by","blocked_reason","unblock_note"];return w.length!==y.length&&v.push("dependencies"),{changedFields:v}}});c.push(`auto_unblocked:${h.item.id}:resolved_blockers=${_.blocker_ids.join(",")}`),d.push(h.item.id)}catch(h){let g=h instanceof Error?h.message.replace(/\s+/g," ").trim():"unknown";tn(h)?(f??=h,l.push(_.id)):u.push({id:_.id,reason:g}),c.push(`auto_unblock_failed:${_.id}:${g}`)}if(f!==void 0){let _=await gp(f,e),h=[...i.blocked_statuses].sort().join(",");throw bN(_,{closedId:r,unblockedIds:d,conflictIds:l,failed:u,openStatus:i.open_status,blockedStatuses:h,commandScope:o})}return c}var At=10,Al=20,wN=[{list:"auto_unblock_failed",omitted:"auto_unblock_failed_omitted",floor:0},{list:"changes_since",omitted:"changes_since_omitted",floor:0},{list:"pending_unblock",omitted:"pending_unblock_omitted",floor:1}];function vN(e){for(let t of wN){let n=e[t.list];if(Array.isArray(n))for(;n.length>t.floor&&!sp(e);)n.pop(),Reflect.set(e,t.omitted,Number(e[t.omitted])+1)}return e}function Uk(e){let t=e.length-At;return`${e.slice(0,At).join(", ")}${t>0?`, and ${t} more`:""}`}var kN="post_close_auto_unblock_refused";function bN(e,t){let{closedId:n,conflictIds:r,failed:s,commandScope:i}=t,o=String(e.context.item_id),a=h=>L([...i,"update",h,"--status",t.openStatus,"--unset","blocked_by","--unset","blocked_reason","--expect-hash",`${h}=<item_hash>`]),c=s.slice(0,At).map(h=>({id:h.id,reason:cf(h.reason,160)})),d=s.length===0?"":` Auto-unblocking also failed for ${Uk(s.map(h=>h.id))}; details.auto_unblock_failed gives the reasons it kept (auto_unblock_failed_omitted counts the rest; their get step shows the item). Fix that cause before unblocking it.`,l=L([...i,"list","--status",t.blockedStatuses,"--fields","id,title,blocked_by,dependencies","--limit","200"]),u=[...r.slice(0,At).flatMap(h=>[L([...i,"get",h,"--json"]),a(h)]),...c.map(h=>L([...i,"get",h.id,"--json"]))],f=r.length>At||s.length>At||u.length>Al,_=u.slice(0,f?Al-1:Al);return new p(`${n} was closed, but auto-unblocking ${o} was refused. ${e.message}`,e.exitCode,{...e.context,reason:kN,examples:kf(o,!1,{scopeArgs:i}).examples,required:`The close of ${n} is complete; do not retry it. Only unblocking ${r.length===1?o:`the guarded dependents it refused (${Uk(r)})`} remains: re-read each one (pm get <id> --json reports item_hash), check that every blocker it declares is resolved, then unblock it with ${a(o)}${r.length===1?"":" for each id"}.${d}${f?` This refusal does not list a step for every dependent left blocked; list them with ${l}, and while it reports has_more, continue with --after <next_cursor>.`:""}`,nextSteps:f?[..._,l]:_,details:vN({...structuredClone(e.context.details),pending_unblock:r.slice(0,At),pending_unblock_omitted:Math.max(0,r.length-At),auto_unblock_failed:c,auto_unblock_failed_omitted:Math.max(0,s.length-At)}),side_effects:[{path:`history/${n}.jsonl`,op:"close"},...t.unblockedIds.map(h=>({path:`history/${h}.jsonl`,op:"update"}))]})}async function bJ(e,t,n){if(!tn(e)||!e.context.side_effects?.some(i=>`${i.op}:${i.path}`==`close:history/${t}.jsonl`))return;let r=String(e.context.item_id);return{warnings:[...e.context.side_effects.filter(i=>i.op==="update").map(i=>i.path.slice(8,-6)).map(i=>`auto_unblocked:${i}`),`auto_unblock_refused:${r}:item_revision_conflict`],dependent_revision_conflict:{item_id:r,error:Ys(e),...await _p(e,n)}}}function xN(e,t){let n=[],r=[{option:t.resolution,key:"resolution"},{option:t.expectedResult,key:"expected_result"},{option:t.actualResult,key:"actual_result"}];for(let{option:s,key:i}of r){if(typeof s!="string")continue;let o=s.trim();o.length!==0&&(e[i]=o,n.push(i))}return n}function SN(e,t){if(t===void 0)return[];e.duplicate_of=t;let n=[],r=[{key:"resolution",value:`Duplicate of ${t}`},{key:"expected_result",value:`Canonical item ${t} tracks the work.`},{key:"actual_result",value:`Closed as duplicate of ${t}.`}];for(let{key:s,value:i}of r)pN(e[s])&&(e[s]=i,n.push(s));return n}function EN(e,t){let r=[["--resolution",e.resolution],["--expected-result",e.expectedResult],["--actual-result",e.actualResult],["--validate-close",e.validateClose],["--completed-at",e.completedAt],["--message",e.message],["--author",e.author]].flatMap(([s,i])=>t.has(s)||i===void 0||i.trim().length===0?[]:[`${s}=${i}`]);return e.force===!0?[...r,"--force"]:r}function AN(e,t,n){let r=t.map(y=>y.label),s=t.map(y=>`--${y.key.replaceAll("_","-")}`),i=s.flatMap(y=>[y,"<value>"]),o=[...n.commandScope,"update",e.id,...i],a=`Cannot close item ${e.id}: missing ${r.join(", ")}. Populate fields or use --validate-close warn.`,c="Use --validate-close warn only when governance permits an evidenced exception.",d=Object.entries(n.options.lifecyclePolicy??{}).filter(([,y])=>y!==void 0).map(([y])=>y),l=Er(n.pmRoot),u=typeof n.options.author=="string"&&n.options.author.trim().length===0,f=d.length>0?`its lifecyclePolicy override (${d.join(", ")}) has no CLI spelling`:u?"its explicitly blank author has no CLI spelling (pm close refuses an empty --author)":l===void 0?"its revision guards cannot be replayed as typed (nested revision guards expect different revisions of one item, or a write in the same operation advanced a guarded revision)":void 0;if(f!==void 0)return new p(a,m.USAGE,{code:"close_validation_missing_fields",required:`Pass ${t.map(y=>y.key).join(", ")} on the same SDK close; ${f}, so no CLI retry reproduces it.`,recovery:{missing:s,next_best_command:L(o)},nextSteps:["Retry the same SDK close with the missing evidence supplied, inside the same lifecycle policy and revision guards.",c]});let _=n.closeReason===void 0?[]:[`--reason=${n.closeReason}`],h=l.map(y=>`--expect-hash=${y}`),g=[...n.commandScope,"close",e.id,..._,...EN(n.options,new Set(s)),...h,...i];return new p(a,m.USAGE,{code:"close_validation_missing_fields",required:`Supply ${s.join(", ")}: pm close accepts them and records them in the same write as the closure.`,recovery:{missing:s,suggested_retry:L(g),suggested_retry_args:g,next_best_command:L(o)},nextSteps:["Run recovery.suggested_retry when it is present: the same close with the missing flags added, so one write records the evidence and the closure.","Without it, record the evidence with recovery.next_best_command, then repeat the original close.",c]})}function CN(e,t,n,r){let s=t.map(a=>zm(a.field).flag),i=[...r.author?.trim()?[`--author=${r.author}`]:[],...r.force===!0?["--force"]:[]],o=[...n,"update",e.id,...i,...s.flatMap(a=>[a,"<value>"])];return new p(`Cannot close item ${e.id}: deferred fields still have no value (${t.map(a=>a.field).join(", ")}). Supply them or use --validate-close warn.`,m.USAGE,{code:"close_validation_deferred_fields",required:`Supply ${s.join(", ")}: each was deferred at create (${t.map(a=>`${a.field}: ${a.reason}`).join("; ")}).`,recovery:{missing:s,next_best_command:L(o)},nextSteps:["Record the now-known values with recovery.next_best_command; the update resolves each deferral, then repeat the close.","Use --validate-close warn only when governance permits closing with deferred values still unknown."]})}function TN(e,t,n){let r=si(e);if(r.length===0)return[];if(t==="strict")throw CN(e,r,n.commandScope,n.options);return[`close_validation_deferred_fields:${e.id}:${r.map(s=>s.field).join(",")}`]}function RN(e,t,n,r){let s=[];if(t!=="off"){s.push(...TN(e,t,r));let i=Gk(e);if(i.length>0){let o=i.map(a=>a.label);if(t==="strict")throw AN(e,i,r);s.push(`close_validation_missing_fields:${e.id}:${o.join(",")}`)}if(n.length>0){if(t==="strict")throw new p(`Cannot close item ${e.id}: active child items remain open (${n.join(", ")}). Close, cancel, or re-parent them first, or use --validate-close warn.`,m.USAGE);s.push(`close_validation_active_children:${e.id}:${n.join(",")}`)}return s}return n.length>0&&s.push(`closed_with_active_children:${e.id}:${n.join(",")}`),s}function IN(e,t){return t!==void 0?(e.close_reason=t,["close_reason"]):[]}function ON(e){let t=["assignee","claim_principal"].filter(n=>e[n]!==void 0);for(let n of t)delete e[n];return[...t]}function LN(e,t){if(_e(e.status,t.statusRegistry)&&!t.force)throw new p(`Item ${e.id} is already terminal; use pm update to append acceptance evidence, or --force only for an intentional repeat closure.`,m.CONFLICT,{recovery:qk(e,t.commandScope,t.options)});let n=xN(e,t.options),r=SN(e,t.duplicateOf),s=RN(e,t.validateCloseMode,t.activeChildIds,t);e.status=t.statusRegistry.close_status,e.closed_at=t.closedAt;let i=t.options.completedAt!==void 0||e.completed_at===void 0;i&&(e.completed_at=t.completedAt);let o=["status","closed_at",...i?["completed_at"]:[],...IN(e,t.closeReason),...n];if(cp(e)&&(e.plan_mode="completed",o.push("plan_mode")),t.duplicateOf!==void 0){o.push("duplicate_of");for(let c of r)o.includes(c)||o.push(c)}o.push(...ON(e));let a=jk(e,t.lifecyclePolicy);return o.push(...a.changedFields),s.push(...a.warnings),{changedFields:o,...s.length>0?{warnings:s}:{}}}async function $N(e,t,n,r){let s=I(process.cwd(),r.path),i=Le(r);await j(s);let o=await C(s),a=z(o.schema),c=G(n.author,o.author_default),d=D(o,F()).type_to_folder,l=await Y(s,e,o.id_prefix,o.item_format,d);if(!l)throw await Zt(s,e,o.id_prefix,d);let u=await _N(s,o,n.duplicateOf,l.id),f={requireCloseReason:n.lifecyclePolicy?.requireCloseReason??o.governance.require_close_reason,orderingEdges:n.lifecyclePolicy?.orderingEdges??"preserve"},_=To({explicit:t,duplicateOf:u,resolution:n.resolution,message:n.message},f.requireCloseReason).closeReason,h=mN(n.validateClose)??o.governance.close_validation_default,g=await Ae(s,o.item_format,d,void 0,o.schema),y=hN(g,l.id,a),w=O(),v=n.completedAt===void 0?w:me(n.completedAt,new Date(w),"completed-at"),S={timestamp:v,source:n.completedAt===void 0?"close_time":"asserted",...n.completedAt===void 0?{hint:`completed_at defaults to the close time. If work finished earlier, correct it with ${L([...i,"update",l.id,"--completed-at","<ISO>"])}.`}:{}},b=await Lt({pmRoot:s,settings:o,id:l.id,op:"close",author:c,message:n.message,force:n.force,resolveHistoryContext:()=>({completion:{timestamp:S.timestamp,source:S.source}}),mutate(A){return n.completedAt===void 0&&A.metadata.completed_at!==void 0&&(S={timestamp:A.metadata.completed_at,source:"existing"}),LN(A.metadata,{pmRoot:s,commandScope:i,statusRegistry:a,force:n.force,options:n,duplicateOf:u,validateCloseMode:h,activeChildIds:y,closeReason:_,closedAt:w,completedAt:v,lifecyclePolicy:f})}}),k=h==="warn"?qk(b.item,i):void 0;return{item:b.item,changed_fields:b.changedFields,...k?{follow_up:{kind:"complete_close_evidence",missing:k.missing,suggested_command:k.suggested_retry,suggested_command_args:k.suggested_retry_args}}:{},warnings:[...b.warnings,...await yN(s,o,g,l.id,c,a,i)],completion:S}}function Ro(e,t,n,r){return $N(e,t,n,r)}function Wk(e){return[...e].sort().join("\0")}function NN(e,t,n){let r=e.successors.get(t);r?r.push(n):e.successors.set(t,[n]);let s=e.predecessors.get(n);s?s.push(t):e.predecessors.set(n,[t])}function Kk(e,t,n,r,s){let i=t.resolve(s);if(i?.ordering!==!0)return;let o=bh(r),a=o===void 0?void 0:e.canonicalIds.get(o.toLowerCase());if(a===void 0)return;let c=(i.precedence??"source_before_target")==="source_before_target";NN(e,c?n:a,c?a:n)}function MN(e,t){let n={successors:new Map,predecessors:new Map,canonicalIds:new Map},r=e.filter(s=>typeof s?.id=="string"&&s.id.trim().length>0);for(let s of r){let i=s.id.trim();n.canonicalIds.set(i.toLowerCase(),i)}for(let s of r){let i=s.id.trim();Kk(n,t,i,s.blocked_by,"blocked_by");for(let o of s.dependencies??[])typeof o!="object"||o===null||Kk(n,t,i,o.id,typeof o.kind=="string"?o.kind:"related")}for(let s of[n.successors,n.predecessors])for(let i of s.values())i.sort();return n}function PN(e,t){let n=new Set([t]),r=[t];for(;r.length>0;){let s=r.pop();for(let i of[e.successors,e.predecessors])for(let o of i.get(s)??[])n.has(o)||(n.add(o),r.push(o))}return n}function FN(e,t){let n=new Map;for(let r of t){let s=(e.successors.get(r)??[]).filter(i=>t.has(i));s.length>0&&n.set(r,s)}return n}function zk(e,t,n){let r=MN(e,t),s=r.canonicalIds.get(n.trim().toLowerCase());if(s===void 0)return{cycles:[],successors:new Map,canonical:n};let i=FN(r,PN(r,s));return{cycles:Mh(i).filter(o=>o.includes(s)),successors:i,canonical:s}}function DN(e,t,n){let r=new Set(t),s=r.has(n)?n:t[0];if(e.get(s)?.includes(s))return[s,s];for(let i of e.get(s)??[]){if(!r.has(i))continue;let o=jN(e,r,s,i);if(o)return o}return[...t,t[0]]}function jN(e,t,n,r){let s=[[r]],i=new Set([n,r]);for(;s.length>0;){let o=s.shift(),a=o.at(-1);for(let c of e.get(a)??[]){if(c===n)return[n,...o,n];!t.has(c)||i.has(c)||(i.add(c),s.push([...o,c]))}}}function Io(e,t,n){let r=de(),s=zk(e,r,n),i=zk(t,r,n),o=new Set(s.cycles.map(Wk)),a=new Set(Cc(e,void 0,r).map(d=>`${d.holder_id.toLowerCase()}\0${d.target_id.toLowerCase()}\0${d.dependency_kind}`));return[...Cc(t,void 0,r).filter(d=>d.holder_id.toLowerCase()===n.trim().toLowerCase()&&!a.has(`${d.holder_id.toLowerCase()}\0${d.target_id.toLowerCase()}\0${d.dependency_kind}`)).map(d=>`ordering_storage_contradiction_created:${Ph(d)}:remove_contradicting_dependency_row:run_pm_graph_audit`),...i.cycles.filter(d=>!o.has(Wk(d))).map(d=>`ordering_cycle_created:${DN(i.successors,d,i.canonical).join(" -> ")}:items_will_not_be_ready:run_pm_graph_audit`)]}function Oo(e,t){let n=t.resolve(e);return n?.hierarchy===!0||n?.outgoing==="one"||n?.incoming==="one"}function Bk(e,t,n,r,s){let i=JSON.stringify([t,n,r]),o=e.get(i);o===void 0&&(o={kind:t,direction:n,node_id:r,endpoints:new Set},e.set(i,o)),o.endpoints.add(s)}function Hk(e,t){let n=new Map;for(let r of e)for(let s of r.dependencies??[]){let i=t.resolve(s.kind);i===void 0||i.hierarchy||(i.outgoing==="one"&&Bk(n,i.kind,"outgoing",r.id,s.id),i.incoming==="one"&&Bk(n,i.kind,"incoming",s.id,r.id))}return n}function Lo(e,t,n=de()){let r=Hk(e,n),s=Hk(t,n);for(let i of[...s.keys()].sort()){let o=s.get(i);if(o.endpoints.size<=1)continue;let a=r.get(i);if(![...o.endpoints].every(c=>a?.endpoints.has(c)))throw new p(`Relationship ${o.kind} permits only one ${o.direction} endpoint for ${o.node_id}.`,m.USAGE,{code:"dependency_cardinality_created",field:"dependencies",value:o.kind,relationship_cardinality:{kind:o.kind,direction:o.direction,node_id:o.node_id,endpoint_ids:[...o.endpoints].sort()},required:"The final dependency set must satisfy the active relationship kind's one-edge cardinality.",nextSteps:["Drop extra --dep seeds, or remove conflicting rows with update --dep-remove before adding another edge.","Choose another kind only when its declared semantics match the intended relationship."]})}}var UN=["setup","test"];function Te(e){return e.phase==="setup"}function rr(e,t){if(e===void 0)return;let n=typeof e=="string"?e.trim().toLowerCase():e;if(n==="setup")return"setup";if(!(n==="test"||n===""))throw new p(`${t} field "phase" must be one of: ${UN.join(", ")}`,m.USAGE,{code:"invalid_argument_value",required:"Use phase=setup for a step that runs before the linked commands, or omit phase for a regular linked test.",examples:['pm test <id> --add "command=npm run build,phase=setup"']})}function $o(e){return[...e.filter(Te),...e.filter(t=>!Te(t))]}function Vk(e,t){if(!e.selected.some(i=>!Te(i)))return e;let n=t.flatMap((i,o)=>Te(i)?[o+1]:[]);if(n.length===0)return e;let r=e.selected_indexes.filter(i=>!Te(t[i-1])),s=n.filter(i=>!e.selected_indexes.includes(i));return{...e,selected:[...n,...r].map(i=>t[i-1]),selected_indexes:[...n,...r],selected_count:n.length+r.length,skipped_count:t.length-n.length-r.length,...s.length>0?{setup_indexes:s}:{}}}function Yk(e,t,n){if(!Te(e))return;let r=[...n].filter(s=>s!==t).sort();if(r.length!==0)return{command:e.command,path:e.path,status:"refused",exit_code:null,failure_category:"config_refusal",error:`Setup entry runs in the ${t} workspace, but linked commands it prepares run in ${r.join(", ")}, so its output would not reach them. Set workspace_context_mode on the setup entry and the linked commands to one mode.`}}function _s(){let e;return{blocked(t){if(e!==void 0)return{command:t.command,path:t.path,status:"skipped",...Te(t)?{phase:"setup"}:{},error:`Skipped because setup entry "${e.label}" did not pass (${e.outcome}); no later linked command ran.`}},options(t,n){return!Te(t)||n===void 0?n:{...n,failOnEmptyTestRun:!1,requireAssertionsForPm:!1}},record(t,n){if(!Te(t))return n;if(n.status==="passed")return{...n,phase:"setup"};let s=n.status==="refused"||n.failure_category==="trust_refusal"||n.failure_category==="setup_failed"?{...n,phase:"setup"}:{...n,status:"failed",phase:"setup",failure_category:"setup_failed",...n.failure_category===void 0?{}:{setup_failure_cause:n.failure_category}};return e={label:t.command??t.path??"<no command>",outcome:s.failure_category??s.status},s}}}function GN(){return{infra_collision:0,trust_refusal:0,config_refusal:0,assertion_failure:0,empty_run:0,timeout:0,max_buffer:0,spawn_error:0,signal:0,setup_failed:0}}function sr(e){let t=GN();for(let n of e)n.status!=="failed"&&n.status!=="refused"||!n.failure_category||(t[n.failure_category]+=1);return t}var _n=new Set(["PM_PATH","PM_GLOBAL_PATH","PM_SOURCE_PM_PATH","PM_SOURCE_WORKSPACE_ROOT","PM_BUILD_CONSUMER_LEASE","PM_BUILD_CONSUMER_LEASE_ROOT",jr,Ch,"FORCE_COLOR"]),Po=/^[A-Za-z_][A-Za-z0-9_]*$/,pn=["schema","tracker","auto","none"],Jk=["source","isolated","snapshot"];function hs(e,t){if(!e)return;let n=e.split(/[;\n]/).map(s=>s.trim()).filter(s=>s.length>0);if(n.length===0)throw new p(`${t} env_set must include at least one KEY=VALUE assignment`,m.USAGE);let r=Object.create(null);for(let s of n){let i=s.indexOf("=");if(i<=0)throw new p(`${t} env_set entries must use KEY=VALUE and be separated by semicolons. Example: env_set=PORT=0;PLAYWRIGHT_BASE_URL=http://127.0.0.1:4173`,m.USAGE);let o=s.slice(0,i).trim(),a=s.slice(i+1);if(!Po.test(o))throw new p(`${t} env_set key "${o}" is invalid`,m.USAGE);if(_n.has(o.toUpperCase()))throw new p(`${t} env_set key "${o}" is reserved for sandbox safety`,m.USAGE);r[o]=a}return Object.keys(r).length>0?r:void 0}function gs(e,t){if(!e)return;let n=uc(e,{separators:/[;,\n]/});if(n.length===0)throw new p(`${t} env_clear must include at least one environment variable name`,m.USAGE);for(let r of n){if(!Po.test(r))throw new p(`${t} env_clear key "${r}" is invalid`,m.USAGE);if(_n.has(r.toUpperCase()))throw new p(`${t} env_clear key "${r}" is reserved for sandbox safety`,m.USAGE)}return n}function Fo(e,t,n){if(!e)return;let r=e.trim().toLowerCase();if(r==="true"||r==="1"||r==="yes")return!0;if(r==="false"||r==="0"||r==="no")return!1;throw new p(`${t} ${n} must be one of true|false|1|0|yes|no`,m.USAGE)}function Do(e,t){if(!e)return;let n=e.trim().toLowerCase();if(pn.includes(n))return n;throw new p(`${t} pm_context_mode must be one of: ${pn.join(", ")}`,m.USAGE)}function hn(e,t){if(!e)return;let n=e.trim().toLowerCase();if(Jk.includes(n))return n;throw new p(`${t} workspace_context_mode must be one of: ${Jk.join(", ")}`,m.USAGE)}function gn(e){if(!e)return;let t=uc(e,{separators:/[;\n]/});return t.length>0?t:void 0}function ir(e,t,n){let r=gn(e);if(!(!r||r.length===0)){for(let s of r)try{new RegExp(s,"m")}catch(i){throw new p(`${t} ${n} includes invalid regex "${s}": ${i instanceof Error?i.message:String(i)}`,m.USAGE)}return r}}function jo(e,t){if(!e)return;let n=we(e,"assert_stdout_min_lines");if(!Number.isInteger(n)||n<0)throw new p(`${t} assert_stdout_min_lines must be an integer >= 0`,m.USAGE);return n}function Uo(e,t){if(!e)return;let n=e.split(/[;\n]/).map(s=>s.trim()).filter(s=>s.length>0);if(n.length===0)throw new p(`${t} assert_json_field_equals must include at least one path=value assignment`,m.USAGE);let r=Object.create(null);for(let s of n){let i=s.indexOf("=");if(i<=0)throw new p(`${t} assert_json_field_equals entries must use path=value and be separated by semicolons`,m.USAGE);let o=s.slice(0,i).trim(),a=s.slice(i+1).trim();if(o.length===0||a.length===0)throw new p(`${t} assert_json_field_equals entries must include non-empty path and value`,m.USAGE);r[o]=a}return Object.keys(r).length>0?r:void 0}function Go(e,t){if(!e)return;let n=e.split(/[;\n]/).map(s=>s.trim()).filter(s=>s.length>0);if(n.length===0)throw new p(`${t} assert_json_field_gte must include at least one path=value assignment`,m.USAGE);let r=Object.create(null);for(let s of n){let i=s.indexOf("=");if(i<=0)throw new p(`${t} assert_json_field_gte entries must use path=value and be separated by semicolons`,m.USAGE);let o=s.slice(0,i).trim(),a=s.slice(i+1).trim();if(o.length===0||a.length===0)throw new p(`${t} assert_json_field_gte entries must include non-empty path and value`,m.USAGE);let c=Number(a);if(!Number.isFinite(c))throw new p(`${t} assert_json_field_gte value for "${o}" must be numeric`,m.USAGE);r[o]=c}return Object.keys(r).length>0?r:void 0}var qN=new Set(gt);function qo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function WN(e,t){let n={},r=[];for(let[s,i]of Object.entries(e)){let o=s.toLowerCase();if(!qN.has(o)){r.push(s);continue}if(Object.hasOwn(n,o))throw t(`provides key "${s}" more than once after case normalization`);n[o]=i}if(r.length>0)throw t(`does not recognize key${r.length>1?"s":""} ${r.map(s=>`"${s}"`).join(", ")}. Allowed keys: ${gt.join(", ")}.`);return n}function fn(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r!==void 0){if(typeof r!="string")throw n(`field "${t}" must be a JSON string`);return r}}function No(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r===void 0)return;let s=typeof r=="string"?[r]:r;if(!Array.isArray(s)||s.some(o=>typeof o!="string"))throw n(`field "${t}" must be a string or an array of strings`);let i=s.filter(o=>o.length>0);return i.length>0?i:void 0}function Xk(e,t,n){let r=No(e,t,n);if(r){for(let s of r)try{new RegExp(s,"m")}catch(i){throw n(`field "${t}" includes invalid regex "${s}": ${i instanceof Error?i.message:String(i)}`)}return r}}function Mo(e,t,n){let r=typeof e=="number"?e:typeof e=="string"&&e.trim().length>0?Number(e.trim()):Number.NaN;if(typeof e=="boolean"||!Number.isFinite(r))throw n(`field "${t}" must be a finite number (or numeric string)`);return r}function KN(e,t){let n=e.timeout_seconds,r=e.timeout;if(n===void 0&&r===void 0)return;let s=n===void 0?void 0:Mo(n,"timeout_seconds",t),i=r===void 0?void 0:Mo(r,"timeout",t);if(s!==void 0&&i!==void 0&&s!==i)throw t("timeout and timeout_seconds must match when both are provided");let o=s??i;if(!Number.isInteger(o)||o<=0)throw t("timeout_seconds must be a positive integer");return o}function zN(e,t){let n=fn(e,"scope",t);if(n===void 0)return"project";if(!Be.includes(n))throw t(`field "scope" must be one of: ${Be.join(", ")}`);return n}function BN(e,t){if(!Object.hasOwn(e,"env_set"))return;let n=e.env_set;if(n===void 0)return;if(!qo(n))throw t('field "env_set" must be a JSON object mapping environment names to string values');let r=Object.create(null);for(let[s,i]of Object.entries(n)){if(typeof i!="string")throw t(`field "env_set" value for "${s}" must be a string`);if(!Po.test(s))throw t(`field "env_set" key "${s}" is invalid`);if(_n.has(s.toUpperCase()))throw t(`field "env_set" key "${s}" is reserved for sandbox safety`);r[s]=i}return Object.keys(r).length>0?r:void 0}function HN(e,t){let n=No(e,"env_clear",t);if(n){for(let r of n){if(!Po.test(r))throw t(`field "env_clear" key "${r}" is invalid`);if(_n.has(r.toUpperCase()))throw t(`field "env_clear" key "${r}" is reserved for sandbox safety`)}return n}}function VN(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r!==void 0){if(typeof r!="boolean")throw n(`field "${t}" must be a JSON boolean (true or false)`);return r}}function YN(e,t){if(!Object.hasOwn(e,"assert_stdout_min_lines"))return;let n=e.assert_stdout_min_lines;if(n===void 0)return;let r=Mo(n,"assert_stdout_min_lines",t);if(!Number.isInteger(r)||r<0)throw t('field "assert_stdout_min_lines" must be an integer >= 0');return r}function JN(e,t){if(!Object.hasOwn(e,"assert_json_field_equals"))return;let n=e.assert_json_field_equals;if(n===void 0)return;if(!qo(n))throw t('field "assert_json_field_equals" must be a JSON object mapping field paths to expected values');let r=Object.create(null);for(let[s,i]of Object.entries(n)){if(s.trim().length===0)throw t('field "assert_json_field_equals" keys must be non-empty field paths');if(typeof i!="string"&&typeof i!="number"&&typeof i!="boolean")throw t(`field "assert_json_field_equals" value for "${s}" must be a string, number, or boolean`);r[s]=String(i)}return Object.keys(r).length>0?r:void 0}function XN(e,t){if(!Object.hasOwn(e,"assert_json_field_gte"))return;let n=e.assert_json_field_gte;if(n===void 0)return;if(!qo(n))throw t('field "assert_json_field_gte" must be a JSON object mapping field paths to numeric minimums');let r=Object.create(null);for(let[s,i]of Object.entries(n)){if(s.trim().length===0)throw t('field "assert_json_field_gte" keys must be non-empty field paths');r[s]=Mo(i,`assert_json_field_gte.${s}`,t)}return Object.keys(r).length>0?r:void 0}function QN(e,t,n){let r=f=>new p(`${n} ${t} ${f}`,m.USAGE);if(!qo(e))throw r(`must be a JSON object with linked-test fields. Allowed keys: ${gt.join(", ")}.`);let s=WN(e,r),i=fn(s,"command",r),o=fn(s,"cmd",r);if(i!==void 0&&o!==void 0&&i!==o)throw r("command and cmd must match when both are provided");let a=i??o;if(a===void 0||a.trim().length===0)throw r('requires a non-empty "command" string');let c=fn(s,"path",r),d=fn(s,"pm_context_mode",r);if(d!==void 0&&!pn.includes(d))throw r(`field "pm_context_mode" must be one of: ${pn.join(", ")}`);let l=hn(fn(s,"workspace_context_mode",r),`${n} ${t}`),u=fn(s,"note",r);return{command:a,path:c!==void 0&&c.length>0?c:void 0,scope:zN(s,r),timeout_seconds:KN(s,r),pm_context_mode:d,workspace_context_mode:l,env_set:BN(s,r),env_clear:HN(s,r),shared_host_safe:VN(s,"shared_host_safe",r),assert_stdout_contains:No(s,"assert_stdout_contains",r),assert_stdout_regex:Xk(s,"assert_stdout_regex",r),assert_stderr_contains:No(s,"assert_stderr_contains",r),assert_stderr_regex:Xk(s,"assert_stderr_regex",r),assert_stdout_min_lines:YN(s,r),assert_json_field_equals:JN(s,r),assert_json_field_gte:XN(s,r),note:u!==void 0&&u.trim().length>0?u.trim():void 0,phase:rr(s.phase,`${n} ${t}`)}}function ys(e,t){let n=e.trim();if(n.length===0)throw new p(`${t} requires a JSON object or array of objects describing linked-test entries`,m.USAGE);let r;try{r=JSON.parse(n)}catch(i){throw new p(`${t} value is not valid JSON: ${i instanceof Error?i.message:String(i)}. Provide a JSON object or array of objects, e.g. '{"command":"node scripts/check.js --flag value, with commas","timeout_seconds":120}'.`,m.USAGE)}let s=Array.isArray(r)?r:[r];if(s.length===0)throw new p(`${t} array must include at least one linked-test entry object`,m.USAGE);return s.map((i,o)=>QN(i,s.length>1?`entry ${o+1}`:"entry",t))}var ZN={comment:"--clear-comments",dep:"--clear-deps",doc:"--clear-docs",event:"--clear-events",file:"--clear-files",learning:"--clear-learnings",note:"--clear-notes",reminder:"--clear-reminders",test:"--clear-tests",typeOption:"--clear-type-options"};function eM(e){return ZN[e]}function Tl(e){return eM(e)!==void 0}function Rl(){return ec.map(e=>e.field).join(", ")}var tM=Object.freeze({fields:[],reason:void 0,optionKeys:new Set});function nM(e){return(e??[]).flatMap(t=>t.split(",")).map(t=>t.trim()).filter(t=>t.length>0)}function Qk(e,t){let n=An(t,"defer"),r=An(t,"defer-reason"),s=nM(e.defer),i=e.deferReason?.trim();if(s.length===0){if(i!==void 0&&i.length>0)throw new p(`${r} needs ${n}: name the fields whose values are not known yet.`,m.USAGE,{code:"create_deferral_fields_required",required:`Pass ${n} with ${r}, or drop ${r}.`,nextSteps:[`Deferrable fields: ${Rl()}.`]});return tM}let o=new Map;for(let c of s){let d=tc(c);if(d===void 0)throw new p(`${n} cannot defer "${c}". Deferrable fields: ${Rl()}.`,m.USAGE,{code:"create_deferral_field_unsupported",required:`Defer only ${Rl()}; supply every other field, or clear a repeatable option with its --clear-* flag.`});o.set(d.field,d)}if(i===void 0||i.length===0)throw new p(`${n} requires ${r}: record why the deferred values are not known yet.`,m.USAGE,{code:"create_deferral_reason_required",required:`Pass ${r} "<why>", for example the system the record was imported from.`});let a=ec.filter(c=>o.has(c.field));return{fields:a,reason:i,optionKeys:new Set(a.map(c=>c.option))}}function Il(e,t,n,r,s={}){let i=e.fields.filter(c=>{let d=t[c.option];return typeof d=="string"&&d.trim().length>0||s[c.field]!==void 0||n.has(c.field)});if(i.length===0)return;let o=An(r,"defer"),a=i.map(c=>c.field).join(", ");throw new p(`Cannot both defer and set ${a}: ${o} records a value as not known yet.`,m.USAGE,{code:"create_deferral_conflict",required:`Drop ${o} for ${a}, or drop the value (or unset) you supplied for it.`})}function Zk(e){if(e.fields.length!==0)return Bm(e.fields.map(t=>({field:t.field,reason:e.reason})))}function eb(e,t=[]){let r=(Array.isArray(e)?e:e===void 0?[]:[e]).filter(o=>typeof o=="string").flatMap(o=>o.split(",")).map(o=>tc(o)).filter(o=>o!==void 0),s=new Set(r.map(o=>o.field)),i=t.filter(o=>o.commands.includes("create")&&s.has(o.metadata_key)).flatMap(o=>Gm(o));return[...r.map(o=>o.option),...i]}function tb(e,t,n,r,s={}){let i=new Set(t.fields.map(l=>l.field)),o=n.filter(l=>l.commands.includes("create")),a=l=>l.required!==!0&&i.has(l.metadata_key),c=new Set(o.filter(a).map(l=>`--${l.cli_flag}`)),d=new Set(o.filter(l=>!a(l)&&qm(l,r)&&ei(s,l)===void 0).map(l=>`--${l.cli_flag}`));return e.filter(l=>!c.has(l)||d.has(l))}var rM="hierarchy-integrity";async function Wo(e){let t=e.required?await oi(e.pmRoot,rM,e.ttlSeconds,e.author,!1,!1,e.waitMs,{waitPolicy:"progress"}):async()=>{},n=!1;return async()=>{n||(n=!0,await t())}}function Ko(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function zo(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function Bo(e){let t=e.trim().toLowerCase();if(t==="med")return"medium";if(mm.includes(t))return t;let n=we(e,"confidence");if(!Number.isInteger(n)||n<0||n>100)throw new p("Confidence must be an integer 0..100 or one of low|med|medium|high",m.USAGE);return n}function Ho(e){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1;throw new p("Regression must be one of true|false|1|0",m.USAGE)}var nb=[["dependencies","dep",["id","kind","created_at","author","source_kind"]],["comments","comment",["text","created_at","author"]],["notes","note",["text","created_at","author"]],["learnings","learning",["text","created_at","author"]],["files","file",["path","scope","note"]],["tests","test",["command","scope","timeout_seconds","phase"]],["docs","doc",["path","scope","note"]],["reminders","reminder",["at","text","created_at"]],["events","event",["start_at","end_at","title","location"]],["type_options","typeOption",["key","value"]]];var sM=["documentAnnotationSnapshot","runtimeFieldCommands","ownershipMetadataBypass","ownershipDependencyBypass"];function Vo(e){let t=nb.find(([r])=>r===e)?.[1]??e.replaceAll(/_([a-z])/gu,(r,s)=>s.toUpperCase()),n=[["update",kc],["create",vc]].flatMap(([r,s])=>s.flatMap(i=>{if(i.target!==t)return[];let o=i.option.match(/--[a-z][a-z0-9-]*/u)[0];return[{command:r,flag:o}]}));return{recovery:{provided_fields:[e],...n.length>0?{suggested_flags:[...new Set(n.map(r=>r.flag))]}:{}},nextSteps:n.length>0?n.map(({command:r,flag:s})=>`Use the declared core mutation: pm ${r}${r==="update"?" <id>":""} ${s} <value>; inspect its help for other required options.`):[`No dedicated create/update CLI mutation flag is declared for "${e}". Use its owning lifecycle, evidence, or importer API; --field cannot mutate core metadata.`]}}var sb={create:{name:"create",usage:"pm create",sdkScope:"create options"},update:{name:"update",usage:"pm update <id>",sdkScope:"update options"},update_many:{name:"update-many",usage:"pm update-many <selection flags>",sdkScope:"update options of the update-many request"}};function rb(e){return e.flatMap(t=>[t.flag,...t.short===void 0?[]:[t.short],...t.aliases??[]])}function ib(e){if(e==="update_many"){let s=ib("update"),i=rb(Or("update-many"));return{options:new Set([...s.options,...i.map(o=>Za(o))]),flags:new Set([...s.flags,...i])}}let t=e==="update"?kc:vc,n=rb([...Or(e),...xi]),r=[...t.flatMap(s=>[s.target,...s.keys]),...n.map(s=>Za(s)),...e==="update"?sM:[]];return{options:new Set(r),flags:new Set(n)}}function iM(e,t){let n=sb[t];return e===void 0?`SDK: every option name for this field is shared with another declared field or an option of pm ${n.name}; no SDK option sets it alone.`:`SDK: pass ${e} in the ${n.sdkScope}.`}function oM(e,t,n,r){return e.definitions.some(s=>s.metadata_key===t.metadata_key&&s.commands.includes(n)&&ei(r,s)!==void 0)}function Yo(e,t,n){let r=sb[t],s=n===void 0?void 0:Object.fromEntries(Object.entries(n).filter(([i])=>i!=="field"));return i=>{let o=Dm(i),a=e.definitions.filter(_=>_.metadata_key===o||_.key===o),c=a.find(_=>_.commands.includes(t))??a[0];if(c===void 0)return;let d=`Inspect the value contract with: pm schema show-field ${c.key}`;if(!c.commands.includes(t))return{recovery:{provided_fields:[i]},nextSteps:[`The project schema declares "${c.key}" for ${c.commands.join(", ")} only; ${r.name} cannot set it.`,d]};if(s!==void 0&&oM(e,c,t,s))return{recovery:{provided_fields:[i]},nextSteps:[`This invocation already sets "${c.key}" through a declared flag or option; drop the --field ${i} assignment so the field receives one value.`,d]};let l=ib(t),u=Um(c,e,l,t),f=u===void 0?`Every CLI spelling of "${c.key}" is shared with another declared field or an option of pm ${r.name}; give it a distinct cli_flag in the project schema.`:`Use the declared project-schema flag: ${r.usage} ${Qa(u)} <value>`;return{recovery:{provided_fields:[i],...u===void 0?{}:{suggested_flags:[Qa(u)]}},nextSteps:[f,iM(jm(c,e,l.options,t),t),d]}}}var aM=new Set(["event","meeting","reminder","milestone","decision","adr"]);function ob(e,t,n,r){if(aM.has(t.trim().toLowerCase())||n!==r.open_status)return;let s=Qe("in_progress",r);if(!(s===void 0||s===r.open_status))return{command:`pm claim ${e} --start`,to_status:s}}function cb(e,t){let n=e.trim().toLowerCase();if(n==="true"||n==="1"||n==="yes")return!0;if(n==="false"||n==="0"||n==="no")return!1;throw new p(`${t} must be one of true|false|1|0|yes|no`,m.USAGE)}function Ol(e){return e?e.split("|").map(t=>t.trim()).filter(t=>t.length>0):[]}function rt(e,t,n,r=n){if(!t.includes(e))throw new p(`Invalid ${n} value "${e}". Allowed: ${t.join(", ")}`,m.USAGE,{field:r,value:e,recovery:{allowed_values:[...t]},required:`${n} must be one of: ${t.join(", ")}.`,nextSteps:[`Choose an allowed ${n} and retry the mutation.`]});return e}var db=["recur_freq","recur_interval","recur_count","recur_until","recur_by_weekday","recur_by_month_day","recur_exdates"];function cM(e,t){return t==="defined"?e!==void 0:!!e}function ab(e,t,n){if(!cM(e,n))return;let r=we(e,`event ${t}`);if(!Number.isInteger(r)||r<1)throw new p(`--event ${t} must be an integer >= 1`,m.USAGE);return r}function dM(e,t,n){let r=e?me(e,n,"event.recur_until"):void 0;if(r&&r<t)throw new p("--event recur_until must be at or after start",m.USAGE);return r}function lM(e){return Array.from(new Set(Ol(e).map(t=>rt(t.toLowerCase(),ym,"event weekday")))).sort((t,n)=>qa(t)-qa(n))}function uM(e){return Array.from(new Set(Ol(e).map(t=>{let n=we(t,"event recur_by_month_day");if(!Number.isInteger(n)||n<1||n>31)throw new p("--event recur_by_month_day values must be integers 1..31",m.USAGE);return n}))).sort((t,n)=>t-n)}function mM(e,t){return Array.from(new Set(Ol(e).map(n=>me(n,t,"event.recur_exdates")))).sort((n,r)=>n.localeCompare(r))}function lb(e,t,n,r){let s=e.recur_freq?.trim(),i=e.recur_interval?.trim(),o=e.recur_count?.trim(),a=e.recur_until?.trim(),c=e.recur_by_weekday?.trim(),d=e.recur_by_month_day?.trim(),l=e.recur_exdates?.trim();if(![s,i,o,a,c,d,l].some(S=>S!==void 0))return;if(!s)throw new p("--event recurrence fields require recur_freq=<daily|weekly|monthly|yearly>",m.USAGE);let f=rt(s.toLowerCase(),gm,"event recurrence frequency"),_=ab(i,"recur_interval",r),h=ab(o,"recur_count",r),g=dM(a,t,n),y=lM(c),w=uM(d),v=mM(l,n);return{freq:f,interval:_,count:h,until:g,by_weekday:y.length>0?y:void 0,by_month_day:w.length>0?w:void 0,exdates:v.length>0?v:void 0}}function or(e,t=de()){let n=t.resolve(e);if(n)return n.kind;let r=new Set(Ga),s=[...Ga,...t.list().filter(({kind:i})=>!r.has(i)).flatMap(({kind:i,aliases:o})=>[i,...o])];throw new p(`Invalid dependency kind value "${e}". Allowed: ${s.join(", ")}`,m.USAGE,{field:"kind",value:e,recovery:{allowed_values:s},required:`dependency kind must be one of: ${s.join(", ")}.`,nextSteps:["Choose a registered kind, or install and enable the extension that registers this kind before retrying."]})}function ws(e,t,n="--dep"){if(!t&&/[:,=]/.test(e))throw new p(`Invalid ${n} value "${e}". Use a bare item id or id=<id>,kind=<kind>.`,m.USAGE,{code:"dependency_flag_value_invalid",reason:"malformed_dependency_shorthand",flag:n,value:e,required:"Use a bare item id or an explicit id=<id>,kind=<kind> entry."})}function vs(e,t,n=de()){for(let r of t??[])try{Sf(e,r.id,r.kind,n)}catch(s){throw new p(Ys(s),m.USAGE,{code:"dependency_edge_not_allowed",why:`${e} -> ${r.id} (${r.kind}) violates the active relationship-kind policy`})}}async function ub(e,t){return(await fe(e,{schema:t})).document.metadata.created_at}async function fM(e,t){if(e.createdAt!==void 0)return e.createdAt;let n=await Y(t.pmRoot,e.id,t.idPrefix,t.itemFormat,t.typeToFolder);return n===null?void 0:ub(n,t.schema)}function pM(e){let t=e.registry.require(e.dependency.kind);return new p(`${t.kind} requires source ${e.holder.id} to be created after target ${e.dependency.id}`,m.USAGE,{code:"dependency_temporal_order_invalid",reason:"source_not_after_target",required:`${e.holder.id}.created_at must be later than ${e.dependency.id}.created_at for ${t.kind}.`,why:"Chronological recurrence direction must be validated before the relationship is persisted.",source_id:e.holder.id,source_created_at:e.sourceCreatedAt,target_id:e.dependency.id,target_created_at:e.targetCreatedAt,temporal_order:t.temporalOrder})}async function _M(e){let t=e.dependencies.filter(s=>e.registry.resolve(s.kind)?.temporalOrder==="source_after_target"&&!e.missingTargets.includes(s.id));if(t.length===0||e.holders.length===0)return;let n=new Map(e.resolutions.flatMap(({target:s,located:i})=>i===null?[]:[[s,i]])),r=new Map(await Promise.all([...new Set(t.map(({id:s})=>s))].map(async s=>[s,await ub(n.get(s),e.context.schema)])));for(let s of e.holders){let i=await fM(s,e.context);if(i!==void 0)for(let o of t){let a=r.get(o.id),c=Date.parse(i),d=Date.parse(a);if(!(Number.isFinite(c)&&Number.isFinite(d)&&c>d))throw pM({holder:s,dependency:o,sourceCreatedAt:i,targetCreatedAt:a,registry:e.registry})}}}async function Jo(e){let t=e.registry??de(),n=(e.dependencies??[]).filter(o=>!mp(o.source_kind)),r=[...new Set(n.map(o=>o.id))],s=await Promise.all(r.map(async o=>({target:o,located:await Y(e.pmRoot,o,e.idPrefix,e.itemFormat,e.typeToFolder)}))),i=s.filter(({located:o})=>o===null).map(({target:o})=>o).sort((o,a)=>o<a?-1:1);if(i.length>0&&e.allowUnresolved!==!0)throw new p(`Dependency target${i.length===1?"":"s"} not found: ${i.join(", ")}`,m.NOT_FOUND,{code:"dependency_target_not_found",reason:"unresolved_local_dependency",required:"Every local dependency target must exist before the edge is committed.",why:"Fail-fast target resolution prevents dangling graph nodes and preserves reliable traversal semantics.",unresolved_targets:i,examples:["--dep id=<existing-item-id>,kind=related","--dep id=<external-id>,kind=related,source_kind=external","--allow-unresolved-deps --dep id=<future-item-id>,kind=related"],nextSteps:[`Create or correct ${i.length===1?"the target":"the targets"}, then retry the mutation.`,"Use source_kind=external for a cross-workspace reference.","Use --allow-unresolved-deps only when the dangling local edge is intentional."],recovery:{recovery_mode:"compact",missing:i,suggested_flags:["--allow-unresolved-deps"],suggested_retry:`pm search "${i[0]}" --limit 10`}});return await _M({dependencies:n,missingTargets:i,resolutions:s,holders:e.holders??[],registry:t,context:e}),i.map(o=>`dependency_target_unresolved:${o}`)}var mb="--event end must be strictly after start. Equal start/end timestamps are treated as an instant event (end is dropped); an end earlier than start is rejected. Omit end for an instant event or set end later than start.",hM="--event end and duration are mutually exclusive; provide only one (use duration=<relative> like duration=2h, duration=30min, or duration=PT30M, or set an explicit end).",gM=/^([+-]?)(\d+)(min|mins|minute|minutes)$/i,yM=/^([+-]?)[Pp][Tt](?:(\d+)[Hh])?(?:(\d+)[Mm])?(?:(\d+)[Ss])?$/,pb=1e3,Ll=60*pb,wM=60*Ll;function fb(e,t){let n=new Date(e);if(!Number.isFinite(n.getTime()))throw new p(`Invalid event.duration value "${t}". Duration is out of supported timestamp range.`,m.USAGE);return n.toISOString()}function vM(e,t){let n=new Date(e),r=t.trim();if(/^[+-]?\d+m$/i.test(r))throw new p(`Event duration "${r}" is ambiguous. Use min for minutes or mo for months (for example 5min or 5mo).`,m.USAGE);let s=r.replace(/^([+-]?\d+)mo$/i,"$1m"),i=gM.exec(r);if(i){let c=i[1]==="-"?-1:1,d=Number.parseInt(i[2],10)*c;return fb(n.getTime()+d*Ll,r)}let o=yM.exec(r);if(o){let[,c,d,l,u]=o;if(d||l||u){let _=c==="-"?-1:1,h=Number.parseInt(d??"0",10),g=Number.parseInt(l??"0",10),y=Number.parseInt(u??"0",10),w=h*wM+g*Ll+y*pb;return fb(n.getTime()+_*w,r)}}let a=s.startsWith("+")||s.startsWith("-")?s:`+${s}`;return me(a,n,"event.duration")}function _b(e,t,n,r){if(t&&n)throw new p(hM,m.USAGE);if(n){let i=vM(e,n);if(i<e)throw new p(mb,m.USAGE);return i===e?void 0:i}if(!t)return;let s=me(t,r,"event.end");if(s<e)throw new p(mb,m.USAGE);if(s!==e)return s}var kM=["at","date","text","title"],bM=["start","date","end","duration","title","description","location","timezone","all_day",...db],xM=["key","value"];function hb(e,t){return t==="trimmed"?e?.trim():e}function SM(e,t){return t==="defined"?e!==void 0:!!e}function Xo(e,t,n){return e.map(r=>{let s=ee(r,"--reminder");be(s,"--reminder",kM);let i=hb(s.at??s.date,n.valueMode),o=hb(s.text??s.title,n.valueMode);if(!i||!o)throw new p("--reminder requires at=<iso|relative> or date=<iso|relative>, plus text=<value> or title=<value>",m.USAGE);let a=o.trim();if(!a)throw new p("--reminder text must not be empty",m.USAGE);return{at:me(i,t,"reminder.at"),text:a}})}function Qo(e,t,n){return e.map(r=>{let s=ee(r,"--event");be(s,"--event",bM);let i=(s.start??s.date)?.trim();if(!i)throw new p("--event requires start=<iso|relative> or date=<iso|relative>",m.USAGE);let o=me(i,t,"event.start"),a=s.end?.trim(),c=s.duration?.trim(),d=_b(o,a,c,t),l=s.title,u=s.description,f=s.location,_=s.timezone,h=l?.trim(),g=u?.trim(),y=f?.trim(),w=_?.trim(),v=[["title",l,h],["description",u,g],["location",f,y],["timezone",_,w]];for(let[A,x,E]of v)if(x!==void 0&&!E)throw new p(`--event ${A} must not be empty`,m.USAGE);let S=s.all_day?.trim(),b=lb(s,o,t,n.recurrenceEmptyNumericGuard),k=SM(S,n.allDayEmptyGuard)?cb(S,"--event all_day"):void 0;return{start_at:o,end_at:d,title:h,description:g,location:y,all_day:k,timezone:w,recurrence:b}})}function Zo(e){let t={};for(let n of e){let r=n.trim();if(r.length===0)throw new p("--type-option values must not be empty",m.USAGE);let s,i;if(r.includes(",")||r.includes(`
|
|
10
|
+
`)||r.startsWith("```")||/^(?:[-*+]\s+)?(?:key|value)\s*[:=]/i.test(r)){let a=ee(r,"--type-option");be(a,"--type-option",xM),s=a.key?.trim(),i=a.value?.trim()}else{let a=r.indexOf("="),c=r.indexOf(":"),d=a;if(a<=0&&c>0&&(d=c),d<=0||d===r.length-1)throw new p("--type-option requires key=value or key=<name>,value=<value> entries",m.USAGE);s=r.slice(0,d).trim(),i=r.slice(d+1).trim()}if(!s||!i)throw new p("--type-option requires key and value",m.USAGE);t[s]=i}return Object.fromEntries(Object.entries(t).sort((n,r)=>n[0].localeCompare(r[0])))}var EM=["strict","progressive"],AM=["lightweight"],vb=new Set(["Reminder","Meeting","Event"]),CM=new Set(["author","created_at","text"]),ea=new Map(_h.map(e=>[e.optionKey,e.canonical]));function TM(e,t){let n=ce(e,t);if(!n){let r=t.definitions.map(s=>s.id);throw new p(`Invalid status value "${e}". Allowed: ${r.join(", ")}`,m.USAGE,{code:"invalid_argument_value",field:"status",value:e,allowed:r})}return n}function RM(e,t){let n=e.default_status;if(n!==void 0){let r=ce(n,t);if(r)return r}return t.open_status}function $l(e,t){if(!e||e.trim()===""||e.trim().toLowerCase()==="now")return t;let n=Date.parse(e);if(!Number.isFinite(n))throw new p(`Invalid created_at timestamp "${e}"`,m.USAGE);return new Date(n).toISOString()}var IM=Ai();function kb(e){if(at(e))return e;let t={...e,unset:e.unset?[...e.unset]:void 0},n=s=>{let i=t.unset?[...t.unset]:[];i.includes(s)||i.push(s),t.unset=i};Lr(t.template)&&(t.template=void 0);let r=new Set([...ea.keys(),"rank"]);for(let s of r){if(at(e,s))continue;let i=t[s];if(typeof i!="string"||!Lr(i))continue;let o=s==="rank"?"order":ea.get(s)??s;n(o),t[s]=void 0}return dt(e,Ti(t,IM))}function Ke(e){if(e!==void 0)return e}var gb=["id","kind","type","author","created_at","source_kind"],ta=["path","scope","note"];function OM(e,t,n,r){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:($e(e,"--dep","Use --clear-deps to clear dependencies."),{values:e.map(i=>{let o=i.trim(),a=na(o,gb);ws(o,a);let c=a?ee(i,"--dep"):{id:o,kind:"related"};a&&be(c,"--dep",gb);let d=Ke(c.id),l=LM(Ke(c.kind??c.type));if(!d||!l)throw new p("--dep requires id and kind, or a bare item id to create a related dependency",m.USAGE);if(d.trim().toLowerCase()==="undefined")throw new p(`--dep id must not use placeholder token "${d}". Use --clear-deps to clear dependencies.`,m.USAGE);let u=Fr(Ke(c.source_kind)),f=Hs(c.author,"--dep author");return{id:Dr(d,n,u),kind:or(l),created_at:$l(c.created_at,t),author:f??r,source_kind:u??"cli:create:dep",author_source:f?"asserted":"detected"}}),explicitEmpty:!1})}function LM(e){return typeof e=="string"?de().resolve(e)?.kind??e.trim():e}function na(e,t){return am(e,t)?!0:Cn(e)}function wn(e,t,n,r){return!t||t.length===0?{values:void 0,explicitEmpty:!1}:($e(t,e,e==="--comment"?"Use --clear-comments to clear comments.":e==="--note"?"Use --clear-notes to clear notes.":"Use --clear-learnings to clear learnings."),{values:t.map(o=>{let a=o.trim(),c=()=>{if(a.length===0)throw new p(`${e} requires text=<value>`,m.USAGE);return{created_at:n,author:r,text:a}},d;try{d=ee(o,e)}catch(f){if(e==="--comment"||e==="--note"||e==="--learning")return c();throw f}if(Object.keys(d).filter(f=>!CM.has(f)).length>0)return{created_at:$l(d.created_at,n),author:Hs(d.author,`${e} author`)??r,text:a};let u=d.text??"";if(u==="")throw new p(`${e} requires text=<value>`,m.USAGE);return{created_at:$l(d.created_at,n),author:Hs(d.author,`${e} author`)??r,text:u}}),explicitEmpty:!1})}function Nl(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:($e(e,"--file","Use --clear-files to clear linked files."),{values:e.map(n=>{let r=n.trim(),s=na(r,ta);hr(r,"--file","file path",s);let i=s?ee(n,"--file"):{path:r};if(s&&be(i,"--file",ta),!i.path)throw new p("--file requires path=<value> or a bare file path",m.USAGE);return{path:i.path,scope:rt(i.scope??"project",Be,"file scope"),note:Ke(i.note)}}),explicitEmpty:!1})}function Ml(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:($e(e,"--test","Use --clear-tests to clear linked tests."),{values:e.map(n=>{let r=n.trim(),s=na(r,gt);hr(r,"--test","test command",s);let i=s?Vs(ee(n,"--test"),"--test"):{command:r},o=Ke(i.command),a=Ke(i.path);if(!o)throw new p("--test requires command=<value> or a bare command (path=<value> is optional metadata)",m.USAGE);let c=Ke(i.timeout_seconds),d=Ke(i.timeout);if(c&&d&&c!==d)throw new p("--test timeout and timeout_seconds must match when both are provided",m.USAGE);let l=c??d;return{command:o,path:a,scope:rt(i.scope??"project",Be,"test scope"),timeout_seconds:l?we(l,"timeout_seconds"):void 0,pm_context_mode:Do(i.pm_context_mode,"--test"),workspace_context_mode:hn(i.workspace_context_mode,"--test"),env_set:hs(i.env_set,"--test"),env_clear:gs(i.env_clear,"--test"),shared_host_safe:Fo(i.shared_host_safe,"--test","shared_host_safe"),assert_stdout_contains:gn(i.assert_stdout_contains),assert_stdout_regex:ir(i.assert_stdout_regex,"--test","assert_stdout_regex"),assert_stderr_contains:gn(i.assert_stderr_contains),assert_stderr_regex:ir(i.assert_stderr_regex,"--test","assert_stderr_regex"),assert_stdout_min_lines:jo(i.assert_stdout_min_lines,"--test"),assert_json_field_equals:Uo(i.assert_json_field_equals,"--test"),assert_json_field_gte:Go(i.assert_json_field_gte,"--test"),note:Ke(i.note),phase:rr(i.phase,"--test")}}),explicitEmpty:!1})}function Pl(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:($e(e,"--doc","Use --clear-docs to clear linked docs."),{values:e.map(n=>{let r=n.trim(),s=na(r,ta),i=s?ee(n,"--doc"):{path:r};if(s&&be(i,"--doc",ta),!i.path)throw new p("--doc requires path=<value> or a bare doc path",m.USAGE);return{path:i.path,scope:rt(i.scope??"project",Be,"doc scope"),note:Ke(i.note)}}),explicitEmpty:!1})}function $M(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:($e(e,"--reminder","Use --clear-reminders to clear reminders."),{values:Xo(e,new Date(t),{valueMode:"raw"}),explicitEmpty:!1})}function NM(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:($e(e,"--event","Use --clear-events to clear linked events."),{values:Qo(e,new Date(t),{allDayEmptyGuard:"defined",recurrenceEmptyNumericGuard:"defined"}),explicitEmpty:!1})}function MM(e,t,n,r=[]){let s=[...zu.filter(i=>e[i]!==void 0),...r.filter(i=>e[i]!==void 0),...t.length>0?["body"]:[],...n.map(i=>`unset:${i}`)];return Array.from(new Set(s))}function PM(e,t){let n=e??"";if(t.length===0)return n;let r=`explicit_unset=${t.join(",")}`;return n?`${n} | ${r}`:r}function yb(e,t,n){let r=gr("create",e);if(!r)throw new p(`Unsupported ${n} entry "${e}" for type "${t}"`,m.CONFLICT);return r}function FM(e){return{scalarValues:{title:e.title,description:e.description,type:e.type,status:e.status,priority:e.priority,tags:e.tags,body:e.body,deadline:e.deadline,estimatedMinutes:e.estimatedMinutes,acceptanceCriteria:e.acceptanceCriteria,definitionOfReady:e.definitionOfReady,order:e.order??e.rank,goal:e.goal,objective:e.objective,value:e.value,impact:e.impact,outcome:e.outcome,whyNow:e.whyNow,author:e.author,message:e.message,assignee:e.assignee,parent:e.parent,reviewer:e.reviewer,risk:e.risk,confidence:e.confidence,sprint:e.sprint,release:e.release,blockedBy:e.blockedBy,blockedReason:e.blockedReason,unblockNote:e.unblockNote,reporter:e.reporter,severity:e.severity,environment:e.environment,reproSteps:e.reproSteps,resolution:e.resolution,expectedResult:e.expectedResult,actualResult:e.actualResult,affectedVersion:e.affectedVersion,fixedVersion:e.fixedVersion,component:e.component,regression:e.regression,customerImpact:e.customerImpact},repeatableValues:{dep:e.dep,comment:e.comment,note:e.note,learning:e.learning,file:e.file,test:e.test,doc:e.doc,reminder:e.reminder,event:e.event,typeOption:e.typeOption,field:e.field},addTags:e.addTags}}function bb(e,t){if(t==="tags")return e.scalarValues.tags!==void 0||Array.isArray(e.addTags)&&e.addTags.length>0;if(Object.prototype.hasOwnProperty.call(e.scalarValues,t))return e.scalarValues[t]!==void 0;if(Object.prototype.hasOwnProperty.call(e.repeatableValues,t)){let n=e.repeatableValues[t];return Array.isArray(n)&&n.length>0}return!1}function DM(e,t){let n=new Set(["title","type"]);if(t!=="strict")return n;for(let r of e.required_create_fields)n.add(yb(r,e.name,"required_create_fields"));for(let r of e.required_create_repeatables)n.add(yb(r,e.name,"required_create_repeatables"));return n}function jM(e,t,n,r){for(let s of e)if(!(!bb(t,s)&&!n.has(s)))throw new p(`Option ${Ie("create",s)} is disabled for type "${r}" by command_option_policies`,m.USAGE)}function UM(e,t,n){if(t!=="strict")return;let r=e.filter(i=>n.has(i)&&!Tl(i));if(r.length===0)return;let s=[...new Set(r.map(i=>Ie("create",i)))].sort((i,o)=>i.localeCompare(o));throw new p(`Strict create mode requires concrete values for ${s.join(", ")}; --unset cannot satisfy a required scalar option (only repeatable options accept an explicit --clear-* empty set)`,m.USAGE)}function GM(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:($e(e,"--type-option","Use --clear-type-options to clear existing type options."),{values:Zo(e),explicitEmpty:!1})}async function qM(e){return await Us(e,[["body","--body"],["description","--description"]],[["dep","--dep"],["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"],["field","--field"]])}async function WM(e){return Bt(e)?await qM(e):e}function KM(e,t){if(e===void 0)return t;let n=e.trim().toLowerCase();if(n.length===0)return t;if(n==="strict"||n==="progressive")return n;throw new p(`Invalid --create-mode value "${e}". Allowed: ${EM.join(", ")}`,m.USAGE)}function zM(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)throw new p("--schedule-preset must not be empty",m.USAGE);if(t==="lightweight"||t==="lite"||t==="schedule-lite")return"lightweight";throw new p(`Invalid --schedule-preset value "${e}". Allowed: ${AM.join(", ")}`,m.USAGE)}function BM(e,t,n){let r=KM(e,n);if(t===void 0)return r;if(typeof e=="string"&&e.trim().length>0&&r==="strict")throw new p("--schedule-preset lightweight cannot be combined with --create-mode strict. Use --create-mode progressive or omit --create-mode.",m.USAGE);return"progressive"}function HM(e,t,n,r,s,i){let o=e.name,a=FM(t),c=DM(e,n),d=In(e,"create",c);if(d.errors.length>0)throw new p(d.errors.join("; "),m.CONFLICT);jM(d.disabled,a,r,o),UM(d.required,n,r);let l=f=>f==="author"&&s!=="unknown"||f==="status"&&e.default_status!==void 0||i.has(f)||r.has(f)&&Tl(f)?!0:bb(a,f),u=d.required.filter(f=>!l(f));return[...new Set(u.map(f=>Ie("create",f)))].sort((f,_)=>f.localeCompare(_))}var xb=/^Missing required type option "([^"]+)" for type "([^"]+)"$/;function VM(e,t){let n=[];for(let r of e){let s=r.match(xb);s&&s[2]===t&&n.push(s[1])}return[...new Set(n)].sort((r,s)=>r.localeCompare(s))}function YM(e,t){return e.filter(n=>{let r=n.match(xb);return!r||r[2]!==t})}function JM(e,t,n,r){let s=YM(e,t);if(s.length===0)return;let i=Sb(n,[],[],r.open_status);throw new p(s.join("; "),m.USAGE,{code:"invalid_argument_value",required:`Provide valid --type-option key/value pairs for type "${t}".`,examples:[i],nextSteps:[`Run "pm create --help --type ${t}" to review allowed type-option keys and values.`]})}function XM(e,t){let r=e.options.find(s=>s.key===t)?.values[0];return typeof r=="string"&&r.trim().length>0?r:"<value>"}function QM(e,t,n){let r=e.split("/")[0];switch(r){case"--title":return["--title",`"${t} example title"`];case"--description":return["--description",`"${t} example description"`];case"--type":return["--type",t];case"--status":return["--status",n];case"--priority":return["--priority","1"];case"--message":return["--message",`"Create ${t} item"`];case"--comment":return["--comment",'"author=maintainer,created_at=now,text=Implementation context"'];default:return[r,'"<value>"']}}function Sb(e,t,n,r){let s=["pm","create","--title",`"${e.name} example title"`,"--description",`"${e.name} example description"`,"--type",e.name],i=["--status","--priority","--message"],o=[...new Set([...i,...t])],a=new Set(["--title","--description","--type"]);for(let c of o){if(a.has(c))continue;let d=Ab[c];s.push(...d?[d]:QM(c,e.name,r)),a.add(c)}for(let c of n){let d=XM(e,c);s.push("--type-option",`${c}=${d}`)}return s.join(" ")}function Fl(e,t,n="cli"){let r=e?.trim();if(!r){let s=n==="sdk";throw t==="--title"?e!==void 0?new p(s?"Title cannot be empty or whitespace-only. Retry: pass a non-empty title.":"Title cannot be empty or whitespace-only. Retry: pass a non-empty title with --title.",m.USAGE):new p(s?'Missing required option title. Why required: every item needs a human-readable title for lookup, search, and reporting. Retry: pass title (example: client.create({ type: "Issue", title: "Fix login bug" })).':'Missing required option --title. Why required: every item needs a human-readable title for lookup, search, and reporting. Retry: pass the title as the first positional argument (example: pm create "Fix login bug" --type Issue) or with --title.',m.USAGE):new p(`Missing required option ${s?An("sdk",t.replace(/^--/u,"")):t}`,m.USAGE)}return r}function ZM(e,t,n){let r={};for(let[s,i]of Object.entries(e))r[s]=Array.isArray(i)?[...i]:i;for(let[s,i]of Object.entries(t))i!==void 0&&(r[s]=Array.isArray(i)?[...i]:i);return eP(r,t,n),dt(t,r)}function eP(e,t,n){let r=[...Ec(t.unset,n).optionKeys,...eb(t.defer,n?.definitions)].flatMap(s=>s==="order"?[s,"rank"]:s==="tags"?[s,"addTags"]:[s]);for(let s of r)Reflect.get(t,s)===void 0&&Reflect.deleteProperty(e,s)}function tP(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function nP(){let e=F();return e?e.commands.some(t=>t.action==="templates-show"||tP(t.command)==="templates show"):!1}function rP(e,t){if(typeof e!="object"||e===null||!("options"in e))throw new p(`Templates package returned invalid payload for template "${t}". Expected an options object.`,m.GENERIC_FAILURE);let n=e.options;if(typeof n!="object"||n===null||Array.isArray(n))throw new p(`Templates package returned invalid options for template "${t}".`,m.GENERIC_FAILURE);let r={};for(let[s,i]of Object.entries(n)){if(typeof i=="string"||typeof i=="number"||typeof i=="boolean"){r[s]=i;continue}if(Array.isArray(i)&&i.every(o=>typeof o=="string")){r[s]=[...i];continue}throw new p(`Templates package returned unsupported option value for "${s}" in template "${t}".`,m.GENERIC_FAILURE)}return r}async function sP(e,t,n){if(!nP())throw new p("--template requires the templates package. Install it first (for example: pm install templates --project).",m.USAGE);let r=await Lf({command:"templates show",args:[e],options:{},global:t,pm_root:n});if(!r.handled)throw Object.hasOwn(r,"cause")?op("templates show",r):new p(`Unable to resolve template "${e}" via templates package. Run "pm templates show ${e}" for details.`,m.USAGE);return rP(r.result,e)}function J(e,t,n){return e.has(t)||n===void 0?void 0:Ke(n)}function yn(e,t,n,r){return e.has(t)||n===void 0?void 0:r(n)}var iP=new Set(["milestone","meeting","reminder","event"]);function Eb(e,t,n,r){let s=t!==void 0,i=n!==void 0&&n.length>0,o=r!==void 0&&r.length>0;return iP.has(e.toLowerCase())&&!s&&!i&&!o}function oP(e,t,n,r,s){let i=[];return e.toLowerCase()==="event"&&(s===void 0||s.length===0)&&i.push(`event_without_schedule:${t}:no_time_set`),Eb(e,n,r,s)&&i.push(`calendar_item_without_schedule:${t}:no_deadline_or_reminder_or_event (hint: set --deadline <ISO> or --reminder "<when>", or link an Event via --event "start=<ISO>,end=<ISO>"; otherwise this item never appears on pm calendar)`),i}async function aP(e,t,n,r){if(t.inheritFocus!==!0||e!==void 0||n.has("parent")||t.parent!==void 0)return{parent:e,parentSource:void 0};let s=await sf(r);return s===void 0?{parent:e,parentSource:void 0}:{parent:s,parentSource:"focus"}}async function cP(e,t,n,r,s,i,o){let a=Pn(fi(s,o),t.id_prefix);if(bi(a))return{parent:a,warnings:[]};if(_i(r,a,t.id_prefix,o),await Y(e,a,t.id_prefix,t.item_format,n.type_to_folder))return{parent:a,warnings:[]};let d=Ze(a,t.id_prefix);return{parent:a,warnings:pi(d,i,o).warnings}}async function dP(e){return e.parent===void 0?{parent:void 0,warnings:[]}:await cP(e.pmRoot,e.settings,e.typeRegistry,e.itemId,e.parent,e.policy,e.audience)}async function lP(e){if(e.explicitId===void 0)return Nf(e.pmRoot,e.settings.id_prefix,{tokenLength:e.settings.ids.token_length,typeToFolder:e.typeRegistry.type_to_folder,probeExisting:!1});Nr(e.explicitId,"create","id");let t=e.explicitId.trim();if(t.length===0||Mf(t))throw new p("--id must not be empty or use a placeholder token",m.USAGE);let n=Ze(t,e.settings.id_prefix);if(!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(n))throw new p("--id must contain only letters, numbers, and dashes after normalization",m.USAGE);return n}function wb(e,t,n,r,s,i){let o=J(e,t,n);if(o===void 0)return{value:void 0,warnings:[]};let a=gi(r,o,s,i);return{value:a.value,warnings:a.warnings}}async function uP(e){let{pmRoot:t,settings:n,typeRegistry:r,statusRegistry:s,blockedBy:i,status:o,statusExplicit:a,nowValue:c,author:d}=e,l=e.dependencyValues;if(i===void 0)return{dependencyValues:l,status:o};let u=Ze(i,n.id_prefix),f=await Y(t,u,n.id_prefix,n.item_format,r.type_to_folder);if(!f)return{dependencyValues:l,status:o};if((l??[]).some(g=>g.id===f.id&&g.kind==="blocked_by")||(l=[...l??[],{id:f.id,kind:"blocked_by",created_at:c,author:d,source_kind:"cli:create:blocked_by",author_source:"detected"}]),a)return{dependencyValues:l,status:o};let h=s.blocked_statuses.has("blocked")?"blocked":[...s.blocked_statuses].sort((g,y)=>g.localeCompare(y))[0]??s.open_status;return{dependencyValues:l,status:h}}function mP(e,t,n){if(typeof e.createMode=="string"&&e.createMode.trim().toLowerCase()==="strict")return;let s=t.governance.create_default_type?.trim();if(s&&s.length>0&&_t(s,n)){e.type=s;return}_t("Task",n)&&(e.type="Task")}function fP(e,t){return e.options.filter(n=>gr("create",n.key)===void 0).flatMap(n=>{let r=t[n.key];if(r===void 0)return[];if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")return[n];throw new p(`Template custom type option "${n.key}" must be a string, number, or boolean value`,m.USAGE)})}async function pP(e,t,n,r,s){let i=e,o=[];if(i.template!==void 0){let h=i.template.trim();if(h.length===0)throw new p("--template must not be empty. Omit --template to disable template usage.",m.USAGE);let g=await sP(h,t,n);i=kb(Mr("create",ZM(g,i,Yt(r.schema))))}if(i.type===void 0&&mP(i,r,s),i.type===void 0)throw new p("Missing required option --type <value>",m.USAGE);let a=_t(i.type,s);if(!a){let h=Pf(i.type),g=h?_t(h,s):void 0;if(g)o.push(`type_coercion:${i.type.trim()}:${g}`),i.type=g,a=g;else throw new p(yi(i.type,s.types,Zs(n,r.schema)),m.USAGE)}let c=Ks(a,s);if(!c)throw new p(`Invalid type value "${i.type}"`,m.USAGE);let d=c.name,l=fP(c,i),u=l.map(h=>`${h.key}=${String(i[h.key])}`);if(u.length>0){i.typeOption=[...u,...i.typeOption??[]];for(let h of l)delete i[h.key]}let f=zM(i.schedulePreset);if(f!==void 0&&!vb.has(d))throw new p(`--schedule-preset ${f} is only supported for Reminder, Meeting, or Event types`,m.USAGE);let _=BM(i.createMode,f,r.governance.create_mode_default);return{resolvedOptions:i,typeDefinition:c,type:d,schedulePreset:f,createMode:_,warnings:o}}function _P(e,t){let n=new Set(t.metadataKeys),r=new Set(t.optionKeys),s=[{enabled:e.clearDeps,optionKey:"dep",clearFlag:"--clear-deps",valueFlag:"--dep",values:e.dep,metadataKey:"dependencies"},{enabled:e.clearComments,optionKey:"comment",clearFlag:"--clear-comments",valueFlag:"--comment",values:e.comment,metadataKey:"comments"},{enabled:e.clearNotes,optionKey:"note",clearFlag:"--clear-notes",valueFlag:"--note",values:e.note,metadataKey:"notes"},{enabled:e.clearLearnings,optionKey:"learning",clearFlag:"--clear-learnings",valueFlag:"--learning",values:e.learning,metadataKey:"learnings"},{enabled:e.clearFiles,optionKey:"file",clearFlag:"--clear-files",valueFlag:"--file",values:e.file,metadataKey:"files"},{enabled:e.clearTests,optionKey:"test",clearFlag:"--clear-tests",valueFlag:"--test",values:e.test,metadataKey:"tests"},{enabled:e.clearDocs,optionKey:"doc",clearFlag:"--clear-docs",valueFlag:"--doc",values:e.doc,metadataKey:"docs"},{enabled:e.clearReminders,optionKey:"reminder",clearFlag:"--clear-reminders",valueFlag:"--reminder",values:e.reminder,metadataKey:"reminders"},{enabled:e.clearEvents,optionKey:"event",clearFlag:"--clear-events",valueFlag:"--event",values:e.event,metadataKey:"events"},{enabled:e.clearTypeOptions,optionKey:"typeOption",clearFlag:"--clear-type-options",valueFlag:"--type-option",values:e.typeOption,metadataKey:"type_options"}];for(let i of s)if(i.enabled){if(i.values&&i.values.length>0)throw new p(`Cannot combine ${i.clearFlag} with ${i.valueFlag}`,m.USAGE);n.add(i.metadataKey),r.add(i.optionKey)}return{explicitUnsets:n,clearOptionKeys:r}}function hP(e,t){let n={tags:e.tags!==void 0,deadline:e.deadline!==void 0,estimatedMinutes:e.estimatedMinutes!==void 0,acceptanceCriteria:e.acceptanceCriteria!==void 0,definitionOfReady:e.definitionOfReady!==void 0,order:e.order!==void 0||e.rank!==void 0,goal:e.goal!==void 0,objective:e.objective!==void 0,value:e.value!==void 0,impact:e.impact!==void 0,outcome:e.outcome!==void 0,whyNow:e.whyNow!==void 0,author:e.author!==void 0,assignee:e.assignee!==void 0,parent:e.parent!==void 0,reviewer:e.reviewer!==void 0,risk:e.risk!==void 0,confidence:e.confidence!==void 0,sprint:e.sprint!==void 0,release:e.release!==void 0,blockedBy:e.blockedBy!==void 0,blockedReason:e.blockedReason!==void 0,unblockNote:e.unblockNote!==void 0,reporter:e.reporter!==void 0,severity:e.severity!==void 0,environment:e.environment!==void 0,reproSteps:e.reproSteps!==void 0,resolution:e.resolution!==void 0,expectedResult:e.expectedResult!==void 0,actualResult:e.actualResult!==void 0,affectedVersion:e.affectedVersion!==void 0,fixedVersion:e.fixedVersion!==void 0,component:e.component!==void 0,regression:e.regression!==void 0,customerImpact:e.customerImpact!==void 0};for(let[r,s]of Object.entries(n)){if(!s||!t.optionKeys.has(r))continue;let i=ea.get(r)??r;throw new p(`Cannot combine --unset ${i} with ${Ie("create",r)}`,m.USAGE)}}function gP(e){if(at(e))return;let t=(n,r)=>{if(at(e,r))return;let s=ea.get(r),i=s?`Use --unset ${s} to clear this field.`:void 0;Ci(n,Ie("create",r),i)};t(e.tags,"tags"),t(e.deadline,"deadline"),t(e.estimatedMinutes,"estimatedMinutes"),t(e.acceptanceCriteria,"acceptanceCriteria"),t(e.definitionOfReady,"definitionOfReady"),t(e.order??e.rank,"order"),t(e.goal,"goal"),t(e.objective,"objective"),t(e.value,"value"),t(e.impact,"impact"),t(e.outcome,"outcome"),t(e.whyNow,"whyNow"),t(e.author,"author"),t(e.assignee,"assignee"),t(e.parent,"parent"),t(e.reviewer,"reviewer"),t(e.risk,"risk"),t(e.confidence,"confidence"),t(e.sprint,"sprint"),t(e.release,"release"),t(e.blockedBy,"blockedBy"),t(e.blockedReason,"blockedReason"),t(e.unblockNote,"unblockNote"),t(e.reporter,"reporter"),t(e.severity,"severity"),t(e.environment,"environment"),t(e.reproSteps,"reproSteps"),t(e.resolution,"resolution"),t(e.expectedResult,"expectedResult"),t(e.actualResult,"actualResult"),t(e.affectedVersion,"affectedVersion"),t(e.fixedVersion,"fixedVersion"),t(e.component,"component"),t(e.regression,"regression"),t(e.customerImpact,"customerImpact")}function yP(e,t,n){for(let r of Object.keys(e))if(n.metadataKeys.has(r))throw new p(`Cannot combine --unset ${r.replaceAll("_","-")} with --field ${r}=...`,m.USAGE);for(let r of Object.keys(t.values??{}))if(n.metadataKeys.has(r))throw new p(`Cannot combine --unset ${r.replaceAll("_","-")} with its value flag`,m.USAGE)}var Ab={"--comment":"--clear-comments","--dep":"--clear-deps","--doc":"--clear-docs","--event":"--clear-events","--file":"--clear-files","--learning":"--clear-learnings","--note":"--clear-notes","--reminder":"--clear-reminders","--test":"--clear-tests","--type-option":"--clear-type-options"};function wP(e){let{combinedMissingFlags:t,typeDefinition:n,missingRequiredCreateFlags:r,missingRequiredTypeOptionKeys:s,openStatus:i,type:o,createMode:a,missingRequiredRuntimeFields:c}=e;if(t.length===0)return;let d=c.map(h=>{let g=h.type==="boolean"?"<true|false>":h.type==="array"?"<json-array>":h.type==="object"?"<json-object>":h.type==="number"?"<number>":h.type==="string_array"||h.repeatable?"<value>":"<string>";return{example:`--${h.cli_flag} ${g}`,description:`--${h.cli_flag} maps to ${h.metadata_key} (${h.type}${h.repeatable?", repeatable":""})`}}),l=[Sb(n,r,s,i),...d.map(h=>h.example)].join(" "),u=[`Run "pm create --help --type ${o}" for type-aware required option guidance.`,...t.filter(h=>h==="--title").map(()=>'Title can also be passed as the first positional argument (example: pm create "Your title" --type '+o+").")];a==="strict"&&(u.push('For staged onboarding, retry with "--create-mode progressive".'),vb.has(o)&&u.push('For minimal scheduling inputs, try "--schedule-preset lightweight".')),d.length>0&&u.push(`Required custom field formats: ${d.map(h=>h.description).join("; ")}.`);let f=[...new Set(t.flatMap(h=>{let g=h.split(" ",1)[0],y=Ab[g];return y?[y]:[]}))];f.length>0&&u.push(`If the truthful value is an empty collection, use ${f.join(", ")} instead of inventing metadata.`);let _=t.length===1?`Missing required option ${t[0]} for type "${o}"`:`Missing required options ${t.join(", ")} for type "${o}"`;throw new p(_,m.USAGE,{code:"missing_required_option",required:`Provide all required create options and type options for type "${o}" in one invocation.`,examples:[...f.map(h=>`pm create --type ${o} ${h} ...`),l],nextSteps:u,recovery:a==="strict"?{recovery_mode:"compact",missing_required_fields:t,suggested_flags:[...f,...t,"--create-mode progressive"]}:void 0})}function vP(e,t){if(e.has("tags")&&Array.isArray(t.addTags)&&t.addTags.length>0)throw new p("Cannot combine --unset tags with --add-tags",m.USAGE);let n=e.has("tags")?[]:t.tags!==void 0?Fs(t.tags):[];return js(n,t.addTags)}function kP(e,t){if(t.order!==void 0&&t.rank!==void 0&&t.order!==t.rank)throw new p("--order and --rank must match when both are provided",m.USAGE);let n=t.order??t.rank,r=yn(e,"order",n,s=>we(s,"order"));if(r!==void 0&&!Number.isInteger(r))throw new p("Order must be an integer",m.USAGE);return r}function bP(e,t,n,r,s,i){if(r.completedAt!==void 0&&e!==t.close_status)throw new p("--completed-at requires a terminal create status.",m.USAGE);let o=e!==t.close_status?void 0:r.completedAt===void 0?i:me(r.completedAt,new Date(i),"completed-at");if(e!==t.close_status)return{closeReason:void 0,completedAt:o,warnings:[]};let a=n.governance.require_close_reason?{explicit:r.closeReason??r.message,resolution:s}:{explicit:r.closeReason};return{closeReason:El(a,n.governance.require_close_reason,{operation:"create",status:e}).closeReason,completedAt:o,warnings:[]}}async function xP(e){let{pmRoot:t,type:n,id:r,settings:s,typeRegistry:i,author:o,extensionFieldNames:a,afterDocument:c,beforeDocument:d,historyMessage:l,changedFields:u,nowValue:f,similarityCandidate:_,allowDuplicate:h}=e,g=wm(t,n,r,s.item_format,i.type_to_folder),y=ht(t,r),w=de(),v=c.metadata.parent!==void 0||(c.metadata.dependencies??[]).some(A=>Oo(A.kind,w)),S=await Wo({pmRoot:t,author:o,ttlSeconds:s.locks.ttl_seconds,waitMs:s.locks.wait_ms,required:v}),b=v,k=[];try{let A=await ai(t,r,s.locks.ttl_seconds,o,!1,s.governance.force_required_for_stale_lock,s.locks.wait_ms);try{let x=c.metadata.parent!==void 0||c.metadata.dependencies!==void 0&&c.metadata.dependencies.length>0?await Ae(t,s.item_format,i.type_to_folder,void 0,s.schema):void 0,E=await Y(t,r,s.id_prefix,s.item_format,i.type_to_folder);if(E)throw new p(`Item "${r}" already exists`,m.CONFLICT,{code:"item_already_exists",id:E.id,path:E.itemPath,required:"Read the existing item before deciding whether to update it or create a different ID.",nextSteps:[`Inspect the existing item with pm get ${E.id}.`]});if(x){Lo(x,[...x,c.metadata],w);let T=z(s.schema);Li(x,[...x,c.metadata],r,q=>_e(q,T),w)}let $=await Kf({pmRoot:t,settings:s,operation:"create",author:o,before:null,after:c});await Rf({pm_root:t,operation:"create",before:null,after:c,changed_fields:u,author:o,sdk:Jf({pmRoot:t,settings:s,typeToFolder:i.type_to_folder})});let P=await Vf(t,o,{required:s.governance.duplicate_detection_mode==="strict"&&h!==!0}),R=[];try{s.governance.duplicate_detection_mode==="strict"&&h!==!0&&await bd(_,{pmRoot:t,mode:"strict",threshold:s.governance.duplicate_detection_threshold,limit:s.governance.duplicate_detection_limit,allowDuplicate:!1}),await A.fence(async()=>{await Ge(g,Xm(c,{format:s.item_format,schema:s.schema,extensionFieldNames:a}));try{let T=yf({nowIso:f,author:o,op:"create",before:d,after:c,message:l,context:$.decisions.length===0?void 0:{workflow_policies:$.decisions}});await wf(y,T)}catch(T){throw await um(g),T}}),b&&(await S(),b=!1),R=await Yf({pmRoot:t,preferredFormat:s.item_format,typeToFolder:i.type_to_folder,schema:s.schema,itemPath:g,document:c})}finally{await P()}k=[...$.warnings,...x?Io(x,[...x,c.metadata],r):[],...R,...await yt({path:g,scope:"project",op:"create",item_id:c.metadata.id,item_type:c.metadata.type,before:d,after:c,changed_fields:u}),...await yt({path:y,scope:"project",op:"create:history",item_id:c.metadata.id,item_type:c.metadata.type,before:d,after:c,changed_fields:u})],Cf({id:c.metadata.id,op:"create",item_type:c.metadata.type,status:c.metadata.status,current:Tf(c.metadata,u),changed_fields:u})}finally{await A.release()}}finally{b&&await S()}return k}async function a4(e,t){let n=Mr("create",e),r=ct(n),s=kb(await WM(n)),i=I(process.cwd(),t.path);await j(i);let o=await C(i),a=z(o.schema),c=Yt(o.schema),d=D(o,F()),l=await pP(s,t,i,o,d);s=l.resolvedOptions;let{typeDefinition:u,type:f,createMode:_}=l,h=Ec(s.unset,c),{explicitUnsets:g,clearOptionKeys:y}=_P(s,h);hP(s,h),gP(s);let w=Qk(s,r);Il(w,s,h.metadataKeys,r);let v=G(Ke(s.author),o.author_default),S=HM(u,s,_,y,v,w.optionKeys),b=O(),k=OM(s.dep,b,o.id_prefix,v),A=wn("--comment",s.comment,b,v),x=wn("--note",s.note,b,v),E=wn("--learning",s.learning,b,v),$=Nl(s.file),P=Ml(s.test);P.values=await tr(P.values,v,b);let R=Pl(s.doc),T=$M(s.reminder,b),q=NM(s.event,b),Pe=GM(s.typeOption),ke=yr(f,Pe.values,d),oe=F(),ze=Ot(oe),Fe=li(s.field,oe,Vo,Yo(c,"create",s)),ye=Wm(s,c,f);Il(w,s,h.metadataKeys,r,ye.values),ye.missing_required_flags=tb(ye.missing_required_flags,w,c.definitions,f,s);let Se=new Set(ye.missing_required_flags),re=c.definitions.filter(X=>Se.has(`--${X.cli_flag}`));yP(Fe,ye,h);let Je=VM(ke.errors,f),pt=Je.map(X=>`--type-option ${X}=<value>`),st=[...new Set([...S,...pt,...ye.missing_required_flags])].sort((X,Fa)=>X.localeCompare(Fa));wP({combinedMissingFlags:st,typeDefinition:u,missingRequiredCreateFlags:S,missingRequiredTypeOptionKeys:Je,openStatus:a.open_status,type:f,createMode:_,missingRequiredRuntimeFields:re}),JM(ke.errors,f,u,a);let ue=await lP({pmRoot:i,settings:o,typeRegistry:d,explicitId:s.id}),De=s.status!==void 0?TM(s.status,a):RM(u,a),Ee=s.priority!==void 0?hi(s.priority):2,N=h.metadataKeys,Tt=vP(N,s),je=yn(N,"deadline",s.deadline,X=>me(X,new Date(b),"deadline")),_r=yn(N,"estimated_minutes",s.estimatedMinutes,X=>Gs(X,"estimated-minutes")),Re=J(N,"acceptance_criteria",s.acceptanceCriteria),ae=J(N,"definition_of_ready",s.definitionOfReady),Ls=kP(N,s),Ia=J(N,"goal",s.goal),$s=J(N,"objective",s.objective),iE=J(N,"value",s.value),oE=J(N,"impact",s.impact),aE=J(N,"outcome",s.outcome),cE=J(N,"why_now",s.whyNow),dE=J(N,"assignee",s.assignee),lE=N.has("author")?void 0:Ke(s.author)??v,uE=J(N,"parent",s.parent),$u=await aP(uE,s,N,i),Oa=$u.parent,mE=$u.parentSource,fE=J(N,"reviewer",s.reviewer),pE=yn(N,"risk",s.risk,X=>rt(Ko(X),qs,"risk")),_E=yn(N,"confidence",s.confidence,X=>Bo(X)),hE=s.allowMissingParent===!0&&o.validation.parent_reference==="strict_error"?"warn":o.validation.parent_reference,Nu=o.validation.sprint_release_format,Wt=[...l.warnings,...oP(f,ue,je,T.values,q.values)],Mu=await dP({itemId:ue,parent:Oa,pmRoot:i,settings:o,typeRegistry:d,policy:hE,audience:r});Oa=Mu.parent,Wt.push(...Mu.warnings);let Pu=wb(N,"sprint",s.sprint,"sprint",Nu,r),gE=Pu.value;Wt.push(...Pu.warnings);let Fu=wb(N,"release",s.release,"release",Nu,r),yE=Fu.value;Wt.push(...Fu.warnings);let Du=J(N,"blocked_by",s.blockedBy),ju=await uP({pmRoot:i,settings:o,typeRegistry:d,statusRegistry:a,blockedBy:Du,dependencyValues:k.values,status:De,statusExplicit:s.status!==void 0,nowValue:b,author:v}),La=ju.dependencyValues;vs(ue,La),Wt.push(...await Jo({pmRoot:i,dependencies:La,idPrefix:o.id_prefix,itemFormat:o.item_format,typeToFolder:d.type_to_folder,allowUnresolved:s.allowUnresolvedDeps,holders:[{id:ue,createdAt:b}],schema:o.schema})),De=ju.status;let wE=J(N,"blocked_reason",s.blockedReason),vE=J(N,"unblock_note",s.unblockNote),kE=J(N,"reporter",s.reporter),bE=yn(N,"severity",s.severity,X=>rt(zo(X),Ws,"severity")),xE=J(N,"environment",s.environment),SE=J(N,"repro_steps",s.reproSteps),Uu=J(N,"resolution",s.resolution),EE=J(N,"expected_result",s.expectedResult),AE=J(N,"actual_result",s.actualResult),CE=J(N,"affected_version",s.affectedVersion),TE=J(N,"fixed_version",s.fixedVersion),RE=J(N,"component",s.component),IE=yn(N,"regression",s.regression,X=>Ho(X)),OE=J(N,"customer_impact",s.customerImpact),$a=Fl(s.title,"--title",r),Na=s.description??"",Ns=s.body??"",Gu=await bd({title:$a,description:Na,body:Ns},{pmRoot:i,mode:o.governance.duplicate_detection_mode,threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:s.allowDuplicate});Wt.push(...Jy(Gu));let Ma=bP(De,a,o,s,Uu,b),LE=Ma.closeReason,$E=De===a.close_status?b:void 0,NE=Ma.completedAt;Wt.push(...Ma.warnings);let En=Jm({id:ue,title:$a,description:Na,type:f,type_options:ke.normalized,status:De,closed_at:$E,completed_at:NE,close_reason:LE,priority:Ee,tags:Tt,created_at:b,updated_at:b,deadline:je,assignee:dE,author:lE,estimated_minutes:_r,acceptance_criteria:Re,deferred_fields:Zk(w),definition_of_ready:ae,order:Ls,goal:Ia,objective:$s,value:iE,impact:oE,outcome:aE,why_now:cE,parent:Oa,reviewer:fE,risk:pE,confidence:_E,sprint:gE,release:yE,blocked_by:Du,blocked_reason:wE,unblock_note:vE,reporter:kE,severity:bE,environment:xE,repro_steps:SE,resolution:Uu,expected_result:EE,actual_result:AE,affected_version:CE,fixed_version:TE,component:RE,regression:IE,customer_impact:OE,dependencies:La,comments:A.values,notes:x.values,learnings:E.values,files:$.values,tests:P.values,docs:R.values,reminders:T.values,events:q.values,...Fe,...ye.values});Om(En);try{ui(En,oe)}catch(X){throw new p(X instanceof Error?X.message:"Invalid extension item field values",m.USAGE)}zf(En,i);let ME=Qm({metadata:En,body:Ns},{schema:o.schema,extensionFieldNames:ze}),PE={metadata:{},body:""},qu=[...g].sort((X,Fa)=>X.localeCompare(Fa)),FE=PM(s.message,qu),Wu=MM(En,Ns,qu,[...Object.keys(Fe),...Object.keys(ye.values??{})]),DE=await xP({pmRoot:i,type:f,id:ue,settings:o,typeRegistry:d,author:v,extensionFieldNames:ze,afterDocument:ME,beforeDocument:PE,historyMessage:FE,changedFields:Wu,nowValue:b,similarityCandidate:{title:$a,description:Na,body:Ns},allowDuplicate:s.allowDuplicate}),Pa=structuredClone(En);_==="strict"&&g.has("dependencies")&&(Pa.dependencies=[]);let jE=ob(ue,f,De,a);return Eb(f,je,T.values,q.values)&&gf(`[pm] warning: ${f} '${ue}' has no deadline/reminder/event \u2014 it will not appear on the calendar. Add one via 'pm update ${ue} --deadline <ISO>' or 'pm update ${ue} --event "start=<ISO>,end=<ISO>"'.`),{item:Pa,changed_fields:Wu,warnings:[...$r("create",s,r==="sdk",Pa),...Wt,...DE],...Object.fromEntries([["parent_source",mE],["next_transition",jE],["similarity_advisory",Gu]].filter(X=>X[1]!==void 0))}}function vn(e){return e.in_progress_status!==e.open_status&&e.by_id.has(e.in_progress_status)?e.in_progress_status:Qe("in_progress",e)??e.open_status}import{AsyncLocalStorage as SP}from"node:async_hooks";var EP="strict",sa="start_blocked_by_open_dependency";function Cb(e,t,n){if(t===void 0)return!1;let r=Jt(vn(n),n);return Jt(t,n)===r&&Jt(e??"",n)!==r}function ra(e,t,n){let r=s=>Ze(s.trim(),n).toLowerCase();return r(e)===r(t)}var AP=new Set(["cli:create:blocked_by","cli:update:blocked_by"]);function Dl(e,t,n){if(e.kind!=="blocked_by"||typeof t!="string"||t.trim().length===0)return!1;let r=e.id.trim().toLowerCase();return r===t.trim().toLowerCase()?!0:r===Ze(t.trim(),n).toLowerCase()&&AP.has(e.source_kind?.trim().toLowerCase()??"")}function CP(e,t,n){let r=e.dependencies??[],s=r.filter(o=>o.kind==="blocked_by");if(r.some(o=>o.kind!=="blocked_by"&&Ar(o.kind)==="blocked_by"&&ra(o.id,t,n)))return L(["get",e.id,"--fields","blocked_by,dependencies"]);if(!(typeof e.blocked_by=="string"&&ra(e.blocked_by,t,n))){let o=s.filter(a=>ra(a.id,t,n));return o.length===1&&o.every(a=>a.id===Pn(a.id,n,void 0))?L(["update",e.id,"--dep-remove",`id=${o[0].id},kind=blocked_by`]):L(["get",e.id,"--fields","blocked_by,dependencies"])}return s.filter(o=>ra(o.id,t,n)).every(o=>Dl(o,e.blocked_by,n))?L(["update",e.id,"--unset","blocked_by"]):L(["get",e.id,"--fields","blocked_by,dependencies"])}var TP=new Set(["item_document_invalid","item_document_encoding_invalid","item_format_version_unsupported","item_identity_ambiguous","item_identity_conflict"]);async function RP(e,t){try{return(await pp(e)).filter(n=>!n.resolved)}catch(n){let r=ip(n)?n.context.code:void 0;if(!t||typeof r!="string"||!TP.has(r))throw n;return r}}async function Tb(e){let t=e.settings.governance.start_blocker_enforcement??EP;if(t==="off")return[];let n=D(e.settings,F()).type_to_folder,r=e.metadata.id,s=await RP({pmRoot:e.pmRoot,settings:e.settings,typeToFolder:n,metadata:e.metadata},t==="warn"||e.force===!0);if(typeof s=="string")return[`start_blocker_unverifiable:${r}:${s}`];if(s.length===0)return[];let i=s.map(o=>o.id).join(",");if(t==="warn")return[`start_with_open_blockers:${r}:${i}`];if(e.force===!0)return[`start_blocker_override:${r}:${i}`];throw new p(`Cannot start ${r}: ${s.length===1?"its blocker":`${s.length} of its blockers`} ${i} ${s.length===1?"is":"are"} still open.`,m.CONFLICT,{code:"start_blocked_by_open_dependency",item_id:r,required:`Finish or close the open blocker${s.length===1?"":"s"} first, remove the blocked_by edge if it no longer applies, or start anyway with --force.`,why:"Starting work that a declared blocker still gates would leave an in-progress item that validate reports as non_blocked_status_has_blocked_by. governance.start_blocker_enforcement (strict by default) governs this check.",nextSteps:[...s.filter(o=>o.external!==!0).slice(0,3).map(o=>L(["get",o.id])),CP(e.metadata,s[0].id,e.settings.id_prefix),"pm next"],details:{enforcement:t,open_blockers:s.map(o=>({id:o.id,title:o.title,status:o.status,external:o.external===!0}))}})}async function ia(e){if(e.requested===!1||!Cb(e.fromStatus,e.metadata.status,e.registry))return[];let t=await Tb(e),n=jl.getStore()?.warnings??new Set;return t.filter(r=>!n.has(r))}var jl=new SP;function Rb(e){return jl.run({warnings:new Set},e)}async function Ib(e){let t=jl.getStore();if(t===void 0)return[];let n=Cb(e.metadata.status,vn(e.registry),e.registry)?await Tb(e):[];for(let r of n)t.warnings.add(r);return n}var Ob="terminal_state_unchanged";function Lb(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function IP(e,t){return ce(e,t)===t.close_status}function OP(e){let t=n=>ph.includes(n.trim().toLowerCase());return hh(e.unset??[],t).some(t)}function $b(e){!e.settings.governance.require_close_reason||!OP(e.options)||To({explicit:e.options.closeReason},!0)}function Ul(e,t,n,r=!1){if(!IP(e.status,n))return!1;let s=Lb(t.closeReason);return r&&t.closeReason!==void 0&&s===void 0||s!==void 0&&s!==Lb(e.close_reason)?!1:t.completedAt===void 0||me(t.completedAt,new Date,"completed-at")===e.completed_at}async function Nb(e){let t=await Y(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await Zt(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await fe(t,{schema:e.settings.schema});return n.metadata}async function Mb(e,t,n,r,s){if(n.length===0)return{item:t,changed_fields:[],warnings:[...e.workflowTransitionWarnings,Ob]};let i=dt(e.options,{...e.options,status:void 0,closeReason:void 0,completedAt:void 0}),o=await r(e.id,i,e.global);return Ul(o.item,e.options,e.statusRegistry,e.settings.governance.require_close_reason)?{item:o.item,changed_fields:o.changed_fields,warnings:[...e.workflowTransitionWarnings,...o.warnings,Ob]}:s(o)}function ar(e){if(e.enforcement==="off"||e.typeWorkflows.length===0)return;let t=Ff({typeName:e.typeName,fromStatus:e.fromStatus,toStatus:e.toStatus,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry});if(!t.hasRule||t.allowed)return;let n=Qe(e.fromStatus,e.statusRegistry)??e.fromStatus,r=Qe(e.toStatus,e.statusRegistry)??e.toStatus,s=`Disallowed transition for type "${e.typeName}": ${n} -> ${r}. Allowed transitions: ${Df(t.allowedTransitions)}.`;if(e.enforcement==="strict")throw new p(s,m.USAGE);return`workflow_transition_not_allowed: ${s}`}function oa(e){let t=e.source_kind?.trim().toLowerCase()??"",n=e.author?.trim().toLowerCase()??"",r=e.created_at?.trim()??"",s=Date.parse(r),i=Number.isFinite(s)?new Date(s).toISOString():r;return[e.id.trim().toLowerCase(),e.kind,t,n,i].join("\0")}function Gl(e,t){return!(t.id!==void 0&&e.id.trim().toLowerCase()!==t.id.trim().toLowerCase()||t.kind&&e.kind!==t.kind||t.source_kind!==void 0&&e.source_kind?.trim().toLowerCase()!==t.source_kind.trim().toLowerCase()||t.author!==void 0&&e.author?.trim().toLowerCase()!==t.author.trim().toLowerCase()||t.created_at!==void 0&&(e.created_at===void 0||!Number.isFinite(Date.parse(e.created_at))||new Date(Date.parse(e.created_at)).toISOString()!==t.created_at))}function Pb(e,t,n){let r=t.filter(s=>!e.some(i=>Gl(i,s)));if(r.length!==0)throw new p(`Dependency removal did not match ${r.length===1?"a stored edge":"stored edges"}.`,m.NOT_FOUND,{code:"dependency_remove_no_match",reason:"selector_not_found",unmatched_selectors:r.map(s=>({...s,id:s.id??"*"})),available_dependencies:e.map(s=>({id:s.id,kind:s.kind,source_kind:s.source_kind,author:s.author,created_at:s.created_at})),why:"Failing on a zero-match selector prevents a mistyped dependency removal from being reported as successful.",nextSteps:[`Inspect the current item with: pm get ${n} --full`,"Retry --dep-remove with the exact id plus any kind, source_kind, author, or created_at selectors needed to identify one stored row."]})}function Fb(e,t){if(!Array.isArray(e)||e.length===0)return;let n=i=>(Array.isArray(i)?i:[]).filter(o=>typeof o=="object"&&o!==null&&typeof o.id=="string"),r=new Map;for(let i of n(t)){let o=oa(i);r.set(o,(r.get(o)??0)+1)}let s=[];for(let i of n(e)){let o=oa(i),a=r.get(o)??0;a>0?r.set(o,a-1):s.push(`${i.id}/${i.kind}`)}return s.length>0?s.join(","):void 0}var LP=(()=>{let e=new Map;for(let t of Ri)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),aa=new Map(Ri.map(e=>[e.optionKey,e.canonical])),$P=Ri.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", "),NP=new Set(["close_reason","assignee","parent","blocked_by","blocked_reason","unblock_note","dependencies","comments","notes","learnings","files","tests","docs","reminders","events"]),MP=Ai({depDisableFlagKey:"replaceDeps",fileDisableFlagKey:"replaceFiles",testDisableFlagKey:"replaceTests",docDisableFlagKey:"replaceDocs"});function Bb(e){if(at(e))return e;let t={...e,unset:e.unset?[...e.unset]:void 0},n=s=>{let i=t.unset?[...t.unset]:[];i.includes(s)||i.push(s),t.unset=i},r=new Set([...aa.keys(),"rank"]);for(let s of r){if(at(e,s))continue;let i=t[s];if(typeof i!="string"||!Lr(i))continue;let o=s==="rank"?"order":aa.get(s)??s;n(o),t[s]=void 0}return dt(e,Ti(t,MP))}function u3(e,t,n,r=["update"]){return[...zl([...e],t,n,r).metadataKeys]}function zl(e,t,n=[],r=["update"]){return gh({raw:e,supportedFields:$P,resolveDefinition:s=>{let i=n.find(a=>{let c=a.toLowerCase();return c===s||c.replaceAll("_","-")===s||c.replaceAll("-","_")===s});return LP.get(s)??r.map(a=>Sc(s,a,t)).find(a=>a!==void 0)??(i?{optionKey:"field",metadataKey:i}:void 0)}})}var Db=new Map([["--comment",e=>`pm comments ${e} --add "<text>" --force`],["--file",e=>`pm files ${e} --add "path=<path>,scope=<scope>,note=<note>" --force`],["--doc",e=>`pm docs ${e} --add "path=<path>,scope=<scope>,note=<note>" --force`]]);function jb(e){let t=e.disallowedFlags.flatMap(r=>{let s=Db.get(r);return s?[s(e.id)]:[]}),n=e.disallowedFlags.flatMap(r=>{let s=Db.get(r);return s?[`Replace ${r} with: ${s(e.id)}`]:[]});return new p(e.message,m.USAGE,{code:e.code,required:e.required,why:e.why,...t.length>0?{examples:t}:{},nextSteps:[`Re-run without: ${e.disallowedFlags.join(", ")}`,...n]})}function PP(e,t,n){let r=t.ownershipMetadataBypass===!0,s=t.ownershipDependencyBypass===!0;if(!r&&!s)return;if(r&&s)throw new p("Choose only one package-provided ownership bypass mode.",m.USAGE);let i=(c,d,l)=>{c&&l.push(d)};if(s){let c=[];if(i(t.title!==void 0,"--title",c),i(t.description!==void 0,"--description",c),i(t.body!==void 0,"--body",c),i(t.status!==void 0,"--status",c),i(t.closeReason!==void 0,"--close-reason",c),i(t.priority!==void 0,"--priority",c),i(t.type!==void 0,"--type",c),i(t.tags!==void 0,"--tags",c),i(Array.isArray(t.addTags)&&t.addTags.length>0,"--add-tags",c),i(Array.isArray(t.removeTags)&&t.removeTags.length>0,"--remove-tags",c),i(t.deadline!==void 0,"--deadline",c),i(t.estimatedMinutes!==void 0,"--estimate",c),i(t.acceptanceCriteria!==void 0,"--acceptance-criteria",c),i(Array.isArray(t.addAc)&&t.addAc.length>0,"--add-ac",c),i(Array.isArray(t.removeAc)&&t.removeAc.length>0,"--remove-ac",c),i(t.definitionOfReady!==void 0,"--definition-of-ready",c),i(t.order!==void 0||t.rank!==void 0,"--order/--rank",c),i(t.goal!==void 0,"--goal",c),i(t.objective!==void 0,"--objective",c),i(t.value!==void 0,"--value",c),i(t.impact!==void 0,"--impact",c),i(t.outcome!==void 0,"--outcome",c),i(t.whyNow!==void 0,"--why-now",c),i(t.assignee!==void 0,"--assignee",c),i(t.parent!==void 0,"--parent",c),i(t.reviewer!==void 0,"--reviewer",c),i(t.risk!==void 0,"--risk",c),i(t.confidence!==void 0,"--confidence",c),i(t.sprint!==void 0,"--sprint",c),i(t.release!==void 0,"--release",c),i(t.blockedBy!==void 0,"--blocked-by",c),i(t.blockedReason!==void 0,"--blocked-reason",c),i(t.unblockNote!==void 0,"--unblock-note",c),i(t.reporter!==void 0,"--reporter",c),i(t.severity!==void 0,"--severity",c),i(t.environment!==void 0,"--environment",c),i(t.reproSteps!==void 0,"--repro-steps",c),i(t.resolution!==void 0,"--resolution",c),i(t.expectedResult!==void 0,"--expected-result",c),i(t.actualResult!==void 0,"--actual-result",c),i(t.affectedVersion!==void 0,"--affected-version",c),i(t.fixedVersion!==void 0,"--fixed-version",c),i(t.component!==void 0,"--component",c),i(t.regression!==void 0,"--regression",c),i(t.customerImpact!==void 0,"--customer-impact",c),i(t.depRemove!==void 0,"--dep-remove",c),i(t.replaceDeps===!0,"--replace-deps",c),i(t.replaceTests===!0,"--replace-tests",c),i(t.replaceFiles===!0,"--replace-files",c),i(t.replaceDocs===!0,"--replace-docs",c),i(t.comment!==void 0,"--comment",c),i(t.note!==void 0,"--note",c),i(t.learning!==void 0,"--learning",c),i(t.file!==void 0,"--file",c),i(t.test!==void 0,"--test",c),i(t.doc!==void 0,"--doc",c),i(t.reminder!==void 0,"--reminder",c),i(t.event!==void 0,"--event",c),i(t.typeOption!==void 0,"--type-option",c),i(t.clearDeps===!0,"--clear-deps",c),i(t.clearComments===!0,"--clear-comments",c),i(t.clearNotes===!0,"--clear-notes",c),i(t.clearLearnings===!0,"--clear-learnings",c),i(t.clearFiles===!0,"--clear-files",c),i(t.clearTests===!0,"--clear-tests",c),i(t.clearDocs===!0,"--clear-docs",c),i(t.clearReminders===!0,"--clear-reminders",c),i(t.clearEvents===!0,"--clear-events",c),i(t.clearTypeOptions===!0,"--clear-type-options",c),i(t.force===!0,"--force",c),i(n.size>0,"--unset",c),t.dep===void 0||t.dep.length===0)throw new p("The dependency ownership bypass requires at least one --dep value",m.USAGE);if(c.length>0)throw jb({id:e,code:"ownership_dependency_bypass_restricted_options",message:`The dependency ownership bypass supports append-only dependency additions via --dep. Remove restricted options: ${c.join(", ")}`,required:"Pass only --dep additions (plus --message/--author) with the dependency ownership bypass.",why:"the dependency ownership bypass is a narrow non-owner override scoped to append-only dependency additions; every other mutation keeps its normal ownership rules.",disallowedFlags:c});return}let o=[];i(t.status!==void 0,"--status",o),i(t.closeReason!==void 0,"--close-reason",o),i(t.assignee!==void 0,"--assignee",o),i(t.parent!==void 0,"--parent",o),i(t.blockedBy!==void 0,"--blocked-by",o),i(t.blockedReason!==void 0,"--blocked-reason",o),i(t.unblockNote!==void 0,"--unblock-note",o),i(t.dep!==void 0,"--dep",o),i(t.depRemove!==void 0,"--dep-remove",o),i(t.replaceDeps===!0,"--replace-deps",o),i(t.replaceTests===!0,"--replace-tests",o),i(t.replaceFiles===!0,"--replace-files",o),i(t.replaceDocs===!0,"--replace-docs",o),i(t.note!==void 0,"--note",o),i(t.learning!==void 0,"--learning",o),i(t.test!==void 0,"--test",o),i(t.reminder!==void 0,"--reminder",o),i(t.event!==void 0,"--event",o),i(t.clearDeps===!0,"--clear-deps",o),i(t.clearComments===!0,"--clear-comments",o),i(t.clearNotes===!0,"--clear-notes",o),i(t.clearLearnings===!0,"--clear-learnings",o),i(t.clearFiles===!0,"--clear-files",o),i(t.clearTests===!0,"--clear-tests",o),i(t.clearDocs===!0,"--clear-docs",o),i(t.clearReminders===!0,"--clear-reminders",o),i(t.clearEvents===!0,"--clear-events",o);let a=[...n].filter(c=>NP.has(c)).sort((c,d)=>c.localeCompare(d)).map(c=>`--unset ${c.replaceAll("_","-")}`);if(o.push(...a),o.length>0)throw jb({id:e,code:"ownership_metadata_bypass_restricted_options",message:`The metadata ownership bypass only supports non-lifecycle metadata fields and evidence appends. Remove restricted options: ${o.join(", ")}`,required:"Limit the metadata ownership bypass to non-lifecycle metadata fields plus append-only --comment/--file/--doc evidence; route restricted appends and lifecycle changes through their dedicated commands.",why:"the metadata ownership bypass is a non-owner override scoped to metadata maintenance and append-only evidence; lifecycle, ownership, dependency mutations, restricted append fields, and clear/replace operations keep their normal ownership rules.",disallowedFlags:o})}function FP(e,t){let n=ce(e,t);if(!n){let r=t.definitions.map(s=>s.id);throw new p(`Invalid status value "${e}". Allowed: ${r.join(", ")}`,m.USAGE,{code:"invalid_argument_value",field:"status",value:e,allowed:r})}return n}function DP(e,t){return!e||e.trim()===""||e.trim().toLowerCase()==="now"?t:Hb(e)}function Hb(e){let t=Date.parse(e);if(!Number.isFinite(t))throw new p(`Invalid dependency created_at timestamp "${e}"`,m.USAGE);return new Date(t).toISOString()}function kn(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}var jP=["id","kind","type","author","created_at","source_kind"],UP=["id","kind","type","author","created_at","source_kind"];function Vb(e){return e.startsWith("```")||e.includes(`
|
|
11
|
+
`)||/^(?:[-*+]\s+)?(?:id|kind|type|author|created_at|source_kind)\s*[:=]/i.test(e)?!0:Cn(e)}function Bl(e){return typeof e=="string"?de().resolve(e)?.kind??e.trim():e}function GP(e,t,n,r){return e?($e(e,"--dep","Use --clear-deps to clear dependencies."),{additions:e.map(i=>{let o=i.trim(),a=Vb(o);ws(o,a);let c=a?ee(i,"--dep"):{id:o,kind:"related"};a&&be(c,"--dep",jP);let d=c.id?.trim(),l=Bl((c.kind??c.type)?.trim());if(!d||!l)throw new p("--dep requires id and kind, or a bare item id to add a related dependency",m.USAGE);if(d.toLowerCase()==="undefined")throw new p(`--dep id must not use placeholder token "${d}". Use --clear-deps to clear dependencies.`,m.USAGE);let u=Fr(kn(c.source_kind)),f=kn(c.author);return{id:Dr(d,t,u),kind:or(l),created_at:DP(c.created_at,n),author:f??r,source_kind:u??"cli:update:dep",author_source:f?"asserted":"detected"}})}):{additions:[]}}function qP(e,t){return e?($e(e,"--dep-remove"),e.map(n=>{let r=n.trim();if(!r)throw new p("--dep-remove requires id or key/value selectors",m.USAGE);let s=Vb(r);if(ws(r,s,"--dep-remove"),s){let i=ee(r,"--dep-remove");be(i,"--dep-remove",UP);let o=i.id?.trim();if(i.id===void 0)return WP(i);if(!o)throw new p("--dep-remove key/value form requires a non-empty id=<value>",m.USAGE);if(o.toLowerCase()==="undefined")throw new p(`--dep-remove id must not use placeholder token "${o}"`,m.USAGE);let a=Bl(kn(i.kind??i.type)),c=Fr(kn(i.source_kind)),d=kn(i.author),l=kn(i.created_at);return{id:Dr(o,t,c),kind:a?or(a):void 0,source_kind:c,author:d,created_at:l?Hb(l):void 0}}if(r.toLowerCase()==="undefined")throw new p(`--dep-remove id must not use placeholder token "${r}"`,m.USAGE);return{id:Ze(r,t)}})):[]}function WP(e){let t=Bl(kn(e.kind??e.type)),n=Object.keys(e).filter(r=>r!=="kind"&&r!=="type");if(!t||n.length>0||e.kind!==void 0&&e.type!==void 0)throw new p("--dep-remove key/value form requires id=<value>, or kind=<kind> alone to remove every row of that kind",m.USAGE);return{kind:or(t)}}function ca(e){let t=e.source_kind?.trim().toLowerCase()??"";return[e.id.trim().toLowerCase(),e.kind,t].join("\0")}function KP(e,t,n,r,s){let i=[...e??[]],o=!1;if(t===void 0){let a=i.filter(c=>s===void 0||!Dl(c,s.value,s.idPrefix));return a.length!==i.length&&(i=a,o=!0),o?{dependencies:i.length>0?i:void 0,changed:!0}:{dependencies:e,changed:!1}}return i.some(a=>a.kind==="blocked_by"&&a.id===t)||(i.push({id:t,kind:"blocked_by",created_at:n,author:r,source_kind:"cli:update:blocked_by",author_source:"detected"}),o=!0),o?{dependencies:i.length>0?i:void 0,changed:!0}:{dependencies:e,changed:!1}}async function zP(e,t,n,r,s,i){if(e===void 0||t)return{};let o=e.trim();if(o.length===0)return{};let a=await Y(n,Ze(o,r),r,s,i);return a?{id:a.id}:{unresolved:o}}function BP(e,t,n,r,s,i){let o=KP(e.dependencies,t,n,r,i);o.changed&&(o.dependencies===void 0?delete e.dependencies:e.dependencies=o.dependencies,s.includes("dependencies")||s.push("dependencies"))}function HP(e){return`${e.path}::${e.scope}`}function VP(e){return`${e.path}::${e.scope}`}function YP(e){return`${e.command}::${e.path??""}::${e.scope}::${e.pm_context_mode??""}::${e.workspace_context_mode??""}`}function Ub(e,t){let n=gr("update",e);if(!n)throw new p(`Unsupported command_option_policies option "${e}" for update command on type "${t}"`,m.CONFLICT);return n}function JP(e,t,n){let r=new Set,s=(i,o)=>{o&&r.add(i)};if(s("title",e.title!==void 0),s("description",e.description!==void 0),s("body",e.body!==void 0),s("status",e.status!==void 0),s("closeReason",e.closeReason!==void 0),s("priority",e.priority!==void 0),s("type",e.type!==void 0),s("tags",e.tags!==void 0||Array.isArray(e.addTags)&&e.addTags.length>0||Array.isArray(e.removeTags)&&e.removeTags.length>0),s("deadline",e.deadline!==void 0),s("estimatedMinutes",e.estimatedMinutes!==void 0),s("acceptanceCriteria",e.acceptanceCriteria!==void 0||Array.isArray(e.addAc)&&e.addAc.length>0||Array.isArray(e.removeAc)&&e.removeAc.length>0),s("definitionOfReady",e.definitionOfReady!==void 0),s("order",e.order!==void 0||e.rank!==void 0),s("goal",e.goal!==void 0),s("objective",e.objective!==void 0),s("value",e.value!==void 0),s("impact",e.impact!==void 0),s("outcome",e.outcome!==void 0),s("whyNow",e.whyNow!==void 0),s("author",e.author!==void 0),s("message",e.message!==void 0),s("assignee",e.assignee!==void 0),s("parent",e.parent!==void 0),s("reviewer",e.reviewer!==void 0),s("risk",e.risk!==void 0),s("confidence",e.confidence!==void 0),s("sprint",e.sprint!==void 0),s("release",e.release!==void 0),s("blockedBy",e.blockedBy!==void 0),s("blockedReason",e.blockedReason!==void 0),s("unblockNote",e.unblockNote!==void 0),s("reporter",e.reporter!==void 0),s("severity",e.severity!==void 0),s("environment",e.environment!==void 0),s("reproSteps",e.reproSteps!==void 0),s("resolution",e.resolution!==void 0),s("expectedResult",e.expectedResult!==void 0),s("actualResult",e.actualResult!==void 0),s("affectedVersion",e.affectedVersion!==void 0),s("fixedVersion",e.fixedVersion!==void 0),s("component",e.component!==void 0),s("regression",e.regression!==void 0),s("customerImpact",e.customerImpact!==void 0),s("dep",e.dep!==void 0),s("depRemove",e.depRemove!==void 0),s("dep",e.replaceDeps===!0),s("comment",e.comment!==void 0),s("note",e.note!==void 0),s("learning",e.learning!==void 0),s("file",e.file!==void 0),s("test",e.test!==void 0),s("test",e.replaceTests===!0),s("file",e.replaceFiles===!0),s("doc",e.replaceDocs===!0),s("doc",e.doc!==void 0),s("reminder",e.reminder!==void 0),s("event",e.event!==void 0),s("typeOption",e.typeOption!==void 0),s("field",e.field!==void 0),s("force",e.force===!0),s("ownershipMetadataBypass",e.ownershipMetadataBypass===!0),s("ownershipDependencyBypass",e.ownershipDependencyBypass===!0),s("dep",e.clearDeps===!0),s("comment",e.clearComments===!0),s("note",e.clearNotes===!0),s("learning",e.clearLearnings===!0),s("file",e.clearFiles===!0),s("test",e.clearTests===!0),s("doc",e.clearDocs===!0),s("reminder",e.clearReminders===!0),s("event",e.clearEvents===!0),s("typeOption",e.clearTypeOptions===!0),e.unset&&e.unset.length>0){let i=zl(e.unset,t,n,e.runtimeFieldCommands);for(let o of i.optionKeys)s(o,!0)}return r}function XP(e,t,n,r,s){let i=Ks(e,n);if(!i)throw new p(`Invalid type value "${e}"`,m.USAGE);let o=In(i,"update",[]);if(o.errors.length>0)throw new p(o.errors.join("; "),m.CONFLICT);let a=JP(t,r,s);for(let c of o.disabled)if(a.has(Ub(c,e)))throw new p(`Option ${Ie("update",c)} is disabled for type "${e}" by command_option_policies`,m.USAGE);for(let c of o.required)if(!a.has(Ub(c,e)))throw new p(`Missing required option ${Ie("update",c)} for type "${e}"`,m.USAGE)}var QP=new Set(["order","rank"]),ZP=Wa.filter(e=>!QP.has(e)),Yb=["tags","closeReason",...ZP],eF=["title","description","body","status","closeReason","completedAt","priority","type",...Wa,"dep","depRemove","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],tF=[{optionKey:"deadline",metadataKey:"deadline",transform:(e,t)=>me(e,t.nowValue,"deadline")},{optionKey:"estimatedMinutes",metadataKey:"estimated_minutes",transform:e=>Gs(e,"estimated-minutes")},{optionKey:"acceptanceCriteria",metadataKey:"acceptance_criteria",transform:e=>e},{optionKey:"definitionOfReady",metadataKey:"definition_of_ready"},{optionKey:"goal",metadataKey:"goal"},{optionKey:"objective",metadataKey:"objective"},{optionKey:"value",metadataKey:"value"},{optionKey:"impact",metadataKey:"impact"},{optionKey:"outcome",metadataKey:"outcome"},{optionKey:"whyNow",metadataKey:"why_now"}],nF=[{optionKey:"reviewer",metadataKey:"reviewer"},{optionKey:"risk",metadataKey:"risk",transform:e=>rt(Ko(e),qs,"risk")},{optionKey:"confidence",metadataKey:"confidence",transform:e=>Bo(e)}],rF=[{optionKey:"blockedReason",metadataKey:"blocked_reason"},{optionKey:"unblockNote",metadataKey:"unblock_note"},{optionKey:"reporter",metadataKey:"reporter"},{optionKey:"severity",metadataKey:"severity",transform:e=>rt(zo(e),Ws,"severity")},{optionKey:"environment",metadataKey:"environment"},{optionKey:"reproSteps",metadataKey:"repro_steps"},{optionKey:"resolution",metadataKey:"resolution"},{optionKey:"expectedResult",metadataKey:"expected_result"},{optionKey:"actualResult",metadataKey:"actual_result"},{optionKey:"affectedVersion",metadataKey:"affected_version"},{optionKey:"fixedVersion",metadataKey:"fixed_version"},{optionKey:"component",metadataKey:"component"},{optionKey:"regression",metadataKey:"regression",transform:e=>Ho(e)},{optionKey:"customerImpact",metadataKey:"customer_impact"}];function Kl(e,t,n){for(let r of e){let s=t[r.optionKey],i=n.clearItemMetadataKeys.has(r.metadataKey);if(!(s===void 0&&!i)){if(i){delete n.metadataRecord[r.metadataKey],n.changedFields.push(r.metadataKey);continue}if(typeof s!="string")throw new p(`${Ie("update",String(r.optionKey))} must be a string value`,m.USAGE);n.metadataRecord[r.metadataKey]=r.transform?r.transform(s,n):s.trim(),n.changedFields.push(r.metadataKey)}}}async function sF(e){return Bb(await Us(e,[["body","--body"],["description","--description"]],[["dep","--dep"],["depRemove","--dep-remove"],["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"],["field","--field"]]))}async function iF(e){let t=Mr("update",e);return Bt(t)?await sF(t):Bb(t)}function oF(e){return[{enabled:e.clearDeps||e.replaceDeps,optionKey:"dep",clearFlag:"--clear-deps",valueFlag:"--dep",values:e.dep,metadataKey:"dependencies"},{enabled:e.clearComments,optionKey:"comment",clearFlag:"--clear-comments",valueFlag:"--comment",values:e.comment,metadataKey:"comments"},{enabled:e.clearNotes,optionKey:"note",clearFlag:"--clear-notes",valueFlag:"--note",values:e.note,metadataKey:"notes"},{enabled:e.clearLearnings,optionKey:"learning",clearFlag:"--clear-learnings",valueFlag:"--learning",values:e.learning,metadataKey:"learnings"},{enabled:e.clearFiles||e.replaceFiles,optionKey:"file",clearFlag:"--clear-files",valueFlag:"--file",values:e.file,metadataKey:"files"},{enabled:e.clearTests||e.replaceTests,optionKey:"test",clearFlag:"--clear-tests",valueFlag:"--test",values:e.test,metadataKey:"tests"},{enabled:e.clearDocs||e.replaceDocs,optionKey:"doc",clearFlag:"--clear-docs",valueFlag:"--doc",values:e.doc,metadataKey:"docs"},{enabled:e.clearReminders,optionKey:"reminder",clearFlag:"--clear-reminders",valueFlag:"--reminder",values:e.reminder,metadataKey:"reminders"},{enabled:e.clearEvents,optionKey:"event",clearFlag:"--clear-events",valueFlag:"--event",values:e.event,metadataKey:"events"},{enabled:e.clearTypeOptions,optionKey:"typeOption",clearFlag:"--clear-type-options",valueFlag:"--type-option",values:e.typeOption,metadataKey:"type_options"}]}function ql(e){if(e.enabled&&(!e.values||e.values.length===0))throw new p(`${e.replaceFlag} requires at least one ${e.valueFlag} entry`,m.USAGE);if(e.enabled&&e.clearEnabled)throw new p(`${e.replaceFlag} cannot be combined with ${e.clearFlag}`,m.USAGE)}function aF(e){let t=(e.addAc?.length??0)>0||(e.removeAc?.length??0)>0;if(e.acceptanceCriteria!==void 0&&t)throw new p("Cannot combine --acceptance-criteria replacement with --add-ac or --remove-ac. Use --remove-ac and --add-ac together for an atomic one-entry repair.",m.USAGE,{code:"acceptance_criteria_mutation_conflict",reason:"replacement_and_additive_mutation_combined",nextSteps:["Use --acceptance-criteria alone to replace the complete list.","Use --remove-ac <old> --add-ac <new> to repair one criterion without replacing unrelated entries."]});if(e.replaceDeps===!0&&(e.dep===void 0||e.dep.length===0))throw new p("--replace-deps requires at least one --dep entry",m.USAGE);if(e.replaceDeps===!0&&e.depRemove!==void 0&&e.depRemove.length>0)throw new p("--replace-deps cannot be combined with --dep-remove",m.USAGE);ql({enabled:e.replaceTests===!0,values:e.test,replaceFlag:"--replace-tests",clearEnabled:e.clearTests===!0,clearFlag:"--clear-tests",valueFlag:"--test"}),ql({enabled:e.replaceFiles===!0,values:e.file,replaceFlag:"--replace-files",clearEnabled:e.clearFiles===!0,clearFlag:"--clear-files",valueFlag:"--file"}),ql({enabled:e.replaceDocs===!0,values:e.doc,replaceFlag:"--replace-docs",clearEnabled:e.clearDocs===!0,clearFlag:"--clear-docs",valueFlag:"--doc"})}function cF(e){for(let t of e.definitions){if(!t.enabled)continue;let n=t.optionKey==="dep"&&e.options.replaceDeps===!0||t.optionKey==="test"&&e.options.replaceTests===!0||t.optionKey==="file"&&e.options.replaceFiles===!0||t.optionKey==="doc"&&e.options.replaceDocs===!0;if(t.values&&t.values.length>0&&!n)throw new p(`Cannot combine ${t.clearFlag} with ${t.valueFlag}`,m.USAGE);e.clearOptionKeys.add(t.optionKey),e.clearItemMetadataKeys.add(t.metadataKey)}}function dF(e){let t={};for(let n of Yb)t[String(n)]=e[n]!==void 0;return t.order=e.order!==void 0||e.rank!==void 0,t}function lF(e,t){let n=dF(e);for(let[r,s]of Object.entries(n)){if(!s||!t.optionKeys.has(r))continue;let i=aa.get(r)??r;throw new p(`Cannot combine --unset ${i} with ${Ie("update",r)}`,m.USAGE)}if(t.metadataKeys.has("acceptance_criteria")){if(Array.isArray(e.addAc)&&e.addAc.length>0)throw new p("Cannot combine --unset acceptance-criteria with --add-ac",m.USAGE);if(Array.isArray(e.removeAc)&&e.removeAc.length>0)throw new p("Cannot combine --unset acceptance-criteria with --remove-ac",m.USAGE)}if(t.metadataKeys.has("tags")){if(Array.isArray(e.addTags)&&e.addTags.length>0)throw new p("Cannot combine --unset tags with --add-tags",m.USAGE);if(Array.isArray(e.removeTags)&&e.removeTags.length>0)throw new p("Cannot combine --unset tags with --remove-tags",m.USAGE)}}function uF(e){if(at(e))return;let t=(n,r)=>{if(at(e,r))return;let s=aa.get(r),i=s?`Use --unset ${s} to clear this field.`:void 0;Ci(n,Ie("update",r),i)};for(let n of Yb)t(e[n],String(n));t(e.order??e.rank,"order"),$e(e.reminder,"--reminder","Use --clear-reminders to clear reminders."),$e(e.event,"--event","Use --clear-events to clear linked events.")}function mF(e,t){let n={};for(let r of eF)n[String(r)]=e[r]!==void 0;return n.tags=e.tags!==void 0,n.addTags=Array.isArray(e.addTags)&&e.addTags.length>0,n.removeTags=Array.isArray(e.removeTags)&&e.removeTags.length>0,n.addAc=Array.isArray(e.addAc)&&e.addAc.length>0,n.removeAc=Array.isArray(e.removeAc)&&e.removeAc.length>0,n.order=e.order!==void 0,n.rank=e.rank!==void 0,n.replaceDeps=e.replaceDeps===!0,n.replaceTests=e.replaceTests===!0,n.replaceFiles=e.replaceFiles===!0,n.replaceDocs=e.replaceDocs===!0,n.unset=e.unset!==void 0&&e.unset.length>0,n.clearDeps=e.clearDeps===!0,n.clearComments=e.clearComments===!0,n.clearNotes=e.clearNotes===!0,n.clearLearnings=e.clearLearnings===!0,n.clearFiles=e.clearFiles===!0,n.clearTests=e.clearTests===!0,n.clearDocs=e.clearDocs===!0,n.clearReminders=e.clearReminders===!0,n.clearEvents=e.clearEvents===!0,n.clearTypeOptions=e.clearTypeOptions===!0,n.documentAnnotationSnapshot=e.documentAnnotationSnapshot!==void 0,n.runtimeFields=Object.keys(t).length>0,n}async function fF(e){let t=await Y(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await Zt(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await fe(t,{schema:e.settings.schema});return{item:n.metadata,changed_fields:[],warnings:["noop_no_update_fields"]}}async function pF(e){if(!(!e.fieldFlags.dep&&!e.fieldFlags.blockedBy&&!e.fieldFlags.parent&&!e.clearedMetadataKeys.has("parent")))return Ae(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}function _F(e){e.before&&(Lo(e.before,e.before.map(t=>t.id===e.document.metadata.id?e.document.metadata:t)),Li(e.before,e.before.map(t=>t.id===e.document.metadata.id?e.document.metadata:t),e.document.metadata.id,t=>_e(t,e.statusRegistry),de()))}function hF(e){if(e.order!==void 0&&e.rank!==void 0&&e.order!==e.rank)throw new p("--order and --rank must match when both are provided",m.USAGE)}async function gF(e){if(e.options.parent===void 0||e.unsetTargets.metadataKeys.has("parent"))return{resolvedParentValue:void 0,warnings:[]};let t=ct(e.options),n=Pn(fi(e.options.parent,t),e.settings.id_prefix);if(bi(n))return{resolvedParentValue:n,warnings:[]};if(_i(e.id,n,e.settings.id_prefix,t),await Y(e.pmRoot,n,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder))return{resolvedParentValue:n,warnings:[]};let s=Ze(n,e.settings.id_prefix);return{resolvedParentValue:n,warnings:pi(s,e.parentReferencePolicy,t).warnings}}function yF(e){return e.unresolved===void 0?[]:[`blocked_by_unresolved:${e.unresolved}`]}async function wF(e){if(e.workflowEnforcement==="off"||e.typeWorkflows.length===0||!e.fieldFlags.status||e.options.status===void 0)return[];let t=await Y(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await Zt(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await fe(t,{schema:e.settings.schema}),r=e.options.type!==void 0?_t(e.options.type,e.typeRegistry)??e.options.type:n.metadata?.type??"",s=ar({enforcement:e.workflowEnforcement,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry,typeName:r,fromStatus:n.metadata?.status??"",toStatus:e.options.status});return s?[s]:[]}async function vF(e){if(!e.fieldFlags.status||ce(e.options.status,e.statusRegistry)!==e.statusRegistry.close_status)return;$b(e);let n=Object.entries(e.fieldFlags).filter(([i,o])=>o&&i!=="status"&&i!=="closeReason"&&i!=="completedAt").map(([i])=>i),r=await Nb(e);if(Ul(r,e.options,e.statusRegistry,e.settings.governance.require_close_reason))return Mb(e,r,n,ks,i=>Gb(e,i));let s;if(n.length>0){let i=dt(e.options,{...e.options,status:void 0,closeReason:void 0,message:void 0});s=await ks(e.id,i,e.global)}return Gb(e,s)}async function Gb(e,t){let n=await Ro(e.id,e.options.closeReason,{author:e.options.author,message:e.options.message,force:e.options.force,completedAt:e.options.completedAt},e.global),s=[...$r("update",e.options,ct(e.options)==="sdk",n.item),...e.workflowTransitionWarnings,...(t?.warnings??[]).filter(i=>!i.startsWith("literal_sentinel_stored:")),...n.warnings,"auto_routed_from_update_to_close"];return{item:n.item,changed_fields:[...t?.changed_fields??[],...n.changed_fields],warnings:s}}function kF(e,t,n,r){return t.title!==void 0&&(e.metadata.title=Fl(t.title,"--title",ct(t)),r.push("title")),t.description!==void 0&&(e.metadata.description=t.description,r.push("description")),t.body!==void 0&&(e.body=t.body,r.push("body")),ce(e.metadata.status,n)??e.metadata.status}var bF=["closed_at","completed_at","close_reason","resolution","expected_result","actual_result","fixed_version"];function xF(e,t){for(let n of bF)e[n]!==void 0&&(delete e[n],t.push(n))}function SF(e,t,n,r,s){let i=FP(n,t.statusRegistry);if(e.metadata.status=i,s.push("status"),i===t.statusRegistry.close_status&&(e.metadata.closed_at===void 0||e.metadata.closed_at===null)){e.metadata.closed_at=t.nowIso,e.metadata.completed_at=t.nowIso,s.push("closed_at","completed_at");return}!_e(i,t.statusRegistry)&&_e(r,t.statusRegistry)&&xF(e.metadata,s)}function EF(e,t,n,r){if(t.options.status!==void 0&&SF(e,t,t.options.status,n,r),t.options.completedAt!==void 0){if(!_e(e.metadata.status,t.statusRegistry))throw new p("--completed-at can only be set on a terminal item",m.USAGE);e.metadata.completed_at=me(t.options.completedAt,new Date(t.nowIso),"completed-at"),r.push("completed_at")}}function AF(e,t,n,r){if(t.options.closeReason!==void 0||t.clearItemMetadataKeys.has("close_reason")){if(t.clearItemMetadataKeys.has("close_reason"))delete e.metadata.close_reason;else{let s=t.options.closeReason?.trim()??"";if(s.length===0)throw new p(ja(ct(t.options),"close-reason"),m.USAGE);e.metadata.close_reason=s}r.push("close_reason");return}t.options.status!==void 0&&_e(n,t.statusRegistry)&&!_e(e.metadata.status,t.statusRegistry)&&e.metadata.close_reason!==void 0&&(delete e.metadata.close_reason,r.push("close_reason"))}function CF(e,t,n,r){EF(e,t,n,r),AF(e,t,n,r)}function TF(e,t,n){let r=_t(e.metadata.type,t.typeRegistry)??e.metadata.type;if(t.options.priority!==void 0&&(e.metadata.priority=hi(t.options.priority),n.push("priority")),t.options.type!==void 0){let s=_t(t.options.type,t.typeRegistry);if(!s)throw new p(yi(t.options.type,t.typeRegistry.types,Zs(t.pmRoot,t.settings.schema)),m.USAGE);e.metadata.type=s,r=s,n.push("type")}return XP(r,t.options,t.typeRegistry,t.runtimeFieldRegistry,t.extensionFieldNames),RF(e,t,r,n),r}function RF(e,t,n,r){if(t.options.typeOption!==void 0||t.clearItemMetadataKeys.has("type_options")){if(t.clearItemMetadataKeys.has("type_options"))delete e.metadata.type_options;else{let i=Zo(t.options.typeOption??[]),o=yr(n,i,t.typeRegistry);if(o.errors.length>0)throw new p(o.errors.join("; "),m.USAGE);e.metadata.type_options=o.normalized}r.push("type_options");return}if(t.options.type===void 0||e.metadata.type_options===void 0)return;let s=yr(n,e.metadata.type_options,t.typeRegistry);if(s.errors.length>0)throw new p(`Current type options are incompatible with type "${n}". ${s.errors.join("; ")}. Use --clear-type-options to clear them.`,m.USAGE);e.metadata.type_options=s.normalized}function IF(e,t){let n=new Set(t.map(s=>ca(s))),r=new Set;return e.filter(s=>{if(!n.has(ca(s)))return!0;let i=oa(s);return r.has(i)?!1:(r.add(i),!0)})}function OF(e,t,n){if(t.options.dep===void 0&&t.options.depRemove===void 0&&!t.clearItemMetadataKeys.has("dependencies"))return;let r=t.clearItemMetadataKeys.has("dependencies")?[]:[...e.metadata.dependencies??[]];if(t.dependencyUpdates.additions.length>0){r=IF(r,t.dependencyUpdates.additions);let s=new Set(r.map(i=>ca(i)));for(let i of t.dependencyUpdates.additions){let o=ca(i);s.has(o)||(r.push(i),s.add(o))}}t.dependencyRemovals.length>0&&(Pb(r,t.dependencyRemovals,e.metadata.id),r=r.filter(s=>!t.dependencyRemovals.some(i=>Gl(s,i)))),r.length===0?delete e.metadata.dependencies:e.metadata.dependencies=r,n.push("dependencies")}function LF(e,t,n){Wl(e,"comments",t.options.comment,t.commentUpdates.values,t.clearItemMetadataKeys,n),Wl(e,"notes",t.options.note,t.noteUpdates.values,t.clearItemMetadataKeys,n),Wl(e,"learnings",t.options.learning,t.learningUpdates.values,t.clearItemMetadataKeys,n)}function Wl(e,t,n,r,s,i){n===void 0&&!s.has(t)||(s.has(t)||!r||r.length===0?delete e.metadata[t]:e.metadata[t]=[...e.metadata[t]??[],...r],i.push(t))}function $F(e,t,n){qb(e,"files",t.options.file,t.fileUpdates.values,HP,t.options.replaceFiles===!0,t.clearItemMetadataKeys,n),NF(e,t,n),qb(e,"docs",t.options.doc,t.docUpdates.values,VP,t.options.replaceDocs===!0,t.clearItemMetadataKeys,n)}function qb(e,t,n,r,s,i,o,a){if(!(n===void 0&&!o.has(t))){if(i)e.metadata[t]=r;else if(o.has(t)||!r||r.length===0)delete e.metadata[t];else{let c=[...e.metadata[t]??[]],d=new Set(c.map(l=>s(l)));for(let l of r){let u=s(l);d.has(u)||(c.push(l),d.add(u))}e.metadata[t]=c}a.push(t)}}function NF(e,t,n){t.options.test===void 0&&!t.clearItemMetadataKeys.has("tests")||(t.clearItemMetadataKeys.has("tests")&&t.options.replaceTests===!0?e.metadata.tests=Wb(t.testUpdates.values)??[]:t.clearItemMetadataKeys.has("tests")||!t.testUpdates.values||t.testUpdates.values.length===0?delete e.metadata.tests:e.metadata.tests=Wb([...e.metadata.tests??[],...t.testUpdates.values]),e.metadata.tests!==void 0&&e.metadata.tests.length===0&&delete e.metadata.tests,n.push("tests"))}function Wb(e){if(!e||e.length===0)return;let t=[],n=new Set;for(let r of e){let s=YP(r);n.has(s)||(t.push(r),n.add(s))}return t}function MF(e,t,n){let r=t.options.addTags,s=t.options.removeTags,i=Array.isArray(r)&&r.length>0||Array.isArray(s)&&s.length>0;if(t.options.tags!==void 0||t.clearItemMetadataKeys.has("tags")||i){let o=t.clearItemMetadataKeys.has("tags")?[]:t.options.tags!==void 0?Fs(t.options.tags):Array.isArray(e.metadata.tags)?[...e.metadata.tags]:[];e.metadata.tags=dm(js(o,r),s),n.changedFields.push("tags")}Kl(tF,t.options,n),FF(e,t,n.changedFields)}function PF(e,t,n){let r=t.options.addAc,s=t.options.removeAc;if(!(Array.isArray(r)&&r.length>0)&&!(Array.isArray(s)&&s.length>0))return;let i=cm(Ds(e.metadata.acceptance_criteria),r,s);if(i.unmatchedRemovals.length>0)throw new p(`Acceptance criteria removal did not match: ${i.unmatchedRemovals.join(", ")}`,m.NOT_FOUND,{code:"acceptance_criteria_remove_unmatched",reason:"exact_match_not_found",field:"acceptance_criteria",unmatched:i.unmatchedRemovals,why:"Lossless removal fails instead of silently applying the remaining mutations when an exact selector is wrong.",nextSteps:["Read the current acceptance_criteria value and retry with the exact criterion text.","Use --acceptance-criteria alone only when replacing the complete list is intentional."]});let o=i.criteria.join("; ");e.metadata.acceptance_criteria!==o&&(o===""&&e.metadata.acceptance_criteria===void 0||(e.metadata.acceptance_criteria=o,n.changedFields.includes("acceptance_criteria")||n.changedFields.push("acceptance_criteria")))}function FF(e,t,n){let r=t.options.order??t.options.rank;if(!(r===void 0&&!t.clearItemMetadataKeys.has("order"))){if(t.clearItemMetadataKeys.has("order"))delete e.metadata.order;else{let s=we(r??"","order");if(!Number.isInteger(s))throw new p("Order must be an integer",m.USAGE);e.metadata.order=s}n.push("order")}}function DF(e,t,n,r){jF(e,t,n.changedFields),UF(e,t,n.changedFields),Kl(nF,t.options,n),Kb(e,t,"sprint",r,n.changedFields),Kb(e,t,"release",r,n.changedFields),GF(e,t,n.changedFields),Kl(rF,t.options,n)}function jF(e,t,n){if(!(t.options.assignee===void 0&&!t.clearItemMetadataKeys.has("assignee"))){if(t.clearItemMetadataKeys.has("assignee"))delete e.metadata.assignee;else{let r=t.options.assignee?.trim()??"";if(r==="")throw new p(ja(ct(t.options),"assignee",". Use --unset assignee to clear it."),m.USAGE);Im(r,"--assignee"),e.metadata.assignee=r}n.push("assignee")}}function UF(e,t,n){t.options.parent===void 0&&!t.clearItemMetadataKeys.has("parent")||(t.clearItemMetadataKeys.has("parent")?delete e.metadata.parent:e.metadata.parent=t.resolvedParentValue??"",n.push("parent"))}function Kb(e,t,n,r,s){if(!(t.options[n]===void 0&&!t.clearItemMetadataKeys.has(n))){if(t.clearItemMetadataKeys.has(n))delete e.metadata[n];else{let i=gi(n,t.options[n]??"",t.settings.validation.sprint_release_format,ct(t.options));e.metadata[n]=i.value,r.push(...i.warnings)}s.push(n)}}function GF(e,t,n){if(t.options.blockedBy===void 0&&!t.clearItemMetadataKeys.has("blocked_by"))return;let r=t.clearItemMetadataKeys.has("blocked_by")?e.metadata.blocked_by:void 0;t.clearItemMetadataKeys.has("blocked_by")?delete e.metadata.blocked_by:e.metadata.blocked_by=t.options.blockedBy?.trim()??"",n.push("blocked_by"),(t.clearItemMetadataKeys.has("blocked_by")||t.resolvedBlockedByDependencyId!==void 0)&&BP(e.metadata,t.resolvedBlockedByDependencyId,t.nowIso,t.author,n,{value:r,idPrefix:t.settings.id_prefix})}function qF(e,t,n){(t.options.reminder!==void 0||t.clearItemMetadataKeys.has("reminders"))&&(t.clearItemMetadataKeys.has("reminders")?delete e.metadata.reminders:e.metadata.reminders=Xo(t.options.reminder??[],t.nowValue,{valueMode:"trimmed"}),n.push("reminders")),(t.options.event!==void 0||t.clearItemMetadataKeys.has("events"))&&(t.clearItemMetadataKeys.has("events")?delete e.metadata.events:e.metadata.events=Qo(t.options.event??[],t.nowValue,{allDayEmptyGuard:"truthy",recurrenceEmptyNumericGuard:"truthy"}),n.push("events"))}function WF(e,t,n){zb(e,t.runtimeFieldRegistry.definitions.map(s=>s.metadata_key),t.clearItemMetadataKeys,n),zb(e,t.extensionFieldNames,t.clearItemMetadataKeys,n);for(let[s,i]of Object.entries(t.runtimeFieldUpdates)){if(t.clearItemMetadataKeys.has(s)){let o=s.replaceAll("_","-"),c=t.runtimeFieldRegistry.definitions.find(d=>d.metadata_key===s)?.cli_flag??o;throw new p(`Cannot combine --unset ${o} with --${c}`,m.USAGE)}Ue(e[s],i)||(e[s]=i,n.push(s))}let r=li(t.options.field,t.extensionRegistrations,Vo,Yo(t.runtimeFieldRegistry,(t.options.runtimeFieldCommands??[]).includes("update_many")?"update_many":"update",t.options));for(let s of Object.keys(r))if(t.clearItemMetadataKeys.has(s))throw new p(`Cannot combine --unset ${s.replaceAll("_","-")} with --field ${s}=...`,m.USAGE);for(let[s,i]of Object.entries(r))Ue(e[s],i)||(e[s]=i,n.push(s))}function zb(e,t,n,r){for(let s of t)!n.has(s)||e[s]===void 0||(delete e[s],r.push(s))}function KF(e,t){if(t===void 0)return;let n=e.metadata,r=["comments","notes","learnings"].find(s=>{let i=t[s];return i!==void 0&&(!Array.isArray(i)||!Ue(i,n[s]??[]))});if(r!==void 0)throw new p(`Full-item --stdin-json update changed persisted ${r}; no item fields were written.`,m.USAGE,{code:"stdin_json_persisted_annotation_changed",reason:`${r}_requires_annotation_command`,required:`Use pm ${r} ${e.metadata.id} --edit <index> --add <text> to correct an existing entry.`,why:"Full-item update appends new annotations but cannot replace or remove existing audit entries.",nextSteps:[`Inspect the current ${r} with pm ${r} ${e.metadata.id}.`,`Apply the correction with pm ${r} ${e.metadata.id} --edit <index> --add <text>.`]})}function zF(e,t){KF(e,t.options.documentAnnotationSnapshot);let n=structuredClone(e.metadata),r=e.body,s=[],i=[],o=kF(e,t.options,t.statusRegistry,s),a=e.metadata,c={metadataRecord:a,clearItemMetadataKeys:t.clearItemMetadataKeys,changedFields:s,nowValue:t.nowValue};CF(e,t,o,s),TF(e,t,s),OF(e,t,s),LF(e,t,s),$F(e,t,s),MF(e,t,c),PF(e,t,c),DF(e,t,c,i),(t.options.dep!==void 0||t.options.depRemove!==void 0||t.options.blockedBy!==void 0||t.clearItemMetadataKeys.has("dependencies")||t.clearItemMetadataKeys.has("blocked_by"))&&vs(e.metadata.id,e.metadata.dependencies),ce(e.metadata.status,t.statusRegistry)===t.statusRegistry.canceled_status&&e.metadata.assignee!==void 0&&(delete e.metadata.assignee,s.includes("assignee")||s.push("assignee")),qF(e,t,s),WF(a,t,s);try{ui(a,t.extensionRegistrations,{skipDefaultFields:t.clearItemMetadataKeys})}catch(f){throw new p(f instanceof Error?f.message:"Invalid extension item field values",m.USAGE)}let d=e.metadata,l=[...new Set(s)].filter(f=>f==="body"?e.body!==r:!Ue(n[f],d[f])),u=Fb(n.dependencies,d.dependencies);return u!==void 0&&i.push(`dependencies_removed:${e.metadata.id}:${u}`),t.options.acceptanceCriteria!==void 0&&l.includes("acceptance_criteria")&&i.push(`acceptance_criteria_replaced:${Ds(n.acceptance_criteria).length}:${Ds(d.acceptance_criteria).length}`),{changedFields:l,warnings:i}}async function Jb(e,t,n,r={}){Nr(e,"update","id");let s=await iF(t),i=I(process.cwd(),n.path);await j(i);let o=await C(i),a=z(o.schema),c=Yt(o.schema),d=F(),l=Ot(d),u=D(o,d),f=o.governance.workflow_enforcement??"off",_=f==="off"?[]:Mn(o.schema),h=[{strict_error:"strict_error",warn:"warn",off:"off"},{strict_error:"warn",warn:"warn",off:"off"}][+(s.allowMissingParent===!0)][o.validation.parent_reference],g=zl(s.unset,c,l,s.runtimeFieldCommands),y=new Set(g.optionKeys),w=new Set(g.metadataKeys);aF(s),cF({definitions:oF(s),options:s,clearOptionKeys:y,clearItemMetadataKeys:w}),PP(e,s,w),lF(s,g),uF(s);let v=G(s.author,o.author_default),S=new Date,b=S.toISOString(),k=GP(s.dep,o.id_prefix,b,v);vs(e,k.additions);let A=await Jo({pmRoot:i,dependencies:k.additions,idPrefix:o.id_prefix,itemFormat:o.item_format,typeToFolder:u.type_to_folder,allowUnresolved:s.allowUnresolvedDeps,holders:[{id:e}],schema:o.schema}),x=qP(s.depRemove,o.id_prefix),E=wn("--comment",s.comment,b,v),$=s.ownershipMetadataBypass===!0&&E.values?{...E,values:E.values.map(Ee=>({...Ee,author:v}))}:E,P=wn("--note",s.note,b,v),R=wn("--learning",s.learning,b,v),T=Nl(s.file),q=Ml(s.test);q.values=await tr(q.values,v,b);let Pe=Pl(s.doc),ke=[],oe=await gF({id:e,options:s,unsetTargets:g,pmRoot:i,settings:o,typeRegistry:u,parentReferencePolicy:h}),ze=await zP(s.blockedBy,w.has("blocked_by"),i,o.id_prefix,o.item_format,u.type_to_folder),Fe=ze.id,ye=[...oe.warnings,...yF(ze)],Se=Km(s,c,s.runtimeFieldCommands),re=mF(s,Se);if(!Object.values(re).some(Boolean))return fF({pmRoot:i,id:e,settings:o,typeRegistry:u});ke.push(...await wF({options:s,fieldFlags:re,workflowEnforcement:f,typeWorkflows:_,statusRegistry:a,typeRegistry:u,pmRoot:i,id:e,settings:o}));let pt=await vF({options:s,fieldFlags:re,statusRegistry:a,workflowTransitionWarnings:ke,global:n,id:e,pmRoot:i,settings:o,typeRegistry:u});if(pt)return pt;hF(s);let st=de(),ue=re.parent&&!w.has("parent")||k.additions.some(Ee=>Oo(Ee.kind,st)),De=await Wo({pmRoot:i,author:v,ttlSeconds:o.locks.ttl_seconds,waitMs:o.locks.wait_ms,required:ue});try{let Ee=await pF({fieldFlags:re,clearedMetadataKeys:w,pmRoot:i,settings:o,typeToFolder:u.type_to_folder}),N,Tt,je=await Lt({pmRoot:i,settings:o,typeToFolder:u.type_to_folder,id:e,op:BF(s,r),author:v,message:s.message,resolveHistoryContext:()=>Tt,force:s.force,bypassAssigneeConflict:s.ownershipMetadataBypass===!0||s.ownershipDependencyBypass===!0,extensionFieldNames:l,skipNoop:!0,async mutate(Re){let ae=Re.metadata.status;N=HF({document:Re,recurrenceReason:r.recurrenceReason,requestedStatus:s.status,statusRegistry:a}),Tt=N?{recurrence:N}:void 0,Ee=Ee?.map($s=>$s.id===Re.metadata.id?structuredClone(Re.metadata):$s);let Ls=zF(Re,{options:s,settings:o,typeRegistry:u,statusRegistry:a,runtimeFieldRegistry:c,extensionRegistrations:d,extensionFieldNames:l,clearItemMetadataKeys:w,dependencyUpdates:k,dependencyRemovals:x,commentUpdates:$,noteUpdates:P,learningUpdates:R,fileUpdates:T,testUpdates:q,docUpdates:Pe,resolvedParentValue:oe.resolvedParentValue,resolvedBlockedByDependencyId:Fe,runtimeFieldUpdates:Se,nowValue:S,nowIso:b,author:v,pmRoot:i});_F({before:Ee,document:Re,statusRegistry:a});let Ia=await ia({pmRoot:i,settings:o,metadata:Re.metadata,fromStatus:ae,registry:a,force:s.force===!0});return{...Ls,warnings:[...Ls.warnings,...Ia]}}});await De();let _r=Ee?Io(Ee,Ee.map(Re=>Re.id===je.item.id?je.item:Re),je.item.id):[];return{item:je.item,changed_fields:je.changedFields,warnings:[...$r("update",s,ct(s)==="sdk",je.item),...ke,...ye,...A,..._r,...je.warnings],...N===void 0?{}:{lifecycle_transition:N}}}finally{await De()}}function BF(e,t){return e.ownershipMetadataBypass===!0||e.ownershipDependencyBypass===!0?"update_ownership_bypass":t.recurrenceReason===void 0?"update":"reopen"}function HF(e){if(e.recurrenceReason===void 0)return;let t=ce(e.document.metadata.status,e.statusRegistry)??e.document.metadata.status;if(!_e(t,e.statusRegistry))throw new p(`Item ${e.document.metadata.id} is already active with status ${t}; recurrence transitions require a terminal item.`,m.CONFLICT,{code:"item_already_active",reason:"recurrence_requires_terminal_item",required:"Use item reopen only for a terminal item whose work has recurred.",why:"Appending a recurrence event to active work would corrupt lifecycle history.",recovery:{suggested_retry:`pm get ${e.document.metadata.id} --full`,suggested_retry_args:["get",e.document.metadata.id,"--full"]},nextSteps:[`Inspect the active item with: pm get ${e.document.metadata.id} --full`,`Continue the existing work with: pm update ${e.document.metadata.id} ...`]});let n=e.requestedStatus??e.statusRegistry.open_status,r=ce(n,e.statusRegistry)??n,s=e.document.metadata,i=Object.fromEntries(["close_reason","resolution","expected_result","actual_result","fixed_version"].flatMap(o=>{let a=s[o];return typeof a=="string"?[[o,a]]:[]}));return{reason:e.recurrenceReason,from_status:t,to_status:r,previous_terminal:i}}async function ks(e,t,n){return Jb(e,t,n)}async function m3(e,t,n,r){Nr(r,"reopen","reason");let s=await Jb(e,t,n,{recurrenceReason:r});if(s.lifecycle_transition===void 0)throw new p(`Item ${e} did not produce the required recurrence receipt.`,m.GENERIC_FAILURE,{code:"reopen_receipt_missing",reason:"recurrence_transition_not_recorded",required:"A successful reopen must return the terminal-to-active lifecycle transition recorded in immutable history."});return{...s,lifecycle_transition:s.lifecycle_transition}}function da(e,t){if(e.handoff===void 0)return;if(e.pause===!0)throw new p("--handoff cannot be combined with --pause. Choose a handoff queue or pause the item.",m.USAGE);let n=typeof e.handoff=="string"?Qe(e.handoff,t):void 0;if(n===void 0||It(n,t)||n===t.in_progress_status)throw new p("--handoff must name a configured non-terminal status distinct from the in-progress status. Inspect pm schema statuses or add a project queue with pm schema add-status <queue> --role active.",m.USAGE);if(typeof e.message!="string"||e.message.trim().length===0)throw new p("--handoff requires --message with implementation evidence and the next verification step.",m.USAGE);return n}function Xb(e,t,n,r,s){if(It(e.status,r)||!e.assignee?.trim())throw new p("Handoff requires a claimed, non-terminal item. Claim the active work before handing it off; use pm item reopen for completed work.",m.CONFLICT);let i=n.governance.workflow_enforcement??"off",o=ar({enforcement:i,typeWorkflows:i==="off"?[]:Mn(n.schema),statusRegistry:r,typeName:e.type,fromStatus:e.status,toStatus:t}),a={from_status:e.status,to_status:t,message:s},c=e.status===t?[]:["status"];return e.status=t,{receipt:a,warnings:o?[o]:[],changedFields:c}}var Qb="no_available_next_item",N3="stale_claim_takeover_refused";function Zb(e){if(!(e instanceof Error)||e.name!=="PmCliError")return;let t=e.context;if(typeof t!="object"||t===null)return;let n=t.code;return typeof n=="string"?n:void 0}function ex(e,t){return Zb(e)===t}function VF(e){return ex(e,"already_claimed_by")}async function Vl(e,t,n,r={}){let s=I(process.cwd(),n.path);await j(s);let i=await C(s),o=z(i.schema),a=G(r.author,i.author_default),c=nc(a),d=r.takeoverStale===!0;JF(d,t);let l=null,u=!1,f={},_,h=[],g=await Lt({pmRoot:s,settings:i,id:e,op:"claim",author:a,message:r.message,force:t,skipNoop:!0,resolveHistoryContext:()=>_===void 0?void 0:{stale_claim_takeover:_},async mutate(w,v){let b=w.metadata.assignee??"",k=w.metadata.claim_principal?.trim()||b;if(l=b.trim().length>0?b:null,It(w.metadata.status,o)&&!t)throw new p(`Cannot claim terminal item ${w.metadata.id} without --force`,m.CONFLICT);if(l!==null&&k!==c){let q=await YF({pmRoot:s,storageId:v.storageId,metadata:w.metadata,holder:b,author:a,thresholdHours:i.mutation_guard.stale_in_progress_hours,force:t,ifAvailable:r.ifAvailable===!0,takeoverStale:d});if(q.kind==="skip")return u=!0,h.push(`claim_skipped_held_by:${Va(b)}`),{changedFields:[]};_=q.takeover,h.push(q.warning)}let x={assignee:a,claim_principal:c},E=["assignee","claim_principal"].filter(q=>w.metadata[q]!==x[q]);Object.assign(w.metadata,x);let $=w.metadata.status,{changedFields:P,warnings:R,...T}=sD(w.metadata,r.start===!0,i,o);return R.push(...await rD({pmRoot:s,settings:i,metadata:w.metadata,fromStatus:$,registry:o,force:t,start:r.start===!0})),f=T,h.push(...R),{changedFields:[...E,...P],warnings:h}}}),y=tx(await nx("claim",g.item.id,n,u,()=>Gh({pmRoot:s,settings:i,principal:c,itemId:g.item.id})));return h.push(...y.warnings),{item:Ha(g.item),changed_fields:g.changedFields,claimed_by:u&&l!==null?Bs(l):a,previous_assignee:l===null?null:Bs(l),forced:t,...u?{skipped:!0}:{},...h.length>0?{warnings:h}:{},...Hl("suggestions",y.suggestions),...f,..._===void 0?{}:{takeover:_}}}async function YF(e){if(e.ifAvailable&&!e.takeoverStale)return{kind:"skip"};if(e.force)return{kind:"take",warning:`claim_takeover:${Va(e.holder)}->${e.author}`};let t=await Wh(e.pmRoot,e.storageId,e.holder,{updated_at:e.metadata.updated_at,threshold_hours:e.thresholdHours}),n=e.takeoverStale?XF(t,e.author):void 0;if(n!==void 0)return{kind:"take",warning:`claim_stale_takeover:${n.previous_holder}->${e.author}:idle_hours=${n.idle_hours}`,takeover:n};if(e.takeoverStale&&e.ifAvailable)return{kind:"skip"};throw eD(e.metadata.id,t,e.takeoverStale)}function JF(e,t){if(!(!e||!t))throw new p("--takeover-stale cannot be combined with --force",m.USAGE,{code:"ambiguous_option_combination",required:"Pass --takeover-stale to take over only an idle claim, or --force for a coordinated unconditional takeover.",nextSteps:["Drop --force to let the stale-work policy decide, or drop --takeover-stale for a coordinated override."]})}function XF(e,t){let n=e.activity;if(n.stale_policy.stale)return{previous_holder:e.holder,new_holder:t,claimed_at:e.since,last_activity_at:n.last_activity_at,idle_hours:n.idle_hours,threshold_hours:n.stale_policy.threshold_hours,policy:n.stale_policy.setting}}var QF={claim_record_unavailable:"no original history record shows when the holder took it",discarded_history_tail:"a history salvage after the claim discarded a record whose time is unknown",rewritten_history:"a history repair, redaction or merge reconcile after the claim rewrote its records",workspace_restored:"a workspace snapshot restore at or after the claim may have replaced the holder's work"};function ZF(e,t){return t.history_unreadable===!0?{reason:"its history stream could not be read, so idleness cannot be established",nextStep:`Repair the history stream of ${e} (pm history ${e} --verify), then retry --takeover-stale.`}:t.unproven_activity!==void 0?{reason:`${QF[t.unproven_activity]}, so idleness cannot be proven`,nextStep:`Ask the holder to release ${e} (pm release ${e}); a new claim starts a provable record.`}:t.stale_policy.eligible_at===null?{reason:t.idle_hours===null?"no valid activity time is recorded":`idle ${t.idle_hours}h of ${t.stale_policy.threshold_hours}h`,nextStep:`No eligibility time can be computed for ${e}; inspect pm history ${e}.`}:{reason:`idle ${t.idle_hours}h of ${t.stale_policy.threshold_hours}h`,nextStep:`Retry with --takeover-stale after ${t.stale_policy.eligible_at} if nothing else is recorded on ${e}.`}}function eD(e,t,n){let r=t.activity,s=r.stale_policy,i={item_id:e,claimed_by:t.holder,claimed_at:t.since,claim_source:t.source,claim_activity:r},o="Claim is an atomic test-and-set so parallel agents never proceed believing they own the same item.",a="Re-run with --force only when taking over the item is coordinated.";if(n){let c=ZF(e,r);return new p(`Item ${e} is ${t.phrase}, and its claim is not stale under ${s.setting} (${c.reason}).`,m.CONFLICT,{code:"stale_claim_takeover_refused",...i,required:`The claim must be idle for at least ${s.threshold_hours}h (${s.setting}) before --takeover-stale may take it.`,why:`${o} A stale takeover needs recorded evidence that the claim has been idle for the configured threshold, so an active claim is never taken over.`,nextSteps:[c.nextStep,"Run pm next to pick a different unclaimed item.",a]})}return new p(`Item ${e} is already ${t.phrase}. Use --force to take over, or --if-available to skip without failing.`,m.CONFLICT,{code:"already_claimed_by",...i,why:o,nextSteps:["Run pm next to pick a different unclaimed item.","Re-run with --if-available to treat a held item as a no-op skip.",...s.stale?[`Re-run with --takeover-stale: the claim has been idle ${r.idle_hours}h, past ${s.setting}=${s.threshold_hours}.`]:[],a]})}var tD="claim_semantic_attribution_unrecorded";function tx(e){return e?{warnings:[e.warning],suggestions:[e.suggestion]}:{warnings:[],suggestions:[]}}function Hl(e,t){return t.length>0?{[e]:t}:{}}var nD="release_semantic_attribution_unrecorded";async function nx(e,t,n,r,s){if(!r)try{await s();return}catch(i){let o=Zb(i)??"unexpected_error",a=Le(n);return{warning:e==="claim"?tD:nD,suggestion:`The ${e} of ${t} is saved, but the session attribution that names this agent's active work was not updated (${o}); nothing needs a retry. If ${L([...a,"health"])} reports a stale lock, remove it with ${L([...a,"gc","--scope","locks"])}.`}}}function M3(e,t,n=!1){let r=n?" --start":"";if(!t&&!e)throw new p(n?"pm claim --start needs an item id, or --next to start the next available item":"Specify an item id or pass --next",m.USAGE,{code:"missing_required_argument",field:"id",required:"Pass an item id, or --next to select the next available item.",nextSteps:[`Retry as pm claim <id>${r}, or pm claim --next${r}.`]});if(t&&e)throw new p("Specify either an item id or --next, not both",m.USAGE,{code:"ambiguous_option_combination",required:"Pass either an item id or --next.",nextSteps:[`Retry as pm claim ${e}${r} to claim that item, or drop the id to select with --next.`]})}async function rD(e){return e.start?ia(e):Ib(e)}function sD(e,t,n,r){if(!t)return{changedFields:[],warnings:[]};if(It(e.status,r))throw new p(`Cannot start terminal item ${e.id}; reopen it with pm item reopen before starting it`,m.CONFLICT,{code:"terminal_state_conflict",item_id:e.id,why:"Starting work moves an active item into progress; a terminal item must be reopened so its recurrence evidence is recorded.",nextSteps:[`Run pm item reopen ${e.id} "<reason>", then pm claim ${e.id} --start.`]});let s=vn(r),i=n.governance.workflow_enforcement??"off",o=ar({enforcement:i,typeWorkflows:i==="off"?[]:Mn(n.schema),statusRegistry:r,typeName:e.type,fromStatus:e.status,toStatus:s}),a={from_status:e.status,to_status:s},c=e.status===s?[]:["status"];return e.status=s,{start:a,changedFields:c,warnings:o?[o]:[]}}async function P3(e,t,n={},r={}){if(n.takeoverStale===!0)throw new p("--takeover-stale cannot be combined with --next",m.USAGE,{code:"ambiguous_option_combination",required:"Pass an explicit item id with --takeover-stale; --next only selects work no other author holds.",nextSteps:["Retry as pm claim <id> --takeover-stale for the held item, or drop --takeover-stale to select with --next."]});let s=iD(n.maxAttempts),i=await C(I(process.cwd(),t.path)),o={...n,author:G(n.author,i.author_default)},a=await Kh({...r,callerAuthor:o.author,limit:String(s)},t),c=[a.recommended,...a.ready].filter(d=>d!==null).map(d=>({...d,reasons:"reasons"in d?d.reasons:["ranked ready candidate"]}));return oD(c.slice(0,s),e,t,o)}function iD(e){if(e===void 0)return 10;let t=Number(e);if(!Number.isSafeInteger(t)||t<1||t>100)throw new p("--max-attempts must be an integer from 1 to 100",m.USAGE);return t}async function oD(e,t,n,r={},s=Vl){let i=0,o=[],a=()=>o.length>0?{start_refused:[...o]}:{};for(let c of e){i+=1;try{let d=await s(c.id,t,n,r),l={...d,recommendation:c,attempts:i,available:!0,...a()};if(!d.skipped)return l}catch(d){if(ex(d,sa)){o.push(c.id);continue}if(!VF(d))throw d}}if(r.ifAvailable===!0)return{available:!1,item:null,claimed_by:G(r.author,""),previous_assignee:null,forced:t,skipped:!0,recommendation:null,attempts:i,...a(),warnings:[Qb]};throw aD(i,o,r.start===!0)}function aD(e,t,n){let r=e===0,s="Every ranked candidate was claimed by another agent before this atomic selection completed.";return r?s="No ready items matched the specified filters or selection criteria.":t.length>0&&(s=`${t.length} of ${e} attempted candidates refused their start because a declared blocker is open (${t.join(", ")}), and nothing was written to them; ${t.length===e?"no other candidate was attempted":"every other attempted candidate was claimed by another agent"}.`),new p(r?"No actionable items matched the selection filters":"No actionable item remained available to claim",r?m.NOT_FOUND:m.CONFLICT,{code:Qb,why:s,nextSteps:[r?"Verify the filters or run pm next to inspect all ready work.":`Run pm claim --next${n?" --start":""} again, with the same filters, to refresh the ranked candidate set.`],...t.length>0?{details:{start_refused:[...t]}}:{}})}async function la(e,t,n,r={}){let s=I(process.cwd(),n.path);await j(s);let i=await C(s),o=G(r.author,i.author_default),a=nc(o),c=r.ownershipReleaseBypass===!0,d=null,l=z(i.schema),u=da(r,l);if(u!==void 0&&c)throw new p("Ownership-release bypass only clears ownership; it cannot change a handoff status.",m.USAGE);let f,_;try{_=await he({pmRoot:s,settings:i,id:e,op:"release",author:o,message:r.message,force:t,bypassAssigneeConflict:c,mutate(y){d=y.metadata.assignee??null;let w=u===void 0?void 0:Xb(y.metadata,u,i,l,r.message);return f=w?.receipt,!d&&!y.metadata.claim_principal?{changedFields:[]}:(delete y.metadata.assignee,delete y.metadata.claim_principal,{changedFields:["assignee","claim_principal",...w?.changedFields??[]],warnings:w?.warnings})}})}catch(y){qr(y,{required:"For approved non-owner handoffs, prefer the ownership-release bypass before considering --force.",examples:['pm release pm-a1b2 --author "reviewer" --force'],nextSteps:["Use the package-provided ownership-release bypass for handoffs that only clear assignee metadata.","Use --force only when an explicit override is approved for broader ownership conflicts."]})}let h=tx(await nx("release",_.item.id,n,!1,()=>qh({pmRoot:s,principal:a,itemId:_.item.id}))),g=cD(_.item,l);return{item:Ha(_.item),released_by:o,changed_fields:_.changedFields,previous_assignee:d===null?null:Bs(d),forced:t,...f===void 0?{}:{handoff:f},...Hl("warnings",[..._.warnings,...g.warnings,...h.warnings]),...Hl("suggestions",[...g.suggestions,...h.suggestions])}}function cD(e,t){return Jt(e.status,t)===Jt(t.in_progress_status,t)?{warnings:["released_unclaimed_in_progress"],suggestions:[`${e.id} remains ${e.status} and unclaimed. If work is paused, run pm release ${e.id} --pause to move it to ${t.open_status}.`]}:{warnings:[],suggestions:[]}}async function Yl(e,t,n){try{return await n()}catch(r){let s=r instanceof p?r.context:{},i=new p(r instanceof Error?r.message:String(r),r instanceof p?r.exitCode:m.GENERIC_FAILURE,{...s,item_id:e,why:`${t} completed for ${e} before the following step failed. No rollback was performed.${s.why?` ${s.why}`:""}`,nextSteps:[`Inspect the persisted state with pm get ${e} and pm history ${e} before retrying the failed step.`,...s.nextSteps??[]]});throw i.cause=r,i}}async function X3(e,t,n){if(t.next===!0||t.ifAvailable===!0)throw new p("--start cannot be combined with --next or --if-available for an explicit item",m.USAGE,{code:"invalid_argument_value",required:"Remove --next and --if-available when starting an explicit item.",nextSteps:["Remove --next and --if-available, keep the explicit item ID and other supplied arguments, then retry."]});let r=await C(I(process.cwd(),n.path)),s=vn(z(r.schema));return Rb(async()=>{let i=await Vl(e,t.force===!0,n,Ii(t,{},["start"])),o=i.item.id,a=await Yl(o,"claim",()=>ks(o,Ii(t,{status:s},["assignee","start","next","ifAvailable","maxAttempts","takeoverStale"]),n)).catch(async c=>{throw await dD(c,i,n,t.author)});return{id:o,action:"start_task",claim:i,update:a}})}async function dD(e,t,n,r){if(!(e instanceof p)||e.code!==sa||t.previous_assignee!==null)return e;let s=String(t.item.id);try{await vf({pmRoot:I(process.cwd(),n.path),id:s,validate:o=>{if(o.metadata.assignee!==t.claimed_by||o.metadata.claim_principal!==t.item.claim_principal)throw new p("The claim this start took is no longer its own.",m.CONFLICT)}},()=>la(s,!1,n,{author:r,message:"Release the claim: a blocker opened before its start could be recorded"}))}catch{return e}let i=e.cause instanceof p?e.cause:e;return new p(i.message,i.exitCode,{...i.context,why:`${i.context.why??""} A blocker opened after this start's claim, so the claim was released and no ownership remains.`.trim()})}async function Q3(e,t,n){let r=await C(I(process.cwd(),n.path)),s=z(r.schema);da({...t,pause:!0},s);let i=s.open_status,o=await ks(e,Ii(t,{status:i},["assignee","pause"]),n),a=o.item.id,c=await Yl(a,"update",()=>la(a,t.force===!0,n,t));return{id:a,action:"pause_task",update:o,release:c}}async function Z3(e,t,n,r){let s=await Ro(e,t,n,r),i=s.item.id,o=await Yl(i,"close",()=>la(i,n.force===!0,r,n));return{id:i,action:"close_task",close:s,release:o}}import bs from"node:crypto";import{cp as rx,lstat as lD,mkdir as bn,readFile as dr,readdir as Xl,rename as ox,rm as Zl,writeFile as ua}from"node:fs/promises";import W from"node:path";var ax="https://schema.unbrained.dev/pm/workspace-snapshot/v1",_5=["create","list","inspect","restore","delete"],cx=W.join("runtime","workspace-snapshots"),uD=new Set(["checkpoints","locks","runtime","search","transactions"]),mD=/^[a-z0-9][a-z0-9._-]*$/,cr="sdk-workspace-transaction",Jl={capacity:{code:"workspace_snapshot_storage_exhausted"},permission:{code:"workspace_snapshot_permission_denied"},resource:{code:"workspace_snapshot_resource_exhausted"}},dx={renameEntry:ox,removeEntry:async e=>{await Zl(e,{recursive:!0,force:!0})}},Ql=class{lockPath;owner;intervalMs;timer;refresh;failure;constructor(t,n,r){this.lockPath=t,this.owner=n,this.intervalMs=Math.max(10,Math.floor(r*1e3/3))}start(){this.scheduleRenewal(),this.timer=setInterval(()=>{this.scheduleRenewal()},this.intervalMs),this.timer.unref()}async refreshNow(){this.scheduleRenewal(),await this.refresh,this.assertHealthy()}assertHealthy(){if(this.failure!==void 0)throw new Error("Workspace snapshot restore lost its writer lock",{cause:this.failure})}async stop(){this.timer!==void 0&&clearInterval(this.timer),await this.refresh,this.assertHealthy()}scheduleRenewal(){this.refresh!==void 0||this.failure!==void 0||(this.refresh=this.renew().catch(t=>{this.failure=t}).finally(()=>{this.refresh=void 0}))}async renew(){let t=await tf(this.lockPath,cr);if(t===null)throw new Error("Workspace writer lock cleanup gate stayed held");try{let n=JSON.parse(await dr(this.lockPath,"utf8"));if(typeof n!="object"||n===null||Array.isArray(n))throw new Error("Workspace writer lock has invalid structure");let r=n;if(r.id!==cr||r.owner!==this.owner||r.pid!==process.pid)throw new Error("Workspace writer lock ownership changed");await Ge(this.lockPath,`${JSON.stringify({...r,created_at:new Date().toISOString()},null,2)}
|
|
12
|
+
`)}finally{await t()}}};async function lx(e,t=""){let n=await Xl(W.join(e,t),{withFileTypes:!0}),r=[];for(let s of n.sort((i,o)=>i.name.localeCompare(o.name))){if(t.length===0&&uD.has(s.name))continue;let i=W.posix.join(t.replaceAll(W.sep,"/"),s.name);if(s.isSymbolicLink())throw new Error(`Workspace snapshots reject symbolic links: ${i}`);if(s.isDirectory())r.push(...await lx(e,i));else if(s.isFile())r.push(i);else throw new Error(`Workspace snapshots reject unsupported filesystem entries: ${i}`)}return r}async function ux(e){let t=await lx(e),n=bs.createHash("sha256"),r=[],s=0;for(let o of t){let a=await dr(W.join(e,o));r.push(a),s+=a.byteLength,n.update(o),n.update("\0"),n.update(String(a.byteLength)),n.update("\0"),n.update(a)}let i=n.digest("hex");return{manifest:{schema:ax,fingerprint:i,files:t,bytes:s},contents:r}}function sx(e){return e===void 0||e.byteLength===0?0:e.toString("utf8").split(`
|
|
13
|
+
`).filter(t=>t.trim().length>0).length}async function fD(e,t){let n=new Map;for(let r=0;r<t.length;r+=32){let s=t.slice(r,r+32),i=await Promise.all(s.map(async o=>[o,await dr(W.join(e,o))]));for(let[o,a]of i)n.set(o,a)}return n}function eu(e){if(!mD.test(e))throw new p("Snapshot names and fingerprints must use lowercase letters, digits, dots, underscores, or hyphens",m.USAGE,{code:"invalid_workspace_snapshot_target",required:"Provide a non-empty lowercase snapshot name or 64-character hexadecimal fingerprint.",why:"Snapshot targets are used as portable reference filenames and content identities.",examples:["pm workspace snapshot list --json","pm workspace snapshot inspect baseline --json"],nextSteps:["List available snapshots, then retry with a returned name or fingerprint."],recovery:{suggested_retry:"pm workspace snapshot list --json"}})}async function mx(e,t){return Cr(`workspace_snapshot_${e}`,t,{codes:{capacity:Jl.capacity.code,permission:Jl.permission.code,resource:Jl.resource.code},why:"Snapshot create and restore copy authoritative tracker state before activation, so the stage needs capacity and write access up front.",nextSteps:["Reclaim rebuildable tracker cache space with pm gc, then retry."],suggestedRetry:"pm gc --json"})}function xn(e){return W.join(e,cx)}function fx(e){return new p(`Unknown workspace snapshot: ${e}`,m.NOT_FOUND,{code:"workspace_snapshot_not_found",required:"Use a snapshot name or fingerprint returned by snapshot list.",why:"The requested reference or immutable snapshot object does not exist.",examples:["pm workspace snapshot list --json"],nextSteps:["List available snapshots and retry with an exact target."],recovery:{suggested_retry:"pm workspace snapshot list --json"}})}async function px(e,t){try{return JSON.parse(await dr(e,"utf8"))}catch(n){throw U(n)?fx(t):n}}async function ix(e,t,n){try{await Zl(e,{recursive:n})}catch(r){throw U(r)?fx(t):r}}async function pD(e,t,n=dx){try{return await n.renameEntry(e,t),!1}catch(r){if(!(r instanceof Error&&"code"in r&&(r.code==="EEXIST"||r.code==="ENOTEMPTY")))throw r;return await n.removeEntry(e),!0}}async function _D(e,t,n,r,s){await r.renameEntry(t,n);try{await r.renameEntry(e,t),await s?.()}catch(i){throw await r.renameEntry(n,t),await r.removeEntry(e),i}await r.removeEntry(n)}async function hD(e,t){return eu(t),/^[a-f0-9]{64}$/.test(t)?t:(await px(W.join(xn(e),"refs",`${t}.json`),t)).fingerprint}async function gD(e,t={}){if(t.name!==void 0&&(eu(t.name),/^[a-f0-9]{64}$/.test(t.name)))throw new p("Snapshot names must not be 64-character lowercase hexadecimal fingerprints",m.USAGE,{code:"workspace_snapshot_name_reserved_fingerprint",required:"Choose a human-readable reference name that cannot be mistaken for a content fingerprint.",why:"Exact 64-character hexadecimal values address immutable objects.",examples:["pm workspace snapshot create baseline --json"],nextSteps:["Retry with a shorter descriptive snapshot name."]});let{manifest:n,contents:r}=await ux(e),s=xn(e),i=W.join(s,"objects",n.fingerprint),o=!1;try{o=(await lD(i)).isDirectory()}catch(a){if(!(a instanceof Error&&"code"in a&&U(a)))throw a}if(!o){let a=W.join(s,"objects",`.create-${process.pid}-${bs.randomUUID()}`);await mx("create_object",async()=>{await bn(W.join(a,"files"),{recursive:!0});for(let[c,d]of n.files.entries()){let l=W.join(a,"files",d);await bn(W.dirname(l),{recursive:!0}),await ua(l,r[c])}await ua(W.join(a,"manifest.json"),`${JSON.stringify(n,null,2)}
|
|
14
|
+
`,"utf8"),await bn(W.dirname(i),{recursive:!0})}),o=await pD(a,i)}if(t.name!==void 0){let a={name:t.name,fingerprint:n.fingerprint},c=W.join(s,"refs");await bn(c,{recursive:!0});let d=W.join(c,`.ref-${process.pid}-${bs.randomUUID()}`);await ua(d,`${JSON.stringify(a,null,2)}
|
|
15
|
+
`,"utf8"),await ox(d,W.join(c,`${t.name}.json`))}return{manifest:n,...t.name===void 0?{}:{name:t.name},deduplicated:o}}async function tu(e,t){let n=await hD(e,t),r=await px(W.join(xn(e),"objects",n,"manifest.json"),t);if(r.schema!==ax||r.fingerprint!==n)throw new p(`Snapshot manifest identity mismatch: ${t}`,m.CONFLICT,{code:"workspace_snapshot_manifest_mismatch",required:"Use an intact snapshot whose manifest fingerprint matches its object path.",why:"Content identity must be verified before snapshot data is trusted.",examples:["pm workspace snapshot list --json"],nextSteps:["Inspect or recreate the snapshot before restoring it."]});return r}async function yD(e){let t=xn(e),n=await Xl(W.join(t,"objects")).catch(s=>{if(s instanceof Error&&"code"in s&&U(s))return[];throw s}),r=await Xl(W.join(t,"refs")).catch(s=>{if(s instanceof Error&&"code"in s&&U(s))return[];throw s});return{objects:await Promise.all(n.filter(s=>/^[a-f0-9]{64}$/.test(s)).sort().map(s=>tu(e,s))),references:await Promise.all(r.filter(s=>s.endsWith(".json")).sort().map(async s=>JSON.parse(await dr(W.join(t,"refs",s),"utf8"))))}}async function wD(e,t){let n=await tu(e,t),{manifest:r,contents:s}=await ux(e),i=new Map(r.files.map((u,f)=>[u,s[f]])),o=await fD(W.join(xn(e),"objects",n.fingerprint,"files"),n.files),a=new Set(r.files),c=new Set(n.files),d=new Set([...a,...c]);for(let u of d){let f=i.get(u),_=o.get(u);f!==void 0&&_!==void 0&&f.equals(_)&&d.delete(u)}let l=r.files.filter(u=>u.startsWith("history/")&&u.endsWith(".jsonl")).map(u=>{let f=sx(i.get(u)),_=sx(o.get(u));return{path:u,current_entries:f,target_entries:_,removed_entries:Math.max(0,f-_)}}).filter(u=>u.removed_entries>0).sort((u,f)=>u.path.localeCompare(f.path));return{target_fingerprint:n.fingerprint,current_fingerprint:r.fingerprint,changed_file_count:d.size,removed_file_count:[...a].filter(u=>!c.has(u)).length,added_file_count:[...c].filter(u=>!a.has(u)).length,removed_item_count:[...a].filter(u=>u.endsWith(".toon")&&!c.has(u)).length,affected_history_stream_count:l.length,removed_history_entry_count:l.reduce((u,f)=>u+f.removed_entries,0),affected_history_streams:l,changes_authoritative_state:r.fingerprint!==n.fingerprint}}async function vD(e,t,n={}){if(n.force!==!0)throw new p("Workspace snapshot restore requires explicit force confirmation; inspect the impact with planWorkspaceSnapshotRestore or pm workspace snapshot restore <target> --dry-run, then retry with force",m.USAGE,{code:"workspace_snapshot_force_required",required:"Preview the destructive impact, then explicitly confirm the restore.",why:"A restore replaces the complete authoritative tracker state.",examples:[`pm workspace snapshot restore ${t} --dry-run --json`,`pm workspace snapshot restore ${t} --force --json`],nextSteps:["Review the dry-run counts before retrying with --force."],recovery:{suggested_retry:`pm workspace snapshot restore ${t} --dry-run --json`}});let r=n.author?.trim()||"pm-sdk",s=n.lockTtlSeconds??60,i=n.lockWaitMs??5e3,o=await ai(e,cr,s,r,!1,!1,i),a=o.release,c=new Ql(zs(e,cr),r,s);c.start(),await c.refreshNow();let d,l=!1,u=!1;try{let f=await wD(e,t),_=await tu(e,t),h=await gD(e),g=_.fingerprint,y=xn(e),w=W.join(y,"objects",g,"files"),v=W.dirname(e),S=W.basename(e);d=W.join(v,`.${S}.restore-${bs.randomUUID()}`);let b=W.join(v,`.${S}.backup-${bs.randomUUID()}`);await mx("restore_stage",async()=>{await bn(d,{recursive:!0}),await rx(w,d,{recursive:!0,force:!1}),await bn(W.join(d,"runtime"),{recursive:!0}),await rx(y,W.join(d,cx),{recursive:!0,force:!1})});let k=await $n({pmRoot:d,op:"workspace_snapshot_restore",author:r,message:n.message??`Restore workspace snapshot ${g}; recovery snapshot ${h.manifest.fingerprint}`,context:{target_fingerprint:g,pre_restore_fingerprint:h.manifest.fingerprint,changed_file_count:f.changed_file_count,removed_file_count:f.removed_file_count,removed_item_count:f.removed_item_count,affected_history_stream_count:f.affected_history_stream_count,removed_history_entry_count:f.removed_history_entry_count},lockTtlSeconds:s,lockWaitMs:i}),A=W.relative(d,k.historyPath).replaceAll("\\","/");await c.stop(),u=!0;let x=zs(d,cr),E=d;return await o.fence(async()=>{await bn(W.dirname(x),{recursive:!0}),await ua(x,await dr(zs(e,cr)),{flag:"wx"}),l=!0,await _D(E,e,b,dx,async()=>{c.start(),u=!1,await c.refreshNow()})}),await c.stop(),u=!0,{manifest:_,plan:f,recovery_fingerprint:h.manifest.fingerprint,audit_history_path:A,audit_operation:"workspace_snapshot_restore"}}catch(f){throw d!==void 0&&!l&&await Promise.allSettled([Zl(d,{recursive:!0,force:!0})]),f}finally{try{u||await c.stop()}catch{}finally{await a()}}}async function h5(e,t){return(await vD(e,t,{force:!0,message:"Restore requested through the compatibility SDK signature"})).manifest}async function g5(e,t){eu(t);let n=xn(e);if(!/^[a-f0-9]{64}$/.test(t))return await ix(W.join(n,"refs",`${t}.json`),t,!1),{deleted:"reference",target:t};let{references:r}=await yD(e);if(r.some(s=>s.fingerprint===t))throw new Error(`Snapshot object ${t} is still referenced`);return await ix(W.join(n,"objects",t),t,!0),{deleted:"object",target:t}}function _x(e){return e.invalidEvidenceCount>0?"merge_evidence_invalid":e.historyEvidenceValid?e.pendingDecisionCount>0||e.losslessCount>0?"merge_reconciliation_required":e.driftedItemCount>0?"history_repair_required":e.fence.status!=="ok"||e.drivers===null||e.drivers.status!=="ok"?"merge_fence_unprepared":"ready":"history_evidence_invalid"}function hx(e,t,n=process.platform){let r=["--pm-path",t];return e==="merge_evidence_invalid"?L([...r,"merge","report"],n):e==="history_evidence_invalid"?L([...r,"validate","--check-history-drift","--full"],n):e==="merge_reconciliation_required"?L([...r,"merge","reconcile"],n):e==="history_repair_required"?L([...r,"history-repair","--all"],n):e==="merge_fence_unprepared"?L([...r,"merge","install"],n):null}function gx(e){let t=Array.isArray(e.drifted_items)?e.drifted_items.filter(r=>typeof r=="string"):[];return{evidence_valid:Array.isArray(e.drifted_items)&&e.drifted_items.every(r=>typeof r=="string")&&typeof e.drifted_items_count=="number"&&Number.isInteger(e.drifted_items_count)&&e.drifted_items_count>=0&&typeof e.drifted_items_truncated=="boolean"&&typeof e.counts=="object"&&e.counts!==null&&!Array.isArray(e.counts),drifted_item_count:typeof e.drifted_items_count=="number"?e.drifted_items_count:t.length,drifted_item_ids:t,drifted_item_ids_truncated:e.drifted_items_truncated===!0,counts:typeof e.counts=="object"&&e.counts!==null?e.counts:{}}}async function I5(e){let t=I(process.cwd(),e.path);await j(t);let n=await C(t),r=D(n,F()),s=[],i=await wo({includeBody:!0,pmRoot:t,settings:n,typeToFolder:r.type_to_folder,warnings:s}),o=await Pt(t),[a,c,d,l]=await Promise.all([Dn(t,Fn(n),{gitWorkspaceRoot:o}),o===null?Promise.resolve(null):jn(o),Un(o??t,{includeLossless:!0,pmRoot:t}),vo(t,i,!1)]),{pendingDecisions:u,lossless:f}=Gn(d.receipts),_=[...new Set(u.map(w=>w.item_id))].sort((w,v)=>w.localeCompare(v)),h=l.check.details,g=gx(h),y=_x({invalidEvidenceCount:d.invalid_evidence_count,pendingDecisionCount:u.length,losslessCount:f.length,historyEvidenceValid:g.evidence_valid,driftedItemCount:g.drifted_item_count,fence:a,drivers:c});return{ok:y==="ready",state:y,merge_fence:{committed:a,clone_local_drivers:c},merge_receipts:{pending_decision_count:u.length,pending_item_ids:_.slice(0,25),pending_item_ids_truncated:_.length>25,lossless_count:f.length,invalid_evidence_count:d.invalid_evidence_count},history_drift:g,next_action:{command:hx(y,t),reason:y},warnings:[...new Set(s)].sort((w,v)=>w.localeCompare(v)),generated_at:O()}}function O5(e){let t=e.next_action.command??"none";return[`workspace_position: ${e.state}`,`merge_fence: ${e.merge_fence.committed.status}`,`clone_local_drivers: ${e.merge_fence.clone_local_drivers?.status??"unavailable"}`,`pending_merge_decisions: ${e.merge_receipts.pending_decision_count}`,`history_drifted_items: ${e.history_drift.drifted_item_count}`,`next_action: ${t}`].join(`
|
|
16
|
+
`)}var L5={commandForWorkspacePositionState:hx,normalizeWorkspaceHistoryDrift:gx,selectWorkspacePositionState:_x};import{createHash as bD}from"node:crypto";import{execFile as xD}from"node:child_process";import vx from"node:path";import{promisify as SD}from"node:util";var yx=1;function kD(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.id=="string"&&typeof t.metric=="string"&&typeof t.value=="number"&&Number.isFinite(t.value)&&["higher","lower","target"].includes(String(t.direction))&&typeof t.observed_at=="string"&&typeof t.revision=="string"&&["caller","git","unversioned"].includes(String(t.revision_source))&&typeof t.author=="string"?t.direction!=="target"||typeof t.threshold=="number"&&Number.isFinite(t.threshold):!1}function nu(e){if(e===null)return{format_version:yx,observations:[]};let t;try{t=JSON.parse(e)}catch{throw new p("Improvement ledger contains invalid JSON.",m.GENERIC_FAILURE,{code:"invalid_improvement_ledger"})}if(typeof t!="object"||t===null||Array.isArray(t)||t.format_version!==yx||!Array.isArray(t.observations))throw new p("Improvement ledger has an unsupported shape or format version.",m.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});let n=t.observations;for(let r of n)if(!kD(r))throw new p("Improvement ledger contains an invalid observation.",m.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});return t}var ED=SD(xD),AD=50,wx=1e3,CD=/^[a-z0-9](?:[a-z0-9._/-]{0,126}[a-z0-9])?$/u;function kx(e){let t=e.trim().toLowerCase();if(!CD.test(t))throw new p(`Invalid metric name "${e}"; use 1-128 lowercase letters, digits, dots, slashes, underscores, or hyphens.`,m.USAGE,{code:"invalid_improvement_metric"});return t}function TD(e){let t=e??"lower";if(!["higher","lower","target"].includes(t))throw new p("Improvement direction must be higher, lower, or target.",m.USAGE,{code:"invalid_improvement_observation"});return t}function xs(e,t){let n=e?.trim();if(n){if(n.length>256)throw new p(`${t} must not exceed 256 characters.`,m.USAGE,{code:"invalid_improvement_observation"});return n}}function RD(e){let t=e??AD;if(!Number.isSafeInteger(t)||t<0||t>wx)throw new p(`Improvement observation limit must be an integer from 0 to ${wx}.`,m.USAGE,{code:"invalid_improvement_observation_limit"});return t}function bx(e,t){let n=Date.parse(e);if(!Number.isFinite(n))throw new p(`${t} must be an ISO timestamp.`,m.USAGE,{code:"invalid_improvement_observation_timestamp"});return new Date(n).toISOString()}async function ID(e,t,n){if(!Number.isFinite(n.value))throw new p("Improvement observation value must be finite.",m.USAGE,{code:"invalid_improvement_observation"});let r=kx(n.metric),s=TD(n.direction);if(n.threshold!==void 0&&!Number.isFinite(n.threshold)||s==="target"&&n.threshold===void 0)throw new p("Target-directed observations require a finite threshold.",m.USAGE,{code:"invalid_improvement_observation"});let i=await LD(e,n.revision),o=xs(n.source,"source"),a=xs(n.itemId,"itemId"),c=xs(n.unit,"unit"),d=xs(n.idempotencyKey,"idempotencyKey")??(i.revision_source==="unversioned"?void 0:[i.revision,r,o??"manual",a??"workspace"].join(":")),l={metric:r,value:n.value,direction:s,...c===void 0?{}:{unit:c},...n.threshold===void 0?{}:{threshold:n.threshold},observed_at:bx(n.observedAt??O(),"observedAt"),...i,author:G(n.author,t.author_default),...a===void 0?{}:{item_id:a},...o===void 0?{}:{source:o},...d===void 0?{}:{idempotency_key:d}};return{id:bD("sha256").update(Z(l)).digest("hex").slice(0,24),...l}}function OD(e,t){let n=t.idempotency_key?e.observations.find(s=>s.idempotency_key===t.idempotency_key):e.observations.find(s=>s.id===t.id);if(n){if(n.metric!==t.metric||n.value!==t.value||n.direction!==t.direction||n.threshold!==t.threshold||n.unit!==t.unit)throw new p(`Improvement observation retry key already records a different value for ${t.metric}.`,m.CONFLICT,{code:"improvement_observation_conflict"});return n}let r=e.observations.find(s=>s.metric===t.metric);if(r&&(r.direction!==t.direction||r.unit!==t.unit||t.direction==="target"&&r.threshold!==t.threshold))throw new p(`Metric ${t.metric} is already declared with direction ${r.direction} and unit ${r.unit??"<none>"}.`,m.CONFLICT,{code:"improvement_metric_contract_conflict"})}async function LD(e,t){let n=xs(t,"revision");if(n)return{revision:n,revision_source:"caller"};try{return{revision:(await ED("git",["rev-parse","--verify","HEAD^{commit}"],{cwd:lt(e),encoding:"utf8",timeout:5e3})).stdout.trim(),revision_source:"git"}}catch{}return{revision:"unversioned",revision_source:"unversioned"}}function $D(e){let t=e[0],n=e[e.length-1],r=n.value-t.value,s=n.direction==="higher"?r>0:n.direction==="lower"?r<0:Math.abs(n.value-n.threshold)<Math.abs(t.value-t.threshold);return{metric:n.metric,direction:n.direction,baseline:t,latest:n,delta:r,improved:s,sample_count:e.length}}async function xx(e,t={}){let n=I(process.cwd(),t.path);await j(n);let r=await C(n),s=await ID(n,r,e),i=vx.join(n,"improvement-ledger.json"),o=await Nn({pmRoot:n,filePath:i,op:"improvement_observe",author:s.author,lockTtlSeconds:r.locks.ttl_seconds,lockWaitMs:r.locks.wait_ms,message:e.message??`Record ${s.metric}=${String(e.value)} improvement observation`,mutate:a=>{let c=nu(a),d=OD(c,s);return d?{raw:a,result:d}:(c.observations.push(s),c.observations.sort((l,u)=>l.observed_at.localeCompare(u.observed_at)||l.metric.localeCompare(u.metric)||l.id.localeCompare(u.id)),{raw:`${Z(c)}
|
|
17
|
+
`,result:s})}});return{changed:o.changed,observation:o.result,ledger_path:"improvement-ledger.json"}}async function Sx(e={}){let t=I(e.cwd??process.cwd(),e.pmRoot);await j(t);let n=e.metric===void 0?void 0:kx(e.metric),r=e.since===void 0?void 0:bx(e.since,"since"),s=RD(e.limit),o=nu(await Q(vx.join(t,"improvement-ledger.json"))).observations.filter(c=>(n===void 0||c.metric===n)&&(e.itemId===void 0||c.item_id===e.itemId)&&(r===void 0||c.observed_at>=r)),a=new Map;for(let c of o){let d=a.get(c.metric)??[];d.push(c),a.set(c.metric,d)}return{observations:[...o].reverse().slice(0,s),total:o.length,truncated:o.length>s,trends:[...a].map(([,c])=>$D(c)).sort((c,d)=>c.metric.localeCompare(d.metric)),source:"audited_workspace_singleton"}}function ND(e){return e.agent_episode!==void 0?{id:e.agent_episode.id,source:"declared"}:{id:e.agent_instance?`inferred:instance:${e.agent_instance}`:`inferred:author:${e.author}:${e.ts.slice(0,13)}`,source:"inferred"}}function MD(e,t,n){let r=t,s=new Set([e.id]);for(;r!==void 0&&!s.has(r.id);)s.add(r.id),r=r.parent_id?n.get(r.parent_id):void 0;return r===void 0}function PD(e){let t=[e];for(;t.length>0;){let n=t.pop();n.sort((r,s)=>r.entries[0].ts.localeCompare(s.entries[0].ts)||r.id.localeCompare(s.id)),t.push(...n.map(r=>r.children))}}function Ex(e=Sr,t=xr){return t.map(n=>{let r=e.filter(s=>((n==="model"?s.model_environment_keys:s.provenance_environment_keys?.[n])?.length??0)>0||s.provenance_resolvers?.[n]!==void 0).map(s=>s.harness).sort();return{dimension:n,harnesses:r,covered:r.length>0}})}function e9(e,t=1){let n=new Map;for(let r of e){if(!r.agent_harness)continue;let s=n.get(r.agent_harness)??{harness:r.agent_harness,entries:0,observed:0,unavailable:0,legacy_missing:0};s.entries+=1,r.agent_model||r.agent_provenance?.model&&r.agent_provenance.model.value.length>0?s.observed+=1:r.agent_provenance?.model===null?s.unavailable+=1:s.legacy_missing+=1,n.set(r.agent_harness,s)}return[...n.values()].map(r=>{let s=r.observed+r.unavailable;return{...r,coverage:s===0?null:r.observed/s,inert:s>=t&&r.observed===0}}).sort((r,s)=>r.harness.localeCompare(s.harness))}function Ax(e,t=xr,n=1){let r=new Map;for(let s of e)if(s.agent_harness)for(let i of t){let o=`${s.agent_harness}\0${i}`,a=r.get(o)??{harness:s.agent_harness,dimension:i,entries:0,observed:0,unavailable:0,legacy_missing:0};a.entries+=1;let c=s.agent_provenance?.[i];c!=null&&c.value.length>0?a.observed+=1:c===null?a.unavailable+=1:a.legacy_missing+=1,r.set(o,a)}return[...r.values()].map(s=>{let i=s.observed+s.unavailable;return{...s,coverage:i===0?null:s.observed/i,inert:i>=n&&s.observed===0}}).sort((s,i)=>s.harness.localeCompare(i.harness)||s.dimension.localeCompare(i.dimension))}function t9(e,t={}){let n=t.minimumCoverage??.8,r=t.minimumEntries??5;if(![Number.isFinite(n),n>=0,n<=1].every(Boolean))throw new RangeError("Semantic attribution minimum coverage must be from 0 to 1.");if(![Number.isSafeInteger(r),r>=1].every(Boolean))throw new RangeError("Semantic attribution minimum entries must be a positive integer.");let s=new Map;for(let c of e)if(c.agent_harness)for(let d of["role","topic"]){let l=`${c.agent_harness}\0${d}`,u=s.get(l)??{harness:c.agent_harness,dimension:d,entries:0,observed:0,by_source:{},coverage:0};u.entries+=1;let f=c.agent_provenance?.[d];f?.value&&(u.observed+=1,u.by_source[f.source]=(u.by_source[f.source]??0)+1),s.set(l,u)}let i=[...s.values()].map(c=>({...c,coverage:c.observed/c.entries,by_source:Object.fromEntries(Object.entries(c.by_source).sort(([d],[l])=>d.localeCompare(l)))})).sort((c,d)=>c.harness.localeCompare(d.harness)||c.dimension.localeCompare(d.dimension)),o=i.filter(c=>c.entries>=r),a=o.filter(c=>c.coverage<n).map(c=>`${c.harness}:${c.dimension}`);return{passed:o.length>0&&a.length===0,minimum_coverage:n,minimum_entries:r,rows:i,failures:a}}function n9(e){let t=[...e].sort((i,o)=>i.ts.localeCompare(o.ts)||i.author.localeCompare(o.author)||i.op.localeCompare(o.op)||i.before_hash.localeCompare(o.before_hash)||i.after_hash.localeCompare(o.after_hash)),n=new Map,r=new Map;for(let i of t){let o=i.agent_episode,a=ND(i),c=`${a.source}:${a.id}`,d=n.get(c);if(d){d.entries.push(i);continue}let l={id:a.id,...o?.label===void 0?{}:{label:o.label},...o?.parent_id===void 0?{}:{parent_id:o.parent_id},source:a.source,entries:[i],children:[]};n.set(c,l),o!==void 0&&r.set(a.id,l)}let s=[];for(let i of n.values()){let o=i.parent_id?r.get(i.parent_id):void 0;o&&MD(i,o,r)?o.children.push(i):s.push(i)}return PD(s),s}var FD=1e4,Cx=1e5,DD=1e3,jD=30,UD=["append","comment","docs","file","learning","note","test_run"];function GD(e){let t=e??FD;if(!Number.isSafeInteger(t)||t<1||t>Cx)throw new p(`History analytics event limit must be an integer from 1 to ${Cx}.`,m.USAGE,{code:"invalid_history_analytics_limit"});return t}function Tx(e){let t=e??5;if(!Number.isSafeInteger(t)||t<1||t>1e4)throw new p("History analytics minimum sample must be an integer from 1 to 10000.",m.USAGE,{code:"invalid_history_analytics_minimum_sample"});return t}function qD(e){let t=e?.trim();if(!t)return new Date(Date.now()-jD*864e5).toISOString();let n=/^-(\d+)([dh])$/u.exec(t);if(n){let s=Number(n[1]),i=n[2]==="d"?864e5:36e5;if(!Number.isSafeInteger(s)||s<1)throw new p("History analytics --since duration must be positive.",m.USAGE,{code:"invalid_history_analytics_since"});return new Date(Date.now()-s*i).toISOString()}let r=Date.parse(t);if(!Number.isFinite(r))throw new p("History analytics --since must be an ISO timestamp or negative duration such as -30d.",m.USAGE,{code:"invalid_history_analytics_since"});return new Date(r).toISOString()}async function ma(e,t){let n=GD(t.eventLimit),r=qD(t.since),s=[],i=r,o=!1;for(;s.length<n;){let a=await zh({pmRoot:e,since:i,limit:Math.min(DD,n-s.length),full:!0}),c=a.events.map(d=>({item_id:d.item_id,entry:d.entry}));if(s.push(...c),o=a.has_more,i=a.next_cursor,!a.has_more)break}return{events:s,receipt:{since:r,events:s.length,truncated:o,...o?{next_cursor:i}:{},source:"history_event_index"}}}function WD(e,t){return t==="harness"?e.agent_harness:t==="author_source"?e.author_source:e.agent_model??e.agent_provenance?.model?.value}function KD(e){for(let t=e.patch.length-1;t>=0;t-=1){let n=e.patch[t];if(n.path==="/metadata/status"&&"value"in n&&typeof n.value=="string")return n.value}}function zD(e){return UD.some(t=>e.startsWith(t))}function Rx(e,t){let n=e.get(t);if(n)return n;let r={events:0,stateEvents:0,annotationEvents:0,closes:0,reopens:0,defectEscapes:0};return e.set(t,r),r}function BD(e,t,n){let r=new Map,s=new Map,i=new Map;for(let o of t){let a=WD(o.entry,e),c=KD(o.entry),d=s.get(o.item_id)===!0,l=c===void 0?d:n.has(c);if(c!==void 0&&s.set(o.item_id,l),!a)continue;let u=Rx(r,a);u.events+=1,zD(o.entry.op)?u.annotationEvents+=1:u.stateEvents+=1,c!==void 0&&!d&&l?(u.closes+=1,i.set(o.item_id,a)):c!==void 0&&d&&!l&&(u.reopens+=1)}return{buckets:r,lastCloseValue:i}}function HD(e,t,n){for(let r of n){if(r.type!=="Issue")continue;let s=new Set((r.dependencies??[]).filter(i=>i.kind==="discovered_from").map(i=>i.id));for(let i of s){let o=t.get(i);o&&(Rx(e,o).defectEscapes+=1)}}}function VD(e,t,n,r){let s=t.closes>=n?"available":"insufficient";return{value:e,events:t.events,state_events:t.stateEvents,annotation_events:t.annotationEvents,closes:t.closes,reopens:t.reopens,defect_escapes:t.defectEscapes,throughput_per_day:s==="available"?t.closes/r:null,rework_rate:s==="available"?t.reopens/t.closes:null,defect_escape_rate:s==="available"?t.defectEscapes/t.closes:null,sample_status:s}}function YD(e,t,n,r,s,i){let{buckets:o,lastCloseValue:a}=BD(e,t,r);return HD(o,a,n),{dimension:e,status:o.size===0?"unavailable":"available",rows:[...o].map(([c,d])=>VD(c,d,s,i)).sort((c,d)=>d.events-c.events||c.value.localeCompare(d.value))}}function JD(e,t){let n=e[0]?.entry.ts??t,r=e[e.length-1]?.entry.ts??n,s=Date.parse(n),i=Date.parse(r);return!Number.isFinite(s)||!Number.isFinite(i)?1:Math.max(1,(i-s)/864e5)}function XD(e,t,n){let r=Ex(t),s=Ax(e,xr,n),i=s.filter(a=>a.inert).map(a=>({harness:a.harness,dimension:a.dimension,explicit_samples:a.observed+a.unavailable})),o=r.filter(a=>!a.covered).map(a=>a.dimension);return{descriptors:r,observations:s,inert:i,undeclared:o,warnings:[...i.map(a=>`provenance_dimension_inert:${a.harness}:${a.dimension}:${String(a.explicit_samples)}`),...o.map(a=>`provenance_dimension_undeclared:${a}`)]}}async function d9(e,t=Sr,n={}){return ru(await ma(e,n),t,n)}function ru(e,t=Sr,n={}){let r=Tx(n.minimumSample);return{...XD(e.events.map(s=>s.entry),t,r),window:e.receipt}}async function l9(e,t,n,r={}){return su(await ma(e,r),t,n,r)}function su(e,t,n,r={}){let s=Tx(r.minimumSample),i=JD(e.events,e.receipt.since);return{dimensions:["harness","model","author_source"].map(o=>YD(o,e.events,t,n,s,i)),minimum_sample:s,policy:"observational_only_not_for_authorization_or_routing",window:e.receipt}}var QD=32;function ZD(e){let t=[];for(let n of e??[]){let r=[];for(let s of n.split(",")){let i=s.slice(0,s.indexOf("=")).trim();r.length>0&&i!=="unit"&&i!=="threshold"&&(t.push(r.join(",")),r=[]),r.push(s)}t.push(r.join(","))}return t}function Ss(e,t){let n=ZD(e).map(s=>{let[i,...o]=s.split(","),a=i.indexOf("="),c=i.slice(0,a).trim(),d=i.slice(a+1).trim(),l=Number(d);if(a<=0||c.length===0||d.length===0||!Number.isFinite(l))throw new p(`Invalid --measure "${s}"; expected name=value[,unit=...][,threshold=...]`,m.USAGE);let u,f;for(let _ of o){let h=_.indexOf("="),g=_.slice(0,h).trim(),y=_.slice(h+1).trim();if(g==="unit"&&y.length>0)u=y;else if(g==="threshold"&&y.length>0&&Number.isFinite(Number(y)))f=Number(y);else throw new p(`Invalid --measure attribute "${_}"`,m.USAGE)}return{name:c,value:l,unit:u,threshold:f,recorded_at:t}});return[...new Map(n.map(s=>[s.name,s])).values()].sort((s,i)=>s.name.localeCompare(i.name)).slice(0,QD)}function Ix(e,t,n){return e.flatMap(r=>(r.measurements??[]).filter(s=>s.name===t&&s.value<n).map(s=>({...s,run_id:r.run_id})))}function Ox(e,t){let n=e.flatMap(i=>i.measurements??[]).filter(i=>i.name===t).sort((i,o)=>o.recorded_at.localeCompare(i.recorded_at)),r=n[0],s=n[1];return{name:t,latest:r?.value??null,previous:s?.value??null,delta:r!==void 0&&s!==void 0?r.value-s.value:null,unit:r?.unit}}import tj from"node:fs/promises";import $x from"node:path";function fa(e,t,n,r,s,i="min"){let o=s==="min"?e-t:t-e,a=i==="min"?n.localeCompare(r??n):(r??n).localeCompare(n);return o<0||o===0&&r!==null&&a<0}function ej(e,t){let n=Buffer.byteLength(t,"utf8"),r=0,s=null,i=null,o=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY;for(let c of t.split(/\r?\n/)){let d=c.trim();if(d==="")continue;r+=1;let l;try{l=JSON.parse(d)}catch{continue}if(l===null||typeof l!="object"||!("ts"in l)||typeof l.ts!="string")continue;let u=l.ts,f=Date.parse(u);Number.isNaN(f)||(fa(f,o,u,s,"min")&&(o=f,s=u),fa(f,a,u,i,"max","max")&&(a=f,i=u))}return{id:e,bytes:n,lines:r,oldest_ts:s,newest_ts:i}}function Lx(e,t){let n=t?.topN??5,r=Math.max(0,Math.floor(n)),s=e.map(({id:_,raw:h})=>ej(_,h)),i=0,o=0,a=null,c=null,d=Number.POSITIVE_INFINITY,l=Number.NEGATIVE_INFINITY;for(let _ of s){if(i+=_.lines,o+=_.bytes,_.oldest_ts!==null){let h=Date.parse(_.oldest_ts);fa(h,d,_.id,a?.id??null,"min")&&(d=h,a={id:_.id,ts:_.oldest_ts})}if(_.newest_ts!==null){let h=Date.parse(_.newest_ts);fa(h,l,_.id,c?.id??null,"max")&&(l=h,c={id:_.id,ts:_.newest_ts})}}let u=r===0?[]:[...s].sort((_,h)=>h.bytes-_.bytes||_.id.localeCompare(h.id)).slice(0,r),f=r===0?[]:[...s].sort((_,h)=>h.lines-_.lines||_.id.localeCompare(h.id)).slice(0,r);return{total_streams:e.length,total_lines:i,total_bytes:o,largest_by_bytes:u,deepest_by_lines:f,oldest_entry:a,newest_entry:c}}function nj(e){return e.reduce((t,n)=>(t[n]=0,t),{})}function rj(e,t,n,r,s){let i=Pr(e,"type",r),o=new Set(i.rows.map(f=>f.key)),a=t.filter(f=>!o.has(f)),d=(s?[...i.rows,...a.map(f=>({label:f,key:f,total:0,buckets:{open:0,in_progress:0,blocked:0,draft:0,closed:0,canceled:0,other:0}}))]:i.rows).map(f=>({type:f.key??f.label,total:f.total,open:f.buckets.open,in_progress:f.buckets.in_progress,blocked:f.buckets.blocked,draft:f.buckets.draft,closed:f.buckets.closed,canceled:f.buckets.canceled,other:f.buckets.other})),l=nj([...n]);for(let f of e)l[f.status]+=1;let u=Object.fromEntries(Object.entries(l).filter(([,f])=>s||f>0));return{byType:d,byStatus:u,omitted:s?0:a.length+Object.values(l).filter(f=>f===0).length}}function sj(e){return e.trim().length===0?0:e.split(/\r?\n/u).filter(t=>t.trim().length>0).length}async function ij(e){let t=$x.join(e,"history");if(!await se(t))return[];await He({path:t,scope:"project"});let n=(await tj.readdir(t)).filter(s=>s.endsWith(".jsonl")).sort((s,i)=>s.localeCompare(i)),r=[];for(let s of n){let i=$x.join(t,s),o=await Q(i);o!==null&&(await He({path:i,scope:"project"}),r.push({id:s.slice(0,-6),raw:o}))}return r}async function oj(e,t){let n=[],r=O();for(let s of Ss(t.observe,r))n.push(await xx({metric:s.name,value:s.value,direction:t.direction,unit:s.unit,threshold:s.threshold,source:t.measurementSource,itemId:t.measurementItem,revision:t.measurementRevision,observedAt:r,author:t.author,message:t.message},e));return n}function aj(e,t,n){let r={};return t.byAssignee&&(r.assignee=Pr(e,"assignee",n)),t.byTag&&(r.tag=Pr(e,"tag",n,{tagPrefix:t.tagPrefix})),t.byPriority&&(r.priority=Pr(e,"priority",n)),r}async function cj(e,t,n,r,s){let i={since:s.since,eventLimit:s.eventLimit,minimumSample:s.minimumSample},o=s.provenanceCoverage||s.fleetAttribution?await ma(e,i):void 0;return{provenanceCoverage:s.provenanceCoverage&&o?ru(o,n.agent_identity?.harness_signals,i):void 0,fleetAttribution:s.fleetAttribution&&o?su(o,t,r,i):void 0}}function dj(e,t,n,r,s){let i=Object.keys(s.breakdowns).length>0;return{totals:e,by_type:t,by_status:n,omitted_zero_buckets:r,...s.metadataCoverage?{metadata_coverage:s.metadataCoverage}:{},...i?{breakdowns:s.breakdowns}:{},...s.storage?{storage:s.storage}:{},...s.fieldUtilization?{field_utilization:s.fieldUtilization}:{},...s.improvementLedger?{improvement_ledger:s.improvementLedger}:{},...s.recordedObservations.length>0?{recorded_observations:s.recordedObservations}:{},...s.provenanceCoverage?{provenance_coverage:s.provenanceCoverage}:{},...s.fleetAttribution?{fleet_attribution:s.fleetAttribution}:{},generated_at:O()}}async function $9(e,t={}){let n=I(process.cwd(),e.path);await j(n);let r=await C(n),s=await oj(e,t),i=D(r,F()),o=z(r.schema),a=t.fieldUtilization?await wt(n,r.item_format,i.type_to_folder,void 0,r.schema):await Ae(n,r.item_format,i.type_to_folder,void 0,r.schema);await mi({pmRoot:n,settings:r,itemIds:a.map(S=>S.id),commandLabel:"stats"});let c=wh(o),d=rj(a,i.types,o.definitions.map(S=>S.id),c,t.includeEmpty===!0),l=await ij(n),u=0;for(let S of l)u+=sj(S.raw);let f=t.storage?Lx(l):void 0,_=t.metadataCoverage?vh(a,c):void 0,h=aj(a,t,c),g=t.fieldUtilization?kh(a):void 0,y=t.measurements===!0||s.length>0?await Sx({pmRoot:n,metric:t.metric,itemId:t.measurementItem,limit:t.measurementLimit}):void 0,{provenanceCoverage:w,fleetAttribution:v}=await cj(n,a,r,o.terminal_statuses,t);return dj({items:a.length,history_streams:l.length,history_entries:u},d.byType,d.byStatus,d.omitted,{metadataCoverage:_,breakdowns:h,storage:f,fieldUtilization:g,improvementLedger:y,recordedObservations:s,provenanceCoverage:w,fleetAttribution:v})}import lj from"node:fs/promises";import Ct from"node:path";var Dx=Ct.join("runtime","telemetry","state.json"),Es=Ct.join("runtime","telemetry"),uj=20,au=zt.filter(e=>e.lifecycle==="deprecated"),Nx=["status","flush","stats","clear"],Mx=(e,t)=>{let n=Math.ceil(t*e.length),r=Math.min(e.length-1,Math.max(0,n-1));return e[r]},iu=(e,t)=>typeof e!="string"?t:e.trim().length>0?e:t,Px=e=>{if(!(typeof e!="number"||!Number.isFinite(e)))return Math.trunc(e)},mj=e=>({command:iu(e.event.command,"<unknown>"),eventType:iu(e.event.event_type,"unknown"),eventSchemaVersion:Px(e.event.schema_version),clientSchemaVersion:Px(e.client_schema_version)}),fj=()=>({count:0,max_attempts:0,event_type_counts:{},event_schema_versions:new Set,client_schema_versions:new Set,finish_durations_ms:[],ok_count:0,error_count:0,resolution_counts:{}}),pj=e=>{let t=e?.duration_ms;return typeof t=="number"&&Number.isFinite(t)?t:void 0},_j=e=>{let t=e?.command_resolution;return iu(t,"")||void 0},jx=(e,t)=>{e[t]=(e[t]??0)+1},hj=(e,t)=>{let n=pj(t);n!==void 0&&e.finish_durations_ms.push(n),t?.ok===!0?e.ok_count+=1:e.error_count+=1;let r=_j(t);r!==void 0&&jx(e.resolution_counts,r)},gj=e=>Number.isFinite(e)?Math.max(0,Math.trunc(e)):0,Fx=(e,t)=>{t!==void 0&&e.add(t)},yj=(e,t)=>{let n=mj(t),r=e.get(n.command)??fj();r.count+=1,r.max_attempts=Math.max(r.max_attempts,gj(t.attempts)),jx(r.event_type_counts,n.eventType),Fx(r.event_schema_versions,n.eventSchemaVersion),Fx(r.client_schema_versions,n.clientSchemaVersion),n.eventType==="command_finish"&&hj(r,t.event.payload),e.set(n.command,r)},wj=(e,t)=>{let n=t.ok_count+t.error_count,r=[...t.finish_durations_ms].sort((i,o)=>i-o),s=Object.entries(t.resolution_counts).sort((i,o)=>i[0].localeCompare(o[0]));return{command:e,count:t.count,event_type_counts:Object.fromEntries(Object.entries(t.event_type_counts).sort((i,o)=>i[0].localeCompare(o[0]))),max_attempts:t.max_attempts,event_schema_versions:[...t.event_schema_versions].sort((i,o)=>i-o),client_schema_versions:[...t.client_schema_versions].sort((i,o)=>i-o),...r.length>0?{duration_p50_ms:Mx(r,.5),duration_p95_ms:Mx(r,.95),duration_max_ms:r[r.length-1]}:{},...n>0?{ok_count:t.ok_count,error_count:t.error_count,error_rate:t.error_count/n}:{},...s.length>0?{command_resolution_counts:Object.fromEntries(s)}:{}}},vj=e=>{let t=(e??"status").trim().toLowerCase();if(Nx.includes(t))return t;throw Qs({command_path:"telemetry",token:e?.trim()||"<empty>",allowed:Nx,examples:["pm telemetry status","pm telemetry flush","pm telemetry stats --limit 10","pm telemetry clear"]})},cu=()=>{throw new p("--limit must be a positive integer",m.USAGE)},Ux=e=>[!Number.isFinite(e),!Number.isInteger(e),e<=0].includes(!0)?cu():e,kj=e=>{let t=e.trim();return[t.length===0,!/^\d+$/.test(t)].includes(!0)?cu():Ux(Number.parseInt(t,10))},bj=e=>e===void 0?uj:typeof e=="number"?Ux(e):typeof e=="string"?kj(e):cu(),xj=e=>{if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.attempts=="number"&&typeof t.event=="object"&&t.event!==null},Sj=e=>{try{let t=JSON.parse(e);return xj(t)?t:void 0}catch{return}},Ej=e=>e===null?[]:e.split(`
|
|
18
|
+
`).map(t=>t.trim()).filter(t=>t.length>0),Gx=e=>{let t=Ej(e),n=[],r=0;for(let s of t){let i=Sj(s);i===void 0?r+=1:n.push(i)}return{rows_total:t.length,valid_entries:n.length,invalid_rows:r,entries:n}},Aj=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Cj=e=>{try{let t=JSON.parse(e);return Aj(t)?t:{}}catch{return{}}},_a=async e=>{let t=await Q(e);return t===null||t.trim().length===0?{}:Cj(t)};function qx(e){let t=new Date;return new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()-Math.max(1,Math.trunc(e))+1)).toISOString().slice(0,10)}function Tj(e,t,n){let r=Object.create(null);for(let[s,i]of Object.entries(e)){if(!/^\d{4}-\d{2}-\d{2}$/u.test(s)||s<t||s>n||typeof i!="object"||i===null||Array.isArray(i))continue;let o=i;!Number.isSafeInteger(o.count)||o.count<1||typeof o.last_seen!="string"||!o.last_seen.startsWith(s)||(r[s]={count:o.count,last_seen:o.last_seen})}return r}function ou(e,t){let n=Object.create(null);if(typeof e!="object"||e===null||Array.isArray(e))return n;let r=e,s=new Date().toISOString().slice(0,10);for(let i of au){let o=r[i.alias];if(typeof o!="object"||o===null||Array.isArray(o))continue;let a=o;if(a.canonical!==i.canonical||typeof a.days!="object"||a.days===null||Array.isArray(a.days))continue;let c=Tj(a.days,t,s);Object.keys(c).length>0&&(n[i.alias]={canonical:i.canonical,days:c})}return n}async function Rj(e,t,n){let r=qx(n),s=await _a(t),i=ou(s.alias_usage,r);if(JSON.stringify(s.alias_usage??{})===JSON.stringify(i))return i;try{await ki(async()=>{let o=await _a(t);if(o.alias_usage===void 0)return;let a=ou(o.alias_usage,r);JSON.stringify(o.alias_usage)!==JSON.stringify(a)&&await Ge(t,`${JSON.stringify({...o,alias_usage:a},null,2)}
|
|
19
|
+
`)},e,250)}catch{}return i}async function H9(e){let t=au.find(r=>r.alias===e);if(!t||en().telemetry_disabled)return!1;let n=Xe(process.cwd());try{return await ki(async()=>{let r=await C(n);if(!r.telemetry.enabled||en().telemetry_disabled)return!1;let s=Ct.join(n,Dx),i=await _a(s),o=ou(i.alias_usage,qx(r.telemetry.retention_days)),a=new Date().toISOString().slice(0,10),c=o[e]?.days[a];return o[e]={canonical:t.canonical,days:{...o[e]?.days,[a]:{count:Math.min(Number.MAX_SAFE_INTEGER,(c?.count??0)+1),last_seen:O()}}},await Ge(s,`${JSON.stringify({...i,alias_usage:o},null,2)}
|
|
20
|
+
`),!0},n,250)}catch{return!1}}var pa=e=>e??null,ha=async e=>{let t=await C(e),n=Ct.join(e,Es,$t("events.jsonl")),r=Ct.join(e,Es,$t("state.json")),s=await Q(n),i=Gx(s),o=await _a(r),a=en();return{enabled:t.telemetry.enabled&&!a.telemetry_disabled,configured_enabled:t.telemetry.enabled,env_overrides:a,endpoint:Nt(Ir(t.telemetry.endpoint)),queue_path:n,state_path:r,queue_rows_total:i.rows_total,queue_entries:i.valid_entries,queue_invalid_rows:i.invalid_rows,queue_size_bytes:Buffer.byteLength(s??"","utf8"),last_attempted_flush_at:pa(o.last_attempted_flush_at),last_successful_flush_at:pa(o.last_successful_flush_at),last_failed_flush_at:pa(o.last_failed_flush_at),last_failed_flush_error:pa(o.last_failed_flush_error)}},Ij=e=>{let t=new Map;for(let n of e)yj(t,n);return[...t.entries()].map(([n,r])=>wj(n,r)).sort((n,r)=>r.count-n.count||n.command.localeCompare(r.command))},Oj=async(e,t)=>({action:"telemetry",subcommand:"status",status:await ha(t.globalPmRoot),generated_at:O()}),Lj=async(e,t)=>{let n=await ha(t.globalPmRoot);await up(t.globalPmRoot);let r=await ha(t.globalPmRoot),s=Math.max(0,n.queue_entries-r.queue_entries),i=r.queue_entries===0;return{action:"telemetry",subcommand:"flush",queue_entries_before:n.queue_entries,queue_entries_after:r.queue_entries,queue_entries_drained:s,queue_progressed:s>0,queue_empty:i,queue_drained:i,status:r,generated_at:O()}},$j=async(e,t)=>{let n=bj(e.limit),r=await Q(t.queuePath),s=Gx(r),i=Ij(s.entries),o=i.slice(0,n),a=await C(t.globalPmRoot),c=await Rj(t.globalPmRoot,Ct.join(t.globalPmRoot,Dx),a.telemetry.retention_days),d=Object.entries(c).map(([l,u])=>{let f=Object.values(u.days);return{alias:l,canonical:u.canonical,count:f.reduce((_,h)=>Math.min(Number.MAX_SAFE_INTEGER,_+h.count),0),last_seen:f.map(_=>_.last_seen).sort().at(-1)}}).sort((l,u)=>u.count-l.count||l.alias.localeCompare(u.alias));return{action:"telemetry",subcommand:"stats",limit:n,total_commands:i.length,queue_entries:s.valid_entries,queue_invalid_rows:s.invalid_rows,queue_rows_total:s.rows_total,truncated:i.length>o.length,stats:o,alias_usage:d,zero_use_aliases:au.map(l=>l.alias).filter(l=>c[l]===void 0),alias_usage_retention_days:a.telemetry.retention_days,generated_at:O()}},Nj=async(e,t)=>ki(async()=>{let n=await C(t.globalPmRoot),r=[n.telemetry.enabled!==!1,n.telemetry.installation_id!=="",n.telemetry.first_run_prompt_completed!==!0].includes(!0);n.telemetry.enabled=!1,n.telemetry.first_run_prompt_completed=!0,n.telemetry.installation_id="",r&&await Gf(t.globalPmRoot,n,"telemetry:clear");let s=Ct.join(t.globalPmRoot,Es),i=await se(s);return await lj.rm(s,{recursive:!0,force:!0}),{action:"telemetry",subcommand:"clear",settings_changed:r,runtime_dir_removed:i&&!await se(s),queue_exists_after:await se(t.queuePath),state_exists_after:await se(t.statePath),status:await ha(t.globalPmRoot),generated_at:O()}},t.globalPmRoot),Mj={status:Oj,flush:Lj,stats:$j,clear:Nj};async function V9(e,t){let n=vj(e.subcommand),r=Xe(process.cwd());return Mj[n](e,{globalPmRoot:r,queuePath:Ct.join(r,Es,$t("events.jsonl")),statePath:Ct.join(r,Es,$t("state.json"))})}var Wx=100;function lr(e,t="--only-index"){let n=typeof e=="number"?e:Number(String(e).trim());if(!Number.isInteger(n)||n<1)throw new p(`${t} requires a 1-based integer index into the linked-test list (got "${e}"). Use pm test <id> --list to inspect positions.`,m.USAGE);return n}function Pj(e){let n=(e.command??e.path??"<no command>").replaceAll(/\s+/g," ").trim()||"<no command>";return n.length<=Wx?n:`${n.slice(0,Wx-3)}...`}function Kx(e){return e.map((t,n)=>`${n+1}. ${Pj(t)}`).join("; ")}function Fj(e){let t=[];return e.match!==void 0&&t.push("match"),e.onlyIndex!==void 0&&t.push("only-index"),e.onlyLast===!0&&t.push("only-last"),t}function Dj(e,t){let n=e.command?.toLowerCase()??"",r=e.path?.toLowerCase()??"";return n.includes(t)||r.includes(t)}function zx(e,t){let n=Fj(t);if(n.length===0)return{selector:null,requested:null,selected:e,selected_indexes:e.map((s,i)=>i+1),selected_count:e.length,skipped_count:0};if(n.length>1)throw new p(`Combine at most one linked-test selector per run: ${n.map(s=>`--${s}`).join(" and ")} were provided. Pick one of --match, --only-index, --only-last.`,m.USAGE);let r=n[0];if(e.length===0)throw new p(`--${r} matched no linked tests because this item has none. Add one first with --add, --command, or --add-json.`,m.USAGE);if(r==="match"){let s=t.match.trim().toLowerCase();if(s.length===0)throw new p("--match requires a non-empty substring to match against linked-test command/path values",m.USAGE);let i=[],o=[];for(let a=0;a<e.length;a+=1)Dj(e[a],s)&&(o.push(e[a]),i.push(a+1));if(o.length===0)throw new p(`--match "${t.match}" matched none of the ${e.length} linked test(s). Available entries: ${Kx(e)}`,m.USAGE);return{selector:"match",requested:t.match,selected:o,selected_indexes:i,selected_count:o.length,skipped_count:e.length-o.length}}if(r==="only-index"){let s=lr(t.onlyIndex);if(s>e.length)throw new p(`--only-index ${s} is out of range: this item has ${e.length} linked test(s). Available entries: ${Kx(e)}`,m.USAGE);return{selector:"only-index",requested:String(s),selected:[e[s-1]],selected_indexes:[s],selected_count:1,skipped_count:e.length-1}}return{selector:"only-last",requested:"last",selected:[e[e.length-1]],selected_indexes:[e.length],selected_count:1,skipped_count:e.length-1}}var du=["command","cmd"],As=Object.freeze(gt.filter(e=>!["command","cmd","timeout"].includes(e)));function Bx(e){if(e.update===void 0&&e.updateIndex===void 0&&e.setJson===void 0)return;if(e.update===void 0==(e.updateIndex===void 0)||e.setJson===void 0)throw new p("Use exactly one --update or --update-index with --set-json",m.USAGE);let t;try{t=JSON.parse(e.setJson)}catch{throw new p("--set-json must contain a JSON object with explicit linked-test metadata fields",m.USAGE)}if(e.updateIndex!==void 0)return{selector:{index:lr(e.updateIndex,"--update-index")},patch:t};let n=e.update,r=/^(command|path)=/u.exec(n);return{selector:r?.[1]==="path"?{path:n.slice(r[0].length)}:{command:r?n.slice(r[0].length):n},patch:t}}function Hx(e){if([e.list,e.run,e.progress,e.timeout!==void 0,e.acknowledgeLinkedTests,e.metricBelow!==void 0,e.metricDiff!==void 0,(e.add?.length??0)>0,(e.addJson?.length??0)>0,(e.remove?.length??0)>0,(e.removeIndex?.length??0)>0].some(Boolean))throw new p("Edit linked-test metadata separately from listing, additions, removals, execution options, metric filters and trust acknowledgement",m.USAGE)}function jj(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new p("Select one linked test by index, command, or path",m.USAGE);let n=Object.keys(t);if(n.length!==1||!["index","command","path"].includes(n[0]))throw new p("Select one linked test by index, command, or path",m.USAGE);if("index"in t){let r=lr(t.index,"--update-index");if(r<=e.length)return r-1}else{let r="command"in t?"command":"path",s="command"in t?t.command:t.path;if(typeof s!="string"||s.trim().length===0)throw new p("Linked-test selector must be a non-empty command or path",m.USAGE);let i=e.flatMap((o,a)=>o[r]===s?[a]:[]);if(i.length===1)return i[0];if(i.length>1)throw new p(`Linked-test selector is ambiguous; matching indexes: ${i.map(o=>o+1).join(", ")}`,m.USAGE,{code:"linked_test_update_ambiguous",required:"List linked tests and select one current --update-index."})}throw new p("No linked test matched the update selector",m.NOT_FOUND,{code:"linked_test_update_no_match",required:"List linked tests and select a current command, path, or --update-index."})}function Vx(e,t){let n=Object.keys(e),r=n.filter(s=>!As.includes(s));if(n.length===0&&!t||r.length>0)throw new p("Patch explicit linked-test metadata fields; command, aliases and provenance cannot be edited",m.USAGE,{code:"linked_test_patch_fields_unsupported",changed:!1,...r.length>0?{field:r[0]}:{},required:`Patch at least one editable field: ${As.join(", ")}.`,recovery:{allowed_values:[...As]},...r.length>0?{nextSteps:[`Remove unsupported field(s) from --set-json: ${r.join(", ")}.`]}:{}});if(e.scope===null)throw new p("scope is required and cannot be cleared",m.USAGE)}function Uj(e,t,n){let r={};for(let s of As){let i=t[s]!==void 0?t[s]:e[s];i!=null&&(r[s]=i)}return{command:n,...r}}function ga(e){return{field:e,changed:!1,required:"Replace the entry instead: remove the selected linked test and add the new command in one pm test invocation, which records fresh provenance."}}function Gj(e,t,n){let r=du.filter(i=>Object.hasOwn(e,i)).map(i=>e[i]),s=typeof e[t]=="string"?e[t].trim():"";if(r.length>1&&r.some(i=>typeof i!="string"||i.trim()!==s))throw new p("--set-json sets command and cmd to different values; send one command",m.USAGE,{code:"linked_test_command_immutable",...ga(t),nextSteps:["Send the replacement command once, as command."]});if(s.length===0||s===n.command)throw new p(s.length===0?`--set-json cannot set ${t}: a linked test's command is its immutable identity`:`--set-json ${t} repeats the selected entry's command; omit it to edit only metadata`,m.USAGE,{code:"linked_test_command_immutable",...ga(t),nextSteps:[`Patch only editable fields: ${As.join(", ")}.`]});return os(s),s}function qj(e){let{id:t,tests:n,index:r,identityKey:s,otherFields:i,requested:o,global:a}=e;Vx(i,!0);let c=Uj(n[r],i,o),d=ys(JSON.stringify(c),"--add-json")[0];vr(d);let l=n.findIndex((u,f)=>f!==r&&kr(u,d));if(l>=0)throw new p(`--set-json cannot change ${s}: linked test ${l+1} already has the requested identity, so a replacement would merge into it`,m.USAGE,{code:"linked_test_command_immutable",...ga(s),nextSteps:[`Edit linked test ${l+1} instead: ${L([...Le(a),"test",t,"--update-index",String(l+1),"--set-json","<editable fields>"])}`,`Or drop the selected entry: ${L([...Le(a),"test",t,"--remove-index",String(r+1)])}`]});return c}function Wj(e){return[...e.author!==void 0?["--author",e.author]:[],...e.message!==void 0?["--message",e.message]:[],...e.force===!0?["--force"]:[]]}function Kj(e){let{id:t,tests:n,index:r,patch:s,global:i,controls:o}=e;if(typeof s!="object"||s===null||Array.isArray(s))return;let a=s,c=du.find(g=>Object.hasOwn(a,g));if(c===void 0)return;let d=n[r],l=Gj(a,c,d),u=Object.fromEntries(Object.entries(a).filter(([g])=>!du.includes(g))),f=qj({id:t,tests:n,index:r,identityKey:c,otherFields:u,requested:l,global:i}),_=d.command!==void 0&&n.filter(g=>g.command===d.command).length===1?["--remove",`command=${d.command}`]:["--remove-index",String(r+1)],h=[...Le(i),"test",t,..._,"--add-json",JSON.stringify(f),...Wj(o)];throw new p(`--set-json cannot change ${c}: a linked test's command is its immutable identity; replace the entry instead`,m.USAGE,{code:"linked_test_command_immutable",...ga(c),recovery:{suggested_retry:L(h),suggested_retry_args:h},nextSteps:["Run the suggested retry: it removes the selected entry and adds the new command in one history-recorded write. It selects the entry by its current command or list position, so list the linked tests again first if another writer may have changed them.",`SDK: runTest(${JSON.stringify(t)}, { ${_[0]==="--remove"?"remove":"removeIndex"}: [...], addJson: [...] }, { path: <the same tracker root> }) with the same values.`]})}function zj(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new p("Linked-test metadata patch must be a JSON object",m.USAGE);let n=Object.keys(t);Vx(t,!1);let r=Object.fromEntries(Object.entries(e).filter(([a])=>gt.includes(a))),s=Ym(ys(JSON.stringify({...r,command:e.command??"legacy-path-only",...Object.fromEntries(Object.entries(t).map(([a,c])=>[a,c===null?void 0:c]))}),"--set-json")[0]);vr(s);let i=n.filter(a=>!Ue(e[a],s[a])),o={...e};for(let a of i){let c=s[a];Object.assign(o,{[a]:c}),c===void 0&&delete o[a]}if(!o.command?.trim()&&!o.path?.trim())throw new p("Linked-test entry must retain a command or path",m.USAGE);return{test:o,fields:i}}async function Yx(e,t,n={}){let r=I(process.cwd(),n.path);await j(r);let s=await C(r),i=G(t.author,s.author_default),o=D(s,F()),a=0,c=[],d=await Lt({pmRoot:r,settings:s,id:e,author:i,op:"tests_update",message:t.message,force:t.force,skipNoop:!0,typeToFolder:o.type_to_folder,resolveHistoryContext:()=>({linked_test_update:{index:a,fields:c}}),mutate(u){let f=u.metadata.tests??[],_=jj(f,t.selector);Kj({id:u.metadata.id,tests:f,index:_,patch:t.patch,global:n,controls:t});let h=zj(f[_],t.patch);return a=_+1,c=h.fields,h.fields.length===0?{changedFields:[]}:(u.metadata.tests=f.map((g,y)=>y===_?{...h.test,updated_by:i,updated_at:O()}:g),{changedFields:["tests"]})}}),l=d.item.tests;return{ok:!0,id:d.item.id,tests:l,count:l.length,changed:d.changedFields.length>0,updated_index:a,updated_fields:c}}var Bj=[{code:"no_projects_matched_filters",regex:/\bNo projects matched the filters\b/i},{code:"no_test_files_found",regex:/\bNo test files found\b/i},{code:"no_tests_found",regex:/\bNo tests found\b/i},{code:"no_matching_tests",regex:/\bNo matching tests?\b/i},{code:"collected_zero_items",regex:/\bcollected 0 items?\b/i},{code:"reported_zero_tests",regex:/^\s*Ran 0 tests? across \d+ files?\./imu},{code:"reported_zero_passes",regex:/(?:^\s*(?:#|ℹ)?\s*tests\s+0\s*$[\s\S]*^\s*(?:#|ℹ)?\s*pass\s+0\s*$|^\s*(?:#|ℹ)?\s*pass\s+0\s*$[\s\S]*^\s*(?:#|ℹ)?\s*tests\s+0\s*$)/imu},{code:"reported_zero_tests",regex:/^\s*(?:#|ℹ)?\s*tests\s+0\s*$/imu}],Hj=[{receiptCode:"reported_tests",regex:/^\s*(?:#|ℹ)?\s*tests\s+[1-9]\d*\s*$/imu},{receiptCode:"reported_passes",regex:/^\s*(?:#|ℹ)?\s*pass\s+[1-9]\d*\s*$/imu},{receiptCode:"tests_passed",regex:/\bTests?\s+[1-9]\d*\s+passed\b/iu},{receiptCode:"passed_count",regex:/\b[1-9]\d*\s+passed\b/iu},{receiptCode:"tests_summary",regex:/\bTests:\s+(?:.*\b)?[1-9]\d*\s+passed\b/iu},{receiptCode:"bun_pass_count",regex:/^\s*[1-9]\d* pass\s*$/imu},{receiptCode:"bun_executed_tests",regex:/^\s*Ran [1-9]\d* tests? across \d+ files?\./imu}];function ya(e,t){let n=`${e}
|
|
21
|
+
${t}`;for(let r of Bj)if(r.regex.test(n))return{code:r.code};return null}function Jx(e,t){for(let[n,r]of[["stdout",e],["stderr",t]]){let s=Hj.find(i=>i.regex.test(r));if(s)return{code:s.receiptCode,stream:n}}}function Xx(e,t){return{trackerPath:e.path?.trim()||(process.env.PM_PATH?.trim()?t:void 0),noExtensions:e.noExtensions}}function Qx(e,t={}){let n=t.trackerPath?.trim();return L(["test",e,"--list",...t.noExtensions===!0?["--no-extensions"]:[],...n?["--pm-path",n]:[]],t.platform)}function Zx(e,t,n,r,s){if((t.measure?.length??0)===0||s.some(o=>o.phase!=="setup"&&typeof o.stdout=="string"&&o.failure_category!=="spawn_error"&&o.failure_category!=="empty_run"&&ya(o.stdout,o.stderr??"")===null))return;let i=["--pm-path",r,...n.noExtensions?["--no-extensions"]:[],...n.author?["--author",n.author]:[],"test",e,"--list","--json"];throw new p("--measure requires an executed linked test",m.USAGE,{code:"test_measure_requires_execution",required:"Execute at least one linked command before recording measurement evidence.",why:"Empty, skipped and pre-execution refused runs cannot support measured evidence.",nextSteps:["Inspect the linked commands, adjust empty selections or missing commands, and resolve any trust refusal before retrying the measurement."],recovery:{suggested_retry:L(i),suggested_retry_args:i}})}function lu(e,t,n,r,s=!1){if((t.measure?.length??0)===0||t.run===!0)return;let i=["--pm-path",r,...n.noExtensions?["--no-extensions"]:[],...n.author?["--author",n.author]:[]],o=[...i,...fh(e,t),...t.list?["--list"]:[],...s?["--background"]:[]],a=t.acknowledgeLinkedTests?[...i,"test",e,"--help"]:o,c=[...i,"test",e,"--acknowledge-linked-tests",...t.author?["--author",t.author]:[]];throw new p("--measure requires --run",m.USAGE,{code:"test_measure_requires_run",flag:"--measure",required:"Run the linked tests with --run to record measurement evidence.",why:"Measurements describe an executed linked-test run; recording them without execution would fabricate evidence.",...t.acknowledgeLinkedTests?{nextSteps:[`Review the linked commands and apply any requested link updates separately before acknowledging trust: ${L([...i,"test",e,"--list"])}`,`After review, acknowledge trust as a separate non-executing operation: ${L(c)}`,`Then run the measurement without --acknowledge-linked-tests: ${L(o)}`]}:{},recovery:{missing:["--run"],suggested_retry:L(a),suggested_retry_args:a}})}function eS(e){if(!/^(?:[^.[\]]+|\[\d+\])(?:\.[^.[\]]+|\[\d+\])*$/u.test(e))return[];let t=[],n=e.matchAll(/[^.[\]]+|\[\d+\]/g);for(let[r]of n){if(r.startsWith("[")&&r.endsWith("]")){let s=Number.parseInt(r.slice(1,-1),10);if(!Number.isSafeInteger(s))return[];t.push(s);continue}t.push(r)}return t}function uu(e,t){let n=t.trim();if(n.length===0)return{found:!1,value:void 0};let r=eS(n);if(r.length===0)return{found:!1,value:void 0};let s=e;for(let i of r){if(typeof s!="object"||s===null)return{found:!1,value:void 0};if(typeof i=="number"&&(!Array.isArray(s)||i>=s.length))return{found:!1,value:void 0};let o=Object.getOwnPropertyDescriptor(s,i);if(!o||!Object.hasOwn(o,"value"))return{found:!1,value:void 0};s=o.value}return{found:!0,value:s}}import{cp as Zj,lstat as eU,mkdir as tU,readlink as nU,realpath as pu,stat as rU,symlink as rS}from"node:fs/promises";import{execFile as sU}from"node:child_process";import V from"node:path";import{promisify as iU}from"node:util";import{execFile as Vj}from"node:child_process";import{readdir as Yj,realpath as Jj}from"node:fs/promises";import Xj from"node:path";import{promisify as Qj}from"node:util";var mu=Qj(Vj),tS=".agents/pm/merge-receipts";async function nS(e,t,n){let r=Xj.join(n,"merge-receipts"),s=(await Yj(r).catch(c=>{if(U(c))return[];throw c})).filter(c=>c.endsWith(".json")),{readIndexedReceiptBlobs:i}=await import("./indexed-receipt-blobs-BPYKN5Q7.js"),o=s.length===0?new Map:await i(e,r,s,Rh,await Jj(r),{failOnReadError:!0}),a={cwd:t,env:Th(),timeout:1e4,maxBuffer:1024*1024,windowsHide:!0};await mu("git",["rm","-q","-r","--cached","--ignore-unmatch","--",tS],a);for(let[c,d]of o){let l=mu("git",["hash-object","-w","--stdin"],a),u=l.child.stdin;u!==null&&(u.on("error",()=>{l.child.kill()}),u.end(d));let f=(await l).stdout.trim();if(!/^(?:[a-f\d]{40}|[a-f\d]{64})$/u.test(f))throw new Error("Invalid snapshot receipt object identity.");await mu("git",["update-index","--add","--cacheinfo","100644",f,`${tS}/${c}`],a)}}var oU=new Set([".agents",".git",".nyc_output",".turbo","coverage"]),wa=iU(sU);async function aU(e,t){let n=await va(V.join(e,".git"));if(!n||n.isDirectory()&&!await va(V.join(e,".git/HEAD")))return!1;let r=Object.fromEntries(Object.entries(process.env).filter(([s])=>!s.toUpperCase().startsWith("GIT_")));await wa("git",["clone","--no-local","--no-checkout","--template=","--origin=origin","--",e,t],{env:r,timeout:12e4,maxBuffer:1024*1024,windowsHide:!0}),await wa("git",["-C",t,"remote","remove","origin"],{env:r,timeout:1e4,windowsHide:!0});try{await wa("git",["-C",t,"rev-parse","--verify","--quiet","HEAD"],{env:r,timeout:1e4,windowsHide:!0})}catch(s){if(s.code===1)return!0;throw s}return await wa("git",["-C",t,"read-tree","HEAD"],{env:r,timeout:1e4,windowsHide:!0}),!0}async function cU(e,t,n,r){await aU(e,t)&&n&&r!==!1&&await nS(e,t,n)}function fu(e){return e.split(V.sep).some(t=>oU.has(t.toLowerCase()))}function Cs(e){return e===".."||e.startsWith(`..${V.sep}`)||V.isAbsolute(e)}async function va(e){try{return await rU(e)}catch(t){if(!U(t))throw t;return}}async function ka(e){let t=[],n=e;for(;V.dirname(n)!==n;)try{return V.join(await pu(n),...t)}catch(r){if(!U(r))throw r;t.unshift(V.basename(n)),n=V.dirname(n)}return V.join(await pu(n),...t)}async function dU(e,t,n){let r=V.relative(t,await ka(e));if(!Cs(r))return r;let s=[],i=e;for(;V.dirname(i)!==i;){let o=await ka(i),a=n.find(([,c])=>c===o);if(a)return V.join(a[0],...s);s.unshift(V.basename(i)),i=V.dirname(i)}return r}async function sS(e,t,n,r){let s=[],i=[],o=await pu(e),a=await ka(V.resolve(t));if(![V.relative(o,a),V.relative(a,o)].every(Cs))throw new Error("Snapshot destination must be disjoint from the source workspace; choose a temporary root outside the checkout.");await tU(V.dirname(t),{recursive:!0}),await cU(o,t,n,r),await Zj(o,t,{recursive:!0,force:!0,async filter(c){let d=V.relative(o,c);if(!d)return!0;if(fu(d))return!1;if(V.basename(c).toLowerCase()==="node_modules"){if((await va(c))?.isDirectory()){let l=await ka(c),u=V.relative(o,l);if(!Cs(V.relative(l,o))||!Cs(u)&&(fu(u)||!u.split(V.sep).some(f=>f.toLowerCase()==="node_modules")))throw new Error(`Dependency symlink must target an included dependency directory or external installation: ${d}`);s.push([d,l])}return!1}return(await eU(c)).isSymbolicLink()?(i.push([d,V.resolve(V.dirname(c),await nU(c)),(await va(c))?.isDirectory()?"junction":"file"]),!1):!0}});for(let[c]of s)await rS(V.resolve(o,c),V.join(t,c),"junction");for(let[c,d,l]of i){let u=await dU(d,o,s);if(Cs(u)||fu(u))throw new Error(`Source symlink must target included workspace source: ${c}`);await rS(V.resolve(t,u),V.join(t,c),l)}}import{execFile as lU}from"node:child_process";import{constants as iS}from"node:fs";import{access as uU,open as mU}from"node:fs/promises";import oS from"node:path";import{promisify as fU}from"node:util";var pU=fU(lU);function _U(e){let t=e.match(/^\s*(?:"([^"\r\n]+)"|'([^'\r\n]+)'|([\w./\\:-]+))(?=\s|$)/u),n=t?.[1]??t?.[2]??t?.[3];return n&&!/[$`%&|<>^;]/u.test(n)?n:void 0}function hU(e,t,n){return process.platform==="win32"?(t===1||t===9009)&&n.split(/\r?\n/u).some(r=>r.trim()===`'${e}' is not recognized as an internal or external command,`):t!==126&&t!==127?!1:n.split(/\r?\n/u).some(r=>t===127&&(r.endsWith(`: ${e}: not found`)||r.endsWith(`: ${e}: command not found`))||t===126&&r.includes(`: ${e}: `)&&r.endsWith(": bad interpreter: No such file or directory"))}async function gU(e,t){let n=e.trim();if(!n||/[\r\n]/u.test(n))return!1;try{let r=await mU(oS.resolve(t,n),iS.O_RDONLY|iS.O_NONBLOCK),s;try{let o=Buffer.alloc(256),{bytesRead:a}=await r.read(o,0,o.length,0);if(s=o.toString("utf8",0,a),a===o.length&&!s.includes(`
|
|
22
|
+
`))return!1}finally{await r.close()}let i=s.match(/^#![ \t]*(\/[^ \t\n]+)(?:[ \t\n]|$)/u)?.[1];if(!i)return!1;try{return await uU(i),!1}catch(o){return Rn(o)}}catch{return!1}}async function aS(e,t,n,r){if(/[;&|<>()`$\r\n]/u.test(e))return!1;let s=_U(e);if(!s||!hU(s,t.exitCode,t.stderr))return!1;let i=process.platform==="win32",o=i?oS.join(n.SystemRoot??"C:\\Windows","System32","where.exe"):"/bin/sh",a=i?[s]:["-c",'command -v "$1"',"pm-linked-test-resolution",s];try{let{stdout:c}=await pU(o,a,{env:n,cwd:r,timeout:1e3,windowsHide:!0});return!i&&gU(c,r)}catch(c){let d=c;if(d.killed||d.signal)return!1;let l=d.code;return l===1||!i&&l===127}}import{spawn as wU}from"node:child_process";import{cp as lS,mkdir as wu,mkdtemp as SS,open as hu,readdir as gu,rm as Rs,symlink as vU}from"node:fs/promises";import{tmpdir as ES}from"node:os";import le from"node:path";var cS=20;function yU(){let e=process.env.PM_TRACKED_TEST_RUN_HISTORY_LIMIT;if(!e||e.trim().length===0)return cS;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<=0?cS:t}function _u(e){let t=[...e].filter(r=>r.run_id.trim().length>0&&r.started_at.trim().length>0&&r.finished_at.trim().length>0&&r.recorded_at.trim().length>0).sort((r,s)=>{let i=Js(r.recorded_at,s.recorded_at);if(i!==0)return i;let o=r.run_id.localeCompare(s.run_id);return o!==0?o:r.kind.localeCompare(s.kind)}),n=yU();return t.length>n?t.slice(t.length-n):t}async function ba(e){await he({pmRoot:e.pmRoot,settings:e.settings,id:e.itemId,op:"test_run_track",author:e.author,message:e.message,force:!1,mutate(t){let n=t.metadata.test_runs??[];return t.metadata.test_runs=_u([...n,e.entry]),{changedFields:["test_runs"]}}})}var dS={taskkillTimeoutMs:null},Ea=20*1024*1024,kU=3e3,bU=1e4,xU=5e3,uS=120,SU=new Set(["locks","extensions","runtime"]),EU=new Set(["history","index","search","extensions","locks","runtime"]),AU=[/eaddrinuse/i,/address already in use/i,/port\s+\d+\s+is already in use/i,/web server[^.\n]*already running/i,/failed to listen on/i],CU=/\b(?:could not|failed to|unable to)\s+acquire\b[^\n.]*\block\b/i,TU=/\b(?:already running|timed?\s*out|timeout|held by another|lock\s+is\s+held)\b/i,RU=new Set(["activity","calendar","context","ctx","deps","get","health","history","list","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","search","stats","test-all","validate"]);function vu(e,t){let n=process.env[e];if(typeof n!="string"||n.trim().length===0)return t;let r=Number.parseInt(n,10);return!Number.isFinite(r)||r<=0?t:r}function IU(){return vu("PM_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS",kU)}function OU(){return vu("PM_LINKED_TEST_HEARTBEAT_INTERVAL_MS",bU)}function LU(){return vu("PM_LINKED_TEST_PIPE_CLOSE_GRACE_MS",xU)}function $U(e){let t=process.env.PM_BACKGROUND_TEST_RUN_ID?.trim();return t&&t.length>0?t:`${e}-local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function NU(e){let t=0,n=0,r=0;for(let s of e){if(s.status==="passed"){t+=1;continue}if(s.status==="failed"||s.status==="refused"){n+=1;continue}r+=1}return{passed:t,failed:n,skipped:r}}function ku(e){let t=0,n=0,r=0,s=0;for(let i of e){let o=i.execution_context;!o||o.is_pm_command!==!0||(t+=1,o.is_pm_tracker_read_command===!0&&(n+=1),o.mismatch_detected===!0&&(r+=1),o.auto_pm_context_applied===!0&&(s+=1))}return{checked_pm_commands:t,tracker_read_commands:n,mismatches:r,auto_remediated:s}}function MU(e){let t=e??"project";if(!Be.includes(t))throw new p(`Invalid scope "${e}"`,m.USAGE);return t}function Ca(e){if(!e)return"schema";let t=e.trim().toLowerCase();if(pn.includes(t))return t;throw new p(`Invalid --pm-context value "${e}". Expected one of: ${pn.join(", ")}`,m.USAGE)}function AS(e){return hn(e??"source","--workspace-context")}function CS(e,t,n){return n?t:hn(e.workspace_context_mode,"linked test")??t}function TS(e,t,n){return n||typeof e.pm_context_mode!="string"||e.pm_context_mode.trim().length===0?t:Ca(e.pm_context_mode)}function RS(e,t){return e==="auto"?t?"tracker":"schema":e}function PU(e){return Object.entries(e).filter(([t])=>t.startsWith("assert_")).some(([,t])=>t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:typeof t=="string"?t.trim().length>0:!0)}function FU(e){let{executionContext:t,runLevelPmContextMode:n,linkedOverridePmContextMode:r}=e;return!t.is_pm_tracker_read_command||!t.mismatch_detected?"":n==="tracker"&&r==="schema"?" Linked test metadata pm_context_mode=schema overrides run-level --pm-context tracker. Set pm_context_mode=tracker (or auto) on the linked test, or remove the override, to run against seeded tracker data.":t.pm_context_mode==="schema"?" Use --auto-pm-context to route PM tracker-read linked commands through seeded tracker data automatically. Alternatively, use --pm-context tracker for the whole run.":""}function DU(e,t){let n={};if(!e)return n;for(let r of e){let s=hs(r,t);if(s)for(let[i,o]of Object.entries(s))n[i]=o}return n}function jU(e,t){if(!e)return[];let n=[];for(let r of e){let s=gs(r,t);s&&n.push(...s)}return[...new Set(n)]}function UU(e){let t=er(e);return dn(t).some(n=>_o(n)!==null)}function IS(e){let t=er(e);return dn(t).some(n=>{let r=_o(n);if(!r)return!1;let s=Jd(r);return s?RU.has(s.subcommand):!1})}function xa(e){if(e)return kv.has(e.subcommand)?Ut(e.args,bv)?.subcommand:e.subcommand}function mS(e,t){if(e==="npx"||e==="bunx")return ln(t)?.command;if(e==="pnpm")return xa(Ut(t,Hd));if(e==="npm")return xa(Ut(t,Vd));if(e==="yarn")return xa(Ut(t,wv));if(e==="bun")return xa(Ut(t,vv))}function Sa(e){return e?e==="vitest"||e==="test"||e.startsWith("test:"):!1}function fS(e){return e.includes("node scripts/run-tests.mjs ")||e.endsWith("node scripts/run-tests.mjs")||e.includes("node ./scripts/run-tests.mjs ")||e.endsWith("node ./scripts/run-tests.mjs")}function bu(e){let t=e.split(" ").filter(o=>o.length>0),n=ho(t);if(n.length===0)return!1;let[r,...s]=n,i=Xd.get(r);if(i){let o=s.findIndex(a=>i.test(a));return o>=0&&bu(s.slice(o+1).join(" "))}return r==="vitest"||r.endsWith("/vitest")||r.endsWith("/vitest.mjs")?!0:r==="node"?GU(s):qU(r,s)}function GU(e){return e.includes("--test")||e.some(t=>t==="vitest"||t==="vitest.mjs"||t.endsWith("/vitest")||t.endsWith("/vitest.mjs"))}function qU(e,t){return e==="npx"||e==="bunx"?Sa(ln(t)?.command):e==="pnpm"||e==="npm"?Sa((e==="pnpm"?go(t):yo(t))?.command)||Sa(mS(e,t)):(e==="yarn"||e==="bun")&&Sa(mS(e,t))}function F8(e){let t=er(e),n=dn(t),r=n.some(i=>!fS(i)&&bu(i)),s=n.some(fS);return{accepted:!0,command_kind:r?"direct_runner":s?"sandbox_runner":"other",tracker_isolation:"runtime_injected",trust_boundary:"provenance",advisory:r?"Accepted with runtime-injected tracker isolation. Prefer the repository sandbox runner when available for reproducible build and coverage setup.":"Accepted with runtime-injected tracker isolation and provenance checks before execution."}}function WU(e){if(Zd(e))return'Linked test command skipped: Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.'}function KU(e){return e?e.map(zU):[]}function zU(e){let t=e.trim(),n=Lm(t)?Vs(ee(e,"--add"),"--add"):{command:t},r=ve(n.command);if(!r)throw new p("--add requires command=<value> or a bare command (path=<value> is optional metadata)",m.USAGE);return os(r),{command:r,path:ve(n.path),scope:MU(n.scope),timeout_seconds:BU(ve(n.timeout_seconds),ve(n.timeout)),pm_context_mode:Do(ve(n.pm_context_mode),"--add"),workspace_context_mode:hn(ve(n.workspace_context_mode),"--add"),env_set:hs(ve(n.env_set),"--add"),env_clear:gs(ve(n.env_clear),"--add"),shared_host_safe:Fo(ve(n.shared_host_safe),"--add","shared_host_safe"),assert_stdout_contains:gn(ve(n.assert_stdout_contains)),assert_stdout_regex:ir(ve(n.assert_stdout_regex),"--add","assert_stdout_regex"),assert_stderr_contains:gn(ve(n.assert_stderr_contains)),assert_stderr_regex:ir(ve(n.assert_stderr_regex),"--add","assert_stderr_regex"),assert_stdout_min_lines:jo(ve(n.assert_stdout_min_lines),"--add"),assert_json_field_equals:Uo(ve(n.assert_json_field_equals),"--add"),assert_json_field_gte:Go(ve(n.assert_json_field_gte),"--add"),note:ve(n.note),phase:rr(n.phase,"--add")}}function ve(e){let t=e?.trim();return t&&t.length>0?t:void 0}function BU(e,t){if(e&&t&&e!==t)throw new p("--add timeout and timeout_seconds must match when both are provided",m.USAGE);let n=e??t;if(n===void 0)return;let r=Math.floor(we(n,"timeout_seconds"));if(r<=0)throw new p("--add timeout_seconds must be a positive integer",m.USAGE);return r}function HU(e){return e?e.flatMap(t=>{let n=ys(t,"--add-json");for(let r of n){let s=r.command;if(!s)throw new p("--add-json requires a non-empty command string",m.USAGE);os(s)}return n}):[]}function VU(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new p("--remove requires command or path value",m.USAGE);let r=/^(command|path)\s*=/i.exec(n);if(r){let s=n.slice(r[0].length).trim();if(!s)throw new p("--remove requires a non-empty command=<value> or path=<value>",m.USAGE);return{kind:r[1].toLowerCase(),value:s}}if(/^[A-Za-z_][\w-]*=\S+$/u.test(n))throw new p("--remove structured selectors require command=<value> or path=<value>",m.USAGE);if(/^(?:[-*+]\s+)?(?:path|command)\s*:/i.test(n)||n.startsWith("```")){let s=ee(n,"--remove"),i=s.path!==void 0?"path":"command",o=s.path??s.command;if(!o?.trim())throw new p("--remove requires command=<value> and/or path=<value>",m.USAGE);return{kind:i,value:o.trim()}}return{kind:"either",value:n}}):[]}function YU(e){return e?[...new Set(e.map(t=>{let n=typeof t=="number"?t:Number.parseInt(t,10);if(!Number.isInteger(n)||n<1||String(n)!==String(t).trim())throw new p("--remove-index must be a positive integer",m.USAGE);return n}))]:[]}function JU(e){try{e.stdin?.end()}catch{}}function OS(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length<=uS?t:`${t.slice(0,uS-3)}...`}function LS(e){return e==="off"?!1:e==="always"?!0:process.stderr.isTTY===!0}function yu(e){try{process.stderr.write(`${e}
|
|
23
|
+
`)}catch{}}function XU(e,t){if(!LS(t))return null;let n=OS(e.command),r=Date.now();yu(`[pm test] linked-test ${e.index}/${e.total} start timeout_ms=${e.timeoutMs} command="${n}"`);let s=setInterval(()=>{let i=Date.now()-r;yu(`[pm test] linked-test ${e.index}/${e.total} running elapsed_ms=${i} command="${n}"`)},OU());return s.unref?.(),s}function QU(e,t,n,r){if(!LS(r))return;let s=OS(e.command),i=Date.now()-n,a=t.timedOut||t.maxBufferExceeded||t.exitCode!==0?"failed":"passed",c=[];t.timedOut&&c.push("reason=timeout"),t.maxBufferExceeded&&c.push("reason=max_buffer"),t.outputTruncated&&c.push("output=truncated"),t.signal&&c.push(`signal=${t.signal}`);let d=t.exitCode===null?"null":String(t.exitCode),l=c.length>0?` ${c.join(" ")}`:"";yu(`[pm test] linked-test ${e.index}/${e.total} end status=${a} exit_code=${d} elapsed_ms=${i}${l} command="${s}"`)}function ZU(e){e.heartbeat&&clearInterval(e.heartbeat),e.timedOutTimer&&(clearTimeout(e.timedOutTimer),e.timedOutTimer=null),e.forceKillTimer&&(clearTimeout(e.forceKillTimer),e.forceKillTimer=null)}function e1(e,t){let n=!1;return async()=>{if(n)return;n=!0;let r=e.pid,s={alive:()=>e.exitCode===null&&e.signalCode===null,kill:()=>{e.exitCode===null&&e.signalCode===null&&e.kill("SIGKILL")}};if(!r||r<=0){try{e.kill("SIGTERM")}catch{}return}if(process.platform==="win32"){await Lc(r,s,dS);return}try{process.kill(-r,"SIGTERM")}catch{try{e.kill("SIGTERM")}catch{}}t.forceKillTimer=setTimeout(()=>{Lc(r,s,dS)},IU()),t.forceKillTimer.unref?.()}}function t1(e){return new Promise(t=>{let n=!1,r=null,s=(i,o=!1)=>{n||(n=!0,r&&(clearTimeout(r),r=null),o&&(e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy()),t(i))};e.on("exit",(i,o)=>{n||(r=setTimeout(()=>{s({code:i,signal:o},!0)},LU()),r.unref?.())}),e.on("close",(i,o)=>{s({code:i,signal:o})})})}function n1(e,t,n,r,s){return wU(e,{cwd:s,env:t,shell:!0,windowsHide:!0,detached:process.platform!=="win32",stdio:["pipe",n,r]})}async function pS(e){let t=await hu(e,"r");try{let n=(await t.stat()).size,r=Math.min(n,Ea),s=Buffer.alloc(r);return r>0&&await t.read(s,0,r,0),{text:s.toString("utf8"),truncated:n>Ea}}finally{await t.close()}}async function r1(e,t,n,r,s,i=process.cwd()){let o=Date.now(),a=await SS(le.join(ES(),"pm-linked-test-output-"));try{let c=le.join(a,"stdout.log"),d=le.join(a,"stderr.log"),[l,u]=await Promise.all([hu(c,"w"),hu(d,"w")]),f;try{f=n1(e,n,l.fd,u.fd,i)}catch($){throw await Promise.all([l.close(),u.close()]),$}let _=t1(f),h;f.on("error",$=>{h=$.message}),await Promise.all([l.close(),u.close()]),JU(f);let g={heartbeat:XU(r,s),forceKillTimer:null,timedOutTimer:null},y=e1(f,g),w=!1;g.timedOutTimer=setTimeout(()=>{w=!0,y()},t),g.timedOutTimer.unref?.();let{code:v,signal:S}=await _;ZU(g);let[b,k]=await Promise.all([pS(c),pS(d)]),A=b.truncated||k.truncated,x=A?`
|
|
24
|
+
[pm linked-test output truncated at ${Ea} bytes per stream; the child process continued to completion]
|
|
25
|
+
`:"";!h&&await aS(e,{exitCode:v,stderr:k.text},n,i)&&(h="Linked test executable was not found. Install the tool or update the linked command before retrying.");let E={stdout:`${b.text}${x}`,stderr:k.text,exitCode:v,signal:S,timedOut:w,maxBufferExceeded:!1,outputTruncated:A,spawnError:h};return QU(r,E,o,s),E}finally{await Rs(a,{recursive:!0,force:!0})}}function s1(e,t){let n=[];e.maxBufferExceeded&&n.push(`Linked test output exceeded maxBuffer=${Ea} bytes. Reduce output volume or split the command.`),e.timedOut&&t>0&&n.push(`Linked test timed out after ${t}ms.`);let r=e.signal?`Linked test command terminated by signal ${e.signal}.`:void 0,s=e.spawnError?.trim()||r||"Linked test command failed.";return n.length===0?s:`${s} ${n.join(" ")}`}function i1(e){let t=[e.spawnError??"",e.stderr,e.stdout].join(`
|
|
26
|
+
`);return AU.some(n=>n.test(t))||t.split(/\r?\n/u).some(n=>CU.test(n)&&TU.test(n))}function o1(e){return i1(e)?"infra_collision":e.timedOut?"timeout":e.maxBufferExceeded?"max_buffer":e.spawnError?"spawn_error":e.signal?"signal":"assertion_failure"}function _S(e,t){for(let[n,r]of Object.entries(t.env_set))_n.has(n.toUpperCase())||(e[n]=r);for(let n of t.env_clear)_n.has(n.toUpperCase())||delete e[n]}function a1(e){e.PORT===void 0&&(e.PORT="0"),e.HOST===void 0&&(e.HOST="127.0.0.1"),e.PM_SHARED_HOST_SAFE===void 0&&(e.PM_SHARED_HOST_SAFE="1"),e.PLAYWRIGHT_HTML_OPEN===void 0&&(e.PLAYWRIGHT_HTML_OPEN="never"),e.PW_TEST_HTML_REPORT_OPEN===void 0&&(e.PW_TEST_HTML_REPORT_OPEN="never")}function c1(e,t){let n={...e.env_set,...t.env_set},r=[...new Set([...e.env_clear,...t.env_clear??[]])],s=t.shared_host_safe??e.shared_host_safe;return{env_set:n,env_clear:r,shared_host_safe:s}}function $S(e,t,n){return{env_set:DU(e,"--env-set"),env_clear:jU(t,"--env-clear"),shared_host_safe:n===!0}}async function Ts(e,t,n=!1,r=wu){if(await se(e))try{await Cr("seed_linked_test",async()=>{if(await r(le.dirname(t),{recursive:!0}),n){await lS(e,t,{recursive:!0,force:!0});return}await lS(e,t,{force:!0})},{why:"Linked tests need an isolated PM context without mutating the source tracker.",nextSteps:["Reclaim capacity on the filesystem that hosts the linked-test temporary directory."]})}catch(s){if(typeof s=="object"&&s!==null&&"code"in s&&U(s))return;throw s}}async function hS(e,t,n,r=!1){for(let[s,i]of[[n.projectPmRoot,e],[n.globalPmRoot,t]])if(r){let o=await Q(Oe(s));if(o!==null){let a=await C(i);await sc({pmRoot:i,filePath:Oe(i),raw:o,op:"settings:write",author:G(void 0,a.author_default),lockTtlSeconds:a.locks.ttl_seconds,lockWaitMs:a.locks.wait_ms,recordCreation:!0,message:"Seed linked-test schema settings history"})}}else await Ts(Oe(s),Oe(i));await Ts(le.join(n.projectPmRoot,"extensions"),le.join(e,"extensions"),!0),await Ts(le.join(n.globalPmRoot,"extensions"),le.join(t,"extensions"),!0)}async function gS(e,t){if(!await se(e))return;let n=await gu(e,{withFileTypes:!0});for(let r of n){if(SU.has(r.name))continue;let s=le.join(e,r.name),i=le.join(t,r.name);if(r.isDirectory()){await Ts(s,i,!0);continue}r.isFile()&&await Ts(s,i)}}async function yS(e,t){let n=await Q(Oe(e));if(n===null||await se(Tr(e)))return;let r=await C(t);await Rs(Tr(t),{force:!0}),await Rs(Oe(t),{force:!0}),await sc({pmRoot:t,filePath:Oe(t),raw:n,op:"settings:write",author:G(void 0,r.author_default),lockTtlSeconds:r.locks.ttl_seconds,lockWaitMs:r.locks.wait_ms,recordCreation:!0,message:"Seed linked-test tracker settings history"})}async function ur(e){if(!await se(e))return 0;let t=0,n=await gu(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||EU.has(r.name))continue;let s=le.join(e,r.name),i;try{i=await gu(s,{withFileTypes:!0})}catch{continue}for(let o of i)o.isFile()&&Ht.some(a=>o.name.toLowerCase().endsWith(a))&&(t+=1)}return t}function d1(e){let t=typeof e.exitCode=="number"?e.exitCode:1;return(e.timedOut||e.maxBufferExceeded)&&t===0?1:t}function l1(e){let t=e.trim();if(t==="true")return!0;if(t==="false")return!1;if(t==="null")return null;let n=Number(t);if(t.length>0&&Number.isFinite(n))return n;if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t)}catch{}return t}function u1(e,t){return typeof e=="object"&&e!==null&&typeof t=="object"&&t!==null?Ue(e,t):Object.is(e,t)}function m1(e,t,n){let r=[];r.push(...wS("stdout",t,e.assert_stdout_contains)),r.push(...vS("stdout",t,e.assert_stdout_regex)),r.push(...wS("stderr",n,e.assert_stderr_contains)),r.push(...vS("stderr",n,e.assert_stderr_regex)),r.push(...f1(t,e.assert_stdout_min_lines));let s=e.assert_json_field_equals??{},i=e.assert_json_field_gte??{};if(!(Object.keys(s).length>0||Object.keys(i).length>0))return r;let a;try{a=JSON.parse(t)}catch(c){return r.push(`stdout is not valid JSON for assert_json_field_* checks: ${c instanceof Error?c.message:String(c)}`),r}for(let[c,d]of Object.entries(s)){let l=uu(a,c);if(!l.found){r.push(`assert_json_field_equals missing path "${c}"`);continue}let u=l1(d);u1(l.value,u)||r.push(`assert_json_field_equals mismatch at "${c}" (expected=${JSON.stringify(u)} actual=${JSON.stringify(l.value)})`)}for(let[c,d]of Object.entries(i)){let l=uu(a,c);if(!l.found){r.push(`assert_json_field_gte missing path "${c}"`);continue}if(typeof l.value!="number"||!Number.isFinite(l.value)){r.push(`assert_json_field_gte path "${c}" resolved to non-numeric value`);continue}l.value<d&&r.push(`assert_json_field_gte failed at "${c}" (expected >= ${d}, actual ${l.value})`)}return r}function wS(e,t,n){let r=[];for(let s of n??[])t.includes(s)||r.push(`${e} missing required text: "${s}"`);return r}function vS(e,t,n){let r=[];for(let s of n??[])try{new RegExp(s,"m").test(t)||r.push(`${e} failed regex assertion: /${s}/m`)}catch(i){r.push(`${e} regex assertion is invalid: /${s}/ (${i instanceof Error?i.message:String(i)})`)}return r}function f1(e,t){if(typeof t!="number")return[];let n=e.split(/\r?\n/).map(r=>r.trim()).filter(r=>r.length>0).length;return n<t?[`stdout line count ${n} is below required minimum ${t}`]:[]}function p1(e){let t=er(e);return/(?:^|\s)(?:--test-name-pattern|--testnamepattern)(?:=|\s)/u.test(t)?!0:dn(t).some(n=>/(?:^|\s)-t(?:=|\s)/u.test(n)&&bu(n))}function _1(e){return{root:e,schemaProjectPmPath:le.join(e,"schema","project",".agents","pm"),schemaGlobalPmPath:le.join(e,"schema","global"),trackerProjectPmPath:le.join(e,"tracker","project",".agents","pm"),trackerGlobalPmPath:le.join(e,"tracker","global"),workspaceSnapshotRoot:le.join(e,"workspace","project"),workspaceIsolatedRoot:le.join(e,"workspace","isolated")}}function h1(e,t,n){return e.some(r=>CS(r,t,n)==="snapshot")}async function g1(e,t){let n=le.join(e,".agents"),r=le.join(n,"pm");await wu(n,{recursive:!0}),await Rs(r,{recursive:!0,force:!0}),await vU(t,r,process.platform==="win32"?"junction":"dir")}async function y1(e,t=$c,n=!0){let r={defaults:!0,agentGuidance:"skip"};await t(void 0,{path:e.schemaProjectPmPath},r),await t(void 0,{path:e.schemaGlobalPmPath},r),n&&(await t(void 0,{path:e.trackerProjectPmPath},r),await t(void 0,{path:e.trackerGlobalPmPath},r))}async function w1(e,t,n){t&&(await hS(e.schemaProjectPmPath,e.schemaGlobalPmPath,t,!0),n&&(await hS(e.trackerProjectPmPath,e.trackerGlobalPmPath,t),await gS(t.projectPmRoot,e.trackerProjectPmPath),await gS(t.globalPmRoot,e.trackerGlobalPmPath),await yS(t.projectPmRoot,e.trackerProjectPmPath),await yS(t.globalPmRoot,e.trackerGlobalPmPath)))}function v1(e,t,n){return e.some(r=>{let s=r.command??"",i=s.length>0&&IS(s),o=n?.autoPmContext===!0&&i?"auto":TS(r,t,n?.overrideLinkedPmContext===!0);return RS(o,i)==="tracker"})}async function k1(e,t){return{sourceProjectItemCount:t?await ur(t.projectPmRoot):0,sourceGlobalItemCount:t?await ur(t.globalPmRoot):0,schemaProjectItemCount:await ur(e.schemaProjectPmPath),schemaGlobalItemCount:await ur(e.schemaGlobalPmPath),trackerProjectItemCount:await ur(e.trackerProjectPmPath),trackerGlobalItemCount:await ur(e.trackerGlobalPmPath)}}function b1(e){let t=e.effectivePmContextMode==="tracker",n=t?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath,r=t?e.layout.trackerGlobalPmPath:e.layout.schemaGlobalPmPath,s=t?e.counts.trackerProjectItemCount:e.counts.schemaProjectItemCount,i=t?e.counts.trackerGlobalItemCount:e.counts.schemaGlobalItemCount,o=e.workspaceContextMode==="snapshot"?e.layout.workspaceSnapshotRoot:e.workspaceContextMode==="isolated"?e.layout.workspaceIsolatedRoot:e.sourceWorkspaceRoot,a=e.workspaceContextMode==="isolated"?"":o;return{requested_pm_context_mode:e.requestedPmContextMode,pm_context_mode:e.effectivePmContextMode,auto_pm_context_applied:e.autoPmContextApplied,is_pm_command:e.isPmCommand,is_pm_tracker_read_command:e.isPmTrackerReadCommand,source_project_pm_path:e.sourceRoots?.projectPmRoot??"",sandbox_project_pm_path:n,source_global_pm_path:e.sourceRoots?.globalPmRoot??"",sandbox_global_pm_path:r,source_project_item_count:e.counts.sourceProjectItemCount,sandbox_project_item_count:s,source_global_item_count:e.counts.sourceGlobalItemCount,sandbox_global_item_count:i,mismatch_detected:e.isPmCommand&&(e.counts.sourceProjectItemCount!==s||e.counts.sourceGlobalItemCount!==i),project_extensions_seeded:!!e.sourceRoots,global_extensions_seeded:!!e.sourceRoots,requested_workspace_context_mode:e.requestedWorkspaceContextMode,workspace_context_mode:e.workspaceContextMode,working_directory:o,source_workspace_root:a,trust:e.trust}}async function x1(e){let t=typeof e.linkedTest.pm_context_mode=="string"&&e.linkedTest.pm_context_mode.trim().length>0?Ca(e.linkedTest.pm_context_mode):void 0,n=typeof e.linkedTest.command=="string"&&e.linkedTest.command.length>0?e.linkedTest.command:void 0,r=n?UU(n):!1,s=r&&n?IS(n):!1,i=e.options?.autoPmContext===!0&&s,o=i?"auto":TS(e.linkedTest,e.runLevelPmContextMode,e.options?.overrideLinkedPmContext===!0),a=RS(o,s),c=a==="tracker"?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath;e.workspaceContextMode==="snapshot"&&await g1(e.layout.workspaceSnapshotRoot,c);let d=e.options?.pmRoot?await rl(e.options.pmRoot,e.linkedTest,e.currentSourceRef):await rl(e.layout.root,e.linkedTest,e.currentSourceRef);return{linkedOverridePmContextMode:t,executionContext:b1({layout:e.layout,counts:e.counts,sourceRoots:e.sourceRoots,isPmCommand:r,isPmTrackerReadCommand:s,requestedPmContextMode:o,effectivePmContextMode:a,autoPmContextApplied:i,requestedWorkspaceContextMode:e.requestedWorkspaceContextMode,workspaceContextMode:e.workspaceContextMode,sourceWorkspaceRoot:e.sourceWorkspaceRoot,trust:d})}}function kS(e,t,n){return{command:e.command,path:e.path,status:"skipped",execution_context:t,error:n}}function S1(e,t,n,r){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"assertion_failure",execution_context:t,...r?{stdout:r.stdout,stderr:r.stderr}:{},error:n}}function E1(e,t,n){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"trust_refusal",execution_context:t,error:n}}function A1(e){if(e.executionContext.trust.trusted)return null;let t=e.options?.allowUntrustedLinkedTests===!0,n=e.options?.untrustedLinkedTestsPolicyEnabled===!0;if(t&&n)return null;let r=n?"Retry with --allow-untrusted-linked-tests for this invocation, or acknowledge the current commands with --acknowledge-linked-tests.":"Set testing.allow_untrusted_linked_tests=true, then retry with --allow-untrusted-linked-tests; alternatively acknowledge the current commands with --acknowledge-linked-tests.";return E1(e.linkedTest,e.executionContext,`Linked test command is not trusted by this clone (source_ref=${e.executionContext.trust.source_ref??"unknown"}, current_ref=${e.executionContext.trust.current_source_ref??"unknown"}). ${r}`)}function C1(e){if(!e.linkedTest.command)return kS(e.linkedTest,e.executionContext,"No command configured for this linked test.");let t=WU(e.linkedTest.command);return t?kS(e.linkedTest,e.executionContext,t):null}function T1(e){return e.executionContext.pm_context_mode!=="none"?null:e.executionContext.workspace_context_mode==="source"?Aa(e.linkedTest,e.executionContext,"pm_context_mode=none requires workspace_context_mode=isolated or snapshot so implicit tracker discovery cannot reach the source workspace."):e.executionContext.is_pm_command?Aa(e.linkedTest,e.executionContext,"pm_context_mode=none is for self-isolating SDK tests; direct PM commands require schema, tracker, or auto context."):null}function Aa(e,t,n){return{command:e.command,path:e.path,status:"refused",exit_code:null,failure_category:"config_refusal",execution_context:t,error:n}}function R1(e){let t=e.executionContext.pm_context_mode==="schema"&&e.executionContext.is_pm_tracker_read_command&&e.executionContext.mismatch_detected,n=e.options?.failOnContextMismatch===!0&&e.executionContext.is_pm_command&&e.executionContext.mismatch_detected;if(!t&&!n)return null;let r=FU({executionContext:e.executionContext,runLevelPmContextMode:e.runLevelPmContextMode,linkedOverridePmContextMode:e.linkedOverridePmContextMode}),s=e.options?.checkContext===!0?"Linked test preflight PM context mismatch detected":"Linked test PM context mismatch detected";return Aa(e.linkedTest,e.executionContext,`${s} (source_project_items=${e.executionContext.source_project_item_count}, sandbox_project_items=${e.executionContext.sandbox_project_item_count}).${r}`)}function I1(e){let t=C1(e);if(t)return t;let n=A1(e);if(n)return n;let r=T1(e);if(r)return r;let s=R1(e);return s||(e.options?.requireAssertionsForPm===!0&&e.executionContext.is_pm_command&&!PU(e.linkedTest)?Aa(e.linkedTest,e.executionContext,"Linked PM command requires assertions when --require-assertions-for-pm is enabled."):null)}function O1(e){let t=c1(e.runtimeDirectives,e.linkedTest),n={...process.env,SENTRY_ENVIRONMENT:"test"};return _S(n,e.runtimeDirectives),_S(n,{env_set:e.linkedTest.env_set??{},env_clear:e.linkedTest.env_clear??[]}),t.shared_host_safe&&a1(n),n.FORCE_COLOR="0",e.executionContext.pm_context_mode==="none"?delete n.PM_PATH:n.PM_PATH=e.executionContext.sandbox_project_pm_path,n.PM_GLOBAL_PATH=e.executionContext.sandbox_global_pm_path,e.executionContext.workspace_context_mode!=="source"&&(delete n.PM_BUILD_CONSUMER_LEASE,delete n.PM_BUILD_CONSUMER_LEASE_ROOT),e.executionContext.workspace_context_mode==="isolated"?(delete n.PM_SOURCE_WORKSPACE_ROOT,delete n.PM_SOURCE_PM_PATH,delete n[jr]):(n.PM_SOURCE_WORKSPACE_ROOT=e.executionContext.source_workspace_root,n.PM_SOURCE_PM_PATH=e.executionContext.workspace_context_mode==="snapshot"?e.executionContext.sandbox_project_pm_path:e.executionContext.source_project_pm_path,n[jr]="read_only"),n}function L1(e,t,n,r){return{command:e.command,path:e.path,status:"passed",exit_code:0,execution_context:t,stdout:n.stdout,stderr:n.stderr,...r?{execution_receipt:r}:{}}}function bS(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:1,failure_category:"empty_run",execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:`Linked test reported an empty test run (${e.emptyRunSignal.code}). Update the test selection so at least one test executes; unfiltered commands may opt out by omitting --fail-on-empty-test-run.`}}function $1(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:d1(e.execution),failure_category:o1(e.execution),execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:s1(e.execution,e.timeoutMs)}}function N1(e){let t=Jx(e.execution.stdout,e.execution.stderr),n=e.linkedTest.phase!=="setup"&&p1(e.linkedTest.command??"");if(e.options?.failOnEmptyTestRun===!0||n){let s=ya(e.execution.stdout,e.execution.stderr);if(s)return bS({...e,emptyRunSignal:s});if(n&&!t)return bS({...e,emptyRunSignal:{code:"missing_positive_execution_receipt"}})}let r=m1(e.linkedTest,e.execution.stdout,e.execution.stderr);return r.length>0?S1(e.linkedTest,e.executionContext,`Linked test assertion(s) failed: ${r.join("; ")}`,e.execution):L1(e.linkedTest,e.executionContext,e.execution,t)}async function M1(e){let t=e.linkedTest.command??"",n=(e.linkedTest.timeout_seconds??e.defaultTimeoutSeconds??120)*1e3,r=await r1(t,n,O1(e),{index:e.index+1,total:e.total,timeoutMs:n,command:t},e.progressMode,e.executionContext.working_directory);return r.exitCode===0&&!r.timedOut&&!r.maxBufferExceeded?N1({...e,execution:r}):$1({...e,execution:r,timeoutMs:n})}async function xu(e,t,n){let r=$o(e);for(let y of r)wr(y.command);let s=[],i=await SS(le.join(ES(),"pm-linked-test-")),o=_1(i),a=Ca(n?.pmContext),c=AS(n?.workspaceContext),d=n?.progress===!0?"always":"auto",l=$S(n?.envSet,n?.envClear,n?.sharedHostSafe),u=n?.sourceRoots,f=ds(),_=v1(r,a,n),h=h1(r,c,n?.overrideLinkedWorkspaceContext===!0),g=await cs(f);try{await y1(o,$c,_),await wu(o.workspaceIsolatedRoot,{recursive:!0}),await w1(o,u,_),h&&await sS(f,o.workspaceSnapshotRoot,u?.projectPmRoot,_);let y=await k1(o,u),w=_s(),v=k=>CS(k,c,n?.overrideLinkedWorkspaceContext===!0),S=new Set(r.filter(k=>!Te(k)).map(v)),b=async(k,A)=>{let x=w.options(k,n),E=v(k),$=Yk(k,E,S);if($)return $;let P=await x1({linkedTest:k,layout:o,counts:y,sourceRoots:u,runLevelPmContextMode:a,options:n,requestedWorkspaceContextMode:c,workspaceContextMode:E,currentSourceRef:g,sourceWorkspaceRoot:f});return I1({linkedTest:k,executionContext:P.executionContext,runLevelPmContextMode:a,linkedOverridePmContextMode:P.linkedOverridePmContextMode,options:x})??await M1({linkedTest:k,index:A,total:r.length,defaultTimeoutSeconds:t,runtimeDirectives:l,progressMode:d,executionContext:P.executionContext,options:x})};for(let k=0;k<r.length;k+=1){let A=r[k];s.push(w.blocked(A)??w.record(A,await b(A,k)))}}finally{await Rs(o.root,{recursive:!0,force:!0,maxRetries:3,retryDelay:100})}return s}function P1(e,t){let n=[...t];return e.filter(r=>{let s=n.findIndex(i=>kr(i,r));return s>=0&&n.splice(s,1),s<0}).length}async function F1(e){let{id:t,pmRoot:n,settings:r,typeToFolder:s}=e,i=await Y(n,t,r.id_prefix,r.item_format,s);if(!i)throw new p(`Item ${t} not found`,m.NOT_FOUND);let o=await fe(i,{schema:r.schema});return{itemId:i.id,tests:o.document.metadata.tests??[],testRuns:o.document.metadata.test_runs??[],changed:!1,removed:0}}function D1(e,t){let n=[...e];for(let r of t)n.some(s=>kr(s,r))||n.push(r);return n}function j1(e,t,n){if(t.length===0&&n.length===0)return{tests:e,removed:0};let r=new Set(n),s=e.filter((i,o)=>r.has(o+1)?!1:!t.some(a=>a.kind==="command"?i.command===a.value:a.kind==="path"?i.path===a.value:i.command===a.value||i.path===a.value));return{tests:s,removed:e.length-s.length}}function U1(e,t,n,r){return j1(D1(e,t),n,r)}function G1(e){return[e.timeout!==void 0,e.progress===!0,(e.envSet?.length??0)>0,(e.envClear?.length??0)>0,e.sharedHostSafe===!0,e.pmContext!==void 0,e.overrideLinkedPmContext===!0,e.failOnContextMismatch===!0,e.failOnSkipped===!0,e.failOnEmptyTestRun===!0,e.requireAssertionsForPm===!0,e.checkContext===!0,e.fullOutput===!0,e.autoPmContext===!0,e.workspaceContext!==void 0,e.overrideLinkedWorkspaceContext===!0,e.allowUntrustedLinkedTests===!0].some(Boolean)}function NS(e){if(G1(e)&&e.run!==!0)throw new p("--timeout, --progress, --env-set, --env-clear, --shared-host-safe, --pm-context, --override-linked-pm-context, --workspace-context, --override-linked-workspace-context, --allow-untrusted-linked-tests, --fail-on-context-mismatch, --fail-on-skipped, --fail-on-empty-test-run, --require-assertions-for-pm, --check-context, --full-output, and --auto-pm-context require --run",m.USAGE);if(e.acknowledgeLinkedTests===!0&&e.run===!0)throw new p("--acknowledge-linked-tests records trust without executing commands; run it separately before --run",m.USAGE);if((e.match!==void 0||e.onlyIndex!==void 0||e.onlyLast===!0)&&e.run!==!0)throw new p("--match, --only-index, and --only-last require --run",m.USAGE)}async function q1(e){let{id:t,options:n,pmRoot:r,settings:s,typeToFolder:i,adds:o,removes:a,removeIndexes:c}=e;if(o.length===0&&a.length===0&&c.length===0)return F1({id:t,pmRoot:r,settings:s,typeToFolder:i});let d=0,l=[],u=await he({pmRoot:r,settings:s,id:t,op:o.length>0?"tests_add":"tests_remove",author:G(n.author,s.author_default),message:n.message,force:n.force,skipNoop:!0,mutate(_){let h=_.metadata.tests??[],g=U1(h,o,a,c);if(Ya(()=>MS(n,g.tests)),d=g.removed,(a.length>0||c.length>0)&&d===0)throw new p("No linked tests matched the requested removal selector",m.NOT_FOUND,{code:"linked_test_remove_no_match",unmatched:[...a.map(y=>`${y.kind}=${y.value}`),...c.map(y=>`index=${y}`)],required:"List linked tests and retry with an exact command/path or a current 1-based --remove-index.",examples:[`pm test ${t} --list`,`pm test ${t} --remove-index 1`]});return _.metadata.tests=g.tests,l=h,{changedFields:Ue(h,g.tests)?[]:["tests"]}}}),f=u.item.tests??[];return{itemId:u.item.id,tests:f,testRuns:u.item.test_runs??[],changed:u.changedFields.length>0,removed:d,written:u.changedFields.length>0?hd(l,f):[],storedRemoved:P1(l,f)}}function MS(e,t){let n=Ca(e.pmContext);AS(e.workspaceContext),$S(e.envSet,e.envClear,e.sharedHostSafe);let r={match:e.match,onlyIndex:e.onlyIndex===void 0?void 0:lr(e.onlyIndex),onlyLast:e.onlyLast},s=e.timeout===void 0?void 0:we(e.timeout,"--timeout");if(s!==void 0&&s<=0)throw new p(`--timeout must be a positive number (got "${e.timeout}")`,m.USAGE);NS(e);let i=e.run===!0?Vk(zx(t,r),t):void 0;if(i)for(let o of i.selected)wr(o.command);return{defaultTimeoutSeconds:s,pmContextMode:n,runSelection:i,testsToRun:i?.selected??t}}async function W1(e){let{options:t,runOptions:n,pmRoot:r}=e;return t.run!==!0?[]:await xu(n.testsToRun,n.defaultTimeoutSeconds,{progress:t.progress,envSet:t.envSet,envClear:t.envClear,sharedHostSafe:t.sharedHostSafe,pmContext:n.pmContextMode,overrideLinkedPmContext:t.overrideLinkedPmContext,failOnContextMismatch:t.failOnContextMismatch,failOnEmptyTestRun:t.failOnEmptyTestRun===!0||(t.measure?.length??0)>0,requireAssertionsForPm:t.requireAssertionsForPm,checkContext:t.checkContext,autoPmContext:t.autoPmContext,workspaceContext:t.workspaceContext,overrideLinkedWorkspaceContext:t.overrideLinkedWorkspaceContext,pmRoot:r,allowUntrustedLinkedTests:t.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:e.untrustedLinkedTestsPolicyEnabled,sourceRoots:{projectPmRoot:r,globalPmRoot:Xe(process.cwd())}})}function K1(e,t){let n=[];if(e.run===!0&&e.checkContext===!0){let r=ku(t);n.push(`context_preflight:checked_pm_commands=${r.checked_pm_commands};tracker_read_commands=${r.tracker_read_commands};mismatches=${r.mismatches};auto_remediated=${r.auto_remediated}`)}return n}function z1(e){let t=NU(e.runResults),n=Number.parseInt(process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim()??"",10),r=process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM?.trim(),s=O(),i=Ss(e.options.measure,s);return{run_id:$U("test"),kind:"test",status:t.failed>0||e.failOnSkippedTriggered?"failed":"passed",started_at:e.runStartedAt,finished_at:s,recorded_at:s,attempt:Number.isFinite(n)&&n>=1?n:void 0,resumed_from:r&&r.length>0?r:void 0,passed:t.passed,failed:t.failed,skipped:t.skipped,fail_on_skipped_triggered:e.failOnSkippedTriggered?!0:void 0,measurements:i.length>0?i:void 0,executions:e.runResults.filter(o=>o.command?.trim()).slice(0,32).map(o=>({command:o.command.trim(),requested_pm_context_mode:o.execution_context?.requested_pm_context_mode,pm_context_mode:o.execution_context?.pm_context_mode,workspace_context_mode:o.execution_context?.workspace_context_mode,trust_reason:o.execution_context?.trust.reason}))}}async function B1(e){let{options:t,pmRoot:n,settings:r,itemId:s,runStartedAt:i,runResults:o,failOnSkippedTriggered:a,warnings:c}=e;if(t.run!==!0||!i)return;let d=z1({options:t,runStartedAt:i,runResults:o,failOnSkippedTriggered:a});if(r.testing.record_results_to_items!==!0)return{entry:d,receipt:{recorded:!1,reason:"tracking_disabled",run_id:d.run_id,recovery_command:"pm config project set test-result-tracking --policy enabled"}};try{return await ba({pmRoot:n,settings:r,itemId:s,author:G(t.author,r.author_default),message:`Track test run summary (${d.run_id})`,entry:d}),{entry:d,receipt:{recorded:!0,reason:"recorded",run_id:d.run_id}}}catch(l){if(tn(l))throw l;return c.push(`test_result_tracking_failed:${s}:${l instanceof Error?l.message:String(l)}`),{entry:d,receipt:{recorded:!1,reason:"write_failed",run_id:d.run_id}}}}function xS(e,t,n){let r;if(e.metricBelow!==void 0){let s=e.metricBelow.indexOf("="),i=e.metricBelow.slice(0,s).trim(),o=e.metricBelow.slice(s+1).trim(),a=Number(o);if(s<=0||i.length===0||o.length===0||!Number.isFinite(a))throw new p("--metric-below must use name=value",m.USAGE);r=Ix(t,i,a)}return{measurements:n?.measurements,metric_below:r,metric_diff:e.metricDiff===void 0?void 0:Ox(t,e.metricDiff)}}async function H1(e,t,n){if(e.acknowledgeLinkedTests===!0)return Rv(t,n,O())}function V1(e){let{item:t,runResults:n,failureCategories:r,runSelection:s,failOnSkippedTriggered:i,warnings:o,recording:a,measurementProjection:c,restoreScope:d}=e,l=J1(t,e.fullHistory),u=Y1(t,s,l,d),{counts:f,receipts:_}=Ji(l);return{ok:n.every(h=>h.status!=="failed"&&h.status!=="refused")&&i!==!0,id:t.itemId,tests:u.tests,...u.omitted,run_results:n,...e.ran?{failure_categories:r}:{},selection:s?{selector:s.selector,requested:s.requested,selected_indexes:s.selected_indexes,selected_count:s.selected_count,skipped_count:s.skipped_count,...s.setup_indexes?{setup_indexes:s.setup_indexes}:{}}:void 0,fail_on_skipped_triggered:i?!0:void 0,warnings:o.length>0?o:void 0,changed:t.changed||a?.receipt.recorded===!0,...a?{evidence_recording:a.receipt}:{},count:u.count,...t.removed>0?{removed:t.removed}:{},...f,...c,..._}}function Y1(e,t,n,r){return n!==void 0?{tests:n.entries,count:n.returned_count,omitted:{}}:t!==void 0&&t.selector!==null&&t.skipped_count>0?{tests:t.selected,count:e.tests.length,omitted:{tests_omitted:{count:e.tests.length-t.selected.length,restore_with:Qx(e.itemId,r)}}}:{tests:e.tests,count:e.tests.length,omitted:{}}}function J1(e,t){if(e.written!==void 0)return ns({collectionKey:"tests",stored:e.tests,written:e.written,removedCount:e.storedRemoved,fullHistory:t})}function X1(e,t){let n=e.tests[e.updated_index-1],r=ns({collectionKey:"tests",stored:e.tests,written:e.changed&&n!==void 0?[n]:[],removedCount:0,fullHistory:t}),{counts:s,receipts:i}=Ji(r);return{...e,tests:r.entries,run_results:[],count:r.returned_count,...s,...i}}async function PS(e,t,n){let r=Bx(t);if(r){Hx(t),NS(t),lu(e,t,n,I(process.cwd(),n.path));let P=await Yx(e,{...r,author:t.author,message:t.message,force:t.force},n);return X1(P,t.fullHistory===!0)}let s=Tn(),i=I(process.cwd(),n.path);await j(i);let o=await C(i);lu(e,t,n,i),Ss(t.measure,"validation"),xS(t,[],void 0);let a=D(o,F()),c=await s.resolveList(t.add,"--add"),d=await s.resolveList(t.addJson,"--add-json"),l=await s.resolveList(t.remove,"--remove"),u=[...KU(c),...HU(d)],f=await tr(u,G(t.author,o.author_default),O())??[],_=VU(l),h=YU(t.removeIndex),g=await q1({id:e,options:t,pmRoot:i,settings:o,typeToFolder:a.type_to_folder,adds:f,removes:_,removeIndexes:h}),y=Ya(()=>MS(t,g.tests)),w=await H1(t,i,g.tests),v=t.run===!0?O():void 0,S=await W1({options:t,runOptions:y,pmRoot:i,untrustedLinkedTestsPolicyEnabled:o.testing.allow_untrusted_linked_tests});Zx(e,t,n,i,S);let b=sr(S),k=t.run===!0&&t.failOnSkipped===!0&&S.some(P=>P.status==="skipped"),A=K1(t,S);w&&A.push(`linked_test_trust_acknowledged:${w.acknowledged}`);let x=await B1({options:t,pmRoot:i,settings:o,itemId:g.itemId,runStartedAt:v,runResults:S,failOnSkippedTriggered:k,warnings:A}),E=x?.receipt.recorded?_u([...g.testRuns,x.entry]):g.testRuns,$=xS(t,E,x?.entry);return V1({item:g,runResults:S,failureCategories:b,runSelection:y.runSelection,failOnSkippedTriggered:k,warnings:A,recording:x,measurementProjection:$,restoreScope:Xx(n,i),ran:t.run===!0,fullHistory:t.fullHistory===!0})}var Q1=(e,t)=>{if(e===void 0)return;let n=ce(e,t);if(!n){let r=t.definitions.map(s=>s.id);throw new p(`Invalid --status value "${e}". Allowed: ${r.join(", ")}`,m.USAGE)}return n},Z1=e=>{if(e===void 0)return;let t=we(e,"timeout");if(t<=0)throw new p("timeout must be a positive number",m.USAGE);return t},FS=(e,t)=>{if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<0)throw new p(`${t} must be a non-negative integer`,m.USAGE);return n},eG=e=>e instanceof Error?e.message:String(e),tG=()=>{let e=process.env.PM_BACKGROUND_TEST_RUN_ID?.trim();return e&&e.length>0?e:`test-all-local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`},nG=e=>e.trim().replaceAll(/\s+/g," "),rG=e=>!e||Object.keys(e).length===0?"{}":JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))),sG=e=>!e||e.length===0?"[]":JSON.stringify([...e].sort((t,n)=>t.localeCompare(n))),iG=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"none"},oG=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"source"},Ta=e=>[...new Set(e??[])].sort((t,n)=>t.localeCompare(n)),DS=e=>Object.fromEntries(Object.entries(e??{}).sort(([t],[n])=>t.localeCompare(n))),aG=e=>typeof e=="number"?e:void 0,cG=e=>{let t={assert_stdout_contains:Ta(e.assert_stdout_contains),assert_stdout_regex:Ta(e.assert_stdout_regex),assert_stderr_contains:Ta(e.assert_stderr_contains),assert_stderr_regex:Ta(e.assert_stderr_regex),assert_stdout_min_lines:aG(e.assert_stdout_min_lines),assert_json_field_equals:DS(e.assert_json_field_equals),assert_json_field_gte:DS(e.assert_json_field_gte)};return JSON.stringify(t)},dG=e=>{let t=Eu(e.command);return t!==void 0?`command:${e.scope}:${nG(t)}`:`path:${e.scope}:${Eu(e.path)??""}`},Su=e=>{let t=rG(e.env_set),n=sG(e.env_clear),r=iG(e.pm_context_mode),s=oG(e.workspace_context_mode),i=e.shared_host_safe===!0?"true":"false",o=cG(e);return`${dG(e)}:${t}:${n}:${r}:${s}:${i}:${o}`},lG=(e,t)=>t===void 0?e:e===void 0||t>e?t:e,uG=e=>{let t=0,n=0,r=0;for(let s of e){if(s.status==="passed"){t+=1;continue}if(s.status==="failed"||s.status==="refused"){n+=1;continue}r+=1}return{passed:t,failed:n,skipped:r}},mG=(e,t)=>{for(let[n,r]of Object.entries(t))e[n]+=r},Ra=(e,t)=>{if(e.progress===!0)try{process.stderr.write(`[pm test-all] ${t}
|
|
27
|
+
`)}catch{}},fG=async(e,t,n)=>{let r=[],s=0;for(let i of e){let o=await PS(i.id,{run:!1},{...t,path:n});s+=o.tests.length,r.push({item:i,tests:o.tests})}return{itemTests:r,linkedTests:s}},pG=async e=>{let t=z(e.settings.schema),n=D(e.settings,F()),r=Q1(e.options.status,t),s=FS(e.options.limit,"--limit"),i=FS(e.options.offset,"--offset")??0,a=(await Ae(e.pmRoot,e.settings.item_format,n.type_to_folder,void 0,e.settings.schema)).filter(d=>r?d.status===r:!0).sort((d,l)=>d.id.localeCompare(l.id));return{filteredItems:s===void 0?a.slice(i):a.slice(i,i+s),statusFilter:r,limitFilter:s,offsetFilter:i}},jS=e=>{let t=e.filter(Te).map(({provenance:n,provenance_invalid:r,updated_by:s,updated_at:i,note:o,timeout_seconds:a,...c})=>c);return t.length===0?"":Z(t)},US=(e,t)=>t.length===0?Su(e):`${Su(e)}:setup[${t}]`,_G=e=>{let t=new Map;for(let{tests:n}of e){let r=jS(n);for(let s of n){if(Te(s))continue;let i=US(s,r);if(!t.has(i)){t.set(i,s.timeout_seconds);continue}t.set(i,lG(t.get(i),s.timeout_seconds))}}return t};function hG(e,t){try{wr(e.command);return}catch(n){if(!(n instanceof p)||n.code!=="linked_test_command_not_executable")throw n;return{command:e.command,path:e.path,status:"refused",exit_code:null,failure_category:"config_refusal",error:`Linked test refused for ${t}: ${n.message}`}}}var gG=(e,t)=>{let n=[],r=[],s=$o(e.tests),i=jS(s),o=_s();return{plans:s.map(c=>{let d=Te(c),l=d?Su(c):US(c,i),u=o.blocked(c);if(u)return{test:c,key:l,duplicate:!1,refusal:u};let f=hG(c,e.item.id);if(f)return{test:c,key:l,duplicate:!1,refusal:o.record(c,f)};if(d)return n.push(c),{test:c,key:l,duplicate:!1,refusal:void 0};if(t.seenTestKeys.has(l))return{test:c,key:l,duplicate:!0,refusal:void 0};t.seenTestKeys.add(l),r.push(l);let _=t.effectiveTimeoutByKey.get(l);return n.push(_===void 0?c:{...c,timeout_seconds:_}),{test:c,key:l,duplicate:!1,refusal:void 0}}),testsToRun:n,reservedKeys:r}},yG=(e,t,n)=>{if(e.some(r=>r.phase==="setup"&&r.status!=="passed"))for(let r of t)n.seenTestKeys.delete(r)},wG=async(e,t)=>{let{plans:n,testsToRun:r,reservedKeys:s}=gG(e,t),i=r.length>0?await xu(r,t.defaultTimeoutSeconds,{progress:t.options.progress,sourceRoots:t.sourceRoots,envSet:t.options.envSet,envClear:t.options.envClear,sharedHostSafe:t.options.sharedHostSafe,pmContext:t.options.pmContext,overrideLinkedPmContext:t.options.overrideLinkedPmContext,failOnContextMismatch:t.options.failOnContextMismatch,failOnEmptyTestRun:t.options.failOnEmptyTestRun,requireAssertionsForPm:t.options.requireAssertionsForPm,checkContext:t.options.checkContext,autoPmContext:t.options.autoPmContext,workspaceContext:t.options.workspaceContext,overrideLinkedWorkspaceContext:t.options.overrideLinkedWorkspaceContext,pmRoot:t.pmRoot,allowUntrustedLinkedTests:t.options.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:t.settings.testing.allow_untrusted_linked_tests}):[];yG(i,s,t);let o=0,a=_s(),c=n.map(({test:f,key:_,duplicate:h,refusal:g})=>{if(g)return a.blocked(f)??g;if(!h){let y=i[o];return o+=1,a.blocked(f)??a.record(f,y)}return a.blocked(f)??{command:f.command,path:f.path,status:"skipped",error:`Duplicate linked test skipped (key=${_}).`}}),d=uG(c),l=sr(c),u=await bG(e,d,c,t);return{passed:d.passed,failed:d.failed,skipped:d.skipped,trackingWarnings:u,failureCategories:l,result:{ok:d.failed===0&&!(t.options.failOnSkipped===!0&&d.skipped>0),id:e.item.id,status:e.item.status,test_count:e.tests.length,passed:d.passed,failed:d.failed,skipped:d.skipped,run_results:c,failure_categories:l}}},vG=(e,t)=>[e.failed>0,t.failOnSkipped===!0&&e.skipped>0].includes(!0),kG=e=>e?!0:void 0,bG=async(e,t,n,r)=>{if(!r.trackingEnabled)return[];try{let s=vG(t,r.options);await ba({pmRoot:r.pmRoot,settings:r.settings,itemId:e.item.id,author:r.trackingAuthor,message:`Track test-all run summary (${r.trackingRunId})`,entry:{run_id:r.trackingRunId,kind:"test-all",status:s?"failed":"passed",started_at:r.runStartedAt,finished_at:O(),recorded_at:O(),attempt:r.trackingAttempt,resumed_from:r.trackingResumedFrom,passed:t.passed,failed:t.failed,skipped:t.skipped,items:1,linked_tests:e.tests.length,fail_on_skipped_triggered:kG(r.options.failOnSkipped===!0&&t.skipped>0),executions:n.filter(i=>i.command?.trim()).slice(0,32).map(i=>({command:i.command.trim(),requested_pm_context_mode:i.execution_context?.requested_pm_context_mode,pm_context_mode:i.execution_context?.pm_context_mode,workspace_context_mode:i.execution_context?.workspace_context_mode,trust_reason:i.execution_context?.trust.reason}))}})}catch(s){return tn(s)?(r.revisionConflicts.push(s),[]):[`test_result_tracking_failed:${e.item.id}:${eG(s)}`]}return[]},xG=()=>{let e=process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim(),t=e?Number.parseInt(e,10):Number.NaN;return Number.isFinite(t)&&t>=1?t:void 0},Eu=e=>{let t=e?.trim();return t&&t.length>0?t:void 0},SG=e=>({pmRoot:e.pmRoot,settings:e.settings,options:e.options,defaultTimeoutSeconds:e.defaultTimeoutSeconds,sourceRoots:{projectPmRoot:e.pmRoot,globalPmRoot:Xe(process.cwd())},seenTestKeys:new Set,effectiveTimeoutByKey:_G(e.itemTests),trackingEnabled:e.settings.testing.record_results_to_items===!0,trackingAuthor:G(e.options.author,e.settings.author_default),trackingRunId:tG(),trackingAttempt:xG(),trackingResumedFrom:Eu(process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM),runStartedAt:e.runStartedAt,revisionConflicts:[]}),EG=(e,t,n)=>{let r={results:[],passed:0,failed:0,skipped:0,failureCategories:sr([]),trackingWarnings:[]},s=e.failOnEmptyTestRun===!0&&t===0;return s&&(r.failed+=1,r.failureCategories.empty_run+=1,r.trackingWarnings.push(`empty_linked_test_selection:items=${n.length};linked_tests=0;fail_on_empty_test_run=true`)),{accumulation:r,failOnEmptyTestRunTriggered:s}},AG=async(e,t,n)=>{for(let[s,i]of e.entries()){Ra(t.options,`item ${s+1}/${e.length} start id=${i.item.id} linked_tests=${i.tests.length}`);let o=await wG(i,t);mG(n.failureCategories,o.failureCategories),n.passed+=o.passed,n.failed+=o.failed,n.skipped+=o.skipped,n.trackingWarnings.push(...o.trackingWarnings),n.results.push(o.result),Ra(t.options,`item ${s+1}/${e.length} end id=${i.item.id} status=${o.failed===0?"passed":"failed"} passed=${o.passed} failed=${o.failed} skipped=${o.skipped}`)}let[r]=t.revisionConflicts;if(r!==void 0)throw r},CG=(e,t)=>{if(e.checkContext!==!0)return;let n=t.results.flatMap(s=>s.run_results),r=ku(n);t.trackingWarnings.push(`context_preflight:checked_pm_commands=${r.checked_pm_commands};tracker_read_commands=${r.tracker_read_commands};mismatches=${r.mismatches};auto_remediated=${r.auto_remediated}`)},TG=e=>({ok:e.ok,totals:{items:e.filteredItems.length,linked_tests:e.linkedTests,passed:e.accumulation.passed,failed:e.accumulation.failed,skipped:e.accumulation.skipped,failure_categories:e.accumulation.failureCategories},failed:e.accumulation.failed,passed:e.accumulation.passed,skipped:e.accumulation.skipped,fail_on_skipped_triggered:e.failOnSkippedTriggered?!0:void 0,fail_on_empty_test_run_triggered:e.failOnEmptyTestRunTriggered?!0:void 0,warnings:e.accumulation.trackingWarnings.length>0?e.accumulation.trackingWarnings:void 0,results:e.accumulation.results}),RG=e=>[`selection items=${e.filteredItems.length}`,`linked_tests=${e.linkedTests}`,e.statusFilter===void 0?"":`status=${e.statusFilter}`,e.limitFilter===void 0?"":`limit=${e.limitFilter}`,e.offsetFilter>0?`offset=${e.offsetFilter}`:""].filter(t=>t.length>0).join(" "),IG=async(e,t)=>{let n=I(process.cwd(),t.path);await j(n);let r=await C(n),s=await pG({pmRoot:n,settings:r,options:e}),i=Z1(e.timeout),o=O(),a=await fG(s.filteredItems,t,n);return Ra(e,RG({...s,linkedTests:a.linkedTests})),{pmRoot:n,settings:r,filteredItems:s.filteredItems,itemTests:a.itemTests,linkedTests:a.linkedTests,defaultTimeoutSeconds:i,runStartedAt:o}},OG=e=>{let t=e.options.failOnSkipped===!0&&e.accumulation.skipped>0,n=![e.accumulation.failed>0,t,e.failOnEmptyTestRunTriggered].includes(!0);return{failOnSkippedTriggered:t,ok:n}},oQ=async(e,t)=>{let n=await IG(e,t),{accumulation:r,failOnEmptyTestRunTriggered:s}=EG(e,n.linkedTests,n.filteredItems),i=SG({pmRoot:n.pmRoot,settings:n.settings,options:e,itemTests:n.itemTests,defaultTimeoutSeconds:n.defaultTimeoutSeconds,runStartedAt:n.runStartedAt});await AG(n.itemTests,i,r),CG(e,r);let o=OG({options:e,accumulation:r,failOnEmptyTestRunTriggered:s});return Ra(e,`end status=${o.ok?"passed":"failed"} items=${n.filteredItems.length} linked_tests=${n.linkedTests} passed=${r.passed} failed=${r.failed} skipped=${r.skipped}`),TG({ok:o.ok,filteredItems:n.filteredItems,linkedTests:n.linkedTests,accumulation:r,failOnSkippedTriggered:o.failOnSkippedTriggered,failOnEmptyTestRunTriggered:s})};import aq from"node:os";import mr from"node:fs/promises";import{spawn as zS}from"node:child_process";import{createHash as LG,randomBytes as $G}from"node:crypto";import Is from"node:path";var BS=new Set(["queued","running"]),Ru=new Set(["passed","failed","stopped","canceled"]),NG=3e3,MG=3e3,PG=3e4,HS=100,GS=100;function VS(){return Date.now()}function YS(e){return e.map(t=>t.trim()).filter(t=>t.length>0)}function FG(e){let t=e.join(" ").replaceAll(/\s+/g," ").trim();return t.length<=180?t:`${t.slice(0,177)}...`}function DG(){let e=Date.now().toString(36),t=$G(3).toString("hex");return`tr-${e}-${t}`}function jG(e,t,n){let r={kind:e,command:YS(t),pm_root:Is.resolve(n)};return LG("sha256").update(JSON.stringify(r)).digest("hex")}function fr(e){if(!Number.isInteger(e)||!e||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)==="EPERM"}}async function UG(e){await Rt(bm(e)),await Rt(Ka(e)),await Rt(xm(e)),await Rt(Sm(e)),await Rt(Cm(e))}async function JS(e,t){try{let n=JSON.parse(e);if(!n||typeof n!="object"||typeof n.id!="string")throw new Error("invalid run record payload");return n}catch(n){throw new p(`Failed to parse background test run record at ${t}: ${n instanceof Error?n.message:String(n)}`,m.GENERIC_FAILURE)}}async function ft(e,t){let n={...t,updated_at:O()};await Ge(za(e,t.id),`${JSON.stringify(n,null,2)}
|
|
28
|
+
`)}async function pr(e,t){let n=za(e,t),r=await Q(n);return r?JS(r,n):null}async function GG(e){let t=Ka(e);return await se(t)?(await mr.readdir(t,{withFileTypes:!0})).filter(r=>r.isFile()&&r.name.endsWith(".json")).map(r=>Is.join(t,r.name)).sort((r,s)=>s.localeCompare(r)):[]}function qG(e){let t=e.match(/^VmRSS:\s+(\d+)\s+kB$/m);if(t)return Number.parseInt(t[1],10)*1024}async function WG(e){if(process.platform==="linux")try{let t=await mr.readFile(`/proc/${e}/status`,"utf8");return qG(t)}catch{return}}function KG(e){let t=e.lastIndexOf(")");if(t<0)return{};let r=e.slice(t+2).trim().split(/\s+/),s=Number.parseInt(r[11],10),i=Number.parseInt(r[12],10);return!Number.isFinite(s)||!Number.isFinite(i)?{}:{cpu_user_seconds:s/GS,cpu_system_seconds:i/GS}}async function zG(e){if(process.platform!=="linux")return{};try{let t=await mr.readFile(`/proc/${e}/stat`,"utf8");return KG(t)}catch{return{}}}async function Cu(e){let t=e.child_pid??e.worker_pid;if(!fr(t))return;let n=await WG(t),r=await zG(t),s=e.started_at?Date.parse(e.started_at):Number.NaN,i=Number.isFinite(s)?Math.max(0,(VS()-s)/1e3):void 0;return{recorded_at:O(),rss_bytes:n,cpu_user_seconds:r.cpu_user_seconds,cpu_system_seconds:r.cpu_system_seconds,uptime_seconds:i}}function Au(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function BG(e,t){if(!t||typeof t!="object")return{summary:{passed:0,failed:1,skipped:0},parsedResult:null};let n=t;if(e==="test-all"){let a=n.totals??{};return{summary:{items:typeof a.items=="number"?a.items:void 0,linked_tests:typeof a.linked_tests=="number"?a.linked_tests:void 0,passed:Au(a.passed),failed:Au(a.failed),skipped:Au(a.skipped),fail_on_skipped_triggered:n.fail_on_skipped_triggered===!0?!0:void 0},parsedResult:t}}let r=Array.isArray(n.run_results)?n.run_results:[],s=0,i=0,o=0;for(let a of r){if(!a||typeof a!="object")continue;let c=a.status;if(c==="passed"){s+=1;continue}if(c==="failed"||c==="refused"){i+=1;continue}o+=1}return{summary:{passed:s,failed:i,skipped:o,fail_on_skipped_triggered:n.fail_on_skipped_triggered===!0?!0:void 0},parsedResult:t}}function HG(e){let t=e.trim();if(t.length===0)return null;let n=t.match(/\[pm test-all\]\s+item\s+(\d+)\/(\d+)\s+(start|end)\s+id=([^\s]+)/i);if(n){let d=Number.parseInt(n[1],10),l=Number.parseInt(n[2],10);return{item_index:d,item_total:l,item_id:n[4],linked_test_index:void 0,linked_test_total:void 0,current_command:void 0,elapsed_ms:void 0,heartbeat_at:O(),phase:n[3]?.toLowerCase()==="end"?"finished":"running"}}let r=t.match(/\[pm test\]\s+linked-test\s+(\d+)\/(\d+)\s+(start|running|end)(?:.*elapsed_ms=(\d+))?/i);if(!r)return null;let s=Number.parseInt(r[1],10),i=Number.parseInt(r[2],10),o=r[4]?Number.parseInt(r[4],10):void 0,a=t.match(/\scommand="((?:\\.|[^"\\])*)"/),c=a?a[1].replaceAll('\\"','"').replaceAll("\\\\","\\"):void 0;return{linked_test_index:s,linked_test_total:i,current_command:c,elapsed_ms:Number.isFinite(o)?o:void 0,heartbeat_at:O(),phase:r[3]?.toLowerCase()==="end"?"finished":"running"}}function VG(e){return e.split(/\r?\n/).map(t=>t.trimEnd()).filter(t=>t.length>0)}function Tu(e,t){if(t<=0)return[];let n=VG(e);return n.length<=t?n:n.slice(n.length-t)}async function XS(e){let t=process.env.PM_BACKGROUND_CLI_ENTRY?.trim();if(t&&t.length>0){let s=Is.resolve(e,t);if(await se(s))return s}let n=Is.resolve(e,"dist","cli.js");if(await se(n))return n;let r=process.argv[1]?.trim();if(r&&r.length>0){let s=Is.resolve(e,r);if(await se(s))return s}throw new p("Unable to resolve a CLI entrypoint for background test runs. Build the project or set PM_BACKGROUND_CLI_ENTRY.",m.GENERIC_FAILURE)}async function Os(e,t){if(!BS.has(t.status)||fr(t.worker_pid)||t.finished_at)return t;let r={...t,status:"failed",finished_at:O(),error:t.error??"Background test run worker exited before writing terminal status."};return await ft(e,r),r}async function Iu(e){await UG(e.pmRoot);let t=YS(e.commandArgs);if(t.length===0)throw new p("Background test run requires command arguments.",m.USAGE);let n=jG(e.kind,t,e.pmRoot),r=await Lu(e.pmRoot,{});for(let l of r){let u=await Os(e.pmRoot,l);if(u.fingerprint===n&&!(!BS.has(u.status)||!fr(u.worker_pid)))return{started:!1,run:{...u,duplicate_of:u.id},duplicate_of:u.id}}let s=DG(),i=O(),o=Em(e.pmRoot,s),a=Am(e.pmRoot,s),c=Tm(e.pmRoot,s);await mr.writeFile(o,"","utf8"),await mr.writeFile(a,"","utf8");let d={id:s,kind:e.kind,status:"queued",created_at:i,updated_at:i,requested_by:e.requestedBy,fingerprint:n,command_args:t,command_label:FG(t),pm_root:e.pmRoot,global_pm_root:e.globalPmRoot,target_id:e.targetId,status_filter:e.statusFilter,attempt:typeof e.attempt=="number"&&Number.isFinite(e.attempt)&&e.attempt>=1?Math.floor(e.attempt):1,resumed_from:e.resumedFrom,resumed_by:e.resumedBy,stdout_path:o,stderr_path:a,result_path:c,progress:{phase:"queued",message:"Queued for background execution.",heartbeat_at:i}};return await ft(e.pmRoot,d),{started:!0,run:d}}async function Ou(e){let t=await pr(e.pmRoot,e.runId);if(!t)throw new p(`Background test run ${e.runId} not found`,m.NOT_FOUND);if(Ru.has(t.status))throw new p(`Background test run ${t.id} is already terminal (${t.status}).`,m.CONFLICT);let n=await XS(process.cwd()),r=[];e.noExtensions===!0&&r.push("--no-extensions"),r.push("--path",t.pm_root,"test-runs-worker",t.id);let s={...process.env,PM_PATH:t.pm_root,PM_GLOBAL_PATH:t.global_pm_root,PM_BACKGROUND_TEST_RUN_ID:t.id,PM_BACKGROUND_TEST_RUN_ATTEMPT:String(t.attempt),PM_BACKGROUND_TEST_RUN_RESUMED_FROM:t.resumed_from??"",FORCE_COLOR:"0"},i=zS(process.execPath,[n,...r],{cwd:process.cwd(),env:s,detached:!0,stdio:"ignore",windowsHide:!0});i.unref();let o={...t,status:"queued",worker_pid:i.pid,progress:{phase:"queued",message:"Worker process started.",heartbeat_at:O()}};return await ft(e.pmRoot,o),o}async function qS(e,t,n){await e,await mr.appendFile(t,n,"utf8")}function QS(e,t){let n=Number.parseInt(process.env[e]??"",10);return Number.isFinite(n)&&n>0?n:t}function YG(e){return{...process.env,PM_PATH:e.pm_root,PM_GLOBAL_PATH:e.global_pm_root,FORCE_COLOR:"0"}}function JG(e,t){return t?["--no-extensions",...e.command_args]:[...e.command_args]}function XG(e,t){let n=Promise.resolve();return{schedule(){n=n.then(async()=>{try{await ft(e,t)}catch{}})},async flush(){await n}}}function WS(e,t){try{e.kill(t)}catch{}}async function QG(e,t,n,r){if(n.stopRequested)return;n.stopRequested=!0,e.stop_requested_at=O(),e.progress={...e.progress,phase:"stopping",message:"Stop requested for background run.",heartbeat_at:O()},r(),WS(t,"SIGTERM"),setTimeout(()=>WS(t,"SIGKILL"),QS("PM_BACKGROUND_RUN_FORCE_KILL_DELAY_MS",MG)).unref?.()}function ZG(e,t,n){return{phase:n,message:e,heartbeat_at:O(),item_index:t.item_index,item_total:t.item_total,item_id:t.item_id,linked_test_index:void 0,linked_test_total:void 0,current_command:void 0,elapsed_ms:void 0}}function eq(e,t,n,r){return{phase:r,message:e,heartbeat_at:O(),item_index:n.item_index??t.progress?.item_index,item_total:n.item_total??t.progress?.item_total,item_id:n.item_id??t.progress?.item_id,linked_test_index:n.linked_test_index,linked_test_total:n.linked_test_total,current_command:n.current_command,elapsed_ms:n.elapsed_ms}}function KS(e,t,n){let r=HG(t);if(!r)return!1;let s=e.progress?.phase==="stopping"?"stopping":"running";return e.progress=r.item_id?ZG(t,r,s):eq(t,e,r,s),r.phase==="finished"&&!n&&(e.progress.phase="running"),!0}function tq(e){if(e.trim().length===0)return null;try{return JSON.parse(e)}catch{return null}}function nq(e,t,n){return n?"stopped":e===0&&t.failed===0&&t.fail_on_skipped_triggered!==!0?"passed":"failed"}function rq(e,t){return{phase:"finished",message:t?"Background run stopped.":`Background run finished with status=${e.status}.`,heartbeat_at:O(),item_index:e.progress?.item_index,item_total:e.progress?.item_total,item_id:e.progress?.item_id,linked_test_index:e.progress?.linked_test_index,linked_test_total:e.progress?.linked_test_total,current_command:e.progress?.current_command,elapsed_ms:e.progress?.elapsed_ms}}async function sq(e,t,n){if(t!==null){await Ge(e.result_path,`${JSON.stringify(t,null,2)}
|
|
29
|
+
`);return}await Ge(e.result_path,`${JSON.stringify({parse_error:"Background run output was not valid JSON.",stdout_excerpt:Tu(n,HS)},null,2)}
|
|
30
|
+
`)}async function ZS(e,t,n=!1){let r=await pr(e,t);if(!r)throw new p(`Background test run ${t} not found`,m.NOT_FOUND);let s={...r,status:"running",started_at:r.started_at??O(),worker_pid:process.pid,progress:{phase:"running",message:"Worker started.",heartbeat_at:O()}},i=await XS(process.cwd()),o=YG(s);await ft(e,s);let a=JG(s,n),c=zS(process.execPath,[i,...a],{cwd:process.cwd(),env:o,detached:!1,stdio:["ignore","pipe","pipe"],windowsHide:!0});s.child_pid=c.pid;let d=XG(e,s),l=d.schedule,u=Promise.resolve(),f=Promise.resolve(),_="",h="",g={stopRequested:!1},y=()=>{QG(s,c,g,l)};process.on("SIGTERM",y),process.on("SIGINT",y);let w=setInterval(()=>{(async()=>(s.resource=await Cu(s),s.progress.heartbeat_at=O(),l()))()},QS("PM_BACKGROUND_RUN_RESOURCE_INTERVAL_MS",NG));w.unref?.(),c.stdout?.on("data",x=>{let E=x.toString("utf8");_+=E,u=qS(u,s.stdout_path,E)}),c.stderr?.on("data",x=>{let E=x.toString("utf8");f=qS(f,s.stderr_path,E),h+=E;let $=h.split(/\r?\n/);h=$.pop();let P=!1;for(let R of $){let T=R.trimEnd();T.length>0&&KS(s,T,g.stopRequested)&&(P=!0)}P&&l()});let v=null,S=null;try{({code:v,signal:S}=await new Promise(x=>{c.on("close",(E,$)=>{x({code:E,signal:$})})}))}finally{clearInterval(w),process.off("SIGTERM",y),process.off("SIGINT",y)}await u,await f;let b=h.trimEnd();b.length>0&&KS(s,b,g.stopRequested)&&l(),h="";let k=tq(_),A=BG(s.kind,k);return s.summary=A.summary,s.exit_code=typeof v=="number"?v:void 0,s.signal=S??void 0,s.finished_at=O(),s.status=nq(s.exit_code,A.summary,g.stopRequested),s.progress=rq(s,g.stopRequested),s.resource=await Cu(s),await sq(s,k,_),await ft(e,s),await d.flush(),s}async function Lu(e,t){let n=await GG(e),r=[];for(let c of n){let d=await Q(c);if(!d)continue;let l=await JS(d,c);r.push(l)}let s=[];for(let c of r)s.push(await Os(e,c));let o=(t.status?s.filter(c=>c.status===t.status):s).sort((c,d)=>{let l=Date.parse(d.updated_at)-Date.parse(c.updated_at);return Number.isFinite(l)&&l!==0?l:d.id.localeCompare(c.id)}),a=typeof t.limit=="number"&&t.limit>=0?t.limit:void 0;return a===void 0?o:o.slice(0,a)}async function eE(e,t){let n=await pr(e,t);if(!n)throw new p(`Background test run ${t} not found`,m.NOT_FOUND);let r=await Os(e,n),s=fr(r.worker_pid),i=fr(r.child_pid);r.status==="running"&&!i&&!r.finished_at&&!s&&(r.status="failed",r.finished_at=O(),r.error=r.error??"Background run process exited unexpectedly.",await ft(e,r)),r.status==="running"&&(r.resource=await Cu(r),await ft(e,r));let o=r.progress?.heartbeat_at,a=o?Date.parse(o):Number.NaN,c=Number.isFinite(a)?Math.max(0,VS()-a):void 0,d=Number.parseInt(process.env.PM_BACKGROUND_RUN_HEARTBEAT_STALE_MS??"",10),l=Number.isFinite(d)&&d>0?d:PG,u=r.status==="running"?c!==void 0&&c>l?"stale":"healthy":"inactive";return{run:r,health:{state:u,last_heartbeat_at:o,heartbeat_lag_ms:c,worker_alive:s,child_alive:i}}}function iq(e,t){let n=t?"SIGKILL":"SIGTERM";if(!fr(e.worker_pid)||!e.worker_pid)return"none";try{return process.kill(e.worker_pid,n),n}catch{return"none"}}function oq(e,t){return{phase:"stopping",message:t==="none"?"Run marked stopped.":`Stop requested via ${t}.`,heartbeat_at:O(),item_index:e.progress?.item_index,item_total:e.progress?.item_total,item_id:e.progress?.item_id,linked_test_index:e.progress?.linked_test_index,linked_test_total:e.progress?.linked_test_total,current_command:e.progress?.current_command,elapsed_ms:e.progress?.elapsed_ms}}async function tE(e,t,n=!1){let r=await pr(e,t);if(!r)throw new p(`Background test run ${t} not found`,m.NOT_FOUND);let s=await Os(e,r);if(Ru.has(s.status))return{run:s,signal_sent:"none"};let i=iq(s,n);return i==="none"&&(s.status="stopped",s.finished_at=s.finished_at??O()),s.stop_requested_at=O(),s.progress=oq(s,i),await ft(e,s),{run:s,signal_sent:i}}async function nE(e,t,n,r=!1){let s=await pr(e,t);if(!s)throw new p(`Background test run ${t} not found`,m.NOT_FOUND);let i=await Os(e,s);if(!Ru.has(i.status))throw new p(`Background test run ${t} is not terminal and cannot be resumed.`,m.CONFLICT);let o=await Iu({pmRoot:i.pm_root,globalPmRoot:i.global_pm_root,kind:i.kind,commandArgs:i.command_args,requestedBy:n,targetId:i.target_id,statusFilter:i.status_filter,resumedFrom:i.id,resumedBy:n,attempt:i.attempt+1});if(!o.started)return o.run;let a=await Ou({pmRoot:e,runId:o.run.id,noExtensions:r}),c={...i,resumed_by:a.id};return await ft(e,c),a}async function rE(e,t,n,r){let s=await pr(e,t);if(!s)throw new p(`Background test run ${t} not found`,m.NOT_FOUND);let i=typeof r=="number"&&Number.isFinite(r)&&r>=0?Math.floor(r):HS,o=n==="stdout"||n==="both"?await Q(s.stdout_path)??"":"",a=n==="stderr"||n==="both"?await Q(s.stderr_path)??"":"";return{run:s,stream:n,tail:i,stdout:n==="stdout"||n==="both"?Tu(o,i):[],stderr:n==="stderr"||n==="both"?Tu(a,i):[]}}var cq=["queued","running","passed","failed","stopped","canceled"],dq=["stdout","stderr","both"];function lq(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(cq.includes(t))return t;throw new p(`Invalid --status value "${e}"`,m.USAGE)}function uq(e){if(e===void 0||e.trim().length===0)return"stderr";let t=e.trim().toLowerCase();if(dq.includes(t))return t;throw new p(`Invalid --stream value "${e}"`,m.USAGE)}function mq(){try{let e=aq.userInfo().username.trim();if(e.length>0)return e}catch{}}function sE(e,t){let n=[e,of(),t,process.env.USER,process.env.LOGNAME,process.env.USERNAME,mq()];for(let r of n){if(typeof r!="string")continue;let s=r.trim();if(s.length>0)return s}return"unknown"}async function Sn(e){await j(e)}async function CQ(e,t){let n=I(process.cwd(),t.path),r=Xe(process.cwd());await Sn(n);let s=await C(n),i=sE(e.author,s.author_default),o=await Iu({pmRoot:n,globalPmRoot:r,kind:e.kind,commandArgs:e.commandArgs,requestedBy:i,targetId:e.targetId,statusFilter:e.statusFilter});return o.started?{started:!0,run:await Ou({pmRoot:n,runId:o.run.id,noExtensions:e.noExtensions===!0})}:{started:!1,duplicate_of:o.duplicate_of,run:o.run}}async function TQ(e,t){let n=I(process.cwd(),t.path);await Sn(n);let r=lq(e.status),s=Rr(e.limit,"limit"),i=await Lu(n,{status:r,limit:s});return{runs:i,count:i.length,filters:{status:r,limit:s}}}async function RQ(e,t){let n=I(process.cwd(),t.path);await Sn(n);let r=await eE(n,e);return{run:r.run,health:r.health}}async function IQ(e,t,n){let r=I(process.cwd(),n.path);await Sn(r);let s=uq(t.stream),i=Rr(t.tail,"tail"),o=await rE(r,e,s,i);return{run:o.run,stream:o.stream,tail:o.tail,stdout:o.stdout,stderr:o.stderr}}async function OQ(e,t,n){let r=I(process.cwd(),n.path);await Sn(r);let s=await tE(r,e,t.force===!0);return{run:s.run,signal_sent:s.signal_sent}}async function LQ(e,t,n){let r=I(process.cwd(),n.path);await Sn(r);let s=await C(r),i=sE(t.author,s.author_default),o=await nE(r,e,i,t.noExtensions===!0);return{resumed_from:e,run:o}}async function $Q(e,t){let n=I(process.cwd(),t.path);await Sn(n);let r=await ZS(n,e,t.noExtensions===!0);return{id:r.id,status:r.status,exit_code:r.exit_code}}export{eA as a,Bh as b,pq as c,Nq as d,rA as e,rn as f,Mq as g,sA as h,Vh as i,Pq as j,qr as k,Fq as l,oA as m,cA as n,Dq as o,Xh as p,Kq as q,zq as r,pg as s,Bq as t,Hq as u,Vq as v,qc as w,Yq as x,Jq as y,Xq as z,JA as A,Kn as B,XA as C,tW as D,nW as E,Kc as F,rW as G,sW as H,iW as I,eC as J,oW as K,aW as L,cW as M,dW as N,zc as O,Eg as P,uW as Q,Sg as R,Rg as S,lC as T,Kr as U,_C as V,Og as W,yC as X,SW as Y,Bc as Z,Ng as _,vC as $,TW as aa,RW as ba,Mg as ca,IW as da,OW as ea,M as fa,Ne as ga,ut as ha,zn as ia,Hc as ja,Fg as ka,vt as la,zr as ma,TC as na,Jc as oa,Xc as pa,Gg as qa,Bn as ra,Vr as sa,Zc as ta,HC as ua,Hg as va,Yr as wa,Yg as xa,Ki as ya,ed as za,Jg as Aa,Xg as Ba,Qg as Ca,AT as Da,hK as Ea,_R as Fa,Ay as Ga,AK as Ha,es as Ia,CK as Ja,bR as Ka,xR as La,TK as Ma,SR as Na,dd as Oa,XR as Pa,hd as Qa,ns as Ra,Ky as Sa,gd as Ta,iI as Ua,oI as Va,aI as Wa,Vn as Xa,cI as Ya,xt as Za,dI as _a,lI as $a,_d as ab,yd as bb,wd as cb,uI as db,Xi as eb,Qi as fb,Hy as gb,Jy as hb,kz as ib,OI as jb,LI as kb,ew as lb,bd as mb,Az as nb,Oz as ob,sw as pb,ow as qb,Yz as rb,Jz as sb,rs as tb,ro as ub,lw as vb,uw as wb,mw as xb,fw as yb,gw as zb,yw as Ab,rO as Bb,vw as Cb,iO as Db,aO as Eb,cO as Fb,dO as Gb,Ew as Hb,Aw as Ib,Cw as Jb,io as Kb,oo as Lb,dv as Mb,KH as Nb,lv as Ob,mv as Pb,fv as Qb,hv as Rb,yv as Sb,Yd as Tb,cs as Ub,ds as Vb,fL as Wb,tr as Xb,Av as Yb,rl as Zb,Tv as _b,Rv as $b,GL as ac,J2 as bc,Sk as cc,ms as dc,Ck as ec,Tk as fc,Rk as gc,kl as hc,Y$ as ic,$Y as jc,Mk as kc,nJ as lc,oJ as mc,lN as nc,To as oc,El as pc,jk as qc,bJ as rc,$N as sc,Ro as tc,Io as uc,Lo as vc,nb as wc,sr as xc,_n as yc,Po as zc,pn as Ac,Jk as Bc,hs as Cc,gs as Dc,Fo as Ec,Do as Fc,hn as Gc,gn as Hc,ir as Ic,jo as Jc,Uo as Kc,Go as Lc,ys as Mc,Jo as Nc,eM as Oc,Tl as Pc,a4 as Qc,vn as Rc,EP as Sc,sa as Tc,Cb as Uc,Tb as Vc,u3 as Wc,GP as Xc,iF as Yc,aF as Zc,ks as _c,m3 as $c,N3 as ad,VF as bd,Vl as cd,M3 as dd,P3 as ed,la as fd,X3 as gd,Q3 as hd,Z3 as id,ax as jd,_5 as kd,gD as ld,tu as md,yD as nd,wD as od,vD as pd,h5 as qd,g5 as rd,I5 as sd,O5 as td,L5 as ud,xx as vd,Sx as wd,ND as xd,Ex as yd,e9 as zd,Ax as Ad,t9 as Bd,n9 as Cd,ma as Dd,XD as Ed,d9 as Fd,ru as Gd,l9 as Hd,su as Id,QD as Jd,Ss as Kd,Ix as Ld,Ox as Md,$9 as Nd,Nx as Od,H9 as Pd,V9 as Qd,Yx as Rd,lu as Sd,ku as Td,F8 as Ud,o1 as Vd,d1 as Wd,xu as Xd,PS as Yd,oQ as Zd,CQ as _d,TQ as $d,RQ as ae,IQ as be,OQ as ce,LQ as de,$Q as ee};
|
|
31
|
+
//# sourceMappingURL=chunk-ENKXRSFZ.js.map
|