@unbrained/pm-cli 2026.11.21 → 2026.11.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.agents/skills/pm-developer/SKILL.md +1 -1
- package/.claude-plugin/marketplace.json +1 -1
- package/dist/cli/after-command-context-usage.js +1 -1
- package/dist/cli/argv-utils.js +1 -1
- package/dist/cli/bootstrap-args.js +1 -1
- package/dist/cli/bundle-integrity.js +2 -2
- package/dist/cli/command-namespaces.js +1 -1
- package/dist/cli/commander-usage.js +11 -11
- package/dist/cli/commands/annotations/comments.js +1 -1
- package/dist/cli/commands/annotations/docs.js +1 -1
- package/dist/cli/commands/annotations/files.js +1 -1
- package/dist/cli/commands/annotations/learnings.js +1 -1
- package/dist/cli/commands/annotations/notes.js +1 -1
- package/dist/cli/commands/extension/describe.js +1 -1
- package/dist/cli/commands/extension/extension.js +1 -1
- package/dist/cli/commands/extension/scaffold.js +1 -1
- package/dist/cli/commands/extension/shared.js +1 -1
- package/dist/cli/commands/governance/gc.js +1 -1
- package/dist/cli/commands/governance/health.js +1 -1
- package/dist/cli/commands/governance/telemetry.js +1 -1
- package/dist/cli/commands/governance/validate.js +1 -1
- package/dist/cli/commands/history/activity.js +1 -1
- package/dist/cli/commands/history/history-compact.js +1 -1
- package/dist/cli/commands/history/history-redact.js +1 -1
- package/dist/cli/commands/history/history-repair.js +1 -1
- package/dist/cli/commands/history/history.js +1 -1
- package/dist/cli/commands/history/restore.js +1 -1
- package/dist/cli/commands/lifecycle/append.js +1 -1
- package/dist/cli/commands/lifecycle/claim.js +1 -1
- package/dist/cli/commands/lifecycle/close-many.js +1 -1
- package/dist/cli/commands/lifecycle/close.js +1 -1
- package/dist/cli/commands/lifecycle/copy.js +1 -1
- package/dist/cli/commands/lifecycle/create.js +1 -1
- package/dist/cli/commands/lifecycle/delete.js +1 -1
- package/dist/cli/commands/lifecycle/focus.js +1 -1
- package/dist/cli/commands/lifecycle/plan.js +1 -1
- package/dist/cli/commands/lifecycle/update-many.js +1 -1
- package/dist/cli/commands/lifecycle/update.js +1 -1
- package/dist/cli/commands/query/aggregate.js +1 -1
- package/dist/cli/commands/query/context.js +1 -1
- package/dist/cli/commands/query/deps.js +1 -1
- package/dist/cli/commands/query/duplicates.js +1 -1
- package/dist/cli/commands/query/eval.js +1 -1
- package/dist/cli/commands/query/get.js +1 -1
- package/dist/cli/commands/query/graph.js +1 -1
- package/dist/cli/commands/query/list.js +1 -1
- package/dist/cli/commands/query/next.js +1 -1
- package/dist/cli/commands/query/search.js +1 -1
- package/dist/cli/commands/query/stats.js +1 -1
- package/dist/cli/commands/test/test-all.js +1 -1
- package/dist/cli/commands/test/test-runs.js +1 -1
- package/dist/cli/commands/test/test.js +1 -1
- package/dist/cli/commands/workspace/config.js +1 -1
- package/dist/cli/commands/workspace/contracts.js +1 -1
- package/dist/cli/commands/workspace/init.js +1 -1
- package/dist/cli/commands/workspace/merge.js +1 -1
- package/dist/cli/commands/workspace/profile.js +1 -1
- package/dist/cli/commands/workspace/schema.js +1 -1
- package/dist/cli/commands/workspace/upgrade.js +1 -1
- package/dist/cli/context-intent-invocation.js +1 -1
- package/dist/cli/description-stdin.js +1 -1
- package/dist/cli/error-guidance.js +5 -5
- package/dist/cli/expected-revisions.js +1 -1
- package/dist/cli/extension-command-help.js +6 -6
- package/dist/cli/extension-recovery.js +1 -1
- package/dist/cli/help-content.js +5 -5
- package/dist/cli/help-json-payload.js +7 -7
- package/dist/cli/invocation-profile.js +2 -2
- package/dist/cli/main.js +5 -5
- package/dist/cli/migration-gates.js +1 -1
- package/dist/cli/option-values.js +1 -1
- package/dist/cli/preflight-warnings.js +3 -3
- package/dist/cli/public.js +1 -1
- package/dist/cli/register-annotations.js +1 -1
- package/dist/cli/register-assurance.js +1 -1
- package/dist/cli/register-files-lookup.js +1 -1
- package/dist/cli/register-history-activity.js +1 -1
- package/dist/cli/register-history-author.js +1 -1
- package/dist/cli/register-history-maintenance.js +2 -2
- package/dist/cli/register-list-query.js +10 -10
- package/dist/cli/register-mutation-options.js +0 -1
- package/dist/cli/register-mutation.js +6 -6
- package/dist/cli/register-operations.js +1 -1
- package/dist/cli/register-setup.js +1 -1
- package/dist/cli/register-structured-mutation.js +1 -1
- package/dist/cli/registration-helpers.js +1 -1
- package/dist/cli/runtime/activation.js +1 -1
- package/dist/cli/runtime/annotation-option-retry.js +1 -1
- package/dist/cli/runtime/close-fields-retry.js +1 -1
- package/dist/cli/runtime/field-route-retry.js +1 -1
- package/dist/cli/runtime/invocation-options.js +1 -1
- package/dist/cli/runtime/invocation-rewrites.js +1 -1
- package/dist/cli/runtime/projection-retry.js +1 -1
- package/dist/cli/runtime/read-output-mutation-retry.js +1 -1
- package/dist/cli/runtime/refusal-credential-redaction.js +1 -1
- package/dist/cli/runtime/selection.js +1 -1
- package/dist/cli/runtime/telemetry-outcome.js +1 -1
- package/dist/cli/runtime-compatibility-boundary.js +4 -4
- package/dist/cli/schema/registration.js +15 -15
- package/dist/cli/schema-registration-helpers.js +1 -1
- package/dist/cli/search-refresh.js +1 -1
- package/dist/cli/stats-analytics-json.js +1 -1
- package/dist/cli/telemetry-flush.js +1 -1
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/chunk-2UQU7HRR.js +9 -0
- package/dist/cli-bundle/chunks/chunk-5DUP4AZA.js +2 -0
- package/dist/cli-bundle/chunks/chunk-5WZZ5XEN.js +3 -0
- package/dist/cli-bundle/chunks/chunk-6H36ZHMI.js +2 -0
- package/dist/cli-bundle/chunks/chunk-6MYJLOSG.js +2 -0
- package/dist/cli-bundle/chunks/chunk-AA52P34H.js +3 -0
- package/dist/cli-bundle/chunks/chunk-AEOHUSUI.js +2289 -0
- package/dist/cli-bundle/chunks/chunk-BSRIVYTM.js +8 -0
- package/dist/cli-bundle/chunks/chunk-CFWLQFJM.js +71 -0
- package/dist/cli-bundle/chunks/chunk-D6PDUKUG.js +9 -0
- package/dist/cli-bundle/chunks/chunk-ENKXRSFZ.js +31 -0
- package/dist/cli-bundle/chunks/chunk-F2Z6XLZB.js +3 -0
- package/dist/cli-bundle/chunks/chunk-FJOEL75F.js +2 -0
- package/dist/cli-bundle/chunks/chunk-GDXCAC52.js +2 -0
- package/dist/cli-bundle/chunks/chunk-H7JEXRIN.js +6 -0
- package/dist/cli-bundle/chunks/chunk-J2PDAVBC.js +2 -0
- package/dist/cli-bundle/chunks/chunk-KE7HMBEW.js +2 -0
- package/dist/cli-bundle/chunks/chunk-KZHIBEJL.js +33 -0
- package/dist/cli-bundle/chunks/chunk-NGJ5ERBF.js +115 -0
- package/dist/cli-bundle/chunks/chunk-NQ54T7T2.js +2 -0
- package/dist/cli-bundle/chunks/chunk-O7JHS64G.js +3 -0
- package/dist/cli-bundle/chunks/chunk-OKEZF7HU.js +2 -0
- package/dist/cli-bundle/chunks/chunk-OKIKF4FD.js +2 -0
- package/dist/cli-bundle/chunks/chunk-OPJF254V.js +9 -0
- package/dist/cli-bundle/chunks/chunk-PZA7QECY.js +1 -0
- package/dist/cli-bundle/chunks/chunk-RWA5YZ5X.js +2 -0
- package/dist/cli-bundle/chunks/chunk-S32NGRQM.js +2 -0
- package/dist/cli-bundle/chunks/chunk-SLFRSZK6.js +1 -0
- package/dist/cli-bundle/chunks/chunk-TZY5MVJF.js +125 -0
- package/dist/cli-bundle/chunks/chunk-YYT3MIRF.js +3 -0
- package/dist/cli-bundle/chunks/chunk-ZPS4B6SI.js +8 -0
- package/dist/cli-bundle/chunks/context-budget-recovery-M5RFUEFG.js +2 -0
- package/dist/cli-bundle/chunks/indexed-receipt-blobs-BPYKN5Q7.js +4 -0
- package/dist/cli-bundle/chunks/{item-revision-R5SZPJZ5.js → item-revision-FMD4KWBB.js} +2 -2
- package/dist/cli-bundle/chunks/item-transaction-SEHTH7N2.js +2 -0
- package/dist/cli-bundle/chunks/mutation-actor-SFGYIRPW.js +2 -0
- package/dist/cli-bundle/chunks/mutation-admission-57LBSKQI.js +2 -0
- package/dist/cli-bundle/chunks/{register-list-query-SPGPS3OS.js → register-list-query-L4IBU64P.js} +11 -11
- package/dist/cli-bundle/chunks/register-mutation-6NUOPHZ3.js +21 -0
- package/dist/cli-bundle/chunks/register-operations-JGYVORNN.js +2 -0
- package/dist/cli-bundle/chunks/register-setup-C44SIXEH.js +2 -0
- package/dist/cli-bundle/chunks/settlement-hook-6MR32OOC.js +7 -0
- package/dist/cli-bundle/chunks/stage-PQ7AB63N.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-6LKTEKHS.js +6 -0
- package/dist/cli-bundle/focused-chunks/chunk-6LPXMFLM.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-A6VEMCRR.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-AIDL2ZNT.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-BKPUUW5O.js +1 -0
- package/dist/cli-bundle/focused-chunks/chunk-BWOVFE5B.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-HMDQDRV2.js +8 -0
- package/dist/cli-bundle/focused-chunks/chunk-I66IKYKP.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-IIP6LZ5E.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-IR2J3NOT.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-IROZDIDX.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-ITKDHSBR.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-K53OIT5J.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-LQYYPXUK.js +26 -0
- package/dist/cli-bundle/focused-chunks/chunk-NQTEE66P.js +13 -0
- package/dist/cli-bundle/focused-chunks/chunk-O7Z73ALG.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-OTMMOKPM.js +91 -0
- package/dist/cli-bundle/focused-chunks/chunk-OXOCZJC6.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-QLAHEDT6.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-QQIIMMFU.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-RIE3SJSE.js +9 -0
- package/dist/cli-bundle/focused-chunks/chunk-TD544C74.js +8 -0
- package/dist/cli-bundle/focused-chunks/chunk-UFTUNBMY.js +27 -0
- package/dist/cli-bundle/focused-chunks/chunk-X6CXWWNB.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-XRS3VNC6.js +44 -0
- package/dist/cli-bundle/focused-chunks/chunk-XYPEZGTR.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-Y2ESLKCF.js +8 -0
- package/dist/cli-bundle/focused-chunks/chunk-YSJKQLFR.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-Z2X7HH3C.js +102 -0
- package/dist/cli-bundle/focused-chunks/chunk-ZHWPCVQL.js +78 -0
- package/dist/cli-bundle/focused-chunks/context-budget-recovery-CSJV3TY3.js +2 -0
- package/dist/cli-bundle/focused-chunks/indexed-receipt-blobs-EGEJMG3G.js +4 -0
- package/dist/cli-bundle/focused-chunks/{item-revision-3V3UIP5X.js → item-revision-YDACCDVY.js} +2 -2
- package/dist/cli-bundle/focused-chunks/item-transaction-UKEQCTKB.js +2 -0
- package/dist/cli-bundle/focused-chunks/mutation-actor-AS465LRX.js +2 -0
- package/dist/cli-bundle/focused-chunks/mutation-admission-E5UHJZFE.js +2 -0
- package/dist/cli-bundle/focused-chunks/settlement-hook-FMLGKG7J.js +7 -0
- package/dist/cli-bundle/focused-chunks/stage-36J7YLGI.js +2 -0
- package/dist/cli-bundle/main.js +27 -27
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +5 -5
- package/dist/cli-bundle/sdk-core.js +1 -1
- package/dist/cli-bundle/sdk-governance.js +1 -1
- package/dist/cli-bundle/sdk-graph.js +1 -1
- package/dist/cli-bundle/sdk-merge.js +72 -60
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +13 -13
- package/dist/cli.js +1 -1
- package/dist/core/checkpoint/checkpoint-gc.js +1 -1
- package/dist/core/checkpoint/mutation-checkpoint.js +2 -2
- package/dist/core/checkpoint/mutation-context.js +1 -1
- package/dist/core/config/nested-settings.js +1 -1
- package/dist/core/config/positional-value.js +1 -1
- package/dist/core/diagnostics/remediation.js +1 -1
- package/dist/core/extensions/activation-summary-markdown.js +2 -2
- package/dist/core/extensions/activation-summary.js +1 -1
- package/dist/core/extensions/activation-transaction.js +1 -1
- package/dist/core/extensions/capability-usage.js +1 -1
- package/dist/core/extensions/command-hook-context.js +1 -1
- package/dist/core/extensions/command-metadata-contract.js +1 -1
- package/dist/core/extensions/command-visibility-tier.js +1 -1
- package/dist/core/extensions/contribution-inventory.js +1 -1
- package/dist/core/extensions/exporter-output-contract.js +1 -1
- package/dist/core/extensions/extension-candidate.js +1 -1
- package/dist/core/extensions/extension-capability-aliases.js +1 -1
- package/dist/core/extensions/extension-hook-runtime.js +1 -1
- package/dist/core/extensions/extension-policy.js +1 -1
- package/dist/core/extensions/extension-registries.js +1 -1
- package/dist/core/extensions/extension-runtime-helpers.js +1 -1
- package/dist/core/extensions/extension-types.js +1 -1
- package/dist/core/extensions/flag-definition-validation.js +1 -1
- package/dist/core/extensions/flag-value-types.js +1 -1
- package/dist/core/extensions/index.js +1 -1
- package/dist/core/extensions/item-field-types.js +1 -1
- package/dist/core/extensions/item-fields.js +1 -1
- package/dist/core/extensions/loader.js +1 -1
- package/dist/core/extensions/manifest-parser.js +1 -1
- package/dist/core/extensions/manifest-schema.js +1 -1
- package/dist/core/extensions/module-graph-snapshot.js +1 -1
- package/dist/core/extensions/mutation-actor-snapshot.js +1 -1
- package/dist/core/extensions/mutation-actor.js +1 -1
- package/dist/core/extensions/preflight-ownership.js +1 -1
- package/dist/core/extensions/read-output-contract.js +1 -1
- package/dist/core/extensions/registration-contracts.js +1 -1
- package/dist/core/extensions/registration-validation.js +1 -1
- package/dist/core/extensions/registration-values.js +1 -1
- package/dist/core/extensions/reserved-host-flags.js +1 -1
- package/dist/core/extensions/runtime-registrations.js +1 -1
- package/dist/core/extensions/service-ownership.js +1 -1
- package/dist/core/extensions/version-compat.js +1 -1
- package/dist/core/extensions/version-diagnostics.js +1 -1
- package/dist/core/fs/atomic-create.js +1 -1
- package/dist/core/fs/file-glob.js +1 -1
- package/dist/core/fs/fs-utils.js +2 -2
- package/dist/core/fs/host-environment-errors.js +1 -1
- package/dist/core/fs/index.js +1 -1
- package/dist/core/fs/path-utils.js +1 -1
- package/dist/core/governance/content-fields.js +1 -1
- package/dist/core/governance/issue-codes.js +1 -1
- package/dist/core/governance/metadata-coverage.js +1 -1
- package/dist/core/history/bridge.js +2 -0
- package/dist/core/history/digest.js +1 -1
- package/dist/core/history/drift-cache.js +3 -3
- package/dist/core/history/drift-scan.js +1 -1
- package/dist/core/history/event-classification.js +1 -1
- package/dist/core/history/event-index.js +11 -11
- package/dist/core/history/history-compact-bulk.js +1 -1
- package/dist/core/history/history-diff.js +1 -1
- package/dist/core/history/history-rewrite.js +1 -1
- package/dist/core/history/history-storage-stats.js +1 -1
- package/dist/core/history/history-stream-policy.js +1 -1
- package/dist/core/history/history.d.ts +12 -0
- package/dist/core/history/history.js +2 -2
- package/dist/core/history/identity.js +1 -1
- package/dist/core/history/index.js +1 -1
- package/dist/core/history/operation-contract.js +1 -1
- package/dist/core/history/projection.js +1 -1
- package/dist/core/history/read.d.ts +9 -0
- package/dist/core/history/read.js +1 -1
- package/dist/core/history/replay.d.ts +46 -5
- package/dist/core/history/replay.js +2 -2
- package/dist/core/history/stream-summary.js +2 -2
- package/dist/core/history/tombstone.js +1 -1
- package/dist/core/history/version-address.js +1 -1
- package/dist/core/history/workspace-history.js +2 -2
- package/dist/core/io/body-file.js +1 -1
- package/dist/core/io/bulk-ids-input.js +2 -2
- package/dist/core/item/actionability.js +1 -1
- package/dist/core/item/deferred-fields.js +1 -1
- package/dist/core/item/dependency-reference.js +1 -1
- package/dist/core/item/id.js +1 -1
- package/dist/core/item/index.js +1 -1
- package/dist/core/item/item-format-version.js +1 -1
- package/dist/core/item/item-format.js +7 -7
- package/dist/core/item/item-record.js +1 -1
- package/dist/core/item/item-type-definition.js +1 -1
- package/dist/core/item/literal-mutation-input.js +1 -1
- package/dist/core/item/parent-reference-policy.js +1 -1
- package/dist/core/item/parse.js +8 -8
- package/dist/core/item/plan-lifecycle.js +1 -1
- package/dist/core/item/priority.js +1 -1
- package/dist/core/item/sprint-release-format.js +1 -1
- package/dist/core/item/status-filter.js +1 -1
- package/dist/core/item/status.js +1 -1
- package/dist/core/item/toon-decode.js +1 -1
- package/dist/core/item/type-registry.js +1 -1
- package/dist/core/item/type-synonyms.js +1 -1
- package/dist/core/lock/index.js +1 -1
- package/dist/core/lock/lock-confinement.js +1 -1
- package/dist/core/lock/lock-gc.js +1 -1
- package/dist/core/lock/lock-owner.js +1 -1
- package/dist/core/lock/lock.js +4 -4
- package/dist/core/output/linked-test-projection.js +5 -5
- package/dist/core/output/mutation-projection.js +1 -1
- package/dist/core/output/output-control.js +1 -1
- package/dist/core/output/output.js +19 -19
- package/dist/core/output/query-summary.js +1 -1
- package/dist/core/output/tabular.js +3 -3
- package/dist/core/packages/manifest.js +1 -1
- package/dist/core/packages/root.js +1 -1
- package/dist/core/policy/workflow-policy-schema.js +1 -1
- package/dist/core/policy/workflow-policy-store.js +1 -1
- package/dist/core/policy/workflow-policy.js +1 -1
- package/dist/core/profile/profile-describe.js +1 -1
- package/dist/core/profile/profile-lint.d.ts +1 -1
- package/dist/core/profile/profile-lint.js +1 -1
- package/dist/core/profile/profile-plan.js +1 -1
- package/dist/core/profile/profile-presets.js +4 -4
- package/dist/core/reproducibility/context.js +1 -1
- package/dist/core/schema/fields-file.js +2 -2
- package/dist/core/schema/item-types-file.js +2 -2
- package/dist/core/schema/runtime-field-filters.js +1 -1
- package/dist/core/schema/runtime-field-values.js +1 -1
- package/dist/core/schema/runtime-schema.js +2 -2
- package/dist/core/schema/status-defs-file.js +2 -2
- package/dist/core/schema/status-token.js +1 -1
- package/dist/core/schema/type-inference.js +1 -1
- package/dist/core/schema/type-presets.js +1 -1
- package/dist/core/schema/type-workflows.js +1 -1
- package/dist/core/search/background-refresh.js +2 -2
- package/dist/core/search/bm25.js +1 -1
- package/dist/core/search/cache.js +2 -2
- package/dist/core/search/corpus.js +1 -1
- package/dist/core/search/embedding-batches.js +1 -1
- package/dist/core/search/eval-thresholds.js +1 -1
- package/dist/core/search/eval.js +1 -1
- package/dist/core/search/http-client.js +1 -1
- package/dist/core/search/providers.js +1 -1
- package/dist/core/search/relevance.js +1 -1
- package/dist/core/search/semantic-defaults.js +1 -1
- package/dist/core/search/staleness.js +1 -1
- package/dist/core/search/vector-stores.js +2 -2
- package/dist/core/search/vectorization-metadata.js +1 -1
- package/dist/core/sentry/helpers.js +1 -1
- package/dist/core/sentry/instrument.js +1 -1
- package/dist/core/sentry/sensitive-assignments.js +1 -1
- package/dist/core/session/session-state.js +1 -1
- package/dist/core/shared/agent-session-context.js +1 -1
- package/dist/core/shared/author.js +5 -5
- package/dist/core/shared/command-line.js +1 -1
- package/dist/core/shared/command-types.js +0 -1
- package/dist/core/shared/conflict-markers.js +1 -1
- package/dist/core/shared/constants.js +1 -1
- package/dist/core/shared/error-details.js +1 -1
- package/dist/core/shared/errors.js +1 -1
- package/dist/core/shared/html-entity-decode.js +1 -1
- package/dist/core/shared/index.js +1 -1
- package/dist/core/shared/item-metadata-contract.js +1 -1
- package/dist/core/shared/lazy-module.js +1 -1
- package/dist/core/shared/levenshtein.js +1 -1
- package/dist/core/shared/memo.js +1 -1
- package/dist/core/shared/numeric-parsers.js +1 -1
- package/dist/core/shared/option-alias-visibility.js +1 -1
- package/dist/core/shared/output-unicode.js +1 -1
- package/dist/core/shared/primitives.js +1 -1
- package/dist/core/shared/process-tree.js +2 -2
- package/dist/core/shared/secret-rules.js +5 -5
- package/dist/core/shared/serial-queue.js +1 -1
- package/dist/core/shared/serialization.js +1 -1
- package/dist/core/shared/split-comma-list.js +1 -1
- package/dist/core/shared/text-normalization.js +1 -1
- package/dist/core/shared/time.js +2 -2
- package/dist/core/shared/url-credentials.js +1 -1
- package/dist/core/store/index.js +1 -1
- package/dist/core/store/item-format-migration.js +1 -1
- package/dist/core/store/item-metadata-cache.js +1 -1
- package/dist/core/store/item-metadata-query-index.js +11 -11
- package/dist/core/store/item-metadata-read-work.js +1 -1
- package/dist/core/store/item-mutation-precondition.js +1 -1
- package/dist/core/store/item-store.js +1 -1
- package/dist/core/store/paths.js +1 -1
- package/dist/core/store/settings-concurrency.js +1 -1
- package/dist/core/store/settings-read-cache.js +1 -1
- package/dist/core/store/settings-sections.js +2 -2
- package/dist/core/store/settings-validator.js +1 -1
- package/dist/core/store/settings.d.ts +3 -1
- package/dist/core/store/settings.js +6 -6
- package/dist/core/store/sqlite-runtime.js +1 -1
- package/dist/core/store/tracker-preflight.js +1 -1
- package/dist/core/store/transaction-coordinator-scope.js +1 -1
- package/dist/core/telemetry/consent.js +3 -3
- package/dist/core/telemetry/observability.js +1 -1
- package/dist/core/telemetry/policy.js +1 -1
- package/dist/core/telemetry/read-sampling.js +2 -2
- package/dist/core/telemetry/runtime.js +9 -9
- package/dist/core/test/background-runs.js +4 -4
- package/dist/core/test/item-test-run-tracking.js +1 -1
- package/dist/core/test/run-selectors.js +1 -1
- package/dist/core/validate/estimate-defaults.js +1 -1
- package/dist/core/validate/fix-planning.js +1 -1
- package/dist/core/validate/linked-artifact-reference.js +1 -1
- package/dist/core/validate/missing-by-type.js +1 -1
- package/dist/core/validate/missing-link-owners.js +1 -1
- package/dist/core/validate/stale-file-classification.js +1 -1
- package/dist/mcp/http-server.js +5 -5
- package/dist/mcp/legacy-adapter.js +1 -1
- package/dist/mcp/runtime-capabilities.js +1 -1
- package/dist/mcp/server.js +4 -4
- package/dist/mcp/tool-definitions.js +1 -1
- package/dist/sdk/actionability.js +1 -1
- package/dist/sdk/agent/closed-domain-contracts.js +1 -1
- package/dist/sdk/agent/command-recovery.js +1 -1
- package/dist/sdk/agent/command-suggestions.js +1 -1
- package/dist/sdk/agent/create-option-policy.js +1 -1
- package/dist/sdk/agent/identity-config.js +1 -1
- package/dist/sdk/agent/item-addressing.js +1 -1
- package/dist/sdk/agent/linked-resource-recovery.js +1 -1
- package/dist/sdk/agent/refusal-closure-census.js +2 -2
- package/dist/sdk/agent/refusal-corpus-contracts.js +1 -1
- package/dist/sdk/agent/subcommand-recovery.js +1 -1
- package/dist/sdk/agent-capability-contracts.js +3 -3
- package/dist/sdk/agent-session-context.js +1 -1
- package/dist/sdk/annotations.js +1 -1
- package/dist/sdk/author-attribution.js +1 -1
- package/dist/sdk/cli-bootstrap.js +1 -1
- package/dist/sdk/cli-contracts/agent-output-contracts.js +5 -5
- package/dist/sdk/cli-contracts/bootstrap-command-scanner.js +1 -1
- package/dist/sdk/cli-contracts/command-aliases.js +1 -1
- package/dist/sdk/cli-contracts/command-exit-contracts.js +1 -1
- package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1
- package/dist/sdk/cli-contracts/commander-types.js +1 -1
- package/dist/sdk/cli-contracts/completeness.js +1 -1
- package/dist/sdk/cli-contracts/enum-contracts.js +1 -1
- package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
- package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +2 -2
- package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
- package/dist/sdk/cli-contracts/registration-helpers.js +7 -7
- package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
- package/dist/sdk/cli-contracts/schemas/assurance-definition.js +1 -1
- package/dist/sdk/cli-contracts/string-lists.js +1 -1
- package/dist/sdk/cli-contracts/tool-option-contracts.js +1 -1
- package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
- package/dist/sdk/cli-contracts/tool-schema.js +1 -1
- package/dist/sdk/cli-contracts/typed-action-inputs.d.ts +2 -2
- package/dist/sdk/cli-contracts/typed-action-inputs.js +0 -1
- package/dist/sdk/cli-contracts.js +1 -1
- package/dist/sdk/cli-program.js +1 -1
- package/dist/sdk/command-line.js +1 -1
- package/dist/sdk/comments.js +1 -1
- package/dist/sdk/compile-cache.js +1 -1
- package/dist/sdk/completion/bash.js +2 -2
- package/dist/sdk/completion/fish.js +74 -73
- package/dist/sdk/completion/shared.js +1 -1
- package/dist/sdk/completion/zsh.js +77 -76
- package/dist/sdk/completion.js +1 -1
- package/dist/sdk/config.js +1 -1
- package/dist/sdk/context/recency.js +1 -1
- package/dist/sdk/context/semantic-session-attribution.js +1 -1
- package/dist/sdk/context/usage-egress.js +1 -1
- package/dist/sdk/context/usage-ledger.js +6 -6
- package/dist/sdk/context-intent-contracts.js +1 -1
- package/dist/sdk/context-intent-runtime.js +1 -1
- package/dist/sdk/context-packing.js +1 -1
- package/dist/sdk/context-relevance.js +1 -1
- package/dist/sdk/context-signal-store.js +2 -2
- package/dist/sdk/context-usage.js +1 -1
- package/dist/sdk/dependencies/context-budget-recovery.js +1 -1
- package/dist/sdk/dependencies.js +1 -1
- package/dist/sdk/dependency-flag-validation.js +1 -1
- package/dist/sdk/dependency-provenance.js +1 -1
- package/dist/sdk/docs.js +1 -1
- package/dist/sdk/duplicates.js +1 -1
- package/dist/sdk/environment/host-environment-errors.js +1 -1
- package/dist/sdk/environment/project-runtime-compatibility.js +2 -2
- package/dist/sdk/environment/source-context.js +1 -1
- package/dist/sdk/environment/tracker-preflight.js +1 -1
- package/dist/sdk/error-code-catalog.js +1 -1
- package/dist/sdk/error-runtime.js +1 -1
- package/dist/sdk/errors.js +1 -1
- package/dist/sdk/eval.js +1 -1
- package/dist/sdk/extension/author-manifest.js +1 -1
- package/dist/sdk/extension/bundled-catalog.js +1 -1
- package/dist/sdk/extension/command-options.js +1 -1
- package/dist/sdk/extension/concurrency.js +1 -1
- package/dist/sdk/extension/copy-scope.js +1 -1
- package/dist/sdk/extension/custom-field-collisions.js +1 -1
- package/dist/sdk/extension/describe.js +3 -3
- package/dist/sdk/extension/doctor.js +1 -1
- package/dist/sdk/extension/install-plan.js +1 -1
- package/dist/sdk/extension/install-receipts.js +1 -1
- package/dist/sdk/extension/install-runtime.js +3 -3
- package/dist/sdk/extension/install-snapshot.js +1 -1
- package/dist/sdk/extension/install-sources.js +5 -5
- package/dist/sdk/extension/managed-state.js +2 -2
- package/dist/sdk/extension/managed-update-status.js +1 -1
- package/dist/sdk/extension/migrations.js +2 -2
- package/dist/sdk/extension/native-command-options.js +1 -1
- package/dist/sdk/extension/output-ownership.js +1 -1
- package/dist/sdk/extension/runtime-summary.js +1 -1
- package/dist/sdk/extension/scaffold.js +11 -11
- package/dist/sdk/extension/shared.js +1 -1
- package/dist/sdk/extension/source-resolution.js +1 -1
- package/dist/sdk/extension/static-inventory.js +1 -1
- package/dist/sdk/extension/update-check.js +1 -1
- package/dist/sdk/extension-command-context.js +2 -2
- package/dist/sdk/extension-contracts.js +1 -1
- package/dist/sdk/extension.js +1 -1
- package/dist/sdk/files.js +1 -1
- package/dist/sdk/flag-invocation-contracts.js +1 -1
- package/dist/sdk/generated/error-code-catalog-rows.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
- package/dist/sdk/generated-error-code-catalog.js +1 -1
- package/dist/sdk/governance/assurance-action-contracts.js +0 -1
- package/dist/sdk/governance/assurance-action.js +1 -1
- package/dist/sdk/governance/assurance-limits.js +1 -1
- package/dist/sdk/governance/assurance-mutation-error.js +1 -1
- package/dist/sdk/governance/assurance-presets.js +1 -1
- package/dist/sdk/governance/assurance-runtime.js +1 -1
- package/dist/sdk/governance/assurance.js +4 -4
- package/dist/sdk/governance/boundary-fixtures.js +1 -1
- package/dist/sdk/governance/closure-timestamps.js +1 -1
- package/dist/sdk/governance/defect-recurrence-coverage.js +1 -1
- package/dist/sdk/governance/defect-recurrence-graph.js +1 -1
- package/dist/sdk/governance/defect-recurrence-signals.js +1 -1
- package/dist/sdk/governance/defect-recurrence.js +2 -2
- package/dist/sdk/governance/extension-host-version.js +1 -1
- package/dist/sdk/governance/gc.js +1 -1
- package/dist/sdk/governance/health/history-drift-remedies.js +2 -0
- package/dist/sdk/governance/health/projection.js +1 -1
- package/dist/sdk/governance/health-merge-evidence.js +1 -1
- package/dist/sdk/governance/health.js +2 -2
- package/dist/sdk/governance/hierarchy-validation.js +1 -1
- package/dist/sdk/governance/in-progress-work-health.js +1 -1
- package/dist/sdk/governance/lifecycle-dependency-cycles.js +1 -1
- package/dist/sdk/governance/linked-file-report.js +1 -1
- package/dist/sdk/governance/merge-receipt-history.js +1 -1
- package/dist/sdk/governance/provenance-health.js +4 -4
- package/dist/sdk/governance/reindex.js +5 -5
- package/dist/sdk/governance/stale-work.js +1 -1
- package/dist/sdk/governance/status-role-diagnostics.js +1 -1
- package/dist/sdk/governance/storage-integrity.js +1 -1
- package/dist/sdk/governance/tracked-runtime-cache.js +1 -1
- package/dist/sdk/governance/upgrade.js +2 -2
- package/dist/sdk/governance/validate-deferred-fields.js +1 -1
- package/dist/sdk/governance/validate-history-drift.js +1 -1
- package/dist/sdk/governance/validate-item-reader.js +1 -1
- package/dist/sdk/governance/validate-normalization.js +1 -1
- package/dist/sdk/governance/validate.js +1 -1
- package/dist/sdk/governance/workflow-completeness.js +1 -1
- package/dist/sdk/governance/workflow-policy.js +3 -3
- package/dist/sdk/governance/workspace-position.js +2 -2
- package/dist/sdk/graph/analytics.js +1 -1
- package/dist/sdk/graph/assembly.js +1 -1
- package/dist/sdk/graph/cache.js +1 -1
- package/dist/sdk/graph/cardinality-integrity.js +1 -1
- package/dist/sdk/graph/centrality.js +1 -1
- package/dist/sdk/graph/deadline-scheduling.js +1 -1
- package/dist/sdk/graph/durable-cache.js +1 -1
- package/dist/sdk/graph/governance-contracts.js +1 -1
- package/dist/sdk/graph/governance.js +1 -1
- package/dist/sdk/graph/hierarchy-integrity.js +1 -1
- package/dist/sdk/graph/lifecycle-coverage.js +1 -1
- package/dist/sdk/graph/mutation-advisory.js +1 -1
- package/dist/sdk/graph/query-contracts.js +1 -1
- package/dist/sdk/graph/remediation.js +1 -1
- package/dist/sdk/graph/run.js +1 -1
- package/dist/sdk/graph/scheduling.js +1 -1
- package/dist/sdk/graph/traversal.js +1 -1
- package/dist/sdk/graph/workspace-relationship-kind-registry.js +1 -1
- package/dist/sdk/guide-topics.js +1 -1
- package/dist/sdk/guide.js +7 -7
- package/dist/sdk/history/append-only-repair.d.ts +30 -0
- package/dist/sdk/history/append-only-repair.js +6 -0
- package/dist/sdk/history/attestation-command.js +2 -2
- package/dist/sdk/history/attestation-contract.js +1 -1
- package/dist/sdk/history/attestation-scan.js +1 -1
- package/dist/sdk/history/attestation.js +1 -1
- package/dist/sdk/history/maintenance.d.ts +8 -2
- package/dist/sdk/history/maintenance.js +1 -1
- package/dist/sdk/history/reanchor-refusal.js +2 -0
- package/dist/sdk/history/reseed.d.ts +15 -0
- package/dist/sdk/history/reseed.js +2 -0
- package/dist/sdk/history/salvage.d.ts +19 -8
- package/dist/sdk/history/salvage.js +5 -3
- package/dist/sdk/history/subject.js +1 -1
- package/dist/sdk/history-analytics.js +1 -1
- package/dist/sdk/history-compact.js +1 -1
- package/dist/sdk/history-mcp.js +1 -1
- package/dist/sdk/history-provenance.js +1 -1
- package/dist/sdk/history-read.js +1 -1
- package/dist/sdk/history-redact.js +1 -1
- package/dist/sdk/history-repair.d.ts +8 -2
- package/dist/sdk/history-repair.js +1 -1
- package/dist/sdk/improvement-ledger-validation.js +1 -1
- package/dist/sdk/improvement-ledger.js +2 -2
- package/dist/sdk/index.d.ts +1 -1
- package/dist/sdk/init-agent-guidance.js +10 -10
- package/dist/sdk/init.js +14 -14
- package/dist/sdk/invocation-author.js +1 -1
- package/dist/sdk/item-children.js +1 -1
- package/dist/sdk/item-metadata-index.js +1 -1
- package/dist/sdk/item-schedule.js +1 -1
- package/dist/sdk/item-transaction.d.ts +33 -1
- package/dist/sdk/item-transaction.js +1 -1
- package/dist/sdk/learnings.js +1 -1
- package/dist/sdk/lifecycle/append.js +3 -3
- package/dist/sdk/lifecycle/checkpoint-rollback.js +1 -1
- package/dist/sdk/lifecycle/claim.js +1 -1
- package/dist/sdk/lifecycle/cli-input.js +1 -1
- package/dist/sdk/lifecycle/close-many.js +1 -1
- package/dist/sdk/lifecycle/close.js +1 -1
- package/dist/sdk/lifecycle/copy.js +1 -1
- package/dist/sdk/lifecycle/core-field-recovery.js +1 -1
- package/dist/sdk/lifecycle/core-item-fields.js +1 -1
- package/dist/sdk/lifecycle/create-deferrals.js +1 -1
- package/dist/sdk/lifecycle/create.js +1 -1
- package/dist/sdk/lifecycle/delete.js +1 -1
- package/dist/sdk/lifecycle/dependency-removal.js +1 -1
- package/dist/sdk/lifecycle/event-validation-messages.js +1 -1
- package/dist/sdk/lifecycle/focus.js +1 -1
- package/dist/sdk/lifecycle/hierarchy-mutation-lock.js +1 -1
- package/dist/sdk/lifecycle/item-revision.js +1 -1
- package/dist/sdk/lifecycle/legacy-none-tokens.js +1 -1
- package/dist/sdk/lifecycle/lifecycle-transitions.js +1 -1
- package/dist/sdk/lifecycle/mcp-actions.js +1 -1
- package/dist/sdk/lifecycle/metadata-normalizers.js +1 -1
- package/dist/sdk/lifecycle/mutation-command-options.js +0 -1
- package/dist/sdk/lifecycle/mutation-facet-contracts.js +1 -1
- package/dist/sdk/lifecycle/mutation-option-validation.js +1 -1
- package/dist/sdk/lifecycle/plan-mutation-receipt.js +1 -1
- package/dist/sdk/lifecycle/plan.js +1 -1
- package/dist/sdk/lifecycle/recurrence-parsers.js +1 -1
- package/dist/sdk/lifecycle/release-handoff.js +1 -1
- package/dist/sdk/lifecycle/reopen.js +1 -1
- package/dist/sdk/lifecycle/repeatable-metadata-parsers.js +2 -2
- package/dist/sdk/lifecycle/repeated-terminal-state.js +1 -1
- package/dist/sdk/lifecycle/restore.js +1 -1
- package/dist/sdk/lifecycle/shared-unset-fields.js +1 -1
- package/dist/sdk/lifecycle/start-blockers.js +1 -1
- package/dist/sdk/lifecycle/structured-mutation-plan.js +1 -1
- package/dist/sdk/lifecycle/task-composition.js +1 -1
- package/dist/sdk/lifecycle/update-many.js +1 -1
- package/dist/sdk/lifecycle/update.js +2 -2
- package/dist/sdk/lifecycle/workflow-transition.js +1 -1
- package/dist/sdk/lifecycle-completion.js +1 -1
- package/dist/sdk/lifecycle-policy.js +1 -1
- package/dist/sdk/linked-artifacts.js +2 -2
- package/dist/sdk/mcp/apps.js +5 -5
- package/dist/sdk/mcp/authorization.js +1 -1
- package/dist/sdk/mcp/discovery.js +1 -1
- package/dist/sdk/mcp/executable.js +4 -4
- package/dist/sdk/mcp/interactions.js +1 -1
- package/dist/sdk/mcp/protocol.js +1 -1
- package/dist/sdk/mcp/skills.js +3 -3
- package/dist/sdk/mcp/subscriptions.js +1 -1
- package/dist/sdk/mcp/tasks.js +2 -2
- package/dist/sdk/mcp/transport.js +1 -1
- package/dist/sdk/merge/abandoned-receipts.js +1 -1
- package/dist/sdk/merge/driver.js +7 -7
- package/dist/sdk/merge/history-scalar-rebase.js +1 -1
- package/dist/sdk/merge/ignored-artifacts.js +1 -1
- package/dist/sdk/merge/index.js +1 -1
- package/dist/sdk/merge/indexed-receipt-blobs.js +2 -2
- package/dist/sdk/merge/install.js +6 -6
- package/dist/sdk/merge/receipt-file-boundary.js +1 -1
- package/dist/sdk/merge/receipt-operation.js +1 -1
- package/dist/sdk/merge/receipt-schema.js +1 -1
- package/dist/sdk/merge/receipts.js +4 -4
- package/dist/sdk/merge/reconcile.js +1 -1
- package/dist/sdk/merge/settlement-hook.js +4 -4
- package/dist/sdk/merge/stage.js +1 -1
- package/dist/sdk/merge/three-way.d.ts +22 -3
- package/dist/sdk/merge/three-way.js +9 -3
- package/dist/sdk/merge/worktree-config.js +2 -2
- package/dist/sdk/merge.js +1 -1
- package/dist/sdk/mutation-events.js +1 -1
- package/dist/sdk/mutation-guard.js +1 -1
- package/dist/sdk/notes.js +1 -1
- package/dist/sdk/output/fit-envelope.js +1 -1
- package/dist/sdk/output/list-envelope.js +1 -1
- package/dist/sdk/output/table-rows.js +1 -1
- package/dist/sdk/output-contracts.js +1 -1
- package/dist/sdk/output-projection.js +1 -1
- package/dist/sdk/output-token-accounting.js +1 -1
- package/dist/sdk/output.js +2 -2
- package/dist/sdk/ownership-source.js +1 -1
- package/dist/sdk/package-import-adapters.js +1 -1
- package/dist/sdk/package-migrations.js +1 -1
- package/dist/sdk/package-runtime-options.js +1 -1
- package/dist/sdk/pagination.js +1 -1
- package/dist/sdk/profile.js +5 -5
- package/dist/sdk/provenance.js +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/query/activity.js +1 -1
- package/dist/sdk/query/aggregate.js +1 -1
- package/dist/sdk/query/calendar.js +4 -4
- package/dist/sdk/query/complete-list.js +1 -1
- package/dist/sdk/query/context.js +2 -2
- package/dist/sdk/query/declared-blockers.js +1 -1
- package/dist/sdk/query/duplicate-candidates.js +1 -1
- package/dist/sdk/query/get-facet-roots.js +1 -1
- package/dist/sdk/query/get.js +1 -1
- package/dist/sdk/query/history.js +1 -1
- package/dist/sdk/query/item-filter-options.js +0 -1
- package/dist/sdk/query/light-metadata.js +1 -1
- package/dist/sdk/query/list-filter-shared.js +1 -1
- package/dist/sdk/query/list.js +1 -1
- package/dist/sdk/query/multi-value-filters.js +1 -1
- package/dist/sdk/query/next-ranking-policy.js +1 -1
- package/dist/sdk/query/next-ready-budget.js +1 -1
- package/dist/sdk/query/next.js +2 -2
- package/dist/sdk/query/parsers.js +1 -1
- package/dist/sdk/query/projection-contracts.js +1 -1
- package/dist/sdk/query/search/corpus.js +2 -2
- package/dist/sdk/query/search/filters.js +1 -1
- package/dist/sdk/query/search/input.js +1 -1
- package/dist/sdk/query/search/lexical.js +1 -1
- package/dist/sdk/query/search/response.js +1 -1
- package/dist/sdk/query/search/semantic.js +3 -3
- package/dist/sdk/query/search/types.js +0 -1
- package/dist/sdk/query/search-contracts.js +1 -1
- package/dist/sdk/query/search-pagination.js +1 -1
- package/dist/sdk/query/search-rendering.js +1 -1
- package/dist/sdk/query/search.js +1 -1
- package/dist/sdk/query/window-pagination.js +1 -1
- package/dist/sdk/query/workspace-contracts.js +1 -1
- package/dist/sdk/read-output/continuation.js +1 -1
- package/dist/sdk/read-output/extension.js +1 -1
- package/dist/sdk/read-output/options.js +1 -1
- package/dist/sdk/read-output/positional-rows.js +1 -1
- package/dist/sdk/read-output/provenance.js +1 -1
- package/dist/sdk/read-output/session-result.js +0 -1
- package/dist/sdk/read-output/surfaces.js +1 -1
- package/dist/sdk/read-output/tail-retention.js +1 -1
- package/dist/sdk/read-output-budget.js +1 -1
- package/dist/sdk/read-output-contracts.js +1 -1
- package/dist/sdk/read-output-rows.js +1 -1
- package/dist/sdk/read-output-session.js +1 -1
- package/dist/sdk/relationship-analytics.js +1 -1
- package/dist/sdk/relationship-context.js +1 -1
- package/dist/sdk/relationship-history.js +6 -6
- package/dist/sdk/relationship-kinds/contract.js +1 -1
- package/dist/sdk/relationships.js +1 -1
- package/dist/sdk/reproducibility/process.js +1 -1
- package/dist/sdk/runtime/actions.js +1 -1
- package/dist/sdk/runtime/context.js +1 -1
- package/dist/sdk/runtime/mutation-admission.js +1 -1
- package/dist/sdk/runtime/mutation-value-validation.js +1 -1
- package/dist/sdk/runtime/schema-preview.js +1 -1
- package/dist/sdk/runtime/schema.js +1 -1
- package/dist/sdk/runtime-action-aliases.js +1 -1
- package/dist/sdk/runtime-extended-actions.js +1 -1
- package/dist/sdk/runtime-input.d.ts +8 -2
- package/dist/sdk/runtime-input.js +1 -1
- package/dist/sdk/runtime-primitives.d.ts +1 -1
- package/dist/sdk/runtime-primitives.js +1 -1
- package/dist/sdk/runtime-public-contracts.js +0 -1
- package/dist/sdk/runtime-stats-options.js +1 -1
- package/dist/sdk/runtime.d.ts +9 -0
- package/dist/sdk/runtime.js +1 -1
- package/dist/sdk/scheduling-shortcuts.js +1 -1
- package/dist/sdk/schema/field-option-collisions.js +2 -0
- package/dist/sdk/schema-migration.js +4 -4
- package/dist/sdk/schema.js +7 -7
- package/dist/sdk/search-refresh-worker.js +1 -1
- package/dist/sdk/similarity-scoring.js +1 -1
- package/dist/sdk/similarity.js +1 -1
- package/dist/sdk/start-task-status.js +1 -1
- package/dist/sdk/stats.js +1 -1
- package/dist/sdk/structured-mutations.d.ts +5 -5
- package/dist/sdk/structured-mutations.js +1 -1
- package/dist/sdk/telemetry-flush.js +1 -1
- package/dist/sdk/telemetry.js +4 -4
- package/dist/sdk/templates.js +3 -3
- package/dist/sdk/test/batch.js +2 -2
- package/dist/sdk/test/command-args.js +1 -1
- package/dist/sdk/test/command-resolution.js +2 -2
- package/dist/sdk/test/entry.js +2 -2
- package/dist/sdk/test/execution-receipts.js +2 -2
- package/dist/sdk/test/execution.js +5 -5
- package/dist/sdk/test/json-path.js +1 -1
- package/dist/sdk/test/linked-command-detection.js +1 -1
- package/dist/sdk/test/measurements.js +1 -1
- package/dist/sdk/test/parsers.js +1 -1
- package/dist/sdk/test/prerequisites.js +1 -1
- package/dist/sdk/test/receipt-index-snapshot.js +1 -1
- package/dist/sdk/test/run-phases.js +1 -1
- package/dist/sdk/test/runs.js +1 -1
- package/dist/sdk/test/trust.js +2 -2
- package/dist/sdk/test/update.js +1 -1
- package/dist/sdk/test/workspace-snapshot.js +1 -1
- package/dist/sdk/traceability/runtime-files-lookup.js +1 -1
- package/dist/sdk/traceability/source-traceability.js +2 -2
- package/dist/sdk/tracker-root-discovery.js +1 -1
- package/dist/sdk/transactions/item-finalization.js +2 -0
- package/dist/sdk/workspace-contracts-cache.js +1 -1
- package/dist/sdk/workspace-contracts.js +1 -1
- package/dist/sdk/workspace-memory.js +2 -2
- package/dist/sdk/workspace-snapshot.js +5 -5
- package/dist/sdk/workspace-transaction-gc.js +1 -1
- package/dist/sdk/workspace-transaction.js +2 -2
- package/dist/sdk/workspace.js +6 -6
- package/dist/types/index.js +1 -1
- package/dist/types.d.ts +20 -0
- package/dist/types.js +1 -1
- package/docs/AGENT_GUIDE.md +1 -1
- package/docs/AGENT_RUNTIME_PRIMITIVES.md +1 -1
- package/docs/COMMANDS.md +7 -3
- package/docs/EXTENSIONS.md +1 -1
- package/docs/HISTORY_RECOVERY.md +229 -5
- package/docs/README.md +2 -2
- package/docs/SDK.md +174 -5
- package/docs/SDK_CONTEXT_COORDINATION.md +3 -2
- package/marketplace.json +1 -1
- package/node_modules/tar/package.json +2 -3
- package/package.json +31 -2
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-claude/package.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/plugins/pm-codex/package.json +1 -1
- package/plugins/pm-codex/plugin.json +1 -1
- package/runtime-dependencies.json +1 -1
- package/scripts/finalize-build.mjs +63 -24
- package/scripts/prepare-build-cache.mjs +28 -1
- package/dist/cli-bundle/chunks/chunk-2DXRTIC6.js +0 -21
- package/dist/cli-bundle/chunks/chunk-5647LU3A.js +0 -2287
- package/dist/cli-bundle/chunks/chunk-6QLEXRUG.js +0 -9
- package/dist/cli-bundle/chunks/chunk-AHQB7W2H.js +0 -3
- package/dist/cli-bundle/chunks/chunk-BKSVHOWI.js +0 -2
- package/dist/cli-bundle/chunks/chunk-CASX6SFI.js +0 -2
- package/dist/cli-bundle/chunks/chunk-CIKGG34F.js +0 -2
- package/dist/cli-bundle/chunks/chunk-D6ILFXZY.js +0 -2
- package/dist/cli-bundle/chunks/chunk-DEZPZOQ7.js +0 -2
- package/dist/cli-bundle/chunks/chunk-IB7UB5TE.js +0 -2
- package/dist/cli-bundle/chunks/chunk-IUIOTAF6.js +0 -9
- package/dist/cli-bundle/chunks/chunk-JVGRFU5H.js +0 -3
- package/dist/cli-bundle/chunks/chunk-KQIZ34SF.js +0 -3
- package/dist/cli-bundle/chunks/chunk-KVBIMFUG.js +0 -6
- package/dist/cli-bundle/chunks/chunk-LQBWLNZJ.js +0 -3
- package/dist/cli-bundle/chunks/chunk-NCFCBKIP.js +0 -2
- package/dist/cli-bundle/chunks/chunk-NT5AKFE5.js +0 -31
- package/dist/cli-bundle/chunks/chunk-PJXKA4QU.js +0 -125
- package/dist/cli-bundle/chunks/chunk-RMIRNYRG.js +0 -71
- package/dist/cli-bundle/chunks/chunk-RULHZRFN.js +0 -2
- package/dist/cli-bundle/chunks/chunk-S6HB3WL2.js +0 -2
- package/dist/cli-bundle/chunks/chunk-SA4BNP3Q.js +0 -2
- package/dist/cli-bundle/chunks/chunk-SPPHDVZE.js +0 -2
- package/dist/cli-bundle/chunks/chunk-SRVTCYAU.js +0 -2
- package/dist/cli-bundle/chunks/chunk-WELSVDPU.js +0 -2
- package/dist/cli-bundle/chunks/chunk-XHJ3H5PL.js +0 -3
- package/dist/cli-bundle/chunks/chunk-XWHJIRNV.js +0 -8
- package/dist/cli-bundle/chunks/chunk-YJEBK7HU.js +0 -8
- package/dist/cli-bundle/chunks/chunk-YKJKQ7DM.js +0 -115
- package/dist/cli-bundle/chunks/chunk-YMUSRWV4.js +0 -9
- package/dist/cli-bundle/chunks/chunk-YR2KEBHP.js +0 -2
- package/dist/cli-bundle/chunks/context-budget-recovery-L2WP5S26.js +0 -2
- package/dist/cli-bundle/chunks/indexed-receipt-blobs-ITTXIN4K.js +0 -4
- package/dist/cli-bundle/chunks/item-transaction-7DFCG73I.js +0 -2
- package/dist/cli-bundle/chunks/mutation-actor-3TG636XG.js +0 -2
- package/dist/cli-bundle/chunks/mutation-admission-LICSDNNO.js +0 -2
- package/dist/cli-bundle/chunks/register-mutation-WWVECKFQ.js +0 -21
- package/dist/cli-bundle/chunks/register-operations-L6HFJNWD.js +0 -2
- package/dist/cli-bundle/chunks/register-setup-K7UFG5TD.js +0 -2
- package/dist/cli-bundle/chunks/settlement-hook-BXN5LEQD.js +0 -7
- package/dist/cli-bundle/chunks/stage-57KH3KAC.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-3IRCYJI5.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-3V53UBHN.js +0 -9
- package/dist/cli-bundle/focused-chunks/chunk-532WZV65.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-7A4QWNZX.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-C3O6JJPO.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-CR7CGEB2.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-CU2BRAOX.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-CWWKRI5P.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-EGN2HFRU.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-GHQVM6K6.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-HGFNL5XI.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-I5LGPUWH.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-IQK5NPMG.js +0 -13
- package/dist/cli-bundle/focused-chunks/chunk-J63D6QST.js +0 -6
- package/dist/cli-bundle/focused-chunks/chunk-JMQJBZQ5.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-LNHUE4VV.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-MKM5NKD7.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-NP72ZDXE.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-OSLQD5VH.js +0 -102
- package/dist/cli-bundle/focused-chunks/chunk-QGKLRXP7.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-QSJW6NSQ.js +0 -66
- package/dist/cli-bundle/focused-chunks/chunk-RPE6IX26.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-SRDQSA6M.js +0 -91
- package/dist/cli-bundle/focused-chunks/chunk-SVOOGGAK.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-UOC6257J.js +0 -26
- package/dist/cli-bundle/focused-chunks/chunk-URJ2E6AS.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-WXMI4AV5.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-XCJSHNXK.js +0 -27
- package/dist/cli-bundle/focused-chunks/chunk-XQQSSKJI.js +0 -44
- package/dist/cli-bundle/focused-chunks/chunk-YOAYY3HE.js +0 -2
- package/dist/cli-bundle/focused-chunks/context-budget-recovery-5MKOCGY5.js +0 -2
- package/dist/cli-bundle/focused-chunks/indexed-receipt-blobs-AF4U3F3D.js +0 -4
- package/dist/cli-bundle/focused-chunks/item-transaction-HLBW7B3J.js +0 -2
- package/dist/cli-bundle/focused-chunks/mutation-actor-62HKR5IO.js +0 -2
- package/dist/cli-bundle/focused-chunks/mutation-admission-X4PF2SG3.js +0 -2
- package/dist/cli-bundle/focused-chunks/settlement-hook-ARYCZQY4.js +0 -7
- package/dist/cli-bundle/focused-chunks/stage-O7T7CXBB.js +0 -2
- package/dist/sdk/agent/refusal-closure.js +0 -2
- package/dist/sdk/agent/refusal-reachability.js +0 -4
- package/dist/sdk/agent/task-transcript-contracts.js +0 -2
- package/dist/sdk/agent/tracker-preflight-contracts.js +0 -2
- package/dist/sdk/authoring.js +0 -2
- package/dist/sdk/compose.js +0 -2
- package/dist/sdk/contracts.js +0 -2
- package/dist/sdk/core-governance.js +0 -2
- package/dist/sdk/core.js +0 -2
- package/dist/sdk/corpus-shape.js +0 -2
- package/dist/sdk/define.js +0 -2
- package/dist/sdk/environment/agent-environment.js +0 -2
- package/dist/sdk/governance/artifact-ledgers.js +0 -2
- package/dist/sdk/governance/coverage-assurance.js +0 -2
- package/dist/sdk/governance/reliability.js +0 -2
- package/dist/sdk/governance.js +0 -2
- package/dist/sdk/graph/adapter.js +0 -2
- package/dist/sdk/graph/conformance.js +0 -2
- package/dist/sdk/graph/index.js +0 -2
- package/dist/sdk/graph.js +0 -2
- package/dist/sdk/index.js +0 -2
- package/dist/sdk/query.js +0 -2
- package/dist/sdk/relationship-migration.js +0 -2
- package/dist/sdk/testing.js +0 -8
- package/dist/sdk/workspace-recipe.js +0 -2
- package/docs/AGENT_PROVENANCE_ADR.md +0 -206
- package/docs/DEFECT_RECURRENCE.md +0 -257
- package/docs/PERFORMANCE.md +0 -204
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
|
|
2
|
-
`,{createParentDirectories:!
|
|
3
|
-
`)),resolved}function hashWithInstallationId(installationId,value){return crypto.createHash("sha256").update(`${installationId}:${value}`).digest("hex")}function buildAuthorContextPayloadFields(captureLevel,installationId){const author=(readAuthorEnvironment()??"").trim(),agent=detectAgentIdentity({env:process.env,argv:process.argv}),hasAgentContext=agent.harness!==void 0||agent.model!==void 0;return captureLevel==="minimal"?{has_author_context:author.length>0,has_agent_context:hasAgentContext}:{agent_harness:agent.harness?TELEMETRY_HARNESSES.has(agent.harness)?agent.harness:"other":"none",ci:parseBooleanTrueLike(process.env.CI),...author.length>0?{author_context_hash:hashWithInstallationId(installationId,author)}:{},...agent.harness?{agent_harness_hash:hashWithInstallationId(installationId,agent.harness)}:{},...agent.model?{agent_model_hash:hashWithInstallationId(installationId,agent.model)}:{},...agent.model_source?{agent_model_source:agent.model_source}:{}}}function normalizeForHash(value,depth=0){if(value==null||typeof value=="string"||typeof value=="number"||typeof value=="boolean")return value;if(depth>=TELEMETRY_SANITIZE_MAX_DEPTH)return"[depth_truncated]";if(Array.isArray(value))return value.slice(0,TELEMETRY_SANITIZE_MAX_ARRAY_ITEMS).map(entry=>normalizeForHash(entry,depth+1));if(typeof value=="object"){const record=value,normalized={},sortedKeys=Object.keys(record).sort((left,right)=>left.localeCompare(right));for(const key of sortedKeys)normalized[key]=normalizeForHash(record[key],depth+1);return normalized}return String(value)}function hashTelemetryValue(installationId,value){return hashWithInstallationId(installationId,JSON.stringify(normalizeForHash(value)))}function hashCommandArgs(installationId,args){return{hashes:args.map(arg=>hashWithInstallationId(installationId,arg)),digest:hashWithInstallationId(installationId,args.join("\0"))}}function hashTelemetryErrorFingerprint(installationId,command,errorCode2,errorMessage){const normalizedMessage=sanitizeString(typeof errorMessage=="string"?errorMessage:"","redacted"),normalizedCode=typeof errorCode2=="string"&&errorCode2.length>0?errorCode2:"unknown_error",fingerprintSource=`${command}\0${normalizedCode}\0${normalizedMessage}`;return hashWithInstallationId(installationId,fingerprintSource)}function resolveOtelTracesEndpoint(){if(PM_TELEMETRY_OTEL_DISABLED_VALUES.has((process.env[PM_TELEMETRY_OTEL_DISABLED_ENV]??"").trim().toLowerCase()))return null;const directEndpoint=(process.env[OTEL_TRACES_ENDPOINT_ENV]??"").trim();if(directEndpoint.length>0)try{return new URL(directEndpoint).toString()}catch{return null}const baseEndpoint=(process.env[OTEL_BASE_ENDPOINT_ENV]??"").trim();if(baseEndpoint.length===0)return null;try{const url=new URL(baseEndpoint),normalizedPath=url.pathname.replace(/\/+$/,"");return normalizedPath.endsWith("/v1/traces")||(url.pathname=`${normalizedPath.length===0?"":normalizedPath}/v1/traces`),url.toString()}catch{return null}}function isoToUnixNano(iso){const parsedMs=Date.parse(iso),epochMs=Number.isNaN(parsedMs)?Date.now():parsedMs;return`${BigInt(epochMs)*1000000n}`}function otlpStringAttribute(key,value){return{key,value:{stringValue:value}}}function otlpBoolAttribute(key,value){return{key,value:{boolValue:value}}}function otlpIntAttribute(key,value){return{key,value:{intValue:String(Math.max(0,Math.trunc(value)))}}}function buildOtelSpanRequest(activeCommand,outcome,finishedAtIso,durationMs,sampleRate=1){const endpoint=activeCommand.otel_traces_endpoint;if(typeof endpoint!="string"||endpoint.trim().length===0||[activeCommand.otel_trace_id,activeCommand.otel_span_id].some(id=>typeof id!="string"||id.length===0))return null;const serviceNameCandidate=sanitizeString((process.env[OTEL_SERVICE_NAME_ENV]??"").trim()),serviceName=serviceNameCandidate.length>0?serviceNameCandidate:"pm-cli",normalizedExitCode=normalizeTelemetryExitCode(outcome.exit_code,outcome.ok),normalizedErrorCode=normalizeTelemetryErrorCode(outcome.error_code),normalizedErrorCategory=normalizeTelemetryErrorCategory({ok:outcome.ok,errorCode:normalizedErrorCode,errorCategory:outcome.error_category}),attributes=[otlpStringAttribute("pm.command",sanitizeString(activeCommand.command)),otlpStringAttribute("pm.version",activeCommand.pm_version),otlpStringAttribute("pm.source_context",activeCommand.source_context),otlpStringAttribute("pm.source_context_source",activeCommand.source_context_source),otlpStringAttribute("pm.installation_id",activeCommand.installation_id),otlpStringAttribute("pm.session_id",PROCESS_SESSION_ID),otlpStringAttribute("pm.pm_root_hash",activeCommand.pm_root_hash),otlpStringAttribute("pm.cwd_hash",activeCommand.cwd_hash),otlpBoolAttribute("pm.ok",outcome.ok),otlpIntAttribute("pm.exit_code",normalizedExitCode),otlpIntAttribute("pm.duration_ms",durationMs),otlpStringAttribute("pm.sample_rate",String(sampleRate))];typeof normalizedErrorCode=="string"&&attributes.push(otlpStringAttribute("pm.error_code",normalizedErrorCode)),typeof normalizedErrorCategory=="string"&&attributes.push(otlpStringAttribute("pm.error_category",normalizedErrorCategory)),typeof outcome.error=="string"&&outcome.error.trim().length>0&&attributes.push(otlpStringAttribute("pm.error",sanitizeString(outcome.error)));const payload={resourceSpans:[{resource:{attributes:[otlpStringAttribute("service.name",serviceName)]},scopeSpans:[{scope:{name:"pm-cli.telemetry",version:"1"},spans:[{traceId:activeCommand.otel_trace_id,spanId:activeCommand.otel_span_id,name:`pm.command.${sanitizeString(activeCommand.command)}`,kind:1,startTimeUnixNano:isoToUnixNano(activeCommand.started_at),endTimeUnixNano:isoToUnixNano(finishedAtIso),attributes,status:{code:outcome.ok?1:2,message:outcome.ok?"":sanitizeString(typeof outcome.error=="string"?outcome.error:"command_failed")}}]}]}]};return{endpoint,payload}}function summarizeResult(result,captureLevel="redacted"){if(result==null)return{type:"nullish"};if(typeof result=="string")return{type:"string",value:sanitizeString(result,captureLevel)};if(typeof result=="number"||typeof result=="boolean")return{type:typeof result,value:result};if(Array.isArray(result))return{type:"array",length:result.length,sample:result.slice(0,5).map(entry=>sanitizeValue(entry,void 0,captureLevel))};if(typeof result=="object"){const record=result,keys=Object.keys(record).filter(key=>key!=="tests").sort((left,right)=>left.localeCompare(right)),sanitized={};let previewBytes=0;for(const key of keys.slice(0,25)){const sanitizedValue=sanitizeValue(record[key],key,captureLevel);if(sanitizedValue===void 0)continue;const entrySize=JSON.stringify(sanitizedValue).length;if(previewBytes+entrySize>TELEMETRY_RESULT_PREVIEW_MAX_BYTES){sanitized[key]="[preview_truncated]";break}previewBytes+=entrySize,sanitized[key]=sanitizedValue}return{type:"object",key_count:keys.length,keys_preview:keys.slice(0,50),preview:sanitized}}return{type:typeof result,value:String(result)}}function buildCommandStartPayload(params){const{captureLevel,context,pmVersion,sourceContext,pmRootHash,cwdHash,installationId}=params,commandTaxonomy=deriveTelemetryCommandTaxonomy(context.command),hashedArgs=hashCommandArgs(installationId,context.args),commandInvocationDigest=hashWithInstallationId(installationId,`${context.command}\0${context.args.join("\0")}`),commandOptionsDigest=hashTelemetryValue(installationId,context.options),globalOptionsDigest=hashTelemetryValue(installationId,context.global),authorContextFields=buildAuthorContextPayloadFields(captureLevel,installationId);return captureLevel==="minimal"?{capture_level:captureLevel,pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,command_args_digest:hashedArgs.digest,command_invocation_digest:commandInvocationDigest,command_options_digest:commandOptionsDigest,global_options_digest:globalOptionsDigest,...authorContextFields}:{pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,...authorContextFields,command_args:sanitizeCommandArgs(context.args,captureLevel),command_args_hashes:hashedArgs.hashes,command_args_digest:hashedArgs.digest,command_invocation_digest:commandInvocationDigest,command_options:sanitizeValue(context.options,void 0,captureLevel),command_options_digest:commandOptionsDigest,global_options:sanitizeValue(context.global,void 0,captureLevel),global_options_digest:globalOptionsDigest,pm_root_hash:pmRootHash,cwd_hash:cwdHash,capture_level:captureLevel,runtime:{node:process.version,platform:process.platform,arch:process.arch,hostname_hash:hashWithInstallationId(installationId,os.hostname()),stdin_tty:process.stdin.isTTY===!0,stdout_tty:process.stdout.isTTY===!0}}}function buildCommandFinishPayload(params){const{captureLevel,pmVersion,sourceContext,outcome,durationMs,startedAt,command,installationId,commandTaxonomy,exitCode,errorCode:errorCode2,errorCategory,commandResolution,resolutionStage}=params,errorFingerprint=outcome.ok===!1?hashTelemetryErrorFingerprint(installationId,command,errorCode2,outcome.error):void 0,authorContextFields=buildAuthorContextPayloadFields(captureLevel,installationId);return captureLevel==="minimal"?{capture_level:captureLevel,pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,command_resolution:commandResolution,resolution_stage:resolutionStage,ok:outcome.ok,exit_code:exitCode,error_code:errorCode2,error_category:errorCategory,error:outcome.error?sanitizeString(outcome.error,"redacted"):void 0,error_fingerprint:errorFingerprint,duration_ms:durationMs,...authorContextFields}:{capture_level:captureLevel,pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,command_resolution:commandResolution,resolution_stage:resolutionStage,...authorContextFields,ok:outcome.ok,exit_code:exitCode,error_code:errorCode2,error_category:errorCategory,error:outcome.error?sanitizeString(outcome.error,captureLevel):void 0,error_fingerprint:errorFingerprint,duration_ms:durationMs,started_at:startedAt,result_summary:summarizeResult(outcome.result,captureLevel)}}function buildCommandErrorPayload(params){const{captureLevel,pmVersion,sourceContext,command,commandTaxonomy,commandResolution,resolutionStage,args,options,pmRootHash,cwdHash,installationId,errorCode:errorCode2,errorMessage,errorCategory,exitCode}=params,attemptedArgHashes=hashCommandArgs(installationId,args),attemptedCommandDigest=hashWithInstallationId(installationId,command),attemptedOptionsDigest=hashTelemetryValue(installationId,options),errorFingerprint=hashTelemetryErrorFingerprint(installationId,command,errorCode2,errorMessage),authorContextFields=buildAuthorContextPayloadFields(captureLevel,installationId);return captureLevel==="minimal"?{capture_level:captureLevel,pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,command_resolution:commandResolution,resolution_stage:resolutionStage,attempted_command_digest:attemptedCommandDigest,attempted_args_digest:attemptedArgHashes.digest,attempted_options_digest:attemptedOptionsDigest,error_code:errorCode2,error_category:errorCategory,exit_code:exitCode,error:sanitizeString(errorMessage,"redacted"),error_fingerprint:errorFingerprint,...authorContextFields}:{capture_level:captureLevel,pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,command_resolution:commandResolution,resolution_stage:resolutionStage,...authorContextFields,attempted_command:sanitizeString(command,captureLevel),attempted_command_digest:attemptedCommandDigest,attempted_args:sanitizeCommandArgs(args,captureLevel),attempted_args_hashes:attemptedArgHashes.hashes,attempted_args_digest:attemptedArgHashes.digest,attempted_options:sanitizeValue(options,void 0,captureLevel),attempted_options_digest:attemptedOptionsDigest,error_code:errorCode2,error_category:errorCategory,exit_code:exitCode,error:sanitizeString(errorMessage,captureLevel),error_fingerprint:errorFingerprint,pm_root_hash:pmRootHash,cwd_hash:cwdHash,runtime:{node:process.version,platform:process.platform,arch:process.arch,hostname_hash:hashWithInstallationId(installationId,os.hostname()),stdin_tty:process.stdin.isTTY===!0,stdout_tty:process.stdout.isTTY===!0}}}async function ensureInstallationId(globalPmRoot){const settings=await readSettings(globalPmRoot);if(!settings.telemetry.enabled||resolveTelemetryEnvironmentPolicy().telemetry_disabled)return null;if(settings.telemetry.installation_id.trim().length===0){if(isConfigurationOnlySettingsRead(globalPmRoot)||isSettingsReadFallback(settings))return null;settings.telemetry.installation_id=crypto.randomUUID(),await writeSettings(globalPmRoot,settings,"telemetry:install_id")}return{installationId:settings.telemetry.installation_id,endpoint:settings.telemetry.endpoint,retentionDays:Math.max(1,Math.trunc(settings.telemetry.retention_days)),captureLevel:normalizeCaptureLevel(settings.telemetry.capture_level)}}async function appendTelemetryEvent(globalPmRoot,event){let serialized=JSON.stringify({client_schema_version:TELEMETRY_CLIENT_SCHEMA_VERSION,event,attempts:0});if(serialized.length>TELEMETRY_MAX_EVENT_BYTES){const trimmed={...event,payload:{...event.payload,result_summary:{truncated:!0,reason:"payload_size_exceeded",original_bytes:serialized.length}}};serialized=JSON.stringify({client_schema_version:TELEMETRY_CLIENT_SCHEMA_VERSION,event:trimmed,attempts:0})}await appendLineAtomic(queuePath(globalPmRoot),serialized)}async function enqueueTelemetryEvent(globalPmRoot,event){await withQueueMutation(()=>appendTelemetryEvent(globalPmRoot,event),globalPmRoot)}function parseQueueLines(raw){const entries=[];for(const line of raw.split(`
|
|
4
|
-
`)){const
|
|
5
|
-
`),
|
|
6
|
-
`:"";for(let
|
|
7
|
-
`)){const
|
|
8
|
-
`),
|
|
9
|
-
`:"";for(let attempt=0;;attempt+=1)try{await writeFileAtomic(otelSpansQueuePath(globalPmRoot),contents,{createParentDirectories:!parseBooleanTrueLike(process.env[PM_TELEMETRY_FLUSH_CHILD_ENV])});return}catch(error){const retryDelay=TELEMETRY_QUEUE_REWRITE_RETRY_DELAYS_MS[attempt];if(retryDelay===void 0||!isRetryableQueueRewriteError(error))throw error;await sleep(retryDelay)}}async function reconcilePendingOtelSpansAfterFlush(globalPmRoot,retentionDays,succeededIds,failedUpdates){return withQueueMutation(async()=>{const raw=await readFileIfExists(otelSpansQueuePath(globalPmRoot)),current=raw===null?[]:parsePendingOtelSpanLines(raw),reconciled=[];for(const entry of current){if(succeededIds.has(entry.id))continue;const failure=failedUpdates.get(entry.id);reconciled.push(failure?{...entry,attempts:failure.attempts,next_attempt_after:failure.next_attempt_after}:entry)}const{entries:retained}=prunePendingOtelSpans(reconciled,retentionDays);return await rewritePendingOtelSpans(globalPmRoot,retained),retained.length},globalPmRoot)}async function flushPendingOtelSpans(globalPmRoot,retentionDays){const raw=await readFileIfExists(otelSpansQueuePath(globalPmRoot));if(raw===null||raw.trim().length===0){await writeRuntimeState(globalPmRoot,{pending_otel_spans:0},null);return}const entries=parsePendingOtelSpanLines(raw),{entries:retained,prunedCount}=prunePendingOtelSpans(entries,retentionDays),due=retained.filter(entry=>isDueForRetryAt(entry.next_attempt_after)).slice(0,TELEMETRY_OTEL_SPANS_FLUSH_BATCH_SIZE);if(due.length===0){const remaining2=prunedCount>0?await reconcilePendingOtelSpansAfterFlush(globalPmRoot,retentionDays,new Set,new Map):retained.length;await writeRuntimeState(globalPmRoot,{pending_otel_spans:remaining2},null);return}const attemptTime=nowIso(),succeededIds=new Set,failedUpdates=new Map;let succeededCount=0,lastError;await Promise.all(due.map(async span=>{try{const status=await postTelemetryJson(span.endpoint,{"content-type":"application/json"},JSON.stringify(span.payload));if(status<200||status>=300)throw new Error(`local_otel_export_http_${status}`);succeededIds.add(span.id),succeededCount+=1}catch(error){lastError=error instanceof Error?sanitizeString(redactUrlsInText(error.message),"redacted"):"local_otel_export_failed";const nextAttempts=span.attempts+1;failedUpdates.set(span.id,{attempts:nextAttempts,next_attempt_after:nextRetryIso(nextAttempts)})}}));const remaining=await reconcilePendingOtelSpansAfterFlush(globalPmRoot,retentionDays,succeededIds,failedUpdates),statePatch={pending_otel_spans:remaining,last_otel_attempt_at:attemptTime};succeededCount>0&&(statePatch.last_otel_success_at=attemptTime),lastError!==void 0?(statePatch.last_otel_failure_at=attemptTime,statePatch.last_otel_failure_error=lastError):remaining===0&&(statePatch.last_otel_failure_at=void 0,statePatch.last_otel_failure_error=void 0),await writeRuntimeState(globalPmRoot,statePatch,null)}async function flushTelemetryArtifacts(globalPmRoot,endpoint,retentionDays){try{await flushQueue(globalPmRoot,endpoint,retentionDays)}catch{}try{await flushPendingOtelSpans(globalPmRoot,retentionDays)}catch{}}async function cleanupTelemetryQueueTempOrphans(globalPmRoot,maxAgeMs=TELEMETRY_QUEUE_TMP_ORPHAN_MAX_AGE_MS,activeOverride=resolveTelemetryEndpointOverride().endpoint){try{const dirPath=telemetryRuntimeDirectory(globalPmRoot),entries=await readdir(dirPath,{withFileTypes:!0}),now=Date.now(),active=new Set([telemetryRuntimeFileName("events.jsonl",activeOverride),telemetryRuntimeFileName("state.json",activeOverride)]),cutoffFor=name=>{if(!active.has(name))return/^\.events(?:\.[a-f0-9]{16})?\.jsonl\.\d+\.\d+\.[a-f0-9]+\.tmp$/.test(name)?now-Math.max(0,maxAgeMs):/^(?:events\.[a-f0-9]{16}\.jsonl|state\.[a-f0-9]{16}\.json)$/.test(name)?now-TELEMETRY_OVERRIDE_QUEUE_MAX_IDLE_MS:void 0};await Promise.all(entries.map(async entry=>{const cutoffMs=entry.isFile()?cutoffFor(entry.name):void 0;if(cutoffMs===void 0)return;const candidate=path.join(dirPath,entry.name);(await stat(candidate)).mtimeMs<cutoffMs&&await rm(candidate,{force:!0})}))}catch{}}async function withQueueMutation(operation,globalPmRoot=resolveGlobalPmRoot(process.cwd()),waitMs=5e3){const run=_queueMutationPromise.catch(()=>{}).then(()=>runWithIsolatedExtensionRuntime(async()=>{const release=await acquireLock(globalPmRoot,"telemetry-queue",60,"telemetry",!1,!1,waitMs,{createParentDirectories:!parseBooleanTrueLike(process.env[PM_TELEMETRY_FLUSH_CHILD_ENV])});try{return clearSettingsReadCache(globalPmRoot),await operation()}finally{await release()}}));return _queueMutationPromise=run.catch(()=>{}),run}async function readCurrentQueueEntries(globalPmRoot,override=resolveTelemetryEndpointOverride().endpoint){const raw=await readFileIfExists(queuePath(globalPmRoot,override));return raw===null||raw.trim().length===0?[]:parseQueueLines(raw)}async function removeFlushedEntriesFromCurrentQueue(globalPmRoot,flushedIds,retentionDays,override=resolveTelemetryEndpointOverride().endpoint){return withQueueMutation(async()=>{const currentEntries=await readCurrentQueueEntries(globalPmRoot,override),{entries:retainedEntries}=pruneExpiredQueueEntries(currentEntries,retentionDays),remaining=retainedEntries.filter(entry=>!flushedIds.has(entry.event.event_id));return await rewriteQueue(globalPmRoot,remaining,override),remaining},globalPmRoot)}async function markFailedEntriesInCurrentQueue(globalPmRoot,failedIds,attemptTime,retentionDays,override=resolveTelemetryEndpointOverride().endpoint){return withQueueMutation(async()=>{const currentEntries=await readCurrentQueueEntries(globalPmRoot,override),{entries:retainedEntries}=pruneExpiredQueueEntries(currentEntries,retentionDays),retried=retainedEntries.map(entry=>{if(!failedIds.has(entry.event.event_id))return entry;const attempts=entry.attempts+1;return{...entry,attempts,last_attempt_at:attemptTime,next_attempt_after:nextRetryIso(attempts)}});return await rewriteQueue(globalPmRoot,retried,override),retried},globalPmRoot)}function recordedStateEndpoint(endpoint,override){return override===null?endpoint:redactTelemetryEndpoint(endpoint)}async function flushQueue(globalPmRoot,endpoint,retentionDays){const override=resolveTelemetryEndpointOverride().endpoint;await cleanupTelemetryQueueTempOrphans(globalPmRoot,void 0,override);const normalizedEndpoint=(override??endpoint).trim(),stateEndpoint=recordedStateEndpoint(normalizedEndpoint,override),writeState=patch=>writeRuntimeState(globalPmRoot,patch,override);if(normalizedEndpoint.length===0)return;const raw=await readFileIfExists(queuePath(globalPmRoot,override));if(raw===null||raw.trim().length===0){await writeState({endpoint:stateEndpoint,queue_entries:0});return}const queueEntries=parseQueueLines(raw);if(queueEntries.length===0){await writeState({endpoint:stateEndpoint,queue_entries:0});return}const{entries:retainedEntries,prunedCount}=pruneExpiredQueueEntries(queueEntries,retentionDays);if(retainedEntries.length===0){const remaining=await removeFlushedEntriesFromCurrentQueue(globalPmRoot,new Set,retentionDays,override);await writeState({endpoint:stateEndpoint,queue_entries:remaining.length});return}const dueEntries=retainedEntries.filter(entry=>isDueForRetry(entry)).slice(0,TELEMETRY_FLUSH_BATCH_SIZE);if(dueEntries.length===0){const remaining=prunedCount>0?await removeFlushedEntriesFromCurrentQueue(globalPmRoot,new Set,retentionDays,override):retainedEntries;await writeState({endpoint:stateEndpoint,queue_entries:remaining.length});return}const dueIds=new Set(dueEntries.map(entry=>entry.event.event_id)),attemptTime=nowIso(),requestHeaders={"content-type":"application/json"},ingestKey=process.env.PM_TELEMETRY_INGEST_KEY?.trim();ingestKey&&(requestHeaders["x-pm-telemetry-key"]=ingestKey);try{const status=await postTelemetryJson(normalizedEndpoint,requestHeaders,JSON.stringify({schema_version:TELEMETRY_SCHEMA_VERSION,events:dueEntries.map(entry=>entry.event)}));if(status<200||status>=300)throw new Error(`telemetry_flush_http_${status}`)}catch(error){const retried=await markFailedEntriesInCurrentQueue(globalPmRoot,dueIds,attemptTime,retentionDays,override),errorMessage=error instanceof Error?sanitizeString(redactUrlsInText(error.message),"redacted"):"telemetry_flush_failed";await writeState({endpoint:stateEndpoint,queue_entries:retried.length,last_attempted_flush_at:attemptTime,last_failed_flush_at:attemptTime,last_failed_flush_error:errorMessage});return}try{const remaining=await removeFlushedEntriesFromCurrentQueue(globalPmRoot,dueIds,retentionDays,override);await writeState({endpoint:stateEndpoint,queue_entries:remaining.length,last_attempted_flush_at:attemptTime,last_successful_flush_at:attemptTime,last_failed_flush_at:void 0,last_failed_flush_error:void 0})}catch(error){const errorMessage=error instanceof Error?sanitizeString(redactUrlsInText(error.message),"redacted"):"telemetry_flush_failed",currentEntries=await readCurrentQueueEntries(globalPmRoot,override).catch(()=>retainedEntries);await writeState({endpoint:stateEndpoint,queue_entries:currentEntries.length,last_attempted_flush_at:attemptTime,last_failed_flush_at:attemptTime,last_failed_flush_error:errorMessage})}}async function acquireTelemetryFlushLock(globalPmRoot){const lockPath=flushLockPath(globalPmRoot);parseBooleanTrueLike(process.env[PM_TELEMETRY_FLUSH_CHILD_ENV])||await mkdir(path.dirname(lockPath),{recursive:!0});try{return await mkdir(lockPath),!0}catch(error){if(typeof error!="object"||error===null||!("code"in error)||error.code!=="EEXIST")throw error}try{const lockStats=await stat(lockPath);return Date.now()-lockStats.mtimeMs<TELEMETRY_FLUSH_LOCK_STALE_MS?!1:(await rm(lockPath,{recursive:!0,force:!0}),await mkdir(lockPath),!0)}catch{return!1}}function isFreshDirectoryLock(lockPath,staleMs){try{return Date.now()-statSync(lockPath).mtimeMs<staleMs}catch{return!1}}function removeDirectoryLockBestEffort(lockPath){try{rmSync(lockPath,{recursive:!0,force:!0})}catch{}}function errorCode(error){if(typeof error!="object"||error===null||!("code"in error))return;const code=error.code;return typeof code=="string"?code:void 0}function createDirectoryLock(lockPath){try{return mkdirSync(lockPath),!0}catch(error){if(errorCode(error)==="EEXIST"||!isFileMissingError(error))return!1}try{return mkdirSync(path.dirname(lockPath),{recursive:!0}),mkdirSync(lockPath),!0}catch{return!1}}function acquireTelemetryFlushSpawnGate(globalPmRoot){if(isFreshDirectoryLock(flushLockPath(globalPmRoot),TELEMETRY_FLUSH_LOCK_STALE_MS))return!1;const lockPath=flushSpawnLockPath(globalPmRoot);try{if(Date.now()-statSync(lockPath).mtimeMs<TELEMETRY_FLUSH_SPAWN_LOCK_STALE_MS)return!1;removeDirectoryLockBestEffort(lockPath)}catch(error){if(!isFileMissingError(error))return!1}return createDirectoryLock(lockPath)}function releaseTelemetryFlushSpawnGate(globalPmRoot){removeDirectoryLockBestEffort(flushSpawnLockPath(globalPmRoot))}const _testOnly={queuePath,cleanupTelemetryQueueTempOrphans,acquireTelemetryFlushSpawnGate,acquireTelemetryFlushLock,buildAuthorContextPayloadFields,buildCommandErrorPayload,buildCommandFinishPayload,buildCommandStartPayload,buildOtelSpanRequest,createDirectoryLock,enqueuePendingOtelSpan,enqueueTelemetryEvent,errorCode,flushPendingOtelSpans,flushQueue,flushQueueWithProcessLock,flushTelemetryArtifacts,hashTelemetryErrorFingerprint,hashTelemetryValue,isEmailDomainCharacter,isEmailLocalCharacter,isExpiredPendingOtelSpan,isExpiredQueueEntry,isFreshDirectoryLock,isDueForRetry,isDueForRetryAt,isRetryableQueueRewriteError,looksLikeEmailToken,otelSpansQueuePath,parseBooleanTrueLike,postTelemetryJson,parsePendingOtelSpanLines,prunePendingOtelSpans,reconcilePendingOtelSpansAfterFlush,retentionCutoffMs,resolveOtelTracesEndpoint,resolveTelemetryHttpTimeoutMs,rewritePendingOtelSpans,normalizeForHash,normalizeCaptureLevel,normalizePmVersion,normalizeTelemetryErrorCategory,normalizeTelemetryErrorCode,normalizeTelemetryExitCode,parseQueueLines,pruneExpiredQueueEntries,readRuntimeState,readCurrentQueueEntries,releaseTelemetryFlushSpawnGate,removeFlushedEntriesFromCurrentQueue,removeDirectoryLockBestEffort,resolveTelemetrySourceContext,rewriteQueue,sanitizeCommandArgs,sanitizeStringMax,sanitizeStringRedacted,sanitizeValue,scheduleTelemetryFlush,shouldFlushInline,sleep,summarizeResult,telemetryFlushRunnerPath,withQueueMutation,flushLockPath,flushSpawnLockPath,runtimeStatePath,writeRuntimeState};async function flushQueueWithProcessLock(globalPmRoot,endpoint,retentionDays){const acquired=await acquireTelemetryFlushLock(globalPmRoot);if(releaseTelemetryFlushSpawnGate(globalPmRoot),!acquired)return!1;try{await flushTelemetryArtifacts(globalPmRoot,endpoint,retentionDays)}finally{try{await rm(flushLockPath(globalPmRoot),{recursive:!0,force:!0})}catch{}}return!0}async function dueTelemetryArtifactIds(globalPmRoot,retentionDays){const ids=new Set;try{const{entries}=pruneExpiredQueueEntries(await readCurrentQueueEntries(globalPmRoot),retentionDays);for(const entry of entries.filter(isDueForRetry))ids.add(`event:${entry.event.event_id}`)}catch{}try{const raw=await readFileIfExists(otelSpansQueuePath(globalPmRoot));if(raw!==null)for(const entry of prunePendingOtelSpans(parsePendingOtelSpanLines(raw),retentionDays).entries)isDueForRetryAt(entry.next_attempt_after)&&ids.add(`span:${entry.id}`)}catch{}return ids}function scheduleTelemetryFlush(globalPmRoot,endpoint,retentionDays){if(!isConfigurationOnlySettingsRead(globalPmRoot)){if(shouldFlushInline())return _lastFlushPromise=_lastFlushPromise.then(()=>flushTelemetryArtifacts(globalPmRoot,endpoint,retentionDays)),_lastFlushPromise;try{if(!acquireTelemetryFlushSpawnGate(globalPmRoot))return;const child=spawn(process.execPath,[telemetryFlushRunnerPath()],{detached:!0,stdio:"ignore",cwd:os.tmpdir(),env:{...process.env,PM_GLOBAL_PATH:globalPmRoot,[PM_TELEMETRY_FLUSH_CHILD_ENV]:"1"}});child.on("error",()=>{releaseTelemetryFlushSpawnGate(globalPmRoot)}),child.unref()}catch{releaseTelemetryFlushSpawnGate(globalPmRoot)}}}async function flushTelemetryQueueNow(globalPmRoot=resolveGlobalPmRoot(process.cwd())){if(!resolveTelemetryEnvironmentPolicy().telemetry_disabled)try{await runWithConfigurationOnlySettings(globalPmRoot,async()=>{const detached=parseBooleanTrueLike(process.env[PM_TELEMETRY_FLUSH_CHILD_ENV]);let continueDraining=!0;for(;continueDraining;){if(!(await readSettings(globalPmRoot)).telemetry.enabled)return;const installation=await withQueueMutation(()=>ensureInstallationId(globalPmRoot),globalPmRoot);if(!installation)return;const before=detached?await dueTelemetryArtifactIds(globalPmRoot,installation.retentionDays):new Set;if(!await flushQueueWithProcessLock(globalPmRoot,installation.endpoint,installation.retentionDays)||!detached)return;const after=await dueTelemetryArtifactIds(globalPmRoot,installation.retentionDays);continueDraining=after.size>0&&(after.size!==before.size||[...after].some(id=>!before.has(id)))}},()=>parseBooleanTrueLike(process.env[PM_TELEMETRY_FLUSH_CHILD_ENV]))}catch{}}async function startTelemetryCommand(context){if(resolveTelemetryEnvironmentPolicy().telemetry_disabled||context.command==="telemetry"&&context.args.some(token=>token.trim().toLowerCase()==="clear"))return null;try{const globalPmRoot=resolveGlobalPmRoot(process.cwd());if(!(await readSettings(globalPmRoot)).telemetry.enabled)return null;const coreReadOwned=context.global.noExtensions===!0||isActiveCommandUnextended(context.command),activeCommand=await withQueueMutation(async()=>{const installation=await ensureInstallationId(globalPmRoot);if(!installation)return null;const{installationId,endpoint,retentionDays,captureLevel}=installation,pmVersion=normalizePmVersion(context.pm_version),sourceContext=resolveTelemetrySourceContext(context.global),pmRootHash=hashWithInstallationId(installationId,context.pm_root),cwdHash=hashWithInstallationId(installationId,process.cwd()),otelTracesEndpoint=resolveOtelTracesEndpoint(),occurredAt=nowIso(),event={schema_version:TELEMETRY_SCHEMA_VERSION,event_id:crypto.randomUUID(),event_type:"command_start",occurred_at:occurredAt,installation_id:installationId,session_id:PROCESS_SESSION_ID,command:context.command,payload:buildCommandStartPayload({captureLevel,context,pmVersion,sourceContext,pmRootHash,cwdHash,installationId})},sampleRate=await resolveAutomaticReadSampleRate(globalPmRoot,context.command,coreReadOwned);sampleRate===1&&await appendTelemetryEvent(globalPmRoot,event);const commandTaxonomy=deriveTelemetryCommandTaxonomy(context.command),active={...sampleRate<1?{sample_rate:sampleRate}:{},started_at:occurredAt,started_at_ms:Date.now(),command:context.command,command_taxonomy:commandTaxonomy,pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,installation_id:installationId,pm_root_hash:pmRootHash,cwd_hash:cwdHash,endpoint,retention_days:retentionDays,global_pm_root:globalPmRoot,capture_level:captureLevel,otel_traces_endpoint:otelTracesEndpoint??void 0,otel_trace_id:otelTracesEndpoint?crypto.randomBytes(16).toString("hex"):void 0,otel_span_id:otelTracesEndpoint?crypto.randomBytes(8).toString("hex"):void 0};return sampleRate<1&&deferredReadStarts.set(active,event),active},globalPmRoot,TELEMETRY_FOREGROUND_LOCK_WAIT_MS);return activeCommand&&activeCommand.sample_rate===void 0&&scheduleTelemetryFlush(globalPmRoot,activeCommand.endpoint,activeCommand.retention_days),activeCommand}catch{return null}}async function finishTelemetryCommand(activeCommand,outcome){if(!(!activeCommand||resolveTelemetryEnvironmentPolicy().telemetry_disabled))try{if(!await withQueueMutation(async()=>{const settings=await readSettings(activeCommand.global_pm_root);if(resolveTelemetryEnvironmentPolicy().telemetry_disabled||!settings.telemetry.enabled||settings.telemetry.installation_id!==activeCommand.installation_id)return deferredReadStarts.delete(activeCommand),!1;const deferredStart=deferredReadStarts.get(activeCommand),sampleRate=outcome.ok?activeCommand.sample_rate??1:1;if(deferredStart){if(deferredReadStarts.delete(activeCommand),crypto.randomBytes(6).readUIntBE(0,6)/281474976710656>=sampleRate)return!1;deferredStart.payload.sample_rate=sampleRate,await appendTelemetryEvent(activeCommand.global_pm_root,deferredStart)}const finishedAt=nowIso(),durationMs=Math.max(0,Date.now()-activeCommand.started_at_ms),normalizedErrorCode=normalizeTelemetryErrorCode(inferTelemetryErrorCode({ok:outcome.ok,errorCode:outcome.error_code,errorMessage:outcome.error,exitCode:outcome.exit_code})),normalizedErrorCategory=normalizeTelemetryErrorCategory({ok:outcome.ok,errorCode:normalizedErrorCode,errorCategory:outcome.error_category}),normalizedExitCode=normalizeTelemetryExitCode(outcome.exit_code,outcome.ok),commandResolution=outcome.command_resolution??deriveTelemetryCommandResolution({ok:outcome.ok,errorCode:normalizedErrorCode,errorCategory:normalizedErrorCategory}),resolutionStage=outcome.resolution_stage??"execute",event={schema_version:TELEMETRY_SCHEMA_VERSION,event_id:crypto.randomUUID(),event_type:"command_finish",occurred_at:finishedAt,installation_id:activeCommand.installation_id,session_id:PROCESS_SESSION_ID,command:activeCommand.command,payload:{...deferredStart?{sample_rate:sampleRate}:{},...buildCommandFinishPayload({captureLevel:activeCommand.capture_level,pmVersion:activeCommand.pm_version,sourceContext:{source_context:activeCommand.source_context,source_context_source:activeCommand.source_context_source},outcome,durationMs,startedAt:activeCommand.started_at,command:activeCommand.command,installationId:activeCommand.installation_id,commandTaxonomy:activeCommand.command_taxonomy,exitCode:normalizedExitCode,errorCode:normalizedErrorCode,errorCategory:normalizedErrorCategory,commandResolution,resolutionStage})}};await appendTelemetryEvent(activeCommand.global_pm_root,event);const otelRequest=buildOtelSpanRequest(activeCommand,{...outcome,exit_code:normalizedExitCode,error_code:normalizedErrorCode,error_category:normalizedErrorCategory},finishedAt,durationMs,sampleRate);return otelRequest&&await appendPendingOtelSpan(activeCommand.global_pm_root,otelRequest),!0},activeCommand.global_pm_root,TELEMETRY_FOREGROUND_LOCK_WAIT_MS))return;await scheduleTelemetryFlush(activeCommand.global_pm_root,activeCommand.endpoint,activeCommand.retention_days)}catch{}}async function emitTelemetryErrorEvent(context){if(!resolveTelemetryEnvironmentPolicy().telemetry_disabled)try{const globalPmRoot=resolveGlobalPmRoot(process.cwd());if(!(await readSettings(globalPmRoot)).telemetry.enabled)return;const captured=await withQueueMutation(async()=>{const installation=await ensureInstallationId(globalPmRoot);if(!installation)return null;const{installationId,captureLevel}=installation,pmVersion=normalizePmVersion(context.pm_version),sourceContext=resolveTelemetrySourceContext(context.global),pmRootHash=hashWithInstallationId(installationId,context.pm_root),cwdHash=hashWithInstallationId(installationId,process.cwd()),occurredAt=nowIso(),normalizedErrorCode=normalizeTelemetryErrorCode(inferTelemetryErrorCode({ok:!1,errorCode:context.error_code,errorMessage:context.error_message,exitCode:context.exit_code})),normalizedErrorCategory=context.error_category??resolveTelemetryErrorCategory(normalizedErrorCode),normalizedExitCode=normalizeTelemetryExitCode(context.exit_code,!1),normalizedCommand=context.command.trim().length>0?context.command:"<unknown>",commandTaxonomy=deriveTelemetryCommandTaxonomy(normalizedCommand),commandResolution=context.command_resolution??deriveTelemetryCommandResolution({ok:!1,errorCode:normalizedErrorCode,errorCategory:normalizedErrorCategory}),resolutionStage=context.resolution_stage??"unknown",event={schema_version:TELEMETRY_SCHEMA_VERSION,event_id:crypto.randomUUID(),event_type:"command_error",occurred_at:occurredAt,installation_id:installationId,session_id:PROCESS_SESSION_ID,command:sanitizeString(normalizedCommand,"redacted"),payload:buildCommandErrorPayload({captureLevel,pmVersion,sourceContext,command:normalizedCommand,commandTaxonomy,commandResolution,resolutionStage,args:context.args,options:context.options,pmRootHash,cwdHash,installationId,errorCode:normalizedErrorCode,errorCategory:normalizedErrorCategory,exitCode:normalizedExitCode,errorMessage:context.error_message})};return await appendTelemetryEvent(globalPmRoot,event),installation},globalPmRoot,TELEMETRY_FOREGROUND_LOCK_WAIT_MS);captured&&await scheduleTelemetryFlush(globalPmRoot,captured.endpoint,captured.retentionDays)}catch{}}export{PM_TELEMETRY_SOURCE_CONTEXT_VALUES2 as PM_TELEMETRY_SOURCE_CONTEXT_VALUES,TELEMETRY_MAX_QUEUE_ENTRY_ATTEMPTS,TELEMETRY_SCHEMA_VERSION,_testOnly,emitTelemetryErrorEvent,finishTelemetryCommand,flushTelemetryQueueNow,startTelemetryCommand,waitForPendingFlush,withQueueMutation as withTelemetryQueueMutation};
|
|
1
|
+
import M from"node:crypto";import{spawn as zt}from"node:child_process";import{mkdirSync as se,rmSync as Yt,statSync as Ye}from"node:fs";import{mkdir as ie,readdir as bt,rm as ae,stat as be}from"node:fs/promises";import{request as Ft}from"node:http";import{request as jt}from"node:https";import ce from"node:os";import y from"node:path";import{acquireLock as Ht}from"../lock/lock.js";import{isActiveCommandUnextended as Vt,runWithIsolatedExtensionRuntime as qt}from"../extensions/index.js";import{resolveAutomaticReadSampleRate as $t}from"./read-sampling.js";import{PM_TELEMETRY_SOURCE_CONTEXT_VALUES as Bt,isTelemetryTestEnvironment as Qt,redactTelemetryEndpoint as Jt,redactUrlsInText as ue,resolveTelemetryEndpointOverride as L,resolveTelemetryEnvironmentPolicy as C,resolveTelemetrySourceAttribution as Xt,telemetryRuntimeFileName as F}from"./policy.js";import{redactUrlCredentialsInText as Wt,redactUrlCredentialsInToken as Gt}from"../shared/url-credentials.js";import{resolvePmPackageRootFromModule as Kt}from"../packages/root.js";import{isFileMissingError as Fe,appendLineAtomic as je,readFileIfExists as R,writeFileAtomic as de}from"../fs/fs-utils.js";import{resolveTelemetryErrorCategory as He}from"../shared/constants.js";import{nowIso as v}from"../shared/time.js";import{detectAgentIdentity as Zt,readAuthorEnvironment as en}from"../shared/author.js";import{resolveGlobalPmRoot as j}from"../store/paths.js";import{isConfigurationOnlySettingsRead as Ve,isSettingsReadFallback as tn,readSettings as P,runWithConfigurationOnlySettings as nn,writeSettings as rn}from"../store/settings.js";import{clearSettingsReadCache as on}from"../store/settings-read-cache.js";import{deriveTelemetryCommandResolution as qe,deriveTelemetryCommandTaxonomy as le,inferTelemetryErrorCode as $e}from"./observability.js";const sn=y.join("runtime","telemetry","events.jsonl"),an=y.join("runtime","telemetry","state.json"),cn=y.join("runtime","telemetry","otel-spans.jsonl"),un=8,Be=500,H=1,Qe=1,dn=100,ln=36e5,_n=3e4,Je=2e4,mn=1e3,fn=25e3,_e=250,pn=864e5,V=65536,Xe=6,We=20,Ge=15,hn=8192,Ke=[25,50,100,200],En=3600*1e3,yn=1440*60*1e3,Ze=6e4,gn=6e4,Tn="OTEL_EXPORTER_OTLP_TRACES_ENDPOINT",wn="OTEL_EXPORTER_OTLP_ENDPOINT",Sn="OTEL_SERVICE_NAME",Mn="PM_TELEMETRY_OTEL_DISABLED",xn=new Set(["1","true","yes","on"]),An="PM_TELEMETRY_INLINE_FLUSH",I="PM_TELEMETRY_FLUSH_CHILD",Ln="PM_TELEMETRY_HTTP_TIMEOUT_MS",In=globalThis.fetch;import{PM_TELEMETRY_SOURCE_CONTEXT_VALUES as wr}from"./policy.js";let et=!1,q=Promise.resolve(),me=Promise.resolve();const $=new WeakMap;async function mr(){await q,await me}const Nn=new Set(["1","true","yes","on"]),On=new Set(["claude-code","codex","pi","opencode","cursor","aider","gemini-cli","ci"]),B=M.randomUUID(),Cn=["token","secret","password","passwd","api_key","apikey","authorization","cookie","session","credentials","bearer"],Rn=new Set(["literal","literals","regex","regexes","replacement","replacements","setjson","set_json","update"]),tt="(?:token|secret|password|passwd|api[_-]?key|apikey|authorization|cookie|session|credentials|bearer|literals?|regex(?:es)?|replacements?)",vn=new RegExp(`\\b(${tt})\\s*([:=])\\s*([^\\s,;]+)`,"giu"),kn=new RegExp(`(--${tt})(=|\\s+)([^\\s,;]+)`,"giu"),Dn=/(^|[\s"'`(=])\/(?:[^\s"'`),;]+)/g,Pn=/bearer\s+[a-z0-9._=-]+/giu,Un=/\b(?:10\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|172\.(?:1[6-9]|2\d|3[01])\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|192\.168\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d))\b/g;function k(e,t=L().endpoint){return y.join(y.dirname(y.join(e,sn)),F("events.jsonl",t))}function D(e){return y.join(e,cn)}function zn(e){return y.dirname(k(e,null))}function fe(e,t=L().endpoint){return y.join(y.dirname(y.join(e,an)),F("state.json",t))}function Q(e){return y.join(e,"runtime","telemetry","flush.lock")}function pe(e){return y.join(e,"runtime","telemetry","flush.spawn.lock")}function nt(){return y.join(Kt(import.meta.url,["../../.."]),"dist","cli","telemetry-flush.js")}function rt(){return x(process.env[An])||x(process.env[I])?!0:Qt()}async function ot(e,t=L().endpoint){const r=await R(fe(e,t));if(!r||r.trim().length===0)return{};try{const n=JSON.parse(r);return typeof n!="object"||n===null||Array.isArray(n)?{}:n}catch{return{}}}async function U(e,t,r=L().endpoint){try{await S(async()=>{const o={...await ot(e,r),...t},s=Object.fromEntries(Object.entries(o).filter(([,i])=>i!==void 0).sort((i,a)=>i[0].localeCompare(a[0])));await de(fe(e,r),`${JSON.stringify(s,null,2)}
|
|
2
|
+
`,{createParentDirectories:!x(process.env[I])})},e)}catch{}}function he(e){const t=e.trim().toLowerCase().replaceAll("-","_").replaceAll(/[^a-z0-9_]+/g,"_"),r=t.split("_").filter(n=>n.length>0);return Rn.has(t)||Cn.some(n=>t===n||t.endsWith(`_${n}`)||r.includes(n))}function st(e){return e.replaceAll(vn,(r,n,o)=>`${n}${o}[redacted]`).replaceAll(kn,(r,n,o)=>`${n}${o}[redacted]`)}function it(e){return e.replaceAll(Dn,(t,r)=>`${r}[redacted_path]`)}function at(e){const t=e>=65&&e<=90,r=e>=97&&e<=122,n=e>=48&&e<=57;return t||r||n}function Ee(e){if(!e)return!1;const t=e.charCodeAt(0);return at(t)?!0:e==="."||e==="_"||e==="%"||e==="+"||e==="-"}function ye(e){if(!e)return!1;const t=e.charCodeAt(0);return at(t)?!0:e==="."||e==="-"}function ct(e){const t=e.indexOf("@");if(t<=0||t!==e.lastIndexOf("@")||t===e.length-1)return!1;const r=e.slice(0,t),n=e.slice(t+1),o=n.lastIndexOf(".");if(o<=0||o===n.length-1||n.length-(o+1)<2)return!1;for(const s of r)if(!Ee(s))return!1;for(const s of n)if(!ye(s))return!1;return!0}function Yn(e){let t="",r=0;for(;r<e.length;){const n=e.indexOf("@",r);if(n<0){t+=e.slice(r);break}let o=n-1;for(;o>=r&&Ee(e[o]);)o-=1;o+=1;let s=n+1;for(;s<e.length&&ye(e[s]);)s+=1;const i=e.slice(o,s);if(ct(i)){t+=e.slice(r,o),t+="[redacted_email]",r=s;continue}t+=e.slice(r,n+1),r=n+1}return t}function ut(e){return Yn(Wt(e)).replaceAll(Pn,"bearer [redacted_token]").replaceAll(Un,"[redacted_ip]")}function dt(e){const t=ut(e),r=st(t),n=it(r),o=n.trim();return o.startsWith("/")&&o.length>1?"[redacted_path]":n.length>512?`${n.slice(0,509)}...`:n}function lt(e){const t=ut(e),r=st(t),n=it(r),o=n.trim();return o.startsWith("/")&&o.length>1?"[redacted_path]":n.length>2048?`${n.slice(0,2045)}...`:n}function E(e,t="redacted"){return t==="max"?lt(e):dt(e)}function N(e,t,r="redacted",n=0){if(t&&he(t))return"[redacted]";if(e==null)return e;if(typeof e=="string")return E(e,r);if(typeof e=="number"||typeof e=="boolean")return e;if(n>=Xe)return"[depth_truncated]";if(Array.isArray(e))return e.slice(0,We).map(o=>N(o,void 0,r,n+1));if(typeof e=="object"){const o=e,s={};for(const[i,a]of Object.entries(o))s[i]=N(a,i,r,n+1);return s}return String(e)}function ge(e,t="redacted"){const r=[];let n=!1;for(const o of e){const s=E(Gt(o),t);if(n){r.push("[redacted]"),n=!1;continue}if(s.startsWith("--")){const i=s.slice(2),a=i.indexOf("=");if(a>=0){const c=i.slice(0,a),u=i.slice(a+1);he(c)?r.push(`--${c}=[redacted]`):r.push(`--${c}=${E(u,t)}`);continue}if(he(i)){r.push(`--${i}`),n=!0;continue}}r.push(s)}return r}function _t(e){const t=e?.trim().toLowerCase();return t==="minimal"||t==="redacted"||t==="max"?t:"redacted"}function x(e){return Nn.has((e??"").trim().toLowerCase())}function Te(){const e=process.env[Ln]?.trim();if(!e)return Je;const t=Number(e);return Number.isFinite(t)?Math.min(fn,Math.max(mn,Math.trunc(t))):Je}async function we(e,t,r){const n=new URL(e);if(globalThis.fetch!==In){const s=new AbortController;let i;const a=new Promise((c,u)=>{i=setTimeout(()=>{s.abort(),u(new Error("telemetry_http_timeout"))},Te())});try{return(await Promise.race([globalThis.fetch(e,{method:"POST",headers:t,body:r,signal:s.signal}),a])).status}finally{clearTimeout(i)}}const o=n.protocol==="https:"?jt:n.protocol==="http:"?Ft:void 0;if(!o)throw new Error(`telemetry_http_protocol_unsupported_${n.protocol}`);return new Promise((s,i)=>{const a=Te(),c={method:"POST",headers:{...t,"content-length":Buffer.byteLength(r)},signal:AbortSignal.timeout(a),autoSelectFamilyAttemptTimeout:Math.min(5e3,a)},u=o(n,c,_=>{_.once("error",i),_.once("end",()=>s(_.statusCode)),_.resume()});u.once("error",i),u.end(r)})}function Se(e){const t=typeof e=="string"?e.trim():"";return t.length>0?t:"0.0.0"}function J(e){const t=e?.trim();return t&&t.length>0?t:void 0}function X(e,t){return Number.isFinite(e)?Math.max(0,Math.trunc(e)):t?0:1}function Me(e){if(!e.ok)return typeof e.errorCategory=="string"&&e.errorCategory.trim().length>0?e.errorCategory:typeof e.errorCode=="string"&&e.errorCode.trim().length>0?He(e.errorCode):"unknown"}function xe(e){const t=Xt(e);return t.source_context_source==="env_override_rejected"&&!et&&!e.quiet&&(et=!0,process.stderr.write(`[pm] warning: PM_TELEMETRY_SOURCE_CONTEXT is not one of ${Bt.join("|")}; ignoring override.
|
|
3
|
+
`)),t}function T(e,t){return M.createHash("sha256").update(`${e}:${t}`).digest("hex")}function W(e,t){const r=(en()??"").trim(),n=Zt({env:process.env,argv:process.argv}),o=n.harness!==void 0||n.model!==void 0;return e==="minimal"?{has_author_context:r.length>0,has_agent_context:o}:{agent_harness:n.harness?On.has(n.harness)?n.harness:"other":"none",ci:x(process.env.CI),...r.length>0?{author_context_hash:T(t,r)}:{},...n.harness?{agent_harness_hash:T(t,n.harness)}:{},...n.model?{agent_model_hash:T(t,n.model)}:{},...n.model_source?{agent_model_source:n.model_source}:{}}}function G(e,t=0){if(e==null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(t>=Xe)return"[depth_truncated]";if(Array.isArray(e))return e.slice(0,We).map(r=>G(r,t+1));if(typeof e=="object"){const r=e,n={},o=Object.keys(r).sort((s,i)=>s.localeCompare(i));for(const s of o)n[s]=G(r[s],t+1);return n}return String(e)}function K(e,t){return T(e,JSON.stringify(G(t)))}function mt(e,t){return{hashes:t.map(r=>T(e,r)),digest:T(e,t.join("\0"))}}function Ae(e,t,r,n){const o=E(typeof n=="string"?n:"","redacted"),s=typeof r=="string"&&r.length>0?r:"unknown_error",i=`${t}\0${s}\0${o}`;return T(e,i)}function ft(){if(xn.has((process.env[Mn]??"").trim().toLowerCase()))return null;const e=(process.env[Tn]??"").trim();if(e.length>0)try{return new URL(e).toString()}catch{return null}const t=(process.env[wn]??"").trim();if(t.length===0)return null;try{const r=new URL(t),n=r.pathname.replace(/\/+$/,"");return n.endsWith("/v1/traces")||(r.pathname=`${n.length===0?"":n}/v1/traces`),r.toString()}catch{return null}}function pt(e){const t=Date.parse(e),r=Number.isNaN(t)?Date.now():t;return`${BigInt(r)*1000000n}`}function w(e,t){return{key:e,value:{stringValue:t}}}function bn(e,t){return{key:e,value:{boolValue:t}}}function ht(e,t){return{key:e,value:{intValue:String(Math.max(0,Math.trunc(t)))}}}function Et(e,t,r,n,o=1){const s=e.otel_traces_endpoint;if(typeof s!="string"||s.trim().length===0||[e.otel_trace_id,e.otel_span_id].some(d=>typeof d!="string"||d.length===0))return null;const i=E((process.env[Sn]??"").trim()),a=i.length>0?i:"pm-cli",c=X(t.exit_code,t.ok),u=J(t.error_code),_=Me({ok:t.ok,errorCode:u,errorCategory:t.error_category}),m=[w("pm.command",E(e.command)),w("pm.version",e.pm_version),w("pm.source_context",e.source_context),w("pm.source_context_source",e.source_context_source),w("pm.installation_id",e.installation_id),w("pm.session_id",B),w("pm.pm_root_hash",e.pm_root_hash),w("pm.cwd_hash",e.cwd_hash),bn("pm.ok",t.ok),ht("pm.exit_code",c),ht("pm.duration_ms",n),w("pm.sample_rate",String(o))];typeof u=="string"&&m.push(w("pm.error_code",u)),typeof _=="string"&&m.push(w("pm.error_category",_)),typeof t.error=="string"&&t.error.trim().length>0&&m.push(w("pm.error",E(t.error)));const f={resourceSpans:[{resource:{attributes:[w("service.name",a)]},scopeSpans:[{scope:{name:"pm-cli.telemetry",version:"1"},spans:[{traceId:e.otel_trace_id,spanId:e.otel_span_id,name:`pm.command.${E(e.command)}`,kind:1,startTimeUnixNano:pt(e.started_at),endTimeUnixNano:pt(r),attributes:m,status:{code:t.ok?1:2,message:t.ok?"":E(typeof t.error=="string"?t.error:"command_failed")}}]}]}]};return{endpoint:s,payload:f}}function yt(e,t="redacted"){if(e==null)return{type:"nullish"};if(typeof e=="string")return{type:"string",value:E(e,t)};if(typeof e=="number"||typeof e=="boolean")return{type:typeof e,value:e};if(Array.isArray(e))return{type:"array",length:e.length,sample:e.slice(0,5).map(r=>N(r,void 0,t))};if(typeof e=="object"){const r=e,n=Object.keys(r).filter(i=>i!=="tests").sort((i,a)=>i.localeCompare(a)),o={};let s=0;for(const i of n.slice(0,25)){const a=N(r[i],i,t);if(a===void 0)continue;const c=JSON.stringify(a).length;if(s+c>hn){o[i]="[preview_truncated]";break}s+=c,o[i]=a}return{type:"object",key_count:n.length,keys_preview:n.slice(0,50),preview:o}}return{type:typeof e,value:String(e)}}function gt(e){const{captureLevel:t,context:r,pmVersion:n,sourceContext:o,pmRootHash:s,cwdHash:i,installationId:a}=e,c=le(r.command),u=mt(a,r.args),_=T(a,`${r.command}\0${r.args.join("\0")}`),m=K(a,r.options),f=K(a,r.global),d=W(t,a);return t==="minimal"?{capture_level:t,pm_version:n,source_context:o.source_context,source_context_source:o.source_context_source,command_taxonomy:c,command_args_digest:u.digest,command_invocation_digest:_,command_options_digest:m,global_options_digest:f,...d}:{pm_version:n,source_context:o.source_context,source_context_source:o.source_context_source,command_taxonomy:c,...d,command_args:ge(r.args,t),command_args_hashes:u.hashes,command_args_digest:u.digest,command_invocation_digest:_,command_options:N(r.options,void 0,t),command_options_digest:m,global_options:N(r.global,void 0,t),global_options_digest:f,pm_root_hash:s,cwd_hash:i,capture_level:t,runtime:{node:process.version,platform:process.platform,arch:process.arch,hostname_hash:T(a,ce.hostname()),stdin_tty:process.stdin.isTTY===!0,stdout_tty:process.stdout.isTTY===!0}}}function Tt(e){const{captureLevel:t,pmVersion:r,sourceContext:n,outcome:o,durationMs:s,startedAt:i,command:a,installationId:c,commandTaxonomy:u,exitCode:_,errorCode:m,errorCategory:f,commandResolution:d,resolutionStage:p}=e,h=o.ok===!1?Ae(c,a,m,o.error):void 0,l=W(t,c);return t==="minimal"?{capture_level:t,pm_version:r,source_context:n.source_context,source_context_source:n.source_context_source,command_taxonomy:u,command_resolution:d,resolution_stage:p,ok:o.ok,exit_code:_,error_code:m,error_category:f,error:o.error?E(o.error,"redacted"):void 0,error_fingerprint:h,duration_ms:s,...l}:{capture_level:t,pm_version:r,source_context:n.source_context,source_context_source:n.source_context_source,command_taxonomy:u,command_resolution:d,resolution_stage:p,...l,ok:o.ok,exit_code:_,error_code:m,error_category:f,error:o.error?E(o.error,t):void 0,error_fingerprint:h,duration_ms:s,started_at:i,result_summary:yt(o.result,t)}}function wt(e){const{captureLevel:t,pmVersion:r,sourceContext:n,command:o,commandTaxonomy:s,commandResolution:i,resolutionStage:a,args:c,options:u,pmRootHash:_,cwdHash:m,installationId:f,errorCode:d,errorMessage:p,errorCategory:h,exitCode:l}=e,g=mt(f,c),A=T(f,o),O=K(f,u),Ue=Ae(f,o,d,p),ze=W(t,f);return t==="minimal"?{capture_level:t,pm_version:r,source_context:n.source_context,source_context_source:n.source_context_source,command_taxonomy:s,command_resolution:i,resolution_stage:a,attempted_command_digest:A,attempted_args_digest:g.digest,attempted_options_digest:O,error_code:d,error_category:h,exit_code:l,error:E(p,"redacted"),error_fingerprint:Ue,...ze}:{capture_level:t,pm_version:r,source_context:n.source_context,source_context_source:n.source_context_source,command_taxonomy:s,command_resolution:i,resolution_stage:a,...ze,attempted_command:E(o,t),attempted_command_digest:A,attempted_args:ge(c,t),attempted_args_hashes:g.hashes,attempted_args_digest:g.digest,attempted_options:N(u,void 0,t),attempted_options_digest:O,error_code:d,error_category:h,exit_code:l,error:E(p,t),error_fingerprint:Ue,pm_root_hash:_,cwd_hash:m,runtime:{node:process.version,platform:process.platform,arch:process.arch,hostname_hash:T(f,ce.hostname()),stdin_tty:process.stdin.isTTY===!0,stdout_tty:process.stdout.isTTY===!0}}}async function Le(e){const t=await P(e);if(!t.telemetry.enabled||C().telemetry_disabled)return null;if(t.telemetry.installation_id.trim().length===0){if(Ve(e)||tn(t))return null;t.telemetry.installation_id=M.randomUUID(),await rn(e,t,"telemetry:install_id")}return{installationId:t.telemetry.installation_id,endpoint:t.telemetry.endpoint,retentionDays:Math.max(1,Math.trunc(t.telemetry.retention_days)),captureLevel:_t(t.telemetry.capture_level)}}async function z(e,t){let n=JSON.stringify({client_schema_version:Qe,event:t,attempts:0});if(n.length>V){const o={...t,payload:{...t.payload,result_summary:{truncated:!0,reason:"payload_size_exceeded",original_bytes:n.length}}};n=JSON.stringify({client_schema_version:Qe,event:o,attempts:0})}await je(k(e),n)}async function Fn(e,t){await S(()=>z(e,t),e)}function Ie(e){const t=[];for(const r of e.split(`
|
|
4
|
+
`)){const n=r.trim();if(n.length!==0)try{const o=JSON.parse(n);o&&typeof o=="object"&&o.event&&typeof o.event=="object"&&typeof o.attempts=="number"&&(o.client_schema_version===void 0||typeof o.client_schema_version=="number"&&Number.isFinite(o.client_schema_version))&&t.push(o)}catch{}}return t}function St(e){const t=Math.min(_n*2**Math.max(e-1,0),ln);return new Date(Date.now()+t).toISOString()}function Z(e){if(typeof e!="string"||e.trim().length===0)return!0;const t=Date.parse(e);return Number.isNaN(t)?!0:t<=Date.now()}function Ne(e){return Z(e.next_attempt_after)}function Oe(e){const t=Number.isFinite(e)?Math.max(1,Math.trunc(e)):1;return Date.now()-t*pn}function Mt(e,t){const r=e.event?.occurred_at;if(typeof r!="string"||r.trim().length===0)return!1;const n=Date.parse(r);return Number.isNaN(n)?!1:n<t}function Y(e,t){const r=Oe(t),n=[];let o=0;for(const s of e){if(JSON.stringify(s).length>V||Mt(s,r)||s.attempts>=Ge){o+=1;continue}n.push(s)}return{entries:n,prunedCount:o}}async function Ce(e,t,r=L().endpoint){const n=t.map(s=>JSON.stringify(s)).join(`
|
|
5
|
+
`),o=n.length>0?`${n}
|
|
6
|
+
`:"";for(let s=0;;s+=1)try{await de(k(e,r),o,{createParentDirectories:!x(process.env[I])});return}catch(i){const a=Ke[s];if(a===void 0||!Re(i))throw i;await ve(a)}}function Re(e){if(typeof e!="object"||e===null||!("code"in e))return!1;const t=e.code;return t==="EACCES"||t==="EBUSY"||t==="EPERM"}function ve(e){return new Promise(t=>{setTimeout(t,e)})}async function xt(e,t){const r={id:M.randomUUID(),endpoint:t.endpoint,payload:t.payload,enqueued_at:v(),attempts:0},n=JSON.stringify(r);n.length>V||await je(D(e),n)}async function jn(e,t){await S(()=>xt(e,t),e)}function Hn(e){const t=JSON.stringify([e.endpoint,e.enqueued_at,e.payload]);return M.createHash("sha256").update(t).digest("hex").slice(0,32)}function ee(e){const t=[];for(const r of e.split(`
|
|
7
|
+
`)){const n=r.trim();if(n.length!==0)try{const o=JSON.parse(n);o&&typeof o=="object"&&typeof o.endpoint=="string"&&o.endpoint.trim().length>0&&"payload"in o&&typeof o.attempts=="number"&&Number.isFinite(o.attempts)&&((typeof o.id!="string"||o.id.length===0)&&(o.id=Hn(o)),t.push(o))}catch{}}return t}function At(e,t){if(typeof e.enqueued_at!="string"||e.enqueued_at.trim().length===0)return!1;const r=Date.parse(e.enqueued_at);return Number.isNaN(r)?!1:r<t}function te(e,t){const r=Oe(t),n=[];let o=0;for(const s of e){if(JSON.stringify(s).length>V||At(s,r)||s.attempts>=Ge){o+=1;continue}n.push(s)}if(n.length>Be){const s=n.length-Be;return o+=s,{entries:n.slice(s),prunedCount:o}}return{entries:n,prunedCount:o}}async function Lt(e,t){const r=t.map(o=>JSON.stringify(o)).join(`
|
|
8
|
+
`),n=r.length>0?`${r}
|
|
9
|
+
`:"";for(let o=0;;o+=1)try{await de(D(e),n,{createParentDirectories:!x(process.env[I])});return}catch(s){const i=Ke[o];if(i===void 0||!Re(s))throw s;await ve(i)}}async function ke(e,t,r,n){return S(async()=>{const o=await R(D(e)),s=o===null?[]:ee(o),i=[];for(const c of s){if(r.has(c.id))continue;const u=n.get(c.id);i.push(u?{...c,attempts:u.attempts,next_attempt_after:u.next_attempt_after}:c)}const{entries:a}=te(i,t);return await Lt(e,a),a.length},e)}async function It(e,t){const r=await R(D(e));if(r===null||r.trim().length===0){await U(e,{pending_otel_spans:0},null);return}const n=ee(r),{entries:o,prunedCount:s}=te(n,t),i=o.filter(p=>Z(p.next_attempt_after)).slice(0,un);if(i.length===0){const p=s>0?await ke(e,t,new Set,new Map):o.length;await U(e,{pending_otel_spans:p},null);return}const a=v(),c=new Set,u=new Map;let _=0,m;await Promise.all(i.map(async p=>{try{const h=await we(p.endpoint,{"content-type":"application/json"},JSON.stringify(p.payload));if(h<200||h>=300)throw new Error(`local_otel_export_http_${h}`);c.add(p.id),_+=1}catch(h){m=h instanceof Error?E(ue(h.message),"redacted"):"local_otel_export_failed";const l=p.attempts+1;u.set(p.id,{attempts:l,next_attempt_after:St(l)})}}));const f=await ke(e,t,c,u),d={pending_otel_spans:f,last_otel_attempt_at:a};_>0&&(d.last_otel_success_at=a),m!==void 0?(d.last_otel_failure_at=a,d.last_otel_failure_error=m):f===0&&(d.last_otel_failure_at=void 0,d.last_otel_failure_error=void 0),await U(e,d,null)}async function De(e,t,r){try{await Ot(e,t,r)}catch{}try{await It(e,r)}catch{}}async function Nt(e,t=En,r=L().endpoint){try{const n=zn(e),o=await bt(n,{withFileTypes:!0}),s=Date.now(),i=new Set([F("events.jsonl",r),F("state.json",r)]),a=c=>{if(!i.has(c))return/^\.events(?:\.[a-f0-9]{16})?\.jsonl\.\d+\.\d+\.[a-f0-9]+\.tmp$/.test(c)?s-Math.max(0,t):/^(?:events\.[a-f0-9]{16}\.jsonl|state\.[a-f0-9]{16}\.json)$/.test(c)?s-yn:void 0};await Promise.all(o.map(async c=>{const u=c.isFile()?a(c.name):void 0;if(u===void 0)return;const _=y.join(n,c.name);(await be(_)).mtimeMs<u&&await ae(_,{force:!0})}))}catch{}}async function S(e,t=j(process.cwd()),r=5e3){const n=me.catch(()=>{}).then(()=>qt(async()=>{const o=await Ht(t,"telemetry-queue",60,"telemetry",!1,!1,r,{createParentDirectories:!x(process.env[I])});try{return on(t),await e()}finally{await o()}}));return me=n.catch(()=>{}),n}async function b(e,t=L().endpoint){const r=await R(k(e,t));return r===null||r.trim().length===0?[]:Ie(r)}async function ne(e,t,r,n=L().endpoint){return S(async()=>{const o=await b(e,n),{entries:s}=Y(o,r),i=s.filter(a=>!t.has(a.event.event_id));return await Ce(e,i,n),i},e)}async function Vn(e,t,r,n,o=L().endpoint){return S(async()=>{const s=await b(e,o),{entries:i}=Y(s,n),a=i.map(c=>{if(!t.has(c.event.event_id))return c;const u=c.attempts+1;return{...c,attempts:u,last_attempt_at:r,next_attempt_after:St(u)}});return await Ce(e,a,o),a},e)}function qn(e,t){return t===null?e:Jt(e)}async function Ot(e,t,r){const n=L().endpoint;await Nt(e,void 0,n);const o=(n??t).trim(),s=qn(o,n),i=l=>U(e,l,n);if(o.length===0)return;const a=await R(k(e,n));if(a===null||a.trim().length===0){await i({endpoint:s,queue_entries:0});return}const c=Ie(a);if(c.length===0){await i({endpoint:s,queue_entries:0});return}const{entries:u,prunedCount:_}=Y(c,r);if(u.length===0){const l=await ne(e,new Set,r,n);await i({endpoint:s,queue_entries:l.length});return}const m=u.filter(l=>Ne(l)).slice(0,dn);if(m.length===0){const l=_>0?await ne(e,new Set,r,n):u;await i({endpoint:s,queue_entries:l.length});return}const f=new Set(m.map(l=>l.event.event_id)),d=v(),p={"content-type":"application/json"},h=process.env.PM_TELEMETRY_INGEST_KEY?.trim();h&&(p["x-pm-telemetry-key"]=h);try{const l=await we(o,p,JSON.stringify({schema_version:H,events:m.map(g=>g.event)}));if(l<200||l>=300)throw new Error(`telemetry_flush_http_${l}`)}catch(l){const g=await Vn(e,f,d,r,n),A=l instanceof Error?E(ue(l.message),"redacted"):"telemetry_flush_failed";await i({endpoint:s,queue_entries:g.length,last_attempted_flush_at:d,last_failed_flush_at:d,last_failed_flush_error:A});return}try{const l=await ne(e,f,r,n);await i({endpoint:s,queue_entries:l.length,last_attempted_flush_at:d,last_successful_flush_at:d,last_failed_flush_at:void 0,last_failed_flush_error:void 0})}catch(l){const g=l instanceof Error?E(ue(l.message),"redacted"):"telemetry_flush_failed",A=await b(e,n).catch(()=>u);await i({endpoint:s,queue_entries:A.length,last_attempted_flush_at:d,last_failed_flush_at:d,last_failed_flush_error:g})}}async function Ct(e){const t=Q(e);x(process.env[I])||await ie(y.dirname(t),{recursive:!0});try{return await ie(t),!0}catch(r){if(typeof r!="object"||r===null||!("code"in r)||r.code!=="EEXIST")throw r}try{const r=await be(t);return Date.now()-r.mtimeMs<Ze?!1:(await ae(t,{recursive:!0,force:!0}),await ie(t),!0)}catch{return!1}}function Rt(e,t){try{return Date.now()-Ye(e).mtimeMs<t}catch{return!1}}function Pe(e){try{Yt(e,{recursive:!0,force:!0})}catch{}}function vt(e){if(typeof e!="object"||e===null||!("code"in e))return;const t=e.code;return typeof t=="string"?t:void 0}function kt(e){try{return se(e),!0}catch(t){if(vt(t)==="EEXIST"||!Fe(t))return!1}try{return se(y.dirname(e),{recursive:!0}),se(e),!0}catch{return!1}}function Dt(e){if(Rt(Q(e),Ze))return!1;const t=pe(e);try{if(Date.now()-Ye(t).mtimeMs<gn)return!1;Pe(t)}catch(r){if(!Fe(r))return!1}return kt(t)}function re(e){Pe(pe(e))}const fr={queuePath:k,cleanupTelemetryQueueTempOrphans:Nt,acquireTelemetryFlushSpawnGate:Dt,acquireTelemetryFlushLock:Ct,buildAuthorContextPayloadFields:W,buildCommandErrorPayload:wt,buildCommandFinishPayload:Tt,buildCommandStartPayload:gt,buildOtelSpanRequest:Et,createDirectoryLock:kt,enqueuePendingOtelSpan:jn,enqueueTelemetryEvent:Fn,errorCode:vt,flushPendingOtelSpans:It,flushQueue:Ot,flushQueueWithProcessLock:Pt,flushTelemetryArtifacts:De,hashTelemetryErrorFingerprint:Ae,hashTelemetryValue:K,isEmailDomainCharacter:ye,isEmailLocalCharacter:Ee,isExpiredPendingOtelSpan:At,isExpiredQueueEntry:Mt,isFreshDirectoryLock:Rt,isDueForRetry:Ne,isDueForRetryAt:Z,isRetryableQueueRewriteError:Re,looksLikeEmailToken:ct,otelSpansQueuePath:D,parseBooleanTrueLike:x,postTelemetryJson:we,parsePendingOtelSpanLines:ee,prunePendingOtelSpans:te,reconcilePendingOtelSpansAfterFlush:ke,retentionCutoffMs:Oe,resolveOtelTracesEndpoint:ft,resolveTelemetryHttpTimeoutMs:Te,rewritePendingOtelSpans:Lt,normalizeForHash:G,normalizeCaptureLevel:_t,normalizePmVersion:Se,normalizeTelemetryErrorCategory:Me,normalizeTelemetryErrorCode:J,normalizeTelemetryExitCode:X,parseQueueLines:Ie,pruneExpiredQueueEntries:Y,readRuntimeState:ot,readCurrentQueueEntries:b,releaseTelemetryFlushSpawnGate:re,removeFlushedEntriesFromCurrentQueue:ne,removeDirectoryLockBestEffort:Pe,resolveTelemetrySourceContext:xe,rewriteQueue:Ce,sanitizeCommandArgs:ge,sanitizeStringMax:lt,sanitizeStringRedacted:dt,sanitizeValue:N,scheduleTelemetryFlush:oe,shouldFlushInline:rt,sleep:ve,summarizeResult:yt,telemetryFlushRunnerPath:nt,withQueueMutation:S,flushLockPath:Q,flushSpawnLockPath:pe,runtimeStatePath:fe,writeRuntimeState:U};async function Pt(e,t,r){const n=await Ct(e);if(re(e),!n)return!1;try{await De(e,t,r)}finally{try{await ae(Q(e),{recursive:!0,force:!0})}catch{}}return!0}async function Ut(e,t){const r=new Set;try{const{entries:n}=Y(await b(e),t);for(const o of n.filter(Ne))r.add(`event:${o.event.event_id}`)}catch{}try{const n=await R(D(e));if(n!==null)for(const o of te(ee(n),t).entries)Z(o.next_attempt_after)&&r.add(`span:${o.id}`)}catch{}return r}function oe(e,t,r){if(!Ve(e)){if(rt())return q=q.then(()=>De(e,t,r)),q;try{if(!Dt(e))return;const o=zt(process.execPath,[nt()],{detached:!0,stdio:"ignore",cwd:ce.tmpdir(),env:{...process.env,PM_GLOBAL_PATH:e,[I]:"1"}});o.on("error",()=>{re(e)}),o.unref()}catch{re(e)}}}async function pr(e=j(process.cwd())){if(!C().telemetry_disabled)try{await nn(e,async()=>{const t=x(process.env[I]);let r=!0;for(;r;){if(!(await P(e)).telemetry.enabled)return;const o=await S(()=>Le(e),e);if(!o)return;const s=t?await Ut(e,o.retentionDays):new Set;if(!await Pt(e,o.endpoint,o.retentionDays)||!t)return;const a=await Ut(e,o.retentionDays);r=a.size>0&&(a.size!==s.size||[...a].some(c=>!s.has(c)))}},()=>x(process.env[I]))}catch{}}async function hr(e){if(C().telemetry_disabled||e.command==="telemetry"&&e.args.some(t=>t.trim().toLowerCase()==="clear"))return null;try{const t=j(process.cwd());if(!(await P(t)).telemetry.enabled)return null;const n=e.global.noExtensions===!0||Vt(e.command),o=await S(async()=>{const s=await Le(t);if(!s)return null;const{installationId:i,endpoint:a,retentionDays:c,captureLevel:u}=s,_=Se(e.pm_version),m=xe(e.global),f=T(i,e.pm_root),d=T(i,process.cwd()),p=ft(),h=v(),l={schema_version:H,event_id:M.randomUUID(),event_type:"command_start",occurred_at:h,installation_id:i,session_id:B,command:e.command,payload:gt({captureLevel:u,context:e,pmVersion:_,sourceContext:m,pmRootHash:f,cwdHash:d,installationId:i})},g=await $t(t,e.command,n);g===1&&await z(t,l);const A=le(e.command),O={...g<1?{sample_rate:g}:{},started_at:h,started_at_ms:Date.now(),command:e.command,command_taxonomy:A,pm_version:_,source_context:m.source_context,source_context_source:m.source_context_source,installation_id:i,pm_root_hash:f,cwd_hash:d,endpoint:a,retention_days:c,global_pm_root:t,capture_level:u,otel_traces_endpoint:p??void 0,otel_trace_id:p?M.randomBytes(16).toString("hex"):void 0,otel_span_id:p?M.randomBytes(8).toString("hex"):void 0};return g<1&&$.set(O,l),O},t,_e);return o&&o.sample_rate===void 0&&oe(t,o.endpoint,o.retention_days),o}catch{return null}}async function Er(e,t){if(!(!e||C().telemetry_disabled))try{if(!await S(async()=>{const n=await P(e.global_pm_root);if(C().telemetry_disabled||!n.telemetry.enabled||n.telemetry.installation_id!==e.installation_id)return $.delete(e),!1;const o=$.get(e),s=t.ok?e.sample_rate??1:1;if(o){if($.delete(e),M.randomBytes(6).readUIntBE(0,6)/281474976710656>=s)return!1;o.payload.sample_rate=s,await z(e.global_pm_root,o)}const i=v(),a=Math.max(0,Date.now()-e.started_at_ms),c=J($e({ok:t.ok,errorCode:t.error_code,errorMessage:t.error,exitCode:t.exit_code})),u=Me({ok:t.ok,errorCode:c,errorCategory:t.error_category}),_=X(t.exit_code,t.ok),m=t.command_resolution??qe({ok:t.ok,errorCode:c,errorCategory:u}),f=t.resolution_stage??"execute",d={schema_version:H,event_id:M.randomUUID(),event_type:"command_finish",occurred_at:i,installation_id:e.installation_id,session_id:B,command:e.command,payload:{...o?{sample_rate:s}:{},...Tt({captureLevel:e.capture_level,pmVersion:e.pm_version,sourceContext:{source_context:e.source_context,source_context_source:e.source_context_source},outcome:t,durationMs:a,startedAt:e.started_at,command:e.command,installationId:e.installation_id,commandTaxonomy:e.command_taxonomy,exitCode:_,errorCode:c,errorCategory:u,commandResolution:m,resolutionStage:f})}};await z(e.global_pm_root,d);const p=Et(e,{...t,exit_code:_,error_code:c,error_category:u},i,a,s);return p&&await xt(e.global_pm_root,p),!0},e.global_pm_root,_e))return;await oe(e.global_pm_root,e.endpoint,e.retention_days)}catch{}}async function yr(e){if(!C().telemetry_disabled)try{const t=j(process.cwd());if(!(await P(t)).telemetry.enabled)return;const n=await S(async()=>{const o=await Le(t);if(!o)return null;const{installationId:s,captureLevel:i}=o,a=Se(e.pm_version),c=xe(e.global),u=T(s,e.pm_root),_=T(s,process.cwd()),m=v(),f=J($e({ok:!1,errorCode:e.error_code,errorMessage:e.error_message,exitCode:e.exit_code})),d=e.error_category??He(f),p=X(e.exit_code,!1),h=e.command.trim().length>0?e.command:"<unknown>",l=le(h),g=e.command_resolution??qe({ok:!1,errorCode:f,errorCategory:d}),A=e.resolution_stage??"unknown",O={schema_version:H,event_id:M.randomUUID(),event_type:"command_error",occurred_at:m,installation_id:s,session_id:B,command:E(h,"redacted"),payload:wt({captureLevel:i,pmVersion:a,sourceContext:c,command:h,commandTaxonomy:l,commandResolution:g,resolutionStage:A,args:e.args,options:e.options,pmRootHash:u,cwdHash:_,installationId:s,errorCode:f,errorCategory:d,exitCode:p,errorMessage:e.error_message})};return await z(t,O),o},t,_e);n&&await oe(t,n.endpoint,n.retentionDays)}catch{}}export{wr as PM_TELEMETRY_SOURCE_CONTEXT_VALUES,Ge as TELEMETRY_MAX_QUEUE_ENTRY_ATTEMPTS,H as TELEMETRY_SCHEMA_VERSION,fr as _testOnly,yr as emitTelemetryErrorEvent,Er as finishTelemetryCommand,pr as flushTelemetryQueueNow,hr as startTelemetryCommand,mr as waitForPendingFlush,S as withTelemetryQueueMutation};
|
|
10
10
|
//# sourceMappingURL=runtime.js.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
|
|
2
|
-
`)}async function readBackgroundTestRunRecord(pmRoot,runId){const recordPath=getTestRunRecordPath(pmRoot,runId),raw=await readFileIfExists(recordPath);return raw?parseBackgroundRunRecord(raw,recordPath):null}async function listBackgroundRunRecordPaths(pmRoot){const recordsRoot=getTestRunsRecordsPath(pmRoot);return await pathExists(recordsRoot)?(await fs.readdir(recordsRoot,{withFileTypes:!0})).filter(entry=>entry.isFile()&&entry.name.endsWith(".json")).map(entry=>path.join(recordsRoot,entry.name)).sort((left,right)=>right.localeCompare(left)):[]}function parseLinuxRssStatus(raw){const match=raw.match(/^VmRSS:\s+(\d+)\s+kB$/m);if(match)return Number.parseInt(match[1],10)*1024}async function readLinuxRssBytes(pid){if(process.platform==="linux")try{const raw=await fs.readFile(`/proc/${pid}/status`,"utf8");return parseLinuxRssStatus(raw)}catch{return}}function parseLinuxCpuStat(raw){const closeParenIndex=raw.lastIndexOf(")");if(closeParenIndex<0)return{};const parts=raw.slice(closeParenIndex+2).trim().split(/\s+/),utimeTicks=Number.parseInt(parts[11],10),stimeTicks=Number.parseInt(parts[12],10);return!Number.isFinite(utimeTicks)||!Number.isFinite(stimeTicks)?{}:{cpu_user_seconds:utimeTicks/PROC_STAT_TICKS_PER_SECOND,cpu_system_seconds:stimeTicks/PROC_STAT_TICKS_PER_SECOND}}async function readLinuxCpuSeconds(pid){if(process.platform!=="linux")return{};try{const raw=await fs.readFile(`/proc/${pid}/stat`,"utf8");return parseLinuxCpuStat(raw)}catch{return{}}}async function buildResourceSnapshot(record){const pid=record.child_pid??record.worker_pid;if(!isPidRunning(pid))return;const rssBytes=await readLinuxRssBytes(pid),cpu=await readLinuxCpuSeconds(pid),startedAtMs=record.started_at?Date.parse(record.started_at):Number.NaN,uptimeSeconds=Number.isFinite(startedAtMs)?Math.max(0,(nowMs()-startedAtMs)/1e3):void 0;return{recorded_at:nowIso(),rss_bytes:rssBytes,cpu_user_seconds:cpu.cpu_user_seconds,cpu_system_seconds:cpu.cpu_system_seconds,uptime_seconds:uptimeSeconds}}function readCount(value){return typeof value=="number"&&Number.isFinite(value)?value:0}function evaluateWorkerResult(kind,payload){if(!payload||typeof payload!="object")return{summary:{passed:0,failed:1,skipped:0},parsedResult:null};const record=payload;if(kind==="test-all"){const totals=record.totals??{};return{summary:{items:typeof totals.items=="number"?totals.items:void 0,linked_tests:typeof totals.linked_tests=="number"?totals.linked_tests:void 0,passed:readCount(totals.passed),failed:readCount(totals.failed),skipped:readCount(totals.skipped),fail_on_skipped_triggered:record.fail_on_skipped_triggered===!0?!0:void 0},parsedResult:payload}}const runResults=Array.isArray(record.run_results)?record.run_results:[];let passed=0,failed=0,skipped=0;for(const entry of runResults){if(!entry||typeof entry!="object")continue;const status=entry.status;if(status==="passed"){passed+=1;continue}if(status==="failed"||status==="refused"){failed+=1;continue}skipped+=1}return{summary:{passed,failed,skipped,fail_on_skipped_triggered:record.fail_on_skipped_triggered===!0?!0:void 0},parsedResult:payload}}function parseProgressLine(stderrLine){const line=stderrLine.trim();if(line.length===0)return null;const testAllMatch=line.match(/\[pm test-all\]\s+item\s+(\d+)\/(\d+)\s+(start|end)\s+id=([^\s]+)/i);if(testAllMatch){const itemIndex=Number.parseInt(testAllMatch[1],10),itemTotal=Number.parseInt(testAllMatch[2],10);return{item_index:itemIndex,item_total:itemTotal,item_id:testAllMatch[4],linked_test_index:void 0,linked_test_total:void 0,current_command:void 0,elapsed_ms:void 0,heartbeat_at:nowIso(),phase:testAllMatch[3]?.toLowerCase()==="end"?"finished":"running"}}const linkedTestMatch=line.match(/\[pm test\]\s+linked-test\s+(\d+)\/(\d+)\s+(start|running|end)(?:.*elapsed_ms=(\d+))?/i);if(!linkedTestMatch)return null;const index=Number.parseInt(linkedTestMatch[1],10),total=Number.parseInt(linkedTestMatch[2],10),elapsed=linkedTestMatch[4]?Number.parseInt(linkedTestMatch[4],10):void 0,commandMatch=line.match(/\scommand="((?:\\.|[^"\\])*)"/),currentCommand=commandMatch?commandMatch[1].replaceAll('\\"','"').replaceAll("\\\\","\\"):void 0;return{linked_test_index:index,linked_test_total:total,current_command:currentCommand,elapsed_ms:Number.isFinite(elapsed)?elapsed:void 0,heartbeat_at:nowIso(),phase:linkedTestMatch[3]?.toLowerCase()==="end"?"finished":"running"}}function splitLines(value){return value.split(/\r?\n/).map(entry=>entry.trimEnd()).filter(entry=>entry.length>0)}function tailLines(value,limit){if(limit<=0)return[];const lines=splitLines(value);return lines.length<=limit?lines:lines.slice(lines.length-limit)}async function resolveBackgroundCliEntry(cwd){const configured=process.env.PM_BACKGROUND_CLI_ENTRY?.trim();if(configured&&configured.length>0){const resolvedConfigured=path.resolve(cwd,configured);if(await pathExists(resolvedConfigured))return resolvedConfigured}const distEntry=path.resolve(cwd,"dist","cli.js");if(await pathExists(distEntry))return distEntry;const argvEntry=process.argv[1]?.trim();if(argvEntry&&argvEntry.length>0){const resolvedArgvEntry=path.resolve(cwd,argvEntry);if(await pathExists(resolvedArgvEntry))return resolvedArgvEntry}throw new PmCliError("Unable to resolve a CLI entrypoint for background test runs. Build the project or set PM_BACKGROUND_CLI_ENTRY.",EXIT_CODE.GENERIC_FAILURE)}async function refreshRunIfStale(pmRoot,record){if(!BACKGROUND_RUN_ACTIVE_STATUSES.has(record.status)||isPidRunning(record.worker_pid)||record.finished_at)return record;const next={...record,status:"failed",finished_at:nowIso(),error:record.error??"Background test run worker exited before writing terminal status."};return await writeBackgroundRunRecord(pmRoot,next),next}async function startBackgroundTestRun(options){await ensureBackgroundRunStorage(options.pmRoot);const normalizedArgs=normalizeCommandArgs(options.commandArgs);if(normalizedArgs.length===0)throw new PmCliError("Background test run requires command arguments.",EXIT_CODE.USAGE);const fingerprint=buildBackgroundTestRunFingerprint(options.kind,normalizedArgs,options.pmRoot),existingRuns=await listBackgroundTestRuns(options.pmRoot,{});for(const existing of existingRuns){const refreshed=await refreshRunIfStale(options.pmRoot,existing);if(refreshed.fingerprint===fingerprint&&!(!BACKGROUND_RUN_ACTIVE_STATUSES.has(refreshed.status)||!isPidRunning(refreshed.worker_pid)))return{started:!1,run:{...refreshed,duplicate_of:refreshed.id},duplicate_of:refreshed.id}}const runId=buildRunId(),createdAt=nowIso(),stdoutPath=getTestRunStdoutPath(options.pmRoot,runId),stderrPath=getTestRunStderrPath(options.pmRoot,runId),resultPath=getTestRunResultPath(options.pmRoot,runId);await fs.writeFile(stdoutPath,"","utf8"),await fs.writeFile(stderrPath,"","utf8");const record={id:runId,kind:options.kind,status:"queued",created_at:createdAt,updated_at:createdAt,requested_by:options.requestedBy,fingerprint,command_args:normalizedArgs,command_label:summarizeCommandLabel(normalizedArgs),pm_root:options.pmRoot,global_pm_root:options.globalPmRoot,target_id:options.targetId,status_filter:options.statusFilter,attempt:typeof options.attempt=="number"&&Number.isFinite(options.attempt)&&options.attempt>=1?Math.floor(options.attempt):1,resumed_from:options.resumedFrom,resumed_by:options.resumedBy,stdout_path:stdoutPath,stderr_path:stderrPath,result_path:resultPath,progress:{phase:"queued",message:"Queued for background execution.",heartbeat_at:createdAt}};return await writeBackgroundRunRecord(options.pmRoot,record),{started:!0,run:record}}async function spawnBackgroundTestRunWorker(options){const record=await readBackgroundTestRunRecord(options.pmRoot,options.runId);if(!record)throw new PmCliError(`Background test run ${options.runId} not found`,EXIT_CODE.NOT_FOUND);if(BACKGROUND_RUN_TERMINAL_STATUSES.has(record.status))throw new PmCliError(`Background test run ${record.id} is already terminal (${record.status}).`,EXIT_CODE.CONFLICT);const cliEntry=await resolveBackgroundCliEntry(process.cwd()),args=[];options.noExtensions===!0&&args.push("--no-extensions"),args.push("--path",record.pm_root,"test-runs-worker",record.id);const env={...process.env,PM_PATH:record.pm_root,PM_GLOBAL_PATH:record.global_pm_root,PM_BACKGROUND_TEST_RUN_ID:record.id,PM_BACKGROUND_TEST_RUN_ATTEMPT:String(record.attempt),PM_BACKGROUND_TEST_RUN_RESUMED_FROM:record.resumed_from??"",FORCE_COLOR:"0"},child=spawn(process.execPath,[cliEntry,...args],{cwd:process.cwd(),env,detached:!0,stdio:"ignore",windowsHide:!0});child.unref();const next={...record,status:"queued",worker_pid:child.pid,progress:{phase:"queued",message:"Worker process started.",heartbeat_at:nowIso()}};return await writeBackgroundRunRecord(options.pmRoot,next),next}async function appendFileOrdered(queue,filePath,text){await queue,await fs.appendFile(filePath,text,"utf8")}function resolvePositiveEnvInteger(name,fallback){const parsed=Number.parseInt(process.env[name]??"",10);return Number.isFinite(parsed)&&parsed>0?parsed:fallback}function buildBackgroundWorkerEnv(record){return{...process.env,PM_PATH:record.pm_root,PM_GLOBAL_PATH:record.global_pm_root,FORCE_COLOR:"0"}}function buildBackgroundWorkerChildArgs(record,noExtensions){return noExtensions?["--no-extensions",...record.command_args]:[...record.command_args]}function createBackgroundRunRecordWriteScheduler(pmRoot,record){let writeQueue=Promise.resolve();return{schedule(){writeQueue=writeQueue.then(async()=>{try{await writeBackgroundRunRecord(pmRoot,record)}catch{}})},async flush(){await writeQueue}}}function requestChildSignal(child,signal){try{child.kill(signal)}catch{}}async function requestBackgroundWorkerStop(record,child,state,scheduleRecordWrite){state.stopRequested||(state.stopRequested=!0,record.stop_requested_at=nowIso(),record.progress={...record.progress,phase:"stopping",message:"Stop requested for background run.",heartbeat_at:nowIso()},scheduleRecordWrite(),requestChildSignal(child,"SIGTERM"),setTimeout(()=>requestChildSignal(child,"SIGKILL"),resolvePositiveEnvInteger("PM_BACKGROUND_RUN_FORCE_KILL_DELAY_MS",DEFAULT_BACKGROUND_RUN_FORCE_KILL_DELAY_MS)).unref?.())}function buildItemBackgroundProgress(line,progressPatch,phase){return{phase,message:line,heartbeat_at:nowIso(),item_index:progressPatch.item_index,item_total:progressPatch.item_total,item_id:progressPatch.item_id,linked_test_index:void 0,linked_test_total:void 0,current_command:void 0,elapsed_ms:void 0}}function buildLinkedTestBackgroundProgress(line,record,progressPatch,phase){return{phase,message:line,heartbeat_at:nowIso(),item_index:progressPatch.item_index??record.progress?.item_index,item_total:progressPatch.item_total??record.progress?.item_total,item_id:progressPatch.item_id??record.progress?.item_id,linked_test_index:progressPatch.linked_test_index,linked_test_total:progressPatch.linked_test_total,current_command:progressPatch.current_command,elapsed_ms:progressPatch.elapsed_ms}}function applyBackgroundWorkerProgressLine(record,line,stopRequested){const progressPatch=parseProgressLine(line);if(!progressPatch)return!1;const phase=record.progress?.phase==="stopping"?"stopping":"running";return record.progress=progressPatch.item_id?buildItemBackgroundProgress(line,progressPatch,phase):buildLinkedTestBackgroundProgress(line,record,progressPatch,phase),progressPatch.phase==="finished"&&!stopRequested&&(record.progress.phase="running"),!0}function parseBackgroundWorkerStdout(stdoutBuffer){if(stdoutBuffer.trim().length===0)return null;try{return JSON.parse(stdoutBuffer)}catch{return null}}function resolveBackgroundWorkerFinalStatus(exitCode,summary,stopRequested){return stopRequested?"stopped":exitCode===0&&summary.failed===0&&summary.fail_on_skipped_triggered!==!0?"passed":"failed"}function buildFinishedBackgroundProgress(record,stopRequested){return{phase:"finished",message:stopRequested?"Background run stopped.":`Background run finished with status=${record.status}.`,heartbeat_at:nowIso(),item_index:record.progress?.item_index,item_total:record.progress?.item_total,item_id:record.progress?.item_id,linked_test_index:record.progress?.linked_test_index,linked_test_total:record.progress?.linked_test_total,current_command:record.progress?.current_command,elapsed_ms:record.progress?.elapsed_ms}}async function writeBackgroundWorkerResult(record,parsedResult,stdoutBuffer){if(parsedResult!==null){await writeFileAtomic(record.result_path,`${JSON.stringify(parsedResult,null,2)}
|
|
3
|
-
`);return}await
|
|
4
|
-
`)}async function
|
|
1
|
+
import w from"node:fs/promises";import{spawn as j}from"node:child_process";import{createHash as pt,randomBytes as ft}from"node:crypto";import y from"node:path";import{ensureDir as S,pathExists as A,readFileIfExists as x,writeFileAtomic as F}from"../fs/fs-utils.js";import{PmCliError as p}from"../shared/errors.js";import{EXIT_CODE as f}from"../shared/constants.js";import{nowIso as d}from"../shared/time.js";import{getTestRunRecordPath as H,getTestRunResultPath as mt,getTestRunStderrPath as gt,getTestRunStdoutPath as ht,getTestRunsPath as wt,getTestRunsRecordsPath as J,getTestRunsResultsPath as kt,getTestRunsStderrPath as Rt,getTestRunsStdoutPath as Nt}from"../store/paths.js";const Q=new Set(["queued","running"]),U=new Set(["passed","failed","stopped","canceled"]),bt=3e3,Tt=3e3,yt=3e4,V=100,Y=100;function z(){return Date.now()}function X(t){return t.map(e=>e.trim()).filter(e=>e.length>0)}function St(t){const e=t.join(" ").replaceAll(/\s+/g," ").trim();return e.length<=180?e:`${e.slice(0,177)}...`}function Et(){const t=Date.now().toString(36),e=ft(3).toString("hex");return`tr-${t}-${e}`}function Bt(t,e,n){const r={kind:t,command:X(e),pm_root:y.resolve(n)};return pt("sha256").update(JSON.stringify(r)).digest("hex")}function h(t){if(!Number.isInteger(t)||!t||t<=0)return!1;try{return process.kill(t,0),!0}catch(e){return(typeof e=="object"&&e!==null&&"code"in e?e.code:void 0)==="EPERM"}}async function At(t){await S(wt(t)),await S(J(t)),await S(Nt(t)),await S(Rt(t)),await S(kt(t))}async function Z(t,e){try{const n=JSON.parse(t);if(!n||typeof n!="object"||typeof n.id!="string")throw new Error("invalid run record payload");return n}catch(n){throw new p(`Failed to parse background test run record at ${e}: ${n instanceof Error?n.message:String(n)}`,f.GENERIC_FAILURE)}}async function m(t,e){const n={...e,updated_at:d()};await F(H(t,e.id),`${JSON.stringify(n,null,2)}
|
|
2
|
+
`)}async function k(t,e){const n=H(t,e),r=await x(n);return r?Z(r,n):null}async function xt(t){const e=J(t);return await A(e)?(await w.readdir(e,{withFileTypes:!0})).filter(r=>r.isFile()&&r.name.endsWith(".json")).map(r=>y.join(e,r.name)).sort((r,s)=>s.localeCompare(r)):[]}function tt(t){const e=t.match(/^VmRSS:\s+(\d+)\s+kB$/m);if(e)return Number.parseInt(e[1],10)*1024}async function et(t){if(process.platform==="linux")try{const e=await w.readFile(`/proc/${t}/status`,"utf8");return tt(e)}catch{return}}function nt(t){const e=t.lastIndexOf(")");if(e<0)return{};const r=t.slice(e+2).trim().split(/\s+/),s=Number.parseInt(r[11],10),a=Number.parseInt(r[12],10);return!Number.isFinite(s)||!Number.isFinite(a)?{}:{cpu_user_seconds:s/Y,cpu_system_seconds:a/Y}}async function rt(t){if(process.platform!=="linux")return{};try{const e=await w.readFile(`/proc/${t}/stat`,"utf8");return nt(e)}catch{return{}}}async function O(t){const e=t.child_pid??t.worker_pid;if(!h(e))return;const n=await et(e),r=await rt(e),s=t.started_at?Date.parse(t.started_at):Number.NaN,a=Number.isFinite(s)?Math.max(0,(z()-s)/1e3):void 0;return{recorded_at:d(),rss_bytes:n,cpu_user_seconds:r.cpu_user_seconds,cpu_system_seconds:r.cpu_system_seconds,uptime_seconds:a}}function v(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function st(t,e){if(!e||typeof e!="object")return{summary:{passed:0,failed:1,skipped:0},parsedResult:null};const n=e;if(t==="test-all"){const i=n.totals??{};return{summary:{items:typeof i.items=="number"?i.items:void 0,linked_tests:typeof i.linked_tests=="number"?i.linked_tests:void 0,passed:v(i.passed),failed:v(i.failed),skipped:v(i.skipped),fail_on_skipped_triggered:n.fail_on_skipped_triggered===!0?!0:void 0},parsedResult:e}}const r=Array.isArray(n.run_results)?n.run_results:[];let s=0,a=0,u=0;for(const i of r){if(!i||typeof i!="object")continue;const o=i.status;if(o==="passed"){s+=1;continue}if(o==="failed"||o==="refused"){a+=1;continue}u+=1}return{summary:{passed:s,failed:a,skipped:u,fail_on_skipped_triggered:n.fail_on_skipped_triggered===!0?!0:void 0},parsedResult:e}}function at(t){const e=t.trim();if(e.length===0)return null;const n=e.match(/\[pm test-all\]\s+item\s+(\d+)\/(\d+)\s+(start|end)\s+id=([^\s]+)/i);if(n){const c=Number.parseInt(n[1],10),l=Number.parseInt(n[2],10);return{item_index:c,item_total:l,item_id:n[4],linked_test_index:void 0,linked_test_total:void 0,current_command:void 0,elapsed_ms:void 0,heartbeat_at:d(),phase:n[3]?.toLowerCase()==="end"?"finished":"running"}}const r=e.match(/\[pm test\]\s+linked-test\s+(\d+)\/(\d+)\s+(start|running|end)(?:.*elapsed_ms=(\d+))?/i);if(!r)return null;const s=Number.parseInt(r[1],10),a=Number.parseInt(r[2],10),u=r[4]?Number.parseInt(r[4],10):void 0,i=e.match(/\scommand="((?:\\.|[^"\\])*)"/),o=i?i[1].replaceAll('\\"','"').replaceAll("\\\\","\\"):void 0;return{linked_test_index:s,linked_test_total:a,current_command:o,elapsed_ms:Number.isFinite(u)?u:void 0,heartbeat_at:d(),phase:r[3]?.toLowerCase()==="end"?"finished":"running"}}function it(t){return t.split(/\r?\n/).map(e=>e.trimEnd()).filter(e=>e.length>0)}function I(t,e){if(e<=0)return[];const n=it(t);return n.length<=e?n:n.slice(n.length-e)}async function ot(t){const e=process.env.PM_BACKGROUND_CLI_ENTRY?.trim();if(e&&e.length>0){const s=y.resolve(t,e);if(await A(s))return s}const n=y.resolve(t,"dist","cli.js");if(await A(n))return n;const r=process.argv[1]?.trim();if(r&&r.length>0){const s=y.resolve(t,r);if(await A(s))return s}throw new p("Unable to resolve a CLI entrypoint for background test runs. Build the project or set PM_BACKGROUND_CLI_ENTRY.",f.GENERIC_FAILURE)}async function R(t,e){if(!Q.has(e.status)||h(e.worker_pid)||e.finished_at)return e;const r={...e,status:"failed",finished_at:d(),error:e.error??"Background test run worker exited before writing terminal status."};return await m(t,r),r}async function Ot(t){await At(t.pmRoot);const e=X(t.commandArgs);if(e.length===0)throw new p("Background test run requires command arguments.",f.USAGE);const n=Bt(t.kind,e,t.pmRoot),r=await qt(t.pmRoot,{});for(const l of r){const _=await R(t.pmRoot,l);if(_.fingerprint===n&&!(!Q.has(_.status)||!h(_.worker_pid)))return{started:!1,run:{..._,duplicate_of:_.id},duplicate_of:_.id}}const s=Et(),a=d(),u=ht(t.pmRoot,s),i=gt(t.pmRoot,s),o=mt(t.pmRoot,s);await w.writeFile(u,"","utf8"),await w.writeFile(i,"","utf8");const c={id:s,kind:t.kind,status:"queued",created_at:a,updated_at:a,requested_by:t.requestedBy,fingerprint:n,command_args:e,command_label:St(e),pm_root:t.pmRoot,global_pm_root:t.globalPmRoot,target_id:t.targetId,status_filter:t.statusFilter,attempt:typeof t.attempt=="number"&&Number.isFinite(t.attempt)&&t.attempt>=1?Math.floor(t.attempt):1,resumed_from:t.resumedFrom,resumed_by:t.resumedBy,stdout_path:u,stderr_path:i,result_path:o,progress:{phase:"queued",message:"Queued for background execution.",heartbeat_at:a}};return await m(t.pmRoot,c),{started:!0,run:c}}async function It(t){const e=await k(t.pmRoot,t.runId);if(!e)throw new p(`Background test run ${t.runId} not found`,f.NOT_FOUND);if(U.has(e.status))throw new p(`Background test run ${e.id} is already terminal (${e.status}).`,f.CONFLICT);const n=await ot(process.cwd()),r=[];t.noExtensions===!0&&r.push("--no-extensions"),r.push("--path",e.pm_root,"test-runs-worker",e.id);const s={...process.env,PM_PATH:e.pm_root,PM_GLOBAL_PATH:e.global_pm_root,PM_BACKGROUND_TEST_RUN_ID:e.id,PM_BACKGROUND_TEST_RUN_ATTEMPT:String(e.attempt),PM_BACKGROUND_TEST_RUN_RESUMED_FROM:e.resumed_from??"",FORCE_COLOR:"0"},a=j(process.execPath,[n,...r],{cwd:process.cwd(),env:s,detached:!0,stdio:"ignore",windowsHide:!0});a.unref();const u={...e,status:"queued",worker_pid:a.pid,progress:{phase:"queued",message:"Worker process started.",heartbeat_at:d()}};return await m(t.pmRoot,u),u}async function ut(t,e,n){await t,await w.appendFile(e,n,"utf8")}function dt(t,e){const n=Number.parseInt(process.env[t]??"",10);return Number.isFinite(n)&&n>0?n:e}function Ct(t){return{...process.env,PM_PATH:t.pm_root,PM_GLOBAL_PATH:t.global_pm_root,FORCE_COLOR:"0"}}function Pt(t,e){return e?["--no-extensions",...t.command_args]:[...t.command_args]}function Lt(t,e){let n=Promise.resolve();return{schedule(){n=n.then(async()=>{try{await m(t,e)}catch{}})},async flush(){await n}}}function ct(t,e){try{t.kill(e)}catch{}}async function Ft(t,e,n,r){if(n.stopRequested)return;n.stopRequested=!0,t.stop_requested_at=d(),t.progress={...t.progress,phase:"stopping",message:"Stop requested for background run.",heartbeat_at:d()},r(),ct(e,"SIGTERM"),setTimeout(()=>ct(e,"SIGKILL"),dt("PM_BACKGROUND_RUN_FORCE_KILL_DELAY_MS",Tt)).unref?.()}function Ut(t,e,n){return{phase:n,message:t,heartbeat_at:d(),item_index:e.item_index,item_total:e.item_total,item_id:e.item_id,linked_test_index:void 0,linked_test_total:void 0,current_command:void 0,elapsed_ms:void 0}}function vt(t,e,n,r){return{phase:r,message:t,heartbeat_at:d(),item_index:n.item_index??e.progress?.item_index,item_total:n.item_total??e.progress?.item_total,item_id:n.item_id??e.progress?.item_id,linked_test_index:n.linked_test_index,linked_test_total:n.linked_test_total,current_command:n.current_command,elapsed_ms:n.elapsed_ms}}function lt(t,e,n){const r=at(e);if(!r)return!1;const s=t.progress?.phase==="stopping"?"stopping":"running";return t.progress=r.item_id?Ut(e,r,s):vt(e,t,r,s),r.phase==="finished"&&!n&&(t.progress.phase="running"),!0}function Mt(t){if(t.trim().length===0)return null;try{return JSON.parse(t)}catch{return null}}function Dt(t,e,n){return n?"stopped":t===0&&e.failed===0&&e.fail_on_skipped_triggered!==!0?"passed":"failed"}function Gt(t,e){return{phase:"finished",message:e?"Background run stopped.":`Background run finished with status=${t.status}.`,heartbeat_at:d(),item_index:t.progress?.item_index,item_total:t.progress?.item_total,item_id:t.progress?.item_id,linked_test_index:t.progress?.linked_test_index,linked_test_total:t.progress?.linked_test_total,current_command:t.progress?.current_command,elapsed_ms:t.progress?.elapsed_ms}}async function $t(t,e,n){if(e!==null){await F(t.result_path,`${JSON.stringify(e,null,2)}
|
|
3
|
+
`);return}await F(t.result_path,`${JSON.stringify({parse_error:"Background run output was not valid JSON.",stdout_excerpt:I(n,V)},null,2)}
|
|
4
|
+
`)}async function te(t,e,n=!1){const r=await k(t,e);if(!r)throw new p(`Background test run ${e} not found`,f.NOT_FOUND);const s={...r,status:"running",started_at:r.started_at??d(),worker_pid:process.pid,progress:{phase:"running",message:"Worker started.",heartbeat_at:d()}},a=await ot(process.cwd()),u=Ct(s);await m(t,s);const i=Pt(s,n),o=j(process.execPath,[a,...i],{cwd:process.cwd(),env:u,detached:!1,stdio:["ignore","pipe","pipe"],windowsHide:!0});s.child_pid=o.pid;const c=Lt(t,s),l=c.schedule;let _=Promise.resolve(),C=Promise.resolve(),P="",N="";const b={stopRequested:!1},E=()=>{Ft(s,o,b,l)};process.on("SIGTERM",E),process.on("SIGINT",E);const M=setInterval(()=>{(async()=>(s.resource=await O(s),s.progress.heartbeat_at=d(),l()))()},dt("PM_BACKGROUND_RUN_RESOURCE_INTERVAL_MS",bt));M.unref?.(),o.stdout?.on("data",T=>{const g=T.toString("utf8");P+=g,_=ut(_,s.stdout_path,g)}),o.stderr?.on("data",T=>{const g=T.toString("utf8");C=ut(C,s.stderr_path,g),N+=g;const B=N.split(/\r?\n/);N=B.pop();let K=!1;for(const _t of B){const W=_t.trimEnd();W.length>0&<(s,W,b.stopRequested)&&(K=!0)}K&&l()});let L=null,D=null;try{({code:L,signal:D}=await new Promise(T=>{o.on("close",(g,B)=>{T({code:g,signal:B})})}))}finally{clearInterval(M),process.off("SIGTERM",E),process.off("SIGINT",E)}await _,await C;const G=N.trimEnd();G.length>0&<(s,G,b.stopRequested)&&l(),N="";const $=Mt(P),q=st(s.kind,$);return s.summary=q.summary,s.exit_code=typeof L=="number"?L:void 0,s.signal=D??void 0,s.finished_at=d(),s.status=Dt(s.exit_code,q.summary,b.stopRequested),s.progress=Gt(s,b.stopRequested),s.resource=await O(s),await $t(s,$,P),await m(t,s),await c.flush(),s}async function qt(t,e){const n=await xt(t),r=[];for(const o of n){const c=await x(o);if(!c)continue;const l=await Z(c,o);r.push(l)}const s=[];for(const o of r)s.push(await R(t,o));const u=(e.status?s.filter(o=>o.status===e.status):s).sort((o,c)=>{const l=Date.parse(c.updated_at)-Date.parse(o.updated_at);return Number.isFinite(l)&&l!==0?l:c.id.localeCompare(o.id)}),i=typeof e.limit=="number"&&e.limit>=0?e.limit:void 0;return i===void 0?u:u.slice(0,i)}async function ee(t,e){const n=await k(t,e);if(!n)throw new p(`Background test run ${e} not found`,f.NOT_FOUND);const r=await R(t,n),s=h(r.worker_pid),a=h(r.child_pid);r.status==="running"&&!a&&!r.finished_at&&!s&&(r.status="failed",r.finished_at=d(),r.error=r.error??"Background run process exited unexpectedly.",await m(t,r)),r.status==="running"&&(r.resource=await O(r),await m(t,r));const u=r.progress?.heartbeat_at,i=u?Date.parse(u):Number.NaN,o=Number.isFinite(i)?Math.max(0,z()-i):void 0,c=Number.parseInt(process.env.PM_BACKGROUND_RUN_HEARTBEAT_STALE_MS??"",10),l=Number.isFinite(c)&&c>0?c:yt,_=r.status==="running"?o!==void 0&&o>l?"stale":"healthy":"inactive";return{run:r,health:{state:_,last_heartbeat_at:u,heartbeat_lag_ms:o,worker_alive:s,child_alive:a}}}function Kt(t,e){const n=e?"SIGKILL":"SIGTERM";if(!h(t.worker_pid)||!t.worker_pid)return"none";try{return process.kill(t.worker_pid,n),n}catch{return"none"}}function Wt(t,e){return{phase:"stopping",message:e==="none"?"Run marked stopped.":`Stop requested via ${e}.`,heartbeat_at:d(),item_index:t.progress?.item_index,item_total:t.progress?.item_total,item_id:t.progress?.item_id,linked_test_index:t.progress?.linked_test_index,linked_test_total:t.progress?.linked_test_total,current_command:t.progress?.current_command,elapsed_ms:t.progress?.elapsed_ms}}async function ne(t,e,n=!1){const r=await k(t,e);if(!r)throw new p(`Background test run ${e} not found`,f.NOT_FOUND);const s=await R(t,r);if(U.has(s.status))return{run:s,signal_sent:"none"};const a=Kt(s,n);return a==="none"&&(s.status="stopped",s.finished_at=s.finished_at??d()),s.stop_requested_at=d(),s.progress=Wt(s,a),await m(t,s),{run:s,signal_sent:a}}async function re(t,e,n,r=!1){const s=await k(t,e);if(!s)throw new p(`Background test run ${e} not found`,f.NOT_FOUND);const a=await R(t,s);if(!U.has(a.status))throw new p(`Background test run ${e} is not terminal and cannot be resumed.`,f.CONFLICT);const u=await Ot({pmRoot:a.pm_root,globalPmRoot:a.global_pm_root,kind:a.kind,commandArgs:a.command_args,requestedBy:n,targetId:a.target_id,statusFilter:a.status_filter,resumedFrom:a.id,resumedBy:n,attempt:a.attempt+1});if(!u.started)return u.run;const i=await It({pmRoot:t,runId:u.run.id,noExtensions:r}),o={...a,resumed_by:i.id};return await m(t,o),i}async function se(t,e,n,r){const s=await k(t,e);if(!s)throw new p(`Background test run ${e} not found`,f.NOT_FOUND);const a=typeof r=="number"&&Number.isFinite(r)&&r>=0?Math.floor(r):V,u=n==="stdout"||n==="both"?await x(s.stdout_path)??"":"",i=n==="stderr"||n==="both"?await x(s.stderr_path)??"":"";return{run:s,stream:n,tail:a,stdout:n==="stdout"||n==="both"?I(u,a):[],stderr:n==="stderr"||n==="both"?I(i,a):[]}}const ae={buildResourceSnapshot:O,evaluateWorkerResult:st,isPidRunning:h,parseLinuxCpuStat:nt,parseLinuxRssStatus:tt,parseProgressLine:at,readLinuxCpuSeconds:rt,readLinuxRssBytes:et,refreshRunIfStale:R,splitLines:it,tailLines:I};export{ae as _testOnly,Bt as buildBackgroundTestRunFingerprint,ee as getBackgroundTestRunStatus,qt as listBackgroundTestRuns,se as readBackgroundTestRunLogs,k as readBackgroundTestRunRecord,re as resumeBackgroundTestRun,te as runBackgroundTestRunWorker,It as spawnBackgroundTestRunWorker,Ot as startBackgroundTestRun,ne as stopBackgroundTestRun};
|
|
5
5
|
//# sourceMappingURL=background-runs.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
import{mutateItem as u}from"../store/item-store.js";import{compareTimestampStrings as o}from"../shared/time.js";const m=20;function d(){const t=process.env.PM_TRACKED_TEST_RUN_HISTORY_LIMIT;if(!t||t.trim().length===0)return m;const e=Number.parseInt(t,10);return!Number.isFinite(e)||e<=0?m:e}function c(t){const e=[...t].filter(r=>r.run_id.trim().length>0&&r.started_at.trim().length>0&&r.finished_at.trim().length>0&&r.recorded_at.trim().length>0).sort((r,a)=>{const s=o(r.recorded_at,a.recorded_at);if(s!==0)return s;const i=r.run_id.localeCompare(a.run_id);return i!==0?i:r.kind.localeCompare(a.kind)}),n=d();return e.length>n?e.slice(e.length-n):e}async function l(t){await u({pmRoot:t.pmRoot,settings:t.settings,id:t.itemId,op:"test_run_track",author:t.author,message:t.message,force:!1,mutate(e){const n=e.metadata.test_runs??[];return e.metadata.test_runs=c([...n,t.entry]),{changedFields:["test_runs"]}}})}export{l as appendTrackedTestRunSummary,c as buildTrackedTestRunHistory};
|
|
2
2
|
//# sourceMappingURL=item-test-run-tracking.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
import{EXIT_CODE as o}from"../shared/constants.js";import{PmCliError as l}from"../shared/errors.js";const a=100;function h(e,n="--only-index"){const t=typeof e=="number"?e:Number(String(e).trim());if(!Number.isInteger(t)||t<1)throw new l(`${n} requires a 1-based integer index into the linked-test list (got "${e}"). Use pm test <id> --list to inspect positions.`,o.USAGE);return t}function m(e){const t=(e.command??e.path??"<no command>").replaceAll(/\s+/g," ").trim()||"<no command>";return t.length<=a?t:`${t.slice(0,a-3)}...`}function u(e){return e.map((n,t)=>`${t+1}. ${m(n)}`).join("; ")}function p(e){const n=[];return e.match!==void 0&&n.push("match"),e.onlyIndex!==void 0&&n.push("only-index"),e.onlyLast===!0&&n.push("only-last"),n}function f(e,n){const t=e.command?.toLowerCase()??"",d=e.path?.toLowerCase()??"";return t.includes(n)||d.includes(n)}function _(e,n){const t=p(n);if(t.length===0)return{selector:null,requested:null,selected:e,selected_indexes:e.map((i,s)=>s+1),selected_count:e.length,skipped_count:0};if(t.length>1)throw new l(`Combine at most one linked-test selector per run: ${t.map(i=>`--${i}`).join(" and ")} were provided. Pick one of --match, --only-index, --only-last.`,o.USAGE);const d=t[0];if(e.length===0)throw new l(`--${d} matched no linked tests because this item has none. Add one first with --add, --command, or --add-json.`,o.USAGE);if(d==="match"){const i=n.match.trim().toLowerCase();if(i.length===0)throw new l("--match requires a non-empty substring to match against linked-test command/path values",o.USAGE);const s=[],r=[];for(let c=0;c<e.length;c+=1)f(e[c],i)&&(r.push(e[c]),s.push(c+1));if(r.length===0)throw new l(`--match "${n.match}" matched none of the ${e.length} linked test(s). Available entries: ${u(e)}`,o.USAGE);return{selector:"match",requested:n.match,selected:r,selected_indexes:s,selected_count:r.length,skipped_count:e.length-r.length}}if(d==="only-index"){const i=h(n.onlyIndex);if(i>e.length)throw new l(`--only-index ${i} is out of range: this item has ${e.length} linked test(s). Available entries: ${u(e)}`,o.USAGE);return{selector:"only-index",requested:String(i),selected:[e[i-1]],selected_indexes:[i],selected_count:1,skipped_count:e.length-1}}return{selector:"only-last",requested:"last",selected:[e[e.length-1]],selected_indexes:[e.length],selected_count:1,skipped_count:e.length-1}}export{u as describeLinkedTestEntries,h as parseOnlyIndexValue,_ as resolveLinkedTestRunSelection};
|
|
2
2
|
//# sourceMappingURL=run-selectors.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
const a={Epic:2880,Feature:480,Story:480,Milestone:2880,Task:120,Issue:60,Bug:60,Chore:30,Decision:15,Plan:120},s=120;function i(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function u(e){const t=new Map;for(const[o,n]of Object.entries(e))t.set(o.toLowerCase(),n);return t}const f=u(a),c=new WeakMap;function l(e){const t=c.get(e);if(t)return t;const o=u(e);return c.set(e,o),o}function E(e,t){const o=(e??"").trim().toLowerCase();if(o.length===0)return s;if(t){const r=l(t).get(o);if(i(r))return Math.floor(r)}const n=f.get(o);return i(n)?Math.floor(n):s}function p(e){const t={};if(e===null||typeof e!="object"||Array.isArray(e))return t;for(const[o,n]of Object.entries(e)){const r=o.trim();r.length===0||!i(n)||(t[r]=Math.floor(n))}return t}export{a as DEFAULT_ESTIMATE_MINUTES_BY_TYPE,s as FALLBACK_ESTIMATE_MINUTES,p as normalizeEstimateDefaultOverrides,E as resolveEstimateDefaultMinutes};
|
|
2
2
|
//# sourceMappingURL=estimate-defaults.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
import{EXIT_CODE as s}from"../shared/constants.js";import{PmCliError as d}from"../shared/errors.js";import{resolveEstimateDefaultMinutes as c}from"./estimate-defaults.js";const u=["metadata","resolution"],a=["metadata","resolution","estimates","timestamps","lifecycle"],m="completed";function r(n){return`"${n.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function l(n){const e=n?.trim();return e!==void 0&&e.length>0?e:void 0}function k(n){const e=[];for(const t of n){if(!t.missing_fields.includes("resolution"))continue;const i=l(t.close_reason)??m;e.push({item_id:t.id,check:"resolution",field:"resolution",kind:"set_resolution",value:i,command:`pm update ${t.id} --resolution ${r(i)}`,gate:"resolution"})}return e}function g(n){const e=[];for(const t of n){const i=l(t.resolution);i!==void 0&&e.push({item_id:t.id,check:"metadata",field:"close_reason",kind:"set_close_reason",value:i,command:`pm update ${t.id} --close-reason ${r(i)}`,gate:"metadata"})}return e}function h(n,e){return n.map(t=>{const i=c(t.type,e);return{item_id:t.id,check:"metadata",field:"estimated_minutes",kind:"set_estimate",value:String(i),command:`pm update ${t.id} --estimate ${i}`,gate:"estimates"}})}function x(n){return n.map(e=>e.grandparent_id!==void 0&&e.grandparent_active===!0?{item_id:e.id,check:"lifecycle",field:"parent",kind:"reparent",parent_id:e.grandparent_id,command:`pm update ${e.id} --parent ${e.grandparent_id}`,gate:"lifecycle"}:{item_id:e.id,check:"lifecycle",field:"parent",kind:"unset_parent",command:`pm update ${e.id} --unset parent`,gate:"lifecycle"})}function $(n){const e=[];for(const t of n){if(t.classification!=="deleted")continue;const i=t.link_kind==="files"?"files":"docs";e.push({item_id:t.item_id,check:"files",field:t.link_kind,kind:t.link_kind==="files"?"prune_file_link":"prune_doc_link",path:t.path,command:`pm ${i} ${t.item_id} --remove ${r(t.path)}`})}return e}function E(n){const e=(n??[]).flatMap(i=>i.split(",")).map(i=>i.trim()).filter(i=>i.length>0);if(e.length===0){if(n!==void 0&&n.length>0)throw new d(`--fix-scope values must not be empty. Supported values: ${a.join(", ")}.`,s.USAGE);return new Set(u)}const t=new Set;for(const i of e){const o=i.toLowerCase().replaceAll("-","_");if(a.includes(o)){t.add(o);continue}throw new d(`Unknown --fix-scope value "${i}". Supported values: ${a.join(", ")}.`,s.USAGE)}return t}function F(n,e){const t=[],i=[];for(const o of n)o.gate!==void 0&&!e.has(o.gate)?i.push(o):t.push(o);return{applicable:t,gated:i}}function S(n){return{item_id:n.item_id,check:n.check,field:n.field,command:n.command,...n.gate!==void 0?{gate:n.gate}:{}}}export{u as DEFAULT_GRANTED_FIX_SCOPES,a as SUPPORTED_FIX_SCOPES,F as partitionFixesByGrant,g as planCloseReasonBackfillFixes,h as planEstimateBackfillFixes,k as planResolutionBackfillFixes,$ as planStaleLinkPruneFixes,x as planTerminalParentFixes,E as resolveGrantedFixScopes,S as toFixOutputRow};
|
|
2
2
|
//# sourceMappingURL=fix-planning.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
const t=/^[a-z][a-z0-9+.-]+:\/\//i;function E(e){return t.test(e.trim())}export{E as isRemoteLinkedArtifactReference};
|
|
2
2
|
//# sourceMappingURL=linked-artifact-reference.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
function r(f){const o=new Map;for(const t of f){let e=o.get(t.item_type);e||(e=new Map,o.set(t.item_type,e)),e.set(t.field,(e.get(t.field)??0)+1)}const n={};for(const t of[...o.keys()].sort((e,s)=>e.localeCompare(s))){const e=o.get(t),s={};for(const c of[...e.keys()].sort((i,l)=>i.localeCompare(l)))s[c]=e.get(c);n[t]=s}return n}export{r as buildMissingByTypeCounts};
|
|
2
2
|
//# sourceMappingURL=missing-by-type.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
function r(e,s){return e==="malformed"||s==="malformed"?"malformed":e==="moved"||s==="moved"?"moved":"deleted"}function l(e){return`${e.item_id} ${e.link_kind}`}function d(e,s){const o=new Map;for(const i of e){const t=o.get(i.path);t?(t.classification=r(t.classification,i.classification),t.owners.set(l(i),i)):o.set(i.path,{classification:i.classification,owners:new Map([[l(i),i]])})}return[...o.entries()].sort(([i],[t])=>i.localeCompare(t)).map(([i,t])=>({path:i,classification:t.classification,items:[...t.owners.values()].map(n=>{const a=s(n.item_id);return{id:n.item_id,type:a?.type??"Unknown",title:a?.title??"",status:a?.status??"",field:n.link_kind}}).sort((n,a)=>{const c=n.id.localeCompare(a.id);return c!==0?c:n.field.localeCompare(a.field)})}))}function f(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function m(e){const s=[];for(const o of e)for(const i of o.items)s.push(`${o.path}:${o.classification} owner=${i.id} status=${i.status} field=${i.field} title="${f(i.title)}"`);return s}export{d as buildMissingLinkedPathRows,m as summarizeMissingLinkedPathRows};
|
|
2
2
|
//# sourceMappingURL=missing-link-owners.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
const l=3;function d(a){const n=Math.max(a.lastIndexOf("/"),a.lastIndexOf("\\"));return n===-1?a:a.slice(n+1)}function r(a,n,c=3){const o=Number.isFinite(c)&&c>=1?Math.floor(c):3,i=new Map;for(const e of n){const s=d(e);if(s.length===0)continue;const t=i.get(s);t?t.push(e):i.set(s,[e])}return a.map(e=>{if(e.includes(",")||e.replace(/^[a-z]:[\\/]/i,"").includes(":"))return{path:e,classification:"malformed",candidates:[],candidates_truncated:!1};const s=(i.get(d(e))??[]).filter(t=>t!==e).sort((t,f)=>t.localeCompare(f));return s.length===0?{path:e,classification:"deleted",candidates:[],candidates_truncated:!1}:{path:e,classification:"moved",candidates:s.slice(0,o),candidates_truncated:s.length>o}})}function u(a){return a.map(n=>n.classification==="moved"?`${n.path}:moved:${n.candidates[0]}`:`${n.path}:${n.classification}`)}export{l as DEFAULT_STALE_PATH_CANDIDATE_LIMIT,r as classifyStaleLinkedPaths,u as summarizeStaleLinkedPathClassifications};
|
|
2
2
|
//# sourceMappingURL=stale-file-classification.js.map
|