@unbrained/pm-cli 2026.11.21 → 2026.11.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.agents/skills/pm-developer/SKILL.md +1 -1
- package/.claude-plugin/marketplace.json +1 -1
- package/dist/cli/after-command-context-usage.js +1 -1
- package/dist/cli/argv-utils.js +1 -1
- package/dist/cli/bootstrap-args.js +1 -1
- package/dist/cli/bundle-integrity.js +2 -2
- package/dist/cli/command-namespaces.js +1 -1
- package/dist/cli/commander-usage.js +11 -11
- package/dist/cli/commands/annotations/comments.js +1 -1
- package/dist/cli/commands/annotations/docs.js +1 -1
- package/dist/cli/commands/annotations/files.js +1 -1
- package/dist/cli/commands/annotations/learnings.js +1 -1
- package/dist/cli/commands/annotations/notes.js +1 -1
- package/dist/cli/commands/extension/describe.js +1 -1
- package/dist/cli/commands/extension/extension.js +1 -1
- package/dist/cli/commands/extension/scaffold.js +1 -1
- package/dist/cli/commands/extension/shared.js +1 -1
- package/dist/cli/commands/governance/gc.js +1 -1
- package/dist/cli/commands/governance/health.js +1 -1
- package/dist/cli/commands/governance/telemetry.js +1 -1
- package/dist/cli/commands/governance/validate.js +1 -1
- package/dist/cli/commands/history/activity.js +1 -1
- package/dist/cli/commands/history/history-compact.js +1 -1
- package/dist/cli/commands/history/history-redact.js +1 -1
- package/dist/cli/commands/history/history-repair.js +1 -1
- package/dist/cli/commands/history/history.js +1 -1
- package/dist/cli/commands/history/restore.js +1 -1
- package/dist/cli/commands/lifecycle/append.js +1 -1
- package/dist/cli/commands/lifecycle/claim.js +1 -1
- package/dist/cli/commands/lifecycle/close-many.js +1 -1
- package/dist/cli/commands/lifecycle/close.js +1 -1
- package/dist/cli/commands/lifecycle/copy.js +1 -1
- package/dist/cli/commands/lifecycle/create.js +1 -1
- package/dist/cli/commands/lifecycle/delete.js +1 -1
- package/dist/cli/commands/lifecycle/focus.js +1 -1
- package/dist/cli/commands/lifecycle/plan.js +1 -1
- package/dist/cli/commands/lifecycle/update-many.js +1 -1
- package/dist/cli/commands/lifecycle/update.js +1 -1
- package/dist/cli/commands/query/aggregate.js +1 -1
- package/dist/cli/commands/query/context.js +1 -1
- package/dist/cli/commands/query/deps.js +1 -1
- package/dist/cli/commands/query/duplicates.js +1 -1
- package/dist/cli/commands/query/eval.js +1 -1
- package/dist/cli/commands/query/get.js +1 -1
- package/dist/cli/commands/query/graph.js +1 -1
- package/dist/cli/commands/query/list.js +1 -1
- package/dist/cli/commands/query/next.js +1 -1
- package/dist/cli/commands/query/search.js +1 -1
- package/dist/cli/commands/query/stats.js +1 -1
- package/dist/cli/commands/test/test-all.js +1 -1
- package/dist/cli/commands/test/test-runs.js +1 -1
- package/dist/cli/commands/test/test.js +1 -1
- package/dist/cli/commands/workspace/config.js +1 -1
- package/dist/cli/commands/workspace/contracts.js +1 -1
- package/dist/cli/commands/workspace/init.js +1 -1
- package/dist/cli/commands/workspace/merge.js +1 -1
- package/dist/cli/commands/workspace/profile.js +1 -1
- package/dist/cli/commands/workspace/schema.js +1 -1
- package/dist/cli/commands/workspace/upgrade.js +1 -1
- package/dist/cli/context-intent-invocation.js +1 -1
- package/dist/cli/description-stdin.js +1 -1
- package/dist/cli/error-guidance.js +5 -5
- package/dist/cli/expected-revisions.js +1 -1
- package/dist/cli/extension-command-help.js +6 -6
- package/dist/cli/extension-recovery.js +1 -1
- package/dist/cli/help-content.js +5 -5
- package/dist/cli/help-json-payload.js +7 -7
- package/dist/cli/invocation-profile.js +2 -2
- package/dist/cli/main.js +5 -5
- package/dist/cli/migration-gates.js +1 -1
- package/dist/cli/option-values.js +1 -1
- package/dist/cli/preflight-warnings.js +3 -3
- package/dist/cli/public.js +1 -1
- package/dist/cli/register-annotations.js +1 -1
- package/dist/cli/register-assurance.js +1 -1
- package/dist/cli/register-files-lookup.js +1 -1
- package/dist/cli/register-history-activity.js +1 -1
- package/dist/cli/register-history-author.js +1 -1
- package/dist/cli/register-history-maintenance.js +2 -2
- package/dist/cli/register-list-query.js +10 -10
- package/dist/cli/register-mutation-options.js +0 -1
- package/dist/cli/register-mutation.js +6 -6
- package/dist/cli/register-operations.js +1 -1
- package/dist/cli/register-setup.js +1 -1
- package/dist/cli/register-structured-mutation.js +1 -1
- package/dist/cli/registration-helpers.js +1 -1
- package/dist/cli/runtime/activation.js +1 -1
- package/dist/cli/runtime/annotation-option-retry.js +1 -1
- package/dist/cli/runtime/close-fields-retry.js +1 -1
- package/dist/cli/runtime/field-route-retry.js +1 -1
- package/dist/cli/runtime/invocation-options.js +1 -1
- package/dist/cli/runtime/invocation-rewrites.js +1 -1
- package/dist/cli/runtime/projection-retry.js +1 -1
- package/dist/cli/runtime/read-output-mutation-retry.js +1 -1
- package/dist/cli/runtime/refusal-credential-redaction.js +1 -1
- package/dist/cli/runtime/selection.js +1 -1
- package/dist/cli/runtime/telemetry-outcome.js +1 -1
- package/dist/cli/runtime-compatibility-boundary.js +4 -4
- package/dist/cli/schema/registration.js +15 -15
- package/dist/cli/schema-registration-helpers.js +1 -1
- package/dist/cli/search-refresh.js +1 -1
- package/dist/cli/stats-analytics-json.js +1 -1
- package/dist/cli/telemetry-flush.js +1 -1
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/chunk-2UQU7HRR.js +9 -0
- package/dist/cli-bundle/chunks/chunk-5DUP4AZA.js +2 -0
- package/dist/cli-bundle/chunks/chunk-5WZZ5XEN.js +3 -0
- package/dist/cli-bundle/chunks/chunk-6H36ZHMI.js +2 -0
- package/dist/cli-bundle/chunks/chunk-6MYJLOSG.js +2 -0
- package/dist/cli-bundle/chunks/chunk-AA52P34H.js +3 -0
- package/dist/cli-bundle/chunks/chunk-AEOHUSUI.js +2289 -0
- package/dist/cli-bundle/chunks/chunk-BSRIVYTM.js +8 -0
- package/dist/cli-bundle/chunks/chunk-CFWLQFJM.js +71 -0
- package/dist/cli-bundle/chunks/chunk-D6PDUKUG.js +9 -0
- package/dist/cli-bundle/chunks/chunk-ENKXRSFZ.js +31 -0
- package/dist/cli-bundle/chunks/chunk-F2Z6XLZB.js +3 -0
- package/dist/cli-bundle/chunks/chunk-FJOEL75F.js +2 -0
- package/dist/cli-bundle/chunks/chunk-GDXCAC52.js +2 -0
- package/dist/cli-bundle/chunks/chunk-H7JEXRIN.js +6 -0
- package/dist/cli-bundle/chunks/chunk-J2PDAVBC.js +2 -0
- package/dist/cli-bundle/chunks/chunk-KE7HMBEW.js +2 -0
- package/dist/cli-bundle/chunks/chunk-KZHIBEJL.js +33 -0
- package/dist/cli-bundle/chunks/chunk-NGJ5ERBF.js +115 -0
- package/dist/cli-bundle/chunks/chunk-NQ54T7T2.js +2 -0
- package/dist/cli-bundle/chunks/chunk-O7JHS64G.js +3 -0
- package/dist/cli-bundle/chunks/chunk-OKEZF7HU.js +2 -0
- package/dist/cli-bundle/chunks/chunk-OKIKF4FD.js +2 -0
- package/dist/cli-bundle/chunks/chunk-OPJF254V.js +9 -0
- package/dist/cli-bundle/chunks/chunk-PZA7QECY.js +1 -0
- package/dist/cli-bundle/chunks/chunk-RWA5YZ5X.js +2 -0
- package/dist/cli-bundle/chunks/chunk-S32NGRQM.js +2 -0
- package/dist/cli-bundle/chunks/chunk-SLFRSZK6.js +1 -0
- package/dist/cli-bundle/chunks/chunk-TZY5MVJF.js +125 -0
- package/dist/cli-bundle/chunks/chunk-YYT3MIRF.js +3 -0
- package/dist/cli-bundle/chunks/chunk-ZPS4B6SI.js +8 -0
- package/dist/cli-bundle/chunks/context-budget-recovery-M5RFUEFG.js +2 -0
- package/dist/cli-bundle/chunks/indexed-receipt-blobs-BPYKN5Q7.js +4 -0
- package/dist/cli-bundle/chunks/{item-revision-R5SZPJZ5.js → item-revision-FMD4KWBB.js} +2 -2
- package/dist/cli-bundle/chunks/item-transaction-SEHTH7N2.js +2 -0
- package/dist/cli-bundle/chunks/mutation-actor-SFGYIRPW.js +2 -0
- package/dist/cli-bundle/chunks/mutation-admission-57LBSKQI.js +2 -0
- package/dist/cli-bundle/chunks/{register-list-query-SPGPS3OS.js → register-list-query-L4IBU64P.js} +11 -11
- package/dist/cli-bundle/chunks/register-mutation-6NUOPHZ3.js +21 -0
- package/dist/cli-bundle/chunks/register-operations-JGYVORNN.js +2 -0
- package/dist/cli-bundle/chunks/register-setup-C44SIXEH.js +2 -0
- package/dist/cli-bundle/chunks/settlement-hook-6MR32OOC.js +7 -0
- package/dist/cli-bundle/chunks/stage-PQ7AB63N.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-6LKTEKHS.js +6 -0
- package/dist/cli-bundle/focused-chunks/chunk-6LPXMFLM.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-A6VEMCRR.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-AIDL2ZNT.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-BKPUUW5O.js +1 -0
- package/dist/cli-bundle/focused-chunks/chunk-BWOVFE5B.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-HMDQDRV2.js +8 -0
- package/dist/cli-bundle/focused-chunks/chunk-I66IKYKP.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-IIP6LZ5E.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-IR2J3NOT.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-IROZDIDX.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-ITKDHSBR.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-K53OIT5J.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-LQYYPXUK.js +26 -0
- package/dist/cli-bundle/focused-chunks/chunk-NQTEE66P.js +13 -0
- package/dist/cli-bundle/focused-chunks/chunk-O7Z73ALG.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-OTMMOKPM.js +91 -0
- package/dist/cli-bundle/focused-chunks/chunk-OXOCZJC6.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-QLAHEDT6.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-QQIIMMFU.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-RIE3SJSE.js +9 -0
- package/dist/cli-bundle/focused-chunks/chunk-TD544C74.js +8 -0
- package/dist/cli-bundle/focused-chunks/chunk-UFTUNBMY.js +27 -0
- package/dist/cli-bundle/focused-chunks/chunk-X6CXWWNB.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-XRS3VNC6.js +44 -0
- package/dist/cli-bundle/focused-chunks/chunk-XYPEZGTR.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-Y2ESLKCF.js +8 -0
- package/dist/cli-bundle/focused-chunks/chunk-YSJKQLFR.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-Z2X7HH3C.js +102 -0
- package/dist/cli-bundle/focused-chunks/chunk-ZHWPCVQL.js +78 -0
- package/dist/cli-bundle/focused-chunks/context-budget-recovery-CSJV3TY3.js +2 -0
- package/dist/cli-bundle/focused-chunks/indexed-receipt-blobs-EGEJMG3G.js +4 -0
- package/dist/cli-bundle/focused-chunks/{item-revision-3V3UIP5X.js → item-revision-YDACCDVY.js} +2 -2
- package/dist/cli-bundle/focused-chunks/item-transaction-UKEQCTKB.js +2 -0
- package/dist/cli-bundle/focused-chunks/mutation-actor-AS465LRX.js +2 -0
- package/dist/cli-bundle/focused-chunks/mutation-admission-E5UHJZFE.js +2 -0
- package/dist/cli-bundle/focused-chunks/settlement-hook-FMLGKG7J.js +7 -0
- package/dist/cli-bundle/focused-chunks/stage-36J7YLGI.js +2 -0
- package/dist/cli-bundle/main.js +27 -27
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +5 -5
- package/dist/cli-bundle/sdk-core.js +1 -1
- package/dist/cli-bundle/sdk-governance.js +1 -1
- package/dist/cli-bundle/sdk-graph.js +1 -1
- package/dist/cli-bundle/sdk-merge.js +72 -60
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +13 -13
- package/dist/cli.js +1 -1
- package/dist/core/checkpoint/checkpoint-gc.js +1 -1
- package/dist/core/checkpoint/mutation-checkpoint.js +2 -2
- package/dist/core/checkpoint/mutation-context.js +1 -1
- package/dist/core/config/nested-settings.js +1 -1
- package/dist/core/config/positional-value.js +1 -1
- package/dist/core/diagnostics/remediation.js +1 -1
- package/dist/core/extensions/activation-summary-markdown.js +2 -2
- package/dist/core/extensions/activation-summary.js +1 -1
- package/dist/core/extensions/activation-transaction.js +1 -1
- package/dist/core/extensions/capability-usage.js +1 -1
- package/dist/core/extensions/command-hook-context.js +1 -1
- package/dist/core/extensions/command-metadata-contract.js +1 -1
- package/dist/core/extensions/command-visibility-tier.js +1 -1
- package/dist/core/extensions/contribution-inventory.js +1 -1
- package/dist/core/extensions/exporter-output-contract.js +1 -1
- package/dist/core/extensions/extension-candidate.js +1 -1
- package/dist/core/extensions/extension-capability-aliases.js +1 -1
- package/dist/core/extensions/extension-hook-runtime.js +1 -1
- package/dist/core/extensions/extension-policy.js +1 -1
- package/dist/core/extensions/extension-registries.js +1 -1
- package/dist/core/extensions/extension-runtime-helpers.js +1 -1
- package/dist/core/extensions/extension-types.js +1 -1
- package/dist/core/extensions/flag-definition-validation.js +1 -1
- package/dist/core/extensions/flag-value-types.js +1 -1
- package/dist/core/extensions/index.js +1 -1
- package/dist/core/extensions/item-field-types.js +1 -1
- package/dist/core/extensions/item-fields.js +1 -1
- package/dist/core/extensions/loader.js +1 -1
- package/dist/core/extensions/manifest-parser.js +1 -1
- package/dist/core/extensions/manifest-schema.js +1 -1
- package/dist/core/extensions/module-graph-snapshot.js +1 -1
- package/dist/core/extensions/mutation-actor-snapshot.js +1 -1
- package/dist/core/extensions/mutation-actor.js +1 -1
- package/dist/core/extensions/preflight-ownership.js +1 -1
- package/dist/core/extensions/read-output-contract.js +1 -1
- package/dist/core/extensions/registration-contracts.js +1 -1
- package/dist/core/extensions/registration-validation.js +1 -1
- package/dist/core/extensions/registration-values.js +1 -1
- package/dist/core/extensions/reserved-host-flags.js +1 -1
- package/dist/core/extensions/runtime-registrations.js +1 -1
- package/dist/core/extensions/service-ownership.js +1 -1
- package/dist/core/extensions/version-compat.js +1 -1
- package/dist/core/extensions/version-diagnostics.js +1 -1
- package/dist/core/fs/atomic-create.js +1 -1
- package/dist/core/fs/file-glob.js +1 -1
- package/dist/core/fs/fs-utils.js +2 -2
- package/dist/core/fs/host-environment-errors.js +1 -1
- package/dist/core/fs/index.js +1 -1
- package/dist/core/fs/path-utils.js +1 -1
- package/dist/core/governance/content-fields.js +1 -1
- package/dist/core/governance/issue-codes.js +1 -1
- package/dist/core/governance/metadata-coverage.js +1 -1
- package/dist/core/history/bridge.js +2 -0
- package/dist/core/history/digest.js +1 -1
- package/dist/core/history/drift-cache.js +3 -3
- package/dist/core/history/drift-scan.js +1 -1
- package/dist/core/history/event-classification.js +1 -1
- package/dist/core/history/event-index.js +11 -11
- package/dist/core/history/history-compact-bulk.js +1 -1
- package/dist/core/history/history-diff.js +1 -1
- package/dist/core/history/history-rewrite.js +1 -1
- package/dist/core/history/history-storage-stats.js +1 -1
- package/dist/core/history/history-stream-policy.js +1 -1
- package/dist/core/history/history.d.ts +12 -0
- package/dist/core/history/history.js +2 -2
- package/dist/core/history/identity.js +1 -1
- package/dist/core/history/index.js +1 -1
- package/dist/core/history/operation-contract.js +1 -1
- package/dist/core/history/projection.js +1 -1
- package/dist/core/history/read.d.ts +9 -0
- package/dist/core/history/read.js +1 -1
- package/dist/core/history/replay.d.ts +46 -5
- package/dist/core/history/replay.js +2 -2
- package/dist/core/history/stream-summary.js +2 -2
- package/dist/core/history/tombstone.js +1 -1
- package/dist/core/history/version-address.js +1 -1
- package/dist/core/history/workspace-history.js +2 -2
- package/dist/core/io/body-file.js +1 -1
- package/dist/core/io/bulk-ids-input.js +2 -2
- package/dist/core/item/actionability.js +1 -1
- package/dist/core/item/deferred-fields.js +1 -1
- package/dist/core/item/dependency-reference.js +1 -1
- package/dist/core/item/id.js +1 -1
- package/dist/core/item/index.js +1 -1
- package/dist/core/item/item-format-version.js +1 -1
- package/dist/core/item/item-format.js +7 -7
- package/dist/core/item/item-record.js +1 -1
- package/dist/core/item/item-type-definition.js +1 -1
- package/dist/core/item/literal-mutation-input.js +1 -1
- package/dist/core/item/parent-reference-policy.js +1 -1
- package/dist/core/item/parse.js +8 -8
- package/dist/core/item/plan-lifecycle.js +1 -1
- package/dist/core/item/priority.js +1 -1
- package/dist/core/item/sprint-release-format.js +1 -1
- package/dist/core/item/status-filter.js +1 -1
- package/dist/core/item/status.js +1 -1
- package/dist/core/item/toon-decode.js +1 -1
- package/dist/core/item/type-registry.js +1 -1
- package/dist/core/item/type-synonyms.js +1 -1
- package/dist/core/lock/index.js +1 -1
- package/dist/core/lock/lock-confinement.js +1 -1
- package/dist/core/lock/lock-gc.js +1 -1
- package/dist/core/lock/lock-owner.js +1 -1
- package/dist/core/lock/lock.js +4 -4
- package/dist/core/output/linked-test-projection.js +5 -5
- package/dist/core/output/mutation-projection.js +1 -1
- package/dist/core/output/output-control.js +1 -1
- package/dist/core/output/output.js +19 -19
- package/dist/core/output/query-summary.js +1 -1
- package/dist/core/output/tabular.js +3 -3
- package/dist/core/packages/manifest.js +1 -1
- package/dist/core/packages/root.js +1 -1
- package/dist/core/policy/workflow-policy-schema.js +1 -1
- package/dist/core/policy/workflow-policy-store.js +1 -1
- package/dist/core/policy/workflow-policy.js +1 -1
- package/dist/core/profile/profile-describe.js +1 -1
- package/dist/core/profile/profile-lint.d.ts +1 -1
- package/dist/core/profile/profile-lint.js +1 -1
- package/dist/core/profile/profile-plan.js +1 -1
- package/dist/core/profile/profile-presets.js +4 -4
- package/dist/core/reproducibility/context.js +1 -1
- package/dist/core/schema/fields-file.js +2 -2
- package/dist/core/schema/item-types-file.js +2 -2
- package/dist/core/schema/runtime-field-filters.js +1 -1
- package/dist/core/schema/runtime-field-values.js +1 -1
- package/dist/core/schema/runtime-schema.js +2 -2
- package/dist/core/schema/status-defs-file.js +2 -2
- package/dist/core/schema/status-token.js +1 -1
- package/dist/core/schema/type-inference.js +1 -1
- package/dist/core/schema/type-presets.js +1 -1
- package/dist/core/schema/type-workflows.js +1 -1
- package/dist/core/search/background-refresh.js +2 -2
- package/dist/core/search/bm25.js +1 -1
- package/dist/core/search/cache.js +2 -2
- package/dist/core/search/corpus.js +1 -1
- package/dist/core/search/embedding-batches.js +1 -1
- package/dist/core/search/eval-thresholds.js +1 -1
- package/dist/core/search/eval.js +1 -1
- package/dist/core/search/http-client.js +1 -1
- package/dist/core/search/providers.js +1 -1
- package/dist/core/search/relevance.js +1 -1
- package/dist/core/search/semantic-defaults.js +1 -1
- package/dist/core/search/staleness.js +1 -1
- package/dist/core/search/vector-stores.js +2 -2
- package/dist/core/search/vectorization-metadata.js +1 -1
- package/dist/core/sentry/helpers.js +1 -1
- package/dist/core/sentry/instrument.js +1 -1
- package/dist/core/sentry/sensitive-assignments.js +1 -1
- package/dist/core/session/session-state.js +1 -1
- package/dist/core/shared/agent-session-context.js +1 -1
- package/dist/core/shared/author.js +5 -5
- package/dist/core/shared/command-line.js +1 -1
- package/dist/core/shared/command-types.js +0 -1
- package/dist/core/shared/conflict-markers.js +1 -1
- package/dist/core/shared/constants.js +1 -1
- package/dist/core/shared/error-details.js +1 -1
- package/dist/core/shared/errors.js +1 -1
- package/dist/core/shared/html-entity-decode.js +1 -1
- package/dist/core/shared/index.js +1 -1
- package/dist/core/shared/item-metadata-contract.js +1 -1
- package/dist/core/shared/lazy-module.js +1 -1
- package/dist/core/shared/levenshtein.js +1 -1
- package/dist/core/shared/memo.js +1 -1
- package/dist/core/shared/numeric-parsers.js +1 -1
- package/dist/core/shared/option-alias-visibility.js +1 -1
- package/dist/core/shared/output-unicode.js +1 -1
- package/dist/core/shared/primitives.js +1 -1
- package/dist/core/shared/process-tree.js +2 -2
- package/dist/core/shared/secret-rules.js +5 -5
- package/dist/core/shared/serial-queue.js +1 -1
- package/dist/core/shared/serialization.js +1 -1
- package/dist/core/shared/split-comma-list.js +1 -1
- package/dist/core/shared/text-normalization.js +1 -1
- package/dist/core/shared/time.js +2 -2
- package/dist/core/shared/url-credentials.js +1 -1
- package/dist/core/store/index.js +1 -1
- package/dist/core/store/item-format-migration.js +1 -1
- package/dist/core/store/item-metadata-cache.js +1 -1
- package/dist/core/store/item-metadata-query-index.js +11 -11
- package/dist/core/store/item-metadata-read-work.js +1 -1
- package/dist/core/store/item-mutation-precondition.js +1 -1
- package/dist/core/store/item-store.js +1 -1
- package/dist/core/store/paths.js +1 -1
- package/dist/core/store/settings-concurrency.js +1 -1
- package/dist/core/store/settings-read-cache.js +1 -1
- package/dist/core/store/settings-sections.js +2 -2
- package/dist/core/store/settings-validator.js +1 -1
- package/dist/core/store/settings.d.ts +3 -1
- package/dist/core/store/settings.js +6 -6
- package/dist/core/store/sqlite-runtime.js +1 -1
- package/dist/core/store/tracker-preflight.js +1 -1
- package/dist/core/store/transaction-coordinator-scope.js +1 -1
- package/dist/core/telemetry/consent.js +3 -3
- package/dist/core/telemetry/observability.js +1 -1
- package/dist/core/telemetry/policy.js +1 -1
- package/dist/core/telemetry/read-sampling.js +2 -2
- package/dist/core/telemetry/runtime.js +9 -9
- package/dist/core/test/background-runs.js +4 -4
- package/dist/core/test/item-test-run-tracking.js +1 -1
- package/dist/core/test/run-selectors.js +1 -1
- package/dist/core/validate/estimate-defaults.js +1 -1
- package/dist/core/validate/fix-planning.js +1 -1
- package/dist/core/validate/linked-artifact-reference.js +1 -1
- package/dist/core/validate/missing-by-type.js +1 -1
- package/dist/core/validate/missing-link-owners.js +1 -1
- package/dist/core/validate/stale-file-classification.js +1 -1
- package/dist/mcp/http-server.js +5 -5
- package/dist/mcp/legacy-adapter.js +1 -1
- package/dist/mcp/runtime-capabilities.js +1 -1
- package/dist/mcp/server.js +4 -4
- package/dist/mcp/tool-definitions.js +1 -1
- package/dist/sdk/actionability.js +1 -1
- package/dist/sdk/agent/closed-domain-contracts.js +1 -1
- package/dist/sdk/agent/command-recovery.js +1 -1
- package/dist/sdk/agent/command-suggestions.js +1 -1
- package/dist/sdk/agent/create-option-policy.js +1 -1
- package/dist/sdk/agent/identity-config.js +1 -1
- package/dist/sdk/agent/item-addressing.js +1 -1
- package/dist/sdk/agent/linked-resource-recovery.js +1 -1
- package/dist/sdk/agent/refusal-closure-census.js +2 -2
- package/dist/sdk/agent/refusal-corpus-contracts.js +1 -1
- package/dist/sdk/agent/subcommand-recovery.js +1 -1
- package/dist/sdk/agent-capability-contracts.js +3 -3
- package/dist/sdk/agent-session-context.js +1 -1
- package/dist/sdk/annotations.js +1 -1
- package/dist/sdk/author-attribution.js +1 -1
- package/dist/sdk/cli-bootstrap.js +1 -1
- package/dist/sdk/cli-contracts/agent-output-contracts.js +5 -5
- package/dist/sdk/cli-contracts/bootstrap-command-scanner.js +1 -1
- package/dist/sdk/cli-contracts/command-aliases.js +1 -1
- package/dist/sdk/cli-contracts/command-exit-contracts.js +1 -1
- package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1
- package/dist/sdk/cli-contracts/commander-types.js +1 -1
- package/dist/sdk/cli-contracts/completeness.js +1 -1
- package/dist/sdk/cli-contracts/enum-contracts.js +1 -1
- package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
- package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +2 -2
- package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
- package/dist/sdk/cli-contracts/registration-helpers.js +7 -7
- package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
- package/dist/sdk/cli-contracts/schemas/assurance-definition.js +1 -1
- package/dist/sdk/cli-contracts/string-lists.js +1 -1
- package/dist/sdk/cli-contracts/tool-option-contracts.js +1 -1
- package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
- package/dist/sdk/cli-contracts/tool-schema.js +1 -1
- package/dist/sdk/cli-contracts/typed-action-inputs.d.ts +2 -2
- package/dist/sdk/cli-contracts/typed-action-inputs.js +0 -1
- package/dist/sdk/cli-contracts.js +1 -1
- package/dist/sdk/cli-program.js +1 -1
- package/dist/sdk/command-line.js +1 -1
- package/dist/sdk/comments.js +1 -1
- package/dist/sdk/compile-cache.js +1 -1
- package/dist/sdk/completion/bash.js +2 -2
- package/dist/sdk/completion/fish.js +74 -73
- package/dist/sdk/completion/shared.js +1 -1
- package/dist/sdk/completion/zsh.js +77 -76
- package/dist/sdk/completion.js +1 -1
- package/dist/sdk/config.js +1 -1
- package/dist/sdk/context/recency.js +1 -1
- package/dist/sdk/context/semantic-session-attribution.js +1 -1
- package/dist/sdk/context/usage-egress.js +1 -1
- package/dist/sdk/context/usage-ledger.js +6 -6
- package/dist/sdk/context-intent-contracts.js +1 -1
- package/dist/sdk/context-intent-runtime.js +1 -1
- package/dist/sdk/context-packing.js +1 -1
- package/dist/sdk/context-relevance.js +1 -1
- package/dist/sdk/context-signal-store.js +2 -2
- package/dist/sdk/context-usage.js +1 -1
- package/dist/sdk/dependencies/context-budget-recovery.js +1 -1
- package/dist/sdk/dependencies.js +1 -1
- package/dist/sdk/dependency-flag-validation.js +1 -1
- package/dist/sdk/dependency-provenance.js +1 -1
- package/dist/sdk/docs.js +1 -1
- package/dist/sdk/duplicates.js +1 -1
- package/dist/sdk/environment/host-environment-errors.js +1 -1
- package/dist/sdk/environment/project-runtime-compatibility.js +2 -2
- package/dist/sdk/environment/source-context.js +1 -1
- package/dist/sdk/environment/tracker-preflight.js +1 -1
- package/dist/sdk/error-code-catalog.js +1 -1
- package/dist/sdk/error-runtime.js +1 -1
- package/dist/sdk/errors.js +1 -1
- package/dist/sdk/eval.js +1 -1
- package/dist/sdk/extension/author-manifest.js +1 -1
- package/dist/sdk/extension/bundled-catalog.js +1 -1
- package/dist/sdk/extension/command-options.js +1 -1
- package/dist/sdk/extension/concurrency.js +1 -1
- package/dist/sdk/extension/copy-scope.js +1 -1
- package/dist/sdk/extension/custom-field-collisions.js +1 -1
- package/dist/sdk/extension/describe.js +3 -3
- package/dist/sdk/extension/doctor.js +1 -1
- package/dist/sdk/extension/install-plan.js +1 -1
- package/dist/sdk/extension/install-receipts.js +1 -1
- package/dist/sdk/extension/install-runtime.js +3 -3
- package/dist/sdk/extension/install-snapshot.js +1 -1
- package/dist/sdk/extension/install-sources.js +5 -5
- package/dist/sdk/extension/managed-state.js +2 -2
- package/dist/sdk/extension/managed-update-status.js +1 -1
- package/dist/sdk/extension/migrations.js +2 -2
- package/dist/sdk/extension/native-command-options.js +1 -1
- package/dist/sdk/extension/output-ownership.js +1 -1
- package/dist/sdk/extension/runtime-summary.js +1 -1
- package/dist/sdk/extension/scaffold.js +11 -11
- package/dist/sdk/extension/shared.js +1 -1
- package/dist/sdk/extension/source-resolution.js +1 -1
- package/dist/sdk/extension/static-inventory.js +1 -1
- package/dist/sdk/extension/update-check.js +1 -1
- package/dist/sdk/extension-command-context.js +2 -2
- package/dist/sdk/extension-contracts.js +1 -1
- package/dist/sdk/extension.js +1 -1
- package/dist/sdk/files.js +1 -1
- package/dist/sdk/flag-invocation-contracts.js +1 -1
- package/dist/sdk/generated/error-code-catalog-rows.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
- package/dist/sdk/generated-error-code-catalog.js +1 -1
- package/dist/sdk/governance/assurance-action-contracts.js +0 -1
- package/dist/sdk/governance/assurance-action.js +1 -1
- package/dist/sdk/governance/assurance-limits.js +1 -1
- package/dist/sdk/governance/assurance-mutation-error.js +1 -1
- package/dist/sdk/governance/assurance-presets.js +1 -1
- package/dist/sdk/governance/assurance-runtime.js +1 -1
- package/dist/sdk/governance/assurance.js +4 -4
- package/dist/sdk/governance/boundary-fixtures.js +1 -1
- package/dist/sdk/governance/closure-timestamps.js +1 -1
- package/dist/sdk/governance/defect-recurrence-coverage.js +1 -1
- package/dist/sdk/governance/defect-recurrence-graph.js +1 -1
- package/dist/sdk/governance/defect-recurrence-signals.js +1 -1
- package/dist/sdk/governance/defect-recurrence.js +2 -2
- package/dist/sdk/governance/extension-host-version.js +1 -1
- package/dist/sdk/governance/gc.js +1 -1
- package/dist/sdk/governance/health/history-drift-remedies.js +2 -0
- package/dist/sdk/governance/health/projection.js +1 -1
- package/dist/sdk/governance/health-merge-evidence.js +1 -1
- package/dist/sdk/governance/health.js +2 -2
- package/dist/sdk/governance/hierarchy-validation.js +1 -1
- package/dist/sdk/governance/in-progress-work-health.js +1 -1
- package/dist/sdk/governance/lifecycle-dependency-cycles.js +1 -1
- package/dist/sdk/governance/linked-file-report.js +1 -1
- package/dist/sdk/governance/merge-receipt-history.js +1 -1
- package/dist/sdk/governance/provenance-health.js +4 -4
- package/dist/sdk/governance/reindex.js +5 -5
- package/dist/sdk/governance/stale-work.js +1 -1
- package/dist/sdk/governance/status-role-diagnostics.js +1 -1
- package/dist/sdk/governance/storage-integrity.js +1 -1
- package/dist/sdk/governance/tracked-runtime-cache.js +1 -1
- package/dist/sdk/governance/upgrade.js +2 -2
- package/dist/sdk/governance/validate-deferred-fields.js +1 -1
- package/dist/sdk/governance/validate-history-drift.js +1 -1
- package/dist/sdk/governance/validate-item-reader.js +1 -1
- package/dist/sdk/governance/validate-normalization.js +1 -1
- package/dist/sdk/governance/validate.js +1 -1
- package/dist/sdk/governance/workflow-completeness.js +1 -1
- package/dist/sdk/governance/workflow-policy.js +3 -3
- package/dist/sdk/governance/workspace-position.js +2 -2
- package/dist/sdk/graph/analytics.js +1 -1
- package/dist/sdk/graph/assembly.js +1 -1
- package/dist/sdk/graph/cache.js +1 -1
- package/dist/sdk/graph/cardinality-integrity.js +1 -1
- package/dist/sdk/graph/centrality.js +1 -1
- package/dist/sdk/graph/deadline-scheduling.js +1 -1
- package/dist/sdk/graph/durable-cache.js +1 -1
- package/dist/sdk/graph/governance-contracts.js +1 -1
- package/dist/sdk/graph/governance.js +1 -1
- package/dist/sdk/graph/hierarchy-integrity.js +1 -1
- package/dist/sdk/graph/lifecycle-coverage.js +1 -1
- package/dist/sdk/graph/mutation-advisory.js +1 -1
- package/dist/sdk/graph/query-contracts.js +1 -1
- package/dist/sdk/graph/remediation.js +1 -1
- package/dist/sdk/graph/run.js +1 -1
- package/dist/sdk/graph/scheduling.js +1 -1
- package/dist/sdk/graph/traversal.js +1 -1
- package/dist/sdk/graph/workspace-relationship-kind-registry.js +1 -1
- package/dist/sdk/guide-topics.js +1 -1
- package/dist/sdk/guide.js +7 -7
- package/dist/sdk/history/append-only-repair.d.ts +30 -0
- package/dist/sdk/history/append-only-repair.js +6 -0
- package/dist/sdk/history/attestation-command.js +2 -2
- package/dist/sdk/history/attestation-contract.js +1 -1
- package/dist/sdk/history/attestation-scan.js +1 -1
- package/dist/sdk/history/attestation.js +1 -1
- package/dist/sdk/history/maintenance.d.ts +8 -2
- package/dist/sdk/history/maintenance.js +1 -1
- package/dist/sdk/history/reanchor-refusal.js +2 -0
- package/dist/sdk/history/reseed.d.ts +15 -0
- package/dist/sdk/history/reseed.js +2 -0
- package/dist/sdk/history/salvage.d.ts +19 -8
- package/dist/sdk/history/salvage.js +5 -3
- package/dist/sdk/history/subject.js +1 -1
- package/dist/sdk/history-analytics.js +1 -1
- package/dist/sdk/history-compact.js +1 -1
- package/dist/sdk/history-mcp.js +1 -1
- package/dist/sdk/history-provenance.js +1 -1
- package/dist/sdk/history-read.js +1 -1
- package/dist/sdk/history-redact.js +1 -1
- package/dist/sdk/history-repair.d.ts +8 -2
- package/dist/sdk/history-repair.js +1 -1
- package/dist/sdk/improvement-ledger-validation.js +1 -1
- package/dist/sdk/improvement-ledger.js +2 -2
- package/dist/sdk/index.d.ts +1 -1
- package/dist/sdk/init-agent-guidance.js +10 -10
- package/dist/sdk/init.js +14 -14
- package/dist/sdk/invocation-author.js +1 -1
- package/dist/sdk/item-children.js +1 -1
- package/dist/sdk/item-metadata-index.js +1 -1
- package/dist/sdk/item-schedule.js +1 -1
- package/dist/sdk/item-transaction.d.ts +33 -1
- package/dist/sdk/item-transaction.js +1 -1
- package/dist/sdk/learnings.js +1 -1
- package/dist/sdk/lifecycle/append.js +3 -3
- package/dist/sdk/lifecycle/checkpoint-rollback.js +1 -1
- package/dist/sdk/lifecycle/claim.js +1 -1
- package/dist/sdk/lifecycle/cli-input.js +1 -1
- package/dist/sdk/lifecycle/close-many.js +1 -1
- package/dist/sdk/lifecycle/close.js +1 -1
- package/dist/sdk/lifecycle/copy.js +1 -1
- package/dist/sdk/lifecycle/core-field-recovery.js +1 -1
- package/dist/sdk/lifecycle/core-item-fields.js +1 -1
- package/dist/sdk/lifecycle/create-deferrals.js +1 -1
- package/dist/sdk/lifecycle/create.js +1 -1
- package/dist/sdk/lifecycle/delete.js +1 -1
- package/dist/sdk/lifecycle/dependency-removal.js +1 -1
- package/dist/sdk/lifecycle/event-validation-messages.js +1 -1
- package/dist/sdk/lifecycle/focus.js +1 -1
- package/dist/sdk/lifecycle/hierarchy-mutation-lock.js +1 -1
- package/dist/sdk/lifecycle/item-revision.js +1 -1
- package/dist/sdk/lifecycle/legacy-none-tokens.js +1 -1
- package/dist/sdk/lifecycle/lifecycle-transitions.js +1 -1
- package/dist/sdk/lifecycle/mcp-actions.js +1 -1
- package/dist/sdk/lifecycle/metadata-normalizers.js +1 -1
- package/dist/sdk/lifecycle/mutation-command-options.js +0 -1
- package/dist/sdk/lifecycle/mutation-facet-contracts.js +1 -1
- package/dist/sdk/lifecycle/mutation-option-validation.js +1 -1
- package/dist/sdk/lifecycle/plan-mutation-receipt.js +1 -1
- package/dist/sdk/lifecycle/plan.js +1 -1
- package/dist/sdk/lifecycle/recurrence-parsers.js +1 -1
- package/dist/sdk/lifecycle/release-handoff.js +1 -1
- package/dist/sdk/lifecycle/reopen.js +1 -1
- package/dist/sdk/lifecycle/repeatable-metadata-parsers.js +2 -2
- package/dist/sdk/lifecycle/repeated-terminal-state.js +1 -1
- package/dist/sdk/lifecycle/restore.js +1 -1
- package/dist/sdk/lifecycle/shared-unset-fields.js +1 -1
- package/dist/sdk/lifecycle/start-blockers.js +1 -1
- package/dist/sdk/lifecycle/structured-mutation-plan.js +1 -1
- package/dist/sdk/lifecycle/task-composition.js +1 -1
- package/dist/sdk/lifecycle/update-many.js +1 -1
- package/dist/sdk/lifecycle/update.js +2 -2
- package/dist/sdk/lifecycle/workflow-transition.js +1 -1
- package/dist/sdk/lifecycle-completion.js +1 -1
- package/dist/sdk/lifecycle-policy.js +1 -1
- package/dist/sdk/linked-artifacts.js +2 -2
- package/dist/sdk/mcp/apps.js +5 -5
- package/dist/sdk/mcp/authorization.js +1 -1
- package/dist/sdk/mcp/discovery.js +1 -1
- package/dist/sdk/mcp/executable.js +4 -4
- package/dist/sdk/mcp/interactions.js +1 -1
- package/dist/sdk/mcp/protocol.js +1 -1
- package/dist/sdk/mcp/skills.js +3 -3
- package/dist/sdk/mcp/subscriptions.js +1 -1
- package/dist/sdk/mcp/tasks.js +2 -2
- package/dist/sdk/mcp/transport.js +1 -1
- package/dist/sdk/merge/abandoned-receipts.js +1 -1
- package/dist/sdk/merge/driver.js +7 -7
- package/dist/sdk/merge/history-scalar-rebase.js +1 -1
- package/dist/sdk/merge/ignored-artifacts.js +1 -1
- package/dist/sdk/merge/index.js +1 -1
- package/dist/sdk/merge/indexed-receipt-blobs.js +2 -2
- package/dist/sdk/merge/install.js +6 -6
- package/dist/sdk/merge/receipt-file-boundary.js +1 -1
- package/dist/sdk/merge/receipt-operation.js +1 -1
- package/dist/sdk/merge/receipt-schema.js +1 -1
- package/dist/sdk/merge/receipts.js +4 -4
- package/dist/sdk/merge/reconcile.js +1 -1
- package/dist/sdk/merge/settlement-hook.js +4 -4
- package/dist/sdk/merge/stage.js +1 -1
- package/dist/sdk/merge/three-way.d.ts +22 -3
- package/dist/sdk/merge/three-way.js +9 -3
- package/dist/sdk/merge/worktree-config.js +2 -2
- package/dist/sdk/merge.js +1 -1
- package/dist/sdk/mutation-events.js +1 -1
- package/dist/sdk/mutation-guard.js +1 -1
- package/dist/sdk/notes.js +1 -1
- package/dist/sdk/output/fit-envelope.js +1 -1
- package/dist/sdk/output/list-envelope.js +1 -1
- package/dist/sdk/output/table-rows.js +1 -1
- package/dist/sdk/output-contracts.js +1 -1
- package/dist/sdk/output-projection.js +1 -1
- package/dist/sdk/output-token-accounting.js +1 -1
- package/dist/sdk/output.js +2 -2
- package/dist/sdk/ownership-source.js +1 -1
- package/dist/sdk/package-import-adapters.js +1 -1
- package/dist/sdk/package-migrations.js +1 -1
- package/dist/sdk/package-runtime-options.js +1 -1
- package/dist/sdk/pagination.js +1 -1
- package/dist/sdk/profile.js +5 -5
- package/dist/sdk/provenance.js +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/query/activity.js +1 -1
- package/dist/sdk/query/aggregate.js +1 -1
- package/dist/sdk/query/calendar.js +4 -4
- package/dist/sdk/query/complete-list.js +1 -1
- package/dist/sdk/query/context.js +2 -2
- package/dist/sdk/query/declared-blockers.js +1 -1
- package/dist/sdk/query/duplicate-candidates.js +1 -1
- package/dist/sdk/query/get-facet-roots.js +1 -1
- package/dist/sdk/query/get.js +1 -1
- package/dist/sdk/query/history.js +1 -1
- package/dist/sdk/query/item-filter-options.js +0 -1
- package/dist/sdk/query/light-metadata.js +1 -1
- package/dist/sdk/query/list-filter-shared.js +1 -1
- package/dist/sdk/query/list.js +1 -1
- package/dist/sdk/query/multi-value-filters.js +1 -1
- package/dist/sdk/query/next-ranking-policy.js +1 -1
- package/dist/sdk/query/next-ready-budget.js +1 -1
- package/dist/sdk/query/next.js +2 -2
- package/dist/sdk/query/parsers.js +1 -1
- package/dist/sdk/query/projection-contracts.js +1 -1
- package/dist/sdk/query/search/corpus.js +2 -2
- package/dist/sdk/query/search/filters.js +1 -1
- package/dist/sdk/query/search/input.js +1 -1
- package/dist/sdk/query/search/lexical.js +1 -1
- package/dist/sdk/query/search/response.js +1 -1
- package/dist/sdk/query/search/semantic.js +3 -3
- package/dist/sdk/query/search/types.js +0 -1
- package/dist/sdk/query/search-contracts.js +1 -1
- package/dist/sdk/query/search-pagination.js +1 -1
- package/dist/sdk/query/search-rendering.js +1 -1
- package/dist/sdk/query/search.js +1 -1
- package/dist/sdk/query/window-pagination.js +1 -1
- package/dist/sdk/query/workspace-contracts.js +1 -1
- package/dist/sdk/read-output/continuation.js +1 -1
- package/dist/sdk/read-output/extension.js +1 -1
- package/dist/sdk/read-output/options.js +1 -1
- package/dist/sdk/read-output/positional-rows.js +1 -1
- package/dist/sdk/read-output/provenance.js +1 -1
- package/dist/sdk/read-output/session-result.js +0 -1
- package/dist/sdk/read-output/surfaces.js +1 -1
- package/dist/sdk/read-output/tail-retention.js +1 -1
- package/dist/sdk/read-output-budget.js +1 -1
- package/dist/sdk/read-output-contracts.js +1 -1
- package/dist/sdk/read-output-rows.js +1 -1
- package/dist/sdk/read-output-session.js +1 -1
- package/dist/sdk/relationship-analytics.js +1 -1
- package/dist/sdk/relationship-context.js +1 -1
- package/dist/sdk/relationship-history.js +6 -6
- package/dist/sdk/relationship-kinds/contract.js +1 -1
- package/dist/sdk/relationships.js +1 -1
- package/dist/sdk/reproducibility/process.js +1 -1
- package/dist/sdk/runtime/actions.js +1 -1
- package/dist/sdk/runtime/context.js +1 -1
- package/dist/sdk/runtime/mutation-admission.js +1 -1
- package/dist/sdk/runtime/mutation-value-validation.js +1 -1
- package/dist/sdk/runtime/schema-preview.js +1 -1
- package/dist/sdk/runtime/schema.js +1 -1
- package/dist/sdk/runtime-action-aliases.js +1 -1
- package/dist/sdk/runtime-extended-actions.js +1 -1
- package/dist/sdk/runtime-input.d.ts +8 -2
- package/dist/sdk/runtime-input.js +1 -1
- package/dist/sdk/runtime-primitives.d.ts +1 -1
- package/dist/sdk/runtime-primitives.js +1 -1
- package/dist/sdk/runtime-public-contracts.js +0 -1
- package/dist/sdk/runtime-stats-options.js +1 -1
- package/dist/sdk/runtime.d.ts +9 -0
- package/dist/sdk/runtime.js +1 -1
- package/dist/sdk/scheduling-shortcuts.js +1 -1
- package/dist/sdk/schema/field-option-collisions.js +2 -0
- package/dist/sdk/schema-migration.js +4 -4
- package/dist/sdk/schema.js +7 -7
- package/dist/sdk/search-refresh-worker.js +1 -1
- package/dist/sdk/similarity-scoring.js +1 -1
- package/dist/sdk/similarity.js +1 -1
- package/dist/sdk/start-task-status.js +1 -1
- package/dist/sdk/stats.js +1 -1
- package/dist/sdk/structured-mutations.d.ts +5 -5
- package/dist/sdk/structured-mutations.js +1 -1
- package/dist/sdk/telemetry-flush.js +1 -1
- package/dist/sdk/telemetry.js +4 -4
- package/dist/sdk/templates.js +3 -3
- package/dist/sdk/test/batch.js +2 -2
- package/dist/sdk/test/command-args.js +1 -1
- package/dist/sdk/test/command-resolution.js +2 -2
- package/dist/sdk/test/entry.js +2 -2
- package/dist/sdk/test/execution-receipts.js +2 -2
- package/dist/sdk/test/execution.js +5 -5
- package/dist/sdk/test/json-path.js +1 -1
- package/dist/sdk/test/linked-command-detection.js +1 -1
- package/dist/sdk/test/measurements.js +1 -1
- package/dist/sdk/test/parsers.js +1 -1
- package/dist/sdk/test/prerequisites.js +1 -1
- package/dist/sdk/test/receipt-index-snapshot.js +1 -1
- package/dist/sdk/test/run-phases.js +1 -1
- package/dist/sdk/test/runs.js +1 -1
- package/dist/sdk/test/trust.js +2 -2
- package/dist/sdk/test/update.js +1 -1
- package/dist/sdk/test/workspace-snapshot.js +1 -1
- package/dist/sdk/traceability/runtime-files-lookup.js +1 -1
- package/dist/sdk/traceability/source-traceability.js +2 -2
- package/dist/sdk/tracker-root-discovery.js +1 -1
- package/dist/sdk/transactions/item-finalization.js +2 -0
- package/dist/sdk/workspace-contracts-cache.js +1 -1
- package/dist/sdk/workspace-contracts.js +1 -1
- package/dist/sdk/workspace-memory.js +2 -2
- package/dist/sdk/workspace-snapshot.js +5 -5
- package/dist/sdk/workspace-transaction-gc.js +1 -1
- package/dist/sdk/workspace-transaction.js +2 -2
- package/dist/sdk/workspace.js +6 -6
- package/dist/types/index.js +1 -1
- package/dist/types.d.ts +20 -0
- package/dist/types.js +1 -1
- package/docs/AGENT_GUIDE.md +1 -1
- package/docs/AGENT_RUNTIME_PRIMITIVES.md +1 -1
- package/docs/COMMANDS.md +7 -3
- package/docs/EXTENSIONS.md +1 -1
- package/docs/HISTORY_RECOVERY.md +229 -5
- package/docs/README.md +2 -2
- package/docs/SDK.md +174 -5
- package/docs/SDK_CONTEXT_COORDINATION.md +3 -2
- package/marketplace.json +1 -1
- package/node_modules/tar/package.json +2 -3
- package/package.json +31 -2
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-claude/package.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/plugins/pm-codex/package.json +1 -1
- package/plugins/pm-codex/plugin.json +1 -1
- package/runtime-dependencies.json +1 -1
- package/scripts/finalize-build.mjs +63 -24
- package/scripts/prepare-build-cache.mjs +28 -1
- package/dist/cli-bundle/chunks/chunk-2DXRTIC6.js +0 -21
- package/dist/cli-bundle/chunks/chunk-5647LU3A.js +0 -2287
- package/dist/cli-bundle/chunks/chunk-6QLEXRUG.js +0 -9
- package/dist/cli-bundle/chunks/chunk-AHQB7W2H.js +0 -3
- package/dist/cli-bundle/chunks/chunk-BKSVHOWI.js +0 -2
- package/dist/cli-bundle/chunks/chunk-CASX6SFI.js +0 -2
- package/dist/cli-bundle/chunks/chunk-CIKGG34F.js +0 -2
- package/dist/cli-bundle/chunks/chunk-D6ILFXZY.js +0 -2
- package/dist/cli-bundle/chunks/chunk-DEZPZOQ7.js +0 -2
- package/dist/cli-bundle/chunks/chunk-IB7UB5TE.js +0 -2
- package/dist/cli-bundle/chunks/chunk-IUIOTAF6.js +0 -9
- package/dist/cli-bundle/chunks/chunk-JVGRFU5H.js +0 -3
- package/dist/cli-bundle/chunks/chunk-KQIZ34SF.js +0 -3
- package/dist/cli-bundle/chunks/chunk-KVBIMFUG.js +0 -6
- package/dist/cli-bundle/chunks/chunk-LQBWLNZJ.js +0 -3
- package/dist/cli-bundle/chunks/chunk-NCFCBKIP.js +0 -2
- package/dist/cli-bundle/chunks/chunk-NT5AKFE5.js +0 -31
- package/dist/cli-bundle/chunks/chunk-PJXKA4QU.js +0 -125
- package/dist/cli-bundle/chunks/chunk-RMIRNYRG.js +0 -71
- package/dist/cli-bundle/chunks/chunk-RULHZRFN.js +0 -2
- package/dist/cli-bundle/chunks/chunk-S6HB3WL2.js +0 -2
- package/dist/cli-bundle/chunks/chunk-SA4BNP3Q.js +0 -2
- package/dist/cli-bundle/chunks/chunk-SPPHDVZE.js +0 -2
- package/dist/cli-bundle/chunks/chunk-SRVTCYAU.js +0 -2
- package/dist/cli-bundle/chunks/chunk-WELSVDPU.js +0 -2
- package/dist/cli-bundle/chunks/chunk-XHJ3H5PL.js +0 -3
- package/dist/cli-bundle/chunks/chunk-XWHJIRNV.js +0 -8
- package/dist/cli-bundle/chunks/chunk-YJEBK7HU.js +0 -8
- package/dist/cli-bundle/chunks/chunk-YKJKQ7DM.js +0 -115
- package/dist/cli-bundle/chunks/chunk-YMUSRWV4.js +0 -9
- package/dist/cli-bundle/chunks/chunk-YR2KEBHP.js +0 -2
- package/dist/cli-bundle/chunks/context-budget-recovery-L2WP5S26.js +0 -2
- package/dist/cli-bundle/chunks/indexed-receipt-blobs-ITTXIN4K.js +0 -4
- package/dist/cli-bundle/chunks/item-transaction-7DFCG73I.js +0 -2
- package/dist/cli-bundle/chunks/mutation-actor-3TG636XG.js +0 -2
- package/dist/cli-bundle/chunks/mutation-admission-LICSDNNO.js +0 -2
- package/dist/cli-bundle/chunks/register-mutation-WWVECKFQ.js +0 -21
- package/dist/cli-bundle/chunks/register-operations-L6HFJNWD.js +0 -2
- package/dist/cli-bundle/chunks/register-setup-K7UFG5TD.js +0 -2
- package/dist/cli-bundle/chunks/settlement-hook-BXN5LEQD.js +0 -7
- package/dist/cli-bundle/chunks/stage-57KH3KAC.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-3IRCYJI5.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-3V53UBHN.js +0 -9
- package/dist/cli-bundle/focused-chunks/chunk-532WZV65.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-7A4QWNZX.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-C3O6JJPO.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-CR7CGEB2.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-CU2BRAOX.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-CWWKRI5P.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-EGN2HFRU.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-GHQVM6K6.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-HGFNL5XI.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-I5LGPUWH.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-IQK5NPMG.js +0 -13
- package/dist/cli-bundle/focused-chunks/chunk-J63D6QST.js +0 -6
- package/dist/cli-bundle/focused-chunks/chunk-JMQJBZQ5.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-LNHUE4VV.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-MKM5NKD7.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-NP72ZDXE.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-OSLQD5VH.js +0 -102
- package/dist/cli-bundle/focused-chunks/chunk-QGKLRXP7.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-QSJW6NSQ.js +0 -66
- package/dist/cli-bundle/focused-chunks/chunk-RPE6IX26.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-SRDQSA6M.js +0 -91
- package/dist/cli-bundle/focused-chunks/chunk-SVOOGGAK.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-UOC6257J.js +0 -26
- package/dist/cli-bundle/focused-chunks/chunk-URJ2E6AS.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-WXMI4AV5.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-XCJSHNXK.js +0 -27
- package/dist/cli-bundle/focused-chunks/chunk-XQQSSKJI.js +0 -44
- package/dist/cli-bundle/focused-chunks/chunk-YOAYY3HE.js +0 -2
- package/dist/cli-bundle/focused-chunks/context-budget-recovery-5MKOCGY5.js +0 -2
- package/dist/cli-bundle/focused-chunks/indexed-receipt-blobs-AF4U3F3D.js +0 -4
- package/dist/cli-bundle/focused-chunks/item-transaction-HLBW7B3J.js +0 -2
- package/dist/cli-bundle/focused-chunks/mutation-actor-62HKR5IO.js +0 -2
- package/dist/cli-bundle/focused-chunks/mutation-admission-X4PF2SG3.js +0 -2
- package/dist/cli-bundle/focused-chunks/settlement-hook-ARYCZQY4.js +0 -7
- package/dist/cli-bundle/focused-chunks/stage-O7T7CXBB.js +0 -2
- package/dist/sdk/agent/refusal-closure.js +0 -2
- package/dist/sdk/agent/refusal-reachability.js +0 -4
- package/dist/sdk/agent/task-transcript-contracts.js +0 -2
- package/dist/sdk/agent/tracker-preflight-contracts.js +0 -2
- package/dist/sdk/authoring.js +0 -2
- package/dist/sdk/compose.js +0 -2
- package/dist/sdk/contracts.js +0 -2
- package/dist/sdk/core-governance.js +0 -2
- package/dist/sdk/core.js +0 -2
- package/dist/sdk/corpus-shape.js +0 -2
- package/dist/sdk/define.js +0 -2
- package/dist/sdk/environment/agent-environment.js +0 -2
- package/dist/sdk/governance/artifact-ledgers.js +0 -2
- package/dist/sdk/governance/coverage-assurance.js +0 -2
- package/dist/sdk/governance/reliability.js +0 -2
- package/dist/sdk/governance.js +0 -2
- package/dist/sdk/graph/adapter.js +0 -2
- package/dist/sdk/graph/conformance.js +0 -2
- package/dist/sdk/graph/index.js +0 -2
- package/dist/sdk/graph.js +0 -2
- package/dist/sdk/index.js +0 -2
- package/dist/sdk/query.js +0 -2
- package/dist/sdk/relationship-migration.js +0 -2
- package/dist/sdk/testing.js +0 -8
- package/dist/sdk/workspace-recipe.js +0 -2
- package/docs/AGENT_PROVENANCE_ADR.md +0 -206
- package/docs/DEFECT_RECURRENCE.md +0 -257
- package/docs/PERFORMANCE.md +0 -204
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
|
|
2
|
-
`).entries()){if(
|
|
3
|
-
`})
|
|
1
|
+
import{isUtf8 as C}from"node:buffer";import{resolveHistoryHashAlgorithm as T}from"../../core/history/digest.js";import{readFile as S}from"node:fs/promises";import{isFileMissingError as L,readFileIfExists as N}from"../../core/fs/fs-utils.js";import{acquireLock as x}from"../../core/lock/lock.js";import{createHistoryEntry as P,sealHistoryRecord as F}from"../../core/history/history.js";import{checkHistoryRewriteOwnership as E,writeHistoryRawWithRollback as A}from"../../core/history/history-rewrite.js";import{replayHistoryToTarget as q}from"../../core/history/projection.js";import{cloneEmptyReplayDocument as D,lenientApplyReplayPatch as U,replayToItemDocument as v,tryApplyReplayPatch as $,verifyHistoryChainWithVersion as M}from"../../core/history/replay.js";import{SUPPORTED_HISTORY_ITEM_HASH_VERSIONS as B}from"../../core/history/history.js";import{findFirstMergeConflictMarker as V}from"../../core/shared/conflict-markers.js";import{describeHistoryRecordDefect as W,isNonRecordScalar as J}from"../../core/history/read.js";import{EMPTY_CANONICAL_DOCUMENT as g,EXIT_CODE as s}from"../../core/shared/constants.js";import{advanceItemMutationPreconditions as z,assertItemMutationPreconditions as Y,assertItemRevisionExpectationsOnUnreadable as G}from"../../core/store/item-mutation-precondition.js";import{PmCliError as d}from"../../core/shared/errors.js";import{sha256Hex as X}from"../../core/shared/serialization.js";import{nowIso as _}from"../../core/shared/time.js";import{runActiveOnReadHooks as K,runActiveOnWriteHooks as Q}from"../../core/extensions/index.js";import{locateItem as Z,readLocatedItemSnapshot as j}from"../../core/store/item-store.js";function ee(r){const e=r.trim();let i;try{i=JSON.parse(e)}catch{if(e.startsWith("{")&&e.includes("}"))throw new d("History salvage cannot discard a potentially complete record with trailing corruption.",s.CONFLICT,{code:"history_salvage_refused"});return{kind:"invalid"}}if(J(i))return{kind:"non_record"};if(W(i)!==null)throw new d("History salvage would conceal interior corruption or a malformed record.",s.CONFLICT,{code:"history_salvage_refused",required:"Recover the damaged record from version control or a backup; no bytes were changed."});const t=i;if(!Array.isArray(t.patch)||![t.ts,t.author,t.op,t.before_hash,t.after_hash].every(o=>typeof o=="string"))throw new d("History salvage requires complete history records before the invalid tail.",s.CONFLICT,{code:"history_salvage_refused"});return{kind:"record",entry:t}}function re(r){return[...r].reverse().find(e=>B.includes(e.item_hash_version))?.item_hash_version}function te(r){if(V(r))throw new d("Resolve history merge conflicts before salvage.",s.CONFLICT,{code:"history_salvage_refused"});const e=ie(r),i=oe(e);return{entries:e.entries,...i,...ce(r,e.nonRecord,e.invalidOffset,e.invalidLine,e.entries.length)}}function ie(r){const e={entries:[],nonRecord:[],invalidOffset:void 0,invalidLine:0};let i=0;for(const[t,o]of r.split(`
|
|
2
|
+
`).entries()){const n=i;if(i+=o.length+1,!o.trim())continue;const a=ee(o);if(a.kind==="record"){if(e.invalidOffset!==void 0)throw new d("History salvage would discard a record or conceal interior corruption.",s.CONFLICT,{code:"history_salvage_refused",required:"Recover the damaged record from version control or a backup; no bytes were changed."});e.entries.push(a.entry)}else a.kind==="non_record"&&e.invalidOffset===void 0?e.nonRecord.push({start:n,end:Math.min(i,r.length),line:t+1}):e.invalidOffset===void 0&&(e.invalidOffset=n,e.invalidLine=t+1)}return e}function oe(r){const e=M(r.entries),i=e.ok&&e.item_hash_version!==void 0;if(!(r.invalidOffset===void 0&&r.nonRecord.length>0)&&(r.entries.length===0||!i)){const o=r.entries.length>0&&r.invalidOffset===void 0;throw new d("History salvage requires a nonempty verified prefix.",s.CONFLICT,{code:"history_salvage_refused",verification_errors:e.errors,required:"Recover an intact history prefix from version control or a backup.",...o?{nextSteps:["Run pm history-repair <id> --append-only --dry-run: salvage has nothing to discard, and the chain needs a repair."]}:{}})}return{itemHashVersion:i?e.item_hash_version:re(r.entries),verification:{ok:e.ok,errors:e.errors}}}function ne(r){try{return T(r.hash_algorithm)}catch{const e=typeof r.hash_algorithm=="string";throw new d(e?"History salvage cannot anchor its record: the last kept record uses a digest algorithm this pm version cannot compute.":"History salvage cannot anchor its record: the last kept record's digest label is malformed.",s.CONFLICT,{code:"history_salvage_refused",required:e?"Upgrade pm to a version that reads the stream's digest algorithm; no bytes were changed.":"Recover the damaged record from version control or a backup; no bytes were changed.",nextSteps:[e?"Run npm install -g @unbrained/pm-cli@latest, then preview the salvage again.":"Run pm history <id> --verify --full to locate the record, then restore the stream from version control or a backup."]})}}function ae(r,e,i){const t=r.entries.at(-1);if(t===void 0)return r.prefix;const o=g,{item_hash_version:n,...a}=P({hashAlgorithm:ne(t),nowIso:_(),author:e,op:"history_salvage",before:o,after:o,message:i,context:{history_salvage:r.receipt}}),c=F({...a,before_hash:t.after_hash,after_hash:t.after_hash,...r.itemHashVersion===void 0?{}:{item_hash_version:r.itemHashVersion}});return`${r.prefix}${JSON.stringify(c)}
|
|
3
|
+
`}function se(r,e){if(typeof e.metadata.id=="string"&&e.metadata.id!==r)throw new d("History belongs to another item; salvage refused.",s.CONFLICT,{code:"history_salvage_refused"})}function de(r,e){const i=e.verification.ok;let t=D(),o=t;for(const n of e.entries){const a=i?$(t,n.patch):void 0;t=a?.ok===!0?a.document:U(t,n.patch,n.op).document,se(r,t),Object.keys(t.metadata).length>0&&(o=t)}return i&&e.entries.length>0?{final:q(e.entries,e.entries.length-1),lastItem:o}:{final:t,lastItem:o}}function ce(r,e,i,t,o){const n=i??r.length,a=[...e.map(({start:f,end:l})=>r.slice(f,l)),r.slice(n)].join("");let c="",h=0;for(const{start:f,end:l}of e)c+=r.slice(h,f),h=l;return c+=r.slice(h,n),c!==""&&!c.endsWith(`
|
|
4
|
+
`)&&(c+=`
|
|
5
|
+
`),a===""?{prefix:c,receipt:null}:{prefix:c,receipt:{first_invalid_line:e[0]?.line??t,discarded_bytes:Buffer.byteLength(a),discarded_sha256:X(a),retained_entries:o,...e.length>0?{non_record_lines:e.length}:{}}}}function le(r,e,i){const t=e.metadata?.assignee;if(!(i||t===void 0||t===null||typeof t=="string"))throw new d(`The recorded owner of ${r} is not a name, so salvage cannot check ownership.`,s.CONFLICT,{code:"history_salvage_refused",item_id:r,reason:"owner_malformed",details:{reason:"owner_malformed"},required:"Recover the damaged record from version control or a backup, or override ownership deliberately; no bytes were changed.",nextSteps:[`Inspect ${r}'s raw history stream file or restore it from version control or a backup, or rerun the salvage with --force to override ownership.`]})}async function w(r,e,i){if(!r)return{itemRaw:null,document:i,live:null};const t=await j(r,{schema:e.schema});return{itemRaw:t.raw,document:t.document??i,live:t.document}}function R(r,e,i){i.itemRaw!==null&&i.live===null&&G(r,e,i.itemRaw);const t=i.live??g;return Y(r,t,e),t}async function O(r){let e;try{e=await S(r)}catch(i){if(L(i))return null;throw i}if(!C(e))throw new d("History salvage requires UTF-8 input; recover binary corruption from a byte-preserving backup.",s.CONFLICT,{code:"history_salvage_refused"});return e.toString("utf8")}async function xe(r){const{subject:e,settings:i,options:t,author:o}=r;if([t.normalizeProvenance,t.auditOperation,t.auditContext,t.auditContextById,t.forceAuditEntry,t.mergeReceiptProof,t.mergeReceiptProofById].some(Boolean))throw new d("Tail salvage cannot be combined with other repair modes.",s.USAGE);const n=await O(e.historyPath);if(n===null)throw new d(`No history stream exists for ${e.id}.`,s.NOT_FOUND);await K({path:e.historyPath,scope:"project"});const a=te(n),c=de(e.id,a),h=v(c.final),f=a.receipt===null?n:ae(a,o,t.message),l=await w(e.located,i,v(c.lastItem));le(e.id,l.document,t.force===!0);const m=E({itemDocument:l.document,subjectId:e.id,author:o,force:t.force,settings:i}),p=t.dryRun===!0,y=a.receipt!==null;if(y&&!p){const k=await x(r.pmRoot,e.id,i.locks.ttl_seconds,o,!!t.force,i.governance.force_required_for_stale_lock,i.locks.wait_ms);try{const H=await O(e.historyPath),u=await Z(r.pmRoot,e.id,i.id_prefix,i.item_format,r.typeRegistry.type_to_folder),I=u?await N(u.itemPath):null;if(H!==n||I!==l.itemRaw)throw R(r.pmRoot,e.id,await w(u,i,h)),new d("History or item changed while waiting for salvage lock; retry.",s.CONFLICT);const b=R(r.pmRoot,e.id,l);await A({historyPath:e.historyPath,historyRawUnderLock:n,nextHistoryRaw:f}),z(r.pmRoot,b,e.id),m.push(...await Q({path:e.historyPath,scope:"project",op:"history_salvage:history"}))}finally{await k()}}return fe(e,a,{changed:y,dryRun:p,warnings:m})}function he(r,e){return e.entries.length===0?r.located===null?[]:[`history_stream_empty:${r.id}:run pm history-repair ${r.id}`]:e.verification.ok?[]:[`history_chain_unverified:${r.id}:run pm history-repair ${r.id} --append-only --dry-run, or pm history-repair ${r.id} --dry-run when a bridge refuses`]}function fe(r,e,i){const t=e.itemHashVersion,{ok:o,errors:n}=e.verification;return{id:r.id,dry_run:i.dryRun,changed:i.changed,history:{path:r.historyPath,entries_scanned:e.entries.length,chain_drift_before:!o,entries_rehashed:0,entries_patch_repaired:0,converted_replace_to_add:0,skipped_ops:0,reconciled_with_item:!1,audit_entry_added:i.changed&&!i.dryRun&&e.entries.length>0,verify_ok:o,verify_errors:n,item_hash_version_before:t??null,item_hash_version_after:t??1,version_disposition:"preserved"},item:{exists:r.located!==null,path:r.located?.itemPath??null,matched_chain_before:null},provenance_normalization:{requested:!1,changed:!1,events_changed:0,observations_removed:0,invalid_values:[]},...e.receipt?{salvage:e.receipt}:{},warnings:[...i.warnings,...he(r,e)],generated_at:_()}}export{te as inspectHistoryTail,xe as salvageHistoryTail};
|
|
4
6
|
//# sourceMappingURL=salvage.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
import{pathExists as p}from"../../core/fs/fs-utils.js";import{normalizeItemId as l,normalizeRawItemId as f}from"../../core/item/id.js";import{EXIT_CODE as I}from"../../core/shared/constants.js";import{PmCliError as y}from"../../core/shared/errors.js";import{locateItem as w}from"../../core/store/item-store.js";import{getHistoryPath as m}from"../../core/store/paths.js";import{getActiveExtensionRegistrations as u}from"../../core/extensions/index.js";import{resolveItemTypeRegistry as h}from"../../core/item/type-registry.js";import{resolvePmRoot as x}from"../../core/store/paths.js";import{readSettings as g}from"../../core/store/settings.js";import{assertInitializedTracker as v}from"../environment/tracker-preflight.js";async function D(r){const t=x(process.cwd(),r);await v(t);const o=await g(t),i=h(o,u());return{pmRoot:t,settings:o,typeRegistry:i}}async function S(r,t,o,i){m(r,f(t));const e=await w(r,t,o.id_prefix,o.item_format,i);if(e)return{id:e.id,historyPath:m(r,e.id),located:e};const a=l(t,o.id_prefix),s=f(t),d=a===s?[a]:[a,s];for(const n of d){const c=m(r,n);if(await p(c))return{id:n,historyPath:c,located:null}}throw new y(`Item ${t} not found`,I.NOT_FOUND)}export{S as resolveHistorySubject,D as resolveHistoryWorkspace};
|
|
2
2
|
//# sourceMappingURL=subject.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
import{AGENT_PROVENANCE_DIMENSIONS as w,BUILTIN_HARNESS_SIGNAL_DESCRIPTORS as d}from"../core/shared/author.js";import{EXIT_CODE as m}from"../core/shared/constants.js";import{PmCliError as p}from"../core/shared/errors.js";import{listMutationEvents as D}from"./mutation-events.js";import{analyzeAgentProvenanceDescriptorCoverage as O,summarizeAgentProvenance as b}from"./provenance.js";const x=1e4,v=1e5,M=1e3,C=30,H=["append","comment","docs","file","learning","note","test_run"];function y(t){const e=t??x;if(!Number.isSafeInteger(e)||e<1||e>v)throw new p(`History analytics event limit must be an integer from 1 to ${v}.`,m.USAGE,{code:"invalid_history_analytics_limit"});return e}function f(t){const e=t??5;if(!Number.isSafeInteger(e)||e<1||e>1e4)throw new p("History analytics minimum sample must be an integer from 1 to 10000.",m.USAGE,{code:"invalid_history_analytics_minimum_sample"});return e}function h(t){const e=t?.trim();if(!e)return new Date(Date.now()-C*864e5).toISOString();const n=/^-(\d+)([dh])$/u.exec(e);if(n){const s=Number(n[1]),r=n[2]==="d"?864e5:36e5;if(!Number.isSafeInteger(s)||s<1)throw new p("History analytics --since duration must be positive.",m.USAGE,{code:"invalid_history_analytics_since"});return new Date(Date.now()-s*r).toISOString()}const i=Date.parse(e);if(!Number.isFinite(i))throw new p("History analytics --since must be an ISO timestamp or negative duration such as -30d.",m.USAGE,{code:"invalid_history_analytics_since"});return new Date(i).toISOString()}async function S(t,e){const n=y(e.eventLimit),i=h(e.since),s=[];let r=i,o=!1;for(;s.length<n;){const a=await D({pmRoot:t,since:r,limit:Math.min(M,n-s.length),full:!0}),c=a.events.map(l=>({item_id:l.item_id,entry:l.entry}));if(s.push(...c),o=a.has_more,r=a.next_cursor,!a.has_more)break}return{events:s,receipt:{since:i,events:s.length,truncated:o,...o?{next_cursor:r}:{},source:"history_event_index"}}}function E(t,e){return e==="harness"?t.agent_harness:e==="author_source"?t.author_source:t.agent_model??t.agent_provenance?.model?.value}function g(t){for(let e=t.patch.length-1;e>=0;e-=1){const n=t.patch[e];if(n.path==="/metadata/status"&&"value"in n&&typeof n.value=="string")return n.value}}function A(t){return H.some(e=>t.startsWith(e))}function I(t,e){const n=t.get(e);if(n)return n;const i={events:0,stateEvents:0,annotationEvents:0,closes:0,reopens:0,defectEscapes:0};return t.set(e,i),i}function F(t,e,n){const i=new Map,s=new Map,r=new Map;for(const o of e){const a=E(o.entry,t),c=g(o.entry),l=s.get(o.item_id)===!0,_=c===void 0?l:n.has(c);if(c!==void 0&&s.set(o.item_id,_),!a)continue;const u=I(i,a);u.events+=1,A(o.entry.op)?u.annotationEvents+=1:u.stateEvents+=1,c!==void 0&&!l&&_?(u.closes+=1,r.set(o.item_id,a)):c!==void 0&&l&&!_&&(u.reopens+=1)}return{buckets:i,lastCloseValue:r}}function L(t,e,n){for(const i of n){if(i.type!=="Issue")continue;const s=new Set((i.dependencies??[]).filter(r=>r.kind==="discovered_from").map(r=>r.id));for(const r of s){const o=e.get(r);o&&(I(t,o).defectEscapes+=1)}}}function P(t,e,n,i){const s=e.closes>=n?"available":"insufficient";return{value:t,events:e.events,state_events:e.stateEvents,annotation_events:e.annotationEvents,closes:e.closes,reopens:e.reopens,defect_escapes:e.defectEscapes,throughput_per_day:s==="available"?e.closes/i:null,rework_rate:s==="available"?e.reopens/e.closes:null,defect_escape_rate:s==="available"?e.defectEscapes/e.closes:null,sample_status:s}}function T(t,e,n,i,s,r){const{buckets:o,lastCloseValue:a}=F(t,e,i);return L(o,a,n),{dimension:t,status:o.size===0?"unavailable":"available",rows:[...o].map(([c,l])=>P(c,l,s,r)).sort((c,l)=>l.events-c.events||c.value.localeCompare(l.value))}}function N(t,e){const n=t[0]?.entry.ts??e,i=t[t.length-1]?.entry.ts??n,s=Date.parse(n),r=Date.parse(i);return!Number.isFinite(s)||!Number.isFinite(r)?1:Math.max(1,(r-s)/864e5)}function R(t,e,n){const i=O(e),s=b(t,w,n),r=s.filter(a=>a.inert).map(a=>({harness:a.harness,dimension:a.dimension,explicit_samples:a.observed+a.unavailable})),o=i.filter(a=>!a.covered).map(a=>a.dimension);return{descriptors:i,observations:s,inert:r,undeclared:o,warnings:[...r.map(a=>`provenance_dimension_inert:${a.harness}:${a.dimension}:${String(a.explicit_samples)}`),...o.map(a=>`provenance_dimension_undeclared:${a}`)]}}async function X(t,e=d,n={}){return G(await S(t,n),e,n)}function G(t,e=d,n={}){const i=f(n.minimumSample);return{...R(t.events.map(s=>s.entry),e,i),window:t.receipt}}async function j(t,e,n,i={}){return U(await S(t,i),e,n,i)}function U(t,e,n,i={}){const s=f(i.minimumSample),r=N(t.events,t.receipt.since);return{dimensions:["harness","model","author_source"].map(o=>T(o,t.events,e,n,s,r)),minimum_sample:s,policy:"observational_only_not_for_authorization_or_routing",window:t.receipt}}const B={annotationOperation:A,buildFleetDimension:T,parseHistoryAnalyticsLimit:y,parseMinimumSample:f,provenanceValue:E,resolveHistoryAnalyticsSince:h,resolveHistoryWindowDays:N,statusFromEntry:g};export{B as _testOnlyHistoryAnalytics,R as evaluateProvenanceCoverage,U as projectFleetAttributionAnalytics,G as projectProvenanceCoverageAnalytics,S as readHistoryAnalyticsWindow,j as runFleetAttributionAnalytics,X as runProvenanceCoverageAnalytics};
|
|
2
2
|
//# sourceMappingURL=history-analytics.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="be76e0e9-a03e-528f-8386-28c620f78976")}catch{}})();import{itemRevisionConflictRowFields}from"./lifecycle/item-revision.js";import fs from"node:fs/promises";import{resolveHistoryHashAlgorithm}from"../core/history/digest.js";import path from"node:path";import{createHistoryEntry,hashHistoryStream,sealHistoryRecord,SUPPORTED_HISTORY_ITEM_HASH_VERSIONS}from"../core/history/history.js";import{selectHistoryCompactBulkTargets}from"../core/history/history-compact-bulk.js";import{cloneEmptyReplayDocument,replayHashVerificationCandidates,replayToItemDocument,toReplayDocument}from"../core/history/replay.js";import{applyHistoryPatch}from"../core/history/projection.js";import{historyVersionOffset}from"../core/history/version-address.js";import{lifecycleClassifierFromStatusRegistry}from"../core/governance/metadata-coverage.js";import{resolveRuntimeStatusRegistry}from"../core/schema/runtime-schema.js";import{listAllItemMetadataLight}from"../core/store/item-store.js";import{pathExists}from"../core/fs/fs-utils.js";import{normalizeBulkIdsValue,parseBulkIdsText}from"../core/io/bulk-ids-input.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{nowIso}from"../core/shared/time.js";import{runActiveOnReadHooks}from"../core/extensions/index.js";import{isJudgeableHistoryRecord,recordedPrefixActivity}from"./governance/stale-work.js";import{resolveHistoryWorkspace,resolveHistorySubject}from"./history/subject.js";import{runHistoryMaintenance}from"./history/maintenance.js";function parseBeforeBoundary(before,entries){if(before===void 0)return{kind:"default",raw:null,compactCount:entries.length,retainedCount:0};const raw=before.trim();if(raw.length===0)throw new PmCliError("history-compact --before requires a non-empty value.",EXIT_CODE.USAGE);if(/^\d+$/.test(raw)){const version=Number.parseInt(raw,10),offset=historyVersionOffset(entries);if(!Number.isSafeInteger(version)||version<offset+1||version>offset+entries.length+1)throw new PmCliError(`history-compact --before version must be between ${offset+1} and ${offset+entries.length+1}.`,EXIT_CODE.USAGE);const compactCount2=version-offset-1;return{kind:"version",raw,compactCount:compactCount2,retainedCount:entries.length-compactCount2}}const beforeTs=Date.parse(raw);if(!Number.isFinite(beforeTs))throw new PmCliError(`Invalid history-compact --before value "${before}". Use a version number or ISO timestamp.`,EXIT_CODE.USAGE);let compactCount=0;for(const[index,entry]of entries.entries()){const entryTs=Date.parse(entry.ts);if(!Number.isFinite(entryTs))throw new PmCliError(`History for this item contains invalid timestamp at entry ${index+1}.`,EXIT_CODE.GENERIC_FAILURE);if(entryTs>=beforeTs)break;compactCount+=1}return{kind:"timestamp",raw,compactCount,retainedCount:entries.length-compactCount}}function replayHistoryAndResolveCheckpoint(entries,compactCount){let replay=cloneEmptyReplayDocument(),checkpoint=cloneEmptyReplayDocument();for(let index=0;index<entries.length;index+=1){const entry=entries[index];replay=applyHistoryPatch(replay,entry.patch,index+1,entry.op),index+1===compactCount&&(checkpoint=structuredClone(replay))}return{checkpoint,finalReplay:replay}}function describeHistoryCompactCurrentItem(loadedItem,historyEntries){if(!loadedItem)return{loadedItem:null,currentItemRawBeforeLock:null,matchedChainBefore:null};const lastEntry=historyEntries[historyEntries.length-1];return{loadedItem,currentItemRawBeforeLock:loadedItem.raw,matchedChainBefore:SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.some(version=>(lastEntry.item_hash_version===void 0||lastEntry.item_hash_version===version)&&replayHashVerificationCandidates(toReplayDocument(loadedItem.document),version,resolveHistoryHashAlgorithm(lastEntry.hash_algorithm)).includes(lastEntry.after_hash))}}function buildHistoryCompactMessage(options,boundary){return typeof options.message=="string"&&options.message.trim().length>0?options.message:boundary.raw===null?`history-compact compacted full stream (${boundary.compactCount} entr${boundary.compactCount===1?"y":"ies"}).`:`history-compact compacted ${boundary.compactCount} entr${boundary.compactCount===1?"y":"ies"} before ${boundary.raw}.`}function buildHistoryCompactBaselineMessage(boundary){return boundary.raw===null?`history-compact baseline snapshot after compacting ${boundary.compactCount} entr${boundary.compactCount===1?"y":"ies"}.`:`history-compact baseline snapshot before ${boundary.raw}.`}function assertPrunedRecordsJudgeable(entries,compactCount){const index=entries.slice(0,compactCount).findIndex(entry=>!isJudgeableHistoryRecord(entry));if(index===-1)return;const damage=Number.isFinite(Date.parse(entries[index].ts))?"a malformed record or compaction receipt":"invalid timestamp";throw new PmCliError(`History for this item contains ${damage} at entry ${index+1}.`,EXIT_CODE.GENERIC_FAILURE)}function buildHistoryCompactEntries(params){if(!params.changed)return{rewrittenEntries:params.historyEntries,baselineEntryAdded:!1,auditEntryAdded:!1};const{checkpoint,finalReplay}=replayHistoryAndResolveCheckpoint(params.historyEntries,params.boundary.compactCount),retained=params.historyEntries.slice(params.boundary.compactCount),offset=historyVersionOffset(params.historyEntries,!0),checkpointEntry=params.historyEntries[params.boundary.compactCount-1],baselineEntry=createHistoryEntry({hashAlgorithm:resolveHistoryHashAlgorithm(checkpointEntry.hash_algorithm),nowIso:params.historyEntries[params.boundary.compactCount-1].ts,author:params.author,op:"history_compact_baseline",before:replayToItemDocument(cloneEmptyReplayDocument()),after:replayToItemDocument(checkpoint),message:buildHistoryCompactBaselineMessage(params.boundary),context:{history_compaction:{contract_version:1,version_offset:offset===null?null:offset+params.boundary.compactCount-1,checkpoint_timestamp_semantics:"last_compacted_entry",last_activity_at:recordedPrefixActivity(params.historyEntries.slice(0,params.boundary.compactCount)),pruned_entry_count:params.boundary.compactCount,pruned_stream_digest:hashHistoryStream(params.historyEntries.slice(0,params.boundary.compactCount)),retained_proof:"stream_digest_and_checkpoint",limitation:"individual_pruned_entries_require_pre_compaction_stream"}}}),rewrittenEntries=[sealHistoryRecord({...baselineEntry,before_hash:replayHashVerificationCandidates(cloneEmptyReplayDocument(),checkpointEntry.item_hash_version??1,resolveHistoryHashAlgorithm(checkpointEntry.hash_algorithm))[0],after_hash:checkpointEntry.after_hash,item_hash_version:checkpointEntry.item_hash_version}),...retained];return params.dryRun||rewrittenEntries.push(createHistoryEntry({nowIso:nowIso(),author:params.author,op:"history_compact",before:replayToItemDocument(finalReplay),after:replayToItemDocument(finalReplay),message:buildHistoryCompactMessage(params.options,params.boundary)})),{rewrittenEntries,baselineEntryAdded:!0,auditEntryAdded:!params.dryRun}}async function runHistoryCompact(id,options,global2){const{pmRoot,settings,typeRegistry}=await resolveHistoryWorkspace(global2.path),subject=await resolveHistorySubject(pmRoot,id,settings,typeRegistry.type_to_folder);return runHistoryMaintenance({pmRoot,subject,settings,typeRegistry,operation:"history-compact",options,transform:snapshot=>buildHistoryCompactPlan(subject,options,snapshot)})}function buildHistoryCompactPlan(subject,options,snapshot){const historyPath=subject.historyPath,historyEntries=snapshot.entries,chainVerification=snapshot.verification;if(!chainVerification.ok)throw new PmCliError(`history-compact requires a valid history chain (${chainVerification.errors.join(", ")}). Run pm history-repair ${subject.id} first.`,EXIT_CODE.CONFLICT);const boundary=parseBeforeBoundary(options.before,historyEntries);assertPrunedRecordsJudgeable(historyEntries,boundary.compactCount);const changed=boundary.compactCount>0,dryRun=!!options.dryRun,author=snapshot.author,warnings=[];changed||warnings.push("history_compact_noop_before_boundary");const currentItem=describeHistoryCompactCurrentItem(snapshot.loadedItem,historyEntries);currentItem.matchedChainBefore===!1&&warnings.push("history_compact_item_chain_mismatch");const{rewrittenEntries,baselineEntryAdded,auditEntryAdded}=buildHistoryCompactEntries({historyEntries,boundary,changed,dryRun,author,options}),offset=historyVersionOffset(historyEntries,!0),firstRetainedEntry=boundary.retainedCount>0&&offset!==null?offset+boundary.compactCount+1:null;return{changed,rewrittenEntries,report:({verification:rewrittenVerify,warnings:writeWarnings})=>({id:subject.id,dry_run:dryRun,changed,compact_boundary:{kind:boundary.kind,before:boundary.raw,entries_compacted:boundary.compactCount,entries_retained:boundary.retainedCount,first_retained_entry:firstRetainedEntry},history:{path:historyPath,entries_scanned:historyEntries.length,entries_after:rewrittenEntries.length,baseline_entry_added:baselineEntryAdded,audit_entry_added:auditEntryAdded,verify_ok:rewrittenVerify.ok,verify_errors:rewrittenVerify.errors},item:{exists:subject.located!==null,path:subject.located?.itemPath??null,matched_chain_before:currentItem.matchedChainBefore},warnings:[...new Set([...warnings,...writeWarnings])].sort((left,right)=>left.localeCompare(right)),generated_at:nowIso()})}}const HISTORY_COMPACT_BULK_DEFAULT_MIN_ENTRIES=3;function normalizeHistoryCompactBulkOptions(options){for(const key of["allOver","minEntries"]){const value=options[key];if(value!==void 0&&(!Number.isSafeInteger(value)||value<0))throw new PmCliError(`history-compact ${key} must be a non-negative safe integer.`,EXIT_CODE.USAGE)}const normalizedIdsText=normalizeBulkIdsValue(options.ids);if(options.ids!==void 0&&normalizedIdsText==="")throw new PmCliError("history-compact ids requires at least one valid item ID.",EXIT_CODE.USAGE,{code:"bulk_ids_input_empty",required:"Provide one or more string or finite numeric IDs; non-finite and unsupported selector values are rejected."});return{...options,ids:normalizedIdsText===void 0?void 0:parseBulkIdsText(normalizedIdsText)}}function assertHistoryCompactTarget(id,bulk){const hasIds=bulk.ids!==void 0&&bulk.ids.length>0,hasScan=bulk.allOver!==void 0||bulk.scope!==void 0;if((id!==void 0?1:0)+(hasIds?1:0)+(hasScan?1:0)==0)throw new PmCliError("history-compact: provide an item <id>, or a bulk selector (--ids, --all-over <N>, --closed, or --all-streams).",EXIT_CODE.USAGE);if(id!==void 0&&(hasIds||hasScan))throw new PmCliError("history-compact: <id> and bulk selectors (--ids/--all-over/--closed/--all-streams) are mutually exclusive; pass one item id, or use bulk mode without a positional id.",EXIT_CODE.USAGE);if(hasIds&&hasScan)throw new PmCliError("history-compact: --ids is mutually exclusive with --all-over/--closed/--all-streams; pass an explicit id list or a scan selector, not both.",EXIT_CODE.USAGE)}function countHistoryStreamEntries(raw){let count=0;for(const line of raw.split(/\r?\n/))line.trim().length>0&&(count+=1);return count}async function collectHistoryCompactBulkCandidates(params){const statusRegistry=resolveRuntimeStatusRegistry(params.settings.schema),classifier=lifecycleClassifierFromStatusRegistry(statusRegistry),items=await listAllItemMetadataLight(params.pmRoot,params.settings.item_format,params.typeToFolder,void 0,params.settings.schema),bucketById=new Map(items.map(item=>[item.id,classifier.classify(item.status)])),historyDir=path.join(params.pmRoot,"history"),candidates=[],preselectionErrors=[];if(!await pathExists(historyDir))return{candidates,preselectionErrors};const historyFiles=(await fs.readdir(historyDir)).filter(entry=>entry.endsWith(".jsonl")).sort((left,right)=>left.localeCompare(right));for(const fileName of historyFiles){const historyPath=path.join(historyDir,fileName),id=fileName.slice(0,-6);try{const raw=await fs.readFile(historyPath,"utf8");await runActiveOnReadHooks({path:historyPath,scope:"project"}),candidates.push({id,entries:countHistoryStreamEntries(raw),bucket:bucketById.get(id)??null})}catch(error){preselectionErrors.push({id,outcome:"errored",entries_before:0,entries_after:null,skip_reason:null,changed:!1,error:error instanceof Error?error.message:String(error)})}}return{candidates,preselectionErrors}}async function runHistoryCompactBulkRow(params){if(!params.row.selected)return{selected:!1,compacted:!1,errored:!1,result:{id:params.row.id,outcome:"skipped",entries_before:params.row.entries,entries_after:null,skip_reason:params.row.skip_reason,changed:!1,error:null}};try{const result=await runHistoryCompact(params.row.id,{dryRun:params.dryRun,author:params.options.author,message:params.options.message,force:params.options.force},params.global);return{selected:!0,compacted:!0,errored:!1,result:{id:params.row.id,outcome:"compacted",entries_before:params.row.entries,entries_after:result.history.entries_after,skip_reason:null,changed:result.changed,error:null}}}catch(error){return{selected:!0,compacted:!1,errored:!0,result:{id:params.row.id,outcome:"errored",entries_before:params.row.entries,entries_after:null,skip_reason:null,changed:!1,error:error instanceof Error?error.message:String(error),...await itemRevisionConflictRowFields(error,params.pmRoot)}}}}async function runHistoryCompactBulk(options,global2){const normalizedOptions=normalizeHistoryCompactBulkOptions(options),{pmRoot,settings,typeRegistry}=await resolveHistoryWorkspace(global2.path),{candidates,preselectionErrors}=await collectHistoryCompactBulkCandidates({pmRoot,settings,typeToFolder:typeRegistry.type_to_folder}),mode=normalizedOptions.ids!==void 0&&normalizedOptions.ids.length>0?"ids":"scan",minEntries=options.minEntries??HISTORY_COMPACT_BULK_DEFAULT_MIN_ENTRIES,policy=settings.history.compact_policy,policyThresholdApplied=mode==="scan"&&options.allOver===void 0&&policy.enabled,allOver=options.allOver??(policyThresholdApplied?policy.max_entries:void 0),selection=selectHistoryCompactBulkTargets(candidates,{ids:normalizedOptions.ids,scope:options.scope,minEntries,allOver}),dryRun=!!options.dryRun,results=[...preselectionErrors],totals={streams_considered:candidates.length+preselectionErrors.length,selected:0,items_compacted:0,items_skipped:0,items_errored:preselectionErrors.length};for(const row of selection){const outcome=await runHistoryCompactBulkRow({pmRoot,row,options:normalizedOptions,dryRun,global:global2});if(results.push(outcome.result),!outcome.selected){totals.items_skipped+=1;continue}totals.selected+=1,outcome.compacted&&(totals.items_compacted+=1),outcome.errored&&(totals.items_errored+=1)}return{bulk:!0,dry_run:dryRun,mode,scope:options.scope??null,criteria:{min_entries:minEntries,all_over:allOver??null,policy_threshold_applied:policyThresholdApplied},totals,results,generated_at:nowIso()}}export{HISTORY_COMPACT_BULK_DEFAULT_MIN_ENTRIES,assertHistoryCompactTarget,runHistoryCompact,runHistoryCompactBulk};
|
|
1
|
+
import{itemRevisionConflictRowFields as T}from"./lifecycle/item-revision.js";import I from"node:fs/promises";import{resolveHistoryHashAlgorithm as R}from"../core/history/digest.js";import H from"node:path";import{createHistoryEntry as S,hashHistoryStream as N,sealHistoryRecord as O,SUPPORTED_HISTORY_ITEM_HASH_VERSIONS as F}from"../core/history/history.js";import{selectHistoryCompactBulkTargets as U}from"../core/history/history-compact-bulk.js";import{cloneEmptyReplayDocument as b,replayHashVerificationCandidates as $,replayToItemDocument as C,toReplayDocument as D,verifyHistoryChainWithVersion as G}from"../core/history/replay.js";import{applyHistoryPatch as P}from"../core/history/projection.js";import{historyVersionOffset as E}from"../core/history/version-address.js";import{lifecycleClassifierFromStatusRegistry as M}from"../core/governance/metadata-coverage.js";import{resolveRuntimeStatusRegistry as L}from"../core/schema/runtime-schema.js";import{listAllItemMetadataLight as q}from"../core/store/item-store.js";import{pathExists as V}from"../core/fs/fs-utils.js";import{normalizeBulkIdsValue as j,parseBulkIdsText as z}from"../core/io/bulk-ids-input.js";import{EXIT_CODE as d}from"../core/shared/constants.js";import{PmCliError as l}from"../core/shared/errors.js";import{nowIso as k}from"../core/shared/time.js";import{runActiveOnReadHooks as W}from"../core/extensions/index.js";import{isJudgeableHistoryRecord as Y,recordedPrefixActivity as J}from"./governance/stale-work.js";import{resolveHistoryWorkspace as A,resolveHistorySubject as K}from"./history/subject.js";import{runHistoryMaintenance as X}from"./history/maintenance.js";function Q(e,t){if(e===void 0)return{kind:"default",raw:null,compactCount:t.length,retainedCount:0};const o=e.trim();if(o.length===0)throw new l("history-compact --before requires a non-empty value.",d.USAGE);if(/^\d+$/.test(o)){const i=Number.parseInt(o,10),s=E(t);if(!Number.isSafeInteger(i)||i<s+1||i>s+t.length+1)throw new l(`history-compact --before version must be between ${s+1} and ${s+t.length+1}.`,d.USAGE);const c=i-s-1;return{kind:"version",raw:o,compactCount:c,retainedCount:t.length-c}}const r=Date.parse(o);if(!Number.isFinite(r))throw new l(`Invalid history-compact --before value "${e}". Use a version number or ISO timestamp.`,d.USAGE);let n=0;for(const[i,s]of t.entries()){const c=Date.parse(s.ts);if(!Number.isFinite(c))throw new l(`History for this item contains invalid timestamp at entry ${i+1}.`,d.GENERIC_FAILURE);if(c>=r)break;n+=1}return{kind:"timestamp",raw:o,compactCount:n,retainedCount:t.length-n}}function Z(e,t){let o=b(),r=b();for(let n=0;n<e.length;n+=1){const i=e[n];o=P(o,i.patch,n+1,i.op),n+1===t&&(r=structuredClone(o))}return{checkpoint:r,finalReplay:o}}function ee(e,t){if(!e)return{loadedItem:null,currentItemRawBeforeLock:null,matchedChainBefore:null};const o=t[t.length-1];return{loadedItem:e,currentItemRawBeforeLock:e.raw,matchedChainBefore:F.some(r=>(o.item_hash_version===void 0||o.item_hash_version===r)&&$(D(e.document),r,R(o.hash_algorithm)).includes(o.after_hash))}}function te(e,t){return typeof e.message=="string"&&e.message.trim().length>0?e.message:t.raw===null?`history-compact compacted full stream (${t.compactCount} entr${t.compactCount===1?"y":"ies"}).`:`history-compact compacted ${t.compactCount} entr${t.compactCount===1?"y":"ies"} before ${t.raw}.`}function oe(e){return e.raw===null?`history-compact baseline snapshot after compacting ${e.compactCount} entr${e.compactCount===1?"y":"ies"}.`:`history-compact baseline snapshot before ${e.raw}.`}function re(e,t){const o=e.slice(0,t).findIndex(n=>!Y(n));if(o===-1)return;const r=Number.isFinite(Date.parse(e[o].ts))?"a malformed record or compaction receipt":"invalid timestamp";throw new l(`History for this item contains ${r} at entry ${o+1}.`,d.GENERIC_FAILURE)}function ne(e,t){const o=e[t.start].ts,r=e.slice(0,t.end+1).map(i=>Date.parse(i.ts));if(!r.every(Number.isFinite))return["that boundary",`Choose a --before timestamp at or before "${o}".`,`Run pm history-compact <id> --before "${o}".`];const n=new Date(r.reduce((i,s)=>Math.max(i,s),Number.NEGATIVE_INFINITY)).toISOString();return["that boundary",`Choose a --before timestamp at or before "${o}", or after "${n}".`,`Run pm history-compact <id> --before "${o}", or with a timestamp after "${n}".`]}function ie(e,t){const o=t-1,r=(G(e).bridged_segments??[]).find(({start:f,end:a})=>f<=o&&o<a);if(r===void 0)return;const n=E(e,!0),[i,s,c]=n===null?ne(e,r):[`version ${n+t}`,`Choose --before ${n+r.start+1} or lower, or --before ${n+r.end+2} or higher.`,`Run pm history-compact <id> --before ${n+r.start+1} or --before ${n+r.end+2}.`];throw new l(`history-compact cannot checkpoint ${i}: it lies inside a bridged segment whose states cannot be reconstructed.`,d.USAGE,{code:"history_compact_boundary_bridged",required:s,nextSteps:[c]})}function se(e){if(!e.changed)return{rewrittenEntries:e.historyEntries,baselineEntryAdded:!1,auditEntryAdded:!1};ie(e.historyEntries,e.boundary.compactCount);const{checkpoint:t,finalReplay:o}=Z(e.historyEntries,e.boundary.compactCount),r=e.historyEntries.slice(e.boundary.compactCount),n=E(e.historyEntries,!0),i=e.historyEntries[e.boundary.compactCount-1],s=S({hashAlgorithm:R(i.hash_algorithm),nowIso:e.historyEntries[e.boundary.compactCount-1].ts,author:e.author,op:"history_compact_baseline",before:C(b()),after:C(t),message:oe(e.boundary),context:{history_compaction:{contract_version:1,version_offset:n===null?null:n+e.boundary.compactCount-1,checkpoint_timestamp_semantics:"last_compacted_entry",last_activity_at:J(e.historyEntries.slice(0,e.boundary.compactCount)),pruned_entry_count:e.boundary.compactCount,pruned_stream_digest:N(e.historyEntries.slice(0,e.boundary.compactCount)),retained_proof:"stream_digest_and_checkpoint",limitation:"individual_pruned_entries_require_pre_compaction_stream"}}}),c=[O({...s,before_hash:$(b(),i.item_hash_version??1,R(i.hash_algorithm))[0],after_hash:i.after_hash,item_hash_version:i.item_hash_version,...i.replay_inexact===!0?{replay_inexact:!0}:{}}),...r];return e.dryRun||c.push(S({nowIso:k(),author:e.author,op:"history_compact",before:C(o),after:C(o),message:te(e.options,e.boundary)})),{rewrittenEntries:c,baselineEntryAdded:!0,auditEntryAdded:!e.dryRun}}async function ce(e,t,o){const{pmRoot:r,settings:n,typeRegistry:i}=await A(o.path),s=await K(r,e,n,i.type_to_folder);return X({pmRoot:r,subject:s,settings:n,typeRegistry:i,operation:"history-compact",options:t,transform:c=>ae(s,t,c)})}function ae(e,t,o){const r=e.historyPath,n=o.entries,i=o.verification;if(!i.ok)throw new l(`history-compact requires a valid history chain (${i.errors.join(", ")}). Run pm history-repair ${e.id} first.`,d.CONFLICT);const s=Q(t.before,n);re(n,s.compactCount);const c=s.compactCount>0,f=!!t.dryRun,a=o.author,u=[];c||u.push("history_compact_noop_before_boundary");const h=ee(o.loadedItem,n);h.matchedChainBefore===!1&&u.push("history_compact_item_chain_mismatch");const{rewrittenEntries:m,baselineEntryAdded:v,auditEntryAdded:g}=se({historyEntries:n,boundary:s,changed:c,dryRun:f,author:a,options:t}),_=E(n,!0),p=s.retainedCount>0&&_!==null?_+s.compactCount+1:null;return{changed:c,rewrittenEntries:m,report:({verification:w,warnings:y})=>({id:e.id,dry_run:f,changed:c,compact_boundary:{kind:s.kind,before:s.raw,entries_compacted:s.compactCount,entries_retained:s.retainedCount,first_retained_entry:p},history:{path:r,entries_scanned:n.length,entries_after:m.length,baseline_entry_added:v,audit_entry_added:g,verify_ok:w.ok,verify_errors:w.errors},item:{exists:e.located!==null,path:e.located?.itemPath??null,matched_chain_before:h.matchedChainBefore},warnings:[...new Set([...u,...y])].sort((x,B)=>x.localeCompare(B)),generated_at:k()})}}const de=3;function le(e){for(const o of["allOver","minEntries"]){const r=e[o];if(r!==void 0&&(!Number.isSafeInteger(r)||r<0))throw new l(`history-compact ${o} must be a non-negative safe integer.`,d.USAGE)}const t=j(e.ids);if(e.ids!==void 0&&t==="")throw new l("history-compact ids requires at least one valid item ID.",d.USAGE,{code:"bulk_ids_input_empty",required:"Provide one or more string or finite numeric IDs; non-finite and unsupported selector values are rejected."});return{...e,ids:t===void 0?void 0:z(t)}}function Oe(e,t){const o=t.ids!==void 0&&t.ids.length>0,r=t.allOver!==void 0||t.scope!==void 0;if((e!==void 0?1:0)+(o?1:0)+(r?1:0)===0)throw new l("history-compact: provide an item <id>, or a bulk selector (--ids, --all-over <N>, --closed, or --all-streams).",d.USAGE);if(e!==void 0&&(o||r))throw new l("history-compact: <id> and bulk selectors (--ids/--all-over/--closed/--all-streams) are mutually exclusive; pass one item id, or use bulk mode without a positional id.",d.USAGE);if(o&&r)throw new l("history-compact: --ids is mutually exclusive with --all-over/--closed/--all-streams; pass an explicit id list or a scan selector, not both.",d.USAGE)}function ue(e){let t=0;for(const o of e.split(/\r?\n/))o.trim().length>0&&(t+=1);return t}async function me(e){const t=L(e.settings.schema),o=M(t),r=await q(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema),n=new Map(r.map(a=>[a.id,o.classify(a.status)])),i=H.join(e.pmRoot,"history"),s=[],c=[];if(!await V(i))return{candidates:s,preselectionErrors:c};const f=(await I.readdir(i)).filter(a=>a.endsWith(".jsonl")).sort((a,u)=>a.localeCompare(u));for(const a of f){const u=H.join(i,a),h=a.slice(0,-6);try{const m=await I.readFile(u,"utf8");await W({path:u,scope:"project"}),s.push({id:h,entries:ue(m),bucket:n.get(h)??null})}catch(m){c.push({id:h,outcome:"errored",entries_before:0,entries_after:null,skip_reason:null,changed:!1,error:m instanceof Error?m.message:String(m)})}}return{candidates:s,preselectionErrors:c}}async function fe(e){if(!e.row.selected)return{selected:!1,compacted:!1,errored:!1,result:{id:e.row.id,outcome:"skipped",entries_before:e.row.entries,entries_after:null,skip_reason:e.row.skip_reason,changed:!1,error:null}};try{const t=await ce(e.row.id,{dryRun:e.dryRun,author:e.options.author,message:e.options.message,force:e.options.force},e.global);return{selected:!0,compacted:!0,errored:!1,result:{id:e.row.id,outcome:"compacted",entries_before:e.row.entries,entries_after:t.history.entries_after,skip_reason:null,changed:t.changed,error:null}}}catch(t){return{selected:!0,compacted:!1,errored:!0,result:{id:e.row.id,outcome:"errored",entries_before:e.row.entries,entries_after:null,skip_reason:null,changed:!1,error:t instanceof Error?t.message:String(t),...await T(t,e.pmRoot)}}}}async function Fe(e,t){const o=le(e),{pmRoot:r,settings:n,typeRegistry:i}=await A(t.path),{candidates:s,preselectionErrors:c}=await me({pmRoot:r,settings:n,typeToFolder:i.type_to_folder}),f=o.ids!==void 0&&o.ids.length>0?"ids":"scan",a=e.minEntries??de,u=n.history.compact_policy,h=f==="scan"&&e.allOver===void 0&&u.enabled,m=e.allOver??(h?u.max_entries:void 0),v=U(s,{ids:o.ids,scope:e.scope,minEntries:a,allOver:m}),g=!!e.dryRun,_=[...c],p={streams_considered:s.length+c.length,selected:0,items_compacted:0,items_skipped:0,items_errored:c.length};for(const w of v){const y=await fe({pmRoot:r,row:w,options:o,dryRun:g,global:t});if(_.push(y.result),!y.selected){p.items_skipped+=1;continue}p.selected+=1,y.compacted&&(p.items_compacted+=1),y.errored&&(p.items_errored+=1)}return{bulk:!0,dry_run:g,mode:f,scope:e.scope??null,criteria:{min_entries:a,all_over:m??null,policy_threshold_applied:h},totals:p,results:_,generated_at:k()}}export{de as HISTORY_COMPACT_BULK_DEFAULT_MIN_ENTRIES,Oe as assertHistoryCompactTarget,ce as runHistoryCompact,Fe as runHistoryCompactBulk};
|
|
2
2
|
//# sourceMappingURL=history-compact.js.map
|
package/dist/sdk/history-mcp.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
import{normalizeBulkIdsValue as c,parseBulkIdsText as y}from"../core/io/bulk-ids-input.js";import{EXIT_CODE as l}from"../core/shared/constants.js";import{PmCliError as d}from"../core/shared/errors.js";import{assertHistoryCompactTarget as g,runHistoryCompact as h,runHistoryCompactBulk as R}from"./history-compact.js";import{assertHistoryRepairTarget as S,runHistoryRepair as _,runHistoryRepairAll as v}from"./history-repair.js";import{parseRuntimeInteger as m,readRuntimeString as o}from"./runtime-input.js";function w(r){const i=r.options.all===!0,s=r.id??o(r.options,"id");return S(s,i),i?v(r.options,r.global):_(s,r.options,r.global)}function k(r){const i=r.options.ids,s=c(i);if(i!==void 0&&s==="")throw new d("history-compact ids requires at least one valid item ID.",l.USAGE,{code:"bulk_ids_input_empty",required:"Provide one or more string or finite numeric IDs; non-finite and unsupported selector values are rejected."});const p=s===void 0?void 0:y(s),a=m(r.options.allOver??r.options.all_over,"history-compact allOver"),f=m(r.options.minEntries??r.options.min_entries,"history-compact minEntries"),n=o(r.options,"scope"),e=[];r.options.closed===!0&&e.push("closed"),(r.options.allStreams===!0||r.options.all_streams===!0)&&e.push("all-streams"),(n==="closed"||n==="all-streams")&&e.push(n);const t=[...new Set(e)];if(t.length>1)throw new d("history-compact: closed and all-streams scopes are mutually exclusive.",l.USAGE);const u=t[0];return g(r.id,{ids:p,allOver:a,scope:u}),r.id!==void 0?h(r.id,{before:o(r.options,"before"),dryRun:r.options.dryRun===!0||r.options.dry_run===!0,author:o(r.options,"author"),message:o(r.options,"message"),force:r.force},r.global):R({ids:p,scope:u,allOver:a,minEntries:f,dryRun:r.options.dryRun===!0||r.options.dry_run===!0,author:o(r.options,"author"),message:o(r.options,"message"),force:r.force},r.global)}export{k as runMcpHistoryCompactAction,w as runMcpHistoryRepairAction};
|
|
2
2
|
//# sourceMappingURL=history-mcp.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
import{AGENT_PROVENANCE_DIMENSIONS as u}from"../core/shared/author.js";import{EXIT_CODE as f}from"../core/shared/constants.js";import{PmCliError as p}from"../core/shared/errors.js";const v={version:1,aliases:{}};function A(e=[]){const r=new Set(u),s=n=>{/^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(n)&&r.add(n)};for(const n of e){for(const a of Object.keys(n.provenance_environment_keys??{}))s(a);for(const a of Object.keys(n.provenance_resolvers??{}))s(a);for(const a of n.provenance_unavailable_dimensions??[])s(a)}return[...r].sort()}function _(e){if(e===void 0)return;const s=(typeof e=="string"?[e]:e).flatMap(n=>n.split(",")).map(n=>n.trim()).filter(n=>n.length>0);return s.length===0?void 0:new Set(s)}function m(e,r){if(typeof e.agent_harness=="string"&&e.agent_harness.trim())return{agent_harness:e.agent_harness,harness_source:"recorded"};const s=Object.hasOwn(r.aliases,e.author)?r.aliases[e.author]:void 0;return typeof s=="string"&&s.length>0?{agent_harness:s,harness_source:"vocabulary"}:{harness_source:"unresolved"}}function g(e,r=u){const s=new Set(r),n=new Map,a=e.provenance===void 0?[]:typeof e.provenance=="string"?[e.provenance]:e.provenance;for(const i of a.flatMap(o=>o.split(","))){const o=i.indexOf("=");if(o<0)throw new p(`Provenance predicate must use dimension=value; received "${i.trim()}".`,f.USAGE,{code:"invalid_provenance_predicate"});const t=i.slice(0,o).trim().toLowerCase(),c=i.slice(o+1).trim();if(!s.has(t))throw new p(`Unknown provenance dimension "${t||i.trim()}". Declared dimensions: ${[...s].sort().join(", ")}.`,f.USAGE,{code:"unknown_provenance_dimension"});if(c.length===0)throw new p(`Provenance predicate must use dimension=value; received "${i.trim()}".`,f.USAGE,{code:"invalid_provenance_predicate"});const d=n.get(t)??new Set;d.add(c),n.set(t,d)}return n}function P(e,r=v,s={}){const n=m(e,r);return{...s.itemId===void 0?{}:{item_id:s.itemId},...s.version===void 0?{}:{version:s.version},ts:e.ts,op:e.op,author:e.author,...e.author_source===void 0?{}:{author_source:e.author_source},...n,vocabulary_version:r.version,...e.agent_instance===void 0?{}:{agent_instance:e.agent_instance},agent_provenance:e.agent_provenance??{},...e.message===void 0?{}:{message:e.message}}}function b(e,r,s=v,n=u){return w(r,s,n)(e)}function w(e,r=v,s=u){const n=_(e.harness),a=_(e.agentInstance),i=g(e,s);return o=>{const c=m(o,r).agent_harness;if(n&&(!c||!n.has(c))||a&&!a.has(o.agent_instance??""))return!1;for(const[d,l]of i){const h=o.agent_provenance?.[d];if(!h||!l.has(h.value))return!1}return!0}}function H(e,r=v,s=u){const n=new Set(s),a=new Map;let i=0;for(const o of e){for(const c of Object.keys(o.agent_provenance??{}))n.add(c);m(o,r).agent_harness?i+=1:a.set(o.author,(a.get(o.author)??0)+1)}return{entries:e.length,vocabulary_version:r.version,harness:{resolved:i,unresolved:e.length-i,unresolved_authors:[...a].map(([o,t])=>({author:o,entries:t})).sort((o,t)=>t.entries-o.entries||o.author.localeCompare(t.author)).slice(0,20)},dimensions:[...n].sort().map(o=>{let t=0,c=0;for(const d of e){const l=d.agent_provenance?.[o];l===null?c+=1:l!==void 0&&(t+=1)}return{dimension:o,observed:t,unavailable:c,legacy_missing:e.length-t-c}})}}export{v as DEFAULT_AUTHOR_IDENTITY_VOCABULARY,w as compileHistoryProvenanceMatcher,b as historyEntryMatchesProvenance,g as parseHistoryProvenanceFilters,P as projectHistoryProvenance,A as resolveHistoryProvenanceDimensions,H as summarizeHistoryProvenance};
|
|
2
2
|
//# sourceMappingURL=history-provenance.js.map
|
package/dist/sdk/history-read.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
import{resolveHistoryHashAlgorithm as v}from"../core/history/digest.js";import{assertInitializedTracker as H}from"./environment/tracker-preflight.js";import{getActiveExtensionRegistrations as x}from"../core/extensions/index.js";import{applyHistoryPatch as I,ensureMaterializedHistoryTarget as f,extractPatchFailureContext as E,replayHistoryToTarget as c,resolveHistoryTarget as l}from"../core/history/projection.js";import{readHistoryEntries as p}from"../core/history/read.js";import{historyVersionOffset as w}from"../core/history/version-address.js";import{hashDocument as T,hashDocumentVerificationCandidates as C,hashEmptyDocument as R}from"../core/history/history.js";import{replayToCanonicalItemDocument as A,verifyHistoryChainWithVersion as O}from"../core/history/replay.js";import{resolveItemTypeRegistry as P}from"../core/item/type-registry.js";import{EXIT_CODE as u}from"../core/shared/constants.js";import{PmCliError as y}from"../core/shared/errors.js";import{resolvePmRoot as D}from"../core/store/paths.js";import{readSettings as N}from"../core/store/settings.js";import{resolveHistorySubject as b}from"./history/subject.js";import{findHistoryIdentityDiscontinuities as Y}from"../core/history/identity.js";function B(t,i){const s=O(t),n=t.length>0?t[t.length-1].after_hash:R(),o=i===void 0||s.item_hash_version===void 0?void 0:C(i,s.item_hash_version,v(t.at(-1)?.hash_algorithm)),a=i===void 0?void 0:o===void 0?T(i):o[Math.max(0,o.indexOf(n))],r=a===void 0?void 0:a===n,e=[...s.errors];return r===!1&&e.push("verify_failed:current_item_hash_mismatch"),{ok:e.length===0,entries:t.length,errors:e,latest_after_hash:t.length>0?t[t.length-1].after_hash:void 0,current_item_hash:a,current_matches_latest:r}}async function J(t,i,s={}){const n=D(s.cwd??process.cwd(),s.pmRoot);await H(n);const o=await N(n),a=P(o,x()),r=await b(n,t,o,a.type_to_folder),e=await p(r.historyPath,r.id);if(e.length===0)throw new y(`No history exists for ${r.id}; point-in-time reads are unavailable.`,u.NOT_FOUND);const m=l(i,e),_=f(c(e,m.historyIndex),m),h=A(_,{schema:o.schema});if(h.metadata.id!==r.id)throw new y(`History target resolved to item ${h.metadata.id}, expected ${r.id}.`,u.GENERIC_FAILURE);const g=e[m.historyIndex],d=w(e,!0);return{document:h,reconstructed:!0,as_of_version:d===null?null:d+m.historyIndex+1,as_of_timestamp:g.ts,target:m,history_length:e.length}}export{I as applyHistoryPatch,f as ensureMaterializedHistoryTarget,E as extractPatchFailureContext,Y as findHistoryIdentityDiscontinuities,J as getItemAt,p as readHistoryEntries,c as replayHistoryToTarget,l as resolveHistoryTarget,B as verifyHistoryEntries};
|
|
2
2
|
//# sourceMappingURL=history-read.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="99336062-727a-5797-8586-117c3c106dcc")}catch{}})();import{resolveHistoryWorkspace,resolveHistorySubject}from"./history/subject.js";import{resolveHistorySubject as resolveHistorySubject2}from"./history/subject.js";import fs from"node:fs/promises";import{resolveHistoryHashAlgorithm}from"../core/history/digest.js";import{writeFileAtomic}from"../core/fs/fs-utils.js";import{createHistoryEntry,resealHistoryRewrite,verifyHistoryRecordHash}from"../core/history/history.js";import{invalidateHistoryDriftCacheForPath}from"../core/history/drift-cache.js";import{runHistoryMaintenance}from"./history/maintenance.js";import{EMPTY_REPLAY_DOCUMENT,historyEntriesToRaw,replayHash,replayToItemDocument}from"../core/history/replay.js";import{applyHistoryPatch}from"../core/history/projection.js";import{canonicalDocument,serializeItemDocument}from"../core/item/item-format.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{nowIso}from"../core/shared/time.js";import{runActiveOnWriteHooks}from"../core/extensions/index.js";import{acquireItemMetadataDerivedIndexLock,refreshItemMetadataDerivedIndex}from"../core/store/item-metadata-cache.js";import{getItemPath}from"../core/store/paths.js";function normalizeStringArrayInput(value){return Array.isArray(value)?value:typeof value=="string"?[value]:[]}function normalizeRegexFlags(flags){const unique=[];for(const token of flags)unique.includes(token)||unique.push(token);return unique.includes("g")||unique.push("g"),unique.join("")}function invalidRegexRule(index,reason){return new PmCliError(`Invalid --regex value at --regex #${index}: ${reason}`,EXIT_CODE.USAGE,{code:"invalid_argument_value",field:"regex",reason:"invalid_regex",changed:!1,required:`Correct --regex #${index}: use a non-empty raw source or /pattern/flags with valid JavaScript flags.`})}function parseRegexRule(spec,index=1){const trimmed=spec.trim();if(trimmed.length===0)throw invalidRegexRule(index,"provide a non-empty pattern.");let source=trimmed,flags="g";if(trimmed.startsWith("/")&&trimmed.length>1){const slashIndex=trimmed.lastIndexOf("/");let backslashes=0;for(let index2=slashIndex-1;index2>=0&&trimmed[index2]==="\\";index2--)backslashes++;slashIndex>0&&backslashes%2===0&&/^[dgimsuvy]*$/u.test(trimmed.slice(slashIndex+1))&&(source=trimmed.slice(1,slashIndex),flags=normalizeRegexFlags(trimmed.slice(slashIndex+1)))}if(source.length===0)throw invalidRegexRule(index,"an empty pattern is not allowed.");try{new RegExp(source,flags)}catch{throw invalidRegexRule(index,"provide a valid JavaScript regular expression.")}return{kind:"regex",source,flags}}function buildRedactionRules(literalInput,regexInput){const literalRules=[...new Set(normalizeStringArrayInput(literalInput).map(entry=>entry.trim()))].filter(entry=>entry.length>0).map(entry=>({kind:"literal",value:entry})),seen=new Set,regexRules=normalizeStringArrayInput(regexInput).flatMap((entry,index)=>{const spec=entry.trim();return seen.has(spec)?[]:(seen.add(spec),[parseRegexRule(spec,index+1)])}),rules=[...literalRules,...regexRules];if(rules.length===0)throw new PmCliError("history-redact requires at least one matcher via --literal or --regex.",EXIT_CODE.USAGE,{code:"missing_required_argument",required:"Provide --literal <value> and/or --regex <pattern>.",examples:['pm history-redact pm-a1b2 --literal "[redacted_path_prefix]/private"','pm history-redact pm-a1b2 --regex "/192\\\\.168\\\\.[0-9.]+/g" --replacement "[scrubbed_ip]"']});return rules}function applyLiteralRule(value,literal,replacement){if(literal.length===0)return{value,replacements:0};let cursor=0,replacements=0;for(;cursor<=value.length;){const index=value.indexOf(literal,cursor);if(index===-1)break;replacements+=1,cursor=index+Math.max(1,literal.length)}return replacements===0?{value,replacements:0}:{value:value.split(literal).join(replacement),replacements}}function applyRegexRule(value,rule,replacement){const regex=new RegExp(rule.source,rule.flags),matches=[...value.matchAll(regex)];return matches.length===0?{value,replacements:0}:{value:value.replace(regex,replacement),replacements:matches.length}}function redactStringValue(value,rules,replacement){let next=value,replacements=0;for(const rule of rules){const result=rule.kind==="literal"?applyLiteralRule(next,rule.value,replacement):applyRegexRule(next,rule,replacement);next=result.value,replacements+=result.replacements}return{value:next,replacements}}function redactUnknownValue(value,rules,replacement){if(typeof value=="string")return redactStringValue(value,rules,replacement);if(Array.isArray(value)){let replacements=0;return{value:value.map(entry=>{const redacted=redactUnknownValue(entry,rules,replacement);return replacements+=redacted.replacements,redacted.value}),replacements}}if(typeof value=="object"&&value!==null){let replacements=0;const nextRecord={};for(const[key,entry]of Object.entries(value)){const redacted=redactUnknownValue(entry,rules,replacement);replacements+=redacted.replacements,nextRecord[key]=redacted.value}return{value:nextRecord,replacements}}return{value,replacements:0}}function redactHistoryPatch(patch,rules,replacement){let replacements=0;return{patch:patch.map(operation=>{if(!Object.prototype.hasOwnProperty.call(operation,"value"))return operation;const redactedValue=redactUnknownValue(operation.value,rules,replacement);return replacements+=redactedValue.replacements,redactedValue.replacements>0?{...operation,value:redactedValue.value}:operation}),replacements}}function inspectHistoryIntegrity(entries){let replay=structuredClone(EMPTY_REPLAY_DOCUMENT),hashMismatchesBefore=0,hashMismatchesAfter=0;for(let index=0;index<entries.length;index+=1){const entry=entries[index];replayHash(replay,void 0,resolveHistoryHashAlgorithm(entry.hash_algorithm))!==entry.before_hash&&(hashMismatchesBefore+=1),replay=applyHistoryPatch(replay,entry.patch,index+1,entry.op),replayHash(replay,void 0,resolveHistoryHashAlgorithm(entry.hash_algorithm))!==entry.after_hash&&(hashMismatchesAfter+=1)}return{hashMismatchesBefore,hashMismatchesAfter,finalDocument:replay}}function redactHistoryEntry(entry,rules,replacement){let replacements=0,changed=!1,reanchorEvidenceRedacted=!1,nextMessage=entry.message;if(typeof entry.message=="string"){const redactedMessage=redactStringValue(entry.message,rules,replacement);nextMessage=redactedMessage.value,replacements+=redactedMessage.replacements,redactedMessage.replacements>0&&(changed=!0)}const redactedPatch=redactHistoryPatch(entry.patch,rules,replacement);replacements+=redactedPatch.replacements,changed||=redactedPatch.replacements>0;const nextReanchorEvidence=entry.reanchor_evidence?.map(evidence=>{const redactedEvidencePatch=evidence.patch?redactHistoryPatch(evidence.patch,rules,replacement):{patch:void 0,replacements:0},redactedEvidenceRecord=evidence.record?redactUnknownValue(evidence.record,rules,replacement):{value:void 0,replacements:0};replacements+=redactedEvidencePatch.replacements,replacements+=redactedEvidenceRecord.replacements;const evidenceChanged=redactedEvidencePatch.replacements>0||redactedEvidenceRecord.replacements>0;if(changed||=evidenceChanged,!evidenceChanged)return evidence;reanchorEvidenceRedacted=!0;const{patch:_sensitivePatch,record:_sensitiveRecord,record_hash:_priorRecordHash,record_hash_version:_priorRecordHashVersion,...digestOnlyEvidence}=evidence;return redactedEvidencePatch.replacements>0?digestOnlyEvidence:{...digestOnlyEvidence,patch:evidence.patch}});return{entry:{...entry,message:nextMessage,patch:redactedPatch.patch,...nextReanchorEvidence?{reanchor_evidence:nextReanchorEvidence}:{}},replacements,changed,reanchorEvidenceRedacted}}function rewriteHistoryEntries(entries,rules,replacement){let replay=structuredClone(EMPTY_REPLAY_DOCUMENT),entriesChanged=0,replacements=0;const rewrittenEntries=[];for(let index=0;index<entries.length;index+=1){const original=entries[index],recordVerification=verifyHistoryRecordHash(original);if(!recordVerification.ok)throw new PmCliError(`history-redact refuses invalid immutable record ${index+1} (${recordVerification.error}).`,EXIT_CODE.GENERIC_FAILURE);const redacted=redactHistoryEntry(original,rules,replacement);replacements+=redacted.replacements,redacted.changed&&(entriesChanged+=1);const beforeHash=replayHash(replay,void 0,resolveHistoryHashAlgorithm(original.hash_algorithm));replay=applyHistoryPatch(replay,redacted.entry.patch,index+1,redacted.entry.op);const afterHash=replayHash(replay,void 0,resolveHistoryHashAlgorithm(original.hash_algorithm));rewrittenEntries.push(resealHistoryRewrite(original,{...redacted.entry,before_hash:beforeHash,after_hash:afterHash},{retainPriorRecord:redacted.changed,retainPriorRecordHash:!redacted.changed}))}return{entries:rewrittenEntries,finalDocument:replay,entriesChanged,replacements}}function hasItemMetadata(replay){return Object.keys(replay.metadata).length>0}function resolveHistoryRedactNextItem(params){if(!hasItemMetadata(params.finalDocument))return{raw:null,path:null,document:null};const canonical=canonicalDocument(replayToItemDocument(params.finalDocument),{schema:params.settings.schema});if(canonical.metadata.id!==params.subject.id)throw new PmCliError("history-redact would change the item id; narrow your patterns.",EXIT_CODE.USAGE);return{document:canonical,path:getItemPath(params.pmRoot,canonical.metadata.type,params.subject.id,"toon",params.typeToFolder),raw:serializeItemDocument(canonical,{format:"toon",schema:params.settings.schema})}}function buildHistoryRedactMessage(options,rewritten){return typeof options.message=="string"&&options.message.trim().length>0?options.message:`history-redact replaced ${rewritten.replacements} match(es) across ${rewritten.entriesChanged} entr${rewritten.entriesChanged===1?"y":"ies"}.`}function buildHistoryRedactEntries(params){const rewrittenEntries=[...params.rewritten.entries];if(params.dryRun||!params.changed)return{rewrittenEntries,auditEntryAdded:!1};const finalDocument=params.nextItemDocument??replayToItemDocument(params.rewritten.finalDocument);return rewrittenEntries.push(createHistoryEntry({nowIso:nowIso(),author:params.author,op:"history_redact",before:finalDocument,after:finalDocument,message:params.message})),{rewrittenEntries,auditEntryAdded:!0}}function createHistoryRedactTransaction(params){let derivedIndexWarnings=[];return{applyRewrite:async({historyRawUnderLock})=>{const releaseDerivedIndexLock=await acquireItemMetadataDerivedIndexLock(params.pmRoot,params.author),affectedItemPaths=new Set;params.currentItem.path&&affectedItemPaths.add(params.currentItem.path),params.nextItem.path&&affectedItemPaths.add(params.nextItem.path);const itemSnapshots=new Map;params.currentItem.path&¶ms.currentItem.raw!==null&&itemSnapshots.set(params.currentItem.path,params.currentItem.raw);let rethrowReleaseFailure=()=>{};try{try{params.nextItem.path&¶ms.nextItem.raw!==null&¶ms.nextItem.raw!==params.currentItem.raw&&await writeFileAtomic(params.nextItem.path,params.nextItem.raw),params.currentItem.path&&(!params.nextItem.path||params.nextItem.path!==params.currentItem.path)&&await fs.rm(params.currentItem.path,{force:!0}),await writeFileAtomic(params.subject.historyPath,historyEntriesToRaw(params.rewrittenEntries))}catch(error){try{await rollbackHistoryRedactRewrite(params.subject.historyPath,historyRawUnderLock,affectedItemPaths,itemSnapshots)}finally{await invalidateHistoryDriftCacheForPath(params.subject.historyPath)}throw error}await invalidateHistoryDriftCacheForPath(params.subject.historyPath);const itemPath=params.nextItem.path??params.currentItem.path;itemPath&&(derivedIndexWarnings=await refreshItemMetadataDerivedIndex({pmRoot:params.pmRoot,preferredFormat:params.settings.item_format,typeToFolder:params.typeRegistry.type_to_folder,schema:params.settings.schema,itemPath,...params.currentItem.path?{previousItemPath:params.currentItem.path}:{},document:params.nextItem.document}))}finally{await releaseDerivedIndexLock().catch(error=>{rethrowReleaseFailure=()=>{throw error}})}rethrowReleaseFailure()},afterWrite:async()=>[...derivedIndexWarnings,...await runHistoryRedactWriteHooks(params.subject.historyPath,[params.nextItem.path,params.currentItem.path])]}}async function rollbackHistoryRedactRewrite(historyPath,historyRawUnderLock,affectedItemPaths,itemSnapshots){historyRawUnderLock===null?await fs.rm(historyPath,{force:!0}):await writeFileAtomic(historyPath,historyRawUnderLock);for(const itemPath of affectedItemPaths){const snapshot=itemSnapshots.get(itemPath);snapshot===void 0?await fs.rm(itemPath,{force:!0}):await writeFileAtomic(itemPath,snapshot)}}async function runHistoryRedactWriteHooks(historyPath,itemHookPaths){const hookWarnings=[],uniqueItemHookPaths=new Set(itemHookPaths.filter(itemPath=>itemPath!==null));for(const itemHookPath of uniqueItemHookPaths)hookWarnings.push(...await runActiveOnWriteHooks({path:itemHookPath,scope:"project",op:"history_redact"}));return hookWarnings.push(...await runActiveOnWriteHooks({path:historyPath,scope:"project",op:"history_redact:history"})),hookWarnings}async function runHistoryRedact(id,options,global2){const{pmRoot,settings,typeRegistry}=await resolveHistoryWorkspace(global2.path),replacementInput=options.replacement??"",replacementIsDefault=replacementInput.length===0,replacement=replacementIsDefault?"[redacted]":replacementInput,rules=buildRedactionRules(options.literal,options.regex),subject=await resolveHistorySubject(pmRoot,id,settings,typeRegistry.type_to_folder);return runHistoryMaintenance({pmRoot,subject,settings,typeRegistry,operation:"history-redact",options,transform:snapshot=>buildHistoryRedactPlan({pmRoot,subject,settings,typeRegistry,options,rules,replacement,replacementIsDefault},snapshot)})}function buildHistoryRedactPlan(params,snapshot){const{pmRoot,subject,settings,typeRegistry,options,rules,replacement,replacementIsDefault}=params,historyEntries=snapshot.entries,integritySnapshot=inspectHistoryIntegrity(historyEntries),rewritten=rewriteHistoryEntries(historyEntries,rules,replacement),preexistingHashMismatches=integritySnapshot.hashMismatchesBefore+integritySnapshot.hashMismatchesAfter,dryRun=!!options.dryRun,changed=rewritten.replacements>0,warnings=[];preexistingHashMismatches>0&&warnings.push(`history_redact_preexisting_hash_mismatches:${preexistingHashMismatches}`),changed||warnings.push("history_redact_no_matches");const currentItem={raw:snapshot.loadedItem?.raw??null,path:subject.located?.itemPath??null,document:snapshot.loadedItem?.document??null},nextItem=resolveHistoryRedactNextItem({pmRoot,subject,settings,typeToFolder:typeRegistry.type_to_folder,finalDocument:rewritten.finalDocument}),itemChanged=(currentItem.path??null)!==(nextItem.path??null)||(currentItem.raw??null)!==(nextItem.raw??null),author=snapshot.author,redactionMessage=buildHistoryRedactMessage(options,rewritten),{rewrittenEntries,auditEntryAdded}=buildHistoryRedactEntries({rewritten,dryRun,changed,nextItemDocument:nextItem.document,author,message:redactionMessage});return{changed,rewrittenEntries,...createHistoryRedactTransaction({pmRoot,subject,settings,typeRegistry,currentItem,nextItem,author,rewrittenEntries}),report:({verification:historyVerify,warnings:writeWarnings})=>({id:subject.id,dry_run:dryRun,changed,patterns:{literal_count:rules.filter(rule=>rule.kind==="literal").length,regex_count:rules.filter(rule=>rule.kind==="regex").length,total_count:rules.length,replacement_is_default:replacementIsDefault},history:{path:subject.historyPath,entries_scanned:historyEntries.length,entries_changed:rewritten.entriesChanged,replacements:rewritten.replacements,hash_mismatches_before:integritySnapshot.hashMismatchesBefore,hash_mismatches_after:integritySnapshot.hashMismatchesAfter,preexisting_hash_mismatches:preexistingHashMismatches,audit_entry_added:auditEntryAdded,verify_ok:historyVerify.ok,verify_errors:historyVerify.errors},item:{existed_before:currentItem.path!==null,exists_after:nextItem.path!==null,path_before:currentItem.path,path_after:nextItem.path,changed:itemChanged},warnings:[...new Set([...warnings,...writeWarnings])].sort((left,right)=>left.localeCompare(right)),generated_at:nowIso()})}}const _testOnly={applyLiteralRule,applyRegexRule,buildRedactionRules,hasItemMetadata,normalizeRegexFlags,normalizeStringArrayInput,parseRegexRule,redactStringValue,redactUnknownValue};export{_testOnly,resolveHistorySubject2 as resolveHistorySubject,runHistoryRedact};
|
|
1
|
+
import{resolveHistoryWorkspace as K,resolveHistorySubject as Q}from"./history/subject.js";import{resolveHistorySubject as Ue}from"./history/subject.js";import H from"node:fs/promises";import{resolveHistoryHashAlgorithm as v}from"../core/history/digest.js";import{locateBridgedSegments as Z}from"../core/history/bridge.js";import{writeFileAtomic as b}from"../core/fs/fs-utils.js";import{createHistoryEntry as ee,resealHistoryRewrite as te,verifyHistoryRecordHash as re}from"../core/history/history.js";import{invalidateHistoryDriftCacheForPath as S}from"../core/history/drift-cache.js";import{runHistoryMaintenance as ne}from"./history/maintenance.js";import{EMPTY_REPLAY_DOCUMENT as C,collectBridgedInteriorIndexes as oe,historyEntriesToRaw as ae,replayHash as E,replayToItemDocument as O}from"../core/history/replay.js";import{applyHistoryPatch as $}from"../core/history/projection.js";import{canonicalDocument as ie,serializeItemDocument as se}from"../core/item/item-format.js";import{EXIT_CODE as x}from"../core/shared/constants.js";import{PmCliError as I}from"../core/shared/errors.js";import{nowIso as F}from"../core/shared/time.js";import{runActiveOnWriteHooks as T}from"../core/extensions/index.js";import{acquireItemMetadataDerivedIndexLock as ce,refreshItemMetadataDerivedIndex as le}from"../core/store/item-metadata-cache.js";import{getItemPath as he}from"../core/store/paths.js";function P(e){return Array.isArray(e)?e:typeof e=="string"?[e]:[]}function q(e){const t=[];for(const n of e)t.includes(n)||t.push(n);return t.includes("g")||t.push("g"),t.join("")}function k(e,t){return new I(`Invalid --regex value at --regex #${e}: ${t}`,x.USAGE,{code:"invalid_argument_value",field:"regex",reason:"invalid_regex",changed:!1,required:`Correct --regex #${e}: use a non-empty raw source or /pattern/flags with valid JavaScript flags.`})}function B(e,t=1){const n=e.trim();if(n.length===0)throw k(t,"provide a non-empty pattern.");let r=n,o="g";if(n.startsWith("/")&&n.length>1){const a=n.lastIndexOf("/");let i=0;for(let s=a-1;s>=0&&n[s]==="\\";s--)i++;a>0&&i%2===0&&/^[dgimsuvy]*$/u.test(n.slice(a+1))&&(r=n.slice(1,a),o=q(n.slice(a+1)))}if(r.length===0)throw k(t,"an empty pattern is not allowed.");try{new RegExp(r,o)}catch{throw k(t,"provide a valid JavaScript regular expression.")}return{kind:"regex",source:r,flags:o}}function W(e,t){const n=[...new Set(P(e).map(i=>i.trim()))].filter(i=>i.length>0).map(i=>({kind:"literal",value:i})),r=new Set,o=P(t).flatMap((i,s)=>{const h=i.trim();return r.has(h)?[]:(r.add(h),[B(h,s+1)])}),a=[...n,...o];if(a.length===0)throw new I("history-redact requires at least one matcher via --literal or --regex.",x.USAGE,{code:"missing_required_argument",required:"Provide --literal <value> and/or --regex <pattern>.",examples:['pm history-redact pm-a1b2 --literal "[redacted_path_prefix]/private"','pm history-redact pm-a1b2 --regex "/192\\\\.168\\\\.[0-9.]+/g" --replacement "[scrubbed_ip]"']});return a}function U(e,t,n){if(t.length===0)return{value:e,replacements:0};let r=0,o=0;for(;r<=e.length;){const a=e.indexOf(t,r);if(a===-1)break;o+=1,r=a+Math.max(1,t.length)}return o===0?{value:e,replacements:0}:{value:e.split(t).join(n),replacements:o}}function V(e,t,n){const r=new RegExp(t.source,t.flags),o=[...e.matchAll(r)];return o.length===0?{value:e,replacements:0}:{value:e.replace(r,n),replacements:o.length}}function A(e,t,n){let r=e,o=0;for(const a of t){const i=a.kind==="literal"?U(r,a.value,n):V(r,a,n);r=i.value,o+=i.replacements}return{value:r,replacements:o}}function R(e,t,n){if(typeof e=="string")return A(e,t,n);if(Array.isArray(e)){let r=0;return{value:e.map(a=>{const i=R(a,t,n);return r+=i.replacements,i.value}),replacements:r}}if(typeof e=="object"&&e!==null){let r=0;const o={};for(const[a,i]of Object.entries(e)){const s=R(i,t,n);r+=s.replacements,o[a]=s.value}return{value:o,replacements:r}}return{value:e,replacements:0}}function G(e,t,n){let r=0;return{patch:e.map(a=>{if(!Object.prototype.hasOwnProperty.call(a,"value"))return a;const i=R(a.value,t,n);return r+=i.replacements,i.replacements>0?{...a,value:i.value}:a}),replacements:r}}function de(e){let t=structuredClone(C),n=0,r=0;for(let o=0;o<e.length;o+=1){const a=e[o];E(t,void 0,v(a.hash_algorithm))!==a.before_hash&&(n+=1),t=$(t,a.patch,o+1,a.op),E(t,void 0,v(a.hash_algorithm))!==a.after_hash&&(r+=1)}return{hashMismatchesBefore:n,hashMismatchesAfter:r,finalDocument:t}}function ue(e,t,n){let r=0,o=!1,a=!1,i=e.message;if(typeof e.message=="string"){const c=A(e.message,t,n);i=c.value,r+=c.replacements,c.replacements>0&&(o=!0)}const s=G(e.patch,t,n);r+=s.replacements,o||=s.replacements>0;const h=e.reanchor_evidence?.map(c=>{const l=c.patch?G(c.patch,t,n):{patch:void 0,replacements:0},d=c.record?R(c.record,t,n):{value:void 0,replacements:0};r+=l.replacements,r+=d.replacements;const u=l.replacements>0||d.replacements>0;if(o||=u,!u)return c;a=!0;const{patch:m,record:w,record_hash:p,record_hash_version:g,...f}=c;return l.replacements>0?f:{...f,patch:c.patch}});return{entry:{...e,message:i,patch:s.patch,...h?{reanchor_evidence:h}:{}},replacements:r,changed:o,reanchorEvidenceRedacted:a}}function me(e,t,n){let r=structuredClone(C),o=0,a=0;const i=[],s=Z(e),h=[...s.unlocated,...s.undigested];if(h.length>0)throw new I(`history-redact refuses a stream whose bridge at record ${Math.min(...h)+1} does not prove its segment; repair the history first.`,x.GENERIC_FAILURE,{code:"history_redact_bridge_unlocated",required:"Every bridge's segment digest must match the records it covers, so redaction can keep that segment's versions refused.",nextSteps:["Run pm history-repair <id> --dry-run to see how the stream would be repaired."]});const c=oe(s.segments);for(let l=0;l<e.length;l+=1){const d=e[l],u=re(d);if(!u.ok)throw new I(`history-redact refuses invalid immutable record ${l+1} (${u.error}).`,x.GENERIC_FAILURE);const m=ue(d,t,n);a+=m.replacements,m.changed&&(o+=1);const w=E(r,void 0,v(d.hash_algorithm));r=$(r,m.entry.patch,l+1,m.entry.op);const p=E(r,void 0,v(d.hash_algorithm)),{bridge:g,...f}=m.entry;i.push(te(d,{...f,...c.has(l)?{replay_inexact:!0}:{},before_hash:w,after_hash:p},{retainPriorRecord:m.changed||g!==void 0,retainPriorRecordHash:!m.changed}))}return{entries:i,finalDocument:r,entriesChanged:o,replacements:a}}function L(e){return Object.keys(e.metadata).length>0}function fe(e){if(!L(e.finalDocument))return{raw:null,path:null,document:null};const t=ie(O(e.finalDocument),{schema:e.settings.schema});if(t.metadata.id!==e.subject.id)throw new I("history-redact would change the item id; narrow your patterns.",x.USAGE);return{document:t,path:he(e.pmRoot,t.metadata.type,e.subject.id,"toon",e.typeToFolder),raw:se(t,{format:"toon",schema:e.settings.schema})}}function pe(e,t){return typeof e.message=="string"&&e.message.trim().length>0?e.message:`history-redact replaced ${t.replacements} match(es) across ${t.entriesChanged} entr${t.entriesChanged===1?"y":"ies"}.`}function ge(e){const t=[...e.rewritten.entries];if(e.dryRun||!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};const n=e.nextItemDocument??O(e.rewritten.finalDocument);return t.push(ee({nowIso:F(),author:e.author,op:"history_redact",before:n,after:n,message:e.message})),{rewrittenEntries:t,auditEntryAdded:!0}}function ye(e){let t=[];return{applyRewrite:async({historyRawUnderLock:n})=>{const r=await ce(e.pmRoot,e.author),o=new Set;e.currentItem.path&&o.add(e.currentItem.path),e.nextItem.path&&o.add(e.nextItem.path);const a=new Map;e.currentItem.path&&e.currentItem.raw!==null&&a.set(e.currentItem.path,e.currentItem.raw);let i=()=>{};try{try{e.nextItem.path&&e.nextItem.raw!==null&&e.nextItem.raw!==e.currentItem.raw&&await b(e.nextItem.path,e.nextItem.raw),e.currentItem.path&&(!e.nextItem.path||e.nextItem.path!==e.currentItem.path)&&await H.rm(e.currentItem.path,{force:!0}),await b(e.subject.historyPath,ae(e.rewrittenEntries))}catch(h){try{await we(e.subject.historyPath,n,o,a)}finally{await S(e.subject.historyPath)}throw h}await S(e.subject.historyPath);const s=e.nextItem.path??e.currentItem.path;s&&(t=await le({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:e.typeRegistry.type_to_folder,schema:e.settings.schema,itemPath:s,...e.currentItem.path?{previousItemPath:e.currentItem.path}:{},document:e.nextItem.document}))}finally{await r().catch(s=>{i=()=>{throw s}})}i()},afterWrite:async()=>[...t,...await _e(e.subject.historyPath,[e.nextItem.path,e.currentItem.path])]}}async function we(e,t,n,r){t===null?await H.rm(e,{force:!0}):await b(e,t);for(const o of n){const a=r.get(o);a===void 0?await H.rm(o,{force:!0}):await b(o,a)}}async function _e(e,t){const n=[],r=new Set(t.filter(o=>o!==null));for(const o of r)n.push(...await T({path:o,scope:"project",op:"history_redact"}));return n.push(...await T({path:e,scope:"project",op:"history_redact:history"})),n}async function Te(e,t,n){const{pmRoot:r,settings:o,typeRegistry:a}=await K(n.path),i=t.replacement??"",s=i.length===0,h=s?"[redacted]":i,c=W(t.literal,t.regex),l=await Q(r,e,o,a.type_to_folder);return ne({pmRoot:r,subject:l,settings:o,typeRegistry:a,operation:"history-redact",options:t,transform:d=>xe({pmRoot:r,subject:l,settings:o,typeRegistry:a,options:t,rules:c,replacement:h,replacementIsDefault:s},d)})}function xe(e,t){const{pmRoot:n,subject:r,settings:o,typeRegistry:a,options:i,rules:s,replacement:h,replacementIsDefault:c}=e,l=t.entries,d=de(l),u=me(l,s,h),m=d.hashMismatchesBefore+d.hashMismatchesAfter,w=!!i.dryRun,p=u.replacements>0,g=[];m>0&&g.push(`history_redact_preexisting_hash_mismatches:${m}`),p||g.push("history_redact_no_matches");const f={raw:t.loadedItem?.raw??null,path:r.located?.itemPath??null,document:t.loadedItem?.document??null},y=fe({pmRoot:n,subject:r,settings:o,typeToFolder:a.type_to_folder,finalDocument:u.finalDocument}),N=(f.path??null)!==(y.path??null)||(f.raw??null)!==(y.raw??null),D=t.author,z=pe(i,u),{rewrittenEntries:M,auditEntryAdded:J}=ge({rewritten:u,dryRun:w,changed:p,nextItemDocument:y.document,author:D,message:z});return{changed:p,rewrittenEntries:M,...ye({pmRoot:n,subject:r,settings:o,typeRegistry:a,currentItem:f,nextItem:y,author:D,rewrittenEntries:M}),report:({verification:j,warnings:Y})=>({id:r.id,dry_run:w,changed:p,patterns:{literal_count:s.filter(_=>_.kind==="literal").length,regex_count:s.filter(_=>_.kind==="regex").length,total_count:s.length,replacement_is_default:c},history:{path:r.historyPath,entries_scanned:l.length,entries_changed:u.entriesChanged,replacements:u.replacements,hash_mismatches_before:d.hashMismatchesBefore,hash_mismatches_after:d.hashMismatchesAfter,preexisting_hash_mismatches:m,audit_entry_added:J,verify_ok:j.ok,verify_errors:j.errors},item:{existed_before:f.path!==null,exists_after:y.path!==null,path_before:f.path,path_after:y.path,changed:N},warnings:[...new Set([...g,...Y])].sort((_,X)=>_.localeCompare(X)),generated_at:F()})}}const qe={applyLiteralRule:U,applyRegexRule:V,buildRedactionRules:W,hasItemMetadata:L,normalizeRegexFlags:q,normalizeStringArrayInput:P,parseRegexRule:B,redactStringValue:A,redactUnknownValue:R};export{qe as _testOnly,Ue as resolveHistorySubject,Te as runHistoryRedact};
|
|
2
2
|
//# sourceMappingURL=history-redact.js.map
|
|
@@ -3,11 +3,13 @@
|
|
|
3
3
|
*
|
|
4
4
|
* Implements the pm history repair command surface and its agent-facing runtime behavior.
|
|
5
5
|
*/
|
|
6
|
-
import{type ItemRevisionConflictRowFields}from "./lifecycle/item-revision.js";import{type HistorySalvageReceipt}from "./history/salvage.js";import{type ReplayDocument}from "../core/history/replay.js";import type{GlobalOptions}from "../core/shared/command-types.js";import type{HistoryEntry}from "../types/index.js";import{type MergeDecisionReceipt}from "./merge/receipts.js";import{type ProvenanceNormalizationReceipt}from "./governance/provenance-health.js";
|
|
6
|
+
import{type ItemRevisionConflictRowFields}from "./lifecycle/item-revision.js";import{type HistorySalvageReceipt}from "./history/salvage.js";import{type HistoryRepairBridgeReceipt}from "./history/append-only-repair.js";import{type HistoryRepairReseedReceipt}from "./history/reseed.js";import{type ReplayDocument}from "../core/history/replay.js";import type{GlobalOptions}from "../core/shared/command-types.js";import type{HistoryEntry}from "../types/index.js";import{type MergeDecisionReceipt}from "./merge/receipts.js";import{type ProvenanceNormalizationReceipt}from "./governance/provenance-health.js";export type{HistoryRepairBridgeReceipt,HistoryRepairReseedReceipt,HistorySalvageReceipt,};
|
|
7
7
|
/** Documents the history repair command options payload exchanged by command, SDK, and package integrations. */
|
|
8
8
|
export interface HistoryRepairCommandOptions{
|
|
9
|
-
/** Remove
|
|
9
|
+
/** Remove lines that cannot hold a record (a JSON null, boolean or number) and an invalid trailing suffix after a verified prefix; never re-anchor or reconcile. */
|
|
10
10
|
salvageTail?:boolean;
|
|
11
|
+
/** Bridge chain breaks with one appended record instead of re-anchoring recorded entries, so every earlier line stays byte-identical (GH-1715). */
|
|
12
|
+
appendOnly?:boolean;
|
|
11
13
|
/** Value that configures or reports dry run for this contract. */
|
|
12
14
|
dryRun?:boolean;
|
|
13
15
|
/** Value that configures or reports author for this contract. */
|
|
@@ -40,6 +42,10 @@ receipt:MergeDecisionReceipt;};}
|
|
|
40
42
|
export interface HistoryRepairResult{
|
|
41
43
|
/** Present when invalid trailing bytes were selected for explicit salvage. */
|
|
42
44
|
salvage?:HistorySalvageReceipt;
|
|
45
|
+
/** Present when an append-only repair planned or appended a bridge over chain breaks. */
|
|
46
|
+
bridge?:HistoryRepairBridgeReceipt;
|
|
47
|
+
/** Present when the repair rebuilt a live item's absent or record-less stream from the on-disk item (pm-3os5p6). */
|
|
48
|
+
reseed?:HistoryRepairReseedReceipt;
|
|
43
49
|
/** Stable identifier used to reference this record across commands and storage. */
|
|
44
50
|
id:string;
|
|
45
51
|
/** Value that configures or reports dry run for this contract. */
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="a5461fc0-40f6-5b8b-a535-494c9d840ed1")}catch{}})();import{itemRevisionConflictRowFields}from"./lifecycle/item-revision.js";import{salvageHistoryTail}from"./history/salvage.js";import{resolveHistoryHashAlgorithm}from"../core/history/digest.js";import{realpath}from"node:fs/promises";import path from"node:path";import jsonPatch from"fast-json-patch";import{patchPathToChangedField}from"../core/history/history-diff.js";import{normalizeReplayPatchOps,reanchorHistoryEntries,replayHashVerificationCandidates,resolveHistoryRepairItemHashVersion,toReplayDocument,verifyHistoryChainWithVersion}from"../core/history/replay.js";import{sealHistoryRecord}from"../core/history/history.js";import{classifyHistoryEvent}from"../core/history/event-classification.js";import{scanHistoryDrift}from"../core/history/drift-scan.js";import{invalidateHistoryDriftCache}from"../core/history/drift-cache.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{sha256Hex,stableStringify}from"../core/shared/serialization.js";import{resolveAuthor}from"../core/shared/author.js";import{nowIso}from"../core/shared/time.js";import{listAllItemMetadataWithBody}from"../core/store/item-store.js";import{resolveHistoryWorkspace,resolveHistorySubject}from"./history/subject.js";import{runHistoryMaintenance}from"./history/maintenance.js";import{isOriginalGitStateRestored}from"./merge/receipt-operation.js";import{assertPortableMergeReceiptReferences,inspectMergeReceiptEvidence,summarizeMergeReceipt}from"./merge/receipts.js";import{encodeItemScalarDecisionValue,hashItemScalarDecisionValue}from"./merge/three-way.js";import{listInvalidProvenanceHistoryStreamIds,normalizeInvalidHistoryProvenance}from"./governance/provenance-health.js";function replayFieldValue(document,field){return field==="body"?document.body:document.metadata[field]}function isDiagnosticCollectionRow(field,value){if(value===null||typeof value!="object"||Array.isArray(value))return!1;const row=value;return field==="comments"?typeof row.created_at=="string"&&typeof row.author=="string"&&typeof row.text=="string":typeof row.path=="string"||field==="tests"&&typeof row.command=="string"}function diagnosticLinkedRecord(value){const result={...value};if(result.source_kind==="merge_union"&&(result.source_kind="local_mutation"),result.provenance!==null&&typeof result.provenance=="object"&&!Array.isArray(result.provenance)){const provenance={...result.provenance};provenance.source_kind==="merge_union"&&(provenance.source_kind="local_mutation"),result.provenance=provenance}return result}function diagnosticCollectionValue(field,value){if(!Array.isArray(value)||!["comments","docs","tests"].includes(field)||!value.every(row=>isDiagnosticCollectionRow(field,row)))return value;const rows=value.map(row=>field==="comments"?row:diagnosticLinkedRecord(row));return[...new Map(rows.map(row=>[stableStringify(row),row])).values()]}function isReplayValuePreserved(replayed,reconciled){if(replayed===void 0||Object.is(replayed,reconciled))return!0;if(Array.isArray(replayed)){if(!Array.isArray(reconciled))return!1;const matched=new Set;return replayed.every(expected=>{const index=reconciled.findIndex((candidate,candidateIndex)=>!matched.has(candidateIndex)&&isReplayValuePreserved(expected,candidate));return index<0?!1:(matched.add(index),!0)})}if(replayed===null||reconciled===null||typeof replayed!="object"||typeof reconciled!="object"||Array.isArray(reconciled))return!1;const reconciledRecord=reconciled;return Object.entries(replayed).every(([key,value])=>Object.hasOwn(reconciledRecord,key)&&isReplayValuePreserved(value,reconciledRecord[key]))}function collectReconciliationEvents(entries,fields){const remaining=new Set(fields),events=[];for(let index=entries.length-1;index>=0&&remaining.size>0;index-=1){const entry=entries[index],entryFields=new Set;for(const op of normalizeReplayPatchOps(entry.patch))entryFields.add(patchPathToChangedField(op.path)),op.from&&entryFields.add(patchPathToChangedField(op.from));const overlap=[...remaining].filter(field=>entryFields.has(field));if(overlap.length!==0){for(const field of overlap)remaining.delete(field);events.push({index:index+1,ts:entry.ts,author:entry.author,op:entry.op,fields:overlap.sort((left,right)=>left.localeCompare(right))})}}return events.reverse()}function analyzeReconciliationDiscard(entries,finalReplay,currentItemReplay){const reconcilePatch=jsonPatch.compare(finalReplay,currentItemReplay);if(reconcilePatch.length===0)return;const reconciledFields=new Set;for(const op of reconcilePatch)reconciledFields.add(patchPathToChangedField(op.path));const preservedFields=new Set([...reconciledFields].filter(field=>isReplayValuePreserved(diagnosticCollectionValue(field,replayFieldValue(finalReplay,field)),diagnosticCollectionValue(field,replayFieldValue(currentItemReplay,field))))),revertedFields=new Set([...reconciledFields].filter(field=>!preservedFields.has(field))),discardedEvents=collectReconciliationEvents(entries,revertedFields),preservedEvents=collectReconciliationEvents(entries,preservedFields),sortedReconciledFields=[...reconciledFields].sort((left,right)=>left.localeCompare(right)),sortedRevertedFields=[...revertedFields].sort((left,right)=>left.localeCompare(right)),sortedPreservedFields=[...preservedFields].sort((left,right)=>left.localeCompare(right)),discardedAuthors=[...new Set(discardedEvents.map(event=>event.author))].sort((left,right)=>left.localeCompare(right)),preservedAuthors=[...new Set(preservedEvents.map(event=>event.author))].sort((left,right)=>left.localeCompare(right));return{reconciled_field_count:reconciledFields.size,reconciled_fields:sortedReconciledFields,reverted_field_count:revertedFields.size,reverted_fields:sortedRevertedFields,discarded_events:discardedEvents,discarded_authors:discardedAuthors,preserved_field_count:preservedFields.size,preserved_fields:sortedPreservedFields,preserved_events:preservedEvents,preserved_authors:preservedAuthors,recovery_hint:discardedEvents.length>0?"Reconciliation keeps the on-disk item and overwrites these replayed mutations. To recover one, inspect it with pm history <id> --diff --field <field>, then re-apply the lost value with pm update.":null}}async function canonicalRealPath(value){try{return await realpath(value)}catch{return null}}async function verifyReceiptAgainstSnapshot(params){if(await canonicalRealPath(path.resolve(params.gitWorkspaceRoot,params.receipt.item_path))!==params.currentPath)return null;const declaredFields=[...new Set([...params.receipt.fields_from_theirs,...params.receipt.union_fields,...params.receipt.decisions.map(decision=>decision.field)])].sort(),hashes=params.receipt.merged_field_hashes;if(!hashes||declaredFields.length===0)return null;const hashFields=Object.keys(hashes).sort();if(declaredFields.length!==hashFields.length||declaredFields.some((field,index)=>field!==hashFields[index]))return null;const currentMetadata=params.currentItemReplay.metadata;return declaredFields.every(field=>{const value=field==="body"?params.currentItemReplay.body:currentMetadata[field];return[hashItemScalarDecisionValue(value),sha256Hex(stableStringify(encodeItemScalarDecisionValue(value)))].includes(hashes[field])})?{receipt:params.receipt,declaredFields}:null}async function verifyMergeReceiptProof(params){if(params.proof.gitWorkspaceRoot===null)return{trusted:!1,reason:"git_workspace_unavailable",receipt_ids:[]};if(params.itemPath===null||params.currentItemReplay===null)return{trusted:!1,reason:"item_path_unavailable",receipt_ids:[]};const itemReceipts=params.proof.receipts.filter(receipt=>receipt.item_id===params.id);if(itemReceipts.length===0)return{trusted:!1,reason:"no_item_receipts",receipt_ids:[]};const currentPath=await realpath(params.itemPath),trustedReceipts=[];for(const receipt of itemReceipts){const trusted=await verifyReceiptAgainstSnapshot({receipt,gitWorkspaceRoot:params.proof.gitWorkspaceRoot,currentPath,currentItemReplay:params.currentItemReplay});trusted&&trustedReceipts.push(trusted)}const trustedFields=new Set(trustedReceipts.flatMap(({declaredFields})=>declaredFields)),reconciliationFields=params.reconciliation?.reconciled_fields;return trustedReceipts.length>0&&(reconciliationFields===void 0||reconciliationFields.length>0&&reconciliationFields.every(field=>trustedFields.has(field)))?{trusted:!0,reason:"trusted_merge_driver_hash_evidence",receipt_ids:trustedReceipts.map(({receipt})=>receipt.id)}:{trusted:!1,reason:"no_receipt_set_proves_snapshot",receipt_ids:[]}}async function assertHistoryRepairAbandonmentProof(proof,context,chainOk,reanchor){if(proof===void 0)return;const{receipt,gitWorkspaceRoot}=proof,canonicalPath=context.currentItemPath===null?null:path.relative(gitWorkspaceRoot,context.currentItemPath).split(path.sep).join("/");if(!chainOk||reanchor.entriesRehashed!==0||reanchor.entriesPatchRepaired!==0||context.matchedChainBefore!==!0||context.currentItemRawBeforeLock===null||canonicalPath!==receipt.item_path||receipt.operation===void 0||!await isOriginalGitStateRestored(gitWorkspaceRoot,receipt.item_path,receipt.operation,context.currentItemRawBeforeLock))throw new PmCliError("Restored-origin receipt evidence no longer proves the exact clean item snapshot.",EXIT_CODE.CONFLICT,{code:"merge_reconcile_receipt_evidence_untrusted",recovery:{suggested_retry:"pm merge reconcile --dry-run"}})}async function resolveHistoryRepairMergeEvidence(params){const requestedReceiptIds=new Set(params.options.mergeReceiptProof?.receipts.filter(receipt=>receipt.item_id===params.subjectId).map(receipt=>receipt.id)??[]),authoritativeReceiptEvidence=params.options.mergeReceiptProof?await inspectMergeReceiptEvidence(params.options.mergeReceiptProof.gitWorkspaceRoot??process.cwd(),{includeReconciled:!0,includeLossless:!0,pmRoot:params.pmRoot}):void 0,subjectMergeReceipts=authoritativeReceiptEvidence?.receipts.filter(receipt=>receipt.item_id===params.subjectId&&requestedReceiptIds.has(receipt.id))??[];assertPortableMergeReceiptReferences(requestedReceiptIds,authoritativeReceiptEvidence,params.options.dryRun===!0);const mergeReceiptProof=params.options.mergeReceiptProof?await verifyMergeReceiptProof({proof:{...params.options.mergeReceiptProof,receipts:subjectMergeReceipts},id:params.subjectId,itemPath:params.itemReplayContext.currentItemPath,currentItemReplay:params.itemReplayContext.currentItemReplay,reconciliation:params.reconciliation}):void 0;if(mergeReceiptProof&&!mergeReceiptProof.trusted&¶ms.options.force!==!0)throw new PmCliError(`Merge receipt evidence for ${params.subjectId} does not prove the exact item snapshot (${mergeReceiptProof.reason}).`,EXIT_CODE.CONFLICT,{code:"merge_reconcile_receipt_evidence_untrusted",required:"Use authoritative clone-local or durable receipt evidence whose canonical path, declared fields, and merged-value hashes match the current item, or review the mismatch and rerun with --force.",recovery:{suggested_retry:"pm merge reconcile --dry-run"}});const provenMergeReceipts=mergeReceiptProof?.trusted?subjectMergeReceipts.filter(receipt=>mergeReceiptProof.receipt_ids.includes(receipt.id)):[];return{mergeReceiptProof,effectiveAuditContext:provenMergeReceipts.length>0&¶ms.options.force!==!0?{...params.options.auditContext,merge:{receipts:provenMergeReceipts.map(summarizeMergeReceipt)}}:params.options.auditContext}}function describeHistoryRepairItemReplay(subject,snapshot,itemHashVersion){const currentItemPath=subject.located?.itemPath??null,loadedItem=snapshot.loadedItem,historyEntries=snapshot.entries;if(!loadedItem)return{currentItemReplay:null,currentItemPath,matchedChainBefore:null,currentItemRawBeforeLock:null,loadedItem:null};const currentItemReplay=toReplayDocument(loadedItem.document),lastOriginalAfterHash=historyEntries[historyEntries.length-1].after_hash;return{currentItemReplay,currentItemPath,matchedChainBefore:replayHashVerificationCandidates(currentItemReplay,itemHashVersion,resolveHistoryHashAlgorithm(historyEntries.at(-1)?.hash_algorithm)).includes(lastOriginalAfterHash),currentItemRawBeforeLock:loadedItem.raw,loadedItem}}function buildHistoryRepairMessage(params){return typeof params.message=="string"&¶ms.message.trim().length>0?params.message:`history-repair re-anchored ${params.entriesRehashed} entr${params.entriesRehashed===1?"y":"ies"}${params.entriesPatchRepaired>0?`, repaired ${params.entriesPatchRepaired} patch(es)`:""}${params.reconcileNeeded?", reconciled chain with on-disk item":""}.`}function buildHistoryRepairEntries(params){const rewrittenEntries=[...params.reanchorEntries];if(!params.changed)return{rewrittenEntries,auditEntryAdded:!1};const afterReplay=params.reconcileNeeded&¶ms.currentItemReplay?params.currentItemReplay:params.finalReplay,algorithm=resolveHistoryHashAlgorithm(params.reanchorEntries.at(-1)?.hash_algorithm),beforeHashes=replayHashVerificationCandidates(params.finalReplay,params.itemHashVersion,algorithm),previousAfterHash=params.reanchorEntries[params.reanchorEntries.length-1].after_hash,semanticIndex=beforeHashes.indexOf(previousAfterHash),afterHashes=replayHashVerificationCandidates(afterReplay,params.itemHashVersion,algorithm),auditEntry={hash_algorithm:algorithm,ts:nowIso(),author:params.author,op:params.auditOperation,patch:params.reconcileNeeded&¶ms.currentItemReplay?jsonPatch.compare(params.finalReplay,params.currentItemReplay):[],before_hash:beforeHashes[semanticIndex],after_hash:afterHashes[semanticIndex],message:params.message,...params.explicitItemHashVersion?{item_hash_version:params.itemHashVersion}:{},...params.auditContext===void 0?{}:{context:params.auditContext}};return rewrittenEntries.push(sealHistoryRecord({...auditEntry,event_class:classifyHistoryEvent(auditEntry)})),{rewrittenEntries,auditEntryAdded:!0}}function collectHistoryRepairWarnings(changed,skippedOps,reconciliation){const warnings=[];return changed||warnings.push("history_repair_no_changes"),skippedOps>0&&warnings.push(`history_repair_skipped_unresolvable_ops:${skippedOps}`),reconciliation&&reconciliation.discarded_events.length>0&&warnings.push(`history_repair_reconcile_discards_events:${reconciliation.discarded_events.length}`,`history_repair_discarded_authors:${reconciliation.discarded_authors.join(",")}`),warnings}async function runHistoryRepair(id,options,global2){const{pmRoot,settings,typeRegistry}=await resolveHistoryWorkspace(global2.path),subject=await resolveHistorySubject(pmRoot,id,settings,typeRegistry.type_to_folder);return options.salvageTail===!0?salvageHistoryTail({pmRoot,subject,settings,typeRegistry,options,author:resolveAuthor(options.author,settings.author_default)}):runHistoryMaintenance({pmRoot,subject,settings,typeRegistry,operation:"history-repair",options,transform:snapshot=>buildHistoryRepairPlan({pmRoot,subject,options},snapshot)})}function shouldAppendForcedHistoryAudit(options,verifiedHistoryEntries,auditContext){const alreadyRecorded=(options.mergeAbandonmentProof!==void 0||options.mergeReceiptProof!==void 0&&options.force!==!0)&&auditContext!==void 0&&verifiedHistoryEntries.some(entry=>entry.record_hash_version!==void 0&&entry.op==="merge_reconcile"&&stableStringify(entry.context)===stableStringify(auditContext));return options.forceAuditEntry===!0&&!alreadyRecorded}async function buildHistoryRepairPlan(params,snapshot){const{pmRoot,subject,options}=params,historyEntries=snapshot.entries,chainBefore=snapshot.verification,chainVersionBefore=verifyHistoryChainWithVersion(historyEntries),provenanceNormalization=options.normalizeProvenance?normalizeInvalidHistoryProvenance(historyEntries):{entries:historyEntries,receipt:{changed:!1,events_changed:0,observations_removed:0,invalid_values:[]}},itemHashVersion=resolveHistoryRepairItemHashVersion(provenanceNormalization.entries),explicitVersionsBefore=new Set(provenanceNormalization.entries.map(entry=>entry.item_hash_version).filter(version=>version!==void 0)),reanchor=reanchorHistoryEntries(provenanceNormalization.entries,itemHashVersion),itemReplayContext=describeHistoryRepairItemReplay(subject,snapshot,itemHashVersion);await assertHistoryRepairAbandonmentProof(options.mergeAbandonmentProof,itemReplayContext,chainBefore.ok,reanchor);const finalReplay=reanchor.finalDocument,finalReplayHashes=replayHashVerificationCandidates(finalReplay,itemHashVersion);let reconcileNeeded=!1;if(itemReplayContext.currentItemReplay!==null){const currentItemReplayHashes=replayHashVerificationCandidates(itemReplayContext.currentItemReplay,itemHashVersion);reconcileNeeded=!finalReplayHashes.some((hash,hashIndex)=>hash===currentItemReplayHashes[hashIndex])}const reconciliation=reconcileNeeded&&itemReplayContext.currentItemReplay?analyzeReconciliationDiscard(reanchor.entries,finalReplay,itemReplayContext.currentItemReplay):void 0,{mergeReceiptProof,effectiveAuditContext}=await resolveHistoryRepairMergeEvidence({options,pmRoot,subjectId:subject.id,itemReplayContext,reconciliation}),changed=[reanchor.entriesRehashed>0,reanchor.entriesPatchRepaired>0,reconcileNeeded,shouldAppendForcedHistoryAudit(options,reanchor.entries,effectiveAuditContext),provenanceNormalization.receipt.changed].some(Boolean),author=snapshot.author,dryRun=!!options.dryRun,repairMessage=buildHistoryRepairMessage({message:options.message,entriesRehashed:reanchor.entriesRehashed,entriesPatchRepaired:reanchor.entriesPatchRepaired,reconcileNeeded}),{rewrittenEntries,auditEntryAdded}=buildHistoryRepairEntries({reanchorEntries:reanchor.entries,changed,reconcileNeeded,currentItemReplay:itemReplayContext.currentItemReplay,finalReplay,author,message:repairMessage,auditOperation:options.auditOperation??"history_repair",auditContext:provenanceNormalization.receipt.changed?{...effectiveAuditContext,provenance_normalization:provenanceNormalization.receipt}:effectiveAuditContext,itemHashVersion,explicitItemHashVersion:reanchor.explicitItemHashVersion}),warnings=collectHistoryRepairWarnings(changed,reanchor.skippedOps,reconciliation);return{changed,rewrittenEntries,beforeWrite:async()=>assertHistoryRepairAbandonmentProof(options.mergeAbandonmentProof,itemReplayContext,chainBefore.ok,reanchor),report:({verification:historyVerify,warnings:writeWarnings})=>({id:subject.id,dry_run:dryRun,changed,history:{path:subject.historyPath,entries_scanned:historyEntries.length,chain_drift_before:!chainBefore.ok,entries_rehashed:reanchor.entriesRehashed,entries_patch_repaired:reanchor.entriesPatchRepaired,converted_replace_to_add:reanchor.convertedReplaceToAdd,skipped_ops:reanchor.skippedOps,reconciled_with_item:reconcileNeeded,audit_entry_added:auditEntryAdded,verify_ok:historyVerify.ok,verify_errors:historyVerify.errors,item_hash_version_before:chainVersionBefore.item_hash_version??null,item_hash_version_after:itemHashVersion,version_disposition:explicitVersionsBefore.size>1?"selected_for_ambiguous_stream":"preserved"},item:{exists:itemReplayContext.currentItemPath!==null,path:itemReplayContext.currentItemPath,matched_chain_before:itemReplayContext.matchedChainBefore},provenance_normalization:{requested:options.normalizeProvenance===!0,...provenanceNormalization.receipt},...reconciliation?{reconciliation}:{},...mergeReceiptProof?{merge_receipt_proof:mergeReceiptProof}:{},warnings:[...new Set([...warnings,...writeWarnings])].sort((left,right)=>left.localeCompare(right)),generated_at:nowIso()})}}function assertHistoryRepairTarget(id,all){if(all&&id!==void 0)throw new PmCliError("history-repair: <id> and --all are mutually exclusive; pass an item id to repair one stream or --all to repair every drifted stream.",EXIT_CODE.USAGE);if(!all&&id===void 0)throw new PmCliError("history-repair: provide an item <id> or pass --all to repair every drifted stream.",EXIT_CODE.USAGE)}async function runHistoryRepairAll(options,global2){if(options.salvageTail===!0)throw new PmCliError("Tail salvage requires one explicit item ID; --all is not supported.",EXIT_CODE.USAGE);const{pmRoot,settings,typeRegistry}=await resolveHistoryWorkspace(global2.path),itemReadWarnings=[],items=await listAllItemMetadataWithBody(pmRoot,settings.item_format,typeRegistry.type_to_folder,itemReadWarnings,settings.schema,{forceSourceScan:!0}),drift=await scanHistoryDrift(pmRoot,items),invalidProvenanceIds=options.normalizeProvenance?await listInvalidProvenanceHistoryStreamIds(pmRoot):[],targetedIds=[...new Set([...drift.driftedItems,...invalidProvenanceIds])].sort((left,right)=>left.localeCompare(right)),streams=[],repairWarnings=[],totals={repaired:0,skipped_clean:0,failed:0};for(const driftedId of targetedIds)try{const result=await runHistoryRepair(driftedId,{...options,auditContext:options.auditContextById?.[driftedId],auditContextById:void 0,mergeReceiptProof:options.mergeReceiptProofById?.[driftedId]??options.mergeReceiptProof,mergeReceiptProofById:void 0},global2),outcome=result.changed?"repaired":"skipped_clean";totals[outcome]+=1,repairWarnings.push(...result.warnings.map(warning=>`${driftedId}:${warning}`)),streams.push({id:driftedId,outcome,entries_rehashed:result.history.entries_rehashed,entries_patch_repaired:result.history.entries_patch_repaired,reconciled_with_item:result.history.reconciled_with_item,...result.reconciliation?{reconciliation:result.reconciliation}:{},...result.merge_receipt_proof?{merge_receipt_proof:result.merge_receipt_proof}:{},warnings:result.warnings})}catch(error){totals.failed+=1,streams.push({id:driftedId,outcome:"failed",error:error instanceof Error?error.message:String(error),...await itemRevisionConflictRowFields(error,pmRoot)})}return options.dryRun||await invalidateHistoryDriftCache(pmRoot),{all:!0,dry_run:!!options.dryRun,scanned_streams:items.length,drifted_streams:drift.driftedItems.length,provenance_invalid_streams:invalidProvenanceIds.length,streams,totals,warnings:[...new Set([...itemReadWarnings,...repairWarnings])].sort((left,right)=>left.localeCompare(right)),generated_at:nowIso()}}export{analyzeReconciliationDiscard,assertHistoryRepairTarget,runHistoryRepair,runHistoryRepairAll};
|
|
1
|
+
import{itemRevisionConflictRowFields as Q}from"./lifecycle/item-revision.js";import{salvageHistoryTail as Y}from"./history/salvage.js";import{assertAppendOnlyStreamEncoding as Z,assertRegularStreamEntry as ee,buildAppendOnlyRepairPlan as te}from"./history/append-only-repair.js";import{buildHistoryReseedPlan as k}from"./history/reseed.js";import{reanchorOrRefuse as re}from"./history/reanchor-refusal.js";import{resolveHistoryHashAlgorithm as B}from"../core/history/digest.js";import{realpath as O}from"node:fs/promises";import H from"node:path";import j from"fast-json-patch";import{patchPathToChangedField as C}from"../core/history/history-diff.js";import{normalizeReplayPatchOps as ne,reanchorHistoryEntries as ie,replayHashVerificationCandidates as v,resolveHistoryRepairItemHashVersion as oe,toReplayDocument as se,verifyHistoryChainWithVersion as ae,materializeBridgedSegments as ce}from"../core/history/replay.js";import{sealHistoryRecord as de}from"../core/history/history.js";import{classifyHistoryEvent as le}from"../core/history/event-classification.js";import{scanHistoryDrift as ue}from"../core/history/drift-scan.js";import{invalidateHistoryDriftCache as he}from"../core/history/drift-cache.js";import{EXIT_CODE as _}from"../core/shared/constants.js";import{PmCliError as g}from"../core/shared/errors.js";import{sha256Hex as fe,stableStringify as I}from"../core/shared/serialization.js";import{resolveAuthor as pe}from"../core/shared/author.js";import{nowIso as E}from"../core/shared/time.js";import{listAllItemMetadataWithBody as me}from"../core/store/item-store.js";import{resolveHistoryWorkspace as z,resolveHistorySubject as ye}from"./history/subject.js";import{runHistoryMaintenance as M}from"./history/maintenance.js";import{isOriginalGitStateRestored as _e}from"./merge/receipt-operation.js";import{assertPortableMergeReceiptReferences as ge,inspectMergeReceiptEvidence as Re,summarizeMergeReceipt as ve}from"./merge/receipts.js";import{encodeItemScalarDecisionValue as we,hashItemScalarDecisionValue as Ie}from"./merge/three-way.js";import{listInvalidProvenanceHistoryStreamIds as Pe,normalizeInvalidHistoryProvenance as F}from"./governance/provenance-health.js";function V(e,t){return t==="body"?e.body:e.metadata[t]}function be(e,t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;const i=t;return e==="comments"?typeof i.created_at=="string"&&typeof i.author=="string"&&typeof i.text=="string":typeof i.path=="string"||e==="tests"&&typeof i.command=="string"}function Ae(e){const t={...e};if(t.source_kind==="merge_union"&&(t.source_kind="local_mutation"),t.provenance!==null&&typeof t.provenance=="object"&&!Array.isArray(t.provenance)){const i={...t.provenance};i.source_kind==="merge_union"&&(i.source_kind="local_mutation"),t.provenance=i}return t}function W(e,t){if(!Array.isArray(t)||!["comments","docs","tests"].includes(e)||!t.every(r=>be(e,r)))return t;const i=t.map(r=>e==="comments"?r:Ae(r));return[...new Map(i.map(r=>[I(r),r])).values()]}function x(e,t){if(e===void 0||Object.is(e,t))return!0;if(Array.isArray(e)){if(!Array.isArray(t))return!1;const r=new Set;return e.every(n=>{const a=t.findIndex((o,d)=>!r.has(d)&&x(n,o));return a<0?!1:(r.add(a),!0)})}if(e===null||t===null||typeof e!="object"||typeof t!="object"||Array.isArray(t))return!1;const i=t;return Object.entries(e).every(([r,n])=>Object.hasOwn(i,r)&&x(n,i[r]))}function T(e,t){const i=new Set(t),r=[];for(let n=e.length-1;n>=0&&i.size>0;n-=1){const a=e[n],o=new Set;for(const c of ne(a.patch))o.add(C(c.path)),c.from&&o.add(C(c.from));const d=[...i].filter(c=>o.has(c));if(d.length!==0){for(const c of d)i.delete(c);r.push({index:n+1,ts:a.ts,author:a.author,op:a.op,fields:d.sort((c,f)=>c.localeCompare(f))})}}return r.reverse()}function $(e,t,i){const r=j.compare(t,i);if(r.length===0)return;const n=new Set;for(const s of r)n.add(C(s.path));const a=new Set([...n].filter(s=>x(W(s,V(t,s)),W(s,V(i,s))))),o=new Set([...n].filter(s=>!a.has(s))),d=T(e,o),c=T(e,a),f=[...n].sort((s,u)=>s.localeCompare(u)),y=[...o].sort((s,u)=>s.localeCompare(u)),l=[...a].sort((s,u)=>s.localeCompare(u)),h=[...new Set(d.map(s=>s.author))].sort((s,u)=>s.localeCompare(u)),p=[...new Set(c.map(s=>s.author))].sort((s,u)=>s.localeCompare(u));return{reconciled_field_count:n.size,reconciled_fields:f,reverted_field_count:o.size,reverted_fields:y,discarded_events:d,discarded_authors:h,preserved_field_count:a.size,preserved_fields:l,preserved_events:c,preserved_authors:p,recovery_hint:d.length>0?"Reconciliation keeps the on-disk item and overwrites these replayed mutations. To recover one, inspect it with pm history <id> --diff --field <field>, then re-apply the lost value with pm update.":null}}async function He(e){try{return await O(e)}catch{return null}}async function Ce(e){if(await He(H.resolve(e.gitWorkspaceRoot,e.receipt.item_path))!==e.currentPath)return null;const i=[...new Set([...e.receipt.fields_from_theirs,...e.receipt.union_fields,...e.receipt.decisions.map(d=>d.field)])].sort(),r=e.receipt.merged_field_hashes;if(!r||i.length===0)return null;const n=Object.keys(r).sort();if(i.length!==n.length||i.some((d,c)=>d!==n[c]))return null;const a=e.currentItemReplay.metadata;return i.every(d=>{const c=d==="body"?e.currentItemReplay.body:a[d];return[Ie(c),fe(I(we(c)))].includes(r[d])})?{receipt:e.receipt,declaredFields:i}:null}async function Ee(e){if(e.proof.gitWorkspaceRoot===null)return{trusted:!1,reason:"git_workspace_unavailable",receipt_ids:[]};if(e.itemPath===null||e.currentItemReplay===null)return{trusted:!1,reason:"item_path_unavailable",receipt_ids:[]};const t=e.proof.receipts.filter(o=>o.item_id===e.id);if(t.length===0)return{trusted:!1,reason:"no_item_receipts",receipt_ids:[]};const i=await O(e.itemPath),r=[];for(const o of t){const d=await Ce({receipt:o,gitWorkspaceRoot:e.proof.gitWorkspaceRoot,currentPath:i,currentItemReplay:e.currentItemReplay});d&&r.push(d)}const n=new Set(r.flatMap(({declaredFields:o})=>o)),a=e.reconciliation?.reconciled_fields;return r.length>0&&(a===void 0||a.length>0&&a.every(o=>n.has(o)))?{trusted:!0,reason:"trusted_merge_driver_hash_evidence",receipt_ids:r.map(({receipt:o})=>o.id)}:{trusted:!1,reason:"no_receipt_set_proves_snapshot",receipt_ids:[]}}async function D(e,t,i,r){if(e===void 0)return;const{receipt:n,gitWorkspaceRoot:a}=e,o=t.currentItemPath===null?null:H.relative(a,t.currentItemPath).split(H.sep).join("/");if(!i||r.entriesRehashed!==0||r.entriesPatchRepaired!==0||t.matchedChainBefore!==!0||t.currentItemRawBeforeLock===null||o!==n.item_path||n.operation===void 0||!await _e(a,n.item_path,n.operation,t.currentItemRawBeforeLock))throw new g("Restored-origin receipt evidence no longer proves the exact clean item snapshot.",_.CONFLICT,{code:"merge_reconcile_receipt_evidence_untrusted",recovery:{suggested_retry:"pm merge reconcile --dry-run"}})}async function xe(e){const t=new Set(e.options.mergeReceiptProof?.receipts.filter(o=>o.item_id===e.subjectId).map(o=>o.id)??[]),i=e.options.mergeReceiptProof?await Re(e.options.mergeReceiptProof.gitWorkspaceRoot??process.cwd(),{includeReconciled:!0,includeLossless:!0,pmRoot:e.pmRoot}):void 0,r=i?.receipts.filter(o=>o.item_id===e.subjectId&&t.has(o.id))??[];ge(t,i,e.options.dryRun===!0);const n=e.options.mergeReceiptProof?await Ee({proof:{...e.options.mergeReceiptProof,receipts:r},id:e.subjectId,itemPath:e.itemReplayContext.currentItemPath,currentItemReplay:e.itemReplayContext.currentItemReplay,reconciliation:e.reconciliation}):void 0;if(n&&!n.trusted&&e.options.force!==!0)throw new g(`Merge receipt evidence for ${e.subjectId} does not prove the exact item snapshot (${n.reason}).`,_.CONFLICT,{code:"merge_reconcile_receipt_evidence_untrusted",required:"Use authoritative clone-local or durable receipt evidence whose canonical path, declared fields, and merged-value hashes match the current item, or review the mismatch and rerun with --force.",recovery:{suggested_retry:"pm merge reconcile --dry-run"}});const a=n?.trusted?r.filter(o=>n.receipt_ids.includes(o.id)):[];return{mergeReceiptProof:n,effectiveAuditContext:a.length>0&&e.options.force!==!0?{...e.options.auditContext,merge:{receipts:a.map(ve)}}:e.options.auditContext}}function Se(e,t,i){const r=e.located?.itemPath??null,n=t.loadedItem,a=t.entries;if(!n)return{currentItemReplay:null,currentItemPath:r,matchedChainBefore:null,currentItemRawBeforeLock:null,loadedItem:null};const o=se(n.document),d=a[a.length-1].after_hash;return{currentItemReplay:o,currentItemPath:r,matchedChainBefore:v(o,i,B(a.at(-1)?.hash_algorithm)).includes(d),currentItemRawBeforeLock:n.raw,loadedItem:n}}function ke(e){return typeof e.message=="string"&&e.message.trim().length>0?e.message:`history-repair re-anchored ${e.entriesRehashed} entr${e.entriesRehashed===1?"y":"ies"}${e.entriesPatchRepaired>0?`, repaired ${e.entriesPatchRepaired} patch(es)`:""}${e.reconcileNeeded?", reconciled chain with on-disk item":""}.`}function Be(e){const t=[...e.reanchorEntries];if(!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};const i=e.reconcileNeeded&&e.currentItemReplay?e.currentItemReplay:e.finalReplay,r=B(e.reanchorEntries.at(-1)?.hash_algorithm),n=v(e.finalReplay,e.itemHashVersion,r),a=e.reanchorEntries[e.reanchorEntries.length-1].after_hash,o=n.indexOf(a),d=v(i,e.itemHashVersion,r),c={hash_algorithm:r,ts:E(),author:e.author,op:e.auditOperation,patch:e.reconcileNeeded&&e.currentItemReplay?j.compare(e.finalReplay,e.currentItemReplay):[],before_hash:n[o],after_hash:d[o],message:e.message,...e.explicitItemHashVersion?{item_hash_version:e.itemHashVersion}:{},...e.auditContext===void 0?{}:{context:e.auditContext}};return t.push(de({...c,event_class:le(c)})),{rewrittenEntries:t,auditEntryAdded:!0}}function L(e,t,i){const r=[];return e||r.push("history_repair_no_changes"),t>0&&r.push(`history_repair_skipped_unresolvable_ops:${t}`),i&&i.discarded_events.length>0&&r.push(`history_repair_reconcile_discards_events:${i.discarded_events.length}`,`history_repair_discarded_authors:${i.discarded_authors.join(",")}`),r}async function Oe(e,t,i){const{pmRoot:r,settings:n,typeRegistry:a}=await z(i.path),o=await ye(r,e,n,a.type_to_folder);if(t.salvageTail===!0){if(t.appendOnly===!0)throw new g("Tail salvage cannot be combined with other repair modes.",_.USAGE);return Y({pmRoot:r,subject:o,settings:n,typeRegistry:a,options:t,author:pe(t.author,n.author_default)})}if(t.appendOnly===!0)return ze(t),await Z(o.id,o.historyPath),M({pmRoot:r,subject:o,settings:n,typeRegistry:a,operation:"history-repair",options:t,transform:c=>te(o,t,c,{analyzeDiscard:$,collectWarnings:L}),reseed:(c,f)=>k(o,t,c,f)});const d=je(t)?void 0:async(c,f)=>(await ee(o.id,o.historyPath),k(o,t,c,f));return M({pmRoot:r,subject:o,settings:n,typeRegistry:a,operation:"history-repair",options:t,transform:c=>Ve({pmRoot:r,subject:o,options:t},c),reseed:d})}function je(e){return[e.auditOperation,e.auditContext,e.auditContextById,e.forceAuditEntry,e.mergeReceiptProof,e.mergeReceiptProofById,e.mergeAbandonmentProof].some(t=>t!==void 0&&t!==!1)}function ze(e){if([e.normalizeProvenance,e.auditOperation,e.auditContext,e.auditContextById,e.forceAuditEntry,e.mergeReceiptProof,e.mergeReceiptProofById,e.mergeAbandonmentProof].some(t=>t!==void 0&&t!==!1))throw new g("An append-only repair cannot be combined with other repair modes.",_.USAGE)}function Me(e,t,i){const r=(e.mergeAbandonmentProof!==void 0||e.mergeReceiptProof!==void 0&&e.force!==!0)&&i!==void 0&&t.some(n=>n.record_hash_version!==void 0&&n.op==="merge_reconcile"&&I(n.context)===I(i));return e.forceAuditEntry===!0&&!r}function Fe(e){const t=F(e);return t.receipt.changed?F(ce(e)):t}async function Ve(e,t){const{pmRoot:i,subject:r,options:n}=e,a=t.entries,o=t.verification,d=ae(a),c=n.normalizeProvenance?Fe(a):{entries:a,receipt:{changed:!1,events_changed:0,observations_removed:0,invalid_values:[]}},f=oe(c.entries),y=new Set(c.entries.map(m=>m.item_hash_version).filter(m=>m!==void 0)),l=re(r.id,c.entries,()=>ie(c.entries,f,{callerMarksBridgeCoverage:c.receipt.changed})),h=Se(r,t,f);await D(n.mergeAbandonmentProof,h,o.ok,l);const p=l.finalDocument,s=v(p,f);let u=!1;if(h.currentItemReplay!==null){const m=v(h.currentItemReplay,f);u=!s.some((b,A)=>b===m[A])}const R=u&&h.currentItemReplay?$(l.entries,p,h.currentItemReplay):void 0,{mergeReceiptProof:S,effectiveAuditContext:P}=await xe({options:n,pmRoot:i,subjectId:r.id,itemReplayContext:h,reconciliation:R}),w=[l.entriesRehashed>0,l.entriesPatchRepaired>0,l.entriesResealed>0,u,Me(n,l.entries,P),c.receipt.changed].some(Boolean),N=t.author,G=!!n.dryRun,U=ke({message:n.message,entriesRehashed:l.entriesRehashed,entriesPatchRepaired:l.entriesPatchRepaired,reconcileNeeded:u}),{rewrittenEntries:q,auditEntryAdded:X}=Be({reanchorEntries:l.entries,changed:w,reconcileNeeded:u,currentItemReplay:h.currentItemReplay,finalReplay:p,author:N,message:U,auditOperation:n.auditOperation??"history_repair",auditContext:c.receipt.changed?{...P,provenance_normalization:c.receipt}:P,itemHashVersion:f,explicitItemHashVersion:l.explicitItemHashVersion}),J=L(w,l.skippedOps,R);return{changed:w,rewrittenEntries:q,beforeWrite:async()=>D(n.mergeAbandonmentProof,h,o.ok,l),report:({verification:m,warnings:b})=>({id:r.id,dry_run:G,changed:w,history:{path:r.historyPath,entries_scanned:a.length,chain_drift_before:!o.ok,entries_rehashed:l.entriesRehashed,entries_patch_repaired:l.entriesPatchRepaired,converted_replace_to_add:l.convertedReplaceToAdd,skipped_ops:l.skippedOps,reconciled_with_item:u,audit_entry_added:X,verify_ok:m.ok,verify_errors:m.errors,item_hash_version_before:d.item_hash_version??null,item_hash_version_after:f,version_disposition:y.size>1?"selected_for_ambiguous_stream":"preserved"},item:{exists:h.currentItemPath!==null,path:h.currentItemPath,matched_chain_before:h.matchedChainBefore},provenance_normalization:{requested:n.normalizeProvenance===!0,...c.receipt},...R?{reconciliation:R}:{},...S?{merge_receipt_proof:S}:{},warnings:[...new Set([...J,...b])].sort((A,K)=>A.localeCompare(K)),generated_at:E()})}}function ht(e,t){if(t&&e!==void 0)throw new g("history-repair: <id> and --all are mutually exclusive; pass an item id to repair one stream or --all to repair every drifted stream.",_.USAGE);if(!t&&e===void 0)throw new g("history-repair: provide an item <id> or pass --all to repair every drifted stream.",_.USAGE)}async function ft(e,t){if(e.salvageTail===!0)throw new g("Tail salvage requires one explicit item ID; --all is not supported.",_.USAGE);const{pmRoot:i,settings:r,typeRegistry:n}=await z(t.path),a=[],o=await me(i,r.item_format,n.type_to_folder,a,r.schema,{forceSourceScan:!0}),d=await ue(i,o),c=e.normalizeProvenance?await Pe(i):[],f=[...new Set([...d.driftedItems,...c])].sort((p,s)=>p.localeCompare(s)),y=[],l=[],h={repaired:0,skipped_clean:0,failed:0};for(const p of f)try{const s=await Oe(p,{...e,auditContext:e.auditContextById?.[p],auditContextById:void 0,mergeReceiptProof:e.mergeReceiptProofById?.[p]??e.mergeReceiptProof,mergeReceiptProofById:void 0},t),u=s.changed?"repaired":"skipped_clean";h[u]+=1,l.push(...s.warnings.map(R=>`${p}:${R}`)),y.push({id:p,outcome:u,entries_rehashed:s.history.entries_rehashed,entries_patch_repaired:s.history.entries_patch_repaired,reconciled_with_item:s.history.reconciled_with_item,...s.reconciliation?{reconciliation:s.reconciliation}:{},...s.merge_receipt_proof?{merge_receipt_proof:s.merge_receipt_proof}:{},warnings:s.warnings})}catch(s){h.failed+=1,y.push({id:p,outcome:"failed",error:s instanceof Error?s.message:String(s),...await Q(s,i)})}return e.dryRun||await he(i),{all:!0,dry_run:!!e.dryRun,scanned_streams:o.length,drifted_streams:d.driftedItems.length,provenance_invalid_streams:c.length,streams:y,totals:h,warnings:[...new Set([...a,...l])].sort((p,s)=>p.localeCompare(s)),generated_at:E()}}export{$ as analyzeReconciliationDiscard,ht as assertHistoryRepairTarget,Oe as runHistoryRepair,ft as runHistoryRepairAll};
|
|
2
2
|
//# sourceMappingURL=history-repair.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
import{EXIT_CODE as t}from"../core/shared/constants.js";import{PmCliError as i}from"../core/shared/errors.js";const n=1;function a(r){if(typeof r!="object"||r===null)return!1;const e=r;return typeof e.id=="string"&&typeof e.metric=="string"&&typeof e.value=="number"&&Number.isFinite(e.value)&&["higher","lower","target"].includes(String(e.direction))&&typeof e.observed_at=="string"&&typeof e.revision=="string"&&["caller","git","unversioned"].includes(String(e.revision_source))&&typeof e.author=="string"?e.direction!=="target"||typeof e.threshold=="number"&&Number.isFinite(e.threshold):!1}function m(r){if(r===null)return{format_version:n,observations:[]};let e;try{e=JSON.parse(r)}catch{throw new i("Improvement ledger contains invalid JSON.",t.GENERIC_FAILURE,{code:"invalid_improvement_ledger"})}if(typeof e!="object"||e===null||Array.isArray(e)||e.format_version!==n||!Array.isArray(e.observations))throw new i("Improvement ledger has an unsupported shape or format version.",t.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});const o=e.observations;for(const s of o)if(!a(s))throw new i("Improvement ledger contains an invalid observation.",t.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});return e}export{m as parseImprovementLedgerDocument};
|
|
2
2
|
//# sourceMappingURL=improvement-ledger-validation.js.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
|
|
2
|
-
`,result:
|
|
1
|
+
import{assertInitializedTracker as _}from"./environment/tracker-preflight.js";import{createHash as O}from"node:crypto";import{execFile as T}from"node:child_process";import w from"node:path";import{promisify as k}from"node:util";import{readFileIfExists as M}from"../core/fs/fs-utils.js";import{mutateWorkspaceJsonWithHistory as C}from"../core/history/workspace-history.js";import{EXIT_CODE as d}from"../core/shared/constants.js";import{resolveAuthor as $}from"../core/shared/author.js";import{PmCliError as a}from"../core/shared/errors.js";import{stableStringify as g}from"../core/shared/serialization.js";import{nowIso as x}from"../core/shared/time.js";import{resolvePmRoot as I,resolveWorkspaceRoot as L}from"../core/store/paths.js";import{readSettings as N}from"../core/store/settings.js";import{parseImprovementLedgerDocument as h}from"./improvement-ledger-validation.js";const R=k(T),F=50,b=1e3,z=/^[a-z0-9](?:[a-z0-9._/-]{0,126}[a-z0-9])?$/u;function p(r){const t=r.trim().toLowerCase();if(!z.test(t))throw new a(`Invalid metric name "${r}"; use 1-128 lowercase letters, digits, dots, slashes, underscores, or hyphens.`,d.USAGE,{code:"invalid_improvement_metric"});return t}function y(r){const t=r??"lower";if(!["higher","lower","target"].includes(t))throw new a("Improvement direction must be higher, lower, or target.",d.USAGE,{code:"invalid_improvement_observation"});return t}function v(r,t){const e=r?.trim();if(e){if(e.length>256)throw new a(`${t} must not exceed 256 characters.`,d.USAGE,{code:"invalid_improvement_observation"});return e}}function A(r){const t=r??F;if(!Number.isSafeInteger(t)||t<0||t>b)throw new a(`Improvement observation limit must be an integer from 0 to ${b}.`,d.USAGE,{code:"invalid_improvement_observation_limit"});return t}function E(r,t){const e=Date.parse(r);if(!Number.isFinite(e))throw new a(`${t} must be an ISO timestamp.`,d.USAGE,{code:"invalid_improvement_observation_timestamp"});return new Date(e).toISOString()}async function U(r,t,e){if(!Number.isFinite(e.value))throw new a("Improvement observation value must be finite.",d.USAGE,{code:"invalid_improvement_observation"});const i=p(e.metric),n=y(e.direction);if(e.threshold!==void 0&&!Number.isFinite(e.threshold)||n==="target"&&e.threshold===void 0)throw new a("Target-directed observations require a finite threshold.",d.USAGE,{code:"invalid_improvement_observation"});const u=await G(r,e.revision),s=v(e.source,"source"),c=v(e.itemId,"itemId"),o=v(e.unit,"unit"),m=v(e.idempotencyKey,"idempotencyKey")??(u.revision_source==="unversioned"?void 0:[u.revision,i,s??"manual",c??"workspace"].join(":")),l={metric:i,value:e.value,direction:n,...o===void 0?{}:{unit:o},...e.threshold===void 0?{}:{threshold:e.threshold},observed_at:E(e.observedAt??x(),"observedAt"),...u,author:$(e.author,t.author_default),...c===void 0?{}:{item_id:c},...s===void 0?{}:{source:s},...m===void 0?{}:{idempotency_key:m}};return{id:O("sha256").update(g(l)).digest("hex").slice(0,24),...l}}function D(r,t){const e=t.idempotency_key?r.observations.find(n=>n.idempotency_key===t.idempotency_key):r.observations.find(n=>n.id===t.id);if(e){if(e.metric!==t.metric||e.value!==t.value||e.direction!==t.direction||e.threshold!==t.threshold||e.unit!==t.unit)throw new a(`Improvement observation retry key already records a different value for ${t.metric}.`,d.CONFLICT,{code:"improvement_observation_conflict"});return e}const i=r.observations.find(n=>n.metric===t.metric);if(i&&(i.direction!==t.direction||i.unit!==t.unit||t.direction==="target"&&i.threshold!==t.threshold))throw new a(`Metric ${t.metric} is already declared with direction ${i.direction} and unit ${i.unit??"<none>"}.`,d.CONFLICT,{code:"improvement_metric_contract_conflict"})}async function G(r,t){const e=v(t,"revision");if(e)return{revision:e,revision_source:"caller"};try{return{revision:(await R("git",["rev-parse","--verify","HEAD^{commit}"],{cwd:L(r),encoding:"utf8",timeout:5e3})).stdout.trim(),revision_source:"git"}}catch{}return{revision:"unversioned",revision_source:"unversioned"}}function S(r){const t=r[0],e=r[r.length-1],i=e.value-t.value,n=e.direction==="higher"?i>0:e.direction==="lower"?i<0:Math.abs(e.value-e.threshold)<Math.abs(t.value-t.threshold);return{metric:e.metric,direction:e.direction,baseline:t,latest:e,delta:i,improved:n,sample_count:r.length}}async function re(r,t={}){const e=I(process.cwd(),t.path);await _(e);const i=await N(e),n=await U(e,i,r),u=w.join(e,"improvement-ledger.json"),s=await C({pmRoot:e,filePath:u,op:"improvement_observe",author:n.author,lockTtlSeconds:i.locks.ttl_seconds,lockWaitMs:i.locks.wait_ms,message:r.message??`Record ${n.metric}=${String(r.value)} improvement observation`,mutate:c=>{const o=h(c),m=D(o,n);return m?{raw:c,result:m}:(o.observations.push(n),o.observations.sort((l,f)=>l.observed_at.localeCompare(f.observed_at)||l.metric.localeCompare(f.metric)||l.id.localeCompare(f.id)),{raw:`${g(o)}
|
|
2
|
+
`,result:n})}});return{changed:s.changed,observation:s.result,ledger_path:"improvement-ledger.json"}}async function ie(r={}){const t=I(r.cwd??process.cwd(),r.pmRoot);await _(t);const e=r.metric===void 0?void 0:p(r.metric),i=r.since===void 0?void 0:E(r.since,"since"),n=A(r.limit),s=h(await M(w.join(t,"improvement-ledger.json"))).observations.filter(o=>(e===void 0||o.metric===e)&&(r.itemId===void 0||o.item_id===r.itemId)&&(i===void 0||o.observed_at>=i)),c=new Map;for(const o of s){const m=c.get(o.metric)??[];m.push(o),c.set(o.metric,m)}return{observations:[...s].reverse().slice(0,n),total:s.length,truncated:s.length>n,trends:[...c].map(([,o])=>S(o)).sort((o,m)=>o.metric.localeCompare(m.metric)),source:"audited_workspace_singleton"}}const ne={normalizeMetricName:p,normalizeDirection:y,parseLedger:h,parseObservationLimit:A,trendForMetric:S};export{ne as _testOnlyImprovementLedger,ie as readImprovementLedger,re as recordImprovementObservation};
|
|
3
3
|
//# sourceMappingURL=improvement-ledger.js.map
|