@unbrained/pm-cli 2026.9.7 → 2026.9.8
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 +12 -4
- package/.agents/skills/pm-developer/references/MULTI_AGENT_MERGE.md +19 -10
- package/.agents/skills/pm-extensions/SKILL.md +6 -0
- package/.agents/skills/pm-sdk/SKILL.md +11 -2
- package/.agents/skills/pm-user/SKILL.md +5 -0
- package/.agents/skills/pm-user/references/ECOSYSTEM_PLANNING.md +95 -0
- package/.claude-plugin/marketplace.json +2 -2
- package/CHANGELOG.md +211 -181
- package/dist/cli/after-command-context-usage.js +1 -48
- package/dist/cli/argv-utils.js +1 -40
- package/dist/cli/bootstrap-args.js +1 -9
- package/dist/cli/bundle-integrity.js +2 -110
- package/dist/cli/commander-usage.js +11 -771
- package/dist/cli/commands/activity.js +1 -9
- package/dist/cli/commands/aggregate.js +1 -5
- package/dist/cli/commands/append.js +1 -5
- package/dist/cli/commands/claim.js +1 -5
- package/dist/cli/commands/close-many.js +1 -5
- package/dist/cli/commands/close.js +1 -9
- package/dist/cli/commands/comments.js +1 -5
- package/dist/cli/commands/config.js +1 -9
- package/dist/cli/commands/context.js +1 -9
- package/dist/cli/commands/contracts.js +1 -5
- package/dist/cli/commands/copy.js +1 -9
- package/dist/cli/commands/create.js +1 -9
- package/dist/cli/commands/delete.js +1 -9
- package/dist/cli/commands/deps.js +1 -9
- package/dist/cli/commands/docs.js +1 -9
- package/dist/cli/commands/duplicates.js +1 -9
- package/dist/cli/commands/eval.js +1 -9
- package/dist/cli/commands/extension/describe.js +1 -5
- package/dist/cli/commands/extension/scaffold.js +1 -5
- package/dist/cli/commands/extension/shared.js +1 -5
- package/dist/cli/commands/extension.js +1 -9
- package/dist/cli/commands/files.js +1 -9
- package/dist/cli/commands/focus.js +1 -9
- package/dist/cli/commands/gc.js +1 -9
- package/dist/cli/commands/get.js +1 -9
- package/dist/cli/commands/graph.js +1 -10
- package/dist/cli/commands/health.js +1 -9
- package/dist/cli/commands/history-compact.js +1 -10
- package/dist/cli/commands/history-redact.js +1 -11
- package/dist/cli/commands/history-repair.js +1 -10
- package/dist/cli/commands/history.js +1 -5
- package/dist/cli/commands/index.js +1 -58
- package/dist/cli/commands/init-agent-guidance.js +1 -9
- package/dist/cli/commands/init.js +1 -9
- package/dist/cli/commands/learnings.js +1 -5
- package/dist/cli/commands/lifecycle-transitions.js +1 -5
- package/dist/cli/commands/list.js +1 -9
- package/dist/cli/commands/merge.js +1 -11
- package/dist/cli/commands/next.js +1 -9
- package/dist/cli/commands/notes.js +1 -5
- package/dist/cli/commands/plan.js +1 -9
- package/dist/cli/commands/profile.js +1 -9
- package/dist/cli/commands/restore.js +1 -9
- package/dist/cli/commands/scheduling-shortcuts.js +1 -9
- package/dist/cli/commands/schema.js +1 -10
- package/dist/cli/commands/search.js +1 -9
- package/dist/cli/commands/stats.js +1 -9
- package/dist/cli/commands/telemetry.js +1 -9
- package/dist/cli/commands/test-all.js +1 -9
- package/dist/cli/commands/test-runs.js +1 -9
- package/dist/cli/commands/test.js +1 -9
- package/dist/cli/commands/update-many.js +1 -5
- package/dist/cli/commands/update.js +1 -9
- package/dist/cli/commands/upgrade.js +1 -5
- package/dist/cli/commands/validate.js +1 -15
- package/dist/cli/context-intent-invocation.js +1 -20
- package/dist/cli/description-stdin.js +1 -17
- package/dist/cli/error-guidance.js +1 -1353
- package/dist/cli/extension-command-help.js +5 -636
- package/dist/cli/extension-command-options.js +1 -427
- package/dist/cli/extension-recovery.js +1 -126
- package/dist/cli/help-content.js +2 -1001
- package/dist/cli/help-json-payload.js +4 -570
- package/dist/cli/main.d.ts +4 -0
- package/dist/cli/main.js +5 -2573
- package/dist/cli/migration-gates.js +1 -289
- package/dist/cli/public.js +1 -20
- package/dist/cli/register-annotations.js +1 -270
- package/dist/cli/register-assurance.js +1 -62
- package/dist/cli/register-files-lookup.js +1 -56
- package/dist/cli/register-history-activity.d.ts +8 -0
- package/dist/cli/register-history-activity.js +2 -0
- package/dist/cli/register-history-author.js +1 -38
- package/dist/cli/register-history-maintenance.d.ts +9 -0
- package/dist/cli/register-history-maintenance.js +2 -0
- package/dist/cli/register-list-query.js +10 -943
- package/dist/cli/register-mutation-options.js +1 -9
- package/dist/cli/register-mutation.js +19 -1893
- package/dist/cli/register-operations.js +1 -920
- package/dist/cli/register-setup.js +1 -716
- package/dist/cli/register-structured-mutation.js +1 -196
- package/dist/cli/registration-helpers.js +1 -5
- package/dist/cli/runtime-compatibility-boundary.js +4 -42
- package/dist/cli/schema-registration-helpers.js +1 -73
- package/dist/cli/search-refresh.js +1 -13
- package/dist/cli/stats-analytics-json.js +1 -68
- package/dist/cli/telemetry-flush.js +1 -10
- package/dist/cli-bundle/bundle-manifest.json +164 -156
- package/dist/cli-bundle/chunks/chunk-3BZZA6A3.js +5 -0
- package/dist/cli-bundle/chunks/chunk-AMRDVX36.js +235 -0
- package/dist/cli-bundle/chunks/chunk-DAM4CBBR.js +2202 -0
- package/dist/cli-bundle/chunks/{chunk-WYRZZ5ZE.js → chunk-DEZPZOQ7.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-FLDWYEND.js +77 -0
- package/dist/cli-bundle/chunks/{chunk-NPN5I67J.js → chunk-G5ADGQ2D.js} +3 -3
- package/dist/cli-bundle/chunks/chunk-JAAEYHUA.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-JX4DH4WC.js → chunk-KR3RP4FH.js} +3 -3
- package/dist/cli-bundle/chunks/chunk-LEZOUXG6.js +2 -0
- package/dist/cli-bundle/chunks/chunk-NSAPNEYH.js +2 -0
- package/dist/cli-bundle/chunks/chunk-QOEKOECV.js +29 -0
- package/dist/cli-bundle/chunks/chunk-RHSFOMHU.js +2 -0
- package/dist/cli-bundle/chunks/chunk-XOD2PCB6.js +20 -0
- package/dist/cli-bundle/chunks/{chunk-JT6XF6GE.js → chunk-YVEQ2AMO.js} +4 -4
- package/dist/cli-bundle/chunks/register-list-query-KSK3R63M.js +11 -0
- package/dist/cli-bundle/chunks/register-mutation-IQ5C7U6O.js +20 -0
- package/dist/cli-bundle/chunks/{register-operations-I5W3KMGB.js → register-operations-DWVHR2NC.js} +2 -2
- package/dist/cli-bundle/chunks/register-setup-BQ5SVD4B.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-3WRPWLA7.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-7MBUII7U.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-COPBO5HW.js +8 -0
- package/dist/cli-bundle/focused-chunks/chunk-DUN4IXYN.js +20 -0
- package/dist/cli-bundle/focused-chunks/{chunk-LIJIA4TY.js → chunk-EE5QSM4Z.js} +3 -3
- package/dist/cli-bundle/focused-chunks/chunk-HJVARYM3.js +6 -0
- package/dist/cli-bundle/focused-chunks/chunk-IAUOUGVR.js +177 -0
- package/dist/cli-bundle/focused-chunks/chunk-KOOMJ54F.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-MZDXX7JY.js +56 -0
- package/dist/cli-bundle/focused-chunks/{chunk-M6PBRFSH.js → chunk-OPFHFGDD.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-QHNETP77.js +9 -0
- package/dist/cli-bundle/focused-chunks/{chunk-3BZEOXLT.js → chunk-RMWES4M6.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-RXT4P5QH.js +10 -0
- package/dist/cli-bundle/focused-chunks/chunk-SDOL6FM2.js +12 -0
- package/dist/cli-bundle/focused-chunks/chunk-SQV4AAUC.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-PEFABF7E.js → chunk-WE3IUNIW.js} +3 -3
- package/dist/cli-bundle/focused-chunks/chunk-YALOUBWJ.js +2 -0
- package/dist/cli-bundle/main.js +20 -20
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +2 -2
- package/dist/cli-bundle/sdk-core.js +29 -29
- 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 +42 -42
- 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 +11 -11
- package/dist/cli.js +1 -104
- package/dist/core/checkpoint/checkpoint-gc.js +1 -169
- package/dist/core/checkpoint/mutation-checkpoint.js +2 -133
- package/dist/core/config/nested-settings.js +1 -534
- package/dist/core/config/positional-value.js +1 -109
- package/dist/core/diagnostics/remediation.js +1 -506
- package/dist/core/extensions/activation-summary-markdown.js +2 -145
- package/dist/core/extensions/activation-summary.js +1 -92
- package/dist/core/extensions/activation-transaction.js +1 -46
- package/dist/core/extensions/capability-usage.js +1 -173
- package/dist/core/extensions/command-hook-context.js +1 -13
- package/dist/core/extensions/command-metadata-contract.js +1 -22
- package/dist/core/extensions/command-visibility-tier.js +1 -29
- package/dist/core/extensions/contribution-inventory.js +1 -173
- package/dist/core/extensions/exporter-output-contract.js +1 -66
- package/dist/core/extensions/extension-candidate.js +1 -18
- package/dist/core/extensions/extension-capability-aliases.js +1 -158
- package/dist/core/extensions/extension-hook-runtime.js +1 -699
- package/dist/core/extensions/extension-policy.js +1 -599
- package/dist/core/extensions/extension-registries.js +1 -62
- package/dist/core/extensions/extension-runtime-helpers.js +1 -33
- package/dist/core/extensions/extension-types.js +1 -102
- package/dist/core/extensions/flag-definition-validation.js +1 -52
- package/dist/core/extensions/flag-value-types.js +1 -64
- package/dist/core/extensions/index.js +1 -526
- package/dist/core/extensions/item-field-types.js +1 -39
- package/dist/core/extensions/item-fields.js +1 -261
- package/dist/core/extensions/loader.js +1 -2223
- package/dist/core/extensions/manifest-schema.js +1 -69
- package/dist/core/extensions/module-graph-snapshot.js +1 -33
- package/dist/core/extensions/preflight-ownership.js +1 -41
- package/dist/core/extensions/registration-validation.js +1 -82
- package/dist/core/extensions/registration-values.js +1 -209
- package/dist/core/extensions/reserved-host-flags.js +1 -36
- package/dist/core/extensions/runtime-registrations.js +1 -67
- package/dist/core/extensions/service-ownership.js +1 -19
- package/dist/core/extensions/version-compat.js +1 -216
- package/dist/core/fs/fs-utils.js +2 -158
- package/dist/core/fs/host-environment-errors.js +1 -141
- package/dist/core/fs/index.js +1 -9
- package/dist/core/fs/path-utils.js +1 -17
- package/dist/core/governance/content-fields.js +1 -160
- package/dist/core/governance/issue-codes.js +1 -151
- package/dist/core/governance/metadata-coverage.js +1 -358
- package/dist/core/history/drift-cache.js +3 -72
- package/dist/core/history/drift-scan.js +1 -342
- package/dist/core/history/event-classification.js +1 -109
- package/dist/core/history/event-index.js +8 -784
- package/dist/core/history/history-compact-bulk.js +1 -104
- package/dist/core/history/history-diff.js +1 -158
- package/dist/core/history/history-rewrite.d.ts +6 -1
- package/dist/core/history/history-rewrite.js +1 -107
- package/dist/core/history/history-storage-stats.js +1 -102
- package/dist/core/history/history-stream-policy.js +1 -62
- package/dist/core/history/history.js +2 -617
- package/dist/core/history/identity.js +1 -30
- package/dist/core/history/index.js +1 -9
- package/dist/core/history/projection.js +1 -196
- package/dist/core/history/read.d.ts +9 -0
- package/dist/core/history/read.js +1 -57
- package/dist/core/history/replay.js +2 -439
- package/dist/core/history/version-address.js +1 -32
- package/dist/core/history/workspace-history.js +2 -433
- package/dist/core/io/body-file.js +1 -62
- package/dist/core/io/bulk-ids-input.js +1 -112
- package/dist/core/item/actionability.js +1 -327
- package/dist/core/item/dependency-reference.js +1 -20
- package/dist/core/item/id.js +1 -112
- package/dist/core/item/index.js +1 -12
- package/dist/core/item/item-format-version.js +1 -78
- package/dist/core/item/item-format.js +5 -1473
- package/dist/core/item/item-record.js +1 -23
- package/dist/core/item/item-type-definition.js +1 -133
- package/dist/core/item/parent-reference-policy.js +1 -57
- package/dist/core/item/parse.js +2 -603
- package/dist/core/item/plan-lifecycle.js +1 -19
- package/dist/core/item/priority.js +1 -61
- package/dist/core/item/sprint-release-format.js +1 -38
- package/dist/core/item/status-filter.js +1 -115
- package/dist/core/item/status.js +1 -43
- package/dist/core/item/toon-decode.js +1 -29
- package/dist/core/item/type-registry.js +1 -715
- package/dist/core/item/type-synonyms.js +1 -38
- package/dist/core/lock/index.js +1 -9
- package/dist/core/lock/lock-gc.js +1 -240
- package/dist/core/lock/lock.js +3 -590
- package/dist/core/output/mutation-projection.js +1 -217
- package/dist/core/output/output-control.js +1 -25
- package/dist/core/output/output.js +11 -494
- package/dist/core/output/query-summary.js +1 -58
- package/dist/core/output/tabular.js +1 -77
- package/dist/core/packages/manifest.js +1 -244
- package/dist/core/packages/root.js +1 -84
- package/dist/core/profile/profile-describe.js +1 -83
- package/dist/core/profile/profile-lint.js +1 -415
- package/dist/core/profile/profile-plan.js +0 -0
- package/dist/core/profile/profile-presets.js +1 -370
- package/dist/core/reproducibility/context.js +1 -82
- package/dist/core/schema/fields-file.js +2 -288
- package/dist/core/schema/item-types-file.js +2 -296
- package/dist/core/schema/runtime-field-filters.js +1 -49
- package/dist/core/schema/runtime-field-values.js +1 -313
- package/dist/core/schema/runtime-schema.js +2 -826
- package/dist/core/schema/status-defs-file.js +2 -227
- package/dist/core/schema/status-token.js +1 -31
- package/dist/core/schema/type-inference.js +1 -95
- package/dist/core/schema/type-presets.js +1 -87
- package/dist/core/schema/type-workflows.js +1 -104
- package/dist/core/search/background-refresh.js +2 -286
- package/dist/core/search/bm25.js +1 -146
- package/dist/core/search/cache.js +2 -534
- package/dist/core/search/corpus.js +1 -311
- package/dist/core/search/embedding-batches.js +1 -163
- package/dist/core/search/eval.js +1 -225
- package/dist/core/search/http-client.js +1 -75
- package/dist/core/search/providers.js +1 -242
- package/dist/core/search/relevance.js +1 -244
- package/dist/core/search/semantic-defaults.js +1 -199
- package/dist/core/search/staleness.js +1 -30
- package/dist/core/search/vector-stores.js +2 -664
- package/dist/core/search/vectorization-metadata.js +1 -81
- package/dist/core/sentry/helpers.js +1 -272
- package/dist/core/sentry/instrument.js +1 -387
- package/dist/core/session/session-state.js +1 -260
- package/dist/core/shared/agent-session-context.js +1 -133
- package/dist/core/shared/author.js +1 -1172
- package/dist/core/shared/command-types.js +1 -4
- package/dist/core/shared/conflict-markers.js +1 -31
- package/dist/core/shared/constants.js +1 -405
- package/dist/core/shared/errors.js +1 -20
- package/dist/core/shared/html-entity-decode.js +1 -131
- package/dist/core/shared/index.js +1 -12
- package/dist/core/shared/item-metadata-contract.js +1 -89
- package/dist/core/shared/lazy-module.js +1 -16
- package/dist/core/shared/levenshtein.js +1 -61
- package/dist/core/shared/memo.js +1 -19
- package/dist/core/shared/numeric-parsers.js +1 -20
- package/dist/core/shared/option-alias-visibility.js +1 -67
- package/dist/core/shared/primitives.js +1 -127
- package/dist/core/shared/serial-queue.js +1 -79
- package/dist/core/shared/serialization.js +1 -210
- package/dist/core/shared/split-comma-list.js +1 -30
- package/dist/core/shared/text-normalization.js +1 -38
- package/dist/core/shared/time.js +1 -306
- package/dist/core/store/index.js +1 -12
- package/dist/core/store/item-format-migration.js +1 -125
- package/dist/core/store/item-metadata-cache.js +1 -1116
- package/dist/core/store/item-metadata-query-index.js +9 -394
- package/dist/core/store/item-metadata-read-work.js +1 -43
- package/dist/core/store/item-store.js +1 -693
- package/dist/core/store/paths.d.ts +1 -1
- package/dist/core/store/paths.js +1 -214
- package/dist/core/store/settings-read-cache.js +1 -85
- package/dist/core/store/settings-validator.js +1 -421
- package/dist/core/store/settings.js +3 -1309
- package/dist/core/store/tracker-preflight.js +1 -141
- package/dist/core/telemetry/consent.js +5 -108
- package/dist/core/telemetry/observability.js +1 -246
- package/dist/core/telemetry/runtime.js +4 -1988
- package/dist/core/test/background-runs.js +4 -945
- package/dist/core/test/item-test-run-tracking.js +1 -63
- package/dist/core/test/run-selectors.js +1 -120
- package/dist/core/validate/estimate-defaults.js +1 -89
- package/dist/core/validate/fix-planning.js +1 -189
- package/dist/core/validate/linked-artifact-reference.js +1 -36
- package/dist/core/validate/missing-by-type.js +1 -34
- package/dist/core/validate/missing-link-owners.js +1 -95
- package/dist/core/validate/stale-file-classification.js +1 -82
- package/dist/mcp/http-server.js +5 -448
- package/dist/mcp/legacy-adapter.js +1 -77
- package/dist/mcp/runtime-capabilities.js +1 -200
- package/dist/mcp/server.js +4 -1233
- package/dist/mcp/tool-definitions.js +1 -804
- package/dist/sdk/actionability.js +1 -13
- package/dist/sdk/agent/closed-domain-contracts.js +1 -161
- package/dist/sdk/agent/command-recovery.js +1 -59
- package/dist/sdk/agent/command-suggestions.js +1 -66
- package/dist/sdk/agent/create-option-policy.js +1 -31
- package/dist/sdk/agent/identity-config.js +1 -106
- package/dist/sdk/agent/item-addressing.js +1 -207
- package/dist/sdk/agent/refusal-closure-census.js +1 -151
- package/dist/sdk/agent/refusal-closure.js +1 -133
- package/dist/sdk/agent/refusal-corpus-contracts.js +1 -193
- package/dist/sdk/agent/refusal-reachability.js +1 -593
- package/dist/sdk/agent/subcommand-recovery.js +1 -83
- package/dist/sdk/agent/task-transcript-contracts.js +1 -197
- package/dist/sdk/agent/tracker-preflight-contracts.js +1 -126
- package/dist/sdk/agent-capability-contracts.js +1 -428
- package/dist/sdk/agent-session-context.js +1 -9
- package/dist/sdk/annotations.js +1 -448
- package/dist/sdk/author-attribution.js +1 -468
- package/dist/sdk/authoring.js +1 -20
- package/dist/sdk/cli-bootstrap.js +1 -838
- package/dist/sdk/cli-contracts/agent-output-contracts.d.ts +1 -1
- package/dist/sdk/cli-contracts/agent-output-contracts.js +4 -476
- package/dist/sdk/cli-contracts/bootstrap-command-scanner.js +1 -79
- package/dist/sdk/cli-contracts/command-aliases.d.ts +4 -0
- package/dist/sdk/cli-contracts/command-aliases.js +1 -107
- package/dist/sdk/cli-contracts/command-exit-contracts.js +1 -151
- package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1081
- package/dist/sdk/cli-contracts/commander-types.js +1 -159
- package/dist/sdk/cli-contracts/completeness.js +1 -393
- package/dist/sdk/cli-contracts/enum-contracts.js +1 -222
- package/dist/sdk/cli-contracts/flag-contracts.js +1 -1947
- package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -347
- package/dist/sdk/cli-contracts/grammar-contracts.js +1 -986
- package/dist/sdk/cli-contracts/registration-helpers.js +7 -990
- package/dist/sdk/cli-contracts/runtime-contracts.d.ts +5 -0
- package/dist/sdk/cli-contracts/runtime-contracts.js +1 -2090
- package/dist/sdk/cli-contracts/schemas/assurance-definition.js +1 -324
- package/dist/sdk/cli-contracts/string-lists.js +1 -16
- package/dist/sdk/cli-contracts/tool-option-contracts.js +1 -461
- package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -2167
- package/dist/sdk/cli-contracts/tool-schema.d.ts +3 -1
- package/dist/sdk/cli-contracts/tool-schema.js +1 -1664
- package/dist/sdk/cli-contracts/typed-action-inputs.js +1 -4
- package/dist/sdk/cli-contracts.d.ts +1 -1
- package/dist/sdk/cli-contracts.js +1 -17
- package/dist/sdk/cli-program.js +1 -49
- package/dist/sdk/command-line.d.ts +2 -5
- package/dist/sdk/command-line.js +1 -78
- package/dist/sdk/comments.js +1 -133
- package/dist/sdk/compile-cache.js +1 -73
- package/dist/sdk/completion.js +157 -837
- package/dist/sdk/compose.js +1 -1090
- package/dist/sdk/config.js +1 -1204
- package/dist/sdk/context/recency.js +1 -33
- package/dist/sdk/context/semantic-session-attribution.js +1 -82
- package/dist/sdk/context/usage-egress.js +1 -29
- package/dist/sdk/context/usage-ledger.js +3 -185
- package/dist/sdk/context-intent-contracts.js +1 -709
- package/dist/sdk/context-intent-runtime.js +1 -115
- package/dist/sdk/context-packing.js +1 -218
- package/dist/sdk/context-relevance.js +1 -503
- package/dist/sdk/context-signal-store.js +2 -426
- package/dist/sdk/context-usage.js +1 -367
- package/dist/sdk/contracts.js +1 -23
- package/dist/sdk/core-governance.js +1 -14
- package/dist/sdk/core.js +1 -14
- package/dist/sdk/corpus-shape.js +1 -401
- package/dist/sdk/define.js +1 -220
- package/dist/sdk/dependencies.js +1 -718
- package/dist/sdk/dependency-flag-validation.js +1 -156
- package/dist/sdk/dependency-provenance.js +1 -135
- package/dist/sdk/docs.js +1 -14
- package/dist/sdk/duplicates.js +1 -40
- package/dist/sdk/environment/agent-environment.js +1 -466
- package/dist/sdk/environment/host-environment-errors.js +1 -8
- package/dist/sdk/environment/project-runtime-compatibility.js +1 -481
- package/dist/sdk/environment/source-context.js +1 -28
- package/dist/sdk/environment/tracker-preflight.js +1 -9
- package/dist/sdk/error-code-catalog.js +1 -153
- package/dist/sdk/error-runtime.js +1 -58
- package/dist/sdk/errors.js +1 -58
- package/dist/sdk/eval.js +1 -190
- package/dist/sdk/extension/author-manifest.js +1 -92
- package/dist/sdk/extension/bundled-catalog.js +1 -332
- package/dist/sdk/extension/concurrency.js +1 -25
- package/dist/sdk/extension/copy-scope.d.ts +2 -0
- package/dist/sdk/extension/copy-scope.js +2 -0
- package/dist/sdk/extension/custom-field-collisions.js +1 -30
- package/dist/sdk/extension/describe.js +3 -189
- package/dist/sdk/extension/doctor.js +1 -606
- package/dist/sdk/extension/install-plan.d.ts +69 -0
- package/dist/sdk/extension/install-plan.js +2 -0
- package/dist/sdk/extension/install-receipts.d.ts +7 -0
- package/dist/sdk/extension/install-receipts.js +2 -0
- package/dist/sdk/extension/install-runtime.js +3 -313
- package/dist/sdk/extension/install-snapshot.js +1 -66
- package/dist/sdk/extension/install-sources.js +5 -1057
- package/dist/sdk/extension/managed-state.js +2 -252
- package/dist/sdk/extension/migrations.js +2 -174
- package/dist/sdk/extension/output-ownership.js +1 -25
- package/dist/sdk/extension/runtime-summary.js +1 -18
- package/dist/sdk/extension/scaffold.js +4 -2308
- package/dist/sdk/extension/shared.js +1 -147
- package/dist/sdk/extension/source-resolution.js +1 -65
- package/dist/sdk/extension/update-check.js +1 -67
- package/dist/sdk/extension-command-context.js +1 -44
- package/dist/sdk/extension-contracts.js +1 -73
- package/dist/sdk/extension.d.ts +7 -2
- package/dist/sdk/extension.js +1 -2196
- package/dist/sdk/files.js +1 -535
- package/dist/sdk/flag-invocation-contracts.d.ts +0 -5
- package/dist/sdk/flag-invocation-contracts.js +1 -344
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -2224
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -2236
- package/dist/sdk/generated-error-code-catalog.js +1 -16
- package/dist/sdk/governance/assurance-action-contracts.js +1 -4
- package/dist/sdk/governance/assurance-action.js +1 -411
- package/dist/sdk/governance/assurance-limits.js +1 -10
- package/dist/sdk/governance/assurance-mutation-error.js +1 -81
- package/dist/sdk/governance/assurance-presets.js +1 -135
- package/dist/sdk/governance/assurance-runtime.js +1 -238
- package/dist/sdk/governance/assurance.js +4 -1182
- package/dist/sdk/governance/boundary-fixtures.js +1 -200
- package/dist/sdk/governance/coverage-assurance.js +1 -60
- package/dist/sdk/governance/defect-recurrence-coverage.js +1 -188
- package/dist/sdk/governance/defect-recurrence-graph.js +1 -120
- package/dist/sdk/governance/defect-recurrence-signals.js +1 -24
- package/dist/sdk/governance/defect-recurrence.js +1 -623
- package/dist/sdk/governance/extension-host-version.js +1 -115
- package/dist/sdk/governance/gc.js +1 -368
- package/dist/sdk/governance/health.js +1 -2367
- package/dist/sdk/governance/hierarchy-validation.js +1 -108
- package/dist/sdk/governance/linked-file-report.js +1 -71
- package/dist/sdk/governance/merge-receipt-history.js +1 -206
- package/dist/sdk/governance/provenance-health.js +1 -282
- package/dist/sdk/governance/reindex.js +4 -761
- package/dist/sdk/governance/stale-work.js +1 -82
- package/dist/sdk/governance/status-role-diagnostics.js +1 -35
- package/dist/sdk/governance/storage-integrity.js +1 -280
- package/dist/sdk/governance/tracked-runtime-cache.js +1 -106
- package/dist/sdk/governance/upgrade.js +2 -327
- package/dist/sdk/governance/validate-history-drift.js +1 -81
- package/dist/sdk/governance/validate-item-reader.js +1 -17
- package/dist/sdk/governance/validate-normalization.js +1 -36
- package/dist/sdk/governance/validate.js +1 -2261
- package/dist/sdk/governance/workspace-position.js +1 -163
- package/dist/sdk/governance.d.ts +1 -0
- package/dist/sdk/governance.js +1 -31
- package/dist/sdk/graph/adapter.js +1 -181
- package/dist/sdk/graph/analytics.js +1 -474
- package/dist/sdk/graph/assembly.js +1 -377
- package/dist/sdk/graph/cache.js +1 -160
- package/dist/sdk/graph/centrality.js +1 -258
- package/dist/sdk/graph/conformance.js +1 -130
- package/dist/sdk/graph/deadline-scheduling.d.ts +90 -0
- package/dist/sdk/graph/deadline-scheduling.js +2 -0
- package/dist/sdk/graph/durable-cache.d.ts +1 -1
- package/dist/sdk/graph/durable-cache.js +1 -361
- package/dist/sdk/graph/governance-contracts.js +1 -34
- package/dist/sdk/graph/governance.d.ts +13 -1
- package/dist/sdk/graph/governance.js +1 -735
- package/dist/sdk/graph/hierarchy-integrity.js +1 -310
- package/dist/sdk/graph/index.d.ts +3 -2
- package/dist/sdk/graph/index.js +1 -26
- package/dist/sdk/graph/lifecycle-coverage.d.ts +32 -0
- package/dist/sdk/graph/lifecycle-coverage.js +2 -0
- package/dist/sdk/graph/mutation-advisory.js +1 -176
- package/dist/sdk/graph/remediation.js +1 -197
- package/dist/sdk/graph/run.d.ts +15 -1
- package/dist/sdk/graph/run.js +1 -768
- package/dist/sdk/graph/scheduling.js +1 -124
- package/dist/sdk/graph/traversal.js +1 -284
- package/dist/sdk/graph/workspace-relationship-kind-registry.js +1 -27
- package/dist/sdk/graph.js +1 -15
- package/dist/sdk/guide-topics.js +1 -707
- package/dist/sdk/guide.js +1 -279
- package/dist/sdk/history/maintenance.d.ts +71 -0
- package/dist/sdk/history/maintenance.js +2 -0
- package/dist/sdk/history/salvage.js +2 -247
- package/dist/sdk/history/subject.d.ts +19 -0
- package/dist/sdk/history/subject.js +2 -0
- package/dist/sdk/history-analytics.js +1 -282
- package/dist/sdk/history-compact.js +1 -527
- package/dist/sdk/history-mcp.js +1 -68
- package/dist/sdk/history-provenance.js +1 -182
- package/dist/sdk/history-read.js +1 -96
- package/dist/sdk/history-redact.d.ts +1 -14
- package/dist/sdk/history-redact.js +1 -643
- package/dist/sdk/history-repair.d.ts +5 -0
- package/dist/sdk/history-repair.js +1 -657
- package/dist/sdk/improvement-ledger-validation.js +1 -62
- package/dist/sdk/improvement-ledger.js +2 -257
- package/dist/sdk/index.d.ts +4 -0
- package/dist/sdk/index.js +1 -183
- package/dist/sdk/init-agent-guidance.js +2 -496
- package/dist/sdk/init.js +2 -820
- package/dist/sdk/invocation-author.js +1 -39
- package/dist/sdk/item-children.js +1 -90
- package/dist/sdk/item-metadata-index.js +1 -15
- package/dist/sdk/item-schedule.js +1 -27
- package/dist/sdk/item-transaction.js +1 -396
- package/dist/sdk/learnings.js +1 -29
- package/dist/sdk/lifecycle/append.js +2 -53
- package/dist/sdk/lifecycle/claim.d.ts +2 -0
- package/dist/sdk/lifecycle/claim.js +1 -242
- package/dist/sdk/lifecycle/close-many.js +1 -438
- package/dist/sdk/lifecycle/close.js +1 -468
- package/dist/sdk/lifecycle/copy.js +1 -212
- package/dist/sdk/lifecycle/create.js +1 -1949
- package/dist/sdk/lifecycle/delete.js +1 -45
- package/dist/sdk/lifecycle/event-validation-messages.js +1 -91
- package/dist/sdk/lifecycle/focus.js +1 -91
- package/dist/sdk/lifecycle/hierarchy-mutation-lock.js +1 -24
- package/dist/sdk/lifecycle/legacy-none-tokens.js +1 -149
- package/dist/sdk/lifecycle/lifecycle-transitions.js +1 -40
- package/dist/sdk/lifecycle/mcp-actions.d.ts +2 -0
- package/dist/sdk/lifecycle/mcp-actions.js +1 -51
- package/dist/sdk/lifecycle/metadata-normalizers.js +1 -46
- package/dist/sdk/lifecycle/mutation-command-options.js +1 -9
- package/dist/sdk/lifecycle/plan.js +1 -1606
- package/dist/sdk/lifecycle/recurrence-parsers.js +1 -147
- package/dist/sdk/lifecycle/reopen.js +1 -68
- package/dist/sdk/lifecycle/repeatable-metadata-parsers.js +1 -143
- package/dist/sdk/lifecycle/restore.d.ts +1 -0
- package/dist/sdk/lifecycle/restore.js +1 -330
- package/dist/sdk/lifecycle/shared-unset-fields.js +1 -295
- package/dist/sdk/lifecycle/update-many.js +1 -861
- package/dist/sdk/lifecycle/update.js +1 -2136
- package/dist/sdk/lifecycle-completion.js +1 -92
- package/dist/sdk/lifecycle-policy.js +1 -120
- package/dist/sdk/linked-artifacts.js +1 -530
- package/dist/sdk/mcp/apps.js +4 -133
- package/dist/sdk/mcp/authorization.js +1 -404
- package/dist/sdk/mcp/discovery.js +1 -494
- package/dist/sdk/mcp/interactions.js +1 -336
- package/dist/sdk/mcp/protocol.d.ts +7 -0
- package/dist/sdk/mcp/protocol.js +1 -184
- package/dist/sdk/mcp/skills.js +1 -389
- package/dist/sdk/mcp/subscriptions.js +1 -211
- package/dist/sdk/mcp/tasks.js +2 -430
- package/dist/sdk/mcp/transport.js +1 -260
- package/dist/sdk/merge/abandoned-receipts.js +1 -46
- package/dist/sdk/merge/driver.js +1 -212
- package/dist/sdk/merge/index.js +1 -16
- package/dist/sdk/merge/install.js +3 -561
- package/dist/sdk/merge/receipt-file-boundary.js +1 -46
- package/dist/sdk/merge/receipt-operation.js +1 -96
- package/dist/sdk/merge/receipt-schema.js +1 -397
- package/dist/sdk/merge/receipts.js +4 -525
- package/dist/sdk/merge/reconcile.js +1 -352
- package/dist/sdk/merge/three-way.js +3 -775
- package/dist/sdk/merge.js +1 -10
- package/dist/sdk/mutation-events.js +1 -292
- package/dist/sdk/mutation-guard.js +1 -216
- package/dist/sdk/notes.js +1 -139
- package/dist/sdk/output-contracts.js +1 -172
- package/dist/sdk/output-projection.js +1 -430
- package/dist/sdk/output-token-accounting.js +1 -140
- package/dist/sdk/output.js +1 -64
- package/dist/sdk/ownership-source.js +1 -21
- package/dist/sdk/package-import-adapters.js +1 -442
- package/dist/sdk/package-migrations.js +1 -20
- package/dist/sdk/package-runtime-options.js +1 -80
- package/dist/sdk/pagination.js +1 -162
- package/dist/sdk/profile.js +1 -454
- package/dist/sdk/provenance.js +1 -258
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/query/activity.js +1 -401
- package/dist/sdk/query/aggregate.d.ts +16 -0
- package/dist/sdk/query/aggregate.js +1 -390
- package/dist/sdk/query/calendar.js +1 -964
- package/dist/sdk/query/complete-list.js +1 -215
- package/dist/sdk/query/context.js +1 -1702
- package/dist/sdk/query/duplicate-candidates.js +1 -70
- package/dist/sdk/query/get.js +1 -450
- package/dist/sdk/query/history.js +1 -186
- package/dist/sdk/query/item-filter-options.js +1 -9
- package/dist/sdk/query/light-metadata.js +1 -18
- package/dist/sdk/query/list-filter-shared.js +1 -81
- package/dist/sdk/query/list.js +1 -1304
- package/dist/sdk/query/multi-value-filters.js +1 -78
- package/dist/sdk/query/next.js +1 -513
- package/dist/sdk/query/parsers.js +1 -44
- package/dist/sdk/query/projection-contracts.js +1 -184
- package/dist/sdk/query/search-contracts.js +1 -230
- package/dist/sdk/query/search-pagination.js +1 -35
- package/dist/sdk/query/search-rendering.js +1 -105
- package/dist/sdk/query/search.js +2 -1987
- package/dist/sdk/query.js +1 -35
- package/dist/sdk/read-output/continuation.js +1 -194
- package/dist/sdk/read-output-budget.js +1 -135
- package/dist/sdk/read-output-contracts.js +1 -1225
- package/dist/sdk/read-output-rows.js +1 -186
- package/dist/sdk/read-output-session.js +1 -208
- package/dist/sdk/relationship-analytics.js +1 -410
- package/dist/sdk/relationship-context.js +1 -284
- package/dist/sdk/relationship-history.js +4 -519
- package/dist/sdk/relationship-kinds/contract.js +1 -22
- package/dist/sdk/relationship-migration.js +1 -77
- package/dist/sdk/relationships.js +1 -579
- package/dist/sdk/reproducibility/process.js +1 -87
- package/dist/sdk/runtime-action-aliases.js +1 -59
- package/dist/sdk/runtime-extended-actions.js +1 -177
- package/dist/sdk/runtime-input.js +1 -614
- package/dist/sdk/runtime-primitives.js +1 -84
- package/dist/sdk/runtime-public-contracts.js +1 -4
- package/dist/sdk/runtime-stats-options.js +1 -38
- package/dist/sdk/runtime.js +1 -1928
- package/dist/sdk/scheduling-shortcuts.js +1 -63
- package/dist/sdk/schema-migration.js +3 -856
- package/dist/sdk/schema.js +1 -1376
- package/dist/sdk/search-refresh-worker.js +1 -18
- package/dist/sdk/similarity-scoring.js +1 -53
- package/dist/sdk/similarity.js +1 -326
- package/dist/sdk/start-task-status.js +1 -14
- package/dist/sdk/stats.js +1 -270
- package/dist/sdk/structured-mutations.js +1 -580
- package/dist/sdk/telemetry-flush.js +1 -13
- package/dist/sdk/telemetry.js +1 -405
- package/dist/sdk/templates.js +2 -292
- package/dist/sdk/test/batch.js +2 -509
- package/dist/sdk/test/entry.js +1 -70
- package/dist/sdk/test/execution.js +6 -2211
- package/dist/sdk/test/linked-command-detection.js +1 -546
- package/dist/sdk/test/measurements.js +1 -91
- package/dist/sdk/test/parsers.js +1 -545
- package/dist/sdk/test/runs.js +1 -193
- package/dist/sdk/test/trust.js +2 -206
- package/dist/sdk/testing.js +4 -1391
- package/dist/sdk/traceability/runtime-files-lookup.js +1 -32
- package/dist/sdk/traceability/source-traceability.js +1 -292
- package/dist/sdk/tracker-root-discovery.js +1 -9
- package/dist/sdk/workspace-contracts-cache.js +1 -28
- package/dist/sdk/workspace-contracts.js +1 -33
- package/dist/sdk/workspace-memory.js +2 -318
- package/dist/sdk/workspace-recipe.js +1 -71
- package/dist/sdk/workspace-snapshot.js +4 -613
- package/dist/sdk/workspace-transaction-gc.js +1 -149
- package/dist/sdk/workspace-transaction.js +2 -363
- package/dist/sdk/workspace.js +3 -127
- package/dist/types/index.js +1 -9
- package/dist/types.js +1 -245
- package/docs/AGENT_GUIDE.md +1 -1
- package/docs/CONTEXT_ALGORITHM_PORTFOLIO.md +167 -0
- package/docs/DIAGNOSTIC_OUTPUT_CONTRACTS.md +9 -3
- package/docs/EXTENSIONS.md +1 -0
- package/docs/HISTORY_MAINTENANCE.md +125 -0
- package/docs/MCP_2026_07_28_CONFORMANCE.md +20 -10
- package/docs/PACKAGE_EVIDENCE.md +92 -0
- package/docs/PLANNING_MEASUREMENTS.md +183 -0
- package/docs/README.md +3 -0
- package/docs/SCRIPTING.md +21 -0
- package/docs/TESTING.md +23 -0
- package/docs/generated/FLAG_LEXICON_BUDGETS.md +5 -5
- package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +2 -2
- package/marketplace.json +2 -2
- package/package.json +1 -1
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/scripts/finalize-build.mjs +45 -3
- package/dist/cli-bundle/chunks/chunk-AZDFJGH6.js +0 -9
- package/dist/cli-bundle/chunks/chunk-BAX2BYUW.js +0 -2111
- package/dist/cli-bundle/chunks/chunk-CKOL5U7J.js +0 -77
- package/dist/cli-bundle/chunks/chunk-OF76PSDQ.js +0 -5
- package/dist/cli-bundle/chunks/chunk-QUWFABDM.js +0 -232
- package/dist/cli-bundle/chunks/chunk-QWRRFYK3.js +0 -2
- package/dist/cli-bundle/chunks/chunk-RWWBOWJ5.js +0 -2
- package/dist/cli-bundle/chunks/chunk-WGAOYSYH.js +0 -40
- package/dist/cli-bundle/chunks/chunk-WI2AYPA7.js +0 -2
- package/dist/cli-bundle/chunks/register-list-query-5JL52D33.js +0 -11
- package/dist/cli-bundle/chunks/register-mutation-ZPG7KMVP.js +0 -20
- package/dist/cli-bundle/chunks/register-setup-H4SVAVX7.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-AL5ON6K6.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-CHC2IDXA.js +0 -6
- package/dist/cli-bundle/focused-chunks/chunk-CK6QFAPZ.js +0 -20
- package/dist/cli-bundle/focused-chunks/chunk-EZR3GHFE.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-H2WJWK7L.js +0 -56
- package/dist/cli-bundle/focused-chunks/chunk-NTPY5GSO.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-P5O7MP5Y.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-PDMW2E36.js +0 -177
- package/dist/cli-bundle/focused-chunks/chunk-QTVCLMSZ.js +0 -6
- package/dist/cli-bundle/focused-chunks/chunk-QTZRBUYA.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-SGQST3PQ.js +0 -12
- package/dist/cli-bundle/focused-chunks/chunk-UKHASMMP.js +0 -10
- package/dist/cli-bundle/focused-chunks/chunk-ZPEKQHOC.js +0 -2
|
@@ -1,2368 +1,2 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @module sdk/governance/health
|
|
3
|
-
*
|
|
4
|
-
* Implements the pm health command surface and its agent-facing runtime behavior.
|
|
5
|
-
*/
|
|
6
|
-
|
|
7
|
-
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="cee8abad-51d2-5051-9cb8-81447bf2fd50")}catch(e){}}();
|
|
8
|
-
import fs from "node:fs/promises";
|
|
9
|
-
import path from "node:path";
|
|
10
|
-
import { assertInitializedTracker } from "../environment/tracker-preflight.js";
|
|
11
|
-
import { isTerminalStatus } from "../../core/item/status.js";
|
|
12
|
-
import { resolveItemTypeRegistry } from "../../core/item/type-registry.js";
|
|
13
|
-
import { resolveRuntimeStatusRegistry } from "../../core/schema/runtime-schema.js";
|
|
14
|
-
import { isFileMissingError, readFileIfExists, } from "../../core/fs/fs-utils.js";
|
|
15
|
-
import { activateExtensions, getActiveExtensionRegistrations, loadExtensions, runActiveOnReadHooks, } from "../../core/extensions/index.js";
|
|
16
|
-
import { collectRegisteredItemFieldNames } from "../../core/extensions/item-fields.js";
|
|
17
|
-
import { KNOWN_EXTENSION_CAPABILITIES, } from "../../core/extensions/loader.js";
|
|
18
|
-
import { enforceHistoryStreamPolicyForItems } from "../../core/history/history-stream-policy.js";
|
|
19
|
-
import { scanHistoryDrift } from "../../core/history/drift-scan.js";
|
|
20
|
-
import { scanLockHealth } from "../../core/lock/lock-gc.js";
|
|
21
|
-
import { readVectorizationStatusLedger, refreshSemanticEmbeddingsForMutatedItems, } from "../../core/search/cache.js";
|
|
22
|
-
import { resolveEmbeddingProviders, resolveProviderConfigSource, } from "../../core/search/providers.js";
|
|
23
|
-
import { resolveSettingsWithSemanticRuntimeDefaults } from "../../core/search/semantic-defaults.js";
|
|
24
|
-
import { collectStaleVectorizationIds } from "../../core/search/staleness.js";
|
|
25
|
-
import { buildVectorizationEmbeddingIdentity, hasVectorizationEmbeddingIdentityChanged, } from "../../core/search/vectorization-metadata.js";
|
|
26
|
-
import { resolveVectorStores } from "../../core/search/vector-stores.js";
|
|
27
|
-
import { EXIT_CODE, PM_CORE_REQUIRED_SUBDIRS, TYPE_TO_FOLDER, } from "../../core/shared/constants.js";
|
|
28
|
-
import { findFirstMergeConflictMarker } from "../../core/shared/conflict-markers.js";
|
|
29
|
-
import { PmCliError } from "../../core/shared/errors.js";
|
|
30
|
-
import { toNonEmptyStringOrUndefined } from "../../core/shared/primitives.js";
|
|
31
|
-
import { nowIso } from "../../core/shared/time.js";
|
|
32
|
-
import { parseItemDocument } from "../../core/item/item-format.js";
|
|
33
|
-
import { effectiveItemFormatVersion, scanItemFormatVersions, } from "../../core/item/item-format-version.js";
|
|
34
|
-
import { listAllItemMetadataLight, listAllItemMetadataWithBody, } from "../../core/store/item-store.js";
|
|
35
|
-
import { PM_TELEMETRY_SOURCE_CONTEXT_VALUES, TELEMETRY_MAX_QUEUE_ENTRY_ATTEMPTS, TELEMETRY_SCHEMA_VERSION, } from "../../core/telemetry/runtime.js";
|
|
36
|
-
import { getItemFormatFromPath, getSettingsPath, ITEM_FILE_EXTENSIONS, resolveGlobalPmRoot, resolvePmRoot, resolveWorkspaceRoot, } from "../../core/store/paths.js";
|
|
37
|
-
import { readSettingsWithMetadata } from "../../core/store/settings.js";
|
|
38
|
-
import { buildRemediationMap, resolveRemediation, } from "../../core/diagnostics/remediation.js";
|
|
39
|
-
import { scanExtensionHostVersions } from "./extension-host-version.js";
|
|
40
|
-
import { scanHistoryAuthorAttribution, } from "../author-attribution.js";
|
|
41
|
-
import { readManagedExtensionState } from "../extension.js";
|
|
42
|
-
import { scanProvenanceResolverHealth } from "./provenance-health.js";
|
|
43
|
-
import { applyStoredExtensionMigrationState } from "../extension/migrations.js";
|
|
44
|
-
import { inspectExtensionAuthorManifest } from "../extension/author-manifest.js";
|
|
45
|
-
import { buildCapabilityContractMetadata, buildRegistrationCollisionRemediation, collectUnknownCapabilityGuidance, } from "../extension/doctor.js";
|
|
46
|
-
import { scanStaleInProgressItems, } from "./stale-work.js";
|
|
47
|
-
import { scanTrackedRuntimeCache } from "./tracked-runtime-cache.js";
|
|
48
|
-
import { auditMergeDriverConfiguration, findGitWorkspaceRoot, } from "../merge/install.js";
|
|
49
|
-
import { inspectMergeReceiptEvidence, partitionMergeReceipts, } from "../merge/receipts.js";
|
|
50
|
-
import { classifyHistoryMergeReceiptReferences, extractHistoryMergeReceiptDispositions, extractHistoryMergeReceiptReferences, } from "./merge-receipt-history.js";
|
|
51
|
-
import { runHistoryRepair } from "../history-repair.js";
|
|
52
|
-
import { resolveWorkspaceRelationshipKindRegistry } from "../graph/assembly.js";
|
|
53
|
-
import { analyzeHierarchyIntegrity, } from "../graph/hierarchy-integrity.js";
|
|
54
|
-
import { buildStatusRoleWarnings, inspectStatusRoleAssignments, } from "./status-role-diagnostics.js";
|
|
55
|
-
const PM_TELEMETRY_SOURCE_CONTEXT_SET = new Set(PM_TELEMETRY_SOURCE_CONTEXT_VALUES);
|
|
56
|
-
const STALE_VECTORIZATION_SUMMARY_LIMIT = 25;
|
|
57
|
-
const BRIEF_HEALTH_DETAIL_LIMIT = 8;
|
|
58
|
-
const HEALTH_WARNING_LIMIT = 100;
|
|
59
|
-
const TELEMETRY_QUEUE_RELATIVE_PATH = path.join("runtime", "telemetry", "events.jsonl");
|
|
60
|
-
const TELEMETRY_STATE_RELATIVE_PATH = path.join("runtime", "telemetry", "state.json");
|
|
61
|
-
const TELEMETRY_ENDPOINT_PROBE_TIMEOUT_MS = 2_500;
|
|
62
|
-
const TELEMETRY_QUEUE_HIGH_WATER_MARK = 500;
|
|
63
|
-
const TELEMETRY_QUEUE_HIGH_RETRY_THRESHOLD = TELEMETRY_MAX_QUEUE_ENTRY_ATTEMPTS - 3;
|
|
64
|
-
const TELEMETRY_SERVER_MAX_SCHEMA_VERSION_HEADERS = [
|
|
65
|
-
"x-pm-telemetry-max-schema-version",
|
|
66
|
-
"x-pm-telemetry-max-version",
|
|
67
|
-
];
|
|
68
|
-
/** Advisory warnings are surfaced for visibility but never flip overall health to not-ok. Telemetry is opt-out, non-critical observability: a queued/unreachable telemetry endpoint or corrupt local telemetry state is not a project-health failure and must not block agents that gate on `pm health` `ok`. History over-compaction-threshold warnings are likewise advisory maintenance hints — a deep stream is healthy, just a candidate for `pm history-compact`. Invalid legacy provenance remains advisory until an operator explicitly applies the privacy-safe history normalizer. */
|
|
69
|
-
function isAdvisoryHealthWarning(warning, requireMergeDrivers = false) {
|
|
70
|
-
return (warning.startsWith("telemetry_") ||
|
|
71
|
-
warning.startsWith("history_stream_over_compact_threshold:") ||
|
|
72
|
-
warning.startsWith("integrity_legacy_hierarchy_") ||
|
|
73
|
-
warning.startsWith("stale_in_progress_items:") ||
|
|
74
|
-
warning.startsWith("provenance_resolver_zero_success:") ||
|
|
75
|
-
warning.startsWith("provenance_value_domain_invalid:") ||
|
|
76
|
-
(!requireMergeDrivers &&
|
|
77
|
-
warning.startsWith("merge_driver_configuration_missing:")));
|
|
78
|
-
}
|
|
79
|
-
function warningCode(value) {
|
|
80
|
-
const normalized = value.trim();
|
|
81
|
-
const separator = normalized.indexOf(":");
|
|
82
|
-
if (separator === -1) {
|
|
83
|
-
return normalized;
|
|
84
|
-
}
|
|
85
|
-
return normalized.slice(0, separator);
|
|
86
|
-
}
|
|
87
|
-
function normalizeExtensionNameForMatch(value) {
|
|
88
|
-
return value.trim().toLowerCase();
|
|
89
|
-
}
|
|
90
|
-
function isExpectedUnmanagedExtension(name, directory) {
|
|
91
|
-
const normalizedName = normalizeExtensionNameForMatch(name);
|
|
92
|
-
const normalizedDirectory = normalizeExtensionNameForMatch(directory);
|
|
93
|
-
if (normalizedName.startsWith("builtin-")) {
|
|
94
|
-
return true;
|
|
95
|
-
}
|
|
96
|
-
return normalizedDirectory === "beads" || normalizedDirectory === "todos";
|
|
97
|
-
}
|
|
98
|
-
async function isDirectory(targetPath) {
|
|
99
|
-
try {
|
|
100
|
-
const stats = await fs.stat(targetPath);
|
|
101
|
-
return stats.isDirectory();
|
|
102
|
-
}
|
|
103
|
-
catch {
|
|
104
|
-
return false;
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
|
-
/** Enumerate item document IDs from every direct tracker folder, including unreadable documents and extension-defined folders unavailable to this process. */
|
|
108
|
-
async function listStoredItemDocumentIds(pmRoot) {
|
|
109
|
-
const directories = (await fs.readdir(pmRoot, { withFileTypes: true })).filter((entry) => entry.isDirectory());
|
|
110
|
-
const filesByDirectory = await Promise.all(directories.map((entry) => fs.readdir(path.join(pmRoot, entry.name), { withFileTypes: true })));
|
|
111
|
-
return new Set(filesByDirectory.flatMap((entries) => entries
|
|
112
|
-
.filter((entry) => entry.isFile())
|
|
113
|
-
.filter((entry) => ITEM_FILE_EXTENSIONS.some((extension) => entry.name.endsWith(extension)))
|
|
114
|
-
.map((entry) => path.parse(entry.name).name)));
|
|
115
|
-
}
|
|
116
|
-
async function inspectHistoryStream(streamPath, itemId, compactPolicy, liveItemIds) {
|
|
117
|
-
const warnings = await runActiveOnReadHooks({
|
|
118
|
-
path: streamPath,
|
|
119
|
-
scope: "project",
|
|
120
|
-
});
|
|
121
|
-
const needsClassification = itemId !== "_workspace" && !liveItemIds.has(itemId);
|
|
122
|
-
if (!compactPolicy.enabled && !needsClassification) {
|
|
123
|
-
return { warnings, overThreshold: false, classification: "live" };
|
|
124
|
-
}
|
|
125
|
-
let raw;
|
|
126
|
-
try {
|
|
127
|
-
raw = await fs.readFile(streamPath, "utf8");
|
|
128
|
-
}
|
|
129
|
-
catch {
|
|
130
|
-
return {
|
|
131
|
-
warnings,
|
|
132
|
-
overThreshold: false,
|
|
133
|
-
classification: "unreadable",
|
|
134
|
-
};
|
|
135
|
-
}
|
|
136
|
-
let classification = "live";
|
|
137
|
-
if (needsClassification) {
|
|
138
|
-
const lastLine = raw
|
|
139
|
-
.split(/\r?\n/)
|
|
140
|
-
.map((line) => line.trim())
|
|
141
|
-
.filter(Boolean)
|
|
142
|
-
.at(-1);
|
|
143
|
-
try {
|
|
144
|
-
const lastEntry = JSON.parse(lastLine ?? "{}");
|
|
145
|
-
classification = lastEntry.op === "delete" ? "tombstone" : "orphaned";
|
|
146
|
-
}
|
|
147
|
-
catch {
|
|
148
|
-
classification = "orphaned";
|
|
149
|
-
}
|
|
150
|
-
}
|
|
151
|
-
const entryCount = compactPolicy.enabled
|
|
152
|
-
? raw.split(/\r?\n/).filter((line) => line.trim().length > 0).length
|
|
153
|
-
: 0;
|
|
154
|
-
return {
|
|
155
|
-
warnings,
|
|
156
|
-
overThreshold: compactPolicy.enabled && entryCount > compactPolicy.max_entries,
|
|
157
|
-
classification,
|
|
158
|
-
};
|
|
159
|
-
}
|
|
160
|
-
async function countHistoryStreams(pmRoot, compactPolicy, liveItemIds) {
|
|
161
|
-
const historyDir = path.join(pmRoot, "history");
|
|
162
|
-
if (!(await isDirectory(historyDir))) {
|
|
163
|
-
return {
|
|
164
|
-
count: 0,
|
|
165
|
-
warnings: [],
|
|
166
|
-
over_threshold: [],
|
|
167
|
-
max_entries: null,
|
|
168
|
-
tombstones: [],
|
|
169
|
-
orphaned: [],
|
|
170
|
-
};
|
|
171
|
-
}
|
|
172
|
-
const historyFiles = (await fs.readdir(historyDir))
|
|
173
|
-
.filter((entry) => entry.endsWith(".jsonl"))
|
|
174
|
-
.sort((left, right) => left.localeCompare(right));
|
|
175
|
-
const policyActive = compactPolicy.enabled;
|
|
176
|
-
const maxEntries = policyActive ? compactPolicy.max_entries : null;
|
|
177
|
-
const warnings = [];
|
|
178
|
-
const overThreshold = [];
|
|
179
|
-
const tombstones = [];
|
|
180
|
-
const orphaned = [];
|
|
181
|
-
for (const fileName of historyFiles) {
|
|
182
|
-
const streamPath = path.join(historyDir, fileName);
|
|
183
|
-
const itemId = fileName.slice(0, -".jsonl".length);
|
|
184
|
-
const inspection = await inspectHistoryStream(streamPath, itemId, compactPolicy, liveItemIds);
|
|
185
|
-
warnings.push(...inspection.warnings);
|
|
186
|
-
if (inspection.classification === "tombstone")
|
|
187
|
-
tombstones.push(itemId);
|
|
188
|
-
if (inspection.classification === "orphaned")
|
|
189
|
-
orphaned.push(itemId);
|
|
190
|
-
if (inspection.overThreshold)
|
|
191
|
-
overThreshold.push(itemId);
|
|
192
|
-
}
|
|
193
|
-
return {
|
|
194
|
-
count: historyFiles.length,
|
|
195
|
-
warnings: [
|
|
196
|
-
...warnings,
|
|
197
|
-
...overThreshold.map((id) => `history_stream_over_compact_threshold:${id}`),
|
|
198
|
-
...orphaned.map((id) => `history_orphaned_stream:${id}`),
|
|
199
|
-
],
|
|
200
|
-
over_threshold: overThreshold,
|
|
201
|
-
max_entries: maxEntries,
|
|
202
|
-
tombstones,
|
|
203
|
-
orphaned,
|
|
204
|
-
};
|
|
205
|
-
}
|
|
206
|
-
function normalizeRelativePath(pmRoot, targetPath) {
|
|
207
|
-
return path.relative(pmRoot, targetPath).replaceAll("\\", "/");
|
|
208
|
-
}
|
|
209
|
-
async function listItemDocumentPaths(pmRoot, typeToFolder) {
|
|
210
|
-
const folders = [...new Set(Object.values(typeToFolder))].sort((left, right) => left.localeCompare(right));
|
|
211
|
-
const itemPaths = [];
|
|
212
|
-
for (const folder of folders) {
|
|
213
|
-
const directoryPath = path.join(pmRoot, folder);
|
|
214
|
-
let entries = [];
|
|
215
|
-
try {
|
|
216
|
-
entries = await fs.readdir(directoryPath);
|
|
217
|
-
}
|
|
218
|
-
catch (error) {
|
|
219
|
-
if (typeof error === "object" &&
|
|
220
|
-
error !== null &&
|
|
221
|
-
"code" in error &&
|
|
222
|
-
isFileMissingError(error)) {
|
|
223
|
-
continue;
|
|
224
|
-
}
|
|
225
|
-
continue;
|
|
226
|
-
}
|
|
227
|
-
for (const entry of entries) {
|
|
228
|
-
if (!ITEM_FILE_EXTENSIONS.some((extension) => entry.toLowerCase().endsWith(extension))) {
|
|
229
|
-
continue;
|
|
230
|
-
}
|
|
231
|
-
itemPaths.push(path.join(directoryPath, entry));
|
|
232
|
-
}
|
|
233
|
-
}
|
|
234
|
-
itemPaths.sort((left, right) => normalizeRelativePath(pmRoot, left).localeCompare(normalizeRelativePath(pmRoot, right)));
|
|
235
|
-
return itemPaths;
|
|
236
|
-
}
|
|
237
|
-
function shouldReportHistoryDirectoryUnreadable(error) {
|
|
238
|
-
return !(typeof error === "object" &&
|
|
239
|
-
error !== null &&
|
|
240
|
-
"code" in error &&
|
|
241
|
-
isFileMissingError(error));
|
|
242
|
-
}
|
|
243
|
-
async function scanItemIntegrity(pmRoot, typeToFolder, schema) {
|
|
244
|
-
const paths = await listItemDocumentPaths(pmRoot, typeToFolder);
|
|
245
|
-
const unreadable = [];
|
|
246
|
-
const conflictMarkers = [];
|
|
247
|
-
const parseFailures = [];
|
|
248
|
-
const formatVersions = [];
|
|
249
|
-
const extensionFieldNames = collectRegisteredItemFieldNames(getActiveExtensionRegistrations());
|
|
250
|
-
for (const itemPath of paths) {
|
|
251
|
-
const relativePath = normalizeRelativePath(pmRoot, itemPath);
|
|
252
|
-
let raw;
|
|
253
|
-
try {
|
|
254
|
-
raw = await fs.readFile(itemPath, "utf8");
|
|
255
|
-
}
|
|
256
|
-
catch {
|
|
257
|
-
unreadable.push(relativePath);
|
|
258
|
-
continue;
|
|
259
|
-
}
|
|
260
|
-
const conflictMarker = findFirstMergeConflictMarker(raw);
|
|
261
|
-
if (conflictMarker) {
|
|
262
|
-
conflictMarkers.push({ path: relativePath, ...conflictMarker });
|
|
263
|
-
continue;
|
|
264
|
-
}
|
|
265
|
-
try {
|
|
266
|
-
const parsed = parseItemDocument(raw, {
|
|
267
|
-
format: getItemFormatFromPath(itemPath),
|
|
268
|
-
schema,
|
|
269
|
-
extensionFieldNames,
|
|
270
|
-
});
|
|
271
|
-
formatVersions.push({
|
|
272
|
-
ref: relativePath,
|
|
273
|
-
version: effectiveItemFormatVersion(parsed.metadata),
|
|
274
|
-
});
|
|
275
|
-
}
|
|
276
|
-
catch {
|
|
277
|
-
parseFailures.push(relativePath);
|
|
278
|
-
}
|
|
279
|
-
}
|
|
280
|
-
return { paths, unreadable, conflictMarkers, parseFailures, formatVersions };
|
|
281
|
-
}
|
|
282
|
-
async function scanHistoryIntegrity(pmRoot) {
|
|
283
|
-
const historyDir = path.join(pmRoot, "history");
|
|
284
|
-
const unreadable = [];
|
|
285
|
-
const conflictMarkers = [];
|
|
286
|
-
const invalidJson = [];
|
|
287
|
-
const mergeReceiptReferences = [];
|
|
288
|
-
const mergeReceiptDispositions = [];
|
|
289
|
-
let files = [];
|
|
290
|
-
try {
|
|
291
|
-
files = (await fs.readdir(historyDir))
|
|
292
|
-
.filter((entry) => entry.endsWith(".jsonl"))
|
|
293
|
-
.sort((left, right) => left.localeCompare(right));
|
|
294
|
-
}
|
|
295
|
-
catch (error) {
|
|
296
|
-
/* c8 ignore start -- ENOENT/non-ENOENT differentiation requires filesystem fault injection */
|
|
297
|
-
if (shouldReportHistoryDirectoryUnreadable(error))
|
|
298
|
-
unreadable.push("history");
|
|
299
|
-
/* c8 ignore stop */
|
|
300
|
-
}
|
|
301
|
-
for (const fileName of files) {
|
|
302
|
-
const itemId = fileName.slice(0, -".jsonl".length);
|
|
303
|
-
let raw;
|
|
304
|
-
try {
|
|
305
|
-
raw = await fs.readFile(path.join(historyDir, fileName), "utf8");
|
|
306
|
-
}
|
|
307
|
-
catch {
|
|
308
|
-
unreadable.push(itemId);
|
|
309
|
-
continue;
|
|
310
|
-
}
|
|
311
|
-
const conflictMarker = findFirstMergeConflictMarker(raw);
|
|
312
|
-
if (conflictMarker) {
|
|
313
|
-
conflictMarkers.push({ id: itemId, ...conflictMarker });
|
|
314
|
-
continue;
|
|
315
|
-
}
|
|
316
|
-
raw.split(/\r?\n/).forEach((line, index) => {
|
|
317
|
-
if (!line.trim())
|
|
318
|
-
return;
|
|
319
|
-
try {
|
|
320
|
-
const parsed = JSON.parse(line);
|
|
321
|
-
mergeReceiptReferences.push(...extractHistoryMergeReceiptReferences(parsed, itemId).map((reference) => ({
|
|
322
|
-
itemId,
|
|
323
|
-
line: index + 1,
|
|
324
|
-
...reference,
|
|
325
|
-
})));
|
|
326
|
-
mergeReceiptDispositions.push(...extractHistoryMergeReceiptDispositions(parsed, itemId, index + 1));
|
|
327
|
-
}
|
|
328
|
-
catch {
|
|
329
|
-
invalidJson.push({ id: itemId, line: index + 1 });
|
|
330
|
-
}
|
|
331
|
-
});
|
|
332
|
-
}
|
|
333
|
-
return {
|
|
334
|
-
files,
|
|
335
|
-
unreadable,
|
|
336
|
-
conflictMarkers,
|
|
337
|
-
invalidJson,
|
|
338
|
-
mergeReceiptReferences,
|
|
339
|
-
mergeReceiptDispositions,
|
|
340
|
-
};
|
|
341
|
-
}
|
|
342
|
-
function buildHierarchyIntegrityWarnings(analysis) {
|
|
343
|
-
return [
|
|
344
|
-
...analysis.cycles.map((cycle) => cycle.legacy_terminal
|
|
345
|
-
? `integrity_legacy_hierarchy_cycle:${cycle.item_ids.join(",")}`
|
|
346
|
-
: `integrity_hierarchy_cycle:${cycle.item_ids.join(",")}`),
|
|
347
|
-
...analysis.cardinality_violations.map((finding) => finding.legacy_terminal
|
|
348
|
-
? `integrity_legacy_hierarchy_cardinality:${finding.child_id}`
|
|
349
|
-
: `integrity_hierarchy_cardinality:${finding.child_id}`),
|
|
350
|
-
...analysis.divergences.map((finding) => finding.legacy_terminal
|
|
351
|
-
? `integrity_legacy_hierarchy_divergence:${finding.child_id}`
|
|
352
|
-
: `integrity_hierarchy_divergence:${finding.child_id}`),
|
|
353
|
-
];
|
|
354
|
-
}
|
|
355
|
-
function buildMergeReceiptEvidenceWarnings(params) {
|
|
356
|
-
const warnings = [];
|
|
357
|
-
if (params.invalidEvidenceCount > 0) {
|
|
358
|
-
warnings.push(`merge_receipt_evidence_invalid:${params.invalidEvidenceCount}`);
|
|
359
|
-
}
|
|
360
|
-
if (params.missingHistoryReferenceCount > 0) {
|
|
361
|
-
warnings.push(`merge_receipt_history_reference_missing:${params.missingHistoryReferenceCount}`);
|
|
362
|
-
}
|
|
363
|
-
return warnings;
|
|
364
|
-
}
|
|
365
|
-
async function buildIntegrityCheck(pmRoot, typeToFolder, schema, requireMergeDrivers, items) {
|
|
366
|
-
const itemScan = await scanItemIntegrity(pmRoot, typeToFolder, schema);
|
|
367
|
-
const historyScan = await scanHistoryIntegrity(pmRoot);
|
|
368
|
-
const formatVersionScan = scanItemFormatVersions(itemScan.formatVersions);
|
|
369
|
-
const statusRegistry = resolveRuntimeStatusRegistry(schema);
|
|
370
|
-
const hierarchyIntegrity = analyzeHierarchyIntegrity(items, (status) => isTerminalStatus(status, statusRegistry), resolveWorkspaceRelationshipKindRegistry());
|
|
371
|
-
const trackedRuntimeCache = await scanTrackedRuntimeCache(pmRoot);
|
|
372
|
-
const gitWorkspaceRoot = await findGitWorkspaceRoot(pmRoot);
|
|
373
|
-
const mergeDriverAudit = gitWorkspaceRoot === null
|
|
374
|
-
? null
|
|
375
|
-
: await auditMergeDriverConfiguration(gitWorkspaceRoot);
|
|
376
|
-
const mergeReceiptEvidence = await inspectMergeReceiptEvidence(gitWorkspaceRoot ?? pmRoot, {
|
|
377
|
-
includeReconciled: true,
|
|
378
|
-
includeLossless: true,
|
|
379
|
-
pmRoot,
|
|
380
|
-
});
|
|
381
|
-
const availableMergeReceiptIds = new Set(mergeReceiptEvidence.receipts.map((receipt) => receipt.id));
|
|
382
|
-
const historyReceiptClassification = classifyHistoryMergeReceiptReferences(historyScan.mergeReceiptReferences, availableMergeReceiptIds, historyScan.mergeReceiptDispositions);
|
|
383
|
-
const missingMergeReceiptReferences = historyReceiptClassification.missing;
|
|
384
|
-
const pendingMergeReceipts = mergeReceiptEvidence.receipts.filter((receipt) => receipt.state === "pending");
|
|
385
|
-
const { pendingDecisions: pendingMergeDecisions, lossless: losslessMergeReceipts, } = partitionMergeReceipts(pendingMergeReceipts);
|
|
386
|
-
const mergeDriverInstallationMissing = mergeDriverAudit?.status === "missing" &&
|
|
387
|
-
mergeDriverAudit.missing_keys.length === 5 &&
|
|
388
|
-
mergeDriverAudit.drifted_keys.length === 0;
|
|
389
|
-
const warnings = [
|
|
390
|
-
...itemScan.unreadable.map((entry) => `integrity_item_unreadable:${entry}`),
|
|
391
|
-
...itemScan.conflictMarkers.map((entry) => `integrity_item_conflict_marker:${entry.path}:L${entry.line}`),
|
|
392
|
-
...itemScan.parseFailures.map((entry) => `integrity_item_parse_failed:${entry}`),
|
|
393
|
-
...historyScan.unreadable.map((entry) => `integrity_history_unreadable:${entry}`),
|
|
394
|
-
...historyScan.conflictMarkers.map((entry) => `integrity_history_conflict_marker:${entry.id}:L${entry.line}`),
|
|
395
|
-
...historyScan.invalidJson.map((entry) => `integrity_history_invalid_json:${entry.id}:L${entry.line}`),
|
|
396
|
-
/* c8 ignore start -- outdated-version items are unreachable until CURRENT_ITEM_FORMAT_VERSION advances past the baseline (an effective version below 1 cannot occur); the per-item mapping is covered in item-format-version.spec, and the ahead path below is covered by health-command.spec */
|
|
397
|
-
...formatVersionScan.outdated.map((entry) => `integrity_item_outdated_format_version:${entry}`),
|
|
398
|
-
/* c8 ignore stop */
|
|
399
|
-
...formatVersionScan.ahead.map((entry) => `integrity_item_ahead_format_version:${entry}`),
|
|
400
|
-
...buildHierarchyIntegrityWarnings(hierarchyIntegrity),
|
|
401
|
-
...(trackedRuntimeCache.tracked_path_count > 0
|
|
402
|
-
? [
|
|
403
|
-
`tracked_runtime_cache_files:${trackedRuntimeCache.tracked_path_count}`,
|
|
404
|
-
]
|
|
405
|
-
: []),
|
|
406
|
-
...(mergeDriverAudit !== null && mergeDriverAudit.status !== "ok"
|
|
407
|
-
? [
|
|
408
|
-
`merge_driver_configuration_${mergeDriverInstallationMissing ? "missing" : "drift"}:${mergeDriverAudit.missing_keys.length + mergeDriverAudit.drifted_keys.length}`,
|
|
409
|
-
]
|
|
410
|
-
: []),
|
|
411
|
-
...(pendingMergeDecisions.length > 0
|
|
412
|
-
? [`merge_decisions_unreviewed:${pendingMergeDecisions.length}`]
|
|
413
|
-
: []),
|
|
414
|
-
...(losslessMergeReceipts.length > 0
|
|
415
|
-
? [`merge_receipts_pending:${losslessMergeReceipts.length}`]
|
|
416
|
-
: []),
|
|
417
|
-
...buildMergeReceiptEvidenceWarnings({
|
|
418
|
-
invalidEvidenceCount: mergeReceiptEvidence.invalid_evidence_count,
|
|
419
|
-
missingHistoryReferenceCount: missingMergeReceiptReferences.length,
|
|
420
|
-
}),
|
|
421
|
-
];
|
|
422
|
-
const normalizedWarnings = [...new Set(warnings)].sort((left, right) => left.localeCompare(right));
|
|
423
|
-
const actionableWarnings = normalizedWarnings.filter((warning) => !warning.startsWith("integrity_legacy_hierarchy_"));
|
|
424
|
-
return {
|
|
425
|
-
check: {
|
|
426
|
-
name: "integrity",
|
|
427
|
-
status: actionableWarnings.length === 0 ? "ok" : "warn",
|
|
428
|
-
ok: actionableWarnings.length === 0,
|
|
429
|
-
details: {
|
|
430
|
-
checked_item_files: itemScan.paths.length,
|
|
431
|
-
checked_history_streams: historyScan.files.length,
|
|
432
|
-
counts: {
|
|
433
|
-
item_unreadable: itemScan.unreadable.length,
|
|
434
|
-
item_conflict_markers: itemScan.conflictMarkers.length,
|
|
435
|
-
item_parse_failures: itemScan.parseFailures.length,
|
|
436
|
-
history_unreadable: historyScan.unreadable.length,
|
|
437
|
-
history_conflict_markers: historyScan.conflictMarkers.length,
|
|
438
|
-
history_invalid_json: historyScan.invalidJson.length,
|
|
439
|
-
item_outdated_format_version: formatVersionScan.outdated.length,
|
|
440
|
-
item_ahead_format_version: formatVersionScan.ahead.length,
|
|
441
|
-
hierarchy_cycles: hierarchyIntegrity.cycles.length,
|
|
442
|
-
hierarchy_cardinality_violations: hierarchyIntegrity.cardinality_violations.length,
|
|
443
|
-
hierarchy_parent_divergences: hierarchyIntegrity.divergences.length,
|
|
444
|
-
tracked_runtime_cache_files: trackedRuntimeCache.tracked_path_count,
|
|
445
|
-
merge_driver_configuration: mergeDriverAudit === null || mergeDriverAudit.status === "ok"
|
|
446
|
-
? 0
|
|
447
|
-
: mergeDriverAudit.missing_keys.length +
|
|
448
|
-
mergeDriverAudit.drifted_keys.length,
|
|
449
|
-
pending_merge_decisions: pendingMergeDecisions.length,
|
|
450
|
-
lossless_merge_receipts: losslessMergeReceipts.length,
|
|
451
|
-
invalid_merge_receipt_evidence: mergeReceiptEvidence.invalid_evidence_count,
|
|
452
|
-
missing_merge_receipt_history_references: missingMergeReceiptReferences.length,
|
|
453
|
-
accepted_legacy_merge_receipt_references: historyReceiptClassification.acceptedLegacyCount,
|
|
454
|
-
accepted_missing_merge_receipt_dispositions: historyReceiptClassification.acceptedDispositionCount,
|
|
455
|
-
},
|
|
456
|
-
item_unreadable: itemScan.unreadable,
|
|
457
|
-
item_conflict_markers: itemScan.conflictMarkers,
|
|
458
|
-
item_parse_failures: itemScan.parseFailures,
|
|
459
|
-
item_outdated_format_version: formatVersionScan.outdated,
|
|
460
|
-
item_ahead_format_version: formatVersionScan.ahead,
|
|
461
|
-
hierarchy_integrity: {
|
|
462
|
-
...hierarchyIntegrity,
|
|
463
|
-
relations: summarizeRecordList(hierarchyIntegrity.relations, BRIEF_HEALTH_DETAIL_LIMIT),
|
|
464
|
-
},
|
|
465
|
-
history_unreadable: historyScan.unreadable,
|
|
466
|
-
history_conflict_markers: historyScan.conflictMarkers,
|
|
467
|
-
history_invalid_json: historyScan.invalidJson,
|
|
468
|
-
tracked_runtime_cache: {
|
|
469
|
-
tracker_relative_root: trackedRuntimeCache.tracker_relative_root,
|
|
470
|
-
tracked_paths: trackedRuntimeCache.tracked_paths,
|
|
471
|
-
tracked_path_count: trackedRuntimeCache.tracked_path_count,
|
|
472
|
-
remediation_command: trackedRuntimeCache.remediation_command,
|
|
473
|
-
},
|
|
474
|
-
merge_driver_configuration: mergeDriverAudit === null
|
|
475
|
-
? null
|
|
476
|
-
: {
|
|
477
|
-
...mergeDriverAudit,
|
|
478
|
-
required: requireMergeDrivers,
|
|
479
|
-
},
|
|
480
|
-
pending_merge_decision_items: [
|
|
481
|
-
...new Set(pendingMergeDecisions.map((receipt) => receipt.item_id)),
|
|
482
|
-
].sort((left, right) => left.localeCompare(right)),
|
|
483
|
-
lossless_merge_receipt_items: [
|
|
484
|
-
...new Set(losslessMergeReceipts.map((receipt) => receipt.item_id)),
|
|
485
|
-
].sort((left, right) => left.localeCompare(right)),
|
|
486
|
-
invalid_merge_receipt_evidence_details: mergeReceiptEvidence.invalid_evidence,
|
|
487
|
-
invalid_merge_receipt_evidence_details_truncated: mergeReceiptEvidence.invalid_evidence_truncated,
|
|
488
|
-
missing_merge_receipt_history_reference_details: missingMergeReceiptReferences.slice(0, HEALTH_WARNING_LIMIT),
|
|
489
|
-
missing_merge_receipt_history_reference_details_truncated: missingMergeReceiptReferences.length > HEALTH_WARNING_LIMIT,
|
|
490
|
-
},
|
|
491
|
-
},
|
|
492
|
-
warnings: normalizedWarnings,
|
|
493
|
-
gitWorkspaceRoot,
|
|
494
|
-
pendingMergeReceipts,
|
|
495
|
-
};
|
|
496
|
-
}
|
|
497
|
-
/* c8 ignore start -- activate export shape variants are exercised through integration load tests */
|
|
498
|
-
function hasActivateExport(moduleRecord) {
|
|
499
|
-
if (typeof moduleRecord.activate === "function") {
|
|
500
|
-
return true;
|
|
501
|
-
}
|
|
502
|
-
const defaultExport = moduleRecord.default;
|
|
503
|
-
if (typeof defaultExport !== "object" || defaultExport === null) {
|
|
504
|
-
return false;
|
|
505
|
-
}
|
|
506
|
-
return (typeof defaultExport.activate === "function");
|
|
507
|
-
}
|
|
508
|
-
/* c8 ignore stop */
|
|
509
|
-
function summarizeLoadedExtension(extension) {
|
|
510
|
-
const summary = {
|
|
511
|
-
layer: extension.layer,
|
|
512
|
-
directory: extension.directory,
|
|
513
|
-
manifest_path: extension.manifest_path,
|
|
514
|
-
name: extension.name,
|
|
515
|
-
version: extension.version,
|
|
516
|
-
entry: extension.entry,
|
|
517
|
-
priority: extension.priority,
|
|
518
|
-
entry_path: extension.entry_path,
|
|
519
|
-
has_activate: hasActivateExport(extension.module),
|
|
520
|
-
};
|
|
521
|
-
/* c8 ignore start -- capability list optionality is exercised by extension load integration suites */
|
|
522
|
-
if (Array.isArray(extension.capabilities)) {
|
|
523
|
-
summary.capabilities = [...extension.capabilities];
|
|
524
|
-
}
|
|
525
|
-
/* c8 ignore stop */
|
|
526
|
-
return summary;
|
|
527
|
-
}
|
|
528
|
-
function resolveMigrationId(definition, fallbackIndex) {
|
|
529
|
-
const explicitId = toNonEmptyStringOrUndefined(definition.id);
|
|
530
|
-
if (explicitId) {
|
|
531
|
-
return explicitId;
|
|
532
|
-
}
|
|
533
|
-
return `migration-${String(fallbackIndex + 1).padStart(3, "0")}`;
|
|
534
|
-
}
|
|
535
|
-
function resolveMigrationStatus(definition) {
|
|
536
|
-
const rawStatus = toNonEmptyStringOrUndefined(definition.status);
|
|
537
|
-
const normalized = rawStatus?.toLowerCase();
|
|
538
|
-
if (normalized === "failed") {
|
|
539
|
-
return "failed";
|
|
540
|
-
}
|
|
541
|
-
if (normalized === "applied") {
|
|
542
|
-
return "applied";
|
|
543
|
-
}
|
|
544
|
-
return "pending";
|
|
545
|
-
}
|
|
546
|
-
function resolveMigrationFailureReason(definition) {
|
|
547
|
-
return (toNonEmptyStringOrUndefined(definition.reason) ??
|
|
548
|
-
toNonEmptyStringOrUndefined(definition.error) ??
|
|
549
|
-
toNonEmptyStringOrUndefined(definition.message));
|
|
550
|
-
}
|
|
551
|
-
/* c8 ignore start -- comparator tie-break branches are deterministic ordering glue exercised via migration integration tests */
|
|
552
|
-
function compareMigrationEntries(left, right) {
|
|
553
|
-
const byLayer = (left.layer ?? "").localeCompare(right.layer ?? "");
|
|
554
|
-
if (byLayer !== 0) {
|
|
555
|
-
return byLayer;
|
|
556
|
-
}
|
|
557
|
-
const byName = (left.name ?? "").localeCompare(right.name ?? "");
|
|
558
|
-
if (byName !== 0) {
|
|
559
|
-
return byName;
|
|
560
|
-
}
|
|
561
|
-
return (left.id ?? "").localeCompare(right.id ?? "");
|
|
562
|
-
}
|
|
563
|
-
/* c8 ignore stop */
|
|
564
|
-
function summarizeMigrationStatuses(migrations) {
|
|
565
|
-
const applied = [];
|
|
566
|
-
const pending = [];
|
|
567
|
-
const failed = [];
|
|
568
|
-
migrations.forEach((migration, index) => {
|
|
569
|
-
const id = resolveMigrationId(migration.definition, index);
|
|
570
|
-
const status = resolveMigrationStatus(migration.definition);
|
|
571
|
-
if (status === "applied") {
|
|
572
|
-
applied.push({
|
|
573
|
-
layer: migration.layer,
|
|
574
|
-
name: migration.name,
|
|
575
|
-
id,
|
|
576
|
-
status,
|
|
577
|
-
});
|
|
578
|
-
return;
|
|
579
|
-
}
|
|
580
|
-
if (status === "failed") {
|
|
581
|
-
failed.push({
|
|
582
|
-
layer: migration.layer,
|
|
583
|
-
name: migration.name,
|
|
584
|
-
id,
|
|
585
|
-
status,
|
|
586
|
-
reason: resolveMigrationFailureReason(migration.definition),
|
|
587
|
-
});
|
|
588
|
-
return;
|
|
589
|
-
}
|
|
590
|
-
pending.push({
|
|
591
|
-
layer: migration.layer,
|
|
592
|
-
name: migration.name,
|
|
593
|
-
id,
|
|
594
|
-
status,
|
|
595
|
-
});
|
|
596
|
-
});
|
|
597
|
-
applied.sort(compareMigrationEntries);
|
|
598
|
-
pending.sort(compareMigrationEntries);
|
|
599
|
-
failed.sort(compareMigrationEntries);
|
|
600
|
-
const warnings = [
|
|
601
|
-
...failed.map((entry) => `extension_migration_failed:${entry.layer}:${entry.name}:${entry.id}`),
|
|
602
|
-
...pending.map((entry) => `extension_migration_pending:${entry.layer}:${entry.name}:${entry.id}`),
|
|
603
|
-
];
|
|
604
|
-
return {
|
|
605
|
-
summary: {
|
|
606
|
-
applied,
|
|
607
|
-
pending,
|
|
608
|
-
failed,
|
|
609
|
-
applied_count: applied.length,
|
|
610
|
-
pending_count: pending.length,
|
|
611
|
-
failed_count: failed.length,
|
|
612
|
-
},
|
|
613
|
-
warnings,
|
|
614
|
-
};
|
|
615
|
-
}
|
|
616
|
-
function buildExtensionHealthTriageSummary(warnings, loadFailureCount, activationFailureCount, migrationStatus, managedStateWarningCount, managedExtensionEntriesCount, unmanagedLoadedExtensions, unmanagedExpectedExtensions, unmanagedActionRequiredExtensions) {
|
|
617
|
-
const normalizedWarnings = [...new Set(warnings)].sort((left, right) => left.localeCompare(right));
|
|
618
|
-
const warningCodes = [
|
|
619
|
-
...new Set(normalizedWarnings.map((value) => warningCode(value))),
|
|
620
|
-
].sort((left, right) => left.localeCompare(right));
|
|
621
|
-
const unknownCapabilityCount = normalizedWarnings.filter((warning) => warning.startsWith("extension_capability_unknown:")).length;
|
|
622
|
-
const updateHealthPartial = unmanagedActionRequiredExtensions.length > 0;
|
|
623
|
-
const updateHealthCoverage = updateHealthPartial ? "partial" : "full";
|
|
624
|
-
const remediation = [];
|
|
625
|
-
const registrationCollisionRemediation = buildRegistrationCollisionRemediation(normalizedWarnings, {
|
|
626
|
-
deactivate: "pm extension --deactivate <name> --project/--global",
|
|
627
|
-
doctor: "pm extension --doctor --project/--global --detail deep --trace",
|
|
628
|
-
});
|
|
629
|
-
if (registrationCollisionRemediation) {
|
|
630
|
-
remediation.push(registrationCollisionRemediation);
|
|
631
|
-
}
|
|
632
|
-
if (loadFailureCount > 0) {
|
|
633
|
-
remediation.push("Run pm extension --explore --project and pm extension --explore --global to inspect load failures.");
|
|
634
|
-
}
|
|
635
|
-
if (activationFailureCount > 0) {
|
|
636
|
-
remediation.push("Review checks[name=extensions].details.activation.failed in pm health --json for activation error details.");
|
|
637
|
-
}
|
|
638
|
-
if (migrationStatus.failed_count > 0 || migrationStatus.pending_count > 0) {
|
|
639
|
-
remediation.push("Resolve pending/failed extension migrations before write commands; use --force only when policy allows.");
|
|
640
|
-
}
|
|
641
|
-
if (managedStateWarningCount > 0) {
|
|
642
|
-
remediation.push("Run pm extension --manage --project and pm extension --manage --global to refresh managed-state diagnostics.");
|
|
643
|
-
}
|
|
644
|
-
if (unknownCapabilityCount > 0) {
|
|
645
|
-
remediation.push(`Unknown extension capabilities detected. Allowed capabilities: ${KNOWN_EXTENSION_CAPABILITIES.join(", ")}. ` +
|
|
646
|
-
"Review extension_capability_unknown warning details for suggested replacements.");
|
|
647
|
-
}
|
|
648
|
-
if (normalizedWarnings.some((warning) => warning.startsWith("extension_capability_legacy_alias:"))) {
|
|
649
|
-
remediation.push("Legacy extension capability aliases were auto-remapped to canonical capabilities. " +
|
|
650
|
-
"Update manifests to canonical names (migration/validation -> schema).");
|
|
651
|
-
}
|
|
652
|
-
if (normalizedWarnings.some((warning) => warning.startsWith("extension_command_definition_legacy_handler_alias:"))) {
|
|
653
|
-
remediation.push("Extension command definitions using legacy handler were auto-remapped. " +
|
|
654
|
-
"Update command definitions to use run: (context) => ... for forward compatibility.");
|
|
655
|
-
}
|
|
656
|
-
if (updateHealthPartial) {
|
|
657
|
-
remediation.push("Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via pm extension --manage --project/--global --fix-managed-state, pm extension --adopt-all --project/--global, or pm extension --adopt <name>.");
|
|
658
|
-
}
|
|
659
|
-
else if (unmanagedLoadedExtensions.length > 0) {
|
|
660
|
-
remediation.push("Loaded unmanaged extensions are currently treated as informational. Use pm extension --manage --project/--global --fix-managed-state to adopt them for update checks.");
|
|
661
|
-
}
|
|
662
|
-
if (remediation.length === 0) {
|
|
663
|
-
remediation.push("No immediate action required. Re-run pm health after extension configuration changes.");
|
|
664
|
-
}
|
|
665
|
-
return {
|
|
666
|
-
status: normalizedWarnings.length === 0 ? "ok" : "warn",
|
|
667
|
-
warning_count: normalizedWarnings.length,
|
|
668
|
-
warning_codes: warningCodes,
|
|
669
|
-
load_failure_count: loadFailureCount,
|
|
670
|
-
activation_failure_count: activationFailureCount,
|
|
671
|
-
migration_failed_count: migrationStatus.failed_count,
|
|
672
|
-
migration_pending_count: migrationStatus.pending_count,
|
|
673
|
-
managed_state_warning_count: managedStateWarningCount,
|
|
674
|
-
managed_extension_entries_count: managedExtensionEntriesCount,
|
|
675
|
-
unmanaged_loaded_extension_count: unmanagedLoadedExtensions.length,
|
|
676
|
-
unmanaged_loaded_extensions: unmanagedLoadedExtensions,
|
|
677
|
-
unmanaged_expected_extension_count: unmanagedExpectedExtensions.length,
|
|
678
|
-
unmanaged_expected_extensions: unmanagedExpectedExtensions,
|
|
679
|
-
unmanaged_action_required_extension_count: unmanagedActionRequiredExtensions.length,
|
|
680
|
-
unmanaged_action_required_extensions: unmanagedActionRequiredExtensions,
|
|
681
|
-
update_health_coverage: updateHealthCoverage,
|
|
682
|
-
update_health_partial: updateHealthPartial,
|
|
683
|
-
unknown_capability_count: unknownCapabilityCount,
|
|
684
|
-
top_warnings: normalizedWarnings.slice(0, 8),
|
|
685
|
-
remediation,
|
|
686
|
-
};
|
|
687
|
-
}
|
|
688
|
-
async function buildExtensionCheck(pmRoot, settings, noExtensionsFlag) {
|
|
689
|
-
const authorManifest = await inspectExtensionAuthorManifest(resolveWorkspaceRoot(pmRoot));
|
|
690
|
-
const loadResult = await loadExtensions({
|
|
691
|
-
pmRoot,
|
|
692
|
-
settings,
|
|
693
|
-
cwd: process.cwd(),
|
|
694
|
-
noExtensions: noExtensionsFlag,
|
|
695
|
-
});
|
|
696
|
-
const loadedSummaries = loadResult.loaded.map((extension) => summarizeLoadedExtension(extension));
|
|
697
|
-
const hostVersionCensus = await scanExtensionHostVersions(loadResult.loaded, resolveWorkspaceRoot(pmRoot));
|
|
698
|
-
const activationResult = await activateExtensions({
|
|
699
|
-
...loadResult,
|
|
700
|
-
loaded: loadResult.loaded,
|
|
701
|
-
});
|
|
702
|
-
const [projectManagedState, globalManagedState] = await Promise.all([
|
|
703
|
-
readManagedExtensionState(loadResult.roots.project),
|
|
704
|
-
readManagedExtensionState(loadResult.roots.global),
|
|
705
|
-
]);
|
|
706
|
-
await applyStoredExtensionMigrationState(pmRoot, activationResult.registrations.migrations);
|
|
707
|
-
const migrationStatus = summarizeMigrationStatuses(activationResult.registrations.migrations);
|
|
708
|
-
const activationDetails = {
|
|
709
|
-
failed: activationResult.failed,
|
|
710
|
-
warnings: activationResult.warnings,
|
|
711
|
-
hook_counts: activationResult.hook_counts,
|
|
712
|
-
command_override_count: activationResult.command_override_count,
|
|
713
|
-
command_handler_count: activationResult.command_handler_count,
|
|
714
|
-
parser_override_count: activationResult.parser_override_count,
|
|
715
|
-
preflight_override_count: activationResult.preflight_override_count,
|
|
716
|
-
service_override_count: activationResult.service_override_count,
|
|
717
|
-
renderer_override_count: activationResult.renderer_override_count,
|
|
718
|
-
registration_counts: activationResult.registration_counts,
|
|
719
|
-
registrations: activationResult.registrations,
|
|
720
|
-
migration_status: migrationStatus.summary,
|
|
721
|
-
managed_extensions: {
|
|
722
|
-
project: {
|
|
723
|
-
path: projectManagedState.path,
|
|
724
|
-
count: projectManagedState.state.entries.length,
|
|
725
|
-
entries: projectManagedState.state.entries,
|
|
726
|
-
},
|
|
727
|
-
global: {
|
|
728
|
-
path: globalManagedState.path,
|
|
729
|
-
count: globalManagedState.state.entries.length,
|
|
730
|
-
entries: globalManagedState.state.entries,
|
|
731
|
-
},
|
|
732
|
-
},
|
|
733
|
-
};
|
|
734
|
-
/* c8 ignore start -- unmanaged/expected grouping matrices are exercised in doctor + extension integration suites */
|
|
735
|
-
const managedProjectNames = new Set(projectManagedState.state.entries.map((entry) => normalizeExtensionNameForMatch(entry.name)));
|
|
736
|
-
const managedGlobalNames = new Set(globalManagedState.state.entries.map((entry) => normalizeExtensionNameForMatch(entry.name)));
|
|
737
|
-
const unmanagedLoadedEntries = [
|
|
738
|
-
...new Map(loadResult.loaded
|
|
739
|
-
.filter((entry) => {
|
|
740
|
-
const managedNames = entry.layer === "project"
|
|
741
|
-
? managedProjectNames
|
|
742
|
-
: managedGlobalNames;
|
|
743
|
-
return !managedNames.has(normalizeExtensionNameForMatch(entry.name));
|
|
744
|
-
})
|
|
745
|
-
.map((entry) => [
|
|
746
|
-
`${entry.layer}:${entry.name}`,
|
|
747
|
-
{
|
|
748
|
-
layer: entry.layer,
|
|
749
|
-
name: entry.name,
|
|
750
|
-
directory: entry.directory,
|
|
751
|
-
},
|
|
752
|
-
])).values(),
|
|
753
|
-
].sort((left, right) => {
|
|
754
|
-
const leftKey = `${left.layer}:${left.name}`;
|
|
755
|
-
const rightKey = `${right.layer}:${right.name}`;
|
|
756
|
-
return leftKey.localeCompare(rightKey);
|
|
757
|
-
});
|
|
758
|
-
const unmanagedLoadedExtensions = unmanagedLoadedEntries
|
|
759
|
-
.map((entry) => `${entry.layer}:${entry.name}`)
|
|
760
|
-
.sort((left, right) => left.localeCompare(right));
|
|
761
|
-
const unmanagedExpectedExtensions = unmanagedLoadedEntries
|
|
762
|
-
.filter((entry) => isExpectedUnmanagedExtension(entry.name, entry.directory))
|
|
763
|
-
.map((entry) => `${entry.layer}:${entry.name}`)
|
|
764
|
-
.sort((left, right) => left.localeCompare(right));
|
|
765
|
-
const unmanagedActionRequiredExtensions = unmanagedLoadedEntries
|
|
766
|
-
.filter((entry) => !isExpectedUnmanagedExtension(entry.name, entry.directory))
|
|
767
|
-
.map((entry) => `${entry.layer}:${entry.name}`)
|
|
768
|
-
.sort((left, right) => left.localeCompare(right));
|
|
769
|
-
/* c8 ignore stop */
|
|
770
|
-
const updateCoverageWarnings = unmanagedActionRequiredExtensions.length > 0
|
|
771
|
-
? [
|
|
772
|
-
`extension_update_health_partial_coverage:skipped_unmanaged:${unmanagedActionRequiredExtensions.length}`,
|
|
773
|
-
]
|
|
774
|
-
: [];
|
|
775
|
-
const extensionWarnings = [
|
|
776
|
-
...authorManifest.warnings,
|
|
777
|
-
...loadResult.warnings,
|
|
778
|
-
...activationDetails.warnings,
|
|
779
|
-
...migrationStatus.warnings,
|
|
780
|
-
...projectManagedState.warnings,
|
|
781
|
-
...globalManagedState.warnings,
|
|
782
|
-
...updateCoverageWarnings,
|
|
783
|
-
...hostVersionCensus.warnings,
|
|
784
|
-
];
|
|
785
|
-
const capabilityGuidance = collectUnknownCapabilityGuidance(extensionWarnings);
|
|
786
|
-
const capabilityContract = buildCapabilityContractMetadata();
|
|
787
|
-
const extensionTriage = buildExtensionHealthTriageSummary(extensionWarnings, loadResult.failed.length, activationResult.failed.length, migrationStatus.summary, projectManagedState.warnings.length + globalManagedState.warnings.length, projectManagedState.state.entries.length +
|
|
788
|
-
globalManagedState.state.entries.length, unmanagedLoadedExtensions, unmanagedExpectedExtensions, unmanagedActionRequiredExtensions);
|
|
789
|
-
return {
|
|
790
|
-
check: {
|
|
791
|
-
name: "extensions",
|
|
792
|
-
status: extensionWarnings.length === 0 ? "ok" : "warn",
|
|
793
|
-
ok: extensionWarnings.length === 0,
|
|
794
|
-
details: {
|
|
795
|
-
...loadResult,
|
|
796
|
-
loaded: loadedSummaries,
|
|
797
|
-
warnings: extensionWarnings,
|
|
798
|
-
activation: activationDetails,
|
|
799
|
-
author_manifest: authorManifest,
|
|
800
|
-
triage: extensionTriage,
|
|
801
|
-
...(migrationStatus.summary.pending_count > 0
|
|
802
|
-
? {
|
|
803
|
-
remediation_map: {
|
|
804
|
-
extension_migration_pending: "pm extension migrate --project",
|
|
805
|
-
},
|
|
806
|
-
}
|
|
807
|
-
: {}),
|
|
808
|
-
capability_contract: capabilityContract,
|
|
809
|
-
capability_guidance: capabilityGuidance,
|
|
810
|
-
host_version_census: hostVersionCensus,
|
|
811
|
-
},
|
|
812
|
-
},
|
|
813
|
-
warnings: extensionWarnings,
|
|
814
|
-
};
|
|
815
|
-
}
|
|
816
|
-
function summarizeList(values, limit) {
|
|
817
|
-
if (values.length <= limit) {
|
|
818
|
-
return { values, truncated: false };
|
|
819
|
-
}
|
|
820
|
-
return {
|
|
821
|
-
values: values.slice(0, limit),
|
|
822
|
-
truncated: true,
|
|
823
|
-
};
|
|
824
|
-
}
|
|
825
|
-
function summarizeRecordList(value, limit) {
|
|
826
|
-
if (!Array.isArray(value)) {
|
|
827
|
-
return {
|
|
828
|
-
count: 0,
|
|
829
|
-
sample: [],
|
|
830
|
-
truncated: false,
|
|
831
|
-
};
|
|
832
|
-
}
|
|
833
|
-
return {
|
|
834
|
-
count: value.length,
|
|
835
|
-
sample: value.slice(0, limit),
|
|
836
|
-
truncated: value.length > limit,
|
|
837
|
-
};
|
|
838
|
-
}
|
|
839
|
-
function summarizeExtensionRecord(value) {
|
|
840
|
-
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
841
|
-
return {};
|
|
842
|
-
}
|
|
843
|
-
const record = value;
|
|
844
|
-
return {
|
|
845
|
-
layer: record.layer,
|
|
846
|
-
directory: record.directory,
|
|
847
|
-
name: record.name,
|
|
848
|
-
version: record.version,
|
|
849
|
-
enabled: record.enabled,
|
|
850
|
-
status: record.status,
|
|
851
|
-
has_activate: record.has_activate,
|
|
852
|
-
capabilities: record.capabilities,
|
|
853
|
-
};
|
|
854
|
-
}
|
|
855
|
-
function summarizeExtensionList(value, limit) {
|
|
856
|
-
const summary = summarizeRecordList(value, limit);
|
|
857
|
-
return {
|
|
858
|
-
...summary,
|
|
859
|
-
sample: summary.sample.map((entry) => summarizeExtensionRecord(entry)),
|
|
860
|
-
};
|
|
861
|
-
}
|
|
862
|
-
function summarizeStringList(value, limit) {
|
|
863
|
-
if (!Array.isArray(value)) {
|
|
864
|
-
return {
|
|
865
|
-
count: 0,
|
|
866
|
-
sample: [],
|
|
867
|
-
truncated: false,
|
|
868
|
-
};
|
|
869
|
-
}
|
|
870
|
-
const strings = value.filter((entry) => typeof entry === "string");
|
|
871
|
-
return {
|
|
872
|
-
count: strings.length,
|
|
873
|
-
sample: strings.slice(0, limit),
|
|
874
|
-
truncated: strings.length > limit,
|
|
875
|
-
};
|
|
876
|
-
}
|
|
877
|
-
function summarizeActivationMigrationStatus(value) {
|
|
878
|
-
if (typeof value !== "object" || value === null) {
|
|
879
|
-
return null;
|
|
880
|
-
}
|
|
881
|
-
const status = value;
|
|
882
|
-
return {
|
|
883
|
-
applied_count: status.applied_count,
|
|
884
|
-
pending_count: status.pending_count,
|
|
885
|
-
failed_count: status.failed_count,
|
|
886
|
-
};
|
|
887
|
-
}
|
|
888
|
-
const HEALTH_DETAIL_SUMMARIZERS = {
|
|
889
|
-
settings: (details, limit) => ({
|
|
890
|
-
version: details.version,
|
|
891
|
-
id_prefix: details.id_prefix,
|
|
892
|
-
locks_ttl_seconds: details.locks_ttl_seconds,
|
|
893
|
-
warnings: summarizeStringList(details.warnings, limit),
|
|
894
|
-
}),
|
|
895
|
-
directories: (details, limit) => ({
|
|
896
|
-
required_count: Array.isArray(details.required)
|
|
897
|
-
? details.required.length
|
|
898
|
-
: 0,
|
|
899
|
-
optional_count: Array.isArray(details.optional)
|
|
900
|
-
? details.optional.length
|
|
901
|
-
: 0,
|
|
902
|
-
missing_required: summarizeStringList(details.missing_required, limit),
|
|
903
|
-
missing_optional: summarizeStringList(details.missing_optional, limit),
|
|
904
|
-
missing: summarizeStringList(details.missing, limit),
|
|
905
|
-
strict_directories: details.strict_directories,
|
|
906
|
-
}),
|
|
907
|
-
settings_values: (details, limit) => ({
|
|
908
|
-
warnings: summarizeStringList(details.warnings, limit),
|
|
909
|
-
}),
|
|
910
|
-
telemetry: (details) => ({
|
|
911
|
-
enabled: details.enabled,
|
|
912
|
-
capture_level: details.capture_level,
|
|
913
|
-
endpoint: details.endpoint,
|
|
914
|
-
queue_exists: details.queue_exists,
|
|
915
|
-
queue_entries: details.queue_entries,
|
|
916
|
-
queue_draining: details.queue_draining,
|
|
917
|
-
queue_invalid_rows: details.queue_invalid_rows,
|
|
918
|
-
queue_rows_total: details.queue_rows_total,
|
|
919
|
-
last_successful_flush_at: details.last_successful_flush_at,
|
|
920
|
-
last_failed_flush_at: details.last_failed_flush_at,
|
|
921
|
-
endpoint_probe: details.endpoint_probe,
|
|
922
|
-
env_overrides: details.env_overrides,
|
|
923
|
-
}),
|
|
924
|
-
extensions: (details, limit) => {
|
|
925
|
-
const activation = typeof details.activation === "object" && details.activation !== null
|
|
926
|
-
? details.activation
|
|
927
|
-
: {};
|
|
928
|
-
return {
|
|
929
|
-
disabled_by_flag: details.disabled_by_flag,
|
|
930
|
-
discovered: summarizeExtensionList(details.discovered, limit),
|
|
931
|
-
effective: summarizeExtensionList(details.effective, limit),
|
|
932
|
-
loaded: summarizeExtensionList(details.loaded, limit),
|
|
933
|
-
failed: summarizeRecordList(details.failed, limit),
|
|
934
|
-
warnings: summarizeStringList(details.warnings, limit),
|
|
935
|
-
activation: {
|
|
936
|
-
failed: summarizeRecordList(activation.failed, limit),
|
|
937
|
-
warnings: summarizeStringList(activation.warnings, limit),
|
|
938
|
-
hook_counts: activation.hook_counts,
|
|
939
|
-
command_handler_count: activation.command_handler_count,
|
|
940
|
-
service_override_count: activation.service_override_count,
|
|
941
|
-
renderer_override_count: activation.renderer_override_count,
|
|
942
|
-
registration_counts: activation.registration_counts,
|
|
943
|
-
migration_status: summarizeActivationMigrationStatus(activation.migration_status),
|
|
944
|
-
},
|
|
945
|
-
author_manifest: details.author_manifest,
|
|
946
|
-
triage: details.triage,
|
|
947
|
-
capability_contract: details.capability_contract,
|
|
948
|
-
capability_guidance: summarizeRecordList(details.capability_guidance, limit),
|
|
949
|
-
host_version_census: details.host_version_census,
|
|
950
|
-
};
|
|
951
|
-
},
|
|
952
|
-
storage: (details, limit) => {
|
|
953
|
-
// Preserve compatibility with brief payloads from older builds and extensions.
|
|
954
|
-
const authorAttribution = typeof details.author_attribution === "object" &&
|
|
955
|
-
details.author_attribution !== null
|
|
956
|
-
? details.author_attribution
|
|
957
|
-
: undefined;
|
|
958
|
-
return {
|
|
959
|
-
...details,
|
|
960
|
-
...(authorAttribution
|
|
961
|
-
? {
|
|
962
|
-
author_attribution: {
|
|
963
|
-
...authorAttribution,
|
|
964
|
-
affected_item_ids: summarizeStringList(authorAttribution.affected_item_ids, limit),
|
|
965
|
-
samples: summarizeRecordList(authorAttribution.samples, limit),
|
|
966
|
-
},
|
|
967
|
-
}
|
|
968
|
-
: {}),
|
|
969
|
-
};
|
|
970
|
-
},
|
|
971
|
-
locks: (details) => ({
|
|
972
|
-
active_lock_count: details.active_lock_count,
|
|
973
|
-
stale_lock_count: details.stale_lock_count,
|
|
974
|
-
unreadable_lock_count: details.unreadable_lock_count,
|
|
975
|
-
unparseable_lock_count: details.unparseable_lock_count,
|
|
976
|
-
}),
|
|
977
|
-
integrity: (details, limit) => {
|
|
978
|
-
const trackedRuntimeCache = typeof details.tracked_runtime_cache === "object" &&
|
|
979
|
-
details.tracked_runtime_cache !== null
|
|
980
|
-
? details.tracked_runtime_cache
|
|
981
|
-
: undefined;
|
|
982
|
-
return {
|
|
983
|
-
checked_item_files: details.checked_item_files,
|
|
984
|
-
checked_history_streams: details.checked_history_streams,
|
|
985
|
-
counts: details.counts,
|
|
986
|
-
item_unreadable: summarizeStringList(details.item_unreadable, limit),
|
|
987
|
-
item_conflict_markers: summarizeRecordList(details.item_conflict_markers, limit),
|
|
988
|
-
item_parse_failures: summarizeStringList(details.item_parse_failures, limit),
|
|
989
|
-
tracked_runtime_cache: trackedRuntimeCache === undefined
|
|
990
|
-
? details.tracked_runtime_cache
|
|
991
|
-
: {
|
|
992
|
-
...trackedRuntimeCache,
|
|
993
|
-
tracked_paths: summarizeStringList(trackedRuntimeCache.tracked_paths, limit),
|
|
994
|
-
},
|
|
995
|
-
history_unreadable: summarizeStringList(details.history_unreadable, limit),
|
|
996
|
-
history_conflict_markers: summarizeRecordList(details.history_conflict_markers, limit),
|
|
997
|
-
history_invalid_json: summarizeRecordList(details.history_invalid_json, limit),
|
|
998
|
-
skipped: details.skipped,
|
|
999
|
-
};
|
|
1000
|
-
},
|
|
1001
|
-
history_drift: (details, limit) => {
|
|
1002
|
-
const cacheConfirmation = typeof details.cache_confirmation === "object" &&
|
|
1003
|
-
details.cache_confirmation !== null
|
|
1004
|
-
? details.cache_confirmation
|
|
1005
|
-
: undefined;
|
|
1006
|
-
return {
|
|
1007
|
-
checked_items: details.checked_items,
|
|
1008
|
-
cache_hit_verification: details.cache_hit_verification,
|
|
1009
|
-
cache_confirmation: cacheConfirmation === undefined
|
|
1010
|
-
? details.cache_confirmation
|
|
1011
|
-
: {
|
|
1012
|
-
...cacheConfirmation,
|
|
1013
|
-
candidate_items: summarizeStringList(cacheConfirmation.candidate_items, limit),
|
|
1014
|
-
confirmed_items: summarizeStringList(cacheConfirmation.confirmed_items, limit),
|
|
1015
|
-
resolved_false_positive_items: summarizeStringList(cacheConfirmation.resolved_false_positive_items, limit),
|
|
1016
|
-
},
|
|
1017
|
-
counts: details.counts,
|
|
1018
|
-
drifted_items: summarizeStringList(details.drifted_items, limit),
|
|
1019
|
-
merge_receipt_attributed_items: summarizeStringList(details.merge_receipt_attributed_items, limit),
|
|
1020
|
-
missing_streams: summarizeStringList(details.missing_streams, limit),
|
|
1021
|
-
unreadable_streams: summarizeStringList(details.unreadable_streams, limit),
|
|
1022
|
-
hash_mismatches: summarizeStringList(details.hash_mismatches, limit),
|
|
1023
|
-
chain_mismatches: summarizeStringList(details.chain_mismatches, limit),
|
|
1024
|
-
version_skews: summarizeStringList(details.version_skews, limit),
|
|
1025
|
-
workspace_state_mismatches: summarizeStringList(details.workspace_state_mismatches, limit),
|
|
1026
|
-
workspace_state_missing: summarizeStringList(details.workspace_state_missing, limit),
|
|
1027
|
-
workspace_state_unreadable: summarizeStringList(details.workspace_state_unreadable, limit),
|
|
1028
|
-
skipped: details.skipped,
|
|
1029
|
-
};
|
|
1030
|
-
},
|
|
1031
|
-
vectorization: (details, limit) => ({
|
|
1032
|
-
semantic_runtime_available: details.semantic_runtime_available,
|
|
1033
|
-
compatibility_mode_auto_defaults: details.compatibility_mode_auto_defaults,
|
|
1034
|
-
auto_ollama_defaults_applied: details.auto_ollama_defaults_applied,
|
|
1035
|
-
auto_ollama_defaults_skipped_reason: details.auto_ollama_defaults_skipped_reason,
|
|
1036
|
-
auto_ollama_defaults_remediation: details.auto_ollama_defaults_remediation,
|
|
1037
|
-
refresh_policy: details.refresh_policy,
|
|
1038
|
-
provider_active: details.provider_active,
|
|
1039
|
-
vector_store_active: details.vector_store_active,
|
|
1040
|
-
items: details.items,
|
|
1041
|
-
ledger_entries_before: details.ledger_entries_before,
|
|
1042
|
-
stale_items_before_total: details.stale_items_before_total,
|
|
1043
|
-
stale_items_before: summarizeStringList(details.stale_items_before, limit),
|
|
1044
|
-
refresh_attempted: details.refresh_attempted,
|
|
1045
|
-
refresh_skipped_reason: details.refresh_skipped_reason,
|
|
1046
|
-
refresh_result: details.refresh_result,
|
|
1047
|
-
ledger_entries_after: details.ledger_entries_after,
|
|
1048
|
-
stale_items_after_total: details.stale_items_after_total,
|
|
1049
|
-
stale_items_after: summarizeStringList(details.stale_items_after, limit),
|
|
1050
|
-
skipped: details.skipped,
|
|
1051
|
-
}),
|
|
1052
|
-
};
|
|
1053
|
-
/* c8 ignore start -- brief/summary projection matrix branches are validated in projection integration tests */
|
|
1054
|
-
function summarizeHealthCheckDetails(check, limit) {
|
|
1055
|
-
const summarize = HEALTH_DETAIL_SUMMARIZERS[check.name];
|
|
1056
|
-
return summarize ? summarize(check.details, limit) : check.details;
|
|
1057
|
-
}
|
|
1058
|
-
/* c8 ignore stop */
|
|
1059
|
-
/** Bound diagnostic detail and warnings while retaining every blocking cause and the authoritative verdict. */
|
|
1060
|
-
function applyBriefHealthProjection(result) {
|
|
1061
|
-
const warningsSummary = summarizeStringList(result.warnings, BRIEF_HEALTH_DETAIL_LIMIT);
|
|
1062
|
-
return {
|
|
1063
|
-
ok: result.ok,
|
|
1064
|
-
...(result.verdict ? { verdict: result.verdict } : {}),
|
|
1065
|
-
checks: result.checks.map((check) => ({
|
|
1066
|
-
name: check.name,
|
|
1067
|
-
status: check.status,
|
|
1068
|
-
ok: check.ok,
|
|
1069
|
-
details: summarizeHealthCheckDetails(check, BRIEF_HEALTH_DETAIL_LIMIT),
|
|
1070
|
-
})),
|
|
1071
|
-
warnings: warningsSummary.sample,
|
|
1072
|
-
findings: result.findings.filter((finding) => warningsSummary.sample.includes(finding.warning) ||
|
|
1073
|
-
result.failed_because.includes(finding.warning)),
|
|
1074
|
-
failed_because: result.failed_because,
|
|
1075
|
-
projection: {
|
|
1076
|
-
mode: "brief",
|
|
1077
|
-
warning_count: warningsSummary.count,
|
|
1078
|
-
warnings_truncated: warningsSummary.truncated,
|
|
1079
|
-
detail_limit: BRIEF_HEALTH_DETAIL_LIMIT,
|
|
1080
|
-
},
|
|
1081
|
-
generated_at: result.generated_at,
|
|
1082
|
-
};
|
|
1083
|
-
}
|
|
1084
|
-
function isSkippedHealthCheck(check) {
|
|
1085
|
-
return check.details.skipped === true;
|
|
1086
|
-
}
|
|
1087
|
-
/** Emit verdicts for checks that ran, retain blocking causes, and name omitted checks for recovery. */
|
|
1088
|
-
function applySummaryHealthProjection(result) {
|
|
1089
|
-
const warningsSummary = summarizeStringList(result.warnings, BRIEF_HEALTH_DETAIL_LIMIT);
|
|
1090
|
-
const omittedChecks = result.checks
|
|
1091
|
-
.filter(isSkippedHealthCheck)
|
|
1092
|
-
.map((check) => check.name);
|
|
1093
|
-
return {
|
|
1094
|
-
ok: result.ok,
|
|
1095
|
-
...(result.verdict ? { verdict: result.verdict } : {}),
|
|
1096
|
-
checks: result.checks
|
|
1097
|
-
.filter((check) => !isSkippedHealthCheck(check))
|
|
1098
|
-
.map((check) => ({
|
|
1099
|
-
name: check.name,
|
|
1100
|
-
status: check.status,
|
|
1101
|
-
ok: check.ok,
|
|
1102
|
-
details: {},
|
|
1103
|
-
})),
|
|
1104
|
-
warning_count: warningsSummary.count,
|
|
1105
|
-
warnings: warningsSummary.sample,
|
|
1106
|
-
findings: result.findings.filter((finding) => warningsSummary.sample.includes(finding.warning) ||
|
|
1107
|
-
result.failed_because.includes(finding.warning)),
|
|
1108
|
-
failed_because: result.failed_because,
|
|
1109
|
-
projection: {
|
|
1110
|
-
mode: "summary",
|
|
1111
|
-
warning_count: warningsSummary.count,
|
|
1112
|
-
warnings_truncated: warningsSummary.truncated,
|
|
1113
|
-
detail_limit: BRIEF_HEALTH_DETAIL_LIMIT,
|
|
1114
|
-
omitted_checks: omittedChecks,
|
|
1115
|
-
},
|
|
1116
|
-
generated_at: result.generated_at,
|
|
1117
|
-
};
|
|
1118
|
-
}
|
|
1119
|
-
function selectStaleItemDetail(values, verboseStaleItems) {
|
|
1120
|
-
if (verboseStaleItems) {
|
|
1121
|
-
return {
|
|
1122
|
-
values,
|
|
1123
|
-
truncated: false,
|
|
1124
|
-
total: values.length,
|
|
1125
|
-
};
|
|
1126
|
-
}
|
|
1127
|
-
const summary = summarizeList(values, STALE_VECTORIZATION_SUMMARY_LIMIT);
|
|
1128
|
-
return {
|
|
1129
|
-
values: summary.values,
|
|
1130
|
-
truncated: summary.truncated,
|
|
1131
|
-
total: values.length,
|
|
1132
|
-
};
|
|
1133
|
-
}
|
|
1134
|
-
function telemetryEnvFlagEnabled(envKey) {
|
|
1135
|
-
const value = (process.env[envKey] ?? "").trim().toLowerCase();
|
|
1136
|
-
return value === "1" || value === "true" || value === "yes" || value === "on";
|
|
1137
|
-
}
|
|
1138
|
-
/* c8 ignore start -- environment override permutations are covered by runtime integration tests */
|
|
1139
|
-
function telemetrySourceContextOverride() {
|
|
1140
|
-
// Only report an override the runtime actually honours: runtime.ts ignores any
|
|
1141
|
-
// value outside the enum and falls back to the inferred context, so health must
|
|
1142
|
-
// report null for an unrecognized value rather than implying it took effect.
|
|
1143
|
-
const value = (process.env.PM_TELEMETRY_SOURCE_CONTEXT ?? "")
|
|
1144
|
-
.trim()
|
|
1145
|
-
.toLowerCase();
|
|
1146
|
-
return PM_TELEMETRY_SOURCE_CONTEXT_SET.has(value) ? value : null;
|
|
1147
|
-
}
|
|
1148
|
-
/* c8 ignore stop */
|
|
1149
|
-
function normalizeEndpointForDisplay(rawEndpoint) {
|
|
1150
|
-
const trimmed = rawEndpoint.trim();
|
|
1151
|
-
if (trimmed.length === 0) {
|
|
1152
|
-
return "";
|
|
1153
|
-
}
|
|
1154
|
-
try {
|
|
1155
|
-
const parsed = new URL(trimmed);
|
|
1156
|
-
parsed.username = "";
|
|
1157
|
-
parsed.password = "";
|
|
1158
|
-
parsed.search = "";
|
|
1159
|
-
parsed.hash = "";
|
|
1160
|
-
return parsed.toString();
|
|
1161
|
-
}
|
|
1162
|
-
catch {
|
|
1163
|
-
return trimmed;
|
|
1164
|
-
}
|
|
1165
|
-
}
|
|
1166
|
-
function parseTelemetryQueue(raw) {
|
|
1167
|
-
let validEntries = 0;
|
|
1168
|
-
let invalidRows = 0;
|
|
1169
|
-
let totalRows = 0;
|
|
1170
|
-
let highRetryEntries = 0;
|
|
1171
|
-
let maxAttempts = 0;
|
|
1172
|
-
for (const line of raw.split("\n")) {
|
|
1173
|
-
const trimmed = line.trim();
|
|
1174
|
-
if (trimmed.length === 0) {
|
|
1175
|
-
continue;
|
|
1176
|
-
}
|
|
1177
|
-
totalRows += 1;
|
|
1178
|
-
try {
|
|
1179
|
-
const parsed = JSON.parse(trimmed);
|
|
1180
|
-
if (typeof parsed === "object" &&
|
|
1181
|
-
parsed !== null &&
|
|
1182
|
-
typeof parsed.attempts === "number" &&
|
|
1183
|
-
Number.isFinite(parsed.attempts)) {
|
|
1184
|
-
const attempts = Math.max(0, Math.trunc(parsed.attempts));
|
|
1185
|
-
validEntries += 1;
|
|
1186
|
-
maxAttempts = Math.max(maxAttempts, attempts);
|
|
1187
|
-
if (attempts >= TELEMETRY_QUEUE_HIGH_RETRY_THRESHOLD) {
|
|
1188
|
-
highRetryEntries += 1;
|
|
1189
|
-
}
|
|
1190
|
-
}
|
|
1191
|
-
else {
|
|
1192
|
-
/* c8 ignore next -- invalid queue rows are covered by end-to-end telemetry fixtures */
|
|
1193
|
-
invalidRows += 1;
|
|
1194
|
-
}
|
|
1195
|
-
}
|
|
1196
|
-
catch {
|
|
1197
|
-
invalidRows += 1;
|
|
1198
|
-
}
|
|
1199
|
-
}
|
|
1200
|
-
return {
|
|
1201
|
-
validEntries,
|
|
1202
|
-
invalidRows,
|
|
1203
|
-
totalRows,
|
|
1204
|
-
highRetryEntries,
|
|
1205
|
-
maxAttempts,
|
|
1206
|
-
};
|
|
1207
|
-
}
|
|
1208
|
-
function emptyTelemetryQueueSummary() {
|
|
1209
|
-
return {
|
|
1210
|
-
validEntries: 0,
|
|
1211
|
-
invalidRows: 0,
|
|
1212
|
-
totalRows: 0,
|
|
1213
|
-
highRetryEntries: 0,
|
|
1214
|
-
maxAttempts: 0,
|
|
1215
|
-
};
|
|
1216
|
-
}
|
|
1217
|
-
/* c8 ignore start -- telemetry state corruption and otel-failure branches require runtime-coordinated fixture mutation */
|
|
1218
|
-
function parseTelemetryRuntimeState(stateRaw) {
|
|
1219
|
-
if (!stateRaw || stateRaw.trim().length === 0) {
|
|
1220
|
-
return { runtimeState: {}, stateParseFailed: false };
|
|
1221
|
-
}
|
|
1222
|
-
try {
|
|
1223
|
-
const parsed = JSON.parse(stateRaw);
|
|
1224
|
-
if (typeof parsed === "object" &&
|
|
1225
|
-
parsed !== null &&
|
|
1226
|
-
!Array.isArray(parsed)) {
|
|
1227
|
-
return { runtimeState: parsed, stateParseFailed: false };
|
|
1228
|
-
}
|
|
1229
|
-
return { runtimeState: {}, stateParseFailed: true };
|
|
1230
|
-
}
|
|
1231
|
-
catch {
|
|
1232
|
-
return { runtimeState: {}, stateParseFailed: true };
|
|
1233
|
-
}
|
|
1234
|
-
}
|
|
1235
|
-
async function maybeProbeTelemetryEndpoint(settings, checkTelemetry) {
|
|
1236
|
-
const endpoint = settings.telemetry.endpoint.trim();
|
|
1237
|
-
if (!checkTelemetry || !settings.telemetry.enabled || endpoint.length === 0) {
|
|
1238
|
-
return undefined;
|
|
1239
|
-
}
|
|
1240
|
-
const probe = await probeTelemetryEndpointHealth(endpoint);
|
|
1241
|
-
return {
|
|
1242
|
-
attempted: true,
|
|
1243
|
-
...probe,
|
|
1244
|
-
};
|
|
1245
|
-
}
|
|
1246
|
-
function collectTelemetryQueueWarnings(settings, queueSummary, runtimeState) {
|
|
1247
|
-
const warnings = [];
|
|
1248
|
-
if (queueSummary.invalidRows > 0) {
|
|
1249
|
-
warnings.push(`telemetry_queue_invalid_rows:${queueSummary.invalidRows}`);
|
|
1250
|
-
}
|
|
1251
|
-
if (!settings.telemetry.enabled || queueSummary.validEntries === 0) {
|
|
1252
|
-
return warnings;
|
|
1253
|
-
}
|
|
1254
|
-
const lastSuccess = runtimeState.last_successful_flush_at;
|
|
1255
|
-
const lastFailure = runtimeState.last_failed_flush_at;
|
|
1256
|
-
const activeFailure = lastFailure && (!lastSuccess || lastFailure > lastSuccess);
|
|
1257
|
-
const neverFlushed = !lastSuccess;
|
|
1258
|
-
const highWater = queueSummary.validEntries >= TELEMETRY_QUEUE_HIGH_WATER_MARK;
|
|
1259
|
-
if (activeFailure || neverFlushed || highWater) {
|
|
1260
|
-
warnings.push(`telemetry_queue_pending:${queueSummary.validEntries}`);
|
|
1261
|
-
}
|
|
1262
|
-
if (queueSummary.highRetryEntries > 0) {
|
|
1263
|
-
warnings.push(`telemetry_queue_high_retries:${queueSummary.highRetryEntries}`);
|
|
1264
|
-
}
|
|
1265
|
-
return warnings;
|
|
1266
|
-
}
|
|
1267
|
-
function collectTelemetryEndpointWarnings(endpointProbe) {
|
|
1268
|
-
if (!endpointProbe || endpointProbe.ok !== false) {
|
|
1269
|
-
return [];
|
|
1270
|
-
}
|
|
1271
|
-
return typeof endpointProbe.status === "number"
|
|
1272
|
-
? [`telemetry_endpoint_probe_http_status:${endpointProbe.status}`]
|
|
1273
|
-
: ["telemetry_endpoint_probe_failed"];
|
|
1274
|
-
}
|
|
1275
|
-
function collectTelemetrySchemaWarnings(endpointProbe) {
|
|
1276
|
-
const parsedMaxSchemaVersion = Number.parseInt(endpointProbe?.max_schema_version ?? "", 10);
|
|
1277
|
-
if (endpointProbe?.ok === true &&
|
|
1278
|
-
Number.isInteger(parsedMaxSchemaVersion) &&
|
|
1279
|
-
parsedMaxSchemaVersion > TELEMETRY_SCHEMA_VERSION) {
|
|
1280
|
-
return [`telemetry_schema_version_behind:${parsedMaxSchemaVersion}`];
|
|
1281
|
-
}
|
|
1282
|
-
return [];
|
|
1283
|
-
}
|
|
1284
|
-
function collectTelemetryOtelWarnings(settings, runtimeState) {
|
|
1285
|
-
const pendingOtelSpans = typeof runtimeState.pending_otel_spans === "number"
|
|
1286
|
-
? runtimeState.pending_otel_spans
|
|
1287
|
-
: 0;
|
|
1288
|
-
const lastOtelSuccess = runtimeState.last_otel_success_at;
|
|
1289
|
-
const lastOtelFailure = runtimeState.last_otel_failure_at;
|
|
1290
|
-
const otelExportFailing = settings.telemetry.enabled &&
|
|
1291
|
-
pendingOtelSpans > 0 &&
|
|
1292
|
-
Boolean(lastOtelFailure) &&
|
|
1293
|
-
// >= so a mixed-outcome batch (success + failure share the same attempt
|
|
1294
|
-
// timestamp) still surfaces the warning rather than being masked by the tie.
|
|
1295
|
-
(!lastOtelSuccess || lastOtelFailure >= lastOtelSuccess);
|
|
1296
|
-
return otelExportFailing
|
|
1297
|
-
? [`telemetry_otel_export_failing:${pendingOtelSpans}`]
|
|
1298
|
-
: [];
|
|
1299
|
-
}
|
|
1300
|
-
function buildTelemetryEnvOverrideDetails() {
|
|
1301
|
-
return {
|
|
1302
|
-
telemetry_disabled: telemetryEnvFlagEnabled("PM_TELEMETRY_DISABLED") ||
|
|
1303
|
-
telemetryEnvFlagEnabled("PM_NO_TELEMETRY"),
|
|
1304
|
-
pm_no_telemetry: telemetryEnvFlagEnabled("PM_NO_TELEMETRY"),
|
|
1305
|
-
telemetry_otel_disabled: telemetryEnvFlagEnabled("PM_TELEMETRY_OTEL_DISABLED"),
|
|
1306
|
-
telemetry_inline_flush: telemetryEnvFlagEnabled("PM_TELEMETRY_INLINE_FLUSH"),
|
|
1307
|
-
telemetry_source_context: telemetrySourceContextOverride(),
|
|
1308
|
-
};
|
|
1309
|
-
}
|
|
1310
|
-
/* c8 ignore stop */
|
|
1311
|
-
function telemetryQueueHasEntries(settings, queueSummary) {
|
|
1312
|
-
return settings.telemetry.enabled && queueSummary.validEntries > 0;
|
|
1313
|
-
}
|
|
1314
|
-
function isTelemetryQueueDraining(queueHasEntries, warnings) {
|
|
1315
|
-
return (queueHasEntries &&
|
|
1316
|
-
warnings.every((warning) => !warning.startsWith("telemetry_queue_pending:") &&
|
|
1317
|
-
!warning.startsWith("telemetry_queue_high_retries:")));
|
|
1318
|
-
}
|
|
1319
|
-
async function probeTelemetryEndpointHealth(endpoint) {
|
|
1320
|
-
let probeUrl = endpoint;
|
|
1321
|
-
try {
|
|
1322
|
-
const parsed = new URL(endpoint);
|
|
1323
|
-
parsed.pathname = "/healthz";
|
|
1324
|
-
parsed.search = "";
|
|
1325
|
-
parsed.hash = "";
|
|
1326
|
-
probeUrl = parsed.toString();
|
|
1327
|
-
}
|
|
1328
|
-
catch {
|
|
1329
|
-
// keep original endpoint when URL parsing fails
|
|
1330
|
-
}
|
|
1331
|
-
try {
|
|
1332
|
-
const response = await fetch(probeUrl, {
|
|
1333
|
-
method: "GET",
|
|
1334
|
-
signal: AbortSignal.timeout(TELEMETRY_ENDPOINT_PROBE_TIMEOUT_MS),
|
|
1335
|
-
});
|
|
1336
|
-
return {
|
|
1337
|
-
probe_url: normalizeEndpointForDisplay(probeUrl),
|
|
1338
|
-
ok: response.ok,
|
|
1339
|
-
status: response.status,
|
|
1340
|
-
max_schema_version: (() => {
|
|
1341
|
-
for (const headerName of TELEMETRY_SERVER_MAX_SCHEMA_VERSION_HEADERS) {
|
|
1342
|
-
const value = response.headers.get(headerName)?.trim();
|
|
1343
|
-
if (value && value.length > 0) {
|
|
1344
|
-
return value;
|
|
1345
|
-
}
|
|
1346
|
-
}
|
|
1347
|
-
return undefined;
|
|
1348
|
-
})(),
|
|
1349
|
-
};
|
|
1350
|
-
}
|
|
1351
|
-
catch (error) {
|
|
1352
|
-
return {
|
|
1353
|
-
probe_url: normalizeEndpointForDisplay(probeUrl),
|
|
1354
|
-
ok: false,
|
|
1355
|
-
/* c8 ignore next -- non-Error throwables require transport-layer fault injection */
|
|
1356
|
-
error: error instanceof Error ? error.message : "probe_failed",
|
|
1357
|
-
};
|
|
1358
|
-
}
|
|
1359
|
-
}
|
|
1360
|
-
async function buildTelemetryCheck(settings, options) {
|
|
1361
|
-
const globalPmRoot = resolveGlobalPmRoot(process.cwd());
|
|
1362
|
-
const queuePath = path.join(globalPmRoot, TELEMETRY_QUEUE_RELATIVE_PATH);
|
|
1363
|
-
const statePath = path.join(globalPmRoot, TELEMETRY_STATE_RELATIVE_PATH);
|
|
1364
|
-
const queueRaw = await readFileIfExists(queuePath);
|
|
1365
|
-
const queueExists = queueRaw !== null;
|
|
1366
|
-
const queueSizeBytes = queueRaw ? Buffer.byteLength(queueRaw, "utf8") : 0;
|
|
1367
|
-
const queueSummary = queueRaw
|
|
1368
|
-
? parseTelemetryQueue(queueRaw)
|
|
1369
|
-
: emptyTelemetryQueueSummary();
|
|
1370
|
-
const stateRaw = await readFileIfExists(statePath);
|
|
1371
|
-
const { runtimeState, stateParseFailed } = parseTelemetryRuntimeState(stateRaw);
|
|
1372
|
-
const endpoint = settings.telemetry.endpoint.trim();
|
|
1373
|
-
const endpointDisplay = normalizeEndpointForDisplay(endpoint);
|
|
1374
|
-
const endpointProbe = await maybeProbeTelemetryEndpoint(settings, options.checkTelemetry);
|
|
1375
|
-
const warnings = [];
|
|
1376
|
-
if (stateParseFailed) {
|
|
1377
|
-
warnings.push("telemetry_state_invalid_json");
|
|
1378
|
-
}
|
|
1379
|
-
warnings.push(...collectTelemetryQueueWarnings(settings, queueSummary, runtimeState), ...collectTelemetryEndpointWarnings(endpointProbe), ...collectTelemetrySchemaWarnings(endpointProbe), ...collectTelemetryOtelWarnings(settings, runtimeState));
|
|
1380
|
-
const queueHasEntries = telemetryQueueHasEntries(settings, queueSummary);
|
|
1381
|
-
const pendingOtelSpans = typeof runtimeState.pending_otel_spans === "number"
|
|
1382
|
-
? runtimeState.pending_otel_spans
|
|
1383
|
-
: 0;
|
|
1384
|
-
return {
|
|
1385
|
-
check: {
|
|
1386
|
-
name: "telemetry",
|
|
1387
|
-
status: warnings.length === 0 ? "ok" : "warn",
|
|
1388
|
-
ok: warnings.length === 0,
|
|
1389
|
-
details: {
|
|
1390
|
-
enabled: settings.telemetry.enabled,
|
|
1391
|
-
capture_level: settings.telemetry.capture_level,
|
|
1392
|
-
endpoint: endpointDisplay,
|
|
1393
|
-
global_pm_root: globalPmRoot,
|
|
1394
|
-
queue_path: queuePath,
|
|
1395
|
-
queue_exists: queueExists,
|
|
1396
|
-
queue_entries: queueSummary.validEntries,
|
|
1397
|
-
queue_draining: isTelemetryQueueDraining(queueHasEntries, warnings),
|
|
1398
|
-
queue_invalid_rows: queueSummary.invalidRows,
|
|
1399
|
-
queue_rows_total: queueSummary.totalRows,
|
|
1400
|
-
queue_size_bytes: queueSizeBytes,
|
|
1401
|
-
queue_high_retry_entries: queueSummary.highRetryEntries,
|
|
1402
|
-
queue_high_retry_threshold: TELEMETRY_QUEUE_HIGH_RETRY_THRESHOLD,
|
|
1403
|
-
queue_max_attempts: queueSummary.maxAttempts,
|
|
1404
|
-
runtime_state_path: statePath,
|
|
1405
|
-
last_attempted_flush_at: runtimeState.last_attempted_flush_at ?? null,
|
|
1406
|
-
last_successful_flush_at: runtimeState.last_successful_flush_at ?? null,
|
|
1407
|
-
last_failed_flush_at: runtimeState.last_failed_flush_at ?? null,
|
|
1408
|
-
last_failed_flush_error: runtimeState.last_failed_flush_error ?? null,
|
|
1409
|
-
pending_otel_spans: pendingOtelSpans,
|
|
1410
|
-
last_otel_attempt_at: runtimeState.last_otel_attempt_at ?? null,
|
|
1411
|
-
last_otel_success_at: runtimeState.last_otel_success_at ?? null,
|
|
1412
|
-
last_otel_failure_at: runtimeState.last_otel_failure_at ?? null,
|
|
1413
|
-
last_otel_failure_error: runtimeState.last_otel_failure_error ?? null,
|
|
1414
|
-
endpoint_probe: endpointProbe ?? { attempted: false },
|
|
1415
|
-
env_overrides: buildTelemetryEnvOverrideDetails(),
|
|
1416
|
-
},
|
|
1417
|
-
},
|
|
1418
|
-
warnings,
|
|
1419
|
-
};
|
|
1420
|
-
}
|
|
1421
|
-
/** Read-only locks check (pm-xo1n): surfaces active/stale/unreadable/unparseable lock counts using the exact classification `pm gc --scope locks` acts on, so agents can gate on stale item-claim locks before running gc speculatively. */
|
|
1422
|
-
async function buildLocksCheck(pmRoot) {
|
|
1423
|
-
/* c8 ignore start -- scan failure branches require filesystem-level fault injection */
|
|
1424
|
-
let scan;
|
|
1425
|
-
try {
|
|
1426
|
-
scan = await scanLockHealth(pmRoot);
|
|
1427
|
-
}
|
|
1428
|
-
catch (error) {
|
|
1429
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
1430
|
-
return {
|
|
1431
|
-
check: {
|
|
1432
|
-
name: "locks",
|
|
1433
|
-
status: "warn",
|
|
1434
|
-
ok: false,
|
|
1435
|
-
details: {
|
|
1436
|
-
active_lock_count: 0,
|
|
1437
|
-
stale_lock_count: 0,
|
|
1438
|
-
unreadable_lock_count: 0,
|
|
1439
|
-
unparseable_lock_count: 0,
|
|
1440
|
-
scan_failed: true,
|
|
1441
|
-
error: message,
|
|
1442
|
-
pm_root: pmRoot,
|
|
1443
|
-
},
|
|
1444
|
-
},
|
|
1445
|
-
warnings: [`locks_scan_failed:${message}`],
|
|
1446
|
-
};
|
|
1447
|
-
}
|
|
1448
|
-
const warnings = [];
|
|
1449
|
-
if (scan.stale_lock_count > 0) {
|
|
1450
|
-
warnings.push(`locks_stale_count:${scan.stale_lock_count}`);
|
|
1451
|
-
}
|
|
1452
|
-
if (scan.unreadable_lock_count > 0) {
|
|
1453
|
-
warnings.push(`locks_unreadable:${scan.unreadable_lock_count}`);
|
|
1454
|
-
}
|
|
1455
|
-
/* c8 ignore stop */
|
|
1456
|
-
return {
|
|
1457
|
-
check: {
|
|
1458
|
-
name: "locks",
|
|
1459
|
-
status: warnings.length === 0 ? "ok" : "warn",
|
|
1460
|
-
ok: warnings.length === 0,
|
|
1461
|
-
details: {
|
|
1462
|
-
active_lock_count: scan.active_lock_count,
|
|
1463
|
-
stale_lock_count: scan.stale_lock_count,
|
|
1464
|
-
unreadable_lock_count: scan.unreadable_lock_count,
|
|
1465
|
-
unparseable_lock_count: scan.unparseable_lock_count,
|
|
1466
|
-
},
|
|
1467
|
-
},
|
|
1468
|
-
warnings,
|
|
1469
|
-
};
|
|
1470
|
-
}
|
|
1471
|
-
async function buildHistoryDriftCheck(params) {
|
|
1472
|
-
const cacheHitVerification = "metadata";
|
|
1473
|
-
let items = params.items;
|
|
1474
|
-
let drift = await scanHistoryDrift(params.pmRoot, items, {
|
|
1475
|
-
cacheHitVerification,
|
|
1476
|
-
});
|
|
1477
|
-
const cacheConfirmationCandidates = [
|
|
1478
|
-
...new Set([
|
|
1479
|
-
...drift.hashMismatches,
|
|
1480
|
-
...drift.chainMismatches,
|
|
1481
|
-
...drift.versionSkews,
|
|
1482
|
-
]),
|
|
1483
|
-
].sort((left, right) => left.localeCompare(right));
|
|
1484
|
-
let confirmedItems = [];
|
|
1485
|
-
let resolvedFalsePositiveItems = [];
|
|
1486
|
-
if (cacheConfirmationCandidates.length > 0) {
|
|
1487
|
-
items = await listAllItemMetadataWithBody(params.pmRoot, params.settings.item_format, params.typeRegistry.type_to_folder, params.itemReadWarnings, params.settings.schema, { forceSourceScan: true });
|
|
1488
|
-
drift = await scanHistoryDrift(params.pmRoot, items);
|
|
1489
|
-
confirmedItems = [
|
|
1490
|
-
...new Set([
|
|
1491
|
-
...drift.hashMismatches,
|
|
1492
|
-
...drift.chainMismatches,
|
|
1493
|
-
...drift.versionSkews,
|
|
1494
|
-
]),
|
|
1495
|
-
].sort((left, right) => left.localeCompare(right));
|
|
1496
|
-
const confirmedSet = new Set(confirmedItems);
|
|
1497
|
-
resolvedFalsePositiveItems = cacheConfirmationCandidates.filter((id) => !confirmedSet.has(id));
|
|
1498
|
-
}
|
|
1499
|
-
const { missingStreams, unreadableStreams, hashMismatches, chainMismatches, versionSkews, driftedItems, workspaceStateMismatches, workspaceStateMissing, workspaceStateUnreadable, } = drift;
|
|
1500
|
-
const warnings = [
|
|
1501
|
-
...missingStreams.map((id) => `history_drift_missing_stream:${id}`),
|
|
1502
|
-
...unreadableStreams.map((id) => `history_drift_unreadable_stream:${id}`),
|
|
1503
|
-
...hashMismatches.map((id) => `history_drift_hash_mismatch:${id}`),
|
|
1504
|
-
...chainMismatches.map((id) => `history_drift_chain_mismatch:${id}`),
|
|
1505
|
-
...versionSkews.map((id) => `history_drift_version_skew:${id}`),
|
|
1506
|
-
...workspaceStateMismatches.map((documentPath) => `history_drift_workspace_state_mismatch:${documentPath}`),
|
|
1507
|
-
...workspaceStateMissing.map((documentPath) => `history_drift_workspace_state_missing:${documentPath}`),
|
|
1508
|
-
...workspaceStateUnreadable.map((documentPath) => `history_drift_workspace_state_unreadable:${documentPath}`),
|
|
1509
|
-
];
|
|
1510
|
-
return {
|
|
1511
|
-
check: {
|
|
1512
|
-
name: "history_drift",
|
|
1513
|
-
status: warnings.length === 0 ? "ok" : "warn",
|
|
1514
|
-
ok: warnings.length === 0,
|
|
1515
|
-
details: {
|
|
1516
|
-
checked_items: items.length,
|
|
1517
|
-
cache_hit_verification: cacheConfirmationCandidates.length > 0
|
|
1518
|
-
? "metadata_then_content_hash"
|
|
1519
|
-
: cacheHitVerification,
|
|
1520
|
-
cache_confirmation: {
|
|
1521
|
-
triggered: cacheConfirmationCandidates.length > 0,
|
|
1522
|
-
reason: cacheConfirmationCandidates.length > 0
|
|
1523
|
-
? "cached_corruption_candidate"
|
|
1524
|
-
: null,
|
|
1525
|
-
candidate_items: cacheConfirmationCandidates,
|
|
1526
|
-
confirmed_items: confirmedItems,
|
|
1527
|
-
resolved_false_positive_items: resolvedFalsePositiveItems,
|
|
1528
|
-
authoritative_item_source: cacheConfirmationCandidates.length > 0,
|
|
1529
|
-
},
|
|
1530
|
-
drifted_items: driftedItems,
|
|
1531
|
-
counts: {
|
|
1532
|
-
drifted: driftedItems.length,
|
|
1533
|
-
missing_streams: missingStreams.length,
|
|
1534
|
-
unreadable_streams: unreadableStreams.length,
|
|
1535
|
-
hash_mismatches: hashMismatches.length,
|
|
1536
|
-
chain_mismatches: chainMismatches.length,
|
|
1537
|
-
version_skews: versionSkews.length,
|
|
1538
|
-
workspace_state_mismatches: workspaceStateMismatches.length,
|
|
1539
|
-
workspace_state_missing: workspaceStateMissing.length,
|
|
1540
|
-
workspace_state_unreadable: workspaceStateUnreadable.length,
|
|
1541
|
-
},
|
|
1542
|
-
missing_streams: missingStreams,
|
|
1543
|
-
unreadable_streams: unreadableStreams,
|
|
1544
|
-
hash_mismatches: hashMismatches,
|
|
1545
|
-
chain_mismatches: chainMismatches,
|
|
1546
|
-
version_skews: versionSkews,
|
|
1547
|
-
workspace_state_mismatches: workspaceStateMismatches,
|
|
1548
|
-
workspace_state_missing: workspaceStateMissing,
|
|
1549
|
-
workspace_state_unreadable: workspaceStateUnreadable,
|
|
1550
|
-
},
|
|
1551
|
-
},
|
|
1552
|
-
warnings,
|
|
1553
|
-
};
|
|
1554
|
-
}
|
|
1555
|
-
function buildVectorizationRuntimeSnapshot(settings, pmRoot) {
|
|
1556
|
-
const runtimeDefaults = resolveSettingsWithSemanticRuntimeDefaults(settings);
|
|
1557
|
-
const providerResolution = resolveEmbeddingProviders(runtimeDefaults.settings);
|
|
1558
|
-
const vectorStoreResolution = resolveVectorStores(runtimeDefaults.settings, pmRoot);
|
|
1559
|
-
const runtimeEmbeddingIdentity = providerResolution.active
|
|
1560
|
-
? buildVectorizationEmbeddingIdentity(providerResolution.active.name, providerResolution.active.model)
|
|
1561
|
-
: null;
|
|
1562
|
-
return {
|
|
1563
|
-
runtimeDefaults,
|
|
1564
|
-
providerResolution,
|
|
1565
|
-
vectorStoreResolution,
|
|
1566
|
-
runtimeEmbeddingIdentity,
|
|
1567
|
-
semanticRuntimeAvailable: Boolean(providerResolution.active && vectorStoreResolution.active),
|
|
1568
|
-
};
|
|
1569
|
-
}
|
|
1570
|
-
function emptyVectorizationRefreshResult() {
|
|
1571
|
-
return {
|
|
1572
|
-
refreshed: [],
|
|
1573
|
-
skipped: [],
|
|
1574
|
-
warnings: [],
|
|
1575
|
-
};
|
|
1576
|
-
}
|
|
1577
|
-
async function refreshStaleVectorizationItems(params) {
|
|
1578
|
-
if (!params.refreshPolicy.enabled ||
|
|
1579
|
-
!params.snapshot.semanticRuntimeAvailable ||
|
|
1580
|
-
params.staleBefore.length === 0) {
|
|
1581
|
-
return emptyVectorizationRefreshResult();
|
|
1582
|
-
}
|
|
1583
|
-
return refreshSemanticEmbeddingsForMutatedItems(params.pmRoot, params.staleBefore, {
|
|
1584
|
-
settings: params.snapshot.runtimeDefaults.settings,
|
|
1585
|
-
apply_runtime_defaults: false,
|
|
1586
|
-
});
|
|
1587
|
-
}
|
|
1588
|
-
function vectorizationEmbeddingIdentityChanged(params) {
|
|
1589
|
-
return (params.strictVectorizationWarnings &&
|
|
1590
|
-
params.semanticRuntimeAvailable &&
|
|
1591
|
-
Boolean(params.ledgerBefore.embedding &&
|
|
1592
|
-
params.runtimeEmbeddingIdentity &&
|
|
1593
|
-
hasVectorizationEmbeddingIdentityChanged(params.ledgerBefore.embedding, params.runtimeEmbeddingIdentity)));
|
|
1594
|
-
}
|
|
1595
|
-
/* c8 ignore start -- strict-vectorization warning synthesis branches are integration-only policy permutations */
|
|
1596
|
-
function collectVectorizationWarnings(params) {
|
|
1597
|
-
const warningSet = new Set([
|
|
1598
|
-
...params.ledgerBefore.warnings,
|
|
1599
|
-
...params.ledgerAfter.warnings,
|
|
1600
|
-
]);
|
|
1601
|
-
if (params.strictVectorizationWarnings) {
|
|
1602
|
-
for (const warning of params.refreshResult.warnings) {
|
|
1603
|
-
warningSet.add(warning);
|
|
1604
|
-
}
|
|
1605
|
-
}
|
|
1606
|
-
if (params.embeddingIdentityChanged) {
|
|
1607
|
-
warningSet.add("vectorization_embedding_identity_changed");
|
|
1608
|
-
}
|
|
1609
|
-
if (params.strictVectorizationWarnings &&
|
|
1610
|
-
params.semanticRuntimeAvailable &&
|
|
1611
|
-
params.staleAfter.length > 0) {
|
|
1612
|
-
warningSet.add(`vectorization_stale_items_remaining:${params.staleAfter.length}`);
|
|
1613
|
-
}
|
|
1614
|
-
return [...warningSet].sort((left, right) => left.localeCompare(right));
|
|
1615
|
-
}
|
|
1616
|
-
/* c8 ignore stop */
|
|
1617
|
-
function resolveVectorizationRefreshSkippedReason(refreshPolicy, semanticRuntimeAvailable, staleBefore) {
|
|
1618
|
-
if (refreshPolicy.enabled &&
|
|
1619
|
-
semanticRuntimeAvailable &&
|
|
1620
|
-
staleBefore.length > 0) {
|
|
1621
|
-
return null;
|
|
1622
|
-
}
|
|
1623
|
-
if (!refreshPolicy.enabled) {
|
|
1624
|
-
return "refresh_disabled";
|
|
1625
|
-
}
|
|
1626
|
-
return semanticRuntimeAvailable
|
|
1627
|
-
? "no_stale_items"
|
|
1628
|
-
: "semantic_runtime_unavailable";
|
|
1629
|
-
}
|
|
1630
|
-
function buildVectorizationProviderDetails(settings, snapshot) {
|
|
1631
|
-
const activeProvider = snapshot.providerResolution.active?.name ?? null;
|
|
1632
|
-
const activeVectorStore = snapshot.vectorStoreResolution.active?.name ?? null;
|
|
1633
|
-
return {
|
|
1634
|
-
provider_active: activeProvider,
|
|
1635
|
-
// GH-244: surface the persisted (possibly empty) configured value and
|
|
1636
|
-
// how the active resolution was sourced, so a config audit can tell
|
|
1637
|
-
// "auto-detected" apart from a genuine misconfiguration when
|
|
1638
|
-
// settings.search.provider / vector_store.adapter are empty strings.
|
|
1639
|
-
provider_configured: typeof settings.search?.provider === "string"
|
|
1640
|
-
? settings.search.provider
|
|
1641
|
-
: null,
|
|
1642
|
-
provider_source: resolveProviderConfigSource(activeProvider, settings.search?.provider ?? null),
|
|
1643
|
-
vector_store_active: activeVectorStore,
|
|
1644
|
-
vector_store_configured: typeof settings.vector_store?.adapter === "string"
|
|
1645
|
-
? settings.vector_store.adapter
|
|
1646
|
-
: null,
|
|
1647
|
-
vector_store_source: resolveProviderConfigSource(activeVectorStore, settings.vector_store?.adapter ?? null),
|
|
1648
|
-
};
|
|
1649
|
-
}
|
|
1650
|
-
function buildVectorizationRefreshPolicyDetails(refreshPolicy) {
|
|
1651
|
-
return {
|
|
1652
|
-
enabled: refreshPolicy.enabled,
|
|
1653
|
-
check_only: refreshPolicy.checkOnly,
|
|
1654
|
-
no_refresh: refreshPolicy.noRefresh,
|
|
1655
|
-
refresh_vectors: refreshPolicy.refreshVectors,
|
|
1656
|
-
};
|
|
1657
|
-
}
|
|
1658
|
-
function vectorizationRefreshAttempted(refreshPolicy, semanticRuntimeAvailable, staleBefore) {
|
|
1659
|
-
return (refreshPolicy.enabled && staleBefore.length > 0 && semanticRuntimeAvailable);
|
|
1660
|
-
}
|
|
1661
|
-
async function buildVectorizationCheck(pmRoot, settings, items, refreshPolicy, verboseStaleItems) {
|
|
1662
|
-
const snapshot = buildVectorizationRuntimeSnapshot(settings, pmRoot);
|
|
1663
|
-
const ledgerBefore = await readVectorizationStatusLedger(pmRoot);
|
|
1664
|
-
const staleBefore = snapshot.semanticRuntimeAvailable
|
|
1665
|
-
? collectStaleVectorizationIds(items, ledgerBefore.entries)
|
|
1666
|
-
: [];
|
|
1667
|
-
const refreshResult = await refreshStaleVectorizationItems({
|
|
1668
|
-
pmRoot,
|
|
1669
|
-
snapshot,
|
|
1670
|
-
refreshPolicy,
|
|
1671
|
-
staleBefore,
|
|
1672
|
-
});
|
|
1673
|
-
const ledgerAfter = await readVectorizationStatusLedger(pmRoot);
|
|
1674
|
-
const staleAfter = snapshot.semanticRuntimeAvailable
|
|
1675
|
-
? collectStaleVectorizationIds(items, ledgerAfter.entries)
|
|
1676
|
-
: [];
|
|
1677
|
-
const strictVectorizationWarnings = !snapshot.runtimeDefaults.auto_ollama_defaults_applied;
|
|
1678
|
-
const embeddingIdentityChanged = vectorizationEmbeddingIdentityChanged({
|
|
1679
|
-
strictVectorizationWarnings,
|
|
1680
|
-
semanticRuntimeAvailable: snapshot.semanticRuntimeAvailable,
|
|
1681
|
-
ledgerBefore,
|
|
1682
|
-
runtimeEmbeddingIdentity: snapshot.runtimeEmbeddingIdentity,
|
|
1683
|
-
});
|
|
1684
|
-
const warnings = collectVectorizationWarnings({
|
|
1685
|
-
ledgerBefore,
|
|
1686
|
-
ledgerAfter,
|
|
1687
|
-
refreshResult,
|
|
1688
|
-
strictVectorizationWarnings,
|
|
1689
|
-
semanticRuntimeAvailable: snapshot.semanticRuntimeAvailable,
|
|
1690
|
-
embeddingIdentityChanged,
|
|
1691
|
-
staleAfter,
|
|
1692
|
-
});
|
|
1693
|
-
const staleBeforeDetail = selectStaleItemDetail(staleBefore, verboseStaleItems);
|
|
1694
|
-
const staleAfterDetail = selectStaleItemDetail(staleAfter, verboseStaleItems);
|
|
1695
|
-
const refreshAttempted = vectorizationRefreshAttempted(refreshPolicy, snapshot.semanticRuntimeAvailable, staleBefore);
|
|
1696
|
-
return {
|
|
1697
|
-
check: {
|
|
1698
|
-
name: "vectorization",
|
|
1699
|
-
status: warnings.length === 0 ? "ok" : "warn",
|
|
1700
|
-
ok: warnings.length === 0,
|
|
1701
|
-
details: {
|
|
1702
|
-
semantic_runtime_available: snapshot.semanticRuntimeAvailable,
|
|
1703
|
-
compatibility_mode_auto_defaults: snapshot.runtimeDefaults.auto_ollama_defaults_applied,
|
|
1704
|
-
auto_ollama_defaults_applied: snapshot.runtimeDefaults.auto_ollama_defaults_applied,
|
|
1705
|
-
auto_ollama_defaults_skipped_reason: snapshot.runtimeDefaults.auto_ollama_defaults_skipped_reason ?? null,
|
|
1706
|
-
auto_ollama_defaults_remediation: snapshot.runtimeDefaults.auto_ollama_defaults_remediation ?? null,
|
|
1707
|
-
refresh_policy: buildVectorizationRefreshPolicyDetails(refreshPolicy),
|
|
1708
|
-
...buildVectorizationProviderDetails(settings, snapshot),
|
|
1709
|
-
embedding_identity_changed: embeddingIdentityChanged,
|
|
1710
|
-
embedding_identity_before: ledgerBefore.embedding ?? null,
|
|
1711
|
-
embedding_identity_runtime: snapshot.runtimeEmbeddingIdentity ?? null,
|
|
1712
|
-
items: items.length,
|
|
1713
|
-
ledger_entries_before: Object.keys(ledgerBefore.entries).length,
|
|
1714
|
-
stale_items_detail_mode: verboseStaleItems ? "full" : "summary",
|
|
1715
|
-
stale_items_summary_limit: STALE_VECTORIZATION_SUMMARY_LIMIT,
|
|
1716
|
-
stale_items_before_total: staleBeforeDetail.total,
|
|
1717
|
-
stale_items_before: staleBeforeDetail.values,
|
|
1718
|
-
stale_items_before_truncated: staleBeforeDetail.truncated,
|
|
1719
|
-
refresh_attempted: refreshAttempted,
|
|
1720
|
-
refresh_skipped_reason: resolveVectorizationRefreshSkippedReason(refreshPolicy, snapshot.semanticRuntimeAvailable, staleBefore),
|
|
1721
|
-
refresh_result: refreshResult,
|
|
1722
|
-
ledger_entries_after: Object.keys(ledgerAfter.entries).length,
|
|
1723
|
-
stale_items_after_total: staleAfterDetail.total,
|
|
1724
|
-
stale_items_after: staleAfterDetail.values,
|
|
1725
|
-
stale_items_after_truncated: staleAfterDetail.truncated,
|
|
1726
|
-
},
|
|
1727
|
-
},
|
|
1728
|
-
warnings,
|
|
1729
|
-
};
|
|
1730
|
-
}
|
|
1731
|
-
function validateSettingsValues(settings) {
|
|
1732
|
-
const warnings = [];
|
|
1733
|
-
if (settings.id_prefix.trim().length === 0) {
|
|
1734
|
-
warnings.push("settings:id_prefix_empty");
|
|
1735
|
-
}
|
|
1736
|
-
if (settings.locks.ttl_seconds <= 0) {
|
|
1737
|
-
warnings.push("settings:locks_ttl_non_positive");
|
|
1738
|
-
}
|
|
1739
|
-
return warnings;
|
|
1740
|
-
}
|
|
1741
|
-
function resolveVectorRefreshPolicy(options) {
|
|
1742
|
-
const checkOnly = options.checkOnly === true;
|
|
1743
|
-
const refreshVectors = options.refreshVectors === true;
|
|
1744
|
-
if (refreshVectors && checkOnly) {
|
|
1745
|
-
throw new PmCliError("--check-only cannot be combined with --refresh-vectors", EXIT_CODE.USAGE);
|
|
1746
|
-
}
|
|
1747
|
-
if (refreshVectors && options.noRefresh === true) {
|
|
1748
|
-
throw new PmCliError("--no-refresh cannot be combined with --refresh-vectors", EXIT_CODE.USAGE);
|
|
1749
|
-
}
|
|
1750
|
-
return {
|
|
1751
|
-
enabled: refreshVectors,
|
|
1752
|
-
checkOnly,
|
|
1753
|
-
noRefresh: !refreshVectors,
|
|
1754
|
-
refreshVectors,
|
|
1755
|
-
};
|
|
1756
|
-
}
|
|
1757
|
-
const HEALTH_CLONE_OPTIONAL_DIRECTORIES = new Set([
|
|
1758
|
-
"extensions",
|
|
1759
|
-
"locks",
|
|
1760
|
-
"search",
|
|
1761
|
-
]);
|
|
1762
|
-
function resolveHealthDirectoryLists(typeRegistry) {
|
|
1763
|
-
const requiredDirSet = new Set(PM_CORE_REQUIRED_SUBDIRS.filter((entry) => entry.length > 0));
|
|
1764
|
-
const optionalDirSet = new Set();
|
|
1765
|
-
const builtinItemFolderSet = new Set(Object.values(TYPE_TO_FOLDER));
|
|
1766
|
-
for (const folder of typeRegistry.folders) {
|
|
1767
|
-
if (requiredDirSet.has(folder) && !builtinItemFolderSet.has(folder)) {
|
|
1768
|
-
continue;
|
|
1769
|
-
}
|
|
1770
|
-
requiredDirSet.delete(folder);
|
|
1771
|
-
optionalDirSet.add(folder);
|
|
1772
|
-
}
|
|
1773
|
-
for (const folder of HEALTH_CLONE_OPTIONAL_DIRECTORIES) {
|
|
1774
|
-
requiredDirSet.delete(folder);
|
|
1775
|
-
optionalDirSet.add(folder);
|
|
1776
|
-
}
|
|
1777
|
-
return {
|
|
1778
|
-
requiredDirs: [...requiredDirSet].sort((left, right) => left.localeCompare(right)),
|
|
1779
|
-
optionalDirs: [...optionalDirSet].sort((left, right) => left.localeCompare(right)),
|
|
1780
|
-
optionalDirSet,
|
|
1781
|
-
};
|
|
1782
|
-
}
|
|
1783
|
-
async function scanHealthDirectories(pmRoot, typeRegistry, strictDirectories) {
|
|
1784
|
-
const { requiredDirs, optionalDirs, optionalDirSet } = resolveHealthDirectoryLists(typeRegistry);
|
|
1785
|
-
const missingRequiredDirs = [];
|
|
1786
|
-
const missingOptionalDirs = [];
|
|
1787
|
-
const hookWarnings = [];
|
|
1788
|
-
for (const relativeDir of [...requiredDirs, ...optionalDirs]) {
|
|
1789
|
-
const directoryPath = path.join(pmRoot, relativeDir);
|
|
1790
|
-
hookWarnings.push(...(await runActiveOnReadHooks({
|
|
1791
|
-
path: directoryPath,
|
|
1792
|
-
scope: "project",
|
|
1793
|
-
})));
|
|
1794
|
-
if (await isDirectory(directoryPath)) {
|
|
1795
|
-
continue;
|
|
1796
|
-
}
|
|
1797
|
-
if (optionalDirSet.has(relativeDir)) {
|
|
1798
|
-
missingOptionalDirs.push(relativeDir);
|
|
1799
|
-
}
|
|
1800
|
-
else {
|
|
1801
|
-
missingRequiredDirs.push(relativeDir);
|
|
1802
|
-
}
|
|
1803
|
-
}
|
|
1804
|
-
return {
|
|
1805
|
-
requiredDirs,
|
|
1806
|
-
optionalDirs,
|
|
1807
|
-
missingRequiredDirs,
|
|
1808
|
-
missingOptionalDirs,
|
|
1809
|
-
missingDirs: strictDirectories
|
|
1810
|
-
? [...missingRequiredDirs, ...missingOptionalDirs]
|
|
1811
|
-
: [...missingRequiredDirs],
|
|
1812
|
-
hookWarnings,
|
|
1813
|
-
};
|
|
1814
|
-
}
|
|
1815
|
-
function resolveHealthSkipPolicy(options) {
|
|
1816
|
-
const checkOnlyDefaultSummary = options.checkOnly === true &&
|
|
1817
|
-
options.brief !== true &&
|
|
1818
|
-
options.summary !== true &&
|
|
1819
|
-
options.full !== true;
|
|
1820
|
-
const summaryMode = (options.summary === true || checkOnlyDefaultSummary) &&
|
|
1821
|
-
options.full !== true;
|
|
1822
|
-
const fastProjectionCheckOnly = options.checkOnly === true &&
|
|
1823
|
-
(options.brief === true || options.summary === true) &&
|
|
1824
|
-
options.full !== true;
|
|
1825
|
-
return {
|
|
1826
|
-
summaryMode,
|
|
1827
|
-
skipIntegrity: (options.skipIntegrity === true || fastProjectionCheckOnly) &&
|
|
1828
|
-
options.full !== true,
|
|
1829
|
-
skipDrift: (options.skipDrift === true || fastProjectionCheckOnly) &&
|
|
1830
|
-
options.full !== true,
|
|
1831
|
-
skipVectors: (options.skipVectors === true || fastProjectionCheckOnly) &&
|
|
1832
|
-
options.full !== true,
|
|
1833
|
-
};
|
|
1834
|
-
}
|
|
1835
|
-
async function readHealthItems(params) {
|
|
1836
|
-
if (params.skipPolicy.skipDrift && params.skipPolicy.skipVectors) {
|
|
1837
|
-
return listAllItemMetadataLight(params.pmRoot, params.settings.item_format, params.typeRegistry.type_to_folder, params.itemReadWarnings, params.settings.schema);
|
|
1838
|
-
}
|
|
1839
|
-
return listAllItemMetadataWithBody(params.pmRoot, params.settings.item_format, params.typeRegistry.type_to_folder, params.itemReadWarnings, params.settings.schema);
|
|
1840
|
-
}
|
|
1841
|
-
function buildSkippedHealthCheck(name) {
|
|
1842
|
-
return {
|
|
1843
|
-
check: { name, status: "ok", ok: true, details: { skipped: true } },
|
|
1844
|
-
warnings: [],
|
|
1845
|
-
};
|
|
1846
|
-
}
|
|
1847
|
-
function buildSettingsHealthCheck(settingsPath, settings, normalizedSettingsReadWarnings) {
|
|
1848
|
-
return {
|
|
1849
|
-
name: "settings",
|
|
1850
|
-
/* c8 ignore next -- settings read-warning status split is covered in broader read-settings integration tests */
|
|
1851
|
-
status: normalizedSettingsReadWarnings.length === 0 ? "ok" : "warn",
|
|
1852
|
-
ok: normalizedSettingsReadWarnings.length === 0,
|
|
1853
|
-
details: {
|
|
1854
|
-
path: settingsPath,
|
|
1855
|
-
version: settings.version,
|
|
1856
|
-
id_prefix: settings.id_prefix,
|
|
1857
|
-
locks_ttl_seconds: settings.locks.ttl_seconds,
|
|
1858
|
-
warnings: normalizedSettingsReadWarnings,
|
|
1859
|
-
},
|
|
1860
|
-
};
|
|
1861
|
-
}
|
|
1862
|
-
function buildDirectoriesHealthCheck(directoryState, strictDirectories) {
|
|
1863
|
-
return {
|
|
1864
|
-
name: "directories",
|
|
1865
|
-
status: directoryState.missingDirs.length === 0 ? "ok" : "warn",
|
|
1866
|
-
ok: directoryState.missingDirs.length === 0,
|
|
1867
|
-
details: {
|
|
1868
|
-
required: directoryState.requiredDirs,
|
|
1869
|
-
optional: directoryState.optionalDirs,
|
|
1870
|
-
missing_required: directoryState.missingRequiredDirs,
|
|
1871
|
-
missing_optional: directoryState.missingOptionalDirs,
|
|
1872
|
-
missing: directoryState.missingDirs,
|
|
1873
|
-
strict_directories: strictDirectories,
|
|
1874
|
-
},
|
|
1875
|
-
};
|
|
1876
|
-
}
|
|
1877
|
-
function buildSettingsValuesHealthCheck(settingWarnings, statusRoleDiagnostics) {
|
|
1878
|
-
return {
|
|
1879
|
-
name: "settings_values",
|
|
1880
|
-
status: settingWarnings.length === 0 ? "ok" : "warn",
|
|
1881
|
-
ok: settingWarnings.length === 0,
|
|
1882
|
-
details: {
|
|
1883
|
-
warnings: settingWarnings,
|
|
1884
|
-
...(statusRoleDiagnostics.roleless_status_count > 0
|
|
1885
|
-
? { lifecycle_status_roles: statusRoleDiagnostics }
|
|
1886
|
-
: {}),
|
|
1887
|
-
},
|
|
1888
|
-
};
|
|
1889
|
-
}
|
|
1890
|
-
/** Preserve unknown-author totals for current and legacy scan payloads. */
|
|
1891
|
-
const resolveUnknownAuthorEventCount = (authorAttribution) => authorAttribution.unknown_event_count ?? 0;
|
|
1892
|
-
/** Preserve actionable-author semantics for current and legacy scan payloads. */
|
|
1893
|
-
const resolveActionableUnknownAuthorEventCount = (authorAttribution) => authorAttribution.actionable_unknown_event_count ??
|
|
1894
|
-
resolveUnknownAuthorEventCount(authorAttribution);
|
|
1895
|
-
function buildStorageHealthCheck(items, settings, historySummary, authorAttribution, staleInProgress, provenanceResolverOutcomes, provenanceInvalidValues) {
|
|
1896
|
-
const unknownAuthorEventCount = resolveUnknownAuthorEventCount(authorAttribution);
|
|
1897
|
-
const actionableUnknownAuthorEventCount = resolveActionableUnknownAuthorEventCount(authorAttribution);
|
|
1898
|
-
const hasAuthorEvents = unknownAuthorEventCount > 0;
|
|
1899
|
-
const hasActionableAuthorWarnings = actionableUnknownAuthorEventCount > 0;
|
|
1900
|
-
const hasStaleInProgressItems = staleInProgress.count > 0;
|
|
1901
|
-
return {
|
|
1902
|
-
name: "storage",
|
|
1903
|
-
status: historySummary.over_threshold.length === 0 &&
|
|
1904
|
-
historySummary.orphaned.length === 0 &&
|
|
1905
|
-
!hasActionableAuthorWarnings &&
|
|
1906
|
-
!hasStaleInProgressItems
|
|
1907
|
-
? "ok"
|
|
1908
|
-
: "warn",
|
|
1909
|
-
ok: historySummary.over_threshold.length === 0 &&
|
|
1910
|
-
historySummary.orphaned.length === 0 &&
|
|
1911
|
-
!hasActionableAuthorWarnings &&
|
|
1912
|
-
!hasStaleInProgressItems,
|
|
1913
|
-
details: {
|
|
1914
|
-
items: items.length,
|
|
1915
|
-
history_streams: historySummary.count,
|
|
1916
|
-
tombstones: {
|
|
1917
|
-
retention_policy: "retain_append_only",
|
|
1918
|
-
gc_enabled: false,
|
|
1919
|
-
count: historySummary.tombstones.length,
|
|
1920
|
-
ids: historySummary.tombstones.slice(0, 25),
|
|
1921
|
-
truncated: historySummary.tombstones.length > 25,
|
|
1922
|
-
},
|
|
1923
|
-
orphaned_history_streams: {
|
|
1924
|
-
count: historySummary.orphaned.length,
|
|
1925
|
-
ids: historySummary.orphaned.slice(0, 25),
|
|
1926
|
-
truncated: historySummary.orphaned.length > 25,
|
|
1927
|
-
},
|
|
1928
|
-
...(hasAuthorEvents ? { author_attribution: authorAttribution } : {}),
|
|
1929
|
-
...(hasStaleInProgressItems
|
|
1930
|
-
? { stale_in_progress: staleInProgress }
|
|
1931
|
-
: {}),
|
|
1932
|
-
...(provenanceResolverOutcomes.length > 0
|
|
1933
|
-
? { provenance_resolver_outcomes: provenanceResolverOutcomes }
|
|
1934
|
-
: {}),
|
|
1935
|
-
...(provenanceInvalidValues.length > 0
|
|
1936
|
-
? { provenance_invalid_values: provenanceInvalidValues }
|
|
1937
|
-
: {}),
|
|
1938
|
-
...(historySummary.max_entries !== null
|
|
1939
|
-
? {
|
|
1940
|
-
compact_policy: {
|
|
1941
|
-
enabled: settings.history.compact_policy.enabled,
|
|
1942
|
-
max_entries: historySummary.max_entries,
|
|
1943
|
-
trigger: settings.history.compact_policy.trigger,
|
|
1944
|
-
over_threshold_count: historySummary.over_threshold.length,
|
|
1945
|
-
over_threshold: historySummary.over_threshold,
|
|
1946
|
-
},
|
|
1947
|
-
}
|
|
1948
|
-
: {}),
|
|
1949
|
-
},
|
|
1950
|
-
};
|
|
1951
|
-
}
|
|
1952
|
-
function buildStaleInProgressHealthSummary(scan) {
|
|
1953
|
-
const warnings = scan.count === 0 ? [] : [`stale_in_progress_items:${scan.count}`];
|
|
1954
|
-
return { scan, warnings };
|
|
1955
|
-
}
|
|
1956
|
-
function collectHealthWarnings(params) {
|
|
1957
|
-
const warnings = [
|
|
1958
|
-
...params.directoryState.missingDirs.map((dir) => `missing_directory:${dir}`),
|
|
1959
|
-
...params.normalizedSettingsReadWarnings,
|
|
1960
|
-
...params.settingWarnings,
|
|
1961
|
-
...params.normalizedItemReadWarnings,
|
|
1962
|
-
...params.telemetryCheck.warnings,
|
|
1963
|
-
...params.extensionCheck.warnings,
|
|
1964
|
-
...params.historyPolicyWarnings,
|
|
1965
|
-
...params.historySummary.warnings,
|
|
1966
|
-
...params.authorAttributionWarnings,
|
|
1967
|
-
...params.staleInProgressWarnings,
|
|
1968
|
-
...params.provenanceWarnings,
|
|
1969
|
-
...params.locksCheck.warnings,
|
|
1970
|
-
...params.integrityCheck.warnings,
|
|
1971
|
-
...params.historyDriftCheck.warnings,
|
|
1972
|
-
...params.vectorizationCheck.warnings,
|
|
1973
|
-
...params.directoryState.hookWarnings,
|
|
1974
|
-
];
|
|
1975
|
-
return [...new Set(warnings)];
|
|
1976
|
-
}
|
|
1977
|
-
function extractHistoryDriftedCount(historyDriftCheck) {
|
|
1978
|
-
const counts = historyDriftCheck.check.details.counts;
|
|
1979
|
-
return typeof counts?.drifted === "number" ? counts.drifted : 0;
|
|
1980
|
-
}
|
|
1981
|
-
/** Associate warning producers with their owning checks so findings inherit the correct remediation and severity. */
|
|
1982
|
-
function buildHealthRemediationSources(params) {
|
|
1983
|
-
return {
|
|
1984
|
-
settings: params.normalizedSettingsReadWarnings,
|
|
1985
|
-
directories: params.directoryState.missingDirs
|
|
1986
|
-
.map((dir) => `missing_directory:${dir}`)
|
|
1987
|
-
.concat(params.directoryState.hookWarnings),
|
|
1988
|
-
settings_values: params.settingWarnings,
|
|
1989
|
-
telemetry: params.telemetryCheck.warnings,
|
|
1990
|
-
extensions: params.extensionCheck.warnings,
|
|
1991
|
-
storage: [
|
|
1992
|
-
...params.historyPolicyWarnings,
|
|
1993
|
-
...params.historySummary.warnings,
|
|
1994
|
-
...params.authorAttributionWarnings,
|
|
1995
|
-
...params.staleInProgressWarnings,
|
|
1996
|
-
...params.provenanceWarnings,
|
|
1997
|
-
],
|
|
1998
|
-
locks: params.locksCheck.warnings,
|
|
1999
|
-
integrity: [
|
|
2000
|
-
...params.normalizedItemReadWarnings,
|
|
2001
|
-
...params.integrityCheck.warnings,
|
|
2002
|
-
],
|
|
2003
|
-
history_drift: params.historyDriftCheck.warnings,
|
|
2004
|
-
vectorization: params.vectorizationCheck.warnings,
|
|
2005
|
-
};
|
|
2006
|
-
}
|
|
2007
|
-
/** Index every warning to exactly one health check, severity, and safe next action. */
|
|
2008
|
-
function buildHealthFindings(params) {
|
|
2009
|
-
const owners = new Map();
|
|
2010
|
-
for (const [check, warnings] of Object.entries(params.remediationSources)) {
|
|
2011
|
-
for (const warning of warnings) {
|
|
2012
|
-
if (!owners.has(warning))
|
|
2013
|
-
owners.set(warning, check);
|
|
2014
|
-
}
|
|
2015
|
-
}
|
|
2016
|
-
const checksByName = new Map(params.checks.map((check) => [check.name, check]));
|
|
2017
|
-
const findings = params.warnings.map((warning) => {
|
|
2018
|
-
const check = owners.get(warning) ?? "integrity";
|
|
2019
|
-
const code = resolveRemediation(warning)?.code ?? warningCode(warning);
|
|
2020
|
-
const details = checksByName.get(check)?.details;
|
|
2021
|
-
const remediationMap = typeof details?.remediation_map === "object" &&
|
|
2022
|
-
details.remediation_map !== null
|
|
2023
|
-
? details.remediation_map
|
|
2024
|
-
: {};
|
|
2025
|
-
const remediation = remediationMap[code];
|
|
2026
|
-
const severity = isAdvisoryHealthWarning(warning, params.requireMergeDrivers)
|
|
2027
|
-
? "advisory"
|
|
2028
|
-
: "gate_failing";
|
|
2029
|
-
return {
|
|
2030
|
-
warning,
|
|
2031
|
-
code,
|
|
2032
|
-
check,
|
|
2033
|
-
severity,
|
|
2034
|
-
...(typeof remediation === "string"
|
|
2035
|
-
? { remediation }
|
|
2036
|
-
: severity === "gate_failing"
|
|
2037
|
-
? { disposition: "no_safe_automatic_remediation" }
|
|
2038
|
-
: {}),
|
|
2039
|
-
};
|
|
2040
|
-
});
|
|
2041
|
-
return findings;
|
|
2042
|
-
}
|
|
2043
|
-
function rewriteBulkHealthRemediation(params) {
|
|
2044
|
-
if (params.check.name === "history_drift" && params.historyDriftedCount > 1) {
|
|
2045
|
-
for (const code of Object.keys(params.remediationMap)) {
|
|
2046
|
-
if (code !== "history_drift_merge_receipt" &&
|
|
2047
|
-
code !== "history_drift_version_skew") {
|
|
2048
|
-
params.remediationMap[code] = "pm history-repair --all";
|
|
2049
|
-
}
|
|
2050
|
-
}
|
|
2051
|
-
}
|
|
2052
|
-
if (params.check.name === "storage" && params.overThresholdCount > 1) {
|
|
2053
|
-
for (const code of Object.keys(params.remediationMap)) {
|
|
2054
|
-
params.remediationMap[code] = "pm history-compact --all-streams";
|
|
2055
|
-
}
|
|
2056
|
-
}
|
|
2057
|
-
}
|
|
2058
|
-
function attachHealthRemediationMaps(params) {
|
|
2059
|
-
for (const check of params.checks) {
|
|
2060
|
-
const remediationMap = buildRemediationMap(params.remediationSources[check.name]);
|
|
2061
|
-
rewriteBulkHealthRemediation({
|
|
2062
|
-
check,
|
|
2063
|
-
remediationMap,
|
|
2064
|
-
historyDriftedCount: params.historyDriftedCount,
|
|
2065
|
-
overThresholdCount: params.overThresholdCount,
|
|
2066
|
-
});
|
|
2067
|
-
if (Object.keys(remediationMap).length > 0) {
|
|
2068
|
-
check.details = { ...check.details, remediation_map: remediationMap };
|
|
2069
|
-
}
|
|
2070
|
-
}
|
|
2071
|
-
}
|
|
2072
|
-
/** Attribute drift to merge receipts only when read-only history repair proves their exact current snapshot. */
|
|
2073
|
-
async function correlateMergeReceiptHistoryDriftItems(params) {
|
|
2074
|
-
if (params.gitWorkspaceRoot === null ||
|
|
2075
|
-
params.pendingMergeReceipts.length === 0) {
|
|
2076
|
-
return [];
|
|
2077
|
-
}
|
|
2078
|
-
const details = params.historyDriftCheck.check.details;
|
|
2079
|
-
const hashMismatches = Array.isArray(details.hash_mismatches)
|
|
2080
|
-
? details.hash_mismatches.filter((entry) => typeof entry === "string")
|
|
2081
|
-
: [];
|
|
2082
|
-
const unsafeStreamIds = new Set([
|
|
2083
|
-
details.missing_streams,
|
|
2084
|
-
details.unreadable_streams,
|
|
2085
|
-
details.chain_mismatches,
|
|
2086
|
-
].flatMap((value) => (Array.isArray(value) ? value : [])));
|
|
2087
|
-
const cloneLocalReceiptsByItem = new Map();
|
|
2088
|
-
for (const receipt of params.pendingMergeReceipts) {
|
|
2089
|
-
if (receipt.evidence_source !== "clone_local")
|
|
2090
|
-
continue;
|
|
2091
|
-
const receipts = cloneLocalReceiptsByItem.get(receipt.item_id) ?? [];
|
|
2092
|
-
receipts.push(receipt);
|
|
2093
|
-
cloneLocalReceiptsByItem.set(receipt.item_id, receipts);
|
|
2094
|
-
}
|
|
2095
|
-
const attributed = [];
|
|
2096
|
-
for (const id of hashMismatches) {
|
|
2097
|
-
if (unsafeStreamIds.has(id))
|
|
2098
|
-
continue;
|
|
2099
|
-
const receipts = cloneLocalReceiptsByItem.get(id);
|
|
2100
|
-
if (!receipts || receipts.length === 0)
|
|
2101
|
-
continue;
|
|
2102
|
-
try {
|
|
2103
|
-
await runHistoryRepair(id, {
|
|
2104
|
-
dryRun: true,
|
|
2105
|
-
mergeReceiptProof: {
|
|
2106
|
-
gitWorkspaceRoot: params.gitWorkspaceRoot,
|
|
2107
|
-
receipts,
|
|
2108
|
-
},
|
|
2109
|
-
}, params.global);
|
|
2110
|
-
// An unforced proof-bearing preview rejects untrusted evidence before returning.
|
|
2111
|
-
attributed.push(id);
|
|
2112
|
-
}
|
|
2113
|
-
catch {
|
|
2114
|
-
// Fail closed: generic history-repair guidance remains authoritative.
|
|
2115
|
-
}
|
|
2116
|
-
}
|
|
2117
|
-
return [...new Set(attributed)].sort((left, right) => left.localeCompare(right));
|
|
2118
|
-
}
|
|
2119
|
-
function applyMergeReceiptHistoryDriftAttribution(historyDriftCheck, attributedItems) {
|
|
2120
|
-
const attributed = new Set(attributedItems);
|
|
2121
|
-
historyDriftCheck.warnings = [
|
|
2122
|
-
...historyDriftCheck.warnings.filter((warning) => {
|
|
2123
|
-
if (!warning.startsWith("history_drift_hash_mismatch:"))
|
|
2124
|
-
return true;
|
|
2125
|
-
return !attributed.has(warning.slice(warning.indexOf(":") + 1));
|
|
2126
|
-
}),
|
|
2127
|
-
...attributedItems.map((id) => `history_drift_merge_receipt:${id}`),
|
|
2128
|
-
].sort((left, right) => left.localeCompare(right));
|
|
2129
|
-
historyDriftCheck.check.details = {
|
|
2130
|
-
...historyDriftCheck.check.details,
|
|
2131
|
-
merge_receipt_attributed_items: attributedItems,
|
|
2132
|
-
};
|
|
2133
|
-
}
|
|
2134
|
-
function projectHealthResult(result, options, summaryMode) {
|
|
2135
|
-
const warningCount = result.warning_count ?? result.warnings.length;
|
|
2136
|
-
const boundedResult = {
|
|
2137
|
-
...result,
|
|
2138
|
-
warning_count: warningCount,
|
|
2139
|
-
warning_limit: HEALTH_WARNING_LIMIT,
|
|
2140
|
-
warnings_truncated: warningCount > HEALTH_WARNING_LIMIT,
|
|
2141
|
-
warnings: result.warnings.slice(0, HEALTH_WARNING_LIMIT),
|
|
2142
|
-
findings: (result.findings ?? []).filter((finding) => result.warnings
|
|
2143
|
-
.slice(0, HEALTH_WARNING_LIMIT)
|
|
2144
|
-
.includes(finding.warning) ||
|
|
2145
|
-
result.failed_because.includes(finding.warning)),
|
|
2146
|
-
};
|
|
2147
|
-
const projected = summaryMode
|
|
2148
|
-
? applySummaryHealthProjection(boundedResult)
|
|
2149
|
-
: options.brief === true
|
|
2150
|
-
? applyBriefHealthProjection(boundedResult)
|
|
2151
|
-
: boundedResult;
|
|
2152
|
-
return {
|
|
2153
|
-
...projected,
|
|
2154
|
-
warning_count: warningCount,
|
|
2155
|
-
warning_limit: HEALTH_WARNING_LIMIT,
|
|
2156
|
-
warnings_truncated: warningCount > projected.warnings.length,
|
|
2157
|
-
...(projected.projection
|
|
2158
|
-
? {
|
|
2159
|
-
projection: {
|
|
2160
|
-
...projected.projection,
|
|
2161
|
-
warning_count: warningCount,
|
|
2162
|
-
warnings_truncated: warningCount > projected.warnings.length,
|
|
2163
|
-
},
|
|
2164
|
-
}
|
|
2165
|
-
: {}),
|
|
2166
|
-
};
|
|
2167
|
-
}
|
|
2168
|
-
/** Implements run health for the public runtime surface of this module. */
|
|
2169
|
-
export async function runHealth(global, options = {}) {
|
|
2170
|
-
const pmRoot = resolvePmRoot(process.cwd(), global.path);
|
|
2171
|
-
await assertInitializedTracker(pmRoot);
|
|
2172
|
-
const settingsPath = getSettingsPath(pmRoot);
|
|
2173
|
-
const { settings, warnings: settingsReadWarnings } = await readSettingsWithMetadata(pmRoot);
|
|
2174
|
-
const normalizedSettingsReadWarnings = [...new Set(settingsReadWarnings)];
|
|
2175
|
-
const typeRegistry = resolveItemTypeRegistry(settings, getActiveExtensionRegistrations());
|
|
2176
|
-
const strictDirectories = options.strictDirectories === true;
|
|
2177
|
-
const strictExit = options.strictExit === true || options.failOnWarn === true;
|
|
2178
|
-
const requireMergeDrivers = options.requireMergeDrivers === true || strictExit;
|
|
2179
|
-
const refreshPolicy = resolveVectorRefreshPolicy(options);
|
|
2180
|
-
const directoryState = await scanHealthDirectories(pmRoot, typeRegistry, strictDirectories);
|
|
2181
|
-
const settingsValueWarnings = validateSettingsValues(settings);
|
|
2182
|
-
const telemetryCheck = await buildTelemetryCheck(settings, {
|
|
2183
|
-
checkTelemetry: options.checkTelemetry === true,
|
|
2184
|
-
});
|
|
2185
|
-
const extensionCheck = await buildExtensionCheck(pmRoot, settings, Boolean(global.noExtensions));
|
|
2186
|
-
const skipPolicy = resolveHealthSkipPolicy(options);
|
|
2187
|
-
const itemReadWarnings = [];
|
|
2188
|
-
const items = await readHealthItems({
|
|
2189
|
-
pmRoot,
|
|
2190
|
-
settings,
|
|
2191
|
-
typeRegistry,
|
|
2192
|
-
skipPolicy,
|
|
2193
|
-
itemReadWarnings,
|
|
2194
|
-
});
|
|
2195
|
-
const itemsWithBody = items;
|
|
2196
|
-
const statusRoleDiagnostics = inspectStatusRoleAssignments(resolveRuntimeStatusRegistry(settings.schema), items);
|
|
2197
|
-
const settingWarnings = [
|
|
2198
|
-
...settingsValueWarnings,
|
|
2199
|
-
...buildStatusRoleWarnings(statusRoleDiagnostics),
|
|
2200
|
-
];
|
|
2201
|
-
const historyPolicy = skipPolicy.skipDrift
|
|
2202
|
-
? { warnings: [] }
|
|
2203
|
-
: await enforceHistoryStreamPolicyForItems({
|
|
2204
|
-
pmRoot,
|
|
2205
|
-
settings,
|
|
2206
|
-
itemIds: items.map((item) => item.id),
|
|
2207
|
-
commandLabel: "health",
|
|
2208
|
-
});
|
|
2209
|
-
const historySummary = await countHistoryStreams(pmRoot, settings.history.compact_policy, await listStoredItemDocumentIds(pmRoot));
|
|
2210
|
-
const authorAttribution = await scanHistoryAuthorAttribution(pmRoot, 20, options.verboseAuthorEvents === true);
|
|
2211
|
-
const actionableUnknownAuthorEventCount = resolveActionableUnknownAuthorEventCount(authorAttribution);
|
|
2212
|
-
const authorAttributionWarnings = actionableUnknownAuthorEventCount > 0
|
|
2213
|
-
? [`history_unknown_author_events:${actionableUnknownAuthorEventCount}`]
|
|
2214
|
-
: [];
|
|
2215
|
-
const staleInProgress = buildStaleInProgressHealthSummary(await scanStaleInProgressItems(pmRoot, items, {
|
|
2216
|
-
in_progress_status: settings.schema.workflow.in_progress_status,
|
|
2217
|
-
threshold_hours: settings.mutation_guard.stale_in_progress_hours,
|
|
2218
|
-
}));
|
|
2219
|
-
const provenanceResolverHealth = await scanProvenanceResolverHealth(pmRoot);
|
|
2220
|
-
const provenanceResolverOutcomes = provenanceResolverHealth.outcomes;
|
|
2221
|
-
const provenanceInvalidValues = provenanceResolverHealth.invalid_values;
|
|
2222
|
-
const provenanceWarnings = provenanceResolverHealth.warnings;
|
|
2223
|
-
const locksCheck = await buildLocksCheck(pmRoot);
|
|
2224
|
-
const integrityCheck = skipPolicy.skipIntegrity && !requireMergeDrivers
|
|
2225
|
-
? {
|
|
2226
|
-
...buildSkippedHealthCheck("integrity"),
|
|
2227
|
-
gitWorkspaceRoot: null,
|
|
2228
|
-
pendingMergeReceipts: [],
|
|
2229
|
-
}
|
|
2230
|
-
: await buildIntegrityCheck(pmRoot, typeRegistry.type_to_folder, settings.schema, requireMergeDrivers, items);
|
|
2231
|
-
const historyDriftCheck = skipPolicy.skipDrift
|
|
2232
|
-
? buildSkippedHealthCheck("history_drift")
|
|
2233
|
-
: await buildHistoryDriftCheck({
|
|
2234
|
-
pmRoot,
|
|
2235
|
-
items: itemsWithBody,
|
|
2236
|
-
settings,
|
|
2237
|
-
typeRegistry,
|
|
2238
|
-
itemReadWarnings,
|
|
2239
|
-
});
|
|
2240
|
-
const normalizedItemReadWarnings = [...new Set(itemReadWarnings)];
|
|
2241
|
-
const mergeReceiptAttributedHistoryDriftItems = await correlateMergeReceiptHistoryDriftItems({
|
|
2242
|
-
gitWorkspaceRoot: integrityCheck.gitWorkspaceRoot,
|
|
2243
|
-
pendingMergeReceipts: integrityCheck.pendingMergeReceipts,
|
|
2244
|
-
historyDriftCheck,
|
|
2245
|
-
global,
|
|
2246
|
-
});
|
|
2247
|
-
applyMergeReceiptHistoryDriftAttribution(historyDriftCheck, mergeReceiptAttributedHistoryDriftItems);
|
|
2248
|
-
const vectorizationCheck = skipPolicy.skipVectors
|
|
2249
|
-
? buildSkippedHealthCheck("vectorization")
|
|
2250
|
-
: await buildVectorizationCheck(pmRoot, settings, itemsWithBody, refreshPolicy, options.verboseStaleItems === true);
|
|
2251
|
-
const checks = [
|
|
2252
|
-
buildSettingsHealthCheck(settingsPath, settings, normalizedSettingsReadWarnings),
|
|
2253
|
-
buildDirectoriesHealthCheck(directoryState, strictDirectories),
|
|
2254
|
-
buildSettingsValuesHealthCheck(settingWarnings, statusRoleDiagnostics),
|
|
2255
|
-
telemetryCheck.check,
|
|
2256
|
-
extensionCheck.check,
|
|
2257
|
-
buildStorageHealthCheck(items, settings, historySummary, authorAttribution, staleInProgress.scan, provenanceResolverOutcomes, provenanceInvalidValues),
|
|
2258
|
-
locksCheck.check,
|
|
2259
|
-
integrityCheck.check,
|
|
2260
|
-
historyDriftCheck.check,
|
|
2261
|
-
vectorizationCheck.check,
|
|
2262
|
-
];
|
|
2263
|
-
const normalizedWarnings = collectHealthWarnings({
|
|
2264
|
-
directoryState,
|
|
2265
|
-
normalizedSettingsReadWarnings,
|
|
2266
|
-
settingWarnings,
|
|
2267
|
-
normalizedItemReadWarnings,
|
|
2268
|
-
telemetryCheck,
|
|
2269
|
-
extensionCheck,
|
|
2270
|
-
historyPolicyWarnings: historyPolicy.warnings,
|
|
2271
|
-
historySummary,
|
|
2272
|
-
authorAttributionWarnings,
|
|
2273
|
-
staleInProgressWarnings: staleInProgress.warnings,
|
|
2274
|
-
provenanceWarnings,
|
|
2275
|
-
locksCheck,
|
|
2276
|
-
integrityCheck,
|
|
2277
|
-
historyDriftCheck,
|
|
2278
|
-
vectorizationCheck,
|
|
2279
|
-
});
|
|
2280
|
-
const remediationSources = buildHealthRemediationSources({
|
|
2281
|
-
directoryState,
|
|
2282
|
-
normalizedSettingsReadWarnings,
|
|
2283
|
-
settingWarnings,
|
|
2284
|
-
normalizedItemReadWarnings,
|
|
2285
|
-
telemetryCheck,
|
|
2286
|
-
extensionCheck,
|
|
2287
|
-
historyPolicyWarnings: historyPolicy.warnings,
|
|
2288
|
-
historySummary,
|
|
2289
|
-
authorAttributionWarnings,
|
|
2290
|
-
staleInProgressWarnings: staleInProgress.warnings,
|
|
2291
|
-
provenanceWarnings,
|
|
2292
|
-
locksCheck,
|
|
2293
|
-
integrityCheck,
|
|
2294
|
-
historyDriftCheck,
|
|
2295
|
-
vectorizationCheck,
|
|
2296
|
-
});
|
|
2297
|
-
attachHealthRemediationMaps({
|
|
2298
|
-
checks,
|
|
2299
|
-
remediationSources,
|
|
2300
|
-
historyDriftedCount: extractHistoryDriftedCount(historyDriftCheck),
|
|
2301
|
-
overThresholdCount: historySummary.over_threshold.length,
|
|
2302
|
-
});
|
|
2303
|
-
// Telemetry is an opt-out, non-critical observability feature. Its operational
|
|
2304
|
-
// state (queue backlog, unreachable endpoint, corrupt local state) is advisory:
|
|
2305
|
-
// it must never flip overall project health to not-ok. Such warnings are still
|
|
2306
|
-
// surfaced in `warnings` and the telemetry check's own `warn` status.
|
|
2307
|
-
const blockingWarnings = normalizedWarnings.filter((warning) => !isAdvisoryHealthWarning(warning, requireMergeDrivers));
|
|
2308
|
-
const findings = buildHealthFindings({
|
|
2309
|
-
warnings: normalizedWarnings,
|
|
2310
|
-
checks,
|
|
2311
|
-
remediationSources,
|
|
2312
|
-
requireMergeDrivers,
|
|
2313
|
-
});
|
|
2314
|
-
const failingChecks = new Set(findings.filter((finding) => finding.severity === "gate_failing").map((finding) => finding.check));
|
|
2315
|
-
const warningChecks = new Set(findings.map((finding) => finding.check));
|
|
2316
|
-
for (const check of checks) {
|
|
2317
|
-
check.ok = !failingChecks.has(check.name);
|
|
2318
|
-
if (warningChecks.has(check.name))
|
|
2319
|
-
check.status = "warn";
|
|
2320
|
-
}
|
|
2321
|
-
const result = {
|
|
2322
|
-
ok: blockingWarnings.length === 0,
|
|
2323
|
-
verdict: {
|
|
2324
|
-
authority: "ok",
|
|
2325
|
-
...(strictExit ? { strict_exit: true } : {}),
|
|
2326
|
-
...(requireMergeDrivers ? { require_merge_drivers: true } : {}),
|
|
2327
|
-
exit_code: strictExit && blockingWarnings.length > 0 ? EXIT_CODE.GENERIC_FAILURE : 0,
|
|
2328
|
-
},
|
|
2329
|
-
checks,
|
|
2330
|
-
warnings: normalizedWarnings,
|
|
2331
|
-
findings,
|
|
2332
|
-
failed_because: blockingWarnings,
|
|
2333
|
-
generated_at: nowIso(),
|
|
2334
|
-
};
|
|
2335
|
-
return projectHealthResult(result, options, skipPolicy.summaryMode);
|
|
2336
|
-
}
|
|
2337
|
-
/** Public contract for test only health command, shared by SDK and presentation-layer consumers. */
|
|
2338
|
-
export const _testOnlyHealthCommand = {
|
|
2339
|
-
buildHierarchyIntegrityWarnings,
|
|
2340
|
-
buildExtensionHealthTriageSummary,
|
|
2341
|
-
buildHealthFindings,
|
|
2342
|
-
buildCapabilityContractMetadata,
|
|
2343
|
-
buildStaleInProgressHealthSummary,
|
|
2344
|
-
buildVectorizationProviderDetails,
|
|
2345
|
-
collectUnknownCapabilityGuidance,
|
|
2346
|
-
isAdvisoryHealthWarning,
|
|
2347
|
-
isDirectory,
|
|
2348
|
-
isExpectedUnmanagedExtension,
|
|
2349
|
-
listItemDocumentPaths,
|
|
2350
|
-
normalizeEndpointForDisplay,
|
|
2351
|
-
normalizeExtensionNameForMatch,
|
|
2352
|
-
parseTelemetryQueue,
|
|
2353
|
-
probeTelemetryEndpointHealth,
|
|
2354
|
-
projectHealthResult,
|
|
2355
|
-
resolveActionableUnknownAuthorEventCount,
|
|
2356
|
-
resolveHealthSkipPolicy,
|
|
2357
|
-
resolveUnknownAuthorEventCount,
|
|
2358
|
-
resolveVectorRefreshPolicy,
|
|
2359
|
-
selectStaleItemDetail,
|
|
2360
|
-
summarizeHealthCheckDetails,
|
|
2361
|
-
summarizeExtensionList,
|
|
2362
|
-
summarizeRecordList,
|
|
2363
|
-
summarizeStringList,
|
|
2364
|
-
telemetryEnvFlagEnabled,
|
|
2365
|
-
warningCode,
|
|
2366
|
-
};
|
|
1
|
+
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="205d2dd3-72e4-5ed2-b4c9-cf5000ea8e5f")}catch(e2){}})();import fs from"node:fs/promises";import path from"node:path";import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{isTerminalStatus}from"../../core/item/status.js";import{resolveItemTypeRegistry}from"../../core/item/type-registry.js";import{resolveRuntimeStatusRegistry}from"../../core/schema/runtime-schema.js";import{isFileMissingError,readFileIfExists}from"../../core/fs/fs-utils.js";import{activateExtensions,getActiveExtensionRegistrations,loadExtensions,runActiveOnReadHooks}from"../../core/extensions/index.js";import{collectRegisteredItemFieldNames}from"../../core/extensions/item-fields.js";import{KNOWN_EXTENSION_CAPABILITIES}from"../../core/extensions/loader.js";import{enforceHistoryStreamPolicyForItems}from"../../core/history/history-stream-policy.js";import{scanHistoryDrift}from"../../core/history/drift-scan.js";import{scanLockHealth}from"../../core/lock/lock-gc.js";import{readVectorizationStatusLedger,refreshSemanticEmbeddingsForMutatedItems}from"../../core/search/cache.js";import{resolveEmbeddingProviders,resolveProviderConfigSource}from"../../core/search/providers.js";import{resolveSettingsWithSemanticRuntimeDefaults}from"../../core/search/semantic-defaults.js";import{collectStaleVectorizationIds}from"../../core/search/staleness.js";import{buildVectorizationEmbeddingIdentity,hasVectorizationEmbeddingIdentityChanged}from"../../core/search/vectorization-metadata.js";import{resolveVectorStores}from"../../core/search/vector-stores.js";import{EXIT_CODE,PM_CORE_REQUIRED_SUBDIRS,TYPE_TO_FOLDER}from"../../core/shared/constants.js";import{findFirstMergeConflictMarker}from"../../core/shared/conflict-markers.js";import{PmCliError}from"../../core/shared/errors.js";import{toNonEmptyStringOrUndefined}from"../../core/shared/primitives.js";import{nowIso}from"../../core/shared/time.js";import{parseItemDocument}from"../../core/item/item-format.js";import{effectiveItemFormatVersion,scanItemFormatVersions}from"../../core/item/item-format-version.js";import{listAllItemMetadataLight,listAllItemMetadataWithBody}from"../../core/store/item-store.js";import{PM_TELEMETRY_SOURCE_CONTEXT_VALUES,TELEMETRY_MAX_QUEUE_ENTRY_ATTEMPTS,TELEMETRY_SCHEMA_VERSION}from"../../core/telemetry/runtime.js";import{getItemFormatFromPath,getSettingsPath,ITEM_FILE_EXTENSIONS,resolveGlobalPmRoot,resolvePmRoot,resolveWorkspaceRoot}from"../../core/store/paths.js";import{readSettingsWithMetadata}from"../../core/store/settings.js";import{buildRemediationMap,resolveRemediation}from"../../core/diagnostics/remediation.js";import{scanExtensionHostVersions}from"./extension-host-version.js";import{scanHistoryAuthorAttribution}from"../author-attribution.js";import{readManagedExtensionState}from"../extension.js";import{scanProvenanceResolverHealth}from"./provenance-health.js";import{applyStoredExtensionMigrationState}from"../extension/migrations.js";import{inspectExtensionAuthorManifest}from"../extension/author-manifest.js";import{buildCapabilityContractMetadata,buildRegistrationCollisionRemediation,collectUnknownCapabilityGuidance}from"../extension/doctor.js";import{scanStaleInProgressItems}from"./stale-work.js";import{scanTrackedRuntimeCache}from"./tracked-runtime-cache.js";import{auditMergeDriverConfiguration,findGitWorkspaceRoot}from"../merge/install.js";import{inspectMergeReceiptEvidence,partitionMergeReceipts}from"../merge/receipts.js";import{classifyHistoryMergeReceiptReferences,extractHistoryMergeReceiptDispositions,extractHistoryMergeReceiptReferences}from"./merge-receipt-history.js";import{runHistoryRepair}from"../history-repair.js";import{resolveWorkspaceRelationshipKindRegistry}from"../graph/assembly.js";import{analyzeHierarchyIntegrity}from"../graph/hierarchy-integrity.js";import{buildStatusRoleWarnings,inspectStatusRoleAssignments}from"./status-role-diagnostics.js";const PM_TELEMETRY_SOURCE_CONTEXT_SET=new Set(PM_TELEMETRY_SOURCE_CONTEXT_VALUES);const STALE_VECTORIZATION_SUMMARY_LIMIT=25;const BRIEF_HEALTH_DETAIL_LIMIT=8;const HEALTH_WARNING_LIMIT=100;const TELEMETRY_QUEUE_RELATIVE_PATH=path.join("runtime","telemetry","events.jsonl");const TELEMETRY_STATE_RELATIVE_PATH=path.join("runtime","telemetry","state.json");const TELEMETRY_ENDPOINT_PROBE_TIMEOUT_MS=2500;const TELEMETRY_QUEUE_HIGH_WATER_MARK=500;const TELEMETRY_QUEUE_HIGH_RETRY_THRESHOLD=TELEMETRY_MAX_QUEUE_ENTRY_ATTEMPTS-3;const TELEMETRY_SERVER_MAX_SCHEMA_VERSION_HEADERS=["x-pm-telemetry-max-schema-version","x-pm-telemetry-max-version"];function isAdvisoryHealthWarning(warning,requireMergeDrivers=false){return warning.startsWith("telemetry_")||warning.startsWith("history_stream_over_compact_threshold:")||warning.startsWith("integrity_legacy_hierarchy_")||warning.startsWith("stale_in_progress_items:")||warning.startsWith("provenance_resolver_zero_success:")||warning.startsWith("provenance_value_domain_invalid:")||!requireMergeDrivers&&warning.startsWith("merge_driver_configuration_missing:")}function warningCode(value){const normalized=value.trim();const separator=normalized.indexOf(":");if(separator===-1){return normalized}return normalized.slice(0,separator)}function normalizeExtensionNameForMatch(value){return value.trim().toLowerCase()}function isExpectedUnmanagedExtension(name,directory){const normalizedName=normalizeExtensionNameForMatch(name);const normalizedDirectory=normalizeExtensionNameForMatch(directory);if(normalizedName.startsWith("builtin-")){return true}return normalizedDirectory==="beads"||normalizedDirectory==="todos"}async function isDirectory(targetPath){try{const stats=await fs.stat(targetPath);return stats.isDirectory()}catch{return false}}async function listStoredItemDocumentIds(pmRoot){const directories=(await fs.readdir(pmRoot,{withFileTypes:true})).filter(entry=>entry.isDirectory());const filesByDirectory=await Promise.all(directories.map(entry=>fs.readdir(path.join(pmRoot,entry.name),{withFileTypes:true})));return new Set(filesByDirectory.flatMap(entries=>entries.filter(entry=>entry.isFile()).filter(entry=>ITEM_FILE_EXTENSIONS.some(extension=>entry.name.endsWith(extension))).map(entry=>path.parse(entry.name).name)))}async function inspectHistoryStream(streamPath,itemId,compactPolicy,liveItemIds){const warnings=await runActiveOnReadHooks({path:streamPath,scope:"project"});const needsClassification=itemId!=="_workspace"&&!liveItemIds.has(itemId);if(!compactPolicy.enabled&&!needsClassification){return{warnings,overThreshold:false,classification:"live"}}let raw;try{raw=await fs.readFile(streamPath,"utf8")}catch{return{warnings,overThreshold:false,classification:"unreadable"}}let classification="live";if(needsClassification){const lastLine=raw.split(/\r?\n/).map(line=>line.trim()).filter(Boolean).at(-1);try{const lastEntry=JSON.parse(lastLine??"{}");classification=lastEntry.op==="delete"?"tombstone":"orphaned"}catch{classification="orphaned"}}const entryCount=compactPolicy.enabled?raw.split(/\r?\n/).filter(line=>line.trim().length>0).length:0;return{warnings,overThreshold:compactPolicy.enabled&&entryCount>compactPolicy.max_entries,classification}}async function countHistoryStreams(pmRoot,compactPolicy,liveItemIds){const historyDir=path.join(pmRoot,"history");if(!await isDirectory(historyDir)){return{count:0,warnings:[],over_threshold:[],max_entries:null,tombstones:[],orphaned:[]}}const historyFiles=(await fs.readdir(historyDir)).filter(entry=>entry.endsWith(".jsonl")).sort((left,right)=>left.localeCompare(right));const policyActive=compactPolicy.enabled;const maxEntries=policyActive?compactPolicy.max_entries:null;const warnings=[];const overThreshold=[];const tombstones=[];const orphaned=[];for(const fileName of historyFiles){const streamPath=path.join(historyDir,fileName);const itemId=fileName.slice(0,-".jsonl".length);const inspection=await inspectHistoryStream(streamPath,itemId,compactPolicy,liveItemIds);warnings.push(...inspection.warnings);if(inspection.classification==="tombstone")tombstones.push(itemId);if(inspection.classification==="orphaned")orphaned.push(itemId);if(inspection.overThreshold)overThreshold.push(itemId)}return{count:historyFiles.length,warnings:[...warnings,...overThreshold.map(id=>`history_stream_over_compact_threshold:${id}`),...orphaned.map(id=>`history_orphaned_stream:${id}`)],over_threshold:overThreshold,max_entries:maxEntries,tombstones,orphaned}}function normalizeRelativePath(pmRoot,targetPath){return path.relative(pmRoot,targetPath).replaceAll("\\","/")}async function listItemDocumentPaths(pmRoot,typeToFolder){const folders=[...new Set(Object.values(typeToFolder))].sort((left,right)=>left.localeCompare(right));const itemPaths=[];for(const folder of folders){const directoryPath=path.join(pmRoot,folder);let entries=[];try{entries=await fs.readdir(directoryPath)}catch(error){if(typeof error==="object"&&error!==null&&"code"in error&&isFileMissingError(error)){continue}continue}for(const entry of entries){if(!ITEM_FILE_EXTENSIONS.some(extension=>entry.toLowerCase().endsWith(extension))){continue}itemPaths.push(path.join(directoryPath,entry))}}itemPaths.sort((left,right)=>normalizeRelativePath(pmRoot,left).localeCompare(normalizeRelativePath(pmRoot,right)));return itemPaths}function shouldReportHistoryDirectoryUnreadable(error){return!(typeof error==="object"&&error!==null&&"code"in error&&isFileMissingError(error))}async function scanItemIntegrity(pmRoot,typeToFolder,schema){const paths=await listItemDocumentPaths(pmRoot,typeToFolder);const unreadable=[];const conflictMarkers=[];const parseFailures=[];const formatVersions=[];const extensionFieldNames=collectRegisteredItemFieldNames(getActiveExtensionRegistrations());for(const itemPath of paths){const relativePath=normalizeRelativePath(pmRoot,itemPath);let raw;try{raw=await fs.readFile(itemPath,"utf8")}catch{unreadable.push(relativePath);continue}const conflictMarker=findFirstMergeConflictMarker(raw);if(conflictMarker){conflictMarkers.push({path:relativePath,...conflictMarker});continue}try{const parsed=parseItemDocument(raw,{format:getItemFormatFromPath(itemPath),schema,extensionFieldNames});formatVersions.push({ref:relativePath,version:effectiveItemFormatVersion(parsed.metadata)})}catch{parseFailures.push(relativePath)}}return{paths,unreadable,conflictMarkers,parseFailures,formatVersions}}async function scanHistoryIntegrity(pmRoot){const historyDir=path.join(pmRoot,"history");const unreadable=[];const conflictMarkers=[];const invalidJson=[];const mergeReceiptReferences=[];const mergeReceiptDispositions=[];let files=[];try{files=(await fs.readdir(historyDir)).filter(entry=>entry.endsWith(".jsonl")).sort((left,right)=>left.localeCompare(right))}catch(error){if(shouldReportHistoryDirectoryUnreadable(error))unreadable.push("history")}for(const fileName of files){const itemId=fileName.slice(0,-".jsonl".length);let raw;try{raw=await fs.readFile(path.join(historyDir,fileName),"utf8")}catch{unreadable.push(itemId);continue}const conflictMarker=findFirstMergeConflictMarker(raw);if(conflictMarker){conflictMarkers.push({id:itemId,...conflictMarker});continue}raw.split(/\r?\n/).forEach((line,index)=>{if(!line.trim())return;try{const parsed=JSON.parse(line);mergeReceiptReferences.push(...extractHistoryMergeReceiptReferences(parsed,itemId).map(reference=>({itemId,line:index+1,...reference})));mergeReceiptDispositions.push(...extractHistoryMergeReceiptDispositions(parsed,itemId,index+1))}catch{invalidJson.push({id:itemId,line:index+1})}})}return{files,unreadable,conflictMarkers,invalidJson,mergeReceiptReferences,mergeReceiptDispositions}}function buildHierarchyIntegrityWarnings(analysis){return[...analysis.cycles.map(cycle=>cycle.legacy_terminal?`integrity_legacy_hierarchy_cycle:${cycle.item_ids.join(",")}`:`integrity_hierarchy_cycle:${cycle.item_ids.join(",")}`),...analysis.cardinality_violations.map(finding=>finding.legacy_terminal?`integrity_legacy_hierarchy_cardinality:${finding.child_id}`:`integrity_hierarchy_cardinality:${finding.child_id}`),...analysis.divergences.map(finding=>finding.legacy_terminal?`integrity_legacy_hierarchy_divergence:${finding.child_id}`:`integrity_hierarchy_divergence:${finding.child_id}`)]}function buildMergeReceiptEvidenceWarnings(params){const warnings=[];if(params.invalidEvidenceCount>0){warnings.push(`merge_receipt_evidence_invalid:${params.invalidEvidenceCount}`)}if(params.missingHistoryReferenceCount>0){warnings.push(`merge_receipt_history_reference_missing:${params.missingHistoryReferenceCount}`)}return warnings}async function buildIntegrityCheck(pmRoot,typeToFolder,schema,requireMergeDrivers,items){const itemScan=await scanItemIntegrity(pmRoot,typeToFolder,schema);const historyScan=await scanHistoryIntegrity(pmRoot);const formatVersionScan=scanItemFormatVersions(itemScan.formatVersions);const statusRegistry=resolveRuntimeStatusRegistry(schema);const hierarchyIntegrity=analyzeHierarchyIntegrity(items,status=>isTerminalStatus(status,statusRegistry),resolveWorkspaceRelationshipKindRegistry());const trackedRuntimeCache=await scanTrackedRuntimeCache(pmRoot);const gitWorkspaceRoot=await findGitWorkspaceRoot(pmRoot);const mergeDriverAudit=gitWorkspaceRoot===null?null:await auditMergeDriverConfiguration(gitWorkspaceRoot);const mergeReceiptEvidence=await inspectMergeReceiptEvidence(gitWorkspaceRoot??pmRoot,{includeReconciled:true,includeLossless:true,pmRoot});const availableMergeReceiptIds=new Set(mergeReceiptEvidence.receipts.map(receipt=>receipt.id));const historyReceiptClassification=classifyHistoryMergeReceiptReferences(historyScan.mergeReceiptReferences,availableMergeReceiptIds,historyScan.mergeReceiptDispositions);const missingMergeReceiptReferences=historyReceiptClassification.missing;const pendingMergeReceipts=mergeReceiptEvidence.receipts.filter(receipt=>receipt.state==="pending");const{pendingDecisions:pendingMergeDecisions,lossless:losslessMergeReceipts}=partitionMergeReceipts(pendingMergeReceipts);const mergeDriverInstallationMissing=mergeDriverAudit?.status==="missing"&&mergeDriverAudit.missing_keys.length===5&&mergeDriverAudit.drifted_keys.length===0;const warnings=[...itemScan.unreadable.map(entry=>`integrity_item_unreadable:${entry}`),...itemScan.conflictMarkers.map(entry=>`integrity_item_conflict_marker:${entry.path}:L${entry.line}`),...itemScan.parseFailures.map(entry=>`integrity_item_parse_failed:${entry}`),...historyScan.unreadable.map(entry=>`integrity_history_unreadable:${entry}`),...historyScan.conflictMarkers.map(entry=>`integrity_history_conflict_marker:${entry.id}:L${entry.line}`),...historyScan.invalidJson.map(entry=>`integrity_history_invalid_json:${entry.id}:L${entry.line}`),...formatVersionScan.outdated.map(entry=>`integrity_item_outdated_format_version:${entry}`),...formatVersionScan.ahead.map(entry=>`integrity_item_ahead_format_version:${entry}`),...buildHierarchyIntegrityWarnings(hierarchyIntegrity),...trackedRuntimeCache.tracked_path_count>0?[`tracked_runtime_cache_files:${trackedRuntimeCache.tracked_path_count}`]:[],...mergeDriverAudit!==null&&mergeDriverAudit.status!=="ok"?[`merge_driver_configuration_${mergeDriverInstallationMissing?"missing":"drift"}:${mergeDriverAudit.missing_keys.length+mergeDriverAudit.drifted_keys.length}`]:[],...pendingMergeDecisions.length>0?[`merge_decisions_unreviewed:${pendingMergeDecisions.length}`]:[],...losslessMergeReceipts.length>0?[`merge_receipts_pending:${losslessMergeReceipts.length}`]:[],...buildMergeReceiptEvidenceWarnings({invalidEvidenceCount:mergeReceiptEvidence.invalid_evidence_count,missingHistoryReferenceCount:missingMergeReceiptReferences.length})];const normalizedWarnings=[...new Set(warnings)].sort((left,right)=>left.localeCompare(right));const actionableWarnings=normalizedWarnings.filter(warning=>!warning.startsWith("integrity_legacy_hierarchy_"));return{check:{name:"integrity",status:actionableWarnings.length===0?"ok":"warn",ok:actionableWarnings.length===0,details:{checked_item_files:itemScan.paths.length,checked_history_streams:historyScan.files.length,counts:{item_unreadable:itemScan.unreadable.length,item_conflict_markers:itemScan.conflictMarkers.length,item_parse_failures:itemScan.parseFailures.length,history_unreadable:historyScan.unreadable.length,history_conflict_markers:historyScan.conflictMarkers.length,history_invalid_json:historyScan.invalidJson.length,item_outdated_format_version:formatVersionScan.outdated.length,item_ahead_format_version:formatVersionScan.ahead.length,hierarchy_cycles:hierarchyIntegrity.cycles.length,hierarchy_cardinality_violations:hierarchyIntegrity.cardinality_violations.length,hierarchy_parent_divergences:hierarchyIntegrity.divergences.length,tracked_runtime_cache_files:trackedRuntimeCache.tracked_path_count,merge_driver_configuration:mergeDriverAudit===null||mergeDriverAudit.status==="ok"?0:mergeDriverAudit.missing_keys.length+mergeDriverAudit.drifted_keys.length,pending_merge_decisions:pendingMergeDecisions.length,lossless_merge_receipts:losslessMergeReceipts.length,invalid_merge_receipt_evidence:mergeReceiptEvidence.invalid_evidence_count,missing_merge_receipt_history_references:missingMergeReceiptReferences.length,accepted_legacy_merge_receipt_references:historyReceiptClassification.acceptedLegacyCount,accepted_missing_merge_receipt_dispositions:historyReceiptClassification.acceptedDispositionCount},item_unreadable:itemScan.unreadable,item_conflict_markers:itemScan.conflictMarkers,item_parse_failures:itemScan.parseFailures,item_outdated_format_version:formatVersionScan.outdated,item_ahead_format_version:formatVersionScan.ahead,hierarchy_integrity:{...hierarchyIntegrity,relations:summarizeRecordList(hierarchyIntegrity.relations,BRIEF_HEALTH_DETAIL_LIMIT)},history_unreadable:historyScan.unreadable,history_conflict_markers:historyScan.conflictMarkers,history_invalid_json:historyScan.invalidJson,tracked_runtime_cache:{tracker_relative_root:trackedRuntimeCache.tracker_relative_root,tracked_paths:trackedRuntimeCache.tracked_paths,tracked_path_count:trackedRuntimeCache.tracked_path_count,remediation_command:trackedRuntimeCache.remediation_command},merge_driver_configuration:mergeDriverAudit===null?null:{...mergeDriverAudit,required:requireMergeDrivers},pending_merge_decision_items:[...new Set(pendingMergeDecisions.map(receipt=>receipt.item_id))].sort((left,right)=>left.localeCompare(right)),lossless_merge_receipt_items:[...new Set(losslessMergeReceipts.map(receipt=>receipt.item_id))].sort((left,right)=>left.localeCompare(right)),invalid_merge_receipt_evidence_details:mergeReceiptEvidence.invalid_evidence,invalid_merge_receipt_evidence_details_truncated:mergeReceiptEvidence.invalid_evidence_truncated,missing_merge_receipt_history_reference_details:missingMergeReceiptReferences.slice(0,HEALTH_WARNING_LIMIT),missing_merge_receipt_history_reference_details_truncated:missingMergeReceiptReferences.length>HEALTH_WARNING_LIMIT}},warnings:normalizedWarnings,gitWorkspaceRoot,pendingMergeReceipts}}function hasActivateExport(moduleRecord){if(typeof moduleRecord.activate==="function"){return true}const defaultExport=moduleRecord.default;if(typeof defaultExport!=="object"||defaultExport===null){return false}return typeof defaultExport.activate==="function"}function summarizeLoadedExtension(extension){const summary={layer:extension.layer,directory:extension.directory,manifest_path:extension.manifest_path,name:extension.name,version:extension.version,entry:extension.entry,priority:extension.priority,entry_path:extension.entry_path,has_activate:hasActivateExport(extension.module)};if(Array.isArray(extension.capabilities)){summary.capabilities=[...extension.capabilities]}return summary}function resolveMigrationId(definition,fallbackIndex){const explicitId=toNonEmptyStringOrUndefined(definition.id);if(explicitId){return explicitId}return`migration-${String(fallbackIndex+1).padStart(3,"0")}`}function resolveMigrationStatus(definition){const rawStatus=toNonEmptyStringOrUndefined(definition.status);const normalized=rawStatus?.toLowerCase();if(normalized==="failed"){return"failed"}if(normalized==="applied"){return"applied"}return"pending"}function resolveMigrationFailureReason(definition){return toNonEmptyStringOrUndefined(definition.reason)??toNonEmptyStringOrUndefined(definition.error)??toNonEmptyStringOrUndefined(definition.message)}function compareMigrationEntries(left,right){const byLayer=(left.layer??"").localeCompare(right.layer??"");if(byLayer!==0){return byLayer}const byName=(left.name??"").localeCompare(right.name??"");if(byName!==0){return byName}return(left.id??"").localeCompare(right.id??"")}function summarizeMigrationStatuses(migrations){const applied=[];const pending=[];const failed=[];migrations.forEach((migration,index)=>{const id=resolveMigrationId(migration.definition,index);const status=resolveMigrationStatus(migration.definition);if(status==="applied"){applied.push({layer:migration.layer,name:migration.name,id,status});return}if(status==="failed"){failed.push({layer:migration.layer,name:migration.name,id,status,reason:resolveMigrationFailureReason(migration.definition)});return}pending.push({layer:migration.layer,name:migration.name,id,status})});applied.sort(compareMigrationEntries);pending.sort(compareMigrationEntries);failed.sort(compareMigrationEntries);const warnings=[...failed.map(entry=>`extension_migration_failed:${entry.layer}:${entry.name}:${entry.id}`),...pending.map(entry=>`extension_migration_pending:${entry.layer}:${entry.name}:${entry.id}`)];return{summary:{applied,pending,failed,applied_count:applied.length,pending_count:pending.length,failed_count:failed.length},warnings}}function buildExtensionHealthTriageSummary(warnings,loadFailureCount,activationFailureCount,migrationStatus,managedStateWarningCount,managedExtensionEntriesCount,unmanagedLoadedExtensions,unmanagedExpectedExtensions,unmanagedActionRequiredExtensions){const normalizedWarnings=[...new Set(warnings)].sort((left,right)=>left.localeCompare(right));const warningCodes=[...new Set(normalizedWarnings.map(value=>warningCode(value)))].sort((left,right)=>left.localeCompare(right));const unknownCapabilityCount=normalizedWarnings.filter(warning=>warning.startsWith("extension_capability_unknown:")).length;const updateHealthPartial=unmanagedActionRequiredExtensions.length>0;const updateHealthCoverage=updateHealthPartial?"partial":"full";const remediation=[];const registrationCollisionRemediation=buildRegistrationCollisionRemediation(normalizedWarnings,{deactivate:"pm extension --deactivate <name> --project/--global",doctor:"pm extension --doctor --project/--global --detail deep --trace"});if(registrationCollisionRemediation){remediation.push(registrationCollisionRemediation)}if(loadFailureCount>0){remediation.push("Run pm extension --explore --project and pm extension --explore --global to inspect load failures.")}if(activationFailureCount>0){remediation.push("Review checks[name=extensions].details.activation.failed in pm health --json for activation error details.")}if(migrationStatus.failed_count>0||migrationStatus.pending_count>0){remediation.push("Resolve pending/failed extension migrations before write commands; use --force only when policy allows.")}if(managedStateWarningCount>0){remediation.push("Run pm extension --manage --project and pm extension --manage --global to refresh managed-state diagnostics.")}if(unknownCapabilityCount>0){remediation.push(`Unknown extension capabilities detected. Allowed capabilities: ${KNOWN_EXTENSION_CAPABILITIES.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`)}if(normalizedWarnings.some(warning=>warning.startsWith("extension_capability_legacy_alias:"))){remediation.push("Legacy extension capability aliases were auto-remapped to canonical capabilities. Update manifests to canonical names (migration/validation -> schema).")}if(normalizedWarnings.some(warning=>warning.startsWith("extension_command_definition_legacy_handler_alias:"))){remediation.push("Extension command definitions using legacy handler were auto-remapped. Update command definitions to use run: (context) => ... for forward compatibility.")}if(updateHealthPartial){remediation.push("Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via pm extension --manage --project/--global --fix-managed-state, pm extension --adopt-all --project/--global, or pm extension --adopt <name>.")}else if(unmanagedLoadedExtensions.length>0){remediation.push("Loaded unmanaged extensions are currently treated as informational. Use pm extension --manage --project/--global --fix-managed-state to adopt them for update checks.")}if(remediation.length===0){remediation.push("No immediate action required. Re-run pm health after extension configuration changes.")}return{status:normalizedWarnings.length===0?"ok":"warn",warning_count:normalizedWarnings.length,warning_codes:warningCodes,load_failure_count:loadFailureCount,activation_failure_count:activationFailureCount,migration_failed_count:migrationStatus.failed_count,migration_pending_count:migrationStatus.pending_count,managed_state_warning_count:managedStateWarningCount,managed_extension_entries_count:managedExtensionEntriesCount,unmanaged_loaded_extension_count:unmanagedLoadedExtensions.length,unmanaged_loaded_extensions:unmanagedLoadedExtensions,unmanaged_expected_extension_count:unmanagedExpectedExtensions.length,unmanaged_expected_extensions:unmanagedExpectedExtensions,unmanaged_action_required_extension_count:unmanagedActionRequiredExtensions.length,unmanaged_action_required_extensions:unmanagedActionRequiredExtensions,update_health_coverage:updateHealthCoverage,update_health_partial:updateHealthPartial,unknown_capability_count:unknownCapabilityCount,top_warnings:normalizedWarnings.slice(0,8),remediation}}async function buildExtensionCheck(pmRoot,settings,noExtensionsFlag){const authorManifest=await inspectExtensionAuthorManifest(resolveWorkspaceRoot(pmRoot));const loadResult=await loadExtensions({pmRoot,settings,cwd:process.cwd(),noExtensions:noExtensionsFlag});const loadedSummaries=loadResult.loaded.map(extension=>summarizeLoadedExtension(extension));const hostVersionCensus=await scanExtensionHostVersions(loadResult.loaded,resolveWorkspaceRoot(pmRoot));const activationResult=await activateExtensions({...loadResult,loaded:loadResult.loaded});const[projectManagedState,globalManagedState]=await Promise.all([readManagedExtensionState(loadResult.roots.project),readManagedExtensionState(loadResult.roots.global)]);await applyStoredExtensionMigrationState(pmRoot,activationResult.registrations.migrations);const migrationStatus=summarizeMigrationStatuses(activationResult.registrations.migrations);const activationDetails={failed:activationResult.failed,warnings:activationResult.warnings,hook_counts:activationResult.hook_counts,command_override_count:activationResult.command_override_count,command_handler_count:activationResult.command_handler_count,parser_override_count:activationResult.parser_override_count,preflight_override_count:activationResult.preflight_override_count,service_override_count:activationResult.service_override_count,renderer_override_count:activationResult.renderer_override_count,registration_counts:activationResult.registration_counts,registrations:activationResult.registrations,migration_status:migrationStatus.summary,managed_extensions:{project:{path:projectManagedState.path,count:projectManagedState.state.entries.length,entries:projectManagedState.state.entries},global:{path:globalManagedState.path,count:globalManagedState.state.entries.length,entries:globalManagedState.state.entries}}};const managedProjectNames=new Set(projectManagedState.state.entries.map(entry=>normalizeExtensionNameForMatch(entry.name)));const managedGlobalNames=new Set(globalManagedState.state.entries.map(entry=>normalizeExtensionNameForMatch(entry.name)));const unmanagedLoadedEntries=[...new Map(loadResult.loaded.filter(entry=>{const managedNames=entry.layer==="project"?managedProjectNames:managedGlobalNames;return!managedNames.has(normalizeExtensionNameForMatch(entry.name))}).map(entry=>[`${entry.layer}:${entry.name}`,{layer:entry.layer,name:entry.name,directory:entry.directory}])).values()].sort((left,right)=>{const leftKey=`${left.layer}:${left.name}`;const rightKey=`${right.layer}:${right.name}`;return leftKey.localeCompare(rightKey)});const unmanagedLoadedExtensions=unmanagedLoadedEntries.map(entry=>`${entry.layer}:${entry.name}`).sort((left,right)=>left.localeCompare(right));const unmanagedExpectedExtensions=unmanagedLoadedEntries.filter(entry=>isExpectedUnmanagedExtension(entry.name,entry.directory)).map(entry=>`${entry.layer}:${entry.name}`).sort((left,right)=>left.localeCompare(right));const unmanagedActionRequiredExtensions=unmanagedLoadedEntries.filter(entry=>!isExpectedUnmanagedExtension(entry.name,entry.directory)).map(entry=>`${entry.layer}:${entry.name}`).sort((left,right)=>left.localeCompare(right));const updateCoverageWarnings=unmanagedActionRequiredExtensions.length>0?[`extension_update_health_partial_coverage:skipped_unmanaged:${unmanagedActionRequiredExtensions.length}`]:[];const extensionWarnings=[...authorManifest.warnings,...loadResult.warnings,...activationDetails.warnings,...migrationStatus.warnings,...projectManagedState.warnings,...globalManagedState.warnings,...updateCoverageWarnings,...hostVersionCensus.warnings];const capabilityGuidance=collectUnknownCapabilityGuidance(extensionWarnings);const capabilityContract=buildCapabilityContractMetadata();const extensionTriage=buildExtensionHealthTriageSummary(extensionWarnings,loadResult.failed.length,activationResult.failed.length,migrationStatus.summary,projectManagedState.warnings.length+globalManagedState.warnings.length,projectManagedState.state.entries.length+globalManagedState.state.entries.length,unmanagedLoadedExtensions,unmanagedExpectedExtensions,unmanagedActionRequiredExtensions);return{check:{name:"extensions",status:extensionWarnings.length===0?"ok":"warn",ok:extensionWarnings.length===0,details:{...loadResult,loaded:loadedSummaries,warnings:extensionWarnings,activation:activationDetails,author_manifest:authorManifest,triage:extensionTriage,...migrationStatus.summary.pending_count>0?{remediation_map:{extension_migration_pending:"pm extension migrate --project"}}:{},capability_contract:capabilityContract,capability_guidance:capabilityGuidance,host_version_census:hostVersionCensus}},warnings:extensionWarnings}}function summarizeList(values,limit){if(values.length<=limit){return{values,truncated:false}}return{values:values.slice(0,limit),truncated:true}}function summarizeRecordList(value,limit){if(!Array.isArray(value)){return{count:0,sample:[],truncated:false}}return{count:value.length,sample:value.slice(0,limit),truncated:value.length>limit}}function summarizeExtensionRecord(value){if(typeof value!=="object"||value===null||Array.isArray(value)){return{}}const record=value;return{layer:record.layer,directory:record.directory,name:record.name,version:record.version,enabled:record.enabled,status:record.status,has_activate:record.has_activate,capabilities:record.capabilities}}function summarizeExtensionList(value,limit){const summary=summarizeRecordList(value,limit);return{...summary,sample:summary.sample.map(entry=>summarizeExtensionRecord(entry))}}function summarizeStringList(value,limit){if(!Array.isArray(value)){return{count:0,sample:[],truncated:false}}const strings=value.filter(entry=>typeof entry==="string");return{count:strings.length,sample:strings.slice(0,limit),truncated:strings.length>limit}}function summarizeActivationMigrationStatus(value){if(typeof value!=="object"||value===null){return null}const status=value;return{applied_count:status.applied_count,pending_count:status.pending_count,failed_count:status.failed_count}}const HEALTH_DETAIL_SUMMARIZERS={settings:(details,limit)=>({version:details.version,id_prefix:details.id_prefix,locks_ttl_seconds:details.locks_ttl_seconds,warnings:summarizeStringList(details.warnings,limit)}),directories:(details,limit)=>({required_count:Array.isArray(details.required)?details.required.length:0,optional_count:Array.isArray(details.optional)?details.optional.length:0,missing_required:summarizeStringList(details.missing_required,limit),missing_optional:summarizeStringList(details.missing_optional,limit),missing:summarizeStringList(details.missing,limit),strict_directories:details.strict_directories}),settings_values:(details,limit)=>({warnings:summarizeStringList(details.warnings,limit)}),telemetry:details=>({enabled:details.enabled,capture_level:details.capture_level,endpoint:details.endpoint,queue_exists:details.queue_exists,queue_entries:details.queue_entries,queue_draining:details.queue_draining,queue_invalid_rows:details.queue_invalid_rows,queue_rows_total:details.queue_rows_total,last_successful_flush_at:details.last_successful_flush_at,last_failed_flush_at:details.last_failed_flush_at,endpoint_probe:details.endpoint_probe,env_overrides:details.env_overrides}),extensions:(details,limit)=>{const activation=typeof details.activation==="object"&&details.activation!==null?details.activation:{};return{disabled_by_flag:details.disabled_by_flag,discovered:summarizeExtensionList(details.discovered,limit),effective:summarizeExtensionList(details.effective,limit),loaded:summarizeExtensionList(details.loaded,limit),failed:summarizeRecordList(details.failed,limit),warnings:summarizeStringList(details.warnings,limit),activation:{failed:summarizeRecordList(activation.failed,limit),warnings:summarizeStringList(activation.warnings,limit),hook_counts:activation.hook_counts,command_handler_count:activation.command_handler_count,service_override_count:activation.service_override_count,renderer_override_count:activation.renderer_override_count,registration_counts:activation.registration_counts,migration_status:summarizeActivationMigrationStatus(activation.migration_status)},author_manifest:details.author_manifest,triage:details.triage,capability_contract:details.capability_contract,capability_guidance:summarizeRecordList(details.capability_guidance,limit),host_version_census:details.host_version_census}},storage:(details,limit)=>{const authorAttribution=typeof details.author_attribution==="object"&&details.author_attribution!==null?details.author_attribution:void 0;return{...details,...authorAttribution?{author_attribution:{...authorAttribution,affected_item_ids:summarizeStringList(authorAttribution.affected_item_ids,limit),samples:summarizeRecordList(authorAttribution.samples,limit)}}:{}}},locks:details=>({active_lock_count:details.active_lock_count,stale_lock_count:details.stale_lock_count,unreadable_lock_count:details.unreadable_lock_count,unparseable_lock_count:details.unparseable_lock_count}),integrity:(details,limit)=>{const trackedRuntimeCache=typeof details.tracked_runtime_cache==="object"&&details.tracked_runtime_cache!==null?details.tracked_runtime_cache:void 0;return{checked_item_files:details.checked_item_files,checked_history_streams:details.checked_history_streams,counts:details.counts,item_unreadable:summarizeStringList(details.item_unreadable,limit),item_conflict_markers:summarizeRecordList(details.item_conflict_markers,limit),item_parse_failures:summarizeStringList(details.item_parse_failures,limit),tracked_runtime_cache:trackedRuntimeCache===void 0?details.tracked_runtime_cache:{...trackedRuntimeCache,tracked_paths:summarizeStringList(trackedRuntimeCache.tracked_paths,limit)},history_unreadable:summarizeStringList(details.history_unreadable,limit),history_conflict_markers:summarizeRecordList(details.history_conflict_markers,limit),history_invalid_json:summarizeRecordList(details.history_invalid_json,limit),skipped:details.skipped}},history_drift:(details,limit)=>{const cacheConfirmation=typeof details.cache_confirmation==="object"&&details.cache_confirmation!==null?details.cache_confirmation:void 0;return{checked_items:details.checked_items,cache_hit_verification:details.cache_hit_verification,cache_confirmation:cacheConfirmation===void 0?details.cache_confirmation:{...cacheConfirmation,candidate_items:summarizeStringList(cacheConfirmation.candidate_items,limit),confirmed_items:summarizeStringList(cacheConfirmation.confirmed_items,limit),resolved_false_positive_items:summarizeStringList(cacheConfirmation.resolved_false_positive_items,limit)},counts:details.counts,drifted_items:summarizeStringList(details.drifted_items,limit),merge_receipt_attributed_items:summarizeStringList(details.merge_receipt_attributed_items,limit),missing_streams:summarizeStringList(details.missing_streams,limit),unreadable_streams:summarizeStringList(details.unreadable_streams,limit),hash_mismatches:summarizeStringList(details.hash_mismatches,limit),chain_mismatches:summarizeStringList(details.chain_mismatches,limit),version_skews:summarizeStringList(details.version_skews,limit),workspace_state_mismatches:summarizeStringList(details.workspace_state_mismatches,limit),workspace_state_missing:summarizeStringList(details.workspace_state_missing,limit),workspace_state_unreadable:summarizeStringList(details.workspace_state_unreadable,limit),skipped:details.skipped}},vectorization:(details,limit)=>({semantic_runtime_available:details.semantic_runtime_available,compatibility_mode_auto_defaults:details.compatibility_mode_auto_defaults,auto_ollama_defaults_applied:details.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:details.auto_ollama_defaults_skipped_reason,auto_ollama_defaults_remediation:details.auto_ollama_defaults_remediation,refresh_policy:details.refresh_policy,provider_active:details.provider_active,vector_store_active:details.vector_store_active,items:details.items,ledger_entries_before:details.ledger_entries_before,stale_items_before_total:details.stale_items_before_total,stale_items_before:summarizeStringList(details.stale_items_before,limit),refresh_attempted:details.refresh_attempted,refresh_skipped_reason:details.refresh_skipped_reason,refresh_result:details.refresh_result,ledger_entries_after:details.ledger_entries_after,stale_items_after_total:details.stale_items_after_total,stale_items_after:summarizeStringList(details.stale_items_after,limit),skipped:details.skipped})};function summarizeHealthCheckDetails(check,limit){const summarize=HEALTH_DETAIL_SUMMARIZERS[check.name];return summarize?summarize(check.details,limit):check.details}function applyBriefHealthProjection(result){const warningsSummary=summarizeStringList(result.warnings,BRIEF_HEALTH_DETAIL_LIMIT);return{ok:result.ok,...result.verdict?{verdict:result.verdict}:{},checks:result.checks.map(check=>({name:check.name,status:check.status,ok:check.ok,details:summarizeHealthCheckDetails(check,BRIEF_HEALTH_DETAIL_LIMIT)})),warnings:warningsSummary.sample,findings:result.findings.filter(finding=>warningsSummary.sample.includes(finding.warning)||result.failed_because.includes(finding.warning)),failed_because:result.failed_because,projection:{mode:"brief",warning_count:warningsSummary.count,warnings_truncated:warningsSummary.truncated,detail_limit:BRIEF_HEALTH_DETAIL_LIMIT},generated_at:result.generated_at}}function isSkippedHealthCheck(check){return check.details.skipped===true}function applySummaryHealthProjection(result){const warningsSummary=summarizeStringList(result.warnings,BRIEF_HEALTH_DETAIL_LIMIT);const omittedChecks=result.checks.filter(isSkippedHealthCheck).map(check=>check.name);return{ok:result.ok,...result.verdict?{verdict:result.verdict}:{},checks:result.checks.filter(check=>!isSkippedHealthCheck(check)).map(check=>({name:check.name,status:check.status,ok:check.ok,details:{}})),warning_count:warningsSummary.count,warnings:warningsSummary.sample,findings:result.findings.filter(finding=>warningsSummary.sample.includes(finding.warning)||result.failed_because.includes(finding.warning)),failed_because:result.failed_because,projection:{mode:"summary",warning_count:warningsSummary.count,warnings_truncated:warningsSummary.truncated,detail_limit:BRIEF_HEALTH_DETAIL_LIMIT,omitted_checks:omittedChecks},generated_at:result.generated_at}}function selectStaleItemDetail(values,verboseStaleItems){if(verboseStaleItems){return{values,truncated:false,total:values.length}}const summary=summarizeList(values,STALE_VECTORIZATION_SUMMARY_LIMIT);return{values:summary.values,truncated:summary.truncated,total:values.length}}function telemetryEnvFlagEnabled(envKey){const value=(process.env[envKey]??"").trim().toLowerCase();return value==="1"||value==="true"||value==="yes"||value==="on"}function telemetrySourceContextOverride(){const value=(process.env.PM_TELEMETRY_SOURCE_CONTEXT??"").trim().toLowerCase();return PM_TELEMETRY_SOURCE_CONTEXT_SET.has(value)?value:null}function normalizeEndpointForDisplay(rawEndpoint){const trimmed=rawEndpoint.trim();if(trimmed.length===0){return""}try{const parsed=new URL(trimmed);parsed.username="";parsed.password="";parsed.search="";parsed.hash="";return parsed.toString()}catch{return trimmed}}function parseTelemetryQueue(raw){let validEntries=0;let invalidRows=0;let totalRows=0;let highRetryEntries=0;let maxAttempts=0;for(const line of raw.split("\n")){const trimmed=line.trim();if(trimmed.length===0){continue}totalRows+=1;try{const parsed=JSON.parse(trimmed);if(typeof parsed==="object"&&parsed!==null&&typeof parsed.attempts==="number"&&Number.isFinite(parsed.attempts)){const attempts=Math.max(0,Math.trunc(parsed.attempts));validEntries+=1;maxAttempts=Math.max(maxAttempts,attempts);if(attempts>=TELEMETRY_QUEUE_HIGH_RETRY_THRESHOLD){highRetryEntries+=1}}else{invalidRows+=1}}catch{invalidRows+=1}}return{validEntries,invalidRows,totalRows,highRetryEntries,maxAttempts}}function emptyTelemetryQueueSummary(){return{validEntries:0,invalidRows:0,totalRows:0,highRetryEntries:0,maxAttempts:0}}function parseTelemetryRuntimeState(stateRaw){if(!stateRaw||stateRaw.trim().length===0){return{runtimeState:{},stateParseFailed:false}}try{const parsed=JSON.parse(stateRaw);if(typeof parsed==="object"&&parsed!==null&&!Array.isArray(parsed)){return{runtimeState:parsed,stateParseFailed:false}}return{runtimeState:{},stateParseFailed:true}}catch{return{runtimeState:{},stateParseFailed:true}}}async function maybeProbeTelemetryEndpoint(settings,checkTelemetry){const endpoint=settings.telemetry.endpoint.trim();if(!checkTelemetry||!settings.telemetry.enabled||endpoint.length===0){return void 0}const probe=await probeTelemetryEndpointHealth(endpoint);return{attempted:true,...probe}}function collectTelemetryQueueWarnings(settings,queueSummary,runtimeState){const warnings=[];if(queueSummary.invalidRows>0){warnings.push(`telemetry_queue_invalid_rows:${queueSummary.invalidRows}`)}if(!settings.telemetry.enabled||queueSummary.validEntries===0){return warnings}const lastSuccess=runtimeState.last_successful_flush_at;const lastFailure=runtimeState.last_failed_flush_at;const activeFailure=lastFailure&&(!lastSuccess||lastFailure>lastSuccess);const neverFlushed=!lastSuccess;const highWater=queueSummary.validEntries>=TELEMETRY_QUEUE_HIGH_WATER_MARK;if(activeFailure||neverFlushed||highWater){warnings.push(`telemetry_queue_pending:${queueSummary.validEntries}`)}if(queueSummary.highRetryEntries>0){warnings.push(`telemetry_queue_high_retries:${queueSummary.highRetryEntries}`)}return warnings}function collectTelemetryEndpointWarnings(endpointProbe){if(!endpointProbe||endpointProbe.ok!==false){return[]}return typeof endpointProbe.status==="number"?[`telemetry_endpoint_probe_http_status:${endpointProbe.status}`]:["telemetry_endpoint_probe_failed"]}function collectTelemetrySchemaWarnings(endpointProbe){const parsedMaxSchemaVersion=Number.parseInt(endpointProbe?.max_schema_version??"",10);if(endpointProbe?.ok===true&&Number.isInteger(parsedMaxSchemaVersion)&&parsedMaxSchemaVersion>TELEMETRY_SCHEMA_VERSION){return[`telemetry_schema_version_behind:${parsedMaxSchemaVersion}`]}return[]}function collectTelemetryOtelWarnings(settings,runtimeState){const pendingOtelSpans=typeof runtimeState.pending_otel_spans==="number"?runtimeState.pending_otel_spans:0;const lastOtelSuccess=runtimeState.last_otel_success_at;const lastOtelFailure=runtimeState.last_otel_failure_at;const otelExportFailing=settings.telemetry.enabled&&pendingOtelSpans>0&&Boolean(lastOtelFailure)&&(!lastOtelSuccess||lastOtelFailure>=lastOtelSuccess);return otelExportFailing?[`telemetry_otel_export_failing:${pendingOtelSpans}`]:[]}function buildTelemetryEnvOverrideDetails(){return{telemetry_disabled:telemetryEnvFlagEnabled("PM_TELEMETRY_DISABLED")||telemetryEnvFlagEnabled("PM_NO_TELEMETRY"),pm_no_telemetry:telemetryEnvFlagEnabled("PM_NO_TELEMETRY"),telemetry_otel_disabled:telemetryEnvFlagEnabled("PM_TELEMETRY_OTEL_DISABLED"),telemetry_inline_flush:telemetryEnvFlagEnabled("PM_TELEMETRY_INLINE_FLUSH"),telemetry_source_context:telemetrySourceContextOverride()}}function telemetryQueueHasEntries(settings,queueSummary){return settings.telemetry.enabled&&queueSummary.validEntries>0}function isTelemetryQueueDraining(queueHasEntries,warnings){return queueHasEntries&&warnings.every(warning=>!warning.startsWith("telemetry_queue_pending:")&&!warning.startsWith("telemetry_queue_high_retries:"))}async function probeTelemetryEndpointHealth(endpoint){let probeUrl=endpoint;try{const parsed=new URL(endpoint);parsed.pathname="/healthz";parsed.search="";parsed.hash="";probeUrl=parsed.toString()}catch{}try{const response=await fetch(probeUrl,{method:"GET",signal:AbortSignal.timeout(TELEMETRY_ENDPOINT_PROBE_TIMEOUT_MS)});return{probe_url:normalizeEndpointForDisplay(probeUrl),ok:response.ok,status:response.status,max_schema_version:(()=>{for(const headerName of TELEMETRY_SERVER_MAX_SCHEMA_VERSION_HEADERS){const value=response.headers.get(headerName)?.trim();if(value&&value.length>0){return value}}return void 0})()}}catch(error){return{probe_url:normalizeEndpointForDisplay(probeUrl),ok:false,error:error instanceof Error?error.message:"probe_failed"}}}async function buildTelemetryCheck(settings,options){const globalPmRoot=resolveGlobalPmRoot(process.cwd());const queuePath=path.join(globalPmRoot,TELEMETRY_QUEUE_RELATIVE_PATH);const statePath=path.join(globalPmRoot,TELEMETRY_STATE_RELATIVE_PATH);const queueRaw=await readFileIfExists(queuePath);const queueExists=queueRaw!==null;const queueSizeBytes=queueRaw?Buffer.byteLength(queueRaw,"utf8"):0;const queueSummary=queueRaw?parseTelemetryQueue(queueRaw):emptyTelemetryQueueSummary();const stateRaw=await readFileIfExists(statePath);const{runtimeState,stateParseFailed}=parseTelemetryRuntimeState(stateRaw);const endpoint=settings.telemetry.endpoint.trim();const endpointDisplay=normalizeEndpointForDisplay(endpoint);const endpointProbe=await maybeProbeTelemetryEndpoint(settings,options.checkTelemetry);const warnings=[];if(stateParseFailed){warnings.push("telemetry_state_invalid_json")}warnings.push(...collectTelemetryQueueWarnings(settings,queueSummary,runtimeState),...collectTelemetryEndpointWarnings(endpointProbe),...collectTelemetrySchemaWarnings(endpointProbe),...collectTelemetryOtelWarnings(settings,runtimeState));const queueHasEntries=telemetryQueueHasEntries(settings,queueSummary);const pendingOtelSpans=typeof runtimeState.pending_otel_spans==="number"?runtimeState.pending_otel_spans:0;return{check:{name:"telemetry",status:warnings.length===0?"ok":"warn",ok:warnings.length===0,details:{enabled:settings.telemetry.enabled,capture_level:settings.telemetry.capture_level,endpoint:endpointDisplay,global_pm_root:globalPmRoot,queue_path:queuePath,queue_exists:queueExists,queue_entries:queueSummary.validEntries,queue_draining:isTelemetryQueueDraining(queueHasEntries,warnings),queue_invalid_rows:queueSummary.invalidRows,queue_rows_total:queueSummary.totalRows,queue_size_bytes:queueSizeBytes,queue_high_retry_entries:queueSummary.highRetryEntries,queue_high_retry_threshold:TELEMETRY_QUEUE_HIGH_RETRY_THRESHOLD,queue_max_attempts:queueSummary.maxAttempts,runtime_state_path:statePath,last_attempted_flush_at:runtimeState.last_attempted_flush_at??null,last_successful_flush_at:runtimeState.last_successful_flush_at??null,last_failed_flush_at:runtimeState.last_failed_flush_at??null,last_failed_flush_error:runtimeState.last_failed_flush_error??null,pending_otel_spans:pendingOtelSpans,last_otel_attempt_at:runtimeState.last_otel_attempt_at??null,last_otel_success_at:runtimeState.last_otel_success_at??null,last_otel_failure_at:runtimeState.last_otel_failure_at??null,last_otel_failure_error:runtimeState.last_otel_failure_error??null,endpoint_probe:endpointProbe??{attempted:false},env_overrides:buildTelemetryEnvOverrideDetails()}},warnings}}async function buildLocksCheck(pmRoot){let scan;try{scan=await scanLockHealth(pmRoot)}catch(error){const message=error instanceof Error?error.message:String(error);return{check:{name:"locks",status:"warn",ok:false,details:{active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0,scan_failed:true,error:message,pm_root:pmRoot}},warnings:[`locks_scan_failed:${message}`]}}const warnings=[];if(scan.stale_lock_count>0){warnings.push(`locks_stale_count:${scan.stale_lock_count}`)}if(scan.unreadable_lock_count>0){warnings.push(`locks_unreadable:${scan.unreadable_lock_count}`)}return{check:{name:"locks",status:warnings.length===0?"ok":"warn",ok:warnings.length===0,details:{active_lock_count:scan.active_lock_count,stale_lock_count:scan.stale_lock_count,unreadable_lock_count:scan.unreadable_lock_count,unparseable_lock_count:scan.unparseable_lock_count}},warnings}}async function buildHistoryDriftCheck(params){const cacheHitVerification="metadata";let items=params.items;let drift=await scanHistoryDrift(params.pmRoot,items,{cacheHitVerification});const cacheConfirmationCandidates=[...new Set([...drift.hashMismatches,...drift.chainMismatches,...drift.versionSkews])].sort((left,right)=>left.localeCompare(right));let confirmedItems=[];let resolvedFalsePositiveItems=[];if(cacheConfirmationCandidates.length>0){items=await listAllItemMetadataWithBody(params.pmRoot,params.settings.item_format,params.typeRegistry.type_to_folder,params.itemReadWarnings,params.settings.schema,{forceSourceScan:true});drift=await scanHistoryDrift(params.pmRoot,items);confirmedItems=[...new Set([...drift.hashMismatches,...drift.chainMismatches,...drift.versionSkews])].sort((left,right)=>left.localeCompare(right));const confirmedSet=new Set(confirmedItems);resolvedFalsePositiveItems=cacheConfirmationCandidates.filter(id=>!confirmedSet.has(id))}const{missingStreams,unreadableStreams,hashMismatches,chainMismatches,versionSkews,driftedItems,workspaceStateMismatches,workspaceStateMissing,workspaceStateUnreadable}=drift;const warnings=[...missingStreams.map(id=>`history_drift_missing_stream:${id}`),...unreadableStreams.map(id=>`history_drift_unreadable_stream:${id}`),...hashMismatches.map(id=>`history_drift_hash_mismatch:${id}`),...chainMismatches.map(id=>`history_drift_chain_mismatch:${id}`),...versionSkews.map(id=>`history_drift_version_skew:${id}`),...workspaceStateMismatches.map(documentPath=>`history_drift_workspace_state_mismatch:${documentPath}`),...workspaceStateMissing.map(documentPath=>`history_drift_workspace_state_missing:${documentPath}`),...workspaceStateUnreadable.map(documentPath=>`history_drift_workspace_state_unreadable:${documentPath}`)];return{check:{name:"history_drift",status:warnings.length===0?"ok":"warn",ok:warnings.length===0,details:{checked_items:items.length,cache_hit_verification:cacheConfirmationCandidates.length>0?"metadata_then_content_hash":cacheHitVerification,cache_confirmation:{triggered:cacheConfirmationCandidates.length>0,reason:cacheConfirmationCandidates.length>0?"cached_corruption_candidate":null,candidate_items:cacheConfirmationCandidates,confirmed_items:confirmedItems,resolved_false_positive_items:resolvedFalsePositiveItems,authoritative_item_source:cacheConfirmationCandidates.length>0},drifted_items:driftedItems,counts:{drifted:driftedItems.length,missing_streams:missingStreams.length,unreadable_streams:unreadableStreams.length,hash_mismatches:hashMismatches.length,chain_mismatches:chainMismatches.length,version_skews:versionSkews.length,workspace_state_mismatches:workspaceStateMismatches.length,workspace_state_missing:workspaceStateMissing.length,workspace_state_unreadable:workspaceStateUnreadable.length},missing_streams:missingStreams,unreadable_streams:unreadableStreams,hash_mismatches:hashMismatches,chain_mismatches:chainMismatches,version_skews:versionSkews,workspace_state_mismatches:workspaceStateMismatches,workspace_state_missing:workspaceStateMissing,workspace_state_unreadable:workspaceStateUnreadable}},warnings}}function buildVectorizationRuntimeSnapshot(settings,pmRoot){const runtimeDefaults=resolveSettingsWithSemanticRuntimeDefaults(settings);const providerResolution=resolveEmbeddingProviders(runtimeDefaults.settings);const vectorStoreResolution=resolveVectorStores(runtimeDefaults.settings,pmRoot);const runtimeEmbeddingIdentity=providerResolution.active?buildVectorizationEmbeddingIdentity(providerResolution.active.name,providerResolution.active.model):null;return{runtimeDefaults,providerResolution,vectorStoreResolution,runtimeEmbeddingIdentity,semanticRuntimeAvailable:Boolean(providerResolution.active&&vectorStoreResolution.active)}}function emptyVectorizationRefreshResult(){return{refreshed:[],skipped:[],warnings:[]}}async function refreshStaleVectorizationItems(params){if(!params.refreshPolicy.enabled||!params.snapshot.semanticRuntimeAvailable||params.staleBefore.length===0){return emptyVectorizationRefreshResult()}return refreshSemanticEmbeddingsForMutatedItems(params.pmRoot,params.staleBefore,{settings:params.snapshot.runtimeDefaults.settings,apply_runtime_defaults:false})}function vectorizationEmbeddingIdentityChanged(params){return params.strictVectorizationWarnings&¶ms.semanticRuntimeAvailable&&Boolean(params.ledgerBefore.embedding&¶ms.runtimeEmbeddingIdentity&&hasVectorizationEmbeddingIdentityChanged(params.ledgerBefore.embedding,params.runtimeEmbeddingIdentity))}function collectVectorizationWarnings(params){const warningSet=new Set([...params.ledgerBefore.warnings,...params.ledgerAfter.warnings]);if(params.strictVectorizationWarnings){for(const warning of params.refreshResult.warnings){warningSet.add(warning)}}if(params.embeddingIdentityChanged){warningSet.add("vectorization_embedding_identity_changed")}if(params.strictVectorizationWarnings&¶ms.semanticRuntimeAvailable&¶ms.staleAfter.length>0){warningSet.add(`vectorization_stale_items_remaining:${params.staleAfter.length}`)}return[...warningSet].sort((left,right)=>left.localeCompare(right))}function resolveVectorizationRefreshSkippedReason(refreshPolicy,semanticRuntimeAvailable,staleBefore){if(refreshPolicy.enabled&&semanticRuntimeAvailable&&staleBefore.length>0){return null}if(!refreshPolicy.enabled){return"refresh_disabled"}return semanticRuntimeAvailable?"no_stale_items":"semantic_runtime_unavailable"}function buildVectorizationProviderDetails(settings,snapshot){const activeProvider=snapshot.providerResolution.active?.name??null;const activeVectorStore=snapshot.vectorStoreResolution.active?.name??null;return{provider_active:activeProvider,provider_configured:typeof settings.search?.provider==="string"?settings.search.provider:null,provider_source:resolveProviderConfigSource(activeProvider,settings.search?.provider??null),vector_store_active:activeVectorStore,vector_store_configured:typeof settings.vector_store?.adapter==="string"?settings.vector_store.adapter:null,vector_store_source:resolveProviderConfigSource(activeVectorStore,settings.vector_store?.adapter??null)}}function buildVectorizationRefreshPolicyDetails(refreshPolicy){return{enabled:refreshPolicy.enabled,check_only:refreshPolicy.checkOnly,no_refresh:refreshPolicy.noRefresh,refresh_vectors:refreshPolicy.refreshVectors}}function vectorizationRefreshAttempted(refreshPolicy,semanticRuntimeAvailable,staleBefore){return refreshPolicy.enabled&&staleBefore.length>0&&semanticRuntimeAvailable}async function buildVectorizationCheck(pmRoot,settings,items,refreshPolicy,verboseStaleItems){const snapshot=buildVectorizationRuntimeSnapshot(settings,pmRoot);const ledgerBefore=await readVectorizationStatusLedger(pmRoot);const staleBefore=snapshot.semanticRuntimeAvailable?collectStaleVectorizationIds(items,ledgerBefore.entries):[];const refreshResult=await refreshStaleVectorizationItems({pmRoot,snapshot,refreshPolicy,staleBefore});const ledgerAfter=await readVectorizationStatusLedger(pmRoot);const staleAfter=snapshot.semanticRuntimeAvailable?collectStaleVectorizationIds(items,ledgerAfter.entries):[];const strictVectorizationWarnings=!snapshot.runtimeDefaults.auto_ollama_defaults_applied;const embeddingIdentityChanged=vectorizationEmbeddingIdentityChanged({strictVectorizationWarnings,semanticRuntimeAvailable:snapshot.semanticRuntimeAvailable,ledgerBefore,runtimeEmbeddingIdentity:snapshot.runtimeEmbeddingIdentity});const warnings=collectVectorizationWarnings({ledgerBefore,ledgerAfter,refreshResult,strictVectorizationWarnings,semanticRuntimeAvailable:snapshot.semanticRuntimeAvailable,embeddingIdentityChanged,staleAfter});const staleBeforeDetail=selectStaleItemDetail(staleBefore,verboseStaleItems);const staleAfterDetail=selectStaleItemDetail(staleAfter,verboseStaleItems);const refreshAttempted=vectorizationRefreshAttempted(refreshPolicy,snapshot.semanticRuntimeAvailable,staleBefore);return{check:{name:"vectorization",status:warnings.length===0?"ok":"warn",ok:warnings.length===0,details:{semantic_runtime_available:snapshot.semanticRuntimeAvailable,compatibility_mode_auto_defaults:snapshot.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_applied:snapshot.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:snapshot.runtimeDefaults.auto_ollama_defaults_skipped_reason??null,auto_ollama_defaults_remediation:snapshot.runtimeDefaults.auto_ollama_defaults_remediation??null,refresh_policy:buildVectorizationRefreshPolicyDetails(refreshPolicy),...buildVectorizationProviderDetails(settings,snapshot),embedding_identity_changed:embeddingIdentityChanged,embedding_identity_before:ledgerBefore.embedding??null,embedding_identity_runtime:snapshot.runtimeEmbeddingIdentity??null,items:items.length,ledger_entries_before:Object.keys(ledgerBefore.entries).length,stale_items_detail_mode:verboseStaleItems?"full":"summary",stale_items_summary_limit:STALE_VECTORIZATION_SUMMARY_LIMIT,stale_items_before_total:staleBeforeDetail.total,stale_items_before:staleBeforeDetail.values,stale_items_before_truncated:staleBeforeDetail.truncated,refresh_attempted:refreshAttempted,refresh_skipped_reason:resolveVectorizationRefreshSkippedReason(refreshPolicy,snapshot.semanticRuntimeAvailable,staleBefore),refresh_result:refreshResult,ledger_entries_after:Object.keys(ledgerAfter.entries).length,stale_items_after_total:staleAfterDetail.total,stale_items_after:staleAfterDetail.values,stale_items_after_truncated:staleAfterDetail.truncated}},warnings}}function validateSettingsValues(settings){const warnings=[];if(settings.id_prefix.trim().length===0){warnings.push("settings:id_prefix_empty")}if(settings.locks.ttl_seconds<=0){warnings.push("settings:locks_ttl_non_positive")}return warnings}function resolveVectorRefreshPolicy(options){const checkOnly=options.checkOnly===true;const refreshVectors=options.refreshVectors===true;if(refreshVectors&&checkOnly){throw new PmCliError("--check-only cannot be combined with --refresh-vectors",EXIT_CODE.USAGE)}if(refreshVectors&&options.noRefresh===true){throw new PmCliError("--no-refresh cannot be combined with --refresh-vectors",EXIT_CODE.USAGE)}return{enabled:refreshVectors,checkOnly,noRefresh:!refreshVectors,refreshVectors}}const HEALTH_CLONE_OPTIONAL_DIRECTORIES=new Set(["extensions","locks","search"]);function resolveHealthDirectoryLists(typeRegistry){const requiredDirSet=new Set(PM_CORE_REQUIRED_SUBDIRS.filter(entry=>entry.length>0));const optionalDirSet=new Set;const builtinItemFolderSet=new Set(Object.values(TYPE_TO_FOLDER));for(const folder of typeRegistry.folders){if(requiredDirSet.has(folder)&&!builtinItemFolderSet.has(folder)){continue}requiredDirSet.delete(folder);optionalDirSet.add(folder)}for(const folder of HEALTH_CLONE_OPTIONAL_DIRECTORIES){requiredDirSet.delete(folder);optionalDirSet.add(folder)}return{requiredDirs:[...requiredDirSet].sort((left,right)=>left.localeCompare(right)),optionalDirs:[...optionalDirSet].sort((left,right)=>left.localeCompare(right)),optionalDirSet}}async function scanHealthDirectories(pmRoot,typeRegistry,strictDirectories){const{requiredDirs,optionalDirs,optionalDirSet}=resolveHealthDirectoryLists(typeRegistry);const missingRequiredDirs=[];const missingOptionalDirs=[];const hookWarnings=[];for(const relativeDir of[...requiredDirs,...optionalDirs]){const directoryPath=path.join(pmRoot,relativeDir);hookWarnings.push(...await runActiveOnReadHooks({path:directoryPath,scope:"project"}));if(await isDirectory(directoryPath)){continue}if(optionalDirSet.has(relativeDir)){missingOptionalDirs.push(relativeDir)}else{missingRequiredDirs.push(relativeDir)}}return{requiredDirs,optionalDirs,missingRequiredDirs,missingOptionalDirs,missingDirs:strictDirectories?[...missingRequiredDirs,...missingOptionalDirs]:[...missingRequiredDirs],hookWarnings}}function resolveHealthSkipPolicy(options){const checkOnlyDefaultSummary=options.checkOnly===true&&options.brief!==true&&options.summary!==true&&options.full!==true;const summaryMode=(options.summary===true||checkOnlyDefaultSummary)&&options.full!==true;const fastProjectionCheckOnly=options.checkOnly===true&&(options.brief===true||options.summary===true)&&options.full!==true;return{summaryMode,skipIntegrity:(options.skipIntegrity===true||fastProjectionCheckOnly)&&options.full!==true,skipDrift:(options.skipDrift===true||fastProjectionCheckOnly)&&options.full!==true,skipVectors:(options.skipVectors===true||fastProjectionCheckOnly)&&options.full!==true}}async function readHealthItems(params){if(params.skipPolicy.skipDrift&¶ms.skipPolicy.skipVectors){return listAllItemMetadataLight(params.pmRoot,params.settings.item_format,params.typeRegistry.type_to_folder,params.itemReadWarnings,params.settings.schema)}return listAllItemMetadataWithBody(params.pmRoot,params.settings.item_format,params.typeRegistry.type_to_folder,params.itemReadWarnings,params.settings.schema)}function buildSkippedHealthCheck(name){return{check:{name,status:"ok",ok:true,details:{skipped:true}},warnings:[]}}function buildSettingsHealthCheck(settingsPath,settings,normalizedSettingsReadWarnings){return{name:"settings",status:normalizedSettingsReadWarnings.length===0?"ok":"warn",ok:normalizedSettingsReadWarnings.length===0,details:{path:settingsPath,version:settings.version,id_prefix:settings.id_prefix,locks_ttl_seconds:settings.locks.ttl_seconds,warnings:normalizedSettingsReadWarnings}}}function buildDirectoriesHealthCheck(directoryState,strictDirectories){return{name:"directories",status:directoryState.missingDirs.length===0?"ok":"warn",ok:directoryState.missingDirs.length===0,details:{required:directoryState.requiredDirs,optional:directoryState.optionalDirs,missing_required:directoryState.missingRequiredDirs,missing_optional:directoryState.missingOptionalDirs,missing:directoryState.missingDirs,strict_directories:strictDirectories}}}function buildSettingsValuesHealthCheck(settingWarnings,statusRoleDiagnostics){return{name:"settings_values",status:settingWarnings.length===0?"ok":"warn",ok:settingWarnings.length===0,details:{warnings:settingWarnings,...statusRoleDiagnostics.roleless_status_count>0?{lifecycle_status_roles:statusRoleDiagnostics}:{}}}}const resolveUnknownAuthorEventCount=authorAttribution=>authorAttribution.unknown_event_count??0;const resolveActionableUnknownAuthorEventCount=authorAttribution=>authorAttribution.actionable_unknown_event_count??resolveUnknownAuthorEventCount(authorAttribution);function buildStorageHealthCheck(items,settings,historySummary,authorAttribution,staleInProgress,provenanceResolverOutcomes,provenanceInvalidValues){const unknownAuthorEventCount=resolveUnknownAuthorEventCount(authorAttribution);const actionableUnknownAuthorEventCount=resolveActionableUnknownAuthorEventCount(authorAttribution);const hasAuthorEvents=unknownAuthorEventCount>0;const hasActionableAuthorWarnings=actionableUnknownAuthorEventCount>0;const hasStaleInProgressItems=staleInProgress.count>0;return{name:"storage",status:historySummary.over_threshold.length===0&&historySummary.orphaned.length===0&&!hasActionableAuthorWarnings&&!hasStaleInProgressItems?"ok":"warn",ok:historySummary.over_threshold.length===0&&historySummary.orphaned.length===0&&!hasActionableAuthorWarnings&&!hasStaleInProgressItems,details:{items:items.length,history_streams:historySummary.count,tombstones:{retention_policy:"retain_append_only",gc_enabled:false,count:historySummary.tombstones.length,ids:historySummary.tombstones.slice(0,25),truncated:historySummary.tombstones.length>25},orphaned_history_streams:{count:historySummary.orphaned.length,ids:historySummary.orphaned.slice(0,25),truncated:historySummary.orphaned.length>25},...hasAuthorEvents?{author_attribution:authorAttribution}:{},...hasStaleInProgressItems?{stale_in_progress:staleInProgress}:{},...provenanceResolverOutcomes.length>0?{provenance_resolver_outcomes:provenanceResolverOutcomes}:{},...provenanceInvalidValues.length>0?{provenance_invalid_values:provenanceInvalidValues}:{},...historySummary.max_entries!==null?{compact_policy:{enabled:settings.history.compact_policy.enabled,max_entries:historySummary.max_entries,trigger:settings.history.compact_policy.trigger,over_threshold_count:historySummary.over_threshold.length,over_threshold:historySummary.over_threshold}}:{}}}}function buildStaleInProgressHealthSummary(scan){const warnings=scan.count===0?[]:[`stale_in_progress_items:${scan.count}`];return{scan,warnings}}function collectHealthWarnings(params){const warnings=[...params.directoryState.missingDirs.map(dir=>`missing_directory:${dir}`),...params.normalizedSettingsReadWarnings,...params.settingWarnings,...params.normalizedItemReadWarnings,...params.telemetryCheck.warnings,...params.extensionCheck.warnings,...params.historyPolicyWarnings,...params.historySummary.warnings,...params.authorAttributionWarnings,...params.staleInProgressWarnings,...params.provenanceWarnings,...params.locksCheck.warnings,...params.integrityCheck.warnings,...params.historyDriftCheck.warnings,...params.vectorizationCheck.warnings,...params.directoryState.hookWarnings];return[...new Set(warnings)]}function extractHistoryDriftedCount(historyDriftCheck){const counts=historyDriftCheck.check.details.counts;return typeof counts?.drifted==="number"?counts.drifted:0}function buildHealthRemediationSources(params){return{settings:params.normalizedSettingsReadWarnings,directories:params.directoryState.missingDirs.map(dir=>`missing_directory:${dir}`).concat(params.directoryState.hookWarnings),settings_values:params.settingWarnings,telemetry:params.telemetryCheck.warnings,extensions:params.extensionCheck.warnings,storage:[...params.historyPolicyWarnings,...params.historySummary.warnings,...params.authorAttributionWarnings,...params.staleInProgressWarnings,...params.provenanceWarnings],locks:params.locksCheck.warnings,integrity:[...params.normalizedItemReadWarnings,...params.integrityCheck.warnings],history_drift:params.historyDriftCheck.warnings,vectorization:params.vectorizationCheck.warnings}}function buildHealthFindings(params){const owners=new Map;for(const[check,warnings]of Object.entries(params.remediationSources)){for(const warning of warnings){if(!owners.has(warning))owners.set(warning,check)}}const checksByName=new Map(params.checks.map(check=>[check.name,check]));const findings=params.warnings.map(warning=>{const check=owners.get(warning)??"integrity";const code=resolveRemediation(warning)?.code??warningCode(warning);const details=checksByName.get(check)?.details;const remediationMap=typeof details?.remediation_map==="object"&&details.remediation_map!==null?details.remediation_map:{};const remediation=remediationMap[code];const severity=isAdvisoryHealthWarning(warning,params.requireMergeDrivers)?"advisory":"gate_failing";return{warning,code,check,severity,...typeof remediation==="string"?{remediation}:severity==="gate_failing"?{disposition:"no_safe_automatic_remediation"}:{}}});return findings}function rewriteBulkHealthRemediation(params){if(params.check.name==="history_drift"&¶ms.historyDriftedCount>1){for(const code of Object.keys(params.remediationMap)){if(code!=="history_drift_merge_receipt"&&code!=="history_drift_version_skew"){params.remediationMap[code]="pm history-repair --all"}}}if(params.check.name==="storage"&¶ms.overThresholdCount>1){for(const code of Object.keys(params.remediationMap)){params.remediationMap[code]="pm history-compact --all-streams"}}}function attachHealthRemediationMaps(params){for(const check of params.checks){const remediationMap=buildRemediationMap(params.remediationSources[check.name]);rewriteBulkHealthRemediation({check,remediationMap,historyDriftedCount:params.historyDriftedCount,overThresholdCount:params.overThresholdCount});if(Object.keys(remediationMap).length>0){check.details={...check.details,remediation_map:remediationMap}}}}async function correlateMergeReceiptHistoryDriftItems(params){if(params.gitWorkspaceRoot===null||params.pendingMergeReceipts.length===0){return[]}const details=params.historyDriftCheck.check.details;const hashMismatches=Array.isArray(details.hash_mismatches)?details.hash_mismatches.filter(entry=>typeof entry==="string"):[];const unsafeStreamIds=new Set([details.missing_streams,details.unreadable_streams,details.chain_mismatches].flatMap(value=>Array.isArray(value)?value:[]));const cloneLocalReceiptsByItem=new Map;for(const receipt of params.pendingMergeReceipts){if(receipt.evidence_source!=="clone_local")continue;const receipts=cloneLocalReceiptsByItem.get(receipt.item_id)??[];receipts.push(receipt);cloneLocalReceiptsByItem.set(receipt.item_id,receipts)}const attributed=[];for(const id of hashMismatches){if(unsafeStreamIds.has(id))continue;const receipts=cloneLocalReceiptsByItem.get(id);if(!receipts||receipts.length===0)continue;try{await runHistoryRepair(id,{dryRun:true,mergeReceiptProof:{gitWorkspaceRoot:params.gitWorkspaceRoot,receipts}},params.global);attributed.push(id)}catch{}}return[...new Set(attributed)].sort((left,right)=>left.localeCompare(right))}function applyMergeReceiptHistoryDriftAttribution(historyDriftCheck,attributedItems){const attributed=new Set(attributedItems);historyDriftCheck.warnings=[...historyDriftCheck.warnings.filter(warning=>{if(!warning.startsWith("history_drift_hash_mismatch:"))return true;return!attributed.has(warning.slice(warning.indexOf(":")+1))}),...attributedItems.map(id=>`history_drift_merge_receipt:${id}`)].sort((left,right)=>left.localeCompare(right));historyDriftCheck.check.details={...historyDriftCheck.check.details,merge_receipt_attributed_items:attributedItems}}function projectHealthResult(result,options,summaryMode){const warningCount=result.warning_count??result.warnings.length;const boundedResult={...result,warning_count:warningCount,warning_limit:HEALTH_WARNING_LIMIT,warnings_truncated:warningCount>HEALTH_WARNING_LIMIT,warnings:result.warnings.slice(0,HEALTH_WARNING_LIMIT),findings:(result.findings??[]).filter(finding=>result.warnings.slice(0,HEALTH_WARNING_LIMIT).includes(finding.warning)||result.failed_because.includes(finding.warning))};const projected=summaryMode?applySummaryHealthProjection(boundedResult):options.brief===true?applyBriefHealthProjection(boundedResult):boundedResult;return{...projected,warning_count:warningCount,warning_limit:HEALTH_WARNING_LIMIT,warnings_truncated:warningCount>projected.warnings.length,...projected.projection?{projection:{...projected.projection,warning_count:warningCount,warnings_truncated:warningCount>projected.warnings.length}}:{}}}async function runHealth(global2,options={}){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const settingsPath=getSettingsPath(pmRoot);const{settings,warnings:settingsReadWarnings}=await readSettingsWithMetadata(pmRoot);const normalizedSettingsReadWarnings=[...new Set(settingsReadWarnings)];const typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations());const strictDirectories=options.strictDirectories===true;const strictExit=options.strictExit===true||options.failOnWarn===true;const requireMergeDrivers=options.requireMergeDrivers===true||strictExit;const refreshPolicy=resolveVectorRefreshPolicy(options);const directoryState=await scanHealthDirectories(pmRoot,typeRegistry,strictDirectories);const settingsValueWarnings=validateSettingsValues(settings);const telemetryCheck=await buildTelemetryCheck(settings,{checkTelemetry:options.checkTelemetry===true});const extensionCheck=await buildExtensionCheck(pmRoot,settings,Boolean(global2.noExtensions));const skipPolicy=resolveHealthSkipPolicy(options);const itemReadWarnings=[];const items=await readHealthItems({pmRoot,settings,typeRegistry,skipPolicy,itemReadWarnings});const itemsWithBody=items;const statusRoleDiagnostics=inspectStatusRoleAssignments(resolveRuntimeStatusRegistry(settings.schema),items);const settingWarnings=[...settingsValueWarnings,...buildStatusRoleWarnings(statusRoleDiagnostics)];const historyPolicy=skipPolicy.skipDrift?{warnings:[]}:await enforceHistoryStreamPolicyForItems({pmRoot,settings,itemIds:items.map(item=>item.id),commandLabel:"health"});const historySummary=await countHistoryStreams(pmRoot,settings.history.compact_policy,await listStoredItemDocumentIds(pmRoot));const authorAttribution=await scanHistoryAuthorAttribution(pmRoot,20,options.verboseAuthorEvents===true);const actionableUnknownAuthorEventCount=resolveActionableUnknownAuthorEventCount(authorAttribution);const authorAttributionWarnings=actionableUnknownAuthorEventCount>0?[`history_unknown_author_events:${actionableUnknownAuthorEventCount}`]:[];const staleInProgress=buildStaleInProgressHealthSummary(await scanStaleInProgressItems(pmRoot,items,{in_progress_status:settings.schema.workflow.in_progress_status,threshold_hours:settings.mutation_guard.stale_in_progress_hours}));const provenanceResolverHealth=await scanProvenanceResolverHealth(pmRoot);const provenanceResolverOutcomes=provenanceResolverHealth.outcomes;const provenanceInvalidValues=provenanceResolverHealth.invalid_values;const provenanceWarnings=provenanceResolverHealth.warnings;const locksCheck=await buildLocksCheck(pmRoot);const integrityCheck=skipPolicy.skipIntegrity&&!requireMergeDrivers?{...buildSkippedHealthCheck("integrity"),gitWorkspaceRoot:null,pendingMergeReceipts:[]}:await buildIntegrityCheck(pmRoot,typeRegistry.type_to_folder,settings.schema,requireMergeDrivers,items);const historyDriftCheck=skipPolicy.skipDrift?buildSkippedHealthCheck("history_drift"):await buildHistoryDriftCheck({pmRoot,items:itemsWithBody,settings,typeRegistry,itemReadWarnings});const normalizedItemReadWarnings=[...new Set(itemReadWarnings)];const mergeReceiptAttributedHistoryDriftItems=await correlateMergeReceiptHistoryDriftItems({gitWorkspaceRoot:integrityCheck.gitWorkspaceRoot,pendingMergeReceipts:integrityCheck.pendingMergeReceipts,historyDriftCheck,global:global2});applyMergeReceiptHistoryDriftAttribution(historyDriftCheck,mergeReceiptAttributedHistoryDriftItems);const vectorizationCheck=skipPolicy.skipVectors?buildSkippedHealthCheck("vectorization"):await buildVectorizationCheck(pmRoot,settings,itemsWithBody,refreshPolicy,options.verboseStaleItems===true);const checks=[buildSettingsHealthCheck(settingsPath,settings,normalizedSettingsReadWarnings),buildDirectoriesHealthCheck(directoryState,strictDirectories),buildSettingsValuesHealthCheck(settingWarnings,statusRoleDiagnostics),telemetryCheck.check,extensionCheck.check,buildStorageHealthCheck(items,settings,historySummary,authorAttribution,staleInProgress.scan,provenanceResolverOutcomes,provenanceInvalidValues),locksCheck.check,integrityCheck.check,historyDriftCheck.check,vectorizationCheck.check];const normalizedWarnings=collectHealthWarnings({directoryState,normalizedSettingsReadWarnings,settingWarnings,normalizedItemReadWarnings,telemetryCheck,extensionCheck,historyPolicyWarnings:historyPolicy.warnings,historySummary,authorAttributionWarnings,staleInProgressWarnings:staleInProgress.warnings,provenanceWarnings,locksCheck,integrityCheck,historyDriftCheck,vectorizationCheck});const remediationSources=buildHealthRemediationSources({directoryState,normalizedSettingsReadWarnings,settingWarnings,normalizedItemReadWarnings,telemetryCheck,extensionCheck,historyPolicyWarnings:historyPolicy.warnings,historySummary,authorAttributionWarnings,staleInProgressWarnings:staleInProgress.warnings,provenanceWarnings,locksCheck,integrityCheck,historyDriftCheck,vectorizationCheck});attachHealthRemediationMaps({checks,remediationSources,historyDriftedCount:extractHistoryDriftedCount(historyDriftCheck),overThresholdCount:historySummary.over_threshold.length});const blockingWarnings=normalizedWarnings.filter(warning=>!isAdvisoryHealthWarning(warning,requireMergeDrivers));const findings=buildHealthFindings({warnings:normalizedWarnings,checks,remediationSources,requireMergeDrivers});const failingChecks=new Set(findings.filter(finding=>finding.severity==="gate_failing").map(finding=>finding.check));const warningChecks=new Set(findings.map(finding=>finding.check));for(const check of checks){check.ok=!failingChecks.has(check.name);if(warningChecks.has(check.name))check.status="warn"}const result={ok:blockingWarnings.length===0,verdict:{authority:"ok",...strictExit?{strict_exit:true}:{},...requireMergeDrivers?{require_merge_drivers:true}:{},exit_code:strictExit&&blockingWarnings.length>0?EXIT_CODE.GENERIC_FAILURE:0},checks,warnings:normalizedWarnings,findings,failed_because:blockingWarnings,generated_at:nowIso()};return projectHealthResult(result,options,skipPolicy.summaryMode)}const _testOnlyHealthCommand={buildHierarchyIntegrityWarnings,buildExtensionHealthTriageSummary,buildHealthFindings,buildCapabilityContractMetadata,buildStaleInProgressHealthSummary,buildVectorizationProviderDetails,collectUnknownCapabilityGuidance,isAdvisoryHealthWarning,isDirectory,isExpectedUnmanagedExtension,listItemDocumentPaths,normalizeEndpointForDisplay,normalizeExtensionNameForMatch,parseTelemetryQueue,probeTelemetryEndpointHealth,projectHealthResult,resolveActionableUnknownAuthorEventCount,resolveHealthSkipPolicy,resolveUnknownAuthorEventCount,resolveVectorRefreshPolicy,selectStaleItemDetail,summarizeHealthCheckDetails,summarizeExtensionList,summarizeRecordList,summarizeStringList,telemetryEnvFlagEnabled,warningCode};export{_testOnlyHealthCommand,runHealth};
|
|
2367
2
|
//# sourceMappingURL=health.js.map
|
|
2368
|
-
//# debugId=cee8abad-51d2-5051-9cb8-81447bf2fd50
|