@unbrained/pm-cli 2026.10.3 → 2026.10.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +2 -2
- package/CHANGELOG.md +28 -2
- package/dist/cli/after-command-context-usage.js +1 -1
- package/dist/cli/argv-utils.js +1 -1
- package/dist/cli/bootstrap-args.js +1 -1
- package/dist/cli/bundle-integrity.js +2 -2
- package/dist/cli/command-namespaces.js +1 -1
- package/dist/cli/commander-usage.d.ts +1 -1
- package/dist/cli/commander-usage.js +7 -4
- package/dist/cli/commands/annotations/comments.js +1 -1
- package/dist/cli/commands/annotations/docs.js +1 -1
- package/dist/cli/commands/annotations/files.js +1 -1
- package/dist/cli/commands/annotations/learnings.js +1 -1
- package/dist/cli/commands/annotations/notes.js +1 -1
- package/dist/cli/commands/extension/describe.js +1 -1
- package/dist/cli/commands/extension/extension.js +1 -1
- package/dist/cli/commands/extension/scaffold.js +1 -1
- package/dist/cli/commands/extension/shared.js +1 -1
- package/dist/cli/commands/governance/gc.js +1 -1
- package/dist/cli/commands/governance/health.js +1 -1
- package/dist/cli/commands/governance/telemetry.js +1 -1
- package/dist/cli/commands/governance/validate.js +1 -1
- package/dist/cli/commands/history/activity.js +1 -1
- package/dist/cli/commands/history/history-compact.js +1 -1
- package/dist/cli/commands/history/history-redact.js +1 -1
- package/dist/cli/commands/history/history-repair.js +1 -1
- package/dist/cli/commands/history/history.js +1 -1
- package/dist/cli/commands/history/restore.js +1 -1
- package/dist/cli/commands/lifecycle/append.js +1 -1
- package/dist/cli/commands/lifecycle/claim.js +1 -1
- package/dist/cli/commands/lifecycle/close-many.js +1 -1
- package/dist/cli/commands/lifecycle/close.js +1 -1
- package/dist/cli/commands/lifecycle/copy.js +1 -1
- package/dist/cli/commands/lifecycle/create.js +1 -1
- package/dist/cli/commands/lifecycle/delete.js +1 -1
- package/dist/cli/commands/lifecycle/focus.js +1 -1
- package/dist/cli/commands/lifecycle/plan.js +1 -1
- package/dist/cli/commands/lifecycle/update-many.js +1 -1
- package/dist/cli/commands/lifecycle/update.js +1 -1
- package/dist/cli/commands/query/aggregate.js +1 -1
- package/dist/cli/commands/query/context.js +1 -1
- package/dist/cli/commands/query/deps.js +1 -1
- package/dist/cli/commands/query/duplicates.js +1 -1
- package/dist/cli/commands/query/eval.js +1 -1
- package/dist/cli/commands/query/get.js +1 -1
- package/dist/cli/commands/query/graph.js +1 -1
- package/dist/cli/commands/query/list.js +1 -1
- package/dist/cli/commands/query/next.js +1 -1
- package/dist/cli/commands/query/search.js +1 -1
- package/dist/cli/commands/query/stats.js +1 -1
- package/dist/cli/commands/test/test-all.js +1 -1
- package/dist/cli/commands/test/test-runs.js +1 -1
- package/dist/cli/commands/test/test.js +1 -1
- package/dist/cli/commands/workspace/config.js +1 -1
- package/dist/cli/commands/workspace/contracts.js +1 -1
- package/dist/cli/commands/workspace/init.js +1 -1
- package/dist/cli/commands/workspace/merge.js +1 -1
- package/dist/cli/commands/workspace/profile.js +1 -1
- package/dist/cli/commands/workspace/schema.js +1 -1
- package/dist/cli/commands/workspace/upgrade.js +1 -1
- package/dist/cli/context-intent-invocation.js +1 -1
- package/dist/cli/description-stdin.js +1 -1
- package/dist/cli/error-guidance.js +3 -1
- package/dist/cli/extension-command-help.js +5 -3
- package/dist/cli/extension-command-options.js +1 -1
- package/dist/cli/extension-recovery.js +1 -1
- package/dist/cli/help-content.js +5 -2
- package/dist/cli/help-json-payload.js +6 -3
- package/dist/cli/invocation-profile.js +2 -2
- package/dist/cli/main.js +5 -5
- package/dist/cli/migration-gates.js +1 -1
- package/dist/cli/option-values.js +1 -1
- package/dist/cli/public.js +1 -1
- package/dist/cli/register-annotations.js +1 -1
- package/dist/cli/register-assurance.js +1 -1
- package/dist/cli/register-files-lookup.js +1 -1
- package/dist/cli/register-history-activity.js +1 -1
- package/dist/cli/register-history-author.js +1 -1
- package/dist/cli/register-history-maintenance.js +2 -2
- package/dist/cli/register-list-query.js +10 -10
- package/dist/cli/register-mutation-options.js +1 -1
- package/dist/cli/register-mutation.js +2 -2
- package/dist/cli/register-operations.js +1 -1
- package/dist/cli/register-setup.js +1 -1
- package/dist/cli/register-structured-mutation.js +1 -1
- package/dist/cli/registration-helpers.js +1 -1
- package/dist/cli/runtime/activation.js +1 -1
- package/dist/cli/runtime/invocation-options.js +1 -1
- package/dist/cli/runtime/projection-retry.js +1 -1
- package/dist/cli/runtime/selection.js +1 -1
- package/dist/cli/runtime/telemetry-outcome.js +1 -1
- package/dist/cli/runtime-compatibility-boundary.d.ts +1 -1
- package/dist/cli/runtime-compatibility-boundary.js +4 -4
- package/dist/cli/schema/registration.js +2 -2
- package/dist/cli/schema-registration-helpers.js +1 -1
- package/dist/cli/search-refresh.js +1 -1
- package/dist/cli/stats-analytics-json.js +1 -1
- package/dist/cli/telemetry-flush.js +1 -1
- package/dist/cli-bundle/bundle-manifest.json +162 -162
- package/dist/cli-bundle/chunks/chunk-3CYOBJUK.js +3 -0
- package/dist/cli-bundle/chunks/chunk-5MNOWZPN.js +3 -0
- package/dist/cli-bundle/chunks/chunk-AJ7H6XUF.js +20 -0
- package/dist/cli-bundle/chunks/chunk-D332RXZ7.js +80 -0
- package/dist/cli-bundle/chunks/chunk-HRJ6G6ZG.js +31 -0
- package/dist/cli-bundle/chunks/chunk-KRVI56QE.js +6 -0
- package/dist/cli-bundle/chunks/chunk-N4YGSG6F.js +238 -0
- package/dist/cli-bundle/chunks/chunk-OOLYASYJ.js +2 -0
- package/dist/cli-bundle/chunks/chunk-R7CG2DB7.js +2 -0
- package/dist/cli-bundle/chunks/chunk-TGMONGWX.js +2 -0
- package/dist/cli-bundle/chunks/chunk-UZ7BIUCI.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-44UGMMQ6.js → chunk-VZ63DEVJ.js} +3 -3
- package/dist/cli-bundle/chunks/chunk-WFZ4UEOB.js +2 -0
- package/dist/cli-bundle/chunks/chunk-YVBRASXO.js +8 -0
- package/dist/cli-bundle/chunks/{chunk-5XKF5SQV.js → chunk-Z66DWDAU.js} +91 -91
- package/dist/cli-bundle/chunks/{register-list-query-DYCGUQEW.js → register-list-query-75QXHIFH.js} +11 -11
- package/dist/cli-bundle/chunks/register-mutation-YS54SCHG.js +20 -0
- package/dist/cli-bundle/chunks/register-operations-6KHZQSYJ.js +2 -0
- package/dist/cli-bundle/chunks/register-setup-RTATEN2M.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-3BIYG72P.js → chunk-2CVX3KR3.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-5C3IDDW7.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-DBD4W4QP.js → chunk-ABV67XCC.js} +3 -3
- package/dist/cli-bundle/focused-chunks/chunk-B5RSLVE6.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-C224METM.js +20 -0
- package/dist/cli-bundle/focused-chunks/chunk-CLDPTMQY.js +6 -0
- package/dist/cli-bundle/focused-chunks/chunk-DDRN42PB.js +8 -0
- package/dist/cli-bundle/focused-chunks/{chunk-EJN7DY3B.js → chunk-DOVTUKJQ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-ECBOPEJE.js +75 -0
- package/dist/cli-bundle/focused-chunks/chunk-GITOYRUW.js +165 -0
- package/dist/cli-bundle/focused-chunks/chunk-GUIF3WVC.js +30 -0
- package/dist/cli-bundle/focused-chunks/chunk-LE4JUCRR.js +3 -0
- package/dist/cli-bundle/focused-chunks/{chunk-HFAW3FJQ.js → chunk-PSXFFQFT.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-RHIH6XIW.js +12 -0
- package/dist/cli-bundle/focused-chunks/chunk-UDYRVBOZ.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-XV5RV4ZT.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-XRSCIYHR.js → chunk-YMU42COG.js} +2 -2
- package/dist/cli-bundle/main.js +28 -28
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +2 -2
- package/dist/cli-bundle/sdk-core.js +32 -32
- package/dist/cli-bundle/sdk-governance.js +1 -1
- package/dist/cli-bundle/sdk-graph.js +1 -1
- package/dist/cli-bundle/sdk-merge.js +55 -55
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +10 -10
- package/dist/cli.js +1 -1
- package/dist/core/checkpoint/checkpoint-gc.js +1 -1
- package/dist/core/checkpoint/mutation-checkpoint.js +2 -2
- package/dist/core/config/nested-settings.js +1 -1
- package/dist/core/config/positional-value.js +1 -1
- package/dist/core/diagnostics/remediation.js +1 -1
- package/dist/core/extensions/activation-summary-markdown.js +2 -1
- package/dist/core/extensions/activation-summary.js +1 -1
- package/dist/core/extensions/activation-transaction.js +1 -1
- package/dist/core/extensions/capability-usage.js +1 -1
- package/dist/core/extensions/command-hook-context.js +1 -1
- package/dist/core/extensions/command-metadata-contract.js +1 -1
- package/dist/core/extensions/command-visibility-tier.js +1 -1
- package/dist/core/extensions/contribution-inventory.js +1 -1
- package/dist/core/extensions/exporter-output-contract.js +1 -1
- package/dist/core/extensions/extension-candidate.js +1 -1
- package/dist/core/extensions/extension-capability-aliases.js +1 -1
- package/dist/core/extensions/extension-hook-runtime.js +1 -1
- package/dist/core/extensions/extension-policy.js +1 -1
- package/dist/core/extensions/extension-registries.js +1 -1
- package/dist/core/extensions/extension-runtime-helpers.js +1 -1
- package/dist/core/extensions/extension-types.d.ts +8 -1
- package/dist/core/extensions/extension-types.js +1 -1
- package/dist/core/extensions/flag-definition-validation.js +1 -1
- package/dist/core/extensions/flag-value-types.js +1 -1
- package/dist/core/extensions/index.js +1 -1
- package/dist/core/extensions/item-field-types.js +1 -1
- package/dist/core/extensions/item-fields.js +1 -1
- package/dist/core/extensions/loader.js +1 -1
- package/dist/core/extensions/manifest-parser.js +1 -1
- package/dist/core/extensions/manifest-schema.js +1 -1
- package/dist/core/extensions/module-graph-snapshot.js +1 -1
- package/dist/core/extensions/preflight-ownership.js +1 -1
- package/dist/core/extensions/registration-contracts.js +1 -1
- package/dist/core/extensions/registration-validation.js +1 -1
- package/dist/core/extensions/registration-values.js +1 -1
- package/dist/core/extensions/reserved-host-flags.js +1 -1
- package/dist/core/extensions/runtime-registrations.js +1 -1
- package/dist/core/extensions/service-ownership.js +1 -1
- package/dist/core/extensions/version-compat.js +1 -1
- package/dist/core/fs/atomic-create.js +1 -1
- package/dist/core/fs/fs-utils.js +2 -2
- package/dist/core/fs/host-environment-errors.js +1 -1
- package/dist/core/fs/index.js +1 -1
- package/dist/core/fs/path-utils.js +1 -1
- package/dist/core/governance/content-fields.js +1 -1
- package/dist/core/governance/issue-codes.js +1 -1
- package/dist/core/governance/metadata-coverage.js +1 -1
- package/dist/core/history/digest.js +1 -1
- package/dist/core/history/drift-cache.js +3 -3
- package/dist/core/history/drift-scan.d.ts +4 -0
- package/dist/core/history/drift-scan.js +1 -1
- package/dist/core/history/event-classification.js +1 -1
- package/dist/core/history/event-index.js +8 -7
- package/dist/core/history/history-compact-bulk.js +1 -1
- package/dist/core/history/history-diff.js +1 -1
- package/dist/core/history/history-rewrite.js +1 -1
- package/dist/core/history/history-storage-stats.js +1 -1
- package/dist/core/history/history-stream-policy.js +1 -1
- package/dist/core/history/history.js +2 -2
- package/dist/core/history/identity.js +1 -1
- package/dist/core/history/index.js +1 -1
- package/dist/core/history/operation-contract.js +1 -1
- package/dist/core/history/projection.js +1 -1
- package/dist/core/history/read.js +1 -1
- package/dist/core/history/replay.js +2 -1
- package/dist/core/history/tombstone.js +1 -1
- package/dist/core/history/version-address.js +1 -1
- package/dist/core/history/workspace-history.js +2 -2
- package/dist/core/io/body-file.js +1 -1
- package/dist/core/io/bulk-ids-input.js +2 -1
- package/dist/core/item/actionability.js +1 -1
- package/dist/core/item/dependency-reference.js +1 -1
- package/dist/core/item/id.js +1 -1
- package/dist/core/item/index.js +1 -1
- package/dist/core/item/item-format-version.js +1 -1
- package/dist/core/item/item-format.js +6 -4
- package/dist/core/item/item-record.js +1 -1
- package/dist/core/item/item-type-definition.js +1 -1
- package/dist/core/item/parent-reference-policy.js +1 -1
- package/dist/core/item/parse.js +8 -2
- package/dist/core/item/plan-lifecycle.js +1 -1
- package/dist/core/item/priority.js +1 -1
- package/dist/core/item/sprint-release-format.js +1 -1
- package/dist/core/item/status-filter.js +1 -1
- package/dist/core/item/status.js +1 -1
- package/dist/core/item/toon-decode.js +1 -1
- package/dist/core/item/type-registry.js +1 -1
- package/dist/core/item/type-synonyms.js +1 -1
- package/dist/core/lock/index.js +1 -1
- package/dist/core/lock/lock-gc.js +1 -1
- package/dist/core/lock/lock.js +3 -3
- package/dist/core/output/mutation-projection.js +1 -1
- package/dist/core/output/output-control.js +1 -1
- package/dist/core/output/output.js +22 -10
- package/dist/core/output/query-summary.js +1 -1
- package/dist/core/output/tabular.js +3 -1
- package/dist/core/packages/manifest.js +1 -1
- package/dist/core/packages/root.js +1 -1
- package/dist/core/policy/workflow-policy-schema.js +1 -1
- package/dist/core/policy/workflow-policy-store.js +1 -1
- package/dist/core/policy/workflow-policy.js +1 -1
- package/dist/core/profile/profile-describe.js +1 -1
- package/dist/core/profile/profile-lint.js +1 -1
- package/dist/core/profile/profile-plan.js +1 -1
- package/dist/core/profile/profile-presets.js +25 -1
- package/dist/core/reproducibility/context.js +1 -1
- package/dist/core/schema/fields-file.js +2 -2
- package/dist/core/schema/item-types-file.js +2 -2
- package/dist/core/schema/runtime-field-filters.js +1 -1
- package/dist/core/schema/runtime-field-values.js +1 -1
- package/dist/core/schema/runtime-schema.js +2 -2
- package/dist/core/schema/status-defs-file.js +2 -2
- package/dist/core/schema/status-token.js +1 -1
- package/dist/core/schema/type-inference.js +1 -1
- package/dist/core/schema/type-presets.js +1 -1
- package/dist/core/schema/type-workflows.js +1 -1
- package/dist/core/search/background-refresh.js +2 -2
- package/dist/core/search/bm25.js +1 -1
- package/dist/core/search/cache.js +2 -2
- package/dist/core/search/corpus.js +1 -1
- package/dist/core/search/embedding-batches.js +1 -1
- package/dist/core/search/eval-thresholds.js +1 -1
- package/dist/core/search/eval.js +1 -1
- package/dist/core/search/http-client.js +1 -1
- package/dist/core/search/providers.js +1 -1
- package/dist/core/search/relevance.js +1 -1
- package/dist/core/search/semantic-defaults.js +1 -1
- package/dist/core/search/staleness.js +1 -1
- package/dist/core/search/vector-stores.js +2 -2
- package/dist/core/search/vectorization-metadata.js +1 -1
- package/dist/core/sentry/helpers.js +1 -1
- package/dist/core/sentry/instrument.js +1 -1
- package/dist/core/session/session-state.js +1 -1
- package/dist/core/shared/agent-session-context.js +1 -1
- package/dist/core/shared/author.js +5 -1
- package/dist/core/shared/command-line.js +1 -1
- package/dist/core/shared/command-types.js +1 -1
- package/dist/core/shared/conflict-markers.js +1 -1
- package/dist/core/shared/constants.js +1 -1
- package/dist/core/shared/errors.js +1 -1
- package/dist/core/shared/html-entity-decode.js +1 -1
- package/dist/core/shared/index.js +1 -1
- package/dist/core/shared/item-metadata-contract.js +1 -1
- package/dist/core/shared/lazy-module.js +1 -1
- package/dist/core/shared/levenshtein.js +1 -1
- package/dist/core/shared/memo.js +1 -1
- package/dist/core/shared/numeric-parsers.js +1 -1
- package/dist/core/shared/option-alias-visibility.js +1 -1
- package/dist/core/shared/primitives.js +1 -1
- package/dist/core/shared/secret-rules.js +1 -1
- package/dist/core/shared/serial-queue.js +1 -1
- package/dist/core/shared/serialization.js +1 -1
- package/dist/core/shared/split-comma-list.js +1 -1
- package/dist/core/shared/text-normalization.js +1 -1
- package/dist/core/shared/time.js +2 -1
- package/dist/core/store/index.js +1 -1
- package/dist/core/store/item-format-migration.js +1 -1
- package/dist/core/store/item-metadata-cache.js +1 -1
- package/dist/core/store/item-metadata-query-index.js +7 -7
- package/dist/core/store/item-metadata-read-work.js +1 -1
- package/dist/core/store/item-store.js +1 -1
- package/dist/core/store/paths.js +1 -1
- package/dist/core/store/settings-concurrency.js +1 -1
- package/dist/core/store/settings-read-cache.js +1 -1
- package/dist/core/store/settings-validator.js +1 -1
- package/dist/core/store/settings.d.ts +11 -2
- package/dist/core/store/settings.js +3 -3
- package/dist/core/store/tracker-preflight.js +1 -1
- package/dist/core/telemetry/consent.js +2 -2
- package/dist/core/telemetry/observability.js +1 -1
- package/dist/core/telemetry/policy.js +1 -1
- package/dist/core/telemetry/read-sampling.js +2 -2
- package/dist/core/telemetry/runtime.js +9 -5
- package/dist/core/test/background-runs.js +3 -3
- package/dist/core/test/item-test-run-tracking.js +1 -1
- package/dist/core/test/run-selectors.js +1 -1
- package/dist/core/validate/estimate-defaults.js +1 -1
- package/dist/core/validate/fix-planning.js +1 -1
- package/dist/core/validate/linked-artifact-reference.js +1 -1
- package/dist/core/validate/missing-by-type.js +1 -1
- package/dist/core/validate/missing-link-owners.js +1 -1
- package/dist/core/validate/stale-file-classification.js +1 -1
- package/dist/mcp/http-server.js +6 -4
- package/dist/mcp/legacy-adapter.js +1 -1
- package/dist/mcp/runtime-capabilities.js +1 -1
- package/dist/mcp/server.js +4 -4
- package/dist/mcp/tool-definitions.js +1 -1
- package/dist/sdk/actionability.js +1 -1
- package/dist/sdk/agent/closed-domain-contracts.js +1 -1
- package/dist/sdk/agent/command-recovery.js +1 -1
- package/dist/sdk/agent/command-suggestions.js +1 -1
- package/dist/sdk/agent/create-option-policy.js +1 -1
- package/dist/sdk/agent/identity-config.js +1 -1
- package/dist/sdk/agent/item-addressing.js +1 -1
- package/dist/sdk/agent/refusal-closure-census.js +2 -1
- package/dist/sdk/agent/refusal-closure.js +1 -1
- package/dist/sdk/agent/refusal-corpus-contracts.js +1 -1
- package/dist/sdk/agent/refusal-reachability.js +3 -1
- package/dist/sdk/agent/subcommand-recovery.js +1 -1
- package/dist/sdk/agent/task-transcript-contracts.js +1 -1
- package/dist/sdk/agent/tracker-preflight-contracts.js +1 -1
- package/dist/sdk/agent-capability-contracts.js +3 -1
- package/dist/sdk/agent-session-context.js +1 -1
- package/dist/sdk/annotations.js +1 -1
- package/dist/sdk/author-attribution.js +1 -1
- package/dist/sdk/authoring.js +1 -1
- package/dist/sdk/cli-bootstrap.js +1 -1
- package/dist/sdk/cli-contracts/agent-output-contracts.js +5 -3
- package/dist/sdk/cli-contracts/bootstrap-command-scanner.js +1 -1
- package/dist/sdk/cli-contracts/command-aliases.js +1 -1
- package/dist/sdk/cli-contracts/command-exit-contracts.js +1 -1
- package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1
- package/dist/sdk/cli-contracts/commander-types.js +1 -1
- package/dist/sdk/cli-contracts/completeness.js +1 -1
- package/dist/sdk/cli-contracts/enum-contracts.js +1 -1
- package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
- package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +2 -1
- package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
- package/dist/sdk/cli-contracts/registration-helpers.js +7 -7
- package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
- package/dist/sdk/cli-contracts/schemas/assurance-definition.js +1 -1
- package/dist/sdk/cli-contracts/string-lists.js +1 -1
- package/dist/sdk/cli-contracts/tool-option-contracts.js +1 -1
- package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
- package/dist/sdk/cli-contracts/tool-schema.js +1 -1
- package/dist/sdk/cli-contracts/typed-action-inputs.js +1 -1
- package/dist/sdk/cli-contracts.js +1 -1
- package/dist/sdk/cli-program.js +1 -1
- package/dist/sdk/command-line.js +1 -1
- package/dist/sdk/comments.js +1 -1
- package/dist/sdk/compile-cache.js +1 -1
- package/dist/sdk/completion/bash.js +2 -1
- package/dist/sdk/completion/fish.js +13 -7
- package/dist/sdk/completion/shared.js +1 -1
- package/dist/sdk/completion/zsh.js +14 -8
- package/dist/sdk/completion.js +1 -1
- package/dist/sdk/compose.js +1 -1
- package/dist/sdk/config.js +1 -1
- package/dist/sdk/context/recency.js +1 -1
- package/dist/sdk/context/semantic-session-attribution.js +1 -1
- package/dist/sdk/context/usage-egress.js +1 -1
- package/dist/sdk/context/usage-ledger.js +6 -3
- package/dist/sdk/context-intent-contracts.js +1 -1
- package/dist/sdk/context-intent-runtime.js +1 -1
- package/dist/sdk/context-packing.js +1 -1
- package/dist/sdk/context-relevance.js +1 -1
- package/dist/sdk/context-signal-store.js +2 -2
- package/dist/sdk/context-usage.js +1 -1
- package/dist/sdk/contracts.js +1 -1
- package/dist/sdk/core-governance.js +1 -1
- package/dist/sdk/core.js +1 -1
- package/dist/sdk/corpus-shape.js +1 -1
- package/dist/sdk/define.js +1 -1
- package/dist/sdk/dependencies.js +1 -1
- package/dist/sdk/dependency-flag-validation.js +1 -1
- package/dist/sdk/dependency-provenance.js +1 -1
- package/dist/sdk/docs.js +1 -1
- package/dist/sdk/duplicates.js +1 -1
- package/dist/sdk/environment/agent-environment.js +1 -1
- package/dist/sdk/environment/host-environment-errors.js +1 -1
- package/dist/sdk/environment/project-runtime-compatibility.js +2 -1
- package/dist/sdk/environment/source-context.js +1 -1
- package/dist/sdk/environment/tracker-preflight.js +1 -1
- package/dist/sdk/error-code-catalog.js +1 -1
- package/dist/sdk/error-runtime.js +1 -1
- package/dist/sdk/errors.js +1 -1
- package/dist/sdk/eval.js +1 -1
- package/dist/sdk/extension/author-manifest.js +1 -1
- package/dist/sdk/extension/bundled-catalog.js +1 -1
- package/dist/sdk/extension/concurrency.js +1 -1
- package/dist/sdk/extension/copy-scope.js +1 -1
- package/dist/sdk/extension/custom-field-collisions.js +1 -1
- package/dist/sdk/extension/describe.js +4 -2
- package/dist/sdk/extension/doctor.js +1 -1
- package/dist/sdk/extension/install-plan.js +1 -1
- package/dist/sdk/extension/install-receipts.js +1 -1
- package/dist/sdk/extension/install-runtime.js +3 -3
- package/dist/sdk/extension/install-snapshot.js +1 -1
- package/dist/sdk/extension/install-sources.js +5 -5
- package/dist/sdk/extension/managed-state.js +2 -2
- package/dist/sdk/extension/migrations.js +2 -2
- package/dist/sdk/extension/output-ownership.js +1 -1
- package/dist/sdk/extension/runtime-summary.js +1 -1
- package/dist/sdk/extension/scaffold.js +11 -4
- package/dist/sdk/extension/shared.js +1 -1
- package/dist/sdk/extension/source-resolution.js +1 -1
- package/dist/sdk/extension/static-inventory.js +1 -1
- package/dist/sdk/extension/update-check.js +1 -1
- package/dist/sdk/extension-command-context.js +1 -1
- package/dist/sdk/extension-contracts.js +1 -1
- package/dist/sdk/extension.js +1 -1
- package/dist/sdk/files.js +1 -1
- package/dist/sdk/flag-invocation-contracts.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
- package/dist/sdk/generated-error-code-catalog.js +1 -1
- package/dist/sdk/governance/assurance-action-contracts.js +1 -1
- package/dist/sdk/governance/assurance-action.js +1 -1
- package/dist/sdk/governance/assurance-limits.js +1 -1
- package/dist/sdk/governance/assurance-mutation-error.js +1 -1
- package/dist/sdk/governance/assurance-presets.js +1 -1
- package/dist/sdk/governance/assurance-runtime.js +1 -1
- package/dist/sdk/governance/assurance.js +4 -4
- package/dist/sdk/governance/boundary-fixtures.js +1 -1
- package/dist/sdk/governance/closure-timestamps.js +1 -1
- package/dist/sdk/governance/coverage-assurance.js +1 -1
- package/dist/sdk/governance/defect-recurrence-coverage.js +1 -1
- package/dist/sdk/governance/defect-recurrence-graph.js +1 -1
- package/dist/sdk/governance/defect-recurrence-signals.js +1 -1
- package/dist/sdk/governance/defect-recurrence.js +1 -1
- package/dist/sdk/governance/extension-host-version.js +1 -1
- package/dist/sdk/governance/gc.js +1 -1
- package/dist/sdk/governance/health-merge-evidence.js +1 -1
- package/dist/sdk/governance/health.js +2 -1
- package/dist/sdk/governance/hierarchy-validation.js +1 -1
- package/dist/sdk/governance/linked-file-report.js +1 -1
- package/dist/sdk/governance/merge-receipt-history.js +1 -1
- package/dist/sdk/governance/provenance-health.js +4 -1
- package/dist/sdk/governance/reindex.js +5 -4
- package/dist/sdk/governance/stale-work.js +1 -1
- package/dist/sdk/governance/status-role-diagnostics.js +1 -1
- package/dist/sdk/governance/storage-integrity.js +1 -1
- package/dist/sdk/governance/tracked-runtime-cache.js +1 -1
- package/dist/sdk/governance/upgrade.js +2 -2
- package/dist/sdk/governance/validate-history-drift.js +1 -1
- package/dist/sdk/governance/validate-item-reader.js +1 -1
- package/dist/sdk/governance/validate-normalization.js +1 -1
- package/dist/sdk/governance/validate.js +1 -1
- package/dist/sdk/governance/workflow-completeness.js +1 -1
- package/dist/sdk/governance/workflow-policy.js +3 -3
- package/dist/sdk/governance/workspace-position.js +2 -1
- package/dist/sdk/governance.js +1 -1
- package/dist/sdk/graph/adapter.js +1 -1
- package/dist/sdk/graph/analytics.js +1 -1
- package/dist/sdk/graph/assembly.js +1 -1
- package/dist/sdk/graph/cache.js +1 -1
- package/dist/sdk/graph/centrality.js +1 -1
- package/dist/sdk/graph/conformance.js +1 -1
- package/dist/sdk/graph/deadline-scheduling.js +1 -1
- package/dist/sdk/graph/durable-cache.js +1 -1
- package/dist/sdk/graph/governance-contracts.js +1 -1
- package/dist/sdk/graph/governance.js +1 -1
- package/dist/sdk/graph/hierarchy-integrity.js +1 -1
- package/dist/sdk/graph/index.js +1 -1
- package/dist/sdk/graph/lifecycle-coverage.js +1 -1
- package/dist/sdk/graph/mutation-advisory.js +1 -1
- package/dist/sdk/graph/query-contracts.js +1 -1
- package/dist/sdk/graph/remediation.js +1 -1
- package/dist/sdk/graph/run.js +1 -1
- package/dist/sdk/graph/scheduling.js +1 -1
- package/dist/sdk/graph/traversal.js +1 -1
- package/dist/sdk/graph/workspace-relationship-kind-registry.js +1 -1
- package/dist/sdk/graph.js +1 -1
- package/dist/sdk/guide-topics.js +1 -1
- package/dist/sdk/guide.js +8 -1
- package/dist/sdk/history/attestation-command.js +1 -1
- package/dist/sdk/history/attestation-contract.js +1 -1
- package/dist/sdk/history/attestation-scan.js +1 -1
- package/dist/sdk/history/attestation.js +1 -1
- package/dist/sdk/history/maintenance.js +1 -1
- package/dist/sdk/history/salvage.js +3 -2
- package/dist/sdk/history/subject.js +1 -1
- package/dist/sdk/history-analytics.js +1 -1
- package/dist/sdk/history-compact.js +1 -1
- package/dist/sdk/history-mcp.js +1 -1
- package/dist/sdk/history-provenance.js +1 -1
- package/dist/sdk/history-read.js +1 -1
- package/dist/sdk/history-redact.js +1 -1
- package/dist/sdk/history-repair.js +1 -1
- package/dist/sdk/improvement-ledger-validation.js +1 -1
- package/dist/sdk/improvement-ledger.js +2 -2
- package/dist/sdk/index.js +1 -1
- package/dist/sdk/init-agent-guidance.js +16 -2
- package/dist/sdk/init.js +16 -2
- package/dist/sdk/invocation-author.js +1 -1
- package/dist/sdk/item-children.js +1 -1
- package/dist/sdk/item-metadata-index.js +1 -1
- package/dist/sdk/item-schedule.js +1 -1
- package/dist/sdk/item-transaction.js +1 -1
- package/dist/sdk/learnings.js +1 -1
- package/dist/sdk/lifecycle/append.js +4 -2
- package/dist/sdk/lifecycle/claim.js +1 -1
- package/dist/sdk/lifecycle/close-many.js +1 -1
- package/dist/sdk/lifecycle/close.js +1 -1
- package/dist/sdk/lifecycle/copy.js +1 -1
- package/dist/sdk/lifecycle/create.js +1 -1
- package/dist/sdk/lifecycle/delete.js +1 -1
- package/dist/sdk/lifecycle/event-validation-messages.js +1 -1
- package/dist/sdk/lifecycle/focus.js +1 -1
- package/dist/sdk/lifecycle/hierarchy-mutation-lock.js +1 -1
- package/dist/sdk/lifecycle/legacy-none-tokens.js +1 -1
- package/dist/sdk/lifecycle/lifecycle-transitions.js +1 -1
- package/dist/sdk/lifecycle/mcp-actions.js +1 -1
- package/dist/sdk/lifecycle/metadata-normalizers.js +1 -1
- package/dist/sdk/lifecycle/mutation-command-options.js +1 -1
- package/dist/sdk/lifecycle/plan-mutation-receipt.js +1 -1
- package/dist/sdk/lifecycle/plan.js +1 -1
- package/dist/sdk/lifecycle/recurrence-parsers.js +1 -1
- package/dist/sdk/lifecycle/reopen.js +1 -1
- package/dist/sdk/lifecycle/repeatable-metadata-parsers.js +2 -1
- package/dist/sdk/lifecycle/restore.js +1 -1
- package/dist/sdk/lifecycle/shared-unset-fields.js +1 -1
- package/dist/sdk/lifecycle/task-composition.js +1 -1
- package/dist/sdk/lifecycle/update-many.js +1 -1
- package/dist/sdk/lifecycle/update.js +2 -1
- package/dist/sdk/lifecycle-completion.js +1 -1
- package/dist/sdk/lifecycle-policy.js +1 -1
- package/dist/sdk/linked-artifacts.js +2 -1
- package/dist/sdk/mcp/apps.js +1 -1
- package/dist/sdk/mcp/authorization.js +1 -1
- package/dist/sdk/mcp/discovery.js +1 -1
- package/dist/sdk/mcp/interactions.js +1 -1
- package/dist/sdk/mcp/protocol.js +1 -1
- package/dist/sdk/mcp/skills.js +3 -1
- package/dist/sdk/mcp/subscriptions.js +1 -1
- package/dist/sdk/mcp/tasks.js +2 -2
- package/dist/sdk/mcp/transport.js +1 -1
- package/dist/sdk/merge/abandoned-receipts.js +1 -1
- package/dist/sdk/merge/driver.js +1 -1
- package/dist/sdk/merge/index.js +1 -1
- package/dist/sdk/merge/install.js +4 -2
- package/dist/sdk/merge/receipt-file-boundary.js +1 -1
- package/dist/sdk/merge/receipt-operation.js +1 -1
- package/dist/sdk/merge/receipt-schema.js +1 -1
- package/dist/sdk/merge/receipts.js +4 -4
- package/dist/sdk/merge/reconcile.js +1 -1
- package/dist/sdk/merge/three-way.js +3 -2
- package/dist/sdk/merge/worktree-config.js +1 -1
- package/dist/sdk/merge.js +1 -1
- package/dist/sdk/mutation-events.js +1 -1
- package/dist/sdk/mutation-guard.js +1 -1
- package/dist/sdk/notes.js +1 -1
- package/dist/sdk/output-contracts.js +1 -1
- package/dist/sdk/output-projection.js +1 -1
- package/dist/sdk/output-token-accounting.js +1 -1
- package/dist/sdk/output.js +2 -1
- package/dist/sdk/ownership-source.js +1 -1
- package/dist/sdk/package-import-adapters.js +1 -1
- package/dist/sdk/package-migrations.js +1 -1
- package/dist/sdk/package-runtime-options.js +1 -1
- package/dist/sdk/pagination.js +1 -1
- package/dist/sdk/profile.js +5 -1
- package/dist/sdk/provenance.js +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/query/activity.js +1 -1
- package/dist/sdk/query/aggregate.js +1 -1
- package/dist/sdk/query/calendar.js +4 -1
- package/dist/sdk/query/complete-list.js +1 -1
- package/dist/sdk/query/context.js +2 -1
- package/dist/sdk/query/duplicate-candidates.js +1 -1
- package/dist/sdk/query/get.d.ts +14 -2
- package/dist/sdk/query/get.js +1 -1
- package/dist/sdk/query/history.js +1 -1
- package/dist/sdk/query/item-filter-options.js +1 -1
- package/dist/sdk/query/light-metadata.js +1 -1
- package/dist/sdk/query/list-filter-shared.js +1 -1
- package/dist/sdk/query/list.js +1 -1
- package/dist/sdk/query/multi-value-filters.js +1 -1
- package/dist/sdk/query/next-ready-budget.js +1 -1
- package/dist/sdk/query/next.js +2 -1
- package/dist/sdk/query/parsers.js +1 -1
- package/dist/sdk/query/projection-contracts.js +1 -1
- package/dist/sdk/query/search/corpus.js +2 -1
- package/dist/sdk/query/search/filters.js +1 -1
- package/dist/sdk/query/search/input.js +1 -1
- package/dist/sdk/query/search/lexical.js +1 -1
- package/dist/sdk/query/search/response.js +1 -1
- package/dist/sdk/query/search/semantic.js +3 -2
- package/dist/sdk/query/search/types.js +1 -1
- package/dist/sdk/query/search-contracts.js +1 -1
- package/dist/sdk/query/search-pagination.d.ts +1 -1
- package/dist/sdk/query/search-pagination.js +1 -1
- package/dist/sdk/query/search-rendering.js +1 -1
- package/dist/sdk/query/search.js +1 -1
- package/dist/sdk/query/workspace-contracts.js +1 -1
- package/dist/sdk/query.js +1 -1
- package/dist/sdk/read-output/continuation.js +1 -1
- package/dist/sdk/read-output/options.js +1 -1
- package/dist/sdk/read-output/provenance.js +1 -1
- package/dist/sdk/read-output-budget.js +1 -1
- package/dist/sdk/read-output-contracts.js +1 -1
- package/dist/sdk/read-output-rows.js +1 -1
- package/dist/sdk/read-output-session.js +1 -1
- package/dist/sdk/relationship-analytics.js +1 -1
- package/dist/sdk/relationship-context.js +1 -1
- package/dist/sdk/relationship-history.js +7 -4
- package/dist/sdk/relationship-kinds/contract.js +1 -1
- package/dist/sdk/relationship-migration.js +1 -1
- package/dist/sdk/relationships.js +1 -1
- package/dist/sdk/reproducibility/process.js +1 -1
- package/dist/sdk/runtime/actions.js +1 -1
- package/dist/sdk/runtime/context.js +1 -1
- package/dist/sdk/runtime/schema-preview.js +1 -1
- package/dist/sdk/runtime/schema.js +1 -1
- package/dist/sdk/runtime-action-aliases.js +1 -1
- package/dist/sdk/runtime-extended-actions.js +1 -1
- package/dist/sdk/runtime-input.js +1 -1
- package/dist/sdk/runtime-primitives.js +1 -1
- package/dist/sdk/runtime-public-contracts.js +1 -1
- package/dist/sdk/runtime-stats-options.js +1 -1
- package/dist/sdk/runtime.js +1 -1
- package/dist/sdk/scheduling-shortcuts.js +1 -1
- package/dist/sdk/schema-migration.js +4 -3
- package/dist/sdk/schema.js +7 -1
- package/dist/sdk/search-refresh-worker.js +1 -1
- package/dist/sdk/similarity-scoring.js +1 -1
- package/dist/sdk/similarity.js +1 -1
- package/dist/sdk/start-task-status.js +1 -1
- package/dist/sdk/stats.js +1 -1
- package/dist/sdk/structured-mutations.js +1 -1
- package/dist/sdk/telemetry-flush.js +1 -1
- package/dist/sdk/telemetry.js +4 -3
- package/dist/sdk/templates.js +26 -2
- package/dist/sdk/test/batch.js +2 -2
- package/dist/sdk/test/entry.js +1 -1
- package/dist/sdk/test/execution.js +6 -5
- package/dist/sdk/test/json-path.js +1 -1
- package/dist/sdk/test/linked-command-detection.js +1 -1
- package/dist/sdk/test/measurements.js +1 -1
- package/dist/sdk/test/parsers.js +1 -1
- package/dist/sdk/test/runs.js +1 -1
- package/dist/sdk/test/trust.js +2 -2
- package/dist/sdk/test/workspace-snapshot.js +1 -1
- package/dist/sdk/testing.js +7 -4
- package/dist/sdk/traceability/runtime-files-lookup.js +1 -1
- package/dist/sdk/traceability/source-traceability.js +2 -1
- package/dist/sdk/tracker-root-discovery.js +1 -1
- package/dist/sdk/workspace-contracts-cache.js +1 -1
- package/dist/sdk/workspace-contracts.js +1 -1
- package/dist/sdk/workspace-memory.js +2 -2
- package/dist/sdk/workspace-recipe.js +1 -1
- package/dist/sdk/workspace-snapshot.js +5 -4
- package/dist/sdk/workspace-transaction-gc.js +1 -1
- package/dist/sdk/workspace-transaction.js +2 -2
- package/dist/sdk/workspace.js +3 -2
- package/dist/types/index.js +1 -1
- package/dist/types.js +1 -1
- package/docs/AGENT_EVIDENCE_CONSISTENCY.md +88 -0
- package/docs/DIAGNOSTIC_OUTPUT_CONTRACTS.md +25 -0
- package/docs/GET_READ_EVIDENCE.md +68 -0
- package/docs/OUTPUT_PROJECTION_CONTRACTS.md +23 -0
- package/docs/README.md +2 -0
- package/docs/SDK_AUDITED_MUTATIONS.md +35 -0
- package/docs/TESTING.md +8 -0
- package/docs/ecosystem-review-2026-09-28.json +2864 -3157
- package/marketplace.json +2 -2
- package/package.json +1 -1
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/extensions/vcs/index.ts +4 -2
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-claude/package.json +2 -2
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/plugins/pm-codex/package.json +2 -2
- package/plugins/pm-codex/plugin.json +1 -1
- package/scripts/finalize-build.mjs +3 -2
- package/dist/cli-bundle/chunks/chunk-3AF2R3Y6.js +0 -6
- package/dist/cli-bundle/chunks/chunk-6ST3SCQ6.js +0 -2
- package/dist/cli-bundle/chunks/chunk-6Z4IV2MC.js +0 -8
- package/dist/cli-bundle/chunks/chunk-DEZPZOQ7.js +0 -2
- package/dist/cli-bundle/chunks/chunk-FW5LJXQY.js +0 -31
- package/dist/cli-bundle/chunks/chunk-H2DZW6I6.js +0 -3
- package/dist/cli-bundle/chunks/chunk-H7CXQBGQ.js +0 -2
- package/dist/cli-bundle/chunks/chunk-KP7NBQK3.js +0 -80
- package/dist/cli-bundle/chunks/chunk-MKXBCBAN.js +0 -20
- package/dist/cli-bundle/chunks/chunk-QPKQKSQU.js +0 -238
- package/dist/cli-bundle/chunks/chunk-SGFQQXFD.js +0 -2
- package/dist/cli-bundle/chunks/chunk-YCBGZF3T.js +0 -2
- package/dist/cli-bundle/chunks/chunk-YDWKGUQU.js +0 -3
- package/dist/cli-bundle/chunks/register-mutation-5PT3NW3A.js +0 -20
- package/dist/cli-bundle/chunks/register-operations-QDDQOAAV.js +0 -2
- package/dist/cli-bundle/chunks/register-setup-BBX67YMA.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-4FFPGNCJ.js +0 -6
- package/dist/cli-bundle/focused-chunks/chunk-73DA7ISY.js +0 -75
- package/dist/cli-bundle/focused-chunks/chunk-E754JDLY.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-FKK2HI3S.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-GMYUNHST.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-HIA2ZF64.js +0 -12
- package/dist/cli-bundle/focused-chunks/chunk-UTRSM3ZK.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-VVWYI2X7.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-WAJNX4RN.js +0 -20
- package/dist/cli-bundle/focused-chunks/chunk-WCY6HRZO.js +0 -30
- package/dist/cli-bundle/focused-chunks/chunk-YC32ZSLS.js +0 -165
- package/dist/cli-bundle/focused-chunks/chunk-ZIXFMIUL.js +0 -3
package/dist/sdk/dependencies.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="2f2a7df8-9c95-5ed1-bd43-33dde57dd7f0")}catch(e2){}})();import{assertInitializedTracker}from"./environment/tracker-preflight.js";import{getActiveExtensionRegistrations}from"../core/extensions/index.js";import{resolveItemTypeRegistry}from"../core/item/type-registry.js";import{isTerminalStatus}from"../core/item/status.js";import{resolveRuntimeStatusRegistry}from"../core/schema/runtime-schema.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{formatBuiltInOutput}from"../core/output/output.js";import{listAllItemMetadataLight,locateItem,readLocatedItem}from"../core/store/item-store.js";import{resolvePmRoot}from"../core/store/paths.js";import{readSettings}from"../core/store/settings.js";import{estimatePmOutputTokens}from"./cli-contracts/agent-output-contracts.js";import{assertProjectionModeChoice,attachOutputOmissionReceipt}from"./output-projection.js";import{assembleWorkspaceRelationshipGraph,collectDanglingDependencyReferences,resolveWorkspaceRelationshipKindRegistry}from"./graph/assembly.js";import{computeWorkspaceGraphFingerprint,workspaceGraphCache}from"./graph/cache.js";import{buildRelationshipContext}from"./relationship-context.js";import{createRelationshipKindRegistry}from"./relationships.js";const DEPS_FORMAT_VALUES=["tree","graph","context"];const DEPS_COLLAPSE_VALUES=["none","repeated"];const DEPS_DIRECTION_VALUES=["outgoing","incoming","both"];const DEFAULT_DEPS_TREE_MAX_DEPTH=32;const DEFAULT_DEPS_TREE_NODE_LIMIT=200;const DEFAULT_DEPS_TREE_EDGE_LIMIT=400;const DEFAULT_DEPS_TREE_TOKEN_BUDGET=16e3;function parseFormat(raw){const candidate=raw?.trim().toLowerCase()??"tree";if(DEPS_FORMAT_VALUES.includes(candidate)){return candidate}throw new PmCliError(`Invalid --format value "${raw}". Use "tree", "graph", or "context".`,EXIT_CODE.USAGE)}function parsePositiveInteger(raw,flag){if(raw===void 0)return void 0;const value=typeof raw==="number"?raw:Number(raw.trim());if(!Number.isInteger(value)||value<1)throw new PmCliError(`Invalid --${flag} value "${raw}". Use a positive integer.`,EXIT_CODE.USAGE);return value}function parseMaxDepth(raw){if(raw===void 0){return void 0}const normalized=typeof raw==="number"?raw:Number(raw.trim());if(!Number.isInteger(normalized)||normalized<0){throw new PmCliError(`Invalid --max-depth value "${raw}". Use a non-negative integer.`,EXIT_CODE.USAGE)}return normalized}function parseCollapse(raw){const candidate=raw?.trim().toLowerCase()??"none";if(DEPS_COLLAPSE_VALUES.includes(candidate)){return candidate}throw new PmCliError(`Invalid --collapse value "${raw}". Use "none" or "repeated".`,EXIT_CODE.USAGE)}function parseDirection(raw){const candidate=raw?.trim().toLowerCase()??"both";if(DEPS_DIRECTION_VALUES.includes(candidate)){return candidate}throw new PmCliError(`Invalid --direction value "${raw}". Use "outgoing", "incoming", or "both".`,EXIT_CODE.USAGE)}function parseKinds(raw,registry=createRelationshipKindRegistry()){if(raw===void 0)return void 0;const values=(Array.isArray(raw)?raw:[raw]).flatMap(value=>value.split(",")).map(value=>value.trim()).filter(value=>value.length>0);if(values.length===0)return void 0;const kinds=new Set;for(const value of values){const definition=registry.resolve(value);if(!definition){const known=registry.list().map(entry=>entry.kind).join(", ");throw new PmCliError(`Invalid --kind value "${value}". Registered kinds: ${known}.`,EXIT_CODE.USAGE)}kinds.add(definition.kind)}return[...kinds].sort()}function normalizeDependencies(dependencies){if(!dependencies||dependencies.length===0){return[]}const sorted=dependencies.map(({id,kind})=>({id:id.trim(),kind:kind.trim().toLowerCase()})).sort((left,right)=>{const byKind=left.kind.localeCompare(right.kind);if(byKind!==0)return byKind;return left.id.localeCompare(right.id)});const deduped=new Map;for(const dependency of sorted){const key=`${dependency.kind.toLowerCase()}::${dependency.id.toLowerCase()}`;if(!deduped.has(key)){deduped.set(key,{id:dependency.id,kind:dependency.kind})}}return[...deduped.values()]}function toIndexedItem(item){return{id:item.id,title:item.title,type:item.type,status:item.status,dependencies:normalizeDependencies(item.dependencies)}}function estimateTreeNodeTokens(node){return estimatePmOutputTokens(new TextEncoder().encode(JSON.stringify({...node,dependencies:void 0})).byteLength)}function appendTreeDependencies(baseNode,item,index,nextLineage,maxDepth,collapse,expanded,budget,depth){for(const dependency of item.dependencies){const edgeTokens=Math.max(1,Math.ceil(JSON.stringify({from:baseNode.id,to:dependency.id,kind:dependency.kind}).length/3));if(budget.nodes>=budget.nodeLimit){baseNode.truncated=true;budget.reasons.add("node_limit");break}if(budget.edges>=budget.edgeLimit){baseNode.truncated=true;budget.reasons.add("edge_limit");break}if(budget.estimatedTokens+edgeTokens>=budget.tokenBudget){baseNode.truncated=true;budget.reasons.add("token_budget");break}budget.edges+=1;budget.estimatedTokens+=edgeTokens;baseNode.dependencies.push(toTreeNode(dependency.id,index,nextLineage,maxDepth,collapse,expanded,budget,depth+1,dependency.kind))}}function shouldStopTreeNodeExpansion(node,item,lookupId,maxDepth,collapse,expanded,budget,depth){if(budget.estimatedTokens>=budget.tokenBudget&&item?.dependencies.length){node.truncated=true;budget.reasons.add("token_budget");return true}if(!item||node.cycle){return true}if(maxDepth!==void 0&&depth>=maxDepth){if(item.dependencies.length>0){node.truncated=true;budget.reasons.add("max_depth")}return true}if(collapse==="repeated"&&expanded.has(lookupId)){node.collapsed=true;return true}return false}function toTreeNode(id,index,lineage,maxDepth,collapse,expanded,budget,depth=0,via){const lookupId=id.trim().toLowerCase();const item=index.get(lookupId);const baseNode={id:item?.id??id,title:item?.title,type:item?.type,status:item?.status,via,missing:!item,cycle:lineage.has(lookupId),dependencies:[]};budget.nodes+=1;budget.estimatedTokens+=estimateTreeNodeTokens(baseNode);if(shouldStopTreeNodeExpansion(baseNode,item,lookupId,maxDepth,collapse,expanded,budget,depth)){return baseNode}if(collapse==="repeated"){expanded.add(lookupId)}const nextLineage=new Set(lineage);nextLineage.add(lookupId);appendTreeDependencies(baseNode,item,index,nextLineage,maxDepth,collapse,expanded,budget,depth);return baseNode}function mergeGraphNode(existing,candidate){if(!existing){return candidate}if(existing.missing&&!candidate.missing)return candidate;return{...existing,title:existing.title??candidate.title,type:existing.type??candidate.type,status:existing.status??candidate.status}}function toGraph(root){const nodesById=new Map;const edgesByKey=new Map;const pending=[root];while(pending.length>0){const node=pending.pop();nodesById.set(node.id,mergeGraphNode(nodesById.get(node.id),{id:node.id,title:node.title,type:node.type,status:node.status,missing:node.missing}));for(const child of node.dependencies){nodesById.set(child.id,mergeGraphNode(nodesById.get(child.id),{id:child.id,title:child.title,type:child.type,status:child.status,missing:child.missing}));const relationKind=child.via??"related";const edgeKey=`${node.id}::${child.id}::${relationKind}`;if(!edgesByKey.has(edgeKey)){edgesByKey.set(edgeKey,{from:node.id,to:child.id,kind:relationKind})}if(!child.cycle){pending.push(child)}}}const nodes=[...nodesById.values()].sort((left,right)=>left.id.localeCompare(right.id));const edges=[...edgesByKey.values()].sort((left,right)=>{const byFrom=left.from.localeCompare(right.from);if(byFrom!==0)return byFrom;const byTo=left.to.localeCompare(right.to);if(byTo!==0)return byTo;return left.kind.localeCompare(right.kind)});const missingIds=nodes.filter(node=>node.missing).map(node=>node.id);return{root_id:root.id,nodes,edges,missing_ids:missingIds}}function countDependencyGraph(rootId,index,maxDepth){const nodeIds=new Set;const edgeKeys=new Set;const missingIds=new Set;const expanded=new Set;const pending=[{id:rootId,depth:0}];let pendingIndex=0;while(pendingIndex<pending.length){const current=pending[pendingIndex++];const lookupId=current.id.trim().toLowerCase();nodeIds.add(lookupId);const item=index.get(lookupId);if(!item){missingIds.add(lookupId);continue}if(maxDepth!==void 0&¤t.depth>=maxDepth){continue}if(expanded.has(lookupId)){continue}expanded.add(lookupId);for(const dependency of item.dependencies){edgeKeys.add(`${lookupId}::${dependency.id.trim().toLowerCase()}::${dependency.kind}`);pending.push({id:dependency.id,depth:current.depth+1})}}return{node_count:nodeIds.size,edge_count:edgeKeys.size,edge_basis:"deduplicated_directed",missing_count:missingIds.size}}function parseDepsContextOptions(options,registry=createRelationshipKindRegistry()){const maxDepth=parseMaxDepth(options.maxDepth);const nodeLimit=parsePositiveInteger(options.nodeLimit,"node-limit");const edgeLimit=parsePositiveInteger(options.edgeLimit,"edge-limit");const tokenBudget=parsePositiveInteger(options.tokenBudget,"token-budget");const kinds=parseKinds(options.kind,registry);return{direction:parseDirection(options.direction),...kinds===void 0?{}:{kinds},...maxDepth===void 0?{}:{maxDepth},...nodeLimit===void 0?{}:{nodeLimit},...edgeLimit===void 0?{}:{edgeLimit},...tokenBudget===void 0?{}:{tokenBudget},...options.cursor?.trim()?{cursor:options.cursor.trim()}:{}}}function buildContextFromAssembly(assembly,rootId,options,rootEvidence){return buildRelationshipContext(assembly.graph,rootId,assembly.details.map(detail=>detail.id===rootId&&rootEvidence.length>0?{...detail,evidence:rootEvidence}:detail),options)}function buildDepsRelationshipContext(rootId,items,options,rootEvidence=[]){const assembly=assembleWorkspaceRelationshipGraph(items);return buildContextFromAssembly(assembly,rootId,parseDepsContextOptions(options,assembly.graph.registry()),rootEvidence)}function appendEvidencePointers(evidence,label,values,limit){for(const value of values.slice(0,limit)){const trimmed=value?.trim();if(trimmed)evidence.push(`${label}:${trimmed}`)}}async function collectRootEvidence(pmRoot,id,settings,typeToFolder){const located=await locateItem(pmRoot,id,settings.id_prefix,settings.item_format,typeToFolder);if(!located)return[];const{document}=await readLocatedItem(located,{schema:settings.schema});const metadata=document.metadata;const files=metadata.files??[];const tests=metadata.tests??[];const docs=metadata.docs??[];const counts=[["files",files.length],["tests",tests.length],["docs",docs.length],["comments",(metadata.comments??[]).length],["notes",(metadata.notes??[]).length],["learnings",(metadata.learnings??[]).length]];if(counts.every(([,count])=>count===0))return[];const evidence=[`linked:${counts.map(([key,count])=>`${key}=${count}`).join(",")}`];appendEvidencePointers(evidence,"file",files.map(file=>file.path),3);appendEvidencePointers(evidence,"test",tests.map(test=>test.command??test.path),2);appendEvidencePointers(evidence,"doc",docs.map(doc=>doc.path),2);return evidence}function createContextDepsResult(params){const{canonicalId,context,missingCount,missingReferences,referenceLimit,summaryOnly}=params;return{id:canonicalId,format:"context",node_count:context.nodes.length+1,edge_count:context.edges.length,edge_basis:"deduplicated_directed",missing_count:missingCount,missing_scope:"traversal",missing_reference_count:missingReferences.length,...summaryOnly?{}:{missing_references:missingReferences.slice(0,referenceLimit),context}}}function includesContextMissingReference(params){const{row,missingReachableSet,packetIds,filteredKinds,registry}=params;if(row.no_active_blocker_sentinel||!missingReachableSet.has(row.target_id.trim().toLowerCase())||!packetIds.has(row.holder_id)){return false}if(filteredKinds===void 0)return true;const definition=registry.resolve(row.kind);return definition!==void 0&&(filteredKinds.has(definition.kind)||definition.inverse!==void 0&&filteredKinds.has(definition.inverse))}function settleRenderedTokenCount(result,outputFormat,assign){let embeddedTokens;for(;;){const measuredTokens=estimatePmOutputTokens(new TextEncoder().encode(formatBuiltInOutput(attachOutputOmissionReceipt("deps",result),outputFormat)).byteLength);if(measuredTokens===embeddedTokens)return measuredTokens;assign(measuredTokens);embeddedTokens=measuredTokens}}function isContextBudgetFloorError(error){return error instanceof TypeError&&error.message.startsWith("Relationship context tokenBudget cannot fit ")}function buildContextAtRenderedBudget(params){try{return buildContextFromAssembly(params.assembly,params.canonicalId,{...params.contextOptions,...params.internalTokenBudget===void 0?{}:{tokenBudget:params.internalTokenBudget}},params.rootEvidence)}catch(error){if(params.smallestResult!==void 0&&isContextBudgetFloorError(error)){return params.smallestResult}throw error}}function enforceContextRenderedTokenBudget(params){const{assembly,canonicalId,contextOptions,rootEvidence,summaryOnly,outputFormat,missingCount,missingReferences}=params;const referenceLimit=contextOptions.edgeLimit??40;let emittedReferenceLimit=referenceLimit;let internalTokenBudget=contextOptions.tokenBudget;let requestedTokenBudget;let smallestResult;for(;;){const contextOrFloor=buildContextAtRenderedBudget({assembly,canonicalId,contextOptions,internalTokenBudget,rootEvidence,smallestResult});if("format"in contextOrFloor)return contextOrFloor;const context=contextOrFloor;requestedTokenBudget??=context.meta.tokenBudget;internalTokenBudget??=requestedTokenBudget;const result=createContextDepsResult({canonicalId,context,missingCount,missingReferences,referenceLimit:emittedReferenceLimit,summaryOnly});smallestResult=result;if(summaryOnly)return result;context.meta.tokenBudget=requestedTokenBudget;context.meta.usedTokens=settleRenderedTokenCount(attachDepsProjection(result,false),outputFormat,tokens=>{context.meta.usedTokens=tokens});if(context.meta.usedTokens<=requestedTokenBudget)return result;if(emittedReferenceLimit>0){emittedReferenceLimit-=1;continue}const currentInternalBudget=internalTokenBudget;const scaledInternalBudget=currentInternalBudget*requestedTokenBudget/context.meta.usedTokens;internalTokenBudget=Math.min(currentInternalBudget-1,Math.max(1,Math.floor(scaledInternalBudget*.9)))}}function buildContextDepsResult(params){const{assembly,canonicalId,options,rootEvidence,summaryOnly,outputFormat}=params;const contextOptions=parseDepsContextOptions(options,assembly.graph.registry());const reachable=assembly.graph.closure(canonicalId,{direction:contextOptions.direction,...contextOptions.kinds===void 0?{}:{kinds:contextOptions.kinds},maxDepth:contextOptions.maxDepth??3});const missingReachable=reachable.value.filter(nodeId=>assembly.missingIdSet.has(nodeId.toLowerCase()));const missingReachableSet=new Set(missingReachable.map(nodeId=>nodeId.toLowerCase()));const relationshipRegistry=assembly.graph.registry();const filteredKinds=contextOptions.kinds?new Set(contextOptions.kinds.map(kind=>relationshipRegistry.require(kind).kind)):void 0;const packetIds=new Set([canonicalId,...reachable.value]);const missingReferences=[...assembly.dangling.active,...assembly.dangling.legacy_terminal].filter(row=>includesContextMissingReference({row,missingReachableSet,packetIds,filteredKinds,registry:relationshipRegistry}));return enforceContextRenderedTokenBudget({assembly,canonicalId,contextOptions,rootEvidence,summaryOnly,outputFormat,missingCount:missingReachable.length,missingReferences})}function trimDeepestDependency(tree){const pending=[tree];let parentToTrim;while(pending.length>0){const current=pending.pop();if(current.dependencies.length>0){parentToTrim=current;pending.push(...current.dependencies)}}if(!parentToTrim)return false;parentToTrim.dependencies.pop();parentToTrim.truncated=true;return true}function buildTreeOrGraphDepsResult(id,format,options,index,maxDepth,collapse,outputFormat){const effectiveMaxDepth=maxDepth??DEFAULT_DEPS_TREE_MAX_DEPTH;const nodeLimit=parsePositiveInteger(options.nodeLimit,"node-limit")??DEFAULT_DEPS_TREE_NODE_LIMIT;const edgeLimit=parsePositiveInteger(options.edgeLimit,"edge-limit")??DEFAULT_DEPS_TREE_EDGE_LIMIT;const tokenBudget=parsePositiveInteger(options.tokenBudget,"token-budget")??DEFAULT_DEPS_TREE_TOKEN_BUDGET;const budget={nodeLimit,edgeLimit,tokenBudget,nodes:0,edges:0,estimatedTokens:0,reasons:new Set};const tree=toTreeNode(id,index,new Set,effectiveMaxDepth,format==="graph"?"repeated":collapse,new Set,budget);const totals=countDependencyGraph(id,index,void 0);let result;for(;;){const graph=toGraph(tree);const truncation=budget.reasons.size===0?void 0:{reasons:[...budget.reasons].sort(),limits:{max_depth:effectiveMaxDepth,node_limit:nodeLimit,edge_limit:edgeLimit,token_budget:tokenBudget},estimated_tokens:0,total_node_count:totals.node_count,total_edge_count:totals.edge_count,omitted_node_count:Math.max(0,totals.node_count-graph.nodes.length),omitted_edge_count:Math.max(0,totals.edge_count-graph.edges.length)};const baseResult={id,format,node_count:graph.nodes.length,edge_count:graph.edges.length,edge_basis:"deduplicated_directed",missing_count:graph.missing_ids.length,...truncation?{truncation}:{}};result=format==="tree"?{...baseResult,tree}:{...baseResult,graph};const settledTokens=result.truncation===void 0?estimatePmOutputTokens(new TextEncoder().encode(formatBuiltInOutput(attachOutputOmissionReceipt("deps",attachDepsProjection(result,false)),outputFormat)).byteLength):settleRenderedTokenCount(attachDepsProjection(result,false),outputFormat,tokens=>{result.truncation.estimated_tokens=tokens});if(settledTokens<=tokenBudget){return result}if(!trimDeepestDependency(tree)){budget.reasons.add("token_budget");return result}budget.reasons.add("token_budget")}}function attachDepsProjection(result,summaryOnly,legacyAliasCounts={}){const group={name:result.format==="tree"?"dependency_tree":result.format==="graph"?"dependency_graph":"relationship_context",restore_with:"--full"};return{...result,legacy_alias_counts:legacyAliasCounts,projection:{mode:summaryOnly?"summary":"full",declared_field_groups:[group],included_field_groups:summaryOnly?[]:[group.name]}}}async function runDeps(id,options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const format=parseFormat(options.format);const maxDepth=parseMaxDepth(options.maxDepth);const collapse=parseCollapse(options.collapse);assertProjectionModeChoice(options.summary===true,options.full===true,"--summary");const summaryOnly=options.summary===true;const settings=await readSettings(pmRoot);const typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations());const items=await listAllItemMetadataLight(pmRoot,settings.item_format,typeRegistry.type_to_folder,void 0,settings.schema);const statusRegistry=resolveRuntimeStatusRegistry(settings.schema);const index=new Map(items.map(item=>[item.id.trim().toLowerCase(),toIndexedItem(item)]));const dangling=collectDanglingDependencyReferences(items,status=>isTerminalStatus(status,statusRegistry));for(const reference of[...dangling.active,...dangling.legacy_terminal]){const holder=index.get(reference.holder_id.trim().toLowerCase());const referenceKind=reference.kind.trim().toLowerCase();if(holder&&!holder.dependencies.some(dependency=>dependency.id.trim().toLowerCase()===reference.target_id.trim().toLowerCase()&&dependency.kind===referenceKind)){holder.dependencies.push({id:reference.target_id,kind:referenceKind})}}if(!index.has(id.trim().toLowerCase())){throw new PmCliError(`Item ${id} not found`,EXIT_CODE.NOT_FOUND)}if(format==="context"){const canonicalId=index.get(id.trim().toLowerCase()).id;const rootEvidence=summaryOnly?[]:await collectRootEvidence(pmRoot,canonicalId,settings,typeRegistry.type_to_folder);const isTerminal=status=>isTerminalStatus(status,statusRegistry);const relationshipRegistry=resolveWorkspaceRelationshipKindRegistry();const lookup=workspaceGraphCache().lookup(pmRoot,computeWorkspaceGraphFingerprint(items,isTerminal,relationshipRegistry),()=>assembleWorkspaceRelationshipGraph(items,isTerminal,relationshipRegistry));return attachDepsProjection(buildContextDepsResult({assembly:lookup.assembly,canonicalId,options,rootEvidence,summaryOnly,outputFormat:global2.json===true?"json":"toon"}),summaryOnly,lookup.assembly.legacyAliasCounts)}if(summaryOnly){return attachDepsProjection({id,format,...countDependencyGraph(id,index,maxDepth)},true,Object.fromEntries(Object.entries(assembleWorkspaceRelationshipGraph(items,status=>isTerminalStatus(status,statusRegistry)).legacyAliasCounts)))}return attachDepsProjection(buildTreeOrGraphDepsResult(id,format,options,index,maxDepth,collapse,global2.json===true?"json":"toon"),false,Object.fromEntries(Object.entries(assembleWorkspaceRelationshipGraph(items,status=>isTerminalStatus(status,statusRegistry)).legacyAliasCounts)))}export{DEPS_COLLAPSE_VALUES,DEPS_DIRECTION_VALUES,DEPS_FORMAT_VALUES,buildDepsRelationshipContext,parseDirection,parseKinds,parseMaxDepth,parsePositiveInteger,runDeps};
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="620bf4e4-e6d1-5520-89e4-0859f57c7afe")}catch{}})();import{assertInitializedTracker}from"./environment/tracker-preflight.js";import{getActiveExtensionRegistrations}from"../core/extensions/index.js";import{resolveItemTypeRegistry}from"../core/item/type-registry.js";import{isTerminalStatus}from"../core/item/status.js";import{resolveRuntimeStatusRegistry}from"../core/schema/runtime-schema.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{formatBuiltInOutput}from"../core/output/output.js";import{listAllItemMetadataLight,locateItem,readLocatedItem}from"../core/store/item-store.js";import{resolvePmRoot}from"../core/store/paths.js";import{readSettings}from"../core/store/settings.js";import{estimatePmOutputTokens}from"./cli-contracts/agent-output-contracts.js";import{assertProjectionModeChoice,attachOutputOmissionReceipt}from"./output-projection.js";import{assembleWorkspaceRelationshipGraph,collectDanglingDependencyReferences,resolveWorkspaceRelationshipKindRegistry}from"./graph/assembly.js";import{computeWorkspaceGraphFingerprint,workspaceGraphCache}from"./graph/cache.js";import{buildRelationshipContext}from"./relationship-context.js";import{createRelationshipKindRegistry}from"./relationships.js";const DEPS_FORMAT_VALUES=["tree","graph","context"],DEPS_COLLAPSE_VALUES=["none","repeated"],DEPS_DIRECTION_VALUES=["outgoing","incoming","both"],DEFAULT_DEPS_TREE_MAX_DEPTH=32,DEFAULT_DEPS_TREE_NODE_LIMIT=200,DEFAULT_DEPS_TREE_EDGE_LIMIT=400,DEFAULT_DEPS_TREE_TOKEN_BUDGET=16e3;function parseFormat(raw){const candidate=raw?.trim().toLowerCase()??"tree";if(DEPS_FORMAT_VALUES.includes(candidate))return candidate;throw new PmCliError(`Invalid --format value "${raw}". Use "tree", "graph", or "context".`,EXIT_CODE.USAGE)}function parsePositiveInteger(raw,flag){if(raw===void 0)return;const value=typeof raw=="number"?raw:Number(raw.trim());if(!Number.isInteger(value)||value<1)throw new PmCliError(`Invalid --${flag} value "${raw}". Use a positive integer.`,EXIT_CODE.USAGE);return value}function parseMaxDepth(raw){if(raw===void 0)return;const normalized=typeof raw=="number"?raw:Number(raw.trim());if(!Number.isInteger(normalized)||normalized<0)throw new PmCliError(`Invalid --max-depth value "${raw}". Use a non-negative integer.`,EXIT_CODE.USAGE);return normalized}function parseCollapse(raw){const candidate=raw?.trim().toLowerCase()??"none";if(DEPS_COLLAPSE_VALUES.includes(candidate))return candidate;throw new PmCliError(`Invalid --collapse value "${raw}". Use "none" or "repeated".`,EXIT_CODE.USAGE)}function parseDirection(raw){const candidate=raw?.trim().toLowerCase()??"both";if(DEPS_DIRECTION_VALUES.includes(candidate))return candidate;throw new PmCliError(`Invalid --direction value "${raw}". Use "outgoing", "incoming", or "both".`,EXIT_CODE.USAGE)}function parseKinds(raw,registry=createRelationshipKindRegistry()){if(raw===void 0)return;const values=(Array.isArray(raw)?raw:[raw]).flatMap(value=>value.split(",")).map(value=>value.trim()).filter(value=>value.length>0);if(values.length===0)return;const kinds=new Set;for(const value of values){const definition=registry.resolve(value);if(!definition){const known=registry.list().map(entry=>entry.kind).join(", ");throw new PmCliError(`Invalid --kind value "${value}". Registered kinds: ${known}.`,EXIT_CODE.USAGE)}kinds.add(definition.kind)}return[...kinds].sort()}function normalizeDependencies(dependencies){if(!dependencies||dependencies.length===0)return[];const sorted=dependencies.map(({id,kind})=>({id:id.trim(),kind:kind.trim().toLowerCase()})).sort((left,right)=>{const byKind=left.kind.localeCompare(right.kind);return byKind!==0?byKind:left.id.localeCompare(right.id)}),deduped=new Map;for(const dependency of sorted){const key=`${dependency.kind.toLowerCase()}::${dependency.id.toLowerCase()}`;deduped.has(key)||deduped.set(key,{id:dependency.id,kind:dependency.kind})}return[...deduped.values()]}function toIndexedItem(item){return{id:item.id,title:item.title,type:item.type,status:item.status,dependencies:normalizeDependencies(item.dependencies)}}function estimateTreeNodeTokens(node){return estimatePmOutputTokens(new TextEncoder().encode(JSON.stringify({...node,dependencies:void 0})).byteLength)}function appendTreeDependencies(baseNode,item,index,nextLineage,maxDepth,collapse,expanded,budget,depth){for(const dependency of item.dependencies){const edgeTokens=Math.max(1,Math.ceil(JSON.stringify({from:baseNode.id,to:dependency.id,kind:dependency.kind}).length/3));if(budget.nodes>=budget.nodeLimit){baseNode.truncated=!0,budget.reasons.add("node_limit");break}if(budget.edges>=budget.edgeLimit){baseNode.truncated=!0,budget.reasons.add("edge_limit");break}if(budget.estimatedTokens+edgeTokens>=budget.tokenBudget){baseNode.truncated=!0,budget.reasons.add("token_budget");break}budget.edges+=1,budget.estimatedTokens+=edgeTokens,baseNode.dependencies.push(toTreeNode(dependency.id,index,nextLineage,maxDepth,collapse,expanded,budget,depth+1,dependency.kind))}}function shouldStopTreeNodeExpansion(node,item,lookupId,maxDepth,collapse,expanded,budget,depth){return budget.estimatedTokens>=budget.tokenBudget&&item?.dependencies.length?(node.truncated=!0,budget.reasons.add("token_budget"),!0):!item||node.cycle?!0:maxDepth!==void 0&&depth>=maxDepth?(item.dependencies.length>0&&(node.truncated=!0,budget.reasons.add("max_depth")),!0):collapse==="repeated"&&expanded.has(lookupId)?(node.collapsed=!0,!0):!1}function toTreeNode(id,index,lineage,maxDepth,collapse,expanded,budget,depth=0,via){const lookupId=id.trim().toLowerCase(),item=index.get(lookupId),baseNode={id:item?.id??id,title:item?.title,type:item?.type,status:item?.status,via,missing:!item,cycle:lineage.has(lookupId),dependencies:[]};if(budget.nodes+=1,budget.estimatedTokens+=estimateTreeNodeTokens(baseNode),shouldStopTreeNodeExpansion(baseNode,item,lookupId,maxDepth,collapse,expanded,budget,depth))return baseNode;collapse==="repeated"&&expanded.add(lookupId);const nextLineage=new Set(lineage);return nextLineage.add(lookupId),appendTreeDependencies(baseNode,item,index,nextLineage,maxDepth,collapse,expanded,budget,depth),baseNode}function mergeGraphNode(existing,candidate){return!existing||existing.missing&&!candidate.missing?candidate:{...existing,title:existing.title??candidate.title,type:existing.type??candidate.type,status:existing.status??candidate.status}}function toGraph(root){const nodesById=new Map,edgesByKey=new Map,pending=[root];for(;pending.length>0;){const node=pending.pop();nodesById.set(node.id,mergeGraphNode(nodesById.get(node.id),{id:node.id,title:node.title,type:node.type,status:node.status,missing:node.missing}));for(const child of node.dependencies){nodesById.set(child.id,mergeGraphNode(nodesById.get(child.id),{id:child.id,title:child.title,type:child.type,status:child.status,missing:child.missing}));const relationKind=child.via??"related",edgeKey=`${node.id}::${child.id}::${relationKind}`;edgesByKey.has(edgeKey)||edgesByKey.set(edgeKey,{from:node.id,to:child.id,kind:relationKind}),child.cycle||pending.push(child)}}const nodes=[...nodesById.values()].sort((left,right)=>left.id.localeCompare(right.id)),edges=[...edgesByKey.values()].sort((left,right)=>{const byFrom=left.from.localeCompare(right.from);if(byFrom!==0)return byFrom;const byTo=left.to.localeCompare(right.to);return byTo!==0?byTo:left.kind.localeCompare(right.kind)}),missingIds=nodes.filter(node=>node.missing).map(node=>node.id);return{root_id:root.id,nodes,edges,missing_ids:missingIds}}function countDependencyGraph(rootId,index,maxDepth){const nodeIds=new Set,edgeKeys=new Set,missingIds=new Set,expanded=new Set,pending=[{id:rootId,depth:0}];let pendingIndex=0;for(;pendingIndex<pending.length;){const current=pending[pendingIndex++],lookupId=current.id.trim().toLowerCase();nodeIds.add(lookupId);const item=index.get(lookupId);if(!item){missingIds.add(lookupId);continue}if(!(maxDepth!==void 0&¤t.depth>=maxDepth)&&!expanded.has(lookupId)){expanded.add(lookupId);for(const dependency of item.dependencies)edgeKeys.add(`${lookupId}::${dependency.id.trim().toLowerCase()}::${dependency.kind}`),pending.push({id:dependency.id,depth:current.depth+1})}}return{node_count:nodeIds.size,edge_count:edgeKeys.size,edge_basis:"deduplicated_directed",missing_count:missingIds.size}}function parseDepsContextOptions(options,registry=createRelationshipKindRegistry()){const maxDepth=parseMaxDepth(options.maxDepth),nodeLimit=parsePositiveInteger(options.nodeLimit,"node-limit"),edgeLimit=parsePositiveInteger(options.edgeLimit,"edge-limit"),tokenBudget=parsePositiveInteger(options.tokenBudget,"token-budget"),kinds=parseKinds(options.kind,registry);return{direction:parseDirection(options.direction),...kinds===void 0?{}:{kinds},...maxDepth===void 0?{}:{maxDepth},...nodeLimit===void 0?{}:{nodeLimit},...edgeLimit===void 0?{}:{edgeLimit},...tokenBudget===void 0?{}:{tokenBudget},...options.cursor?.trim()?{cursor:options.cursor.trim()}:{}}}function buildContextFromAssembly(assembly,rootId,options,rootEvidence){return buildRelationshipContext(assembly.graph,rootId,assembly.details.map(detail=>detail.id===rootId&&rootEvidence.length>0?{...detail,evidence:rootEvidence}:detail),options)}function buildDepsRelationshipContext(rootId,items,options,rootEvidence=[]){const assembly=assembleWorkspaceRelationshipGraph(items);return buildContextFromAssembly(assembly,rootId,parseDepsContextOptions(options,assembly.graph.registry()),rootEvidence)}function appendEvidencePointers(evidence,label,values,limit){for(const value of values.slice(0,limit)){const trimmed=value?.trim();trimmed&&evidence.push(`${label}:${trimmed}`)}}async function collectRootEvidence(pmRoot,id,settings,typeToFolder){const located=await locateItem(pmRoot,id,settings.id_prefix,settings.item_format,typeToFolder);if(!located)return[];const{document}=await readLocatedItem(located,{schema:settings.schema}),metadata=document.metadata,files=metadata.files??[],tests=metadata.tests??[],docs=metadata.docs??[],counts=[["files",files.length],["tests",tests.length],["docs",docs.length],["comments",(metadata.comments??[]).length],["notes",(metadata.notes??[]).length],["learnings",(metadata.learnings??[]).length]];if(counts.every(([,count])=>count===0))return[];const evidence=[`linked:${counts.map(([key,count])=>`${key}=${count}`).join(",")}`];return appendEvidencePointers(evidence,"file",files.map(file=>file.path),3),appendEvidencePointers(evidence,"test",tests.map(test=>test.command??test.path),2),appendEvidencePointers(evidence,"doc",docs.map(doc=>doc.path),2),evidence}function createContextDepsResult(params){const{canonicalId,context,missingCount,missingReferences,referenceLimit,summaryOnly}=params;return{id:canonicalId,format:"context",node_count:context.nodes.length+1,edge_count:context.edges.length,edge_basis:"deduplicated_directed",missing_count:missingCount,missing_scope:"traversal",missing_reference_count:missingReferences.length,...summaryOnly?{}:{missing_references:missingReferences.slice(0,referenceLimit),context}}}function includesContextMissingReference(params){const{row,missingReachableSet,packetIds,filteredKinds,registry}=params;if(row.no_active_blocker_sentinel||!missingReachableSet.has(row.target_id.trim().toLowerCase())||!packetIds.has(row.holder_id))return!1;if(filteredKinds===void 0)return!0;const definition=registry.resolve(row.kind);return definition!==void 0&&(filteredKinds.has(definition.kind)||definition.inverse!==void 0&&filteredKinds.has(definition.inverse))}function settleRenderedTokenCount(result,outputFormat,assign){let embeddedTokens;for(;;){const measuredTokens=estimatePmOutputTokens(new TextEncoder().encode(formatBuiltInOutput(attachOutputOmissionReceipt("deps",result),outputFormat)).byteLength);if(measuredTokens===embeddedTokens)return measuredTokens;assign(measuredTokens),embeddedTokens=measuredTokens}}function isContextBudgetFloorError(error){return error instanceof TypeError&&error.message.startsWith("Relationship context tokenBudget cannot fit ")}function buildContextAtRenderedBudget(params){try{return buildContextFromAssembly(params.assembly,params.canonicalId,{...params.contextOptions,...params.internalTokenBudget===void 0?{}:{tokenBudget:params.internalTokenBudget}},params.rootEvidence)}catch(error){if(params.smallestResult!==void 0&&isContextBudgetFloorError(error))return params.smallestResult;throw error}}function enforceContextRenderedTokenBudget(params){const{assembly,canonicalId,contextOptions,rootEvidence,summaryOnly,outputFormat,missingCount,missingReferences}=params;let emittedReferenceLimit=contextOptions.edgeLimit??40,internalTokenBudget=contextOptions.tokenBudget,requestedTokenBudget,smallestResult;for(;;){const contextOrFloor=buildContextAtRenderedBudget({assembly,canonicalId,contextOptions,internalTokenBudget,rootEvidence,smallestResult});if("format"in contextOrFloor)return contextOrFloor;const context=contextOrFloor;requestedTokenBudget??=context.meta.tokenBudget,internalTokenBudget??=requestedTokenBudget;const result=createContextDepsResult({canonicalId,context,missingCount,missingReferences,referenceLimit:emittedReferenceLimit,summaryOnly});if(smallestResult=result,summaryOnly||(context.meta.tokenBudget=requestedTokenBudget,context.meta.usedTokens=settleRenderedTokenCount(attachDepsProjection(result,!1),outputFormat,tokens=>{context.meta.usedTokens=tokens}),context.meta.usedTokens<=requestedTokenBudget))return result;if(emittedReferenceLimit>0){emittedReferenceLimit-=1;continue}const currentInternalBudget=internalTokenBudget,scaledInternalBudget=currentInternalBudget*requestedTokenBudget/context.meta.usedTokens;internalTokenBudget=Math.min(currentInternalBudget-1,Math.max(1,Math.floor(scaledInternalBudget*.9)))}}function buildContextDepsResult(params){const{assembly,canonicalId,options,rootEvidence,summaryOnly,outputFormat}=params,contextOptions=parseDepsContextOptions(options,assembly.graph.registry()),reachable=assembly.graph.closure(canonicalId,{direction:contextOptions.direction,...contextOptions.kinds===void 0?{}:{kinds:contextOptions.kinds},maxDepth:contextOptions.maxDepth??3}),missingReachable=reachable.value.filter(nodeId=>assembly.missingIdSet.has(nodeId.toLowerCase())),missingReachableSet=new Set(missingReachable.map(nodeId=>nodeId.toLowerCase())),relationshipRegistry=assembly.graph.registry(),filteredKinds=contextOptions.kinds?new Set(contextOptions.kinds.map(kind=>relationshipRegistry.require(kind).kind)):void 0,packetIds=new Set([canonicalId,...reachable.value]),missingReferences=[...assembly.dangling.active,...assembly.dangling.legacy_terminal].filter(row=>includesContextMissingReference({row,missingReachableSet,packetIds,filteredKinds,registry:relationshipRegistry}));return enforceContextRenderedTokenBudget({assembly,canonicalId,contextOptions,rootEvidence,summaryOnly,outputFormat,missingCount:missingReachable.length,missingReferences})}function trimDeepestDependency(tree){const pending=[tree];let parentToTrim;for(;pending.length>0;){const current=pending.pop();current.dependencies.length>0&&(parentToTrim=current,pending.push(...current.dependencies))}return parentToTrim?(parentToTrim.dependencies.pop(),parentToTrim.truncated=!0,!0):!1}function buildTreeOrGraphDepsResult(id,format,options,index,maxDepth,collapse,outputFormat){const effectiveMaxDepth=maxDepth??DEFAULT_DEPS_TREE_MAX_DEPTH,nodeLimit=parsePositiveInteger(options.nodeLimit,"node-limit")??DEFAULT_DEPS_TREE_NODE_LIMIT,edgeLimit=parsePositiveInteger(options.edgeLimit,"edge-limit")??DEFAULT_DEPS_TREE_EDGE_LIMIT,tokenBudget=parsePositiveInteger(options.tokenBudget,"token-budget")??DEFAULT_DEPS_TREE_TOKEN_BUDGET,budget={nodeLimit,edgeLimit,tokenBudget,nodes:0,edges:0,estimatedTokens:0,reasons:new Set},tree=toTreeNode(id,index,new Set,effectiveMaxDepth,format==="graph"?"repeated":collapse,new Set,budget),totals=countDependencyGraph(id,index,void 0);let result;for(;;){const graph=toGraph(tree),truncation=budget.reasons.size===0?void 0:{reasons:[...budget.reasons].sort(),limits:{max_depth:effectiveMaxDepth,node_limit:nodeLimit,edge_limit:edgeLimit,token_budget:tokenBudget},estimated_tokens:0,total_node_count:totals.node_count,total_edge_count:totals.edge_count,omitted_node_count:Math.max(0,totals.node_count-graph.nodes.length),omitted_edge_count:Math.max(0,totals.edge_count-graph.edges.length)},baseResult={id,format,node_count:graph.nodes.length,edge_count:graph.edges.length,edge_basis:"deduplicated_directed",missing_count:graph.missing_ids.length,...truncation?{truncation}:{}};if(result=format==="tree"?{...baseResult,tree}:{...baseResult,graph},(result.truncation===void 0?estimatePmOutputTokens(new TextEncoder().encode(formatBuiltInOutput(attachOutputOmissionReceipt("deps",attachDepsProjection(result,!1)),outputFormat)).byteLength):settleRenderedTokenCount(attachDepsProjection(result,!1),outputFormat,tokens=>{result.truncation.estimated_tokens=tokens}))<=tokenBudget)return result;if(!trimDeepestDependency(tree))return budget.reasons.add("token_budget"),result;budget.reasons.add("token_budget")}}function attachDepsProjection(result,summaryOnly,legacyAliasCounts={}){const group={name:result.format==="tree"?"dependency_tree":result.format==="graph"?"dependency_graph":"relationship_context",restore_with:"--full"};return{...result,legacy_alias_counts:legacyAliasCounts,projection:{mode:summaryOnly?"summary":"full",declared_field_groups:[group],included_field_groups:summaryOnly?[]:[group.name]}}}async function runDeps(id,options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const format=parseFormat(options.format),maxDepth=parseMaxDepth(options.maxDepth),collapse=parseCollapse(options.collapse);assertProjectionModeChoice(options.summary===!0,options.full===!0,"--summary");const summaryOnly=options.summary===!0,settings=await readSettings(pmRoot),typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()),items=await listAllItemMetadataLight(pmRoot,settings.item_format,typeRegistry.type_to_folder,void 0,settings.schema),statusRegistry=resolveRuntimeStatusRegistry(settings.schema),index=new Map(items.map(item=>[item.id.trim().toLowerCase(),toIndexedItem(item)])),dangling=collectDanglingDependencyReferences(items,status=>isTerminalStatus(status,statusRegistry));for(const reference of[...dangling.active,...dangling.legacy_terminal]){const holder=index.get(reference.holder_id.trim().toLowerCase()),referenceKind=reference.kind.trim().toLowerCase();holder&&!holder.dependencies.some(dependency=>dependency.id.trim().toLowerCase()===reference.target_id.trim().toLowerCase()&&dependency.kind===referenceKind)&&holder.dependencies.push({id:reference.target_id,kind:referenceKind})}if(!index.has(id.trim().toLowerCase()))throw new PmCliError(`Item ${id} not found`,EXIT_CODE.NOT_FOUND);if(format==="context"){const canonicalId=index.get(id.trim().toLowerCase()).id,rootEvidence=summaryOnly?[]:await collectRootEvidence(pmRoot,canonicalId,settings,typeRegistry.type_to_folder),isTerminal=status=>isTerminalStatus(status,statusRegistry),relationshipRegistry=resolveWorkspaceRelationshipKindRegistry(),lookup=workspaceGraphCache().lookup(pmRoot,computeWorkspaceGraphFingerprint(items,isTerminal,relationshipRegistry),()=>assembleWorkspaceRelationshipGraph(items,isTerminal,relationshipRegistry));return attachDepsProjection(buildContextDepsResult({assembly:lookup.assembly,canonicalId,options,rootEvidence,summaryOnly,outputFormat:global2.json===!0?"json":"toon"}),summaryOnly,lookup.assembly.legacyAliasCounts)}return summaryOnly?attachDepsProjection({id,format,...countDependencyGraph(id,index,maxDepth)},!0,Object.fromEntries(Object.entries(assembleWorkspaceRelationshipGraph(items,status=>isTerminalStatus(status,statusRegistry)).legacyAliasCounts))):attachDepsProjection(buildTreeOrGraphDepsResult(id,format,options,index,maxDepth,collapse,global2.json===!0?"json":"toon"),!1,Object.fromEntries(Object.entries(assembleWorkspaceRelationshipGraph(items,status=>isTerminalStatus(status,statusRegistry)).legacyAliasCounts)))}export{DEPS_COLLAPSE_VALUES,DEPS_DIRECTION_VALUES,DEPS_FORMAT_VALUES,buildDepsRelationshipContext,parseDirection,parseKinds,parseMaxDepth,parsePositiveInteger,runDeps};
|
|
2
2
|
//# sourceMappingURL=dependencies.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="f2c9f586-3e93-5caf-a5c2-38be30c67171")}catch{}})();import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{toErrorMessage}from"../core/shared/primitives.js";import{locateItem,readLocatedItem}from"../core/store/item-store.js";import{isExternalDependencySourceKind}from"./dependency-provenance.js";import{resolveWorkspaceRelationshipKindRegistry}from"./graph/assembly.js";import{assertRelationshipEdgeAllowed}from"./relationships.js";function assertValidBareDependencyFlagValue(value,structured,flag="--dep"){if(!structured&&/[:,=]/.test(value))throw new PmCliError(`Invalid ${flag} value "${value}". Use a bare item id or id=<id>,kind=<kind>.`,EXIT_CODE.USAGE,{code:"dependency_flag_value_invalid",reason:"malformed_dependency_shorthand",flag,value,required:"Use a bare item id or an explicit id=<id>,kind=<kind> entry."})}function assertDependencyEdgesAllowed(holderId,dependencies,registry=resolveWorkspaceRelationshipKindRegistry()){for(const dependency of dependencies??[])try{assertRelationshipEdgeAllowed(holderId,dependency.id,dependency.kind,registry)}catch(error){throw new PmCliError(toErrorMessage(error),EXIT_CODE.USAGE,{code:"dependency_edge_not_allowed",why:`${holderId} -> ${dependency.id} (${dependency.kind}) violates the active relationship-kind policy`})}}async function readDependencyEndpointCreatedAt(located,schema){return(await readLocatedItem(located,{schema})).document.metadata.created_at}async function resolveDependencyHolderCreatedAt(holder,context){if(holder.createdAt!==void 0)return holder.createdAt;const located=await locateItem(context.pmRoot,holder.id,context.idPrefix,context.itemFormat,context.typeToFolder);return located===null?void 0:readDependencyEndpointCreatedAt(located,context.schema)}function dependencyTemporalOrderError(params){const definition=params.registry.require(params.dependency.kind);return new PmCliError(`${definition.kind} requires source ${params.holder.id} to be created after target ${params.dependency.id}`,EXIT_CODE.USAGE,{code:"dependency_temporal_order_invalid",reason:"source_not_after_target",required:`${params.holder.id}.created_at must be later than ${params.dependency.id}.created_at for ${definition.kind}.`,why:"Chronological recurrence direction must be validated before the relationship is persisted.",source_id:params.holder.id,source_created_at:params.sourceCreatedAt,target_id:params.dependency.id,target_created_at:params.targetCreatedAt,temporal_order:definition.temporalOrder})}async function assertTemporalDependencyChronology(params){const temporalDependencies=params.dependencies.filter(dependency=>params.registry.resolve(dependency.kind)?.temporalOrder==="source_after_target"&&!params.missingTargets.includes(dependency.id));if(temporalDependencies.length===0||params.holders.length===0)return;const locatedTargets=new Map(params.resolutions.flatMap(({target,located})=>located===null?[]:[[target,located]])),targetCreatedAt=new Map(await Promise.all([...new Set(temporalDependencies.map(({id})=>id))].map(async target=>[target,await readDependencyEndpointCreatedAt(locatedTargets.get(target),params.context.schema)])));for(const holder of params.holders){const sourceCreatedAt=await resolveDependencyHolderCreatedAt(holder,params.context);if(sourceCreatedAt!==void 0)for(const dependency of temporalDependencies){const targetTimestamp=targetCreatedAt.get(dependency.id),sourceTime=Date.parse(sourceCreatedAt),targetTime=Date.parse(targetTimestamp);if(!(Number.isFinite(sourceTime)&&Number.isFinite(targetTime)&&sourceTime>targetTime))throw dependencyTemporalOrderError({holder,dependency,sourceCreatedAt,targetCreatedAt:targetTimestamp,registry:params.registry})}}}async function assertDependencyTargetsResolvable(params){const registry=params.registry??resolveWorkspaceRelationshipKindRegistry(),localDependencies=(params.dependencies??[]).filter(dependency=>!isExternalDependencySourceKind(dependency.source_kind)),localTargets=[...new Set(localDependencies.map(dependency=>dependency.id))],resolutions=await Promise.all(localTargets.map(async target=>({target,located:await locateItem(params.pmRoot,target,params.idPrefix,params.itemFormat,params.typeToFolder)}))),missingTargets=resolutions.filter(({located})=>located===null).map(({target})=>target).sort((left,right)=>left<right?-1:1);if(missingTargets.length>0&¶ms.allowUnresolved!==!0)throw new PmCliError(`Dependency target${missingTargets.length===1?"":"s"} not found: ${missingTargets.join(", ")}`,EXIT_CODE.NOT_FOUND,{code:"dependency_target_not_found",reason:"unresolved_local_dependency",required:"Every local dependency target must exist before the edge is committed.",why:"Fail-fast target resolution prevents dangling graph nodes and preserves reliable traversal semantics.",unresolved_targets:missingTargets,examples:["--dep id=<existing-item-id>,kind=related","--dep id=<external-id>,kind=related,source_kind=external","--allow-unresolved-deps --dep id=<future-item-id>,kind=related"],nextSteps:[`Create or correct ${missingTargets.length===1?"the target":"the targets"}, then retry the mutation.`,"Use source_kind=external for a cross-workspace reference.","Use --allow-unresolved-deps only when the dangling local edge is intentional."],recovery:{recovery_mode:"compact",missing:missingTargets,suggested_flags:["--allow-unresolved-deps"],suggested_retry:`pm search "${missingTargets[0]}" --limit 10`}});return await assertTemporalDependencyChronology({dependencies:localDependencies,missingTargets,resolutions,holders:params.holders??[],registry,context:params}),missingTargets.map(target=>`dependency_target_unresolved:${target}`)}export{assertDependencyEdgesAllowed,assertDependencyTargetsResolvable,assertValidBareDependencyFlagValue};
|
|
2
2
|
//# sourceMappingURL=dependency-flag-validation.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="6c580b70-76eb-51db-8587-99b73dd20875")}catch{}})();import{normalizeItemId}from"../core/item/id.js";import{isExternalDependencyReference,isExternalDependencySourceKind}from"../core/item/dependency-reference.js";import{isExternalDependencyReference as isExternalDependencyReference2,isExternalDependencySourceKind as isExternalDependencySourceKind2}from"../core/item/dependency-reference.js";const EXTERNAL_DEPENDENCY_SOURCE_KIND="global",EXTERNAL_DEPENDENCY_SOURCE_KIND_ALIAS="external",EXTERNAL_DEPENDENCY_RESOLUTION_STATUSES=["open","closed","unknown"],externalDependencyResolvers=new Map,MAX_EXTERNAL_TITLE_LENGTH=240,MAX_EXTERNAL_SOURCE_LENGTH=2048;function boundedExternalText(value,fallback,maximumLength){return(value?.trim()||fallback).slice(0,maximumLength)}function isExternalDependencyResolverResult(value){if(typeof value!="object"||value===null||Array.isArray(value))return!1;const candidate=value;return typeof candidate.status=="string"&&(candidate.title==null||typeof candidate.title=="string")&&(candidate.source==null||typeof candidate.source=="string")&&(candidate.checkedAt==null||typeof candidate.checkedAt=="string")}function registerExternalDependencyResolver(resolver){const name=resolver.name.trim();if(name.length===0)throw new Error("External dependency resolver name must not be empty");if(externalDependencyResolvers.has(name))throw new Error(`External dependency resolver already registered: ${name}`);const registeredResolver={name,supports:reference=>resolver.supports(reference),resolve:reference=>resolver.resolve(reference)};return externalDependencyResolvers.set(name,registeredResolver),()=>{externalDependencyResolvers.get(name)===registeredResolver&&externalDependencyResolvers.delete(name)}}async function resolveExternalDependencyReference(reference,options={}){const id=reference.trim();if(!isExternalDependencyReference(id))return null;const resolvers=[...externalDependencyResolvers.values()].filter(resolver=>{try{return resolver.supports(id)}catch{return!1}}),outcomes=await Promise.allSettled(resolvers.map(resolver=>Promise.resolve().then(()=>resolver.resolve(id))));for(const[index,outcome]of outcomes.entries()){if(outcome.status!=="fulfilled"||!isExternalDependencyResolverResult(outcome.value))continue;const resolver=resolvers[index],candidate=outcome.value,status=EXTERNAL_DEPENDENCY_RESOLUTION_STATUSES.includes(candidate.status)?candidate.status:"unknown",title=boundedExternalText(candidate.title,"",MAX_EXTERNAL_TITLE_LENGTH),source=boundedExternalText(candidate.source,id,MAX_EXTERNAL_SOURCE_LENGTH),observedAtMs=Date.parse(candidate.checkedAt?.trim()??""),checkedAt=Number.isFinite(observedAtMs)?new Date(observedAtMs).toISOString():options.now?.()??new Date().toISOString();return{id,status,resolved:status==="closed",title:title.length>0?title:null,source,checked_at:checkedAt,resolver:resolver.name}}return null}function normalizeDependencySourceKind(sourceKind){const trimmed=sourceKind?.trim();if(trimmed)return isExternalDependencySourceKind(trimmed)?EXTERNAL_DEPENDENCY_SOURCE_KIND:trimmed}function normalizeDependencySeedId(id,prefix,sourceKind){return normalizeItemReference(id,prefix,sourceKind)}function normalizeItemReference(reference,prefix,sourceKind){const trimmed=reference.trim();return isExternalDependencySourceKind(sourceKind)||isExternalDependencyReference(trimmed)?trimmed:normalizeItemId(trimmed,prefix)}export{EXTERNAL_DEPENDENCY_RESOLUTION_STATUSES,EXTERNAL_DEPENDENCY_SOURCE_KIND,EXTERNAL_DEPENDENCY_SOURCE_KIND_ALIAS,isExternalDependencyReference2 as isExternalDependencyReference,isExternalDependencySourceKind2 as isExternalDependencySourceKind,normalizeDependencySeedId,normalizeDependencySourceKind,normalizeItemReference,registerExternalDependencyResolver,resolveExternalDependencyReference};
|
|
2
2
|
//# sourceMappingURL=dependency-provenance.js.map
|
package/dist/sdk/docs.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="79f1acaf-8ef7-5725-900a-fbeced1c57e6")}catch{}})();import{renameArtifactsResultKey,runLinkedArtifacts}from"./linked-artifacts.js";async function runDocs(id,options,global2){const result=await runLinkedArtifacts(id,options,global2,{metadataKey:"docs",op:"docs_add",bareNoun:"doc",supportsAppendStable:!1});return renameArtifactsResultKey(result,"docs")}export{runDocs};
|
|
2
2
|
//# sourceMappingURL=docs.js.map
|
package/dist/sdk/duplicates.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="499dfc08-cf70-55fe-8868-65c3107e3a91")}catch{}})();import{resolvePmRoot}from"../core/store/paths.js";import{findDuplicateClusters}from"./similarity.js";async function runDuplicates(global2,options={}){const result=await findDuplicateClusters({pmRoot:resolvePmRoot(process.cwd(),global2.path),exhaustive:options.exhaustive,...options.status===void 0?{}:{statuses:options.status.flatMap(status=>status.split(",").map(value=>value.trim()).filter(Boolean))},...options.since===void 0?{}:{since:options.since},...options.threshold===void 0?{}:{threshold:options.threshold},...options.limit===void 0?{}:{limit:options.limit}});return{...result,clusters:result.clusters.map(cluster=>{const canonicalId=cluster.id;return{...cluster,canonical_id:canonicalId,close_command:`pm close <duplicate-id> --duplicate-of ${canonicalId}`}}),guidance:{strategy:"review_then_close_duplicate",command:"pm close <duplicate-id> --duplicate-of <canonical-id>"}}}export{runDuplicates};
|
|
2
2
|
//# sourceMappingURL=duplicates.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="6e293af6-ee81-59b4-8d80-05e5c20bdcf1")}catch(e2){}})();import{sha256Hex,stableStringify}from"../../core/shared/serialization.js";import{runWithAgentSessionContext}from"../agent-session-context.js";import{defineWorkspaceRecipe}from"../workspace-recipe.js";const PM_OBSERVATION_SCHEMA="pm.agent-observation/v1";const PM_VERDICT_SCHEMA="pm.agent-verdict/v1";const PM_EPISODE_SCHEMA="pm.agent-episode/v1";function assertPositiveInteger(value,label){if(!Number.isSafeInteger(value)||value<=0){throw new Error(`${label} must be a positive safe integer.`)}}function assertNonEmpty(value,label){if(value.trim().length===0)throw new Error(`${label} must not be empty.`)}function frozenCopy(value){if(value!==null&&typeof value==="object"&&!Object.isFrozen(value)){Object.freeze(value);for(const nested of Object.values(value))frozenCopy(nested)}return value}function validateObservationReads(reads){if(reads.length===0){throw new Error("observation.reads must declare at least one bounded read.")}let readCeiling=0;for(const read of reads){assertNonEmpty(read.command,"observation.reads.command");assertPositiveInteger(read.budget_tokens,"observation.reads.budget_tokens");readCeiling+=read.budget_tokens;if(!Number.isSafeInteger(readCeiling)){throw new Error("observation read ceilings exceed safe integer range.")}}}function validateObservationCalibration(calibration){if(calibration.basis!=="emitted_bytes"){throw new Error("observation calibration must use emitted_bytes.")}for(const sample of calibration.samples){if(!Number.isSafeInteger(sample)||sample<0){throw new Error("observation calibration samples must be non-negative safe integers.")}}if(calibration.samples.length===0){throw new Error("observation calibration must include at least one sample.")}assertPositiveInteger(calibration.expected_emitted_bytes,"observation.calibration.expected_emitted_bytes");if(!Number.isSafeInteger(calibration.tolerance_bytes)||calibration.tolerance_bytes<0){throw new Error("observation.calibration.tolerance_bytes must be a non-negative safe integer.")}const sampleMean=calibration.samples.reduce((total,sample)=>total+sample,0)/calibration.samples.length;if(Math.abs(sampleMean-calibration.expected_emitted_bytes)>calibration.tolerance_bytes){throw new Error("observation expected_emitted_bytes is outside the calibrated sample tolerance.")}}function validateObservationTiers(tiers){if(tiers.length===0){throw new Error("observation.tiers must declare a degradation ladder.")}const tierIds=new Set;let previousTierBudget=Number.POSITIVE_INFINITY;for(const tier of tiers){assertNonEmpty(tier.id,"observation.tiers.id");assertPositiveInteger(tier.max_tokens,"observation.tiers.max_tokens");if(tierIds.has(tier.id))throw new Error(`Duplicate observation tier: ${tier.id}.`);tierIds.add(tier.id);if(tier.max_tokens>previousTierBudget){throw new Error("observation tiers must be ordered from largest to smallest max_tokens.")}previousTierBudget=tier.max_tokens;const fields=new Set;for(const field of tier.fields){parseFieldPath(field,"observation.tiers.fields");if(fields.has(field)){throw new Error(`Duplicate observation tier field: ${field}.`)}fields.add(field)}}}function defineObservationContract(declaration){if(declaration.schema!==PM_OBSERVATION_SCHEMA){throw new Error(`observation.schema must be ${PM_OBSERVATION_SCHEMA}.`)}assertNonEmpty(declaration.id,"observation.id");assertPositiveInteger(declaration.version,"observation.version");validateObservationReads(declaration.reads);validateObservationCalibration(declaration.calibration);if(declaration.corpus_dependence.kind==="bounded"){assertNonEmpty(declaration.corpus_dependence.dimension,"observation.corpus_dependence.dimension");assertPositiveInteger(declaration.corpus_dependence.maximum,"observation.corpus_dependence.maximum")}validateObservationTiers(declaration.tiers);return frozenCopy(structuredClone(declaration))}function describeObservationCost(contract){return{contract_id:contract.id,contract_version:contract.version,guaranteed_ceiling_tokens:contract.reads.reduce((total,read)=>total+read.budget_tokens,0),expected_emitted_bytes:contract.calibration.expected_emitted_bytes,expected_tokens:Math.ceil(contract.calibration.expected_emitted_bytes/4),tolerance_bytes:contract.calibration.tolerance_bytes,calibration_basis:"emitted_bytes",corpus_dependence:contract.corpus_dependence}}async function serveDeclaredObservation(contract,collect,request){assertPositiveInteger(request.budget_tokens,"observation request budget_tokens");const attempted=[];for(const[index,tier]of contract.tiers.entries()){attempted.push(tier.id);const payload=await collect(tier);const emittedBytes=Buffer.byteLength(stableStringify(payload),"utf8");const estimatedTokens=Math.ceil(emittedBytes/4);if(estimatedTokens<=Math.min(request.budget_tokens,tier.max_tokens)){return{status:"served",payload,receipt:{contract_id:contract.id,contract_version:contract.version,served_tier:tier.id,degraded:index>0,attempted_tiers:attempted,emitted_bytes:emittedBytes,estimated_tokens:estimatedTokens,calibration_basis:"emitted_bytes"}}}}return{status:"refused",reason:"no_declared_tier_fits_budget",receipt:{contract_id:contract.id,contract_version:contract.version,served_tier:null,degraded:contract.tiers.length>1,attempted_tiers:attempted,emitted_bytes:null,estimated_tokens:null,calibration_basis:"emitted_bytes"}}}function parseFieldPath(path,label){const segments=path.split(".");if(segments.some(segment=>segment.length===0||segment==="__proto__"||segment==="prototype"||segment==="constructor")){throw new Error(`${label} must be a safe, non-empty dot-separated path.`)}return segments}function valueAtPath(root,path){let value=root;for(const segment of parseFieldPath(path,"recorded field path")){if(value===null||typeof value!=="object"||!Object.hasOwn(value,segment)){return void 0}value=value[segment]}return value}function jsonPointer(path){return`/${parseFieldPath(path,"verdict predicate path").map(segment=>segment.replaceAll("~","~0").replaceAll("/","~1")).join("/")}`}function assertPortableExpectedValue(predicate){if(predicate.kind!=="field_equals")return;let serializedExpected;try{serializedExpected=JSON.stringify(predicate.expected)}catch{throw new Error(`Expected value for verdict predicate ${predicate.id} must be JSON serializable.`)}if(serializedExpected===void 0){throw new Error(`Expected value for verdict predicate ${predicate.id} must be JSON serializable.`)}}function defineVerdictContract(declaration){if(declaration.schema!==PM_VERDICT_SCHEMA){throw new Error(`verdict.schema must be ${PM_VERDICT_SCHEMA}.`)}assertNonEmpty(declaration.id,"verdict.id");assertPositiveInteger(declaration.version,"verdict.version");const predicateIds=new Set;for(const predicate of declaration.predicates){assertNonEmpty(predicate.id,"verdict.predicates.id");parseFieldPath(predicate.path,"verdict.predicates.path");const runtimeKind=predicate.kind;if(runtimeKind!=="field_equals"&&runtimeKind!=="field_present"&&runtimeKind!=="field_absent"){throw new Error(`Unsupported verdict predicate kind for ${predicate.id}.`)}if(predicateIds.has(predicate.id))throw new Error(`Duplicate verdict predicate: ${predicate.id}.`);assertPortableExpectedValue(predicate);predicateIds.add(predicate.id)}if(declaration.composition.operator!=="all"&&declaration.composition.operator!=="any"){throw new Error("verdict composition operator must be all or any.")}if(declaration.composition.predicate_ids.length!==declaration.predicates.length){throw new Error("verdict composition must reference every predicate exactly once.")}const compositionIds=new Set(declaration.composition.predicate_ids);if(compositionIds.size!==declaration.composition.predicate_ids.length||[...compositionIds].some(id=>!predicateIds.has(id))){throw new Error("verdict composition contains duplicate or unknown predicate ids.")}return frozenCopy(structuredClone(declaration))}function evaluateVerdictContract(contract,recorded){if(contract.predicates.length===0){return{contract_id:contract.id,contract_version:contract.version,snapshot_id:recorded.snapshot_id,outcome:"not_applicable",score:null,policy:"verdict_only_no_reward",reason:"no_predicates_declared",predicates:[]}}const byId=new Map(contract.predicates.map(predicate=>[predicate.id,predicate]));const predicates=contract.composition.predicate_ids.map(id=>{const predicate=byId.get(id);const observed=valueAtPath(recorded.state,predicate.path);const satisfied2=predicate.kind==="field_present"?observed!==void 0:predicate.kind==="field_absent"?observed===void 0:stableStringify(observed)===stableStringify(predicate.expected);return{id,outcome:satisfied2?"satisfied":"violated",evidence_pointer:`${recorded.snapshot_id}#${jsonPointer(predicate.path)}`,evidence_digest:sha256Hex(stableStringify(observed))}});const satisfiedCount=predicates.filter(predicate=>predicate.outcome==="satisfied").length;const satisfied=contract.composition.operator==="all"?satisfiedCount===predicates.length:satisfiedCount>0;return{contract_id:contract.id,contract_version:contract.version,snapshot_id:recorded.snapshot_id,outcome:satisfied?"satisfied":"violated",score:satisfiedCount/predicates.length,policy:"verdict_only_no_reward",predicates}}function defineEpisodeSpecification(declaration){if(declaration.schema!==PM_EPISODE_SCHEMA){throw new Error(`episode.schema must be ${PM_EPISODE_SCHEMA}.`)}assertNonEmpty(declaration.id,"episode.id");assertPositiveInteger(declaration.version,"episode.version");if(!["benchmark","evaluation","training","scale_transfer"].includes(declaration.mode)){throw new Error("episode.mode is not supported.")}if(declaration.task_item_ids.length===0){throw new Error("episode.task_item_ids must declare at least one pm item.")}for(const itemId of declaration.task_item_ids){assertNonEmpty(itemId,"episode.task_item_ids")}assertPositiveInteger(declaration.limits.max_actions,"episode.limits.max_actions");assertPositiveInteger(declaration.limits.max_observations,"episode.limits.max_observations");assertPositiveInteger(declaration.limits.max_tokens_per_observation,"episode.limits.max_tokens_per_observation");for(const field of declaration.observable_fields){parseFieldPath(field,"episode.observable_fields")}for(const field of declaration.withheld_fields){parseFieldPath(field,"episode.withheld_fields")}for(const observable of declaration.observable_fields){const overlap=declaration.withheld_fields.find(withheld=>observable===withheld||observable.startsWith(`${withheld}.`)||withheld.startsWith(`${observable}.`));if(overlap!==void 0){throw new Error(`Observable field ${observable} overlaps withheld field ${overlap}.`)}}for(const tier of declaration.observation.tiers){for(const field of tier.fields){if(!declaration.observable_fields.includes(field)){throw new Error(`Observation tier field ${field} is not declared observable.`)}}}defineObservationContract(declaration.observation);defineVerdictContract(declaration.verdict);defineWorkspaceRecipe(declaration.recipe);return frozenCopy(structuredClone(declaration))}function assignProjectedPath(target,path,value){const segments=parseFieldPath(path,"observation projection field");let cursor=target;for(const[index,segment]of segments.entries()){if(index===segments.length-1){if(value!==void 0)cursor[segment]=structuredClone(value);return}const nested=cursor[segment];if(nested===null||typeof nested!=="object"||Array.isArray(nested)){cursor[segment]={}}cursor=cursor[segment]}}function projectedState(state,fields){const result={};for(const field of fields)assignProjectedPath(result,field,valueAtPath(state,field));return result}async function openPmEpisode(specification,adapter){const trajectory=[];let actions=0;let observations=0;let closed=false;let closing;const context={episode:{id:specification.id,label:`pm agent environment v${specification.version}`},provenance:{role:specification.mode,topic:"agent-environment"}};const reset=await runWithAgentSessionContext(context,()=>adapter.reset(specification.recipe));trajectory.push({sequence:1,kind:"reset",state_id:reset.state_id});const readObservation=async()=>{if(closed)throw new Error("episode is already closed.");if(observations>=specification.limits.max_observations){throw new Error("episode exceeded limits.max_observations.")}observations+=1;const recorded=await adapter.readRecordedState();const result=await serveDeclaredObservation(specification.observation,async tier=>projectedState(recorded.state,tier.fields),{budget_tokens:specification.limits.max_tokens_per_observation});trajectory.push({sequence:trajectory.length+1,kind:"observation",state_id:result.receipt.served_tier??recorded.snapshot_id});return result};const evaluate=async(reservedForClose=false)=>{if(closed&&!reservedForClose)throw new Error("episode is already closed.");if(observations>=specification.limits.max_observations){throw new Error("episode exceeded limits.max_observations.")}observations+=1;const recorded=await adapter.readRecordedState();const result=evaluateVerdictContract(specification.verdict,recorded);trajectory.push({sequence:trajectory.length+1,kind:"verdict",state_id:recorded.snapshot_id});return result};return{observe:()=>runWithAgentSessionContext(context,readObservation),step:async action=>{if(closed)throw new Error("episode is already closed.");if(actions>=specification.limits.max_actions){throw new Error("episode exceeded limits.max_actions.")}actions+=1;const result=await runWithAgentSessionContext(context,()=>adapter.execute(action));trajectory.push({sequence:trajectory.length+1,kind:"action",state_id:result.state_id});return result},score:()=>runWithAgentSessionContext(context,evaluate),close:()=>{if(closing!==void 0)return closing;if(closed)return Promise.reject(new Error("episode is already closed."));closed=true;const operation=runWithAgentSessionContext(context,()=>evaluate(true)).then(verdict=>{trajectory.push({sequence:trajectory.length+1,kind:"close",state_id:verdict.snapshot_id});return{verdict,trajectory:frozenCopy(structuredClone(trajectory))}}).catch(error=>{closed=false;throw error});closing=operation.finally(()=>{closing=void 0});return closing}}}export{PM_EPISODE_SCHEMA,PM_OBSERVATION_SCHEMA,PM_VERDICT_SCHEMA,defineEpisodeSpecification,defineObservationContract,defineVerdictContract,describeObservationCost,evaluateVerdictContract,openPmEpisode,serveDeclaredObservation};
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="c234be1c-35b7-5388-8a70-a012e9a34389")}catch{}})();import{sha256Hex,stableStringify}from"../../core/shared/serialization.js";import{runWithAgentSessionContext}from"../agent-session-context.js";import{defineWorkspaceRecipe}from"../workspace-recipe.js";const PM_OBSERVATION_SCHEMA="pm.agent-observation/v1",PM_VERDICT_SCHEMA="pm.agent-verdict/v1",PM_EPISODE_SCHEMA="pm.agent-episode/v1";function assertPositiveInteger(value,label){if(!Number.isSafeInteger(value)||value<=0)throw new Error(`${label} must be a positive safe integer.`)}function assertNonEmpty(value,label){if(value.trim().length===0)throw new Error(`${label} must not be empty.`)}function frozenCopy(value){if(value!==null&&typeof value=="object"&&!Object.isFrozen(value)){Object.freeze(value);for(const nested of Object.values(value))frozenCopy(nested)}return value}function validateObservationReads(reads){if(reads.length===0)throw new Error("observation.reads must declare at least one bounded read.");let readCeiling=0;for(const read of reads)if(assertNonEmpty(read.command,"observation.reads.command"),assertPositiveInteger(read.budget_tokens,"observation.reads.budget_tokens"),readCeiling+=read.budget_tokens,!Number.isSafeInteger(readCeiling))throw new Error("observation read ceilings exceed safe integer range.")}function validateObservationCalibration(calibration){if(calibration.basis!=="emitted_bytes")throw new Error("observation calibration must use emitted_bytes.");for(const sample of calibration.samples)if(!Number.isSafeInteger(sample)||sample<0)throw new Error("observation calibration samples must be non-negative safe integers.");if(calibration.samples.length===0)throw new Error("observation calibration must include at least one sample.");if(assertPositiveInteger(calibration.expected_emitted_bytes,"observation.calibration.expected_emitted_bytes"),!Number.isSafeInteger(calibration.tolerance_bytes)||calibration.tolerance_bytes<0)throw new Error("observation.calibration.tolerance_bytes must be a non-negative safe integer.");const sampleMean=calibration.samples.reduce((total,sample)=>total+sample,0)/calibration.samples.length;if(Math.abs(sampleMean-calibration.expected_emitted_bytes)>calibration.tolerance_bytes)throw new Error("observation expected_emitted_bytes is outside the calibrated sample tolerance.")}function validateObservationTiers(tiers){if(tiers.length===0)throw new Error("observation.tiers must declare a degradation ladder.");const tierIds=new Set;let previousTierBudget=Number.POSITIVE_INFINITY;for(const tier of tiers){if(assertNonEmpty(tier.id,"observation.tiers.id"),assertPositiveInteger(tier.max_tokens,"observation.tiers.max_tokens"),tierIds.has(tier.id))throw new Error(`Duplicate observation tier: ${tier.id}.`);if(tierIds.add(tier.id),tier.max_tokens>previousTierBudget)throw new Error("observation tiers must be ordered from largest to smallest max_tokens.");previousTierBudget=tier.max_tokens;const fields=new Set;for(const field of tier.fields){if(parseFieldPath(field,"observation.tiers.fields"),fields.has(field))throw new Error(`Duplicate observation tier field: ${field}.`);fields.add(field)}}}function defineObservationContract(declaration){if(declaration.schema!==PM_OBSERVATION_SCHEMA)throw new Error(`observation.schema must be ${PM_OBSERVATION_SCHEMA}.`);return assertNonEmpty(declaration.id,"observation.id"),assertPositiveInteger(declaration.version,"observation.version"),validateObservationReads(declaration.reads),validateObservationCalibration(declaration.calibration),declaration.corpus_dependence.kind==="bounded"&&(assertNonEmpty(declaration.corpus_dependence.dimension,"observation.corpus_dependence.dimension"),assertPositiveInteger(declaration.corpus_dependence.maximum,"observation.corpus_dependence.maximum")),validateObservationTiers(declaration.tiers),frozenCopy(structuredClone(declaration))}function describeObservationCost(contract){return{contract_id:contract.id,contract_version:contract.version,guaranteed_ceiling_tokens:contract.reads.reduce((total,read)=>total+read.budget_tokens,0),expected_emitted_bytes:contract.calibration.expected_emitted_bytes,expected_tokens:Math.ceil(contract.calibration.expected_emitted_bytes/4),tolerance_bytes:contract.calibration.tolerance_bytes,calibration_basis:"emitted_bytes",corpus_dependence:contract.corpus_dependence}}async function serveDeclaredObservation(contract,collect,request){assertPositiveInteger(request.budget_tokens,"observation request budget_tokens");const attempted=[];for(const[index,tier]of contract.tiers.entries()){attempted.push(tier.id);const payload=await collect(tier),emittedBytes=Buffer.byteLength(stableStringify(payload),"utf8"),estimatedTokens=Math.ceil(emittedBytes/4);if(estimatedTokens<=Math.min(request.budget_tokens,tier.max_tokens))return{status:"served",payload,receipt:{contract_id:contract.id,contract_version:contract.version,served_tier:tier.id,degraded:index>0,attempted_tiers:attempted,emitted_bytes:emittedBytes,estimated_tokens:estimatedTokens,calibration_basis:"emitted_bytes"}}}return{status:"refused",reason:"no_declared_tier_fits_budget",receipt:{contract_id:contract.id,contract_version:contract.version,served_tier:null,degraded:contract.tiers.length>1,attempted_tiers:attempted,emitted_bytes:null,estimated_tokens:null,calibration_basis:"emitted_bytes"}}}function parseFieldPath(path,label){const segments=path.split(".");if(segments.some(segment=>segment.length===0||segment==="__proto__"||segment==="prototype"||segment==="constructor"))throw new Error(`${label} must be a safe, non-empty dot-separated path.`);return segments}function valueAtPath(root,path){let value=root;for(const segment of parseFieldPath(path,"recorded field path")){if(value===null||typeof value!="object"||!Object.hasOwn(value,segment))return;value=value[segment]}return value}function jsonPointer(path){return`/${parseFieldPath(path,"verdict predicate path").map(segment=>segment.replaceAll("~","~0").replaceAll("/","~1")).join("/")}`}function assertPortableExpectedValue(predicate){if(predicate.kind!=="field_equals")return;let serializedExpected;try{serializedExpected=JSON.stringify(predicate.expected)}catch{throw new Error(`Expected value for verdict predicate ${predicate.id} must be JSON serializable.`)}if(serializedExpected===void 0)throw new Error(`Expected value for verdict predicate ${predicate.id} must be JSON serializable.`)}function defineVerdictContract(declaration){if(declaration.schema!==PM_VERDICT_SCHEMA)throw new Error(`verdict.schema must be ${PM_VERDICT_SCHEMA}.`);assertNonEmpty(declaration.id,"verdict.id"),assertPositiveInteger(declaration.version,"verdict.version");const predicateIds=new Set;for(const predicate of declaration.predicates){assertNonEmpty(predicate.id,"verdict.predicates.id"),parseFieldPath(predicate.path,"verdict.predicates.path");const runtimeKind=predicate.kind;if(runtimeKind!=="field_equals"&&runtimeKind!=="field_present"&&runtimeKind!=="field_absent")throw new Error(`Unsupported verdict predicate kind for ${predicate.id}.`);if(predicateIds.has(predicate.id))throw new Error(`Duplicate verdict predicate: ${predicate.id}.`);assertPortableExpectedValue(predicate),predicateIds.add(predicate.id)}if(declaration.composition.operator!=="all"&&declaration.composition.operator!=="any")throw new Error("verdict composition operator must be all or any.");if(declaration.composition.predicate_ids.length!==declaration.predicates.length)throw new Error("verdict composition must reference every predicate exactly once.");const compositionIds=new Set(declaration.composition.predicate_ids);if(compositionIds.size!==declaration.composition.predicate_ids.length||[...compositionIds].some(id=>!predicateIds.has(id)))throw new Error("verdict composition contains duplicate or unknown predicate ids.");return frozenCopy(structuredClone(declaration))}function evaluateVerdictContract(contract,recorded){if(contract.predicates.length===0)return{contract_id:contract.id,contract_version:contract.version,snapshot_id:recorded.snapshot_id,outcome:"not_applicable",score:null,policy:"verdict_only_no_reward",reason:"no_predicates_declared",predicates:[]};const byId=new Map(contract.predicates.map(predicate=>[predicate.id,predicate])),predicates=contract.composition.predicate_ids.map(id=>{const predicate=byId.get(id),observed=valueAtPath(recorded.state,predicate.path),satisfied2=predicate.kind==="field_present"?observed!==void 0:predicate.kind==="field_absent"?observed===void 0:stableStringify(observed)===stableStringify(predicate.expected);return{id,outcome:satisfied2?"satisfied":"violated",evidence_pointer:`${recorded.snapshot_id}#${jsonPointer(predicate.path)}`,evidence_digest:sha256Hex(stableStringify(observed))}}),satisfiedCount=predicates.filter(predicate=>predicate.outcome==="satisfied").length,satisfied=contract.composition.operator==="all"?satisfiedCount===predicates.length:satisfiedCount>0;return{contract_id:contract.id,contract_version:contract.version,snapshot_id:recorded.snapshot_id,outcome:satisfied?"satisfied":"violated",score:satisfiedCount/predicates.length,policy:"verdict_only_no_reward",predicates}}function defineEpisodeSpecification(declaration){if(declaration.schema!==PM_EPISODE_SCHEMA)throw new Error(`episode.schema must be ${PM_EPISODE_SCHEMA}.`);if(assertNonEmpty(declaration.id,"episode.id"),assertPositiveInteger(declaration.version,"episode.version"),!["benchmark","evaluation","training","scale_transfer"].includes(declaration.mode))throw new Error("episode.mode is not supported.");if(declaration.task_item_ids.length===0)throw new Error("episode.task_item_ids must declare at least one pm item.");for(const itemId of declaration.task_item_ids)assertNonEmpty(itemId,"episode.task_item_ids");assertPositiveInteger(declaration.limits.max_actions,"episode.limits.max_actions"),assertPositiveInteger(declaration.limits.max_observations,"episode.limits.max_observations"),assertPositiveInteger(declaration.limits.max_tokens_per_observation,"episode.limits.max_tokens_per_observation");for(const field of declaration.observable_fields)parseFieldPath(field,"episode.observable_fields");for(const field of declaration.withheld_fields)parseFieldPath(field,"episode.withheld_fields");for(const observable of declaration.observable_fields){const overlap=declaration.withheld_fields.find(withheld=>observable===withheld||observable.startsWith(`${withheld}.`)||withheld.startsWith(`${observable}.`));if(overlap!==void 0)throw new Error(`Observable field ${observable} overlaps withheld field ${overlap}.`)}for(const tier of declaration.observation.tiers)for(const field of tier.fields)if(!declaration.observable_fields.includes(field))throw new Error(`Observation tier field ${field} is not declared observable.`);return defineObservationContract(declaration.observation),defineVerdictContract(declaration.verdict),defineWorkspaceRecipe(declaration.recipe),frozenCopy(structuredClone(declaration))}function assignProjectedPath(target,path,value){const segments=parseFieldPath(path,"observation projection field");let cursor=target;for(const[index,segment]of segments.entries()){if(index===segments.length-1){value!==void 0&&(cursor[segment]=structuredClone(value));return}const nested=cursor[segment];(nested===null||typeof nested!="object"||Array.isArray(nested))&&(cursor[segment]={}),cursor=cursor[segment]}}function projectedState(state,fields){const result={};for(const field of fields)assignProjectedPath(result,field,valueAtPath(state,field));return result}async function openPmEpisode(specification,adapter){const trajectory=[];let actions=0,observations=0,closed=!1,closing;const context={episode:{id:specification.id,label:`pm agent environment v${specification.version}`},provenance:{role:specification.mode,topic:"agent-environment"}},reset=await runWithAgentSessionContext(context,()=>adapter.reset(specification.recipe));trajectory.push({sequence:1,kind:"reset",state_id:reset.state_id});const readObservation=async()=>{if(closed)throw new Error("episode is already closed.");if(observations>=specification.limits.max_observations)throw new Error("episode exceeded limits.max_observations.");observations+=1;const recorded=await adapter.readRecordedState(),result=await serveDeclaredObservation(specification.observation,async tier=>projectedState(recorded.state,tier.fields),{budget_tokens:specification.limits.max_tokens_per_observation});return trajectory.push({sequence:trajectory.length+1,kind:"observation",state_id:result.receipt.served_tier??recorded.snapshot_id}),result},evaluate=async(reservedForClose=!1)=>{if(closed&&!reservedForClose)throw new Error("episode is already closed.");if(observations>=specification.limits.max_observations)throw new Error("episode exceeded limits.max_observations.");observations+=1;const recorded=await adapter.readRecordedState(),result=evaluateVerdictContract(specification.verdict,recorded);return trajectory.push({sequence:trajectory.length+1,kind:"verdict",state_id:recorded.snapshot_id}),result};return{observe:()=>runWithAgentSessionContext(context,readObservation),step:async action=>{if(closed)throw new Error("episode is already closed.");if(actions>=specification.limits.max_actions)throw new Error("episode exceeded limits.max_actions.");actions+=1;const result=await runWithAgentSessionContext(context,()=>adapter.execute(action));return trajectory.push({sequence:trajectory.length+1,kind:"action",state_id:result.state_id}),result},score:()=>runWithAgentSessionContext(context,evaluate),close:()=>closing!==void 0?closing:closed?Promise.reject(new Error("episode is already closed.")):(closed=!0,closing=runWithAgentSessionContext(context,()=>evaluate(!0)).then(verdict=>(trajectory.push({sequence:trajectory.length+1,kind:"close",state_id:verdict.snapshot_id}),{verdict,trajectory:frozenCopy(structuredClone(trajectory))})).catch(error=>{throw closed=!1,error}).finally(()=>{closing=void 0}),closing)}}export{PM_EPISODE_SCHEMA,PM_OBSERVATION_SCHEMA,PM_VERDICT_SCHEMA,defineEpisodeSpecification,defineObservationContract,defineVerdictContract,describeObservationCost,evaluateVerdictContract,openPmEpisode,serveDeclaredObservation};
|
|
2
2
|
//# sourceMappingURL=agent-environment.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="62b04ebf-f842-5a88-8817-ed9b17350034")}catch{}})();import{classifyHostEnvironmentFault,translateHostEnvironmentFault,withHostEnvironmentBoundary}from"../../core/fs/host-environment-errors.js";export{classifyHostEnvironmentFault,translateHostEnvironmentFault,withHostEnvironmentBoundary};
|
|
2
2
|
//# sourceMappingURL=host-environment-errors.js.map
|
|
@@ -1,2 +1,3 @@
|
|
|
1
|
-
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="7ab9180f-dfcb-579d-bc0c-dbba2e4ad77e")}catch(e2){}})();import fs from"node:fs";import path from"node:path";import{EXIT_CODE}from"../../core/shared/constants.js";import{PmCliError}from"../../core/shared/errors.js";const PACKAGE_NAME="@unbrained/pm-cli";const MUTATING_COMMANDS=new Set(["append","claim","changelog","close","close-many","close-task","comments","config","copy","create","dedupe-merge","delete","deps","docs","extension","event","events","files","focus","gc","history-author-acknowledge","history-compact","history-redact","history-repair","init","install","item","learnings","meet","merge","normalize","notes","package","packages","pause-task","plan","profile","reindex","release","remind","restore","schema","start-task","test","test-all","test-runs","test-runs-worker","telemetry","templates","twin","update","update-many","upgrade","vcs","workspace"]);const GLOBAL_VALUE_FLAGS=new Set(["--author","--output-budget","--output-format","--output-include","--output-limit","--output-session","--path","--pm-path"]);const VERSION_PATTERN=/\b(\d{4})\.(\d{1,2})\.(\d{1,2})(?:-(\d+))?\b/u;const HISTORY_ITEM_HASH_VERSION_3_INTRODUCED_IN="2026.8.31";function hasAnyToken(argv,tokens){return argv.some(token=>tokens.includes(token.split("=",1)[0]))}function isPackageMutation(argv,positionals){return["activate","adopt","adopt-all","deactivate","init","install","migrate","reload","uninstall"].includes(positionals[0]??"")||hasAnyToken(argv,["--activate","--adopt","--adopt-all","--deactivate","--fix-managed-state","--init","--install","--output","--reload","--scaffold","--uninstall"])}const MIXED_COMMAND_CLASSIFIERS={changelog:(argv,positionals)=>{if(positionals[0]==="generate")return!hasAnyToken(argv,["--check"]);const exportIndex=argv.indexOf("export");return positionals[0]==="export"&&(hasAnyToken(argv,["--output"])||exportIndex>=0&&argv[exportIndex+1]!==void 0&&!argv[exportIndex+1].startsWith("-"))},comments:argv=>hasAnyToken(argv,["--add","--delete","--edit","--file","--stdin"]),config:(_argv,positionals)=>(positionals[0]==="project"||positionals[0]==="global"?positionals[1]:positionals[0])==="set",deps:()=>false,docs:argv=>hasAnyToken(argv,["--add","--add-glob","--migrate","--remove"]),duplicates:()=>false,events:()=>false,extension:isPackageMutation,files:(argv,positionals)=>hasAnyToken(argv,["--add","--add-glob","--migrate","--remove"])||positionals[0]==="discover"&&hasAnyToken(argv,["--apply"]),health:argv=>!hasAnyToken(argv,["--check-only","--no-refresh","--skip-vectors"]),learnings:argv=>hasAnyToken(argv,["--add","--delete","--edit","--file","--stdin"]),merge:(_argv,positionals)=>positionals[0]!=="report",notes:argv=>hasAnyToken(argv,["--add","--delete","--edit","--file","--stdin"]),package:isPackageMutation,packages:isPackageMutation,profile:(_argv,positionals)=>positionals[0]==="apply",schema:(argv,positionals)=>["add-field","add-status","add-type","remove-field","remove-status","remove-type","remap-status","rename-field","rename-type"].includes(positionals[0]??"")&&!(hasAnyToken(argv,["--infer"])&&!hasAnyToken(argv,["--apply"])),telemetry:(_argv,positionals)=>positionals.slice(0,2).some(token=>["clear","flush"].includes(token)),templates:(_argv,positionals)=>positionals[0]==="save",test:argv=>hasAnyToken(argv,["--add","--add-json","--background","--measure","--remove","--resume","--run","--stop"]),validate:argv=>hasAnyToken(argv,["--auto-fix","--prune-missing"]),vcs:(_argv,positionals)=>["abandon","create","merge","propose","ref-create"].includes(positionals[0]??""),workspace:(_argv,positionals)=>positionals[0]==="snapshot"&&["create","delete","restore"].includes(positionals[1]??"")};function parseDateVersion(value){const match=value.match(VERSION_PATTERN);return match?[Number(match[1]),Number(match[2]),Number(match[3]),Number(match[4]??0)]:null}function comparePmDateVersions(left,right){const leftParts=parseDateVersion(left);const rightParts=parseDateVersion(right);if(!leftParts||!rightParts)return null;for(let index=0;index<leftParts.length;index+=1){const delta=leftParts[index]-rightParts[index];if(delta!==0)return Math.sign(delta)}return 0}function historyItemHashVersionForRuntime(version){return comparePmDateVersions(version,HISTORY_ITEM_HASH_VERSION_3_INTRODUCED_IN)!==-1?3:2}function findIncompatibleHistoryEpochPin(pins,writerItemHashVersion){if(writerItemHashVersion!==3)return void 0;return pins.filter(pin=>pin.history_epoch_compatible===false).map(pin=>({...pin,declaration:pin.declaration??pin.version})).sort((left,right)=>comparePmDateVersions(left.version,right.version))[0]}function readJsonRecord(filePath){try{const parsed=JSON.parse(fs.readFileSync(filePath,"utf8"));return typeof parsed==="object"&&parsed!==null&&!Array.isArray(parsed)?parsed:null}catch{return null}}function rangeUpperBounds(alternative){const comparators=[...alternative.matchAll(/(<=|<)\s*v?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/gu)].map(match=>({inclusive:match[1]==="<=",version:match[2]}));const hyphen=alternative.match(/\b\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?\s+-\s+v?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/u);return hyphen?[...comparators,{inclusive:true,version:hyphen[1]}]:comparators}function analyzeHistoryEpochRange(specification){const alternativeBounds=specification.split("||").map(alternative=>rangeUpperBounds(alternative));return{bounded:alternativeBounds.some(bounds=>bounds.length>0),compatible:alternativeBounds.some(bounds=>bounds.every(bound=>{const comparison=comparePmDateVersions(HISTORY_ITEM_HASH_VERSION_3_INTRODUCED_IN,bound.version);return comparison!==null&&(bound.inclusive?comparison!==1:comparison===-1)}))}}function dependencyPins(packageJson){return["dependencies","devDependencies","optionalDependencies","peerDependencies"].flatMap(field=>{const dependencies=packageJson[field];if(typeof dependencies!=="object"||dependencies===null)return[];const value=dependencies[PACKAGE_NAME];const specification=typeof value==="string"?value.trim():"";const version=/^[<!]/u.test(specification)?void 0:specification.match(VERSION_PATTERN)?.[0];if(!version)return[];const exact=/^(?:=|v)?\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?$/u.test(specification);const range=analyzeHistoryEpochRange(specification);return[{version,constraint:exact?"exact":range.bounded?"range":"minimum",...exact?{}:{declaration:specification},history_epoch_compatible:exact?comparePmDateVersions(version,HISTORY_ITEM_HASH_VERSION_3_INTRODUCED_IN)!==-1:range.compatible}]})}function packageLockPin(projectRoot){const lock=readJsonRecord(path.join(projectRoot,"package-lock.json"));const packages=lock?.packages;if(typeof packages!=="object"||packages===null)return void 0;const installed=packages["node_modules/@unbrained/pm-cli"];if(typeof installed!=="object"||installed===null)return void 0;const version=installed.version;return typeof version==="string"?version:void 0}function textLockPin(projectRoot,file){try{const lines=fs.readFileSync(path.join(projectRoot,file),"utf8").split(/\r?\n/u);const packageLineIndex=lines.findIndex(line=>line.includes(PACKAGE_NAME));if(packageLineIndex<0)return void 0;const packageIndent=lines[packageLineIndex].match(/^\s*/u)[0].length;const entry=[lines[packageLineIndex]];for(let index=packageLineIndex+1;index<lines.length;index+=1){const line=lines[index];const trimmed=line.trim();const indent=line.match(/^\s*/u)[0].length;if(trimmed.length>0&&indent<=packageIndent)break;entry.push(line)}const entrySource=entry.join("\n");const explicitVersion=entrySource.match(/^\s*version(?::\s*|\s+)["']?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/mu)?.[1];return explicitVersion??entry[0].match(VERSION_PATTERN)?.[0]}catch{return void 0}}function discoverProjectRuntimeVersionPins(projectRoot){const pins=[];const projectPackage=readJsonRecord(path.join(projectRoot,"package.json"));if(projectPackage){pins.push(...dependencyPins(projectPackage).map(pin=>({...pin,source:"package.json"})))}const installedPackage=readJsonRecord(path.join(projectRoot,"node_modules","@unbrained","pm-cli","package.json"));const installedVersion=installedPackage?.version;if(typeof installedVersion==="string"&&parseDateVersion(installedVersion)){pins.push({version:installedVersion,source:"installed-package",constraint:"exact",history_epoch_compatible:historyItemHashVersionForRuntime(installedVersion)===3})}const packageLockVersion=packageLockPin(projectRoot);if(packageLockVersion&&parseDateVersion(packageLockVersion)){pins.push({version:packageLockVersion,source:"package-lock.json",constraint:"exact",history_epoch_compatible:historyItemHashVersionForRuntime(packageLockVersion)===3})}for(const file of["pnpm-lock.yaml","yarn.lock"]){const version=textLockPin(projectRoot,file);if(version){pins.push({version,source:file,constraint:"exact",history_epoch_compatible:historyItemHashVersionForRuntime(version)===3})}}return pins}function commandTokenFromArgv(argv){for(let index=0;index<argv.length;index+=1){const token=argv[index];if(GLOBAL_VALUE_FLAGS.has(token)){index+=1;continue}if(!token.startsWith("-"))return{command:token.toLowerCase(),index}}return void 0}function isProjectMutatingInvocation(argv){const commandToken=commandTokenFromArgv(argv);if(!commandToken)return false;if(hasAnyToken(argv,["--help","-h","--dry-run"]))return false;const{command,index:commandIndex}=commandToken;const positionals=[];for(let index=commandIndex+1;index<argv.length;index+=1){const token=argv[index];if(GLOBAL_VALUE_FLAGS.has(token)){index+=1;continue}if(!token.startsWith("-"))positionals.push(token.toLowerCase())}const mixedClassifier=MIXED_COMMAND_CLASSIFIERS[command];return mixedClassifier?mixedClassifier(argv,positionals):MUTATING_COMMANDS.has(command)}function inspectProjectRuntimeCompatibility(options){const command=commandTokenFromArgv(options.argv)?.command;const mutating=isProjectMutatingInvocation(options.argv);const pins=discoverProjectRuntimeVersionPins(options.projectRoot).filter(pin=>comparePmDateVersions(pin.version,options.executingVersion)!==null).sort((left,right)=>comparePmDateVersions(right.version,left.version));const newest=pins[0];const stale=newest!==void 0&&comparePmDateVersions(options.executingVersion,newest.version)===-1;const writerItemHashVersion=historyItemHashVersionForRuntime(options.executingVersion);const incompatibleEpochPin=findIncompatibleHistoryEpochPin(pins,writerItemHashVersion);const historyEpochIncompatible=mutating&&incompatibleEpochPin!==void 0;const warning=stale&&!mutating?{code:"project_runtime_stale_read",executing_version:options.executingVersion,project_version:newest.version,source:newest.source,message:"This read is using an older pm runtime than the project requires.",next_steps:[`Run the command through the project's installed ${PACKAGE_NAME} ${newest.version}.`,"Install the project dependencies with its declared package manager if the local executable is missing."]}:void 0;return{compatible:!mutating||!stale&&!historyEpochIncompatible||options.allowStale===true,executing_version:options.executingVersion,...newest?{project_version:newest.version,source:newest.source}:{},...command?{command}:{},mutating,stale,history_epoch_incompatible:historyEpochIncompatible,writer_item_hash_version:writerItemHashVersion,...incompatibleEpochPin?{incompatible_project_version:incompatibleEpochPin.declaration,incompatible_source:incompatibleEpochPin.source}:{},...warning?{warning}:{},override_applied:mutating&&(stale||historyEpochIncompatible)&&options.allowStale===true}}function assertProjectRuntimeCompatibility(options){const result=inspectProjectRuntimeCompatibility(options);if(result.compatible)return result;if(result.history_epoch_incompatible){throw new PmCliError(`pm ${result.executing_version} cannot write item-hash epoch ${result.writer_item_hash_version} into a project pinned to pm ${result.incompatible_project_version}.`,EXIT_CODE.CONFLICT,{code:"project_runtime_history_epoch_incompatible",reason:result.incompatible_source,why:`The pinned runtime cannot read item_hash_version ${result.writer_item_hash_version}; allowing the write would break its health and validation gates.`,nextSteps:[`Upgrade the project's ${PACKAGE_NAME} pin to ${HISTORY_ITEM_HASH_VERSION_3_INTRODUCED_IN} or newer before mutating tracker history.`,"For an intentional coordinated migration only, set PM_ALLOW_STALE_CLI=1 for this invocation and record why.","Read-only commands remain available without an override."]})}throw new PmCliError(`pm ${result.executing_version} cannot mutate a project pinned to newer pm ${result.project_version}.`,EXIT_CODE.CONFLICT,{code:"project_runtime_stale_mutation",reason:result.source,why:"An older runtime can write storage, history, and merge contracts it does not understand.",nextSteps:[`Run this command through the project's installed ${PACKAGE_NAME} ${result.project_version}.`,"For an intentional recovery only, set PM_ALLOW_STALE_CLI=1 for this invocation and record why.","Read-only commands remain available without an override."]})}export{HISTORY_ITEM_HASH_VERSION_3_INTRODUCED_IN,PmCliError,assertProjectRuntimeCompatibility,comparePmDateVersions,discoverProjectRuntimeVersionPins,historyItemHashVersionForRuntime,inspectProjectRuntimeCompatibility,isProjectMutatingInvocation};
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="2d40ac36-0627-5636-9679-5669dbacf06b")}catch{}})();import fs from"node:fs";import path from"node:path";import{EXIT_CODE}from"../../core/shared/constants.js";import{PmCliError}from"../../core/shared/errors.js";const PACKAGE_NAME="@unbrained/pm-cli",MUTATING_COMMANDS=new Set(["append","claim","changelog","close","close-many","close-task","comments","config","copy","create","dedupe-merge","delete","deps","docs","extension","event","events","files","focus","gc","history-author-acknowledge","history-compact","history-redact","history-repair","init","install","item","learnings","meet","merge","normalize","notes","package","packages","pause-task","plan","profile","reindex","release","remind","restore","schema","start-task","test","test-all","test-runs","test-runs-worker","telemetry","templates","twin","update","update-many","upgrade","vcs","workspace"]),GLOBAL_VALUE_FLAGS=new Set(["--author","--output-budget","--output-format","--output-include","--output-limit","--output-session","--path","--pm-path"]),VERSION_PATTERN=/\b(\d{4})\.(\d{1,2})\.(\d{1,2})(?:-(\d+))?\b/u,HISTORY_ITEM_HASH_VERSION_3_INTRODUCED_IN="2026.8.31";function hasAnyToken(argv,tokens){return argv.some(token=>tokens.includes(token.split("=",1)[0]))}function isPackageMutation(argv,positionals){return["activate","adopt","adopt-all","deactivate","init","install","migrate","reload","uninstall"].includes(positionals[0]??"")||hasAnyToken(argv,["--activate","--adopt","--adopt-all","--deactivate","--fix-managed-state","--init","--install","--output","--reload","--scaffold","--uninstall"])}const MIXED_COMMAND_CLASSIFIERS={changelog:(argv,positionals)=>{if(positionals[0]==="generate")return!hasAnyToken(argv,["--check"]);const exportIndex=argv.indexOf("export");return positionals[0]==="export"&&(hasAnyToken(argv,["--output"])||exportIndex>=0&&argv[exportIndex+1]!==void 0&&!argv[exportIndex+1].startsWith("-"))},comments:argv=>hasAnyToken(argv,["--add","--delete","--edit","--file","--stdin"]),config:(_argv,positionals)=>(positionals[0]==="project"||positionals[0]==="global"?positionals[1]:positionals[0])==="set",deps:()=>!1,docs:argv=>hasAnyToken(argv,["--add","--add-glob","--migrate","--remove"]),duplicates:()=>!1,events:()=>!1,extension:isPackageMutation,files:(argv,positionals)=>hasAnyToken(argv,["--add","--add-glob","--migrate","--remove"])||positionals[0]==="discover"&&hasAnyToken(argv,["--apply"]),health:argv=>!hasAnyToken(argv,["--check-only","--no-refresh","--skip-vectors"]),learnings:argv=>hasAnyToken(argv,["--add","--delete","--edit","--file","--stdin"]),merge:(_argv,positionals)=>positionals[0]!=="report",notes:argv=>hasAnyToken(argv,["--add","--delete","--edit","--file","--stdin"]),package:isPackageMutation,packages:isPackageMutation,profile:(_argv,positionals)=>positionals[0]==="apply",schema:(argv,positionals)=>["add-field","add-status","add-type","remove-field","remove-status","remove-type","remap-status","rename-field","rename-type"].includes(positionals[0]??"")&&!(hasAnyToken(argv,["--infer"])&&!hasAnyToken(argv,["--apply"])),telemetry:(_argv,positionals)=>positionals.slice(0,2).some(token=>["clear","flush"].includes(token)),templates:(_argv,positionals)=>positionals[0]==="save",test:argv=>hasAnyToken(argv,["--add","--add-json","--background","--measure","--remove","--resume","--run","--stop"]),validate:argv=>hasAnyToken(argv,["--auto-fix","--prune-missing"]),vcs:(_argv,positionals)=>["abandon","create","merge","propose","ref-create"].includes(positionals[0]??""),workspace:(_argv,positionals)=>positionals[0]==="snapshot"&&["create","delete","restore"].includes(positionals[1]??"")};function parseDateVersion(value){const match=value.match(VERSION_PATTERN);return match?[Number(match[1]),Number(match[2]),Number(match[3]),Number(match[4]??0)]:null}function comparePmDateVersions(left,right){const leftParts=parseDateVersion(left),rightParts=parseDateVersion(right);if(!leftParts||!rightParts)return null;for(let index=0;index<leftParts.length;index+=1){const delta=leftParts[index]-rightParts[index];if(delta!==0)return Math.sign(delta)}return 0}function historyItemHashVersionForRuntime(version){return comparePmDateVersions(version,HISTORY_ITEM_HASH_VERSION_3_INTRODUCED_IN)!==-1?3:2}function findIncompatibleHistoryEpochPin(pins,writerItemHashVersion){if(writerItemHashVersion===3)return pins.filter(pin=>pin.history_epoch_compatible===!1).map(pin=>({...pin,declaration:pin.declaration??pin.version})).sort((left,right)=>comparePmDateVersions(left.version,right.version))[0]}function readJsonRecord(filePath){try{const parsed=JSON.parse(fs.readFileSync(filePath,"utf8"));return typeof parsed=="object"&&parsed!==null&&!Array.isArray(parsed)?parsed:null}catch{return null}}function rangeUpperBounds(alternative){const comparators=[...alternative.matchAll(/(<=|<)\s*v?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/gu)].map(match=>({inclusive:match[1]==="<=",version:match[2]})),hyphen=alternative.match(/\b\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?\s+-\s+v?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/u);return hyphen?[...comparators,{inclusive:!0,version:hyphen[1]}]:comparators}function analyzeHistoryEpochRange(specification){const alternativeBounds=specification.split("||").map(alternative=>rangeUpperBounds(alternative));return{bounded:alternativeBounds.some(bounds=>bounds.length>0),compatible:alternativeBounds.some(bounds=>bounds.every(bound=>{const comparison=comparePmDateVersions(HISTORY_ITEM_HASH_VERSION_3_INTRODUCED_IN,bound.version);return comparison!==null&&(bound.inclusive?comparison!==1:comparison===-1)}))}}function dependencyPins(packageJson){return["dependencies","devDependencies","optionalDependencies","peerDependencies"].flatMap(field=>{const dependencies=packageJson[field];if(typeof dependencies!="object"||dependencies===null)return[];const value=dependencies[PACKAGE_NAME],specification=typeof value=="string"?value.trim():"",version=/^[<!]/u.test(specification)?void 0:specification.match(VERSION_PATTERN)?.[0];if(!version)return[];const exact=/^(?:=|v)?\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?$/u.test(specification),range=analyzeHistoryEpochRange(specification);return[{version,constraint:exact?"exact":range.bounded?"range":"minimum",...exact?{}:{declaration:specification},history_epoch_compatible:exact?comparePmDateVersions(version,HISTORY_ITEM_HASH_VERSION_3_INTRODUCED_IN)!==-1:range.compatible}]})}function packageLockPin(projectRoot){const packages=readJsonRecord(path.join(projectRoot,"package-lock.json"))?.packages;if(typeof packages!="object"||packages===null)return;const installed=packages["node_modules/@unbrained/pm-cli"];if(typeof installed!="object"||installed===null)return;const version=installed.version;return typeof version=="string"?version:void 0}function textLockPin(projectRoot,file){try{const lines=fs.readFileSync(path.join(projectRoot,file),"utf8").split(/\r?\n/u),packageLineIndex=lines.findIndex(line=>line.includes(PACKAGE_NAME));if(packageLineIndex<0)return;const packageIndent=lines[packageLineIndex].match(/^\s*/u)[0].length,entry=[lines[packageLineIndex]];for(let index=packageLineIndex+1;index<lines.length;index+=1){const line=lines[index],trimmed=line.trim(),indent=line.match(/^\s*/u)[0].length;if(trimmed.length>0&&indent<=packageIndent)break;entry.push(line)}return entry.join(`
|
|
2
|
+
`).match(/^\s*version(?::\s*|\s+)["']?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/mu)?.[1]??entry[0].match(VERSION_PATTERN)?.[0]}catch{return}}function discoverProjectRuntimeVersionPins(projectRoot){const pins=[],projectPackage=readJsonRecord(path.join(projectRoot,"package.json"));projectPackage&&pins.push(...dependencyPins(projectPackage).map(pin=>({...pin,source:"package.json"})));const installedVersion=readJsonRecord(path.join(projectRoot,"node_modules","@unbrained","pm-cli","package.json"))?.version;typeof installedVersion=="string"&&parseDateVersion(installedVersion)&&pins.push({version:installedVersion,source:"installed-package",constraint:"exact",history_epoch_compatible:historyItemHashVersionForRuntime(installedVersion)===3});const packageLockVersion=packageLockPin(projectRoot);packageLockVersion&&parseDateVersion(packageLockVersion)&&pins.push({version:packageLockVersion,source:"package-lock.json",constraint:"exact",history_epoch_compatible:historyItemHashVersionForRuntime(packageLockVersion)===3});for(const file of["pnpm-lock.yaml","yarn.lock"]){const version=textLockPin(projectRoot,file);version&&pins.push({version,source:file,constraint:"exact",history_epoch_compatible:historyItemHashVersionForRuntime(version)===3})}return pins}function commandTokenFromArgv(argv){for(let index=0;index<argv.length;index+=1){const token=argv[index];if(GLOBAL_VALUE_FLAGS.has(token)){index+=1;continue}if(!token.startsWith("-"))return{command:token.toLowerCase(),index}}}function isProjectMutatingInvocation(argv){const commandToken=commandTokenFromArgv(argv);if(!commandToken||hasAnyToken(argv,["--help","-h","--dry-run"]))return!1;const{command,index:commandIndex}=commandToken,positionals=[];for(let index=commandIndex+1;index<argv.length;index+=1){const token=argv[index];if(GLOBAL_VALUE_FLAGS.has(token)){index+=1;continue}token.startsWith("-")||positionals.push(token.toLowerCase())}const mixedClassifier=MIXED_COMMAND_CLASSIFIERS[command];return mixedClassifier?mixedClassifier(argv,positionals):MUTATING_COMMANDS.has(command)}function inspectProjectRuntimeCompatibility(options){const command=commandTokenFromArgv(options.argv)?.command,mutating=isProjectMutatingInvocation(options.argv),pins=discoverProjectRuntimeVersionPins(options.projectRoot).filter(pin=>comparePmDateVersions(pin.version,options.executingVersion)!==null).sort((left,right)=>comparePmDateVersions(right.version,left.version)),newest=pins[0],stale=newest!==void 0&&comparePmDateVersions(options.executingVersion,newest.version)===-1,writerItemHashVersion=historyItemHashVersionForRuntime(options.executingVersion),incompatibleEpochPin=findIncompatibleHistoryEpochPin(pins,writerItemHashVersion),historyEpochIncompatible=mutating&&incompatibleEpochPin!==void 0,warning=stale&&!mutating?{code:"project_runtime_stale_read",executing_version:options.executingVersion,project_version:newest.version,source:newest.source,message:"This read is using an older pm runtime than the project requires.",next_steps:[`Run the command through the project's installed ${PACKAGE_NAME} ${newest.version}.`,"Install the project dependencies with its declared package manager if the local executable is missing."]}:void 0;return{compatible:!mutating||!stale&&!historyEpochIncompatible||options.allowStale===!0,executing_version:options.executingVersion,...newest?{project_version:newest.version,source:newest.source}:{},...command?{command}:{},mutating,stale,history_epoch_incompatible:historyEpochIncompatible,writer_item_hash_version:writerItemHashVersion,...incompatibleEpochPin?{incompatible_project_version:incompatibleEpochPin.declaration,incompatible_source:incompatibleEpochPin.source}:{},...warning?{warning}:{},override_applied:mutating&&(stale||historyEpochIncompatible)&&options.allowStale===!0}}function assertProjectRuntimeCompatibility(options){const result=inspectProjectRuntimeCompatibility(options);if(result.compatible)return result;throw result.history_epoch_incompatible?new PmCliError(`pm ${result.executing_version} cannot write item-hash epoch ${result.writer_item_hash_version} into a project pinned to pm ${result.incompatible_project_version}.`,EXIT_CODE.CONFLICT,{code:"project_runtime_history_epoch_incompatible",reason:result.incompatible_source,why:`The pinned runtime cannot read item_hash_version ${result.writer_item_hash_version}; allowing the write would break its health and validation gates.`,nextSteps:[`Upgrade the project's ${PACKAGE_NAME} pin to ${HISTORY_ITEM_HASH_VERSION_3_INTRODUCED_IN} or newer before mutating tracker history.`,"For an intentional coordinated migration only, set PM_ALLOW_STALE_CLI=1 for this invocation and record why.","Read-only commands remain available without an override."]}):new PmCliError(`pm ${result.executing_version} cannot mutate a project pinned to newer pm ${result.project_version}.`,EXIT_CODE.CONFLICT,{code:"project_runtime_stale_mutation",reason:result.source,why:"An older runtime can write storage, history, and merge contracts it does not understand.",nextSteps:[`Run this command through the project's installed ${PACKAGE_NAME} ${result.project_version}.`,"For an intentional recovery only, set PM_ALLOW_STALE_CLI=1 for this invocation and record why.","Read-only commands remain available without an override."]})}export{HISTORY_ITEM_HASH_VERSION_3_INTRODUCED_IN,PmCliError,assertProjectRuntimeCompatibility,comparePmDateVersions,discoverProjectRuntimeVersionPins,historyItemHashVersionForRuntime,inspectProjectRuntimeCompatibility,isProjectMutatingInvocation};
|
|
2
3
|
//# sourceMappingURL=project-runtime-compatibility.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="6d1f8e03-97b4-5d83-b85c-e47f39c07d48")}catch{}})();const SOURCE_CONTEXT_ACCESS_ENV="PM_SOURCE_CONTEXT_ACCESS",SOURCE_CONTEXT_WRITE_OVERRIDE_ENV="PM_ALLOW_SOURCE_CONTEXT_WRITES";function resolveSourceContextWritePolicy(environment){const declaredAccess=environment[SOURCE_CONTEXT_ACCESS_ENV],access=declaredAccess===void 0||declaredAccess.trim().toLowerCase()==="write"?"write":"read_only",writeOverrideApplied=access==="read_only"&&environment[SOURCE_CONTEXT_WRITE_OVERRIDE_ENV]?.trim()==="1";return{access,write_override_applied:writeOverrideApplied,source_writes_allowed:access==="write"||writeOverrideApplied}}export{SOURCE_CONTEXT_ACCESS_ENV,SOURCE_CONTEXT_WRITE_OVERRIDE_ENV,resolveSourceContextWritePolicy};
|
|
2
2
|
//# sourceMappingURL=source-context.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="5c8194ff-d877-51b8-bd54-d206f85a979c")}catch{}})();import{assertInitializedTracker,assertReadableTrackerRoot,buildTrackerInitializationRecovery}from"../../core/store/tracker-preflight.js";export{assertInitializedTracker,assertReadableTrackerRoot,buildTrackerInitializationRecovery};
|
|
2
2
|
//# sourceMappingURL=tracker-preflight.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="7df4fe91-e8a4-540f-8737-c67f2efa460e")}catch{}})();const PM_ERROR_CODE_EXIT_CLASS_CONTRACTS=[{exit_code:1,class:"generic_failure"},{exit_code:2,class:"usage"},{exit_code:3,class:"not_found"},{exit_code:4,class:"conflict"},{exit_code:5,class:"dependency_failed"}],ERROR_CLASS_BY_EXIT_CODE=new Map(PM_ERROR_CODE_EXIT_CLASS_CONTRACTS.map(contract=>[contract.exit_code,contract.class]));function normalizeContractList(values){return[...new Set(values.map(value=>value.trim()).filter(Boolean))].sort()}function normalizeOwnedStates(states){if(!states)return[];const seenStates=new Set,seenProbes=new Set;return states.map(state=>{const normalizedState=state.state.trim(),probeId=state.probe_id.trim(),entrypoints=normalizeContractList(state.entrypoints);if(!/^[a-z][a-z0-9_]*$/.test(normalizedState)||!/^[a-z][a-z0-9-]*$/.test(probeId)||entrypoints.length===0||seenStates.has(normalizedState)||seenProbes.has(probeId))throw new TypeError("Invalid pm refusal state contract");return seenStates.add(normalizedState),seenProbes.add(probeId),{state:normalizedState,probe_id:probeId,entrypoints,expected_exit_class:state.expected_exit_class}}).sort((left,right)=>left.state.localeCompare(right.state))}function isValidNormalizedErrorCodeContract(declaration,sources,emittingCommands,canonicalCode,aliases){return![[1,2,3,4,5].includes(declaration.exit_code),declaration.meaning.trim().length>0,declaration.recovery.trim().length>0,sources.length>0,emittingCommands.length>0,/^[a-z][a-z0-9_]*$/.test(canonicalCode),aliases.every(alias=>/^[a-z][a-z0-9_]*$/.test(alias)),ERROR_CLASS_BY_EXIT_CODE.get(declaration.exit_code)===declaration.class].includes(!1)}function resolveCanonicalErrorCodeDeclaration(declaration,byCode){let current=declaration;const path=new Set;for(;current.canonical_code!==current.code;){if(path.has(current.code))throw new TypeError(`Alias cycle in pm error code catalog: ${declaration.code}`);path.add(current.code);const target=byCode.get(current.canonical_code);if(!target)throw new TypeError(`Invalid pm error code contract: ${declaration.code}`);current=target}return current}function validateErrorCodeAliases(declarations){const byCode=new Map(declarations.map(entry=>[entry.code,entry]));for(const declaration of declarations){const canonical=resolveCanonicalErrorCodeDeclaration(declaration,byCode);if(canonical.exit_code!==declaration.exit_code||canonical.class!==declaration.class)throw new TypeError(`Alias transport mismatch for pm error code: ${declaration.code}`);const expectedAliases=declarations.filter(candidate=>candidate.code!==canonical.code&&candidate.canonical_code===canonical.code).map(candidate=>candidate.code).sort();if(declaration.code===canonical.code?JSON.stringify(declaration.aliases)!==JSON.stringify(expectedAliases):declaration.aliases.length>0)throw new TypeError(`Invalid pm error code contract: ${declaration.code}`)}}function definePmErrorCodeCatalog(declarations){const seen=new Set,normalized=declarations.map(declaration=>{const code=declaration.code.trim();if(!/^[a-z][a-z0-9_]*$/.test(code))throw new TypeError(`Invalid pm error code: ${JSON.stringify(declaration.code)}`);if(seen.has(code))throw new TypeError(`Duplicate pm error code: ${code}`);seen.add(code);const sources=normalizeContractList(declaration.sources),emittingCommands=normalizeContractList(declaration.emitting_commands),canonicalCode=(declaration.canonical_code??code).trim(),aliases=normalizeContractList(declaration.aliases??[]),ownedStates=normalizeOwnedStates(declaration.owned_states);if(!isValidNormalizedErrorCodeContract(declaration,sources,emittingCommands,canonicalCode,aliases))throw new TypeError(`Invalid pm error code contract: ${code}`);if(ownedStates.some(state=>state.expected_exit_class!==declaration.class))throw new TypeError(`Invalid pm refusal state exit class: ${code}`);return Object.freeze({...declaration,code,meaning:declaration.meaning.trim(),recovery:declaration.recovery.trim(),sources,emitting_commands:emittingCommands,canonical_code:canonicalCode,aliases,owned_states:ownedStates})});return validateErrorCodeAliases(normalized),Object.freeze(normalized.sort((left,right)=>left.code.localeCompare(right.code)))}function resolveCanonicalPmErrorCodeContract(code,catalog){const emitted=resolvePmErrorCodeContract(code,catalog);return resolvePmErrorCodeContract(emitted.canonical_code??emitted.code,catalog)}function resolvePmErrorCodeContract(code,catalog){const normalized=code.trim(),contract=catalog.find(entry=>entry.code===normalized);if(!contract)throw new TypeError(`Unknown pm error code "${normalized}"`);return contract}export{PM_ERROR_CODE_EXIT_CLASS_CONTRACTS,definePmErrorCodeCatalog,resolveCanonicalPmErrorCodeContract,resolvePmErrorCodeContract};
|
|
2
2
|
//# sourceMappingURL=error-code-catalog.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="be9abae1-85ae-5a68-96bc-c738218ace5e")}catch{}})();import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";function describeUnknownError(error){return error instanceof PmCliError||error instanceof Error?error.message:"Unknown failure"}function readThrownExitCode(error){if(typeof error!="object"||error===null||!("exitCode"in error))return;const exitCode=error.exitCode;return typeof exitCode=="number"&&Number.isFinite(exitCode)?exitCode:void 0}function normalizeThrownExitCode(exitCode){const normalized=Math.trunc(exitCode);return normalized>EXIT_CODE.SUCCESS?normalized:EXIT_CODE.GENERIC_FAILURE}function isCommanderError(error){return typeof error=="object"&&error!==null&&"code"in error&&typeof error.code=="string"&&error.code.startsWith("commander.")}function wrapThrownErrorForSentry(error,message){if(error instanceof Error)return error;const wrapped=new Error(message),exitCode=readThrownExitCode(error);return exitCode!==void 0&&(wrapped.exitCode=normalizeThrownExitCode(exitCode)),wrapped}export{describeUnknownError,isCommanderError,normalizeThrownExitCode,readThrownExitCode,wrapThrownErrorForSentry};
|
|
2
2
|
//# sourceMappingURL=error-runtime.js.map
|
package/dist/sdk/errors.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="c08374a3-4ac6-5f9a-be69-0ac9839bba39")}catch{}})();import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";const PM_CLI_EXPECTED_ERROR_NAME="PmCliError";function normalizeExpectedErrorExitCode(value){if(!Number.isFinite(value))throw new TypeError("createPmCliExpectedError options.exitCode must be a finite number");const normalized=Math.trunc(value);if(normalized<=EXIT_CODE.SUCCESS)throw new TypeError("createPmCliExpectedError options.exitCode must be a positive exit code");return normalized}function createPmCliExpectedError(message,options={}){if(typeof message!="string"||message.trim().length===0)throw new TypeError("createPmCliExpectedError message must be a non-empty string");const error=new PmCliError(message,normalizeExpectedErrorExitCode(options.exitCode??EXIT_CODE.USAGE),options.context??{});return"cause"in options&&Object.defineProperty(error,"cause",{value:options.cause,enumerable:!1,configurable:!0,writable:!0}),error}function isPmCliExpectedError(error){if(!(error instanceof Error)||error.name!==PM_CLI_EXPECTED_ERROR_NAME)return!1;const candidate=error;return typeof candidate.exitCode=="number"&&Number.isFinite(candidate.exitCode)}export{PM_CLI_EXPECTED_ERROR_NAME,createPmCliExpectedError,isPmCliExpectedError};
|
|
2
2
|
//# sourceMappingURL=errors.js.map
|
package/dist/sdk/eval.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="5d26721c-719a-5c7e-8baf-72cbf1088988")}catch{}})();import{evaluateMetricFloors}from"../core/search/eval-thresholds.js";import{assertInitializedTracker}from"./environment/tracker-preflight.js";import fs from"node:fs/promises";import path from"node:path";import{aggregateEvalMetrics,DEFAULT_EVAL_K,EVAL_QUERY_SET_EXAMPLE,EVAL_QUERY_SET_SCHEMA_ID,evaluateRanking,parseEvalQuerySet}from"../core/search/eval.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{coercePositiveInteger}from"../core/shared/primitives.js";import{resolvePmRoot}from"../core/store/paths.js";import{runSearch}from"./query/search.js";import{EVAL_QUERY_SET_CONTRACT,EVAL_QUERY_SET_EXAMPLE as EVAL_QUERY_SET_EXAMPLE2,EVAL_QUERY_SET_SCHEMA_ID as EVAL_QUERY_SET_SCHEMA_ID2,parseEvalQuerySet as parseEvalQuerySet2}from"../core/search/eval.js";const DEFAULT_EVAL_QUERIES_RELATIVE_PATH=path.join("search","eval-queries.json"),EVAL_QUERY_SET_ERROR_CONTEXT={schema:EVAL_QUERY_SET_SCHEMA_ID,examples:[JSON.stringify(EVAL_QUERY_SET_EXAMPLE)],nextSteps:["Create a git-tracked golden-query JSON file that follows the schema, then re-run pm eval."]},VALID_EVAL_MODES=new Set(["keyword","semantic","hybrid"]),parseEvalMode=raw=>{if(raw===void 0)return"keyword";const normalized=raw.trim().toLowerCase();if(!VALID_EVAL_MODES.has(normalized))throw new PmCliError("Eval --mode must be one of keyword|semantic|hybrid",EXIT_CODE.USAGE);return normalized},parseEvalK=raw=>{if(raw===void 0||raw==="")return DEFAULT_EVAL_K;const parsed=coercePositiveInteger(raw);if(parsed===null)throw new PmCliError("Eval --k must be a positive integer",EXIT_CODE.USAGE);return parsed},parseFailUnder=raw=>{if(raw===void 0||raw==="")return;const normalized=String(raw).trim(),parsed=Number(normalized);if([normalized.length===0,!Number.isFinite(parsed),parsed<0,parsed>1].includes(!0))throw new PmCliError("Eval --fail-under must be a number in the range [0, 1]",EXIT_CODE.USAGE);return parsed},roundMetric=value=>Math.round(value*1e4)/1e4,readEvalQuerySetFile=async queriesPath=>{try{return await fs.readFile(queriesPath,"utf8")}catch{throw new PmCliError(`Eval query set not found at ${queriesPath}`,EXIT_CODE.NOT_FOUND,{...EVAL_QUERY_SET_ERROR_CONTEXT,examples:[`echo '${JSON.stringify(EVAL_QUERY_SET_EXAMPLE)}' > ${queriesPath}`,"pm eval --queries ./my-eval.json"]})}},parseEvalQuerySetJson=(raw,queriesPath)=>{try{return JSON.parse(raw)}catch(error){throw new PmCliError(`Eval query set at ${queriesPath} is not valid JSON: ${error instanceof Error?error.message:String(error)}`,EXIT_CODE.USAGE,EVAL_QUERY_SET_ERROR_CONTEXT)}},validateEvalQuerySet=parsed=>{try{return parseEvalQuerySet(parsed)}catch(error){throw new PmCliError(error instanceof Error?error.message:String(error),EXIT_CODE.USAGE,EVAL_QUERY_SET_ERROR_CONTEXT)}},loadEvalQuerySet=async queriesPath=>validateEvalQuerySet(parseEvalQuerySetJson(await readEvalQuerySetFile(queriesPath),queriesPath)),evaluateEvalQuery=async(evalQuery,defaultMode,k,global2)=>{const mode=evalQuery.mode??defaultMode,rankedIds=(await runSearch(evalQuery.query,{mode,limit:String(k),fields:"id"},global2)).items.map(item=>item.id).filter(id=>typeof id=="string"),metrics=evaluateRanking(rankedIds,new Set(evalQuery.relevant_ids),k);return{metrics,report:{query:evalQuery.query,...evalQuery.minimum===void 0?{}:{violations:evaluateMetricFloors(metrics,evalQuery.minimum)},mode,relevant_total:metrics.relevant_total,retrieved_relevant:metrics.retrieved_relevant,ndcg:roundMetric(metrics.ndcg),mrr:roundMetric(metrics.mrr),precision:roundMetric(metrics.precision),recall:roundMetric(metrics.recall)}}},buildEvalResult=(k,reports,rawMetrics,failUnder)=>{const aggregate=aggregateEvalMetrics(rawMetrics);return{k,query_count:reports.length,aggregate:{ndcg:roundMetric(aggregate.ndcg),mrr:roundMetric(aggregate.mrr),precision:roundMetric(aggregate.precision),recall:roundMetric(aggregate.recall)},queries:reports,...failUnder!==void 0?{fail_under:failUnder}:{},passed:(failUnder===void 0||aggregate.ndcg>=failUnder)&&reports.every(report=>(report.violations?.length??0)===0)}},runEval=async(options,global2)=>{const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const k=parseEvalK(options.k),defaultMode=parseEvalMode(options.mode),failUnder=parseFailUnder(options.failUnder),queriesPath=options.queries?path.resolve(process.cwd(),options.queries):path.join(pmRoot,DEFAULT_EVAL_QUERIES_RELATIVE_PATH),querySet=await loadEvalQuerySet(queriesPath),reports=[],rawMetrics=[];for(const evalQuery of querySet.queries){const{report,metrics}=await evaluateEvalQuery(evalQuery,defaultMode,k,global2);rawMetrics.push(metrics),reports.push(report)}return buildEvalResult(k,reports,rawMetrics,failUnder)};export{DEFAULT_EVAL_QUERIES_RELATIVE_PATH,EVAL_QUERY_SET_CONTRACT,EVAL_QUERY_SET_EXAMPLE2 as EVAL_QUERY_SET_EXAMPLE,EVAL_QUERY_SET_SCHEMA_ID2 as EVAL_QUERY_SET_SCHEMA_ID,parseEvalQuerySet2 as parseEvalQuerySet,runEval};
|
|
2
2
|
//# sourceMappingURL=eval.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="955d33c5-8c96-5ed6-bbd1-fc8a26801df4")}catch{}})();import fs from"node:fs/promises";import path from"node:path";import{isFileAbsentError}from"../../core/fs/fs-utils.js";import{lintExtensionManifestSchema}from"../../core/extensions/manifest-schema.js";import{resolveWorkspaceRoot}from"../../core/store/paths.js";function manifestName(raw){return typeof raw.name=="string"&&raw.name.trim().length>0?raw.name.trim():"workspace-manifest"}function authorManifestWarning(name,finding){return finding.code==="manifest_unknown_key"?`extension_manifest_unknown_key:author:${name}:key=${finding.path}${finding.suggested_key?`:suggested=${finding.suggested_key}`:""}`:`extension_manifest_no_version_bounds:author:${name}:suggested=pm_min_version`}async function inspectExtensionAuthorManifest(workspaceRoot){const manifestPath=path.join(workspaceRoot,"manifest.json");let content;try{content=await fs.readFile(manifestPath,"utf8")}catch(error){if(isFileAbsentError(error))return{path:manifestPath,present:!1,parse_status:"absent",package_metadata_location:"package.json#pm",schema_findings:[],warnings:[],remediation:[]};throw error}let parsed;try{parsed=JSON.parse(content)}catch{return{path:manifestPath,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 parsed!="object"||parsed===null||Array.isArray(parsed))return{path:manifestPath,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."]};const raw=parsed,lint=lintExtensionManifestSchema(raw),name=manifestName(raw);return{path:manifestPath,present:!0,parse_status:"valid",package_metadata_location:"package.json#pm",schema_findings:lint.findings,warnings:lint.findings.map(finding=>authorManifestWarning(name,finding)),remediation:lint.findings.map(finding=>finding.message)}}function inspectExtensionAuthorManifestAtPmRoot(pmRoot){return inspectExtensionAuthorManifest(resolveWorkspaceRoot(pmRoot))}export{inspectExtensionAuthorManifest,inspectExtensionAuthorManifestAtPmRoot};
|
|
2
2
|
//# sourceMappingURL=author-manifest.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="96c5708d-1f4d-5f94-9945-7f8baa337106")}catch(e2){}})();import fs from"node:fs/promises";import path from"node:path";import{collectPackageExtensionDirectories,PM_PACKAGE_RESOURCE_KINDS,readPmPackageManifest}from"../../core/packages/manifest.js";import{resolvePmPackageRootFromModule}from"../../core/packages/root.js";import{pathExists}from"../../core/fs/fs-utils.js";import{EXIT_CODE}from"../../core/shared/constants.js";import{PmCliError}from"../../core/shared/errors.js";import{splitCommaList}from"../../core/shared/split-comma-list.js";import{resolveExtensionRoots}from"../../core/extensions/loader.js";import{resolvePmRoot}from"../../core/store/paths.js";import{validateExtensionDirectory}from"./shared.js";import{readManagedExtensionState}from"./managed-state.js";const PM_PACKAGE_ROOT_ENV="PM_CLI_PACKAGE_ROOT";const LEGACY_BUNDLED_PACKAGE_ALIASES={beads:{package_directory:"pm-beads",legacy_extension_directory:"beads"},todos:{package_directory:"pm-todos",legacy_extension_directory:"todos"}};const BUNDLED_PACKAGE_INSTALL_ALL_TARGETS=new Set(["*","all"]);function resolvePackageRootCandidates(){const candidates=[];const envRoot=process.env[PM_PACKAGE_ROOT_ENV];if(typeof envRoot==="string"&&envRoot.trim().length>0){candidates.push(path.resolve(envRoot.trim()))}candidates.push(resolvePmPackageRootFromModule(import.meta.url,["../../.."]));return[...new Set(candidates)]}async function resolveBundledExtensionAliasSource(input){const normalized=input.trim().toLowerCase();const packageRoot=await resolveBundledPackageRoot(normalized);if(packageRoot){return packageRoot}const alias=LEGACY_BUNDLED_PACKAGE_ALIASES[normalized];if(!alias){return null}for(const packageRoot2 of resolvePackageRootCandidates()){const legacyExtensionPath=path.join(packageRoot2,".agents","pm","extensions",alias.legacy_extension_directory);if(await pathExists(path.join(legacyExtensionPath,"manifest.json"))){return legacyExtensionPath}}return null}function isBundledPackageInstallAllTarget(input){return BUNDLED_PACKAGE_INSTALL_ALL_TARGETS.has(input.trim().toLowerCase())}function derivePackageAlias(packageDirectory){return packageDirectory.replace(/^pm-/i,"").trim().toLowerCase()}async function collectManifestPackageEntries(packagesRoot,entriesByAlias){const entries=await fs.readdir(packagesRoot,{withFileTypes:true});for(const entry of entries){if(!entry.isDirectory()||!entry.name.startsWith("pm-")){continue}const candidateRoot=path.join(packagesRoot,entry.name);if(!await pathExists(path.join(candidateRoot,"package.json"))){continue}const manifest=await readPmPackageManifest(candidateRoot);const aliases=manifest.aliases&&manifest.aliases.length>0?manifest.aliases:[derivePackageAlias(entry.name)];for(const alias of aliases){const normalizedAlias=alias.trim().toLowerCase();if(normalizedAlias.length===0||entriesByAlias.has(normalizedAlias)){continue}entriesByAlias.set(normalizedAlias,{alias:normalizedAlias,package_directory:entry.name,package_root:candidateRoot,package_name:manifest.package_name??null})}}}async function collectBundledPackageEntries(){const entriesByAlias=new Map;for(const packageRoot of resolvePackageRootCandidates()){const packagesRoot=path.join(packageRoot,"packages");if(!await pathExists(packagesRoot)){continue}await collectManifestPackageEntries(packagesRoot,entriesByAlias)}for(const[alias,legacy]of Object.entries(LEGACY_BUNDLED_PACKAGE_ALIASES)){if(entriesByAlias.has(alias)){continue}for(const packageRoot of resolvePackageRootCandidates()){const packagePath=path.join(packageRoot,"packages",legacy.package_directory);if(await pathExists(path.join(packagePath,"package.json"))){entriesByAlias.set(alias,{alias,package_directory:legacy.package_directory,package_root:packagePath,package_name:null});break}}}return[...entriesByAlias.values()].sort((left,right)=>left.alias.localeCompare(right.alias))}async function listBundledPackageAliases(){return(await collectBundledPackageEntries()).map(entry=>entry.alias)}async function resolveBundledPackageRoot(alias){const normalized=alias.trim().toLowerCase();const entry=(await collectBundledPackageEntries()).find(candidate=>candidate.alias===normalized||candidate.package_directory.toLowerCase()===normalized||candidate.package_name?.toLowerCase()===normalized);return entry?.package_root??null}async function resolveBundledPackageNpmName(alias){const packageRoot=await resolveBundledPackageRoot(alias);if(!packageRoot){return null}const manifest=await readPmPackageManifest(packageRoot);return manifest.package_name??null}async function resolveBundledAliasManifestName(input){const bundledAliasSource=await resolveBundledExtensionAliasSource(input);if(!bundledAliasSource){return null}try{const extensionDirectories=await collectPackageExtensionDirectories(bundledAliasSource);if(extensionDirectories.length!==1){return null}const validated=await validateExtensionDirectory(extensionDirectories[0]);return validated.manifest.name}catch{return null}}function buildBundledCatalogLinks(manifest){return{docs:manifest.catalog?.links?.docs??manifest.package_homepage,npm:manifest.catalog?.links?.npm??(manifest.package_name&&manifest.package_private!==true?`https://www.npmjs.com/package/${encodeURIComponent(manifest.package_name)}`:void 0),repository:manifest.catalog?.links?.repository??manifest.package_repository_url,report:manifest.catalog?.links?.report??manifest.package_bugs_url}}function buildBundledCatalogPackageEntry(manifest,bundledEntry,aliases,scope,installedBuiltinAliases,installedLocations){const installScopeFlag=scope==="global"?"--global":"--project";const metadataOnlyResources=Object.fromEntries(PM_PACKAGE_RESOURCE_KINDS.filter(resourceKind=>resourceKind!=="extensions").map(resourceKind=>[resourceKind,manifest.resources[resourceKind]??[]]).filter(([,entries])=>Array.isArray(entries)&&entries.length>0));return{alias:bundledEntry.alias,aliases,bundled:true,available:true,installed:aliases.some(alias=>installedBuiltinAliases.has(alias))||installedLocations.has(path.resolve(bundledEntry.package_root)),install_target:bundledEntry.alias,install_command:`pm install ${bundledEntry.alias} ${installScopeFlag}`,package_name:manifest.package_name,package_version:manifest.package_version,description:manifest.catalog?.summary??manifest.package_description,keywords:manifest.package_keywords??[],resources:manifest.resources,installable_resources:{extensions:manifest.resources.extensions??[]},metadata_only_resources:metadataOnlyResources,catalog:{display_name:manifest.catalog?.display_name,category:manifest.catalog?.category,tags:manifest.catalog?.tags??manifest.package_keywords??[],links:buildBundledCatalogLinks(manifest),media:manifest.catalog?.media}}}async function buildBundledPackageCatalog(scope,global2,options={}){const roots=resolveExtensionRoots(resolvePmRoot(process.cwd(),global2.path),process.cwd());const selectedRoot=scope==="global"?roots.global:roots.project;const managedStateRead=await readManagedExtensionState(selectedRoot);const installedLocations=new Set(managedStateRead.state.entries.filter(entry=>entry.scope===scope).filter(entry=>entry.source.kind!=="builtin").map(entry=>path.resolve(entry.source.location)));const installedBuiltinAliases=new Set(managedStateRead.state.entries.filter(entry=>entry.scope===scope&&entry.source.kind==="builtin").flatMap(entry=>[entry.source.name,entry.source.input,entry.source.location]).filter(value=>typeof value==="string"&&value.trim().length>0).map(value=>value.trim().toLowerCase()));const packages=[];const bundledEntriesByRoot=new Map;for(const entry of await collectBundledPackageEntries()){const packageRoot=path.resolve(entry.package_root);const groupedEntries=bundledEntriesByRoot.get(packageRoot)??[];groupedEntries.push(entry);bundledEntriesByRoot.set(packageRoot,groupedEntries)}for(const bundledEntries of bundledEntriesByRoot.values()){const bundledEntry=bundledEntries[0];const aliases=bundledEntries.map(entry=>entry.alias).sort((left,right)=>left.localeCompare(right));const manifest=await readPmPackageManifest(bundledEntry.package_root);packages.push(buildBundledCatalogPackageEntry(manifest,bundledEntry,aliases,scope,installedBuiltinAliases,installedLocations))}const fields=parsePackageCatalogFields(options.fields);const outputPackages=fields?packages.map(entry=>projectPackageCatalogEntry(entry,fields)):packages;return{total:outputPackages.length,scope,installable_resource_kinds:["extensions"],metadata_only_resource_kinds:PM_PACKAGE_RESOURCE_KINDS.filter(resourceKind=>resourceKind!=="extensions"),packages:outputPackages}}const PACKAGE_CATALOG_FIELD_KEYS=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 parsePackageCatalogFields(raw){if(raw===void 0){return void 0}const fields=splitCommaList(raw);if(fields.length===0){throw new PmCliError("Package catalog --fields requires a comma-separated list of field names",EXIT_CODE.USAGE)}const unknown=fields.filter(field=>!PACKAGE_CATALOG_FIELD_KEYS.has(field));if(unknown.length>0){throw new PmCliError(`Unknown package catalog --fields value(s): ${unknown.join(", ")}`,EXIT_CODE.USAGE,{examples:["pm package list --project --fields alias,installed,install_command","pm package catalog --project --fields alias,package_name,category"]})}return fields}function projectPackageCatalogEntry(entry,fields){const projected={};for(const field of fields){if(field==="category"){projected[field]=entry.catalog?.category??null}else if(field==="display_name"){projected[field]=entry.catalog?.display_name??null}else{projected[field]=entry[field]??null}}return projected}const _testOnlyBundledCatalog={parsePackageCatalogFields,projectPackageCatalogEntry};export{_testOnlyBundledCatalog,buildBundledPackageCatalog,isBundledPackageInstallAllTarget,listBundledPackageAliases,resolveBundledAliasManifestName,resolveBundledExtensionAliasSource,resolveBundledPackageNpmName,resolveBundledPackageRoot};
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="c9a362e5-6eb5-52dc-aa74-6c6c0df2c291")}catch{}})();import fs from"node:fs/promises";import path from"node:path";import{collectPackageExtensionDirectories,PM_PACKAGE_RESOURCE_KINDS,readPmPackageManifest}from"../../core/packages/manifest.js";import{resolvePmPackageRootFromModule}from"../../core/packages/root.js";import{pathExists}from"../../core/fs/fs-utils.js";import{EXIT_CODE}from"../../core/shared/constants.js";import{PmCliError}from"../../core/shared/errors.js";import{splitCommaList}from"../../core/shared/split-comma-list.js";import{resolveExtensionRoots}from"../../core/extensions/loader.js";import{resolvePmRoot}from"../../core/store/paths.js";import{validateExtensionDirectory}from"./shared.js";import{readManagedExtensionState}from"./managed-state.js";const PM_PACKAGE_ROOT_ENV="PM_CLI_PACKAGE_ROOT",LEGACY_BUNDLED_PACKAGE_ALIASES={beads:{package_directory:"pm-beads",legacy_extension_directory:"beads"},todos:{package_directory:"pm-todos",legacy_extension_directory:"todos"}},BUNDLED_PACKAGE_INSTALL_ALL_TARGETS=new Set(["*","all"]);function resolvePackageRootCandidates(){const candidates=[],envRoot=process.env[PM_PACKAGE_ROOT_ENV];return typeof envRoot=="string"&&envRoot.trim().length>0&&candidates.push(path.resolve(envRoot.trim())),candidates.push(resolvePmPackageRootFromModule(import.meta.url,["../../.."])),[...new Set(candidates)]}async function resolveBundledExtensionAliasSource(input){const normalized=input.trim().toLowerCase(),packageRoot=await resolveBundledPackageRoot(normalized);if(packageRoot)return packageRoot;const alias=LEGACY_BUNDLED_PACKAGE_ALIASES[normalized];if(!alias)return null;for(const packageRoot2 of resolvePackageRootCandidates()){const legacyExtensionPath=path.join(packageRoot2,".agents","pm","extensions",alias.legacy_extension_directory);if(await pathExists(path.join(legacyExtensionPath,"manifest.json")))return legacyExtensionPath}return null}function isBundledPackageInstallAllTarget(input){return BUNDLED_PACKAGE_INSTALL_ALL_TARGETS.has(input.trim().toLowerCase())}function derivePackageAlias(packageDirectory){return packageDirectory.replace(/^pm-/i,"").trim().toLowerCase()}async function collectManifestPackageEntries(packagesRoot,entriesByAlias){const entries=await fs.readdir(packagesRoot,{withFileTypes:!0});for(const entry of entries){if(!entry.isDirectory()||!entry.name.startsWith("pm-"))continue;const candidateRoot=path.join(packagesRoot,entry.name);if(!await pathExists(path.join(candidateRoot,"package.json")))continue;const manifest=await readPmPackageManifest(candidateRoot),aliases=manifest.aliases&&manifest.aliases.length>0?manifest.aliases:[derivePackageAlias(entry.name)];for(const alias of aliases){const normalizedAlias=alias.trim().toLowerCase();normalizedAlias.length===0||entriesByAlias.has(normalizedAlias)||entriesByAlias.set(normalizedAlias,{alias:normalizedAlias,package_directory:entry.name,package_root:candidateRoot,package_name:manifest.package_name??null})}}}async function collectBundledPackageEntries(){const entriesByAlias=new Map;for(const packageRoot of resolvePackageRootCandidates()){const packagesRoot=path.join(packageRoot,"packages");await pathExists(packagesRoot)&&await collectManifestPackageEntries(packagesRoot,entriesByAlias)}for(const[alias,legacy]of Object.entries(LEGACY_BUNDLED_PACKAGE_ALIASES))if(!entriesByAlias.has(alias))for(const packageRoot of resolvePackageRootCandidates()){const packagePath=path.join(packageRoot,"packages",legacy.package_directory);if(await pathExists(path.join(packagePath,"package.json"))){entriesByAlias.set(alias,{alias,package_directory:legacy.package_directory,package_root:packagePath,package_name:null});break}}return[...entriesByAlias.values()].sort((left,right)=>left.alias.localeCompare(right.alias))}async function listBundledPackageAliases(){return(await collectBundledPackageEntries()).map(entry=>entry.alias)}async function resolveBundledPackageRoot(alias){const normalized=alias.trim().toLowerCase();return(await collectBundledPackageEntries()).find(candidate=>candidate.alias===normalized||candidate.package_directory.toLowerCase()===normalized||candidate.package_name?.toLowerCase()===normalized)?.package_root??null}async function resolveBundledPackageNpmName(alias){const packageRoot=await resolveBundledPackageRoot(alias);return packageRoot?(await readPmPackageManifest(packageRoot)).package_name??null:null}async function resolveBundledAliasManifestName(input){const bundledAliasSource=await resolveBundledExtensionAliasSource(input);if(!bundledAliasSource)return null;try{const extensionDirectories=await collectPackageExtensionDirectories(bundledAliasSource);return extensionDirectories.length!==1?null:(await validateExtensionDirectory(extensionDirectories[0])).manifest.name}catch{return null}}function buildBundledCatalogLinks(manifest){return{docs:manifest.catalog?.links?.docs??manifest.package_homepage,npm:manifest.catalog?.links?.npm??(manifest.package_name&&manifest.package_private!==!0?`https://www.npmjs.com/package/${encodeURIComponent(manifest.package_name)}`:void 0),repository:manifest.catalog?.links?.repository??manifest.package_repository_url,report:manifest.catalog?.links?.report??manifest.package_bugs_url}}function buildBundledCatalogPackageEntry(manifest,bundledEntry,aliases,scope,installedBuiltinAliases,installedLocations){const installScopeFlag=scope==="global"?"--global":"--project",metadataOnlyResources=Object.fromEntries(PM_PACKAGE_RESOURCE_KINDS.filter(resourceKind=>resourceKind!=="extensions").map(resourceKind=>[resourceKind,manifest.resources[resourceKind]??[]]).filter(([,entries])=>Array.isArray(entries)&&entries.length>0));return{alias:bundledEntry.alias,aliases,bundled:!0,available:!0,installed:aliases.some(alias=>installedBuiltinAliases.has(alias))||installedLocations.has(path.resolve(bundledEntry.package_root)),install_target:bundledEntry.alias,install_command:`pm install ${bundledEntry.alias} ${installScopeFlag}`,package_name:manifest.package_name,package_version:manifest.package_version,description:manifest.catalog?.summary??manifest.package_description,keywords:manifest.package_keywords??[],resources:manifest.resources,installable_resources:{extensions:manifest.resources.extensions??[]},metadata_only_resources:metadataOnlyResources,catalog:{display_name:manifest.catalog?.display_name,category:manifest.catalog?.category,tags:manifest.catalog?.tags??manifest.package_keywords??[],links:buildBundledCatalogLinks(manifest),media:manifest.catalog?.media}}}async function buildBundledPackageCatalog(scope,global2,options={}){const roots=resolveExtensionRoots(resolvePmRoot(process.cwd(),global2.path),process.cwd()),selectedRoot=scope==="global"?roots.global:roots.project,managedStateRead=await readManagedExtensionState(selectedRoot),installedLocations=new Set(managedStateRead.state.entries.filter(entry=>entry.scope===scope).filter(entry=>entry.source.kind!=="builtin").map(entry=>path.resolve(entry.source.location))),installedBuiltinAliases=new Set(managedStateRead.state.entries.filter(entry=>entry.scope===scope&&entry.source.kind==="builtin").flatMap(entry=>[entry.source.name,entry.source.input,entry.source.location]).filter(value=>typeof value=="string"&&value.trim().length>0).map(value=>value.trim().toLowerCase())),packages=[],bundledEntriesByRoot=new Map;for(const entry of await collectBundledPackageEntries()){const packageRoot=path.resolve(entry.package_root),groupedEntries=bundledEntriesByRoot.get(packageRoot)??[];groupedEntries.push(entry),bundledEntriesByRoot.set(packageRoot,groupedEntries)}for(const bundledEntries of bundledEntriesByRoot.values()){const bundledEntry=bundledEntries[0],aliases=bundledEntries.map(entry=>entry.alias).sort((left,right)=>left.localeCompare(right)),manifest=await readPmPackageManifest(bundledEntry.package_root);packages.push(buildBundledCatalogPackageEntry(manifest,bundledEntry,aliases,scope,installedBuiltinAliases,installedLocations))}const fields=parsePackageCatalogFields(options.fields),outputPackages=fields?packages.map(entry=>projectPackageCatalogEntry(entry,fields)):packages;return{total:outputPackages.length,scope,installable_resource_kinds:["extensions"],metadata_only_resource_kinds:PM_PACKAGE_RESOURCE_KINDS.filter(resourceKind=>resourceKind!=="extensions"),packages:outputPackages}}const PACKAGE_CATALOG_FIELD_KEYS=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 parsePackageCatalogFields(raw){if(raw===void 0)return;const fields=splitCommaList(raw);if(fields.length===0)throw new PmCliError("Package catalog --fields requires a comma-separated list of field names",EXIT_CODE.USAGE);const unknown=fields.filter(field=>!PACKAGE_CATALOG_FIELD_KEYS.has(field));if(unknown.length>0)throw new PmCliError(`Unknown package catalog --fields value(s): ${unknown.join(", ")}`,EXIT_CODE.USAGE,{examples:["pm package list --project --fields alias,installed,install_command","pm package catalog --project --fields alias,package_name,category"]});return fields}function projectPackageCatalogEntry(entry,fields){const projected={};for(const field of fields)field==="category"?projected[field]=entry.catalog?.category??null:field==="display_name"?projected[field]=entry.catalog?.display_name??null:projected[field]=entry[field]??null;return projected}const _testOnlyBundledCatalog={parsePackageCatalogFields,projectPackageCatalogEntry};export{_testOnlyBundledCatalog,buildBundledPackageCatalog,isBundledPackageInstallAllTarget,listBundledPackageAliases,resolveBundledAliasManifestName,resolveBundledExtensionAliasSource,resolveBundledPackageNpmName,resolveBundledPackageRoot};
|
|
2
2
|
//# sourceMappingURL=bundled-catalog.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="eb830963-f036-5f98-ab26-786240b3e0fd")}catch{}})();const mapWithFixedConcurrency=async(inputs,concurrency,mapper)=>{if(!Number.isInteger(concurrency)||concurrency<1)throw new RangeError("concurrency must be a positive integer");const results=new Array(inputs.length);let nextIndex=0;const workers=Array.from({length:Math.min(concurrency,inputs.length)},async()=>{for(;nextIndex<inputs.length;){const index=nextIndex;nextIndex+=1,results[index]=await mapper(inputs[index])}});return await Promise.all(workers),results};export{mapWithFixedConcurrency};
|
|
2
2
|
//# sourceMappingURL=concurrency.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="147fb29e-ad06-5850-b0b1-f643e32e9b1f")}catch{}})();import path from"node:path";import{isPathWithinDirectory}from"../../core/fs/path-utils.js";function includesExtensionCopyPath(source,destination,candidate,nestedDestination){const relative=path.relative(source,candidate);if(relative!==""&&!isPathWithinDirectory(source,candidate)||candidate===destination||isPathWithinDirectory(destination,candidate))return!1;const segments=relative.split(path.sep);return segments.includes(".git")?!1:nestedDestination?!segments.some(segment=>segment===".agents"||segment==="node_modules"||segment.startsWith(".pm-extension-install-backup-")):!0}export{includesExtensionCopyPath};
|
|
2
2
|
//# sourceMappingURL=copy-scope.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="a1803149-25ca-5bb0-a178-afa2d85d2ec9")}catch{}})();import{resolvePmToolCustomFieldCollision}from"../cli-contracts/tool-schema.js";const collectMcpCustomFieldCollisionDoctorWarnings=activationResult=>[...activationResult.registrations.item_fields.flatMap(registration=>registration.fields.map(field=>({layer:registration.layer,extension:registration.name,field:field.name}))),...activationResult.registrations.profiles.flatMap(registration=>registration.profile.fields.map(field=>({layer:registration.layer,extension:registration.name,field:field.key??""})))].flatMap(entry=>{const collision=resolvePmToolCustomFieldCollision(entry.field);return collision?[`extension_custom_field_mcp_input_collision:${entry.layer}:${entry.extension}:${collision.field}:${collision.property}:${collision.owner}:use=${collision.nested_path}`]:[]}).filter((warning,index,warnings)=>warnings.indexOf(warning)===index).sort((left,right)=>left.localeCompare(right));export{collectMcpCustomFieldCollisionDoctorWarnings};
|
|
2
2
|
//# sourceMappingURL=custom-field-collisions.js.map
|