@unbrained/pm-cli 2026.11.21 → 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/.agents/skills/pm-developer/SKILL.md +1 -1
- 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-AEOHUSUI.js +2289 -0
- 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-R5SZPJZ5.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-SPGPS3OS.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-3V3UIP5X.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 +72 -60
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +13 -13
- package/dist/cli.js +1 -1
- package/dist/core/checkpoint/checkpoint-gc.js +1 -1
- package/dist/core/checkpoint/mutation-checkpoint.js +2 -2
- package/dist/core/checkpoint/mutation-context.js +1 -1
- package/dist/core/config/nested-settings.js +1 -1
- package/dist/core/config/positional-value.js +1 -1
- package/dist/core/diagnostics/remediation.js +1 -1
- package/dist/core/extensions/activation-summary-markdown.js +2 -2
- package/dist/core/extensions/activation-summary.js +1 -1
- package/dist/core/extensions/activation-transaction.js +1 -1
- package/dist/core/extensions/capability-usage.js +1 -1
- package/dist/core/extensions/command-hook-context.js +1 -1
- package/dist/core/extensions/command-metadata-contract.js +1 -1
- package/dist/core/extensions/command-visibility-tier.js +1 -1
- package/dist/core/extensions/contribution-inventory.js +1 -1
- package/dist/core/extensions/exporter-output-contract.js +1 -1
- package/dist/core/extensions/extension-candidate.js +1 -1
- package/dist/core/extensions/extension-capability-aliases.js +1 -1
- package/dist/core/extensions/extension-hook-runtime.js +1 -1
- package/dist/core/extensions/extension-policy.js +1 -1
- package/dist/core/extensions/extension-registries.js +1 -1
- package/dist/core/extensions/extension-runtime-helpers.js +1 -1
- package/dist/core/extensions/extension-types.js +1 -1
- package/dist/core/extensions/flag-definition-validation.js +1 -1
- package/dist/core/extensions/flag-value-types.js +1 -1
- package/dist/core/extensions/index.js +1 -1
- package/dist/core/extensions/item-field-types.js +1 -1
- package/dist/core/extensions/item-fields.js +1 -1
- package/dist/core/extensions/loader.js +1 -1
- package/dist/core/extensions/manifest-parser.js +1 -1
- package/dist/core/extensions/manifest-schema.js +1 -1
- package/dist/core/extensions/module-graph-snapshot.js +1 -1
- package/dist/core/extensions/mutation-actor-snapshot.js +1 -1
- package/dist/core/extensions/mutation-actor.js +1 -1
- package/dist/core/extensions/preflight-ownership.js +1 -1
- package/dist/core/extensions/read-output-contract.js +1 -1
- package/dist/core/extensions/registration-contracts.js +1 -1
- package/dist/core/extensions/registration-validation.js +1 -1
- package/dist/core/extensions/registration-values.js +1 -1
- package/dist/core/extensions/reserved-host-flags.js +1 -1
- package/dist/core/extensions/runtime-registrations.js +1 -1
- package/dist/core/extensions/service-ownership.js +1 -1
- package/dist/core/extensions/version-compat.js +1 -1
- package/dist/core/extensions/version-diagnostics.js +1 -1
- package/dist/core/fs/atomic-create.js +1 -1
- package/dist/core/fs/file-glob.js +1 -1
- package/dist/core/fs/fs-utils.js +2 -2
- package/dist/core/fs/host-environment-errors.js +1 -1
- package/dist/core/fs/index.js +1 -1
- package/dist/core/fs/path-utils.js +1 -1
- package/dist/core/governance/content-fields.js +1 -1
- package/dist/core/governance/issue-codes.js +1 -1
- package/dist/core/governance/metadata-coverage.js +1 -1
- package/dist/core/history/bridge.js +2 -0
- 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.d.ts +12 -0
- 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.d.ts +9 -0
- package/dist/core/history/read.js +1 -1
- package/dist/core/history/replay.d.ts +46 -5
- 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.d.ts +2 -2
- 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 +74 -73
- package/dist/sdk/completion/shared.js +1 -1
- package/dist/sdk/completion/zsh.js +77 -76
- 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 +2 -0
- 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.d.ts +30 -0
- package/dist/sdk/history/append-only-repair.js +6 -0
- 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.d.ts +8 -2
- package/dist/sdk/history/maintenance.js +1 -1
- package/dist/sdk/history/reanchor-refusal.js +2 -0
- package/dist/sdk/history/reseed.d.ts +15 -0
- package/dist/sdk/history/reseed.js +2 -0
- package/dist/sdk/history/salvage.d.ts +19 -8
- package/dist/sdk/history/salvage.js +5 -3
- 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.d.ts +8 -2
- package/dist/sdk/history-repair.js +1 -1
- package/dist/sdk/improvement-ledger-validation.js +1 -1
- package/dist/sdk/improvement-ledger.js +2 -2
- package/dist/sdk/index.d.ts +1 -1
- package/dist/sdk/init-agent-guidance.js +10 -10
- package/dist/sdk/init.js +14 -14
- package/dist/sdk/invocation-author.js +1 -1
- package/dist/sdk/item-children.js +1 -1
- package/dist/sdk/item-metadata-index.js +1 -1
- package/dist/sdk/item-schedule.js +1 -1
- package/dist/sdk/item-transaction.d.ts +33 -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.d.ts +22 -3
- package/dist/sdk/merge/three-way.js +9 -3
- 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 +8 -2
- package/dist/sdk/runtime-input.js +1 -1
- package/dist/sdk/runtime-primitives.d.ts +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 +9 -0
- 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.d.ts +5 -5
- 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 +2 -0
- 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.d.ts +20 -0
- package/dist/types.js +1 -1
- package/docs/AGENT_GUIDE.md +1 -1
- package/docs/AGENT_RUNTIME_PRIMITIVES.md +1 -1
- package/docs/COMMANDS.md +7 -3
- package/docs/EXTENSIONS.md +1 -1
- package/docs/HISTORY_RECOVERY.md +229 -5
- package/docs/README.md +2 -2
- package/docs/SDK.md +174 -5
- package/docs/SDK_CONTEXT_COORDINATION.md +3 -2
- package/marketplace.json +1 -1
- package/node_modules/tar/package.json +2 -3
- package/package.json +31 -2
- 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-2DXRTIC6.js +0 -21
- package/dist/cli-bundle/chunks/chunk-5647LU3A.js +0 -2287
- package/dist/cli-bundle/chunks/chunk-6QLEXRUG.js +0 -9
- package/dist/cli-bundle/chunks/chunk-AHQB7W2H.js +0 -3
- package/dist/cli-bundle/chunks/chunk-BKSVHOWI.js +0 -2
- package/dist/cli-bundle/chunks/chunk-CASX6SFI.js +0 -2
- package/dist/cli-bundle/chunks/chunk-CIKGG34F.js +0 -2
- package/dist/cli-bundle/chunks/chunk-D6ILFXZY.js +0 -2
- package/dist/cli-bundle/chunks/chunk-DEZPZOQ7.js +0 -2
- package/dist/cli-bundle/chunks/chunk-IB7UB5TE.js +0 -2
- package/dist/cli-bundle/chunks/chunk-IUIOTAF6.js +0 -9
- package/dist/cli-bundle/chunks/chunk-JVGRFU5H.js +0 -3
- package/dist/cli-bundle/chunks/chunk-KQIZ34SF.js +0 -3
- package/dist/cli-bundle/chunks/chunk-KVBIMFUG.js +0 -6
- package/dist/cli-bundle/chunks/chunk-LQBWLNZJ.js +0 -3
- package/dist/cli-bundle/chunks/chunk-NCFCBKIP.js +0 -2
- package/dist/cli-bundle/chunks/chunk-NT5AKFE5.js +0 -31
- package/dist/cli-bundle/chunks/chunk-PJXKA4QU.js +0 -125
- package/dist/cli-bundle/chunks/chunk-RMIRNYRG.js +0 -71
- package/dist/cli-bundle/chunks/chunk-RULHZRFN.js +0 -2
- package/dist/cli-bundle/chunks/chunk-S6HB3WL2.js +0 -2
- package/dist/cli-bundle/chunks/chunk-SA4BNP3Q.js +0 -2
- package/dist/cli-bundle/chunks/chunk-SPPHDVZE.js +0 -2
- package/dist/cli-bundle/chunks/chunk-SRVTCYAU.js +0 -2
- package/dist/cli-bundle/chunks/chunk-WELSVDPU.js +0 -2
- package/dist/cli-bundle/chunks/chunk-XHJ3H5PL.js +0 -3
- package/dist/cli-bundle/chunks/chunk-XWHJIRNV.js +0 -8
- package/dist/cli-bundle/chunks/chunk-YJEBK7HU.js +0 -8
- package/dist/cli-bundle/chunks/chunk-YKJKQ7DM.js +0 -115
- 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-7DFCG73I.js +0 -2
- package/dist/cli-bundle/chunks/mutation-actor-3TG636XG.js +0 -2
- package/dist/cli-bundle/chunks/mutation-admission-LICSDNNO.js +0 -2
- package/dist/cli-bundle/chunks/register-mutation-WWVECKFQ.js +0 -21
- package/dist/cli-bundle/chunks/register-operations-L6HFJNWD.js +0 -2
- package/dist/cli-bundle/chunks/register-setup-K7UFG5TD.js +0 -2
- package/dist/cli-bundle/chunks/settlement-hook-BXN5LEQD.js +0 -7
- package/dist/cli-bundle/chunks/stage-57KH3KAC.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-532WZV65.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-7A4QWNZX.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-CU2BRAOX.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-CWWKRI5P.js +0 -2
- 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-HGFNL5XI.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-I5LGPUWH.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-IQK5NPMG.js +0 -13
- package/dist/cli-bundle/focused-chunks/chunk-J63D6QST.js +0 -6
- package/dist/cli-bundle/focused-chunks/chunk-JMQJBZQ5.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-LNHUE4VV.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-MKM5NKD7.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-NP72ZDXE.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-OSLQD5VH.js +0 -102
- package/dist/cli-bundle/focused-chunks/chunk-QGKLRXP7.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-QSJW6NSQ.js +0 -66
- package/dist/cli-bundle/focused-chunks/chunk-RPE6IX26.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-SRDQSA6M.js +0 -91
- package/dist/cli-bundle/focused-chunks/chunk-SVOOGGAK.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-UOC6257J.js +0 -26
- package/dist/cli-bundle/focused-chunks/chunk-URJ2E6AS.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-WXMI4AV5.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-XCJSHNXK.js +0 -27
- package/dist/cli-bundle/focused-chunks/chunk-XQQSSKJI.js +0 -44
- package/dist/cli-bundle/focused-chunks/chunk-YOAYY3HE.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-HLBW7B3J.js +0 -2
- package/dist/cli-bundle/focused-chunks/mutation-actor-62HKR5IO.js +0 -2
- package/dist/cli-bundle/focused-chunks/mutation-admission-X4PF2SG3.js +0 -2
- package/dist/cli-bundle/focused-chunks/settlement-hook-ARYCZQY4.js +0 -7
- package/dist/cli-bundle/focused-chunks/stage-O7T7CXBB.js +0 -2
- package/dist/sdk/agent/refusal-closure.js +0 -2
- package/dist/sdk/agent/refusal-reachability.js +0 -4
- package/dist/sdk/agent/task-transcript-contracts.js +0 -2
- package/dist/sdk/agent/tracker-preflight-contracts.js +0 -2
- package/dist/sdk/authoring.js +0 -2
- package/dist/sdk/compose.js +0 -2
- package/dist/sdk/contracts.js +0 -2
- package/dist/sdk/core-governance.js +0 -2
- package/dist/sdk/core.js +0 -2
- package/dist/sdk/corpus-shape.js +0 -2
- package/dist/sdk/define.js +0 -2
- package/dist/sdk/environment/agent-environment.js +0 -2
- package/dist/sdk/governance/artifact-ledgers.js +0 -2
- package/dist/sdk/governance/coverage-assurance.js +0 -2
- package/dist/sdk/governance/reliability.js +0 -2
- package/dist/sdk/governance.js +0 -2
- package/dist/sdk/graph/adapter.js +0 -2
- package/dist/sdk/graph/conformance.js +0 -2
- package/dist/sdk/graph/index.js +0 -2
- package/dist/sdk/graph.js +0 -2
- package/dist/sdk/index.js +0 -2
- package/dist/sdk/query.js +0 -2
- package/dist/sdk/relationship-migration.js +0 -2
- package/dist/sdk/testing.js +0 -8
- package/dist/sdk/workspace-recipe.js +0 -2
- package/docs/AGENT_PROVENANCE_ADR.md +0 -206
- package/docs/DEFECT_RECURRENCE.md +0 -257
- package/docs/PERFORMANCE.md +0 -204
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import{h as cm,j as dm}from"./chunk-O7Z73ALG.js";import{c as Mt,d as Cn,e as $n,f as Tn,g as om,j as am}from"./chunk-Y2ESLKCF.js";import{a as im}from"./chunk-RIE3SJSE.js";import{K as Zu,v as te,z as Hs}from"./chunk-XYPEZGTR.js";import{a as ys,c as ui,d as mi,e as dl,g as ll,h as vs,i as ul,j as fn,k as hn,l as ml,m as pl,n as ks,o as yl,p as _n,q as gn,r as wl,s as vl,t as bs,w as cu,x as du,y as $s}from"./chunk-6LKTEKHS.js";import{a as js}from"./chunk-K53OIT5J.js";import{H as nu,I as $i,J as ru,K as Cs,M as iu,N as ou,P as su,Q as au,R as Ti,_ as Oi}from"./chunk-IROZDIDX.js";import{K as sm}from"./chunk-I66IKYKP.js";import{G as zs,w as tm,y as rm}from"./chunk-OXOCZJC6.js";import{a as Us,b as nm}from"./chunk-6LPXMFLM.js";import{$a as Ds,A as ur,Aa as pr,B as uu,C as mu,Ca as Ps,D as mr,Ga as Nu,Ha as Du,Hb as Vu,Ia as Mu,Ja as Fu,Jb as Ku,Ka as Hi,M as pu,Ma as ju,Na as Hu,Oa as Uu,Pa as Yt,Pb as Yu,Qa as zu,Qb as Xu,R as fu,Ra as Rn,Sa as Wu,Ta as Ls,Ua as An,Va as qu,Wa as Gu,Xa as Bu,Ya as Ns,Za as Ju,_a as In,a as ol,ab as Ms,b as pn,ba as hu,c as ws,ca as _u,d as sl,da as gu,e as al,f as ft,g as pi,ga as Ni,h as cl,i as Ot,rb as Fs,v as Pi,xa as Mi,ya as xu,z as lu,za as Os}from"./chunk-UFTUNBMY.js";import{d as fr,f as Ui,m as Qu,p as em}from"./chunk-ITKDHSBR.js";import{E as Fi,G as Ou,H as ge,I as ye,J as Pu,K as ji,L as _t,M as gt,Q as Lu,R as yt,b as ln,e as Li,g as yu,n as Su,o as Eu,q as Ru,r as Au,s as Dt,t as Iu,u as Cu,y as $u,z as Tu}from"./chunk-OTMMOKPM.js";import{a as re,b as bn,c as wu,d as Ts,e as xn,f as Sn,g as En,j as vu,k as ku,n as Je,r as bu,s as T,t as Di,y as ie}from"./chunk-HMDQDRV2.js";import{$ as et,$f as Be,Aa as un,Ae as Nt,Af as Ri,Bd as Lt,Ca as Jd,Cc as ve,Cd as Cl,Ce as qe,Da as pt,Db as tl,Dc as xs,Dd as $l,De as Rs,Eb as nl,Fa as Vd,Fc as C,Fe as wn,Ff as Yl,Ga as I,Gc as bl,Ge as vi,Ha as ps,Hc as yn,He as ht,Hf as Ai,Ia as Ce,Ic as Pt,Id as Tl,Ie as ke,If as Xl,Jc as Vt,Jd as Ol,Je as cr,Jf as Zl,Ka as li,Ke as Ul,La as Kd,Ld as Pl,Le as zl,Lf as Ql,Ma as fs,Mb as rl,Mc as hi,Md as Ll,Me as Wl,Na as hs,Nb as Jt,Nc as K,Nd as se,Ne as ql,Oa as _s,Oe as Gl,Pe as ki,Q as Ud,Qa as Yd,Qe as Kt,Ra as Xd,Re as bi,T as zd,Tf as U,Ua as Zd,V as ms,Vc as xl,Wb as gs,Xb as il,Xe as Bl,Xf as Y,Yb as mn,Ye as dr,Ze as vn,_ as he,_b as nt,_e as Ge,a as Pd,aa as Wd,ac as rt,bf as kn,bg as eu,ca as X,cb as Qd,cc as ce,cf as xi,cg as Ii,d as Ld,dc as fl,df as Jl,e as Nd,ec as hl,ef as Si,fa as qd,fc as Le,fd as _i,gd as ar,gf as Vl,hc as $e,hd as Sl,hg as tu,ic as it,id as gi,if as Ei,jd as El,lb as el,ld as yi,mc as _e,md as wi,nc as _l,ng as Ci,o as us,oc as fi,od as Rl,oe as q,pa as Gd,pe as Nl,pf as As,qa as Bd,qc as gl,qf as Is,ra as W,re as Dl,rf as Kl,sd as Al,se as Ml,td as Il,te as We,ue as Fl,ve as jl,wa as sr,wd as Ne,we as Ss,xa as M,xe as Hl,ya as tt,ye as Es,za as di,zc as kl,zf as lr}from"./chunk-Z2X7HH3C.js";import{a as zi,b as hr}from"./chunk-IIP6LZ5E.js";import{A as _,B as or,C as P,D as Qe,E as F,F as B,I as ee,a as si,d as ai,p as Dd,r as Md,t as Fd,v as jd,w as ci,x as Hd,y as Tt,z as g}from"./chunk-A6VEMCRR.js";var L=class extends TypeError{constructor(t){super(t),this.name="AssuranceMutationRefusalError"}},Re=class extends TypeError{context;constructor(t,n={}){super(t),this.name="AssuranceEvaluationRefusalError",this.context=n}},ot=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 On(e){try{return await e()}catch(t){throw t instanceof L?new _(t.message,g.USAGE,{code:"invalid_argument_value",reason:"assurance_mutation_refused"}):t}}async function Ws(e){try{return await e()}catch(t){throw t instanceof Re?new _(t.message,g.USAGE,{code:"invalid_argument_value",reason:"assurance_evaluation_refused",...t.context}):t}}import{createHash as ov}from"node:crypto";import sv from"node:path";var um=1,Xt=["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"],qs=["items","dependency_kind","prose_edge_gap","graph","validate","health","history","links","provider","derived"],av=["ceiling","floor","equals","zero","monotone_nondecreasing","monotone_nonincreasing","subset_of"],cv=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,Wi=30,qi=5e3,mm=4,dv=50;function wt(e,t){if(!cv.test(e))throw new L(`${t} must be a stable lowercase id`)}function lv(e,t){if(!Number.isFinite(e)||e<0)throw new L(`${t} must be a finite non-negative number`)}function gr(e){let t=av.filter(i=>e[i]!==void 0);if(t.length!==1)throw new L(`assertion ${e.id} must declare exactly one polarity`);let n=t[0],r=e[n];return{polarity:n,value:n==="zero"?0:r}}function Bs(e,t){return I(e)===I(t)}function pm(e,t){if(t.polarity==="equals")return Bs(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(i=>r.includes(i))}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 fm(e){let t=gr(e),n=e.negative_control.cases;return n.some(r=>r.expected==="pass")&&n.some(r=>r.expected==="fail")&&n.every(r=>pm(r.observed,t)===(r.expected==="pass"))}function uv(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(i=>!n.includes(i))}return!Bs(e.value,t.value)}function mv(e,t){if(e.measurement_id!==t.measurement_id||e.owner_item_id!==t.owner_item_id||I(e.scope)!==I(t.scope))return!0;let n={observe:0,warn:1,block:2},r=(e.lifetime??"hold")==="hold"&&(t.lifetime??"hold")==="retire";return uv(gr(e),gr(t))||n[t.enforcement]<n[e.enforcement]||r}function pv(e){if(e.state!==void 0&&!(e.state==="present"||e.state==="missing"))throw new L("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 L("items source with field requires exactly one of equals or state");if(e.field===void 0&&r!==0)throw new L("items source equals/state requires field")}function fv(e){if(typeof e.dependency_kind!="string"||e.dependency_kind.trim().length===0)throw new L("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 L("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 L("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 L("dependency_kind source source_kind_state must be present or missing")}function hv(e){if(e.sample_limit!==void 0&&(!Number.isInteger(e.sample_limit)||e.sample_limit<1))throw new L("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 L("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 L("prose_edge_gap exemption selectors must not be empty")}}function Js(e){wt(e.id,"measurement.id"),e.max_cost!==void 0&&lv(e.max_cost,"measurement.max_cost");let t=e.source;if(Object.prototype.toString.call(t)!=="[object Object]")throw new L(`measurement.source.kind must be one of ${qs.join(", ")}`);let n=Reflect.get(t,"kind");if(!qs.includes(n))throw new L(`measurement.source.kind must be one of ${qs.join(", ")}`);let r=t;if(r.kind==="items"&&pv(r),r.kind==="dependency_kind"&&fv(r),r.kind==="prose_edge_gap"&&hv(r),(r.kind==="graph"||r.kind==="validate"||r.kind==="health")&&(typeof r.field!="string"||r.field.trim().length===0))throw new L(`${r.kind} source requires field`);return r.kind==="provider"&&(wt(r.provider,"provider source provider"),wt(r.key,"provider source key")),e}function Vs(e){if(wt(e.id,"assertion.id"),wt(e.measurement_id,"assertion.measurement_id"),typeof e.owner_item_id!="string"||e.owner_item_id.trim().length===0)throw new L("assertion.owner_item_id is required");let t=gr(e);if(typeof t.value=="number"&&!Number.isFinite(t.value))throw new L(`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 L("retired assertion requires retire_reason");e.scope.kind==="filter"&&wt(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 L("assertion negative control requires pass and fail cases");if(!fm(e))throw new L(`assertion ${e.id} negative control does not prove its bound`);return e}function _v(e){if(!Array.isArray(e.allowed_providers))throw new L("gate provider_policy.allowed_providers must be an array");for(let t of e.allowed_providers)wt(t,"gate.provider_policy.allowed_provider");if(typeof e.triggers!="object"||e.triggers===null||Array.isArray(e.triggers))throw new L("gate provider_policy.triggers must be an object");for(let[t,n]of Object.entries(e.triggers)){if(!Xt.includes(t))throw new L(`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 L(`gate provider policy trigger ${t} is invalid`)}}function hm(e){if(wt(e.id,"gate.id"),!Array.isArray(e.assertion_ids))throw new L("gate.assertion_ids is required and must be an array");if(e.assertion_ids.length===0)throw new L("gate requires at least one assertion");for(let t of e.assertion_ids)wt(t,"gate.assertion_id");if(!Array.isArray(e.triggers))throw new L(`gate.triggers is required and must be an array of ${Xt.join(", ")}`);if(e.triggers.length===0)throw new L("gate requires at least one trigger");for(let t of e.triggers)if(!Xt.includes(t))throw new L(`gate trigger must be one of ${Xt.join(", ")}`);return e.provider_policy&&_v(e.provider_policy),e}function Pn(e){if(e.version!==um)throw new L(`unsupported assurance document version ${String(e.version)}`);let t=new Set;for(let r of e.measurements){if(Js(r),t.has(`measurement:${r.id}`))throw new L(`duplicate measurement ${r.id}`);t.add(`measurement:${r.id}`)}for(let r of e.assertions){if(Vs(r),t.has(`assertion:${r.id}`))throw new L(`duplicate assertion ${r.id}`);t.add(`assertion:${r.id}`)}for(let r of e.gates){hm(r);let i=r.assertion_ids.filter(o=>!e.assertions.some(s=>s.id===o));if(i.length>0)throw new L(`gate ${r.id} references missing assertions: ${i.join(", ")}`);if(t.has(`gate:${r.id}`))throw new L(`duplicate gate ${r.id}`);t.add(`gate:${r.id}`)}let n=new Set(e.measurements.map(r=>r.id));for(let[r,i]of _m(e))if(!n.has(r))throw new L(`${i.join(", ")} references missing measurement ${r}`);return e}function Ks(e,t){if("measurement"in e){t.push(e.measurement);return}if("operator"in e)for(let n of e.operands)Ks(n,t)}function _m(e){let t=new Map,n=(r,i)=>{let o=t.get(r)??[];o.push(i),t.set(r,o)};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 i=[];Ks(r.source.expression,i);for(let o of i)n(o,`derived measurement ${r.id}`)}return t}function gv(e,t){let n=e.assertion_ids.flatMap(o=>{let s=t.assertions.find(a=>a.id===o);return[s.measurement_id,...s.scope.kind==="filter"?[s.scope.measurement_id]:[]]}),r=new Set,i=new Set;for(;n.length>0;){let o=n.pop();if(r.has(o))continue;r.add(o);let s=t.measurements.find(a=>a.id===o);s.source.kind==="provider"?i.add(s.source.provider):s.source.kind==="derived"&&Ks(s.source.expression,n)}return i}function yr(){return{version:um,measurements:[],assertions:[],gates:[]}}function yv(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(i=>r.tags?.includes(i)))&&(e.field===void 0||(()=>{let i=r[e.field];if(e.state!==void 0){let o=i==null||i===""||Array.isArray(i)&&i.length===0;return e.state==="missing"?o:!o}return Bs(i,e.equals)})()));return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(r=>r.id)}}function wv(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 vv(e,t){let n=[],r=ms(e.dependency_kind)??e.dependency_kind.trim().toLowerCase();for(let i of t.items)for(let o of i.dependencies??[]){let s=ms(o.kind)??o.kind.trim().toLowerCase(),a=o.source_kind?.trim();s===r&&wv(e,a)&&n.push(`${i.id}->${o.id}${a?`@${a}`:""}`)}return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n}}function kv(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 i of r)if(typeof i=="string")t.push(i);else if(typeof i=="object"&&i!==null){let o=Reflect.get(i,"text");typeof o=="string"&&t.push(o)}}}return t}function bv(e,t,n,r){return e.some(i=>i.holder_id.trim().toLowerCase()===t.toLowerCase()&&(i.target_id===void 0||i.target_id.trim().toLowerCase()===n.toLowerCase())&&(i.text_contains===void 0||r.toLowerCase().includes(i.text_contains.trim().toLowerCase())))}function Gs(e,t){return[e.toLowerCase(),t.toLowerCase()].sort().join("\0")}function xv(e){let t=new Map,n=new Set,r=[],i=/(?<![\w-])[a-z0-9]+(?:-+[a-z0-9]+)+(?![\w-])/giu,o=0;for(let s of e){t.set(s.id.toLowerCase(),s.id);for(let a of s.dependencies??[])n.add(Gs(s.id,a.id));for(let a of[s.parent,s.blocked_by])typeof a=="string"&&n.add(Gs(s.id,a));for(let a of kv(s)){let c=[...a.matchAll(i)].map(d=>d[0]);o+=c.length,r.push({holder_id:s.id,segment:a,mentioned_ids:c})}}return{canonical_ids:t,linked_pairs:n,prose_mentions:r,mention_count:o}}function Sv(e,t){let n=xv(t.items),r=new Map;for(let s of n.prose_mentions){let a=s.mentioned_ids.map(d=>n.canonical_ids.get(d.toLowerCase())).filter(d=>d!==void 0&&d!==s.holder_id),c=[...new Set(a)];for(let d of c){let l=Gs(s.holder_id,d);if(n.linked_pairs.has(l)||bv(e.exemptions??[],s.holder_id,d,s.segment))continue;let u=c.some(m=>m!==d);r.get(l)?.explicit===!0&&!u||r.set(l,{contributor:`${s.holder_id}->${d}|subject=${u?"explicit":"implicit"}`,explicit:u})}}let i=[...r.values()],o=i.map(s=>s.contributor).sort();return{value:o.length,population_size:n.canonical_ids.size,cost:t.items.length+n.linked_pairs.size+n.mention_count,contributors:o.slice(0,e.sample_limit??25),partitions:{explicit_subject:i.filter(s=>s.explicit).length,implicit_subject:i.filter(s=>!s.explicit).length}}}function Ev(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 Rv(e,t){let n=t.items.filter(r=>{let i=r[e.link],o=Array.isArray(i)&&i.length>0;return e.state==="present"?o:!o});return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(r=>r.id)}}function Av(e,t){let n=e.source;return n.kind==="items"?yv(n,t):n.kind==="dependency_kind"?vv(n,t):n.kind==="prose_edge_gap"?Sv(n,t):n.kind==="history"?Ev(n,t):n.kind==="links"?Rv(n,t):null}function gm(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 Iv(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 ym(e,t,n){let r=new Array(e.length),i=0,o=Array.from({length:Math.min(t,e.length)},async()=>{for(;i<e.length;){let s=i;i+=1,r[s]=await n(e[s],s)}});return await Promise.all(o),r}async function wm(e,t,n,r,i){if("literal"in e)return{value:e.literal,costs:[],population_size:0,contributors:[]};if("measurement"in e){let s=n.find(d=>d.id===e.measurement);if(!s)throw new TypeError(`derived measurement references missing ${e.measurement}`);let a=await vm(s,t,n,r,i);if(typeof a.value!="number")throw new TypeError(`derived measurement ${s.id} is not numeric`);let c=i.charged.has(s.id)?[]:[a.cost];return i.charged.add(s.id),{value:a.value,costs:c,population_size:a.population_size,contributors:a.contributors}}let o=await ym(e.operands,mm,s=>wm(s,t,n,r,i));return{value:Iv(e.operator,o.map(s=>s.value)),costs:o.flatMap(s=>s.costs),population_size:Math.max(0,...o.map(s=>s.population_size)),contributors:[...new Set(o.flatMap(s=>s.contributors))]}}async function Cv(e,t,n,r,i){Js(e);let o=Date.now(),s,a=[],c=0;if(e.source.kind==="derived"){let u=await wm(e.source.expression,t,n,[...r,e.id],i);s={value:u.value,population_size:u.population_size,cost:0,contributors:u.contributors},a=u.costs}else{let u=Av(e,t);u!==null?s=u:(s=await t.external(e.source),c=1)}let d={units:s.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()-o},l=gm([...a,d],Date.now()-o);if(e.max_cost!==void 0&&l.units>e.max_cost)throw new Re(`measurement ${e.id} exceeded cost ceiling ${e.max_cost} with ${l.units}`);return{id:e.id,definition_fingerprint:`sha256:${ov("sha256").update(I(e)).digest("hex")}`,value:s.value,population_size:s.population_size,cost:l,contributors:s.contributors??[],...s.partitions?{partitions:s.partitions}:{}}}function vm(e,t,n,r,i){if(r.includes(e.id))throw new TypeError(`derived measurement cycle: ${[...r,e.id].join(" -> ")}`);let o=i.cache.get(e.id);if(o)return o;let s=Cv(e,t,n,r,i).catch(a=>{if(a instanceof ot&&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 ot(a.message,c);throw d.cause=a,d}throw a});return i.cache.set(e.id,s),s}async function Ys(e,t,n=[e]){return vm(e,t,n,[],{cache:new Map,charged:new Set})}function $v(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 Tv(e,t,n={}){Vs(e);let r=gr(e),i=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:$v(t.value,r),verdict:i?"retired":pm(t.value,r)?"pass":"fail",enforcement:e.enforcement,negative_control_proven:fm(e),cost:t.cost,contributors:t.contributors,...t.partitions?{partitions:t.partitions}:{}}}function Ov(e,t,n,r){let i=gv(e,t);if(i.size===0)return;let o=e.provider_policy,s=o?.triggers[r];if(!o||!s)throw new Re(`assurance gate ${e.id} refuses provider execution at trigger ${r} without an explicit provider policy`);let a=new Set(o.allowed_providers),c={low:0,medium:1,high:2};for(let d of i){if(!a.has(d))throw new Re(`assurance gate ${e.id} refuses provider ${d}`);let l=n.provider_capabilities?.[d];if(!l)throw new Re(`assurance provider ${d} has no declared capabilities`);if(c[l.cost_class]>c[s.max_cost_class])throw new Re(`assurance gate ${e.id} refuses ${l.cost_class}-cost provider ${d} at trigger ${r}`);if(l.network&&!s.allow_network)throw new Re(`assurance gate ${e.id} refuses network provider ${d} at trigger ${r}`)}}async function lm(e,t,n,r,i){try{return await Ys(n,r,i)}catch(o){if(o instanceof ot){let s=o.check?` check ${o.check}`:"",a=o.measurement_id??n.id,c=new Re(`assurance gate ${e} assertion ${t} measurement ${a} source ${o.source_kind}${s} field ${o.field} could not resolve: ${o.message}`,{gate_id:e,assertion_id:t,measurement_id:a,source_kind:o.source_kind,field:o.field,...o.check?{check:o.check}:{}});throw c.cause=o,c}throw o}}async function km(e,t,n,r){Pn(t);let i=t.gates.find(c=>c.id===e);if(!i)throw new Re(`assurance gate ${e} not found`);if(!i.triggers.includes(r.trigger))throw new Re(`assurance gate ${e} does not declare trigger ${r.trigger}`);Ov(i,t,n,r.trigger);let o=await ym(i.assertion_ids,mm,async c=>{let d=t.assertions.find(f=>f.id===c),l=t.measurements.find(f=>f.id===d.measurement_id),u=n;if(d.scope.kind==="active"){let f=new Set(n.terminal_statuses??["closed","canceled"]);u={...n,items:n.items.filter(h=>!f.has(h.status))}}else if(d.scope.kind==="filter"){let f=d.scope.measurement_id,h=t.measurements.find(v=>v.id===f),y=await lm(i.id,d.id,h,n,t.measurements),w=new Set(y.contributors);u={...n,items:n.items.filter(v=>w.has(v.id))}}let m=n.items.find(f=>f.id===d.owner_item_id),p=m!==void 0&&new Set(n.terminal_statuses??["closed","canceled"]).has(m.status);return Tv(d,await lm(i.id,d.id,l,u,t.measurements),{owner_terminal:p})}),s=o.some(c=>c.verdict==="fail"&&c.enforcement==="block"),a=o.some(c=>c.verdict==="fail"&&c.enforcement==="warn");return{gate_id:i.id,tree_id:n.tree_id,trigger:r.trigger,dry_run:r.dry_run===!0,evaluated_at:new Date().toISOString(),verdict:s?"block":a?"warn":"pass",exit_code:s?1:0,assertions:o,assertions_total:o.length,row_contract:{row_keys:["assertions"],jq_selector:".assertions[]"},cost:gm(o.map(c=>c.cost),Math.max(0,...o.map(c=>c.cost.duration_ms)))}}function Gi(e){return sv.join(e,"assurance.json")}async function bm(e){let t=await B(Gi(e));return t===null?yr():Bi(t)}function Bi(e){try{return Pn(JSON.parse(e))}catch(t){throw new _("The assurance registry is invalid. Repair or restore .agents/pm/assurance.json and retry.",g.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 Ji(e,t){return t==="measurement"?e.measurements:t==="assertion"?e.assertions:e.gates}function Pv(e,t){e==="measurement"?Js(t):e==="assertion"?Vs(t):hm(t)}async function wr(e,t){let n=structuredClone(Ji(await bm(e),t));return{items:n,count:n.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function xm(e,t,n){let r=Ji(await bm(e),t).find(i=>i.id===n);if(!r)throw new Re(`assurance ${t} ${n} not found`);return structuredClone(r)}async function Vi(e,t,n,r={}){Pv(t,n);let i=await T(e),o=q(r.author,i.author_default),s=await Sn({pmRoot:e,filePath:Gi(e),op:`assurance:${t}:put`,author:o,message:r.message,lockTtlSeconds:Wi,lockWaitMs:qi,mutate:a=>{let c=a===null?yr():Bi(a),d=Ji(c,t),l=d.findIndex(m=>m.id===n.id),u=l<0?"created":"updated";if(t==="assertion"&&l>=0&&mv(d[l],n)){let m=n.authorization_decision;if(!m||!r.authorized_decision_ids?.includes(m))throw new L(`loosening assertion ${n.id} requires a verified authorization_decision`)}return l<0?d.push(structuredClone(n)):d[l]=structuredClone(n),Pn(c),{raw:`${JSON.stringify(c,null,2)}
|
|
2
|
+
`,result:{changed:!0,action:u,kind:t,id:n.id}}}});return{...s.result,changed:s.changed}}async function Xs(e,t,n={}){let r=yr();r.measurements=structuredClone(t.measurements),r.assertions=structuredClone(t.assertions),r.gates=structuredClone(t.gates),Pn(r);let i=await T(e),o=q(n.author,i.author_default),s=await Sn({pmRoot:e,filePath:Gi(e),op:"assurance:bundle:apply",author:o,message:n.message,lockTtlSeconds:Wi,lockWaitMs:qi,mutate:a=>{let c=a===null?yr():Bi(a),d=[],l=[],u=(m,p,f)=>{for(let h of p){let y=m.find(w=>w.id===h.id);if(!y){m.push(structuredClone(h)),d.push(`${f}:${h.id}`);continue}if(I(y)!==I(h))throw new L(`assurance bundle refuses to replace divergent ${f} ${h.id}`);l.push(`${f}:${h.id}`)}};return u(c.measurements,r.measurements,"measurement"),u(c.assertions,r.assertions,"assertion"),u(c.gates,r.gates,"gate"),Pn(c),{raw:`${JSON.stringify(c,null,2)}
|
|
3
|
+
`,result:{changed:d.length>0,created_ids:d,unchanged_ids:l}}}});return{...s.result,changed:s.changed}}async function Sm(e,t,n,r={}){let i=await T(e),o=q(r.author,i.author_default),s=await Sn({pmRoot:e,filePath:Gi(e),op:`assurance:${t}:remove`,author:o,message:r.message,lockTtlSeconds:Wi,lockWaitMs:qi,mutate:a=>{let c=a===null?yr():Bi(a);if(t==="measurement"){let u=_m(c).get(n);if(u&&u.length>0)throw new L(`assurance measurement ${n} is referenced by ${u.join(", ")}`)}if(t==="assertion"&&c.gates.some(u=>u.assertion_ids.includes(n)))throw new L(`assurance assertion ${n} is referenced by gate`);let d=Ji(c,t),l=d.findIndex(u=>u.id===n);if(l<0)throw new L(`assurance ${t} ${n} not found`);return d.splice(l,1),Pn(c),{raw:`${JSON.stringify(c,null,2)}
|
|
4
|
+
`,result:{changed:!0,action:"removed",kind:t,id:n}}}});return{...s.result,changed:s.changed}}async function Em(e,t,n={}){if(t.dry_run)throw new TypeError("dry-run assurance verdicts are not persisted");let r=await T(e);await xn({pmRoot:e,op:"assurance:gate:verdict",author:q(n.author,r.author_default),context:{assurance_verdict:t},message:n.message??`Assurance gate ${t.gate_id} returned ${t.verdict}`,lockTtlSeconds:Wi,lockWaitMs:qi})}async function Rm(e,t={}){let n=t.limit??dv;if(!Number.isInteger(n)||n<1||n>1e3)throw new TypeError(`assurance verdict limit must be an integer from 1 through ${1e3}`);return(await We(bn(e),re)).reverse().filter(i=>i.op==="assurance:gate:verdict").map(i=>i.context?.assurance_verdict).filter(i=>typeof i=="object"&&i!==null&&"gate_id"in i).filter(i=>t.gate_id===void 0||i.gate_id===t.gate_id).slice(0,n)}import{AsyncLocalStorage as Lv}from"node:async_hooks";import Am from"node:path";var Im=new Lv;function Cm(e,t){return Im.run({...e,pmRoot:Am.resolve(e.pmRoot)},t)}function DL(e,t){let n=Im.getStore();return n!==void 0&&n.pmRoot===Am.resolve(e)&&n.transactionId===t?n.step:void 0}import{mkdir as Nv,readFile as Dv}from"node:fs/promises";import Tm from"node:path";import{createHash as Mv}from"node:crypto";var Zs=class extends Error{constructor(t="Workspace transaction interrupted"){super(t),this.name="WorkspaceTransactionInterruptedError"}},Om="sdk-workspace-transaction",Pm=/^[a-zA-Z0-9._-]+$/,Lm=30,Nm=3e3;function ra(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n||!Pm.test(n))throw new TypeError(`${t} must match [a-zA-Z0-9._-]+`);return n}function Qs(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n)throw new TypeError(`${t} must be non-empty`);return n}function ia(e){return{pmRoot:Qs(e.pmRoot,"Transaction pmRoot"),transactionId:ra(e.transactionId,"Transaction id"),author:Qs(e.author,"Transaction author")}}function Yi(e,t,n){let r=e??t;if(!Number.isInteger(r)||r<=0)throw new TypeError(`${n} must be a positive integer`);return r}function Dm(e,t){return Tm.join(e,"transactions","sdk",`${t}.json`)}async function st(e,t){t.updatedAt=C();let n=Dm(e,t.transactionId);await Nv(Tm.dirname(n),{recursive:!0}),await ee(n,`${JSON.stringify(t,null,2)}
|
|
5
|
+
`)}function Fv(e){return Number.isInteger(e.attempt)&&typeof e.author=="string"&&typeof e.createdAt=="string"&&typeof e.updatedAt=="string"&&jv(e)}function jv(e){let t=e.abandonment;return t===void 0?e.schemaVersion===1&&e.status!=="abandoned":e.schemaVersion!==2||t===null||typeof t!="object"||e.status==="committed"?!1:typeof t.reason=="string"&&t.reason.trim().length>0&&typeof t.author=="string"&&t.author.trim().length>0&&(t.supersededBy===void 0||typeof t.supersededBy=="string"&&Pm.test(t.supersededBy)&&t.supersededBy!==e.transactionId)}function Zt(e){return Object.assign(Object.create(null),e)}function Mm(e,t){try{let n=JSON.stringify(e,(r,i)=>{if(typeof i=="number"&&!Number.isFinite(i))throw new TypeError(`${t} contains a non-finite number`);if(i===void 0||typeof i=="function"||typeof i=="symbol")throw new TypeError(`${t} contains a non-JSON value`);return i});return JSON.parse(n)}catch(n){throw new TypeError(`${t} must be JSON serializable`,{cause:n})}}function ea(e,t){return e===void 0?void 0:Mm(e,t)}function ta(e,t,n,r){let i=ea(n,r);i===void 0?delete e[t]:e[t]=i}function $m(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function na(e,t){return Array.isArray(e)&&new Set(e).size===e.length&&e.every(n=>typeof n=="string"&&t.includes(n))}function Hv(e,t){if(!na(e.startedStepIds,t)||!na(e.completedStepIds,t)||!$m(e.results)||!$m(e.compensationData))return!1;let n=e.startedStepIds,r=new Set(n),i=e.completedStepIds,o=new Set(i);return Object.keys(e.compensationData).some(s=>!r.has(s))||Object.keys(e.results).some(s=>!o.has(s))?!1:e.status==="committed"?t.every(s=>o.has(s)):!["compensated","abandoned"].includes(e.status??"")||o.size===0&&r.size===0}function Ki(e,t){return new _(`Workspace transaction ${e} journal is invalid (${t})`,g.CONFLICT,{code:"transaction_journal_invalid",required:"A valid durable journal is required before transaction recovery can continue.",why:"Corrupt journal data cannot establish which steps applied or still require compensation.",nextSteps:["Preserve the journal and inspect its integrity or restore a verified backup before retrying.","Do not switch to a new transaction id to bypass an unreadable journal; previously applied work may remain."]})}function Fm(e){return new _(`Workspace transaction ${e} journal does not match the supplied plan`,g.CONFLICT,{code:"transaction_plan_mismatch",required:"Replay the original plan or safely abandon the interrupted transaction before replacing it.",why:"A journal records the plan it is resuming; applying a different plan under the same id could skip or duplicate steps.",nextSteps:["Re-run with the original document to resume or replay it.","For item batches use client.itemTransactions.status(transactionId), then client.itemTransactions.abandon(transactionId, { reason }) before committing a changed plan with a new transactionId.","Run pm ops gc --scope transactions --dry-run to inspect retention; active and explicitly abandoned journals remain protected."]})}function Uv(e,t,n){return n===void 0||e.abandonment!==void 0||e.status==="compensated"||t.length===n.length&&t.every((r,i)=>r===n[i])}function zv(e,t,n){let r;try{r=JSON.parse(e)}catch{throw Ki(t,"invalid JSON")}if(!r||typeof r!="object"||Array.isArray(r))throw Ki(t,"expected an object");let i=r;if(!((i.schemaVersion===1||i.schemaVersion===2)&&i.transactionId===t))throw Ki(t,"schema version or transaction id does not match the journal file");let s=i.stepIds;if(!Array.isArray(s)||!na(s,s)||!Hv(i,s)||!Fv(i)||typeof i.status!="string"||!["applying","compensating","compensated","committed","abandoned"].includes(i.status))throw Ki(t,"invalid lifecycle, metadata, status or step ids");if(!Uv(i,s,n))throw Fm(t);return{...i,results:Zt(i.results),compensationData:Zt(i.compensationData)}}async function Wv(e,t,n,r,i){let o=i,s=o!==void 0;if(o?.status==="compensating"&&await oa(e,o),o===void 0||o.status==="compensated"){let a=C();o={schemaVersion:1,transactionId:t,author:n,status:"applying",attempt:(o?.attempt??0)+1,createdAt:o?.createdAt??a,updatedAt:a,stepIds:r,startedStepIds:[],completedStepIds:[],results:Zt(),compensationData:Zt(),...e.recoveryData===void 0?{}:{recoveryData:Mm(e.recoveryData,"Transaction recovery data")}},await st(e.pmRoot,o),await vt(e,o,"prepared")}return{journal:o,recovered:s}}async function qv(e,t,n){try{await Gv(t,e.steps),await st(e.pmRoot,t);let r=new Set(t.completedStepIds),i=new Set(t.startedStepIds);for(let o of e.steps){if(r.has(o.id))continue;let s=await o.inspect(),a=ea(s.result,`Step ${o.id} result`);if(s.state!=="applied"){let c=await o.prepareCompensation?.();ta(t.compensationData,o.id,c,`Step ${o.id} compensation data`),i.add(o.id),t.startedStepIds=e.steps.map(l=>l.id).filter(l=>i.has(l)),await st(e.pmRoot,t);let d=await o.apply();a=ea(d,`Step ${o.id} result`)}await vt(e,t,"step_applied",o.id),r.add(o.id),t.completedStepIds=e.steps.map(c=>c.id).filter(c=>r.has(c)),ta(t.results,o.id,a,`Step ${o.id} result`),await st(e.pmRoot,t),await vt(e,t,"step_recorded",o.id)}return await vt(e,t,"committing"),t.status="committed",await st(e.pmRoot,t),await vt(e,t,"committed"),{transactionId:t.transactionId,status:"committed",recovered:n,results:Zt(t.results)}}catch(r){if(r instanceof Zs||t.status==="committed")throw r;try{await oa(e,t)}catch(i){throw new AggregateError([r,i],`Workspace transaction failed and compensation failed: ${String(i)}`,{cause:i})}throw r}}async function Xi(e,t,n){try{return zv(await Dv(Dm(e,t),"utf8"),t,n)}catch(r){if(r!==null&&typeof r=="object"&&"code"in r&&F(r))return;throw r}}async function vt(e,t,n,r){await e.onTransition?.({transactionId:t.transactionId,attempt:t.attempt,transition:n,...r===void 0?{}:{stepId:r}})}async function Gv(e,t){let n=new Set,r=Zt();for(let i of t){let o=await i.inspect();o.state==="applied"&&(n.add(i.id),ta(r,i.id,o.result,`Step ${i.id} result`))}e.results=r,e.completedStepIds=t.map(i=>i.id).filter(i=>n.has(i))}async function oa(e,t){t.status="compensating",await st(e.pmRoot,t),await vt(e,t,"compensating");let n=new Set(t.completedStepIds),r=new Set(t.startedStepIds);for(let i of[...e.steps].reverse()){if(!r.has(i.id)&&!n.has(i.id))continue;let o;try{let s=(await i.inspect()).state;o=r.has(i.id)&&(s==="applied"||s==="pending"&&i.compensatePending===!0)}catch{o=r.has(i.id)}o&&(await vt(e,t,"step_compensating",i.id),await Cm({pmRoot:e.pmRoot,transactionId:t.transactionId,step:i},()=>i.compensate(t.compensationData[i.id]))),n.delete(i.id),r.delete(i.id),t.completedStepIds=e.steps.map(s=>s.id).filter(s=>n.has(s)),t.startedStepIds=e.steps.map(s=>s.id).filter(s=>r.has(s)),delete t.results[i.id],delete t.compensationData[i.id],await st(e.pmRoot,t),await vt(e,t,"step_compensated",i.id)}t.status="compensated",await st(e.pmRoot,t),await vt(e,t,"compensated")}async function jm(e){let{pmRoot:t,transactionId:n,author:r}=ia(e),i=Yi(e.lockTtlSeconds,Lm,"Transaction lock TTL"),o=Yi(e.lockWaitMs,Nm,"Transaction lock wait"),s=[...e.steps];if(s.length===0)throw new TypeError("Workspace transaction requires at least one step");let a=s.map(l=>{let u=ra(l.id,"Transaction step id");if(u!==l.id)throw new TypeError("Transaction step id must not contain surrounding whitespace");return u});if(new Set(a).size!==a.length)throw new TypeError("Workspace transaction step ids must be unique");let c={...e,pmRoot:t,transactionId:n,author:r,steps:s,lockTtlSeconds:i,lockWaitMs:o},d=await se(t,Om,i,r,!1,!1,o);try{let l=await Xi(t,n,a);if(l?.status==="abandoned"||l?.abandonment!==void 0)throw Hm(l);let u=l!==void 0;if(l?.status==="committed")return{transactionId:n,status:"committed",recovered:!0,results:Zt(l.results)};let m=await Wv(c,n,r,a,l);return await qv(c,m.journal,u||m.recovered)}finally{await d()}}function Hm(e){let t=e.status!=="abandoned",n=e.abandonment.supersededBy,r=n===void 0?`Retry abandonment without supersededBy to finish retirement of ${JSON.stringify(e.transactionId)}.`:`Retry abandonment with supersededBy ${JSON.stringify(n)} to finish retirement of ${JSON.stringify(e.transactionId)}.`;return new _(t?`Transaction ${e.transactionId} retirement is incomplete`:`Transaction ${e.transactionId} has been abandoned`,g.CONFLICT,{code:"transaction_abandoned",required:t?r:"Use a new transactionId for the replacement plan.",why:t?"Forward replay is fenced, but the recorded retirement has not finished. Preserve its replacement identity.":"An explicitly retired transaction identity cannot be resumed.",...t?{retirement:{state:"pending",superseded_by:n??null},nextSteps:[r]}:{}})}async function KL(e,t){let n=ia({pmRoot:e,transactionId:t,author:"reader"});return Xi(n.pmRoot,n.transactionId)}function Bv(e){return Mv("sha256").update(JSON.stringify(e.stepIds)).digest("hex")}async function YL(e){let t=ia(e),n=Qs(e.reason,"Abandonment reason"),r=e.supersededBy===void 0?void 0:ra(e.supersededBy,"Replacement transaction id");if(r===t.transactionId)throw new TypeError("Replacement transaction id must differ from the abandoned id");let i=Yi(e.lockTtlSeconds,Lm,"Transaction lock TTL"),o=Yi(e.lockWaitMs,Nm,"Transaction lock wait"),s=await se(t.pmRoot,Om,i,t.author,!1,!1,o);try{let a=await Xi(t.pmRoot,t.transactionId);if(a===void 0)throw new _(`Transaction ${t.transactionId} was not found`,g.NOT_FOUND);if(a.status==="committed")throw new _(`Transaction ${t.transactionId} is committed and cannot be abandoned`,g.CONFLICT,{code:"transaction_committed",required:"Plan a separate explicit corrective mutation.",why:"Recovery cannot silently undo committed work."});if(a.abandonment!==void 0&&a.abandonment.supersededBy!==r)throw Hm(a);if(a.status==="abandoned")return a;let c=e.resolveSteps(structuredClone(a));if(JSON.stringify(c.map(d=>d.id))!==JSON.stringify(a.stepIds))throw Fm(t.transactionId);if(a.abandonment===void 0){if(r!==void 0&&await Xi(t.pmRoot,r)!==void 0)throw new _(`Replacement transaction ${r} already exists`,g.CONFLICT);a.schemaVersion=2,a.abandonment={reason:n,author:t.author,...r===void 0?{}:{supersededBy:r}},await st(t.pmRoot,a)}return a.status!=="compensated"&&await oa({...e,...t,steps:c},a),await Jv(a,t.pmRoot,i,o),a.status="abandoned",await st(t.pmRoot,a),a}finally{await s()}}async function Jv(e,t,n,r){let i=Bv(e);if((await We(bn(t),re)).some(a=>a.op==="transaction_abandon"&&a.context?.transaction_id===e.transactionId&&a.context?.attempt===e.attempt&&a.context?.plan_digest===i))return;let s=e.abandonment;await xn({pmRoot:t,author:s.author,lockTtlSeconds:n,lockWaitMs:r,op:"transaction_abandon",message:s.reason,context:{transaction_id:e.transactionId,attempt:e.attempt,plan_digest:i,...s.supersededBy===void 0?{}:{superseded_by:s.supersededBy}}})}var vr={type:"string",minLength:1,maxLength:128,pattern:"\\S"},Zi={type:"array",minItems:1,maxItems:fs,items:vr},Um={...Zi,items:{...vr,pattern:"^(?!(?:.*\\.)?(?:__proto__|constructor|prototype)(?:\\.|$))[a-zA-Z_][a-zA-Z0-9_]*(?:\\.[a-zA-Z_][a-zA-Z0-9_]*){0,7}$"}},Vv={type:"object",additionalProperties:!1,required:["id","rule"],properties:{id:{type:"string",minLength:1,maxLength:128,pattern:"^[a-zA-Z0-9][a-zA-Z0-9._-]*$"},description:{type:"string",minLength:1,maxLength:500,pattern:"\\S"},effect:{enum:["advise","warn","refuse"]},subject:{type:"object",additionalProperties:!1,properties:{...Object.fromEntries(["types","tags","statuses","operations","parents"].map(e=>[e,Zi])),dependency:{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:vr,id:vr}}}},rule:{oneOf:[{type:"object",additionalProperties:!1,required:["kind","fields"],properties:{kind:{const:"require_fields"},fields:Um}},{type:"object",additionalProperties:!1,required:["kind","authors"],properties:{kind:{const:"authors"},authors:Zi}},...["field_writers","approval"].map(e=>({type:"object",additionalProperties:!1,required:["kind","fields","authors"],properties:{kind:{const:e},fields:Um,authors:Zi}})),{type:"object",additionalProperties:!1,required:["kind","allowed"],properties:{kind:{const:"transition"},allowed:{type:"array",maxItems:fs,items:{type:"array",minItems:2,maxItems:2,items:vr}}}}]}}},QL={$schema:"https://json-schema.org/draft/2020-12/schema",title:"pm workflow policy registry",type:"object",additionalProperties:!1,required:["version","policies"],properties:{version:{const:1},enforcement:{enum:["advise","refuse"],default:"advise"},policies:{type:"array",maxItems:Kd,items:Vv}}};async function zm(e,t,n,r){let i=await Dt(e).catch(()=>null);return i===null?{check:{name:"completeness",status:"error",ok:!1,details:{policy_registry_readable:!1,policy_registry_path:"schema/policies.json",remediation_hint:"Repair schema/policies.json, then rerun pm validate."}},warnings:["validate_completeness_policy_registry_unreadable"]}:Wm(i,t,n,r)}function Kv(e,t,n){return e===0?"undeclared":t===0?"empty":n===0?"inapplicable":n===t?"covered":"partial"}function Wm(e,t,n=5,r=!1){let i=[],o=new Map,s=e.policies.filter(y=>y.rule.kind==="require_fields"),a=s.filter(y=>y.subject?.operations===void 0),c=new Set,d=0,l=0,u=0,m=0,p=0,f=Zd(e);for(let y of t){let w=f({operation:"",author:"",before:y,after:y,completeness_only:!0});d+=+(w.decisions.length>0),l+=w.decisions.length,w.decisions.forEach(x=>c.add(x.policy_id));let v=w.decisions.filter(x=>!x.satisfied);if(v.length===0)continue;m+=1;let k=o.get(y.type)??{items:0,violations:0,missing_fields:0};k.items+=1;for(let x of v)u+=1,k.violations+=1,k.missing_fields+=x.missing_fields.length,x.effect==="refuse"&&(p+=1),i.length<n&&i.push({id:y.id,type:y.type,status:y.status,decision:x});o.set(y.type,k)}let h=r||p>0?"error":u>0?"warn":"ok";return{check:{name:"completeness",status:h,ok:h==="ok",details:{scope:"operation_independent_require_fields",declared_requirement_count:s.length,state_requirement_count:a.length,applicable_requirement_count:c.size,requirement_application_count:l,governed_items:d,ungoverned_items:t.length-d,contract_status:Kv(s.length,t.length,d),applied_policy_ids:[...c].sort().slice(0,Math.max(0,n)),applied_policy_ids_truncated:c.size>Math.max(0,n),checked_items:t.length,incomplete_items:m,violation_count:u,refused_violations:p,missing_by_type:Object.fromEntries(o),violations:i,violations_truncated:i.length<u,enforcement:e.enforcement}},warnings:[...u>0?[`validate_completeness_missing_fields:${u}`]:[],...r?["validate_completeness_source_incomplete"]:[]]}}import Yv from"node:path";function Xv(){return{version:1,enforcement:"advise",policies:[...[["Epic",["goal","objective","body"]],["Story",["description","value","acceptance_criteria"]],["Decision",["body","resolution"]],["Feature",["acceptance_criteria","expected_result"]],["Task",["description"]],["Issue",["repro_steps","expected_result"]],["Chore",["description"]]].map(([t,n])=>({id:`completeness-${t.toLowerCase()}`,effect:"advise",description:`Evidence expected when ${t} work reaches completion.`,subject:{types:[t],statuses:["closed"]},rule:{kind:"require_fields",fields:[...n]}})),{id:"completeness-resolution",effect:"advise",subject:{statuses:["closed"]},rule:{kind:"require_fields",fields:["resolution","expected_result","actual_result"]}}]}}function Bm(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{throw new _("Policy definition must be valid JSON.",g.USAGE)}if(typeof t!="object"||t===null||Array.isArray(t))throw new _("Policy definition must be an object.",g.USAGE);return t}async function Zv(e,t){let n=M(process.cwd(),e.path);await ie(n);let r=await T(n);return{pmRoot:n,settings:r,author:q(t,r.author_default)}}function qm(e,t,n,r){if(e==="policy-mode")return _s({...n,enforcement:t});let i=n.policies.filter(a=>a.id!==t);if(e==="policy-remove")return{...n,policies:i};let o=hs(r.definition),s=_s({...n,policies:[...i,o].sort((a,c)=>a.id.localeCompare(c.id))});if(Buffer.byteLength(`${JSON.stringify(s,null,2)}
|
|
6
|
+
`)>Ru)throw new _("Policy registry exceeds its byte ceiling.",g.USAGE);return s}async function Gm(e,t,n,r){if(n.dryRun)return{policy_result:!0,action:e,changed:!1,result:qm(e,t,await Dt(r.pmRoot),n)};let i=await Sn({pmRoot:r.pmRoot,filePath:Yv.join(r.pmRoot,"schema","policies.json"),op:`schema:${e}`,author:r.author,message:n.message,lockTtlSeconds:r.settings.locks.ttl_seconds,lockWaitMs:r.settings.locks.wait_ms,mutate(o){let s=qm(e,t,Au(o),n);return{raw:`${JSON.stringify(s,null,2)}
|
|
7
|
+
`,result:s}}});return{policy_result:!0,action:e,changed:i.changed,result:i.result}}async function Qv(e,t,n){let r,i=await Lu({...n,id:e,op:"policy_approve",message:t.message,resolveHistoryContext:()=>({workflow_approval:r}),async mutate(o){let a=(await Dt(n.pmRoot)).policies.find(c=>c.id===t.policy);if(!a||a.rule.kind!=="approval")throw new _("--policy must name an approval rule.",g.USAGE);if(!a.rule.authors.includes(n.author))throw new _("This actor is not a declared approver.",g.CONFLICT);return await Iu(n.pmRoot,o.metadata.id),r={policy_id:a.id,policy_fingerprint:Yd(a),content_fingerprint:Xd(a,{...o.metadata,body:o.body})},{changedFields:[]}}});return{policy_result:!0,action:"policy-approve",changed:!0,result:{id:i.item.id,...r,warnings:i.warnings}}}function ek(e,t){let n=Bm(t),r=hs({...n,id:n.id===void 0?e:n.id});if(e!==void 0&&e.trim()!==r.id)throw new _("Policy id operand does not match definition.id.",g.USAGE,{required:"Use the same policy id operand and definition.id, or supply only one of them.",nextSteps:["Omit the policy id operand to use definition.id, or omit definition.id to use the operand."]});return r}async function gN(e,t,n={},r={}){if(!li.includes(e))throw new _("Unknown workflow policy action.",g.USAGE);if(e==="policy-presets")return{policy_result:!0,action:e,changed:!1,result:Xv()};let i=await Zv(r,n.author);if(e==="policies")return{policy_result:!0,action:e,changed:!1,result:await Dt(i.pmRoot)};if(e==="policy-put"){let l=ek(t,n.definition);return Gm(e,l.id,{...n,definition:l},i)}if(!t?.trim())throw new _(`schema ${e} requires an operand.`,g.USAGE);if(["policy-remove","policy-mode"].includes(e))return Gm(e,t,n,i);if(e==="policy-approve"){if(n.dryRun)throw new _("Use policy-check to preview; policy-approve records an approval.",g.USAGE);return Qv(t,n,i)}let o=W(i.settings,U()),s=await ge(i.pmRoot,t,i.settings.id_prefix,i.settings.item_format,o.type_to_folder);if(!s)throw new _(`Item ${t} not found.`,g.NOT_FOUND);let{document:a}=await ye(s,{schema:i.settings.schema}),c={...a.metadata,body:a.body},d=n.definition===void 0?c:{...c,...Bm(n.definition)};if(d.id!==c.id)throw new _("Policy preview cannot change the item id.",g.USAGE);return{policy_result:!0,action:e,changed:!1,result:await Cu(i.pmRoot,await Dt(i.pmRoot),{operation:"update",author:i.author,before:c,after:d,completeness_only:n.definition===void 0})}}import{createHash as Vm}from"node:crypto";import kr from"node:fs/promises";import br from"node:path";function De(e,t){throw new _(e,g.USAGE,t)}var tk="2026-07-15T06:22:12.276Z",nk=Date.parse(tk),rk=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],Jm=e=>typeof e=="string"?e:"",Km=e=>{let t=e??{},n=Jm(t.author).trim().toLowerCase(),r=Number(["","unknown"].includes(n)),i=+(Date.parse(Jm(t.ts))>=nk);return rk[r][i]};function Ym(e,t,n=20,r=new Set,i=!1){let o=[],s=[],a={legacy_unknown:0,actionable_unknown:0},c=Math.max(0,n),d=0,l=0,u=0;for(let[m,p]of t.split(/\r?\n/).entries()){let f;try{f=JSON.parse(p)}catch{continue}d+=1;let h=Km(f);if(h!=="attributed"){if(l+=1,h==="actionable_unknown"&&r.has(`${e}:${m+1}`)){u+=1;continue}a[h]+=1,i&&h==="actionable_unknown"&&s.push({item_id:e,line:m+1}),o.length<c&&o.push({item_id:e,line:m+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:o,samples_truncated:a.legacy_unknown+a.actionable_unknown>o.length,actionable_events:s}}var TN=(e,t,n=20,r=new Set)=>Ym(e,t,n,r);function Xm(e){let t=new Set;for(let n of e.split(/\r?\n/)){let r;try{r=JSON.parse(n)}catch{continue}let o=(typeof r=="object"&&r!==null&&typeof r.context=="object"&&r.context!==null?r.context:{}).author_acknowledgment;if(!(typeof o!="object"||o===null||!Array.isArray(o.events)))for(let s of o.events)typeof s=="object"&&s!==null&&typeof s.item_id=="string"&&Number.isSafeInteger(s.line)&&t.add(`${s.item_id}:${String(s.line)}`)}return t}var xr=async(e,t=20,n=!1)=>{let r=br.join(e,"history"),i;try{i=(await kr.readdir(r)).filter(w=>w.endsWith(".jsonl")).sort((w,v)=>w.localeCompare(v))}catch{i=[]}let o=new Set,s=[],a=[],c=0,d=0,l=0,u=0,m=0,p=0,f="_workspace.jsonl",h=new Set;if(i.includes(f))try{h=Xm(await kr.readFile(br.join(r,f),"utf8"))}catch{h=new Set}for(let w of i){let v;try{v=await kr.readFile(br.join(r,w),"utf8")}catch{continue}let k=w.slice(0,-6),x=Ym(k,v,t-s.length,h,n);c+=1,d+=x.checked_events,l+=x.unknown_event_count,u+=x.legacy_unknown_event_count,m+=x.actionable_unknown_event_count,p+=x.acknowledged_actionable_event_count,x.unknown_event_count>0&&o.add(k),s.push(...x.samples),n&&a.push(...x.actionable_events)}let y=u+m;return{checked_streams:c,checked_events:d,unknown_event_count:l,legacy_unknown_event_count:u,actionable_unknown_event_count:m,acknowledged_actionable_event_count:p,affected_item_ids:[...o].sort((w,v)=>w.localeCompare(v)),samples:s,samples_truncated:y>s.length,...n?{actionable_events:a}:{}}};function ik(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 ok(e){try{return Xm(await kr.readFile(br.join(e,"history","_workspace.jsonl"),"utf8"))}catch{return new Set}}function sk(e){return(e.item_id===re||/^[a-z0-9][a-z0-9-]*$/iu.test(e.item_id))&&Number.isSafeInteger(e.line)&&e.line>=1}function ak(e,t,n){let r=n[e.line-1]??"",i;try{i=JSON.parse(r)}catch{De(`Unknown-author acknowledgment target ${e.item_id}:${e.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}return Km(i)!=="actionable_unknown"&&De(`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:Vm("sha256").update(r).digest("hex"),disposition:t.has(`${e.item_id}:${e.line}`)?"already_acknowledged":"actionable"}}async function Zm(e,t,n){let r=t.events??[],i=+(t.all_actionable===!0)+ +(r.length>0);i===0&&De("Specify exactly one selector: events or all_actionable.",{code:"history_author_acknowledge_selector_required"}),i>1&&De("Author acknowledgment accepts either explicit events or all_actionable, not both.",{code:"history_author_acknowledge_selector_conflict"}),(!Number.isSafeInteger(n)||n<0)&&De("Author acknowledgment coordinate_limit must be a non-negative integer.",{code:"history_author_acknowledge_preview_limit_invalid"});let o=ik(t.all_actionable===!0?(await xr(e,0,!0)).actionable_events:r),s=await ok(e),a=new Map;for(let m of o)if(sk(m)||De(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"}),!a.has(m.item_id))try{a.set(m.item_id,(await kr.readFile(br.join(e,"history",`${m.item_id}.jsonl`),"utf8")).split(/\r?\n/u))}catch{De(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}let c=o.map(m=>ak(m,s,a.get(m.item_id))),d=t.all_actionable===!0?"all_actionable":"events",l=Vm("sha256").update(JSON.stringify({version:1,selection:d,coordinates:c})).digest("hex"),u=c.filter(({disposition:m})=>m==="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 ON(e,t,n=50){return(await Zm(e,t,n)).plan}function ck(e,t){let n=e.length>0;return n&&t&&De("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&&De("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:dk(e),all_actionable:t}}function dk(e){return e.map(t=>{let n=t.lastIndexOf(":"),r=t.slice(0,n).trim(),i=Number(t.slice(n+1)),o=r===re||/^[a-z0-9][a-z0-9-]*$/iu.test(r);return(n<1||!o||!Number.isSafeInteger(i)||i<1)&&De(`history-author-acknowledge --event expects <item-id>:<one-based-line>, received "${t}".`,{code:"history_author_acknowledge_target_unreadable"}),{item_id:r,line:i}})}function PN(e,t){let n=ck(Zu(t.historyEvent),t.allActionable===!0||t.all_actionable===!0);return lk(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 lk(e,t){let n=t.reviewer?.trim()??"",r=t.attributed_author?.trim()??"",i=t.reason?.trim()??"",o=await Zm(e,t,t.coordinate_limit??50);if(t.dry_run===!0)return{dry_run:!0,mutated:!1,acknowledged:0,outcome:"preview",exit_code:g.SUCCESS,plan:o.plan};if([n.length>0,n.toLowerCase()!=="unknown",r.length>0,r.toLowerCase()!=="unknown",i.length>0].includes(!1)&&De("Author acknowledgment requires events, reviewer, attributed_author, and reason.",{code:"history_author_acknowledge_required_values_missing"}),t.plan_fingerprint?.trim()||De("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()!==o.plan.plan_fingerprint)throw new _("Author acknowledgment selection changed after preview; no history was mutated.",g.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=o.completeCoordinates.filter(({disposition:u})=>o.plan.selection.kind==="events"||u==="actionable").map(({item_id:u,line:m})=>({item_id:u,line:m}));if(a.length===0)return{dry_run:!1,mutated:!1,acknowledged:0,outcome:"no_effect",exit_code:g.NO_EFFECT,plan:o.plan};let c=await T(e),d=await xn({pmRoot:e,op:"history:author-acknowledge",author:n,context:{author_acknowledgment:{events:a,attributed_author:r}},message:i,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),l=o.plan.actionable_count>0&&o.plan.already_acknowledged_count>0?{outcome:"partial_effect",exit_code:g.PARTIAL_EFFECT}:{outcome:"effect",exit_code:g.SUCCESS};return{dry_run:!1,mutated:!0,acknowledged:a.length,...l,plan:o.plan,history_path:d.historyPath}}import{execFile as uk}from"node:child_process";import Qm from"node:path";function ep(e,t){return new Promise((n,r)=>{uk("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:4*1024*1024},(i,o)=>{i?r(i):n(o)})})}function tp(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 FN(e){let t=/^(\d+):(\d+)$/u.exec(e.trim()),n=t?{start:Number(t[1]),end:Number(t[2])}:void 0;if(tp(n),!n)throw new RangeError("Source line range must use start:end.");return n}function mk(e){let t=new Map;for(let n of e.split(`
|
|
8
|
+
`)){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 pk(e){let t=e.split("\0"),n=new Map;for(let r=0;r+1<t.length;r+=2){let i=t[r]?.trim();if(!i)continue;let o=[...new Set(t[r+1]?.match(/\bpm-[a-z0-9][a-z0-9-]{2,63}\b/gu)??[])].sort((s,a)=>s.localeCompare(a));n.set(i,o)}return n}async function fk(e){let t=Qm.relative(e.workspaceRoot,Qm.resolve(e.workspaceRoot,e.sourcePath)),n=await ep(e.workspaceRoot,["blame","--line-porcelain","-L",`${e.lineRange.start},${e.lineRange.end}`,"--",t]),r=await ep(e.workspaceRoot,["log","-n","256","--format=%H%x00%B%x00","--",t]);return{commitLines:mk(n),commitItems:pk(r),available:!0}}function hk(e){let t=e.current.nodes.at(-1),n=e.current.kinds.length+1,r;for(let i of e.graph.incidentEdges(t)){let o=i.source===t,s=o?i.target:i.source;if((e.visitedDepth.get(s)??Number.POSITIVE_INFINITY)<n)continue;e.visitedDepth.set(s,n);let a=e.graph.registry().require(i.kind),c={nodes:[...e.current.nodes,s],kinds:[...e.current.kinds,o?i.kind:a.inverse??i.kind]};e.details.get(s)?.type?.toLowerCase()==="decision"?(r=n,e.found.push(c)):e.queue.push(c)}return r}function _k(e){let t=[{nodes:[e.itemId],kinds:[]}],n=new Map([[e.itemId,0]]),r=[],i;for(;t.length>0;){let o=t.shift(),s=o.kinds.length;i!==void 0&&s>=i||s>=e.maxDepth||(i=hk({current:o,graph:e.graph,details:e.details,visitedDepth:n,queue:t,found:r})??i)}return r.sort((o,s)=>o.nodes.join("\0").localeCompare(s.nodes.join("\0"))),r}function gk(e,t,n){let r=em(t);if(!r.graph.hasNode(e))return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let i=_k({itemId:e,maxDepth:n,graph:r.graph,details:new Map(r.details.map(a=>[a.id,a]))}),o=i[0];if(!o)return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let s=[...new Set(i.map(a=>a.nodes.at(-1)))];return{status:s.length===1?"found":"ambiguous",nodes:o.nodes,kinds:o.kinds,alternative_decision_ids:s.slice(1)}}async function yk(e){if(!e.lineRange)return{commitLines:new Map,commitItems:new Map,available:!0};try{return await fk({workspaceRoot:e.workspaceRoot,sourcePath:e.paths[0],lineRange:e.lineRange})}catch{return{commitLines:new Map,commitItems:new Map,available:!1}}}function wk(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 vk(e){return[...e.commitLines.keys()].filter(t=>(e.commitItems.get(t)?.length??0)>0)}async function np(e){tp(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 yk(e),r=vk(n),i=new Map;for(let o of e.candidates){let s=[...n.commitLines.entries()].filter(([l])=>n.commitItems.get(l)?.includes(o.item.id)),a=s.reduce((l,[,u])=>l+u,0),c=gk(o.item.id,e.corpus,t),d=wk({hasLineRange:e.lineRange!==void 0,attributionAvailable:n.available,contributionLines:a,decisionStatus:c.status});i.set(o.item.id,{score:a*100+o.files.length*10+Math.max(0,9-Math.floor((Date.now()-Date.parse(o.item.updated_at))/(720*60*60*1e3))),contribution_lines:a,evidence:[...o.files.map(l=>({kind:"linked_file",reference:l.path})),...s.map(([l,u])=>({kind:"git_commit",reference:l.slice(0,12),contribution_lines:u}))],rationale:{value:o.item.value?.trim()||null,why_now:o.item.why_now?.trim()||null,outcome:o.item.outcome?.trim()||null,objective:o.item.objective?.trim()||null},decision_path:c,ambiguities:d})}return{explanations:i,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}}}var Sr=["software-delivery","research","agent-evaluation","operations"];function rp(e,t,n,r,i){return{id:e,measurement_id:t,owner_item_id:n,scope:{kind:"active"},ceiling:r,lifetime:"hold",enforcement:i,negative_control:{cases:[{observed:r,expected:"pass"},{observed:r+1,expected:"fail"}]}}}function Qi(e,t,n,r,i){let o=`preset-${e}`,s=i.map(c=>({id:`${o}-missing-${c}`,description:`Active items missing ${c} evidence.`,source:{kind:"links",link:c,state:"missing"}})),a=s.map(c=>rp(`${c.id}-zero`,c.id,r,0,"warn"));return{id:e,title:t,description:n,declarations:{measurements:s,assertions:a,gates:[{id:`${o}-readiness`,description:n,assertion_ids:a.map(c=>c.id),triggers:["ci","scheduled"]}]}}}function eo(e,t){return e==="software-delivery"?Qi(e,"Software delivery","Warn when active delivery work lacks executable tests or documentation.",t,["tests","docs"]):e==="research"?Qi(e,"Research","Warn when active research work lacks reproducibility files or documentation.",t,["files","docs"]):e==="agent-evaluation"?Qi(e,"Agent evaluation","Warn when active evaluation work lacks executable scenarios or recorded artifacts.",t,["tests","files"]):Qi(e,"Operations","Warn when active operational work lacks runbook documentation or repair evidence.",t,["docs","files"])}function ip(e,t,n,r={}){return Xs(e,eo(t,n).declarations,r)}async function op(e,t){let n=new Set(e.terminal_statuses??["closed","canceled"]),r={...e,items:e.items.filter(o=>!n.has(o.status))};return await Promise.all(["files","tests","docs"].map(async o=>{let s={id:`derived-active-missing-${o}`,description:`Observed active items missing ${o} evidence.`,source:{kind:"links",link:o,state:"missing"}},c=(await Ys(s,r)).value,d=rp(`${s.id}-ceiling`,s.id,t,c,"observe"),l=`active-missing-${o}`;return{id:l,population_size:r.items.length,scope:{kind:"active"},observed:c,declarations:{measurements:[s],assertions:[d],gates:[{id:`derived-${l}`,description:`Observe the accepted ${o} evidence baseline.`,assertion_ids:[d.id],triggers:["ci","scheduled"]}]}}}))}function sp(e,t,n={}){return Xs(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 ap(e,t,n,r={}){let i=t.enforcement==="observe"?"warn":"block";if(t.enforcement==="block"||n!==i)throw new TypeError(`assurance assertion ${t.id} promotion must be ${t.enforcement} -> ${i}`);return Vi(e,"assertion",{...t,enforcement:n},{...r,message:r.message??`Promote assurance assertion ${t.id} from ${t.enforcement} to ${n}`})}import lp from"node:fs/promises";import{createRequire as kk}from"node:module";import Te from"node:path";function cp(e,t){let n=Te.relative(t,e);if(n.length>0&&n!==".."&&!n.startsWith(`..${Te.sep}`)&&!Te.isAbsolute(n))return n.split(Te.sep).join("/");let r=Te.resolve(e),i=0xcbf29ce484222325n;for(let s=0;s<r.length;s+=1)i^=BigInt(r.charCodeAt(s)),i=BigInt.asUintN(64,i*0x100000001b3n);return`<external>/${i.toString(16).padStart(16,"0")}/${Te.basename(Te.dirname(e))}/package.json`}function bk(e){return e.includes(`${Te.sep}.pnpm${Te.sep}`)?"pnpm":e.includes(`${Te.sep}node_modules${Te.sep}`)?"npm":"other"}async function dp(e){try{let t=JSON.parse(await lp.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 sa(e){try{return await lp.realpath(e)}catch{return Te.resolve(e)}}async function up(e,t,n=et(import.meta.url,["../../.."])){let r=await sa(t),i=await sa(Te.join(n,"package.json")),o=await dp(i),s=new Map;o!==void 0&&s.set(i,{version:o,path:cp(i,r),layout:"host",consumers:["pm-cli-host"]});for(let d of e)try{let l=kk(d.entry_path).resolve("@unbrained/pm-cli/package.json"),u=await sa(l),m=await dp(u);if(m===void 0)continue;let p=u,f=s.get(p);if(f){f.consumers.includes(d.name)||(f.consumers.push(d.name),f.consumers.sort((h,y)=>h.localeCompare(y)));continue}s.set(p,{version:m,path:cp(u,r),layout:bk(u),consumers:[d.name]})}catch{}let a=[...s.values()].sort((d,l)=>d.path.localeCompare(l.path)),c=o===void 0?[]:a.filter(d=>d.version!==o);return{host_version:o??null,copies:a,mismatches:c,warnings:c.map(d=>`extension_host_pm_cli_version_skew:${o}:${d.version}:${d.consumers.join("+")}`)}}import aa from"node:fs/promises";import ca from"node:path";var mp=8388608,xk=new Set(["resolved","failed"]),Sk=[{kind:"boolean",matches:e=>typeof e=="boolean"||typeof e=="string"&&/^(?:true|false)$/iu.test(e.trim())},{kind:"single_digit",matches:e=>typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=9||typeof e=="string"&&/^\d$/u.test(e.trim())}];function at(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function da(e){return Sk.find(t=>t.matches(e))?.kind}function la(e){let t=new Map,n=0,r=0;return{entries:e.map(o=>{let s=at(o.agent_provenance)?o.agent_provenance:void 0;if(s===void 0||!Jl(o).ok)return o;let a={},c=!1;for(let[l,u]of Object.entries(s)){let m=at(u)?da(u.value):void 0;if(m===void 0){a[l]=u;continue}c=!0,r+=1;let p=o.agent_harness??"unknown",f=`${p}\0${l}\0${m}`,h=t.get(f)??{harness:p,dimension:l,kind:m,count:0};h.count+=1,t.set(f,h)}if(!c)return o;n+=1;let d={...o};return Object.keys(a).length===0?delete d.agent_provenance:d.agent_provenance=a,Si(o,d,{retainPriorRecord:!0,retainPriorRecordHash:!1})}),receipt:{changed:n>0,events_changed:n,observations_removed:r,invalid_values:[...t.values()].sort((o,s)=>o.harness.localeCompare(s.harness)||o.dimension.localeCompare(s.dimension)||o.kind.localeCompare(s.kind))}}}async function pp(e){let t=[];for(let n of await fp(e)??[])try{let r=await aa.readFile(ca.join(e,"history",n),"utf8");for(let i of r.split(`
|
|
9
|
+
`)){if(i.trim().length===0)continue;let o=hp(i);if(o===null||!at(o.agent_provenance))continue;if(Object.values(o.agent_provenance).some(a=>at(a)&&da(a.value)!==void 0)){t.push(n.slice(0,-6));break}}}catch{}return t}async function fp(e){try{return(await aa.readdir(ca.join(e,"history"))).filter(t=>t.endsWith(".jsonl")).sort()}catch{return null}}async function Ek(e,t,n){let r;try{r=await aa.open(ca.join(e,"history",t),"r");let i=(await r.stat()).size,o=Math.min(i,Math.max(0,n)),s=Buffer.alloc(o),{bytesRead:a}=await r.read(s,0,o,0),c=s.subarray(0,a).toString("utf8"),d=a>=i,l=c.lastIndexOf(`
|
|
10
|
+
`),u=c;return d||(u=l===-1?"":c.slice(0,l+1)),{content:u,bytesRead:a,complete:d}}catch{return null}finally{await r?.close()}}function hp(e){try{let t=JSON.parse(e);return at(t)?t:null}catch{return null}}function Rk(e,t,n){let r=typeof e.agent_harness=="string"?e.agent_harness:void 0;if(r===void 0)return;let i=at(e.agent_provenance)?e.agent_provenance:{};if(Object.entries(i).forEach(([s,a])=>{if(!at(a))return;let c=da(a.value);if(!c)return;let d=`${r}\0${s}\0${c}`,l=n.get(d)??{harness:r,dimension:s,kind:c,count:0};l.count+=1,n.set(d,l)}),!at(e.context))return;let o=e.context.agent_provenance_outcomes;at(o)&&Object.entries(o).forEach(([s,a])=>{if(!at(a)||typeof a.resolver!="string"||!xk.has(String(a.status)))return;let c=`${r}\0${s}\0${a.resolver}`,d=t.get(c)??{harness:r,dimension:s,resolver:a.resolver,attempts:0,successes:0};d.attempts+=1,a.status==="resolved"&&(d.successes+=1),t.set(c,d)})}function Ak(e,t,n,r,i,o){let s=i;for(let a of e.split(`
|
|
11
|
+
`)){if(a.trim().length===0)continue;if(s>=r)return{eventsRead:s,truncated:!0};s+=1;let c=hp(a);if(c===null){o.malformed_events+=1;continue}if(typeof c.ts=="string"&&Pt(c.ts)){let d=new Date(c.ts).toISOString();(o.earliest_event_at===null||d<o.earliest_event_at)&&(o.earliest_event_at=d),(o.latest_event_at===null||d>o.latest_event_at)&&(o.latest_event_at=d)}Rk(c,t,n)}return{eventsRead:s,truncated:!1}}function Ik(e,t,n){return n?[...e.filter(r=>r.attempts>0&&r.successes===0).map(r=>`provenance_resolver_zero_success:${r.harness}:${r.dimension}:${r.resolver}:${String(r.attempts)}`),...t.map(r=>`provenance_value_domain_invalid:${r.harness}:${r.dimension}:${r.kind}:${String(r.count)}`)]:[]}async function _p(e,t=1e4){if(!Number.isSafeInteger(t)||t<0)throw new RangeError("Provenance event limit must be a non-negative safe integer.");let n={scope:"history_prefix",event_limit:t,byte_limit:mp,bytes_read:0,events_read:0,truncated:!1,unreadable_sources:0,malformed_events:0,earliest_event_at:null,latest_event_at:null,complete:!1},r=new Map,i=new Map,o=0,s=0,a=!1,c=await fp(e);c===null&&(n.unreadable_sources+=1);for(let u of c??[]){let m=await Ek(e,u,Math.max(0,mp-s));if(m===null){n.unreadable_sources+=1;continue}s+=m.bytesRead;let p=Ak(m.content,r,i,t,o,n);if(o=p.eventsRead,p.truncated){a=!0;break}if(!m.complete){a=!0;break}}let d=[...r.values()].sort((u,m)=>u.harness.localeCompare(m.harness)||u.dimension.localeCompare(m.dimension)||u.resolver.localeCompare(m.resolver)),l=[...i.values()].sort((u,m)=>u.harness.localeCompare(m.harness)||u.dimension.localeCompare(m.dimension)||u.kind.localeCompare(m.kind));return n.bytes_read=s,n.events_read=o,n.truncated=a,n.complete=!a&&n.unreadable_sources===0&&n.malformed_events===0,{outcomes:d,sample:n,invalid_values:l,warnings:Ik(d,l,n.complete),events_read:o,truncated:a}}var gp=25;function Ck(e,t,n=[]){let r=["list","--status",e,...n],i=["--assignee-filter","unassigned"],o=["--updated-before",`-${t}h`];return{unowned:K([...r,...i]),idle:K([...r,...o]),stale:K([...r,...i,...o])}}function yp(e,t){let n=e.items.length>gp;return{count:e.count,items:e.items.slice(0,gp),...n?{truncated:!0}:{},sweep:t}}function wp(e,t,n=[]){let r=Ck(t.in_progress,e.threshold_hours,n),i=(s,...a)=>`pm ${s} <id>${[...a,...n].map(c=>` ${hi(c)}`).join("")}`,o=[...e.unowned.count>0?[`in_progress_unowned:${e.unowned.count}`]:[],...e.idle.count>0?[`in_progress_idle:${e.idle.count}`]:[]];return{warnings:o,details:o.length===0?void 0:{threshold_hours:e.threshold_hours,threshold_setting:"mutation_guard.stale_in_progress_hours",unowned:yp(e.unowned,r.unowned),idle:yp(e.idle,r.idle),item_remedies:{claim:i("claim"),take_over_idle:i("claim","--takeover-stale"),return_to_open:i("update","--status",t.open)}},remediation:{stale_in_progress_items:r.stale,in_progress_unowned:r.unowned,in_progress_idle:r.idle}}}import $k from"node:fs/promises";function ua(e){if(!e.itemDocument||e.force)return[];let t=e.itemDocument.metadata?.assignee?.trim();if(!t||t===e.author)return[];let n=xl(t),r=Je(e.settings);if(r.ownership_enforcement==="strict")throw new _(`Item ${e.subjectId} is assigned to ${n}. Use --force to override.`,g.CONFLICT);return r.ownership_enforcement==="warn"?[`ownership_warning:assignee_conflict:${e.subjectId}:${n}`]:[]}async function vp(e){if(!Is(e.pmRoot))return;let t=await ge(e.pmRoot,e.subject.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder),n=t===null?Tt:(await ye(t,{schema:e.settings.schema}).catch(()=>null))?.document;n!==void 0&&lr(e.pmRoot,n,e.subject.id)}async function Tk(e){let t=await B(e.subject.historyPath);if(t!==e.historyRawBeforeLock)throw await vp(e),new _(`History for ${e.subject.id} changed while waiting for lock; retry ${e.operation}.`,g.CONFLICT);let n=await ge(e.pmRoot,e.subject.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder),r=n?e.readItem?await e.readItem(n):await ye(n,{schema:e.settings.schema}):null;if((r?.raw??null)!==(e.currentItemRawBeforeLock??null))throw await vp(e),new _(`Item ${e.subject.id} changed while waiting for lock; retry ${e.operation}.`,g.CONFLICT);return{historyRawUnderLock:t,locatedUnderLock:n,loadedItemUnderLock:r}}async function to(e){let t=e.writeHistoryRaw??ee;try{await t(e.historyPath,e.nextHistoryRaw),await dr(e.historyPath)}catch(n){try{e.historyRawUnderLock===null?await $k.rm(e.historyPath,{force:!0}):await t(e.historyPath,e.historyRawUnderLock),await dr(e.historyPath)}catch(r){throw new AggregateError([n,r],`History rewrite failed and rollback also failed: ${String(n)}`)}throw n}}async function kp(e){let t=[...ua({itemDocument:e.itemDocument,subjectId:e.subject.id,author:e.author,force:e.force,settings:e.settings})],n=await se(e.pmRoot,e.subject.id,e.settings.locks.ttl_seconds,e.author,!!e.force,e.settings.governance.force_required_for_stale_lock,e.settings.locks.wait_ms);try{let r=await Tk({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:e.operation}),i=Tt;if(lr(e.pmRoot,r.loadedItemUnderLock?.document??i,e.subject.id),await e.applyRewrite(r),Is(e.pmRoot)){let o=await ge(e.pmRoot,e.subject.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder),s=o===null?i:(await ye(o,{schema:e.settings.schema})).document;Ri(e.pmRoot,s,e.subject.id)}return e.applyPostRewrite&&t.push(...await e.applyPostRewrite(r)),t}finally{await n()}}function Ok(e,t,n){if(n.raw===null)throw new _(`No history stream exists for ${e}.`,g.NOT_FOUND);if(n.entries.length===0)throw new _(`No history entries exist for ${e}; nothing to ${t.slice(8)}.`,g.USAGE)}async function ma(e){let{subject:t,settings:n,operation:r,options:i}=e,o=await Nl(t.historyPath,t.id),s=o.entries.length===0&&t.located!==null?e.reseed:void 0;s===void 0&&Ok(t.id,r,o);let a=t.located?await ye(t.located,{schema:n.schema}):null,c=q(i.author,n.author_default),d={raw:o.raw??"",entries:o.entries,verification:cr(o.entries),loadedItem:a,author:c},l=await(s===void 0?e.transform(d):s(d,{absent:o.raw===null})),u=cr(l.rewrittenEntries);if(!u.ok)throw new _(`${r} produced an invalid rewritten chain (${u.errors.join(", ")}).`,g.GENERIC_FAILURE);let m=l.changed&&!i.dryRun?await kp({pmRoot:e.pmRoot,subject:t,settings:n,typeRegistry:e.typeRegistry,historyRawBeforeLock:o.raw,currentItemRawBeforeLock:a?.raw??null,operation:r,author:c,force:i.force,itemDocument:a?.document??null,applyRewrite:async p=>{await l.beforeWrite?.(),l.applyRewrite?await l.applyRewrite(p):await to({historyPath:t.historyPath,nextHistoryRaw:Kt(l.rewrittenEntries),historyRawUnderLock:p.historyRawUnderLock})},applyPostRewrite:l.afterWrite??(async()=>Y({path:t.historyPath,scope:"project",op:`${r.replace("-","_")}:history`}))}):[];return l.report({verification:u,warnings:m})}function no(e,t,n=25){let r=e.definitions.filter(s=>s.roles.length===0).map(s=>s.id).sort((s,a)=>s.localeCompare(a)),i=new Set(r),o=t.filter(s=>{let a=_l(s.status,e);return a!==void 0&&i.has(a)}).map(s=>s.id).sort((s,a)=>s.localeCompare(a));return{roleless_status_count:r.length,roleless_statuses:r.slice(0,n),roleless_statuses_truncated:r.length>n,affected_item_count:o.length,affected_item_ids:o.slice(0,n),affected_item_ids_truncated:o.length>n}}function ro(e){return e.roleless_status_count===0?[]:[`schema_status_missing_lifecycle_role:${e.roleless_status_count}`]}function xp(e,t){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function Ve(e,t){return Array.isArray(e)?{count:e.length,sample:e.slice(0,t),truncated:e.length>t}:{count:0,sample:[],truncated:!1}}function Pk(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 Er(e,t){let n=Ve(e,t);return{...n,sample:n.sample.map(r=>Pk(r))}}function G(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 Lk(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 Nk={settings:(e,t)=>({version:e.version,id_prefix:e.id_prefix,locks_ttl_seconds:e.locks_ttl_seconds,warnings:G(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:G(e.missing_required,t),missing_optional:G(e.missing_optional,t),missing:G(e.missing,t),strict_directories:e.strict_directories}),settings_values:(e,t)=>({warnings:G(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:Er(e.discovered,t),effective:Er(e.effective,t),loaded:Er(e.loaded,t),failed:Ve(e.failed,t),warnings:G(e.warnings,t),activation:{failed:Ve(n.failed,t),warnings:G(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:Lk(n.migration_status)},author_manifest:e.author_manifest,triage:e.triage,capability_contract:e.capability_contract,capability_guidance:Ve(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:G(n.affected_item_ids,t),samples:Ve(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:G(e.item_unreadable,t),item_conflict_markers:Ve(e.item_conflict_markers,t),item_parse_failures:G(e.item_parse_failures,t),tracked_runtime_cache:n===void 0?e.tracked_runtime_cache:{...n,tracked_paths:G(n.tracked_paths,t)},history_unreadable:G(e.history_unreadable,t),history_conflict_markers:Ve(e.history_conflict_markers,t),history_invalid_json:Ve(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:G(n.candidate_items,t),confirmed_items:G(n.confirmed_items,t),resolved_false_positive_items:G(n.resolved_false_positive_items,t)},counts:e.counts,drifted_items:G(e.drifted_items,t),merge_receipt_attributed_items:G(e.merge_receipt_attributed_items,t),missing_streams:G(e.missing_streams,t),unreadable_streams:G(e.unreadable_streams,t),hash_mismatches:G(e.hash_mismatches,t),chain_mismatches:G(e.chain_mismatches,t),version_skews:G(e.version_skews,t),workspace_state_mismatches:G(e.workspace_state_mismatches,t),workspace_state_missing:G(e.workspace_state_missing,t),workspace_state_unreadable:G(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:G(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:G(e.stale_items_after,t),skipped:e.skipped})};function pa(e,t){let n=Nk[e.name];return n?n(e.details,t):e.details}function Sp(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 Dk(e){if(e.name==="extensions"&&e.status==="ok")return Sp(e);let t=pa(e,8);return Buffer.byteLength(JSON.stringify(t))<Buffer.byteLength(JSON.stringify(e.details))?t:e.details}function fa(e,t){let n=new Set([...t,...e.failed_because]);return(e.findings??[]).filter(r=>n.has(r.warning))}function Mk(e){let t=G(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:Dk(n)})),warnings:t.sample,findings:fa(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 bp(e){return e.details.skipped===!0}function Fk(e){let t=G(e.warnings,8),n=e.checks.filter(bp).map(r=>r.name);return{ok:e.ok,...e.verdict?{verdict:e.verdict}:{},checks:e.checks.filter(r=>!bp(r)).map(r=>({name:r.name,status:r.status,ok:r.ok,details:{}})),warning_count:t.count,warnings:t.sample,findings:fa(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 jk(e,t,n){return n?Fk(e):t.brief===!0?Mk(e):t.full===!0?e:{...e,checks:e.checks.map(r=>r.name==="extensions"&&r.status==="ok"?{...r,details:Sp(r)}:r),projection:{mode:"standard",warning_count:e.warning_count,warnings_truncated:e.warnings_truncated===!0,detail_limit:8}}}function ha(e,t,n){let r=e.warning_count??e.warnings.length,i=e.warnings.slice(0,100),o={...e,warning_count:r,warning_limit:100,warnings_truncated:r>100,warnings:i,findings:fa(e,i)},s=jk(o,t,n);return{...s,warning_count:r,warning_limit:100,warnings_truncated:r>s.warnings.length,...s.projection?{projection:{...s.projection,warning_count:r,warnings_truncated:r>s.warnings.length}}:{}}}import ga from"node:fs/promises";import le from"node:path";import Hk from"node:readline/promises";import{stdin as Uk,stdout as io}from"node:process";var CD=["ask","add","skip","status"],zk=["AGENTS.md","CLAUDE.md"],Wk=["pm init","pm context","pm search","pm create","pm claim","pm files","pm docs","pm test --run","pm close","pm release","pm_author"],qk=8,ya=1,Gk="<!-- pm-cli:agent-guidance:start:",Bk=`<!-- pm-cli:agent-guidance:start:v${ya} -->`,_a="<!-- pm-cli:agent-guidance:end -->",Ar="Add workflow guidance later: pm init --agent-guidance add";var Jk=()=>Hk.createInterface({input:Uk,output:io});function Ln(e,t){let n=le.relative(e,t);return n.length===0?le.basename(t):n.split(le.sep).join("/")}function Ep(e){return e.endsWith(`
|
|
12
|
+
`)?e:`${e}
|
|
13
|
+
`}function Vk(e){return e.includes(`\r
|
|
14
|
+
`)?`\r
|
|
15
|
+
`:`
|
|
16
|
+
`}function Rp(e){let t=e.indexOf(Gk);if(t===-1)return null;let n=e.indexOf(_a,t);return n===-1?null:{start_index:t,end_index:n+_a.length}}function Kk(e){return Rp(e)!==null}function Yk(e,t="<your project test command>"){return[Bk,"## pm Workflow (Agent Quickstart)","",'- Cold start with the measured canonical orientation: `pm context --for orient`; before item mutation, also run `pm search "<keywords>" --limit 10`, `pm list --status open --limit 20`, and `pm list --status in_progress --limit 20`.',"- Claim and start: `pm claim <id> --start`, or `pm claim --next --start` to take the next available item in one write.",`- Link evidence while coding: \`pm files <id> --add ...\`, \`pm docs <id> --add ...\`, \`pm test <id> --add command="${t}"\`.`,'- Verify and close: `pm test <id> --run --progress`, then atomically record closure evidence with `pm close <id> "<reason>" --resolution "<what changed>" --expected "<expected outcome>" --actual "<observed outcome>" --validate-close warn`, then `pm release <id>`.',"- Author identity is automatic for supported agent harnesses; use `--author` only for an explicit override.","",_a,""].join(e)}function Ap(e,t="<your project test command>"){let n=Vk(e),r=Yk(n,t),i=Rp(e);if(i){let a=e.slice(i.end_index),c=a.startsWith(`\r
|
|
17
|
+
`)?a.slice(2):a.startsWith(`
|
|
18
|
+
`)?a.slice(1):a,d=Ep(`${e.slice(0,i.start_index)}${r}${c}`);return{next_content:d,changed:d!==e}}let o=e.length===0?"":e.endsWith(`
|
|
19
|
+
`)?`
|
|
20
|
+
`:`
|
|
21
|
+
|
|
22
|
+
`,s=Ep(`${e}${o}${r}`);return{next_content:s,changed:s!==e}}async function Ip(e){if(await P(le.join(e,"scripts","run-tests.mjs")))return"node scripts/run-tests.mjs test";let t;try{t=JSON.parse(await ga.readFile(le.join(e,"package.json"),"utf8"))}catch{return"<your project test command>"}let n=Xk(t);if(n===void 0)return"<your project test command>";let r=n.packageManager?.split("@")[0];return r==="pnpm"?"pnpm test":r==="bun"?"bun run test":r==="yarn"?"yarn test":r==="npm"?"npm test":await P(le.join(e,"pnpm-lock.yaml"))?"pnpm test":await P(le.join(e,"bun.lock"))||await P(le.join(e,"bun.lockb"))?"bun run test":await P(le.join(e,"yarn.lock"))?"yarn test":"npm test"}function Xk(e){if(typeof e!="object"||e===null||!("scripts"in e))return;let t=e.scripts;if(!(typeof t!="object"||t===null||!("test"in t)||typeof t.test!="string"||t.test.trim().length===0))return{scripts:{test:t.test},..."packageManager"in e&&typeof e.packageManager=="string"?{packageManager:e.packageManager}:{}}}function Zk(e,t){let n=le.dirname(e);return le.basename(e)==="pm"&&le.basename(n)===".agents"?le.dirname(n):le.resolve(t,e)}function Qk(e,t){let n=e.find(i=>le.basename(i.file_path)==="AGENTS.md"&&i.exists);if(n)return n.file_path;let r=e.find(i=>i.exists);return r?r.file_path:le.join(t,"AGENTS.md")}function eb(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}async function tb(e){let t=Jk();try{io.write(`
|
|
23
|
+
Agent guidance check
|
|
24
|
+
`),io.write(`No AGENTS.md/CLAUDE.md file currently contains compact pm workflow guidance.
|
|
25
|
+
`);let n=await t.question(`Add a compact pm workflow section to ${e}? [Y/n] `);return io.write(`
|
|
26
|
+
`),eb(n,!0)}finally{t.close()}}function Cp(e){let t=e.agent_guidance;return{prompt_completed:t?.prompt_completed===!0,declined:t?.declined===!0,declined_at:typeof t?.declined_at=="string"?t.declined_at:"",template_version:typeof t?.template_version=="number"&&Number.isInteger(t.template_version)&&t.template_version>0?t.template_version:ya,last_checked_files:Array.isArray(t?.last_checked_files)?[...new Set(t.last_checked_files.map(n=>n.trim()).filter(n=>n.length>0))].sort((n,r)=>n.localeCompare(r)):[]}}async function $p(e){let t=[],n=await Ip(e);for(let r of zk){let i=le.join(e,r),o=await P(i);if(!o){t.push({file_path:i,exists:o,has_guidance:!1,has_marker:!1});continue}let s=await ga.readFile(i,"utf8"),a=s.toLowerCase(),c=Wk.filter(l=>a.includes(l)),d=Kk(s);t.push({file_path:i,exists:o,has_guidance:d||c.length>=qk,has_marker:d,outdated:d&&Ap(s,n).changed})}return t}function Qt(e,t){e.includes(t)||e.push(t)}function nb(e,t){let n=Cp(e),r=JSON.stringify(n)!==JSON.stringify(t);return r&&(e.agent_guidance=t),{changed:r,state:t}}async function Tp(e,t=le.dirname(e)){let r=await P(e)?await ga.readFile(e,"utf8"):"",i=Ap(r,await Ip(t));return i.changed?(await ee(e,i.next_content),{changed:!0,warnings:await Y({path:e,scope:"project",op:"init:agent_guidance_file"})}):{changed:!1,warnings:[]}}function rb(e){return{mode:e.mode,present:e.scans.some(t=>t.has_guidance),prompted:e.prompted,applied:e.applied,skipped:e.skipped,declined:e.state.declined,prompt_completed:e.state.prompt_completed,template_version:e.state.template_version,target_file:e.targetRelativePath,checked_files:e.scans.map(t=>Ln(e.projectRoot,t.file_path)),files_with_guidance:e.scans.filter(t=>t.has_guidance).map(t=>Ln(e.projectRoot,t.file_path)),missing_files:e.scans.filter(t=>!t.exists).map(t=>Ln(e.projectRoot,t.file_path))}}async function ib(e,t,n){return e?await $p(n):t}function Rr(e,t,n){e.state={...e.state,...n,template_version:ya,last_checked_files:t}}async function Op(e,t){if(t.presentBefore)return;let n=await Tp(t.targetPath,t.projectRoot);e.warnings.push(...n.warnings),n.changed&&(e.applied=!0,e.warnings.push(`agent_guidance:added:${t.targetRelativePath}`))}function ob(e,t){t||(e.warnings.push("agent_guidance:missing"),Qt(e.nextSteps,Ar))}function sb(e,t){e.skipped=!0,Rr(e,t,{prompt_completed:!0,declined:!0,declined_at:e.state.declined_at||new Date().toISOString()}),e.warnings.push("agent_guidance:explicit_skip"),Qt(e.nextSteps,Ar)}async function ab(e,t){await Op(e,t),Rr(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""})}function cb(e,t){e.state.declined&&Rr(e,t,{prompt_completed:!0,declined:!1,declined_at:""})}function db(e){e.skipped=!0,e.warnings.push("agent_guidance:skipped_declined"),Qt(e.nextSteps,Ar)}async function lb(e,t){if(e.prompted=!0,await tb(t.targetRelativePath)){await Op(e,t),Rr(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""});return}e.skipped=!0,Rr(e,t.checkedFiles,{prompt_completed:!0,declined:!0,declined_at:new Date().toISOString()}),e.warnings.push("agent_guidance:declined"),Qt(e.nextSteps,Ar)}function ub(e){e.warnings.push("agent_guidance:missing_non_interactive"),Qt(e.nextSteps,"Inspect workflow guidance: pm init --agent-guidance status"),Qt(e.nextSteps,Ar)}async function mb(e,t){let n={warnings:[],nextSteps:[],prompted:!1,applied:!1,skipped:!1,state:e};return t.mode==="status"?(ob(n,t.presentBefore),n):t.mode==="skip"?(sb(n,t.checkedFiles),n):t.mode==="add"?(await ab(n,t),n):t.presentBefore?(cb(n,t.checkedFiles),n):n.state.prompt_completed&&n.state.declined?(db(n),n):t.interactive?(await lb(n,t),n):(ub(n),n)}async function Pp(e){let t=Zk(e.pm_root,e.cwd),n=await $p(t),r=Qk(n,t),i=Ln(t,r),o=n.map(u=>Ln(t,u.file_path)),s=n.some(u=>u.has_guidance),a=await mb(Cp(e.settings),{mode:e.mode,interactive:e.interactive,targetPath:r,targetRelativePath:i,checkedFiles:o,presentBefore:s,projectRoot:t});if(e.mode==="add")for(let u of n.filter(m=>m.outdated)){let m=await Tp(u.file_path,t);a.applied||=m.changed,a.warnings.push(...m.warnings)}let c=nb(e.settings,a.state);n=await ib(a.applied,n,t);let d=n.filter(u=>u.outdated).map(u=>Ln(t,u.file_path));return d.length>0&&(a.warnings.push(`agent_guidance_outdated:${d.join(",")}`),Qt(a.nextSteps,"pm init --agent-guidance add")),{summary:rb({mode:e.mode,scans:n,projectRoot:t,targetRelativePath:i,prompted:a.prompted,applied:a.applied,skipped:a.skipped,state:a.state}),warnings:a.warnings,next_steps:a.nextSteps,settings_changed:c.changed}}function Ir(e){let t=/^extension_(disabled_)?pm_(min|max)_version_([a-z_]+):(project|global):([^:]+):(.+)$/u.exec(e);if(!t)return;let[,n,r,i,o,s,a]=t,c=a.split(":")[0].replace(r==="min"?"required=":"allowed=",""),d=i==="invalid"?`a valid pm_${r}_version instead of ${c}`:`pm ${r==="min"?">=":"<="} ${c}`;return n?`Package ${s} is disabled and requires ${d} before activation. After satisfying the bound, run ${K(["package","activate",s,`--${o}`])}.`:`Package ${s} requires ${d}. Use a compatible host or package version, or keep it disabled with ${K(["package","deactivate",s,`--${o}`])}.`}import It from"node:fs/promises";import me from"node:path";import Cr from"node:fs/promises";import{createHash as pb}from"node:crypto";import Np from"node:path";var wa=new Set([void 0,...kl]),Dp=13,fb="history-drift-cache.json";function Mp(e){return Np.join(e,"runtime",fb)}async function hb(e){try{let t=await Cr.readFile(Mp(e),"utf8"),n=JSON.parse(t);return n.version!==Dp||n.history_item_hash_version!==vn||typeof n.entries!="object"||n.entries===null||Object.values(n.entries).some(r=>typeof r.chain_ok!="boolean"||typeof r.latest_hash_comparable!="boolean"||!wa.has(r.hash_algorithm)||!Ge.includes(r.item_hash_version)&&r.version_skew!==!0||r.chain_ok&&r.version_skew!==!0&&Ge.includes(r.item_hash_version)&&!r.latest_hash_comparable)?null:n}catch{return null}}function Fp(){return{missingStreams:[],unreadableStreams:[],hashMismatches:[],chainMismatches:[],versionSkews:[],workspaceStateMismatches:[],workspaceStateMissing:[],workspaceStateUnreadable:[]}}function jp(e){let t=[...new Set([...e.missingStreams,...e.unreadableStreams,...e.hashMismatches,...e.chainMismatches,...e.versionSkews,...e.workspaceStateMismatches.length>0||e.workspaceStateMissing.length>0||e.workspaceStateUnreadable.length>0?[re]:[]])].sort((n,r)=>n.localeCompare(r));return{...e,driftedItems:t}}async function _b(e,t,n,r,i){let o=bn(e),s;try{s=await Cr.stat(o)}catch(d){return F(d)||i.unreadableStreams.push(re),!1}let a=i.missingStreams.length,c=await Hp({itemId:re,historyPath:o,stat:s,cached:t[re],verifyCacheHitByContent:r,accumulator:i});return c.verification?(c.verification.versionSkew&&i.versionSkews.push(re),c.verification.chainOk||i.chainMismatches.push(re),n[re]={mtime_ms:s.mtimeMs,ctime_ms:s.ctimeMs,size:s.size,content_hash:c.verification.contentHash,latest_after_hash:c.verification.latestAfterHash,chain_ok:c.verification.chainOk,version_skew:c.verification.versionSkew,latest_hash_comparable:c.verification.latestHashComparable,item_hash_version:c.verification.itemHashVersion,hash_algorithm:c.verification.hashAlgorithm},c.cacheDirty):(i.missingStreams.splice(a),c.cacheDirty)}function gb(e){return!wa.has(e.hash_algorithm)||e.item_hash_version!==void 0&&!Ge.includes(e.item_hash_version)||xi(e)}async function yb(e){let t=await Cr.readFile(e,"utf8"),n=pb("sha256").update(t).digest("hex");if(t.trim().length===0)return null;let r=[],i=null;for(let m of t.split(/\r?\n/)){let p=m.trim();if(p.length===0)continue;let f=JSON.parse(p);if(typeof f.after_hash!="string"||f.after_hash.trim().length===0)throw new Error("missing after_hash");r.push(f),i=f.after_hash}if(!i)return null;let o=ke(r),s=r.some(gb),a=r[r.length-1],c=wa.has(a.hash_algorithm),d=a.item_hash_version,l=d!==void 0&&Ge.includes(d),u=l?d:o.item_hash_version;return{latestAfterHash:i,hashAlgorithm:c?ve(a.hash_algorithm):void 0,identityDiscontinuities:Fl(r),chainOk:o.ok,versionSkew:s,latestHashComparable:c&&u!==void 0&&(!s||l||d===void 0),contentHash:n,itemHashVersion:u??vn}}function wb(e,t){return e!==void 0&&e.mtime_ms===t.mtimeMs&&e.ctime_ms===t.ctimeMs&&e.size===t.size}async function Lp(e,t,n){try{let r=await yb(t);return r||(n.missingStreams.push(e),null)}catch{return n.unreadableStreams.push(e),null}}function vb(e,t){return e!==null&&e.contentHash===t.content_hash&&e.latestAfterHash===t.latest_after_hash&&e.chainOk===t.chain_ok&&e.versionSkew===(t.version_skew===!0)&&e.latestHashComparable===t.latest_hash_comparable&&e.itemHashVersion===t.item_hash_version&&e.hashAlgorithm===t.hash_algorithm}async function Hp(e){let t=typeof e.cached?.content_hash=="string"&&e.cached.content_hash.length>0?e.cached.content_hash:void 0;if(!(wb(e.cached,e.stat)&&t!==void 0)||!e.cached||!e.cached.chain_ok)return{verification:await Lp(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0};if(e.verifyCacheHitByContent){let r=await Lp(e.itemId,e.historyPath,e.accumulator);return{verification:r,cacheDirty:!vb(r,e.cached)}}return{verification:{identityDiscontinuities:[],latestAfterHash:e.cached.latest_after_hash,chainOk:e.cached.chain_ok,versionSkew:e.cached.version_skew===!0,latestHashComparable:e.cached.latest_hash_comparable&&Ge.includes(e.cached.item_hash_version),contentHash:t,itemHashVersion:e.cached.item_hash_version,hashAlgorithm:e.cached.hash_algorithm},cacheDirty:!1}}async function Up(e,t,n,r){let i,o;try{i=pt(e,t.id),o=await Cr.stat(i)}catch(l){return(F(l)?r.missingStreams:r.unreadableStreams).push(t.id),!1}let s=await Hp({itemId:t.id,historyPath:i,stat:o,cached:n.previousEntries[t.id],verifyCacheHitByContent:n.verifyCacheHitByContent,accumulator:r});if(!s.verification)return s.cacheDirty;s.verification.identityDiscontinuities.length>0&&(r.identityDiscontinuities??=[]).push(...s.verification.identityDiscontinuities.map(l=>({...l,item_id:t.id}))),s.verification.versionSkew&&r.versionSkews.push(t.id),s.verification.chainOk||r.chainMismatches.push(t.id),n.nextEntries[t.id]={mtime_ms:o.mtimeMs,ctime_ms:o.ctimeMs,size:o.size,content_hash:s.verification.contentHash,latest_after_hash:s.verification.latestAfterHash,chain_ok:s.verification.chainOk,version_skew:s.verification.versionSkew,latest_hash_comparable:s.verification.latestHashComparable,item_hash_version:s.verification.itemHashVersion,hash_algorithm:s.verification.hashAlgorithm};let{body:a,...c}=t;return s.verification.latestHashComparable&&(Vl({metadata:c,body:a},s.verification.itemHashVersion,s.verification.hashAlgorithm).includes(s.verification.latestAfterHash)||r.hashMismatches.push(t.id)),s.cacheDirty}async function kb(e,t){if(!(t.unreadableStreams.includes(re)||t.chainMismatches.includes(re)||t.versionSkews.includes(re)))try{let n=await wu(e);t.workspaceStateMismatches.push(...n.mismatched_documents),t.workspaceStateMissing.push(...n.missing_documents),t.workspaceStateUnreadable.push(...n.unreadable_documents)}catch{t.unreadableStreams.push(re)}}async function zp(e,t){let n=Fp();return await Up(e,t,{previousEntries:{},nextEntries:{},verifyCacheHitByContent:!0},n),jp(n)}async function en(e,t,n={}){let r=Fp(),o=(await hb(e))?.entries??{},s={},a=!1,c=n.cacheHitVerification!=="metadata",d={previousEntries:o,nextEntries:s,verifyCacheHitByContent:c};for(let u of t)await Up(e,u,d,r)&&(a=!0);let l=await _b(e,o,s,c,r);if(a||=l,await kb(e,r),a||Object.keys(o).length!==Object.keys(s).length){let u=Mp(e);try{await Cr.mkdir(Np.dirname(u),{recursive:!0}),await ee(u,JSON.stringify({version:Dp,history_item_hash_version:vn,entries:s}))}catch{}}return jp(r)}import Nn from"node:fs/promises";import $r from"node:path";function Wp(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:i,created_at:o,ttl_seconds:s}=n;return typeof r!="string"||typeof i!="string"||typeof o!="string"||typeof s!="number"||!Number.isFinite(s)?null:{id:r,owner:i,created_at:o,ttl_seconds:s,pid:n.pid,host_identity:n.host_identity,process_start_identity:n.process_start_identity}}function bb(e,t,n){let r=Wp(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 i=Date.parse(r.created_at);if(!Number.isFinite(i))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 o=n-i,s=Math.floor(o/1e3),a=o>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:s,stale:a,reason:a?"expired":"active"}}}async function qp(e,t,n){let r=bb(e,t,n);if(r.detail!=="active")return r;let i=Wp(t),o=await Ol(i);return o==="unknown"?r:{detail:o==="dead"?"owner_dead":"active",entry:{...r.entry,owner_state:o,pid:i.pid,...o==="dead"?{stale:!0,reason:"owner_dead"}:{}}}}async function xb(e,t,n){let r=await Pl(e,"gc");if(r===null)return!1;try{let i;try{i=await Nn.readFile(e,"utf8")}catch(o){if(F(o))return!0;throw o}if(i!==t)return!1;n&&await Ll(e,t);try{await Nn.unlink(e)}catch(o){if(!F(o))throw o}return!0}finally{await r()}}function Sb(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 Gp(e,t){let n=t??Date.now(),r=$r.join(e,"locks"),i={scanned:0,active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0},o;try{o=(await Nn.readdir(r)).filter(a=>a.endsWith(".lock")).sort()}catch(s){if(F(s))return i;throw s}for(let s of o){let a;try{a=await Nn.readFile($r.join(r,s),"utf8")}catch(l){if(F(l))continue;i.scanned+=1,i.unreadable_lock_count+=1;continue}i.scanned+=1;let{detail:c,entry:d}=await qp(s,a,n);Sb(i,c,d)}return i}async function Eb(e,t,n,r,i,o,s){if(!t.dryRun){try{if(!await xb(n,o,s.reason==="owner_dead")){e.warnings.push(`lock_changed_or_busy:${i}`),e.retained.push(r),e.entries.push(s);return}}catch{e.warnings.push(`lock_remove_failed:${i}`),e.retained.push(r),e.entries.push(s);return}if(t.hooks?.onWrite){let a=await t.hooks.onWrite(n);e.warnings.push(...a)}}e.removed.push(r),e.entries.push(s)}async function Bp(e,t){let{hooks:n}=t,r=t.now??Date.now(),i=$r.join(e,"locks"),o={scanned:0,removed:[],retained:[],warnings:[],entries:[]};await Tl(e,$r.join(i,"gc.lock"),"gc");let s;try{s=(await Nn.readdir(i)).filter(c=>c.endsWith(".lock")).sort()}catch(a){if(F(a))return o;throw a}for(let a of s){o.scanned+=1;let c=$r.join(i,a),d=`locks/${a}`;if(n?.onRead){let m=await n.onRead(c);o.warnings.push(...m)}let l;try{l=await Nn.readFile(c,"utf8")}catch(m){if(F(m)){o.scanned-=1;continue}o.warnings.push(`lock_unreadable:${a}`),o.retained.push(d),o.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 qp(a,l,r);if(u.detail==="unparseable_json"){o.warnings.push(`lock_unparseable:${a}`),o.retained.push(d),o.entries.push(u.entry);continue}if(u.detail==="invalid_timestamp"){o.warnings.push(`lock_invalid_timestamp:${a}`),o.retained.push(d),o.entries.push(u.entry);continue}if(u.detail==="active"){o.retained.push(d),o.entries.push(u.entry);continue}await Eb(o,t,c,d,a,l,u.entry)}return o}var Rb=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 va(e){if(typeof e!="string")return;let t=e.trim();for(let n of Rb)if(t===n.code||t.startsWith(`${n.code}:`))return n}function ka(e){let t={};for(let n of e){let r=va(n);r!==void 0&&!Object.prototype.hasOwnProperty.call(t,r.code)&&(t[r.code]=r.command)}return t}function Jp(e){return Object.values(ka(e))}import Bn from"node:fs/promises";import Fe from"node:path";var Ab=[["beforeCommand","before_command"],["beforeMutation","before_mutation"],["afterCommand","after_command"],["onWrite","on_write"],["onRead","on_read"],["onIndex","on_index"]];function Dn(e,t={}){let n=new Set;t.extensionName!==void 0&&n.add(Ai(t.extensionName));for(let y of t.extensionNames??[])n.add(Ai(y));let r=y=>n.size===0||n.has(Ai(y)),i=(y,w)=>Vp(y.filter(v=>r(v.name)).map(w)),o=(y,w)=>Vp(y.filter(v=>r(v.name)).flatMap(w)),{registrations:s,commands:a,parsers:c,preflight:d,services:l,renderers:u,hooks:m}=e,p=o(s.relationship_kinds??[],y=>y.definitions.map(w=>w.kind)),f=u.overrides.filter(y=>r(y.name)&&((y.commands?.length??0)>0||y.resultDiscriminator!==void 0)).map(y=>({format:y.format,commands:[...y.commands??[]],result_discriminator:y.resultDiscriminator!==void 0})).sort((y,w)=>y.format.localeCompare(w.format)),h=i(s.assurance_providers??[],y=>y.definition.id);return{capabilities:Xl(e,t),commands:i(s.commands,y=>y.command),command_overrides:i(a.overrides,y=>y.command),command_handlers:i(a.handlers,y=>y.command),hooks:Ab.filter(([y])=>m[y].some(w=>r(w.name))).map(([,y])=>y),flag_commands:i(s.flags,y=>y.target_command),item_types:o(s.item_types,y=>y.types.map(w=>w.name)),item_fields:o(s.item_fields,y=>y.fields.map(w=>w.name)),...p.length>0?{relationship_kinds:p}:{},migrations:o(s.migrations,y=>typeof y.definition.id=="string"?[y.definition.id]:[]),profiles:i(s.profiles,y=>y.profile.name),importers:i(s.importers,y=>y.importer),exporters:i(s.exporters,y=>y.exporter),search_providers:i(s.search_providers,y=>y.definition.name),vector_store_adapters:i(s.vector_store_adapters,y=>y.definition.name),...h.length>0?{assurance_providers:h}:{},parser_overrides:i(c.overrides,y=>y.command),service_overrides:i(l.overrides,y=>y.service),renderer_overrides:i(u.overrides,y=>y.format),...f.length>0?{renderer_ownership:f}:{},preflight_overrides:d.overrides.filter(y=>r(y.name)).length,preflight_ownership:d.overrides.filter(y=>r(y.name)).map(y=>({commands:[...y.commands??[]]}))}}function Vp(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}import nx from"node:path";import{mkdir as rx}from"node:fs/promises";var Ib=/^([A-Za-z][A-Za-z0-9_-]*?)\s*[-:]\s+\S/;function Cb(e){let t=Ib.exec(e.trim());if(!t)return;let n=t[1];if(!(n.length<2)&&!/^[A-Za-z]\d+$/.test(n))return n.toLowerCase()}function $b(e){return e.split(/[-_]+/).filter(t=>t.length>0).map(t=>`${t.slice(0,1).toUpperCase()}${t.slice(1).toLowerCase()}`).join("")}function Kp(e,t={}){let n=typeof t.minCount=="number"&&t.minCount>0?Math.trunc(t.minCount):10,r=typeof t.maxExamples=="number"&&t.maxExamples>0?Math.trunc(t.maxExamples):3,i=new Map;for(let s of e){let a=typeof s=="string"?s.trim():"";if(a.length===0)continue;let c=Cb(a);if(c===void 0)continue;let d=i.get(c)??{count:0,examples:[]};d.count+=1,d.examples.length<r&&d.examples.push(a),i.set(c,d)}let o=[];for(let[s,a]of i.entries()){if(a.count<n)continue;let c=$b(s);o.push({name:c,prefix:s,count:a.count,examples:a.examples,shadows_builtin:ol(c)!==void 0})}return o.sort((s,a)=>a.count-s.count||s.name.localeCompare(a.name)),o}import{createHash as Zp}from"node:crypto";import Fn from"node:fs/promises";import jn from"node:path";function kt(e,t){if(typeof e!="string"||e.trim().length===0)throw new TypeError(`Schema migration ${t} must be non-empty`);return e.trim()}function Qp(e){let t=kt(e,"migrationId");if(!/^[a-zA-Z0-9._-]+$/.test(t))throw new TypeError("Schema migration migrationId must match [a-zA-Z0-9._-]+");return t}function ef(e,t){let n=xa(e),r=kt(t,"migrationScope");return`auto-${Zp("sha256").update(JSON.stringify({scope:r,request:n})).digest("hex").slice(0,20)}`}function xa(e){let t=e.kind==="rename-type"?{kind:e.kind,from:kt(e.from,"source"),to:kt(e.to,"target")}:e.kind==="rename-field"?{kind:e.kind,from:ce(kt(e.from,"source")),to:ce(kt(e.to,"target")),...e.type===void 0?{}:{type:kt(e.type,"type")}}:{kind:e.kind,from:ce(kt(e.from,"source")),to:ce(kt(e.to,"target"))};if(t.from.toLowerCase()===t.to.toLowerCase())throw new TypeError("Schema migration source and target must differ");return t}function Tb(e){return e.kind==="rename-type"?"types":e.kind==="rename-field"?"fields":"statuses"}function Ob(e,t,n){let r=$e(t.schema),i=Tb(n);return it(e,r.files[i],Le[i])}function tf(e,t){return jn.join(e,"transactions","schema",`${t}-plan.json`)}function oo(e){return e.length===0?null:JSON.parse(e)}async function Mn(e){let t=await B(e);return{exists:t!==null,raw:t??""}}async function nf(e,t){t.exists?await ee(e,t.raw):await Fn.rm(e,{force:!0})}function Pb(e,t,n){let r=ft(e),i=r.definitions.findIndex(s=>s.name.trim().toLowerCase()===t.from.toLowerCase()),o=r.definitions.findIndex(s=>s.name.trim().toLowerCase()===t.to.toLowerCase());if(n==="stage"){if(o>=0)return Ot(r);if(i<0)throw new TypeError(`Unknown custom type "${t.from}".`);r.definitions.push({...r.definitions[i],name:t.to})}else i>=0&&r.definitions.splice(i,1);return Ot(r)}function rf(e,t){return{...e,key:t,metadata_key:t,front_matter_key:t,cli_flag:t.replaceAll("_","-")}}function Lb(e,t,n){if(t.kind!=="rename-field"||n)return;let r=e.schema.fields.find(i=>ce(i.key)===t.from);r!==void 0&&$s(rf(r,t.to))}function Nb(e,t,n){let r=fn(e),i=r.fields.findIndex(s=>s.key===t.from),o=r.fields.findIndex(s=>s.key===t.to);if(n==="stage"){if(o>=0)return hn(r);if(i<0)throw new TypeError(`Unknown custom field "${t.from}".`);let s=rf(r.fields[i],t.to);$s(s),r.fields.push(s)}else i>=0&&r.fields.splice(i,1);return hn(r)}function Db(e,t,n){let r=_n(e),i=r.statuses.findIndex(s=>s.id===t.from),o=r.statuses.findIndex(s=>s.id===t.to);if(n==="stage"){if(o>=0)return gn(r);if(i<0)throw new TypeError(`Unknown custom status "${t.from}".`);r.statuses.push({...r.statuses[i],id:t.to})}else i>=0&&r.statuses.splice(i,1);return gn(r)}function Mb(e,t,n){return t.kind==="rename-type"?Pb(e,t,n):t.kind==="rename-field"?Nb(e,t,n):Db(e,t,n)}function Ft(e,t){return typeof e=="string"&&e.trim().toLowerCase()===t.from.toLowerCase()?t.to:e}function Sa(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function Hn(e){return Array.isArray(e)?e.map(t=>Sa(t)).filter(t=>t!==void 0):[]}function Fb(e,t){for(let n of Hn(e.fields))Array.isArray(n.required_types)&&(n.required_types=n.required_types.map(r=>Ft(r,t)));for(let n of Hn(e.type_workflows))n.type=Ft(n.type,t)}function jb(e,t){for(let r of Hn(e.definitions))r.default_status=Ft(r.default_status,t);let n=Sa(e.workflow);if(n)for(let[r,i]of Object.entries(n))n[r]=Ft(i,t);for(let r of Hn(e.type_workflows))Array.isArray(r.allowed_transitions)&&(r.allowed_transitions=r.allowed_transitions.map(i=>Array.isArray(i)?i.map(o=>Ft(o,t)):i))}function Hb(e,t){for(let n of Hn(e.definitions)){for(let r of["required_create_fields","required_create_repeatables"])Array.isArray(n[r])&&(n[r]=n[r].map(i=>Ft(i,t)));for(let r of["options","command_option_policies"])for(let i of Hn(n[r])){let o=r==="options"?"key":"option";i[o]=Ft(i[o],t)}}}function Ub(e,t){let n=Sa(e.options);if(!n)return;if(t.kind==="rename-field"){if(!Object.prototype.hasOwnProperty.call(n,t.from))return;if(Object.prototype.hasOwnProperty.call(n,t.to))throw new TypeError(`Schema migration collision in saved template "${String(e.name??"unknown")}": target field "${t.to}" already exists.`);n[t.to]=n[t.from],delete n[t.from];return}let r=t.kind==="rename-type"?"type":"status";n[r]=Ft(n[r],t)}function ba(e,t){let n=JSON.parse(e);if(typeof n!="object"||n===null||Array.isArray(n))return e;let r=n;return t.kind==="rename-type"?Fb(r,t):t.kind==="rename-field"?Hb(r,t):jb(r,t),Ub(r,t),`${JSON.stringify(r,null,2)}
|
|
27
|
+
`}function of(e,t){if(t.kind==="rename-type"){let r=ft(e).definitions;return{source:r.some(i=>i.name.trim().toLowerCase()===t.from.toLowerCase()),target:r.some(i=>i.name.trim().toLowerCase()===t.to.toLowerCase())}}if(t.kind==="rename-field"){let r=fn(e).fields;return{source:r.some(i=>i.key===t.from),target:r.some(i=>i.key===t.to)}}let n=_n(e).statuses;return{source:n.some(r=>r.id===t.from),target:n.some(r=>r.id===t.to)}}function zb(e,t){let n=e;return t.kind==="rename-type"?e.type.toLowerCase()===t.to.toLowerCase()?[]:["type"]:t.kind==="remap-status"?e.status.toLowerCase()===t.to.toLowerCase()?[]:["status"]:Object.prototype.hasOwnProperty.call(n,t.to)&&!Object.prototype.hasOwnProperty.call(n,t.from)?[]:[t.from,t.to]}function Wb(e,t){if(t.kind==="rename-type")return e.type.toLowerCase()===t.from.toLowerCase()?{id:e.id,changes:[{field:"type",before:e.type,after:t.to}]}:null;if(t.kind==="remap-status")return e.status.toLowerCase()===t.from.toLowerCase()?{id:e.id,changes:[{field:"status",before:e.status,after:t.to}]}:null;if(t.type!==void 0&&e.type.toLowerCase()!==t.type.toLowerCase())return null;let n=e;if(!Object.prototype.hasOwnProperty.call(n,t.from))return null;if(Object.prototype.hasOwnProperty.call(n,t.to))throw new TypeError(`Schema migration collision on item "${e.id}": target field "${t.to}" already exists.`);return{id:e.id,changes:[{field:t.from,before:n[t.from],after:void 0},{field:t.to,before:void 0,after:n[t.from]}]}}function sf(e,t){let n=xa(t.request),r=t.migrationId===void 0?ef(n,t.migrationScope??"plan"):Qp(t.migrationId),i=e.map(c=>Wb(c,n)).filter(c=>c!==null).sort((c,d)=>c.id.localeCompare(d.id)),o=Zp("sha256").update(JSON.stringify({migrationId:r,request:n,items:i})).digest("hex"),s=new Set([...t.completedItemIds??[]].map(c=>c.trim()).filter(c=>c.length>0)),a=i.filter(c=>!s.has(c.id));return Object.freeze({migration_id:r,request:n,fingerprint:o,affected_item_count:i.length,pending_item_count:a.length,skipped_completed_count:i.length-a.length,items:Object.freeze(a)})}async function qb(e){let t=W(e.settings,U()),n=[...new Set(Object.values(t.type_to_folder))],r=await Fi(e.pmRoot,n),i=e.request.kind==="rename-type"?{types:[e.request.from]}:e.request.kind==="remap-status"?{statuses:[e.request.from]}:{metadataKeys:[e.request.from],...e.request.type===void 0?{}:{types:[e.request.type]}},o=r?await $u({pmRoot:e.pmRoot,expectedSourceCursor:r.source_cursor,query:i}):null;return o?{items:o.items,selectionSource:"derived_index",typeToFolder:t.type_to_folder}:{items:await _t(e.pmRoot,e.settings.item_format,t.type_to_folder,[],e.settings.schema),selectionSource:"scan",typeToFolder:t.type_to_folder}}async function Gb(e,t){let n=await B(tf(e,t));if(n===null)return null;try{let r=JSON.parse(n);if(r.schema_version!==1||r.plan.migration_id!==t||!Array.isArray(r.plan.items))throw new TypeError("invalid plan envelope");return r.plan}catch(r){throw new _(`Stored schema migration plan "${t}" is invalid: ${qd(r)}`,g.GENERIC_FAILURE)}}async function Bb(e,t){let n=tf(e,t.migration_id);await Fn.mkdir(jn.dirname(n),{recursive:!0});let r={schema_version:1,plan:t,created_at:new Date().toISOString()};await ee(n,`${JSON.stringify(r,null,2)}
|
|
28
|
+
`)}function Jb(e,t){return JSON.stringify(e)===JSON.stringify(t)}async function Vb(e){let t=await ge(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!t)throw new _(`Schema migration item "${e.id}" no longer exists.`,g.NOT_FOUND);return(await ye(t,{schema:e.settings.schema})).document.metadata}function Yp(e,t,n){let r=n==="forward"?t.from:t.to,i=n==="forward"?t.to:t.from;if(t.kind==="rename-type"){if(e.metadata.type.toLowerCase()===i.toLowerCase())return[];if(e.metadata.type.toLowerCase()!==r.toLowerCase())throw new TypeError(`Schema migration expected type "${r}" on item "${e.metadata.id}".`);return e.metadata.type=i,["type"]}if(t.kind==="remap-status"){if(e.metadata.status.toLowerCase()===i.toLowerCase())return[];if(e.metadata.status.toLowerCase()!==r.toLowerCase())throw new TypeError(`Schema migration expected status "${r}" on item "${e.metadata.id}".`);return e.metadata.status=i,["status"]}let o=e.metadata;if(Object.prototype.hasOwnProperty.call(o,i)&&!Object.prototype.hasOwnProperty.call(o,r))return[];if(!Object.prototype.hasOwnProperty.call(o,r)||Object.prototype.hasOwnProperty.call(o,i))throw new TypeError(`Schema migration field state changed concurrently on item "${e.metadata.id}".`);return o[i]=o[r],delete o[r],[r,i]}function Xp(e){return{id:e.id,inspect:async()=>{let t=await Mn(e.filePath),n=of(t.raw,e.request),r=e.phase==="stage"?n.source&&n.target:!n.source&&n.target;return{state:r?"applied":"pending",...r?{result:{phase:e.phase}}:{}}},prepareCompensation:async()=>{let t=await Mn(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await Mn(e.filePath);return await ee(e.filePath,Mb(t.raw,e.request,e.phase)),{phase:e.phase}},compensate:async t=>{if(typeof t!="object"||t===null||Array.isArray(t)||typeof t.exists!="boolean"||typeof t.raw!="string")throw new TypeError(`Missing schema snapshot for ${e.id} compensation.`);await nf(e.filePath,{exists:t.exists,raw:t.raw})}}}function Kb(e){return{id:e.stepId,inspect:async()=>{let t=await Mn(e.filePath);return{state:ba(t.raw,e.request)===t.raw?"applied":"pending"}},prepareCompensation:async()=>{let t=await Mn(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await Mn(e.filePath);return await ee(e.filePath,ba(t.raw,e.request)),{file:e.filePath}},compensate:async t=>{if(typeof t!="object"||t===null||Array.isArray(t)||typeof t.exists!="boolean"||typeof t.raw!="string")throw new TypeError(`Missing schema reference snapshot for ${e.stepId} compensation.`);await nf(e.filePath,{exists:t.exists,raw:t.raw})}}}function Yb(e){return{id:`item-${e.id}`,inspect:async()=>{let t=await T(e.pmRoot),n=W(t,U()).type_to_folder,r=await Vb({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id}),i=zb(r,e.request).length===0;return{state:i?"applied":"pending",...i?{result:{item_id:e.id}}:{}}},apply:async()=>{let t=await T(e.pmRoot),n=W(t,U()).type_to_folder,r=await yt({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id,op:`schema_${e.request.kind.replaceAll("-","_")}`,author:e.author,message:`Schema migration ${e.request.kind}: ${e.request.from} -> ${e.request.to}`,force:e.force,skipNoop:!0,mutate(i){return{changedFields:Yp(i,e.request,"forward")}}});return{item_id:e.id,changed_fields:r.changedFields}},compensate:async()=>{let t=await T(e.pmRoot),n=W(t,U()).type_to_folder;await yt({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id,op:`schema_${e.request.kind.replaceAll("-","_")}_compensate`,author:e.author,message:`Compensate schema migration ${e.request.kind}: ${e.request.to} -> ${e.request.from}`,force:!0,skipNoop:!0,mutate(r){return{changedFields:Yp(r,e.request,"reverse")}}})}}}async function Xb(e){let t=await Gb(e.pmRoot,e.migrationId);if(t){if(!Jb(t.request,e.request))throw new _(`Schema migration id "${e.migrationId}" already belongs to a different request.`,g.CONFLICT);return{plan:t,stored:!0}}let n=await qb({pmRoot:e.pmRoot,settings:e.settings,request:e.request});return{plan:{...sf(n.items,{migrationId:e.migrationId,request:e.request}),selection_source:n.selectionSource},stored:!1}}async function Zb(e){let t=of(await B(e.schemaPath)??"",e.request);if(!t.source)throw new _(`Schema migration source "${e.request.from}" is not a custom definition.`,g.NOT_FOUND);if(t.target)throw new _(`Schema migration target "${e.request.to}" already exists.`,g.CONFLICT);await Bb(e.pmRoot,e.plan)}async function Qb(e){let t=$e(e.settings.schema),n=[...new Set([["types",Le.types],["fields",Le.fields],["workflows",Le.workflows]].map(([i,o])=>it(e.pmRoot,t.files[i],o)).filter(i=>i!==e.schemaPath))];try{let i=jn.join(e.pmRoot,"templates"),o=await Fn.readdir(i,{withFileTypes:!0});n.push(...o.filter(s=>s.isFile()&&s.name.toLowerCase().endsWith(".json")).map(s=>jn.join(i,s.name)))}catch(i){if(typeof i!="object"||i===null||!("code"in i)||!F(i))throw i}n.sort((i,o)=>i.localeCompare(o));let r=[];for(let i of n){let o=await B(i);o!==null&&ba(o,e.request)!==o&&r.push({filePath:i,beforeRaw:o})}return{paths:n,snapshots:r}}async function ex(e){for(let t of e.snapshots){let n=await Fn.readFile(t.filePath,"utf8"),r=jn.relative(e.pmRoot,t.filePath).replaceAll("\\","/");await Ts({pmRoot:e.pmRoot,author:e.author,documentPath:r,before:oo(t.beforeRaw),after:oo(n),op:"schema_migration_reference",idempotencyKey:`${e.plan.migration_id}:${e.plan.fingerprint}:${r}`,message:`${e.request.kind}: ${e.request.from} -> ${e.request.to}`,lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}}async function tx(e,t,n){let r=xa(e),i=M(process.cwd(),n.path);await ie(i);let o=t.migrationId===void 0?ef(r,await Fn.realpath(i)):Qp(t.migrationId),s=await T(i),a=q(t.author,s.author_default),c=await Xb({pmRoot:i,settings:s,migrationId:o,request:r});Lb(s,r,c.stored);let d=c.plan;if(t.dryRun===!0)return{...d,action:r.kind,applied:!1,recovered:!1,migrated_item_count:0};let l=Ob(i,s,r),u=await B(l)??"";c.stored||await Zb({pmRoot:i,schemaPath:l,request:r,plan:d});let m=await Qb({pmRoot:i,schemaPath:l,settings:s,request:r}),p=[Xp({id:"stage-schema",filePath:l,request:r,phase:"stage"}),...m.paths.map((w,v)=>Kb({filePath:w,request:r,stepId:`reference-${String(v+1).padStart(4,"0")}`})),...d.items.map(w=>Yb({pmRoot:i,id:w.id,request:r,author:a,force:t.force===!0})),Xp({id:"retire-source",filePath:l,request:r,phase:"retire"})],f=await jm({pmRoot:i,transactionId:`schema-${o}`,author:a,steps:p,lockTtlSeconds:Math.max(s.locks.ttl_seconds,300),lockWaitMs:s.locks.wait_ms}),h=await Fn.readFile(l,"utf8"),{historyPath:y}=await Ts({pmRoot:i,author:a,documentPath:jn.relative(i,l).replaceAll("\\","/"),before:oo(u),after:oo(h),op:"schema_migration",idempotencyKey:`${d.migration_id}:${d.fingerprint}`,message:`${r.kind}: ${r.from} -> ${r.to}; affected=${d.affected_item_count}`,lockTtlSeconds:s.locks.ttl_seconds,lockWaitMs:s.locks.wait_ms});return await ex({pmRoot:i,author:a,settings:s,request:r,plan:d,snapshots:m.snapshots}),{...d,action:r.kind,applied:!0,recovered:f.recovered,migrated_item_count:d.affected_item_count,workspace_history_path:y}}var ZM=[...li,"add-type","remove-type","add-status","remove-status","add-field","remove-field","list-fields","show-field","apply-preset","list","show","show-status","rename-type","rename-field","remap-status"],so="schema-types",af="schema-statuses",cf="schema-fields";function jt(e){return En({pmRoot:e.pmRoot,filePath:e.filePath,raw:e.raw,op:e.op,author:e.author,lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}async function QM(e,t,n){let r=M(process.cwd(),n.path);await bt(r);let i;try{i=ws({name:e,description:t.description,defaultStatus:t.defaultStatus,folder:t.folder,aliases:t.alias})}catch(p){throw new _(p instanceof Error?p.message:String(p),g.USAGE)}let o=await T(r),s=$e(o.schema),a=it(r,s.files.types,Le.types),c=[],d=q(t.author,o.author_default),l=Je(o),u=await se(r,so,o.locks.ttl_seconds,d,!!t.force,l.force_required_for_stale_lock,o.locks.wait_ms),m;try{let p=await B(a),f;try{f=ft(p)}catch(h){throw new _(h instanceof Error?h.message:String(h),g.GENERIC_FAILURE)}try{sl(i,f);let h=new Map,y=W(o,U());for(let[w,v]of Object.entries(y.type_to_folder)){let k=v.trim().toLowerCase();k.length>0&&!h.has(k)&&h.set(k,w)}al(i,f,h)}catch(h){throw new _(h instanceof Error?h.message:String(h),g.USAGE)}m=pi(f,i),m.replaced&&m.previousName!==void 0&&m.previousName!==m.definition.name&&c.push(`type_recased:${m.previousName}->${m.definition.name}`),await jt({pmRoot:r,filePath:a,raw:Ot(m.file),op:"schema:add-type",author:d,settings:o}),await Tr(r,[m.definition],c,"schema:add-type-folder"),c.push(...await Y({path:a,scope:"project",op:"schema:add-type"}))}finally{await u()}return await df(r,c),{action:"add-type",registered:!0,replaced:m.replaced,type:m.definition,file:{path:a,definitions:m.file.definitions.length},warnings:Ht(c),generated_at:C()}}async function bt(e){await ie(e)}async function df(e,t){try{let n=await om(e);n.status==="refreshed"?t.push("merge_fence_refreshed"):n.status==="not_installed"&&t.push('merge_fence_not_installed:type folders lack git merge drivers; run "pm merge install"')}catch{t.push('merge_fence_refresh_failed:run "pm merge install" to reconcile')}}function Ht(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}async function ix(e,t,n,r){let i=W(t,U()),o=r.trim().toLowerCase();return(await _t(e,t.item_format,i.type_to_folder,[],n)).filter(a=>typeof a.type=="string"&&a.type.toLowerCase()===o).length}async function ox(e,t,n,r){let i=W(t,U()),o=_e(n),s=ce(r);return(await _t(e,t.item_format,i.type_to_folder,[],n)).filter(c=>{let d=typeof c.status=="string"?c.status:"";return(o.alias_to_id.get(ce(d))??ce(d))===s}).length}async function sx(e,t,n,r,i){if(i.length===0||ks.has(i))return;let o=await ox(t,n,r,i);o>0&&e.push(`items_using_status:${o}`);let s=ax(r.workflow,i);s.length>0&&e.push(`status_referenced_by_workflow:${s.join(",")}`)}function ax(e,t){return[["draft_status",e.draft_status],["open_status",e.open_status],["in_progress_status",e.in_progress_status],["blocked_status",e.blocked_status],["close_status",e.close_status],["canceled_status",e.canceled_status]].filter(([,r])=>r!==void 0&&ce(r)===t).map(([r])=>r)}async function eF(e,t,n){let r=M(process.cwd(),n.path);await bt(r);let i=await T(r),o=$e(i.schema),s=it(r,o.files.types,Le.types),a=[],c=q(t.author,i.author_default),d=Je(i),l=await se(r,so,i.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,i.locks.wait_ms),u;try{let m=await B(s),p;try{p=ft(m)}catch(f){throw new _(f instanceof Error?f.message:String(f),g.GENERIC_FAILURE)}try{u=cl(p,e)}catch(f){throw new _(f instanceof Error?f.message:String(f),g.USAGE)}if(u.removed){let f=(u.definition?.name??e??"").trim();if(f.length>0){let h=await ix(r,i,o,f);h>0&&a.push(`items_using_type:${h}`)}await jt({pmRoot:r,filePath:s,raw:Ot(u.file),op:"schema:remove-type",author:c,settings:i}),a.push(...await Y({path:s,scope:"project",op:"schema:remove-type"}))}}finally{await l()}return u.removed&&await df(r,a),{action:"remove-type",removed:u.removed,...u.definition?{type:u.definition}:{},file:{path:s,definitions:u.file.definitions.length},warnings:Ht(a),generated_at:C()}}function Ea(e,t){return it(e,t.files.statuses,Le.statuses)}function ao(e,t){return it(e,t.files.fields,Le.fields)}function lf(e,t){return it(e,t.files.types,Le.types)}async function Tr(e,t,n,r){for(let i of t){let o=Bd(i.folder??Gd(i.name)),s=nx.join(e,o);await P(s)||(await rx(s,{recursive:!0}),n.push(...await Y({path:s,scope:"project",op:r})))}}function Ra(e){return{key:e.key,type:e.type,commands:[...e.commands],cli_flag:`--${e.cli_flag}`,cli_aliases:e.cli_aliases.map(t=>`--${t}`),...e.description?{description:e.description}:{},required:e.required,required_on_create:e.required_on_create,allow_unset:e.allow_unset,required_types:[...e.required_types]}}function cx(e){if(e)return{id:e.id,...e.roles.length>0?{roles:[...e.roles]}:{},...e.aliases.length>0?{aliases:[...e.aliases]}:{},...e.description?{description:e.description}:{},...typeof e.order=="number"?{order:e.order}:{}}}function dx(e){let t=new Map;for(let n of e){let r=ce(n.id);if(r.length!==0){t.set(r,r);for(let i of Array.isArray(n.aliases)?n.aliases:[]){let o=ce(i);o.length>0&&!t.has(o)&&t.set(o,r)}}}return t}async function tF(e,t,n){let r=M(process.cwd(),n.path);await bt(r);let i;try{i=yl({id:e,roles:t.role,aliases:t.alias,description:t.description,order:t.order})}catch(y){throw new _(y instanceof Error?y.message:String(y),g.USAGE)}let o=await T(r),s=$e(o.schema),a=Ea(r,s),c=_e(s);try{bs(i,c.alias_to_id)}catch(y){throw new _(y instanceof Error?y.message:String(y),g.USAGE)}let d=cx(c.by_id.get(i.id));if((i.roles??d?.roles??[]).length===0)throw new _(`Status "${i.id}" requires at least one lifecycle role. Re-run with --role active, --role blocked, --role draft, or an appropriate terminal/default role.`,g.USAGE,{code:"status_lifecycle_role_required",examples:[`pm schema add-status "${pn(i.id)}" --role active`,`pm schema add-status "${pn(i.id)}" --role blocked`]});let u=[],m=q(t.author,o.author_default),p=Je(o),f=await se(r,af,o.locks.ttl_seconds,m,!!t.force,p.force_required_for_stale_lock,o.locks.wait_ms),h;try{let y=await B(a),w;try{w=_n(y)}catch(k){throw new _(k instanceof Error?k.message:String(k),g.GENERIC_FAILURE)}let v=dx(w.statuses);try{bs(i,v)}catch(k){throw new _(k instanceof Error?k.message:String(k),g.USAGE)}h=wl(w,i,d),await jt({pmRoot:r,filePath:a,raw:gn(h.file),op:"schema:add-status",author:m,settings:o}),u.push(...await Y({path:a,scope:"project",op:"schema:add-status"}))}finally{await f()}return{action:"add-status",registered:!0,replaced:h.replaced,status:h.definition,file:{path:a,statuses:h.file.statuses.length},warnings:Ht(u),generated_at:C()}}async function nF(e,t,n){let r=M(process.cwd(),n.path);await bt(r);let i=await T(r),o=$e(i.schema),s=Ea(r,o),a=[],c=q(t.author,i.author_default),d=Je(i),l=await se(r,af,i.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,i.locks.wait_ms),u;try{let m=await B(s),p;try{p=_n(m)}catch(f){throw new _(f instanceof Error?f.message:String(f),g.GENERIC_FAILURE)}try{u=vl(p,e)}catch(f){throw new _(f instanceof Error?f.message:String(f),g.USAGE)}if(u.removed){let f=ce(u.definition?.id??e);await sx(a,r,i,o,f),await jt({pmRoot:r,filePath:s,raw:gn(u.file),op:"schema:remove-status",author:c,settings:i}),a.push(...await Y({path:s,scope:"project",op:"schema:remove-status"}))}}finally{await l()}return{action:"remove-status",removed:u.removed,...u.definition?{status:u.definition}:{},file:{path:s,statuses:u.file.statuses.length},warnings:Ht(a),generated_at:C()}}function uf(e){return{name:e.name,folder:e.folder,aliases:Array.isArray(e.aliases)?[...e.aliases]:[],...e.default_status?{default_status:e.default_status}:{},...e.description?{description:e.description}:{}}}function lx(e,t,n){return{...uf(e),source:t,...n?{extension:n}:{},required_create_fields:[...e.required_create_fields],required_create_repeatables:[...e.required_create_repeatables],options:structuredClone(e.options),command_option_policies:structuredClone(e.command_option_policies)}}function mf(e){return{id:e.id,source:ks.has(e.id)?"builtin":"custom",roles:Array.isArray(e.roles)?[...e.roles]:[],aliases:Array.isArray(e.aliases)?[...e.aliases]:[],...e.description?{description:e.description}:{},...typeof e.order=="number"?{order:e.order}:{}}}function pf(e,t,n){let r=e.toLowerCase();return n.has(r)?"extension":t.has(r)?"custom":"builtin"}function ux(){let e=new Map,t=U();for(let n of t?.item_types??[]){let r=n.types;if(Array.isArray(r))for(let i of r){if(typeof i!="object"||i===null||Array.isArray(i))continue;let o=i.name;typeof o=="string"&&o.trim().length>0&&e.set(o.trim().toLowerCase(),{layer:n.layer,name:n.name})}}return e}function mx(e){let t=_e(e),n=[],r=[];for(let i of t.definitions){let o=mf(i);o.source==="builtin"?n.push(o):r.push(o)}return{builtin:n,custom:r}}async function Or(e){let t=M(process.cwd(),e.path);await bt(t);let n=await T(t),r=$e(n.schema),i=it(t,r.files.types,Le.types),o=Ea(t,r),s=W(n,U()),a=ux(),c=new Set((n.item_types?.definitions??[]).map(d=>d.name.trim().toLowerCase()).filter(d=>d.length>0&&!a.has(d)));return{pmRoot:t,typesPath:i,statusesPath:o,byType:s.by_type,customNames:c,extensionProvenance:a,schema:r}}async function rF(e){let t=await Or(e),n=[],r=[],i=[];for(let a of Object.values(t.byType).sort((c,d)=>c.name.localeCompare(d.name))){let c=pf(a.name,t.customNames,new Set(t.extensionProvenance.keys())),d=uf(a);c==="extension"?i.push(d):c==="custom"?r.push(d):n.push(d)}let o=mx(t.schema),s=fi(t.schema).definitions.map(Ra);return{action:"list",builtin:n,custom:r,extension:i,counts:{builtin:n.length,custom:r.length,extension:i.length,total:n.length+r.length+i.length},statuses:{builtin:o.builtin,custom:o.custom,counts:{builtin:o.builtin.length,custom:o.custom.length,total:o.builtin.length+o.custom.length}},fields:{custom:s,counts:{total:s.length}},file:{path:t.typesPath},generated_at:C()}}async function iF(e,t){let n=(e??"").trim();if(n.length===0)throw new _("Type name must not be empty.",g.USAGE);let r=await Or(t),i=Object.values(r.byType).find(o=>o.name.toLowerCase()===n.toLowerCase()||o.aliases.some(s=>s.toLowerCase()===n.toLowerCase()));if(!i)throw new _(`Unknown item type "${n}". Run pm schema list to inspect registered types, or pm schema add-type "${pn(n)}" to register it.`,g.NOT_FOUND,{code:"unknown_item_type"});return{action:"show",type:lx(i,pf(i.name,r.customNames,new Set(r.extensionProvenance.keys())),r.extensionProvenance.get(i.name.toLowerCase())),file:{path:r.typesPath},generated_at:C()}}async function oF(e,t){let n=ce(e);if(n.length===0)throw new _("Status id must not be empty.",g.USAGE);let r=await Or(t),i=_e(r.schema),o=i.alias_to_id.get(n)??n,s=i.by_id.get(o);if(!s)throw new _(`Unknown status "${e}". Run pm schema list to inspect registered statuses, or pm schema add-status "${pn(e??"")}" to register it.`,g.NOT_FOUND,{code:"unknown_status"});return{action:"show-status",status:mf(s),file:{path:r.statusesPath},generated_at:C()}}async function sF(e,t,n){let r=M(process.cwd(),n.path);await bt(r);let i;try{i=ul({key:e,type:t.type,commands:t.commands,description:t.description,cliFlag:t.cliFlag,aliases:t.alias,required:t.required,requiredOnCreate:t.requiredOnCreate,allowUnset:t.allowUnset,requiredTypes:t.requiredTypes})}catch(f){throw new _(f instanceof Error?f.message:String(f),g.USAGE)}du(i);let o=await T(r),s=$e(o.schema),a=ao(r,s),c=[],d=Oi(i.key);d&&c.push(`custom_field_mcp_input_collision:${d.field}:${d.property}:${d.owner}:use=${d.nested_path}`);let l=q(t.author,o.author_default),u=Je(o),m=await se(r,cf,o.locks.ttl_seconds,l,!!t.force,u.force_required_for_stale_lock,o.locks.wait_ms),p;try{let f=await B(a),h;try{h=fn(f)}catch(y){throw new _(y instanceof Error?y.message:String(y),g.GENERIC_FAILURE)}p=ml(h,i),await jt({pmRoot:r,filePath:a,raw:hn(p.file),op:"schema:add-field",author:l,settings:o}),c.push(...await Y({path:a,scope:"project",op:"schema:add-field"}))}finally{await m()}return{action:"add-field",registered:!0,replaced:p.replaced,field:p.definition,file:{path:a,fields:p.file.fields.length},warnings:Ht(c),generated_at:C()}}async function px(e,t,n,r){let i=W(t,U());return(await _t(e,t.item_format,i.type_to_folder,[],n)).filter(s=>{let a=s[r];return a==null?!1:Array.isArray(a)?a.length>0:typeof a=="string"?a.trim().length>0:!0}).length}async function aF(e,t,n){let r=M(process.cwd(),n.path);await bt(r);let i=await T(r),o=$e(i.schema),s=ao(r,o),a=[],c=q(t.author,i.author_default),d=Je(i),l=await se(r,cf,i.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,i.locks.wait_ms),u;try{let m=await B(s),p;try{p=fn(m)}catch(f){throw new _(f instanceof Error?f.message:String(f),g.GENERIC_FAILURE)}try{u=pl(p,e)}catch(f){throw new _(f instanceof Error?f.message:String(f),g.USAGE)}if(u.removed){let f=ce(u.definition?.key??e),h=ce(u.definition?.metadata_key??u.definition?.front_matter_key??f);if(h.length>0){let y=await px(r,i,o,h);y>0&&a.push(`items_using_field:${y}`)}await jt({pmRoot:r,filePath:s,raw:hn(u.file),op:"schema:remove-field",author:c,settings:i}),a.push(...await Y({path:s,scope:"project",op:"schema:remove-field"}))}}finally{await l()}return{action:"remove-field",removed:u.removed,...u.definition?{field:u.definition}:{},file:{path:s,fields:u.file.fields.length},warnings:Ht(a),generated_at:C()}}async function cF(e){let t=await Or(e),n=fi(t.schema).definitions.map(Ra);return{action:"list-fields",fields:n,counts:{total:n.length},file:{path:ao(t.pmRoot,t.schema)},generated_at:C()}}async function dF(e,t){let n=ce(e);if(n.length===0)throw new _("Field key must not be empty.",g.USAGE);let r=await Or(t),i=fi(r.schema).by_key.get(n);if(!i)throw new _(`Unknown custom field "${e}". Run pm schema list-fields to inspect registered fields, or pm schema add-field "${pn(e??"")}" to register it.`,g.NOT_FOUND,{code:"unknown_field"});return{action:"show-field",field:Ra(i),file:{path:ao(r.pmRoot,r.schema)},generated_at:C()}}async function lF(e,t,n){let r=M(process.cwd(),n.path);await bt(r);let i;try{let h=ll(e);if(h===void 0)throw new Error(`Type preset name is required. Allowed: ${dl.join(", ")}.`);i=h}catch(h){throw new _(h instanceof Error?h.message:String(h),g.USAGE)}let o=await T(r),s=$e(o.schema),a=lf(r,s),c=[],d=q(t.author,o.author_default),l=Je(o),u=[],m=[],p,f=await se(r,so,o.locks.ttl_seconds,d,!!t.force,l.force_required_for_stale_lock,o.locks.wait_ms);try{let h=await B(a),y;try{y=ft(h)}catch(v){throw new _(v instanceof Error?v.message:String(v),g.GENERIC_FAILURE)}let w=y;for(let v of vs(i)){let k=pi(w,v);w=k.file,(k.replaced?m:u).push(k.definition.name)}p=w.definitions.length,await jt({pmRoot:r,filePath:a,raw:Ot(w),op:"schema:apply-preset",author:d,settings:o}),await Tr(r,vs(i),c,"schema:apply-preset-folder"),c.push(...await Y({path:a,scope:"project",op:"schema:apply-preset"}))}finally{await f()}return{action:"apply-preset",preset:i,registered:u,replaced:m,file:{path:a,definitions:p},warnings:Ht(c),generated_at:C()}}function fx(e){if(e===void 0)return 10;if(!Number.isInteger(e)||e<1)throw new _("--min-count must be a positive integer (>= 1).",g.USAGE);return e}async function uF(e,t){let n=M(process.cwd(),t.path);await bt(n);let r=await T(n),i=$e(r.schema),o=lf(n,i),s=fx(e.minCount),a=W(r,U()),d=(await _t(n,r.item_format,a.type_to_folder,[],i)).map(k=>typeof k.title=="string"?k.title:""),l=Kp(d,{minCount:s}),u=[],m=[],p=[],f=[],h;if(!e.apply){let k;try{k=ft(await B(o))}catch(x){throw new _(x instanceof Error?x.message:String(x),g.GENERIC_FAILURE)}return h=k.definitions.length,{action:"infer-types",applied:!1,min_count:s,candidates:l,registered:m,replaced:p,skipped:f,file:{path:o,definitions:h},warnings:u,generated_at:C()}}let y=q(e.author,r.author_default),w=Je(r),v=await se(n,so,r.locks.ttl_seconds,y,!!e.force,w.force_required_for_stale_lock,r.locks.wait_ms);try{let k=await B(o),x;try{x=ft(k)}catch(A){throw new _(A instanceof Error?A.message:String(A),g.GENERIC_FAILURE)}let E=x;for(let A of l){if(A.shadows_builtin){f.push({name:A.name,reason:"shadows_builtin"});continue}let S;try{S=ws({name:A.name})}catch{f.push({name:A.name,reason:"invalid_type_token"});continue}let b=pi(E,S);E=b.file,(b.replaced?p:m).push(b.definition.name)}h=E.definitions.length,await jt({pmRoot:n,filePath:o,raw:Ot(E),op:"schema:infer-types",author:y,settings:r}),await Tr(n,E.definitions.filter(A=>m.includes(A.name)||p.includes(A.name)),u,"schema:infer-types-folder"),u.push(...await Y({path:o,scope:"project",op:"schema:infer-types"}))}finally{await v()}return{action:"infer-types",applied:!0,min_count:s,candidates:l,registered:m,replaced:p,skipped:f,file:{path:o,definitions:h},warnings:Ht(u),generated_at:C()}}import ff from"node:fs/promises";import Aa from"node:path";function Oe(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function R(e){return e.trim().toLowerCase()}function co(e){let t=e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-"),n=0;for(;t[n]==="-";)n+=1;let r=t.length;for(;r>n&&t[r-1]==="-";)r-=1;let i=t.slice(n,r);if(i.length===0)throw new _("Extension manifest name must resolve to a non-empty directory name.",g.USAGE);if(i==="."||i==="..")throw new _('Extension manifest name must not resolve to "." or "..".',g.USAGE);return i}function Ia(e){return rl(e)}async function hx(e){try{let t=JSON.parse(await ff.readFile(Aa.join(e,"package.json"),"utf8")),n=typeof t.name=="string"&&/^(?:@[a-z0-9._~-]+\/)?[a-z0-9._~-]+$/iu.test(t.name)?t.name:void 0;return{...n?{package_name:n}:{},has_build_script:["build","prepare","prepack"].some(r=>typeof t.scripts?.[r]=="string")}}catch{return{has_build_script:!1}}}async function _x(e,t,n){if(n.source_kind!=="github"||typeof n.source_root!="string")return new _(`Extension entry file is missing at "${t}".`,g.USAGE);let r=await hx(n.source_root),i=r.package_name?`pm package install npm:${r.package_name}`:void 0,o=n.source_input??n.source_root;return new _(`Extension entry "${e.entry}" is absent from GitHub source "${o}". pm package install copies GitHub repositories without running package scripts${r.has_build_script?", and this package declares a build or publish script":""}. ${i?`Try "${i}" if the package is published, or install a locally built directory.`:"Build the source locally and install that directory, or use its published npm: package."}`,g.USAGE,{code:"github_source_entry_unbuilt",required:"Use a GitHub tree with committed runtime output, a published npm artifact, or a locally built source directory.",why:"GitHub installation is a source copy and never executes untrusted package build scripts.",examples:i?[i,`pm package install ${n.source_root}`]:[`pm package install ${n.source_root}`],nextSteps:i?[`Retry with ${i}.`,"Or build the repository locally, then install its directory."]:["Build the repository locally, then install its directory.","If it is published, retry with pm package install npm:<package-name>."],recovery:{attempted_command:`pm install ${o}`,normalized_args:["install",o],...i?{next_best_command:i}:{}}})}async function Un(e,t={}){let n=Aa.join(e,"manifest.json");if(!await P(n))throw new _(`Extension manifest is missing at "${n}".`,g.USAGE);let r;try{r=JSON.parse(await ff.readFile(n,"utf8"))}catch(s){throw new _(`Failed to parse extension manifest at "${n}": ${gx(s)}`,g.USAGE)}let i=Ia(r);if(!i)throw new _(`Extension manifest at "${n}" is invalid.`,g.USAGE);let o=Aa.resolve(e,i.entry);if(!he(e,o))throw new _(`Extension entry "${i.entry}" resolves outside extension directory "${e}".`,g.USAGE);if(!await P(o))throw await _x(i,o,t);if(!await il(e,o))throw new _(`Extension entry "${i.entry}" resolves outside extension directory after symlink resolution.`,g.USAGE);return{directory:e,manifest_path:n,entry_path:o,manifest:i}}function gx(e){return e instanceof Error?e.message:String(e)}import Ca from"node:fs/promises";import yx from"node:path";var wx=".managed-extensions.json",lo=1;function Pr(e){return yx.join(e,wx)}function vx(){return{version:lo,updated_at:C(),entries:[]}}function Lr(e){return[...e].sort((t,n)=>{let r=t.scope.localeCompare(n.scope);if(r!==0)return r;let i=t.name.localeCompare(n.name);return i!==0?i:t.directory.localeCompare(n.directory)})}function hf(e,t){return e.kind!==t.kind||e.input!==t.input||e.location!==t.location?!1:e.kind==="npm"&&t.kind==="npm"?e.package===t.package&&e.version===t.version:e.kind==="github"&&t.kind==="github"?e.repository===t.repository&&e.ref===t.ref&&e.subpath===t.subpath&&e.commit===t.commit:e.kind==="builtin"&&t.kind==="builtin"?e.name===t.name:!0}function Ae(e){return typeof e=="string"?e:void 0}var kx=/^(?:npm_registry|github_remote)_lookup_timed_out$/u;function bx(e,t){let n=Ae(t);return n===void 0||e.kind!=="github"||n.trim().length===0||/^[a-z0-9_]+$/u.test(n.trim())?n:"github_remote_lookup_failed"}function _f(e){return typeof e=="string"&&kx.test(e.trim())}function xx(e,t){return _f(e)&&typeof t=="number"&&Number.isSafeInteger(t)&&t>0?{update_check_timeout_ms:t}:{}}function Sx(e){return typeof e.name=="string"&&e.name.trim().length>0&&typeof e.directory=="string"&&e.directory.trim().length>0&&(e.scope==="project"||e.scope==="global")&&typeof e.manifest_version=="string"&&typeof e.manifest_entry=="string"&&Array.isArray(e.capabilities)&&e.capabilities.every(t=>typeof t=="string")&&typeof e.installed_at=="string"&&typeof e.updated_at=="string"}function Ex(e){if(typeof e!="object"||e===null)return null;let t=e;return t.kind!=="local"&&t.kind!=="github"&&t.kind!=="npm"&&t.kind!=="builtin"||typeof t.input!="string"||typeof t.location!="string"?null:{kind:t.kind,input:t.input,location:t.location,name:Ae(t.name),package:Ae(t.package),version:Ae(t.version),repository:Ae(t.repository),owner:Ae(t.owner),repo:Ae(t.repo),ref:Ae(t.ref),subpath:Ae(t.subpath),commit:Ae(t.commit)}}function Rx(e){if(typeof e!="object"||e===null)return null;let t=e;if(!Sx(t))return null;let n=Ex(t.source);if(!n)return null;let r=tl(t.contributions);return r===null?null:{name:t.name.trim(),directory:t.directory.trim(),scope:t.scope,manifest_version:t.manifest_version,manifest_entry:t.manifest_entry,capabilities:Oe(t.capabilities),contributions:r,installed_at:t.installed_at,updated_at:t.updated_at,source:n,last_update_check_at:Ae(t.last_update_check_at),last_update_remote_commit:Ae(t.last_update_remote_commit),last_update_remote_version:Ae(t.last_update_remote_version),update_available:_f(t.update_error)?null:typeof t.update_available=="boolean"||t.update_available===null?t.update_available:void 0,update_error:bx(n,t.update_error),...xx(t.update_error,t.update_check_timeout_ms)}}function Ax(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.version!==lo||!Array.isArray(t.entries))return null;let n=[];for(let r of t.entries){let i=Rx(r);i&&n.push(i)}return{version:lo,updated_at:Ae(t.updated_at)??C(),entries:Lr(n)}}async function be(e){let t=Pr(e),n=vx();try{let r=await Ca.readFile(t,"utf8"),i=JSON.parse(r),o=Ax(i);if(!o)throw new _(`Managed extension state file "${t}" has an invalid schema. Repair or remove it before mutating extension state.`,g.GENERIC_FAILURE);return{path:t,state:o,warnings:[]}}catch(r){if(r instanceof _)throw r;if(typeof r=="object"&&r!==null&&"code"in r&&F(r))return{path:t,state:n,warnings:[]};throw new _(`Managed extension state file "${t}" could not be read. Repair or remove it before mutating extension state.`,g.GENERIC_FAILURE)}}async function zn(e,t){let n=Pr(e),r={version:lo,updated_at:C(),entries:Lr(t.entries)};await Ca.mkdir(e,{recursive:!0}),await Ca.writeFile(n,`${JSON.stringify(r,null,2)}
|
|
29
|
+
`,"utf8")}function Nr(e,t){let n=e.entries.filter(r=>R(r.name)!==R(t.name)&&R(r.directory)!==R(t.directory));return n.push(t),{...e,updated_at:C(),entries:Lr(n)}}async function gf(e,t,n,r){let i=t.entries.find(s=>R(s.name)===R(n));if(!i)return t;let o=Nr(t,{...i,contributions:r});return await zn(e,o),o}import{execFile as Fx}from"node:child_process";import J from"node:fs/promises";import Na from"node:os";import N from"node:path";import{fileURLToPath as jx}from"node:url";import{promisify as Hx}from"node:util";import Ux from"npm-package-arg";import{extract as zx,list as Wx}from"tar";import Ix from"node:fs/promises";import Ke from"node:path";var Cx="PM_CLI_PACKAGE_ROOT",yf={beads:{package_directory:"pm-beads",legacy_extension_directory:"beads"},todos:{package_directory:"pm-todos",legacy_extension_directory:"todos"}},$x=new Set(["*","all"]);function $a(){let e=[],t=process.env[Cx];return typeof t=="string"&&t.trim().length>0&&e.push(Ke.resolve(t.trim())),e.push(et(import.meta.url,["../../.."])),[...new Set(e)]}async function Dr(e){let t=e.trim().toLowerCase(),n=await vf(t);if(n)return n;let r=yf[t];if(!r)return null;for(let i of $a()){let o=Ke.join(i,".agents","pm","extensions",r.legacy_extension_directory);if(await P(Ke.join(o,"manifest.json")))return o}return null}function wf(e){return $x.has(e.trim().toLowerCase())}function Tx(e){return e.replace(/^pm-/i,"").trim().toLowerCase()}async function Ox(e,t){let n=await Ix.readdir(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||!r.name.startsWith("pm-"))continue;let i=Ke.join(e,r.name);if(!await P(Ke.join(i,"package.json")))continue;let o=await ui(i),s=o.aliases&&o.aliases.length>0?o.aliases:[Tx(r.name)];for(let a of s){let c=a.trim().toLowerCase();c.length===0||t.has(c)||t.set(c,{alias:c,package_directory:r.name,package_root:i,package_name:o.package_name??null})}}}async function Ta(){let e=new Map;for(let t of $a()){let n=Ke.join(t,"packages");await P(n)&&await Ox(n,e)}for(let[t,n]of Object.entries(yf))if(!e.has(t))for(let r of $a()){let i=Ke.join(r,"packages",n.package_directory);if(await P(Ke.join(i,"package.json"))){e.set(t,{alias:t,package_directory:n.package_directory,package_root:i,package_name:null});break}}return[...e.values()].sort((t,n)=>t.alias.localeCompare(n.alias))}async function uo(){return(await Ta()).map(e=>e.alias)}async function vf(e){let t=e.trim().toLowerCase();return(await Ta()).find(r=>r.alias===t||r.package_directory.toLowerCase()===t||r.package_name?.toLowerCase()===t)?.package_root??null}async function kf(e){let t=await vf(e);return t?(await ui(t)).package_name??null:null}async function bf(e){let t=await Dr(e);if(!t)return null;try{let n=await mi(t);return n.length!==1?null:(await Un(n[0])).manifest.name}catch{return null}}function Px(e){return{docs:e.catalog?.links?.docs??e.package_homepage,npm:e.catalog?.links?.npm??(e.package_name&&e.package_private!==!0?`https://www.npmjs.com/package/${encodeURIComponent(e.package_name)}`:void 0),repository:e.catalog?.links?.repository??e.package_repository_url,report:e.catalog?.links?.report??e.package_bugs_url}}function Lx(e,t,n,r,i,o){let s=r==="global"?"--global":"--project",a=Object.fromEntries(ys.filter(c=>c!=="extensions").map(c=>[c,e.resources[c]??[]]).filter(([,c])=>Array.isArray(c)&&c.length>0));return{alias:t.alias,aliases:n,bundled:!0,available:!0,installed:n.some(c=>i.has(c))||o.has(Ke.resolve(t.package_root)),install_target:t.alias,install_command:`pm install ${t.alias} ${s}`,package_name:e.package_name,package_version:e.package_version,description:e.catalog?.summary??e.package_description,keywords:e.package_keywords??[],resources:e.resources,installable_resources:{extensions:e.resources.extensions??[]},metadata_only_resources:a,catalog:{display_name:e.catalog?.display_name,category:e.catalog?.category,tags:e.catalog?.tags??e.package_keywords??[],links:Px(e),media:e.catalog?.media}}}async function xf(e,t,n={}){let r=mn(M(process.cwd(),t.path),process.cwd()),i=e==="global"?r.global:r.project,o=await be(i),s=new Set(o.state.entries.filter(m=>m.scope===e).filter(m=>m.source.kind!=="builtin").map(m=>Ke.resolve(m.source.location))),a=new Set(o.state.entries.filter(m=>m.scope===e&&m.source.kind==="builtin").flatMap(m=>[m.source.name,m.source.input,m.source.location]).filter(m=>typeof m=="string"&&m.trim().length>0).map(m=>m.trim().toLowerCase())),c=[],d=new Map;for(let m of await Ta()){let p=Ke.resolve(m.package_root),f=d.get(p)??[];f.push(m),d.set(p,f)}for(let m of d.values()){let p=m[0],f=m.map(y=>y.alias).sort((y,w)=>y.localeCompare(w)),h=await ui(p.package_root);c.push(Lx(h,p,f,e,a,s))}let l=Dx(n.fields),u=l?c.map(m=>Mx(m,l)):c;return{total:u.length,scope:e,installable_resource_kinds:["extensions"],metadata_only_resource_kinds:ys.filter(m=>m!=="extensions"),packages:u}}var Nx=new Set(["alias","aliases","bundled","available","installed","install_target","install_command","package_name","package_version","description","keywords","resources","installable_resources","metadata_only_resources","catalog","category","display_name"]);function Dx(e){if(e===void 0)return;let t=Ku(e);if(t.length===0)throw new _("Package catalog --fields requires a comma-separated list of field names",g.USAGE);let n=t.filter(r=>!Nx.has(r));if(n.length>0)throw new _(`Unknown package catalog --fields value(s): ${n.join(", ")}`,g.USAGE,{examples:["pm package list --project --fields alias,installed,install_command","pm package catalog --project --fields alias,package_name,category"]});return t}function Mx(e,t){let n={};for(let r of t)r==="category"?n[r]=e.catalog?.category??null:r==="display_name"?n[r]=e.catalog?.display_name??null:n[r]=e[r]??null;return n}var Rf=Hx(Fx),mo="@unbrained/pm-cli",qx={maxArchiveBytes:64*1024*1024,maxEntries:4096,maxExpandedBytes:256*1024*1024,maxEntryBytes:64*1024*1024},Oa;async function Af(e,t=process.cwd()){let n=e.trim();if(!/^(@[^/\\\s]+\/[^/\\\s]+|[^@/\\\s][^/\\\s]*)$/u.test(n))return null;let r=N.resolve(t);for(;;){let i=N.join(r,"node_modules",...n.split("/")),o=N.join(i,"package.json");if(await P(o))try{let a=JSON.parse(await J.readFile(o,"utf8"));if(a.name===n)return{package:n,...typeof a.version=="string"?{version:a.version}:{},directory:i}}catch{return null}let s=N.dirname(r);if(s===r)return null;r=s}}function Pa(e,t,n){let r=e.split("/").map(d=>d.trim()).filter(d=>d.length>0);if(r.length<2)return null;let i=r[0],o=r[1].replace(/\.git$/i,"");if(i.length===0||o.length===0)return null;let s=r.slice(2),a,c;return s[0]==="tree"&&s.length>=2?(a=s[1],c=s.slice(2).join("/")):s.length>0&&(c=s.join("/")),typeof n=="string"&&n.trim().length>0&&(a=n.trim()),{kind:"github",input:t,owner:i,repo:o,repository:`https://github.com/${i}/${o}.git`,ref:a,subpath:c&&c.length>0?c:void 0}}function Gx(e,t,n){let r=e.slice(4).trim();if(r.length===0)throw new _('npm package source must include a package spec after "npm:".',g.USAGE);if(t)throw new _('Options "--gh/--github" cannot be combined with npm: package sources.',g.USAGE);if(n)throw new _('Option "--ref" cannot be combined with npm: package sources.',g.USAGE);return{kind:"npm",input:e,spec:r}}function Mr(e,t={}){let n=e.trim();if(n.length===0)throw new _("Extension source is required for --install.",g.USAGE);let r=typeof t.ref=="string"&&t.ref.trim().length>0?t.ref.trim():void 0;if(n.startsWith("npm:"))return Gx(n,t.forceGithub===!0,r);let i=(()=>{try{let s=new URL(n);if(s.hostname!=="github.com")return null;let a=s.pathname.replace(/^\/+/,"");return Pa(a,n,r)}catch{return null}})();if(i)return i;let o=n.startsWith("github.com/")?n.slice(11):null;if(o){let s=Pa(o,n,r);if(!s)throw new _(`Invalid GitHub source "${n}".`,g.USAGE);return s}if(t.forceGithub){let s=Pa(n,n,r);if(!s)throw new _(`Invalid GitHub shorthand "${n}".`,g.USAGE);return s}if(/^https?:\/\//i.test(n))throw new _(`Unsupported extension source URL "${n}". Supported remote source host: github.com.`,g.USAGE);return{kind:"local",input:n,absolute_path:N.resolve(process.cwd(),n)}}async function Sf(e,t=Rf,n){try{return((await t("git",e,{encoding:"utf8",timeout:n})).stdout??"").trim()}catch(r){let i=typeof r=="object"&&r!==null&&"stderr"in r?String(r.stderr):"",o=i.trim().length>0?i.trim():r instanceof Error?r.message:String(r);throw new _(`Git command failed: git ${e.join(" ")}
|
|
30
|
+
${o}`,g.GENERIC_FAILURE)}}function Da(e=process.platform){return e==="win32"?"npm.cmd":"npm"}function Ma(e=process.platform){return e==="win32"}async function If(e,t,n=Rf,r=process.platform,i=process.env){let o=Da(r),s=Object.fromEntries(Object.entries(i).filter(([a])=>a.toLowerCase()!=="npm_config_allow_scripts"));s.NPM_CONFIG_ALLOW_SCRIPTS="";try{return((await n(o,e,{cwd:t,encoding:"utf8",env:s,shell:Ma(r)})).stdout??"").trim()}catch(a){let c=typeof a=="object"&&a!==null&&"stderr"in a?String(a.stderr):"",d=c.trim().length>0?c.trim():a instanceof Error?a.message:String(a);throw new _(`npm command failed: ${o} ${e.join(" ")}
|
|
31
|
+
${d}`,g.GENERIC_FAILURE)}}function Cf(e){let t=e.trim(),n=t.includes("@file:")?t.slice(0,t.lastIndexOf("@file:")):t;return n.startsWith("@")?n.match(/^(@[^/@\s]+\/[^/@\s]+)/)?.[1]??n:n.match(/^([^/@\s]+)/)?.[1]??n}function $f(e){let t="@file:",n=e.lastIndexOf(t);return n>0&&e.slice(0,n).trim().length>0&&e.slice(n+t.length).trim().length>0}function Bx(e){let n=(e instanceof Error?e.message:String(e)).toLowerCase();return n.includes("npm err! code e404")||n.includes("404 not found")||n.includes("is not in this registry")}function Jx(e){let n=(e instanceof Error?e.message:String(e)).toLowerCase();return Bx(e)||n.includes("not found")}function Vx(e){let t=e.trim().toLowerCase();return t.startsWith("@unbrained/pm-")||t.startsWith("pm-")}function Kx(e){let t=Cf(e),n=Vx(t),r=t.replace(/^.*\//,""),i=n?`github.com/unbraind/${r}`:void 0,o=i?`pm package install --project ${i}`:void 0;return{message:n?`npm package "${e}" was not found in the registry. If this is an unpublished first-party pm package, install its GitHub repository instead.`:`npm package "${e}" was not found in the registry.`,context:{code:"npm_package_not_found",required:"Use an install source that exists, or publish the npm package before installing it with npm:<name>.",why:"Classifying npm 404s avoids repeated registry retries and gives agents a deterministic fallback path.",examples:o?[o,"pm package catalog --project --json"]:[`npm view ${t}`,"pm package catalog --project --json"],nextSteps:o?[`Try ${o} if the repository exists.`,"Use pm package catalog --project --json to inspect bundled package aliases before installing."]:[`Verify ${t} exists in the npm registry and that you have access to it.`,"Use pm package catalog --project --json to inspect bundled package aliases before installing."],recovery:{attempted_command:`pm install --project npm:${e}`,normalized_args:["install","--project",`npm:${e}`],...i&&o?{fallback_candidates:[{source:i,command:o,reason:"canonical first-party GitHub repository fallback for unpublished pm packages"}],next_best_command:o}:{}}}}}function Yx(e,t){if(!Jx(t))return null;let n=Kx(e);return new _(n.message,g.NOT_FOUND,n.context)}async function Tf(e){if(N.isAbsolute(e)||e.startsWith(".")||e.startsWith("..")){let t=N.resolve(process.cwd(),e);return await P(t)?t:null}try{let t=new URL(e);if(t.protocol==="file:"){let n=jx(t);return await P(n)?n:null}}catch{}if(!/^[a-z][a-z0-9+.-]*:/i.test(e)){let t=N.resolve(process.cwd(),e);if(await P(t))return t}return null}async function Xx(e){let t=await Tf(e);if(t)return t;let n=Zx(e);return n!==e?n:(/^[a-z][a-z0-9+.-]*:/i.test(e),e)}function Zx(e,t=process.cwd()){let n="@file:",r=e.lastIndexOf(n);if(!$f(e))return e;let i=e.slice(0,r),o=e.slice(r+n.length);if(o.startsWith("//")&&!o.startsWith("///"))return e;if(!o.startsWith("/"))return`${i}@${N.resolve(t,o)}`;let s;try{s=decodeURIComponent(new URL(`file:${o}`).pathname)}catch{return e}let a=/^\/[A-Za-z]:/.test(s)?s.slice(1):s;return`${i}@${a}`}function Ef(e,t){let n=N.resolve(e,t),r=N.relative(e,n);if(r.length===0||r===".."||r.startsWith(`..${N.sep}`)||N.isAbsolute(r))throw new _("npm pack reported a package archive outside its isolated destination.",g.GENERIC_FAILURE,{code:"npm_package_archive_unsafe",required:"Retry with a trusted npm client that writes its archive inside the requested pack destination.",why:"pm will not read a package-manager artifact outside the isolated directory created for this install."});return n}function Qx(e,t){if(typeof e!="object"||e===null||Array.isArray(e))return;let n=e;if(!(typeof n.filename!="string"||n.filename.trim().length===0))return{...t===void 0?{}:{key:t},filename:n.filename,...typeof n.name=="string"?{name:n.name}:{},...typeof n.version=="string"?{version:n.version}:{}}}function eS(e){return(Array.isArray(e)?e.map(n=>({value:n})):typeof e=="object"&&e!==null?Object.entries(e).map(([n,r])=>({key:n,value:r})):[]).flatMap(({key:n,value:r})=>{let i=Qx(r,n);return i?[i]:[]})}function tS(e,t){let n=t?.trim().toLowerCase(),r=n?e.filter(s=>{let a=s.name?.trim().toLowerCase();return a!==void 0?a===n:s.key?.trim().toLowerCase()===n}):[];if(r.length===1)return r[0];if(e.length!==1)return;let i=e[0],o=i.name??i.key;return n&&o!==void 0&&o.trim().toLowerCase()!==n?void 0:i}function nS(e,t,n){let r;try{r=JSON.parse(e)}catch{let s=e.split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0).at(-1);if(!s)throw new _("npm pack did not report a tarball filename.",g.GENERIC_FAILURE);return{tarball:Ef(t,s)}}let i=eS(r),o=tS(i,n);if(!o)throw new _("npm pack --json returned an unsupported or ambiguous package receipt.",g.GENERIC_FAILURE,{code:"npm_pack_json_shape_unsupported",required:"Use an npm client that returns an array of package receipts or an object keyed by package name, with exactly one requested package entry containing filename.",why:`Well-formed JSON contained ${i.length} usable package receipt(s), but pm could not select ${n??"one package"} deterministically.`});return{tarball:Ef(t,o.filename),package:o.name??o.key,version:o.version}}async function rS(e){return iS(e,If)}async function iS(e,t){let n=await Tf(e.spec);if(n){if((await J.stat(n)).isFile()&&Of(n))return La(n);let s=N.join(n,"package.json"),a=await P(s)?JSON.parse(await J.readFile(s,"utf8")):{};return{directory:await po(n,e.input),package:typeof a.name=="string"?a.name:void 0,version:typeof a.version=="string"?a.version:void 0,cleanup:async()=>{}}}let r=await J.mkdtemp(N.join(Na.tmpdir(),"pm-npm-package-source-")),i=N.join(r,"pack");await J.mkdir(i,{recursive:!0});try{let o=await Xx(e.spec),s=await t(["pack",o,"--json","--pack-destination",i]),a=nS(s,i,$f(e.spec)?void 0:Cf(e.spec));if(!await P(a.tarball))throw new _("npm pack did not create its reported package archive.",g.GENERIC_FAILURE,{code:"npm_package_archive_missing",required:"Retry the npm package install with a healthy registry and writable temporary directory.",why:"The package manager reported a tarball filename that was absent before validation, so pm cannot safely extract or install it."});let c=await La(a.tarball);return{directory:c.directory,package:a.package??c.package,version:a.version??c.version,cleanup:async()=>{try{await c.cleanup()}finally{await J.rm(r,{recursive:!0,force:!0})}}}}catch(o){await J.rm(r,{recursive:!0,force:!0});let s=Yx(e.spec,o);throw s||o}}function Of(e){let t=e.toLowerCase();return t.endsWith(".tgz")||t.endsWith(".tar.gz")}function xt(e){throw new _(e,g.USAGE,{code:"local_package_archive_unsafe",required:"Use a bounded npm .tgz or .tar.gz archive with one package/ root and no links or escaping paths.",why:"Package archives are untrusted input and must be validated before any entry reaches the filesystem."})}function oS(e,t,n){if(e.meta)return;n.entries+=1,n.entries>t.maxEntries&&xt(`Local package archive exceeds the ${t.maxEntries} entry limit.`);let r=e.path,i=r.split("/");(r.includes("\\")||r.startsWith("/")||/^[A-Za-z]:/u.test(r)||i.some(o=>o===".."))&&xt(`Local package archive contains an escaping path: "${r}".`),i[0]!=="package"&&xt(`Local package archive entry "${r}" is outside the required package/ root.`),(e.type==="SymbolicLink"||e.type==="Link")&&xt(`Local package archive link "${r}" is not supported.`),e.type!=="File"&&e.type!=="OldFile"&&e.type!=="Directory"&&xt(`Local package archive entry "${r}" uses unsupported type "${e.type}".`),e.size>t.maxEntryBytes&&xt(`Local package archive entry "${r}" exceeds the ${t.maxEntryBytes} byte entry limit.`),n.expandedBytes+=e.size,n.expandedBytes>t.maxExpandedBytes&&xt(`Local package archive exceeds the ${t.maxExpandedBytes} expanded byte limit.`),r==="package/package.json"&&(n.packageJsonEntries+=1)}async function La(e,t=qx){(await J.stat(e)).size>t.maxArchiveBytes&&xt(`Local package archive exceeds the ${t.maxArchiveBytes} archive byte limit.`);let r=await J.mkdtemp(N.join(Na.tmpdir(),"pm-local-package-archive-")),i=N.join(r,"extract");await J.mkdir(i,{recursive:!0});let o={entries:0,expandedBytes:0,packageJsonEntries:0},s;try{if(await Wx({file:e,strict:!0,maxDecompressionRatio:100,onReadEntry:l=>{if(s===void 0)try{oS(l,t,o)}catch(u){s=u}}}),s!==void 0)throw s;o.packageJsonEntries!==1&&xt(`Local package archive must contain exactly one package/package.json entry; found ${o.packageJsonEntries}.`),await zx({file:e,cwd:i,strict:!0,preservePaths:!1,preserveOwner:!1,noMtime:!0,unlink:!0,maxDepth:64,maxDecompressionRatio:100});let a=N.join(i,"package"),c=N.join(a,"package.json"),d=JSON.parse(await J.readFile(c,"utf8"));return await sS(a),{directory:await po(a,e),package:typeof d.name=="string"?d.name:void 0,version:typeof d.version=="string"?d.version:void 0,cleanup:async()=>{await J.rm(r,{recursive:!0,force:!0})}}}catch(a){throw await J.rm(r,{recursive:!0,force:!0}),a}}async function sS(e,t=If){let n=N.join(e,"package.json");if(!await P(n))return;let r;try{r=JSON.parse(await J.readFile(n,"utf8"))}catch{return}if(typeof r!="object"||r===null)return;let i=r,o=mS(i),s=aS(i);if(o.length===0&&!s)return;let a={...r};delete a.devDependencies;let c={...a};cS(c),await J.writeFile(n,`${JSON.stringify(c,null,2)}
|
|
32
|
+
`,"utf8");try{await Promise.all([J.rm(N.join(e,"package-lock.json"),{force:!0}),J.rm(N.join(e,"npm-shrinkwrap.json"),{force:!0})]),o.length>0&&await t(["install","--ignore-scripts","--no-audit","--fund=false","--package-lock=false","--no-save","--omit=peer","--"],e),s&&await dS(e)}finally{await J.writeFile(n,`${JSON.stringify(a,null,2)}
|
|
33
|
+
`,"utf8")}}function aS(e){for(let t of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(typeof t=="object"&&t!==null&&mo in t)return!0;return!1}function cS(e){for(let t of["dependencies","optionalDependencies","peerDependencies"]){let n=e[t];if(typeof n!="object"||n===null)continue;let r={...n};delete r[mo],Object.keys(r).length===0?delete e[t]:e[t]=r}}async function dS(e){let t=et(import.meta.url,["../../.."]),[n,r]=mo.split("/"),i=N.join(e,"node_modules",n),o=N.join(i,r);await J.mkdir(i,{recursive:!0}),await J.rm(o,{recursive:!0,force:!0}),await J.symlink(t,o,lS(process.platform))}function lS(e){return e==="win32"?"junction":"dir"}function uS(e,t){if(e.startsWith("-"))throw new _(`Extension runtime dependency name "${e}" is unsafe because npm could interpret it as a command-line option.`,g.USAGE,{code:"extension_dependency_name_unsafe",required:"Use a valid npm package name that does not begin with a dash.",why:"Extension manifests are untrusted input and dependency names must never become npm options."});if([...t].some(r=>{let i=r.charCodeAt(0);return i<=31||i===127||"&|;()`\"'".includes(r)}))throw new _(`Extension runtime dependency "${e}" has an unsafe version specifier.`,g.USAGE,{code:"extension_dependency_version_unsafe",required:"Use an npm version, range, dist-tag, URL, or file specifier without shell metacharacters.",why:"npm.cmd requires a command shell on Windows, so untrusted shell metacharacters cannot be forwarded."});try{Ux.resolve(e,t)}catch{throw new _(`Extension runtime dependency "${e}@${t}" is not a valid npm dependency specifier.`,g.USAGE,{code:"extension_dependency_spec_invalid",required:"Use a valid npm package name and npm-supported version, range, dist-tag, URL, or file specifier.",why:"Only grammar-validated dependency specs may be written to the isolated runtime install manifest."})}return`${e}@${t}`}function mS(e){let t=new Map;for(let n of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(!(typeof n!="object"||n===null))for(let[r,i]of Object.entries(n)){if(r===mo||typeof i!="string"||i.trim().length===0||t.has(r))continue;let o=i.trim();t.set(r,uS(r,o))}return[...t.values()]}async function po(e,t){let n=await mi(e);if(n.length===1)return n[0];if(n.length>1){let r=n.map(i=>N.relative(e,i).replaceAll(N.sep,"/")).sort((i,o)=>i.localeCompare(o));throw new _(`Package source "${t}" contains multiple extension manifests. Provide an explicit extension path. Candidates: ${r.join(", ")}`,g.USAGE)}throw new _(`Unable to locate a pm extension manifest in package source "${t}". Package installs currently activate only extension resources, so add package.json pm.extensions or an extensions/ directory. Metadata-only resources like pm.docs/pm.examples are catalog metadata and do not activate commands.`,g.USAGE)}async function pS(e,t){let n=[];t.subpath&&(n.push(t.subpath),n.push(N.posix.join(".agents/pm/extensions",t.subpath)),n.push(N.posix.join(".custom/pm-extensions",t.subpath)),n.push(N.posix.join(".custom/pm-extension",t.subpath)));for(let i of n){let o=N.resolve(e,i);if(he(e,o)&&await P(N.join(o,"manifest.json")))return{directory:o,resolved_subpath:i}}if(await P(N.join(e,"manifest.json")))return{directory:e,resolved_subpath:"."};let r=await po(e,t.input);return{directory:r,resolved_subpath:N.relative(e,r).replaceAll(N.sep,"/")}}function fS(e){let t=e.trim();return t.length===0||t.startsWith(".")||t.startsWith("~")?!1:t.startsWith("@")?t.split("/").length===2:!t.includes("/")&&!t.includes("\\")}async function hS(e){let t=`Local extension source does not exist: "${e.absolute_path}".`,n=e.input.trim();if(!fS(n))return new _(t,g.NOT_FOUND);let r=[];try{let o=process.env.PM_CLI_PACKAGE_ROOT,s=typeof o=="string"&&o.trim().length>0?N.resolve(o.trim()):"";Oa?.key!==s&&(Oa={key:s,aliases:await uo()}),r=Oa.aliases}catch{}let i=[`Retry with pm package install npm:${n} if the package is published to npm.`,`Or inspect bundled packages with pm package catalog --project --json before installing by alias. Known aliases (blank means none found): ${r.join(", ")}`];return new _(`${t} "${n}" did not match a local directory, bundled package alias, or bundled package name; if you meant an npm package, install it as "npm:${n}".`,g.NOT_FOUND,{code:"local_source_not_found_bare_name",required:`Use "npm:${n}" for npm registry packages, a bundled catalog alias, or an existing local directory path.`,why:"Bare names resolve as local paths only after bundled aliases, so unmatched names need an explicit npm: source.",examples:[`pm package install npm:${n}`,"pm package catalog --project --json"],nextSteps:i,recovery:{attempted_command:`pm install ${n}`,normalized_args:["install",n],next_best_command:`pm package install npm:${n}`}})}async function Pf(e){if(e.kind==="local"){let r;try{r=await J.stat(e.absolute_path)}catch{throw await hS(e)}if(r.isFile()&&Of(e.absolute_path)){let o=await La(e.absolute_path);return{source:e,directory:o.directory,source_root:N.dirname(o.directory),resolved_subpath:N.relative(N.dirname(o.directory),o.directory).replaceAll(N.sep,"/"),npm_package:o.package,npm_version:o.version,cleanup:o.cleanup}}if(!r.isDirectory())throw new _(`Local extension source must be a directory or npm .tgz/.tar.gz archive: "${e.absolute_path}".`,g.USAGE);let i=await po(e.absolute_path,e.input);return{source:e,directory:i,source_root:e.absolute_path}}if(e.kind==="npm"){let r=await rS(e);return{source:e,directory:r.directory,source_root:N.dirname(r.directory),cleanup:r.cleanup,resolved_subpath:N.relative(N.dirname(r.directory),r.directory).replaceAll(N.sep,"/"),npm_package:r.package,npm_version:r.version}}let t=await J.mkdtemp(N.join(Na.tmpdir(),"pm-extension-source-")),n=["clone","--depth","1"];e.ref&&n.push("--branch",e.ref),n.push(e.repository,t);try{await Sf(n);let r=await Sf(["-C",t,"rev-parse","HEAD"]),i=await pS(t,e);return{source:e,directory:i.directory,source_root:t,resolved_subpath:i.resolved_subpath,commit:r,cleanup:async()=>{await J.rm(t,{recursive:!0,force:!0})}}}catch(r){throw await J.rm(t,{recursive:!0,force:!0}),r}}async function Wn(e,t){if(!await P(e)||!await P(t))return!1;let[n,r]=await Promise.all([J.realpath(e),J.realpath(t)]);return n===r}import Fr from"node:fs/promises";import jr from"node:path";var Fa=1,tn="2026.6.24",_S=">=22.18.0",gS={fs_read:!1,fs_write:!1,network:!1,env_read:!1,env_write:!1,process_spawn:!1},Lf=new Set([...el.map(e=>e.split("-")[0].toLowerCase()),...Object.keys(Qd).map(e=>e.toLowerCase()),"scaffold"]),yS="^6.0.0",wS="^22.0.0",Mf=["type StarterHarness = Awaited<ReturnType<typeof createExtensionTestHarness>>;","","async function deactivateIfNeeded(ext: StarterHarness, deactivated: boolean): Promise<void> {"," if (!deactivated) {"," try {"," await ext.deactivate();"," } catch {"," // Preserve the original assertion error; cleanup is best effort."," }"," }","}",""],ct=[" } finally {"," await deactivateIfNeeded(ext, deactivated);"," }"];function Nf(e,t){return e.map(n=>n===""?n:`${t}${n}`)}function Ff(e){let t=e.includeMigrationReplacementHint===!0?[" // as your migration grows."]:[];return[" // assertItemType/Field/Migration throw unless the registration is present, so"," // reaching each next line already proves the wiring; assert on the returned"," // definitions to demonstrate inspecting registered metadata.",` const itemType = ext.assertItemType({ name: ${JSON.stringify(e.itemTypeName)}, extensionName: ${JSON.stringify(e.extensionName)} });`,` assert.equal(itemType.itemType.folder, ${JSON.stringify(e.itemTypeFolder)});`,` const itemField = ext.assertItemField({ name: ${JSON.stringify(e.fieldName)}, extensionName: ${JSON.stringify(e.extensionName)} });`,' assert.equal(itemField.field.type, "string");',` ext.assertMigration({ name: ${JSON.stringify(e.migrationId)}, extensionName: ${JSON.stringify(e.extensionName)}, mandatory: false });`,""," // runMigration invokes the migration through pm's real runner with a synthetic"," // context and returns its result.",...t,` const migrated = await ext.runMigration({ migration: ${JSON.stringify(e.migrationId)} });`,` assert.deepEqual(migrated, { migrated: true, id: ${JSON.stringify(e.migrationId)} });`]}function jf(e){return[" // assertProfile throws unless the profile is registered, so reaching the next"," // line already proves the wiring; assert on the returned definition to inspect"," // the bundled archetype dimensions.",` const { profile } = ext.assertProfile({ name: ${JSON.stringify(e)}, extensionName: ${JSON.stringify(e)} });`,` assert.equal(profile.title, ${JSON.stringify(`${e} archetype`)});`," assert.equal(profile.types.length, 1);"," assert.equal(profile.workflows.length, 1);"]}var vS={compilerOptions:{target:"ES2022",module:"NodeNext",moduleResolution:"NodeNext",strict:!0,esModuleInterop:!0,skipLibCheck:!0,noEmit:!0,allowImportingTsExtensions:!0,resolveJsonModule:!0,types:["node"]},include:["**/*.ts"]},Df=["commands","hooks","search","importers","schema","profile","renderers","parser","preflight","services"],Hf={commands:["commands"],hooks:["commands","hooks"],search:["commands","search"],importers:["commands","schema","importers"],schema:["commands","schema"],profile:["commands","schema"],renderers:["commands","renderers"],parser:["commands","parser","schema"],preflight:["commands","preflight"],services:["commands","services"]},kS={commands:'["commands"]',hooks:'["commands", "hooks"]',search:'["commands", "search"]',importers:'["commands", "schema", "importers"]',schema:'["commands", "schema"]',profile:'["commands", "schema"]',renderers:'["commands", "renderers"]',parser:'["commands", "parser", "schema"]',preflight:'["commands", "preflight"]',services:'["commands", "services"]'},bS={commands:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration plus a `deactivate` teardown stub.",hooks:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, an `after_command` lifecycle hook, and a `deactivate` teardown stub.",search:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a search provider, a vector-store adapter, and a `deactivate` teardown stub.",importers:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, importer/exporter command registrations, and a `deactivate` teardown stub.",schema:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a custom item type, a custom item field, a schema migration, and a `deactivate` teardown stub.",profile:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a project profile (item types, statuses, fields, a workflow, config, a template, and package recommendations) registered via `api.registerProfile`, and a `deactivate` teardown stub.",renderers:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a `toon` output renderer override, and a `deactivate` teardown stub.",parser:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a parser override that rewrites the command's parsed options, and a `deactivate` teardown stub.",preflight:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a preflight override over pm's pre-run gate decision, and a `deactivate` teardown stub.",services:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, an `output_format` service override, and a `deactivate` teardown stub."},xS={commands:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, and teardown via the SDK testing helpers.",hooks:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, the after_command hook, and teardown via the SDK testing helpers.",search:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, search provider/vector adapter invocation, and teardown via the SDK testing helpers.",importers:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, importer/exporter invocation, and teardown via the SDK testing helpers.",schema:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, item type/field/migration registration, migration invocation, and teardown via the SDK testing helpers.",profile:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, project-profile registration (asserting the bundled archetype dimensions), and teardown via the SDK testing helpers.",renderers:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, renderer override registration and invocation (including format pass-through), and teardown via the SDK testing helpers.",parser:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, parser override registration and the option rewrite it produces, and teardown via the SDK testing helpers.",preflight:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, preflight override registration and the gate decision it returns, and teardown via the SDK testing helpers.",services:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, service override registration and invocation (including command pass-through), and teardown via the SDK testing helpers."},Uf="- `tsconfig.json`: strict type-check-only TypeScript config (`noEmit`) for the `.ts` source the loader runs directly.",SS={commands:[],hooks:["","## Lifecycle Hook","`index.ts` registers an `after_command` hook via `api.hooks.afterCommand`.","pm fires it once a command finishes, passing the command outcome and the","items it mutated (`context.affected`). React there to keep external context","in sync - sync records, emit telemetry, or refresh derived state. The","`hooks` capability in `manifest.json` is what grants the hook registration;","remove it (and the hook) if your package only needs commands."],search:["","## Search Provider","`index.ts` registers a deterministic in-memory search provider and","vector-store adapter through `api.registerSearchProvider` and","`api.registerVectorStoreAdapter`. Replace the sample scoring,","embedding, and storage behavior with your project-specific retrieval","logic. The `search` capability in `manifest.json` grants both","registrations."],importers:["","## Importer and Exporter","`index.ts` registers paired project-context import/export commands through","`api.registerImporter` and `api.registerExporter`. Replace the starter","payloads with your domain adapter: GitHub issues, CSV rows, documents,","tickets, or another project-management source of truth. The `importers`","capability grants both registrations, and `schema` grants the example","command flag metadata."],schema:["","## Custom Schema","`index.ts` models a project domain by registering a custom item type, a","custom item field, and a schema migration through `api.registerItemTypes`,","`api.registerItemFields`, and `api.registerMigration`. This is how a package","turns pm into a domain-specific tracker \u2014 `project management = context","management`. Replace the sample type/field/migration with your own domain","model; the `schema` capability in `manifest.json` grants all three","registrations. Once installed, the custom type is usable everywhere, e.g.",'`pm create <type> "<title>"` and `pm list --type <type>`.'],profile:["","## Project Profile","`index.ts` registers a complete project-profile archetype through","`api.registerProfile`. A profile is the broadest customization primitive pm","has \u2014 one declarative bundle of item types, custom statuses, fields, a per-type","workflow, config knobs, create templates, and package recommendations. Once the","package is installed the profile resolves by name through `pm profile list`,","`pm profile show <name>`, and `pm profile apply <name>`, which stages every","dimension idempotently \u2014 exactly like a core archetype (agile/ops/research),","with no consumer code required. Replace the sample archetype with your own","domain; the `schema` capability in `manifest.json` grants the registration (a","profile is a schema+config bundle, so it needs no separate capability)."],renderers:["","## Output Renderer","`index.ts` registers a `toon` output renderer override through","`api.registerRenderer`. Renderer overrides run for every command's output in","that format, so this starter scopes itself to THIS package's own command and","returns `null` (pass-through to pm's default renderer) for everything else.","Return a string to take over rendering. Replace the sample serialization with","your own; the `renderers` capability in `manifest.json` grants the","registration."],parser:["","## Parser Override","`index.ts` registers a parser override for the starter command through","`api.registerParser`. pm runs it on the command's parsed options BEFORE the","handler, merging the delta you return. This starter rewrites a deprecated","`--shout` alias to the canonical `--upper` flag; replace it with your","command's real normalization. The `parser` capability in `manifest.json`","grants the registration."],preflight:["","## Preflight Override","`index.ts` registers a preflight override through `api.registerPreflight`. pm","calls it only for its declared command ownership to compute the migration/format","gate decision. Overlapping or legacy global ownership is diagnosed. Return only","the decision keys you want to","change; this starter echoes the current decision unchanged (a safe no-op) so","installing the package does not alter gate behavior. The `preflight`","capability in `manifest.json` grants the registration."],services:["","## Service Override","`index.ts` overrides the built-in `output_format` service through","`api.registerService`. The service renders a command's structured result;","returning the payload unchanged passes through to pm's default formatting.","This starter scopes itself to THIS package's own command and passes every","other command through, so it never disrupts unrelated output. The `services`","capability in `manifest.json` grants the registration."]},ES={package:["","## Lazy Activation","`manifest.json` declares `activation.commands`: the exact command paths this","package's `activate` registers. pm imports and activates the package lazily \u2014","only when an invoked command path matches one of these entries \u2014 so unrelated","commands (`pm list`, `pm search`, ...) never pay to load it. Keep this list in","sync with the registrations in `index.ts`: add an entry when you register a new","command, importer, or exporter, and remove one you drop. An omitted or stale","entry means the matching command will not dispatch from the CLI. Globally-scoped","surfaces (hooks, parser/preflight/renderer overrides, and search providers for","built-in search commands) still activate regardless of this list."],extension:["","## Lazy Activation","`manifest.json` declares `activation.commands`: the exact command paths this","extension's `activate` registers. pm imports and activates the extension lazily \u2014","only when an invoked command path matches one of these entries \u2014 so unrelated","commands never pay to load it. Keep this list in sync with the registrations in","`index.ts`: an omitted or stale entry means the matching command will not dispatch","from the CLI. Globally-scoped surfaces (hooks, parser/preflight/renderer overrides,","and search providers for built-in search commands) still activate regardless."]},RS={package:["","## Activation","This package contributes a GLOBAL custom item type and field, so `manifest.json`","intentionally declares no `activation.commands`. pm activates the package","conservatively \u2014 for every command \u2014 so the custom type is present wherever it is","used: `pm create <type>`, `pm list --type <type>`, `pm validate`, and so on.","Declaring narrow `activation.commands` here would gate activation to only those","commands and silently leave the custom type unregistered for `pm create`. If you","drop the schema registrations and keep only command/hook/search/importer surfaces,","add `activation.commands` back so pm can load the package lazily."],extension:["","## Activation","This extension contributes a GLOBAL custom item type and field, so `manifest.json`","intentionally declares no `activation.commands`. pm activates the extension","conservatively \u2014 for every command \u2014 so the custom type is present wherever it is","used: `pm create <type>`, `pm list --type <type>`, `pm validate`, and so on.","Declaring narrow `activation.commands` here would gate activation to only those","commands and silently leave the custom type unregistered for `pm create`."]},AS={package:["","## Activation","This package contributes a project profile resolved by the built-in","`pm profile list`, `pm profile show <name>`, and `pm profile apply <name>`","commands \u2014 commands the package does not own \u2014 so `manifest.json` intentionally","declares no `activation.commands`. pm activates the package conservatively (for","every command, granted by the `schema` capability) so the profile is present","whenever `pm profile` runs. Declaring narrow `activation.commands` here would","gate activation to only the listed commands and silently leave the profile","unregistered for `pm profile`."],extension:["","## Activation","This extension contributes a project profile resolved by the built-in","`pm profile list`, `pm profile show <name>`, and `pm profile apply <name>`","commands, so `manifest.json` intentionally declares no `activation.commands`. pm","activates the extension conservatively (for every command, granted by the","`schema` capability) so the profile is present whenever `pm profile` runs.","Declaring narrow `activation.commands` here would silently leave the profile","unregistered for `pm profile`."]};function zf(e,t){return e==="schema"?`- \`manifest.json\`: ${t} metadata and capabilities (no \`activation.commands\` \u2014 the custom item type activates for every command).`:e==="profile"?`- \`manifest.json\`: ${t} metadata and capabilities (no \`activation.commands\` \u2014 the contributed profile resolves through \`pm profile\` for every command).`:`- \`manifest.json\`: ${t} metadata, capabilities, and \`activation.commands\` (the command paths that lazily activate this ${t}).`}function Wf(e,t){return e==="schema"?RS[t]:e==="profile"?AS[t]:ES[t]}function IS(e){let t=e.replace(/-/g," ").trim().split(/\s+/).filter(c=>c.length>0);if(t.length===0)return"starter ping";let n=t[0].toLowerCase(),r=0;for(;t[r]?.toLowerCase()==="starter";)r+=1;let i=t[r]?.toLowerCase(),o=r>0&&(r===t.length||i!==void 0&&Lf.has(i));return`${(Lf.has(n)||o?["starter",...t]:t).join(" ")} ping`}function qf(e){let t=e,n=`${e}s`,r=e.replace(/-/g,""),i=r===t?[]:[r],o=`${e.replace(/-/g,"_")}_owner`,s="reviewing";return[` name: ${JSON.stringify(e)},`,` title: ${JSON.stringify(`${e} archetype`)},`,' summary: "Starter project profile. Replace these dimensions with your own archetype.",'," // Item types the profile upserts into the project schema when applied."," types: ["," {",` name: ${JSON.stringify(t)},`,` folder: ${JSON.stringify(n)},`,` aliases: ${JSON.stringify(i)},`,` description: ${JSON.stringify(`A ${e} work item that flows to done.`)},`," },"," ],"," // Custom statuses upserted into the project status set."," statuses: ["," {",` id: ${JSON.stringify(s)},`,' roles: ["active"],',' aliases: ["in-review"],',' description: "Work is implementation-complete and awaiting review.",'," },"," ],"," // Custom item-metadata fields the archetype tracks."," fields: ["," {",` key: ${JSON.stringify(o)},`,' type: "string",',' commands: ["create", "update", "list"],',' description: "Stakeholder accountable for the item.",'," },"," ],"," // Per-type workflow transition allow-list staged into settings."," workflows: ["," {",` type: ${JSON.stringify(t)},`," allowed_transitions: [",' ["open", "in_progress"],',` ["in_progress", ${JSON.stringify(s)}],`,` [${JSON.stringify(s)}, "in_progress"],`,` [${JSON.stringify(s)}, "closed"],`,' ["in_progress", "blocked"],',' ["blocked", "in_progress"],'," ],"," },"," ],"," // Nested-settings knobs staged when the profile is applied."," config: [",' { key: "search_provider", value: "bm25", summary: "Offline BM25 lexical search needs no embedding service." },',' { key: "search_max_results", value: "20", summary: "Result cap tuned for quick triage." },'," ],"," // Create templates staged into <pmRoot>/templates."," templates: ["," {",` name: ${JSON.stringify(e)},`," options: {",` type: ${JSON.stringify(t)},`,' priority: "2",',` tags: ${JSON.stringify(e)},`,' acceptanceCriteria: "Item delivers the stated outcome with tests and docs updated.",',' body: "## Context\\n\\n## Acceptance\\n- [ ] \\n",'," },"," },"," ],"," // Advisory package recommendations (never auto-installed)."," packages: [",' { spec: "templates", reason: "Reusable create templates for recurring item shapes." },'," ],"]}function CS(e,t,n){let r=`${e}-search`,i=`${e}-vector`,o=`${e.replace(/-/g," ")} items`,s=[" api.registerCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",'," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,",' message: "Starter extension scaffold is active.",'," }),"," });"];if(n==="commands")return s;if(n==="search")return[...s,""," // Search providers let packages customize how pm ranks and retrieves"," // project context. This starter is deterministic and dependency-free:"," // replace the scoring with your domain retrieval, embedding, or rerank"," // logic as the package grows."," api.registerSearchProvider({",` name: ${JSON.stringify(r)},`," query: async (context) => {"," const needle = context.query.toLowerCase();"," const hits = context.documents"," .filter((document) => {",' const title = String(document.metadata.title ?? "").toLowerCase();'," return title.includes(needle);"," })"," .map((document) => ({"," id: document.metadata.id,"," score: 1,",' matched_fields: ["title"],'," }));"," return { hits };"," },"," embed: async (context) => [context.input.length],"," });",""," // Vector-store adapters let packages own semantic index storage. This"," // starter returns a stable in-memory hit so generated tests can exercise"," // the adapter without external services."," api.registerVectorStoreAdapter({",` name: ${JSON.stringify(i)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),"," });"];if(n==="schema"){let a=e,c=`${e}s`,d=e.replace(/-/g,""),l=d===a?[]:[d],u=`${e.replace(/-/g,"_")}_note`,m=`${e}-0001-init`;return[...s,""," // Schema registrations let a package model its own project domain \u2014 the",' // heart of "project management = context management". Item types and fields'," // are GLOBAL contributions: built-in commands like `pm create <type>` and"," // `pm list --type <type>` must see them, so this package declares no"," // `activation.commands` and pm activates it conservatively for every command."," // The `schema` capability in manifest.json grants all three registrations."," api.registerItemFields(["," {",` name: ${JSON.stringify(u)},`,' type: "string",'," optional: true,"," },"," ]);",""," api.registerItemTypes(["," {",` name: ${JSON.stringify(a)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(c)},`,` aliases: ${JSON.stringify(l)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],"," },"," ]);",""," // Migrations let a package evolve stored items as its schema changes. pm"," // runs each migration ONCE through the preflight gate (not once per item),"," // passing a context that identifies the migration itself: `context.id` is"," // the migration id (not an item id), alongside `context.pm_root` \u2014 iterate"," // the corpus yourself from there. This starter is a deterministic no-op so"," // package tests can invoke it without touching the corpus; replace the body"," // with your real rewrite."," api.registerMigration({",` id: ${JSON.stringify(m)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),"," });"]}return n==="profile"?[...s,""," // A project profile is the broadest customization primitive pm has: one"," // declarative bundle of item types, custom statuses, fields, a per-type"," // workflow, config knobs, create templates, and package recommendations. Once"," // this package is installed the profile resolves by name through `pm profile"," // list`, `pm profile show`, and `pm profile apply`, which stages every dimension"," // idempotently like a core archetype. A profile registration is a schema+config"," // bundle, so the `schema` capability in manifest.json grants it."," api.registerProfile({",...qf(e).map(a=>` ${a}`)," });"]:n==="importers"?[...s,""," // Importers/exporters are the bridge between pm's context graph and"," // another project-management system. Keep the starter deterministic so"," // package tests can run without touching the network or filesystem; replace"," // these payloads with your adapter's real mapping as the package grows."," api.registerImporter(",` ${JSON.stringify(o)},`," async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${o} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," },"," );",""," api.registerExporter(",` ${JSON.stringify(o)},`," async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${o} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," },"," );"]:n==="renderers"?[...s,""," // Renderer overrides customize how pm serializes a command's structured",' // result for an output format ("toon" or "json"). Host-enforced ownership'," // prevents unrelated commands from reaching this callback."," // The `renderers` capability in manifest.json grants the registration.",' api.registerRenderer("toon", (context) => {',` return ${JSON.stringify(`${e}: `)} + JSON.stringify(context.result);`,` }, { commands: [${JSON.stringify(t)}] });`]:n==="parser"?[" api.registerCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",'," flags: ["," {",' long: "--shout",',' value_type: "boolean",',' description: "Deprecated alias for --upper; the parser override rewrites it.",'," },"," {",' long: "--upper",',' value_type: "boolean",',' description: "Echo the canonical flag the parser override produces.",'," },"," ],"," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,"," // Surfaces the normalized option so `--shout`/`--upper` is observable."," upper: context.options.upper === true,",' message: "Starter extension scaffold is active.",'," }),"," });",""," // Parser overrides preprocess a command's parsed options BEFORE its handler"," // runs, returning a delta \u2014 only the keys you set are merged over the parsed"," // input. This override is scoped to THIS package's own command. Here it"," // rewrites the deprecated `--shout` boolean alias to the canonical `--upper`"," // flag; replace it with your command's real normalization. The `parser`"," // capability in manifest.json grants the registration.",` api.registerParser(${JSON.stringify(t)}, (context) => {`," const options = { ...context.options };"," if (options.shout === true) {"," options.upper = true;"," }"," delete options.shout;"," return { options };"," });"]:n==="preflight"?[...s,""," // Preflight overrides adjust pm's pre-run gate decision (extension"," // migrations + item-format checks) for the commands it owns. Disjoint"," // packages compose; overlapping or legacy global ownership is diagnosed."," // Return a delta of the keys you want to change"," // (enforce_item_format_gate, run_preflight_item_format_sync,"," // run_extension_migrations, enforce_mandatory_migration_gate); returning"," // context.decision unchanged is a safe no-op so installing the package does"," // not alter gate behavior \u2014 replace it with your policy, e.g."," // `{ run_extension_migrations: false }`. The `preflight` capability in"," // manifest.json grants the registration."," api.registerPreflight({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,"," });"]:n==="services"?[...s,""," // Service overrides replace a built-in pm service. The `output_format`"," // service renders a command's structured result; returning the payload"," // unchanged passes through to pm's default formatting. This override scopes"," // itself to THIS package's own command and passes every other command"," // through, so it never disrupts unrelated output. The `services` capability"," // in manifest.json grants the registration.",' api.registerService("output_format", (context) => {',` if (context.command !== ${JSON.stringify(t)}) {`," return { handled: false };"," }",` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`," });"]:[...s,""," // after_command hooks fire once pm finishes a command, receiving the items"," // it mutated. This is the natural place to react to every change - sync to"," // an external system, emit telemetry, or refresh derived context",' // ("project management = context management"). This starter is a documented'," // no-op on the success path; replace the body with your own reaction."," api.hooks.afterCommand((context) => {"," if (!context.ok) {"," return;"," }"," // `context.affected` lists the items pm mutated (id, status,"," // changed_fields). React here, e.g.:"," // for (const item of context.affected ?? []) { /* ...item.id... */ }"," });"]}function $S(e,t,n){let r=n==="hooks",i=n==="search",o=n==="importers",s=n==="schema",a=n==="profile",c=n==="renderers",d=n==="parser",l=n==="preflight",u=n==="services",m=kS[n],p=e,f=`${e}s`,h=`${e.replace(/-/g,"_")}_note`,y=`${e}-0001-init`,w=[" assertExtensionDeactivated,"," createExtensionTestHarness,"],v=r?[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertHook throws unless an after_command hook is registered, so"," // reaching the next line already proves the hook is wired."," ext.assertHook({",' kind: "after_command",',` extensionName: ${JSON.stringify(e)},`," });"," // runHook fires the hook through pm's real runner with a synthetic"," // context and returns the warnings it produced; a clean hook returns none."," // Replace the context/assertions as your hook grows."," const warnings = await ext.runHook({",' kind: "after_command",'," context: {",` command: ${JSON.stringify(t)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ct,"});",""]:[],k=i?ja(e,t,"search",m):[],x=o?ja(e,t,"importers",m):[],E=s?[`test(${JSON.stringify(`${e} registers and runs its custom schema`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {",...Nf(Ff({extensionName:e,itemTypeName:p,itemTypeFolder:f,fieldName:h,migrationId:y,includeMigrationReplacementHint:!0})," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ct,"});",""]:[],A=a?[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {",...Nf(jf(e)," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ct,"});",""]:[],S=c?[`test(${JSON.stringify(`${e} registers and invokes its renderer override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertRendererOverride throws unless a renderer is registered for the"," // format, so reaching the next line already proves the wiring.",` const override = ext.assertRendererOverride({ name: "toon", extensionName: ${JSON.stringify(e)} });`,' assert.equal(override.format, "toon");',""," // runRendererOverride renders through pm's real runner. The override"," // customizes only THIS package's command output and returns a string the"," // host uses verbatim. Replace the assertions as it grows."," const rendered = await ext.runRendererOverride({",' format: "toon",',` command: ${JSON.stringify(t)},`," result: { ok: true },"," });"," assert.equal(rendered.overridden, true);",` assert.equal(rendered.rendered, ${JSON.stringify(`${e}: `)} + JSON.stringify({ ok: true }));`,""," // Output for any other command passes through to pm's default renderer."," const passthrough = await ext.runRendererOverride({",' format: "toon",',' command: "list",'," result: { ok: true },"," });"," assert.equal(passthrough.overridden, false);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ct,"});",""]:[],b=d?[`test(${JSON.stringify(`${e} rewrites command options via its parser override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertParserOverride throws unless a parser is registered for the"," // command, so reaching the next line already proves the wiring.",` ext.assertParserOverride({ name: ${JSON.stringify(t)}, extensionName: ${JSON.stringify(e)} });`,""," // runParserOverride runs the override through pm's real parser runner and"," // returns the rewritten context. The starter rewrites the deprecated"," // `shout` alias to the canonical `upper` flag."," const result = await ext.runParserOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: { shout: true },"," global: {},",' pm_root: "",'," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.context.options, { upper: true });",""," // End to end: feed the rewritten options into the command handler to"," // prove `pm <command> --shout` surfaces the normalized `upper` flag in"," // the result.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)}, options: result.context.options });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`," upper: true,",' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ct,"});",""]:[],D=l?[`test(${JSON.stringify(`${e} returns a preflight gate decision via its override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertPreflightOverride throws unless a preflight override is"," // registered, so reaching the next line already proves the wiring.",` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(e)} });`,""," // runPreflightOverride runs the override through pm's real runner with a"," // synthetic gate decision. The starter echoes the decision unchanged;"," // replace the values/assertions with your real policy."," const decision = {"," enforce_item_format_gate: true,"," run_preflight_item_format_sync: false,"," run_extension_migrations: true,"," enforce_mandatory_migration_gate: false,"," };"," const result = await ext.runPreflightOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: {},"," global: {},",' pm_root: "",'," decision,"," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.decision, decision);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ct,"});",""]:[],j=u?[`test(${JSON.stringify(`${e} customizes command output via its service override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertServiceOverride throws unless a service override is registered"," // for the service, so reaching the next line proves the wiring.",` ext.assertServiceOverride({ name: "output_format", extensionName: ${JSON.stringify(e)} });`,""," // runServiceOverride runs the override through pm's real service runner."," // The override customizes only THIS package's command output (handled),"," // passing every other command through (not handled)."," const handled = await ext.runServiceOverride({",' service: "output_format",',` command: ${JSON.stringify(t)},`," payload: { ok: true },"," });"," assert.equal(handled.handled, true);",` assert.deepEqual(handled.result, { rendered_by: ${JSON.stringify(e)}, payload: { ok: true } });`,""," // Output for any other command passes through to pm's default formatter."," const passthrough = await ext.runServiceOverride({",' service: "output_format",',' command: "list",'," payload: { ok: true },"," });"," assert.equal(passthrough.handled, false);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ct,"});",""]:[];return['import assert from "node:assert/strict";','import { test } from "node:test";',"import {",...w,'} from "@unbrained/pm-cli/sdk/testing";',...i?['import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";']:[],'import extension from "./index.ts";',"",...Mf,`test(${JSON.stringify(`${e} registers its starter command`)}, async () => {`," // `capabilities` mirrors manifest.json so the in-memory activation grants"," // the capabilities the entrypoint relies on."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertCommandContract is bound to the right activation registry and throws"," // if the command is not registered, so reaching here already proves the"," // wiring; assert on the returned definition to inspect metadata."," const registered = ext.assertCommandContract({",` name: ${JSON.stringify(t)},`,` extensionName: ${JSON.stringify(e)},`," });",' assert.equal(typeof registered.command.description, "string");',""," // runCommand invokes the handler through pm's real dispatch engine, so this"," // asserts behavior - not just that the command is wired. Replace these"," // assertions as you flesh out your command."," const invocation = await ext.runCommand({",` command: ${JSON.stringify(t)},`," });"," assert.equal(invocation.handled, true);"," // The handler result is typed `unknown`, so deep-equality on the whole"," // structured payload keeps the assertion type-safe without a cast."," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`,...d?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ct,"});","",...v,...k,...x,...E,...A,...S,...b,...D,...j,`test(${JSON.stringify(`${e} tears down cleanly via deactivate`)}, async () => {`," // createExtensionTestHarness binds teardown to the same name/layer used for"," // activation, so this proves your `deactivate` hook runs without throwing."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," const teardown = await ext.deactivate();"," // assertExtensionDeactivated throws unless exactly one extension tore down"," // with no failures, so reaching the next line already proves teardown ran."," assertExtensionDeactivated(teardown);"," assert.equal(teardown.deactivated, 1);","});",""].join(`
|
|
34
|
+
`)}function TS(e,t,n){if(n==="schema"||n==="profile")return[];if(n==="importers"){let r=`${e.replace(/-/g," ")} items`;return[t,`${r} import`,`${r} export`]}return[t]}var OS={commands:"starter command",hooks:"starter command and after_command hook",search:"starter command, search provider, and vector-store adapter",importers:"starter command, importer, and exporter",schema:"starter command, custom item type, item field, and migration",profile:"starter command and project profile",renderers:"starter command and toon renderer override",parser:"starter command and parser override",preflight:"starter command and preflight override",services:"starter command and output_format service override"},PS={commands:"`commands`",hooks:"`commands` and `hooks.afterCommand`",search:"`commands`, `searchProviders`, and `vectorStoreAdapters`",importers:"`commands`, `importers`, and `exporters`",schema:"`commands`, `itemTypes`, `itemFields`, and `migrations`",profile:"`commands` and `profiles`",renderers:"`commands` and `renderers`",parser:"`commands` and `parsers`",preflight:"`commands` and `preflights`",services:"`commands` and `services`"};function LS(e,t,n){let r=n==="parser";return["// The starter command, authored with the `defineCommand` builder so its literal","// name is preserved and the handler `context` is inferred. Exporting it lets you","// unit-test the definition in isolation, apart from the blueprint.","export const pingCommand = defineCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",',...r?[" flags: ["," {",' long: "--shout",',' value_type: "boolean",',' description: "Deprecated alias for --upper; the parser override rewrites it.",'," },"," {",' long: "--upper",',' value_type: "boolean",',' description: "Echo the canonical flag the parser override produces.",'," },"," ],"]:[]," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,",...r?[" upper: context.options.upper === true,"]:[],' message: "Starter extension scaffold is active.",'," }),","});"]}function NS(e,t,n){let r=[],i=[...LS(e,t,n)],o=[" commands: [pingCommand],"],s=`${e}-search`,a=`${e}-vector`,c=`${e.replace(/-/g," ")} items`,d=e,l=`${e}s`,u=e.replace(/-/g,""),m=u===d?[]:[u],p=`${e.replace(/-/g,"_")}_note`,f=`${e}-0001-init`;switch(n){case"commands":break;case"hooks":r.push("defineAfterCommandHook"),i.push("","// after_command hooks fire once pm finishes a command, receiving the items it","// mutated. React here - sync to an external system, emit telemetry, or refresh",'// derived context ("project management = context management"). This starter is a',"// documented no-op on the success path; replace the body with your own reaction.","export const afterCommandHook = defineAfterCommandHook((context) => {"," if (!context.ok) {"," return;"," }"," // `context.affected` lists the items pm mutated (id, status, changed_fields):"," // for (const item of context.affected ?? []) { /* ...item.id... */ }","});"),o.push(" hooks: { afterCommand: [afterCommandHook] },");break;case"search":r.push("defineSearchProvider","defineVectorStoreAdapter"),i.push("","// Search providers let packages customize how pm ranks and retrieves project","// context. This starter is deterministic and dependency-free: replace the scoring","// with your domain retrieval, embedding, or rerank logic as the package grows.","export const searchProvider = defineSearchProvider({",` name: ${JSON.stringify(s)},`," query: async (context) => {"," const needle = context.query.toLowerCase();"," const hits = context.documents"," .filter((document) => {",' const title = String(document.metadata.title ?? "").toLowerCase();'," return title.includes(needle);"," })"," .map((document) => ({"," id: document.metadata.id,"," score: 1,",' matched_fields: ["title"],'," }));"," return { hits };"," },"," embed: async (context) => [context.input.length],","});","","// Vector-store adapters let packages own semantic index storage. This starter","// returns a stable in-memory hit so generated tests can exercise the adapter","// without external services.","export const vectorStoreAdapter = defineVectorStoreAdapter({",` name: ${JSON.stringify(a)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),","});"),o.push(" searchProviders: [searchProvider],"," vectorStoreAdapters: [vectorStoreAdapter],");break;case"importers":r.push("defineExporter","defineImporter"),i.push("","// Importers/exporters are the bridge between pm's context graph and another","// project-management system. Keep the starter deterministic so package tests can","// run without touching the network or filesystem; replace these payloads with","// your adapter's real mapping as the package grows.","export const importer = defineImporter(async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,","}));","","export const exporter = defineExporter(async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,","}));"),o.push(" importers: ["," {",` name: ${JSON.stringify(c)},`," importer,"," options: {",` action: ${JSON.stringify(`${c} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," },"," },"," ],"," exporters: ["," {",` name: ${JSON.stringify(c)},`," exporter,"," options: {",` action: ${JSON.stringify(`${c} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," },"," },"," ],");break;case"schema":r.push("defineItemField","defineItemType","defineMigration"),i.push("","// Schema registrations let a package model its own project domain - the heart of",'// "project management = context management". Item types and fields are GLOBAL',"// contributions, so this package declares no `activation.commands` and pm","// activates it conservatively for every command.","export const noteField = defineItemField({",` name: ${JSON.stringify(p)},`,' type: "string",'," optional: true,","});","","export const itemType = defineItemType({",` name: ${JSON.stringify(d)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(l)},`,` aliases: ${JSON.stringify(m)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],","});","","// Migrations let a package evolve stored items as its schema changes. pm runs each","// migration ONCE through the preflight gate (not once per item), passing a context","// that identifies the migration itself: `context.id` is the migration id (not an","// item id), alongside `context.pm_root`. This starter is a deterministic no-op so","// package tests can invoke it without touching the corpus; replace the body with","// your real rewrite.","export const initMigration = defineMigration({",` id: ${JSON.stringify(f)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),o.push(" itemTypes: [itemType],"," itemFields: [noteField],"," migrations: [initMigration],");break;case"profile":r.push("defineProjectProfile"),i.push("","// A project profile is the broadest customization primitive pm has: one","// declarative bundle of item types, custom statuses, fields, a per-type workflow,","// config knobs, create templates, and package recommendations. Once installed it","// resolves by name through `pm profile list/show/apply`, which stages every","// dimension idempotently like a core archetype. A profile registration is a","// schema+config bundle, so the `schema` capability grants it.","export const starterProfile = defineProjectProfile({",...qf(e),"});"),o.push(" profiles: [starterProfile],");break;case"renderers":r.push("defineRendererOverride"),i.push("","// Host-enforced command ownership prevents unrelated output from reaching","// this renderer callback; return a string to take over serialization.","export const toonRenderer = defineRendererOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => {",` return ${JSON.stringify(`${e}: `)} + JSON.stringify(context.result);`," },","});"),o.push(" renderers: { toon: toonRenderer },");break;case"parser":r.push("defineParserOverride"),i.push("","// Parser overrides preprocess a command's parsed options BEFORE its handler runs,","// returning a delta - only the keys you set are merged over the parsed input. This","// override is scoped to THIS package's own command; here it rewrites the deprecated","// `--shout` boolean alias to the canonical `--upper` flag.","export const pingParser = defineParserOverride((context) => {"," const options = { ...context.options };"," if (options.shout === true) {"," options.upper = true;"," }"," delete options.shout;"," return { options };","});"),o.push(` parsers: { ${JSON.stringify(t)}: pingParser },`);break;case"preflight":r.push("definePreflightOverride"),i.push("","// Preflight overrides adjust pm's pre-run gate decision (extension migrations +","// item-format checks) for the commands it owns. Scoped ownership composes with","// other packages; overlapping or legacy global ownership is diagnosed.","// Return a delta of the keys you want to change (enforce_item_format_gate,","// run_preflight_item_format_sync, run_extension_migrations,","// enforce_mandatory_migration_gate); returning context.decision unchanged is a","// safe no-op - replace it with your policy, e.g. { run_extension_migrations: false }.","export const preflightOverride = definePreflightOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,","});"),o.push(" preflights: [preflightOverride],");break;case"services":r.push("defineServiceOverride"),i.push("","// Service overrides replace a built-in pm service. The `output_format` service","// renders a command's structured result; returning the payload unchanged passes","// through to pm's default formatting. This override scopes itself to THIS","// package's own command and passes every other command through.","export const outputService = defineServiceOverride((context) => {",` if (context.command !== ${JSON.stringify(t)}) {`," return { handled: false };"," }",` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`,"});"),o.push(" services: { output_format: outputService },");break}return{builderImports:r,definitions:i,blueprintFields:o}}function DS(e,t,n){let r=NS(e,t,n);return[`import { ${["composeExtension","defineCommand","defineExtensionBlueprint",...r.builderImports].sort((o,s)=>o.localeCompare(s)).join(", ")} } from "@unbrained/pm-cli/sdk";`,"",...r.definitions,"","// Declarative authoring: describe WHAT the package registers as a blueprint and","// let `composeExtension` generate the `activate` that wires every surface in order,","// instead of hand-writing each `api.register*` call. `defineExtensionBlueprint`","// contract-checks the blueprint where it is authored. Keep `manifest.json`'s","// `capabilities` equal to the set this blueprint derives.","export const blueprint = defineExtensionBlueprint({",...r.blueprintFields," // `deactivate` is the teardown counterpart to the generated `activate`: pm runs"," // it on host shutdown/reload to release anything the package opened (timers,"," // connections, caches). This starter holds none, so it stays a no-op."," deactivate: () => {},","});","","// `composeExtension(blueprint)` is the package's default export \u2014 the runtime","// `ExtensionModule` pm loads. Guard the blueprint with `assertExtensionPreflight`","// in index.test.ts before publishing.","export default composeExtension(blueprint);",""].join(`
|
|
35
|
+
`)}function ja(e,t,n,r){if(n==="commands")return[];let i=`${e}-search`,o=`${e}-vector`,s=`${e.replace(/-/g," ")} items`,a=e,c=`${e}s`,d=`${e.replace(/-/g,"_")}_note`,l=`${e}-0001-init`,u=[" const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${r},`," });"],m=p=>[...u," let deactivated = false;"," try {",...p.map(f=>f===""?f:` ${f}`)," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ct];switch(n){case"hooks":return[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`,...m([" // assertHook throws unless an after_command hook is registered, so reaching the"," // next line already proves the hook is wired.",` ext.assertHook({ kind: "after_command", extensionName: ${JSON.stringify(e)} });`," // runHook fires the hook through pm's real runner with a synthetic context and"," // returns the warnings it produced; a clean hook returns none."," const warnings = await ext.runHook({",' kind: "after_command",'," context: {",` command: ${JSON.stringify(t)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"]),"});",""];case"search":return[`test(${JSON.stringify(`${e} registers and invokes search primitives`)}, async () => {`,...m([` ext.assertSearchProvider({ name: ${JSON.stringify(i)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertVectorStoreAdapter({ name: ${JSON.stringify(o)}, extensionName: ${JSON.stringify(e)} });`,""," // The starter provider reads only document title/id, so `settings` is a minimal"," // typed stub and `documents` carry just the fields it inspects."," const settings = {"," testing: {"," record_results_to_items: false,"," allow_untrusted_linked_tests: false,"," },"," } as PmSettings;"," const query = await ext.runSearchProvider({",` provider: ${JSON.stringify(i)},`,' operation: "query",'," context: {",' query: "sync",',' mode: "semantic",',' tokens: ["sync"],'," options: {},"," settings,"," documents: [",' { metadata: { id: "pm-1", title: "Sync external context" }, body: "" },',' { metadata: { id: "pm-2", title: "Unrelated task" }, body: "" },'," ] as ItemDocument[],"," },"," });",' assert.deepEqual(query, { hits: [{ id: "pm-1", score: 1, matched_fields: ["title"] }] });',""," const embedding = await ext.runSearchProvider({",` provider: ${JSON.stringify(i)},`,' operation: "embed",',' context: { input: "abc", settings, model: "starter-model" },'," });"," assert.deepEqual(embedding, [3]);",""," const vectorHits = await ext.runVectorStoreAdapter({",` adapter: ${JSON.stringify(o)},`,' operation: "query",'," context: { vector: [0.1, 0.2], limit: 2, settings },"," });",' assert.deepEqual(vectorHits, [{ id: "starter-vector-hit", score: 2 }]);']),"});",""];case"importers":return[`test(${JSON.stringify(`${e} registers and invokes import/export primitives`)}, async () => {`,...m([` ext.assertImporter({ name: ${JSON.stringify(s)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertExporter({ name: ${JSON.stringify(s)}, extensionName: ${JSON.stringify(e)} });`,""," const imported = await ext.runImporter({",` importer: ${JSON.stringify(s)},`,' options: { source: "tickets" },',' args: ["batch-1"],'," });"," assert.equal(imported.handled, true);",' assert.deepEqual(imported.result, { imported: 1, source: "tickets", args: ["batch-1"] });',""," const exported = await ext.runExporter({",` exporter: ${JSON.stringify(s)},`,' options: { destination: "archive" },',' args: ["done"],'," });"," assert.equal(exported.handled, true);",' assert.deepEqual(exported.result, { exported: true, destination: "archive", args: ["done"] });']),"});",""];case"schema":return[`test(${JSON.stringify(`${e} registers and runs its custom schema`)}, async () => {`,...m(Ff({extensionName:e,itemTypeName:a,itemTypeFolder:c,fieldName:d,migrationId:l})),"});",""];case"profile":return[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`,...m(jf(e)),"});",""];case"renderers":return[`test(${JSON.stringify(`${e} registers and invokes its renderer override`)}, async () => {`,...m([" // assertRendererOverride throws unless a renderer is registered for the format,"," // so reaching the next line already proves the wiring.",` const override = ext.assertRendererOverride({ name: "toon", extensionName: ${JSON.stringify(e)} });`,' assert.equal(override.format, "toon");',""," // runRendererOverride renders through pm's real runner. The override customizes"," // only THIS package's command output and returns a string the host uses verbatim."," const rendered = await ext.runRendererOverride({",' format: "toon",',` command: ${JSON.stringify(t)},`," result: { ok: true },"," });"," assert.equal(rendered.overridden, true);"," assert.equal(rendered.rendered, JSON.stringify({ ok: true }));",""," // Output for any other command passes through to pm's default renderer."," const passthrough = await ext.runRendererOverride({",' format: "toon",',' command: "list",'," result: { ok: true },"," });"," assert.equal(passthrough.overridden, false);"]),"});",""];case"parser":return[`test(${JSON.stringify(`${e} rewrites command options via its parser override`)}, async () => {`,...m([" // assertParserOverride throws unless a parser is registered for the command, so"," // reaching the next line already proves the wiring.",` ext.assertParserOverride({ name: ${JSON.stringify(t)}, extensionName: ${JSON.stringify(e)} });`,""," // runParserOverride runs the override through pm's real parser runner and returns"," // the rewritten context. The starter rewrites the deprecated `shout` alias to the"," // canonical `upper` flag."," const result = await ext.runParserOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: { shout: true },"," global: {},",' pm_root: "",'," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.context.options, { upper: true });",""," // End to end: feed the rewritten options into the command handler to prove"," // `pm <command> --shout` surfaces the normalized `upper` flag in the result.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)}, options: result.context.options });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`," upper: true,",' message: "Starter extension scaffold is active.",'," });"]),"});",""];case"preflight":return[`test(${JSON.stringify(`${e} returns a preflight gate decision via its override`)}, async () => {`,...m([" // assertPreflightOverride throws unless a preflight override is registered, so"," // reaching the next line already proves the wiring.",` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(e)} });`,""," // runPreflightOverride runs the override through pm's real runner with a synthetic"," // gate decision. The starter echoes the decision unchanged; replace the"," // values/assertions with your real policy."," const decision = {"," enforce_item_format_gate: true,"," run_preflight_item_format_sync: false,"," run_extension_migrations: true,"," enforce_mandatory_migration_gate: false,"," };"," const result = await ext.runPreflightOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: {},"," global: {},",' pm_root: "",'," decision,"," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.decision, decision);"]),"});",""];case"services":return[`test(${JSON.stringify(`${e} customizes command output via its service override`)}, async () => {`,...m([" // assertServiceOverride throws unless a service override is registered for the"," // service, so reaching the next line proves the wiring.",` ext.assertServiceOverride({ name: "output_format", extensionName: ${JSON.stringify(e)} });`,""," // runServiceOverride runs the override through pm's real service runner. The"," // override customizes only THIS package's command output (handled), passing every"," // other command through (not handled)."," const handled = await ext.runServiceOverride({",' service: "output_format",',` command: ${JSON.stringify(t)},`," payload: { ok: true },"," });"," assert.equal(handled.handled, true);",` assert.deepEqual(handled.result, { rendered_by: ${JSON.stringify(e)}, payload: { ok: true } });`,""," // Output for any other command passes through to pm's default formatter."," const passthrough = await ext.runServiceOverride({",' service: "output_format",',' command: "list",'," payload: { ok: true },"," });"," assert.equal(passthrough.handled, false);"]),"});",""]}}function MS(e,t,n){let r=n==="parser",i=JSON.stringify([...Hf[n]].sort());return['import assert from "node:assert/strict";','import { test } from "node:test";','import { assertExtensionDeactivated, assertExtensionManifestMatchesBlueprint, assertExtensionPreflight, createExtensionTestHarness } from "@unbrained/pm-cli/sdk/testing";',...n==="search"?['import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";']:[],'import extension, { blueprint } from "./index.ts";','import manifest from "./manifest.json" with { type: "json" };',"",...Mf,`test(${JSON.stringify(`${e} passes author-time preflight`)}, () => {`," // assertExtensionPreflight is the author-time capstone: it lints the blueprint,"," // synthesizes the least-privilege manifest from `identity`, and checks the version"," // bounds against `target` in one call, throwing on any blocking finding. It returns"," // the full report so you can inspect the derived data."," const report = assertExtensionPreflight(blueprint, {"," identity: {",` name: ${JSON.stringify(e)},`,' version: "0.1.0",',' entry: "./index.ts",'," priority: 0,",` pm_min_version: ${JSON.stringify(tn)},`," },",` target: { pmVersion: ${JSON.stringify(tn)} },`," });"," // Fail the starter suite whenever the checked-in manifest drifts from the"," // capabilities derived from the blueprint."," assertExtensionManifestMatchesBlueprint(manifest, blueprint);"," // The capability set is DERIVED from the blueprint, never hand-synced. Keep"," // manifest.json's `capabilities` equal to this list (set match, sorted).",` assert.deepEqual(report.capabilities, ${i});`,` assert.deepEqual(report.manifest?.capabilities, ${i});`,"});","",`test(${JSON.stringify(`${e} registers and runs its starter command`)}, async () => {`," // createExtensionTestHarness activates the composed module once and binds the"," // assert*/run*/deactivate helpers to the right activation sub-registry, so you"," // never thread activation.registrations vs activation.commands by hand."," // `capabilities` mirrors manifest.json so the in-memory activation grants what the"," // blueprint needs."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${i},`," });"," let deactivated = false;"," try {"," // assertCommandContract throws unless the command is registered, so reaching"," // the next line already proves the wiring; assert on the returned definition"," // to demonstrate inspecting registered metadata.",` const registered = ext.assertCommandContract({ name: ${JSON.stringify(t)} });`,' assert.equal(typeof registered.command.description, "string");',""," // runCommand invokes the handler through pm's real dispatch engine, so this"," // asserts behavior - not just that the command is wired. Replace these"," // assertions as you flesh out your command.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)} });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`,...r?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," // deactivate runs pm's real teardown engine over the module; exactly one"," // extension tears down with no failures."," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...ct,"});","",...ja(e,t,n,i)].join(`
|
|
36
|
+
`)}function FS(e,t,n){let r=zf(n,"package"),i=Wf(n,"package");return[`# ${e}`,"","Generated by `pm package init --declarative`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",r,`- \`index.ts\`: the TypeScript manifest entry \u2014 a \`defineExtensionBlueprint\` blueprint (${OS[n]}) composed into the runtime module by \`composeExtension\`, plus a \`deactivate\` teardown stub.`,"- `index.test.ts`: sample `node:test` suite covering author-time preflight (`assertExtensionPreflight`) and runtime surface invocation/teardown via `createExtensionTestHarness`.",Uf,"- `.gitignore`: ignores `node_modules/`, logs, and the TypeScript build cache.","","## Quick Start","This package is authored AND loaded as TypeScript: the manifest `entry` is","`./index.ts` and pm imports it directly via Node's native type stripping","(Node >=22.18), so there is no build step \u2014 install and run:","```bash","npm install","pm install --project <package-path>",`pm ${t}`,"pm package doctor --project --detail summary","```","","## Declarative Authoring","`index.ts` uses the SDK's declarative authoring loop instead of an imperative","`activate` body. You describe WHAT the package registers as an","`ExtensionBlueprint` and `composeExtension` generates the `activate` that wires","every surface in order:","- The `define*` builders author each surface with literal-type preservation and"," contextual handler inference (`defineCommand`, `defineSearchProvider`,"," `defineItemType`, `defineParserOverride`, ...).","- `defineExtensionBlueprint({ ... })` collects the definitions into the blueprint;",` this starter populates ${PS[n]}. Add more`," fields as the package grows.","- `composeExtension(blueprint)` is the default export \u2014 the runtime module pm"," loads. Its generated `activate` requires exactly the capabilities the blueprint"," derives, so `manifest.json`'s `capabilities` never drift.","","## Validate the Package","`npm install` pulls the peer SDK and TypeScript. `npm test` is the default","validation gate: it type-checks the package, then runs the colocated sample:","```bash","npm install","npm test","```","`index.test.ts` exercises both authoring capstones: `assertExtensionPreflight`","(the author-time lint + manifest synthesis + version-compatibility check over the","exported `blueprint`) and `createExtensionTestHarness` (the runtime fixture whose","`assert*`/`run*`/`deactivate` methods bind to the right activation sub-registry).","`npm run typecheck` is available when you only want the SDK contract check.","`npm run test:runtime` runs just `node --test`, which strips types on load and","executes `index.test.ts` directly against the `@unbrained/pm-cli/sdk/testing`","helpers - no compile step and no extra test runner required.",...i,"","## Compatibility Bounds","`manifest.json` cannot hold comments, so the version-compatibility fields are documented here:",`- \`manifest_version\` (integer): manifest schema generation. Leave at \`${Fa}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${tn}\`. The loader blocks the package on older CLIs.`,"- `pm_max_version` (string, optional): highest pm CLI version that may load this package. Add it to block CLIs that are newer than the version you have validated against. The loader blocks the package when the CLI exceeds this bound.","","## Policy Metadata",'The starter command is pure compute, so `manifest.json` declares `trusted: true`, `sandbox_profile: "strict"`, and all six permission keys as `false`. Keep that least-privilege shape for pure packages; relax only the specific permission your package actually needs and verify with `pm package doctor --project --detail deep --trace`.',"","## Notes","- Author in `index.ts`; pm loads it directly (no build), so edits take effect on the next install/reload \u2014 there is no `.js` to regenerate.","- Move larger runtimes into sibling or subdirectory `*.ts` modules and import them with their real `.ts` extension; `tsconfig.json` type-checks every `*.ts` in the package (recursively).","- Use `@unbrained/pm-cli/sdk` as the public SDK import for richer package runtimes.",""].join(`
|
|
37
|
+
`)}function jS(e){let t=e,n=e.replace(/-/g,"");return{searchProviderName:`${e}-search`,vectorAdapterName:`${e}-vector`,adapterName:`${e.replace(/-/g," ")} items`,itemTypeName:t,itemTypeFolder:`${e}s`,itemTypeAliases:n===t?[]:[n],fieldName:`${e.replace(/-/g,"_")}_note`,migrationId:`${e}-0001-init`}}function HS(e){return["defineCommand",...e==="hooks"?["defineAfterCommandHook"]:[],...e==="search"?["defineSearchProvider","defineVectorStoreAdapter"]:[],...e==="importers"?["defineImporter","defineExporter"]:[],...e==="schema"?["defineItemType","defineItemField","defineMigration"]:[],...e==="profile"?["defineProjectProfile"]:[],...e==="renderers"?["defineRendererOverride"]:[],...e==="parser"?["defineParserOverride"]:[],...e==="preflight"?["definePreflightOverride"]:[],...e==="services"?["defineServiceOverride"]:[]].join(", ")}function US(e,t,n,r){let i=["export const pingCommand = defineCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",',...n==="parser"?[" flags: [",' { long: "--shout", value_type: "boolean", description: "Deprecated alias for --upper." },',' { long: "--upper", value_type: "boolean", description: "Canonical flag the parser produces." },'," ],"," run: (context) => ({ ok: true, command: context.command, upper: context.options.upper === true }),"]:[" run: (context) => ({ ok: true, command: context.command }),"],"});"];return n==="hooks"&&i.push("","export const afterCommandHook = defineAfterCommandHook((context) => {"," if (!context.ok) return;"," // React to context.affected here as your package grows.","});"),n==="search"&&i.push("","export const searchProvider = defineSearchProvider({",` name: ${JSON.stringify(r.searchProviderName)},`," query: async (context) => ({"," hits: context.documents",' .filter((document) => String(document.metadata.title ?? "").toLowerCase().includes(context.query.toLowerCase()))',' .map((document) => ({ id: document.metadata.id, score: 1, matched_fields: ["title"] })),'," }),"," embed: async (context) => [context.input.length],","});","","export const vectorStoreAdapter = defineVectorStoreAdapter({",` name: ${JSON.stringify(r.vectorAdapterName)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),","});"),n==="importers"&&i.push("","export const importer = defineImporter(async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,","}));","","export const exporter = defineExporter(async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,","}));"),n==="schema"&&i.push("",`export const noteField = defineItemField({ name: ${JSON.stringify(r.fieldName)}, type: "string", optional: true });`,"","export const itemType = defineItemType({",` name: ${JSON.stringify(r.itemTypeName)},`,` folder: ${JSON.stringify(r.itemTypeFolder)},`,` aliases: ${JSON.stringify(r.itemTypeAliases)},`," required_create_fields: [],","});","","export const initMigration = defineMigration({",` id: ${JSON.stringify(r.migrationId)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),n==="profile"&&i.push("","export const starterProfile = defineProjectProfile({",` name: ${JSON.stringify(e)},`,` title: ${JSON.stringify(`${e} archetype`)},`,' summary: "Starter project profile. Replace these dimensions with your own archetype.",'," types: [",` { name: ${JSON.stringify(r.itemTypeName)}, folder: ${JSON.stringify(r.itemTypeFolder)} },`," ],"," // ...plus statuses, fields, workflows, config, templates, and packages.","});"),n==="renderers"&&i.push("","export const toonRenderer = defineRendererOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => JSON.stringify(context.result),","});"),n==="parser"&&i.push("","export const pingParser = defineParserOverride((context) => {"," const options = { ...context.options };"," if (options.shout === true) options.upper = true;"," delete options.shout;"," return { options };","});"),n==="preflight"&&i.push("","// Return a delta of the gate-decision keys you want to change; returning","// context.decision unchanged is a safe no-op (e.g. { run_extension_migrations: false }).","export const preflightOverride = definePreflightOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,","});"),n==="services"&&i.push("","export const outputService = defineServiceOverride((context) => {",` if (context.command !== ${JSON.stringify(t)}) return { handled: false };`,` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`,"});"),i}function zS(e,t,n){let r=[];return t==="renderers"&&r.push(' api.registerRenderer("toon", toonRenderer.run, toonRenderer);'),t==="parser"&&r.push(` api.registerParser(${JSON.stringify(e)}, pingParser);`),t==="preflight"&&r.push(" api.registerPreflight(preflightOverride);"),t==="services"&&r.push(' api.registerService("output_format", outputService);'),t==="hooks"&&r.push(" api.hooks.afterCommand(afterCommandHook);"),t==="search"&&r.push(" api.registerSearchProvider(searchProvider);"," api.registerVectorStoreAdapter(vectorStoreAdapter);"),t==="schema"&&r.push(" api.registerItemFields([noteField]);"," api.registerItemTypes([itemType]);"," api.registerMigration(initMigration);"),t==="profile"&&r.push(" api.registerProfile(starterProfile);"),t==="importers"&&r.push(` api.registerImporter(${JSON.stringify(n.adapterName)}, importer, {`,` action: ${JSON.stringify(`${n.adapterName} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," });",` api.registerExporter(${JSON.stringify(n.adapterName)}, exporter, {`,` action: ${JSON.stringify(`${n.adapterName} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," });"),r}function WS(e,t,n,r="commands",i=!1){let o=`pm-${e}`,s=Hf[r],a=TS(e,t,r),c=`${JSON.stringify({name:e,version:"0.1.0",entry:"./index.ts",manifest_version:Fa,pm_min_version:tn,trusted:!0,sandbox_profile:"strict",permissions:{...gS},capabilities:s,...a.length>0?{activation:{commands:a}}:{}},null,2)}
|
|
38
|
+
`,d=['import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"","export function activate(api: ExtensionApi): void {",...CS(e,t,r),"}","","// `deactivate` is the teardown counterpart to `activate`: pm runs it on host","// shutdown/reload (e.g. the MCP server between requests) to release anything","// `activate` opened - timers, connections, caches. This starter holds no such","// resources, so it stays a documented no-op; add cleanup here as you grow.","export function deactivate(): void {}","","export default {"," activate,"," deactivate,","};",""].join(`
|
|
39
|
+
`),l=`${JSON.stringify(vS,null,2)}
|
|
40
|
+
`,u=bS[r],m=zf(r,"package"),p=`${JSON.stringify({name:o,version:"0.1.0",private:!0,type:"module",keywords:["pm-package"],engines:{node:_S},scripts:{typecheck:"tsc --noEmit","test:runtime":"node --test",test:"npm run typecheck && npm run test:runtime"},peerDependencies:{"@unbrained/pm-cli":`>=${tn}`},devDependencies:{"@types/node":wS,typescript:yS},pm:{aliases:[e],extensions:["."],docs:["README.md"],examples:["README.md"],catalog:{display_name:e,category:"workflow",summary:"Starter pm package scaffold.",tags:["starter"]}}},null,2)}
|
|
41
|
+
`,f=$S(e,t,r),h=xS[r],y=["node_modules/","*.log","*.tsbuildinfo",""].join(`
|
|
42
|
+
`),w=jS(e),k=["```ts",`import { ${HS(r)} } from "@unbrained/pm-cli/sdk";`,'import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"",...US(e,t,r,w),"","export function activate(api: ExtensionApi): void {"," api.registerCommand(pingCommand);",...zS(t,r,w),"}","","export function deactivate(): void {}","","export default { activate, deactivate };","```"],x=[`# ${o}`,"","Generated by `pm package init` or `pm extension init`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",m,u,h,Uf,"- `.gitignore`: ignores `node_modules/`, logs, and the TypeScript build cache.","","## Quick Start","This package is authored AND loaded as TypeScript: the manifest `entry` is","`./index.ts` and pm imports it directly via Node's native type stripping","(Node >=22.18), so there is no build step \u2014 install and run:","```bash","npm install","pm install --project <package-path>",`pm ${t}`,"pm package doctor --project --detail summary","```","","## Validate the Package","`npm install` pulls the peer SDK and TypeScript. `npm test` is the default","validation gate: it type-checks the package, then runs the colocated sample:","```bash","npm install","npm test","```","`npm run typecheck` is available when you only want the SDK contract check.","`npm run test:runtime` runs just `node --test`, which strips types on load and","executes `index.test.ts` directly against the `@unbrained/pm-cli/sdk/testing`","helpers - no compile step and no extra test runner required.","","## Authoring With define* Builders","`index.ts` is authored fully in TypeScript so every registration is checked","against the SDK contracts at author time. Use the public SDK authoring","builders for exported definitions you want literal-type preservation,","contextual handler inference, and direct unit tests for:",...k,"The builders return their argument unchanged; runtime validation still lives","in `api.register*`, and behavior validation lives in `sdk/testing`.",...SS[r],...Wf(r,"package"),"","## Compatibility Bounds",`- \`peerDependencies["@unbrained/pm-cli"]\` uses the stable range \`>=${tn}\`. Keep a normal stable range instead of pinning a date ordinal: SemVer excludes prerelease ordinals such as \`2026.7.24-3\`, while daily stable releases continue to satisfy the range.`,"`manifest.json` cannot hold comments, so the version-compatibility fields are documented here:",`- \`manifest_version\` (integer): manifest schema generation. Leave at \`${Fa}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${tn}\`. The loader blocks the package on older CLIs.`,"- `pm_max_version` (string, optional): highest pm CLI version that may load this package. Add it to block CLIs that are newer than the version you have validated against. The loader blocks the package when the CLI exceeds this bound.","","## Policy Metadata",'The starter command is pure compute, so `manifest.json` declares `trusted: true`, `sandbox_profile: "strict"`, and all six permission keys as `false`. Keep that least-privilege shape for pure packages; relax only the specific permission your package actually needs and verify with `pm package doctor --project --detail deep --trace`.',"","## Notes","- Author in `index.ts`; pm loads it directly (no build), so edits take effect on the next install/reload \u2014 there is no `.js` to regenerate.","- Move larger runtimes into sibling or subdirectory `*.ts` modules and import them with their real `.ts` extension; `tsconfig.json` type-checks every `*.ts` in the package (recursively).","- Add capabilities to the extension manifest only when the entrypoint uses the matching SDK API.","- Use `@unbrained/pm-cli/sdk` as the public SDK import for richer package runtimes.",""].join(`
|
|
43
|
+
`);return{"package.json":p,"manifest.json":c,"index.ts":i?DS(e,t,r):d,"index.test.ts":i?MS(e,t,r):f,"tsconfig.json":l,".gitignore":y,"README.md":i?FS(o,t,r):x}}async function Gf(e,t="extension",n="commands",r=!1){let i=n.trim().toLowerCase();if(!Df.includes(i))throw new _(`Unknown scaffold capability "${n}". Supported capabilities: ${Df.join(", ")}.`,g.USAGE);let o=i;if(r&&t!=="package")throw new _("--declarative scaffolds a package-mode blueprint starter (composeExtension is a runtime SDK import). Use `pm package init`, not `pm extension init`.",g.USAGE);let s=r?"declarative":"imperative",a=e.trim(),c=jr.resolve(process.cwd(),a),d=co(jr.basename(c)).replace(/^(?:pm-)+/u,""),l=IS(d),u=WS(d,l,t,o,r),m=!1;if(await P(c)){if(!(await Fr.stat(c)).isDirectory())throw new _(`Scaffold target "${c}" exists and is not a directory.`,g.CONFLICT)}else await Fr.mkdir(c,{recursive:!0}),m=!0;for(let[f,h]of Object.entries(u)){let y=jr.join(c,f);if(!await P(y))continue;if(await Fr.readFile(y,"utf8")!==h)throw new _(`Scaffold file "${f}" already exists with different content in "${c}". Choose a new target path or remove conflicting files.`,g.CONFLICT)}let p=[];for(let[f,h]of Object.entries(u)){let y=jr.join(c,f);if(await P(y)){p.push({path:f,status:"unchanged"});continue}await Fr.mkdir(jr.dirname(y),{recursive:!0}),await Fr.writeFile(y,h,"utf8"),p.push({path:f,status:"created"})}return{extension_name:d,package_name:`pm-${d}`,command_name:l,invocation_command:`pm ${l}`,capability:o,style:s,target_path:c,created_directory:m,files:p}}function Bf(e,t){return`${e}:${R(t)}`}function qS(e,t){let n=[];for(let[r,i]of[["handler",e.commands.handlers],["override",e.commands.overrides]]){let o=new Map;for(let s of i){let a=o.get(s.command)??[];o.set(s.command,[...a,s])}for(let[s,a]of o){if(t!==null&&!a.some(d=>t.has(R(d.name))))continue;let c=a.at(-1);n.push({command:s,surface:r,policy:"last_activated_wins",collision:a.length>1,claimants:a.map(d=>({name:d.name,layer:d.layer,winner:d===c}))})}}return n.sort((r,i)=>r.command.localeCompare(i.command)||r.surface.localeCompare(i.surface))}function Jf(e,t,n){let r=new Set(n.failed.map(d=>Bf(d.layer,d.name))),i=[...t.loaded.map(d=>({name:d.name,layer:d.layer,version:d.version,activation_status:r.has(Bf(d.layer,d.name))?"failed":"ok",surfaces:Dn(n,{extensionName:d.name})})),...t.failed.map(d=>({name:d.name,layer:d.layer,version:"unknown",activation_status:"not_loaded",surfaces:Dn(n,{extensionName:d.name})}))].sort((d,l)=>d.name.localeCompare(l.name)||d.layer.localeCompare(l.layer)),o=typeof e=="string"?R(e):null,s=o===null?null:new Set(t.loaded.filter(d=>R(d.name)===o||typeof d.source_package=="string"&&R(d.source_package)===o||(d.source_aliases??[]).some(l=>R(l)===o)).map(d=>R(d.name)).concat(o)),a=s===null?i:i.filter(d=>s.has(R(d.name))),c=s===null?{}:{extensionNames:[...s]};return{target:typeof e=="string"?e.trim():null,total:a.length,extensions:a,union:Dn(n,c),command_ownership:qS(n,s)}}function Ha(e){return e.map(({layer:t,name:n,error:r})=>({layer:t,name:n,error:r}))}function fo(e,t,n){let r=R(t),i=n.trim();if(r.length===0||i.length===0)return;let o=e.get(r)??new Set;o.add(i),e.set(r,o)}function GS(e){let t=new Map,n=new Map;for(let r of e.registrations.commands)fo(t,r.name,r.command),fo(n,r.name,r.action);for(let r of e.commands.handlers)fo(t,r.name,r.command);for(let r of e.commands.overrides)fo(t,r.name,r.command);return{commandPathsByExtension:t,actionPathsByExtension:n}}function Vf(e){if(!(!e||e.size===0))return[...e].sort((t,n)=>t.localeCompare(n))}function BS(e){let{enabled:t,normalizedName:n,loadedNames:r,loadFailedNames:i,activationFailedNames:o}=e;return t?i.has(n)||o.has(n)?{runtime_active:!1,activation_status:"failed"}:r.has(n)?{runtime_active:!0,activation_status:"ok"}:{runtime_active:!1,activation_status:"not_loaded"}:{runtime_active:!1,activation_status:"not_loaded"}}function ho(e,t,n){let r=new Set(t.loaded.map(c=>R(c.name))),i=new Set(t.failed.map(c=>R(c.name))),o=new Set(n.failed.map(c=>R(c.name))),{commandPathsByExtension:s,actionPathsByExtension:a}=GS(n);return e.map(c=>{let d=R(c.name),l=Vf(s.get(d)),u=Vf(a.get(d)),m={...l?{command_paths:l}:{},...u?{action_paths:u}:{}},p=BS({enabled:c.enabled,normalizedName:d,loadedNames:r,loadFailedNames:i,activationFailedNames:o});return{...c,...p,...m}})}function JS(e){let t=0,n=0,r=0;for(let i of e)if(i.startsWith("extension_policy_")){if(t+=1,i.startsWith("extension_policy_violation_")){n+=1;continue}i.startsWith("extension_policy_blocked_")&&(r+=1)}return{warning_count:t,violation_count:n,blocked_count:r}}function ue(e,t){return e.vocabulary==="package"?`pm package --${t}`:`pm extension --${t}`}var Xf=new Set(["extension_command_handler_collision","extension_command_override_collision","extension_command_override_handler_overlap","extension_parser_override_collision","extension_preflight_override_collision","extension_renderer_collision","extension_service_override_collision"]);function VS(e){return Xf.has(rh(e))}function Kf(e){return e==="project"||e==="global"}function Zf(e){let t=e.split(":"),n=t[0];if(!n||!Xf.has(n))return null;let r=t.at(-4),i=t.at(-3)?.trim(),o=t.at(-2),s=t.at(-1)?.trim();return!Kf(r)||!Kf(o)||!i||!s?null:{code:n,surface:t.slice(1,-4).join(":")||"global",winner:{layer:r,name:i},displaced:{layer:o,name:s}}}function KS(e){let t=new Set;for(let n of e){let r=Zf(n);r&&(t.add(r.winner.name),t.add(r.displaced.name))}return[...t].sort((n,r)=>n.localeCompare(r))}function Ua(e,t){let n=e.filter(VS);if(n.length===0)return null;let r=KS(n);return`Extension registration collisions or handler/override overlaps detected.${r.length>0?` Conflicting extensions: ${r.join(", ")}.`:""} Single-winner surfaces can hide earlier package behavior. Deactivate one conflicting package with ${t.deactivate}, or scope registration surfaces in extensions.policy.extension_overrides, then rerun ${t.doctor}.`}function YS(e,t,n,r){let i=t.map(u=>Zf(u)).filter(u=>u!==null).sort((u,m)=>`${u.code}:${u.surface}:${u.winner.name}:${u.displaced.name}`.localeCompare(`${m.code}:${m.surface}:${m.winner.name}:${m.displaced.name}`));if(i.length===0)return;let o=e==="global"?"--global":"--project",s=ue(r,"deactivate"),a=`${ue(r,"doctor")} ${o} --detail deep --trace`,c=new Map(n.map(u=>[R(u.name),u])),d=new Map;for(let u of i)for(let m of[u.winner.name,u.displaced.name]){let p=R(m);d.set(p,(d.get(p)??0)+1)}let l=[...d.entries()].map(([u,m])=>{let p=c.get(u),f=p?.name??u,h=p?.command_paths??[],y=p?.action_paths??[];return{action:"deactivate",extension:f,command:`${s} ${f} ${o}`,affected_collisions:m,feature_loss:{command_paths:[...h].sort((w,v)=>w.localeCompare(v)),action_paths:[...y].sort((w,v)=>w.localeCompare(v))}}}).sort((u,m)=>{let p=m.affected_collisions-u.affected_collisions;if(p!==0)return p;let f=u.feature_loss.command_paths.length+u.feature_loss.action_paths.length,h=m.feature_loss.command_paths.length+m.feature_loss.action_paths.length;return f!==h?f-h:u.extension.localeCompare(m.extension)});return{status:"conflicts_detected",collision_count:i.length,extension_count:d.size,next_best_command:a,collisions:i,remediation_candidates:l}}function Qf(e){let t=[];for(let n of e){let r=n.error.toLowerCase();(r.includes("cannot find package '@unbrained/pm-cli'")||r.includes('cannot find module "@unbrained/pm-cli"')||r.includes("cannot find module '@unbrained/pm-cli'"))&&t.push(`extension_load_failed_sdk_dependency_missing:${n.name}`),(r.includes("cannot use import statement outside a module")||r.includes("to load an es module")||r.includes("must use import to load es module"))&&t.push(`extension_load_failed_module_mode_mismatch:${n.name}`)}return[...new Set(t)].sort((n,r)=>n.localeCompare(r))}function eh(e=[]){let t=Array.isArray(e)?e:[],n=[];for(let r of t){if(!r||typeof r.name!="string")continue;let i=r.trace?.missing_capability??r.trace?.capability;typeof i=="string"&&i.trim().length>0&&n.push(`extension_capability_missing:${r.name}:${i.trim().toLowerCase()}`)}return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}function th(e,t){let n=[];for(let r of Zl(e.loaded,t))for(let i of r.unused)n.push(`extension_capability_unused:${r.layer}:${r.name}:${i}`);return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}var XS=[{matches:e=>e.some(t=>t.startsWith("extension_manifest_")),build:e=>`Run ${ue(e.options,"explore")} ${e.scopeFlag} to inspect discovered manifests and directories.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_unknown:")),build:()=>`Unknown extension capabilities detected. Allowed capabilities: ${si.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_legacy_alias:")),build:()=>"Legacy extension capability aliases were auto-remapped to canonical capabilities. Update manifests to canonical names (migration/validation -> schema)."},{matches:e=>e.some(t=>t.startsWith("extension_capability_missing:")),build:e=>`Extension activation failed because code registered a surface missing from manifest capabilities. Run ${ue(e.options,"doctor")} ${e.scopeFlag} --detail deep --trace and add the reported missing_capability to manifest.json before publishing.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_unused:")),build:e=>`Extension manifests declare capabilities that are never registered against. Remove each reported unused capability from manifest.json to keep least privilege, or add the matching registration. Run ${ue(e.options,"doctor")} ${e.scopeFlag} --detail deep --trace for per-extension registration counts.`},{matches:e=>e.some(t=>t.startsWith("extension_command_definition_legacy_handler_alias:")),build:()=>"Extension command definitions using legacy handler were auto-remapped. Update command definitions to use run: (context) => ... for forward compatibility."},{matches:e=>e.some(t=>t.startsWith("extension_output_service_override_global:")||t.startsWith("extension_output_renderer_override_global:")),build:()=>"Global output service/renderer overrides are active. For output_format, return context.payload/null/undefined unless the extension owns the command. For renderers, return null for unrelated payloads so pm falls back to native rendering."},{matches:e=>e.some(t=>t.startsWith("extension_schema_narrow_activation:")),build:()=>"A package registers custom item types/fields (a GLOBAL schema contribution) but also declares narrow activation.commands, so it never activates for built-in commands like pm create <type> and the custom type silently fails to register. Remove activation.commands from manifest.json so pm activates the package for every command, or \u2014 if the schema is intentionally command-scoped \u2014 knowingly ignore this advisory."},{matches:e=>e.some(t=>t.startsWith("extension_load_failed_sdk_dependency_missing:")),build:e=>`Detected extension load failures caused by missing SDK dependency resolution. Ensure extension package dependencies include "@unbrained/pm-cli" and reinstall dependencies before running ${ue(e.options,"doctor")} ${e.scopeFlag}.`},{matches:e=>e.some(t=>t.startsWith("extension_load_failed_module_mode_mismatch:")),build:e=>`Detected extension module-mode mismatches. For ESM-based extension entries/imports, set package.json "type": "module" or use an explicit .mjs entry and rerun ${ue(e.options,"doctor")} ${e.scopeFlag}.`},{matches:e=>e.some(t=>t.startsWith("extension_pm_min_version_")||t.startsWith("extension_pm_max_version_")),build:e=>`Extension pm version-bound warnings detected. Align each package manifest's pm_min_version/pm_max_version with the installed pm CLI version (see the warning's required/allowed=...:current=... details), or upgrade/downgrade the pm CLI to satisfy the declared bounds, then rerun ${ue(e.options,"doctor")} ${e.scopeFlag}.`},{matches:(e,t)=>t.updateCheckFailedTotal>0,build:e=>`Run ${ue(e.options,"manage")} ${e.scopeFlag} after validating network and repository access.`},{matches:e=>e.some(t=>t.startsWith("extension_manager_state_")),build:e=>`Review and repair ${e.scope} managed extension state file if schema/read warnings persist.`},{matches:(e,t)=>t.policyWarningCount>0,build:()=>"Extension governance policy warnings detected. Review settings.extensions.policy mode and allow/block lists to confirm intended capabilities and registration surfaces."}];function ZS(e){let{normalizedWarnings:t,options:n,scope:r,scopeFlag:i,updateCheckFailedTotal:o,policyWarningCount:s,unmanagedActionRequiredTotal:a,notCheckedTotal:c,skippedNonGithubTotal:d,updateAvailableTotal:l}=e,u=t.map(Ir).filter(p=>p!==void 0),m={options:n,scope:r,scopeFlag:i,updateCheckFailedTotal:o,policyWarningCount:s};if(t.length>0){let p=Ua(t,{deactivate:`${ue(n,"deactivate")} <name> ${i}`,doctor:`${ue(n,"doctor")} ${i} --detail deep --trace`});p&&u.push(p);for(let f of XS)f.matches(t,m)&&u.push(f.build(m))}return a>0&&u.push(`Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via ${ue(n,"manage")} ${i} --fix-managed-state (or ${ue(n,"adopt-all")} ${i}, ${ue(n,"adopt")} <name> ${i}, or reinstall via ${ue(n,"install")} ${i} <source>).`),d>0&&u.push("Update-check coverage is partial: non-GitHub managed sources were not checked. Inspect their registry or source directly; zero detected updates does not mean these packages are current. Runtime activation health is independent."),c>0&&u.push(`Update-check coverage is partial: some sources have no completed check. Run ${ue(n,"manage")} ${i} to request update checks.`),l>0&&u.push(`Update available managed extensions via ${ue(n,"install")} ${i} <source>.`),u.length===0&&u.push(`No immediate action required. Re-run ${ue(n,"manage")} ${i} after extension changes.`),u}function _o(e,t,n,r={}){let i=[...new Set(t)].sort((b,D)=>b.localeCompare(D)),o=n.filter(b=>b.managed).length,s=n.filter(b=>b.enabled).length,a=n.filter(b=>b.active).length,c=n.filter(b=>b.update_check_status==="checked"&&b.update_available===!0).length,d=n.filter(b=>b.managed===!1),l=d.filter(b=>Yf(b)).map(b=>b.name).sort((b,D)=>b.localeCompare(D)),u=d.filter(b=>!Yf(b)).map(b=>b.name).sort((b,D)=>b.localeCompare(D)),m={checked:0,skipped_unmanaged:0,skipped_non_github:0,failed:0,not_checked:0};for(let b of n)m[b.update_check_status]+=1;let p=m.failed,f=n.filter(b=>b.update_check_status==="skipped_non_github"&&b.source?.kind!=="builtin").length,h=Object.entries({skipped_unmanaged:u.length,skipped_non_github:f,failed:p,not_checked:m.not_checked}).filter(([,b])=>b>0).map(([b,D])=>`extension_update_health_partial_coverage:${b}:${D}`),y=h.length>0,w=y?"partial":"full",v=[...new Set([...i,...h])].sort((b,D)=>b.localeCompare(D)),k=[...new Set(v.map(b=>rh(b)))].sort((b,D)=>b.localeCompare(D)),x=JS(v),E=e==="global"?"--global":"--project",A=YS(e,i,n,r),S=ZS({normalizedWarnings:v,options:r,scope:e,scopeFlag:E,updateCheckFailedTotal:p,policyWarningCount:x.warning_count,unmanagedActionRequiredTotal:u.length,notCheckedTotal:m.not_checked,skippedNonGithubTotal:f,updateAvailableTotal:c});return{status:v.length===0?"ok":"warn",warning_count:v.length,warning_codes:k,warnings:v,policy_warning_count:x.warning_count,policy_violation_count:x.violation_count,policy_blocked_count:x.blocked_count,total_extensions:n.length,managed_total:o,enabled_total:s,active_total:a,update_available_total:c,update_health_coverage:w,update_health_partial:y,unmanaged_loaded_extension_count:d.length,unmanaged_loaded_extensions:d.map(b=>b.name).sort((b,D)=>b.localeCompare(D)),unmanaged_expected_extension_count:l.length,unmanaged_expected_extensions:l,unmanaged_action_required_extension_count:u.length,unmanaged_action_required_extensions:u,update_check_status_totals:m,update_check_failed_total:p,top_warnings:v.slice(0,8),remediation:S,...A?{collision_plan:A}:{}}}function nh(e){if(!e||e.trim().length===0)return"summary";let t=e.trim().toLowerCase();if(t==="summary"||t==="deep")return t;throw new _(`Invalid --detail value "${e}". Expected summary or deep.`,g.USAGE)}function rh(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function Hr(e){let t=new Set,n=[];for(let r of e){let i=(()=>{let o=Ld(r);return o?[o]:Nd(r)})();for(let o of i){let s=`${o.layer}:${o.name}:${o.capability}`;t.has(s)||(t.add(s),n.push(o))}}return n}function Ur(){return{version:ai.version,capabilities:[...ai.capabilities],legacy_aliases:{...ai.legacy_aliases}}}function Yf(e){let t=R(e.name),n=R(e.directory);return t.startsWith("builtin-")?!0:n==="beads"||n==="todos"}function ih(e,t,n,r,i){if(e!=="project"||i)return{warnings:[],summary:{active_project_count:0,loaded_project_count:0,active_project_names:[],loaded_project_names:[],missing_active_project_names:[]}};let o=[...new Set(t.filter(l=>l.active).map(l=>R(l.name)))].sort((l,u)=>l.localeCompare(u)),s=[...new Set(n.filter(l=>l.layer==="project").map(l=>R(l.name)))].sort((l,u)=>l.localeCompare(u)),a=new Set(r.map(l=>R(l.name))),c=o.filter(l=>!s.includes(l)&&!a.has(l)).sort((l,u)=>l.localeCompare(u));return{warnings:c.length>0?[`extension_doctor_consistency_active_not_loaded:${c.join(",")}`]:[],summary:{active_project_count:o.length,loaded_project_count:s.length,active_project_names:o,loaded_project_names:s,missing_active_project_names:c}}}import oh from"node:path";function zr(e,t,n,r){let i=oh.relative(e,n);if(i!==""&&!he(e,n)||n===t||he(t,n))return!1;let o=i.split(oh.sep);return o.includes(".git")?!1:r?!o.some(s=>s===".agents"||s==="node_modules"||s.startsWith(".pm-extension-install-backup-")):!0}import{randomUUID as QS}from"node:crypto";import oe from"node:fs/promises";import eE from"node:os";import Z from"node:path";var sh=3,tE=120,ah=250,nE=12e4,rE=new Set(["EEXIST","ENOTEMPTY","ENOENT"]),ch=e=>typeof e=="object"&&e!==null&&"code"in e?e.code:void 0,dh=e=>rE.has(String(ch(e))),go=(e,t)=>ch(e)===t,lh=e=>new Promise(t=>{setTimeout(t,e)}),uh=async e=>{let t=Z.join(e,"package.json");await P(t)||await oe.writeFile(t,`${JSON.stringify({type:"module"},null,2)}
|
|
44
|
+
`,"utf8")},mh=async e=>{let t=et(import.meta.url,["../../.."]),n=Z.join(e,"node_modules","@unbrained"),r=Z.join(n,"pm-cli");await oe.mkdir(n,{recursive:!0}),await oe.rm(r,{recursive:!0,force:!0}),await oe.symlink(t,r,process.platform==="win32"?"junction":"dir")},Wr=async e=>{let t=Z.resolve(e),n=Z.dirname(t),r=Z.parse(n).root,i=await oe.realpath(r).catch(()=>r),o=Z.relative(r,n),s=o===""?[]:o.split(Z.sep);for(let[a,c]of s.entries()){let d=Z.join(i,c);try{i=await oe.realpath(d)}catch{i=Z.join(i,...s.slice(a));break}}return Z.join(i,Z.basename(t))},ph=async(e,t,n,r=eE.tmpdir())=>Jt("extension_install_copy",async()=>{let i=Z.resolve(e),o=await oe.realpath(i).catch(()=>i),s=await Wr(t);if(o===s)return;if(!he(o,s)){await n(o,t,{recursive:!0,force:!0,filter:u=>zr(o,s,Z.resolve(u),!1)});return}let a=await oe.realpath(Z.resolve(r)).catch(()=>Wr(r)),c=he(o,a)?Z.dirname(o):a;if(he(o,c))throw new _(`Extension source "${e}" contains its install destination and no external staging directory is available. Install a narrower package directory instead.`,g.USAGE,{code:"extension_install_source_contains_destination"});let d=await oe.mkdtemp(Z.join(c,"pm-extension-copy-")),l=Z.join(d,"extension");try{await n(o,l,{recursive:!0,force:!0,filter:u=>zr(o,s,Z.resolve(u),!0)}),await n(l,t,{recursive:!0,force:!0})}finally{await oe.rm(d,{recursive:!0,force:!0})}}),fh=async(e,t,n=oe.cp)=>{for(let r=1;r<=sh;r+=1)try{await Jt("extension_install_copy",async()=>{await oe.rm(t,{recursive:!0,force:!0}),await ph(e,t,n)});return}catch(i){if(!dh(i)||r===sh)throw i;await lh(ah)}},za=async e=>{let t;try{t=await oe.readFile(Z.join(e,"owner.json"),"utf8")}catch(i){if(!Qe(i))throw i;return null}let n;try{n=JSON.parse(t)}catch{return null}if(typeof n!="object"||n===null||!("token"in n))return null;let r=n.token;return typeof r=="string"&&r.length>0?r:null},hh=async(e,t)=>await za(e)!==t?!1:(await oe.rm(e,{recursive:!0,force:!0}),!0),iE=async(e,t)=>{let n;try{n=await oe.stat(e)}catch{return!1}if(Date.now()-n.mtimeMs<=t)return!1;let r=await za(e);return r===null?(await oe.rm(e,{recursive:!0,force:!0}),!0):hh(e,r)},oE=(e,t,n)=>{let r=Promise.resolve(),i=setInterval(()=>{r=r.then(async()=>{if(await za(e)!==t)return;let o=new Date;await oe.utimes(e,o,o)}).catch(()=>{})},n);return i.unref(),async()=>{clearInterval(i),await r}},sE=async(e,t)=>{await oe.mkdir(e);try{await oe.writeFile(Z.join(e,"owner.json"),`${JSON.stringify(t,null,2)}
|
|
45
|
+
`,"utf8")}catch(n){throw await oe.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}},aE=async(e,t,n,r,i)=>{for(let o=1;o<=n;o+=1)try{return await sE(e,t),!0}catch(s){if(!go(s,"EEXIST"))throw s;await iE(e,i)?o-=1:await lh(r)}return!1},Wa=async(e,t,n,r)=>Jt("extension_install",async()=>{let i=Z.join(e,"runtime","extension-install-locks"),o=Z.join(i,"scope.lock");await oe.mkdir(i,{recursive:!0});let{attempts:s=tE,delay_ms:a=ah,stale_ms:c=nE,heartbeat_ms:d}=r??{};if(![s,a,c,d].filter(v=>v!==void 0).every(Number.isFinite))throw new _("Extension install lock timings must be finite numbers.",g.USAGE);let l=Math.max(1,Math.floor(s)),u=Math.max(0,Math.floor(a)),m=Math.floor(c),p=Math.floor(d??m/3);if(m<=0||p<=0||p>=m)throw new _("Extension install lock timings require stale_ms > 0 and 0 < heartbeat_ms < stale_ms.",g.USAGE);let f={pid:process.pid,token:QS(),created_at:C(),destination:t};if(!await aE(o,f,l,u,m))throw new _(`Timed out waiting for extension install lock for "${t}".`,g.CONFLICT);let y=oE(o,f.token,p),w=!1;try{let v=await n();return w=!0,v}finally{await y(),await hh(o,f.token).catch(v=>{if(w)throw v})}});function _h(e,t){let n=R(e),r=t.find(i=>R(i.name)===n);return{command_paths:[...r?.command_paths??[]].sort((i,o)=>i.localeCompare(o)),action_paths:[...r?.action_paths??[]].sort((i,o)=>i.localeCompare(o))}}function gh(e,t){let n=new Set((t?.loaded??[]).flatMap(o=>(o.activation?.commands?.length??0)>0?[`${o.layer}:${R(o.name)}`]:[])),r=e.services.overrides.filter(o=>o.service==="output_format").filter(o=>o.passThrough!==!0).filter(o=>!n.has(`${o.layer}:${R(o.name)}`)).map(o=>`extension_output_service_override_global:${o.service}:${o.layer}:${o.name}`),i=e.renderers.overrides.filter(o=>(o.commands?.length??0)===0&&o.resultDiscriminator===void 0).map(o=>`extension_output_renderer_override_global:${o.format}:${o.layer}:${o.name}`);return[...new Set([...r,...i])].sort((o,s)=>o.localeCompare(s))}var yh=e=>[...e.registrations.item_fields.flatMap(t=>t.fields.map(n=>({layer:t.layer,extension:t.name,field:n.name}))),...e.registrations.profiles.flatMap(t=>t.profile.fields.map(n=>({layer:t.layer,extension:t.name,field:n.key??""})))].flatMap(t=>{let n=Oi(t.field);return n?[`extension_custom_field_mcp_input_collision:${t.layer}:${t.extension}:${n.field}:${n.property}:${n.owner}:use=${n.nested_path}`]:[]}).filter((t,n,r)=>r.indexOf(t)===n).sort((t,n)=>t.localeCompare(n));import{spawn as vE}from"node:child_process";import{AsyncLocalStorage as kE}from"node:async_hooks";import{isMainThread as bE}from"node:worker_threads";import xE from"npm-package-arg";import{spawn as cE}from"node:child_process";import{existsSync as yo,readFileSync as dE}from"node:fs";import wh from"node:path";var vh=2e3;function lE(e,t){let n=new Map;for(let s of e.split(`
|
|
46
|
+
`)){let a=s.trim().split(/\s+/u);if(a.length!==2)continue;let[c,d]=a.map(Number);if(!Number.isSafeInteger(c)||!Number.isSafeInteger(d)||c<=0)continue;let l=n.get(d);l?l.push(c):n.set(d,[c])}let r=new Set([t]),i=[],o=(n.get(t)??[]).map(s=>({pid:s,parent:t}));for(let s=0;s<o.length;s+=1){let a=o[s];if(!r.has(a.pid)){r.add(a.pid),i.push(a);for(let c of n.get(a.pid)??[])o.push({pid:c,parent:a.pid})}}return i.reverse()}function qa(e,t=kh){let n=t(`/proc/${e.pid}/stat`);if(n===void 0)return!yo("/proc/self/stat");let r=n.slice(n.lastIndexOf(")")+1).trim().split(/\s+/u);return Number(r[1])===e.parent}function uE(e=kh,t=process.platform){let n=e("/proc/self/status");if(n===void 0)return t!=="linux"&&!yo("/proc/self/status");let r=/^NSpid:\s*(.*)$/mu.exec(n)?.[1]?.trim().split(/\s+/u);return r?.length===1&&Number(r[0])===process.pid}function mE(e,t,n,r=qa,i=new Map){let o=[],s=!0;for(let a=e;a!==t;){let c=i.get(a);if(c!==void 0){s=c;break}o.push(a);let d=n.get(a);if(d===void 0||!r({pid:a,parent:d})){s=!1;break}a=d}for(let a of o)i.set(a,s);return s}function kh(e){try{return dE(e,"utf8")}catch{return}}var pE=["/bin/ps","/usr/bin/ps"],fE={PATH:"/usr/bin:/bin",LC_ALL:"C"};function hE(e=yo){return pE.find(t=>e(t))}var _E="C:\\Windows";function gE(e=process.env,t=yo){let n=r=>Object.entries(e).find(([i])=>i.toLowerCase()===r)?.[1];return[n("systemroot"),n("windir"),_E].find(r=>typeof r=="string"&&/^[A-Za-z]:[\\/]/u.test(r)&&t(wh.win32.join(r,"System32","taskkill.exe")))}function bh(e){try{process.kill(e,"SIGKILL")}catch{}}function xh(e,t,n,r=vh){return new Promise(i=>{let o=!1,s="",a;try{a=cE(e,t,{stdio:["ignore","pipe","ignore"],windowsHide:!0,...n===void 0?{}:{env:n}})}catch{i(void 0);return}let c=r===null?void 0:setTimeout(()=>{d(void 0),a.stdout?.destroy(),a.kill("SIGKILL"),a.unref()},r);function d(l){o||(o=!0,clearTimeout(c),i(l))}if(a.on("error",()=>d(void 0)),!a.stdout){d(void 0);return}a.stdout.setEncoding("utf8"),a.stdout.on("data",l=>{s+=l}),a.on("close",l=>d({code:l,stdout:s}))})}async function Sh(e,t={kill:()=>bh(e),alive:()=>!0},n={}){if(!(!Number.isInteger(e)||e<=0)){if(process.platform==="win32"){await yE(e,t,n.taskkillTimeoutMs===void 0?vh:n.taskkillTimeoutMs);return}try{process.kill(-e,"SIGKILL");return}catch{}await wE(e,t),t.kill()}}async function yE(e,t,n){let r=gE();if(r===void 0){t.alive()&&t.kill();return}let i=wh.win32.join(r,"System32","taskkill.exe");(await xh(i,["/pid",String(e),"/T","/F"],void 0,n))?.code!==0&&t.alive()&&t.kill()}async function wE(e,t){let n=hE();if(n===void 0||!uE())return;let r=await xh(n,["-A","-o","pid=","-o","ppid="],fE);if(r?.code!==0||!t.alive())return;let i=lE(r.stdout,e),o=new Map(i.map(a=>[a.pid,a.parent])),s=new Map;for(let a of i)qa(a)&&mE(a.parent,e,o,qa,s)&&bh(a.pid)}var SE="PM_EXTENSION_UPDATE_CHECK_TIMEOUT_MS",Ga=1e4,EE=1e3,RE=25e3,AE=2e3,IE="npm_registry_lookup_failed",CE="npm_registry_lookup_timed_out",$E="github_remote_lookup_failed",TE="github_remote_lookup_timed_out";function qn(e=process.env){let t=e[SE]?.trim(),n=t?Number(t):Number.NaN;return Number.isFinite(n)?Math.min(RE,Math.max(EE,Math.trunc(n))):Ga}var Me=class extends Error{timeout_ms;teardown;constructor(t,n,r){super(t),this.name="UpdateQueryError",this.timeout_ms=n,this.teardown=r}},Ah=new WeakMap;function Ih(e){return Ah.get(e)??Promise.resolve()}function Ch(e,t){let n={checked_at:e,available:null,error:t instanceof Error?t.message:String(t)};return t instanceof Me&&t.timeout_ms!==void 0&&(n.timeout_ms=t.timeout_ms),t instanceof Me&&t.teardown!==void 0&&Ah.set(n,t.teardown),n}var qr=new Set;function Eh(){for(let e of qr)e()}var $h=new kE;async function Th(e){let t=new Set;try{return await $h.run(t,e)}finally{bE||await Promise.all(t)}}function OE(e){return qr.size===0&&process.on("exit",Eh),qr.add(e),()=>{qr.delete(e),qr.size===0&&process.off("exit",Eh)}}function PE(e){let t=()=>e.exitCode!==null||e.signalCode!==null,n=()=>{t()||e.kill("SIGKILL")},r=()=>t()||e.pid===void 0?Promise.resolve():new Promise(o=>{let s=setTimeout(()=>{e.unref(),o()},AE);e.once("exit",()=>{clearTimeout(s),o()})}),i=()=>(n(),e.stdout?.destroy(),r());return{stop:()=>t()||e.pid===void 0?Promise.resolve().then(i):Sh(e.pid,{kill:n,alive:()=>!t()}).then(i,i),killNow:n}}function Oh(e,t,n,r){return new Promise((i,o)=>{let s;try{s=vE(e,t,{env:r.env,shell:r.shell,stdio:["ignore","pipe","ignore"]})}catch{o(new Me(r.failed));return}let a=s,c=performance.now()+n,d=!1,l="",u=0,m=PE(a),p=$h.getStore(),f,h=()=>{let v=OE(m.killNow),k=new Promise(x=>{setTimeout(()=>{m.stop().then(x,x)},0)}).finally(v);return p?.add(k),f=k,k},y=setTimeout(()=>{w(new Me(r.timedOut,n,h()))},n);function w(v){d||(d=!0,clearTimeout(y),performance.now()>=c?o(new Me(r.timedOut,n,f)):v?o(v):i(l.trim()))}if(a.on("error",()=>w(new Me(r.failed))),!a.stdout){w(new Me(r.failed,void 0,h()));return}a.stdout.setEncoding("utf8"),a.stdout.on("data",v=>{if(!d){if(u+=Buffer.byteLength(v),u>r.maxBuffer){w(new Me(r.failed,void 0,h()));return}l+=v}}),a.on("exit",(v,k)=>{v===0&&k===null||(w(new Me(r.failed)),a.stdout.destroy())}),a.on("close",(v,k)=>w(v===0&&k===null?void 0:new Me(r.failed)))})}function Rh(e,t,n){if(typeof t=="string")try{let r=xE.resolve(e,t);if(r.type==="version")return r.fetchSpec}catch{}throw new Error(n)}var LE=(e,t)=>Oh(Da(),e,t,{env:{...process.env,npm_config_ignore_scripts:"true"},shell:Ma(),maxBuffer:64*1024,timedOut:CE,failed:IE}),NE=(e,t)=>Oh("git",e,t,{env:{...process.env,GIT_TERMINAL_PROMPT:"0",GCM_INTERACTIVE:"never"},maxBuffer:1024*1024,timedOut:TE,failed:$E});async function Ph(e,t=LE,n=qn()){let r=C();try{if(e.kind!=="npm"||!e.package||!/^(?:@[a-zA-Z0-9._-]+\/)?[a-zA-Z0-9._-]+$/u.test(e.package))throw new Error("missing_or_invalid_npm_package_identity");let i=Rh(e.package,e.version,"missing_or_invalid_installed_npm_version"),o=await t(["view",e.package,"dist-tags.latest","--json","--ignore-scripts"],n),s;try{s=JSON.parse(o)}catch{throw new Error("invalid_npm_registry_metadata")}let a=Array.isArray(s)&&s.length===1?s[0]:s,c=Rh(e.package,a,"invalid_npm_registry_version");return{checked_at:r,available:c!==i,remote_version:c}}catch(i){return Ch(r,i)}}var DE=(e,t,n)=>{let r=e.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).map(s=>{let[a,c=""]=s.split(/\s+/);return{commit:a,ref:c}}),i=r.find(s=>s.ref.endsWith("^{}"))??r[0];if(!i)return{checked_at:n,available:null,error:"no_remote_reference_found"};let o=t?.trim();return o?{checked_at:n,remote_commit:i.commit,available:i.commit!==o}:{checked_at:n,remote_commit:i.commit,available:null,error:"missing_installed_commit"}},Ba=async(e,t=NE,n=qn())=>{let r=C();if(e.kind!=="github"||!e.repository)return{checked_at:r,available:null,error:"not_a_github_managed_source"};try{let i=[e.ref?.trim(),"HEAD"].find(Boolean),o=await t(["ls-remote",e.repository,i,`${i}^{}`],n);return DE(o,e.commit,r)}catch(i){return Ch(r,i)}};var Lh=4;function ME(e){let t=e,n=[];return{acquire:()=>t>0?(t-=1,Promise.resolve()):new Promise(r=>n.push(r)),release:()=>{let r=n.shift();r?r():t+=1}}}function Nh(e,t){let{update_check_timeout_ms:n,...r}=e;return t===void 0?r:{...r,update_check_timeout_ms:t}}async function Dh(e,t=!1,n=qn(),r=!0){let i=ME(Lh),o=await Fs(e.entries,Lh,async s=>{if(!["github","npm"].includes(s.source.kind))return s;if(t)return Nh({...s,last_update_check_at:void 0,last_update_remote_commit:void 0,last_update_remote_version:void 0,update_available:null,update_error:void 0},void 0);await i.acquire();let a=s.source.kind==="github"?await Ba(s.source,void 0,n):await Ph(s.source,void 0,n);return r?Ih(a).then(i.release):i.release(),Nh({...s,last_update_check_at:a.checked_at,last_update_remote_commit:"remote_commit"in a?a.remote_commit:void 0,last_update_remote_version:"remote_version"in a?a.remote_version:void 0,update_available:a.available,update_error:a.error},a.timeout_ms)});return{...e,entries:Lr(o)}}import FE from"node:fs/promises";import jE from"node:path";function Ja(e){return jE.join(e,"extension-migrations.json")}function Mh(e,t){let n=e.definition.id;return typeof n=="string"&&n.trim().length>0?n.trim():`migration-${String(t+1).padStart(3,"0")}`}function Fh(e,t){return`${e.layer}:${e.name}:${t}`}async function HE(e){let t=Ja(e);if(!await P(t))return{version:1,updated_at:"",entries:[]};let n=JSON.parse(await FE.readFile(t,"utf8"));return{version:1,updated_at:typeof n.updated_at=="string"?n.updated_at:"",entries:Array.isArray(n.entries)?n.entries.filter(r=>typeof r?.key=="string"&&(r.status==="applied"||r.status==="failed")):[]}}async function Va(e,t){let n=await HE(e),r=new Map(n.entries.map(i=>[i.key,i]));return t.forEach((i,o)=>{let s=Mh(i,o),a=r.get(Fh(i,s));a&&(i.definition.status=a.status,a.status==="failed"?i.definition.reason=a.error:(delete i.definition.reason,delete i.definition.error,delete i.definition.message))}),n}async function UE(e){let t=await Va(e.pmRoot,e.migrations),n=new Map(t.entries.map(l=>[l.key,l])),r=[],i=!1,o=e.migrations.map((l,u)=>({migration:l,index:u})).filter(({migration:l})=>e.scope===void 0||l.layer===e.scope);for(let{migration:l,index:u}of o){let m=Mh(l,u),p=Fh(l,m),f=n.get(p),h=String(l.definition.status??"pending").toLowerCase(),y=f?.status??(h==="applied"||h==="failed"?h:"pending");if(y==="applied"){r.push({key:p,layer:l.layer,extension:l.name,id:m,before:y,outcome:"skipped"});continue}if(e.dryRun===!0){r.push({key:p,layer:l.layer,extension:l.name,id:m,before:y,outcome:"pending"});continue}let w=l.runtime_definition?.run??l.definition.run;if(typeof w!="function"){r.push({key:p,layer:l.layer,extension:l.name,id:m,before:y,outcome:"pending"});continue}let v=new Date().toISOString();try{await Promise.resolve(w({id:m,command:"migration",layer:l.layer,extension:l.name,pm_root:e.pmRoot,status:y}));let k={key:p,layer:l.layer,extension:l.name,id:m,status:"applied",attempted_at:v};n.set(p,k),l.definition.status="applied",delete l.definition.reason,delete l.definition.error,delete l.definition.message,r.push({key:p,layer:l.layer,extension:l.name,id:m,before:y,outcome:"applied"}),i=!0}catch(k){let x=k instanceof Error?k.message:String(k),E={key:p,layer:l.layer,extension:l.name,id:m,status:"failed",attempted_at:v,error:x};n.set(p,E),l.definition.status="failed",l.definition.reason=x,r.push({key:p,layer:l.layer,extension:l.name,id:m,before:y,outcome:"failed",error:x}),i=!0}}if(i){let l=await T(e.pmRoot),u={version:1,updated_at:new Date().toISOString(),entries:[...n.values()].sort((m,p)=>m.key.localeCompare(p.key))};await En({pmRoot:e.pmRoot,filePath:Ja(e.pmRoot),raw:`${JSON.stringify(u,null,2)}
|
|
47
|
+
`,op:"extension_migrations_apply",author:e.author,lockTtlSeconds:l.locks.ttl_seconds,lockWaitMs:l.locks.wait_ms})}let s=r.filter(l=>l.outcome==="pending").length,a=r.filter(l=>l.outcome==="applied").length,c=r.filter(l=>l.outcome==="skipped").length,d=r.filter(l=>l.outcome==="failed").length;return{ok:d===0,dry_run:e.dryRun===!0,state_path:Ja(e.pmRoot),total:r.length,pending_count:s,applied_count:a,skipped_count:c,failed_count:d,migrations:r}}async function jh(e){let t=await T(e.resolvedRoots.settings_root),n=await nt({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),r=await rt(n);e.warnings.push(...n.warnings,...r.warnings);let i=await UE({pmRoot:e.resolvedRoots.pm_root,migrations:r.registrations.migrations,author:typeof e.global.author=="string"&&e.global.author.trim().length>0?e.global.author.trim():"pm-extension-migration",dryRun:e.options.dryRun===!0,...e.scope==="global"?{scope:"global"}:{}});return e.withResult({migration:i,load_failure_count:n.failed.length,activation_failure_count:r.failed.length},i.ok)}function Hh(e,t){let n=e.filter(r=>r.result.ok).length;return{installed_all:!t&&n===e.length,installed_count:t?0:n,...t?{dry_run:!0,planned_count:n}:{},failed_count:e.length-n,packages:e.map(({alias:r,result:i})=>{let o=i.details;return{alias:r,ok:i.ok,extension:o.extension,source:o.source,source_resolution:o.source_resolution,install_plan:o.install_plan,dry_run:o.dry_run,destination_path:o.destination_path,activated:o.activated,settings_changed:o.settings_changed,previous_state_preserved:o.previous_state_preserved,rollback:o.rollback,command_paths:o.command_paths,action_paths:o.action_paths,command_discovery:o.command_discovery,verification:o.verification,runtime_activation_status:o.runtime_activation_status,activation_diagnostics:o.activation_diagnostics,warnings:i.warnings}})}}import vo from"node:fs/promises";import wo from"node:path";var zE=new Set(["node_modules",".git","dist","build","coverage"]);async function Uh(e,t,n,r){let i=e.source.kind==="local"?await vo.stat(e.source.absolute_path):void 0,o=e.source.kind==="local"?i.isDirectory()?"directory":"archive":e.source.kind,s=await WE(e.directory,t,r),a={source_mode:o,...o==="archive"?{archive_bytes:i.size}:{},copy:s},c=e.source_root??e.directory;if(o==="directory"&&(!s.complete||s.development_entries>0||s.bytes>=16*1024*1024)&&await P(wo.join(c,"package.json"))&&(a.packed_alternative={cwd:c,pack:{command:"npm",args:["pack","--ignore-scripts","--json"]},install:{command:"pm",args:["package","install","<archive-filename>",`--${n}`]},archive_argument:"pack_result[0].filename"}),o==="directory"&&!s.complete){let d=s.stop_reason==="entry_limit"?`${s.max_entries} entries`:`${s.max_depth} directory levels`;throw new _(`Local extension source scan stopped at ${d}; the directory snapshot is incomplete and installation was refused. ${a.packed_alternative?"Pack the package with npm pack --ignore-scripts --json, then install its archive.":"Install a smaller source directory or a packed archive."}`,g.USAGE,{code:"extension_install_incomplete_source_scan",reason:s.stop_reason,nextSteps:a.packed_alternative?[`Run npm pack --ignore-scripts --json from the package root, then pm package install <archive-filename> --${n}.`]:["Choose a smaller source directory or install a packed archive."]})}return a}async function WE(e,t,n={}){let{maxEntries:r=1e4,maxDepth:i=64,signal:o}=n;if(![r,i].every(u=>Number.isSafeInteger(u)&&u>0))throw new _("maxEntries and maxDepth must be positive safe integers.",g.USAGE);o?.throwIfAborted();let s=await vo.realpath(e),a=await Wr(t),c=await Wn(s,a);o?.throwIfAborted();let d=c?"in_place":he(s,a)?"nested_filtered_snapshot":"directory_snapshot",l={copy_scope:d,source_directory:s,destination_directory:a,files:0,bytes:0,directories:0,symlinks:0,other_entries:0,scanned_entries:0,excluded_entries:0,development_entries:0,complete:!0,stop_reason:"complete",max_entries:r,max_depth:i};return d==="in_place"||await zh(s,0,l,o),l}async function zh(e,t,n,r){r?.throwIfAborted();let i=await vo.opendir(e);for await(let o of i){if(r?.throwIfAborted(),n.scanned_entries>=n.max_entries){n.complete=!1,n.stop_reason="entry_limit";return}n.scanned_entries+=1;let s=wo.join(e,o.name);if(!zr(n.source_directory,n.destination_directory,s,n.copy_scope==="nested_filtered_snapshot")){n.excluded_entries+=1;continue}if(wo.relative(n.source_directory,s).split(wo.sep).some(a=>zE.has(a))&&(n.development_entries+=1),await qE(s,t,n,r),!n.complete)return}}async function qE(e,t,n,r){let i=await vo.lstat(e);if(r?.throwIfAborted(),i.isDirectory()){if(n.directories+=1,t+1>=n.max_depth){n.complete=!1,n.stop_reason="depth_limit";return}await zh(e,t+1,n,r)}else i.isFile()?(n.files+=1,n.bytes+=i.size):i.isSymbolicLink()?n.symlinks+=1:n.other_entries+=1}import GE from"node:fs/promises";import BE from"node:path";function JE(e){return typeof e.name=="string"&&e.name.trim().length>0?e.name.trim():"workspace-manifest"}function VE(e,t){return t.code==="manifest_unknown_key"?`extension_manifest_unknown_key:author:${e}:key=${t.path}${t.suggested_key?`:suggested=${t.suggested_key}`:""}`:`extension_manifest_no_version_bounds:author:${e}:suggested=pm_min_version`}async function Ka(e){let t=BE.join(e,"manifest.json"),n;try{n=await GE.readFile(t,"utf8")}catch(a){if(Qe(a))return{path:t,present:!1,parse_status:"absent",package_metadata_location:"package.json#pm",schema_findings:[],warnings:[],remediation:[]};throw a}let r;try{r=JSON.parse(n)}catch{return{path:t,present:!0,parse_status:"invalid_json",package_metadata_location:"package.json#pm",schema_findings:[],warnings:["extension_author_manifest_invalid_json:manifest.json"],remediation:["Repair manifest.json so it contains one valid JSON object, then rerun pm package doctor --project."]}}if(typeof r!="object"||r===null||Array.isArray(r))return{path:t,present:!0,parse_status:"invalid_shape",package_metadata_location:"package.json#pm",schema_findings:[],warnings:["extension_author_manifest_invalid_shape:manifest.json"],remediation:["Replace manifest.json with one JSON object, then rerun pm package doctor --project."]};let i=r,o=Ud(i),s=JE(i);return{path:t,present:!0,parse_status:"valid",package_metadata_location:"package.json#pm",schema_findings:o.findings,warnings:o.findings.map(a=>VE(s,a)),remediation:o.findings.map(a=>a.message)}}function Wh(e){return Ka(tt(e))}import KE from"node:fs/promises";import YE from"npm-package-arg";async function XE(e,t){if(e.kind!=="local"||e.input.startsWith(".")||e.input.includes("\\")||e.input.includes("/")&&!/^@[a-zA-Z0-9._-]+\/[a-zA-Z0-9._-]+$/u.test(e.input))return e;try{return await KE.lstat(e.absolute_path),e}catch(s){if(!F(s))throw s}let n=e.input.trim(),r=t.filter(s=>s.source.kind==="npm"),o=(r.find(s=>s.name===n)??r.find(s=>s.directory===n)??r.find(s=>s.source.package===n))?.source.package;if(o===void 0)return e;try{let s=YE(o);if(!s.registry||s.name!==o)return e}catch{return e}return Mr(`npm:${o}`,{})}async function qh(e,t,n,r=[]){let i=typeof t=="string"?null:await Dr(e),o=i===null?null:e.trim().toLowerCase(),s=o===null?null:await kf(o),a=await XE(Mr(i??e,{forceGithub:typeof t=="string",ref:n}),r),c=o===null?null:await Af(e);return{bundledAliasName:o,bundledPackageName:s,installSource:a,sourceResolution:{requested:e,selected:{kind:o===null?a.kind:"builtin",input:o??a.input,...s===null?{}:{package:s}},ambiguous:c!==null,precedence:"bundled_alias_before_installed_npm",candidates:[...o===null?[]:[{kind:"builtin",input:o,...s===null?{}:{package:s},command:`pm install ${o}`}],...c===null?[]:[{kind:"npm",input:`npm:${c.package}`,package:c.package,...c.version===void 0?{}:{version:c.version},directory:c.directory,command:`pm install npm:${c.package}`}]]}}}import Ye from"node:fs/promises";import Gn from"node:path";var Ya=async e=>Ye.readFile(e).catch(t=>{if(go(t,"ENOENT"))return null;throw t}),ZE=async(e,t,n,r,i)=>Jt("extension_install_backup",async()=>{let o=Pr(e),s=un(t),[a,c]=await Promise.all([Ya(o),Ya(s)]);return r&&await Ye.cp(n,i,{recursive:!0,force:!0}),{backupDirectory:i,destinationDirectory:n,destinationExists:r,managedStatePath:o,managedStateContents:a,settingsPath:s,settingsContents:c}}),Gh=async e=>Jt("extension_install_rollback",async()=>{await Ye.rm(e.destinationDirectory,{recursive:!0,force:!0}),e.destinationExists&&await Ye.cp(e.backupDirectory,e.destinationDirectory,{recursive:!0,force:!0});for(let[t,n]of[[e.managedStatePath,e.managedStateContents],[e.settingsPath,e.settingsContents]])if(n===null)await Ye.rm(t,{force:!0});else if(t===e.settingsPath){let r=Gn.dirname(e.settingsPath),i=await T(r);try{await En({pmRoot:r,filePath:t,raw:n.toString("utf8"),op:"extension:install:rollback",author:q(void 0,i.author_default),lockTtlSeconds:i.locks.ttl_seconds,lockWaitMs:i.locks.wait_ms})}finally{ku(r)}}else await Ye.mkdir(Gn.dirname(t),{recursive:!0}),await Ye.writeFile(t,n)});async function Bh(e,t){let n=await P(e.destinationDirectory),r=await Wn(e.sourceDirectory,e.destinationDirectory);await Ye.mkdir(e.selectedRoot,{recursive:!0});let i=Gn.join(Gn.dirname(e.selectedRoot),"runtime","extension-installs");await Ye.mkdir(i,{recursive:!0});let o=await Ye.mkdtemp(Gn.join(i,".pm-extension-install-backup-")),s=Gn.join(o,"destination"),a=["package","install",s,`--${e.scope}`],c=K(a),d=!1;try{let l=await ZE(e.selectedRoot,e.settingsRoot,e.destinationDirectory,n,s),u;try{u=await t()}catch(m){try{await Gh(l)}catch(p){d=!0;let f=new _(`Extension install failed: ${String(m)}; rollback failed: ${String(p)}`,g.GENERIC_FAILURE,{code:"extension_install_rollback_failed",original_code:m instanceof _?m.code:void 0,required:"Restore the previous package before retrying the replacement. Previous state was not preserved.",nextSteps:[n?c:"Repair the reported metadata write failure, then retry the original install."],...n?{recovery:{suggested_retry:c,suggested_retry_args:a}}:{}});throw Object.defineProperty(f,"cause",{value:m,configurable:!0,writable:!0}),f}throw m}if(u.ok)return u;if(!n||r)return{...u,details:{...u.details,previous_state_preserved:!1}};try{await Gh(l)}catch(m){return d=!0,{...u,details:{...u.details,previous_state_preserved:!1,rollback:{status:"failed",error:String(m),backup_directory:s,recovery_command:c,recovery_args:a}}}}return{...u,details:{...u.details,overwritten:!1,settings_changed:!1,previous_state_preserved:!0,rollback:{status:"restored"}}}}finally{d||await Ye.rm(o,{recursive:!0,force:!0}).catch(()=>{})}}var Yh=[["install","install","--install"],["uninstall","uninstall","--uninstall"],["explore","explore","--explore"],["list","explore","--explore"],["manage","manage","--manage"],["describe","describe","--describe"],["reload","reload","--reload"],["doctor","doctor","--doctor"],["catalog","catalog","--catalog"],["init","init","--init"],["scaffold","init","--scaffold"],["adopt","adopt","--adopt"],["adopt-all","adopt-all","--adopt-all"],["activate","activate","--activate"],["deactivate","deactivate","--deactivate"],["migrate","migrate","--migrate"]],QE=Yh.map(([,,e])=>e).filter((e,t,n)=>n.indexOf(e)===t).join(", "),eR={install:"--install",uninstall:"--uninstall",explore:"--explore",manage:"--manage",describe:"--describe",reload:"--reload",doctor:"--doctor",catalog:"--catalog",adopt:"--adopt","adopt-all":"--adopt-all",activate:"--activate",deactivate:"--deactivate",migrate:"--migrate",init:"--init"},tR="__pm_native_output",nR=["trusted_extensions","allowed_extensions","blocked_extensions","allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],Xh=["allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],rR=["disabled","require_trusted","require_provenance"],Zh={mode:"off",trust_mode:"off",require_provenance:!1,trusted_extensions:[],default_sandbox_profile:"none",allowed_extensions:[],blocked_extensions:[],allowed_capabilities:[],blocked_capabilities:[],allowed_surfaces:[],blocked_surfaces:[],allowed_commands:[],blocked_commands:[],allowed_actions:[],blocked_actions:[],allowed_services:[],blocked_services:[],extension_overrides:[]},iR=e=>{let t=e??Zh,n={};for(let r of nR)n[r]=Oe(t[r]??[]);return n},oR=(e,t)=>{for(let n of Xh)t[n].length>0&&(e[n]=t[n]);return e},sR=(e,t)=>{for(let n of rR)t[n]===!0&&(e[n]=!0);return t.sandbox_profile&&(e.sandbox_profile=t.sandbox_profile),e},aR=e=>{let t={};for(let n of Xh)t[n]=Oe(e[n]??[]);return t},cR=e=>{let t=typeof e.name=="string"?e.name.trim():"";return t.length===0?null:oR(sR({name:t},e),aR(e))},dR=e=>(e??[]).map(t=>cR(t)).filter(t=>t!==null).sort((t,n)=>t.name.localeCompare(n.name)),lR=e=>{let t=Object.assign({},Zh,e??{}),n=iR(e),r=dR(t.extension_overrides);return{mode:t.mode,trust_mode:t.trust_mode,require_provenance:t.require_provenance===!0,trusted_extensions:n.trusted_extensions,default_sandbox_profile:t.default_sandbox_profile,allowed_extensions:n.allowed_extensions,blocked_extensions:n.blocked_extensions,allowed_capabilities:n.allowed_capabilities,blocked_capabilities:n.blocked_capabilities,allowed_surfaces:n.allowed_surfaces,blocked_surfaces:n.blocked_surfaces,allowed_commands:n.allowed_commands,blocked_commands:n.blocked_commands,allowed_actions:n.allowed_actions,blocked_actions:n.blocked_actions,allowed_services:n.allowed_services,blocked_services:n.blocked_services,extension_overrides:r}},Qh=async(e,t)=>{let n=[t],r=await bf(t);r&&n.push(r);let i=[...new Set(n.map(o=>R(o)).filter(o=>o.length>0))];for(let o of i){let s=e.find(c=>R(c.name)===o);if(s)return s;let a=e.find(c=>R(c.directory)===o);if(a)return a}},e_=(e,t)=>{let n=t.trim(),r=new Set(Oe(e.extensions.enabled));return new Set(Oe(e.extensions.disabled)).has(n)?!1:r.size===0?!0:r.has(n)},t_=(e,t)=>{let n=t.trim(),r=new Set(Oe(e.extensions.enabled)),i=new Set(Oe(e.extensions.disabled)),o=[...r],s=[...i];return i.delete(n),r.size>0&&r.add(n),e.extensions.enabled=[...r].sort((a,c)=>a.localeCompare(c)),e.extensions.disabled=[...i].sort((a,c)=>a.localeCompare(c)),e.extensions.enabled.join("\0")!==o.join("\0")||e.extensions.disabled.join("\0")!==s.join("\0")},uR=(e,t)=>{let n=t.trim(),r=new Set(Oe(e.extensions.enabled)),i=new Set(Oe(e.extensions.disabled)),o=[...r],s=[...i];return r.delete(n),i.add(n),e.extensions.enabled=[...r].sort((a,c)=>a.localeCompare(c)),e.extensions.disabled=[...i].sort((a,c)=>a.localeCompare(c)),e.extensions.enabled.join("\0")!==o.join("\0")||e.extensions.disabled.join("\0")!==s.join("\0")},mR=(e,t)=>{let n=t.trim(),r=new Set(Oe(e.extensions.enabled)),i=new Set(Oe(e.extensions.disabled)),o=[...r],s=[...i];return r.delete(n),i.delete(n),e.extensions.enabled=[...r].sort((a,c)=>a.localeCompare(c)),e.extensions.disabled=[...i].sort((a,c)=>a.localeCompare(c)),e.extensions.enabled.join("\0")!==o.join("\0")||e.extensions.disabled.join("\0")!==s.join("\0")},pR=e=>{let t=e.trim().toLowerCase(),n=Math.min(2,Math.max(1,Math.ceil(t.length/4))),r=Yh.map(([i,o,s])=>({action:o,flag:s,distance:Pd(t,i,n)})).filter(i=>i.distance!==null).sort((i,o)=>i.distance-o.distance)[0];return r?{action:r.action,flag:r.flag}:null},fR=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",r=pR(e);if(!r)return new _(`One action flag is required. Use one of: ${QE}. Bare \`pm package\` and \`pm extension\` default to --explore.`,g.USAGE);let i=`pm ${n} ${r.flag}`;return Li({command_path:n,display_name:`${n} lifecycle`,token_kind:"action",token:e,allowed:Object.keys(n_),retry_command:i,message_suffix:`. Did you mean "${r.flag}"?`,fallback_candidates:[{source:"lifecycle_action",command:i,reason:`nearest lifecycle action for "${e}"`}]})},hR=[["install","install"],["uninstall","uninstall"],["explore","explore"],["manage","manage"],["describe","describe"],["reload","reload"],["doctor","doctor"],["catalog","catalog"],["init","init"],["scaffold","init"],["adopt","adopt"],["adoptAll","adopt-all"],["activate","activate"],["deactivate","deactivate"],["migrate","migrate"]],n_={doctor:"doctor",reload:"reload",catalog:"catalog",init:"init",scaffold:"init",explore:"explore",manage:"manage",migrate:"migrate",list:"explore","":"explore"},_R=e=>n_[e]??null,gR=(e,t)=>{let n=[...new Set(hR.filter(([r])=>t[r]===!0).map(([,r])=>r))];if(n.length===0){if(e===void 0)return"explore";let r=_R(e.trim().toLowerCase());if(r)return r;throw fR(e,t)}if(n.length>1)throw new _("Extension action flags are mutually exclusive.",g.USAGE);return n[0]},yR=e=>{let t=e.project===!0||e.local===!0,n=e.global===!0;if(t&&n)throw new _('Options "--project/--local" and "--global" are mutually exclusive.',g.USAGE);return n?"global":"project"},wR=[e=>e?null:{status:"skipped_unmanaged",reason:"extension_not_managed"},e=>e&&!["github","npm"].includes(e.source.kind)?{status:"skipped_non_github",reason:`managed_source_kind_${e.source.kind}`}:null,e=>{let t=typeof e?.update_error=="string"?e.update_error.trim():"";return t.length>0?{status:"failed",reason:t}:null},e=>{let t=e;return(typeof t.last_update_check_at=="string"?t.last_update_check_at.trim():"").length===0?null:{status:"checked",reason:{true:"update_available",false:"up_to_date"}[String(t.update_available)]??"checked_without_commit_baseline"}}],r_=e=>{for(let t of wR){let n=t(e);if(n)return n}return{status:"not_checked",reason:"no_update_check_recorded"}},i_=(e,t,n,r)=>{let i=n??{};return{name:e.name,directory:e.directory,version:e.version,entry:e.entry,scope:t,active:e.enabled,enabled:e.enabled,runtime_active:null,activation_status:"unknown",contributions:i.contributions,managed:!!n,source:i.source,update_available:i.update_available,last_update_check_at:i.last_update_check_at,last_update_remote_commit:i.last_update_remote_commit,last_update_remote_version:i.last_update_remote_version,update_error:i.update_error,...r.status==="failed"&&i.update_check_timeout_ms!==void 0?{update_check_timeout_ms:i.update_check_timeout_ms}:{},update_check_status:r.status,update_check_reason:r.reason}},vR=(e,t,n,r)=>{let i=Object.assign({name:e,manifest_version:"unknown",manifest_entry:"unknown"},r),o=r?e_(n,r.name):!1;return{warning:`extension_manifest_missing:${t}:${e}`,summary:i_({name:i.name,directory:e,version:i.manifest_version,entry:i.manifest_entry,enabled:o},t,r,r_(r))}},kR=async(e,t,n,r,i,o)=>{let s=Fe.join(e,t),a=Fe.join(s,"manifest.json"),c=o.get(R(t));if(!await P(a))return vR(t,n,r,c);let d=Symbol("invalid-extension-manifest-json"),l=await Bn.readFile(a,"utf8").then(p=>JSON.parse(p)).catch(()=>d);if(l===d)return{warning:`extension_manifest_invalid_json:${n}:${t}`};let u=Ia(l);if(!u)return{warning:`extension_manifest_invalid:${n}:${t}`};let m=i.get(R(u.name))??o.get(R(t));return{summary:i_({name:u.name,directory:t,version:u.version,entry:u.entry,enabled:e_(r,u.name)},n,m,r_(m))}},dt=async(e,t,n,r)=>{if(!await P(e))return{extensions:[],warnings:[]};let o=(await Bn.readdir(e,{withFileTypes:!0})).filter(l=>l.isDirectory()).map(l=>l.name).sort((l,u)=>l.localeCompare(u)),s=new Map(r.entries.map(l=>[R(l.name),l])),a=new Map(r.entries.map(l=>[R(l.directory),l])),c=[],d=[];for(let l of o){let u=await kR(e,l,t,n,s,a);u.warning&&c.push(u.warning),u.summary&&d.push(u.summary)}return{extensions:d.sort((l,u)=>l.name.localeCompare(u.name)),warnings:c.sort((l,u)=>l.localeCompare(u))}},bR=Yl(),xR=(e,t)=>[t.package,t.kind==="builtin"?t.name:void 0].find(n=>n?.trim())?.trim()??e,SR=(e,t,n,r)=>{let i=n.command_paths.map(a=>`pm ${a} --help`),o=r?.error.toLowerCase().includes("@unbrained/pm-cli")===!0,s=n.command_paths.length>0?[...i]:["Run pm package doctor --project --detail deep if expected package commands are missing."];return o&&s.unshift("Install @unbrained/pm-cli in the target workspace so declarative package runtime imports resolve, then reinstall the package."),{package_name:xR(e,t),extension_name:e,command_paths:n.command_paths,action_paths:n.action_paths,help_commands:i,next_steps:s,...o?{sdk_dependency_status:"missing"}:{}}},ER=e=>{let t=e.trace,n={layer:e.layer,name:e.name,entry_path:e.entry_path,error:e.error};return t&&(n.trace=Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0)),t.missing_capability&&(n.missing_capability=t.missing_capability),t.hint&&(n.hint=t.hint)),n},o_=e=>e.map(t=>ER(t)).sort((t,n)=>`${t.layer}:${t.name}`.localeCompare(`${n.layer}:${n.name}`)),s_=(e,t,n)=>{let r=R(e);return t.find(i=>(n===void 0||i.layer===n)&&R(i.name)===r)},RR=(e,t,n,r)=>n.find(o=>o.scope===t&&R(o.name)===R(e))?.activation_status??(r?"failed":"unknown"),a_=(e,t,n,r,i)=>bR.enqueue(async()=>{let o=process.env.PM_CLI_PACKAGE_ROOT,s=await Bn.mkdtemp(Fe.join(t,".pm-module-graph-"));process.env.PM_CLI_PACKAGE_ROOT=et(import.meta.url,["../.."]);try{let a=await nt({pmRoot:e,settings:n,cwd:process.cwd(),noExtensions:i.noExtensions===!0,reload_token:gs(),cache_bust:!0,module_graph_snapshot_root:s}),c=await rt({...a}),d=[...a.failed.map(u=>({layer:u.layer,name:u.name,entry_path:u.entry_path,error:u.error})),...o_(c.failed)],l=Object.fromEntries(a.loaded.map(u=>[R(u.name),nl(Dn(c,{extensionName:u.name}))]));return{installed:ho(r,a,c),warnings:[...a.warnings,...c.warnings],activation_failures:d,extensions_disabled:a.disabled_by_flag,item_type_registrations:c.registrations.item_types,contribution_inventories:l}}finally{await Bn.rm(s,{recursive:!0,force:!0}),o===void 0?delete process.env.PM_CLI_PACKAGE_ROOT:process.env.PM_CLI_PACKAGE_ROOT=o}}),Za=async(e,t,n,r)=>{let i=n.filter(c=>!c.managed),o=[...i].sort((c,d)=>{let l=c.name.localeCompare(d.name);return l!==0?l:c.directory.localeCompare(d.directory)}),s=r,a=[];for(let c of o){let d=Fe.join(e,c.directory),l=await Un(d),u=C(),m={kind:"local",input:c.name,location:d};s=Nr(s,{name:l.manifest.name,directory:c.directory,scope:t,manifest_version:l.manifest.version,manifest_entry:l.manifest.entry,capabilities:[...l.manifest.capabilities],contributions:l.manifest.contributions,installed_at:u,updated_at:u,source:m}),a.push({name:l.manifest.name,directory:c.directory,version:l.manifest.version,entry:l.manifest.entry,source:m})}return a.length>0&&await zn(e,s),{state:s,adopted_entries:a,unmanaged_candidates:o,already_managed_count:n.length-i.length}},AR=(e,t)=>{let n=M(process.cwd(),t.path),r=mn(n,process.cwd()),i=e==="global"?di(process.cwd()):n,o=e==="global"?r.global:r.project;return{pm_root:n,scope:e,settings_root:i,selected_root:o,roots:r}},ko=e=>{let t=[e.gh,e.github].filter(r=>typeof r=="string").map(r=>r.trim()).filter(Boolean),n=[...new Set(t)];if(n.length>1)throw new _('Options "--gh" and "--github" must match when both are provided.',g.USAGE);return n[0]},IR=e=>eR[e],CR=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",r=e==="install"?"source":"name",i=`${n} ${r}`,o=IR(e),s=`<${r}>`,a=`pm ${n} ${o} ${s}`;throw new _(`Action "${e}" requires ${i} input.`,g.USAGE,{code:"missing_lifecycle_target",required:`Provide a ${r} target for ${e}.`,examples:[`pm ${n} ${e} ${s}`,a,`pm ${n} --help`],recovery:{attempted_command:`pm ${n} ${e}`,suggested_retry:a,fallback_candidates:[{source:"lifecycle_action",command:a,reason:`flag-form ${e} command with required ${r} target`}]}})},bo=(e,t,n={})=>{let r=e?.trim();if(r)return r;if(t==="init")throw new _('Action "init" requires a scaffold target path (for example: pm package init ./my-package or pm extension init ./my-extension).',g.USAGE);return CR(t,n)},$R=(e,t)=>{let n=new Set([...t.registrations.item_types.map(r=>({entry:r,count:r.types.length})),...t.registrations.item_fields.map(r=>({entry:r,count:r.fields.length}))].filter(({count:r})=>r>0).map(({entry:r})=>`${r.layer}:${R(r.name)}`));return e.loaded.filter(r=>(r.activation?.commands??[]).length>0).filter(r=>n.has(`${r.layer}:${R(r.name)}`)).map(r=>`extension_schema_narrow_activation:${r.layer}:${r.name}`).filter((r,i,o)=>o.indexOf(r)===i).sort((r,i)=>r.localeCompare(i))},TR=(e,t)=>{let r=[{triggered:t.strictExit===!0||t.failOnWarn===!0,allowed:e==="doctor",message:"--strict-exit and --fail-on-warn are only valid with --doctor."},{triggered:t.trace===!0,allowed:e==="doctor",message:"--trace is only valid with --doctor."},{triggered:t.watch===!0,allowed:e==="reload",message:"--watch is only valid with --reload."},{triggered:t.runtimeProbe===!0,allowed:e==="manage",message:"--runtime-probe is only valid with --manage."},{triggered:t.fixManagedState===!0,allowed:e==="manage"||e==="doctor",message:"--fix-managed-state is only valid with --manage or --doctor."},{triggered:t.isolated===!0||t.ignoreGlobal===!0,allowed:e==="doctor",message:"--isolated and --ignore-global are only valid with --doctor."},{triggered:t.capability!==void 0,allowed:e==="init",message:"--capability is only valid with --init/--scaffold."},{triggered:t.declarative===!0,allowed:e==="init",message:"--declarative is only valid with --init/--scaffold."},{triggered:t.dryRun===!0,allowed:e==="migrate"||e==="install",message:"--dry-run is only valid with --migrate or --install."}].find(i=>i.triggered&&!i.allowed);if(r)throw new _(r.message,g.USAGE)},OR=(e,t,n)=>{let r=String(e??"").trim().toLowerCase(),i=[n.init,n.scaffold].includes(!0);return({doctor:["doctor"],reload:["reload"],catalog:["catalog"],init:i?[]:["init","scaffold"]}[t]??[]).includes(r)?void 0:e},PR=e=>[e.action==="catalog",typeof e.options.fields=="string",String(e.options.fields).trim().length>0].every(Boolean)?{project:"project",global:"global",selected:e.scope,settings_root:"project"}:{project:e.resolvedRoots.roots.project,global:e.resolvedRoots.roots.global,selected:e.resolvedRoots.selected_root,settings_root:e.resolvedRoots.settings_root},LR=(e,t,n)=>{let r={ok:n,action:e.action,scope:e.scope,roots:PR(e),warnings:[...new Set(e.warnings)].sort((i,o)=>i.localeCompare(o)),details:t};return e.action==="doctor"&&Object.defineProperty(r,tR,{value:!0,enumerable:!1,configurable:!1}),r},Qa=async(e,t,n)=>{let r=gR(e,t);TR(r,t);let i=OR(e,r,t),o=yR(t),s=AR(o,n),c={action:r,normalizedTarget:i,scope:o,resolvedRoots:s,warnings:[],options:t,global:n},l={...c,withResult:(u,m=!0)=>LR(c,u,m)};return await Th(()=>pA(l))},NR=(e,t)=>{let n=t.vocabulary??"extension",r=e.target_path.replace(/\\/g,"/"),i=hi(r),o={package:`Install dependencies: cd ${i}, then run "npm install"`,extension:`Install type-check dependencies: cd ${i}, then run "npm install -D typescript @types/node @unbrained/pm-cli"`},s={package:`Validate the package: cd ${i}, then run "npm run typecheck" and "npm test"`,extension:`Type-check the source (optional): cd ${i}, then run "npx tsc --noEmit"`},a=[];return[n==="package",t.declarative===!0].every(Boolean)&&a.push("Ensure the target workspace can resolve @unbrained/pm-cli before installing this declarative package."),[o[n],...a,`Install the scaffold: ${K(n==="package"?["install","--project",r]:["extension","--install","--project",r])}`,`Smoke-test command path: pm ${e.command_name}`,s[n],`Run diagnostics: ${n==="package"?"pm package doctor":"pm extension --doctor"} --project --detail summary`]},DR=async e=>{let{action:t,normalizedTarget:n,options:r,withResult:i}=e;if([ko(r),r.ref].filter(d=>typeof d=="string").map(d=>d.trim()).filter(Boolean).length>0)throw new _('Action "init" does not accept --gh/--github/--ref options.',g.USAGE);let a=bo(n,t,r),c=await Gf(a,r.vocabulary??"extension",r.capability,r.declarative===!0);return i({scaffolded:c.created_directory||c.files.some(d=>d.status==="created"),extension:{name:c.extension_name,command:c.command_name},capability:c.capability,style:c.style,target_path:c.target_path,created_directory:c.created_directory,files:c.files,next_steps:NR(c,r)})},MR=async e=>{let{normalizedTarget:t,resolvedRoots:n,warnings:r,options:i,global:o,withResult:s}=e;if(t!==void 0)throw new _('Action "reload" does not accept a target argument.',g.USAGE);let a=await T(n.settings_root),c=gs(),d=await nt({pmRoot:n.settings_root,settings:a,cwd:process.cwd(),noExtensions:o.noExtensions,reload_token:c,cache_bust:!0});r.push(...d.warnings);let l=await rt(d);r.push(...l.warnings);let u={reload:{token:c,cache_bust:!0,watch:i.watch===!0},loaded_count:d.loaded.length,failed_count:d.failed.length,activated_count:Math.max(0,d.loaded.length-l.failed.length),activation_failed_count:l.failed.length,loaded_extensions:d.loaded.map(m=>({name:m.name,layer:m.layer,version:m.version})),failed_extensions:d.failed.map(m=>({name:m.name,layer:m.layer,error:m.error})),activation_failures:l.failed.map(m=>({name:m.name,layer:m.layer,error:m.error}))};return i.watch===!0&&r.push("extension_reload_watch_hint:watch_mode_requested_non_interactive_single_pass_only"),s(u)},FR=async e=>{let{normalizedTarget:t,scope:n,options:r,global:i,withResult:o}=e;if(typeof t=="string"&&t.length>0&&t!=="catalog")throw new _('Action "catalog" does not accept a package target.',g.USAGE);return o(await xf(n,i,r))},jR=(e,t)=>({kind:"builtin",input:e,location:e,name:e,...t===null?{}:{package:t}}),HR=e=>({kind:"local",input:e.input,location:e.absolute_path}),UR=(e,t)=>({kind:"npm",input:e.input,location:t.resolved_subpath??".",package:t.npm_package,version:t.npm_version}),zR=(e,t)=>({kind:"github",input:e.input,location:t.resolved_subpath??e.subpath??".",repository:e.repository,owner:e.owner,repo:e.repo,ref:e.ref,subpath:t.resolved_subpath??e.subpath,commit:t.commit}),WR=(e,t,n,r)=>e?jR(e,t):n.kind==="local"?HR(n):n.kind==="npm"?UR(n,r):zR(n,r),qR=(e,t,n,r)=>e?e.manifest_version!==t?{installed_at:e.installed_at,updated_at:r}:hf(e.source,n)?{installed_at:e.installed_at,updated_at:e.updated_at}:{installed_at:e.installed_at,updated_at:r}:{installed_at:r,updated_at:r},GR=async(e,t)=>{let{scope:n,resolvedRoots:r,warnings:i}=e,{validated:o,destinationDirectoryName:s}=t,a=await T(r.settings_root),c=await be(r.selected_root);i.push(...c.warnings);let d=Fe.join(r.selected_root,s),l=await P(d),u=await Wn(o.directory,d);await Bn.mkdir(r.selected_root,{recursive:!0});let m=WR(t.bundledAliasName,t.bundledPackageName,t.installSource,t.resolvedSource),p=c.state.entries.find(w=>R(w.name)===R(o.manifest.name)),f=qR(p,o.manifest.version,m,C()),h=Nr(c.state,{name:o.manifest.name,directory:s,scope:n,manifest_version:o.manifest.version,manifest_entry:o.manifest.entry,capabilities:[...o.manifest.capabilities],contributions:o.manifest.contributions,...f,source:m}),y=t_(a,o.manifest.name);return u||await fh(o.directory,d),await uh(d),await mh(d),await zn(r.selected_root,h),y&&await Di(r.settings_root,a,"settings:write"),{settings:a,managedState:h,sourceRecord:m,destinationDirectory:d,destinationExists:l,installInPlace:u,activationChanged:y}},BR=async(e,t,n)=>{let r=n.filter(i=>R(i.name)===R(t)).flatMap(i=>i.types.map(o=>({name:o.name,folder:o.folder})));return e.scope==="project"&&r.length>0&&await Tr(e.resolvedRoots.pm_root,r,e.warnings,"install:type-folder"),r},JR=(e,t,n,r,i)=>{let o=s_(t,n.activation_failures,e.scope),s=RR(t,e.scope,n.installed,o),a=[!n.extensions_disabled,s==="ok"].every(Boolean);a||e.warnings.push(`extension_install_activation_failed:${e.scope}:${t}:${s}`);let c={true:{status:"ok",blocking_failure_count:0},false:{status:"degraded",blocking_failure_count:1}};return{activated:a,status:s,failure:o,verification:{status:c[String(a)].status,target_pm_root:e.resolvedRoots.pm_root,activation_status:s,activated:a,registered_commands:r.command_paths,registered_actions:r.action_paths,registered_item_types:i,module_graph_verification:"fresh_in_topology_snapshot",health:c[String(a)]}}},VR=async(e,t)=>{let{scope:n,resolvedRoots:r,warnings:i,global:o,withResult:s}=e,{validated:a,destinationDirectoryName:c}=t;return Bh({selectedRoot:r.selected_root,settingsRoot:r.settings_root,destinationDirectory:Fe.join(r.selected_root,c),sourceDirectory:a.directory,scope:n},async()=>{let d=await GR(e,t),l=await dt(r.selected_root,n,d.settings,d.managedState);i.push(...l.warnings);let u=await a_(r.pm_root,Fe.dirname(r.selected_root),d.settings,l.extensions,o);i.push(...u.warnings);let m=await BR(e,a.manifest.name,u.item_type_registrations),p=_h(a.manifest.name,u.installed),f=JR(e,a.manifest.name,u,p,m),h=u.contribution_inventories[R(a.manifest.name)];return h&&(d.managedState=await gf(r.selected_root,d.managedState,a.manifest.name,h)),s({extension:{name:a.manifest.name,version:a.manifest.version,entry:a.manifest.entry,capabilities:a.manifest.capabilities,directory:c},source:d.sourceRecord,source_resolution:t.sourceResolution,...t.installPlan?{install_plan:t.installPlan}:{},destination_path:d.destinationDirectory,overwritten:[d.destinationExists,!d.installInPlace].every(Boolean),installed_in_place:d.installInPlace,activated:f.activated,settings_changed:d.activationChanged,runtime_activation_status:f.status,command_paths:p.command_paths,action_paths:p.action_paths,contributions:h,command_discovery:SR(a.manifest.name,d.sourceRecord,p,f.failure),verification:f.verification,activation_diagnostics:{failed_count:u.activation_failures.length,failed:u.activation_failures,installed_extension_failed:f.failure??null}},f.activated)})},KR=async e=>{let{options:t,global:n,warnings:r,withResult:i}=e;if(typeof t.ref=="string"&&t.ref.trim().length>0)throw new _('Action "install all" does not accept --ref.',g.USAGE);let o=[],s=new Map;for(let a of await uo()){let c=await Dr(a),d=Fe.resolve(c),l=s.get(d);l===void 0&&(l=await Qa(a,{...t,install:!0},n),s.set(d,l)),o.push({alias:a,result:l})}return r.push(...o.flatMap(a=>a.result.warnings)),i(Hh(o,t.dryRun===!0),o.every(a=>a.result.ok))},YR=async(e,t,n)=>{let{resolvedRoots:r}=e,{bundledAliasName:i,bundledPackageName:o,installSource:s,sourceResolution:a}=await qh(t,n,e.options.ref,(await be(r.selected_root)).state.entries);if(a.ambiguous){let d=a.candidates.find(l=>l.kind==="npm");e.warnings.push(`extension_install_source_ambiguous:${t}:builtin:${i}:npm:${d.package}`)}let c=await Pf(s);try{let d=await Un(c.directory,{source_kind:s.kind,source_input:s.input,source_root:c.source_root}),l=co(d.manifest.name),u=e.options.dryRun===!0||s.kind==="local"&&i===null?await Uh(c,Fe.join(r.selected_root,l),e.scope,e.options.copyPlan):void 0;return e.options.dryRun===!0?e.withResult({dry_run:!0,installed:!1,activated:!1,extension:{name:d.manifest.name,version:d.manifest.version},source_resolution:a,install_plan:u}):await Wa(r.settings_root,l,()=>VR(e,{validated:d,destinationDirectoryName:l,bundledAliasName:i,bundledPackageName:o,sourceResolution:a,installSource:s,resolvedSource:c,installPlan:u}))}finally{c.cleanup&&await c.cleanup()}},XR=async e=>{let t=ko(e.options),n=t??bo(e.normalizedTarget,e.action,e.options);return[t===void 0,wf(n)].every(Boolean)?KR(e):YR(e,n,t)},ZR=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:i,options:o,withResult:s}=e;if(t!==void 0)throw new _('Action "adopt-all" does not accept a target argument.',g.USAGE);if(ko(o)!==void 0||typeof o.ref=="string"&&o.ref.trim().length>0)throw new _('Action "adopt-all" does not accept --gh/--github/--ref options.',g.USAGE);let c=await T(r.settings_root),d=await be(r.selected_root);i.push(...d.warnings);let l=await dt(r.selected_root,n,c,d.state);i.push(...l.warnings);let u=await Za(r.selected_root,n,l.extensions,d.state),m=await dt(r.selected_root,n,c,u.state);i.push(...m.warnings);let p=_o(n,i,m.extensions,o);i.push(...p.warnings);let f=new Map(m.extensions.map(w=>[`${R(w.name)}:${R(w.directory)}`,w])),h=new Map(m.extensions.map(w=>[R(w.directory),w])),y=u.adopted_entries.map(w=>{let v=R(w.directory),k=f.get(`${R(w.name)}:${v}`)??h.get(v);return{...w,...c_(k)}});return s({adopted_all:y.length>0,adopted_count:y.length,already_managed_count:u.already_managed_count,extensions:y,triage:p,warning_codes:p.warning_codes,update_health_partial:p.update_health_partial,update_health_coverage:p.update_health_coverage})},c_=e=>({update_check_status:e?.update_check_status??null,update_check_reason:e?.update_check_reason??null}),QR=(e,t,n,r)=>{if(e===void 0)return{kind:"local",input:t,location:n};let i=Mr(e,{forceGithub:!0,ref:r});if(i.kind!=="github")throw new _(`Invalid GitHub shorthand "${e}".`,g.USAGE);return{kind:"github",input:i.input,location:i.subpath??".",repository:i.repository,owner:i.owner,repo:i.repo,ref:i.ref,subpath:i.subpath}},eA=async e=>{let{action:t,normalizedTarget:n,scope:r,resolvedRoots:i,warnings:o,options:s,withResult:a}=e,c=bo(n,t,s),d=ko(s),l=await T(i.settings_root),u=await be(i.selected_root);o.push(...u.warnings);let m=await dt(i.selected_root,r,l,u.state);o.push(...m.warnings);let p=await Qh(m.extensions,c);if(!p)throw new _(`Installed extension "${c}" was not found in ${r} scope.`,g.NOT_FOUND);if(p.managed)return a({adopted:!1,already_managed:!0,extension:{name:p.name,directory:p.directory}});let f=Fe.join(i.selected_root,p.directory),h=await Un(f),y=C(),w=QR(d,c,f,s.ref),v=Nr(u.state,{name:h.manifest.name,directory:p.directory,scope:r,manifest_version:h.manifest.version,manifest_entry:h.manifest.entry,capabilities:[...h.manifest.capabilities],contributions:h.manifest.contributions,installed_at:y,updated_at:y,source:w});await zn(i.selected_root,v);let k=await dt(i.selected_root,r,l,v);o.push(...k.warnings);let x=k.extensions.find(E=>R(E.name)===R(h.manifest.name))??k.extensions.find(E=>R(E.directory)===R(p.directory));return a({adopted:!0,extension:{name:h.manifest.name,directory:p.directory,version:h.manifest.version,entry:h.manifest.entry},source:w,...c_(x)})},d_=async e=>{let{action:t,normalizedTarget:n,scope:r,resolvedRoots:i,warnings:o,options:s}=e,a=bo(n,t,s),c=await T(i.settings_root),d=await be(i.selected_root);o.push(...d.warnings);let l=await dt(i.selected_root,r,c,d.state);o.push(...l.warnings);let u=await Qh(l.extensions,a);if(!u)throw new _(`Installed extension "${a}" was not found in ${r} scope.`,g.NOT_FOUND);return{settings:c,managedStateRead:d,candidate:u}},tA=async e=>{let{resolvedRoots:t,withResult:n}=e,{settings:r,managedStateRead:i,candidate:o}=await d_(e),s=Fe.join(t.selected_root,o.directory);await Bn.rm(s,{recursive:!0,force:!0});let a={...i.state,updated_at:C(),entries:i.state.entries.filter(d=>R(d.name)!==R(o.name)&&R(d.directory)!==R(o.directory))};await zn(t.selected_root,a);let c=mR(r,o.name);return c&&await Di(t.settings_root,r,"settings:write"),n({removed:!0,extension:{name:o.name,directory:o.directory},destination_path:s,settings_changed:c})},Jh=async e=>{let{action:t,resolvedRoots:n,warnings:r,global:i,withResult:o}=e,{settings:s,candidate:a}=await d_(e),c=t==="activate"?t_(s,a.name):uR(s,a.name);c&&await Di(n.settings_root,s,"settings:write");let d=t==="activate"?await a_(n.pm_root,Fe.dirname(n.selected_root),s,[a],i).then(l=>(r.push(...l.warnings),s_(a.name,l.activation_failures,e.scope))):void 0;return d&&r.push(`extension_activate_failed:${e.scope}:${a.name}`),o({extension:{name:a.name,directory:a.directory},active:t==="activate"&&d===void 0,runtime_active:t==="activate"&&d===void 0,activation_failure:d??null,settings_changed:c,settings:{enabled:[...s.extensions.enabled],disabled:[...s.extensions.disabled]}},d===void 0)},nA=(e,t,n,r,i,o)=>{let s=r==="package"?"package":"extension",a={package:"doctor",extension:"--doctor"}[s],c=i?.adopted_entries.length??0,d=[[o!==null,o??""],[t>0,`Run pm ${s} explore --project and pm ${s} explore --global to inspect load failures.`],[n>0,`Review activation failures in pm ${s} ${a} --detail deep output.`],[c>0,`Managed-state fix adopted ${c} extension(s).`]];return[...new Set([...e,...d.filter(([l])=>l).map(([,l])=>l)].map(l=>l.trim()).filter(l=>l.length>0))]},Xa=e=>e.loaded.some(t=>t.layer==="global")||e.failed.some(t=>t.layer==="global")||e.warnings.some(t=>t.includes(":global:")),rA=(e,t,n,r)=>{if(e!=="project"||t||!Xa(r))return null;let i=n==="package"?"package":"extension";return`Global ${i} registrations are included in project diagnostics. For hermetic ${i} smoke tests, rerun pm ${i} doctor --project --isolated --detail deep --trace, or set PM_GLOBAL_PATH to a temporary directory for the whole test process.`},iA=(e,t,n)=>{if(String(e??"").trim().length>0)throw new _('Action "doctor" does not accept a target argument.',g.USAGE);let r=[n.isolated,n.ignoreGlobal].includes(!0);if([r,t==="global"].every(Boolean))throw new _("--isolated and --ignore-global are only valid with project-scope doctor diagnostics.",g.USAGE);let i=nh(n.detail),o=n.trace===!0;if([o,i!=="deep"].every(Boolean))throw new _("--trace requires --detail deep with --doctor.",g.USAGE);return{isolated:r,detailMode:i,includeTrace:o}},oA=async(e,t,n)=>{if(e.options.fixManagedState!==!0)return{state:n,fix:null};let r=await Za(e.resolvedRoots.selected_root,e.scope,t,n);return{state:r.state,fix:r}},sA=(e,t,n,r)=>{let i=n==="package"?"package":"extension";if(e!=="project")return{isolated:t,global_extensions_included:!1,global_diagnostics_present:Xa(r),rerun_command:null,pm_global_path_recipe:null};let o=`pm ${i} doctor --project --isolated --detail deep --trace`;return{isolated:t,global_extensions_included:!t,global_diagnostics_present:Xa(r),rerun_command:t?null:o,pm_global_path_recipe:`PM_GLOBAL_PATH=$(mktemp -d) pm ${i} doctor --project --detail deep --trace`}},aA=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:i,options:o,global:s,withResult:a}=e,{isolated:c,detailMode:d,includeTrace:l}=iA(t,n,o),u=await T(r.settings_root),m=await be(r.selected_root);i.push(...m.warnings);let p=await dt(r.selected_root,n,u,m.state);i.push(...p.warnings);let{state:f,fix:h}=await oA(e,p.extensions,m.state),y=await dt(r.selected_root,n,u,f);i.push(...y.warnings);let w=await nt({pmRoot:r.pm_root,settings:u,cwd:process.cwd(),noExtensions:s.noExtensions===!0,ignoreGlobalExtensions:c}),v=await rt({...w,loaded:w.loaded}),k=await Wh(r.pm_root);i.push(...k.warnings,...w.warnings),i.push(...Qf(w.failed)),i.push(...v.warnings),i.push(...eh(v.failed)),i.push(...th(w,v)),i.push(...gh(v,w)),i.push(...$R(w,v)),i.push(...yh(v));let x=ho(y.extensions,w,v),E=ih(n,x,w.loaded.map(H=>({layer:H.layer,name:H.name})),w.failed.map(H=>({name:H.name})),w.disabled_by_flag);i.push(...E.warnings);let A=x.filter(H=>H.update_check_status==="failed").map(H=>`extension_update_check_failed:${H.name}`);i.push(...A);let S=_o(n,i,x,o);i.push(...S.warnings);let b=[...S.warnings],D={mode:w.policy.mode,trust_mode:w.policy.trust_mode,require_provenance:w.policy.require_provenance,default_sandbox_profile:w.policy.default_sandbox_profile,sandbox_enforcement:"advisory: sandbox_profile/permissions are declaration-based load gates, not runtime isolation (ADR pm-6ef3)",trusted_extensions_count:w.policy.trusted_extensions.length,allowed_extensions_count:w.policy.allowed_extensions.length,blocked_extensions_count:w.policy.blocked_extensions.length,allowed_capabilities_count:w.policy.allowed_capabilities.length,blocked_capabilities_count:w.policy.blocked_capabilities.length,allowed_surfaces_count:w.policy.allowed_surfaces.length,blocked_surfaces_count:w.policy.blocked_surfaces.length,allowed_commands_count:w.policy.allowed_commands.length,blocked_commands_count:w.policy.blocked_commands.length,allowed_actions_count:w.policy.allowed_actions.length,blocked_actions_count:w.policy.blocked_actions.length,allowed_services_count:w.policy.allowed_services.length,blocked_services_count:w.policy.blocked_services.length,extension_override_count:w.policy.extension_overrides.length},j=Hr(b),$=Ur(),O=S.warning_codes,Q=rA(n,c,o.vocabulary,w),He=nA(S.remediation,w.failed.length,v.failed.length,o.vocabulary,h,Q),Ue=sA(n,c,o.vocabulary,w),we={status:S.status,scope:n,warning_count:S.warning_count,warning_codes:O,total_extensions:x.length,managed_total:x.filter(H=>H.managed).length,enabled_total:x.filter(H=>H.enabled).length,active_total:x.filter(H=>H.active).length,unmanaged_loaded_extension_count:S.unmanaged_loaded_extension_count,unmanaged_action_required_extension_count:S.unmanaged_action_required_extension_count,unmanaged_expected_extension_count:S.unmanaged_expected_extension_count,runtime_active_total:x.filter(H=>H.runtime_active===!0).length,activation_status_totals:{ok:x.filter(H=>H.activation_status==="ok").length,failed:x.filter(H=>H.activation_status==="failed").length,not_loaded:x.filter(H=>H.activation_status==="not_loaded").length,unknown:x.filter(H=>H.activation_status==="unknown").length},unknown_capability_count:j.length,capability_contract_version:$.version,update_available_total:S.update_available_total,update_check_status_totals:S.update_check_status_totals,update_health_coverage:S.update_health_coverage,update_health_partial:S.update_health_partial,update_check_failed_total:x.filter(H=>H.update_check_status==="failed").length,load_failure_count:w.failed.length,activation_failure_count:v.failed.length,load_failures:Ha(w.failed),activation_failures:Ha(v.failed),blocking_failure_count:w.failed.length+v.failed.length,has_blocking_failures:w.failed.length+v.failed.length>0,consistency_warning_count:E.warnings.length,trace_enabled:l,isolation:Ue,policy:D,remediation:He},$t=h?{requested:!0,applied:h.adopted_entries.length>0,adopted_count:h.adopted_entries.length,already_managed_count:h.already_managed_count,adopted_extensions:h.adopted_entries.map(H=>H.name)}:{requested:!1,applied:!1,adopted_count:0,already_managed_count:y.extensions.filter(H=>H.managed).length,adopted_extensions:[]},ze={mode:d,summary:we,triage:S,trace_enabled:l,capability_contract:$,capability_guidance:j,managed_state_fix:$t,author_manifest:k,isolation:Ue,policy:w.policy};if(d==="deep"){let H=l?v.failed:v.failed.map(z=>{let{trace:Ee,...mt}=z;return mt});ze.deep={warnings:b,warning_codes:O,capability_contract:$,capability_guidance:j,trace_enabled:l,managed_state:{path:m.path,count:f.entries.length,entries:f.entries},installed_extensions:x,load:{roots:w.roots,policy:w.policy,warnings:w.warnings,failed:w.failed,loaded:w.loaded.map(z=>({layer:z.layer,directory:z.directory,name:z.name,version:z.version,entry:z.entry,priority:z.priority}))},activation:{failed:H,warnings:v.warnings,hook_counts:v.hook_counts,registration_counts:v.registration_counts,parser_override_count:v.parser_override_count,preflight_override_count:v.preflight_override_count,service_override_count:v.service_override_count,renderer_override_count:v.renderer_override_count},consistency:E.summary},l&&(ze.deep.trace={activation_failures:v.failed.filter(z=>z.trace!==void 0).map(z=>({layer:z.layer,name:z.name,entry_path:z.entry_path,error:z.error,method:z.trace.method,command:z.trace.command,capability:z.trace.capability,missing_capability:z.trace.missing_capability,registration_index:z.trace.registration_index,expected_schema:z.trace.expected_schema,hint:z.trace.hint,received:z.trace.received}))})}return a(ze)},cA=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:i,options:o,global:s,withResult:a}=e,c=await T(r.settings_root),d=await nt({pmRoot:r.pm_root,settings:c,cwd:process.cwd(),noExtensions:s.noExtensions===!0}),l=await rt(d);i.push(...d.warnings),i.push(...l.warnings);let u=Jf(t,d,l);if(t!==void 0&&u.extensions.length===0){let m=o.vocabulary==="package"?"package":"extension",p=[...new Set(d.loaded.map(h=>o.vocabulary==="package"&&typeof h.source_package=="string"&&h.source_package.trim().length>0?h.source_package.trim():h.name))].sort((h,y)=>h.localeCompare(y)),f=p.length>0?` Loaded ${m} names: ${p.join(", ")}.`:"";throw new _(`No loaded ${m} named "${t}" was found in ${n} scope.${f} Run pm ${m} explore to list discovered ${m}s.`,g.NOT_FOUND)}return a({target:u.target,total:u.total,extensions:u.extensions,union:u.union,command_ownership:u.command_ownership})},dA=async(e,t,n)=>{let r=n,i=null;if([e.action==="manage",e.options.fixManagedState===!0].every(Boolean)&&(i=await Za(e.resolvedRoots.selected_root,e.scope,t,n),r=i.state),e.action==="manage"){let o=e.options.fixManagedState===!0;r=await Dh(r,e.options.offline,o?Ga:qn(),!o)}return{state:r,fix:i}},lA=async(e,t,n)=>{let r=await nt({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),i=await rt({...r,loaded:r.loaded});return e.warnings.push(...r.warnings,...i.warnings),{installed:ho(n,r,i),failures:o_(i.failed),summary:{requested:!0,executed:!0,reason:e.action==="explore"?"explore_defaults_to_runtime_probe":e.options.runtimeProbe===!0?"runtime_probe_requested":"manage_defaults_to_runtime_probe",load_failure_count:r.failed.length,activation_failure_count:i.failed.length,warning_count:[...new Set([...r.warnings,...i.warnings])].length,policy:r.policy}}},uA=(e,t)=>e?{requested:!0,applied:e.adopted_entries.length>0,adopted_count:e.adopted_entries.length,adopted_extensions:e.adopted_entries.map(n=>n.name),already_managed_count:e.already_managed_count}:{requested:!1,applied:!1,adopted_count:0,adopted_extensions:[],already_managed_count:t.filter(n=>n.managed).length},Vh=async e=>{let{action:t,scope:n,resolvedRoots:r,warnings:i,options:o,withResult:s}=e,a=await T(r.settings_root),c=lR(a.extensions.policy),d=await be(r.selected_root);i.push(...d.warnings);let l=await dt(r.selected_root,n,a,d.state);i.push(...l.warnings);let{state:u,fix:m}=await dA(e,l.extensions,d.state),p=await dt(r.selected_root,n,a,u);if(i.push(...p.warnings),t==="manage"&&o.offline===!0)for(let v of p.extensions)v.managed&&["npm","github"].includes(v.source.kind)&&(v.update_check_reason="offline_requested");if(t==="manage"){let v=p.extensions.filter(k=>k.update_check_status==="failed").map(k=>`extension_update_check_failed:${k.name}`);i.push(...v)}let f=await lA(e,a,p.extensions),h=f.installed,y=_o(n,i,h,o);i.push(...y.warnings);let w={total:h.length,managed_total:h.filter(v=>v.managed).length,enabled_total:h.filter(v=>v.enabled).length,active_total:h.filter(v=>v.active).length,extensions:h,triage:y,policy:c};return f.failures!==void 0&&(w.activation_diagnostics={failed_count:f.failures.length,failed:f.failures}),t==="explore"&&(w.runtime_probe=f.summary),t==="manage"&&(w.runtime_probe=f.summary,w.managed_state_fix=uA(m,h)),s(w)},Kh={init:DR,install:XR,uninstall:tA,explore:Vh,manage:Vh,describe:cA,reload:MR,doctor:aA,catalog:FR,adopt:eA,"adopt-all":ZR,activate:Jh,deactivate:Jh,migrate:jh},mA=e=>[e.action==="uninstall",e.action==="adopt",e.action==="adopt-all",e.action==="activate",e.action==="deactivate",e.action==="migrate",[["doctor","manage"].includes(e.action),e.options.fixManagedState===!0].every(Boolean)].some(Boolean),pA=e=>mA(e)?Wa(e.resolvedRoots.settings_root,`${e.action}-state`,()=>Kh[e.action](e)):Kh[e.action](e);import{execFile as fA}from"node:child_process";import{realpath as hA}from"node:fs/promises";import l_ from"node:path";import{promisify as _A}from"node:util";var gA=_A(fA),yA=32*1024*1024,wA=1e4,vA=["search/eval-queries.json"];function ec(e){return e.replaceAll("\\","/").replace(/\/+$/,"")}function kA(e){return`'${e.replaceAll("'","'\\''")}'`}async function bA(e,t=hA){return t(e).catch(()=>l_.resolve(e))}async function xo(e){let t=await Mt(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 bA(e),r=ec(l_.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 i=im.map(o=>`${r}/${ec(o)}`);try{let{stdout:o}=await gA("git",["ls-files","-z","--",...i.map(d=>`:(literal)${d}`)],{cwd:t,encoding:"utf8",maxBuffer:yA,windowsHide:!0,timeout:wA}),s=new Set(vA.map(d=>`${r}/${d}`)),a=[...new Set(o.split("\0").filter(d=>d.length>0&&!s.has(ec(d))))].sort((d,l)=>d.localeCompare(l)),c=i.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=>kA(`:(literal)${d}`)).join(" ")}`}}catch{return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:[],tracked_path_count:0,remediation_command:null}}}import u_ from"node:path";import{realpath as xA}from"node:fs/promises";async function m_(e,t){let n=t===null?[]:await am(t,[u_.relative(t,u_.join(await xA(e),"merge-receipts","00000000-0000-4000-8000-000000000000.json")).replaceAll("\\","/")]);return{rules:n,warnings:n.length>0?[`merge_artifacts_ignored:${n.length}`]:[]}}async function p_(e,t,n,r){if(t===null)return{audit:null,count:0,warnings:[]};let i=await $n(e,Cn(n),{gitWorkspaceRoot:t});if(i.status==="ok")return{audit:i,count:0,warnings:[]};let o=Math.max(1,i.missing_patterns.length+i.stale_patterns.length);return{audit:i,count:o,warnings:r?[`merge_fence_${i.status==="not_installed"?"missing":"drift"}:${o}`]:[]}}function f_(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{execFile as wI}from"node:child_process";import{randomUUID as vI}from"node:crypto";import{readdir as kI,realpath as zt,stat as bI}from"node:fs/promises";import ae from"node:path";import{promisify as xI}from"node:util";import SA from"fast-json-patch";function h_(e,t,n){let r=ht(e,t);if(r.ok)return r.document;let i=structuredClone(e);for(let[o,s]of t.entries()){let a=/^\/metadata\/([^/]*)$/u.exec(s.path)?.[1],c=a!==void 0&&!Object.hasOwn(i.metadata,a.replaceAll("~1","/").replaceAll("~0","~"));if(c&&s.op==="remove")continue;let d=c&&s.op==="replace"?{...s,op:"add"}:s,l=ht(i,[d]);if(!l.ok)throw new _(`History union cannot rebase a scalar patch at ${n.branch} line ${n.line} (${n.op}), operation ${o+1} ${s.op} ${s.path}; preserve the source histories for manual recovery.`,g.CONFLICT,{code:"history_union_rebase_conflict",field:s.path,history_merge:{...n,patch_index:o,patch_path:s.path},nextSteps:["Preserve all three history inputs and both item snapshots. Review the named branch event against the merged replay state; do not drop the event or concatenate unchecked patches. After resolving the history and item deliberately, run pm history <id> --verify and pm merge reconcile --dry-run before committing."]});i=l.document}return i}var EA=Object.freeze({pm_item_scalar_missing:!0});function Jn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.keys(e).length===1&&e.pm_item_scalar_missing===!0}function V(e){return e===void 0?EA:e}function Ut(e){return Ce(I(e===void 0?{pm_item_scalar_presence:"missing"}:{pm_item_scalar_presence:"present",value:e}))}function tc(e,t){let n=Ne(e);if(n)throw new _(`History merge input (${t}) contains unresolved conflict markers at line ${n.line}. Merge drivers must receive clean per-side versions.`,g.GENERIC_FAILURE);let r=[];for(let[i,o]of e.split(/\r?\n/).entries()){let s=o.trim();if(s)try{let a=JSON.parse(s);if(typeof a!="object"||a===null||Array.isArray(a))throw new TypeError("history entry must be an object");r.push(a)}catch{throw new _(`History merge input (${t}) contains invalid JSON at line ${i+1}.`,g.GENERIC_FAILURE)}}return r}function Eo(e){if(e.op!=="history_repair"||Object.hasOwn(e,"bridge")||!Array.isArray(e.patch)||e.patch.length>0)return;let t=e.reanchor_evidence;if(Array.isArray(t))return t.map(n=>n!==null&&typeof n=="object"?n.record:void 0).reverse().find(n=>n!==null&&typeof n=="object"&&Object.hasOwn(n,"bridge"))}function pe(e){let t=Eo(e)??e;return RA(t)}function RA(e){return I({ts:e.ts,author:e.author,op:e.op,patch:e.patch,message:e.message??null,...Object.hasOwn(e,"bridge")?{bridge:e.bridge}:{}})}function k_(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&pe(e[r])===pe(t[r]);)r+=1;return r}function AA(e,t,n,r){let i=[...e,...n],o=new Map(i.map((u,m)=>[u,m])),s=new Map(i.map((u,m)=>[pe(u),m])),a=i.map(()=>new Set);for(let u of[e,t]){let m=u.map(p=>o.get(p)??s.get(pe(p)));for(let p=1;p<m.length;p+=1)m[p-1]!==m[p]&&a[m[p-1]].add(m[p])}let c=i.map(()=>0);for(let u of a)for(let m of u)c[m]+=1;let d=i.map((u,m)=>m).filter(u=>c[u]===0),l=[];for(;d.length>0;){d.sort((m,p)=>{let f=i[m],h=i[p],y=Vt(f.ts,h.ts),w=pe(f),v=pe(h);return y||Number(r.has(v))-Number(r.has(w))});let u=d.shift();l.push(i[u]);for(let m of a[u])c[m]-=1,c[m]===0&&d.push(m)}if(l.length!==i.length)throw new _("History union cannot preserve contradictory original branch event orders; leave the file unresolved for manual recovery.",g.GENERIC_FAILURE);return l}function __(e){return{entries:e,positions:new Map(e.map((t,n)=>[pe(t),n])),index:-1,document:Nt()}}function ac(e,t){let n=t??e.index;for(;e.index<n;){let r=ht(e.document,e.entries[e.index+1].patch);if(!r.ok)throw new _("History union cannot preserve a patch that does not apply in its original branch.",g.GENERIC_FAILURE);e.document=r.document,e.index+=1}return e.document}function g_(e,t){if(t!==void 0&&t>e.index+1)throw new _("History union cannot attribute multiple original branch events to one semantic identity; preserve the source histories for manual recovery.",g.GENERIC_FAILURE);return ac(e,t)}function IA(e,t,n){if(n===0)return;let r=__(e),i=__(t),o=ac(r,n-1);ac(i,n-1);let s=0,a=new Set([...E_,...R_]);return(c,d)=>{if(s++<n)return c.patch;let l=pe(c),u=g_(r,r.positions.get(l)),m=g_(i,i.positions.get(l)),p=vi(c.patch).filter(v=>{let[k,x]=v.path.slice(1).split("/");return k!=="metadata"||!a.has(x)}),f=r.positions.get(l),h=h_(d,p,{branch:f===void 0?"theirs":"ours",line:(f??i.positions.get(l))+1,op:c.op}),y=C_(o.metadata,u.metadata,m.metadata,"ours","latest_document_update",String(u.metadata.updated_at),String(m.metadata.updated_at));for(let v of a)Object.hasOwn(y.merged,v)?h.metadata[v]=y.merged[v]:delete h.metadata[v];VA(h.metadata,o.metadata,u.metadata,m.metadata);let w=wn({metadata:h.metadata,body:h.body});return SA.compare(d,w)}}function b_(e){let t=jl(e);return typeof t=="object"?I({bridge:t,patch:e.patch,before_hash:e.before_hash,after_hash:e.after_hash,item_hash_version:e.item_hash_version,hash_algorithm:e.hash_algorithm}):null}function cc(e,t,n,r=[]){let i=y_(e).positions,o=new Set;return[...t,...r].forEach((s,a)=>{let{occurrence:c}=y_(s),d=l=>CA(i,s,c,l);s.forEach((l,u)=>{l.replay_inexact===!0&&x_(o,d(u))}),n&&a<t.length&&$A(o,s,d)}),n||TA(o,e),o}function y_(e){let t=new Map,n=e.map((r,i)=>{let o=pe(r),s=t.get(o);return s===void 0?(t.set(o,[i]),0):(s.push(i),s.length-1)});return{positions:t,occurrence:n}}function CA(e,t,n,r){return e.get(pe(t[r]))?.[n[r]]}function x_(e,t){t!==void 0&&e.add(t)}function $A(e,t,n){for(let r of Es(t).segments){for(let s of Wl([r]))x_(e,n(s));let i=n(r.start),o=n(r.end);if(!(i===void 0||o===void 0))for(let s=i;s<o;s+=1)e.add(s)}}function TA(e,t){for(let n of Es(t).segments)if(n.exact)for(let r=n.start;r<n.end;r+=1)e.delete(r)}function dc(e,t){let n=!1;return{entries:e.map((i,o)=>i.replay_inexact===!0||!t.has(o)?i:(n=!0,ql(i))),changed:n}}function OA(e,t,n,r,i){let o=PA(e,t,n);if(o===null)return null;let s=[...e,...o],a=dc(s,cc(s,[e,t],!1,i)),c=e.every((u,m)=>a.entries[m]===u),d=a.entries.slice(e.length),l=r.endsWith(`
|
|
48
|
+
`)||d.length===0?"":`
|
|
49
|
+
`;return{merged:c?`${r}${l}${d.map(u=>`${JSON.stringify(u)}
|
|
50
|
+
`).join("")}`:Kt(a.entries),strategy:"equivalent_bridges",common_entries:n,entries_from_ours:e.length-n,entries_from_theirs:o.length,entries_total:s.length,reanchored:!1}}function PA(e,t,n){let r=e.slice(n),i=t.slice(n),o=new Set([...r,...i].map(a=>b_(Eo(a)??a)));if(r.length===0||i.length===0||o.size!==1||o.has(null))return null;let s=S_(r,i,e.at(-1).after_hash);return[e,t,[...e,...s]].every(a=>ke(a).ok)?s:null}function lc(e){return e===void 0?null:b_(Eo(e)??e)}function S_(e,t,n){let r=new Set(e.map(pe));return t.filter(i=>!r.has(pe(i))).map(i=>{let o=Eo(i)??i,{bridge:s,replay_inexact:a,...c}=o;return Si(o,{...c,patch:[],before_hash:n,after_hash:n,...i.replay_inexact===!0?{replay_inexact:!0}:{}},{retainOriginalPatch:!0,retainPriorRecord:!0})})}function LA(e,t){let n=new Set(e.map(pe));return t.some(r=>n.has(pe(r)))}function NA(e,t,n){return!LA(e,t)&&n.every(r=>ke(r).ok)}function w_(e,t,n){let r=0;for(;lc(e[t+r])===n;)r+=1;return r}function DA(e,t){let n={ours:e,theirs:t,normalization:null},r=k_(e,t),i=lc(e[r]);if(i===null||lc(t[r])!==i)return n;let o=e.slice(r,r+w_(e,r,i)),s=t.slice(r,r+w_(t,r,i)),a=e.slice(r+o.length),c=t.slice(r+s.length);if(a.length===0&&c.length===0)return n;let d=S_(o,s,o.at(-1).after_hash),l=[...e.slice(0,r),...o,...d],u={ours:[...l,...a],theirs:[...l,...c]},m=[e,t,u.ours,u.theirs];return NA([...o,...s],[...a,...c],m)?{...u,normalization:{shared:r,neutralCopies:d.length}}:n}function MA(e,t){let n=e.entries_from_theirs+t.neutralCopies;return{...e,strategy:e.strategy==="union_reanchor"?"union_reanchor":"equivalent_bridges",common_entries:t.shared,entries_from_ours:e.entries_total-t.shared-n,entries_from_theirs:n}}function y1(e,t,n){let r=tc(e,"base"),i=[tc(t,"ours"),tc(n,"theirs")],{ours:o,theirs:s,normalization:a}=DA(i[0],i[1]),c=jA(r,o,s,a===null||a.neutralCopies===0?t:Kt(o),a===null?[]:i);return a===null?c:FA(MA(c,a),i[0],t)}function FA(e,t,n){let r=e.merged.split(`
|
|
51
|
+
`);return t.every((i,o)=>r[o]===JSON.stringify(i))?{...e,merged:`${n.replace(/(?<!\n)$/u,`
|
|
52
|
+
`)}${r.slice(t.length).join(`
|
|
53
|
+
`)}`}:e}function jA(e,t,n,r,i){let o=[e,t,n].map(h=>h.filter(y=>y.op==="create"));if(o[0].length===0&&o.slice(1).every(h=>h.length>0)||o.some(h=>h.length>1)||new Set(o.flat().map(pe)).size>1)throw new _("Duplicate item identity: history contains independent or unproven create events. Preserve both branches and assign distinct item ids before merging.",g.CONFLICT,{code:"item_identity_conflict"});let s=k_(t,n),a=h=>Kt(dc(h,cc(h,[t,n],!1,i)).entries);if(s===t.length&&s===n.length)return{merged:a(t),strategy:"identical",common_entries:s,entries_from_ours:0,entries_from_theirs:0,entries_total:t.length,reanchored:!1};if(s===n.length)return{merged:a(t),strategy:"fast_forward_ours",common_entries:s,entries_from_ours:t.length-s,entries_from_theirs:0,entries_total:t.length,reanchored:!1};if(s===t.length)return{merged:a(n),strategy:"fast_forward_theirs",common_entries:s,entries_from_ours:0,entries_from_theirs:n.length-s,entries_total:n.length,reanchored:!1};let c=t.slice(s),d=OA(t,n,s,r,i);if(d!==null)return d;let l=new Set(c.map(pe)),u=n.slice(s).filter(h=>!l.has(pe(h))),m=AA(c,n.slice(s),u,l),p=[...t.slice(0,s),...m],f=ki(dc(p,cc(p,[t,n],!0,i)).entries,void 0,{continuousHashSurface:!0,projectPatch:IA(t,n,s),callerMarksBridgeCoverage:!0});if(f.skippedOps>0)throw new _(`History union cannot preserve ${f.skippedOps} patch operation(s) after deterministic suffix ordering; leave the file unresolved for manual recovery.`,g.GENERIC_FAILURE);return{merged:Kt(f.entries),strategy:"union_reanchor",common_entries:s,entries_from_ours:c.length,entries_from_theirs:u.length,entries_total:f.entries.length,reanchored:!0}}function nc(e,t){let n=Ne(e);if(n)throw new _(`Relationship merge input (${t}) contains unresolved conflict markers at line ${n.line}. Merge drivers must receive clean per-side versions.`,g.GENERIC_FAILURE);let r=[];for(let[i,o]of e.split(/\r?\n/).entries()){let s=o.trim();if(!s)continue;let a;try{a=JSON.parse(s)}catch{throw new _(`Relationship merge input (${t}) contains invalid JSON at line ${i+1}.`,g.GENERIC_FAILURE)}if(typeof a!="object"||a===null||Array.isArray(a)||typeof a.eventId!="string"||typeof a.sequence!="number")throw new _(`Relationship merge input (${t}) line ${i+1} is not a relationship event (eventId + sequence required).`,g.GENERIC_FAILURE);r.push(a)}return r}function So(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
|
|
54
|
+
`)}
|
|
55
|
+
`}function HA(e){return e.map((t,n)=>({...t,sequence:n+1}))}function w1(e,t,n){nc(e,"base");let r=nc(t,"ours"),i=nc(n,"theirs"),o=Math.min(r.length,i.length),s=0;for(;s<o&&r[s].eventId===i[s].eventId;)s+=1;if(s===r.length&&s===i.length)return{merged:So(r),strategy:"identical",common_entries:s,entries_from_ours:0,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(s===i.length)return{merged:So(r),strategy:"fast_forward_ours",common_entries:s,entries_from_ours:r.length-s,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(s===r.length)return{merged:So(i),strategy:"fast_forward_theirs",common_entries:s,entries_from_ours:0,entries_from_theirs:i.length-s,entries_total:i.length,reanchored:!1};let a=r.slice(s),c=new Set(a.map(m=>m.eventId)),d=i.slice(s).filter(m=>!c.has(m.eventId)),l=[...a,...d].sort((m,p)=>{if(m.timestamp!==void 0&&p.timestamp!==void 0){let y=Vt(m.timestamp,p.timestamp);if(y!==0)return y}else{if(m.timestamp===void 0&&p.timestamp!==void 0)return 1;if(m.timestamp!==void 0)return-1}let f=c.has(m.eventId),h=c.has(p.eventId);return f!==h?Number(h)-Number(f):0}),u=HA([...r.slice(0,s),...l]);return{merged:So(u),strategy:"union_reanchor",common_entries:s,entries_from_ours:a.length,entries_from_theirs:d.length,entries_total:u.length,reanchored:!0}}var E_=["tags","dependencies","comments","notes","learnings","files","tests","test_runs","docs","reminders","events","deferred_fields"],R_=["acceptance_criteria"],UA=["updated_at"];function nn(e,t){return e===void 0||t===void 0?e===void 0&&t===void 0:I(e)===I(t)}function v_(e,t,n){let r=l=>Array.isArray(l)?l:[],i=new Set(r(e).map(l=>I(l))),o=r(t),s=new Set(o.map(l=>I(l))),a=r(n),c=new Set(a.map(l=>I(l))),d=o.filter(l=>{let u=I(l);return!i.has(u)||c.has(u)});for(let l of a){let u=I(l);!s.has(u)&&!i.has(u)&&d.push(l)}return d}function Gr(e){if(typeof e!="object"||e===null||Array.isArray(e))return I(e);let{provenance:t,...n}=e;return I(n)}function zA(e){if(typeof e!="object"||e===null||Array.isArray(e))return e;let t=e;return t.provenance?{...t,provenance:{...t.provenance,source_kind:"merge_union"}}:{...t,provenance:{source_kind:"merge_union"}}}function WA(e,t,n){let r=l=>Array.isArray(l)?l:[],i=new Set(r(e).map(Gr)),o=r(t),s=new Set(o.map(Gr)),a=r(n),c=new Set(a.map(Gr)),d=o.filter(l=>{let u=Gr(l);return!i.has(u)||c.has(u)});for(let l of a){let u=Gr(l);!s.has(u)&&!i.has(u)&&d.push(zA(l))}return d}function qA(e,t){return Vt(String(e),String(t))>=0?e:t}function uc(e,t,n,r){return nn(t,n)?{value:t,from_theirs:!1,conflict:!1}:nn(e,t)?{value:n,from_theirs:!0,conflict:!1}:nn(e,n)?{value:t,from_theirs:!1,conflict:!1}:{value:r==="theirs"?n:t,from_theirs:r==="theirs",conflict:!0}}function A_(e,t,n,r,i,o,s){let a=uc(e,t,n,r);if(!a.conflict)return{...a,conflict:!1};if(i==="preferred_side")return{...a,resolution_basis:"requested_preference",retained_side:a.from_theirs?"theirs":"ours"};let c=Vt(o,s);if(i==="latest_document_update"&&c!==0){let l=c<0;return{value:l?n:t,from_theirs:l,conflict:!0,resolution_basis:"document_updated_at",retained_side:l?"theirs":"ours"}}let d=I(V(n)).localeCompare(I(V(t)))<0;return{value:d?n:t,from_theirs:d,conflict:!0,resolution_basis:"stable_value_tiebreak",retained_side:d?"theirs":"ours"}}function rc(e){return{...e.metadata}}function ic(e,t,n){try{let r=$l(Lt(e,{...n,requireSupportedFormat:!0}),n),i=Object.entries(r.metadata).find(([,o])=>Jn(o))?.[0];if(i!==void 0)throw new TypeError(`metadata field ${i} uses the reserved missing-scalar evidence marker`);return r}catch(r){throw r instanceof _&&r.context?.code==="item_format_version_unsupported"?r:new _(`Item merge input (${t}) is not a readable item document: ${String(r)}`,g.GENERIC_FAILURE)}}function GA(e,t,n,r){return e==="tests"?WA(t,n,r):e==="deferred_fields"?I_(t,n,r):e==="acceptance_criteria"?v_(Pi(t),Pi(n),Pi(r)).join("; "):v_(t,n,r)}function I_(e,t,n){let r=c=>new Map((Array.isArray(c)?c:[]).map(d=>[String(d.field),d])),[i,o,s]=[r(e),r(t),r(n)],a=[];for(let c of[...new Set([...o.keys(),...s.keys()])].sort()){let[d,l,u]=[i.get(c),o.get(c),s.get(c)];if(l===void 0||u===void 0){a.push(l??u);continue}let m=uc(d,l,u,"ours");a.push(m.conflict&&I(u).localeCompare(I(l))<0?u:m.value)}return a}function BA(e){if(!e.unionFieldSet.has(e.field))return!1;let t=GA(e.field,e.baseValue,e.oursValue,e.theirsValue);return e.accumulator.merged[e.field]=t,nn(t,e.oursValue)||e.accumulator.unionFields.push(e.field),!0}function JA(e){let t=A_(e.baseValue,e.oursValue,e.theirsValue,e.preferred,e.conflictResolution,e.oursUpdatedAt,e.theirsUpdatedAt);t.value!==void 0&&(e.accumulator.merged[e.field]=t.value),t.conflict?(e.accumulator.conflictFields.push(e.field),e.accumulator.conflictDecisions.push({field:e.field,base:V(e.baseValue),ours:V(e.oursValue),theirs:V(e.theirsValue),retained:V(t.value),discarded:V(t.from_theirs?e.oursValue:e.theirsValue),retained_side:t.retained_side,resolution_basis:t.resolution_basis})):t.from_theirs&&e.accumulator.fieldsFromTheirs.push(e.field)}function C_(e,t,n,r,i,o,s){let a=new Set([...E_,...R_]),c=new Set(UA),d=[...new Set([...Object.keys(t),...Object.keys(n)])].sort((u,m)=>u.localeCompare(m)),l={merged:{},conflictFields:[],fieldsFromTheirs:[],unionFields:[],conflictDecisions:[]};for(let u of d){let m=e[u],p=t[u],f=n[u];if(!BA({field:u,baseValue:m,oursValue:p,theirsValue:f,unionFieldSet:a,accumulator:l})){if(c.has(u)){l.merged[u]=qA(p,f);continue}JA({field:u,baseValue:m,oursValue:p,theirsValue:f,preferred:r,conflictResolution:i,oursUpdatedAt:o,theirsUpdatedAt:s,accumulator:l})}}return $_(l.merged),l}function VA(e,t,n,r){let i=I_(t.deferred_fields,n.deferred_fields,r.deferred_fields);e.deferred_fields=i,$_(e),e.deferred_fields.length===0&&delete e.deferred_fields}function $_(e){Array.isArray(e.deferred_fields)&&(e.deferred_fields=e.deferred_fields.filter(t=>!Al(e,String(t.field))))}function v1(e,t,n,r={}){let i=r.preferred??"ours",o=r.conflictResolution??"preferred_side",s=ic(t,"ours",r),a=ic(n,"theirs",r);if(e.trim().length===0)throw new _("Duplicate item identity: add/add item documents have no common ancestor. Preserve both branches and assign distinct item ids before merging.",g.CONFLICT,{code:"item_identity_conflict",item_id:s.metadata.id});let c=ic(e,"base",r);if(c.metadata.id!==s.metadata.id||c.metadata.id!==a.metadata.id)throw new _("Duplicate or mismatched item identity: all merge sides must address the common ancestor's item id.",g.CONFLICT,{code:"item_identity_conflict",item_id:c.metadata.id});let d=rc(c),l=rc(s),u=rc(a),{merged:m,conflictFields:p,fieldsFromTheirs:f,unionFields:h,conflictDecisions:y}=C_(d,l,u,i,o,s.metadata.updated_at,a.metadata.updated_at),w=A_(c.body,s.body,a.body,i,o,s.metadata.updated_at,a.metadata.updated_at);w.conflict?(p.push("body"),y.push({field:"body",base:V(c.body),ours:V(s.body),theirs:V(a.body),retained:V(w.value),discarded:V(w.from_theirs?s.body:a.body),retained_side:w.retained_side,resolution_basis:w.resolution_basis})):w.from_theirs&&f.push("body");let v=m;return v.pm_format_version=El(Math.max(...[c.metadata,s.metadata,a.metadata,v].map(Sl))),{merged:Cl({metadata:v,body:w.value},r),conflict_fields:p,fields_from_theirs:f,union_fields:h,conflict_decisions:y,requested_preference:i,requested_preference_applied:o==="preferred_side",conflict_resolution:o}}function oc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function sc(e,t){let n=Ne(e);if(n)throw new _(`JSON merge input (${t}) contains unresolved conflict markers at line ${n.line}.`,g.GENERIC_FAILURE);if(e.trim().length!==0)try{return JSON.parse(e)}catch{throw new _(`JSON merge input (${t}) is not valid JSON.`,g.GENERIC_FAILURE)}}function KA(e,t,n){if(!Array.isArray(e)||!Array.isArray(t)||!Array.isArray(n))return null;let r=d=>{let l=new Map;for(let u of d){let m=I(u);l.set(m,(l.get(m)??0)+1)}return l},i=r(e),o=r(t),s=r(n);for(let[d,l]of i)if((o.get(d)??0)<l||(s.get(d)??0)<l)return null;let a=new Map(o),c=[];for(let d of n){let l=I(d),u=a.get(l)??0;u>0?a.set(l,u-1):c.push(d)}return{merged:[...t,...c],acceptedTheirs:c.length>0}}function YA(e,t,n,r,i,o,s){if(!oc(t)||!oc(n))return null;let a=oc(e)?e:{},c={},d=[...new Set([...Object.keys(t),...Object.keys(n)])].sort((l,u)=>l.localeCompare(u));for(let l of d){let u=i.length>0?`${i}.${l}`:l,m=XA(a,t,n,l,r,u,o,s);m!==void 0&&(c[l]=m)}return c}function T_(e,t,n,r,i,o,s){if(nn(t,n))return t;let a=KA(e,t,n);if(a!==null)return a.acceptedTheirs&&s.push(i),a.merged;let c=YA(e,t,n,r,i,o,s);if(c!==null)return c;let d=uc(e,t,n,r);return d.conflict?o.push(i):d.from_theirs&&s.push(i),d.value}function XA(e,t,n,r,i,o,s,a){let c=Object.prototype.hasOwnProperty.call(t,r),d=Object.prototype.hasOwnProperty.call(n,r),l=Object.prototype.hasOwnProperty.call(e,r);if(c&&d)return T_(e[r],t[r],n[r],i,o,s,a);if(c){if(l&&nn(e[r],t[r])){a.push(o);return}return l?(s.push(o),i==="theirs"?void 0:t[r]):t[r]}if(!(l&&nn(e[r],n[r])))return l?(s.push(o),i==="theirs"?n[r]:void 0):(a.push(o),n[r])}function k1(e,t,n,r={}){let i=r.preferred??"ours",o=sc(e,"base"),s=sc(t,"ours"),a=sc(n,"theirs"),c=[],d=[],l=T_(o,s,a,i,"",c,d);return{merged:`${JSON.stringify(l??null,null,2)}
|
|
56
|
+
`,conflict_paths:c,paths_from_theirs:d,preferred:i}}import Ao from"node:path";import{execFile as ZA}from"node:child_process";import{createHash as O_}from"node:crypto";import{readdir as QA}from"node:fs/promises";import eI from"node:path";import{promisify as tI}from"node:util";var St=tI(ZA),Ro=/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u;async function C1(e,t,n){let r=t.trim(),i=/^(['"])(.*)\1$/su.exec(r)?.[2]??r;for(let o of["rebase-merge","rebase-apply"])try{let{stdout:s}=await St("git",["rev-parse","--path-format=absolute","--git-path",`${o}/orig-head`],{cwd:e,timeout:1e4}),a=(await hr(s.trim(),128))?.trim();if(a===void 0||!Ro.test(a))continue;let{stdout:c}=await St("git",["rev-parse","--verify",`${a}:${i}`],{cwd:e,timeout:1e4}),d=c.trim();return{kind:"rebase",original_head:a,original_blob:d}}catch{}if(n!==void 0&&Object.keys(process.env).some(o=>/^GITHEAD_[a-f0-9]{40}(?:[a-f0-9]{24})?$/u.test(o)))try{let{stdout:o}=await St("git",["rev-parse","HEAD","ORIG_HEAD"],{cwd:e,timeout:1e4}),[s,a]=o.trim().split(/\r?\n/u);if(s!==a||!Ro.test(s))return;let{stdout:c}=await St("git",["rev-parse","--verify",`${s}:${i}`],{cwd:e,timeout:1e4}),d=c.trim(),l=O_(d.length===40?"sha1":"sha256").update(`blob ${Buffer.byteLength(n)}\0`).update(n).digest("hex");return d!==l?void 0:{kind:"merge",original_head:s,original_blob:d}}catch{}}function P_(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;return Object.keys(t).length===3&&(t.kind==="rebase"||t.kind==="merge")&&typeof t.original_head=="string"&&Ro.test(t.original_head)&&typeof t.original_blob=="string"&&Ro.test(t.original_blob)}async function L_(e,t,n,r){if(r!==void 0&&O_(n.original_blob.length===40?"sha1":"sha256").update(`blob ${Buffer.byteLength(r)}\0`).update(r).digest("hex")!==n.original_blob)return!1;try{let{stdout:i}=await St("git",["rev-parse","--absolute-git-dir"],{cwd:e,timeout:1e4}),o=new Set(["rebase-merge","rebase-apply","MERGE_HEAD","CHERRY_PICK_HEAD","REVERT_HEAD"]);if((await QA(i.trim())).some(d=>o.has(d)))return!1;let{stdout:s}=await St("git",["rev-parse","HEAD"],{cwd:e,timeout:1e4});if(s.trim()!==n.original_head)return!1;let{stdout:a}=await St("git",["rev-parse","--verify",`HEAD:${t}`],{cwd:e,timeout:1e4});if(a.trim()!==n.original_blob)return!1;let{stdout:c}=await St("git",["hash-object","--",eI.resolve(e,t)],{cwd:e,timeout:1e4});return c.trim()!==n.original_blob?!1:(await St("git",["diff","--cached","--quiet","HEAD","--",t],{cwd:e,timeout:1e4}),!0)}catch{return!1}}var nI=/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/u,rI=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u,Co=2048,iI=64,oI=1e5,sI=new Set(["version","id","item_path","item_id","requested_preference","requested_preference_applied","preferred","conflict_resolution","fields_from_theirs","union_fields","merged_field_hashes","decisions","state","created_at","reconciled_at","value_availability","value_policy","evidence_source","operation","settlement"]);function Et(e){return nI.test(e)}var aI=new Set(["field","base","ours","theirs","retained","discarded","retained_side","resolution_basis"]),$o="bounded_non_sensitive_scalars_v1",cI=new Set(["open","in_progress","blocked","closed","canceled"]),dI=new Set(["risk","confidence","severity"]),lI=new Set(["low","medium","high","critical"]),D_=new Map([["priority",new Set([0,1,2,3,4].map(I))],["status",new Set([...cI].map(I))],...[...dI].map(e=>[e,new Set([...lI].map(I))])]);function lt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function M_(e,t){return Object.keys(e).every(n=>t.has(n))}function Io(e){return Array.isArray(e)&&e.length<=Co&&e.every(t=>typeof t=="string"&&t.length>0&&t.length<=256)}function Br(e){let t=[{value:e,depth:0}],n=0;for(;t.length>0;){let r=t.pop();if(n+=1,n>oI||r.depth>iI)return!1;if(Array.isArray(r.value))for(let i of r.value)t.push({value:i,depth:r.depth+1});else if(lt(r.value))for(let i of Object.values(r.value))t.push({value:i,depth:r.depth+1})}return!0}function F_(e){if(!lt(e))return!1;let t=[void 0,"ours","theirs"],n=[void 0,"requested_preference","document_updated_at","stable_value_tiebreak"];return[M_(e,aI),typeof e.field=="string",typeof e.field=="string"&&e.field.length>0,typeof e.field=="string"&&e.field.length<=256,Object.hasOwn(e,"base"),Object.hasOwn(e,"ours"),Object.hasOwn(e,"theirs"),Object.hasOwn(e,"retained"),Object.hasOwn(e,"discarded"),Br(e.base),Br(e.ours),Br(e.theirs),Br(e.retained),Br(e.discarded),t.includes(e.retained_side),n.includes(e.resolution_basis)].every(Boolean)}function uI(e){if(!lt(e))return!1;let t=Object.entries(e);return t.length<=Co&&t.every(([n,r])=>n.length>0&&n.length<=256&&typeof r=="string"&&/^[a-f0-9]{64}$/u.test(r))}function mI(e,t){if(typeof e!="string"||e.length===0||e.length>4096||e.includes("\0")||e.includes("\\")||Ao.posix.isAbsolute(e))return!1;let n=Ao.posix.normalize(e);return n!==".."&&!n.startsWith("../")&&Ao.posix.basename(n,Ao.posix.extname(n))===t}function pI(e){return!Io(e.fields_from_theirs)||!Io(e.union_fields)||!Array.isArray(e.decisions)||e.decisions.length>Co||!e.decisions.every(F_)?!1:e.merged_field_hashes===void 0||uI(e.merged_field_hashes)}function fI(e){let t=[void 0,"ours","theirs"],n=[void 0,"preferred_side","stable_value_order","latest_document_update"],r=[void 0,"clone_local","hash_only","bounded_inline","mixed"],i=[void 0,"clone_local","durable"];return t.includes(e.requested_preference)&&t.includes(e.preferred)&&(e.requested_preference_applied===void 0||typeof e.requested_preference_applied=="boolean")&&n.includes(e.conflict_resolution)&&(e.state==="pending"||e.state==="reconciled")&&r.includes(e.value_availability)&&(e.value_policy===void 0||e.value_policy===$o)&&i.includes(e.evidence_source)}function hI(e){return typeof e.created_at=="string"&&yn(e.created_at)&&(e.reconciled_at===void 0||typeof e.reconciled_at=="string"&&yn(e.reconciled_at))}function N_(e,t){if(!lt(t)||Po(t)===void 0)return!1;let n=Object.keys(t);if(!n.every(o=>o==="pm_value_hash"||o==="pm_value"))return!1;if(!Object.hasOwn(t,"pm_value"))return n.length===1;let r=t.pm_value;return(r===null||D_.get(e)?.has(I(r))===!0)&&Ut(r)===t.pm_value_hash}function _I(e){if(!e.decisions.every(r=>r.base===null&&r.ours===null&&r.theirs===null&&N_(r.field,r.retained)&&N_(r.field,r.discarded)))return!1;let t=e.decisions.reduce((r,i)=>r+(lt(i.retained)&&Object.hasOwn(i.retained,"pm_value")?1:0)+(lt(i.discarded)&&Object.hasOwn(i.discarded,"pm_value")?1:0),0),n=t===0?"hash_only":t===e.decisions.length*2?"bounded_inline":"mixed";return e.value_availability===n&&(t===0||e.value_policy===$o)}function gI(e){return e.operation!==void 0&&!P_(e.operation)?!1:e.settlement===void 0||e.settlement==="original_git_state_restored"&&e.state==="reconciled"&&e.operation!==void 0}function yI(e){for(let t of["version","id","item_path","item_id","fields_from_theirs","union_fields","decisions","state","created_at"])if(!Object.hasOwn(e,t))return"required_fields";return e.version!==1||!M_(e,sI)?"required_fields":typeof e.id!="string"||!Et(e.id)?"receipt_id":typeof e.item_id!="string"||!rI.test(e.item_id)?"item_id":mI(e.item_path,e.item_id)?null:"item_path"}function To(e,t){if(!lt(e))return"required_fields";let n=yI(e);return n!==null?n:gI(e)?pI(e)?fI(e)?hI(e)?t==="durable"&&!_I(e)?"durable_decisions":null:"timestamps":"enums":"collections":"operation"}function Oo(e){if(!lt(e)||e.version!==1||e.value_policy!==void 0||!Array.isArray(e.decisions))return e;let t=(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0,n=(e.requested_preference==="ours"||e.requested_preference==="theirs")&&e.value_availability==="clone_local";return!t&&!n?e:{...e,decisions:e.decisions.map(r=>!lt(r)||!Object.hasOwn(r,"retained")||!Object.hasOwn(r,"discarded")?r:{base:V(void 0),ours:V(void 0),theirs:V(void 0),...r})}}function j_(e){if(!lt(e))return;if(!Io(e.fields_from_theirs))return"fields_from_theirs";if(!Io(e.union_fields))return"union_fields";if(!Array.isArray(e.decisions)||e.decisions.length>Co)return"decisions";let t=e.decisions.findIndex(n=>!F_(n));return t>=0?`decisions[${t}]`:"merged_field_hashes"}function mc(e,t){return To(e,t)===null}function Po(e){if(typeof e!="object"||e===null||Array.isArray(e)||!("pm_value_hash"in e))return;let t=e.pm_value_hash;return typeof t=="string"&&/^[a-f0-9]{64}$/u.test(t)?t:void 0}function pc(e,t){let n=Jn(t),r=Ut(n?void 0:t);return!n&&(t===null||D_.get(e)?.has(I(t))===!0)?{pm_value_hash:r,pm_value:t}:{pm_value_hash:r}}var SI=xI(wI),Lo=100;async function fc(e){try{let{stdout:t}=await SI("git",["rev-parse","--path-format=absolute","--git-path","pm-merge-receipts"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return t.trim()}catch{return null}}async function z_(e,t){let n=ae.dirname(ae.resolve(e,t));for(let r=0;r<12;r+=1){if(await P(ae.join(n,"settings.json")))return n;let i=ae.dirname(n);if(i===n)break;n=i}return null}function Vn(e){return ae.join(e,"merge-receipts")}function Wt(e){return`${e}.json`}async function H_(e){let t;try{t=e.readReceipt?await e.readReceipt(e.receiptPath):await hr(e.receiptPath,zi)}catch(o){if(Qe(o))return null;throw o}if(t===null)throw new Error(`Receipt ${e.receiptId} settlement source is not a bounded regular file.`);let n;try{n=Oo(JSON.parse(t))}catch{throw new Error(`Receipt ${e.receiptId} settlement source is not valid JSON.`)}if(!mc(n,e.evidenceSource)||n.id!==e.receiptId||e.settlement!==void 0&&n.operation===void 0||ae.basename(e.receiptPath)!==Wt(n.id))throw new Error(`Receipt ${e.receiptId} settlement source failed schema or identity validation.`);let{evidence_source:r,...i}=n;return{path:e.receiptPath,fingerprints:Vr(n),modern:n.value_policy!==void 0,content:`${JSON.stringify({...i,state:"reconciled",reconciled_at:e.reconciledAt,...e.settlement?{settlement:e.settlement}:{}},null,2)}
|
|
57
|
+
`}}function Jr(e,t=!1){return Ce(I({id:e.id,item_id:e.item_id,item_path:e.item_path,created_at:e.created_at,requested_preference:e.requested_preference??e.preferred??"ours",requested_preference_applied:e.requested_preference_applied??(e.conflict_resolution??"preferred_side")==="preferred_side",conflict_resolution:e.conflict_resolution??"preferred_side",fields_from_theirs:e.fields_from_theirs,union_fields:e.union_fields,merged_field_hashes:e.merged_field_hashes??null,operation:e.operation??null,decisions:t?e.decisions.map(n=>({field:n.field,retained_hash:Ce(I(V(n.retained))),discarded_hash:Ce(I(V(n.discarded)))})):No(e).decisions}))}function Vr(e){let t=[Jr(e)];return e.value_policy===void 0&&(e.value_availability===void 0||e.value_availability==="clone_local")&&t.push(Jr(e,!0)),t}function EI(e,t){let{reconciled_at:n,settlement:r,...i}=e;return t.state==="reconciled"?{...i,state:"reconciled",reconciled_at:t.reconciled_at,...t.settlement===void 0?{}:{settlement:t.settlement}}:{...i,state:"pending"}}async function RI(e,t,n){let r=new Map;for(let i of t){let o=e.get(i.id);if(i.state!=="reconciled"||o===void 0)continue;let s=r.get(o.item_id);if(s===void 0){try{s=await We(ae.join(n,"history",`${o.item_id}.jsonl`),o.item_id),ke(s).ok||(s=[])}catch{s=[]}r.set(o.item_id,s)}let a=o.settlement==="original_git_state_restored",c=I({...No(o),...a?{reason:o.settlement,operation:o.operation}:{}});if(!s.some(l=>{if(l.op!=="merge_reconcile"||l.record_hash_version===void 0)return!1;let u=l.context?.merge;if(typeof u!="object"||u===null||Array.isArray(u))return!1;let m=u[a?"abandoned_receipts":"receipts"];return Array.isArray(m)&&m.some(p=>I(p)===c)})){let{reconciled_at:l,settlement:u,...m}=o;e.set(o.id,{...m,state:"pending"})}}}function No(e){return{receipt_id:e.id,item_id:e.item_id,item_path:e.item_path,conflict_fields:e.decisions.map(t=>t.field),fields_from_theirs:e.fields_from_theirs,union_fields:e.union_fields,requested_preference:e.requested_preference??e.preferred??"ours",requested_preference_applied:e.requested_preference_applied??(e.conflict_resolution??"preferred_side")==="preferred_side",conflict_resolution:e.conflict_resolution,decisions:e.decisions.map(t=>({field:t.field,retained_hash:Po(t.retained)??Ut(Jn(t.retained)?void 0:t.retained),discarded_hash:Po(t.discarded)??Ut(Jn(t.discarded)?void 0:t.discarded)}))}}async function Z1(e){let t=await fc(e.cwd);if(t===null)return null;let n=e.itemPath.trim(),r=/^(['"])(.*)\1$/su.exec(n)?.[2]??n,i=ae.basename(r,ae.extname(r)),o={version:1,id:vI(),item_path:r.replaceAll("\\","/"),item_id:i,requested_preference:e.preferred,requested_preference_applied:(e.conflictResolution??"preferred_side")==="preferred_side",conflict_resolution:e.conflictResolution??"preferred_side",fields_from_theirs:[...e.fieldsFromTheirs],union_fields:[...e.unionFields],...e.mergedFieldHashes?{merged_field_hashes:{...e.mergedFieldHashes}}:{},decisions:structuredClone(e.decisions).map(a=>({...a,base:V(a.base),ours:V(a.ours),theirs:V(a.theirs),retained:V(a.retained),discarded:V(a.discarded)})),...e.operation?{operation:e.operation}:{},state:"pending",created_at:C(),value_availability:"clone_local"};await or(t),await ee(ae.join(t,Wt(o.id)),`${JSON.stringify(o,null,2)}
|
|
58
|
+
`);let s=await z_(e.cwd,o.item_path);if(s!==null){let a=Vn(s),c=o.decisions.map(u=>({field:u.field,base:null,ours:null,theirs:null,retained:pc(u.field,u.retained),discarded:pc(u.field,u.discarded),retained_side:u.retained_side,resolution_basis:u.resolution_basis})),d=c.reduce((u,m)=>u+(Object.hasOwn(m.retained,"pm_value")?1:0)+(Object.hasOwn(m.discarded,"pm_value")?1:0),0),l={...o,decisions:c,value_availability:d===0?"hash_only":d===c.length*2?"bounded_inline":"mixed",value_policy:$o};await or(a),await ee(ae.join(a,Wt(o.id)),`${JSON.stringify(l,null,2)}
|
|
59
|
+
`)}return o}async function U_(e,t){let n;try{n=await kI(e)}catch(a){let c=await AI(e,a);return{receipts:[],invalid_evidence_count:c?0:1,invalid_evidence:c?[]:[{evidence_source:t,reason:"directory_unreadable"}],invalid_evidence_truncated:!1}}let r=[],i=0,o=[],s=(a,c)=>{if(i+=1,o.length>=Lo)return;let d=a.slice(0,-5);o.push({evidence_source:t,reason:c.reason,...c.validation_path?{validation_path:c.validation_path}:{},...c.validation_error===void 0?{}:{validation_error:c.validation_error},...Et(d)?{receipt_id:d}:{candidate_name_hash:Ce(a)}})};for(let a of n.sort((c,d)=>c.localeCompare(d))){if(!a.endsWith(".json"))continue;let c=await II(e,a,t);c.receipt!==void 0?r.push(c.receipt):s(a,c)}return{receipts:r,invalid_evidence_count:i,invalid_evidence:o,invalid_evidence_truncated:i>o.length}}async function AI(e,t,n=bI){if(!F(t))return!1;let r=e;for(;;)try{return(await n(r)).isDirectory()}catch(i){if(!F(i))return!1;let o=ae.dirname(r);if(o===r)return!0;r=o}}async function II(e,t,n){let r;try{r=await hr(ae.join(e,t),zi)}catch{return{reason:"candidate_unreadable"}}if(r===null)return{reason:"candidate_not_bounded_regular_file"};let i;try{i=Oo(JSON.parse(r))}catch{return{reason:"candidate_invalid_json"}}let o=To(i,n);if(o!==null)return{reason:new Set(["receipt_id","item_id","item_path"]).has(o)?"identity_invalid":"schema_invalid",validation_error:o,...o==="collections"?{validation_path:j_(i)}:{}};let s=i;if(t!==Wt(s.id))return{reason:"identity_invalid",validation_error:"filename"};let{preferred:a,evidence_source:c,...d}=s;return{receipt:{...d,requested_preference:s.requested_preference??a??"ours",requested_preference_applied:s.requested_preference_applied??(s.conflict_resolution??"preferred_side")==="preferred_side",conflict_resolution:s.conflict_resolution??"preferred_side",evidence_source:n}}}async function CI(e,t,n){if(n.length===0)return[];let{readIndexedReceiptBlobs:r}=await import("./indexed-receipt-blobs-EGEJMG3G.js"),i=await $I(t),o=await r(i?.workspace??e,Vn(t),n.map(s=>Wt(s.id)),zi,i?.directory);return n.flatMap(s=>{try{let a=Oo(JSON.parse(o.get(Wt(s.id))??""));if(To(a,"durable")!==null)return[];let c=a,d=Vr(s);return c.id===s.id&&Vr(c).some(l=>d.includes(l))?[s.id]:[]}catch{return[]}})}async function $I(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT,n=process.env.PM_SOURCE_PM_PATH,r=process.env.PM_PATH;if(!(process.env.PM_SOURCE_CONTEXT_ACCESS!=="read_only"||!t||!n||!r))try{if(await zt(e)!==await zt(r))return;let i=ae.relative(await zt(t),await zt(n)),o=i===".."||i.startsWith(`..${ae.sep}`)||ae.isAbsolute(i),s=Vn(o?ae.join(await zt(t),".agents","pm"):await zt(n)),[a,c]=await Promise.all([zt(s),zt(Vn(n))]);return a!==c?void 0:{workspace:t,directory:s}}catch{return}}async function Rt(e,t={}){let n=await fc(e),r=n===null?{receipts:[],invalid_evidence_count:0,invalid_evidence:[],invalid_evidence_truncated:!1}:await U_(n,"clone_local"),i=t.pmRoot??ae.join(e,".agents","pm"),o=await U_(Vn(i),"durable"),s=new Map(o.receipts.map(u=>[u.id,u])),a=0,c=[];for(let u of r.receipts){let m=s.get(u.id);if(m!==void 0&&!(m.value_policy===void 0?Vr(u):[Jr(u)]).includes(Jr(m))){s.delete(u.id),a+=1,r.invalid_evidence.length+o.invalid_evidence.length+c.length<Lo&&c.push({evidence_source:"clone_local_and_durable",reason:"copy_provenance_mismatch",receipt_id:u.id});continue}s.set(u.id,m===void 0?u:EI(u,m))}await RI(s,o.receipts,i);let d=o.receipts.filter(u=>s.has(u.id)),l=new Set(await CI(e,i,d));return{durable_receipt_ids:[...l],unstaged_durable_receipt_ids:d.filter(u=>!l.has(u.id)).map(u=>u.id),receipts:[...s.values()].filter(u=>(t.includeReconciled||u.state==="pending")&&(t.includeLossless!==!1||u.decisions.length>0)).sort((u,m)=>u.created_at.localeCompare(m.created_at)),invalid_evidence_count:r.invalid_evidence_count+o.invalid_evidence_count+a,invalid_evidence:[...r.invalid_evidence,...o.invalid_evidence,...c].slice(0,Lo),invalid_evidence_truncated:r.invalid_evidence_truncated||o.invalid_evidence_truncated||r.invalid_evidence_count+o.invalid_evidence_count+a>Lo,clone_local_evidence_resolved:n!==null}}function W_(e,t,n){let r=new Set([...t?.durable_receipt_ids??[],...n?t?.unstaged_durable_receipt_ids??[]:[]]),i=[...e].filter(o=>!r.has(o));if(i.length!==0)throw new _(`Merge reconciliation refused ${i.length} receipt(s) without validated tracked evidence; no audit history was written.`,g.CONFLICT,{code:"merge_receipt_not_portable",required:"Every receipt cited by tracked history must have matching validated evidence in the Git index before any audit write.",recovery:{suggested_retry:"pm merge report --include-reconciled"},nextSteps:["Stage valid project sidecars after reviewing git diff, or use pm merge reconcile --stage for guarded lossless settlement. Restore missing original counterparts or preserve unrelated stale receipts outside the active store. Never copy private clone-local values into tracked evidence. Then rerun pm merge reconcile --dry-run."]})}function Kn(e){let t=[],n=[];for(let r of e)(Array.isArray(r.decisions)&&r.decisions.length>0?t:n).push(r);return{pendingDecisions:t,lossless:n}}async function Q1(e,t,n={}){let r=await fc(e);if(r===null){if(n.requireExisting===!0)throw new Error(`Receipt ${t.id} disappeared before settlement.`);return}let i=t.evidence_source??"clone_local";if(!mc(t,i))throw new Error("Merge receipt trusted settlement input failed schema validation.");let o=C(),s=ae.join(r,Wt(t.id)),a=await z_(e,t.item_path),c=a===null?null:ae.join(Vn(a),Wt(t.id)),l=(await Promise.all([H_({receiptPath:s,receiptId:t.id,evidenceSource:"clone_local",reconciledAt:o,settlement:n.settlement}),...c===null?[]:[H_({receiptPath:c,receiptId:t.id,evidenceSource:"durable",reconciledAt:o,settlement:n.settlement})]])).filter(m=>m!==null);if(l.length===0){if(n.requireExisting===!0)throw new Error(`Receipt ${t.id} disappeared before settlement.`);return}if(!(l.some(m=>m.modern)?[Jr(t)]:Vr(t)).some(m=>l.every(p=>p.fingerprints.includes(m))))throw new Error(`Receipt ${t.id} settlement copies disagree on immutable merge provenance.`);for(let m of l)await ee(m.path,m.content)}async function ez(e){let t=await Rt(e.cwd??process.cwd(),{...e,includeLossless:!0}),n=t.clone_local_evidence_resolved===!0&&t.invalid_evidence_count===0;return{ok:n,complete:n,count:t.receipts.length,invalid_evidence_count:t.invalid_evidence_count,invalid_evidence:t.invalid_evidence,invalid_evidence_truncated:t.invalid_evidence_truncated,clone_local_evidence_resolved:t.clone_local_evidence_resolved,receipts:t.receipts,generated_at:C()}}import{createHash as TI}from"node:crypto";import Do from"node:path";var OI="2026-08-09T16:15:18.000Z",G_=Symbol("pre-durable-disposition-eligible");function At(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function hc(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 q_(e){return At(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 B_(e,t){if(typeof e!="string")return!1;let n=Do.posix.normalize(e);return e.length<=4096&&!e.includes("\\")&&!e.includes("\0")&&!Do.posix.isAbsolute(e)&&n===e&&!n.startsWith("../")&&(Do.posix.basename(n)===`${t}.toon`||Do.posix.basename(n)===`${t}.md`)}function PI(e,t){return typeof e.receipt_id=="string"&&Et(e.receipt_id)&&(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0&&e.conflict_resolution===void 0&&e.item_id===t&&B_(e.item_path,t)}function J_(e){let t=e.conflict_fields,n=e.fields_from_theirs,r=e.union_fields,i=e.decisions,o=Array.isArray(i)?new Set(i.flatMap(s=>q_(s)?[s.field]:[])):new Set;return hc(t)&&hc(n)&&hc(r)&&Array.isArray(i)&&i.length>0&&i.length<=256&&Object.keys(i).length===i.length&&i.every(q_)&&o.size===i.length&&t.length===o.size&&t.every(s=>o.has(s))}function LI(e,t){return PI(e,t)&&J_(e)}function NI(e,t){return typeof e.receipt_id=="string"&&Et(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&&B_(e.item_path,t)&&J_(e)}function DI(e){return e[G_]===!0}function V_(e,t){if(!At(e)||!At(e.context))return[];let n=e.context.merge;return!At(n)||!Array.isArray(n.receipts)?[]:n.receipts.flatMap(r=>!At(r)||typeof r.receipt_id!="string"||r.receipt_id.trim().length===0?[]:[{receiptId:r.receipt_id,legacySummaryAccepted:LI(r,t),[G_]:NI(r,t),...typeof e.ts=="string"&&yn(e.ts)?{eventTimestamp:e.ts}:{}}])}function K_(e,t,n){if(!At(e)||e.op!=="merge_reconcile")return[];if(!At(e.context)||!At(e.context.merge))return[];let r=e.context.merge.missing_receipt_dispositions;return!Array.isArray(r)||r.length>256?[]:r.flatMap(i=>!At(i)||typeof i.receipt_id!="string"||!Et(i.receipt_id)||typeof i.original_history_line!="number"||!Number.isSafeInteger(i.original_history_line)||i.original_history_line<1||typeof i.original_event_ts!="string"||!yn(i.original_event_ts)||i.reason!=="legacy_clone_local_only"?[]:[{itemId:t,receiptId:i.receipt_id,originalHistoryLine:i.original_history_line,originalEventTimestamp:i.original_event_ts,auditHistoryLine:n,reason:i.reason}])}function Y_(e,t,n=[]){let r=new Map;for(let s of n){let a=`${s.itemId}\0${s.originalHistoryLine}\0${s.receiptId}\0${s.originalEventTimestamp}`;r.set(a,Math.max(r.get(a)??0,s.auditHistoryLine))}let i=s=>DI(s)&&s.eventTimestamp!==void 0&&Vt(s.eventTimestamp,OI)<0&&(r.get(`${s.itemId}\0${s.line}\0${s.receiptId}\0${s.eventTimestamp}`)??0)>s.line;return{missing:e.filter(s=>!s.legacySummaryAccepted&&!t.has(s.receiptId)&&!i(s)).map(s=>({item_id:s.itemId,history_line:s.line,...Et(s.receiptId)?{receipt_id:s.receiptId}:{receipt_reference_hash:TI("sha256").update(s.receiptId).digest("hex")}})),acceptedLegacyCount:e.filter(s=>s.legacySummaryAccepted).length,acceptedDispositionCount:e.filter(i).length}}import{isUtf8 as MI}from"node:buffer";import{readFile as FI}from"node:fs/promises";function jI(e){let t=e.trim(),n;try{n=JSON.parse(t)}catch{if(t.startsWith("{")&&t.includes("}"))throw new _("History salvage cannot discard a potentially complete record with trailing corruption.",g.CONFLICT,{code:"history_salvage_refused"});return{kind:"invalid"}}if(Ml(n))return{kind:"non_record"};if(Dl(n)!==null)throw new _("History salvage would conceal interior corruption or a malformed record.",g.CONFLICT,{code:"history_salvage_refused",required:"Recover the damaged record from version control or a backup; no bytes were changed."});let r=n;if(!Array.isArray(r.patch)||![r.ts,r.author,r.op,r.before_hash,r.after_hash].every(i=>typeof i=="string"))throw new _("History salvage requires complete history records before the invalid tail.",g.CONFLICT,{code:"history_salvage_refused"});return{kind:"record",entry:r}}function HI(e){return[...e].reverse().find(t=>Ge.includes(t.item_hash_version))?.item_hash_version}function UI(e){if(Ne(e))throw new _("Resolve history merge conflicts before salvage.",g.CONFLICT,{code:"history_salvage_refused"});let t=zI(e),n=WI(t);return{entries:t.entries,...n,...VI(e,t.nonRecord,t.invalidOffset,t.invalidLine,t.entries.length)}}function zI(e){let t={entries:[],nonRecord:[],invalidOffset:void 0,invalidLine:0},n=0;for(let[r,i]of e.split(`
|
|
60
|
+
`).entries()){let o=n;if(n+=i.length+1,!i.trim())continue;let s=jI(i);if(s.kind==="record"){if(t.invalidOffset!==void 0)throw new _("History salvage would discard a record or conceal interior corruption.",g.CONFLICT,{code:"history_salvage_refused",required:"Recover the damaged record from version control or a backup; no bytes were changed."});t.entries.push(s.entry)}else s.kind==="non_record"&&t.invalidOffset===void 0?t.nonRecord.push({start:o,end:Math.min(n,e.length),line:r+1}):t.invalidOffset===void 0&&(t.invalidOffset=o,t.invalidLine=r+1)}return t}function WI(e){let t=ke(e.entries),n=t.ok&&t.item_hash_version!==void 0;if(!(e.invalidOffset===void 0&&e.nonRecord.length>0)&&(e.entries.length===0||!n)){let i=e.entries.length>0&&e.invalidOffset===void 0;throw new _("History salvage requires a nonempty verified prefix.",g.CONFLICT,{code:"history_salvage_refused",verification_errors:t.errors,required:"Recover an intact history prefix from version control or a backup.",...i?{nextSteps:["Run pm history-repair <id> --append-only --dry-run: salvage has nothing to discard, and the chain needs a repair."]}:{}})}return{itemHashVersion:n?t.item_hash_version:HI(e.entries),verification:{ok:t.ok,errors:t.errors}}}function qI(e){try{return ve(e.hash_algorithm)}catch{let t=typeof e.hash_algorithm=="string";throw new _(t?"History salvage cannot anchor its record: the last kept record uses a digest algorithm this pm version cannot compute.":"History salvage cannot anchor its record: the last kept record's digest label is malformed.",g.CONFLICT,{code:"history_salvage_refused",required:t?"Upgrade pm to a version that reads the stream's digest algorithm; no bytes were changed.":"Recover the damaged record from version control or a backup; no bytes were changed.",nextSteps:[t?"Run npm install -g @unbrained/pm-cli@latest, then preview the salvage again.":"Run pm history <id> --verify --full to locate the record, then restore the stream from version control or a backup."]})}}function GI(e,t,n){let r=e.entries.at(-1);if(r===void 0)return e.prefix;let i=Tt,{item_hash_version:o,...s}=Ei({hashAlgorithm:qI(r),nowIso:C(),author:t,op:"history_salvage",before:i,after:i,message:n,context:{history_salvage:e.receipt}}),a=kn({...s,before_hash:r.after_hash,after_hash:r.after_hash,...e.itemHashVersion===void 0?{}:{item_hash_version:e.itemHashVersion}});return`${e.prefix}${JSON.stringify(a)}
|
|
61
|
+
`}function BI(e,t){if(typeof t.metadata.id=="string"&&t.metadata.id!==e)throw new _("History belongs to another item; salvage refused.",g.CONFLICT,{code:"history_salvage_refused"})}function JI(e,t){let n=t.verification.ok,r=Nt(),i=r;for(let o of t.entries){let s=n?ht(r,o.patch):void 0;r=s?.ok===!0?s.document:Ul(r,o.patch,o.op).document,BI(e,r),Object.keys(r.metadata).length>0&&(i=r)}return n&&t.entries.length>0?{final:Eu(t.entries,t.entries.length-1),lastItem:i}:{final:r,lastItem:i}}function VI(e,t,n,r,i){let o=n??e.length,s=[...t.map(({start:d,end:l})=>e.slice(d,l)),e.slice(o)].join(""),a="",c=0;for(let{start:d,end:l}of t)a+=e.slice(c,d),c=l;return a+=e.slice(c,o),a!==""&&!a.endsWith(`
|
|
62
|
+
`)&&(a+=`
|
|
63
|
+
`),s===""?{prefix:a,receipt:null}:{prefix:a,receipt:{first_invalid_line:t[0]?.line??r,discarded_bytes:Buffer.byteLength(s),discarded_sha256:Ce(s),retained_entries:i,...t.length>0?{non_record_lines:t.length}:{}}}}function KI(e,t,n){let r=t.metadata?.assignee;if(!(n||r===void 0||r===null||typeof r=="string"))throw new _(`The recorded owner of ${e} is not a name, so salvage cannot check ownership.`,g.CONFLICT,{code:"history_salvage_refused",item_id:e,reason:"owner_malformed",details:{reason:"owner_malformed"},required:"Recover the damaged record from version control or a backup, or override ownership deliberately; no bytes were changed.",nextSteps:[`Inspect ${e}'s raw history stream file or restore it from version control or a backup, or rerun the salvage with --force to override ownership.`]})}async function X_(e,t,n){if(!e)return{itemRaw:null,document:n,live:null};let r=await Pu(e,{schema:t.schema});return{itemRaw:r.raw,document:r.document??n,live:r.document}}function Z_(e,t,n){n.itemRaw!==null&&n.live===null&&Kl(e,t,n.itemRaw);let r=n.live??Tt;return lr(e,r,t),r}async function Q_(e){let t;try{t=await FI(e)}catch(n){if(F(n))return null;throw n}if(!MI(t))throw new _("History salvage requires UTF-8 input; recover binary corruption from a byte-preserving backup.",g.CONFLICT,{code:"history_salvage_refused"});return t.toString("utf8")}async function eg(e){let{subject:t,settings:n,options:r,author:i}=e;if([r.normalizeProvenance,r.auditOperation,r.auditContext,r.auditContextById,r.forceAuditEntry,r.mergeReceiptProof,r.mergeReceiptProofById].some(Boolean))throw new _("Tail salvage cannot be combined with other repair modes.",g.USAGE);let o=await Q_(t.historyPath);if(o===null)throw new _(`No history stream exists for ${t.id}.`,g.NOT_FOUND);await Be({path:t.historyPath,scope:"project"});let s=UI(o),a=JI(t.id,s),c=Rs(a.final),d=s.receipt===null?o:GI(s,i,r.message),l=await X_(t.located,n,Rs(a.lastItem));KI(t.id,l.document,r.force===!0);let u=ua({itemDocument:l.document,subjectId:t.id,author:i,force:r.force,settings:n}),m=r.dryRun===!0,p=s.receipt!==null;if(p&&!m){let f=await se(e.pmRoot,t.id,n.locks.ttl_seconds,i,!!r.force,n.governance.force_required_for_stale_lock,n.locks.wait_ms);try{let h=await Q_(t.historyPath),y=await ge(e.pmRoot,t.id,n.id_prefix,n.item_format,e.typeRegistry.type_to_folder),w=y?await B(y.itemPath):null;if(h!==o||w!==l.itemRaw)throw Z_(e.pmRoot,t.id,await X_(y,n,c)),new _("History or item changed while waiting for salvage lock; retry.",g.CONFLICT);let v=Z_(e.pmRoot,t.id,l);await to({historyPath:t.historyPath,historyRawUnderLock:o,nextHistoryRaw:d}),Ri(e.pmRoot,v,t.id),u.push(...await Y({path:t.historyPath,scope:"project",op:"history_salvage:history"}))}finally{await f()}}return XI(t,s,{changed:p,dryRun:m,warnings:u})}function YI(e,t){return t.entries.length===0?e.located===null?[]:[`history_stream_empty:${e.id}:run pm history-repair ${e.id}`]:t.verification.ok?[]:[`history_chain_unverified:${e.id}:run pm history-repair ${e.id} --append-only --dry-run, or pm history-repair ${e.id} --dry-run when a bridge refuses`]}function XI(e,t,n){let r=t.itemHashVersion,{ok:i,errors:o}=t.verification;return{id:e.id,dry_run:n.dryRun,changed:n.changed,history:{path:e.historyPath,entries_scanned:t.entries.length,chain_drift_before:!i,entries_rehashed:0,entries_patch_repaired:0,converted_replace_to_add:0,skipped_ops:0,reconciled_with_item:!1,audit_entry_added:n.changed&&!n.dryRun&&t.entries.length>0,verify_ok:i,verify_errors:o,item_hash_version_before:r??null,item_hash_version_after:r??1,version_disposition:"preserved"},item:{exists:e.located!==null,path:e.located?.itemPath??null,matched_chain_before:null},provenance_normalization:{requested:!1,changed:!1,events_changed:0,observations_removed:0,invalid_values:[]},...t.receipt?{salvage:t.receipt}:{},warnings:[...n.warnings,...YI(e,t)],generated_at:C()}}import{isUtf8 as ng}from"node:buffer";import{constants as _c}from"node:fs";import{lstat as ZI,open as QI,readFile as eC,stat as tC}from"node:fs/promises";import nC from"fast-json-patch";var rC=/^verify_failed:before_hash_mismatch:entry_(\d+)$/u,iC=/^verify_failed:patch_apply_failed:entry_(\d+)$/u;function xe(e,t,n,r=[]){throw new _(n,g.CONFLICT,{code:"history_append_only_repair_unavailable",item_id:e,reason:t,...r.length>0?{verification_errors:r}:{},required:"An append-only repair can only bridge chain breaks whose recorded links and patches still replay.",nextSteps:[`Run pm history-repair ${e} --dry-run to preview the rewriting repair, which re-anchors the recorded entries instead.`]})}function oC(e,t){if(t.ok)return null;let n=t.errors.length===1?t.errors[0]:"",r=iC.exec(n);r!==null&&xe(e,"patch_does_not_replay",`History entry ${r[1]} of ${e} does not apply without the unrecorded change, so only a rewriting repair can keep its effect.`,t.errors);let i=rC.exec(n),o=i===null?0:Number(i[1])-1;return o<1&&xe(e,"chain_failure_not_a_break",`History for ${e} fails verification for a reason an append-only bridge cannot name (${t.errors.join(", ")}).`,t.errors),o}function sC(e,t){let n=Nt();for(let[r,i]of t.entries()){let o=ht(n,i.patch);o.ok||xe(e,"patch_does_not_replay",`History entry ${r+1} of ${e} does not apply without the unrecorded change, so only a rewriting repair can keep its effect.`),n=o.document}return n}function aC(e,t,n,r,i){let o;try{o=ve(t.at(-1).hash_algorithm)}catch{xe(e,"chain_failure_not_a_break",`History for ${e} ends with record ${t.length}, whose digest algorithm this build cannot anchor on.`)}let s=[...t].reverse().find(m=>Ge.includes(m.item_hash_version))?.item_hash_version;if(s!==void 0)return{itemHashVersion:s,explicitVersion:!0,algorithm:o};let a=n===null?t:t.slice(0,n),c=ke(a).item_hash_version,d=t.at(-1).after_hash,l=Ge.filter(m=>[r,i].some(p=>p!==null&&qe(p,m,o).includes(d))),u=c;return l.includes(c)||(l.length===0&&xe(e,"hash_surface_ambiguous",`History for ${e} declares no hash epoch, and neither replay nor the on-disk item proves its last record's epoch.`),u=l.at(-1)),{itemHashVersion:u,explicitVersion:u!==1,algorithm:o}}function cC(e,t,n,r,i){let o=c=>qe(c,t.itemHashVersion,t.algorithm),s=o(i);if(new Set(s).size===1)return 0;let a=[o(r),s].map(c=>c.indexOf(n)).find(c=>c>=0);return a===void 0&&xe(e,"hash_surface_ambiguous",`History for ${e} records an epoch-2 hash variant that neither replay nor the on-disk item proves, so an appended record cannot anchor on it.`),a}function dC(e){let{entries:t,surface:n,finalReplay:r,itemReplay:i}=e,o=t.at(-1).after_hash,s=cC(e.id,n,o,r,i),a={hash_algorithm:n.algorithm,ts:C(),author:e.author,op:"history_repair",patch:nC.compare(r,i),before_hash:o,after_hash:qe(i,n.itemHashVersion,n.algorithm)[s],message:e.message,...n.explicitVersion?{item_hash_version:n.itemHashVersion}:{},...e.breaks.length===0?{}:{bridge:{version:1,breaks:e.breaks,segment_digest:Hl(t.slice(e.segmentStart),{hash_algorithm:n.algorithm})}}};return kn({...a,event_class:bi(a)})}function lC(e,t,n){return e!==void 0?e:`${[...t>0?[`history-repair bridged ${t} chain break${t===1?"":"s"} without rewriting recorded entries`]:[],...n?["reconciled replay with the on-disk item"]:[]].join("; ")}.`}function uC(e,t){if(t===null)return[];let n=[Ss(e[t-1],e[t])];for(let r=t+1;r<e.length;r+=1)e[r].before_hash!==e[r-1].after_hash&&n.push(Ss(e[r-1],e[r]));return n}async function tg(e,t,n,r){let[i,o]=[await t.stat(),await r(n).catch(()=>null)];(o===null||o.ino!==i.ino||o.dev!==i.dev)&&xe(e,"stream_changed",`History for ${e} was replaced while the repair appended; the bridge was not recorded, retry.`)}async function mC(e,t){let n=Buffer.alloc(t),r=0;for(;r<t;){let{bytesRead:i}=await e.read({buffer:n,offset:r,length:t-r,position:r});if(i===0)break;r+=i}return n.subarray(0,r)}async function rg(e,t,n,r,i=tC){let o=await QI(t,_c.O_RDWR|_c.O_APPEND|_c.O_NOFOLLOW).catch(s=>{throw Qe(s)&&xe(e,"stream_changed",`History for ${e} was removed after the repair verified it; retry.`),s.code==="ELOOP"&&og(e),s});try{let s=await o.readFile();ng(s)||xe(e,"stream_not_utf8",`History for ${e} is not valid UTF-8, so its bytes cannot be kept exactly.`);let a=s.toString("utf8");a!==n&&xe(e,"stream_changed",`History for ${e} changed after the repair verified it; retry.`);let d=`${a===""||a.endsWith(`
|
|
64
|
+
`)?"":`
|
|
65
|
+
`}${JSON.stringify(r)}
|
|
66
|
+
`;await o.appendFile(d),await o.sync(),await tg(e,o,t,i);let l=Buffer.concat([s,Buffer.from(d)]);(await mC(o,l.length+1)).equals(l)||xe(e,"stream_changed",`History for ${e} received another write while the repair appended; run pm health to re-verify the stream.`),await tg(e,o,t,i)}finally{await o.close()}}async function pC(e,t,n){let r;try{r=await hl(t,`${JSON.stringify(n)}
|
|
67
|
+
`,{sync:!0})}catch(i){throw i instanceof fl?new _(`History for ${e} cannot be rebuilt here: the tracker's filesystem cannot publish a new stream atomically (${i.code}).`,g.CONFLICT,{code:"history_append_only_repair_unavailable",item_id:e,reason:"stream_publish_unsupported",required:"Rebuilding an absent stream needs a filesystem with hard links; no stream was published.",nextSteps:[`Restore ${e}'s history stream from version control or a backup, or run the repair from a clone on a filesystem with hard links.`]}):i}r||xe(e,"stream_changed",`History for ${e} was created after the repair verified it; retry.`)}async function ig(e,t,n,r){await(n===null?pC(e,t,r):rg(e,t,n,r)),await dr(t)}function og(e){throw new _(`History for ${e} is a symbolic link, so an appended record could land in another stream.`,g.CONFLICT,{code:"history_append_only_repair_unavailable",item_id:e,reason:"stream_not_regular_file",required:"A history stream must be a regular file at its own path; no bytes were changed.",nextSteps:[`Restore ${e}'s own history stream as a regular file from version control or a backup. When none exists and the item is live, move the link aside and preview the rebuild with pm history-repair ${e} --dry-run.`]})}async function gc(e,t){(await ZI(t).catch(()=>null))?.isSymbolicLink()===!0&&og(e)}async function sg(e,t){await gc(e,t);let n=await eC(t).catch(()=>null);n!==null&&!ng(n)&&xe(e,"stream_not_utf8",`History for ${e} is not valid UTF-8, so its bytes cannot be kept exactly.`)}function ag(e,t,n,r){let{entries:i}=n,o=e.id,s=ke(i),a=oC(o,s),c=uC(i,a);c.length>0&&n.loadedItem===null&&xe(o,"item_missing",`History for ${o} has a chain break, but no on-disk item exists to anchor an append-only bridge.`);let d=sC(o,i),l=n.loadedItem===null?null:wn(n.loadedItem.document),u=l===null?void 0:r.analyzeDiscard(i,d,l),m=u!==void 0,p=c.length>0||m,f=aC(o,i,a,d,l),h=p?dC({id:o,entries:i,surface:f,finalReplay:d,itemReplay:l,author:n.author,message:lC(t.message,c.length,m),breaks:c,segmentStart:a??i.length}):null,y=h===null?i:[...i,h],w=ke(y);w.ok||xe(o,"bridge_does_not_verify",`An append-only bridge for ${o} would not verify (${w.errors.join(", ")}).`,w.errors);let v=h?.bridge===void 0?void 0:{...h.bridge,first_break_entry:a+1},k=r.collectWarnings(p,0,u);return{changed:p,rewrittenEntries:y,applyRewrite:async x=>rg(o,e.historyPath,x.historyRawUnderLock,h),report:({verification:x,warnings:E})=>fC({subject:e,options:t,entries:i,before:s,surface:f,changed:p,itemReplay:l,reconciliation:u,receipt:v,verification:x,warnings:[...k,...E]})}}function fC(e){let{subject:t,entries:n,surface:r,itemReplay:i}=e;return{id:t.id,dry_run:e.options.dryRun===!0,changed:e.changed,history:{path:t.historyPath,entries_scanned:n.length,chain_drift_before:!e.before.ok,entries_rehashed:0,entries_patch_repaired:0,converted_replace_to_add:0,skipped_ops:0,reconciled_with_item:e.reconciliation!==void 0,audit_entry_added:e.changed&&e.options.dryRun!==!0,verify_ok:e.verification.ok,verify_errors:e.verification.errors,item_hash_version_before:e.before.item_hash_version??null,item_hash_version_after:r.itemHashVersion,version_disposition:"preserved"},item:{exists:t.located!==null,path:t.located?.itemPath??null,matched_chain_before:i===null?null:qe(i,r.itemHashVersion,r.algorithm).includes(n.at(-1).after_hash)},provenance_normalization:{requested:!1,changed:!1,events_changed:0,observations_removed:0,invalid_values:[]},...e.receipt===void 0?{}:{bridge:e.receipt},...e.reconciliation===void 0?{}:{reconciliation:e.reconciliation},warnings:[...new Set(e.warnings)].sort((o,s)=>o.localeCompare(s)),generated_at:C()}}function yc(e,t,n,r){let i={reason:r.absent?"missing_stream":"empty_stream",prior_versions:"unrecorded"},o=n.loadedItem,s=e.located.itemPath,a=Ei({nowIso:C(),author:n.author,op:"history_repair",before:Tt,after:o.document,message:t.message??`history-repair rebuilt ${r.absent?"the missing":"the empty"} history stream from the on-disk item; earlier versions are not recorded.`,context:{history_reseed:{contract_version:1,...i}}}),c=t.dryRun===!0;return{changed:!0,rewrittenEntries:[a],applyRewrite:async d=>ig(e.id,e.historyPath,d.historyRawUnderLock,a),report:({verification:d,warnings:l})=>({id:e.id,dry_run:c,changed:!0,history:{path:e.historyPath,entries_scanned:0,chain_drift_before:!0,entries_rehashed:0,entries_patch_repaired:0,converted_replace_to_add:0,skipped_ops:0,reconciled_with_item:!0,audit_entry_added:!c,verify_ok:d.ok,verify_errors:d.errors,item_hash_version_before:null,item_hash_version_after:vn,version_disposition:"preserved"},item:{exists:!0,path:s,matched_chain_before:!1},provenance_normalization:{requested:t.normalizeProvenance===!0,changed:!1,events_changed:0,observations_removed:0,invalid_values:[]},reseed:i,warnings:[...new Set(l)],generated_at:C()})}}var hC=/^(incomplete_record_hash_envelope|record_hash_mismatch|unsupported_record_hash_version|rewrite_evidence_[a-z_]+):entry_(\d+)$/u;function _C(e,t){return new _(`History entry ${t} of ${e} is sealed in a record format this pm version cannot read, so it cannot repair the stream.`,g.CONFLICT,{code:"history_record_version_unsupported",item_id:e,reason:"unsupported_record_hash_version",details:{entry:Number(t),reason:"unsupported_record_hash_version"},required:"Upgrade pm to a version that reads the stream's record format; no bytes were changed.",nextSteps:["Run npm install -g @unbrained/pm-cli@latest, then run pm health again."]})}function cg(e,t,n){try{return n()}catch(r){let i=r instanceof TypeError?hC.exec(r.message):null;if(i===null)throw r;let o=t[Number(i[2])-1];throw o!==void 0&&xi(o)?_C(e,i[2]):new _(`History entry ${i[2]} of ${e} no longer matches its seal (${i[1]}), so a repair cannot tell which part of the record to keep.`,g.CONFLICT,{code:"history_record_integrity_invalid",item_id:e,reason:i[1],details:{entry:Number(i[2]),reason:i[1]},required:"Restore the item's history stream from version control or a backup; no bytes were changed.",nextSteps:[`Run pm history ${e} --verify --full to locate the record, restore the stream, then run pm history ${e} --verify --strict-exit.`]})}}import{realpath as pg}from"node:fs/promises";import wc from"node:path";import fg from"fast-json-patch";function dg(e,t){return t==="body"?e.body:e.metadata[t]}function gC(e,t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;let n=t;return e==="comments"?typeof n.created_at=="string"&&typeof n.author=="string"&&typeof n.text=="string":typeof n.path=="string"||e==="tests"&&typeof n.command=="string"}function yC(e){let t={...e};if(t.source_kind==="merge_union"&&(t.source_kind="local_mutation"),t.provenance!==null&&typeof t.provenance=="object"&&!Array.isArray(t.provenance)){let n={...t.provenance};n.source_kind==="merge_union"&&(n.source_kind="local_mutation"),t.provenance=n}return t}function lg(e,t){if(!Array.isArray(t)||!["comments","docs","tests"].includes(e)||!t.every(r=>gC(e,r)))return t;let n=t.map(r=>e==="comments"?r:yC(r));return[...new Map(n.map(r=>[I(r),r])).values()]}function vc(e,t){if(e===void 0||Object.is(e,t))return!0;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let r=new Set;return e.every(i=>{let o=t.findIndex((s,a)=>!r.has(a)&&vc(i,s));return o<0?!1:(r.add(o),!0)})}if(e===null||t===null||typeof e!="object"||typeof t!="object"||Array.isArray(t))return!1;let n=t;return Object.entries(e).every(([r,i])=>Object.hasOwn(n,r)&&vc(i,n[r]))}function ug(e,t){let n=new Set(t),r=[];for(let i=e.length-1;i>=0&&n.size>0;i-=1){let o=e[i],s=new Set;for(let c of vi(o.patch))s.add(Ni(c.path)),c.from&&s.add(Ni(c.from));let a=[...n].filter(c=>s.has(c));if(a.length!==0){for(let c of a)n.delete(c);r.push({index:i+1,ts:o.ts,author:o.author,op:o.op,fields:a.sort((c,d)=>c.localeCompare(d))})}}return r.reverse()}function hg(e,t,n){let r=fg.compare(t,n);if(r.length===0)return;let i=new Set;for(let f of r)i.add(Ni(f.path));let o=new Set([...i].filter(f=>vc(lg(f,dg(t,f)),lg(f,dg(n,f))))),s=new Set([...i].filter(f=>!o.has(f))),a=ug(e,s),c=ug(e,o),d=[...i].sort((f,h)=>f.localeCompare(h)),l=[...s].sort((f,h)=>f.localeCompare(h)),u=[...o].sort((f,h)=>f.localeCompare(h)),m=[...new Set(a.map(f=>f.author))].sort((f,h)=>f.localeCompare(h)),p=[...new Set(c.map(f=>f.author))].sort((f,h)=>f.localeCompare(h));return{reconciled_field_count:i.size,reconciled_fields:d,reverted_field_count:s.size,reverted_fields:l,discarded_events:a,discarded_authors:m,preserved_field_count:o.size,preserved_fields:u,preserved_events:c,preserved_authors:p,recovery_hint:a.length>0?"Reconciliation keeps the on-disk item and overwrites these replayed mutations. To recover one, inspect it with pm history <id> --diff --field <field>, then re-apply the lost value with pm update.":null}}async function wC(e){try{return await pg(e)}catch{return null}}async function vC(e){if(await wC(wc.resolve(e.gitWorkspaceRoot,e.receipt.item_path))!==e.currentPath)return null;let n=[...new Set([...e.receipt.fields_from_theirs,...e.receipt.union_fields,...e.receipt.decisions.map(a=>a.field)])].sort(),r=e.receipt.merged_field_hashes;if(!r||n.length===0)return null;let i=Object.keys(r).sort();if(n.length!==i.length||n.some((a,c)=>a!==i[c]))return null;let o=e.currentItemReplay.metadata;return n.every(a=>{let c=a==="body"?e.currentItemReplay.body:o[a];return[Ut(c),Ce(I(V(c)))].includes(r[a])})?{receipt:e.receipt,declaredFields:n}:null}async function kC(e){if(e.proof.gitWorkspaceRoot===null)return{trusted:!1,reason:"git_workspace_unavailable",receipt_ids:[]};if(e.itemPath===null||e.currentItemReplay===null)return{trusted:!1,reason:"item_path_unavailable",receipt_ids:[]};let t=e.proof.receipts.filter(s=>s.item_id===e.id);if(t.length===0)return{trusted:!1,reason:"no_item_receipts",receipt_ids:[]};let n=await pg(e.itemPath),r=[];for(let s of t){let a=await vC({receipt:s,gitWorkspaceRoot:e.proof.gitWorkspaceRoot,currentPath:n,currentItemReplay:e.currentItemReplay});a&&r.push(a)}let i=new Set(r.flatMap(({declaredFields:s})=>s)),o=e.reconciliation?.reconciled_fields;return r.length>0&&(o===void 0||o.length>0&&o.every(s=>i.has(s)))?{trusted:!0,reason:"trusted_merge_driver_hash_evidence",receipt_ids:r.map(({receipt:s})=>s.id)}:{trusted:!1,reason:"no_receipt_set_proves_snapshot",receipt_ids:[]}}async function mg(e,t,n,r){if(e===void 0)return;let{receipt:i,gitWorkspaceRoot:o}=e,s=t.currentItemPath===null?null:wc.relative(o,t.currentItemPath).split(wc.sep).join("/");if(!n||r.entriesRehashed!==0||r.entriesPatchRepaired!==0||t.matchedChainBefore!==!0||t.currentItemRawBeforeLock===null||s!==i.item_path||i.operation===void 0||!await L_(o,i.item_path,i.operation,t.currentItemRawBeforeLock))throw new _("Restored-origin receipt evidence no longer proves the exact clean item snapshot.",g.CONFLICT,{code:"merge_reconcile_receipt_evidence_untrusted",recovery:{suggested_retry:"pm merge reconcile --dry-run"}})}async function bC(e){let t=new Set(e.options.mergeReceiptProof?.receipts.filter(s=>s.item_id===e.subjectId).map(s=>s.id)??[]),n=e.options.mergeReceiptProof?await Rt(e.options.mergeReceiptProof.gitWorkspaceRoot??process.cwd(),{includeReconciled:!0,includeLossless:!0,pmRoot:e.pmRoot}):void 0,r=n?.receipts.filter(s=>s.item_id===e.subjectId&&t.has(s.id))??[];W_(t,n,e.options.dryRun===!0);let i=e.options.mergeReceiptProof?await kC({proof:{...e.options.mergeReceiptProof,receipts:r},id:e.subjectId,itemPath:e.itemReplayContext.currentItemPath,currentItemReplay:e.itemReplayContext.currentItemReplay,reconciliation:e.reconciliation}):void 0;if(i&&!i.trusted&&e.options.force!==!0)throw new _(`Merge receipt evidence for ${e.subjectId} does not prove the exact item snapshot (${i.reason}).`,g.CONFLICT,{code:"merge_reconcile_receipt_evidence_untrusted",required:"Use authoritative clone-local or durable receipt evidence whose canonical path, declared fields, and merged-value hashes match the current item, or review the mismatch and rerun with --force.",recovery:{suggested_retry:"pm merge reconcile --dry-run"}});let o=i?.trusted?r.filter(s=>i.receipt_ids.includes(s.id)):[];return{mergeReceiptProof:i,effectiveAuditContext:o.length>0&&e.options.force!==!0?{...e.options.auditContext,merge:{receipts:o.map(No)}}:e.options.auditContext}}function xC(e,t,n){let r=e.located?.itemPath??null,i=t.loadedItem,o=t.entries;if(!i)return{currentItemReplay:null,currentItemPath:r,matchedChainBefore:null,currentItemRawBeforeLock:null,loadedItem:null};let s=wn(i.document),a=o[o.length-1].after_hash;return{currentItemReplay:s,currentItemPath:r,matchedChainBefore:qe(s,n,ve(o.at(-1)?.hash_algorithm)).includes(a),currentItemRawBeforeLock:i.raw,loadedItem:i}}function SC(e){return typeof e.message=="string"&&e.message.trim().length>0?e.message:`history-repair re-anchored ${e.entriesRehashed} entr${e.entriesRehashed===1?"y":"ies"}${e.entriesPatchRepaired>0?`, repaired ${e.entriesPatchRepaired} patch(es)`:""}${e.reconcileNeeded?", reconciled chain with on-disk item":""}.`}function EC(e){let t=[...e.reanchorEntries];if(!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let n=e.reconcileNeeded&&e.currentItemReplay?e.currentItemReplay:e.finalReplay,r=ve(e.reanchorEntries.at(-1)?.hash_algorithm),i=qe(e.finalReplay,e.itemHashVersion,r),o=e.reanchorEntries[e.reanchorEntries.length-1].after_hash,s=i.indexOf(o),a=qe(n,e.itemHashVersion,r),c={hash_algorithm:r,ts:C(),author:e.author,op:e.auditOperation,patch:e.reconcileNeeded&&e.currentItemReplay?fg.compare(e.finalReplay,e.currentItemReplay):[],before_hash:i[s],after_hash:a[s],message:e.message,...e.explicitItemHashVersion?{item_hash_version:e.itemHashVersion}:{},...e.auditContext===void 0?{}:{context:e.auditContext}};return t.push(kn({...c,event_class:bi(c)})),{rewrittenEntries:t,auditEntryAdded:!0}}function _g(e,t,n){let r=[];return e||r.push("history_repair_no_changes"),t>0&&r.push(`history_repair_skipped_unresolvable_ops:${t}`),n&&n.discarded_events.length>0&&r.push(`history_repair_reconcile_discards_events:${n.discarded_events.length}`,`history_repair_discarded_authors:${n.discarded_authors.join(",")}`),r}async function Kr(e,t,n){let{pmRoot:r,settings:i,typeRegistry:o}=await Us(n.path),s=await nm(r,e,i,o.type_to_folder);if(t.salvageTail===!0){if(t.appendOnly===!0)throw new _("Tail salvage cannot be combined with other repair modes.",g.USAGE);return eg({pmRoot:r,subject:s,settings:i,typeRegistry:o,options:t,author:q(t.author,i.author_default)})}if(t.appendOnly===!0)return AC(t),await sg(s.id,s.historyPath),ma({pmRoot:r,subject:s,settings:i,typeRegistry:o,operation:"history-repair",options:t,transform:c=>ag(s,t,c,{analyzeDiscard:hg,collectWarnings:_g}),reseed:(c,d)=>yc(s,t,c,d)});let a=RC(t)?void 0:async(c,d)=>(await gc(s.id,s.historyPath),yc(s,t,c,d));return ma({pmRoot:r,subject:s,settings:i,typeRegistry:o,operation:"history-repair",options:t,transform:c=>$C({pmRoot:r,subject:s,options:t},c),reseed:a})}function RC(e){return[e.auditOperation,e.auditContext,e.auditContextById,e.forceAuditEntry,e.mergeReceiptProof,e.mergeReceiptProofById,e.mergeAbandonmentProof].some(t=>t!==void 0&&t!==!1)}function AC(e){if([e.normalizeProvenance,e.auditOperation,e.auditContext,e.auditContextById,e.forceAuditEntry,e.mergeReceiptProof,e.mergeReceiptProofById,e.mergeAbandonmentProof].some(t=>t!==void 0&&t!==!1))throw new _("An append-only repair cannot be combined with other repair modes.",g.USAGE)}function IC(e,t,n){let r=(e.mergeAbandonmentProof!==void 0||e.mergeReceiptProof!==void 0&&e.force!==!0)&&n!==void 0&&t.some(i=>i.record_hash_version!==void 0&&i.op==="merge_reconcile"&&I(i.context)===I(n));return e.forceAuditEntry===!0&&!r}function CC(e){let t=la(e);return t.receipt.changed?la(Gl(e)):t}async function $C(e,t){let{pmRoot:n,subject:r,options:i}=e,o=t.entries,s=t.verification,a=ke(o),c=i.normalizeProvenance?CC(o):{entries:o,receipt:{changed:!1,events_changed:0,observations_removed:0,invalid_values:[]}},d=zl(c.entries),l=new Set(c.entries.map(j=>j.item_hash_version).filter(j=>j!==void 0)),u=cg(r.id,c.entries,()=>ki(c.entries,d,{callerMarksBridgeCoverage:c.receipt.changed})),m=xC(r,t,d);await mg(i.mergeAbandonmentProof,m,s.ok,u);let p=u.finalDocument,f=qe(p,d),h=!1;if(m.currentItemReplay!==null){let j=qe(m.currentItemReplay,d);h=!f.some(($,O)=>$===j[O])}let y=h&&m.currentItemReplay?hg(u.entries,p,m.currentItemReplay):void 0,{mergeReceiptProof:w,effectiveAuditContext:v}=await bC({options:i,pmRoot:n,subjectId:r.id,itemReplayContext:m,reconciliation:y}),k=[u.entriesRehashed>0,u.entriesPatchRepaired>0,u.entriesResealed>0,h,IC(i,u.entries,v),c.receipt.changed].some(Boolean),x=t.author,E=!!i.dryRun,A=SC({message:i.message,entriesRehashed:u.entriesRehashed,entriesPatchRepaired:u.entriesPatchRepaired,reconcileNeeded:h}),{rewrittenEntries:S,auditEntryAdded:b}=EC({reanchorEntries:u.entries,changed:k,reconcileNeeded:h,currentItemReplay:m.currentItemReplay,finalReplay:p,author:x,message:A,auditOperation:i.auditOperation??"history_repair",auditContext:c.receipt.changed?{...v,provenance_normalization:c.receipt}:v,itemHashVersion:d,explicitItemHashVersion:u.explicitItemHashVersion}),D=_g(k,u.skippedOps,y);return{changed:k,rewrittenEntries:S,beforeWrite:async()=>mg(i.mergeAbandonmentProof,m,s.ok,u),report:({verification:j,warnings:$})=>({id:r.id,dry_run:E,changed:k,history:{path:r.historyPath,entries_scanned:o.length,chain_drift_before:!s.ok,entries_rehashed:u.entriesRehashed,entries_patch_repaired:u.entriesPatchRepaired,converted_replace_to_add:u.convertedReplaceToAdd,skipped_ops:u.skippedOps,reconciled_with_item:h,audit_entry_added:b,verify_ok:j.ok,verify_errors:j.errors,item_hash_version_before:a.item_hash_version??null,item_hash_version_after:d,version_disposition:l.size>1?"selected_for_ambiguous_stream":"preserved"},item:{exists:m.currentItemPath!==null,path:m.currentItemPath,matched_chain_before:m.matchedChainBefore},provenance_normalization:{requested:i.normalizeProvenance===!0,...c.receipt},...y?{reconciliation:y}:{},...w?{merge_receipt_proof:w}:{},warnings:[...new Set([...D,...$])].sort((O,Q)=>O.localeCompare(Q)),generated_at:C()})}}function RW(e,t){if(t&&e!==void 0)throw new _("history-repair: <id> and --all are mutually exclusive; pass an item id to repair one stream or --all to repair every drifted stream.",g.USAGE);if(!t&&e===void 0)throw new _("history-repair: provide an item <id> or pass --all to repair every drifted stream.",g.USAGE)}async function AW(e,t){if(e.salvageTail===!0)throw new _("Tail salvage requires one explicit item ID; --all is not supported.",g.USAGE);let{pmRoot:n,settings:r,typeRegistry:i}=await Us(t.path),o=[],s=await gt(n,r.item_format,i.type_to_folder,o,r.schema,{forceSourceScan:!0}),a=await en(n,s),c=e.normalizeProvenance?await pp(n):[],d=[...new Set([...a.driftedItems,...c])].sort((p,f)=>p.localeCompare(f)),l=[],u=[],m={repaired:0,skipped_clean:0,failed:0};for(let p of d)try{let f=await Kr(p,{...e,auditContext:e.auditContextById?.[p],auditContextById:void 0,mergeReceiptProof:e.mergeReceiptProofById?.[p]??e.mergeReceiptProof,mergeReceiptProofById:void 0},t),h=f.changed?"repaired":"skipped_clean";m[h]+=1,u.push(...f.warnings.map(y=>`${p}:${y}`)),l.push({id:p,outcome:h,entries_rehashed:f.history.entries_rehashed,entries_patch_repaired:f.history.entries_patch_repaired,reconciled_with_item:f.history.reconciled_with_item,...f.reconciliation?{reconciliation:f.reconciliation}:{},...f.merge_receipt_proof?{merge_receipt_proof:f.merge_receipt_proof}:{},warnings:f.warnings})}catch(f){m.failed+=1,l.push({id:p,outcome:"failed",error:f instanceof Error?f.message:String(f),...await cm(f,n)})}return e.dryRun||await Bl(n),{all:!0,dry_run:!!e.dryRun,scanned_streams:s.length,drifted_streams:a.driftedItems.length,provenance_invalid_streams:c.length,streams:l,totals:m,warnings:[...new Set([...o,...u])].sort((p,f)=>p.localeCompare(f)),generated_at:C()}}import{lstat as TC}from"node:fs/promises";var kc="history_drift_chain_mismatch",OC="history_drift_chain_unbridgeable",wg="history_drift_unrepairable_stream",gg="history_drift_hash_mismatch",vg="history_drift_missing_stream",PC=["history_drift_unreadable_stream",wg,"history_drift_version_skew","history_drift_merge_receipt"],LC=new Set([kc,vg]);function Mo(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function NC(e,t){return e instanceof _?typeof e.context.reason=="string"?e.context.reason:e.code??t:t}async function yg(e,t,n){try{await Kr(e,{appendOnly:t,dryRun:!0},n);return}catch(r){return NC(r,t?"append_only_preview_failed":"rewrite_preview_failed")}}async function DC(e,t){let n=[];for(let r of Mo(e.check.details.missing_streams)){let[i]=await Promise.allSettled([TC(pt(t,r))]);i.status==="fulfilled"&&i.value.isSymbolicLink()&&n.push({id:r,reason:"stream_not_regular_file",rewrite_refusal:"stream_not_regular_file"})}return n}async function kg(e,t,n){let r=[],i=new Set(Mo(e.check.details.version_skews));for(let o of Mo(e.check.details.chain_mismatches)){if(i.has(o))continue;let s=await yg(o,!0,t);if(s===void 0)continue;let a=await yg(o,!1,t);r.push({id:o,reason:s,...a===void 0?{}:{rewrite_refusal:a}})}return[...r,...await DC(e,n)]}function MC(e,t,n){for(let r of[kc,vg]){if(!e.startsWith(`${r}:`))continue;let i=e.slice(r.length+1),o=t.get(i);return o===null?[]:[o===void 0?e:`${o}:${i}`]}return e.startsWith(`${gg}:`)?n.has(e.slice(gg.length+1))?[]:[e]:[e]}function bg(e,t){let n=Mo(e.check.details.version_skews),r=new Map([...n.map(o=>[o,null]),...t.map(o=>[o.id,o.rewrite_refusal===void 0?OC:wg])]),i=new Set([...n,...t.filter(o=>o.rewrite_refusal!==void 0).map(o=>o.id)]);e.warnings=e.warnings.flatMap(o=>MC(o,r,i)).sort((o,s)=>o.localeCompare(s)),t.length!==0&&(e.check.details={...e.check.details,repair_refusals:t})}function xg(e){if(PC.some(r=>Object.hasOwn(e,r)))return;let t=Object.keys(e),n=t.every(r=>LC.has(r));for(let r of t)n?e[r]="pm history-repair --all --append-only":r!==kc&&(e[r]="pm history-repair --all")}var FC=5;function Fo(e,t){let n=[],r={};for(let o of e){let s=Il(o);if(s.length!==0){for(let a of s)r[a.field]=(r[a.field]??0)+1;n.push({id:o.id,fields:s.map(a=>a.field),reasons:[...new Set(s.map(a=>a.reason))]})}}if(n.length===0)return;n.sort((o,s)=>o.id.localeCompare(s.id));let i=t?n.length:FC;return{details:{items:n.length,by_field:Object.fromEntries(Object.entries(r).sort(([o],[s])=>o.localeCompare(s))),rows:n.slice(0,i),truncated:n.length>i},warning:`validate_metadata_deferred_fields:${n.length}`}}var Ag=25,HC=me.join("runtime","telemetry","events.jsonl"),UC=me.join("runtime","telemetry","state.json"),zC=2500,WC=500,Ig=Xu-3,qC=["x-pm-telemetry-max-schema-version","x-pm-telemetry-max-version"];function Ac(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 Ic(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function Yn(e){return e.trim().toLowerCase()}function Sc(e,t){let n=Yn(e),r=Yn(t);return n.startsWith("builtin-")?!0:r==="beads"||r==="todos"}async function Cc(e){try{return(await It.stat(e)).isDirectory()}catch{return!1}}async function GC(e){let t=(await It.readdir(e,{withFileTypes:!0})).filter(r=>r.isDirectory()),n=await Promise.all(t.map(r=>It.readdir(me.join(e,r.name),{withFileTypes:!0})));return new Set(n.flatMap(r=>r.filter(i=>i.isFile()).filter(i=>sr.some(o=>i.name.endsWith(o))).map(i=>me.parse(i.name).name)))}async function BC(e,t,n,r){let i=await Be({path:e,scope:"project"}),o=t!=="_workspace"&&!r.has(t);if(!n.enabled&&!o)return{warnings:i,overThreshold:!1,classification:"live"};let s;try{s=await It.readFile(e,"utf8")}catch{return{warnings:i,overThreshold:!1,classification:"unreadable"}}let a="live";if(o){let d=s.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?s.split(/\r?\n/).filter(d=>d.trim().length>0).length:0;return{warnings:i,overThreshold:n.enabled&&c>n.max_entries,classification:a}}async function JC(e,t,n){let r=me.join(e,"history");if(!await Cc(r))return{count:0,warnings:[],over_threshold:[],max_entries:null,tombstones:[],orphaned:[]};let i=(await It.readdir(r)).filter(u=>u.endsWith(".jsonl")).sort((u,m)=>u.localeCompare(m)),s=t.enabled?t.max_entries:null,a=[],c=[],d=[],l=[];for(let u of i){let m=me.join(r,u),p=u.slice(0,-6),f=await BC(m,p,t,n);a.push(...f.warnings),f.classification==="tombstone"&&d.push(p),f.classification==="orphaned"&&l.push(p),f.overThreshold&&c.push(p)}return{count:i.length,warnings:[...a,...c.map(u=>`history_stream_over_compact_threshold:${u}`),...l.map(u=>`history_orphaned_stream:${u}`)],over_threshold:c,max_entries:s,tombstones:d,orphaned:l}}function Ec(e,t){return me.relative(e,t).replaceAll("\\","/")}async function Cg(e,t){let n=[...new Set(Object.values(t))].sort((i,o)=>i.localeCompare(o)),r=[];for(let i of n){let o=me.join(e,i),s=[];try{s=await It.readdir(o)}catch(a){if(typeof a=="object"&&a!==null&&"code"in a&&F(a))continue;continue}for(let a of s)sr.some(c=>a.toLowerCase().endsWith(c))&&r.push(me.join(o,a))}return r.sort((i,o)=>Ec(e,i).localeCompare(Ec(e,o))),r}function VC(e){return!(typeof e=="object"&&e!==null&&"code"in e&&F(e))}function KC(e){let t=Fo(e,!1);return t===void 0?{}:{curation:{deferred_fields:t.details}}}async function YC(e,t,n){let r=await Cg(e,t),i=[],o=[],s=[],a=[],c=ln(U());for(let d of r){let l=Ec(e,d),u;try{u=await It.readFile(d,"utf8")}catch{i.push(l);continue}let m=Ne(u);if(m){o.push({path:l,...m});continue}try{let p=Lt(u,{format:Jd(d),schema:n,extensionFieldNames:c});a.push({ref:l,version:gi(p.metadata)})}catch{s.push(l)}}return{paths:r,unreadable:i,conflictMarkers:o,parseFailures:s,formatVersions:a}}async function XC(e){let t=me.join(e,"history"),n=[],r=[],i=[],o=[],s=[],a=[];try{a=(await It.readdir(t)).filter(c=>c.endsWith(".jsonl")).sort((c,d)=>c.localeCompare(d))}catch(c){VC(c)&&n.push("history")}for(let c of a){let d=c.slice(0,-6),l;try{l=await It.readFile(me.join(t,c),"utf8")}catch{n.push(d);continue}let u=Ne(l);if(u){r.push({id:d,...u});continue}l.split(/\r?\n/).forEach((m,p)=>{if(m.trim())try{let f=JSON.parse(m);o.push(...V_(f,d).map(h=>({itemId:d,line:p+1,...h}))),s.push(...K_(f,d,p+1))}catch{i.push({id:d,line:p+1})}})}return{files:a,unreadable:n,conflictMarkers:r,invalidJson:i,mergeReceiptReferences:o,mergeReceiptDispositions:s}}function $g(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 ZC(e,t,n,r,i,o){let s=await YC(e,t,n),a=await XC(e),c=yi(s.formatVersions,4,1),d=_e(n),l=Ui(o,$=>Rl($,d),fr()),u=await xo(e),m=await Mt(e),p=await m_(e,m),f=await p_(e,m,r,i),h=m===null?null:await Tn(m),y=await Rt(m??e,{includeReconciled:!0,includeLossless:!0,pmRoot:e}),w=new Set(y.durable_receipt_ids),v=Y_(a.mergeReceiptReferences,w,a.mergeReceiptDispositions),k=v.missing,x=y.receipts.filter($=>$.state==="pending"),{pendingDecisions:E,lossless:A}=Kn(x),S=h?.status==="missing"&&h.missing_keys.length===5&&h.drifted_keys.length===0,b=[...s.unreadable.map($=>`integrity_item_unreadable:${$}`),...s.conflictMarkers.map($=>`integrity_item_conflict_marker:${$.path}:L${$.line}`),...s.parseFailures.map($=>`integrity_item_parse_failed:${$}`),...a.unreadable.map($=>`integrity_history_unreadable:${$}`),...a.conflictMarkers.map($=>`integrity_history_conflict_marker:${$.id}:L${$.line}`),...a.invalidJson.map($=>`integrity_history_invalid_json:${$.id}:L${$.line}`),...c.outdated.map($=>`integrity_item_outdated_format_version:${$}`),...c.ahead.map($=>`integrity_item_ahead_format_version:${$}`),...$g(l),...u.tracked_path_count>0?[`tracked_runtime_cache_files:${u.tracked_path_count}`]:[],...h!==null&&h.status!=="ok"?[`merge_driver_configuration_${S?"missing":"drift"}:${h.missing_keys.length+h.drifted_keys.length}`]:[],...f.warnings,...p.warnings,...E.length>0?[`merge_decisions_unreviewed:${E.length}`]:[],...A.length>0?[`merge_receipts_pending:${A.length}`]:[],...f_({invalidEvidenceCount:y.invalid_evidence_count,missingHistoryReferenceCount:k.length})],D=[...new Set(b)].sort(($,O)=>$.localeCompare(O)),j=D.filter($=>!$.startsWith("integrity_legacy_hierarchy_"));return{check:{name:"integrity",status:j.length===0?"ok":"warn",ok:j.length===0,details:{checked_item_files:s.paths.length,checked_history_streams:a.files.length,counts:{item_unreadable:s.unreadable.length,item_conflict_markers:s.conflictMarkers.length,item_parse_failures:s.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:h===null||h.status==="ok"?0:h.missing_keys.length+h.drifted_keys.length,merge_fence:f.count,ignored_merge_artifacts:p.rules.length,pending_merge_decisions:E.length,lossless_merge_receipts:A.length,invalid_merge_receipt_evidence:y.invalid_evidence_count,missing_merge_receipt_history_references:k.length,accepted_legacy_merge_receipt_references:v.acceptedLegacyCount,accepted_missing_merge_receipt_dispositions:v.acceptedDispositionCount},item_unreadable:s.unreadable,item_conflict_markers:s.conflictMarkers,item_parse_failures:s.parseFailures,item_outdated_format_version:c.outdated,item_ahead_format_version:c.ahead,...KC(o),hierarchy_integrity:{...l,relations:Ve(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:h===null?null:{...h,required:i},merge_fence:f.audit,ignored_merge_artifacts:p.rules,pending_merge_decision_items:[...new Set(E.map($=>$.item_id))].sort(($,O)=>$.localeCompare(O)),lossless_merge_receipt_items:[...new Set(A.map($=>$.item_id))].sort(($,O)=>$.localeCompare(O)),invalid_merge_receipt_evidence_details:y.invalid_evidence,invalid_merge_receipt_evidence_details_truncated:y.invalid_evidence_truncated,missing_merge_receipt_history_reference_details:k.slice(0,100),missing_merge_receipt_history_reference_details_truncated:k.length>100}},warnings:D,gitWorkspaceRoot:m,pendingMergeReceipts:x}}function QC(e){if(typeof e.activate=="function")return!0;let t=e.default;return typeof t!="object"||t===null?!1:typeof t.activate=="function"}function e$(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:QC(e.module)};return Array.isArray(e.capabilities)&&(t.capabilities=[...e.capabilities]),t}function t$(e,t){let n=X(e.id);return n||`migration-${String(t+1).padStart(3,"0")}`}function n$(e){let n=X(e.status)?.toLowerCase();return n==="failed"?"failed":n==="applied"?"applied":"pending"}function r$(e){return X(e.reason)??X(e.error)??X(e.message)}function bc(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 i$(e){let t=[],n=[],r=[];e.forEach((o,s)=>{let a=t$(o.definition,s),c=n$(o.definition);if(c==="applied"){t.push({layer:o.layer,name:o.name,id:a,status:c});return}if(c==="failed"){r.push({layer:o.layer,name:o.name,id:a,status:c,reason:r$(o.definition)});return}n.push({layer:o.layer,name:o.name,id:a,status:c})}),t.sort(bc),n.sort(bc),r.sort(bc);let i=[...r.map(o=>`extension_migration_failed:${o.layer}:${o.name}:${o.id}`),...n.map(o=>`extension_migration_pending:${o.layer}:${o.name}:${o.id}`)];return{summary:{applied:t,pending:n,failed:r,applied_count:t.length,pending_count:n.length,failed_count:r.length},warnings:i}}function Tg(e,t,n,r,i,o,s,a,c){let d=[...new Set(e)].sort((y,w)=>y.localeCompare(w)),l=[...new Set(d.map(y=>Ic(y)))].sort((y,w)=>y.localeCompare(w)),u=d.filter(y=>y.startsWith("extension_capability_unknown:")).length,m=c.length>0,p=m?"partial":"full",f=d.map(Ir).filter(y=>y!==void 0),h=Ua(d,{deactivate:"pm extension --deactivate <name> --project/--global",doctor:"pm extension --doctor --project/--global --detail deep --trace"});return h&&f.push(h),t>0&&f.push("Run pm extension --explore --project and pm extension --explore --global to inspect load failures."),n>0&&f.push("Review checks[name=extensions].details.activation.failed in pm health --json for activation error details."),(r.failed_count>0||r.pending_count>0)&&f.push("Resolve pending/failed extension migrations before write commands; use --force only when policy allows."),i>0&&f.push("Run pm extension --manage --project and pm extension --manage --global to refresh managed-state diagnostics."),u>0&&f.push(`Unknown extension capabilities detected. Allowed capabilities: ${si.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`),d.some(y=>y.startsWith("extension_capability_legacy_alias:"))&&f.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:"))&&f.push("Extension command definitions using legacy handler were auto-remapped. Update command definitions to use run: (context) => ... for forward compatibility."),m?f.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>."):s.length>0&&f.push("Loaded unmanaged extensions are currently treated as informational. Use pm extension --manage --project/--global --fix-managed-state to adopt them for update checks."),f.length===0&&f.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:i,managed_extension_entries_count:o,unmanaged_loaded_extension_count:s.length,unmanaged_loaded_extensions:s,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:p,update_health_partial:m,unknown_capability_count:u,top_warnings:d.slice(0,8),remediation:f}}async function o$(e,t,n){let r=await Ka(tt(e)),i=await nt({pmRoot:e,settings:t,cwd:process.cwd(),noExtensions:n}),o=i.loaded.map(S=>e$(S)),s=await up(i.loaded,tt(e)),a=await rt({...i,loaded:i.loaded}),[c,d]=await Promise.all([be(i.roots.project),be(i.roots.global)]);await Va(e,a.registrations.migrations);let l=i$(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}}},m=new Set(c.state.entries.map(S=>Yn(S.name))),p=new Set(d.state.entries.map(S=>Yn(S.name))),f=[...new Map(i.loaded.filter(S=>!(S.layer==="project"?m:p).has(Yn(S.name))).map(S=>[`${S.layer}:${S.name}`,{layer:S.layer,name:S.name,directory:S.directory}])).values()].sort((S,b)=>{let D=`${S.layer}:${S.name}`,j=`${b.layer}:${b.name}`;return D.localeCompare(j)}),h=f.map(S=>`${S.layer}:${S.name}`).sort((S,b)=>S.localeCompare(b)),y=f.filter(S=>Sc(S.name,S.directory)).map(S=>`${S.layer}:${S.name}`).sort((S,b)=>S.localeCompare(b)),w=f.filter(S=>!Sc(S.name,S.directory)).map(S=>`${S.layer}:${S.name}`).sort((S,b)=>S.localeCompare(b)),v=w.length>0?[`extension_update_health_partial_coverage:skipped_unmanaged:${w.length}`]:[],k=[...r.warnings,...i.warnings,...u.warnings,...l.warnings,...c.warnings,...d.warnings,...v,...s.warnings],x=Hr(k),E=Ur(),A=Tg(k,i.failed.length,a.failed.length,l.summary,c.warnings.length+d.warnings.length,c.state.entries.length+d.state.entries.length,h,y,w);return{check:{name:"extensions",status:k.length===0?"ok":"warn",ok:k.length===0,details:{...i,loaded:o,warnings:k,activation:u,author_manifest:r,triage:A,...l.summary.pending_count>0?{remediation_map:{extension_migration_pending:"pm extension migrate --project"}}:{},capability_contract:E,capability_guidance:x,host_version_census:s}},warnings:k}}function Rc(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=xp(e,Ag);return{values:n.values,truncated:n.truncated,total:e.length}}function jo(e){let t=(process.env[e]??"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function s$(){let e=Bu();return e.source_context_source==="env_override"?e.source_context:null}function Og(e){let t=0,n=0,r=0,i=0,o=0;for(let s of e.split(`
|
|
68
|
+
`)){let a=s.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,o=Math.max(o,d),d>=Ig&&(i+=1)}else n+=1}catch{n+=1}}}return{validEntries:t,invalidRows:n,totalRows:r,highRetryEntries:i,maxAttempts:o}}function a$(){return{validEntries:0,invalidRows:0,totalRows:0,highRetryEntries:0,maxAttempts:0}}function Eg(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 c$(e,t){let n=Ds(e.telemetry.endpoint).trim();return!t||!e.telemetry.enabled||n.length===0||Ms().telemetry_disabled?void 0:{attempted:!0,...await Pg(n)}}function d$(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 i=n.last_successful_flush_at,o=n.last_failed_flush_at,s=o&&(!i||o>i),a=!i,c=t.validEntries>=WC;return(s||a||c)&&r.push(`telemetry_queue_pending:${t.validEntries}`),t.highRetryEntries>0&&r.push(`telemetry_queue_high_retries:${t.highRetryEntries}`),r}function l$(e){return!e||e.ok!==!1?[]:typeof e.status=="number"?[`telemetry_endpoint_probe_http_status:${e.status}`]:["telemetry_endpoint_probe_failed"]}function u$(e){let t=Number.parseInt(e?.max_schema_version??"",10);return e?.ok===!0&&Number.isInteger(t)&&t>Yu?[`telemetry_schema_version_behind:${t}`]:[]}function m$(e,t){let n=typeof t.pending_otel_spans=="number"?t.pending_otel_spans:0,r=t.last_otel_success_at,i=t.last_otel_failure_at;return e.telemetry.enabled&&n>0&&!!i&&(!r||i>=r)?[`telemetry_otel_export_failing:${n}`]:[]}function p$(){return{...Ms(),pm_no_telemetry:jo("PM_NO_TELEMETRY"),telemetry_otel_disabled:jo("PM_TELEMETRY_OTEL_DISABLED"),telemetry_inline_flush:jo("PM_TELEMETRY_INLINE_FLUSH"),telemetry_source_context:s$()}}function f$(e,t){return e.telemetry.enabled&&t.validEntries>0}function h$(e,t){return e&&t.every(n=>!n.startsWith("telemetry_queue_pending:")&&!n.startsWith("telemetry_queue_high_retries:"))}function Rg(e){try{return decodeURIComponent(e)}catch{return e}}async function Pg(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(`${Rg(r.username)}:${Rg(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(zC)});return{probe_url:In(t),ok:r.ok,status:r.status,max_schema_version:(()=>{for(let i of qC){let o=r.headers.get(i)?.trim();if(o&&o.length>0)return o}})()}}catch(r){return{probe_url:In(t),ok:!1,error:r instanceof Error?Ju(r.message.replaceAll(t,In(t))):"probe_failed"}}}async function _$(e,t){let n=Eg(await B(e)),r=e===t?n:Eg(await B(t));return{runtimeState:n.runtimeState,spanState:r.runtimeState,stateParseFailed:n.stateParseFailed||r.stateParseFailed}}async function g$(e){let t=di(process.cwd()),n=await T(t),r=me.join(me.dirname(me.join(t,HC)),Ns("events.jsonl")),i=me.join(t,UC),o=me.join(me.dirname(i),Ns("state.json")),s=await B(r),a=s!==null,c=s?Buffer.byteLength(s,"utf8"):0,d=s?Og(s):a$(),{runtimeState:l,spanState:u,stateParseFailed:m}=await _$(o,i),p=Ds(n.telemetry.endpoint).trim(),f=In(p),h=await c$(n,e.checkTelemetry),y=[];m&&y.push("telemetry_state_invalid_json"),y.push(...d$(n,d,l),...l$(h),...u$(h),...m$(n,u));let w=f$(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:f,global_pm_root:t,queue_path:r,queue_exists:a,queue_entries:d.validEntries,queue_draining:h$(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:Ig,queue_max_attempts:d.maxAttempts,runtime_state_path:o,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:h??{attempted:!1},env_overrides:p$()}},warnings:y}}async function y$(e){let t;try{t=await Gp(e)}catch(r){let i=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:i,pm_root:e}},warnings:[`locks_scan_failed:${i}`]}}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 w$(e){let t="metadata",n=e.items,r=await en(e.pmRoot,n,{cacheHitVerification:t}),i=[...new Set([...r.hashMismatches,...r.chainMismatches,...r.versionSkews])].sort((w,v)=>w.localeCompare(v)),o=[],s=[];if(i.length>0){n=await gt(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema,{forceSourceScan:!0}),r=await en(e.pmRoot,n),o=[...new Set([...r.hashMismatches,...r.chainMismatches,...r.versionSkews])].sort((v,k)=>v.localeCompare(k));let w=new Set(o);s=i.filter(v=>!w.has(v))}let{missingStreams:a,unreadableStreams:c,hashMismatches:d,chainMismatches:l,versionSkews:u,driftedItems:m,workspaceStateMismatches:p,workspaceStateMissing:f,workspaceStateUnreadable:h}=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}`),...p.map(w=>`history_drift_workspace_state_mismatch:${w}`),...f.map(w=>`history_drift_workspace_state_missing:${w}`),...h.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:i.length>0?"metadata_then_content_hash":t,cache_confirmation:{triggered:i.length>0,reason:i.length>0?"cached_corruption_candidate":null,candidate_items:i,confirmed_items:o,resolved_false_positive_items:s,authoritative_item_source:i.length>0},drifted_items:m,counts:{drifted:m.length,missing_streams:a.length,unreadable_streams:c.length,hash_mismatches:d.length,chain_mismatches:l.length,version_skews:u.length,workspace_state_mismatches:p.length,workspace_state_missing:f.length,workspace_state_unreadable:h.length},missing_streams:a,unreadable_streams:c,hash_mismatches:d,chain_mismatches:l,version_skews:u,workspace_state_mismatches:p,workspace_state_missing:f,workspace_state_unreadable:h}},warnings:y}}function v$(e,t){let n=Mi(e),r=pr(n.settings),i=Hi(n.settings,t),o=r.active?Yt(r.active.name,r.active.model):null;return{runtimeDefaults:n,providerResolution:r,vectorStoreResolution:i,runtimeEmbeddingIdentity:o,semanticRuntimeAvailable:!!(r.active&&i.active)}}function k$(){return{refreshed:[],skipped:[],warnings:[]}}async function b$(e){return!e.refreshPolicy.enabled||!e.snapshot.semanticRuntimeAvailable||e.staleBefore.length===0?k$():Gu(e.pmRoot,e.staleBefore,{settings:e.snapshot.runtimeDefaults.settings,apply_runtime_defaults:!1})}function x$(e){return e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&!!(e.ledgerBefore.embedding&&e.runtimeEmbeddingIdentity&&Rn(e.ledgerBefore.embedding,e.runtimeEmbeddingIdentity))}function S$(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 E$(e,t,n){return e.enabled&&t&&n.length>0?null:e.enabled?t?"no_stale_items":"semantic_runtime_unavailable":"refresh_disabled"}function Lg(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:Os(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:Os(r,e.vector_store?.adapter??null)}}function R$(e){return{enabled:e.enabled,check_only:e.checkOnly,no_refresh:e.noRefresh,refresh_vectors:e.refreshVectors}}function A$(e,t,n){return e.enabled&&n.length>0&&t}async function I$(e,t,n,r,i){let o=v$(t,e),s=await An(e),a=o.semanticRuntimeAvailable?zs(n,s.entries):[],c=await b$({pmRoot:e,snapshot:o,refreshPolicy:r,staleBefore:a}),d=await An(e),l=o.semanticRuntimeAvailable?zs(n,d.entries):[],u=!o.runtimeDefaults.auto_ollama_defaults_applied,m=x$({strictVectorizationWarnings:u,semanticRuntimeAvailable:o.semanticRuntimeAvailable,ledgerBefore:s,runtimeEmbeddingIdentity:o.runtimeEmbeddingIdentity}),p=S$({ledgerBefore:s,ledgerAfter:d,refreshResult:c,strictVectorizationWarnings:u,semanticRuntimeAvailable:o.semanticRuntimeAvailable,embeddingIdentityChanged:m,staleAfter:l}),f=Rc(a,i),h=Rc(l,i),y=A$(r,o.semanticRuntimeAvailable,a);return{check:{name:"vectorization",status:p.length===0?"ok":"warn",ok:p.length===0,details:{semantic_runtime_available:o.semanticRuntimeAvailable,compatibility_mode_auto_defaults:o.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_applied:o.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:o.runtimeDefaults.auto_ollama_defaults_skipped_reason??null,auto_ollama_defaults_remediation:o.runtimeDefaults.auto_ollama_defaults_remediation??null,refresh_policy:R$(r),...Lg(t,o),embedding_identity_changed:m,embedding_identity_before:s.embedding??null,embedding_identity_runtime:o.runtimeEmbeddingIdentity??null,items:n.length,ledger_entries_before:Object.keys(s.entries).length,stale_items_detail_mode:i?"full":"summary",stale_items_summary_limit:Ag,stale_items_before_total:f.total,stale_items_before:f.values,stale_items_before_truncated:f.truncated,refresh_attempted:y,refresh_skipped_reason:E$(r,o.semanticRuntimeAvailable,a),refresh_result:c,ledger_entries_after:Object.keys(d.entries).length,stale_items_after_total:h.total,stale_items_after:h.values,stale_items_after_truncated:h.truncated}},warnings:p}}function C$(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 Ng(e){let t=e.checkOnly===!0,n=e.refreshVectors===!0;if(n&&t)throw new _("--check-only cannot be combined with --refresh-vectors",g.USAGE);if(n&&e.noRefresh===!0)throw new _("--no-refresh cannot be combined with --refresh-vectors",g.USAGE);return{enabled:n,checkOnly:t,noRefresh:!n,refreshVectors:n}}var $$=new Set(["extensions","locks","search"]);function T$(e){let t=new Set(Md.filter(i=>i.length>0)),n=new Set,r=new Set(Object.values(Fd));for(let i of e.folders)t.has(i)&&!r.has(i)||(t.delete(i),n.add(i));for(let i of $$)t.delete(i),n.add(i);return{requiredDirs:[...t].sort((i,o)=>i.localeCompare(o)),optionalDirs:[...n].sort((i,o)=>i.localeCompare(o)),optionalDirSet:n}}async function O$(e,t,n){let{requiredDirs:r,optionalDirs:i,optionalDirSet:o}=T$(t),s=[],a=[],c=[];for(let d of[...r,...i]){let l=me.join(e,d);c.push(...await Be({path:l,scope:"project"})),!await Cc(l)&&(o.has(d)?a.push(d):s.push(d))}return{requiredDirs:r,optionalDirs:i,missingRequiredDirs:s,missingOptionalDirs:a,missingDirs:n?[...s,...a]:[...s],hookWarnings:c}}function Dg(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 P$(e){return e.skipPolicy.skipDrift&&e.skipPolicy.skipVectors?_t(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema):gt(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema)}function xc(e){return{check:{name:e,status:"ok",ok:!0,details:{skipped:!0}},warnings:[]}}function L$(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 N$(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 D$(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 $c=e=>e.unknown_event_count??0,Tc=e=>e.actionable_unknown_event_count??$c(e);function M$(e,t,n,r,i,o,s){let a=$c(r),c=Tc(r),d=a>0,l=c>0,u=i.count>0||s!==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}:{},...i.count>0?{stale_in_progress:i}:{},...s===void 0?{}:{in_progress_work:s},...o.outcomes.length>0?{provenance_resolver_outcomes:o.outcomes}:{},...o.invalid_values.length>0?{provenance_invalid_values:o.invalid_values}:{},provenance_sample:o.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 Mg(e){let t=e.count===0?[]:[`stale_in_progress_items:${e.count}`];return{scan:e,warnings:t}}function F$(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 j$(e){let t=e.check.details.counts;return typeof t?.drifted=="number"?t.drifted:0}function H$(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 Fg(e){let t=new Map;for(let[i,o]of Object.entries(e.remediationSources))for(let s of o)t.has(s)||t.set(s,i);let n=new Map(e.checks.map(i=>[i.name,i]));return e.warnings.map(i=>{let o=t.get(i)??"integrity",s=va(i)?.code??Ic(i),a=n.get(o)?.details,c=typeof a?.remediation_map=="object"&&a.remediation_map!==null?a.remediation_map:{},d=Ir(i)??(s==="agent_guidance_outdated"?"pm init --agent-guidance add":s==="agent_guidance_unreadable"?"Check AGENTS.md and CLAUDE.md read permissions and file types, then retry pm health.":c[s]),l=Ac(i,e.requireMergeDrivers)?"advisory":"gate_failing";return{warning:i,code:s,check:o,severity:l,...typeof d=="string"?{remediation:d}:l==="gate_failing"?{disposition:"no_safe_automatic_remediation"}:{}}})}function U$(e){if(e.check.name==="history_drift"&&e.historyDriftedCount>1&&xg(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 z$(e){for(let t of e.checks){let n=ka(e.remediationSources[t.name]);U$({check:t,remediationMap:n,historyDriftedCount:e.historyDriftedCount,overThresholdCount:e.overThresholdCount});for(let[r,i]of Object.entries(t.name==="storage"?e.storageRemediation:{}))Object.hasOwn(n,r)&&(n[r]=i);Object.keys(n).length>0&&(t.details={...t.details,remediation_map:n})}}async function W$(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(s=>typeof s=="string"):[],r=new Set([t.missing_streams,t.unreadable_streams,t.chain_mismatches].flatMap(s=>Array.isArray(s)?s:[])),i=new Map;for(let s of e.pendingMergeReceipts){let a=i.get(s.item_id)??[];a.push(s),i.set(s.item_id,a)}let o=[];for(let s of n){if(r.has(s))continue;let a=i.get(s);if(!(!a||a.length===0))try{await Kr(s,{dryRun:!0,mergeReceiptProof:{gitWorkspaceRoot:e.gitWorkspaceRoot,receipts:a}},e.global),o.push(s)}catch{}}return[...new Set(o)].sort((s,a)=>s.localeCompare(a))}function q$(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,i)=>r.localeCompare(i)),e.check.details={...e.check.details,merge_receipt_attributed_items:t}}async function jg(e,t={}){let n=M(process.cwd(),e.path);await ie(n);let r=un(n),{settings:i,warnings:o}=await bu(n),s=[...new Set(o)],a=W(i,U()),c=t.strictDirectories===!0,d=t.strictExit===!0||t.failOnWarn===!0,l=t.requireMergeDrivers===!0||d,u=Ng(t),m=await O$(n,a,c),p=C$(i),f=await g$({checkTelemetry:t.checkTelemetry===!0}),h=await o$(n,i,!!e.noExtensions),y=Dg(t),w=[],v=await P$({pmRoot:n,settings:i,typeRegistry:a,skipPolicy:y,itemReadWarnings:w}),k=v,x=no(_e(i.schema),v),A=[...(await Pp({pm_root:n,cwd:process.cwd(),mode:"status",interactive:!1,settings:i}).catch(()=>({warnings:["agent_guidance_unreadable:AGENTS.md,CLAUDE.md"]}))).warnings.filter(fe=>fe.startsWith("agent_guidance_")),...p,...ro(x)],S=y.skipDrift?{warnings:[]}:await yu({pmRoot:n,settings:i,itemIds:v.map(fe=>fe.id),commandLabel:"health"}),b=await JC(n,i.history.compact_policy,await GC(n)),D=await xr(n,20,t.verboseAuthorEvents===!0),j=Tc(D),$=j>0?[`history_unknown_author_events:${j}`]:[],O=_e(i.schema),Q=await Vu(n,v,{in_progress_status:O.in_progress_status,status_registry:O,threshold_hours:i.mutation_guard.stale_in_progress_hours}),He=Mg(Q.stale),Ue=wp(Q,{in_progress:O.in_progress_status,open:O.open_status},Ci(e)),we=[...He.warnings,...Ue.warnings],$t=await _p(n),ze=$t.warnings,H=await y$(n),z=y.skipIntegrity&&!l?{...xc("integrity"),gitWorkspaceRoot:null,pendingMergeReceipts:[]}:await ZC(n,a.type_to_folder,i.schema,i,l,v),Ee=y.skipDrift?xc("history_drift"):await w$({pmRoot:n,items:k,settings:i,typeRegistry:a,itemReadWarnings:w}),mt=[...new Set(w)],oi=await W$({gitWorkspaceRoot:z.gitWorkspaceRoot,pendingMergeReceipts:z.pendingMergeReceipts,historyDriftCheck:Ee,global:e});q$(Ee,oi),bg(Ee,await kg(Ee,e,n));let cn=y.skipVectors?xc("vectorization"):await I$(n,i,k,u,t.verboseStaleItems===!0),dn=[L$(r,i,s),N$(m,c),D$(A,x),f.check,h.check,M$(v,i,b,D,He.scan,$t,Ue.details),H.check,z.check,Ee.check,cn.check],cs=F$({directoryState:m,normalizedSettingsReadWarnings:s,settingWarnings:A,normalizedItemReadWarnings:mt,telemetryCheck:f,extensionCheck:h,historyPolicyWarnings:S.warnings,historySummary:b,authorAttributionWarnings:$,staleInProgressWarnings:we,provenanceWarnings:ze,locksCheck:H,integrityCheck:z,historyDriftCheck:Ee,vectorizationCheck:cn}),Od=H$({directoryState:m,normalizedSettingsReadWarnings:s,settingWarnings:A,normalizedItemReadWarnings:mt,telemetryCheck:f,extensionCheck:h,historyPolicyWarnings:S.warnings,historySummary:b,authorAttributionWarnings:$,staleInProgressWarnings:we,provenanceWarnings:ze,locksCheck:H,integrityCheck:z,historyDriftCheck:Ee,vectorizationCheck:cn});z$({checks:dn,remediationSources:Od,historyDriftedCount:j$(Ee),overThresholdCount:b.over_threshold.length,storageRemediation:Ue.remediation});let ds=cs.filter(fe=>!Ac(fe,l)),ls=Fg({warnings:cs,checks:dn,remediationSources:Od,requireMergeDrivers:l}),nv=new Set(ls.filter(fe=>fe.severity==="gate_failing").map(fe=>fe.check)),rv=new Set(ls.map(fe=>fe.check));for(let fe of dn)fe.ok=!nv.has(fe.name),rv.has(fe.name)&&(fe.status="warn");let iv={ok:ds.length===0,verdict:{authority:"ok",...d?{strict_exit:!0}:{},...l?{require_merge_drivers:!0}:{},exit_code:d&&ds.length>0?g.GENERIC_FAILURE:0},checks:dn,warnings:cs,findings:ls,failed_because:ds,generated_at:C()};return ha(iv,t,y.summaryMode)}var Fq={buildHierarchyIntegrityWarnings:$g,buildExtensionHealthTriageSummary:Tg,buildHealthFindings:Fg,buildCapabilityContractMetadata:Ur,buildStaleInProgressHealthSummary:Mg,buildVectorizationProviderDetails:Lg,collectUnknownCapabilityGuidance:Hr,isAdvisoryHealthWarning:Ac,isDirectory:Cc,isExpectedUnmanagedExtension:Sc,listItemDocumentPaths:Cg,normalizeEndpointForDisplay:In,normalizeExtensionNameForMatch:Yn,parseTelemetryQueue:Og,probeTelemetryEndpointHealth:Pg,projectHealthResult:ha,resolveActionableUnknownAuthorEventCount:Tc,resolveHealthSkipPolicy:Dg,resolveUnknownAuthorEventCount:$c,resolveVectorRefreshPolicy:Ng,selectStaleItemDetail:Rc,summarizeHealthCheckDetails:pa,summarizeExtensionList:Er,summarizeRecordList:Ve,summarizeStringList:G,telemetryEnvFlagEnabled:jo,warningCode:Ic};function Hg(e,t,n){if(!n.has(t.metadata.status))return{reason:"not_terminal"};if(e.length===0)return{reason:"missing_history"};if(!rm(e,t).ok)return{reason:"unverified_history"};let r=Nt(),i={reason:"no_proven_transition"};for(let[o,s]of e.entries()){let a=n.has(String(r.metadata.status));r=Su(r,s.patch,o+1,s.op),n.has(String(r.metadata.status))?a||(i=["create","close","cancel","update","update_audit"].includes(s.op)&&Pt(s.ts)?{timestamp:s.ts,source_index:o+1}:{reason:"no_proven_transition"}):i={reason:"no_proven_transition"}}return i}function Ug(e){return new Set([...e.terminal_statuses,...[...e.alias_to_id].filter(([,t])=>e.terminal_statuses.has(t)).map(([t])=>t)])}async function zg(e,t,n,r,i){let o=Ug(n),s=t.filter(d=>o.has(d.status)&&!d.closed_at),a=[],c=[];for(let d of r?s:[]){let l;try{let u=await We(pt(e,d.id),d.id),{body:m,...p}=d;l=Hg(u,{metadata:p,body:m},o)}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:s.length,missing_closed_at_item_ids:s.slice(0,i).map(d=>d.id),missing_closed_at_item_ids_truncated:s.length>i,closure_history_inspected:r,closure_timestamp_derivable_count:a.length,closure_timestamp_residual_count:c.length,closure_timestamp_residual:c.slice(0,i),closure_timestamp_residual_truncated:c.length>i,...s.length>0?{closure_timestamp_fix_hint:"pm validate --check-metadata --auto-fix --fix-scope timestamps --dry-run"}:{}},fixes:a,warnings:s.length>0?[`validate_metadata_missing_closed_at:${s.length}`]:[]}}async function Wg(e,t){let n=M(process.cwd(),t.path),r=await T(n),i=_e(r.schema);await yt({pmRoot:n,settings:r,id:e.item_id,op:"update",author:q(t.author,r.author_default),message:"Backfill closed_at from verified lifecycle history",skipNoop:!0,async mutate(o){if(o.metadata.closed_at)return{changedFields:[]};let s=await We(pt(n,o.metadata.id),o.metadata.id),a=Ug(i),c=Hg(s,o,a);if(!("timestamp"in c)||c.timestamp!==e.value)throw new _("Closure timestamp evidence changed or cannot be verified; rerun the timestamp repair preview.",g.GENERIC_FAILURE);return o.metadata.closed_at=c.timestamp,{changedFields:["closed_at"]}}})}function G$(e,t){return e==="malformed"||t==="malformed"?"malformed":e==="moved"||t==="moved"?"moved":"deleted"}function qg(e){return`${e.item_id} ${e.link_kind}`}function Gg(e,t){let n=new Map;for(let r of e){let i=n.get(r.path);i?(i.classification=G$(i.classification,r.classification),i.owners.set(qg(r),r)):n.set(r.path,{classification:r.classification,owners:new Map([[qg(r),r]])})}return[...n.entries()].sort(([r],[i])=>r.localeCompare(i)).map(([r,i])=>({path:r,classification:i.classification,items:[...i.owners.values()].map(o=>{let s=t(o.item_id);return{id:o.item_id,type:s?.type??"Unknown",title:s?.title??"",status:s?.status??"",field:o.link_kind}}).sort((o,s)=>{let a=o.id.localeCompare(s.id);return a!==0?a:o.field.localeCompare(s.field)})}))}function Bg(e,t,n,r,i=40){let o=i===1/0?1/0:Number.isFinite(i)?Math.max(0,Math.floor(i)):40,s=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=Gg(e,n).map(d=>{let l=[],u=[];for(let p of d.items){let f=wi(p.status,r)??p.status;r.terminal_statuses.has(f)?(u.push(p),f===r.close_status&&(a.legacy_closed_missing_linked_links_count+=1)):l.push(p)}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 m=s.get(d.path);return{...d,candidates:m?.candidates??[],candidates_truncated:m?.candidates_truncated??!1,link_count:d.items.length,active_link_count:l.length,items:[...l,...u].slice(0,o),items_truncated:d.items.length>o}});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,o),a.missing_linked_path_rows_truncated=c.length>o,a}import Xn from"node:fs/promises";import Zn from"node:path";async function B$(e,t){let n=[...new Set(Object.values(t))],r=[];return await Promise.all(n.map(async i=>{let o;try{o=await Xn.readdir(Zn.join(e,i))}catch{return}for(let s of o)for(let a of sr)if(s.toLowerCase().endsWith(a)){r.push({relativePath:`${i}/${s}`,id:s.slice(0,-a.length)});break}})),r.sort((i,o)=>i.relativePath.localeCompare(o.relativePath))}function J$(e,t){let{id:n,relativePath:r,liveItemIds:i,out:o}=e,s=Ne(t);if(s){o.conflictMarkers.push({id:n,path:r,line:s.line,detail:`unresolved merge conflict marker ${s.marker}`});return}let a=V$(e,t);a!==null&&(a.op==="delete"&&i.has(n)&&o.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&&(o.repairReconciliations+=1))}function V$(e,t){let{id:n,relativePath:r,out:i}=e,o=null,s=!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");o=d}catch{return i.unparseable.push({id:n,path:r,line:c.number,detail:"history line is not a valid JSON object"}),null}if(o.op==="create"){if(s)return i.unparseable.push({id:n,path:r,line:c.number,detail:"duplicate item identity: more than one create event in one history stream"}),null;s=!0}}return o}function Oc(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 K$(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},r;try{r=await Xn.readdir(Zn.join(e,"history"))}catch{return n}for(let i of r.sort((o,s)=>o.localeCompare(s))){if(!i.endsWith(".jsonl"))continue;n.scanned+=1;let o;try{o=await Xn.readFile(Zn.join(e,"history",i),"utf8")}catch(s){n.unparseable.push({id:i.slice(0,-6),path:`history/${i}`,detail:Oc("history stream",s)});continue}J$({id:i.slice(0,-6),relativePath:`history/${i}`,liveItemIds:t,out:n},o)}return n}function Jg(e){let t=Ne(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 Y$(e){let t=[],n=0,r=null;try{r=await B(un(e))}catch(o){n+=1,t.push({path:"settings.json",detail:Oc("configuration file",o)})}if(r!==null){n+=1;let o=Jg(r);o!==null&&t.push({path:"settings.json",detail:o})}let i;try{i=await Xn.readdir(Zn.join(e,"schema"))}catch{return{scanned:n,unparseable:t}}for(let o of i.sort((s,a)=>s.localeCompare(a))){if(!o.endsWith(".json"))continue;n+=1;let s;try{s=await Xn.readFile(Zn.join(e,"schema",o),"utf8")}catch(c){t.push({path:`schema/${o}`,detail:Oc("configuration file",c)});continue}let a=Jg(s);a!==null&&t.push({path:`schema/${o}`,detail:a})}return{scanned:n,unparseable:t}}async function Vg(e,t,n,r={}){let i=await B$(e,n),o=new Set(i.map(u=>u.id)),s=new Map;for(let u of i){let m=s.get(u.id);m===void 0?s.set(u.id,[u.relativePath]):m.push(u.relativePath)}let a=[...s.entries()].filter(([,u])=>u.length>1).map(([u,m])=>({id:u,paths:[...m].sort((p,f)=>p.localeCompare(f))})).sort((u,m)=>u.id.localeCompare(m.id)),c=(await Promise.all(i.map(async u=>{if(!t.has(u.id))return{path:u.relativePath,id:u.id};try{let m=Zn.join(e,u.relativePath);return Lt(await Xn.readFile(m,"utf8"),{format:m.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 K$(e,o),l=await Y$(e);return{item_files_on_disk:i.length,item_ids_on_disk:o.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 gd from"node:fs/promises";import{realpathSync as UT}from"node:fs";import{execFile as zT}from"node:child_process";import Ie from"node:path";import{promisify as WT}from"node:util";var X$=["metadata","resolution"],Pc=["metadata","resolution","estimates","timestamps","lifecycle"],Z$="completed";function Lc(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function Kg(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function Yg(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let r=Kg(n.close_reason)??Z$;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:r,command:`pm update ${n.id} --resolution ${Lc(r)}`,gate:"resolution"})}return t}function Xg(e){let t=[];for(let n of e){let r=Kg(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 ${Lc(r)}`,gate:"metadata"})}return t}function Zg(e,t){return e.map(n=>{let r=vu(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 Qg(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 ey(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 ${Lc(n.path)}`})}return t}function ty(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 _(`--fix-scope values must not be empty. Supported values: ${Pc.join(", ")}.`,g.USAGE);return new Set(X$)}let n=new Set;for(let r of t){let i=r.toLowerCase().replaceAll("-","_");if(Pc.includes(i)){n.add(i);continue}throw new _(`Unknown --fix-scope value "${r}". Supported values: ${Pc.join(", ")}.`,g.USAGE)}return n}function ny(e,t){let n=[],r=[];for(let i of e)i.gate!==void 0&&!t.has(i.gate)?r.push(i):n.push(i);return{applicable:n,gated:r}}function Yr(e){return{item_id:e.item_id,check:e.check,field:e.field,command:e.command,...e.gate!==void 0?{gate:e.gate}:{}}}var Q$=/^([A-Z][A-Z0-9]*-\d+)\b/iu;function e0(e,t={}){if(typeof e!="string")return null;let n=e.trim();if(n.length===0)return null;let r=Q$.exec(n);if(!r)return null;let i=r[1],o=i.toUpperCase(),s=i.slice(0,i.lastIndexOf("-")),a=new Set((t.configuredPrefixes??[]).map(m=>m.trim().replace(/-+$/u,"").toUpperCase())),c=n.slice(i.length),d=t.evidenceText?.toUpperCase()??"",l=d.includes(`ISSUE CODE: ${o}`)||d.includes(`ISSUE CODE \`${o}\``)||d.includes(`\`${o}\``)||d.includes(`[${o}]`);return s===s.toUpperCase()||/^\s*(?::|—|–|\])/u.test(c)||a.has(s.toUpperCase())||l?o:null}function ry(e){return typeof e=="string"&&e.trim().length>0}function t0(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 o=[...[...n].filter(([,a])=>a.size===0).map(([a])=>a)],s=new Set;for(let a=0;a<o.length;a+=1)for(let c of r.get(o[a])??[]){let d=n.get(c);d.delete(o[a]),d.size===0&&(s.add(c),o.push(c))}return e.filter(a=>!s.has(a.id.toLowerCase()))}function iy(e,t={}){let n=new Map;for(let i of e){if(typeof i.title!="string"||ry(i.duplicate_of))continue;let o=e0(i.title,{...t,evidenceText:i.body});if(o===null)continue;let s=n.get(o);s||(s=[],n.set(o,s)),s.some(a=>a.id===i.id)||s.push({id:i.id,title:i.title,parent:ry(i.parent)?i.parent.trim():null,derivations:(i.dependencies??[]).filter(a=>["discovered_from","supersedes","incident_from"].includes(a.kind)).map(a=>a.id.trim().toLowerCase()).filter(a=>a!==i.id.toLowerCase())})}let r=[];for(let[i,o]of n){if(o.length<2)continue;let s=t0(o);if(s.length<2)continue;let a=[...s].sort((c,d)=>c.id.localeCompare(d.id));r.push({code:i,count:a.length,ids:a.map(c=>c.id),titles:a.map(c=>c.title)})}return r.sort((i,o)=>i.code.localeCompare(o.code))}function oy(e){let t=new Map;for(let r of e){let i=t.get(r.item_type);i||(i=new Map,t.set(r.item_type,i)),i.set(r.field,(i.get(r.field)??0)+1)}let n={};for(let r of[...t.keys()].sort((i,o)=>i.localeCompare(o))){let i=t.get(r),o={};for(let s of[...i.keys()].sort((a,c)=>a.localeCompare(c)))o[s]=i.get(s);n[r]=o}return n}function sy(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function ay(e,t,n=3){let r=Number.isFinite(n)&&n>=1?Math.floor(n):3,i=new Map;for(let o of t){let s=sy(o);if(s.length===0)continue;let a=i.get(s);a?a.push(o):i.set(s,[o])}return e.map(o=>{if(o.includes(",")||o.replace(/^[a-z]:[\\/]/i,"").includes(":"))return{path:o,classification:"malformed",candidates:[],candidates_truncated:!1};let s=(i.get(sy(o))??[]).filter(a=>a!==o).sort((a,c)=>a.localeCompare(c));return s.length===0?{path:o,classification:"deleted",candidates:[],candidates_truncated:!1}:{path:o,classification:"moved",candidates:s.slice(0,r),candidates_truncated:s.length>r}})}function cy(e){return e.map(t=>t.classification==="moved"?`${t.path}:moved:${t.candidates[0]}`:`${t.path}:${t.classification}`)}var n0=/^[a-z][a-z0-9+.-]+:\/\//i;function Xr(e){return n0.test(e.trim())}import R0 from"node:fs/promises";import Pe from"node:path";import{readdir as uy,realpath as my,stat as py}from"node:fs/promises";import Se from"node:path";var r0=4096,i0=32,o0=1e3,s0=5e4,a0={nodes:1e4,edges:4e4,stateIds:2e6},on=47,Qn=class extends Error{},c0=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 fy(){return new _("--add-glob does not support negated patterns (a leading ! or !(...)); list the files or patterns to link instead",g.USAGE)}function d0(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 i=e.indexOf(":",n+2);i===-1||e[i+1]!=="]"?n+=1:n=i+2}else{if(r==="]")return n+1;n+=1}}return-1}function l0(e,t,n){let r=e[t];if(r==="{")return{index:t,kind:"{"};if(r!=="(")return;let i=e[t-1];return i!==void 0&&"@?*+!".includes(i)&&!hy(e,t-1)?{index:t-1,kind:"("}:n.some(o=>o.kind==="(")?{index:t,kind:"plain"}:void 0}function u0(e,t,n,r,i){let o=e[t],s=n.at(-1);if(o===")"&&s?.kind==="plain"){n.pop(),i.set(s.index,t);return}let a=o==="}"?"{":o===")"?"(":void 0;if(!(a===void 0||s?.kind!==a)&&(n.pop(),r.set(s.index,t),e[s.index]==="!"))throw fy()}function m0(e){let t=new Map,n=new Map,r=new Map,i=[],o=0;for(;o<e.length;){if(e[o]==="\\"){o+=2;continue}let s=e[o]==="["?d0(e,o):-1;if(s!==-1){n.set(o,s),o=s;continue}let a=l0(e,o,i);if(a!==void 0?i.push(a):u0(e,o,i,t,r),i.length>i0)throw new Qn;o+=1}return{closers:t,brackets:n,groups:r}}function hy(e,t){let n=0;for(let r=t-1;r>=0&&e[r]==="\\";r-=1)n+=1;return n%2===1}function rn(e){return Array.from(e,t=>({kind:"char",value:t.codePointAt(0)}))}function p0(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,i]=t!==null?[Number(t[1]),Number(t[2])]:[n[1].codePointAt(0),n[2].codePointAt(0)];if(Math.abs(i-r)+1>o0)throw new Qn;let o=r<=i?1:-1,s=[];for(let a=r;a!==i+o;a+=o)s.push(t!==null?String(a):String.fromCodePoint(a));return s}function f0(e,t){if(e[t]!=="["||e[t+1]!==":")return;let n=e.indexOf(":",t+2);if(!(n===-1||e[n+1]!=="]"))return{ranges:c0.get(e.slice(t+2,n).join(""))??[],next:n+2}}function dy(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 h0(e,t,n){let r=[];for(let i=t;i<n;i+=1)e[i]==="\\"&&i+1<n&&(i+=1),r.push(e[i].codePointAt(0));return r}function _0(e,t,n){let r=t+1,i=e[r]==="!"||e[r]==="^";i&&(r+=1);let o=[],s=n-1;for(;r<s;){let a=f0(e,r);if(a!==void 0){o.push(...a.ranges),r=a.next;continue}let c=dy(e,r,s);if(r=c.next,e[r]!=="-"||r+1>=s){o.push([c.codePoint,c.codePoint]);continue}let d=dy(e,r+1,s);r=d.next,c.codePoint<=d.codePoint&&o.push([c.codePoint,d.codePoint])}return{kind:"class",negated:i,ranges:o,literal:h0(e,t,n)}}var Nc=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 i=[],o=t;for(;;){let{nodes:s,stop:a}=this.sequence(o,n,r);if(i.push(s),a>=n)return i;o=a+1}}sequence(t,n,r){let i=[],o=t;for(;o<n;){if(this.chars[o]===r)return{nodes:i,stop:o};let s=this.token(o,n);i.push(...s.nodes),o=s.next}return{nodes:i,stop:n}}token(t,n){let r=this.chars[t];if(r==="\\")return{nodes:rn(t+1<n?this.chars[t+1]:"\\"),next:t+2};let i=this.closers.get(t);if(i!==void 0)return{nodes:r==="{"?this.brace(t,i):this.extglob(r,t,i),next:i+1};let o=this.groups.get(t);if(o!==void 0)return{nodes:[...rn("("),...this.sequence(t+1,o,void 0).nodes,...rn(")")],next:o+1};let s=this.brackets.get(t);return s!==void 0?{nodes:[_0(this.chars,t,s)],next:s}:r==="*"?this.stars(t,n):{nodes:r==="?"?[{kind:"any"}]:rn(r),next:t+1}}extglob(t,n,r){let i=this.alternatives(n+2,r,"|");return[t==="@"?{kind:"alt",options:i}:{kind:"repeat",optional:t!=="+",many:t!=="?",options:i}]}brace(t,n){let r=this.alternatives(t+1,n,",");if(r.length>1)return[{kind:"alt",options:r}];let i=p0(this.chars.slice(t+1,n).join(""));return i!==void 0?[{kind:"alt",options:i.map(rn)}]:[...rn("{"),...r[0],...rn("}")]}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 i=t+r<n&&this.chars[t+r]==="/";return{nodes:[{kind:"globstar",slash:i}],next:t+r+(i?1:0)}}},Dc=["segment","inside"],Ho={kind:"any"};function Mc(e){return Dc.flatMap(t=>e[t]===void 0?[]:[e[t]])}var Fc=class{states=[];add(){if(this.states.length>=s0)throw new Qn;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 i=this.add();for(let o of Mc(t))this.states[o].edges.push({test:n,to:i});return{[r]:i}}join(t){let n={};for(let r of Dc){let i=t.flatMap(o=>o[r]===void 0?[]:[o[r]]);if(i.length===1&&(n[r]=i[0]),i.length>1){let o=this.add();for(let s of i)this.epsilon(s,o);n[r]=o}}return n}feed(t,n){for(let r of Dc)t[r]!==void 0&&this.epsilon(t[r],n[r])}build(t,n){let r=n;for(let i of t)r=this.node(i,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 Mc(t))this.epsilon(r,n,!1);return this.states[n].edges.push({test:Ho,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:Ho,to:r}),this.states[r].edges.push({test:Ho,to:r},{test:{kind:"char",value:on},to:n}),n}globstar(t,n){if(n){let i=[];return t.segment!==void 0&&i.push({segment:this.segments(t.segment)}),t.inside!==void 0&&i.push(this.consume(this.star({inside:t.inside}),{kind:"char",value:on},"segment")),this.join(i)}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 i of this.states[r.pop()].syntactic)n.has(i)||(n.add(i),r.push(i));return n}resolveGlobstars(t){for(let{continuation:n,entry:r}of this.globstars){let i=this.syntacticClosure([n]);if(i.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 o=new Set;for(let a of i)for(let{test:c,to:d}of this.states[a].edges)_y(c,on)&&o.add(d);if(o.size===0)continue;let s=this.segments(r);for(let a of o)this.epsilon(s,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===on?"segment":"inside");case"any":return this.consume(n,Ho,"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 _y(e,t){switch(e.kind){case"char":return e.value===t;case"any":return t!==on;case"all":return!0;case"class":return t!==on&&e.ranges.some(([n,r])=>t>=n&&t<=r)!==e.negated}}var jc=class{generation=0;nextId=0;nodes=new Map;edges=new Map;stateIds=0;nfa;acceptState;limits;start;constructor(t,n,r,i){this.nfa=t,this.acceptState=r,this.limits=i,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 i of this.nfa.states[r.pop()].epsilon)n.has(i)||(n.add(i),r.push(i));return[...n].sort((i,o)=>i-o)}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 i={id:this.nextId,generation:this.generation,states:t,accepting:t.includes(this.acceptState)};return this.nextId+=1,this.nodes.set(n,i),this.stateIds+=t.length,i}step(t,n){let r=`${t.id}:${n}`,i=t.generation===this.generation?this.edges.get(r):void 0;if(i!==void 0)return i;let o=[];for(let a of t.states)for(let{test:c,to:d}of this.nfa.states[a].edges)_y(c,n)&&o.push(d);let s=this.node(this.closure(o));return this.edges.size>=this.limits.edges&&this.reset(),t.generation===this.generation&&this.edges.set(r,s),s}advance(t,n){let r=t;for(let i of n){if(r.states.length===0)return r;r=this.step(r,i.codePointAt(0))}return r}};function g0(e,t=a0){let n=Array.from(e),r=new Nc(n,m0(n)).sequence(0,n.length,void 0).nodes,i=new Fc,o=i.add(),s=i.add();for(let a of Mc(i.build(r,{segment:o})))i.epsilon(a,s);return i.resolveGlobstars(s),new jc(i,o,s,t)}function y0(e){return!/[*?[\]{}()!@+\\]/u.test(e)}function ly(e){return e.isFile()?"file":e.isDirectory()?"directory":"other"}async function w0(e,t,n){if(!n.isSymbolicLink())return{kind:ly(n),real:Se.join(t,n.name)};try{let r=await my(Se.join(e,n.name));return{kind:ly(await py(r)),real:r}}catch{return}}async function gy(e,t,n,r,i,o,s){let a;try{a=await uy(t,{withFileTypes:!0})}catch{return}for(let c of a){let d=e.advance(i,c.name);if(d.states.length===0)continue;let l=await w0(t,n,c);if(l===void 0)continue;let u=Se.posix.join(r,c.name);if(l.kind==="file"&&d.accepting&&s.push(u),l.kind!=="directory")continue;let m=e.step(d,on);m.states.length===0||o.has(l.real)||(o.add(l.real),await gy(e,Se.join(t,c.name),l.real,u,m,o,s),o.delete(l.real))}}function v0(e){let t=Se.posix.normalize(e);return/^\/\/[^/]/u.test(e)?`/${t}`:t}function k0(e){let t=e;for(;t.length>1&&t.endsWith("/")&&!hy(t,t.length-1);)t=t.slice(0,-1);return t}async function yy(e,t){return(await uy(e).catch(()=>[])).includes(t)}async function wy(e,t){let n=e,r=0;for(;t[r]==="..";)n=Se.dirname(n),r+=1;for(;r<t.length;r+=1){if(!await yy(n,t[r]))return!1;n=Se.join(n,t[r])}return!0}function vy(e,t=process.platform){return e.startsWith("/")||t==="win32"&&/^[A-Za-z]:\//u.test(e)}async function b0(e,t){let n=Se.resolve(t,e),r=await py(n).catch(()=>{});if(r===void 0||!r.isFile())return[];let i=vy(e);return(i?await yy(Se.dirname(n),Se.basename(n)):await wy(t,e.split("/")))?[i?n.replaceAll("\\","/"):Se.posix.normalize(e)]:[]}function x0(e,t){let n=e.split("/"),r=0;for(;r<n.length&&y0(n[r]);)r+=1;if(r===n.length)return;let i=r===0?"":`${n.slice(0,r).join("/")}/`,o=Se.resolve(t,i),s=n.slice(r).join("/");if(vy(e))return{root:o,base:o.replaceAll("\\","/"),rest:s,prefix:[]};let a=Se.posix.normalize(i===""?".":i).replace(/\/$/u,"");return{root:o,base:a==="."?"":a,rest:s,prefix:n.slice(0,r)}}function S0(e){try{return g0(e)}catch(t){if(t instanceof Qn)return;throw t}}async function ky(e,t){if(e.startsWith("!"))throw fy();if(Array.from(e).length>r0)return[];let n=k0(v0(e)),r=x0(n,t);if(r===void 0)return b0(n,t);let i=S0(r.rest);if(i===void 0||!await wy(t,r.prefix))return[];let o=await my(r.root).catch(()=>{});if(o===void 0)return[];let s=[];return await gy(i,r.root,o,"",i.start,new Set([o]),s),s.map(a=>E0(r.base,a))}function E0(e,t){return e.startsWith("//")?`/${Se.posix.join(e.slice(1),t)}`:Se.posix.join(e,t)}var Hc=["refuse","replace","append"],zc="; ";function A0(e,t){if(e===void 0)return"refuse";let n=e.trim().toLowerCase();if(!Hc.some(r=>r===n))throw new _(`--note-conflict must be one of ${Hc.join(", ")}; got "${e}"`,g.USAGE,{code:"invalid_argument_value",flag:"--note-conflict",value:e,required:`Pass --note-conflict ${Hc.join("|")}.`});if(!t)throw new _("--note-conflict requires --add or --add-glob in the same invocation (it decides how those links treat an existing note)",g.USAGE,{code:"missing_required_argument",flag:"--note-conflict",required:"Pass --add or --add-glob with --note-conflict."});return n}function I0(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=zc;return`${r}${e}${r}`.includes(`${r}${t}${r}`)?{note:e,outcome:"unchanged",conflict:!1}:{note:`${e}${zc}${t}`,outcome:"note_appended",conflict:!1}}return{note:e,outcome:"unchanged",conflict:!0}}function C0(e){let t=e.conflicts[0],n=e.conflicts.length>1?` and ${e.conflicts.length-1} more`:"",r=e.retryArgs("append"),i=e.retryArgs("replace"),o=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 _(o,g.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||i===void 0?{}:{nextSteps:[e.render(r),e.render(i)],recovery:{suggested_retry:e.render(r),suggested_retry_args:r}},details:{conflicts:e.conflicts.map(s=>({...s}))}})}var Wc=["path","scope","note"],$0=["pattern","glob","path","scope","note"],T0=["path"],O0=["from","to"],P0=new Set(["note","scope"]);function by(e){return JSON.parse(JSON.stringify(e))}function L0(e,t){let n=e.map(by);return t.filter(r=>{let i=by(r),o=n.findIndex(s=>ps(s,i));return o>=0&&n.splice(o,1),o<0})}function xy(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 Sy(e){let t=e??"project";if(!us.includes(t))throw new _(`Invalid scope "${e}". Valid scopes: ${us.join(", ")} (default: project).`,g.USAGE);return t}function qc(e){if(e.startsWith("```")||e.includes(`
|
|
69
|
+
`)||/^(?:[-*+]\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(i=>i>=0&&i<r))?!1:n.includes("=")||uu(e)}function N0(e){let t=0;for(let n of e)if(n==="("&&(t+=1),n===")"&&(t-=1),t<0)return!1;return t===0}function D0(e){if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)&&!qc(e))return{path:e,scope:"project",note:void 0};let t=e.indexOf("](");if(e.startsWith("[")&&t>0&&e.endsWith(")")){let o=e.slice(t+2,-1).trim();if(o.length>0&&N0(o))return{path:o,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(),i=e.slice(n+1).trim();if(!(r.length===0||!/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(i)))return{path:i,scope:"project",note:r}}function Jc(e,t){return e?e.flatMap(n=>{let r=n.trim();if(t==="doc"){let o=D0(r);if(o!==void 0)return[o]}mu(r,"--add",`${t} path`,qc(r));let i=qc(r)?ur(n,"--add"):{path:r};if(mr(i,"--add",Wc),!i.path)throw new _(`--add requires path=<value> or a bare ${t} path`,g.USAGE);return[{path:i.path,scope:Sy(i.scope),note:i.note?.trim()||void 0}]}):[]}function M0(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new _("--add-glob requires a glob pattern value",g.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?(?:pattern|glob|path)\s*[:=]/i.test(n)||n.startsWith("```")){let r=ur(n,"--add-glob");mr(r,"--add-glob",$0);let i=r.pattern?.trim()||r.glob?.trim()||r.path?.trim();if(!i)throw new _("--add-glob key/value form requires pattern=<glob>",g.USAGE);return{pattern:i,scope:Sy(r.scope),note:r.note?.trim()||void 0}}return{pattern:n,scope:"project"}}):[]}function F0(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new _("--remove requires a path value",g.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?path\s*[:=]/i.test(n)||n.startsWith("```")){let r=ur(n,"--remove"),i=Object.keys(r).filter(o=>P0.has(o.toLowerCase()));if(i.length>0)throw new _(`--remove identifies a linked artifact by path only and does not accept ${i.map(o=>`"${o}"`).join(", ")}. Pass just the path (path=<value>, path:<value>, or a bare path); record removal context with --message "<why removed>".`,g.USAGE);if(mr(r,"--remove",T0),!r.path)throw new _("--remove key/value form requires path=<value>",g.USAGE);return r.path}return n}):[]}function j0(e){return e?e.map(t=>{let n=ur(t,"--migrate");mr(n,"--migrate",O0);let r=n.from?.trim(),i=n.to?.trim();if(!r||!i)throw new _("--migrate requires from=<value> and to=<value>",g.USAGE);return{from:r,to:i}}):[]}function er(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 H0(e,t,n=[]){if(e.length===0||t.length===0)return;let r=new Set(e.map(o=>qt(er(o.path,n)))),i=[...new Set(t.map(o=>qt(er(o,n))).filter(o=>r.has(o)))].sort((o,s)=>o.localeCompare(s));if(i.length!==0)throw new _(`Linked artifact mutation cannot add and remove the same normalized path in one transaction: ${i.join(", ")}. Split the replacement into separate commands so each history event has one unambiguous intent.`,g.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 Ct(e){return e.split(Pe.sep).join("/")}function Gc(e,t,n=process.cwd()){let r=e.trim();if(Xr(r))return r;if(Pe.isAbsolute(r)||/^[A-Za-z]:[\\/]/.test(r))return Ct(r.replaceAll("\\",Pe.sep));let i=Pe.relative(t,n);return i.startsWith(`..${Pe.sep}`)||i===".."||Pe.isAbsolute(i)?Ct(Pe.normalize(r)):Ct(Pe.relative(t,Pe.resolve(n,r)))}async function U0(e,t=process.cwd(),n=process.cwd()){let r=[];for(let i of e){if(Pe.resolve(n,i.pattern)===Pe.resolve(n))continue;let o=await ky(i.pattern,n),s=[...new Set(o.map(a=>Gc(a,t,n)))].sort((a,c)=>a.localeCompare(c));for(let a of s)r.push({path:a,scope:i.scope,note:i.note})}return r}function z0(e,t,n){if(t===void 0)return e;if(!n)throw new _("--note requires --add or --add-glob in the same invocation (the note annotates the links being added)",g.USAGE);let r=t.trim();return r.length===0?e:e.map(i=>i.note===void 0?{...i,note:r}:i)}function Bc(e){return`${e.path}::${e.scope}`}function Vc(e){return[...e].sort((t,n)=>{let r=t.path.localeCompare(n.path);return r!==0?r:t.scope.localeCompare(n.scope)})}function Kc(e){return[...new Map(e.map(t=>[Bc(t),t])).values()].map(t=>({...t,note:t.note?.trim()||void 0}))}async function W0(e,t=process.cwd()){let n=[...new Set(e)].sort((a,c)=>a.localeCompare(c)),r=[],i=[],o=[],s=[];for(let a of n){if(Xr(a)){s.push(a.trim());continue}let c=Pe.isAbsolute(a)?a:Pe.resolve(t,a);try{(await R0.stat(c)).isFile()?r.push(a):o.push(a)}catch(d){if(typeof d=="object"&&d!==null&&"code"in d&&Qe(d)){i.push(a);continue}o.push(a)}}return{checked:n.length,existing_files:r,missing_paths:i,non_file_paths:o,remote_references:s}}function q0(e,t,n,r){let i=0;for(let s=0;s<e.length;s+=1){let a=er(e[s].path,r);a!==e[s].path&&(i+=1);let c=qt(a);c!==e[s].path&&(e[s]={...e[s],path:c})}return{adds:t.map(s=>{let a=er(s.path,r);return a!==s.path&&(i+=1),{...s,path:qt(a)}}),removes:n.map(s=>qt(er(s,r))),count:i}}function qt(e){return e.replaceAll("\\","/")}function Uc(e){return`${e.scope}\0${qt(e.path)}`}function G0(e,t,n){let r=new Map(e.map(s=>[Uc(s),s.note])),i=new Map(t.map(s=>[Uc(s),s.note])),o=new Map;for(let s of n){let a=Uc(s);o.has(a)||o.set(a,{path:qt(s.path),scope:s.scope,outcome:B0(r.has(a),r.get(a),i.get(a))})}return[...o.values()]}function B0(e,t,n){return e?n===t?"unchanged":t===void 0?"note_added":n?.startsWith(`${t}${zc}`)?"note_appended":"note_replaced":"added"}function J0(e,t,n){let r=e.merged.findIndex(s=>s.path===t.path&&s.scope===t.scope),i=e.merged[r];if(i===void 0){e.merged.push(t),t.note!==void 0&&e.notedHere.add(t);return}let o=I0(i.note,t.note,n);if(o.conflict)e.conflicts.push({path:t.path,scope:t.scope,existing_note:i.note,requested_note:t.note,source:e.notedHere.has(i)?"this_write":"stored"});else if(o.note!==i.note){let s={...i,note:o.note};e.merged[r]=s,e.notedHere.add(s)}}function V0(e,t,n,r,i){let o=Kc(e),s={merged:[...o],notedHere:new Set,conflicts:[]};for(let d of t)J0(s,d,i);let{merged:a}=s,c=G0(o,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:Vc(a),outcomes:c,conflicts:s.conflicts}}async function Ey(e){let t=e.mutation?.entries??e.artifacts,n=e.options.validatePaths?e.artifacts:t,{counts:r,receipts:i}=eT(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 W0(n.map(o=>o.path),e.workspaceRoot):void 0,...i}}function K0(e,t,n){let r=new Map;for(let o of t){let s=Bc(o);r.set(s,(r.get(s)??0)+1)}let i=0;for(let o of e){let s=Bc({...o,path:qt(er(o.path,n))}),a=r.get(s)??0;a>0?r.set(s,a-1):i+=1}return i}function Y0(e,t){let n=/[\n\r]|^\s*[-*+`]/u.test(e)?[]:lu(e),r=n.findIndex(l=>l.key?.toLowerCase()==="note");if(r<0)return;let i=n.slice(0,r).map(l=>l.raw.trim()),o=new Set(n.slice(0,r).map(l=>l.key?.toLowerCase())),s=[n[r].value],a;for(let l of n.slice(r+1)){let u=l.key?.toLowerCase();if((u==="path"||u==="scope")&&!o.has(u)){i.push(l.raw.trim()),o.add(u);continue}a??=l.key===void 0?void 0:{segment:l.text.trim(),key:l.key},s.push(l.text)}if(a===void 0)return;let c=s.join(",").trim(),d=[...i,`note=${JSON.stringify(c)}`].join(",");try{Jc([d],t)}catch{return}return{entry:d,note:c,...a}}function X0(e,t){return e.findIndex(n=>{try{return Jc([n],t),!1}catch{return!0}})+1}function Uo(e,t,n){return(t??[]).flatMap(r=>[e,n!==void 0&&r.trim()==="-"?`${n}=-`:r])}function Ry(e){let{options:t}=e,n=e.noteConflict??t.noteConflict;return[...Ci(e.global),...e.guards.map(r=>`--expect-hash=${r}`),e.config.metadataKey,e.id,...Uo("--add",e.entries.map((r,i)=>i===e.position-1?e.rewritten:r),"path"),...Uo("--add-glob",e.resolved.addGlob,"pattern"),...Uo("--remove",e.resolved.remove,"path"),...Uo("--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 Z0(e){return Wc.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: ${Wc.join(", ")}.`}function Q0(e){try{return Jc(e.entries,e.config.bareNoun)}catch(t){let n=e.entries,r=t,i=X0(n,e.config.bareNoun),o=Y0(n[i-1],e.config.bareNoun);if(o===void 0)throw t;let s=As(e.pmRoot),a=s===void 0?void 0:Ry({...e,entries:n,position:i,rewritten:o.entry,guards:s});throw new _(`--add read the note segment "${o.segment}" as a new key "${o.key}", so the ${e.config.bareNoun} link was refused (${r.message})`,g.USAGE,{code:"linked_artifact_note_key_misread",flag:"--add",value:n[i-1],required:`Retry with the note quoted so its commas stay prose (${a===void 0?`as ${o.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. ${Z0(o.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:[K(a)]},details:{entry_index:i,misread_segment:o.segment,misread_key:o.key,note:o.note,rewritten_entry:o.entry,cause:r.context.code??"invalid_argument_value"},...a===void 0?{}:{recovery:{suggested_retry:K(a),suggested_retry_args:a}}})}}function eT(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 tT(e){let{settings:t,config:n}=e,r=await ge(e.pmRoot,e.id,t.id_prefix,t.item_format,e.typeToFolder);if(!r)throw new _(`Item ${e.id} not found`,g.NOT_FOUND);let o=(await ye(r,{schema:t.schema})).document.metadata[n.metadataKey]??[],s=e.writeRequested?xy({collectionKey:n.metadataKey,stored:o,written:[],removedCount:0,fullHistory:e.options.fullHistory===!0}):void 0;return Ey({id:r.id,artifacts:o,changed:!1,options:e.options,workspaceRoot:e.workspaceRoot,mutation:s})}async function zo(e,t,n,r){let{metadataKey:i}=r,o=pu(),s=M(process.cwd(),n.path),a=tt(s),c=process.cwd();await ie(s);let d=await T(s),l=W(d,U()),u=await o.resolveList(t.add,"--add"),m=await o.resolveList(t.addGlob,"--add-glob"),p=await o.resolveList(t.remove,"--remove"),f=await o.resolveList(t.migrate,"--migrate"),h=Q0({id:e,pmRoot:s,entries:u,resolved:{addGlob:m,remove:p,migrate:f},options:t,global:n,config:r}).map(we=>({...we,path:Gc(we.path,a,c)})),y=M0(m),w=await U0(y,a,c),v=h.length>0||y.length>0,k=z0([...h,...w],t.note,v),x=A0(t.noteConflict,v),E=F0(p).map(we=>Gc(we,a,c)),A=j0(f);if(H0(k,E,A),!(k.length>0||E.length>0||A.length>0))return tT({id:e,pmRoot:s,settings:d,typeToFolder:l.type_to_folder,options:t,workspaceRoot:a,config:r,writeRequested:y.length>0});let b=q(t.author,d.author_default),D=[],j=0,$=[],O=await yt({pmRoot:s,settings:d,id:e,op:r.op,author:b,message:t.message,force:t.force,skipNoop:!0,mutate(we){let $t=we.metadata,ze=$t[i]??[],H=[...ze],z=q0(H,k,E,A),Ee=V0(H,z.adds,z.removes,r.supportsAppendStable&&t.appendStable===!0,x);if(Ee.conflicts.length>0){let cn=As(s);throw C0({itemId:we.metadata.id,noun:r.bareNoun,conflicts:Ee.conflicts,retryArgs:dn=>cn===void 0?void 0:Ry({id:we.metadata.id,entries:u??[],position:0,rewritten:"",resolved:{addGlob:m,remove:p,migrate:f},options:t,global:n,config:r,guards:cn,noteConflict:dn}),render:K})}let mt=Ee.entries;$=Ee.outcomes,mt.length>0?$t[i]=mt:delete $t[i];let oi=!ps(ze,mt);return D=ze,j=K0(ze,mt,A),{changedFields:oi?[i]:[],warnings:oi&&z.count>0?[`path_migrations_applied:${z.count}`]:[]}}}),Q=O.item[i]??[],He=O.warnings.find(we=>we.startsWith("path_migrations_applied:")),Ue=He?Number(He.slice(24)):0;return Ey({id:O.item.id,artifacts:Q,changed:O.changedFields.includes(i),migrationsApplied:Ue,options:t,workspaceRoot:a,mutation:xy({collectionKey:i,stored:Q,written:L0(D,Q),removedCount:j,fullHistory:t.fullHistory===!0,linkOutcomes:$})})}function Wo(e,t){let n={};for(let[r,i]of Object.entries(e))n[r==="artifacts"?t:r]=i;return n}async function Ay(e,t,n){let r=await zo(e,t,n,{metadataKey:"docs",op:"docs_add",bareNoun:"doc",supportsAppendStable:!1});return Wo(r,"docs")}import Iy from"node:fs/promises";import je from"node:path";var nT=32768;function Yc(e){return Ct(je.normalize(e))}async function qo(e){try{return await Iy.realpath(e)}catch{return je.resolve(e)}}function tr(e,t){let n=je.isAbsolute(e.path)?je.resolve(e.path):je.resolve(t,e.path);return`${Yc(n)}::${e.scope}`}function Go(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,i)=>Go(r,`${t}[${i}]`,n));return}if(typeof e=="object"&&e!==null)for(let[r,i]of Object.entries(e))Go(i,t?`${t}.${r}`:r,n)}function rT(e){let t=[];return Go(e.metadata,"metadata",t),Go(e.body,"body",t),t}function iT(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 oT(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 i of e){let o=new Set,s=i.value.slice(0,nT);for(let[a,c]of[[n,i.value],[r,s]]){a.lastIndex=0;for(let d of c.matchAll(a)){let l=iT(d[0]);!l||o.has(l)||(o.add(l),t.push({field:i.field,value:l}))}}}return t}async function sT(e,t,n=t){let r=je.isAbsolute(e)?je.resolve(e):je.resolve(n,e),i;try{i=await Iy.stat(r)}catch{return}if(!i.isFile())return;let[o,s]=await Promise.all([qo(t),qo(r)]);if(he(o,s)){let a=je.relative(o,s);return!a||a.startsWith("..")||je.isAbsolute(a)?void 0:{path:Yc(a),scope:"project"}}return{path:Yc(r),scope:"global"}}async function aT(e,t,n=t){let r=new Set((e.metadata.files??[]).map(c=>tr(c,t))),i=new Map,o=oT(rT(e)),s=new Map;await Promise.all([...new Set(o.map(c=>c.value))].map(async c=>{s.set(c,await sT(c,t,n))}));let a=o.map(c=>({reference:c,resolved:s.get(c.value)}));for(let{reference:c,resolved:d}of a){if(!d)continue;let l=tr(d,t),u=i.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,i.set(l,u)}return[...i.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 Cy(e,t,n){let r=await zo(e,t,n,{metadataKey:"files",op:"files_add",bareNoun:"file",supportsAppendStable:!0});return Wo(r,"files")}async function cT(e,t){let n=await qo(t),r=await Promise.all(e.map(async o=>{let s=o.trim();if(!s)throw new _("Files lookup paths must not be empty.",g.USAGE);if(!je.isAbsolute(s))return Ct(s);let a=await qo(s);return he(n,a)?Ct(je.relative(n,a)):Ct(a)})),i=[...new Set(r)].sort((o,s)=>o.localeCompare(s));if(i.length===0)throw new _("Files lookup requires at least one path.",g.USAGE);return i}function dT(e){for(let[r,i]of[["limit",e.limit],["offset",e.offset]])if(i!==void 0&&(!Number.isInteger(i)||i<0))throw new _(`Files lookup ${r} must be a non-negative integer.`,g.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 $y(e){return{id:e.id,title:e.title,type:e.type,status:e.status,priority:e.priority,updated_at:e.updated_at}}function Ty(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 lT(e){return e.metadata.map(t=>({item:t,files:(t.files??[]).filter(n=>e.paths.includes(Ct(n.path))&&(e.scope===void 0||n.scope===e.scope)).sort((n,r)=>{let i=n.path.localeCompare(r.path);return i===0?n.scope.localeCompare(r.scope):i})})).filter(t=>t.files.length>0).sort(Ty)}async function uT(e){if(e.explain)return np({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 mT(e){if([e.strictRead,e.noTruncate,e.explain,eu()].includes(!0))return null;let t=await Fi(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]);return t?Tu({pmRoot:e.pmRoot,expectedSourceCursor:t.source_cursor,paths:e.paths,scope:e.scope,limit:e.limit,offset:e.offset}):null}async function pT(e){let t=[],n=await ji(e.pmRoot,e.settings.item_format,e.typeToFolder,t,e.settings.schema),r=lT({metadata:n,paths:e.paths,scope:e.scope}),i=t.filter(c=>/^item_list_(?:item|directory)_read_failed:/u.test(c));if(e.strictRead&&i.length>0)throw new _(`Files lookup could not read every item: ${i.join("; ")}`,g.GENERIC_FAILURE);let o=await uT({explain:e.explain,workspaceRoot:e.workspaceRoot,paths:e.paths,matching:r,metadata:n,lineRange:e.lineRange,decisionDepth:e.decisionDepth}),a=(o?[...r].sort((c,d)=>{let l=o.explanations.get(d.item.id).score-o.explanations.get(c.item.id).score;return l!==0?l:Ty(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:i.length===0?"complete":"partial",source:"source_scan"},warnings:t,matches:a.map(c=>({item:$y(c.item),files:c.files,...o?{traceability:o.explanations.get(c.item.id)}:{}})),...o?{traceability_receipt:o.receipt}:{}}}async function oB(e,t){let n=M(process.cwd(),t.path),r=tt(n);await ie(n);let i=await cT(e.paths,r);if(e.lineRange&&i.length!==1)throw new _("Files lookup line attribution requires exactly one source path.",g.USAGE);let o=await T(n),s=W(o,U()),{offset:a,limit:c}=dT(e),d=await mT({pmRoot:n,typeToFolder:s.type_to_folder,paths:i,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:i,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:$y(l.item),files:l.files}))}:pT({pmRoot:n,settings:o,typeToFolder:s.type_to_folder,paths:i,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 sB(e,t,n){let r=M(process.cwd(),n.path),i=tt(r);await ie(r);let o=await T(r),s=W(o,U()),a=await ge(r,e,o.id_prefix,o.item_format,s.type_to_folder);if(!a)throw new _(`Item ${e} not found`,g.NOT_FOUND);let c=await ye(a,{schema:o.schema}),d=await aT(c.document,i,process.cwd()),l=d.filter(b=>b.status==="addable"),u=d.filter(b=>b.status==="already_linked"),m=t.apply===!0,p=t.note?.trim()||"discovered from item text";if(!m||l.length===0){let b=c.document.metadata.files??[];return{id:a.id,files:b,changed:!1,apply:m,count:b.length,candidate_count:d.length,addable_count:l.length,added_count:0,skipped_existing_count:u.length,candidates:d,added:[],skipped_existing:u}}let f=q(t.author,o.author_default),h=l.map(b=>({path:b.path,scope:b.scope,note:p})),y=[],w=new Set,v=await yt({pmRoot:r,settings:o,id:e,op:"files_discover",author:f,message:t.message??"Discover referenced file links",force:t.force,mutate(b){let D=[...b.metadata.files??[]],j=new Set(D.map(Q=>tr(Q,i)));y=[],w.clear();for(let[Q,He]of h.entries()){let Ue=tr(He,i);j.has(Ue)||(D.push(He),j.add(Ue),y.push(He),w.add(Q))}let $=Kc(D),O=t.appendStable?$:Vc($);return O.length>0?b.metadata.files=O:delete b.metadata.files,{changedFields:y.length>0?["files"]:[],warnings:y.length!==h.length?[`files_discover_skipped_existing:${h.length-y.length}`]:[]}}}),k=v.item.files??[],x=new Set(y.map(b=>tr(b,i))),E=k.filter(b=>x.has(tr(b,i))),A=l.filter((b,D)=>!w.has(D)),S=[...u,...A];return{id:v.item.id,files:k,changed:E.length>0,apply:!0,count:k.length,candidate_count:d.length,addable_count:l.length,added_count:E.length,skipped_existing_count:S.length,candidates:d,added:E,skipped_existing:S}}import{readFileSync as fT}from"node:fs";import Bo from"node:path";var hT=new Set(["get","history","restore","update","close","delete","append","claim","release","comments","notes","learnings","files","docs","deps","test"]),Qc=new Set(["--pm-path","--path","--author","--expect-hash"]),_T={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"])},gT=new Set(["-p","--package"]),yT=new Set(["-c","--call"]),wT=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),vT=new Set(["-C","--prefix","--userconfig","--cache"]),mB=new Set(["--cwd"]),pB=new Set(["--cwd"]),kT=new Set(["exec","x"]),fB=new Set(["run","run-script"]),hB=new Set(["-C","--dir","--cwd","-w","--workspace","--filter"]);function Oy(e){return e.split(/&&|\|\||\||;/).map(t=>t.trim()).filter(t=>t.length>0)}function bT(e,t=process.cwd()){let n=Ly(e.split(" ").filter(s=>s.length>0));if(n.length===0)return null;let[r,...i]=n;if(Jo(r)||Vo(r,t))return i;if(r==="node"&&i[0]&&Vo(i[0],t))return i.slice(1);let o=r==="npx"||r==="bunx"?Ko(i):r==="pnpm"?My(i):r==="npm"?Fy(i):null;return o&&(Jo(o.command)||Ny(o.command))?o.args:null}var Py=(e,t="pm")=>{let n=t.trim().toLowerCase(),r=n.length;for(;r>0&&n[r-1]==="-";)r-=1;let i=n.slice(0,r);if(i.length===0)return[];let o=e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase(),s=new Set;for(let a of Oy(o)){let c=bT(a),d=c?ST(c):null,l=d&&hT.has(d.subcommand)?ET(d.remaining,_T[d.subcommand]):void 0,u=l?.trim().toLowerCase();u?.startsWith(`${i}-`)===!0&&u.length>i.length+1&&s.add(l)}return[...s].sort((a,c)=>a.localeCompare(c))};function Ly(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 Zc(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(Qc.has(n)){t+=2;continue}t+=1;continue}return n}}function Jo(e){return e==="pm"||e==="pm.cmd"||e==="pm.exe"||e.endsWith("/pm")||e.endsWith("/pm.cmd")||e.endsWith("/pm.exe")}function xT(e){let t=e.trim();if(!t.startsWith("@")){let i=t.indexOf("@");return i===-1?t:t.slice(0,i)}let n=t.indexOf("/");if(n===-1)return t;let r=t.indexOf("@",n+1);return r===-1?t:t.slice(0,r)}function Ny(e){let t=xT(e);return t==="pm-cli"||t.endsWith("/pm-cli")||e==="pm-cli"||e.endsWith("/pm-cli")}function Vo(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=Bo.resolve(t,e);try{return JSON.parse(fT(Bo.join(Bo.dirname(Bo.dirname(r)),"package.json"),"utf8")).name==="@unbrained/pm-cli"}catch{return!1}}function Ko(e){let t=0;for(;t<e.length;){let r=e[t];if(r==="--"){t+=1;break}if(!r.startsWith("-"))break;let i=/^(?:-c|--call)=(.*)$/.exec(r);if(i){let o=i[1];return o?{command:o,args:e.slice(t+1)}:null}if(yT.has(r)){t+=1;break}t+=gT.has(r)&&!r.includes("=")?2:1}let n=e[t];return n?{command:n,args:e.slice(t+1)}:null}function Dy(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 My(e){let t=Dy(e,wT);return t?.subcommand!=="dlx"?null:Ko(t.args)}function Fy(e){let t=Dy(e,vT);return!t||!kT.has(t.subcommand)?null:Ko(t.args)}function ST(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(Qc.has(n)){t+=2;continue}t+=1;continue}return{subcommand:n,remaining:e.slice(t+1)}}return null}function ET(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("=")&&(Qc.has(r)||t.has(r))&&(n+=1)}}function Xc(e){return!e||!Jo(e.command)&&!Ny(e.command)?!1:Zc(e.args)==="test-all"}var RT=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])]),AT=new Set(["npx","bunx"]);function jy(e){let t=e.split(" ").filter(s=>s.length>0),n=Ly(t);if(n.length===0)return!1;let[r,...i]=n,o=RT.get(r);if(o){let s=i.findIndex(a=>o.test(a));return s>=0?jy(i.slice(s+1).join(" ")):!1}return Jo(r)||Vo(r)?Zc(i)==="test-all":r==="node"&&i.length>0&&Vo(i[0])?Zc(i.slice(1))==="test-all":AT.has(r)?Xc(Ko(i)):r==="pnpm"?Xc(My(i)):r==="npm"?Xc(Fy(i)):!1}function IT(e){let t=CT(e);return Oy(t).some(n=>jy(n))}function _B(e){if(IT(e))throw new _('Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.',g.USAGE)}function CT(e){return e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase()}import{execFile as $T}from"node:child_process";import{readFile as TT}from"node:fs/promises";import Uy from"node:path";import{promisify as OT}from"node:util";var PT=OT($T),ed=1,LT="linked-test-trust.json";function td(e){return Uy.join(Vd(e),LT)}function Hy(){return{version:ed,acknowledged:{}}}async function nd(e){try{let t=JSON.parse(await TT(td(e),"utf8"));return t.version!==ed||typeof t.acknowledged!="object"||t.acknowledged===null||Array.isArray(t.acknowledged)?Hy():{version:ed,acknowledged:t.acknowledged}}catch{return Hy()}}async function rd(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 PT("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 id(e=process.cwd()){return process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||e}function NT(e){return e===null||typeof e!="object"?!1:typeof e.author=="string"&&e.author.trim().length>0&&typeof e.created_at=="string"&&bl(e.created_at)&&(e.source_kind==="local_mutation"||e.source_kind==="merge_union")}function Zr(e,t){return{...e?{source_ref:e}:{},...t?{current_source_ref:t}:{}}}function DT(e,t,n,r){return e?.map(i=>i.command&&!i.provenance?{...i,provenance:{author:t,created_at:n,source_kind:"local_mutation",...r?{source_ref:r}:{}}}:i)}async function AB(e,t,n){if(!e||e.length===0)return e;for(let i of e)fu(i);let r=id();return DT(e,t,n,await rd(r))}function zy(e){return Ce(I({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 IB(e,t,n){let r=await nd(e);return Wy(t,n,r)}function Wy(e,t,n){let r=zy(e),i=e.provenance?.source_ref;if(e.provenance===void 0&&e.provenance_invalid!==!0)return{fingerprint:r,trusted:!0,reason:"legacy"};let o=Object.hasOwn(n.acknowledged,r);return e.provenance_invalid===!0||!NT(e.provenance)?o?{fingerprint:r,trusted:!0,reason:"acknowledged",...Zr(void 0,t)}:{fingerprint:r,trusted:!1,reason:"invalid_provenance",...Zr(void 0,t)}:e.provenance.source_kind==="local_mutation"&&i===void 0?{fingerprint:r,trusted:!0,reason:"local_mutation",...Zr(void 0,t)}:e.provenance.source_kind==="local_mutation"&&i!==void 0&&i===t?{fingerprint:r,trusted:!0,reason:"local_source_ref",source_ref:i,current_source_ref:t}:o?{fingerprint:r,trusted:!0,reason:"acknowledged",...Zr(i,t)}:{fingerprint:r,trusted:!1,reason:"foreign_source_ref",...Zr(i,t)}}async function qy(e,t,n){let r=await nd(e);return t.map(i=>Wy(i,n,r))}async function CB(e,t,n){let r=await nd(e),i=t.filter(o=>typeof o.command=="string"&&o.command.length>0).map(zy);for(let o of i)r.acknowledged[o]={acknowledged_at:n};return await or(Uy.dirname(td(e))),await ee(td(e),`${JSON.stringify(r,null,2)}
|
|
70
|
+
`),{acknowledged:i.length,fingerprints:i}}async function Yo(e){return e.includeBody?gt(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema,{forceSourceScan:!0}):ji(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema)}var MT=5;async function FT(e,t){let n=t.hashMismatches.filter(o=>o!==re);if(n.length===0)return;let r=await T(e),i=W(r,U());for(let o of n){let s=await se(e,o,r.locks.ttl_seconds,"history-drift-read",!1,!0,r.locks.wait_ms);try{let a=await ge(e,o,r.id_prefix,r.item_format,i.type_to_folder);if(a===null)throw new _(`Item ${o} not found`,g.NOT_FOUND,{code:"item_not_found",required:"Repeat validation after writers finish; each item-hash discrepancy requires readable canonical source."});let{document:c}=await ye(a,{schema:r.schema});if(c.metadata.id!==o)throw new _(`Item identity changed while validating ${o}`,g.CONFLICT,{code:"item_identity_conflict",required:"Restore the canonical item identity and validate storage integrity before retrying history validation."});let d=await zp(e,{...c.metadata,body:c.body});for(let u of["missingStreams","unreadableStreams","hashMismatches","chainMismatches","versionSkews","driftedItems"])t[u]=[...t[u].filter(m=>m!==o),...d[u].filter(m=>m===o)].sort((m,p)=>m.localeCompare(p));let l=[...(t.identityDiscontinuities??[]).filter(u=>u.item_id!==o),...(d.identityDiscontinuities??[]).filter(u=>u.item_id===o)];l.length>0?t.identityDiscontinuities=l:delete t.identityDiscontinuities}finally{await s()}}}async function Xo(e,t,n){let r=await en(e,t);await FT(e,r);let o=[["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}`),s=n?Number.POSITIVE_INFINITY:MT,a=r.driftedItems.slice(0,s),c=r.identityDiscontinuities??[];return{check:{name:"history_drift",status:c.length>0?"error":o.length===0?"ok":"warn",ok:c.length===0&&o.length===0,details:{identity_discontinuities:c.slice(0,s),identity_discontinuities_count:c.length,identity_discontinuities_truncated:c.length>s,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,s)}},warnings:o}}function od(e){let t=0,n=new Map,r=new Map,i=[],o=new Set,s=[],a=l=>{n.set(l,t),r.set(l,t),t+=1,i.push(l),o.add(l);for(let m of e.get(l)??[])n.has(m)?o.has(m)&&r.set(l,Math.min(r.get(l),n.get(m))):(a(m),r.set(l,Math.min(r.get(l),r.get(m))));if(r.get(l)!==n.get(l))return;let u=[];for(;i.length>0;){let m=i.pop();if(o.delete(m),u.push(m),m===l)break}u.sort((m,p)=>m.localeCompare(p)),s.push(u)},c=[...e.keys()].sort((l,u)=>l.localeCompare(u));for(let l of c)n.has(l)||a(l);return s.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 Zo(e,t){let n=e[0];if(e.length===1)return[n,n];let r=new Set(e),i=[n],o=new Set([n]),s=a=>{for(let c of(t.get(a)??[]).filter(d=>r.has(d))){if(c===n&&i.length>1)return i.push(n),!0;if(!o.has(c)){if(o.add(c),i.push(c),s(c))return!0;i.pop(),o.delete(c)}}return!1};return s(n)?[...i]:[...e,n]}function jT(e,t){if(typeof e!="string")return;let n=e.trim().toLowerCase();return n.length>0?t.get(n):void 0}function HT(e,t,n,r){for(let i of e.dependencies??[]){if(typeof i!="object"||i===null||typeof i.id!="string")continue;let o=r.resolve(i.kind);if(!o?.hierarchy)continue;let s=n.get(i.id.toLowerCase());s&&(o.hierarchyDirection==="source_parent"?t.get(s).push(e.id):t.get(e.id).push(s))}}function sd(e,t=fr()){let n=new Map(e.map(i=>[i.id.toLowerCase(),i.id])),r=new Map(e.map(i=>[i.id,[]]));for(let i of[...e].sort((o,s)=>o.id.localeCompare(s.id))){let o=r.get(i.id),s=jT(i.parent,n);s&&o.push(s),HT(i,r,n,t)}for(let[i,o]of r)r.set(i,[...new Set(o)].sort());return r}function ad(e,t,n=fr()){let r=Ui(e,s=>t?gl(s,t):s==="closed"||s==="canceled",n),i=sd(e,n),o=r.cycles.map(s=>s.item_ids);return{cycle_count:o.length,active_cycle_count:r.cycles.filter(s=>!s.legacy_terminal).length,legacy_cycle_count:r.cycles.filter(s=>s.legacy_terminal).length,cycle_item_ids:[...new Set(o.flat())].sort(),cycle_sample_paths:o.map(s=>Zo(s,i).join("->")),cardinality_violation_count:r.cardinality_violations.length,active_cardinality_violation_count:r.cardinality_violations.filter(s=>!s.legacy_terminal).length,legacy_cardinality_violation_count:r.cardinality_violations.filter(s=>s.legacy_terminal).length,cardinality_violation_rows:r.cardinality_violations.map(s=>`${s.child_id}:${s.parent_ids.join(",")}:${s.legacy_terminal?"legacy":"active"}`),parent_divergence_count:r.divergences.length,active_parent_divergence_count:r.divergences.filter(s=>!s.legacy_terminal).length,legacy_parent_divergence_count:r.divergences.filter(s=>s.legacy_terminal).length,parent_divergence_rows:r.divergences.map(s=>`${s.child_id}:scalar=${s.scalar_parent_id}:dependencies=${s.dependency_parent_ids.join(",")}:${s.legacy_terminal?"legacy":"active"}`)}}function Gt(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/^\/+/,"")}function cd(e){return Gt(e).replace(/\/+$/,"")}function Xe(e){let t=X(e);if(!t)return;let n=t.toLowerCase();if(!(n==="none"||n==="null"||n==="n/a"||n==="na"))return t}function dd(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length>120?`${t.slice(0,117)}...`:t}var qT=["src","tests","docs"],GT=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],BT=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),JT=["resolution","expected_result","actual_result"],VT=["default","tracked-all","tracked-all-strict"],Gy=["core","strict","custom"],ts=["off","warn","error"],md=["author","acceptance_criteria","estimated_minutes","close_reason"],Vy=[...md,"reviewer","risk","confidence","sprint","release"],pd=Array.from(new Set(Vy)),KT={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"},YT={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"},XT={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"},ZT={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"},QT={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"},eO=32*1024*1024,tO=1e4,fd=40,Ze=5,nO=4096,rO=255,iO=WT(zT);function Ky(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?Ky(r):r);return t}function oO(e){return{...e,checks:e.checks.map(t=>({...t,details:Ky(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 rs(e,t){return wi(e,t)??e}function Qr(e,t){return t.terminal_statuses.has(rs(e,t))}function Bt(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function Qo(e,t){return e.length!==t.length?!1:e.every((n,r)=>n===t[r])}function sO(e){let t=Bt(jd),n={blocked_reason:Bt(ci.blocked_reason),resolution:Bt(ci.resolution),actual_result:Bt(ci.actual_result)},r=Bt(e.validation.lifecycle_stale_blocker_reason_patterns),i={blocked_reason:Bt(e.validation.lifecycle_closure_like_blocked_reason_patterns),resolution:Bt(e.validation.lifecycle_closure_like_resolution_patterns),actual_result:Bt(e.validation.lifecycle_closure_like_actual_result_patterns)};return{stale_blocker_reason_patterns:r,stale_blocker_reason_pattern_source:Qo(r,t)?"default":"settings",closure_like_metadata_field_patterns:i,closure_like_metadata_field_pattern_sources:{blocked_reason:Qo(i.blocked_reason,n.blocked_reason)?"default":"settings",resolution:Qo(i.resolution,n.resolution)?"default":"settings",actual_result:Qo(i.actual_result,n.actual_result)?"default":"settings"}}}function Yy(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"core";if(Gy.includes(t))return t;throw new _(`Unknown --metadata-profile value "${e}". Supported values: ${Gy.join(", ")}.`,g.USAGE)}function Xy(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(ts.includes(t))return t;throw new _(`Unknown --dependency-cycle-severity value "${e}". Supported values: ${ts.join(", ")}.`,g.USAGE)}function Zy(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(ts.includes(t))return t;throw new _(`Unknown --parent-cycle-severity value "${e}". Supported values: ${ts.join(", ")}.`,g.USAGE)}function aO(e){return[...new Set((e??[]).map(n=>n.trim().toLowerCase().replaceAll("-","_")))].map(n=>KT[n]).filter(n=>n!==void 0).sort((n,r)=>n.localeCompare(r))}function cO(e,t,n){let r=aO(n);return e==="core"?{profile:e,profile_source:t,required_fields:[...md],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:e==="strict"?{profile:e,profile_source:t,required_fields:[...Vy],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:[...md],configured_custom_fields:r,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}var dO=new Set(["acceptance_criteria","estimated_minutes"]);function Qy(e,t,n,r){return!r&&dO.has(t)&&Qr(e.status,n)?!1:t==="author"?!X(e.author):t==="acceptance_criteria"?!X(e.acceptance_criteria):t==="estimated_minutes"?!Number.isFinite(e.estimated_minutes):t==="close_reason"?rs(e.status,n)===n.close_status&&!X(e.close_reason):t==="reviewer"?!X(e.reviewer):t==="risk"?!X(e.risk):t==="confidence"?typeof e.confidence=="number"?!Number.isFinite(e.confidence):!X(e.confidence):t==="sprint"?!X(e.sprint):!X(e.release)}function ew(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 _(`Unknown --scan-mode value "${e}". Supported values: ${VT.join(", ")}.`,g.USAGE)}function tw(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim();if(t)return Ie.resolve(t);let n=Ie.resolve(e);if(n.replaceAll("\\","/").endsWith("/.agents/pm"))return Ie.dirname(Ie.dirname(n));let i=Ie.resolve(process.cwd()),o=By(n),s=By(i),a=Ie.relative(o,s);return a.length===0||!a.startsWith("..")&&!Ie.isAbsolute(a)?n:i}function By(e){try{return UT.native(e)}catch{return Ie.resolve(e)}}function lO(e,t){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&t.includes(e.code)}async function yd(e,t,n){let r=t.length>0?Ie.join(e,t):e,i;try{i=await gd.readdir(r,{withFileTypes:!0})}catch(o){if(F(o))return;throw o}for(let o of i){if(o.name.startsWith("."))continue;let s=t.length>0?Ie.join(t,o.name):o.name;if(o.isDirectory()){if(BT.has(o.name))continue;await yd(e,s,n);continue}o.isFile()&&n.push(Gt(s))}}async function hd(e){let t=[];for(let n of qT)await yd(e,n,t);for(let n of GT){let r=Ie.join(e,n);try{(await gd.stat(r)).isFile()&&t.push(Gt(n))}catch{}}return[...new Set(t)].sort((n,r)=>n.localeCompare(r))}async function nw(e){try{let{stdout:t}=await iO("git",["ls-files","-z"],{cwd:e,encoding:"utf8",maxBuffer:eO,windowsHide:!0,timeout:tO}),n=t.split("\0").map(r=>Gt(r)).filter(r=>r.length>0);return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}catch{return null}}function uO(e,t){let n=new Set,r=cd(Dd);r.length>0&&n.add(r);let i=cd(Ie.relative(t,e));return i.length>0&&!i.startsWith("..")&&n.add(i),[...n].sort((o,s)=>o.localeCompare(s))}function Jy(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}async function mO(e,t){if(t==="tracked-all"||t==="tracked-all-strict"){let r=await nw(e);if(r)return{requestedMode:t,appliedMode:t,source:"tracked-git",candidateFiles:r,candidateTotal:r.length,candidateScanned:r.length};let i=await hd(e);return{requestedMode:t,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:i,candidateTotal:i.length,candidateScanned:i.length}}let n=await hd(e);return{requestedMode:t,appliedMode:"default",source:"default-curated",candidateFiles:n,candidateTotal:n.length,candidateScanned:n.length}}function ne(e,t=Ze){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function sn(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=ne(e,fd);return{values:n.values,truncated:n.truncated,total:e.length}}var pO={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},fO={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function hO(e){let t=e.missing_fields.map(n=>`${pO[n]} "${fO[n]}"`).join(" ");return`pm update ${e.id} ${t} --message "Backfill resolution metadata"`}function rw(e,t){let n=e.details?.missing_resolution_remediation_hints,r=Array.isArray(n)&&n.length>0,i=r?n.filter(s=>typeof s=="string"):Jp(t);if(i.length===0)return;let o=r&&e.details?.missing_resolution_remediation_hints_truncated===!0;e.details={...e.details,fix_hints:i,...o?{fix_hints_truncated:!0}:{}}}function iw(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 _O="validate_metadata_duplicate_issue_codes";function ow(e,t){if(e.length===0)return{rows:[],truncated:!1,warnings:[]};let n=t?e.length:Ze,r=e.slice(0,n);return{rows:r.map(o=>({code:o.code,count:o.count,ids:o.ids,titles:o.titles,remediation_hint:`Items ${o.ids.join(", ")} share issue code "${o.code}"; rename or merge so each logical code maps to one item.`})),truncated:r.length<e.length,warnings:[`${_O}:${e.length}`]}}function gO(e,t,n){let r=Object.fromEntries(pd.map(i=>[i,[]]));for(let i of e)for(let o of pd)Qy(i,o,t,n)&&r[o].push(i.id);return r}function yO(e,t,n){let r=[...e.warnings];for(let i of e.required_fields){let o=t[i];o.length>0&&r.push(`${YT[i]}:${o.length}`)}return r.push(...n),r}function sw(e,t){let n={};for(let r of e.required_fields){let i=t[r],o=i?i.length:0,s=XT[r];n[s]=o}return n}function aw(e,t,n){let r=[];for(let i of e.required_fields){let o=t[i];if(o)for(let s of o){let a=n.get(s)?.type,c=typeof a=="string"&&a.length>0?a:"Unknown";r.push({item_type:c,field:i})}}return r}function wO(e,t,n,r){for(let i of t.required_fields){let o=n[i];if(!o||o.length===0)continue;let s=ZT[i],a=QT[i];if(!s||!a)continue;let c=ne(o,r?o.length:Ze);e[s]=c.values,e[a]=c.truncated}}function cw(e,t,n){if(!e.required_fields.includes("close_reason"))return[];let r=t.close_reason;return r?r.map(i=>({id:i,resolution:X(n.get(i)?.resolution)})):[]}function dw(e,t,n){if(!e.required_fields.includes("estimated_minutes"))return[];let r=t.estimated_minutes;return r?r.map(i=>({id:i,type:X(n.get(i)?.type)})):[]}function vO(e,t,n,r,i){let o=new Map(e.map(v=>[v.id,v])),s=t.profile==="strict",a=gO(e,n,s),c=iy(e,{configuredPrefixes:i}),d=ow(c,r),l=yO(t,a,d.warnings),u=sw(t,a),m=aw(t,a,o),p=oy(m),f={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:[...pd],counts:u,missing_by_type:p,duplicate_issue_codes_count:c.length,duplicate_issue_codes:d.rows,duplicate_issue_codes_truncated:d.truncated};t.configured_custom_fields.length>0&&(f.configured_custom_required_fields=[...t.configured_custom_fields]);let h=Fo(e,r);h!==void 0&&(f.deferred_fields=h.details,l.push(h.warning)),wO(f,t,a,r);let y=cw(t,a,o),w=dw(t,a,o);return{check:{name:"metadata",status:l.length===0?"ok":"warn",ok:l.length===0,details:f},warnings:l,closeReasonBackfillRows:y,estimateBackfillRows:w}}function kO(e,t,n){let r=new Set(t.terminal_done_statuses);r.add(t.close_status);let i=e.filter(m=>r.has(rs(m.status,t))),o=[],s=[];for(let m of i){let p=JT.filter(f=>!X(m[f]));p.length!==0&&(o.push({id:m.id,missing_fields:p}),s.push({id:m.id,missing_fields:p,close_reason:X(m.close_reason)}))}let a=o.length>0?[`validate_resolution_missing_fields:${o.length}`]:[],c=n?Number.POSITIVE_INFINITY:Ze,d=ne(o.map(m=>`${m.id}:${m.missing_fields.join(",")}`),c),l=o.map(m=>hO(m)),u=ne(l,c);return{check:{name:"resolution",status:a.length===0?"ok":"warn",ok:a.length===0,details:{checked_closed_items:i.length,missing_resolution_items:o.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:s}}function lw(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function uw(e,t="pm",n=zd()){let r=new Set(e.map(o=>o.id)),i=[...e].sort((o,s)=>o.id.localeCompare(s.id));return new Map(i.map(o=>{let s=new Set,a=Xe(o.blocked_by);a&&r.has(a)&&s.add(a),(o.dependencies??[]).filter(d=>{let l=Xe(d.kind);return l!==void 0&&n.resolve(l)?.ordering===!0}).map(d=>Xe(d.id)).filter(d=>d!==void 0&&r.has(d)).forEach(d=>s.add(d));let c=Xe(o.definition_of_ready);return pw(c??"",t).filter(d=>r.has(d)).forEach(d=>s.add(d)),[o.id,[...s].sort((d,l)=>d.localeCompare(l))]}))}function mw(e,t,n){let r=Qu(e,n?l=>Qr(l,n):void 0),i=r.active.map(l=>`${l.holder_id}:${l.target_id}:${l.kind}`),o=r.legacy_terminal.map(l=>`${l.holder_id}:${l.target_id}:${l.kind}:${l.holder_status}`),s=t?Number.POSITIVE_INFINITY:Ze,a=ne(i,s),c=ne(o,s),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>'`),s);return{check:{name:"dependency_references",status:i.length===0?"ok":"warn",ok:i.length===0,details:{checked_items:e.length,dangling_reference_count:i.length+o.length,active_dangling_reference_count:i.length,dangling_reference_rows:a.values,dangling_reference_rows_truncated:a.truncated,legacy_terminal_dangling_reference_count:o.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:i.length>0?[`validate_dangling_dependency_references:${i.length}`]:[]}}function pw(e,t="pm"){let n=(t.trim().toLowerCase()||"pm").replace(/-+$/g,""),r=new RegExp(`(?:^|[^a-z0-9-])(${lw(n)}-[a-z0-9][a-z0-9-]*)`,"gi");return[...new Set([...e.matchAll(r)].map(i=>i[1].toLowerCase()))].sort((i,o)=>i.localeCompare(o))}function fw(e,t="pm"){let n=uw(e,t),r=od(n),i=[...new Set(r.flat())].sort((s,a)=>s.localeCompare(a)),o=r.map(s=>Zo(s,n).join("->"));return{cycle_count:r.length,cycle_item_ids:i,cycle_sample_paths:o}}function hw(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 ns(e){let t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function _w(e,t){let n=ns(e).split("/").filter(Boolean),r=ns(t).split("/").filter(Boolean),i=0;for(;i<n.length&&i<r.length&&n[i]===r[i];)i+=1;return i}function bO(e,t){let n=ns(t),r=ns(e),i=t.endsWith("/")?t:`${t}/`,o=e.startsWith(i),s=n.length>0&&n===r,a=_w(e,t);return!o&&!s&&a===0?null:o?{score:t.length+1e3,confidence:"path_prefix"}:s?{score:a+500,confidence:"same_directory"}:{score:a,confidence:"shared_directory"}}function xO(e,t,n){return e===void 0||n>e.score||n===e.score&&t.id.localeCompare(e.item.id)<0}function SO(e,t,n){let r=t==="docs_unowned"?"docs":"files",i;return n.flatMap(o=>(r==="docs"?o.docs??[]:o.files??[]).map(s=>({item:o,link:s}))).forEach(({item:o,link:s})=>{if(s.scope!=="project")return;let a=Gt(s.path);if(a.length===0||a===e)return;let c=bO(e,a);c!==null&&xO(i,o,c.score)&&(i={item:o,score:c.score,confidence:c.confidence})}),i?{id:i.item.id,type:i.item.type,title:i.item.title,status:i.item.status,confidence:i.confidence}:null}function gw(e,t){return e.map(n=>{let r=hw(n),i=r==="docs_unowned"?"docs":"files",o=SO(n,r,t),s=o?.id??"<id>";return{path:n,classification:r,owner_candidate:o,remediation_hint:`pm ${i} ${s} --add path=${n},scope=project,note="<why this artifact belongs to the item>"`}})}function yw(e){return e.map(t=>`${t.path}:${t.classification} owner_candidate=${t.owner_candidate?.id??"unowned"} hint=${JSON.stringify(t.remediation_hint)}`)}function EO(e,t){return Object.entries(t.closure_like_metadata_field_patterns).filter(([n,r])=>{let i=Xe(e[n]);return i?r.some(o=>i.toLowerCase().includes(o)):!1}).map(([n])=>n).sort((n,r)=>n.localeCompare(r))}function RO(e,t,n,r,i){let o=Xe(t.parent),s=o?n.get(r.get(o.toLowerCase())??o):void 0;return{id:e.id,parent_id:t.id,grandparent_id:s?.id,grandparent_active:s!==void 0&&!Qr(s.status,i)}}function AO(e,t,n,r){let i=Xe(e.blocked_by),o=Xe(e.blocked_reason),s=o?.toLowerCase(),a=rs(e.status,n),c=[];return t.has(a)?(!i&&!o&&c.push("blocked_status_missing_blocker_context"),s?.includes("no active blocker")&&c.push("blocked_status_reason_reports_no_active_blocker"),s&&r.stale_blocker_reason_patterns.some(d=>s.includes(d))&&c.push("blocked_status_reason_matches_stale_pattern"),c):(i&&c.push("non_blocked_status_has_blocked_by"),o&&c.push("non_blocked_status_has_blocked_reason"),c)}function IO(e,t,n,r){let i=new Map(e.map(c=>[c.id,c])),o=new Map(e.map(c=>[c.id.toLowerCase(),c.id])),s=n.blocked_statuses.size>0?n.blocked_statuses:new Set(["blocked"]),a={activeItems:e.filter(c=>!Qr(c.status,n)),closureLikeRows:[],terminalParentRows:[],terminalParentFixRows:[],staleBlockerRows:[]};for(let c of a.activeItems){let d=EO(c,r);d.length>0&&a.closureLikeRows.push({id:c.id,fields:d});let l=Xe(c.parent),u=l?i.get(o.get(l.toLowerCase())??l):void 0;if(u&&Qr(u.status,n)&&(a.terminalParentRows.push({id:c.id,parent_id:u.id,parent_status:u.status}),a.terminalParentFixRows.push(RO(c,u,i,o,n))),t){let m=AO(c,s,n,r);m.length>0&&a.staleBlockerRows.push({id:c.id,status:c.status,reasons:[...new Set(m)].sort((p,f)=>p.localeCompare(f))})}}return a}function CO(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 es(e,t,n){return n<=0||t==="off"?null:`${t==="error"?`${e}_error`:e}:${n}`}function ld(e,t,n){return n>0&&t!=="off"?`${e}:${n}`:null}function $O(e,t,n,r,i){let o=[];e.closureLikeRows.length>0&&o.push(`validate_lifecycle_active_closure_like_metadata:${e.closureLikeRows.length}`),e.terminalParentRows.length>0&&o.push(`validate_lifecycle_active_terminal_parent:${e.terminalParentRows.length}`),t&&e.staleBlockerRows.length>0&&o.push(`validate_lifecycle_stale_blockers:${e.staleBlockerRows.length}`);let s=es("validate_lifecycle_dependency_cycles",n,i.dependencyCycles),a=es("validate_hierarchy_parent_cycle",r,i.activeHierarchyCycles),c=es("validate_hierarchy_cardinality_violation",r,i.activeHierarchyCardinality),d=es("validate_hierarchy_parent_divergence",r,i.activeHierarchyDivergence),l=ld("validate_legacy_hierarchy_parent_cycle",r,i.legacyHierarchyCycles),u=ld("validate_legacy_hierarchy_cardinality_violation",r,i.legacyHierarchyCardinality),m=ld("validate_legacy_hierarchy_parent_divergence",r,i.legacyHierarchyDivergence);return[...o,...s?[s]:[],...a?[a]:[],...c?[c]:[],...d?[d]:[],...l?[l]:[],...u?[u]:[],...m?[m]:[]]}function ww(e){let t=Gt(e);return t.length>nO||t.split(/[\\/]/).some(n=>n.length>rO)}async function TO(e,t){let n=Ie.isAbsolute(t)?t:Ie.resolve(e,t);if(ww(n))return!1;try{let r=await gd.stat(n);return!r.isFile()&&!r.isDirectory()}catch(r){return lO(r,["ENOENT","ENOTDIR"])}}async function OO(e,t){let n={linkedProjectPaths:new Set,remoteLinkedPaths:new Set,missingLinkedPaths:[],staleLinkRows:[]},r=e.flatMap(i=>[...(i.files??[]).map(o=>({item:i,artifact:o,link_kind:"files"})),...(i.docs??[]).map(o=>({item:i,artifact:o,link_kind:"docs"}))]);for(let{item:i,artifact:o,link_kind:s}of r){if(o.scope!=="project")continue;if(Xr(o.path)){n.remoteLinkedPaths.add(o.path.trim());continue}let a=Gt(o.path);a.length!==0&&(n.linkedProjectPaths.add(a),await TO(t,o.path)&&(n.missingLinkedPaths.push(a),n.staleLinkRows.push({item_id:i.id,path:a,link_kind:s})))}return n}function PO(e,t,n,r,i,o){let s=r==="tracked-all-strict",a=s&&!i,c=i||s,d=c?[]:uO(t,n),l=d.length===0?[]:e.candidateFiles.filter(p=>Jy(p,d)),u=d.length===0?e.candidateFiles:e.candidateFiles.filter(p=>!Jy(p,d)),m={};if(l.length>0){let p=sn(l,o);m.pm_internals={count:l.length,paths:p.values,paths_truncated:p.truncated,paths_total:p.total}}return{strictTrackedAllMode:s,strictModeForcesPmInternals:a,includePmInternalsEffective:c,pmInternalCandidatePrefixes:d,excludedPmInternalPaths:l,candidateFiles:u,excludedByReason:m}}function vw(e,t,n,r,i,o,s,a="pm"){let c=IO(e,t,i,o);CO(c);let d=fw(c.activeItems,a),l=ad(e,i),u=no(i,e,s?Number.POSITIVE_INFINITY:Ze),m=[...$O(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}),...ro(u)],p=s?Number.POSITIVE_INFINITY:Ze,f=ne(c.closureLikeRows.map(b=>`${b.id}:${b.fields.join(",")}`),p),h=ne(c.terminalParentRows.map(b=>`${b.id}:${b.parent_id}:${b.parent_status}`),p),y=ne(c.staleBlockerRows.map(b=>`${b.id}:${b.status}:${b.reasons.join(",")}`),p),w=ne(d.cycle_item_ids,p),v=ne(d.cycle_sample_paths,p),k=ne(l.cycle_item_ids,p),x=ne(l.cycle_sample_paths,p),E=ne(l.cardinality_violation_rows,p),A=ne(l.parent_divergence_rows,p),S=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:S?"error":m.length===0?"ok":"warn",ok:!S&&m.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:f.values,active_closure_like_metadata_rows_truncated:f.truncated,active_terminal_parent_items:c.terminalParentRows.length,active_terminal_parent_rows:h.values,active_terminal_parent_rows_truncated:h.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:k.values,parent_cycle_item_ids_truncated:k.truncated,parent_cycle_sample_paths:x.values,parent_cycle_sample_paths_truncated:x.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:E.values,hierarchy_cardinality_violation_rows_truncated:E.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:[...o.stale_blocker_reason_patterns],stale_blocker_reason_pattern_source:o.stale_blocker_reason_pattern_source,closure_like_blocked_reason_patterns:[...o.closure_like_metadata_field_patterns.blocked_reason],closure_like_blocked_reason_pattern_source:o.closure_like_metadata_field_pattern_sources.blocked_reason,closure_like_resolution_patterns:[...o.closure_like_metadata_field_patterns.resolution],closure_like_resolution_pattern_source:o.closure_like_metadata_field_pattern_sources.resolution,closure_like_actual_result_patterns:[...o.closure_like_metadata_field_patterns.actual_result],closure_like_actual_result_pattern_source:o.closure_like_metadata_field_pattern_sources.actual_result}},warnings:m,terminalParentFixRows:c.terminalParentFixRows}}async function kw(e,t,n,r,i,o,s=_e(Hd.schema)){let a=await OO(e,t),c=new Map(e.map(O=>[O.id,O])),d=[...new Set(a.missingLinkedPaths)].sort((O,Q)=>O.localeCompare(Q)),l=await mO(t,r),u=PO(l,n,t,r,i,o),m=u.candidateFiles.filter(O=>!a.linkedProjectPaths.has(O)),p=gw(m,e),f=ay(d,u.candidateFiles),h=new Map(f.map(O=>[O.path,O.classification])),y=f.filter(O=>O.classification==="moved").length,w=a.staleLinkRows.map(O=>({...O,classification:h.get(O.path)??"deleted"})).sort((O,Q)=>O.item_id.localeCompare(Q.item_id)||O.path.localeCompare(Q.path)||O.link_kind.localeCompare(Q.link_kind)),v=[];u.strictModeForcesPmInternals&&v.push("validate_files_tracked_all_strict_forces_pm_internals"),m.length>0&&v.push(`validate_files_orphaned_paths:${m.length}`);let k=[...a.remoteLinkedPaths].sort((O,Q)=>O.localeCompare(Q)),x=sn(k,o),E=sn(d,o),A=sn(m,o),S=sn(p.map(O=>`${O.path}:${O.classification}:owner_candidate=${O.owner_candidate?.id??"unowned"}`),o),b=o?p:sn(yw(p),!1).values,D=sn(cy(f),o),$=Bg(w,f,O=>c.get(O),s,o?1/0:fd);return $.active_missing_linked_paths_count>0&&v.push(`validate_files_missing_linked_paths:${$.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:o?"full":"summary",file_list_summary_limit:fd,candidate_scan_source:l.source,include_pm_internals:u.includePmInternalsEffective,include_pm_internals_requested:i,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:k.length,remote_linked_paths_total:x.total,remote_linked_paths:x.values,remote_linked_paths_truncated:x.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:E.total,missing_linked_paths:E.values,missing_linked_paths_truncated:E.truncated,missing_linked_paths_moved_count:y,missing_linked_paths_deleted_count:f.filter(O=>O.classification==="deleted").length,missing_linked_paths_malformed_count:f.filter(O=>O.classification==="malformed").length,missing_linked_path_classifications:D.values,missing_linked_path_classifications_truncated:D.truncated,...$,orphaned_paths_count:m.length,orphaned_paths_total:A.total,orphaned_paths:A.values,orphaned_paths_truncated:A.truncated,orphaned_path_classifications:S.values,orphaned_path_classifications_truncated:S.truncated,orphaned_path_rows_count:p.length,orphaned_path_rows:b}},warnings:v,staleLinkPruneRows:w}}function LO(e,t){let n=[];return e.forEach(({item:r,linkedTest:i},o)=>{let s=t[o];if(s.trusted)return;let a=dd(i.command??"");n.push(`${r.id}:${s.source_ref??"unknown"}->${s.current_source_ref??"unknown"}:${a}`)}),n}async function bw(e,t,n,r){let i=new Set(e.map(E=>E.id.toLowerCase())),o=0,s=0,a=new Set,c=[],d=e.flatMap(E=>(E.tests??[]).map(A=>({item:E,linkedTest:A}))),l=await rd(id()),u=await qy(r,d.map(({linkedTest:E})=>E),l),m=LO(d,u);for(let{item:E,linkedTest:A}of d){if(typeof A.command!="string"||A.command.trim().length===0)continue;o+=1;let S=Py(A.command,t);if(S.length!==0){s+=S.length;for(let b of S)a.add(b),i.has(b.toLowerCase())||c.push(`${E.id}:${b}:${dd(A.command)}`)}}let p=[...new Set(c)].sort((E,A)=>E.localeCompare(A)),f=[...new Set(p.map(E=>E.split(":")[1]??""))].filter(E=>E.length>0).sort((E,A)=>E.localeCompare(A)),h=[];p.length>0&&h.push(`validate_command_references_stale_pm_ids:${p.length}`),m.length>0&&h.push(`validate_linked_test_trust_unacknowledged:${m.length}`);let y=n?Number.POSITIVE_INFINITY:Ze,w=ne(p,y),v=ne(f,y),k=ne([...a].sort((E,A)=>E.localeCompare(A)),y),x=ne(m,y);return{check:{name:"command_references",status:h.length===0?"ok":"warn",ok:h.length===0,details:{checked_items:e.length,linked_commands_scanned:o,referenced_pm_ids_count:s,unique_referenced_pm_ids_count:a.size,unique_referenced_pm_ids:k.values,unique_referenced_pm_ids_truncated:k.truncated,linked_test_trust_current_source_ref:l??null,untrusted_linked_tests_count:m.length,untrusted_linked_tests:x.values,untrusted_linked_tests_truncated:x.truncated,stale_pm_id_references_count:p.length,stale_pm_ids_count:f.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:h}}function NO(e,t){let n=yi(e.map(c=>({ref:c.id,version:gi(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 i=t?Number.POSITIVE_INFINITY:Ze,o=ne(n.outdated,i),s=ne(n.ahead,i),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:o.values,outdated_items_truncated:o.truncated,ahead_items_count:n.ahead.length,ahead_items:s.values,ahead_items_truncated:s.truncated}},warnings:r}}var _d="pm validate auto-fix";async function xw(e,t,n){switch(e.kind){case"set_closed_at":await Wg(e,t);return;case"set_resolution":case"set_close_reason":case"set_estimate":case"reparent":case"unset_parent":{let r={message:_d};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 _("Applying validate metadata/lifecycle fixes requires a runUpdate mutation service.",g.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 ud(e){return e.kind!=="prune_file_link"&&e.kind!=="prune_doc_link"?null:`${e.kind}:${e.item_id}`}async function Sw(e,t,n){let r=[],i=[],o=new Map;for(let s of e.filter(a=>ud(a)===null))try{await xw(s,t,n),r.push(s)}catch(a){i.push({fix:s,error:a})}for(let s of e.filter(a=>ud(a)!==null)){let a=ud(s),c=o.get(a);c?c.push(s):o.set(a,[s])}for(let s of o.values()){let a=s[0];if(!a)continue;let c=s.map(d=>d.path).filter(d=>typeof d=="string"&&d.length>0);try{a.kind==="prune_file_link"?await Cy(a.item_id,{remove:c,message:_d},t):await Ay(a.item_id,{remove:c,message:_d},t),r.push(...s)}catch(d){i.push(...s.map(l=>({fix:l,error:d})))}}return dm(i.map(s=>s.error)),{applied:r,failed:i}}var GJ={applyValidateFix:xw,applyValidateFixes:Sw,attachValidateFixHints:rw,buildCommandReferencesCheck:bw,buildDependencyReferencesCheck:mw,buildCloseReasonBackfillRows:cw,buildFilesCheck:kw,buildLifecycleCheck:vw,buildLifecycleDependencyGraph:uw,buildLifecycleParentGraph:sd,buildEstimateBackfillRows:dw,buildMetadataCounts:sw,buildMissingFieldOccurrences:aw,buildOrphanedPathRows:gw,classifyOrphanedPath:hw,collectDefaultProjectFileCandidates:hd,collectTrackedGitFileCandidates:nw,detectLifecycleDependencyCycles:fw,detectLifecycleParentCycles:ad,escapeRegExp:lw,extractItemIds:pw,findLifecycleDependencyCycleComponents:od,isMetadataFieldMissing:Qy,linkedArtifactPathExceedsFilesystemLimits:ww,listFilesRecursive:yd,resolveDependencyCycleSeverity:Xy,resolveParentCycleSeverity:Zy,resolveFileScanMode:ew,resolveLifecycleDependencyCycleSamplePath:Zo,resolveRequestedChecks:iw,resolveValidateMetadataProfile:Yy,resolveWorkspaceRoot:tw,sharedDirectoryPrefixLength:_w,summarizeOrphanedPathRows:yw,summarizeDuplicateIssueCodes:ow,toMeaningfulString:Xe};function DO(e,t){t>0&&e.push(`merge_receipt_evidence_invalid:${t}`)}async function MO(e,t,n,r){let i=await Vg(e,new Set(t.map(y=>y.id)),n,{schema:r.schema,extensionFieldNames:ln(U())}),o=[];i.unreadable_item_files.length>0&&o.push(`validate_storage_unreadable_items:${i.unreadable_item_files.length}`),i.duplicate_item_ids.length>0&&o.push(`validate_storage_duplicate_item_ids:${i.duplicate_item_ids.length}`),i.history_conflict_marker_streams.length>0&&o.push(`validate_storage_history_conflict_markers:${i.history_conflict_marker_streams.length}`),i.history_unparseable_streams.length>0&&o.push(`validate_storage_unparseable_history:${i.history_unparseable_streams.length}`),i.resurrected_items.length>0&&o.push(`validate_storage_resurrected_items:${i.resurrected_items.length}`),i.unparseable_config_files.length>0&&o.push(`validate_storage_unparseable_config:${i.unparseable_config_files.length}`);let s=o.length,a=await xo(e);a.tracked_path_count>0&&o.push(`validate_storage_tracked_runtime_cache_files:${a.tracked_path_count}`);let c=await Mt(e),d=await $n(e,Cn(r),{gitWorkspaceRoot:c});d.status==="drift"&&o.push(`validate_merge_fence_drift:${d.missing_patterns.length+d.stale_patterns.length}`);let l=c===null?null:await Tn(c);l!==null&&l.status!=="ok"&&o.push(`validate_merge_driver_configuration:${l.missing_keys.length+l.drifted_keys.length}`);let u=await Rt(c??e,{includeLossless:!0,pmRoot:e}),m=u.receipts,{pendingDecisions:p,lossless:f}=Kn(m);p.length>0&&o.push(`validate_merge_decisions_unreviewed:${p.length}`),DO(o,u.invalid_evidence_count);let h=s>0?"error":o.length>0?"warn":"ok";return{check:{name:"storage_integrity",status:h,ok:h==="ok",details:{...i,merge_fence:d,merge_driver_configuration:l,pending_merge_decision_count:p.length,pending_merge_decision_items:[...new Set(p.map(y=>y.item_id))].sort((y,w)=>y.localeCompare(w)),lossless_merge_receipt_count:f.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(f.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:o}}function ut(e,t,n){n&&rw(t.check,t.warnings),e.checks.push(t.check),e.warnings.push(...t.warnings)}async function FO(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 i=await zm(e.pmRoot,e.items,r?1/0:Ze,e.sourceIncomplete);ut(t,i,n)}if(e.requestedChecks.has("metadata")){let i=vO(e.items,e.metadataPolicy,e.statusRegistry,r,[e.settings.id_prefix]);t.closeReasonBackfillRows=i.closeReasonBackfillRows,t.estimateBackfillRows=i.estimateBackfillRows;let o=r?1/0:Ze,s=await zg(e.pmRoot,e.items,e.statusRegistry,e.options.autoFix===!0||n,o);t.closureTimestampFixes=s.fixes,Object.assign(i.check.details,s.details),i.warnings.push(...s.warnings);let a=cu(e.settings.schema,o);Object.assign(i.check.details,a.details),i.warnings.push(...a.warnings),i.check.ok=i.warnings.length===0,i.check.status=i.check.ok?"ok":"warn",ut(t,i,n)}if(e.requestedChecks.has("resolution")){let i=kO(e.items,e.statusRegistry,r);t.resolutionBackfillRows=i.resolutionBackfillRows,ut(t,i,n)}if(e.requestedChecks.has("lifecycle")){let i=vw(e.items,!!e.options.checkStaleBlockers,e.dependencyCycleSeverity,e.parentCycleSeverity,e.statusRegistry,e.lifecyclePatternPolicy,r,e.settings.id_prefix);t.terminalParentFixRows=i.terminalParentFixRows,ut(t,i,n),ut(t,mw(e.items,r,e.statusRegistry),n)}if(e.requestedChecks.has("files")){let i=await kw(e.items,e.workspaceRoot,e.pmRoot,e.fileScanMode,!!e.options.includePmInternals,!!e.options.verboseFileLists,e.statusRegistry);t.staleLinkPruneRows=i.staleLinkPruneRows,ut(t,i,n)}return e.requestedChecks.has("command_references")&&ut(t,await bw(e.items,e.settings.id_prefix,r,e.pmRoot),n),e.requestedChecks.has("history_drift")&&ut(t,await Xo(e.pmRoot,e.items,r),n),e.requestedChecks.has("format_version")&&ut(t,NO(e.items,r),n),e.requestedChecks.has("storage_integrity")&&ut(t,await MO(e.pmRoot,e.items,W(e.settings,U()).type_to_folder,e.settings),n),t}function jO(e,t,n){let r=[];return e.autoFix===!0&&(r.push(...t.closureTimestampFixes),r.push(...Xg(t.closeReasonBackfillRows)),r.push(...Yg(t.resolutionBackfillRows)),r.push(...Zg(t.estimateBackfillRows,n.validation.estimate_defaults_by_type)),r.push(...Qg(t.terminalParentFixRows))),e.pruneMissing===!0&&r.push(...ey(t.staleLinkPruneRows)),r}async function HO(e,t,n,r,i,o){if(e.autoFix!==!0&&e.pruneMissing!==!0)return;let s=jO(e,t,n),{applicable:a,gated:c}=ny(s,r),d=e.dryRun===!0,l=[],u=[];if(!d){let m=await Sw(a,i,o);l.push(...m.applied.map(Yr)),u.push(...m.failed.map(({fix:p,error:f})=>({...Yr(p),error:f instanceof Error?f.message:String(f)})))}return{mode:d?"dry_run":"apply",auto_fix:e.autoFix===!0,prune_missing:e.pruneMissing===!0,granted_fix_scopes:[...r].sort((m,p)=>m.localeCompare(p)),planned_count:s.length,applied_count:l.length,gated_count:c.length,failed_count:u.length,planned_fixes:s.map(Yr),applied_fixes:l,gated_fixes:c.map(m=>({...Yr(m),gate_hint:`Withheld: re-run with --fix-scope ${m.gate} to apply.`})),failed_fixes:u}}async function Ew(e,t,n={}){tu(e.counts===!0,e.full===!0,"--counts");let r=e.autoFix===!0||e.pruneMissing===!0;if(e.dryRun===!0&&!r)throw new _("--dry-run requires --auto-fix or --prune-missing (there is nothing to preview otherwise).",g.USAGE);if(e.fixScope!==void 0&&e.fixScope.length>0&&e.autoFix!==!0)throw new _("--fix-scope requires --auto-fix.",g.USAGE);let i=ty(e.fixScope),o=M(process.cwd(),t.path);await ie(o);let s=await T(o),a=_e(s.schema),c=W(s,U()),d=iw(e),l=[],u=await Yo({includeBody:["history_drift","metadata","completeness"].some(j=>d.has(j)),pmRoot:o,settings:s,typeToFolder:c.type_to_folder,warnings:l}),m=l.length>0;if(d.has("history_drift")){let j=await xr(o);j.actionable_unknown_event_count>0&&l.push(`validate_history_unknown_author_events:${j.actionable_unknown_event_count}`)}let p=typeof e.metadataProfile=="string"?"option":"settings",f=Yy(typeof e.metadataProfile=="string"?e.metadataProfile:s.validation.metadata_profile),h=cO(f,p,s.validation.metadata_required_fields),y=sO(s),w=Xy(e.dependencyCycleSeverity),v=Zy(e.parentCycleSeverity),k=ew(e.scanMode),x=tw(o),E=await FO({requestedChecks:d,options:e,global:t,pmRoot:o,workspaceRoot:x,settings:s,items:u,statusRegistry:a,metadataPolicy:h,lifecyclePatternPolicy:y,dependencyCycleSeverity:w,parentCycleSeverity:v,fileScanMode:k,initialWarnings:[...new Set(l)],sourceIncomplete:m}),A=r?await HO(e,E,s,i,t,n):void 0,S=[...new Set(E.warnings)].sort((j,$)=>j.localeCompare($)),D={ok:!E.checks.some(j=>j.status==="error"),has_warnings:S.length>0,checks:E.checks,warnings:S,...A!==void 0?{fixes:A}:{},generated_at:C(),projection:{mode:"full",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:["diagnostic_rows"]}};return e.counts!==!0?D:{...oO(D),projection:{mode:"counts",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:[]}}}import{execFile as UO}from"node:child_process";import{promisify as zO}from"node:util";var WO=zO(UO),qO=16,GO=3e4;function BO(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(o=>typeof o=="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 JO(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??{},i=n.parameters??{};for(let o of Object.entries(i).filter(([,s])=>s.required===!0).map(([s])=>s))if(!Object.hasOwn(r,o))throw new TypeError(`assurance provider ${e.id} key ${t.key} requires parameter ${o}`);for(let[o,s]of Object.entries(r)){let a=i[o];if(!a)throw new TypeError(`assurance provider ${e.id} key ${t.key} does not declare parameter ${o}`);if(s===null||typeof s!==a.type)throw new TypeError(`assurance provider ${e.id} parameter ${o} must be ${a.type}`)}return{...r}}async function VO(e,t,n,r){let i=JO(e,t),o=Promise.resolve().then(()=>e.resolve({provider:e.id,key:t.key,parameters:i,trigger:r,pm_root:n,...Ql(n)}));o.catch(()=>{});let s;try{let a=await Promise.race([o,new Promise((c,d)=>{s=setTimeout(()=>d(new TypeError(`assurance provider ${e.id} timed out`)),e.timeout_ms??GO),s.unref?.()})]);return BO(e,t.key,a)}finally{clearTimeout(s)}}function Aw(e,t,n,r){let i=e;for(let o of t.split(".")){if(typeof i!="object"||i===null||Array.isArray(i))throw new ot(`assurance field ${t} is not present`,{source_kind:n,field:t,...r?{check:r}:{}});i=i[o]}if(typeof i=="number"&&Number.isFinite(i)||Array.isArray(i)&&i.every(o=>typeof o=="string"))return i;throw new ot(`assurance field ${t} must resolve to a finite number or string array`,{source_kind:n,field:t,...r?{check:r}:{}})}function Rw(e,t,n,r){let i=e.checks.find(s=>s.name===t);if(!i)throw new ot(`assurance check ${t} is not present`,{source_kind:r,field:n,check:t});return{value:n==="status"||n==="ok"?i.ok?0:1:Aw(i.details,n,r,t),population_size:1,cost:e.checks.length}}async function KO(e,t){if(t?.trim())return t.trim();try{let{stdout:n}=await WO("git",["rev-parse","HEAD^{commit}"],{cwd:e,encoding:"utf8",timeout:5e3,windowsHide:!0});return n.trim()}catch{return"working-copy"}}async function YO(e,t){let n=new Array(t.length),r=0,i=Array.from({length:Math.min(qO,t.length)},async()=>{for(;r<t.length;){let o=r;r+=1;let s=t[o],a=await We(pt(e,s.id),s.id);n[o]=a.map(c=>({op:c.op,author:c.author,agent_harness:c.agent_harness,agent_model:c.agent_model}))}});return await Promise.all(i),n.flat()}async function ei(e,t={}){let n=await T(e),r=W(n),i=_e(n.schema),s=(t.strict_read===!0?(await tm(void 0,{status:"all",full:!0,includeBody:!0,noTruncate:!0,strictRead:!0},{path:e})).items:await gt(e,n.item_format,r.type_to_folder,void 0,n.schema)).map(p=>({...p,id:p.id,status:p.status,type:p.type})),a={path:e},c=U(),d=Object.fromEntries((c?.assurance_providers??[]).map(p=>[p.definition.id,{cost_class:p.runtime_definition.cost_class,network:p.runtime_definition.network}])),l=new Map,u,m;return{tree_id:t.resolve_tree===!1?t.tree_id??"working-copy":await KO(e,t.tree_id),items:s,history:t.include_history===!1?[]:await YO(e,s),terminal_statuses:[...i.terminal_statuses],provider_capabilities:{...d,...t.provider_capabilities},external:async p=>{if(p.kind==="graph"){let y=I({operation:p.operation,parameters:p.parameters??{}}),w=l.get(y);w===void 0&&(w=sm(p.operation,void 0,void 0,{...p.parameters,full:!0},a),l.set(y,w));let v=await w;return{value:Aw(v,p.field,p.kind),population_size:s.length,cost:s.length}}if(p.kind==="validate"){u??=Ew({counts:!0},a);let y=await u;return Rw(y,p.check,p.field,p.kind)}if(p.kind==="health"){m??=jg(a,{checkOnly:!0,full:!0});let y=await m;return Rw(y,p.check,p.field,p.kind)}let f=t.providers?.[p.provider];if(f)return f(p);let h=hu(c,p.provider);if(!h)throw new TypeError(`assurance provider ${p.provider} is not registered`);return VO(h.runtime_definition,p,e,t.trigger??"sdk")}}}import{createHash as XO}from"node:crypto";function Iw(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:i}=Ti({...t,change:{}});return{policy:n,...r===void 0?{}:{cursor:r},...i===void 0?{}:{limit:i},...t.uncoveredOnly===void 0?{}:{uncoveredOnly:t.uncoveredOnly}}}function ZO(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 QO(e,t,n,r,i,o){let s=Object.fromEntries(Cs.map(p=>[p,0])),a=0,c=0,d=0,l=0,u=[],m=XO("sha256").update(i);for(let p of r){let f=e.membership.get(p),h=n.has(p),y=f.family_ids.length>0;y&&h&&(a+=1),y||(c+=1),h||(d+=1);let w=t.get(p)?.escape_class;w!==void 0&&Cs.includes(w)&&(s[w]+=1,l+=1),m.update(I([p,h,t.get(p)??null,f.id,f.family_ids])),(!o||!y||!h)&&u.push(p)}return{classCounts:s,coveredCount:a,uncoveredCount:c,missingCount:d,classifiedCount:l,selected:u,fingerprint:m.digest("hex")}}function Cw(e,t,n={}){au(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 i=new Set,o=new Map;for(let x of t){if(i.has(x.id))throw new TypeError(`Duplicate recurrence item ${x.id}`);i.add(x.id);let E=$i(x);E!==void 0&&o.set(x.id,E)}let s=ru(e.families,o),a=[...s.membership.keys()].sort(),c=I({policy:e,uncoveredOnly:n.uncoveredOnly===!0}),{classCounts:d,coveredCount:l,uncoveredCount:u,missingCount:m,classifiedCount:p,selected:f,fingerprint:h}=QO(s,o,i,a,c,n.uncoveredOnly===!0),y=ZO(n.cursor,h);if(y>f.length)throw new TypeError("recurrence coverage cursor offset exceeds the selected population");let w=f.slice(y,y+r).map(x=>{let E=s.membership.get(x),A=i.has(x);return{item_id:x,lineage_id:E.id,lineage_item_count:E.item_ids.length,family_ids:E.family_ids,present:A,...A?E.family_ids.length===0?{finding:"unregistered_recurrence_item"}:{}:{finding:"missing_recurrence_item"}}}),v=y+w.length,k=a.length===0?null:d.production_defect/a.length;return{ok:u===0&&m===0,fingerprint:h,items:w,total:f.length,has_more:v<f.length,...v<f.length?{next_cursor:Buffer.from(JSON.stringify({fingerprint:h,offset:v})).toString("base64url")}:{},population:{scope:"all_recorded_recurrence_items",item_count:a.length,lineage_count:s.lineages.length,edge_count:s.edge_count,covered_item_count:l,uncovered_item_count:u,missing_item_count:m,classified_item_count:p,unclassified_item_count:a.length-p,class_counts:d,escape_rate:p===a.length?k:null,escape_rate_lower_bound:k},budget_scope:"registered_families_only",cost:{items_scanned:t.length,edges_scanned:s.edge_count,row_limit:r},row_contract:{row_keys:["items"],jq_selector:".items[]"}}}import{createHash as eP}from"node:crypto";var wd,$w=["list","show","put","remove","run","verdicts","presets","apply","derive","promote","risk","lineages"],vd=["measurement","assertion","gate"];function tP(e){if($w.includes(e))return e;throw Li({command_path:"assurance",token:e,allowed:$w,display_name:"assurance action"})}function nr(e,t,n){throw new _(t,g.USAGE,{code:"missing_required_argument",required:`Provide the missing assurance operand: ${e}.`,examples:[n],recovery:{missing:[e]}})}function nP(e){if(!e)return nr("kind",`Assurance declaration kind is required. Expected: ${vd.join(", ")}`,"pm assurance list measurement");if(vd.includes(e))return e;throw new _(`Assurance declaration kind is required. Expected: ${vd.join(", ")}`,g.USAGE)}function Tw(e){if(!e)return nr("preset",`Assurance preset is required. Expected: ${Sr.join(", ")}`,"pm assurance apply software-delivery --owner <pm-item-id>");if(Sr.includes(e))return e;throw new _(`Assurance preset is required. Expected: ${Sr.join(", ")}`,g.USAGE)}function kd(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 rP(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 _("assurance definition must be valid JSON",g.USAGE,{reason:r instanceof Error?r.message:"invalid_json"})}if(typeof n!="object"||n===null||Array.isArray(n))throw new _("assurance put requires a JSON object definition",g.USAGE);return n}async function iP(e){let[t,n,r]=await Promise.all([wr(e,"measurement"),wr(e,"assertion"),wr(e,"gate")]);return{version:1,measurements:t.items,assertions:n.items,gates:r.items}}function Ow(e,t){return t===!0?{id:e.id}:e}async function oP(e,t){let n=t.authorization_decision;if(!n)return[];let r=await ei(e,{include_history:!1,resolve_tree:!1}),i=r.items.find(s=>s.id===n),o=new Set(r.terminal_statuses);if(!i||i.type.toLowerCase()!=="decision"||!o.has(i.status))throw new _(`Assurance authorization ${n} must name a terminal Decision item`,g.USAGE);return[i.id]}async function sP(e,t){let n=Hs(e.limit,"assurance verdict limit");if(n!==void 0&&(n<1||n>1e3))throw new _(`assurance verdict limit must be an integer from 1 through ${1e3}`,g.USAGE);let r=await Rm(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 Pw(e,t,n){try{return await Ws(()=>xm(e,t,n))}catch(r){if(!(r instanceof _)||r.context.reason!=="assurance_evaluation_refused")throw r;let i=["--pm-path",e,"assurance","list",t,"--output-budget","2000","--json"],o=K(i);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:[o],recovery:{next_best_command:o,suggested_retry:o,suggested_retry_args:i}}),r}}async function aP(e,t,n){if(e==="presets"){if(t.preset??t.id)return eo(Tw(t.preset??t.id),kd(t));let i=Sr.map(o=>{let s=eo(o,"pm-owner");return{id:o,title:s.title,description:s.description}});return{items:i,count:i.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}if(e==="apply")return On(()=>ip(n,Tw(t.preset??t.id),kd(t),{author:t.author,message:t.message}));if(e==="derive"){let i=await op(await ei(n,{resolve_tree:!1,trigger:"derive"}),kd(t)),o=t.apply?await On(()=>sp(n,i,{author:t.author,message:t.message??"Accept observation-derived assurance proposals"})):void 0;return{items:i,count:i.length,...o?{applied:o}:{}}}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 _("assurance promote requires --enforcement warn|block",g.USAGE);let r=await Pw(n,"assertion",t.id);return On(()=>ap(n,r,t.enforcement,{author:t.author,message:t.message}))}async function cP(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 _("assurance run requires a trigger",g.USAGE);if(!Xt.includes(e.trigger))throw new _(`Unknown assurance trigger ${e.trigger}. Expected: ${Xt.join(", ")}`,g.USAGE);let i=e.trigger,[o,s]=await Promise.all([iP(t),ei(t,{...n.workspace,tree_id:e.tree,trigger:i})]),a=await Ws(()=>km(r,o,s,{trigger:i,dry_run:e.dry_run===!0}));return a.dry_run||await Em(t,a,{author:e.author,message:e.message}),a}function Lw(e){throw e instanceof _?e:new _(e instanceof Error?e.message:"assurance risk request is invalid",g.USAGE)}function dP(e){if(e.limit!==void 0)throw new _(`assurance ${e.action} does not accept --limit; set limit inside the definition`,g.USAGE);let t=e.definition;if(typeof t=="string")try{t=JSON.parse(t)}catch(n){throw new _(`assurance ${e.action} definition must be valid JSON`,g.USAGE,{reason:n instanceof Error?n.message:"invalid_json"})}try{return e.action==="lineages"?Iw(t):Ti(t)}catch(n){if(e.action==="risk"&&n instanceof su)throw new _(n.message,g.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 Lw(n)}}function lP(e,t){let n=new Set;for(let[r,i]of t)e.item_fingerprints.get(r)!==i&&n.add(r);for(let r of e.item_fingerprints.keys())t.has(r)||n.add(r);return n}function uP(e,t,n){let r=I(t.policy),i=wd?.pm_root===e?wd:void 0,o=new Map(n.map(d=>[d.id,eP("sha256").update(I([nu(d),$i(d)])).digest("hex")])),s=i?.policy_serialized===r?i:void 0,a=s?lP(s,o):new Set,c=iu(t.policy,s?n.filter(d=>a.has(d.id)):n,s?{previous_index:s.index,changed_item_ids:[...a]}:{});return wd={pm_root:e,policy_serialized:r,item_fingerprints:o,index:c},c}async function mP(e,t){let n=dP(e),r=await ei(t,{strict_read:!0,include_history:!1,resolve_tree:!1});try{return"change"in n?ou(uP(t,n,r.items),n.change,{cursor:n.cursor,limit:n.limit}):Cw(n.policy,r.items,n)}catch(i){return Lw(i)}}async function pP(e,t={},n={}){let r=tP(e.action),i=M(process.cwd(),t.path);if(r==="presets"||r==="apply"||r==="derive"||r==="promote")return aP(r,e,i);if(r==="verdicts")return sP(e,i);if(r==="run")return cP(e,i,n);if(["risk","lineages"].includes(r))return mP(e,i);let o=nP(e.kind);if(r==="list")return wr(i,o);if(!e.id)return nr("id",`assurance ${r} requires an id`,`pm assurance ${r} ${o} <id>`);let s=e.id;if(r==="show")return Pw(i,o,s);if(r==="remove"){let l=await On(()=>Sm(i,o,s,{author:e.author,message:e.message}));return Ow(l,e.idOnly)}let a=rP(o,e.definition);if(a.id!==s)throw new _(`Assurance definition id ${a.id} does not match requested id ${s}`,g.USAGE);let c={author:e.author,message:e.message,...o==="assertion"?{authorized_decision_ids:await oP(i,a)}:{}},d=await On(()=>Vi(i,o,a,c));return Ow(d,e.idOnly)}function IV(e,t,n){let r={...e,...t};return pP({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:Hs(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 an from"node:fs/promises";import ni from"node:path";import is from"node:fs/promises";import bd from"node:path";var fP=864e5;function hP(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 _P(e,t){let n;try{n=await is.readdir(e,{withFileTypes:!0})}catch(i){if(F(i))return[];throw i}let r=[];for(let i of n)if(i.isDirectory()){let o=bd.join(e,i.name),s;try{s=await is.readdir(o)}catch(a){F(a)||t.push(`checkpoint_subdir_unreadable:${i.name}`);continue}for(let a of s)a.endsWith(".json")&&r.push(`${i.name}/${a}`)}else i.name.endsWith(".json")&&r.push(i.name);return r.sort()}async function Nw(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),o=Math.max(0,t.retentionDays)*fP,s=bd.join(e,"checkpoints"),a={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c=await _P(s,a.warnings);for(let d of c){let l=bd.join(s,d),u=`checkpoints/${d}`;a.scanned+=1,r?.onRead&&a.warnings.push(...await r.onRead(l));let m;try{m=await is.readFile(l,"utf8")}catch(w){if(F(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 p=hP(m),f=p===null?Number.NaN:Date.parse(p);if(!Number.isFinite(f)){a.warnings.push(`checkpoint_unparseable:${d}`),a.retained.push(u),a.entries.push({file:u,created_at:p,age_seconds:null,stale:!1,reason:"unparseable"});continue}let h=i-f,y={file:u,created_at:p,age_seconds:Math.floor(h/1e3),stale:h>o,reason:h>o?"expired":"active"};if(!y.stale){a.retained.push(u),a.entries.push(y);continue}if(!n){try{await is.unlink(l)}catch(w){if(!F(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}import xd from"node:fs/promises";import Dw from"node:path";var gP=1440*60*1e3,yP=new Set(["committed","compensated"]);function wP(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 vP(e,t,n,r,i){let o=n===null?Number.NaN:Date.parse(n);if(t===null||!Number.isFinite(o))return{entry:{file:e,status:t,age_seconds:null,stale:!1,reason:"unparseable"},remove:!1};let s=r-o;return yP.has(t)?s>i?{entry:{file:e,status:t,age_seconds:Math.floor(s/1e3),stale:!0},remove:!0}:{entry:{file:e,status:t,age_seconds:Math.floor(s/1e3),stale:!1,reason:"fresh"},remove:!1}:{entry:{file:e,status:t,age_seconds:Math.floor(s/1e3),stale:!1,reason:"active"},remove:!1}}async function kP(e,t,n,r){let i=r.hooks?.onRead?await r.hooks.onRead(e):[],o=wP(await xd.readFile(e,"utf8")),s=vP(t,o.status,o.updatedAt,r.nowMs,r.retentionMs);return s.entry.reason==="unparseable"&&i.push(`transaction_journal_unparseable:${n}`),s.remove&&!r.dryRun&&(await xd.rm(e,{force:!0}),r.hooks?.onWrite&&i.push(...await r.hooks.onWrite(e))),{decision:s,warnings:i}}async function Mw(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),o=Math.max(0,t.retentionDays)*gP,s=Dw.join(e,"transactions","sdk"),a={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c;try{c=(await xd.readdir(s)).filter(d=>d.endsWith(".json")).sort((d,l)=>d.localeCompare(l))}catch(d){if(F(d))return a;throw d}for(let d of c){let l=Dw.join(s,d),u=`transactions/sdk/${d}`,m=await kP(l,u,d,{dryRun:n,hooks:r,nowMs:i,retentionMs:o});a.warnings.push(...m.warnings),a.scanned+=1;let{decision:p}=m;if(!p.remove){a.retained.push(u),a.entries.push(p.entry);continue}a.removed.push(u),a.entries.push(p.entry)}return a}var ti=["index","embeddings","runtime","locks","checkpoints","transactions"],bP=1440*60*1e3,Fw=[{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 xP(e,t,n){let r=t.relativePath,i=ni.join(e,r),o=await Be({path:i,scope:"project"});if(t.scope==="runtime"&&await jw(e))return{removed:!1,redirected:!0,warnings:o};try{let s=await an.lstat(i);if(t.kind==="file"&&!s.isFile())return{removed:!1,warnings:[...o,`not_a_file:${r}`]};if(t.kind==="directory"&&!s.isDirectory())return{removed:!1,warnings:[...o,`not_a_directory:${r}`]};if(n)return{removed:!0,warnings:o};t.kind==="file"?await an.unlink(i):await an.rm(i,{recursive:!0,force:!0});let a=await Y({path:i,scope:"project",op:"gc:remove"});return{removed:!0,warnings:[...o,...a]}}catch(s){if(F(s))return{removed:!1,warnings:o};throw s}}async function SP(e,t,n){let r=[],i=[],o=[],s=!1;for(let a of Fw.filter(c=>t.includes(c.scope))){if(a.scope==="runtime"&&s){i.push(a.relativePath);continue}let c=await xP(e,a,n);s||=c.redirected===!0,(c.removed?r:i).push(a.relativePath),o.push(...c.warnings)}if(t.includes("runtime")&&!s&&(s=await jw(e)),s)o.push("redirected_runtime_directory:runtime");else if(t.includes("runtime")){let a=await EP(e,n);r.push(...a.removed),i.push(...a.retained),o.push(...a.warnings)}return{removed:r,retained:i,warnings:o}}async function jw(e){try{return!(await an.lstat(ni.join(e,"runtime"))).isDirectory()}catch(t){if(F(t))return!1;throw t}}async function EP(e,t){let n=[{relativePath:"runtime/workspace-snapshots/objects",prefix:".create-"},{relativePath:"runtime/workspace-snapshots/refs",prefix:".ref-"}],r=[],i=[],o=[],s=Date.now()-bP;for(let a of n){let c=ni.join(e,a.relativePath);if(!await P(c))continue;let d=(await an.readdir(c)).filter(l=>l.startsWith(a.prefix)).sort();for(let l of d){let u=ni.posix.join(a.relativePath,l),m=ni.join(c,l);o.push(...await Be({path:m,scope:"project"}));let p=await an.stat(m).catch(f=>{if(!F(f))throw f});if(p){if(p.mtimeMs>s){i.push(u);continue}r.push(u),!t&&(await an.rm(m,{recursive:!0,force:!0}),o.push(...await Y({path:m,scope:"project",op:"gc:workspace_snapshot_temp_remove"})))}}}return{removed:r,retained:i,warnings:o}}function RP(e){if(!e||e.length===0)return[...ti];let t=e.flatMap(r=>r.split(",")).map(r=>r.trim().toLowerCase()).filter(r=>r.length>0);if(t.length===0)throw new _(`--scope requires at least one value (${ti.join(",")})`,g.USAGE);let n=new Set;for(let r of t){if(!ti.includes(r))throw new _(`Invalid --scope value "${r}". Expected one or more of: ${ti.join(", ")}`,g.USAGE);n.add(r)}return ti.filter(r=>n.has(r))}function AP(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(i=>i==="index/manifest.json"||i==="search/embeddings.jsonl"||i==="search/vectorization-status.json"||i==="search/lancedb"||i==="search/pending-refresh.json"||i==="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(i=>i.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(i=>i.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 XV(e,t={}){let n=M(process.cwd(),e.path);await ie(n);let r=await T(n),i=t.dryRun===!0,o=RP(t.scope),{removed:s,retained:a,warnings:c}=await SP(n,o,i),d;if(o.includes("locks")){let p=await Bp(n,{dryRun:i,hooks:{onRead:f=>Be({path:f,scope:"project"}),onWrite:f=>Y({path:f,scope:"project",op:"gc:lock_remove"})}});s.push(...p.removed),a.push(...p.retained),c.push(...p.warnings),d={scanned:p.scanned,removed:p.removed.length,retained:p.retained.length}}let l;if(o.includes("transactions")){let p=r.checkpoints.retention_days,f=await Mw(n,{dryRun:i,retentionDays:p,hooks:{onRead:h=>Be({path:h,scope:"project"}),onWrite:h=>Y({path:h,scope:"project",op:"gc:transaction_journal_remove"})}});s.push(...f.removed),a.push(...f.retained),c.push(...f.warnings),l={scanned:f.scanned,removed:f.removed.length,retained:f.retained.length,retention_days:p}}let u;if(o.includes("checkpoints")){let p=r.checkpoints.retention_days,f=await Nw(n,{dryRun:i,retentionDays:p,hooks:{onRead:h=>Be({path:h,scope:"project"}),onWrite:h=>Y({path:h,scope:"project",op:"gc:checkpoint_remove"})}});s.push(...f.removed),a.push(...f.retained),c.push(...f.warnings),u={scanned:f.scanned,removed:f.removed.length,retained:f.retained.length,retention_days:p}}c.push(...await Ii({mode:i?"gc:dry-run":"gc",total_items:Fw.filter(p=>o.includes(p.scope)).length}));let m=AP({dryRun:i,scopes:o,removed:s});return{ok:c.length===0,dry_run:i,scope:o,removed:s,retained:a,warnings:c,...d?{locks:d}:{},...u?{checkpoints:u}:{},...l?{transactions:l}:{},guidance:m,generated_at:C()}}import{execFile as IP}from"node:child_process";import CP from"node:path";import{promisify as $P}from"node:util";var TP=$P(IP),Uw="@unbrained/pm-cli",OP="latest",PP={global:["--global"],project:[]};function Hw(e){let t=e.project===!0||e.local===!0||e.scope==="project",n=e.global===!0||e.scope==="global";if(t&&n)throw new _('Options "--project/--local" and "--global" are mutually exclusive.',g.USAGE);return n?"global":"project"}function ss(e){return e.trim().toLowerCase()}function zw(e,t){let n=ss(t);return[e.name,e.directory,e.source.input,e.source.location,e.source.package,e.source.repository,e.source.owner&&e.source.repo?`${e.source.owner}/${e.source.repo}`:void 0].some(i=>typeof i=="string"&&ss(i)===n)}function LP(e,t){let n=M(process.cwd(),t.path),r=mn(n,process.cwd());return{selected_root:e==="global"?r.global:r.project}}async function NP(e,t,n){try{let r=await TP(e,t,{cwd:n?.cwd,encoding:"utf8"});return{stdout:r.stdout,stderr:r.stderr}}catch(r){let i=typeof r=="object"&&r!==null&&"stderr"in r?String(r.stderr??""):"",o=i.trim().length>0?i.trim():r instanceof Error?r.message:String(r);throw new _(`Command failed: ${e} ${t.join(" ")}
|
|
71
|
+
${o}`,g.GENERIC_FAILURE)}}function as(e){return typeof e.tag=="string"&&e.tag.trim().length>0?e.tag.trim():OP}function os(e){return typeof e.packageName=="string"&&e.packageName.trim().length>0?e.packageName.trim():Uw}async function DP(e,t){let n=e.commandRunner??NP,r=os(e),i=as(e),o=`${r}@${i}`,s=["npm","install","-g",o];e.repair===!0&&s.push("--force");let a=Wd(import.meta.url,["../../.."]),c={requested:!0,status:"planned",package:r,target:o,command:s,before_version:a,...r===Uw?{migration_guidance:["Calendar scheduling commands are package-owned. If calendar is absent, run pm package install calendar --project; use pm calendar meet, pm calendar event, or pm calendar remind."]}:{},repair:e.repair===!0};if(t)return c;try{await n(s[0],s.slice(1));let d=await n("pm",["--version"]);return{...c,status:"updated",after_version:d.stdout.trim()||void 0}}catch(d){return{...c,status:"failed",error:d instanceof Error?d.message:String(d)}}}function MP(e){return CP.isAbsolute(e)||e.startsWith(".")||e.startsWith("..")||e.startsWith("file:")}function FP(e,t){if(e.kind==="npm"){let n=e.input.startsWith("npm:")?e.input.slice(4).trim():e.input.trim();return!MP(n)&&e.package&&e.package.trim().length>0?`npm:${e.package.trim()}@${t}`:e.input.startsWith("npm:")?e.input:`npm:${e.input}`}return e.input}async function jP(e,t){let n=FP(e,t);return e.kind!=="local"||await P(n)?n:await P(e.location)?e.location:n}function HP(e,t,n,r){let i=["pm","package","install",t,n==="global"?"--global":"--project"];return e.kind==="github"&&r&&r.trim().length>0&&i.push("--ref",r.trim()),i}async function Ww(e,t){let n=LP(e,t);return(await be(n.selected_root)).state.entries.filter(i=>i.scope===e)}async function UP(e,t,n){let r=await Ww(e,t);return r.find(i=>zw(i,n.name))??r.find(i=>ss(i.directory)===ss(n.directory))}async function zP(e,t,n,r,i){let o=as(t),s=await jP(e.source,o),a=HP(e.source,s,r,e.source.ref),c={name:e.name,directory:e.directory,scope:r,source:e.source,status:"planned",command:a,previous_version:e.manifest_version};if(i)return c;try{await Qa(s,{install:!0,project:r==="project",global:r==="global",ref:e.source.kind==="github"?e.source.ref:void 0},n);let d=await UP(r,n,e);return{...c,status:"updated",installed_version:d?.manifest_version}}catch(d){return{...c,status:"failed",error:d instanceof Error?d.message:String(d)}}}function WP(e,t,n,r){let i=[n?e.status:void 0,...t.map(o=>o.status)].filter(o=>typeof o=="string");return{requested_cli:n,requested_packages:r,planned:i.filter(o=>o==="planned").length,updated:i.filter(o=>o==="updated").length,skipped:i.filter(o=>o==="skipped").length,failed:i.filter(o=>o==="failed").length}}async function o2(e,t,n){let r=typeof e=="string"&&e.trim().length>0?e.trim():void 0;if(t.cliOnly===!0&&t.packagesOnly===!0){let m=["package","upgrade",...r?[r]:[],"--packages-only","--dry-run",...PP[Hw(t)]];throw new _('Options "--cli-only" and "--packages-only" are mutually exclusive.',g.USAGE,{code:"package_upgrade_modes_mutually_exclusive",recovery:{suggested_retry:K(m),suggested_retry_args:m}})}let i=Hw(t),o=t.dryRun===!0;if(t.cliOnly===!0&&r)throw new _('A package target cannot be used with "--cli-only".',g.USAGE);let s=!(t.packagesOnly===!0||r),a=t.cliOnly!==!0,c=s?await DP(t,o):{requested:!1,status:"skipped",package:os(t),target:`${os(t)}@${as(t)}`,command:["npm","install","-g",`${os(t)}@${as(t)}`],repair:t.repair===!0,reason:"not_requested"},d=a?await Ww(i,n):[];if(r&&(d=d.filter(m=>zw(m,r)),d.length===0))throw new _(`Managed package "${r}" was not found in ${i} scope.`,g.NOT_FOUND);let l=[];for(let m of d)l.push(await zP(m,t,n,i,o));let u=WP(c,l,s,a);return{ok:u.failed===0,action:"upgrade",dry_run:o,scope:i,target:r,cli:c,packages:l,summary:u}}import{createHash as qP}from"node:crypto";import{isUtf8 as GP}from"node:buffer";import ri from"node:fs/promises";import Sd from"node:path";async function qw(e){try{return(await ri.readdir(e)).filter(t=>t.endsWith(".jsonl")).sort()}catch(t){if(F(t))return[];throw t}}function BP(e,t,n,r){let i=t.at(-1),o;for(let c=t.length-1;c>=0;c-=1)if(["history_compact","history_compact_baseline","history_redact","history_repair","history_salvage","merge_reconcile"].includes(t[c].op)){o=t[c];break}let s=t[0]?.context?.history_compaction,a=typeof s=="object"&&s!==null&&"pruned_stream_digest"in s&&typeof s.pruned_stream_digest=="string"?s.pruned_stream_digest:null;return{id:e,entries:t.length,bytes:n,stream_digest:r,latest_after_hash:i?.after_hash??null,latest_record_hash:i?.record_hash??null,latest_hash_algorithm:i?ve(i.hash_algorithm):null,rewrite_count:t.reduce((c,d)=>c+(d.reanchor_evidence?.length??0),0),checkpoint_digest:a,last_maintenance:o?{op:o.op,ts:o.ts,record_hash:o.record_hash??null}:null}}function JP(e,t,n){try{if(!/^[A-Za-z0-9_-]+$/u.test(e)||!GP(t))return null;let r=[];for(let i of t.toString("utf8").split(/\r?\n/u)){if(!i.trim())continue;let o=JSON.parse(i);if(typeof o!="object"||o===null||Array.isArray(o))return null;let s=o;if(![s.op,s.author,s.ts,s.before_hash,s.after_hash].every(a=>typeof a=="string")||!Array.isArray(s.patch))return null;r.push(s)}return cr(r).ok?BP(e,r,t.length,n):null}catch{return null}}async function Ed(e,t){if(!(await ri.stat(e)).isDirectory())throw new TypeError("attestation tracker root must be a directory");let n=Sd.join(e,"history"),r=await qw(n),i=new Map,o=[];for(let s of r){let a=s.slice(0,-6),c={id:a,digest:null,stream:null};o.push(c);let d=Sd.join(n,s);try{let l=await ri.lstat(d);if(i.set(s,I([l.ino,l.size,l.mtimeMs,l.ctimeMs])),!l.isFile())continue;let u=await ri.readFile(d);c.digest=qP(t).update(u).digest("hex"),c.stream=JP(a,u,c.digest)}catch{}}if(I(r)!==I(await qw(n)))throw new TypeError("attestation history inventory changed during read; retry");for(let[s,a]of i){let c=await ri.lstat(Sd.join(n,s));if(a!==I([c.ino,c.size,c.mtimeMs,c.ctimeMs]))throw new TypeError("attestation history stream changed during read; retry")}return o}function Rd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ad(e,t){return Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n))}function rr(e,t){return typeof e=="string"&&(t==="sha256"?/^[a-f0-9]{64}$/u:/^[a-f0-9]{128}$/u).test(e)}function VP(e){return e.entries===0?[e.latest_hash_algorithm,e.latest_after_hash,e.latest_record_hash,e.checkpoint_digest,e.last_maintenance].every(t=>t===null)&&e.rewrite_count===0:e.latest_hash_algorithm!=="sha256"&&e.latest_hash_algorithm!=="sha512"?!1:rr(e.latest_after_hash,e.latest_hash_algorithm)&&(e.latest_record_hash===null||rr(e.latest_record_hash,e.latest_hash_algorithm))}function KP(e){return e===null?!0:!Rd(e)||!Ad(e,["op","ts","record_hash"])?!1:typeof e.op=="string"&&["history_compact","history_compact_baseline","history_redact","history_repair","history_salvage","merge_reconcile"].includes(e.op)&&typeof e.ts=="string"&&Pt(e.ts)&&(e.record_hash===null||rr(e.record_hash,"sha256")||rr(e.record_hash,"sha512"))}function YP(e,t){return!Rd(e)||!Ad(e,["id","entries","bytes","stream_digest","latest_after_hash","latest_record_hash","latest_hash_algorithm","rewrite_count","checkpoint_digest","last_maintenance"])?!1:typeof e.id=="string"&&/^[A-Za-z0-9_-]+$/u.test(e.id)&&[e.entries,e.bytes,e.rewrite_count].every(n=>typeof n=="number"&&Number.isSafeInteger(n)&&n>=0)&&rr(e.stream_digest,t)&&VP(e)&&(e.checkpoint_digest===null||rr(e.checkpoint_digest,"sha256"))&&KP(e.last_maintenance)}function Gw(e){if(!Rd(e)||!Ad(e,["format","version","hash_algorithm","generated_at","streams","workspace_digest"]))throw new TypeError("Invalid history attestation bundle");if(e.format!==js.format||e.version!==1||typeof e.generated_at!="string"||!Pt(e.generated_at)||!Array.isArray(e.streams)||e.hash_algorithm!=="sha256"&&e.hash_algorithm!=="sha512")throw new TypeError("Invalid history attestation format");let t=e.hash_algorithm,n;for(let o of e.streams){if(!YP(o,t))throw new TypeError("Invalid history attestation stream");let s=o.id;if(n!==void 0&&s<=n)throw new TypeError("Invalid history attestation stream order");n=s}let{workspace_digest:r,...i}=e;if(xs(I(i),t)!==r)throw new TypeError("History attestation rollup mismatch");return e}async function Bw(e={}){let t=ve(e.hashAlgorithm),n=e.generatedAt??C();if(!Pt(n))throw new TypeError("Invalid history attestation timestamp");let r=await Ed(M(e.cwd??process.cwd(),e.pmRoot),t),i=r.filter(s=>s.stream===null);if(i.length>0)throw new TypeError(`Cannot export history attestation: invalid streams ${i.map(s=>s.id).join(", ")}`);let o={format:js.format,version:1,hash_algorithm:t,generated_at:n,streams:r.map(s=>s.stream)};return Gw({...o,workspace_digest:xs(I(o),t)})}async function Jw(e,t={}){let n=Gw(e),r=await Ed(M(t.cwd??process.cwd(),t.pmRoot),n.hash_algorithm),i=new Map(r.map(l=>[l.id,l])),o=new Map(n.streams.map(l=>[l.id,l])),s=n.streams.filter(l=>!i.has(l.id)).map(l=>l.id),a=r.filter(l=>!o.has(l.id)).map(l=>l.id),c=r.filter(l=>l.stream===null).map(l=>l.id),d=[];for(let l of n.streams){let u=i.get(l.id);u&&(u.digest!==l.stream_digest||I(u.stream)!==I(l))&&d.push({id:l.id,before_digest:l.stream_digest,after_digest:u.digest,last_maintenance:u.stream?.last_maintenance??null})}return{ok:s.length+a.length+c.length+d.length===0,workspace_digest:n.workspace_digest,streams_checked:r.length,changed_streams:d.map(l=>l.id),missing_streams:s,added_streams:a,invalid_streams:c,transitions:d}}import Vw from"node:fs/promises";async function C2(e,t){for(let r of["verify","output","hashAlgorithm"]){let i=e[r];if(!(r==="verify"&&typeof i=="object"&&i!==null)&&i!==void 0&&(typeof i!="string"||i.trim().length===0))throw new _(`history attest ${r} requires a nonempty string.`,g.USAGE)}if(e.verify!==void 0){if(e.output!==void 0||e.hashAlgorithm!==void 0)throw new _("history attest --verify cannot be combined with --output or --hash-algorithm",g.USAGE);let r;try{r=typeof e.verify=="string"?JSON.parse(await Vw.readFile(e.verify,"utf8")):e.verify}catch{throw new _("Cannot read history attestation proof. Provide --verify with a readable JSON proof file.",g.USAGE)}return Jw(r,{pmRoot:t.path})}let n=await Bw({pmRoot:t.path,hashAlgorithm:ve(e.hashAlgorithm)});if(e.output===void 0)return n;try{await Vw.writeFile(e.output,`${JSON.stringify(n,null,2)}
|
|
72
|
+
`,{flag:"wx",mode:384})}catch{throw new _("Cannot create history attestation proof. Choose --output with a new filename in a writable directory; existing files are never overwritten.",g.USAGE)}return{output:e.output,workspace_digest:n.workspace_digest,streams:n.streams.length}}function Kw(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 Yw(e,t,n=process.platform){let r=["--pm-path",t];return e==="merge_evidence_invalid"?K([...r,"merge","report"],n):e==="history_evidence_invalid"?K([...r,"validate","--check-history-drift","--full"],n):e==="merge_reconciliation_required"?K([...r,"merge","reconcile"],n):e==="history_repair_required"?K([...r,"history-repair","--all"],n):e==="merge_fence_unprepared"?K([...r,"merge","install"],n):null}function Xw(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 z2(e){let t=M(process.cwd(),e.path);await ie(t);let n=await T(t),r=W(n,U()),i=[],o=await Yo({includeBody:!0,pmRoot:t,settings:n,typeToFolder:r.type_to_folder,warnings:i}),s=await Mt(t),[a,c,d,l]=await Promise.all([$n(t,Cn(n),{gitWorkspaceRoot:s}),s===null?Promise.resolve(null):Tn(s),Rt(s??t,{includeLossless:!0,pmRoot:t}),Xo(t,o,!1)]),{pendingDecisions:u,lossless:m}=Kn(d.receipts),p=[...new Set(u.map(w=>w.item_id))].sort((w,v)=>w.localeCompare(v)),f=l.check.details,h=Xw(f),y=Kw({invalidEvidenceCount:d.invalid_evidence_count,pendingDecisionCount:u.length,losslessCount:m.length,historyEvidenceValid:h.evidence_valid,driftedItemCount:h.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:p.slice(0,25),pending_item_ids_truncated:p.length>25,lossless_count:m.length,invalid_evidence_count:d.invalid_evidence_count},history_drift:h,next_action:{command:Yw(y,t),reason:y},warnings:[...new Set(i)].sort((w,v)=>w.localeCompare(v)),generated_at:C()}}function W2(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(`
|
|
73
|
+
`)}var q2={commandForWorkspacePositionState:Yw,normalizeWorkspaceHistoryDrift:Xw,selectWorkspacePositionState:Kw};import XP from"node:fs/promises";import ii from"node:path";var Id="index/manifest.json",Cd="search/embeddings.jsonl",ZP="Provider or model has changed since last index. Run pm reindex --mode semantic to rebuild.";function QP(e){return e.progress===!0||process.stderr.isTTY===!0}function de(e,t){if(e)try{process.stderr.write(`[pm reindex] ${t}
|
|
74
|
+
`)}catch{}}function eL(e){let t=(e??"keyword").trim().toLowerCase();if(t==="keyword")return"keyword";if(t==="semantic"||t==="hybrid")return t;throw new _("Reindex mode must be one of keyword|semantic|hybrid",g.USAGE)}async function tL(e,t,n,r){let i=[];return{candidates:await Ou(e,t,n,i,r),warnings:i}}async function Td(e,t,n,r,i){let o=ln(U()),s=[];for(let a of t)if(!(i&&!i.has(a.metadata.id))){if(typeof a.body=="string"){s.push({metadata:a.metadata,body:a.body});continue}try{let c=await XP.readFile(a.item_path,"utf8"),d=Lt(c,{format:a.item_format,schema:n,extensionFieldNames:o,onWarning:l=>r.push(l)});s.push({metadata:a.metadata,body:d.body})}catch{r.push(`item_list_item_read_failed:${ii.relative(e,a.item_path)}`),s.push({metadata:a.metadata,body:""})}}return s}function nL(e,t,n){let r=e.metadata;return{id:r.id,mode:t,updated_at:r.updated_at,corpus:Nu(e,{fields:n})}}var ir=X;function rL(e){let t=U(),n=ir(e.search?.provider);if(!n)return null;let r=_u(t,n);if(!r)return null;let i=r.runtime_definition??r.definition,o=ir(i.name)??ir(r.definition.name);if(!o)return null;let s=i.embedBatch,a=i.embed_batch,c=i.embed,d=typeof s=="function"?s:typeof a=="function"?a:void 0,l=typeof c=="function"?c:void 0;return!d&&!l?null:{name:o,embedBatch:d,embed:l}}function iL(e){let t=U(),n=ir(e.vector_store?.adapter);if(!n)return null;let r=gu(t,n);if(!r)return null;let i=r.runtime_definition??r.definition,o=ir(i.name)??ir(r.definition.name);if(!o)return null;let s=i.upsert,a=i.delete;return{adapterName:o,...typeof s=="function"?{upsert:s}:{},...typeof a=="function"?{delete:a}:{}}}function $d(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="number"||!Number.isFinite(n)))throw new _(`Invalid vector returned by ${t}`,g.GENERIC_FAILURE);return e}async function oL(e,t,n){let r=t.search?.embedding_model?.trim()||"text-embedding-3-small";if(e.embedBatch){let o=await Promise.resolve(e.embedBatch({inputs:n,settings:t,model:r}));if(!Array.isArray(o))throw new _(`Extension search provider "${e.name}" embedBatch must return an array of vectors`,g.GENERIC_FAILURE);return o.map((s,a)=>$d(s,`extension search provider "${e.name}" embedBatch output at index ${a}`))}if(!e.embed)throw new _(`Extension search provider "${e.name}" does not implement embed/embedBatch`,g.GENERIC_FAILURE);let i=[];for(let[o,s]of n.entries()){let a=await Promise.resolve(e.embed({input:s,settings:t,model:r}));i.push($d(a,`extension search provider "${e.name}" embed output at index ${o}`))}return i}function Zw(e){return e.search?.embedding_model?.trim()||"text-embedding-3-small"}function Qw(e,t,n){let r=n?Yt(n.name,Zw(e)):t?Yt(t.name,t.model):null;if(!r)throw new _("No embedding identity available for semantic reindex mode",g.USAGE);return r}function sL(e,t){return Object.keys(e).filter(n=>!t.has(n)).sort((n,r)=>n.localeCompare(r))}async function ev(e,t,n,r,i,o,s,a){let c=r?.name??n?.name,d=Du(c,e.search.embedding_corpus_max_characters).maxCharacters,l=Ps(e),u=i.map(f=>Mu(f,{providerName:c,maxCharacters:d,fields:l})),m=[],p=null;if(r)try{m=await oL(r,e,u),p=Yt(r.name,Zw(e))}catch(f){if(!n)throw new _(`Extension search provider "${r.name}" failed to generate embeddings: ${f instanceof Error?f.message:String(f)}`,g.GENERIC_FAILURE);o.push(`Extension search provider "${r.name}" failed; falling back to built-in provider (${f instanceof Error?f.message:String(f)})`)}if(m.length===0){if(!n)throw new _(`No embedding executor available for reindex mode '${t}'`,g.USAGE);let f=await Fu(n,e,u,{onProgress:h=>{h.phase==="complete"&&(s.batches_completed=h.batch_index),de(a,`embedding_batch_${h.phase} batch=${h.batch_index}/${h.batch_total} size=${h.batch_size} completed_inputs=${h.completed_inputs}/${h.total_inputs}`)}});o.push(...f.warnings),s.batching=f.receipt,m=f.vectors,p=Yt(n.name,n.model)}if(de(a,`embedding_complete vectors=${m.length}`),m.length!==i.length)throw new _(`Embedding output size mismatch (expected ${i.length}, received ${m.length})`,g.GENERIC_FAILURE);if(!p)throw new _(`No embedding identity available for reindex mode '${t}'`,g.USAGE);return{vectors:m,embeddingIdentity:p}}async function aL(e,t,n,r,i,o){let s=Object.keys(n);if(t){if(s.length>0&&t.delete)try{await Promise.resolve(t.delete({ids:s.sort((a,c)=>a.localeCompare(c)),settings:r}))}catch(a){throw new _(`Extension vector adapter "${t.adapterName}" failed to delete vectors during reindex reset: ${a instanceof Error?a.message:String(a)}`,g.GENERIC_FAILURE)}else s.length>0&&i.push(`search_semantic_reindex_reset_skipped:adapter=${t.adapterName}:known_ids=${s.length}`);if(!e)return}e&&await Uu(e,s,{},o)}async function tv(e,t,n,r,i){if(n.length!==0){if(t){if(t.delete)try{await Promise.resolve(t.delete({ids:n,settings:r}))}catch(o){throw new _(`Extension vector adapter "${t.adapterName}" failed to delete orphan vectors during reindex: ${o instanceof Error?o.message:String(o)}`,g.GENERIC_FAILURE)}else i.push(`search_semantic_reindex_orphan_prune_skipped:adapter=${t.adapterName}:count=${n.length}`);if(!e)return}e&&await Hu(e,n)}}function cL(e){return{enabled:e!=="keyword",stale_items:0,unchanged_items:0,embedded_items:0,vector_upserted:0,batches_completed:0}}function dL(e,t,n){return{version:1,mode:e,generated_at:t,total_items:n.length,items:n.map(r=>({id:r.metadata.id,type:r.metadata.type,status:r.metadata.status,priority:r.metadata.priority,updated_at:r.metadata.updated_at}))}}function lL(e){if(e.requestedMode==="keyword")return{activeEmbeddingProvider:null,activeVectorStore:null};let t=pr(e.settings);if(!t.active&&!e.extensionEmbedding)throw new _(`Reindex mode '${e.requestedMode}' requires a configured embedding provider in settings.providers.openai/settings.providers.ollama or an extension provider selected by settings.search.provider`,g.USAGE);let n=Hi(e.settings,e.pmRoot);if(!n.active&&!e.extensionVectorAdapter)throw new _(`Reindex mode '${e.requestedMode}' requires a configured vector store in settings.vector_store.qdrant/settings.vector_store.lancedb or an extension adapter selected by settings.vector_store.adapter`,g.USAGE);return{activeEmbeddingProvider:t.active,activeVectorStore:n.active}}async function uL(e){let t=W(e.settings,U()),n=await tL(e.pmRoot,e.settings.item_format,t.type_to_folder,e.settings.schema);return{documentCandidates:n.candidates,warnings:[...n.warnings],metadataDocuments:n.candidates.map(r=>({metadata:r.metadata,body:typeof r.body=="string"?r.body:""}))}}async function mL(e){let t=await An(e.pmRoot);if(e.reindexWarnings.push(...t.warnings),e.forceFullSemantic&&e.reindexWarnings.push("search_semantic_reindex_full_ignored:mode_keyword"),!t.embedding)return;let n=(()=>{try{return Qw(e.settings,pr(e.settings).active,e.extensionEmbedding)}catch{return null}})();n&&Rn(t.embedding,n)&&(e.reindexWarnings.push("search_semantic_reindex_requires_rebuild:embedding_identity_changed"),e.reindexWarnings.push(ZP))}async function pL(e){let t=await An(e.pmRoot);e.semanticWarnings.push(...t.warnings);let n=Qw(e.settings,e.activeEmbeddingProvider,e.extensionEmbedding),r=new Set(e.metadataDocuments.map(d=>d.metadata.id)),i=sL(t.entries,r),o=Rn(t.embedding,n);e.forceFullSemantic&&!o&&e.semanticWarnings.push("search_semantic_reindex_full_rebuild_forced");let s=e.forceFullSemantic||o?e.metadataDocuments:e.metadataDocuments.filter(d=>t.entries[d.metadata.id]!==d.metadata.updated_at),a=new Set(s.map(d=>d.metadata.id)),c=a.size>0?await Td(e.pmRoot,e.documentCandidates,e.settings.schema,e.reindexWarnings,a):[];return{ledgerEntries:t.entries,ledgerEmbedding:t.embedding,orphanIds:i,resetRequired:o,staleDocuments:c,freshDocuments:e.metadataDocuments.length-c.length}}async function fL(e){let t=new Set(e.metadataDocuments.map(i=>i.metadata.id)),n=await Td(e.pmRoot,e.documentCandidates,e.settings.schema,e.reindexWarnings,t);e.semanticSummary.stale_items=n.length,e.semanticSummary.unchanged_items=0,de(e.progressEnabled,`embedding_dimension_changed reset_items=${n.length}`);let r=await ev(e.settings,e.requestedMode,e.activeEmbeddingProvider,e.extensionEmbedding,n,e.semanticWarnings,e.semanticSummary,e.progressEnabled);return{...r,staleDocuments:n,vectorDimension:Ls(r.vectors,"Reindex embeddings")}}async function hL(e){let t=await ev(e.settings,e.requestedMode,e.activeEmbeddingProvider,e.extensionEmbedding,e.staleDocuments,e.semanticWarnings,e.semanticSummary,e.progressEnabled),n=t.vectors,r=t.embeddingIdentity,i=Ls(n,"Reindex embeddings");if(!(!e.resetRequired&&(Rn(e.ledgerEmbedding,r)||Wu(e.ledgerEmbedding,i))))return{vectors:n,embeddingIdentity:r,staleDocuments:e.staleDocuments,vectorDimension:i,resetRequired:e.resetRequired};let s=await fL(e);return n=s.vectors,r=s.embeddingIdentity,i=s.vectorDimension,{vectors:n,embeddingIdentity:r,staleDocuments:s.staleDocuments,vectorDimension:i,resetRequired:!0}}async function _L(e){if(e.extensionVectorAdapter)try{let t=e.extensionVectorAdapter.adapterName;if(de(e.progressEnabled,`vector_upsert_start adapter=${t} points=${e.points.length}`),typeof e.extensionVectorAdapter.upsert!="function")throw new _(`Extension vector adapter "${t}" does not support upserting vectors.`,g.USAGE);await Promise.resolve(e.extensionVectorAdapter.upsert({points:e.points,settings:e.settings})),e.semanticSummary.vector_upserted=e.points.length,de(e.progressEnabled,`vector_upsert_complete adapter=${t}`);return}catch(t){if(t instanceof _)throw t;if(!e.activeVectorStore)throw new _(`Extension vector adapter "${e.extensionVectorAdapter.adapterName}" failed to upsert vectors: ${t instanceof Error?t.message:String(t)}`,g.GENERIC_FAILURE);e.semanticWarnings.push(`Extension vector adapter "${e.extensionVectorAdapter.adapterName}" failed; falling back to built-in vector store (${t instanceof Error?t.message:String(t)})`),de(e.progressEnabled,"vector_upsert_fallback built_in_store")}if(e.activeVectorStore){de(e.progressEnabled,`vector_upsert_start adapter=${e.activeVectorStore.name} points=${e.points.length}`),await ju(e.activeVectorStore,e.points),e.semanticSummary.vector_upserted=e.points.length,de(e.progressEnabled,`vector_upsert_complete adapter=${e.activeVectorStore.name}`);return}throw new _(`No vector upsert executor available for reindex mode '${e.requestedMode}'`,g.USAGE)}function gL(e,t){return e.map((n,r)=>({id:n.metadata.id,vector:$d(t[r],`reindex embeddings output at index ${r}`),payload:{id:n.metadata.id,type:n.metadata.type,status:n.metadata.status,priority:n.metadata.priority,updated_at:n.metadata.updated_at}}))}async function yL(e){de(e.progressEnabled,`embedding_start items=${e.plan.staleDocuments.length} unchanged_items=${e.plan.freshDocuments}`);let t=await hL({pmRoot:e.pmRoot,settings:e.settings,requestedMode:e.requestedMode,activeEmbeddingProvider:e.activeEmbeddingProvider,extensionEmbedding:e.extensionEmbedding,documentCandidates:e.documentCandidates,metadataDocuments:e.metadataDocuments,staleDocuments:e.plan.staleDocuments,ledgerEmbedding:e.plan.ledgerEmbedding,resetRequired:e.plan.resetRequired,semanticWarnings:e.semanticWarnings,reindexWarnings:e.reindexWarnings,semanticSummary:e.semanticSummary,progressEnabled:e.progressEnabled});t.resetRequired?(de(e.progressEnabled,"vector_reset_start"),await aL(e.activeVectorStore,e.extensionVectorAdapter,e.plan.ledgerEntries,e.settings,e.semanticWarnings,e.plan.ledgerEmbedding?t.vectorDimension:void 0),de(e.progressEnabled,"vector_reset_complete")):await tv(e.activeVectorStore,e.extensionVectorAdapter,e.plan.orphanIds,e.settings,e.semanticWarnings);let n=gL(t.staleDocuments,t.vectors);return e.semanticSummary.embedded_items=t.vectors.length,await _L({requestedMode:e.requestedMode,activeVectorStore:e.activeVectorStore,extensionVectorAdapter:e.extensionVectorAdapter,settings:e.settings,points:n,semanticWarnings:e.semanticWarnings,semanticSummary:e.semanticSummary,progressEnabled:e.progressEnabled}),{staleDocuments:t.staleDocuments,embeddingMetadata:zu(t.embeddingIdentity,t.vectorDimension)}}async function wL(e){let t=await pL(e);e.semanticSummary.stale_items=t.staleDocuments.length,e.semanticSummary.unchanged_items=t.freshDocuments;let n=Object.fromEntries(e.metadataDocuments.map(o=>[o.metadata.id,o.metadata.updated_at]));if(de(e.progressEnabled,`semantic_stale_items stale=${t.staleDocuments.length} total=${e.metadataDocuments.length} unchanged=${t.freshDocuments} full=${e.forceFullSemantic||t.resetRequired}`),t.staleDocuments.length===0)return de(e.progressEnabled,`embedding_skipped unchanged_items=${t.freshDocuments}`),e.semanticWarnings.push(`search_semantic_reindex_skipped_unchanged:count=${t.freshDocuments}`),await tv(e.activeVectorStore,e.extensionVectorAdapter,t.orphanIds,e.settings,e.semanticWarnings),{documentsForKeywordArtifacts:e.documentsForKeywordArtifacts,vectorizationLedgerEntries:n,vectorizationEmbeddingMetadata:t.ledgerEmbedding};let r=await yL({...e,plan:t});t.freshDocuments>0&&e.semanticWarnings.push(`search_semantic_reindex_skipped_unchanged:count=${t.freshDocuments}`);let i=new Map(r.staleDocuments.map(o=>[o.metadata.id,o]));return{documentsForKeywordArtifacts:e.metadataDocuments.map(o=>i.get(o.metadata.id)??o),vectorizationLedgerEntries:n,vectorizationEmbeddingMetadata:r.embeddingMetadata}}async function vL(e){let t=ii.join(e.pmRoot,Id),n=ii.join(e.pmRoot,Cd),r=Ps(e.settings),i=e.documentsForKeywordArtifacts.map(s=>JSON.stringify(nL(s,e.mode,r))).join(`
|
|
75
|
+
`);de(e.progressEnabled,"writing keyword artifacts"),await ee(t,`${JSON.stringify(e.manifest,null,2)}
|
|
76
|
+
`),await ee(n,`${i}
|
|
77
|
+
`);let o=[];if(e.mode!=="keyword")try{de(e.progressEnabled,"writing vectorization status ledger"),await qu(e.pmRoot,e.vectorizationLedgerEntries,e.vectorizationEmbeddingMetadata)}catch(s){o.push(`search_vectorization_status_ledger_write_failed:${s instanceof Error?s.message:String(s)}`)}return o}async function Y2(e,t){let n=eL(e.mode),r=QP(e),i=e.full===!0;de(r,`start mode=${n}`);let o=M(process.cwd(),t.path);await ie(o);let s=Mi(await T(o)).settings,a=null;try{a=await se(o,xu,s.locks.ttl_seconds,q(void 0,"pm-reindex"),!1,s.governance.force_required_for_stale_lock,s.locks.wait_ms)}catch(c){throw c instanceof _&&c.exitCode===g.CONFLICT?new _("Another pm reindex run is already active for this project. Wait for it to finish before starting a new keyword, semantic, or hybrid reindex.",g.CONFLICT,{code:"reindex_already_running",type:"urn:pm-cli:error:reindex_already_running",why:"Semantic reindex can be expensive and duplicate runs compete for the same local embedding model and vector store.",nextSteps:["Check active pm reindex processes before starting another reindex.","Rerun with --progress when you need non-interactive visibility."]}):c}try{let c=rL(s),d=iL(s),l=lL({requestedMode:n,pmRoot:o,settings:s,extensionEmbedding:c,extensionVectorAdapter:d}),u=n;de(r,"loading item corpus");let m=await uL({pmRoot:o,settings:s}),p=m.warnings,{documentCandidates:f,metadataDocuments:h}=m;de(r,`loaded_items=${h.length}`);let y=C(),w=dL(u,y,h),v=ii.join(o,Id),k=ii.join(o,Cd),x=u==="keyword"?await Td(o,f,s.schema,p):h,E=[],A={},S=null,b=cL(u);if(u==="keyword"&&await mL({pmRoot:o,settings:s,forceFullSemantic:i,extensionEmbedding:c,reindexWarnings:p}),u!=="keyword"){let $=await wL({pmRoot:o,settings:s,requestedMode:n,activeEmbeddingProvider:l.activeEmbeddingProvider,activeVectorStore:l.activeVectorStore,extensionEmbedding:c,extensionVectorAdapter:d,documentCandidates:f,metadataDocuments:h,documentsForKeywordArtifacts:x,forceFullSemantic:i,reindexWarnings:p,semanticWarnings:E,semanticSummary:b,progressEnabled:r});x=$.documentsForKeywordArtifacts,A=$.vectorizationLedgerEntries,S=$.vectorizationEmbeddingMetadata}let D=await vL({pmRoot:o,mode:u,manifest:w,documentsForKeywordArtifacts:x,settings:s,vectorizationLedgerEntries:A,vectorizationEmbeddingMetadata:S,progressEnabled:r}),j=[...await Y({path:v,scope:"project",op:"reindex:manifest"}),...await Y({path:k,scope:"project",op:"reindex:embeddings"}),...await Ii({mode:u,total_items:h.length})];return de(r,"done"),{ok:!0,mode:u,total_items:h.length,semantic:b,artifacts:{manifest:Id,embeddings:Cd},warnings:[...p,...E,...D,...j],generated_at:y}}finally{await a?.()}}export{L as a,Re as b,ot as c,On as d,Ws as e,um as f,Xt as g,qs as h,mv as i,Js as j,Vs as k,hm as l,Pn as m,yr as n,Ys as o,Tv as p,km as q,wr as r,xm as s,Vi as t,Xs as u,Sm as v,Em as w,Rm as x,DL as y,ia as z,jm as A,KL as B,Bv as C,YL as D,Vv as E,QL as F,Wm as G,Xv as H,gN as I,tx as J,ZM as K,QM as L,eF as M,Tr as N,tF as O,nF as P,rF as Q,iF as R,oF as S,sF as T,aF as U,cF as V,dF as W,lF as X,uF as Y,Sh as Z,Qa as _,CD as $,Pp as aa,tk as ba,Km as ca,TN as da,xr as ea,ON as fa,ck as ga,dk as ha,PN as ia,lk as ja,L0 as ka,xy as la,eT as ma,Ay as na,FN as oa,np as pa,Cy as qa,oB as ra,sB as sa,Sr as ta,eo as ua,ip as va,op as wa,sp as xa,ap as ya,up as za,la as Aa,pp as Ba,_p as Ca,gp as Da,Ck as Ea,wp as Fa,Ut as Ga,y1 as Ha,w1 as Ia,v1 as Ja,k1 as Ka,C1 as La,L_ as Ma,No as Na,Z1 as Oa,Rt as Pa,W_ as Qa,Q1 as Ra,ez as Sa,OI as Ta,DI as Ua,V_ as Va,Tk as Wa,ma as Xa,Kr as Ya,RW as Za,AW as _a,no as $a,ro as ab,jg as bb,Fq as cb,Hg as db,zg as eb,Wg as fb,Bg as gb,Vg as hb,wT as ib,vT as jb,mB as kb,pB as lb,fB as mb,hB as nb,Oy as ob,bT as pb,Ly as qb,Ko as rb,Dy as sb,My as tb,Fy as ub,ST as vb,RT as wb,IT as xb,_B as yb,CT as zb,rd as Ab,id as Bb,AB as Cb,IB as Db,CB as Eb,oO as Fb,GJ as Gb,Ew as Hb,ei as Ib,Iw as Jb,Cw as Kb,$w as Lb,vd as Mb,pP as Nb,IV as Ob,XV as Pb,o2 as Qb,Gw as Rb,Bw as Sb,Jw as Tb,C2 as Ub,z2 as Vb,W2 as Wb,q2 as Xb,Y2 as Yb};
|
|
78
|
+
//# sourceMappingURL=chunk-ZHWPCVQL.js.map
|