@unbrained/pm-cli 2026.11.22 → 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/.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-B76TFRO2.js → chunk-AEOHUSUI.js} +101 -101
- 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-4QBMZXKX.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-RR5KACJ3.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-2O6MLPEX.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 +66 -66
- 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 +12 -12
- 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 +1 -1
- package/dist/core/history/digest.js +1 -1
- package/dist/core/history/drift-cache.js +3 -3
- package/dist/core/history/drift-scan.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.js +2 -2
- package/dist/core/history/identity.js +1 -1
- package/dist/core/history/index.js +1 -1
- package/dist/core/history/operation-contract.js +1 -1
- package/dist/core/history/projection.js +1 -1
- package/dist/core/history/read.js +1 -1
- package/dist/core/history/replay.js +2 -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.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 +72 -72
- package/dist/sdk/completion/shared.js +1 -1
- package/dist/sdk/completion/zsh.js +75 -75
- 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 +1 -1
- 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.js +4 -4
- 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.js +1 -1
- package/dist/sdk/history/reanchor-refusal.js +1 -1
- package/dist/sdk/history/reseed.js +1 -1
- package/dist/sdk/history/salvage.js +5 -5
- package/dist/sdk/history/subject.js +1 -1
- package/dist/sdk/history-analytics.js +1 -1
- package/dist/sdk/history-compact.js +1 -1
- package/dist/sdk/history-mcp.js +1 -1
- package/dist/sdk/history-provenance.js +1 -1
- package/dist/sdk/history-read.js +1 -1
- package/dist/sdk/history-redact.js +1 -1
- package/dist/sdk/history-repair.js +1 -1
- package/dist/sdk/improvement-ledger-validation.js +1 -1
- package/dist/sdk/improvement-ledger.js +2 -2
- package/dist/sdk/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.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.js +9 -9
- 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 +2 -0
- package/dist/sdk/runtime-input.js +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 +5 -3
- 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.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 +1 -1
- package/dist/sdk/workspace-contracts-cache.js +1 -1
- package/dist/sdk/workspace-contracts.js +1 -1
- package/dist/sdk/workspace-memory.js +2 -2
- package/dist/sdk/workspace-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.js +1 -1
- package/docs/COMMANDS.md +1 -1
- package/docs/EXTENSIONS.md +1 -1
- package/docs/SDK.md +74 -4
- package/marketplace.json +1 -1
- package/package.json +2 -1
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-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-3W47ZZ5T.js +0 -9
- package/dist/cli-bundle/chunks/chunk-4TB5D6HL.js +0 -125
- package/dist/cli-bundle/chunks/chunk-5ZMVLWE3.js +0 -2
- package/dist/cli-bundle/chunks/chunk-6BBDEIKC.js +0 -33
- package/dist/cli-bundle/chunks/chunk-AR4NP5HI.js +0 -3
- package/dist/cli-bundle/chunks/chunk-B4PPFOPY.js +0 -3
- package/dist/cli-bundle/chunks/chunk-CAR2L5NW.js +0 -8
- package/dist/cli-bundle/chunks/chunk-DEZPZOQ7.js +0 -2
- package/dist/cli-bundle/chunks/chunk-EIGUKEV6.js +0 -2
- package/dist/cli-bundle/chunks/chunk-GTPCAJMZ.js +0 -8
- package/dist/cli-bundle/chunks/chunk-GYP24M7W.js +0 -2
- package/dist/cli-bundle/chunks/chunk-HC2OPETM.js +0 -2
- package/dist/cli-bundle/chunks/chunk-HKUV74K3.js +0 -2
- package/dist/cli-bundle/chunks/chunk-HXHYDO2R.js +0 -115
- package/dist/cli-bundle/chunks/chunk-IB7UB5TE.js +0 -2
- package/dist/cli-bundle/chunks/chunk-J2LABXBL.js +0 -2
- package/dist/cli-bundle/chunks/chunk-J52BEBSS.js +0 -2
- package/dist/cli-bundle/chunks/chunk-KQIZ34SF.js +0 -3
- package/dist/cli-bundle/chunks/chunk-LQBWLNZJ.js +0 -3
- package/dist/cli-bundle/chunks/chunk-OJTMGDON.js +0 -31
- package/dist/cli-bundle/chunks/chunk-SPPHDVZE.js +0 -2
- package/dist/cli-bundle/chunks/chunk-TC6XLIYO.js +0 -2
- package/dist/cli-bundle/chunks/chunk-U7EL3AYA.js +0 -3
- package/dist/cli-bundle/chunks/chunk-VQFWW4EF.js +0 -6
- package/dist/cli-bundle/chunks/chunk-X6MIWTTT.js +0 -2
- package/dist/cli-bundle/chunks/chunk-XC5Q2ZV7.js +0 -2
- package/dist/cli-bundle/chunks/chunk-XFHPKXAE.js +0 -71
- package/dist/cli-bundle/chunks/chunk-YHVLVSEZ.js +0 -9
- 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-QY3PUHEI.js +0 -2
- package/dist/cli-bundle/chunks/mutation-actor-FWLYWJ37.js +0 -2
- package/dist/cli-bundle/chunks/mutation-admission-7ZDCK3G2.js +0 -2
- package/dist/cli-bundle/chunks/register-mutation-57AJQWFV.js +0 -21
- package/dist/cli-bundle/chunks/register-operations-RKWST7CU.js +0 -2
- package/dist/cli-bundle/chunks/register-setup-CMI23PC5.js +0 -2
- package/dist/cli-bundle/chunks/settlement-hook-BXN5LEQD.js +0 -7
- package/dist/cli-bundle/chunks/stage-4KDVXC5Z.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-2ZD7275J.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-324AHXJO.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-3XSWH6QC.js +0 -91
- package/dist/cli-bundle/focused-chunks/chunk-4JZITIJB.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-4KTFKSS3.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-5C5TK3ET.js +0 -78
- package/dist/cli-bundle/focused-chunks/chunk-AKJYOZZP.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-BRZV7BFV.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-EGN2HFRU.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-GHQVM6K6.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-HDEKFSOK.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-I5LGPUWH.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-IWOXAUDU.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-ML3JHCC6.js +0 -6
- package/dist/cli-bundle/focused-chunks/chunk-OPGOOP25.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-RE7ZWT7D.js +0 -27
- package/dist/cli-bundle/focused-chunks/chunk-RKQNVYGF.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-RQ252B6V.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-SVOOGGAK.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-URGHTTT3.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-USPYKWQG.js +0 -13
- package/dist/cli-bundle/focused-chunks/chunk-UWS3FC4D.js +0 -102
- package/dist/cli-bundle/focused-chunks/chunk-UXQGFGAT.js +0 -44
- package/dist/cli-bundle/focused-chunks/chunk-WZWXGDYY.js +0 -26
- package/dist/cli-bundle/focused-chunks/chunk-YKSLZPLT.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-ZWJTY4ID.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-GLACUTPL.js +0 -2
- package/dist/cli-bundle/focused-chunks/mutation-actor-TCYDPUGG.js +0 -2
- package/dist/cli-bundle/focused-chunks/mutation-admission-LY73EJWM.js +0 -2
- package/dist/cli-bundle/focused-chunks/settlement-hook-ARYCZQY4.js +0 -7
- package/dist/cli-bundle/focused-chunks/stage-DQ7RQQ52.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
|
|
2
|
-
`}}function
|
|
3
|
-
`);const
|
|
4
|
-
`)}return receipt}async function readReceiptsFromDirectory(directory,evidenceSource){let names;try{names=await readdir(directory)}catch(error){const absent=await receiptDirectoryFailureMeansAbsent(directory,error);return{receipts:[],invalid_evidence_count:absent?0:1,invalid_evidence:absent?[]:[{evidence_source:evidenceSource,reason:"directory_unreadable"}],invalid_evidence_truncated:!1}}const receipts=[];let invalidEvidenceCount=0;const invalidEvidence=[],recordInvalidEvidence=(name,candidate)=>{if(invalidEvidenceCount+=1,invalidEvidence.length>=RECEIPT_INVALID_EVIDENCE_DETAIL_LIMIT)return;const receiptId=name.slice(0,-5);invalidEvidence.push({evidence_source:evidenceSource,reason:candidate.reason,...candidate.validation_path?{validation_path:candidate.validation_path}:{},...candidate.validation_error===void 0?{}:{validation_error:candidate.validation_error},...isSafeReceiptId(receiptId)?{receipt_id:receiptId}:{candidate_name_hash:sha256Hex(name)}})};for(const name of names.sort((left,right)=>left.localeCompare(right))){if(!name.endsWith(".json"))continue;const candidate=await inspectReceiptCandidate(directory,name,evidenceSource);candidate.receipt!==void 0?receipts.push(candidate.receipt):recordInvalidEvidence(name,candidate)}return{receipts,invalid_evidence_count:invalidEvidenceCount,invalid_evidence:invalidEvidence,invalid_evidence_truncated:invalidEvidenceCount>invalidEvidence.length}}async function receiptDirectoryFailureMeansAbsent(directory,error,inspectAncestor=stat){if(!isFileMissingError(error))return!1;let ancestor=directory;for(;;)try{return(await inspectAncestor(ancestor)).isDirectory()}catch(ancestorError){if(!isFileMissingError(ancestorError))return!1;const parent=path.dirname(ancestor);if(parent===ancestor)return!0;ancestor=parent}}async function inspectReceiptCandidate(directory,name,evidenceSource){let raw;try{raw=await readBoundedRegularFile(path.join(directory,name),RECEIPT_FILE_MAX_BYTES)}catch{return{reason:"candidate_unreadable"}}if(raw===null)return{reason:"candidate_not_bounded_regular_file"};let parsed;try{parsed=normalizeLegacyReceipt(JSON.parse(raw))}catch{return{reason:"candidate_invalid_json"}}const validationError=receiptValidationError(parsed,evidenceSource);if(validationError!==null)return{reason:new Set(["receipt_id","item_id","item_path"]).has(validationError)?"identity_invalid":"schema_invalid",validation_error:validationError,...validationError==="collections"?{validation_path:receiptCollectionValidationPath(parsed)}:{}};const receipt=parsed;if(name!==receiptFileName(receipt.id))return{reason:"identity_invalid",validation_error:"filename"};const{preferred:legacyPreference,evidence_source:_serializedEvidenceSource,...receiptWithoutRuntimeKeys}=receipt;return{receipt:{...receiptWithoutRuntimeKeys,requested_preference:receipt.requested_preference??legacyPreference??"ours",requested_preference_applied:receipt.requested_preference_applied??(receipt.conflict_resolution??"preferred_side")==="preferred_side",conflict_resolution:receipt.conflict_resolution??"preferred_side",evidence_source:evidenceSource}}}async function indexedDurableReceiptIds(cwd,trackerRoot,receipts){if(receipts.length===0)return[];const{readIndexedReceiptBlobs}=await import("./indexed-receipt-blobs.js"),linked=await linkedReceiptIndexContext(trackerRoot),blobs=await readIndexedReceiptBlobs(linked?.workspace??cwd,durableReceiptDirectory(trackerRoot),receipts.map(receipt=>receiptFileName(receipt.id)),RECEIPT_FILE_MAX_BYTES,linked?.directory);return receipts.flatMap(receipt=>{try{const indexed=normalizeLegacyReceipt(JSON.parse(blobs.get(receiptFileName(receipt.id))??""));if(receiptValidationError(indexed,"durable")!==null)return[];const stored=indexed,fingerprints=receiptProvenanceFingerprints(receipt);return stored.id===receipt.id&&receiptProvenanceFingerprints(stored).some(fingerprint=>fingerprints.includes(fingerprint))?[receipt.id]:[]}catch{return[]}})}async function linkedReceiptIndexContext(trackerRoot){const workspace=process.env.PM_SOURCE_WORKSPACE_ROOT,source=process.env.PM_SOURCE_PM_PATH,active=process.env.PM_PATH;if(!(process.env.PM_SOURCE_CONTEXT_ACCESS!=="read_only"||!workspace||!source||!active))try{if(await realpath(trackerRoot)!==await realpath(active))return;const relative=path.relative(await realpath(workspace),await realpath(source)),outside=relative===".."||relative.startsWith(`..${path.sep}`)||path.isAbsolute(relative),directory=durableReceiptDirectory(outside?path.join(await realpath(workspace),".agents","pm"):await realpath(source)),[boundDirectory,sourceDirectory]=await Promise.all([realpath(directory),realpath(durableReceiptDirectory(source))]);return boundDirectory!==sourceDirectory?void 0:{workspace,directory}}catch{return}}async function inspectMergeReceiptEvidence(cwd,options={}){const directory=await resolveReceiptDirectory(cwd),local=directory===null?{receipts:[],invalid_evidence_count:0,invalid_evidence:[],invalid_evidence_truncated:!1}:await readReceiptsFromDirectory(directory,"clone_local"),trackerRoot=options.pmRoot??path.join(cwd,".agents","pm"),durable=await readReceiptsFromDirectory(durableReceiptDirectory(trackerRoot),"durable"),receipts=new Map(durable.receipts.map(receipt=>[receipt.id,receipt]));let divergentCopyCount=0;const divergentCopyEvidence=[];for(const receipt of local.receipts){const durableCopy=receipts.get(receipt.id);if(durableCopy!==void 0&&!(durableCopy.value_policy===void 0?receiptProvenanceFingerprints(receipt):[receiptProvenanceFingerprint(receipt)]).includes(receiptProvenanceFingerprint(durableCopy))){receipts.delete(receipt.id),divergentCopyCount+=1,local.invalid_evidence.length+durable.invalid_evidence.length+divergentCopyEvidence.length<RECEIPT_INVALID_EVIDENCE_DETAIL_LIMIT&&divergentCopyEvidence.push({evidence_source:"clone_local_and_durable",reason:"copy_provenance_mismatch",receipt_id:receipt.id});continue}receipts.set(receipt.id,durableCopy===void 0?receipt:mergeReceiptCopyLifecycle(receipt,durableCopy))}await retainAuditedDurableSettlements(receipts,durable.receipts,trackerRoot);const validDurable=durable.receipts.filter(receipt=>receipts.has(receipt.id)),indexedIds=new Set(await indexedDurableReceiptIds(cwd,trackerRoot,validDurable));return{durable_receipt_ids:[...indexedIds],unstaged_durable_receipt_ids:validDurable.filter(receipt=>!indexedIds.has(receipt.id)).map(receipt=>receipt.id),receipts:[...receipts.values()].filter(receipt=>(options.includeReconciled||receipt.state==="pending")&&(options.includeLossless!==!1||receipt.decisions.length>0)).sort((left,right)=>left.created_at.localeCompare(right.created_at)),invalid_evidence_count:local.invalid_evidence_count+durable.invalid_evidence_count+divergentCopyCount,invalid_evidence:[...local.invalid_evidence,...durable.invalid_evidence,...divergentCopyEvidence].slice(0,RECEIPT_INVALID_EVIDENCE_DETAIL_LIMIT),invalid_evidence_truncated:local.invalid_evidence_truncated||durable.invalid_evidence_truncated||local.invalid_evidence_count+durable.invalid_evidence_count+divergentCopyCount>RECEIPT_INVALID_EVIDENCE_DETAIL_LIMIT,clone_local_evidence_resolved:directory!==null}}async function listMergeReceipts(cwd,options={}){return(await inspectMergeReceiptEvidence(cwd,options)).receipts}function assertPortableMergeReceiptReferences(receiptIds,evidence,preview){const portable=new Set([...evidence?.durable_receipt_ids??[],...preview?evidence?.unstaged_durable_receipt_ids??[]:[]]),nonportable=[...receiptIds].filter(id=>!portable.has(id));if(nonportable.length!==0)throw new PmCliError(`Merge reconciliation refused ${nonportable.length} receipt(s) without validated tracked evidence; no audit history was written.`,EXIT_CODE.CONFLICT,{code:"merge_receipt_not_portable",required:"Every receipt cited by tracked history must have matching validated evidence in the Git index before any audit write.",recovery:{suggested_retry:"pm merge report --include-reconciled"},nextSteps:["Stage valid project sidecars after reviewing git diff, or use pm merge reconcile --stage for guarded lossless settlement. Restore missing original counterparts or preserve unrelated stale receipts outside the active store. Never copy private clone-local values into tracked evidence. Then rerun pm merge reconcile --dry-run."]})}function partitionMergeReceipts(receipts){const pendingDecisions=[],lossless=[];for(const receipt of receipts)(Array.isArray(receipt.decisions)&&receipt.decisions.length>0?pendingDecisions:lossless).push(receipt);return{pendingDecisions,lossless}}async function markMergeReceiptReconciled(cwd,receipt,options={}){const directory=await resolveReceiptDirectory(cwd);if(directory===null){if(options.requireExisting===!0)throw new Error(`Receipt ${receipt.id} disappeared before settlement.`);return}const receiptEvidenceSource=receipt.evidence_source??"clone_local";if(!isMergeDecisionReceipt(receipt,receiptEvidenceSource))throw new Error("Merge receipt trusted settlement input failed schema validation.");const reconciledAt=nowIso(),localPath=path.join(directory,receiptFileName(receipt.id)),trackerRoot=await resolveTrackerRootFromItemPath(cwd,receipt.item_path),durablePath=trackerRoot===null?null:path.join(durableReceiptDirectory(trackerRoot),receiptFileName(receipt.id)),writes=(await Promise.all([prepareReceiptSettlement({receiptPath:localPath,receiptId:receipt.id,evidenceSource:"clone_local",reconciledAt,settlement:options.settlement}),...durablePath===null?[]:[prepareReceiptSettlement({receiptPath:durablePath,receiptId:receipt.id,evidenceSource:"durable",reconciledAt,settlement:options.settlement})]])).filter(entry=>entry!==null);if(writes.length===0){if(options.requireExisting===!0)throw new Error(`Receipt ${receipt.id} disappeared before settlement.`);return}if(!(writes.some(write=>write.modern)?[receiptProvenanceFingerprint(receipt)]:receiptProvenanceFingerprints(receipt)).some(fingerprint=>writes.every(write=>write.fingerprints.includes(fingerprint))))throw new Error(`Receipt ${receipt.id} settlement copies disagree on immutable merge provenance.`);for(const write of writes)await writeFileAtomic(write.path,write.content)}async function runMergeReceiptReport(options){const receipts=await listMergeReceipts(options.cwd??process.cwd(),{...options,includeLossless:!0});return{ok:!0,count:receipts.length,receipts,generated_at:nowIso()}}async function runMergeReceiptEvidenceReport(options){const evidence=await inspectMergeReceiptEvidence(options.cwd??process.cwd(),{...options,includeLossless:!0}),complete=evidence.clone_local_evidence_resolved===!0&&evidence.invalid_evidence_count===0;return{ok:complete,complete,count:evidence.receipts.length,invalid_evidence_count:evidence.invalid_evidence_count,invalid_evidence:evidence.invalid_evidence,invalid_evidence_truncated:evidence.invalid_evidence_truncated,clone_local_evidence_resolved:evidence.clone_local_evidence_resolved,receipts:evidence.receipts,generated_at:nowIso()}}const _testOnlyMergeReceipts={prepareReceiptSettlement,receiptDirectoryFailureMeansAbsent};export{_testOnlyMergeReceipts,assertPortableMergeReceiptReferences,inspectMergeReceiptEvidence,isSafeReceiptId2 as isSafeReceiptId,listMergeReceipts,markMergeReceiptReconciled,partitionMergeReceipts,runMergeReceiptEvidenceReport,runMergeReceiptReport,summarizeMergeReceipt,writeMergeReceipt};
|
|
1
|
+
import{execFile as U}from"node:child_process";import{randomUUID as B}from"node:crypto";import{readdir as W,realpath as p,stat as X}from"node:fs/promises";import u from"node:path";import{promisify as z}from"node:util";import{readHistoryEntries as Y}from"../../core/history/read.js";import{verifyHistoryChainWithVersion as G}from"../../core/history/replay.js";import{ensureDir as A,isFileAbsentError as K,isFileMissingError as D,pathExists as Q,writeFileAtomic as P}from"../../core/fs/fs-utils.js";import{sha256Hex as b,stableStringify as g}from"../../core/shared/serialization.js";import{nowIso as R}from"../../core/shared/time.js";import{EXIT_CODE as Z}from"../../core/shared/constants.js";import{PmCliError as ee}from"../../core/shared/errors.js";import{encodeItemScalarDecisionValue as m,hashItemScalarDecisionValue as O,isItemScalarMissingValue as F}from"./three-way.js";import{MERGE_RECEIPT_FILE_MAX_BYTES as x,readBoundedRegularFile as j}from"./receipt-file-boundary.js";import{DURABLE_VALUE_POLICY as te,durableValueEvidence as q,isSafeReceiptId as ie,isMergeDecisionReceipt as T,isPrehashedValue as k,normalizeLegacyReceipt as S,receiptCollectionValidationPath as ne,receiptValidationError as L}from"./receipt-schema.js";import{isSafeReceiptId as qe}from"./receipt-schema.js";const re=z(U),E=100;async function C(e){try{const{stdout:t}=await re("git",["rev-parse","--path-format=absolute","--git-path","pm-merge-receipts"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return t.trim()}catch{return null}}async function $(e,t){let i=u.dirname(u.resolve(e,t));for(let r=0;r<12;r+=1){if(await Q(u.join(i,"settings.json")))return i;const o=u.dirname(i);if(o===i)break;i=o}return null}function h(e){return u.join(e,"merge-receipts")}function v(e){return`${e}.json`}async function M(e){let t;try{t=e.readReceipt?await e.readReceipt(e.receiptPath):await j(e.receiptPath,x)}catch(n){if(K(n))return null;throw n}if(t===null)throw new Error(`Receipt ${e.receiptId} settlement source is not a bounded regular file.`);let i;try{i=S(JSON.parse(t))}catch{throw new Error(`Receipt ${e.receiptId} settlement source is not valid JSON.`)}if(!T(i,e.evidenceSource)||i.id!==e.receiptId||e.settlement!==void 0&&i.operation===void 0||u.basename(e.receiptPath)!==v(i.id))throw new Error(`Receipt ${e.receiptId} settlement source failed schema or identity validation.`);const{evidence_source:r,...o}=i;return{path:e.receiptPath,fingerprints:w(i),modern:i.value_policy!==void 0,content:`${JSON.stringify({...o,state:"reconciled",reconciled_at:e.reconciledAt,...e.settlement?{settlement:e.settlement}:{}},null,2)}
|
|
2
|
+
`}}function y(e,t=!1){return b(g({id:e.id,item_id:e.item_id,item_path:e.item_path,created_at:e.created_at,requested_preference:e.requested_preference??e.preferred??"ours",requested_preference_applied:e.requested_preference_applied??(e.conflict_resolution??"preferred_side")==="preferred_side",conflict_resolution:e.conflict_resolution??"preferred_side",fields_from_theirs:e.fields_from_theirs,union_fields:e.union_fields,merged_field_hashes:e.merged_field_hashes??null,operation:e.operation??null,decisions:t?e.decisions.map(i=>({field:i.field,retained_hash:b(g(m(i.retained))),discarded_hash:b(g(m(i.discarded)))})):N(e).decisions}))}function w(e){const t=[y(e)];return e.value_policy===void 0&&(e.value_availability===void 0||e.value_availability==="clone_local")&&t.push(y(e,!0)),t}function oe(e,t){const{reconciled_at:i,settlement:r,...o}=e;return t.state==="reconciled"?{...o,state:"reconciled",reconciled_at:t.reconciled_at,...t.settlement===void 0?{}:{settlement:t.settlement}}:{...o,state:"pending"}}async function de(e,t,i){const r=new Map;for(const o of t){const n=e.get(o.id);if(o.state!=="reconciled"||n===void 0)continue;let c=r.get(n.item_id);if(c===void 0){try{c=await Y(u.join(i,"history",`${n.item_id}.jsonl`),n.item_id),G(c).ok||(c=[])}catch{c=[]}r.set(n.item_id,c)}const a=n.settlement==="original_git_state_restored",s=g({...N(n),...a?{reason:n.settlement,operation:n.operation}:{}});if(!c.some(_=>{if(_.op!=="merge_reconcile"||_.record_hash_version===void 0)return!1;const d=_.context?.merge;if(typeof d!="object"||d===null||Array.isArray(d))return!1;const l=d[a?"abandoned_receipts":"receipts"];return Array.isArray(l)&&l.some(I=>g(I)===s)})){const{reconciled_at:_,settlement:d,...l}=n;e.set(n.id,{...l,state:"pending"})}}}function N(e){return{receipt_id:e.id,item_id:e.item_id,item_path:e.item_path,conflict_fields:e.decisions.map(t=>t.field),fields_from_theirs:e.fields_from_theirs,union_fields:e.union_fields,requested_preference:e.requested_preference??e.preferred??"ours",requested_preference_applied:e.requested_preference_applied??(e.conflict_resolution??"preferred_side")==="preferred_side",conflict_resolution:e.conflict_resolution,decisions:e.decisions.map(t=>({field:t.field,retained_hash:k(t.retained)??O(F(t.retained)?void 0:t.retained),discarded_hash:k(t.discarded)??O(F(t.discarded)?void 0:t.discarded)}))}}async function xe(e){const t=await C(e.cwd);if(t===null)return null;const i=e.itemPath.trim(),r=/^(['"])(.*)\1$/su.exec(i)?.[2]??i,o=u.basename(r,u.extname(r)),n={version:1,id:B(),item_path:r.replaceAll("\\","/"),item_id:o,requested_preference:e.preferred,requested_preference_applied:(e.conflictResolution??"preferred_side")==="preferred_side",conflict_resolution:e.conflictResolution??"preferred_side",fields_from_theirs:[...e.fieldsFromTheirs],union_fields:[...e.unionFields],...e.mergedFieldHashes?{merged_field_hashes:{...e.mergedFieldHashes}}:{},decisions:structuredClone(e.decisions).map(a=>({...a,base:m(a.base),ours:m(a.ours),theirs:m(a.theirs),retained:m(a.retained),discarded:m(a.discarded)})),...e.operation?{operation:e.operation}:{},state:"pending",created_at:R(),value_availability:"clone_local"};await A(t),await P(u.join(t,v(n.id)),`${JSON.stringify(n,null,2)}
|
|
3
|
+
`);const c=await $(e.cwd,n.item_path);if(c!==null){const a=h(c),s=n.decisions.map(d=>({field:d.field,base:null,ours:null,theirs:null,retained:q(d.field,d.retained),discarded:q(d.field,d.discarded),retained_side:d.retained_side,resolution_basis:d.resolution_basis})),f=s.reduce((d,l)=>d+(Object.hasOwn(l.retained,"pm_value")?1:0)+(Object.hasOwn(l.discarded,"pm_value")?1:0),0),_={...n,decisions:s,value_availability:f===0?"hash_only":f===s.length*2?"bounded_inline":"mixed",value_policy:te};await A(a),await P(u.join(a,v(n.id)),`${JSON.stringify(_,null,2)}
|
|
4
|
+
`)}return n}async function V(e,t){let i;try{i=await W(e)}catch(a){const s=await H(e,a);return{receipts:[],invalid_evidence_count:s?0:1,invalid_evidence:s?[]:[{evidence_source:t,reason:"directory_unreadable"}],invalid_evidence_truncated:!1}}const r=[];let o=0;const n=[],c=(a,s)=>{if(o+=1,n.length>=E)return;const f=a.slice(0,-5);n.push({evidence_source:t,reason:s.reason,...s.validation_path?{validation_path:s.validation_path}:{},...s.validation_error===void 0?{}:{validation_error:s.validation_error},...ie(f)?{receipt_id:f}:{candidate_name_hash:b(a)}})};for(const a of i.sort((s,f)=>s.localeCompare(f))){if(!a.endsWith(".json"))continue;const s=await ce(e,a,t);s.receipt!==void 0?r.push(s.receipt):c(a,s)}return{receipts:r,invalid_evidence_count:o,invalid_evidence:n,invalid_evidence_truncated:o>n.length}}async function H(e,t,i=X){if(!D(t))return!1;let r=e;for(;;)try{return(await i(r)).isDirectory()}catch(o){if(!D(o))return!1;const n=u.dirname(r);if(n===r)return!0;r=n}}async function ce(e,t,i){let r;try{r=await j(u.join(e,t),x)}catch{return{reason:"candidate_unreadable"}}if(r===null)return{reason:"candidate_not_bounded_regular_file"};let o;try{o=S(JSON.parse(r))}catch{return{reason:"candidate_invalid_json"}}const n=L(o,i);if(n!==null)return{reason:new Set(["receipt_id","item_id","item_path"]).has(n)?"identity_invalid":"schema_invalid",validation_error:n,...n==="collections"?{validation_path:ne(o)}:{}};const c=o;if(t!==v(c.id))return{reason:"identity_invalid",validation_error:"filename"};const{preferred:a,evidence_source:s,...f}=c;return{receipt:{...f,requested_preference:c.requested_preference??a??"ours",requested_preference_applied:c.requested_preference_applied??(c.conflict_resolution??"preferred_side")==="preferred_side",conflict_resolution:c.conflict_resolution??"preferred_side",evidence_source:i}}}async function ae(e,t,i){if(i.length===0)return[];const{readIndexedReceiptBlobs:r}=await import("./indexed-receipt-blobs.js"),o=await se(t),n=await r(o?.workspace??e,h(t),i.map(c=>v(c.id)),x,o?.directory);return i.flatMap(c=>{try{const a=S(JSON.parse(n.get(v(c.id))??""));if(L(a,"durable")!==null)return[];const s=a,f=w(c);return s.id===c.id&&w(s).some(_=>f.includes(_))?[c.id]:[]}catch{return[]}})}async function se(e){const t=process.env.PM_SOURCE_WORKSPACE_ROOT,i=process.env.PM_SOURCE_PM_PATH,r=process.env.PM_PATH;if(!(process.env.PM_SOURCE_CONTEXT_ACCESS!=="read_only"||!t||!i||!r))try{if(await p(e)!==await p(r))return;const o=u.relative(await p(t),await p(i)),n=o===".."||o.startsWith(`..${u.sep}`)||u.isAbsolute(o),c=h(n?u.join(await p(t),".agents","pm"):await p(i)),[a,s]=await Promise.all([p(c),p(h(i))]);return a!==s?void 0:{workspace:t,directory:c}}catch{return}}async function J(e,t={}){const i=await C(e),r=i===null?{receipts:[],invalid_evidence_count:0,invalid_evidence:[],invalid_evidence_truncated:!1}:await V(i,"clone_local"),o=t.pmRoot??u.join(e,".agents","pm"),n=await V(h(o),"durable"),c=new Map(n.receipts.map(d=>[d.id,d]));let a=0;const s=[];for(const d of r.receipts){const l=c.get(d.id);if(l!==void 0&&!(l.value_policy===void 0?w(d):[y(d)]).includes(y(l))){c.delete(d.id),a+=1,r.invalid_evidence.length+n.invalid_evidence.length+s.length<E&&s.push({evidence_source:"clone_local_and_durable",reason:"copy_provenance_mismatch",receipt_id:d.id});continue}c.set(d.id,l===void 0?d:oe(d,l))}await de(c,n.receipts,o);const f=n.receipts.filter(d=>c.has(d.id)),_=new Set(await ae(e,o,f));return{durable_receipt_ids:[..._],unstaged_durable_receipt_ids:f.filter(d=>!_.has(d.id)).map(d=>d.id),receipts:[...c.values()].filter(d=>(t.includeReconciled||d.state==="pending")&&(t.includeLossless!==!1||d.decisions.length>0)).sort((d,l)=>d.created_at.localeCompare(l.created_at)),invalid_evidence_count:r.invalid_evidence_count+n.invalid_evidence_count+a,invalid_evidence:[...r.invalid_evidence,...n.invalid_evidence,...s].slice(0,E),invalid_evidence_truncated:r.invalid_evidence_truncated||n.invalid_evidence_truncated||r.invalid_evidence_count+n.invalid_evidence_count+a>E,clone_local_evidence_resolved:i!==null}}async function le(e,t={}){return(await J(e,t)).receipts}function Se(e,t,i){const r=new Set([...t?.durable_receipt_ids??[],...i?t?.unstaged_durable_receipt_ids??[]:[]]),o=[...e].filter(n=>!r.has(n));if(o.length!==0)throw new ee(`Merge reconciliation refused ${o.length} receipt(s) without validated tracked evidence; no audit history was written.`,Z.CONFLICT,{code:"merge_receipt_not_portable",required:"Every receipt cited by tracked history must have matching validated evidence in the Git index before any audit write.",recovery:{suggested_retry:"pm merge report --include-reconciled"},nextSteps:["Stage valid project sidecars after reviewing git diff, or use pm merge reconcile --stage for guarded lossless settlement. Restore missing original counterparts or preserve unrelated stale receipts outside the active store. Never copy private clone-local values into tracked evidence. Then rerun pm merge reconcile --dry-run."]})}function Ce(e){const t=[],i=[];for(const r of e)(Array.isArray(r.decisions)&&r.decisions.length>0?t:i).push(r);return{pendingDecisions:t,lossless:i}}async function Me(e,t,i={}){const r=await C(e);if(r===null){if(i.requireExisting===!0)throw new Error(`Receipt ${t.id} disappeared before settlement.`);return}const o=t.evidence_source??"clone_local";if(!T(t,o))throw new Error("Merge receipt trusted settlement input failed schema validation.");const n=R(),c=u.join(r,v(t.id)),a=await $(e,t.item_path),s=a===null?null:u.join(h(a),v(t.id)),_=(await Promise.all([M({receiptPath:c,receiptId:t.id,evidenceSource:"clone_local",reconciledAt:n,settlement:i.settlement}),...s===null?[]:[M({receiptPath:s,receiptId:t.id,evidenceSource:"durable",reconciledAt:n,settlement:i.settlement})]])).filter(l=>l!==null);if(_.length===0){if(i.requireExisting===!0)throw new Error(`Receipt ${t.id} disappeared before settlement.`);return}if(!(_.some(l=>l.modern)?[y(t)]:w(t)).some(l=>_.every(I=>I.fingerprints.includes(l))))throw new Error(`Receipt ${t.id} settlement copies disagree on immutable merge provenance.`);for(const l of _)await P(l.path,l.content)}async function Ae(e){const t=await le(e.cwd??process.cwd(),{...e,includeLossless:!0});return{ok:!0,count:t.length,receipts:t,generated_at:R()}}async function De(e){const t=await J(e.cwd??process.cwd(),{...e,includeLossless:!0}),i=t.clone_local_evidence_resolved===!0&&t.invalid_evidence_count===0;return{ok:i,complete:i,count:t.receipts.length,invalid_evidence_count:t.invalid_evidence_count,invalid_evidence:t.invalid_evidence,invalid_evidence_truncated:t.invalid_evidence_truncated,clone_local_evidence_resolved:t.clone_local_evidence_resolved,receipts:t.receipts,generated_at:R()}}const Oe={prepareReceiptSettlement:M,receiptDirectoryFailureMeansAbsent:H};export{Oe as _testOnlyMergeReceipts,Se as assertPortableMergeReceiptReferences,J as inspectMergeReceiptEvidence,qe as isSafeReceiptId,le as listMergeReceipts,Me as markMergeReceiptReconciled,Ce as partitionMergeReceipts,De as runMergeReceiptEvidenceReport,Ae as runMergeReceiptReport,N as summarizeMergeReceipt,xe as writeMergeReceipt};
|
|
5
5
|
//# sourceMappingURL=receipts.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]="4d506b3c-f1c1-5642-a258-45d93ba64d81")}catch{}})();import{settleAbandonedMergeReceipts}from"./abandoned-receipts.js";import{readFile}from"node:fs/promises";import path from"node:path";import{EXIT_CODE}from"../../core/shared/constants.js";import{PmCliError}from"../../core/shared/errors.js";import{compareTimestampStrings}from"../../core/shared/time.js";import{resolvePmRoot}from"../../core/store/paths.js";import{mapWithFixedConcurrency}from"../extension/concurrency.js";import{runHealth}from"../governance/health.js";import{DURABLE_MERGE_RECEIPT_INTRODUCED_AT,extractHistoryMergeReceiptReferences,isPreDurableDispositionEligibleReference}from"../governance/merge-receipt-history.js";import{runValidate}from"../governance/validate.js";import{runHistoryRepair,runHistoryRepairAll}from"../history-repair.js";import{findGitWorkspaceRoot}from"./install.js";import{assertPortableMergeReceiptReferences,inspectMergeReceiptEvidence,markMergeReceiptReconciled,summarizeMergeReceipt}from"./receipts.js";const RECEIPT_ONLY_REPAIR_CONCURRENCY=4;function missingReceiptCoordinates(health){const integrity=health.checks.find(check=>check.name==="integrity"),counts=integrity?.details.counts,count=typeof counts=="object"&&counts!==null&&!Array.isArray(counts)&&typeof counts.missing_merge_receipt_history_references=="number"?counts.missing_merge_receipt_history_references:0,details=integrity?.details.missing_merge_receipt_history_reference_details,truncated=integrity?.details.missing_merge_receipt_history_reference_details_truncated===!0,coordinates=Array.isArray(details)?details.flatMap(detail=>{if(typeof detail!="object"||detail===null||Array.isArray(detail))return[];const record=detail;return typeof record.item_id=="string"&&typeof record.history_line=="number"&&Number.isSafeInteger(record.history_line)&&typeof record.receipt_id=="string"?[{item_id:record.item_id,history_line:record.history_line,receipt_id:record.receipt_id}]:[]}):[];return{count,truncated,coordinates}}async function identifyLegacyDispositionCandidates(pmRoot,coordinates){const candidates=[];for(const coordinate of coordinates){let raw;try{raw=await readFile(path.join(pmRoot,"history",`${coordinate.item_id}.jsonl`),"utf8")}catch{continue}const line=raw.split(/\r?\n/)[coordinate.history_line-1];if(line===void 0||line.trim().length===0)continue;let parsed;try{parsed=JSON.parse(line)}catch{continue}const reference=extractHistoryMergeReceiptReferences(parsed,coordinate.item_id).find(entry=>entry.receiptId===coordinate.receipt_id);reference===void 0||!isPreDurableDispositionEligibleReference(reference)||reference.eventTimestamp===void 0||compareTimestampStrings(reference.eventTimestamp,DURABLE_MERGE_RECEIPT_INTRODUCED_AT)>=0||candidates.push({...coordinate,original_event_ts:reference.eventTimestamp})}return candidates}async function recordLegacyReceiptDispositions(params){if(params.options.dryRun===!0||params.options.force!==!0||params.candidates.length===0)return 0;const byItem=new Map;for(const candidate of params.candidates){const itemCandidates=byItem.get(candidate.item_id)??[];itemCandidates.push(candidate),byItem.set(candidate.item_id,itemCandidates)}for(const[itemId,itemCandidates]of byItem)await runHistoryRepair(itemId,{author:params.options.author??params.global.author,message:params.options.message??"accept unrecoverable pre-durable merge receipt references",force:!0,auditOperation:"merge_reconcile",forceAuditEntry:!0,auditContext:{merge:{missing_receipt_dispositions:itemCandidates.map(candidate=>({receipt_id:candidate.receipt_id,original_history_line:candidate.history_line,original_event_ts:candidate.original_event_ts,reason:"legacy_clone_local_only"}))}}},params.global);return params.candidates.length}async function runReceiptOnlyRepair(params){try{return{status:"fulfilled",value:await runHistoryRepair(params.id,{dryRun:params.dryRun,author:params.options.author??params.global.author,message:params.options.message??"record field-aware branch merge provenance",force:params.options.force,auditOperation:"merge_reconcile",auditContext:params.auditContext,forceAuditEntry:!0,mergeReceiptProof:params.mergeReceiptProof},params.global)}}catch(reason){return{status:"rejected",reason}}}function appendReceiptOnlyResults(params){params.results.forEach((settled,index)=>{const id=params.receiptOnlyIds[index];if(settled.status==="fulfilled"){const outcome=settled.value.changed?"repaired":"skipped_clean";params.repair.streams.push({id,outcome,entries_rehashed:settled.value.history.entries_rehashed,entries_patch_repaired:settled.value.history.entries_patch_repaired,reconciled_with_item:settled.value.history.reconciled_with_item,...settled.value.merge_receipt_proof?{merge_receipt_proof:settled.value.merge_receipt_proof}:{},warnings:settled.value.warnings}),params.repair.totals[outcome]+=1;return}params.repair.streams.push({id,outcome:"failed",error:settled.reason instanceof Error?settled.reason.message:String(settled.reason)}),params.repair.totals.failed+=1})}async function settleProvenReceipts(params){if(params.dryRun||params.repair.totals.failed>0)return 0;const trustedReceiptIds=new Set(params.repair.streams.flatMap(stream=>stream.merge_receipt_proof?.trusted?stream.merge_receipt_proof.receipt_ids:[])),receiptsToSettle=params.pendingReceipts.filter(receipt=>trustedReceiptIds.has(receipt.id));return await Promise.all(receiptsToSettle.map(receipt=>markMergeReceiptReconciled(params.receiptWorkspaceRoot,receipt,{requireExisting:!0}))),receiptsToSettle.length}function receiptReviewGuidance(pendingCount,complete){if(!(pendingCount===0||complete))return'If receipt proof is unavailable or competing values were discarded, first review receipts.summaries and repair.streams and re-apply intended values. Only with explicit authority to accept that review, run pm merge reconcile --force --message "<reviewed receipt disposition and rationale>". This appends an audit event; it does not restore missing evidence or discarded values.'}async function runStagedMergeReconcile(options,global2){if(options.force===!0)throw new PmCliError("Automatic staging cannot accept forced reconciliation.",EXIT_CODE.CONFLICT,{code:"merge_settlement_review_required",recovery:{suggested_retry:"pm merge reconcile --dry-run"}});const unstagedOptions={...options,stage:!1},{stageLosslessMergeReconciliation,resolveMergeSettlementGlobal}=await import("./stage.js"),settledGlobal=await resolveMergeSettlementGlobal(global2),preview=await runMergeReconcile({...unstagedOptions,dryRun:!0},settledGlobal);return stageLosslessMergeReconciliation({preview,dryRun:options.dryRun===!0,global:settledGlobal,apply:()=>runMergeReconcile({...unstagedOptions,dryRun:!1},settledGlobal)})}async function runMergeReconcile(options,global2){return options.stage===!0?runStagedMergeReconcile(options,global2):reconcileMergeHistory(options,global2)}async function reconcileMergeHistory(options,global2){const dryRun=options.dryRun===!0,pmRoot=resolvePmRoot(process.cwd(),global2.path),preflightHealth=await runHealth(global2,{checkOnly:!0,full:!0,skipVectors:!0,skipDrift:!0}),missingBefore=missingReceiptCoordinates(preflightHealth),legacyDispositionCandidates=await identifyLegacyDispositionCandidates(pmRoot,missingBefore.coordinates),gitWorkspaceRoot=await findGitWorkspaceRoot(pmRoot),receiptWorkspaceRoot=gitWorkspaceRoot??pmRoot,receiptEvidence=await inspectMergeReceiptEvidence(receiptWorkspaceRoot,{includeLossless:!0,pmRoot});if(receiptEvidence.invalid_evidence_count>0)throw new PmCliError(`Merge reconciliation refused ${receiptEvidence.invalid_evidence_count} invalid receipt evidence file(s).`,EXIT_CODE.CONFLICT,{code:"merge_receipt_evidence_invalid",required:"Every clone-local and durable receipt candidate must pass bounded-file, schema, and identity validation.",recovery:{suggested_retry:"pm health --check-only --full"}});assertPortableMergeReceiptReferences(receiptEvidence.receipts.map(receipt=>receipt.id),receiptEvidence,dryRun);const recordedLegacyDispositionCount=await recordLegacyReceiptDispositions({candidates:legacyDispositionCandidates,options,global:global2}),pendingReceipts=receiptEvidence.receipts,abandonedReceiptIds=await settleAbandonedMergeReceipts({cwd:gitWorkspaceRoot,receipts:pendingReceipts,dryRun,author:options.author,message:options.message,global:global2}),abandonedIds=new Set(abandonedReceiptIds),receiptsByItem=new Map;for(const receipt of pendingReceipts.filter(entry=>!abandonedIds.has(entry.id))){const receipts=receiptsByItem.get(receipt.item_id)??[];receipts.push(receipt),receiptsByItem.set(receipt.item_id,receipts)}const auditContextById=Object.fromEntries([...receiptsByItem].map(([id,receipts])=>[id,{merge:{receipts:receipts.map(summarizeMergeReceipt)}}])),mergeReceiptProofById=Object.fromEntries([...receiptsByItem].map(([id,receipts])=>[id,{gitWorkspaceRoot,receipts}])),repair=await runHistoryRepairAll({dryRun,author:options.author??global2.author,message:options.message??"post-merge reconciliation of field-aware tracker history",force:options.force,auditOperation:"merge_reconcile",auditContextById,...pendingReceipts.length>0?{mergeReceiptProofById}:{}},global2),representedIds=new Set(repair.streams.map(stream=>stream.id)),receiptOnlyIds=[...receiptsByItem.keys()].filter(id=>!representedIds.has(id)),receiptOnlyResults=await mapWithFixedConcurrency(receiptOnlyIds,RECEIPT_ONLY_REPAIR_CONCURRENCY,id=>runReceiptOnlyRepair({id,dryRun,options,global:global2,auditContext:auditContextById[id],mergeReceiptProof:mergeReceiptProofById[id]}));appendReceiptOnlyResults({receiptOnlyIds,results:receiptOnlyResults,repair});const reconciledReceiptCount=await settleProvenReceipts({dryRun,pendingReceipts,repair,receiptWorkspaceRoot}),validation=await runValidate({checkHistoryDrift:!0,checkStorageIntegrity:!0},global2),postflightHealth=recordedLegacyDispositionCount===0?preflightHealth:await runHealth(global2,{checkOnly:!0,full:!0,skipVectors:!0,skipDrift:!0}),missingAfter=missingReceiptCoordinates(postflightHealth),mergeChecksGreen=validation.checks.every(check=>check.status==="ok"),receiptSettlementComplete=dryRun?pendingReceipts.length===0:reconciledReceiptCount+abandonedReceiptIds.length===pendingReceipts.length,ok=[repair.totals.failed===0,mergeChecksGreen,receiptSettlementComplete,missingAfter.count===0,!missingAfter.truncated].every(Boolean),boundedBatchGuidance=missingBefore.truncated||missingAfter.truncated?"Missing receipt coordinates exceed the bounded detail response; each reviewed --force pass can disposition only the reported eligible batch. Repeat dry-run and --force passes until receipts.missing_history_references_after=0 and pm merge reconcile returns ok=true.":void 0,explicitReviewGuidance=receiptReviewGuidance(pendingReceipts.length,ok),guidance=(dryRun?["Review repair.streams, then rerun pm merge reconcile without --dry-run to apply audited repairs.",boundedBatchGuidance,explicitReviewGuidance,"No Git hook is installed automatically; invoke this command from an explicit post-merge hook only when your repository policy opts in."]:ok?["Reconciliation is complete; commit changed history streams with the merge result.","Rerun pm merge reconcile --dry-run after future tracker-data merges as a non-mutating integrity check."]:["Reconciliation remains incomplete; inspect repair failures and non-green validation checks before retrying.",boundedBatchGuidance,explicitReviewGuidance,...legacyDispositionCandidates.length>0&&recordedLegacyDispositionCount===0?["Pre-durable clone-local-only receipt references are eligible for an audited disposition; rerun with --force after reviewing receipts.legacy_disposition_eligible."]:[],"Do not commit repaired history streams as reconciled until pm merge reconcile returns ok=true."]).filter(message=>message!==void 0);return{ok,dry_run:dryRun,repair,receipts:{pending_before:pendingReceipts.length,reconciled:reconciledReceiptCount,abandoned:abandonedReceiptIds.length,summaries:pendingReceipts.map(summarizeMergeReceipt),unstaged_durable_receipt_ids:receiptEvidence.unstaged_durable_receipt_ids,missing_history_references_before:missingBefore.count,legacy_disposition_eligible:legacyDispositionCandidates.length,legacy_disposition_recorded:recordedLegacyDispositionCount,missing_history_references_after:missingAfter.count},validation,guidance,generated_at:validation.generated_at}}export{runMergeReconcile};
|
|
1
|
+
import{settleAbandonedMergeReceipts as B}from"./abandoned-receipts.js";import{readFile as W}from"node:fs/promises";import F from"node:path";import{EXIT_CODE as I}from"../../core/shared/constants.js";import{PmCliError as O}from"../../core/shared/errors.js";import{compareTimestampStrings as q}from"../../core/shared/time.js";import{resolvePmRoot as U}from"../../core/store/paths.js";import{mapWithFixedConcurrency as V}from"../extension/concurrency.js";import{runHealth as M}from"../governance/health.js";import{DURABLE_MERGE_RECEIPT_INTRODUCED_AT as Y,extractHistoryMergeReceiptReferences as $,isPreDurableDispositionEligibleReference as z}from"../governance/merge-receipt-history.js";import{runValidate as J}from"../governance/validate.js";import{runHistoryRepair as A,runHistoryRepairAll as X}from"../history-repair.js";import{findGitWorkspaceRoot as K}from"./install.js";import{assertPortableMergeReceiptReferences as Q,inspectMergeReceiptEvidence as Z,markMergeReceiptReconciled as ee,summarizeMergeReceipt as D}from"./receipts.js";const te=4;function P(e){const t=e.checks.find(c=>c.name==="integrity"),r=t?.details.counts,i=typeof r=="object"&&r!==null&&!Array.isArray(r)&&typeof r.missing_merge_receipt_history_references=="number"?r.missing_merge_receipt_history_references:0,o=t?.details.missing_merge_receipt_history_reference_details,s=t?.details.missing_merge_receipt_history_reference_details_truncated===!0,d=Array.isArray(o)?o.flatMap(c=>{if(typeof c!="object"||c===null||Array.isArray(c))return[];const a=c;return typeof a.item_id=="string"&&typeof a.history_line=="number"&&Number.isSafeInteger(a.history_line)&&typeof a.receipt_id=="string"?[{item_id:a.item_id,history_line:a.history_line,receipt_id:a.receipt_id}]:[]}):[];return{count:i,truncated:s,coordinates:d}}async function re(e,t){const r=[];for(const i of t){let o;try{o=await W(F.join(e,"history",`${i.item_id}.jsonl`),"utf8")}catch{continue}const s=o.split(/\r?\n/)[i.history_line-1];if(s===void 0||s.trim().length===0)continue;let d;try{d=JSON.parse(s)}catch{continue}const c=$(d,i.item_id).find(a=>a.receiptId===i.receipt_id);c===void 0||!z(c)||c.eventTimestamp===void 0||q(c.eventTimestamp,Y)>=0||r.push({...i,original_event_ts:c.eventTimestamp})}return r}async function ie(e){if(e.options.dryRun===!0||e.options.force!==!0||e.candidates.length===0)return 0;const t=new Map;for(const r of e.candidates){const i=t.get(r.item_id)??[];i.push(r),t.set(r.item_id,i)}for(const[r,i]of t)await A(r,{author:e.options.author??e.global.author,message:e.options.message??"accept unrecoverable pre-durable merge receipt references",force:!0,auditOperation:"merge_reconcile",forceAuditEntry:!0,auditContext:{merge:{missing_receipt_dispositions:i.map(o=>({receipt_id:o.receipt_id,original_history_line:o.history_line,original_event_ts:o.original_event_ts,reason:"legacy_clone_local_only"}))}}},e.global);return e.candidates.length}async function ne(e){try{return{status:"fulfilled",value:await A(e.id,{dryRun:e.dryRun,author:e.options.author??e.global.author,message:e.options.message??"record field-aware branch merge provenance",force:e.options.force,auditOperation:"merge_reconcile",auditContext:e.auditContext,forceAuditEntry:!0,mergeReceiptProof:e.mergeReceiptProof},e.global)}}catch(t){return{status:"rejected",reason:t}}}function oe(e){e.results.forEach((t,r)=>{const i=e.receiptOnlyIds[r];if(t.status==="fulfilled"){const o=t.value.changed?"repaired":"skipped_clean";e.repair.streams.push({id:i,outcome:o,entries_rehashed:t.value.history.entries_rehashed,entries_patch_repaired:t.value.history.entries_patch_repaired,reconciled_with_item:t.value.history.reconciled_with_item,...t.value.merge_receipt_proof?{merge_receipt_proof:t.value.merge_receipt_proof}:{},warnings:t.value.warnings}),e.repair.totals[o]+=1;return}e.repair.streams.push({id:i,outcome:"failed",error:t.reason instanceof Error?t.reason.message:String(t.reason)}),e.repair.totals.failed+=1})}async function ce(e){if(e.dryRun||e.repair.totals.failed>0)return 0;const t=new Set(e.repair.streams.flatMap(i=>i.merge_receipt_proof?.trusted?i.merge_receipt_proof.receipt_ids:[])),r=e.pendingReceipts.filter(i=>t.has(i.id));return await Promise.all(r.map(i=>ee(e.receiptWorkspaceRoot,i,{requireExisting:!0}))),r.length}function se(e,t){if(!(e===0||t))return'If receipt proof is unavailable or competing values were discarded, first review receipts.summaries and repair.streams and re-apply intended values. Only with explicit authority to accept that review, run pm merge reconcile --force --message "<reviewed receipt disposition and rationale>". This appends an audit event; it does not restore missing evidence or discarded values.'}async function ae(e,t){if(e.force===!0)throw new O("Automatic staging cannot accept forced reconciliation.",I.CONFLICT,{code:"merge_settlement_review_required",recovery:{suggested_retry:"pm merge reconcile --dry-run"}});const r={...e,stage:!1},{stageLosslessMergeReconciliation:i,resolveMergeSettlementGlobal:o}=await import("./stage.js"),s=await o(t),d=await x({...r,dryRun:!0},s);return i({preview:d,dryRun:e.dryRun===!0,global:s,apply:()=>x({...r,dryRun:!1},s)})}async function x(e,t){return e.stage===!0?ae(e,t):de(e,t)}async function de(e,t){const r=e.dryRun===!0,i=U(process.cwd(),t.path),o=await M(t,{checkOnly:!0,full:!0,skipVectors:!0,skipDrift:!0}),s=P(o),d=await re(i,s.coordinates),c=await K(i),a=c??i,p=await Z(a,{includeLossless:!0,pmRoot:i});if(p.invalid_evidence_count>0)throw new O(`Merge reconciliation refused ${p.invalid_evidence_count} invalid receipt evidence file(s).`,I.CONFLICT,{code:"merge_receipt_evidence_invalid",required:"Every clone-local and durable receipt candidate must pass bounded-file, schema, and identity validation.",recovery:{suggested_retry:"pm health --check-only --full"}});Q(p.receipts.map(n=>n.id),p,r);const _=await ie({candidates:d,options:e,global:t}),u=p.receipts,y=await B({cwd:c,receipts:u,dryRun:r,author:e.author,message:e.message,global:t}),T=new Set(y),m=new Map;for(const n of u.filter(l=>!T.has(l.id))){const l=m.get(n.item_id)??[];l.push(n),m.set(n.item_id,l)}const v=Object.fromEntries([...m].map(([n,l])=>[n,{merge:{receipts:l.map(D)}}])),w=Object.fromEntries([...m].map(([n,l])=>[n,{gitWorkspaceRoot:c,receipts:l}])),f=await X({dryRun:r,author:e.author??t.author,message:e.message??"post-merge reconciliation of field-aware tracker history",force:e.force,auditOperation:"merge_reconcile",auditContextById:v,...u.length>0?{mergeReceiptProofById:w}:{}},t),S=new Set(f.streams.map(n=>n.id)),b=[...m.keys()].filter(n=>!S.has(n)),G=await V(b,te,n=>ne({id:n,dryRun:r,options:e,global:t,auditContext:v[n],mergeReceiptProof:w[n]}));oe({receiptOnlyIds:b,results:G,repair:f});const k=await ce({dryRun:r,pendingReceipts:u,repair:f,receiptWorkspaceRoot:a}),h=await J({checkHistoryDrift:!0,checkStorageIntegrity:!0},t),L=_===0?o:await M(t,{checkOnly:!0,full:!0,skipVectors:!0,skipDrift:!0}),g=P(L),N=h.checks.every(n=>n.status==="ok"),H=r?u.length===0:k+y.length===u.length,R=[f.totals.failed===0,N,H,g.count===0,!g.truncated].every(Boolean),C=s.truncated||g.truncated?"Missing receipt coordinates exceed the bounded detail response; each reviewed --force pass can disposition only the reported eligible batch. Repeat dry-run and --force passes until receipts.missing_history_references_after=0 and pm merge reconcile returns ok=true.":void 0,E=se(u.length,R),j=(r?["Review repair.streams, then rerun pm merge reconcile without --dry-run to apply audited repairs.",C,E,"No Git hook is installed automatically; invoke this command from an explicit post-merge hook only when your repository policy opts in."]:R?["Reconciliation is complete; commit changed history streams with the merge result.","Rerun pm merge reconcile --dry-run after future tracker-data merges as a non-mutating integrity check."]:["Reconciliation remains incomplete; inspect repair failures and non-green validation checks before retrying.",C,E,...d.length>0&&_===0?["Pre-durable clone-local-only receipt references are eligible for an audited disposition; rerun with --force after reviewing receipts.legacy_disposition_eligible."]:[],"Do not commit repaired history streams as reconciled until pm merge reconcile returns ok=true."]).filter(n=>n!==void 0);return{ok:R,dry_run:r,repair:f,receipts:{pending_before:u.length,reconciled:k,abandoned:y.length,summaries:u.map(D),unstaged_durable_receipt_ids:p.unstaged_durable_receipt_ids,missing_history_references_before:s.count,legacy_disposition_eligible:d.length,legacy_disposition_recorded:_,missing_history_references_after:g.count},validation:h,guidance:j,generated_at:h.generated_at}}export{x as runMergeReconcile};
|
|
2
2
|
//# sourceMappingURL=reconcile.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
|
|
1
|
+
import{execFile as s}from"node:child_process";import{chmod as c,lstat as p}from"node:fs/promises";import{promisify as l}from"node:util";import{isFileMissingError as g,writeFileAtomic as d}from"../../core/fs/fs-utils.js";import{EXIT_CODE as f}from"../../core/shared/constants.js";import{PmCliError as h}from"../../core/shared/errors.js";import{readBoundedRegularFile as u}from"./receipt-file-boundary.js";import{gitWorkspaceEnvironment as w}from"./worktree-config.js";const x=l(s),a=`#!/bin/sh
|
|
2
2
|
# pm-cli:lossless-merge-settlement:v1
|
|
3
|
-
`;async function
|
|
3
|
+
`;async function A(e,m){const r=(await x("git",["rev-parse","--path-format=absolute","--git-path","hooks/pre-commit"],{cwd:e,env:w(),timeout:1e4})).stdout.trim();let t,o=!1;try{t=await u(r,65536)??"",o=process.platform==="win32"||((await p(r)).mode&73)!==0}catch(n){if(!g(n))throw n}if(t!==void 0&&!t.startsWith(a))throw new h("The pre-commit hook already exists and is not owned by pm; it was preserved.",f.CONFLICT,{code:"merge_settlement_hook_conflict",recovery:{suggested_retry:"pm merge install --dry-run"},nextSteps:["Integrate pm merge reconcile --stage into your existing hook after reviewing its policy, or keep manual settlement. pm never replaces an existing unowned hook."]});const i=`${a}merge_head=$(git rev-parse --git-path MERGE_HEAD) || exit 1
|
|
4
4
|
[ -f "$merge_head" ] || exit 0
|
|
5
|
-
exec ${
|
|
6
|
-
`;return{path:
|
|
5
|
+
exec ${m} merge reconcile --stage
|
|
6
|
+
`;return{path:r,changed:t!==i||!o,content:i}}async function C(e){e.changed&&(await d(e.path,e.content),await c(e.path,493))}export{A as prepareMergeSettlementHook,C as writeMergeSettlementHook};
|
|
7
7
|
//# sourceMappingURL=settlement-hook.js.map
|
package/dist/sdk/merge/stage.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
import{execFile as g}from"node:child_process";import{realpath as w}from"node:fs/promises";import p from"node:path";import{promisify as y}from"node:util";import{EXIT_CODE as d}from"../../core/shared/constants.js";import{PmCliError as f}from"../../core/shared/errors.js";import{resolvePmRoot as v}from"../../core/store/paths.js";import{findGitWorkspaceRoot as _}from"./install.js";import{gitWorkspaceEnvironment as x}from"./worktree-config.js";import{inspectIgnoredMergeArtifacts as R}from"./ignored-artifacts.js";import{isPathOutsideRoot as $}from"../workspace.js";const b=y(g);function c(t){return new f(`Automatic merge settlement refused: ${t}`,d.CONFLICT,{code:"merge_settlement_review_required",recovery:{suggested_retry:"pm merge reconcile --dry-run"},nextSteps:["Inspect receipts, repair streams and Git changes. Resolve competing values or unrelated drift explicitly, then run pm merge reconcile and stage the reviewed artifacts manually."]})}async function G(t){const e=process.env.GIT_INDEX_FILE;if(e===void 0)return;const s=(await t(["rev-parse","--path-format=absolute","--git-path","index"])).stdout.trim();if(p.resolve(e)!==p.resolve(s))throw c("an alternate Git index requires explicit manual settlement")}async function k(t,e){if(e.length===0)return[];const s=e.map(n=>`:(literal)${n}`),a=new Set((await t(["ls-files","--cached","-z","--",...s])).stdout.split("\0")),i=e.filter(n=>!a.has(n)).map(n=>`:(literal)${n}`);if(i.length>0&&(await t(["diff","--cached","--name-only","--diff-filter=D","-z","--",...i])).stdout.length>0)throw c("a receipt has a staged deletion that requires explicit review");return i}async function I(t){const{git:e,preview:s,paths:a,newReceiptPathspecs:i}=t;let n=!1;try{i.length>0&&(n=!0,await e(["add","--",...i]));const o=await t.apply();if(!o.ok||JSON.stringify(o.receipts.summaries)!==JSON.stringify(s.receipts.summaries)||o.repair.streams.some(m=>!s.repair.streams.some(l=>l.id===m.id)))throw c("reconciliation changed or did not finish; inspect the audit artifacts before staging");return a.length>0&&await e(["add","--",...a.map(m=>`:(literal)${m}`)]),{...o,staged_paths:a,guidance:["Lossless reconciliation artifacts are staged for the merge commit. Review git diff --cached before committing."]}}catch(o){throw n&&await e(["reset","--quiet","--",...i]),o}}function S(t){if(t.repair.totals.failed>0||t.receipts.missing_history_references_after>0||t.receipts.summaries.some(e=>e.conflict_fields.length>0)||t.repair.streams.some(e=>e.merge_receipt_proof?.trusted!==!0)||t.validation.checks.some(e=>e.name!=="history_drift"&&e.status!=="ok"))throw c("only fully authenticated receipt-backed repairs without discarded values can be staged")}async function q(t){try{return{...t,path:await w(v(process.cwd(),t.path))}}catch{throw c("the tracker root cannot be resolved")}}async function z(t){const{preview:e}=t;S(e);const{path:s}=await q(t.global),a=await _(s);if(a===null)throw c("a Git workspace is required");const i=r=>b("git",r,{cwd:a,env:x(),timeout:1e4});if(await G(i),(await i(["ls-files","--unmerged","-z"])).stdout.length>0)throw c("Git still has unresolved paths");const o=[...new Set([...[...new Set([...e.repair.streams.map(r=>r.id),...e.receipts.summaries.map(r=>r.item_id)])].map(r=>p.join(s,"history",`${r}.jsonl`)),...e.receipts.summaries.map(r=>p.join(s,"merge-receipts",`${r.receipt_id}.json`))])].map(r=>p.relative(a,r).replaceAll("\\","/"));if(o.some($))throw c("reconciliation artifacts must belong to this Git workspace");const m=await R(a,o);if(m.length>0)throw new f(`Automatic merge settlement refused: required artifacts are ignored by Git: ${m.map(r=>`${r.path} (${r.source}:${r.line}: ${r.pattern})`).join(", ")}. Remove or narrow the owning ignore rules because merge receipts must travel with the commit.`,d.CONFLICT,{code:"merge_settlement_review_required",reason:"ignored_merge_artifacts",paths:m.map(r=>r.path),nextSteps:["Remove or narrow the named ignore rules, preserve receipt and history files, then retry pm merge reconcile --stage --dry-run before applying pm merge reconcile --stage. Do not force-add ignored proof as a substitute for fixing the shared policy."]});const l=o.map(r=>`:(literal)${r}`),h=e.receipts.summaries.map(r=>p.relative(a,p.join(s,"merge-receipts",`${r.receipt_id}.json`)).replaceAll("\\","/"));if(l.length>0)try{await i(["diff","--quiet","--",...l])}catch{throw c("reconciliation paths have unstaged edits or Git cannot verify their index state")}const u=await k(i,h);return t.dryRun?{...e,staged_paths:[]}:I({...t,git:i,paths:o,newReceiptPathspecs:u})}export{q as resolveMergeSettlementGlobal,z as stageLosslessMergeReconciliation};
|
|
2
2
|
//# sourceMappingURL=stage.js.map
|
|
@@ -1,11 +1,11 @@
|
|
|
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]="daf42303-3202-5824-975c-054e24d275d4")}catch{}})();import{cloneEmptyReplayDocument,historyEntriesToRaw,normalizeReplayPatchOps,reanchorHistoryEntries,toReplayDocument,tryApplyReplayPatch,verifyHistoryChainWithVersion,collectBridgedInteriorIndexes,markHistoryEntryInexact}from"../../core/history/replay.js";import jsonPatch from"fast-json-patch";import{locateBridgedSegments,readHistoryBridge}from"../../core/history/bridge.js";import{resealHistoryRewrite}from"../../core/history/history.js";import{rebaseHistoryScalarPatch}from"./history-scalar-rebase.js";import{canonicalDocument,parseItemDocument,serializeItemDocument}from"../../core/item/item-format.js";import{splitAcceptanceCriteria}from"../../core/item/parse.js";import{normalizeItemFormatVersion,requiredItemFormatVersion}from"../../core/item/item-format-version.js";import{EXIT_CODE}from"../../core/shared/constants.js";import{findFirstMergeConflictMarker}from"../../core/shared/conflict-markers.js";import{PmCliError}from"../../core/shared/errors.js";import{sha256Hex,stableStringify}from"../../core/shared/serialization.js";import{compareTimestampStrings}from"../../core/shared/time.js";import{hasConcreteItemFieldValue}from"../../core/item/deferred-fields.js";const ITEM_SCALAR_MISSING_VALUE=Object.freeze({pm_item_scalar_missing:!0});function isItemScalarMissingValue(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)&&Object.keys(value).length===1&&value.pm_item_scalar_missing===!0}function encodeItemScalarDecisionValue(value){return value===void 0?ITEM_SCALAR_MISSING_VALUE:value}function hashItemScalarDecisionValue(value){return sha256Hex(stableStringify(value===void 0?{pm_item_scalar_presence:"missing"}:{pm_item_scalar_presence:"present",value}))}function parseHistoryJsonl(raw,label){const conflictMarker=findFirstMergeConflictMarker(raw);if(conflictMarker)throw new PmCliError(`History merge input (${label}) contains unresolved conflict markers at line ${conflictMarker.line}. Merge drivers must receive clean per-side versions.`,EXIT_CODE.GENERIC_FAILURE);const entries=[];for(const[index,rawLine]of raw.split(/\r?\n/).entries()){const line=rawLine.trim();if(line)try{const parsed=JSON.parse(line);if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))throw new TypeError("history entry must be an object");entries.push(parsed)}catch{throw new PmCliError(`History merge input (${label}) contains invalid JSON at line ${index+1}.`,EXIT_CODE.GENERIC_FAILURE)}}return entries}function neutralizedBridgeOriginal(entry){if(entry.op!=="history_repair"||Object.hasOwn(entry,"bridge")||!Array.isArray(entry.patch)||entry.patch.length>0)return;const evidence=entry.reanchor_evidence;if(Array.isArray(evidence))return evidence.map(item=>item!==null&&typeof item=="object"?item.record:void 0).reverse().find(original=>original!==null&&typeof original=="object"&&Object.hasOwn(original,"bridge"))}function historyEntryIdentity(entry){const subject=neutralizedBridgeOriginal(entry)??entry;return historyRecordIdentity(subject)}function historyRecordIdentity(entry){return stableStringify({ts:entry.ts,author:entry.author,op:entry.op,patch:entry.patch,message:entry.message??null,...Object.hasOwn(entry,"bridge")?{bridge:entry.bridge}:{}})}function commonHistoryPrefixLength(ours,theirs){const limit=Math.min(ours.length,theirs.length);let shared=0;for(;shared<limit&&historyEntryIdentity(ours[shared])===historyEntryIdentity(theirs[shared]);)shared+=1;return shared}function orderHistoryUnionSuffix(ours,theirs,incoming,oursIdentities){const entries=[...ours,...incoming],positions=new Map(entries.map((entry,index)=>[entry,index])),aliases=new Map(entries.map((entry,index)=>[historyEntryIdentity(entry),index])),successors=entries.map(()=>new Set);for(const branch of[ours,theirs]){const coordinates=branch.map(entry=>positions.get(entry)??aliases.get(historyEntryIdentity(entry)));for(let index=1;index<coordinates.length;index+=1)coordinates[index-1]!==coordinates[index]&&successors[coordinates[index-1]].add(coordinates[index])}const predecessors=entries.map(()=>0);for(const targets of successors)for(const target of targets)predecessors[target]+=1;const ready=entries.map((_,index)=>index).filter(index=>predecessors[index]===0),result=[];for(;ready.length>0;){ready.sort((leftIndex,rightIndex)=>{const left=entries[leftIndex],right=entries[rightIndex],byTs=compareTimestampStrings(left.ts,right.ts),leftIdentity=historyEntryIdentity(left),rightIdentity=historyEntryIdentity(right);return byTs||Number(oursIdentities.has(rightIdentity))-Number(oursIdentities.has(leftIdentity))});const index=ready.shift();result.push(entries[index]);for(const target of successors[index])predecessors[target]-=1,predecessors[target]===0&&ready.push(target)}if(result.length!==entries.length)throw new PmCliError("History union cannot preserve contradictory original branch event orders; leave the file unresolved for manual recovery.",EXIT_CODE.GENERIC_FAILURE);return result}function createHistoryBranchProjection(entries){return{entries,positions:new Map(entries.map((entry,index)=>[historyEntryIdentity(entry),index])),index:-1,document:cloneEmptyReplayDocument()}}function advanceHistoryBranch(state,target){const end=target??state.index;for(;state.index<end;){const applied=tryApplyReplayPatch(state.document,state.entries[state.index+1].patch);if(!applied.ok)throw new PmCliError("History union cannot preserve a patch that does not apply in its original branch.",EXIT_CODE.GENERIC_FAILURE);state.document=applied.document,state.index+=1}return state.document}function advanceOrderedHistoryBranch(state,target){if(target!==void 0&&target>state.index+1)throw new PmCliError("History union cannot attribute multiple original branch events to one semantic identity; preserve the source histories for manual recovery.",EXIT_CODE.GENERIC_FAILURE);return advanceHistoryBranch(state,target)}function historyUnionPatchProjection(ours,theirs,shared){if(shared===0)return;const oursBranch=createHistoryBranchProjection(ours),theirsBranch=createHistoryBranchProjection(theirs),prefix=advanceHistoryBranch(oursBranch,shared-1);advanceHistoryBranch(theirsBranch,shared-1);let position=0;const unionFields=new Set([...ITEM_UNION_COLLECTION_FIELDS,...ITEM_UNION_DELIMITED_FIELDS]);return(entry,current)=>{if(position++<shared)return entry.patch;const identity=historyEntryIdentity(entry),oursState=advanceOrderedHistoryBranch(oursBranch,oursBranch.positions.get(identity)),theirsState=advanceOrderedHistoryBranch(theirsBranch,theirsBranch.positions.get(identity)),scalarPatch=normalizeReplayPatchOps(entry.patch).filter(operation=>{const[root,field]=operation.path.slice(1).split("/");return root!=="metadata"||!unionFields.has(field)}),oursPosition=oursBranch.positions.get(identity),next=rebaseHistoryScalarPatch(current,scalarPatch,{branch:oursPosition===void 0?"theirs":"ours",line:(oursPosition??theirsBranch.positions.get(identity))+1,op:entry.op}),merged=mergeItemMetadataRecords(prefix.metadata,oursState.metadata,theirsState.metadata,"ours","latest_document_update",String(oursState.metadata.updated_at),String(theirsState.metadata.updated_at));for(const field of unionFields)Object.hasOwn(merged.merged,field)?next.metadata[field]=merged.merged[field]:delete next.metadata[field];rebaseReplayDeferrals(next.metadata,prefix.metadata,oursState.metadata,theirsState.metadata);const canonical=toReplayDocument({metadata:next.metadata,body:next.body});return jsonPatch.compare(current,canonical)}}function historyBridgeRepairIdentity(entry){const bridge=readHistoryBridge(entry);return typeof bridge=="object"?stableStringify({bridge,patch:entry.patch,before_hash:entry.before_hash,after_hash:entry.after_hash,item_hash_version:entry.item_hash_version,hash_algorithm:entry.hash_algorithm}):null}function collectUnionInexactIndexes(merged,sides,bridgesDissolve,markerOnlySides=[]){const position=occurrencePositions(merged).positions,marked=new Set;return[...sides,...markerOnlySides].forEach((side,sideIndex)=>{const{occurrence}=occurrencePositions(side),place=index=>mergedPosition(position,side,occurrence,index);side.forEach((entry,index)=>{entry.replay_inexact===!0&&addUnionPosition(marked,place(index))}),bridgesDissolve&&sideIndex<sides.length&&markBranchBridgeCoverage(marked,side,place)}),bridgesDissolve||releaseRetainedBridgeSegments(marked,merged),marked}function occurrencePositions(entries){const positions=new Map,occurrence=entries.map((entry,index)=>{const identity=historyEntryIdentity(entry),seen=positions.get(identity);return seen===void 0?(positions.set(identity,[index]),0):(seen.push(index),seen.length-1)});return{positions,occurrence}}function mergedPosition(merged,side,sideOccurrence,index){return merged.get(historyEntryIdentity(side[index]))?.[sideOccurrence[index]]}function addUnionPosition(marked,index){index!==void 0&&marked.add(index)}function markBranchBridgeCoverage(marked,side,place){for(const segment of locateBridgedSegments(side).segments){for(const index of collectBridgedInteriorIndexes([segment]))addUnionPosition(marked,place(index));const from=place(segment.start),to=place(segment.end);if(!(from===void 0||to===void 0))for(let index=from;index<to;index+=1)marked.add(index)}}function releaseRetainedBridgeSegments(marked,merged){for(const segment of locateBridgedSegments(merged).segments)if(segment.exact)for(let index=segment.start;index<segment.end;index+=1)marked.delete(index)}function markInexactUnionEntries(entries,indexes){let changed=!1;return{entries:entries.map((entry,index)=>entry.replay_inexact===!0||!indexes.has(index)?entry:(changed=!0,markHistoryEntryInexact(entry))),changed}}function mergeEquivalentBridgeResult(ours,theirs,shared,oursRaw,recordedSides){const neutralBridges=mergeEquivalentBridges(ours,theirs,shared);if(neutralBridges===null)return null;const output=[...ours,...neutralBridges],marked=markInexactUnionEntries(output,collectUnionInexactIndexes(output,[ours,theirs],!1,recordedSides)),oursKept=ours.every((entry,index)=>marked.entries[index]===entry),appended=marked.entries.slice(ours.length),separator=oursRaw.endsWith(`
|
|
2
|
-
`)||
|
|
3
|
-
`;return{merged:
|
|
4
|
-
`).join("")}`:
|
|
5
|
-
`);return
|
|
6
|
-
`)}${
|
|
7
|
-
`)}`}:
|
|
1
|
+
import{cloneEmptyReplayDocument as fe,historyEntriesToRaw as R,normalizeReplayPatchOps as le,reanchorHistoryEntries as me,toReplayDocument as he,tryApplyReplayPatch as pe,verifyHistoryChainWithVersion as P,collectBridgedInteriorIndexes as _e,markHistoryEntryInexact as ge}from"../../core/history/replay.js";import ye from"fast-json-patch";import{locateBridgedSegments as q,readHistoryBridge as be}from"../../core/history/bridge.js";import{resealHistoryRewrite as Ie}from"../../core/history/history.js";import{rebaseHistoryScalarPatch as Ee}from"./history-scalar-rebase.js";import{canonicalDocument as Se,parseItemDocument as we,serializeItemDocument as ve}from"../../core/item/item-format.js";import{splitAcceptanceCriteria as N}from"../../core/item/parse.js";import{normalizeItemFormatVersion as Oe,requiredItemFormatVersion as Re}from"../../core/item/item-format-version.js";import{EXIT_CODE as b}from"../../core/shared/constants.js";import{findFirstMergeConflictMarker as j}from"../../core/shared/conflict-markers.js";import{PmCliError as y}from"../../core/shared/errors.js";import{sha256Hex as Ae,stableStringify as _}from"../../core/shared/serialization.js";import{compareTimestampStrings as A}from"../../core/shared/time.js";import{hasConcreteItemFieldValue as xe}from"../../core/item/deferred-fields.js";const Ce=Object.freeze({pm_item_scalar_missing:!0});function Fe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.keys(e).length===1&&e.pm_item_scalar_missing===!0}function S(e){return e===void 0?Ce:e}function pt(e){return Ae(_(e===void 0?{pm_item_scalar_presence:"missing"}:{pm_item_scalar_presence:"present",value:e}))}function M(e,t){const r=j(e);if(r)throw new y(`History merge input (${t}) contains unresolved conflict markers at line ${r.line}. Merge drivers must receive clean per-side versions.`,b.GENERIC_FAILURE);const n=[];for(const[o,c]of e.split(/\r?\n/).entries()){const i=c.trim();if(i)try{const s=JSON.parse(i);if(typeof s!="object"||s===null||Array.isArray(s))throw new TypeError("history entry must be an object");n.push(s)}catch{throw new y(`History merge input (${t}) contains invalid JSON at line ${o+1}.`,b.GENERIC_FAILURE)}}return n}function x(e){if(e.op!=="history_repair"||Object.hasOwn(e,"bridge")||!Array.isArray(e.patch)||e.patch.length>0)return;const t=e.reanchor_evidence;if(Array.isArray(t))return t.map(r=>r!==null&&typeof r=="object"?r.record:void 0).reverse().find(r=>r!==null&&typeof r=="object"&&Object.hasOwn(r,"bridge"))}function g(e){const t=x(e)??e;return Ne(t)}function Ne(e){return _({ts:e.ts,author:e.author,op:e.op,patch:e.patch,message:e.message??null,...Object.hasOwn(e,"bridge")?{bridge:e.bridge}:{}})}function G(e,t){const r=Math.min(e.length,t.length);let n=0;for(;n<r&&g(e[n])===g(t[n]);)n+=1;return n}function je(e,t,r,n){const o=[...e,...r],c=new Map(o.map((d,l)=>[d,l])),i=new Map(o.map((d,l)=>[g(d),l])),s=o.map(()=>new Set);for(const d of[e,t]){const l=d.map(m=>c.get(m)??i.get(g(m)));for(let m=1;m<l.length;m+=1)l[m-1]!==l[m]&&s[l[m-1]].add(l[m])}const u=o.map(()=>0);for(const d of s)for(const l of d)u[l]+=1;const f=o.map((d,l)=>l).filter(d=>u[d]===0),a=[];for(;f.length>0;){f.sort((l,m)=>{const p=o[l],h=o[m],I=A(p.ts,h.ts),w=g(p),E=g(h);return I||Number(n.has(E))-Number(n.has(w))});const d=f.shift();a.push(o[d]);for(const l of s[d])u[l]-=1,u[l]===0&&f.push(l)}if(a.length!==o.length)throw new y("History union cannot preserve contradictory original branch event orders; leave the file unresolved for manual recovery.",b.GENERIC_FAILURE);return a}function z(e){return{entries:e,positions:new Map(e.map((t,r)=>[g(t),r])),index:-1,document:fe()}}function T(e,t){const r=t??e.index;for(;e.index<r;){const n=pe(e.document,e.entries[e.index+1].patch);if(!n.ok)throw new y("History union cannot preserve a patch that does not apply in its original branch.",b.GENERIC_FAILURE);e.document=n.document,e.index+=1}return e.document}function W(e,t){if(t!==void 0&&t>e.index+1)throw new y("History union cannot attribute multiple original branch events to one semantic identity; preserve the source histories for manual recovery.",b.GENERIC_FAILURE);return T(e,t)}function Me(e,t,r){if(r===0)return;const n=z(e),o=z(t),c=T(n,r-1);T(o,r-1);let i=0;const s=new Set([...ne,...re]);return(u,f)=>{if(i++<r)return u.patch;const a=g(u),d=W(n,n.positions.get(a)),l=W(o,o.positions.get(a)),m=le(u.patch).filter(E=>{const[B,ue]=E.path.slice(1).split("/");return B!=="metadata"||!s.has(ue)}),p=n.positions.get(a),h=Ee(f,m,{branch:p===void 0?"theirs":"ours",line:(p??o.positions.get(a))+1,op:u.op}),I=ce(c.metadata,d.metadata,l.metadata,"ours","latest_document_update",String(d.metadata.updated_at),String(l.metadata.updated_at));for(const E of s)Object.hasOwn(I.merged,E)?h.metadata[E]=I.merged[E]:delete h.metadata[E];Qe(h.metadata,c.metadata,d.metadata,l.metadata);const w=he({metadata:h.metadata,body:h.body});return ye.compare(f,w)}}function K(e){const t=be(e);return typeof t=="object"?_({bridge:t,patch:e.patch,before_hash:e.before_hash,after_hash:e.after_hash,item_hash_version:e.item_hash_version,hash_algorithm:e.hash_algorithm}):null}function C(e,t,r,n=[]){const o=X(e).positions,c=new Set;return[...t,...n].forEach((i,s)=>{const{occurrence:u}=X(i),f=a=>Te(o,i,u,a);i.forEach((a,d)=>{a.replay_inexact===!0&&Q(c,f(d))}),r&&s<t.length&&Le(c,i,f)}),r||$e(c,e),c}function X(e){const t=new Map,r=e.map((n,o)=>{const c=g(n),i=t.get(c);return i===void 0?(t.set(c,[o]),0):(i.push(o),i.length-1)});return{positions:t,occurrence:r}}function Te(e,t,r,n){return e.get(g(t[n]))?.[r[n]]}function Q(e,t){t!==void 0&&e.add(t)}function Le(e,t,r){for(const n of q(t).segments){for(const i of _e([n]))Q(e,r(i));const o=r(n.start),c=r(n.end);if(!(o===void 0||c===void 0))for(let i=o;i<c;i+=1)e.add(i)}}function $e(e,t){for(const r of q(t).segments)if(r.exact)for(let n=r.start;n<r.end;n+=1)e.delete(n)}function L(e,t){let r=!1;return{entries:e.map((o,c)=>o.replay_inexact===!0||!t.has(c)?o:(r=!0,ge(o))),changed:r}}function ke(e,t,r,n,o){const c=Ve(e,t,r);if(c===null)return null;const i=[...e,...c],s=L(i,C(i,[e,t],!1,o)),u=e.every((d,l)=>s.entries[l]===d),f=s.entries.slice(e.length),a=n.endsWith(`
|
|
2
|
+
`)||f.length===0?"":`
|
|
3
|
+
`;return{merged:u?`${n}${a}${f.map(d=>`${JSON.stringify(d)}
|
|
4
|
+
`).join("")}`:R(s.entries),strategy:"equivalent_bridges",common_entries:r,entries_from_ours:e.length-r,entries_from_theirs:c.length,entries_total:i.length,reanchored:!1}}function Ve(e,t,r){const n=e.slice(r),o=t.slice(r),c=new Set([...n,...o].map(s=>K(x(s)??s)));if(n.length===0||o.length===0||c.size!==1||c.has(null))return null;const i=Y(n,o,e.at(-1).after_hash);return[e,t,[...e,...i]].every(s=>P(s).ok)?i:null}function $(e){return e===void 0?null:K(x(e)??e)}function Y(e,t,r){const n=new Set(e.map(g));return t.filter(o=>!n.has(g(o))).map(o=>{const c=x(o)??o,{bridge:i,replay_inexact:s,...u}=c;return Ie(c,{...u,patch:[],before_hash:r,after_hash:r,...o.replay_inexact===!0?{replay_inexact:!0}:{}},{retainOriginalPatch:!0,retainPriorRecord:!0})})}function Z(e,t){const r=new Set(e.map(g));return t.some(n=>r.has(g(n)))}function ee(e,t,r){return!Z(e,t)&&r.every(n=>P(n).ok)}function te(e,t,r){let n=0;for(;$(e[t+n])===r;)n+=1;return n}function De(e,t){const r={ours:e,theirs:t,normalization:null},n=G(e,t),o=$(e[n]);if(o===null||$(t[n])!==o)return r;const c=e.slice(n,n+te(e,n,o)),i=t.slice(n,n+te(t,n,o)),s=e.slice(n+c.length),u=t.slice(n+i.length);if(s.length===0&&u.length===0)return r;const f=Y(c,i,c.at(-1).after_hash),a=[...e.slice(0,n),...c,...f],d={ours:[...a,...s],theirs:[...a,...u]},l=[e,t,d.ours,d.theirs];return ee([...c,...i],[...s,...u],l)?{...d,normalization:{shared:n,neutralCopies:f.length}}:r}function Ue(e,t){const r=e.entries_from_theirs+t.neutralCopies;return{...e,strategy:e.strategy==="union_reanchor"?"union_reanchor":"equivalent_bridges",common_entries:t.shared,entries_from_ours:e.entries_total-t.shared-r,entries_from_theirs:r}}function _t(e,t,r){const n=M(e,"base"),o=[M(t,"ours"),M(r,"theirs")],{ours:c,theirs:i,normalization:s}=De(o[0],o[1]),u=Je(n,c,i,s===null||s.neutralCopies===0?t:R(c),s===null?[]:o);return s===null?u:He(Ue(u,s),o[0],t)}function He(e,t,r){const n=e.merged.split(`
|
|
5
|
+
`);return t.every((o,c)=>n[c]===JSON.stringify(o))?{...e,merged:`${r.replace(/(?<!\n)$/u,`
|
|
6
|
+
`)}${n.slice(t.length).join(`
|
|
7
|
+
`)}`}:e}function Je(e,t,r,n,o){const c=[e,t,r].map(h=>h.filter(I=>I.op==="create"));if(c[0].length===0&&c.slice(1).every(h=>h.length>0)||c.some(h=>h.length>1)||new Set(c.flat().map(g)).size>1)throw new y("Duplicate item identity: history contains independent or unproven create events. Preserve both branches and assign distinct item ids before merging.",b.CONFLICT,{code:"item_identity_conflict"});const i=G(t,r),s=h=>R(L(h,C(h,[t,r],!1,o)).entries);if(i===t.length&&i===r.length)return{merged:s(t),strategy:"identical",common_entries:i,entries_from_ours:0,entries_from_theirs:0,entries_total:t.length,reanchored:!1};if(i===r.length)return{merged:s(t),strategy:"fast_forward_ours",common_entries:i,entries_from_ours:t.length-i,entries_from_theirs:0,entries_total:t.length,reanchored:!1};if(i===t.length)return{merged:s(r),strategy:"fast_forward_theirs",common_entries:i,entries_from_ours:0,entries_from_theirs:r.length-i,entries_total:r.length,reanchored:!1};const u=t.slice(i),f=ke(t,r,i,n,o);if(f!==null)return f;const a=new Set(u.map(g)),d=r.slice(i).filter(h=>!a.has(g(h))),l=je(u,r.slice(i),d,a),m=[...t.slice(0,i),...l],p=me(L(m,C(m,[t,r],!0,o)).entries,void 0,{continuousHashSurface:!0,projectPatch:Me(t,r,i),callerMarksBridgeCoverage:!0});if(p.skippedOps>0)throw new y(`History union cannot preserve ${p.skippedOps} patch operation(s) after deterministic suffix ordering; leave the file unresolved for manual recovery.`,b.GENERIC_FAILURE);return{merged:R(p.entries),strategy:"union_reanchor",common_entries:i,entries_from_ours:u.length,entries_from_theirs:d.length,entries_total:p.entries.length,reanchored:!0}}function k(e,t){const r=j(e);if(r)throw new y(`Relationship merge input (${t}) contains unresolved conflict markers at line ${r.line}. Merge drivers must receive clean per-side versions.`,b.GENERIC_FAILURE);const n=[];for(const[o,c]of e.split(/\r?\n/).entries()){const i=c.trim();if(!i)continue;let s;try{s=JSON.parse(i)}catch{throw new y(`Relationship merge input (${t}) contains invalid JSON at line ${o+1}.`,b.GENERIC_FAILURE)}if(typeof s!="object"||s===null||Array.isArray(s)||typeof s.eventId!="string"||typeof s.sequence!="number")throw new y(`Relationship merge input (${t}) line ${o+1} is not a relationship event (eventId + sequence required).`,b.GENERIC_FAILURE);n.push(s)}return n}function F(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
|
|
8
8
|
`)}
|
|
9
|
-
`}function renumberRelationshipEvents(events){return events.map((event,index)=>({...event,sequence:index+1}))}function mergeRelationshipEventStreams(baseRaw,oursRaw,theirsRaw){parseRelationshipJsonl(baseRaw,"base");const ours=parseRelationshipJsonl(oursRaw,"ours"),theirs=parseRelationshipJsonl(theirsRaw,"theirs"),limit=Math.min(ours.length,theirs.length);let shared=0;for(;shared<limit&&ours[shared].eventId===theirs[shared].eventId;)shared+=1;if(shared===ours.length&&shared===theirs.length)return{merged:relationshipEventsToRaw(ours),strategy:"identical",common_entries:shared,entries_from_ours:0,entries_from_theirs:0,entries_total:ours.length,reanchored:!1};if(shared===theirs.length)return{merged:relationshipEventsToRaw(ours),strategy:"fast_forward_ours",common_entries:shared,entries_from_ours:ours.length-shared,entries_from_theirs:0,entries_total:ours.length,reanchored:!1};if(shared===ours.length)return{merged:relationshipEventsToRaw(theirs),strategy:"fast_forward_theirs",common_entries:shared,entries_from_ours:0,entries_from_theirs:theirs.length-shared,entries_total:theirs.length,reanchored:!1};const oursSuffix=ours.slice(shared),oursEventIds=new Set(oursSuffix.map(event=>event.eventId)),theirsSuffix=theirs.slice(shared).filter(event=>!oursEventIds.has(event.eventId)),mergedSuffix=[...oursSuffix,...theirsSuffix].sort((left,right)=>{if(left.timestamp!==void 0&&right.timestamp!==void 0){const byTs=compareTimestampStrings(left.timestamp,right.timestamp);if(byTs!==0)return byTs}else{if(left.timestamp===void 0&&right.timestamp!==void 0)return 1;if(left.timestamp!==void 0)return-1}const leftFromOurs=oursEventIds.has(left.eventId),rightFromOurs=oursEventIds.has(right.eventId);return leftFromOurs!==rightFromOurs?Number(rightFromOurs)-Number(leftFromOurs):0}),merged=renumberRelationshipEvents([...ours.slice(0,shared),...mergedSuffix]);return{merged:relationshipEventsToRaw(merged),strategy:"union_reanchor",common_entries:shared,entries_from_ours:oursSuffix.length,entries_from_theirs:theirsSuffix.length,entries_total:merged.length,reanchored:!0}}const ITEM_UNION_COLLECTION_FIELDS=["tags","dependencies","comments","notes","learnings","files","tests","test_runs","docs","reminders","events","deferred_fields"],ITEM_UNION_DELIMITED_FIELDS=["acceptance_criteria"],ITEM_LATEST_TIMESTAMP_FIELDS=["updated_at"];function jsonEquals(left,right){return left===void 0||right===void 0?left===void 0&&right===void 0:stableStringify(left)===stableStringify(right)}function unionCollection(base,ours,theirs){const toEntries=value=>Array.isArray(value)?value:[],baseIds=new Set(toEntries(base).map(entry=>stableStringify(entry))),oursEntries=toEntries(ours),oursIds=new Set(oursEntries.map(entry=>stableStringify(entry))),theirsEntries=toEntries(theirs),theirsIds=new Set(theirsEntries.map(entry=>stableStringify(entry))),merged=oursEntries.filter(entry=>{const identity=stableStringify(entry);return!baseIds.has(identity)||theirsIds.has(identity)});for(const entry of theirsEntries){const identity=stableStringify(entry);!oursIds.has(identity)&&!baseIds.has(identity)&&merged.push(entry)}return merged}function linkedTestDefinitionIdentity(value){if(typeof value!="object"||value===null||Array.isArray(value))return stableStringify(value);const{provenance:_provenance,...definition}=value;return stableStringify(definition)}function markMergedLinkedTest(value){if(typeof value!="object"||value===null||Array.isArray(value))return value;const test=value;return test.provenance?{...test,provenance:{...test.provenance,source_kind:"merge_union"}}:{...test,provenance:{source_kind:"merge_union"}}}function unionLinkedTests(base,ours,theirs){const toEntries=value=>Array.isArray(value)?value:[],baseIds=new Set(toEntries(base).map(linkedTestDefinitionIdentity)),oursEntries=toEntries(ours),oursIds=new Set(oursEntries.map(linkedTestDefinitionIdentity)),theirsEntries=toEntries(theirs),theirsIds=new Set(theirsEntries.map(linkedTestDefinitionIdentity)),merged=oursEntries.filter(entry=>{const identity=linkedTestDefinitionIdentity(entry);return!baseIds.has(identity)||theirsIds.has(identity)});for(const entry of theirsEntries){const identity=linkedTestDefinitionIdentity(entry);!oursIds.has(identity)&&!baseIds.has(identity)&&merged.push(markMergedLinkedTest(entry))}return merged}function latestTimestamp(ours,theirs){return compareTimestampStrings(String(ours),String(theirs))>=0?ours:theirs}function mergeScalarThreeWay(base,ours,theirs,preferred){return jsonEquals(ours,theirs)?{value:ours,from_theirs:!1,conflict:!1}:jsonEquals(base,ours)?{value:theirs,from_theirs:!0,conflict:!1}:jsonEquals(base,theirs)?{value:ours,from_theirs:!1,conflict:!1}:{value:preferred==="theirs"?theirs:ours,from_theirs:preferred==="theirs",conflict:!0}}function mergeItemScalarThreeWay(base,ours,theirs,preferred,conflictResolution,oursUpdatedAt,theirsUpdatedAt){const outcome=mergeScalarThreeWay(base,ours,theirs,preferred);if(!outcome.conflict)return{...outcome,conflict:!1};if(conflictResolution==="preferred_side")return{...outcome,resolution_basis:"requested_preference",retained_side:outcome.from_theirs?"theirs":"ours"};const timestampOrder=compareTimestampStrings(oursUpdatedAt,theirsUpdatedAt);if(conflictResolution==="latest_document_update"&×tampOrder!==0){const retainTheirs2=timestampOrder<0;return{value:retainTheirs2?theirs:ours,from_theirs:retainTheirs2,conflict:!0,resolution_basis:"document_updated_at",retained_side:retainTheirs2?"theirs":"ours"}}const retainTheirs=stableStringify(encodeItemScalarDecisionValue(theirs)).localeCompare(stableStringify(encodeItemScalarDecisionValue(ours)))<0;return{value:retainTheirs?theirs:ours,from_theirs:retainTheirs,conflict:!0,resolution_basis:"stable_value_tiebreak",retained_side:retainTheirs?"theirs":"ours"}}function toMetadataRecord(document){return{...document.metadata}}function parseItemMergeSide(raw,label,options){try{const document=canonicalDocument(parseItemDocument(raw,{...options,requireSupportedFormat:!0}),options),reservedField=Object.entries(document.metadata).find(([,value])=>isItemScalarMissingValue(value))?.[0];if(reservedField!==void 0)throw new TypeError(`metadata field ${reservedField} uses the reserved missing-scalar evidence marker`);return document}catch(error){throw error instanceof PmCliError&&error.context?.code==="item_format_version_unsupported"?error:new PmCliError(`Item merge input (${label}) is not a readable item document: ${String(error)}`,EXIT_CODE.GENERIC_FAILURE)}}function mergeUnionFieldValue(field,base,ours,theirs){return field==="tests"?unionLinkedTests(base,ours,theirs):field==="deferred_fields"?unionDeferredFields(base,ours,theirs):field==="acceptance_criteria"?unionCollection(splitAcceptanceCriteria(base),splitAcceptanceCriteria(ours),splitAcceptanceCriteria(theirs)).join("; "):unionCollection(base,ours,theirs)}function unionDeferredFields(base,ours,theirs){const byField=value=>new Map((Array.isArray(value)?value:[]).map(entry=>[String(entry.field),entry])),[baseEntries,oursEntries,theirsEntries]=[byField(base),byField(ours),byField(theirs)],merged=[];for(const field of[...new Set([...oursEntries.keys(),...theirsEntries.keys()])].sort()){const[baseEntry,oursEntry,theirsEntry]=[baseEntries.get(field),oursEntries.get(field),theirsEntries.get(field)];if(oursEntry===void 0||theirsEntry===void 0){merged.push(oursEntry??theirsEntry);continue}const outcome=mergeScalarThreeWay(baseEntry,oursEntry,theirsEntry,"ours");merged.push(outcome.conflict&&stableStringify(theirsEntry).localeCompare(stableStringify(oursEntry))<0?theirsEntry:outcome.value)}return merged}function mergeItemUnionField(params){if(!params.unionFieldSet.has(params.field))return!1;const union=mergeUnionFieldValue(params.field,params.baseValue,params.oursValue,params.theirsValue);return params.accumulator.merged[params.field]=union,jsonEquals(union,params.oursValue)||params.accumulator.unionFields.push(params.field),!0}function mergeItemScalarField(params){const outcome=mergeItemScalarThreeWay(params.baseValue,params.oursValue,params.theirsValue,params.preferred,params.conflictResolution,params.oursUpdatedAt,params.theirsUpdatedAt);outcome.value!==void 0&&(params.accumulator.merged[params.field]=outcome.value),outcome.conflict?(params.accumulator.conflictFields.push(params.field),params.accumulator.conflictDecisions.push({field:params.field,base:encodeItemScalarDecisionValue(params.baseValue),ours:encodeItemScalarDecisionValue(params.oursValue),theirs:encodeItemScalarDecisionValue(params.theirsValue),retained:encodeItemScalarDecisionValue(outcome.value),discarded:encodeItemScalarDecisionValue(outcome.from_theirs?params.oursValue:params.theirsValue),retained_side:outcome.retained_side,resolution_basis:outcome.resolution_basis})):outcome.from_theirs&¶ms.accumulator.fieldsFromTheirs.push(params.field)}function mergeItemMetadataRecords(baseRecord,oursRecord,theirsRecord,preferred,conflictResolution,oursUpdatedAt,theirsUpdatedAt){const unionFieldSet=new Set([...ITEM_UNION_COLLECTION_FIELDS,...ITEM_UNION_DELIMITED_FIELDS]),latestFieldSet=new Set(ITEM_LATEST_TIMESTAMP_FIELDS),fieldNames=[...new Set([...Object.keys(oursRecord),...Object.keys(theirsRecord)])].sort((left,right)=>left.localeCompare(right)),accumulator={merged:{},conflictFields:[],fieldsFromTheirs:[],unionFields:[],conflictDecisions:[]};for(const field of fieldNames){const baseValue=baseRecord[field],oursValue=oursRecord[field],theirsValue=theirsRecord[field];if(!mergeItemUnionField({field,baseValue,oursValue,theirsValue,unionFieldSet,accumulator})){if(latestFieldSet.has(field)){accumulator.merged[field]=latestTimestamp(oursValue,theirsValue);continue}mergeItemScalarField({field,baseValue,oursValue,theirsValue,preferred,conflictResolution,oursUpdatedAt,theirsUpdatedAt,accumulator})}}return reconcileMergedDeferrals(accumulator.merged),accumulator}function rebaseReplayDeferrals(replay,base,ours,theirs){const union=unionDeferredFields(base.deferred_fields,ours.deferred_fields,theirs.deferred_fields);replay.deferred_fields=union,reconcileMergedDeferrals(replay),replay.deferred_fields.length===0&&delete replay.deferred_fields}function reconcileMergedDeferrals(merged){Array.isArray(merged.deferred_fields)&&(merged.deferred_fields=merged.deferred_fields.filter(entry=>!hasConcreteItemFieldValue(merged,String(entry.field))))}function mergeItemDocuments(baseRaw,oursRaw,theirsRaw,options={}){const preferred=options.preferred??"ours",conflictResolution=options.conflictResolution??"preferred_side",ours=parseItemMergeSide(oursRaw,"ours",options),theirs=parseItemMergeSide(theirsRaw,"theirs",options);if(baseRaw.trim().length===0)throw new PmCliError("Duplicate item identity: add/add item documents have no common ancestor. Preserve both branches and assign distinct item ids before merging.",EXIT_CODE.CONFLICT,{code:"item_identity_conflict",item_id:ours.metadata.id});const base=parseItemMergeSide(baseRaw,"base",options);if(base.metadata.id!==ours.metadata.id||base.metadata.id!==theirs.metadata.id)throw new PmCliError("Duplicate or mismatched item identity: all merge sides must address the common ancestor's item id.",EXIT_CODE.CONFLICT,{code:"item_identity_conflict",item_id:base.metadata.id});const baseRecord=toMetadataRecord(base),oursRecord=toMetadataRecord(ours),theirsRecord=toMetadataRecord(theirs),{merged,conflictFields,fieldsFromTheirs,unionFields,conflictDecisions}=mergeItemMetadataRecords(baseRecord,oursRecord,theirsRecord,preferred,conflictResolution,ours.metadata.updated_at,theirs.metadata.updated_at),bodyOutcome=mergeItemScalarThreeWay(base.body,ours.body,theirs.body,preferred,conflictResolution,ours.metadata.updated_at,theirs.metadata.updated_at);bodyOutcome.conflict?(conflictFields.push("body"),conflictDecisions.push({field:"body",base:encodeItemScalarDecisionValue(base.body),ours:encodeItemScalarDecisionValue(ours.body),theirs:encodeItemScalarDecisionValue(theirs.body),retained:encodeItemScalarDecisionValue(bodyOutcome.value),discarded:encodeItemScalarDecisionValue(bodyOutcome.from_theirs?ours.body:theirs.body),retained_side:bodyOutcome.retained_side,resolution_basis:bodyOutcome.resolution_basis})):bodyOutcome.from_theirs&&fieldsFromTheirs.push("body");const mergedMetadata=merged;return mergedMetadata.pm_format_version=normalizeItemFormatVersion(Math.max(...[base.metadata,ours.metadata,theirs.metadata,mergedMetadata].map(requiredItemFormatVersion))),{merged:serializeItemDocument({metadata:mergedMetadata,body:bodyOutcome.value},options),conflict_fields:conflictFields,fields_from_theirs:fieldsFromTheirs,union_fields:unionFields,conflict_decisions:conflictDecisions,requested_preference:preferred,requested_preference_applied:conflictResolution==="preferred_side",conflict_resolution:conflictResolution}}function isPlainObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function parseJsonSide(raw,label){const conflictMarker=findFirstMergeConflictMarker(raw);if(conflictMarker)throw new PmCliError(`JSON merge input (${label}) contains unresolved conflict markers at line ${conflictMarker.line}.`,EXIT_CODE.GENERIC_FAILURE);if(raw.trim().length!==0)try{return JSON.parse(raw)}catch{throw new PmCliError(`JSON merge input (${label}) is not valid JSON.`,EXIT_CODE.GENERIC_FAILURE)}}function mergeAdditiveJsonArrays(base,ours,theirs){if(!Array.isArray(base)||!Array.isArray(ours)||!Array.isArray(theirs))return null;const countEntries=entries=>{const counts=new Map;for(const entry of entries){const identity=stableStringify(entry);counts.set(identity,(counts.get(identity)??0)+1)}return counts},baseCounts=countEntries(base),oursCounts=countEntries(ours),theirsCounts=countEntries(theirs);for(const[identity,baseCount]of baseCounts)if((oursCounts.get(identity)??0)<baseCount||(theirsCounts.get(identity)??0)<baseCount)return null;const unmatchedOursCounts=new Map(oursCounts),additionsFromTheirs=[];for(const entry of theirs){const identity=stableStringify(entry),unmatchedOursCount=unmatchedOursCounts.get(identity)??0;unmatchedOursCount>0?unmatchedOursCounts.set(identity,unmatchedOursCount-1):additionsFromTheirs.push(entry)}return{merged:[...ours,...additionsFromTheirs],acceptedTheirs:additionsFromTheirs.length>0}}function mergeJsonObjects(base,ours,theirs,preferred,pathPrefix,conflictPaths,pathsFromTheirs){if(!isPlainObject(ours)||!isPlainObject(theirs))return null;const baseObject=isPlainObject(base)?base:{},merged={},keys=[...new Set([...Object.keys(ours),...Object.keys(theirs)])].sort((left,right)=>left.localeCompare(right));for(const key of keys){const childPath=pathPrefix.length>0?`${pathPrefix}.${key}`:key,child=mergeJsonKey(baseObject,ours,theirs,key,preferred,childPath,conflictPaths,pathsFromTheirs);child!==void 0&&(merged[key]=child)}return merged}function mergeJsonValue(base,ours,theirs,preferred,pathPrefix,conflictPaths,pathsFromTheirs){if(jsonEquals(ours,theirs))return ours;const additiveArrayMerge=mergeAdditiveJsonArrays(base,ours,theirs);if(additiveArrayMerge!==null)return additiveArrayMerge.acceptedTheirs&&pathsFromTheirs.push(pathPrefix),additiveArrayMerge.merged;const mergedObject=mergeJsonObjects(base,ours,theirs,preferred,pathPrefix,conflictPaths,pathsFromTheirs);if(mergedObject!==null)return mergedObject;const outcome=mergeScalarThreeWay(base,ours,theirs,preferred);return outcome.conflict?conflictPaths.push(pathPrefix):outcome.from_theirs&&pathsFromTheirs.push(pathPrefix),outcome.value}function mergeJsonKey(base,ours,theirs,key,preferred,childPath,conflictPaths,pathsFromTheirs){const inOurs=Object.prototype.hasOwnProperty.call(ours,key),inTheirs=Object.prototype.hasOwnProperty.call(theirs,key),inBase=Object.prototype.hasOwnProperty.call(base,key);if(inOurs&&inTheirs)return mergeJsonValue(base[key],ours[key],theirs[key],preferred,childPath,conflictPaths,pathsFromTheirs);if(inOurs){if(inBase&&jsonEquals(base[key],ours[key])){pathsFromTheirs.push(childPath);return}return inBase?(conflictPaths.push(childPath),preferred==="theirs"?void 0:ours[key]):ours[key]}if(!(inBase&&jsonEquals(base[key],theirs[key])))return inBase?(conflictPaths.push(childPath),preferred==="theirs"?theirs[key]:void 0):(pathsFromTheirs.push(childPath),theirs[key])}function mergeJsonDocuments(baseRaw,oursRaw,theirsRaw,options={}){const preferred=options.preferred??"ours",base=parseJsonSide(baseRaw,"base"),ours=parseJsonSide(oursRaw,"ours"),theirs=parseJsonSide(theirsRaw,"theirs"),conflictPaths=[],pathsFromTheirs=[],merged=mergeJsonValue(base,ours,theirs,preferred,"",conflictPaths,pathsFromTheirs);return{merged:`${JSON.stringify(merged??null,null,2)}
|
|
10
|
-
`,conflict_paths:
|
|
9
|
+
`}function Be(e){return e.map((t,r)=>({...t,sequence:r+1}))}function gt(e,t,r){k(e,"base");const n=k(t,"ours"),o=k(r,"theirs"),c=Math.min(n.length,o.length);let i=0;for(;i<c&&n[i].eventId===o[i].eventId;)i+=1;if(i===n.length&&i===o.length)return{merged:F(n),strategy:"identical",common_entries:i,entries_from_ours:0,entries_from_theirs:0,entries_total:n.length,reanchored:!1};if(i===o.length)return{merged:F(n),strategy:"fast_forward_ours",common_entries:i,entries_from_ours:n.length-i,entries_from_theirs:0,entries_total:n.length,reanchored:!1};if(i===n.length)return{merged:F(o),strategy:"fast_forward_theirs",common_entries:i,entries_from_ours:0,entries_from_theirs:o.length-i,entries_total:o.length,reanchored:!1};const s=n.slice(i),u=new Set(s.map(l=>l.eventId)),f=o.slice(i).filter(l=>!u.has(l.eventId)),a=[...s,...f].sort((l,m)=>{if(l.timestamp!==void 0&&m.timestamp!==void 0){const I=A(l.timestamp,m.timestamp);if(I!==0)return I}else{if(l.timestamp===void 0&&m.timestamp!==void 0)return 1;if(l.timestamp!==void 0)return-1}const p=u.has(l.eventId),h=u.has(m.eventId);return p!==h?Number(h)-Number(p):0}),d=Be([...n.slice(0,i),...a]);return{merged:F(d),strategy:"union_reanchor",common_entries:i,entries_from_ours:s.length,entries_from_theirs:f.length,entries_total:d.length,reanchored:!0}}const ne=["tags","dependencies","comments","notes","learnings","files","tests","test_runs","docs","reminders","events","deferred_fields"],re=["acceptance_criteria"],Pe=["updated_at"];function v(e,t){return e===void 0||t===void 0?e===void 0&&t===void 0:_(e)===_(t)}function ie(e,t,r){const n=a=>Array.isArray(a)?a:[],o=new Set(n(e).map(a=>_(a))),c=n(t),i=new Set(c.map(a=>_(a))),s=n(r),u=new Set(s.map(a=>_(a))),f=c.filter(a=>{const d=_(a);return!o.has(d)||u.has(d)});for(const a of s){const d=_(a);!i.has(d)&&!o.has(d)&&f.push(a)}return f}function O(e){if(typeof e!="object"||e===null||Array.isArray(e))return _(e);const{provenance:t,...r}=e;return _(r)}function qe(e){if(typeof e!="object"||e===null||Array.isArray(e))return e;const t=e;return t.provenance?{...t,provenance:{...t.provenance,source_kind:"merge_union"}}:{...t,provenance:{source_kind:"merge_union"}}}function Ge(e,t,r){const n=a=>Array.isArray(a)?a:[],o=new Set(n(e).map(O)),c=n(t),i=new Set(c.map(O)),s=n(r),u=new Set(s.map(O)),f=c.filter(a=>{const d=O(a);return!o.has(d)||u.has(d)});for(const a of s){const d=O(a);!i.has(d)&&!o.has(d)&&f.push(qe(a))}return f}function ze(e,t){return A(String(e),String(t))>=0?e:t}function V(e,t,r,n){return v(t,r)?{value:t,from_theirs:!1,conflict:!1}:v(e,t)?{value:r,from_theirs:!0,conflict:!1}:v(e,r)?{value:t,from_theirs:!1,conflict:!1}:{value:n==="theirs"?r:t,from_theirs:n==="theirs",conflict:!0}}function oe(e,t,r,n,o,c,i){const s=V(e,t,r,n);if(!s.conflict)return{...s,conflict:!1};if(o==="preferred_side")return{...s,resolution_basis:"requested_preference",retained_side:s.from_theirs?"theirs":"ours"};const u=A(c,i);if(o==="latest_document_update"&&u!==0){const a=u<0;return{value:a?r:t,from_theirs:a,conflict:!0,resolution_basis:"document_updated_at",retained_side:a?"theirs":"ours"}}const f=_(S(r)).localeCompare(_(S(t)))<0;return{value:f?r:t,from_theirs:f,conflict:!0,resolution_basis:"stable_value_tiebreak",retained_side:f?"theirs":"ours"}}function D(e){return{...e.metadata}}function U(e,t,r){try{const n=Se(we(e,{...r,requireSupportedFormat:!0}),r),o=Object.entries(n.metadata).find(([,c])=>Fe(c))?.[0];if(o!==void 0)throw new TypeError(`metadata field ${o} uses the reserved missing-scalar evidence marker`);return n}catch(n){throw n instanceof y&&n.context?.code==="item_format_version_unsupported"?n:new y(`Item merge input (${t}) is not a readable item document: ${String(n)}`,b.GENERIC_FAILURE)}}function We(e,t,r,n){return e==="tests"?Ge(t,r,n):e==="deferred_fields"?se(t,r,n):e==="acceptance_criteria"?ie(N(t),N(r),N(n)).join("; "):ie(t,r,n)}function se(e,t,r){const n=u=>new Map((Array.isArray(u)?u:[]).map(f=>[String(f.field),f])),[o,c,i]=[n(e),n(t),n(r)],s=[];for(const u of[...new Set([...c.keys(),...i.keys()])].sort()){const[f,a,d]=[o.get(u),c.get(u),i.get(u)];if(a===void 0||d===void 0){s.push(a??d);continue}const l=V(f,a,d,"ours");s.push(l.conflict&&_(d).localeCompare(_(a))<0?d:l.value)}return s}function Ke(e){if(!e.unionFieldSet.has(e.field))return!1;const t=We(e.field,e.baseValue,e.oursValue,e.theirsValue);return e.accumulator.merged[e.field]=t,v(t,e.oursValue)||e.accumulator.unionFields.push(e.field),!0}function Xe(e){const t=oe(e.baseValue,e.oursValue,e.theirsValue,e.preferred,e.conflictResolution,e.oursUpdatedAt,e.theirsUpdatedAt);t.value!==void 0&&(e.accumulator.merged[e.field]=t.value),t.conflict?(e.accumulator.conflictFields.push(e.field),e.accumulator.conflictDecisions.push({field:e.field,base:S(e.baseValue),ours:S(e.oursValue),theirs:S(e.theirsValue),retained:S(t.value),discarded:S(t.from_theirs?e.oursValue:e.theirsValue),retained_side:t.retained_side,resolution_basis:t.resolution_basis})):t.from_theirs&&e.accumulator.fieldsFromTheirs.push(e.field)}function ce(e,t,r,n,o,c,i){const s=new Set([...ne,...re]),u=new Set(Pe),f=[...new Set([...Object.keys(t),...Object.keys(r)])].sort((d,l)=>d.localeCompare(l)),a={merged:{},conflictFields:[],fieldsFromTheirs:[],unionFields:[],conflictDecisions:[]};for(const d of f){const l=e[d],m=t[d],p=r[d];if(!Ke({field:d,baseValue:l,oursValue:m,theirsValue:p,unionFieldSet:s,accumulator:a})){if(u.has(d)){a.merged[d]=ze(m,p);continue}Xe({field:d,baseValue:l,oursValue:m,theirsValue:p,preferred:n,conflictResolution:o,oursUpdatedAt:c,theirsUpdatedAt:i,accumulator:a})}}return ae(a.merged),a}function Qe(e,t,r,n){const o=se(t.deferred_fields,r.deferred_fields,n.deferred_fields);e.deferred_fields=o,ae(e),e.deferred_fields.length===0&&delete e.deferred_fields}function ae(e){Array.isArray(e.deferred_fields)&&(e.deferred_fields=e.deferred_fields.filter(t=>!xe(e,String(t.field))))}function yt(e,t,r,n={}){const o=n.preferred??"ours",c=n.conflictResolution??"preferred_side",i=U(t,"ours",n),s=U(r,"theirs",n);if(e.trim().length===0)throw new y("Duplicate item identity: add/add item documents have no common ancestor. Preserve both branches and assign distinct item ids before merging.",b.CONFLICT,{code:"item_identity_conflict",item_id:i.metadata.id});const u=U(e,"base",n);if(u.metadata.id!==i.metadata.id||u.metadata.id!==s.metadata.id)throw new y("Duplicate or mismatched item identity: all merge sides must address the common ancestor's item id.",b.CONFLICT,{code:"item_identity_conflict",item_id:u.metadata.id});const f=D(u),a=D(i),d=D(s),{merged:l,conflictFields:m,fieldsFromTheirs:p,unionFields:h,conflictDecisions:I}=ce(f,a,d,o,c,i.metadata.updated_at,s.metadata.updated_at),w=oe(u.body,i.body,s.body,o,c,i.metadata.updated_at,s.metadata.updated_at);w.conflict?(m.push("body"),I.push({field:"body",base:S(u.body),ours:S(i.body),theirs:S(s.body),retained:S(w.value),discarded:S(w.from_theirs?i.body:s.body),retained_side:w.retained_side,resolution_basis:w.resolution_basis})):w.from_theirs&&p.push("body");const E=l;return E.pm_format_version=Oe(Math.max(...[u.metadata,i.metadata,s.metadata,E].map(Re))),{merged:ve({metadata:E,body:w.value},n),conflict_fields:m,fields_from_theirs:p,union_fields:h,conflict_decisions:I,requested_preference:o,requested_preference_applied:c==="preferred_side",conflict_resolution:c}}function H(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function J(e,t){const r=j(e);if(r)throw new y(`JSON merge input (${t}) contains unresolved conflict markers at line ${r.line}.`,b.GENERIC_FAILURE);if(e.trim().length!==0)try{return JSON.parse(e)}catch{throw new y(`JSON merge input (${t}) is not valid JSON.`,b.GENERIC_FAILURE)}}function Ye(e,t,r){if(!Array.isArray(e)||!Array.isArray(t)||!Array.isArray(r))return null;const n=f=>{const a=new Map;for(const d of f){const l=_(d);a.set(l,(a.get(l)??0)+1)}return a},o=n(e),c=n(t),i=n(r);for(const[f,a]of o)if((c.get(f)??0)<a||(i.get(f)??0)<a)return null;const s=new Map(c),u=[];for(const f of r){const a=_(f),d=s.get(a)??0;d>0?s.set(a,d-1):u.push(f)}return{merged:[...t,...u],acceptedTheirs:u.length>0}}function Ze(e,t,r,n,o,c,i){if(!H(t)||!H(r))return null;const s=H(e)?e:{},u={},f=[...new Set([...Object.keys(t),...Object.keys(r)])].sort((a,d)=>a.localeCompare(d));for(const a of f){const d=o.length>0?`${o}.${a}`:a,l=et(s,t,r,a,n,d,c,i);l!==void 0&&(u[a]=l)}return u}function de(e,t,r,n,o,c,i){if(v(t,r))return t;const s=Ye(e,t,r);if(s!==null)return s.acceptedTheirs&&i.push(o),s.merged;const u=Ze(e,t,r,n,o,c,i);if(u!==null)return u;const f=V(e,t,r,n);return f.conflict?c.push(o):f.from_theirs&&i.push(o),f.value}function et(e,t,r,n,o,c,i,s){const u=Object.prototype.hasOwnProperty.call(t,n),f=Object.prototype.hasOwnProperty.call(r,n),a=Object.prototype.hasOwnProperty.call(e,n);if(u&&f)return de(e[n],t[n],r[n],o,c,i,s);if(u){if(a&&v(e[n],t[n])){s.push(c);return}return a?(i.push(c),o==="theirs"?void 0:t[n]):t[n]}if(!(a&&v(e[n],r[n])))return a?(i.push(c),o==="theirs"?r[n]:void 0):(s.push(c),r[n])}function bt(e,t,r,n={}){const o=n.preferred??"ours",c=J(e,"base"),i=J(t,"ours"),s=J(r,"theirs"),u=[],f=[],a=de(c,i,s,o,"",u,f);return{merged:`${JSON.stringify(a??null,null,2)}
|
|
10
|
+
`,conflict_paths:u,paths_from_theirs:f,preferred:o}}const It={collectUnionInexactIndexes:C,normalizationApplies:ee,repairRecursAfterRuns:Z};export{Pe as ITEM_LATEST_TIMESTAMP_FIELDS,Ce as ITEM_SCALAR_MISSING_VALUE,ne as ITEM_UNION_COLLECTION_FIELDS,It as _testOnly,S as encodeItemScalarDecisionValue,pt as hashItemScalarDecisionValue,Fe as isItemScalarMissingValue,_t as mergeHistoryStreams,yt as mergeItemDocuments,bt as mergeJsonDocuments,gt as mergeRelationshipEventStreams};
|
|
11
11
|
//# sourceMappingURL=three-way.js.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
|
|
2
|
-
`)?
|
|
1
|
+
import{execFile as d}from"node:child_process";import p from"node:path";import{promisify as g}from"node:util";import{setTimeout as _}from"node:timers/promises";const f=g(d);async function c(e,r){const t=performance.now()+5e3;let o=25;for(;;)try{await f("git",["config",...r],{cwd:e,env:{...s(),LC_ALL:"C"},timeout:1e4});return}catch(n){const i=t-performance.now();if(typeof n!="object"||n===null||!("stderr"in n)||typeof n.stderr!="string"||!/could not lock config file [^\r\n]+: File exists/u.test(n.stderr)||i<=0)throw n;await _(Math.min(o,i)),o=Math.min(o*2,200)}}function I(e,r=process.platform){const t=e.endsWith(`
|
|
2
|
+
`)?e.slice(0,-1):e;return r==="win32"&&t.endsWith("\r")?t.slice(0,-1):t}function s(){const e={...process.env};for(const r of["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES","GIT_DISCOVERY_ACROSS_FILESYSTEM"])delete e[r];return e}async function l(e,r){try{return(await f("git",["config","--local",...r==="core.bare"||r==="extensions.worktreeConfig"?["--type=bool"]:[],"--get",r],{cwd:e,env:s(),timeout:1e4})).stdout.trim()}catch(t){if(typeof t=="object"&&t!==null&&"code"in t&&t.code===1)return;throw t}}async function y(e){if(await l(e,"extensions.worktreeConfig")==="true")return"--worktree";const r=async i=>I((await f("git",["rev-parse","--path-format=absolute",i],{cwd:e,env:s(),timeout:1e4})).stdout),t=await r("--git-dir"),o=await r("--git-common-dir");if(t===o)return"--local";const n=p.join(o,"config.worktree");for(const i of["core.bare","core.worktree"]){const a=await l(e,i);a===void 0||i==="core.bare"&&a!=="true"||(await c(e,["--file",n,i,a]),await c(e,["--local","--unset-all",i]))}for(const i of["pm-item-toon","pm-item-markdown","pm-history","pm-relationship","pm-json"])for(const a of["name","driver"]){const m=`merge.${i}.${a}`,u=await l(e,m);u!==void 0&&await c(e,["--file",n,m,u])}return await c(e,["--local","extensions.worktreeConfig","true"]),"--worktree"}export{s as gitWorkspaceEnvironment,y as resolveMergeDriverConfigScope,I as stripGitPathTerminator,c as writeMergeDriverGitConfig};
|
|
3
3
|
//# sourceMappingURL=worktree-config.js.map
|
package/dist/sdk/merge.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
export*from"./merge/index.js";export*from"./merge/install.js";
|
|
2
2
|
//# sourceMappingURL=merge.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
import{assertInitializedTracker as C}from"./environment/tracker-preflight.js";import{createHash as F}from"node:crypto";import{setTimeout as G}from"node:timers/promises";import{readHistoryEventIndexPage as E,queryHistoryEventStreams as L,rebuildHistoryEventIndex as P}from"../core/history/event-index.js";import{EXIT_CODE as c}from"../core/shared/constants.js";import{PmCliError as o}from"../core/shared/errors.js";import{stableStringify as R}from"../core/shared/serialization.js";import{toErrorMessage as H}from"../core/shared/primitives.js";import{resolvePmRoot as z}from"../core/store/paths.js";import{readSettings as D}from"../core/store/settings.js";import{parseHistoryProvenanceFilters as V,projectHistoryProvenance as B,resolveHistoryProvenanceDimensions as j,summarizeHistoryProvenance as W}from"./history-provenance.js";const g=1,w=/^[A-Za-z0-9_-]+$/,k=100,p=1e3,q=250,ce=Object.freeze({batch_to_row_ratio:.6,fixture_events:200});function i(e){if(e===void 0)return;const r=typeof e=="string"?[e]:e,t=[...new Set(r.flatMap(n=>n.split(",")).map(n=>n.trim()).filter(Boolean))].sort((n,f)=>n.localeCompare(f));return t.length===0?void 0:t}function M(e){return F("sha256").update(R({type:i(e.type),author:i(e.author),item:i(e.item),harness:i(e.harness),agent_instance:i(e.agentInstance),provenance:i(e.provenanceFilter)})).digest("hex").slice(0,24)}function _(e,r){const t={version:g,fingerprint:r,ts:e.entry.ts,stream_id:e.stream_id,stream_offset:e.stream_offset};return Buffer.from(JSON.stringify(t),"utf8").toString("base64url")}function b(e,r){if(typeof e!="object"||e===null)return!1;const t=e;return[t.version===g,t.fingerprint===r,typeof t.ts=="string",typeof t.stream_id=="string",typeof t.stream_offset=="number",Number.isSafeInteger(t.stream_offset),Number(t.stream_offset)>=0].every(Boolean)}function S(e,r){const t=e.trim();if(t.length===0||t.length>4096||!w.test(t))throw new o("Invalid mutation event cursor.",c.USAGE,{code:"invalid_event_cursor"});let n;try{n=JSON.parse(Buffer.from(t,"base64url").toString("utf8"))}catch{throw new o("Invalid mutation event cursor.",c.USAGE,{code:"invalid_event_cursor"})}if(!b(n,r))throw new o("Mutation event cursor does not match this query.",c.USAGE,{code:"event_cursor_query_mismatch"});return n}function I(e){const r=e??k;if(!Number.isSafeInteger(r)||r<0||r>p)throw new o(`Mutation event limit must be an integer from 0 to ${p}.`,c.USAGE,{code:"invalid_event_limit"});return r}function T(e){return e instanceof Error&&e.name==="AbortError"}function A(e,r){const t=e?.trim();if(!t)return{};if(w.test(t))return{cursor:S(t,r)};const n=Date.parse(t);if(!Number.isFinite(n))throw new o("Mutation event --since must be an event cursor or ISO timestamp.",c.USAGE,{code:"invalid_event_since"});return{sinceTimestamp:new Date(n).toISOString()}}async function J(e,r){if(r.verify)return x(e,r);const t=await E(e,r);let n=t.result;if(n===null&&t.repair_needed)try{await P(e,{lockWaitMs:0})&&(n=(await E(e,r)).result)}catch{}return n===null?x(e,r):{...n,source:"derived_index"}}async function x(e,r){try{return{...await L(e,r),source:"authoritative_history"}}catch(t){throw t instanceof o?t:new o("Mutation events are unavailable because authoritative history could not be read.",c.GENERIC_FAILURE,{code:"event_index_unavailable",why:H(t)})}}function X(e){const r=e??"batch";if(r!=="batch"&&r!=="row")throw new o("Mutation event cursor mode must be batch or row.",c.USAGE,{code:"invalid_event_cursor_mode"});return r}async function $(e={}){const r=z(e.cwd??process.cwd(),e.pmRoot);await C(r);const t=I(e.limit),n=X(e.cursorMode);if(e.full===!0&&e.provenance===!0)throw new o("Mutation event projections are mutually exclusive. Use --provenance or --full.",c.USAGE);const f=await D(r),u=f.agent_identity.identity_vocabulary,v=j(f.agent_identity.harness_signals),N=V({provenance:e.provenanceFilter},v),d=i(e.harness),l=M(e),{cursor:m,sinceTimestamp:y}=A(e.since,l),U={verify:e.verify===!0,...m?{after_ts:m.ts,after_stream_id:m.stream_id,after_stream_offset:m.stream_offset}:y?{since_ts:y}:{},ops:i(e.type),authors:i(e.author),harnesses:d,harness_alias_authors:d?Object.entries(u.aliases).filter(([,s])=>d.includes(s)).map(([s])=>s):void 0,agent_instances:i(e.agentInstance),provenance:[...N].map(([s,O])=>({dimension:s,values:[...O]})),stream_ids:i(e.item),limit:t},a=await J(r,U),h=a.events.map(s=>({...n==="row"?{cursor:_(s,l)}:{},item_id:s.stream_id,version:s.stream_offset+1,ts:s.entry.ts,author:s.entry.author,type:s.entry.op,...s.entry.message===void 0?{}:{message:s.entry.message},patch_count:s.entry.patch.length,...e.full===!0?{entry:structuredClone(s.recorded_entry??s.entry)}:{},...e.provenance===!0?{provenance:B(s.entry,u,{itemId:s.stream_id,version:s.stream_offset+1})}:{}}));return{integrity:e.verify===!0?"verified":"unverified",...a.verified_streams===void 0?{}:{verified_streams:a.verified_streams},events:h,count:h.length,has_more:a.has_more,cursor_mode:n,...a.events.length===0?{}:{next_cursor:_(a.events[a.events.length-1],l)},source:a.source,...e.provenanceSummary===!0?{provenance_summary:W(a.events.map(s=>s.entry),u,v)}:{}}}async function*Q(e={}){const r=e.intervalMs??q;if(!Number.isSafeInteger(r)||r<10)throw new o("Mutation event follow interval must be an integer of at least 10ms.",c.USAGE,{code:"invalid_event_follow_interval"});let t=e.since;for(;e.signal?.aborted!==!0;){const n=await $({...e,cursorMode:e.cursorMode??"batch",since:t});if(yield n.next_cursor===void 0&&t!==void 0?{...n,next_cursor:t}:n,n.events.length>0){t=n.next_cursor;continue}try{await G(r,void 0,{signal:e.signal})}catch(u){if(T(u))return;throw u}}}async function*ue(e={}){for await(const r of Q({...e,cursorMode:"row"}))for(const t of r.events)yield t}const fe={decodeMutationEventCursor:S,encodeMutationEventCursor:_,eventQueryFingerprint:M,isAbortError:T,isMutationEventCursorEnvelope:b,parseMutationEventLimit:I,resolveMutationEventStart:A};export{ce as MUTATION_EVENT_WIRE_BUDGET,fe as _testOnlyMutationEvents,$ as listMutationEvents,Q as subscribeMutationEventBatches,ue as subscribeMutationEvents};
|
|
2
2
|
//# sourceMappingURL=mutation-events.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]="e55d27db-d28f-56da-ac44-2ed6c19f8609")}catch{}})();import{SECRET_RULES,acceptsStructuredValue,findSecretRuleMatches,structuredKeyShape}from"../core/shared/secret-rules.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";const CATEGORY_SETS_MATCH=!0,PM_MUTATION_ACTION_CONTRACTS=[{action:"append",history_scope:"item"},{action:"claim",history_scope:"item"},{action:"close",history_scope:"item"},{action:"close-many",history_scope:"item"},{action:"close-task",history_scope:"item"},{action:"comments",history_scope:"conditional"},{action:"config",history_scope:"conditional"},{action:"copy",history_scope:"item"},{action:"create",history_scope:"item"},{action:"delete",history_scope:"item"},{action:"deps",history_scope:"conditional"},{action:"discover",history_scope:"item"},{action:"docs",history_scope:"conditional"},{action:"files",history_scope:"conditional"},{action:"focus",history_scope:"conditional"},{action:"gc",history_scope:"conditional"},{action:"history-compact",history_scope:"history"},{action:"history-author-acknowledge",history_scope:"workspace"},{action:"history-redact",history_scope:"history"},{action:"history-repair",history_scope:"history"},{action:"init",history_scope:"workspace"},{action:"install",history_scope:"conditional"},{action:"learnings",history_scope:"conditional"},{action:"notes",history_scope:"conditional"},{action:"package",history_scope:"conditional"},{action:"pause-task",history_scope:"item"},{action:"plan",history_scope:"conditional"},{action:"profile",history_scope:"conditional"},{action:"release",history_scope:"item"},{action:"restore",history_scope:"item"},{action:"schema",history_scope:"conditional"},{action:"start-task",history_scope:"item"},{action:"templates",history_scope:"conditional"},{action:"test",history_scope:"conditional"},{action:"test-all",history_scope:"conditional"},{action:"update",history_scope:"item"},{action:"update-many",history_scope:"item"},{action:"upgrade",history_scope:"conditional"}],MUTATION_ACTION_CONTRACTS_BY_NAME=new Map(PM_MUTATION_ACTION_CONTRACTS.map(contract=>[contract.action,contract])),ARRAY_INDEX=/^(?:0|[1-9]\d*)$/u,MAX_ARRAY_INDEX=2**32-2;function isArrayIndex(key){return ARRAY_INDEX.test(key)&&Number(key)<=MAX_ARRAY_INDEX}function ruleMatches(value){const matches=[];for(const rule of SECRET_RULES){const match=preflightRuleMatch(rule,value);match&&matches.push({rule,match})}return matches}function nameMatches(name,cache){let matches=cache.names.get(name);return matches===void 0&&(matches=ruleMatches(name),cache.names.set(name,matches)),matches}function ownEntries(value,cache){let entries=cache.entries.get(value);return entries===void 0&&(entries=Array.isArray(value)?Object.getOwnPropertyNames(value).filter(isArrayIndex).map(name=>({name,value:value[Number(name)],segment:`[${name}]`,nameMatches:[]})):Object.entries(value).map(([name,entry],position)=>{const matches=nameMatches(name,cache);return{name,value:entry,segment:matches.length>0?`[key ${position}]`:`.${name}`,nameMatches:matches}}),cache.entries.set(value,entries)),entries}function findingFor({rule,match},path,propertyName){const finding={rule:rule.mutationRule,path};return propertyName&&(finding.property_name=!0),match.normalizations&&(finding.normalizations=match.normalizations),match.normalization_incomplete&&(finding.normalization_incomplete=!0),finding}function pushReversed(pending,children){for(let index=children.length-1;index>=0;index-=1)pending.push(children[index])}function preflightRuleMatch(rule,value){try{return firstRuleMatch(rule,value)}catch(error){return judgeTooLarge(error)}}function judgeTooLarge(error){if(!(error instanceof RangeError))throw error;return{index:0,normalization_incomplete:!0}}function firstRuleMatch(rule,value){const matches=findSecretRuleMatches(rule,value),first=matches.next().value;if(!first||rule.mutationRule!=="absolute_home_path"||first.normalization_incomplete)return first;for(const later of matches)if(later.normalization_incomplete)return{...first,normalizations:[...new Set([first.normalizations,later.normalizations].flatMap(kinds=>kinds??[]))],normalization_incomplete:!0};return first}function scanStringLeaves(payload,cache){const findings=[],seen=new WeakSet,pending=[{value:payload,path:"$"}];for(let step=pending.pop();step!==void 0;step=pending.pop()){const{value,path}=step;if(typeof value=="string")for(const match of ruleMatches(value))findings.push(findingFor(match,path,!1));else if(typeof value=="object"&&value!==null&&!seen.has(value)){seen.add(value);const entries=ownEntries(value,cache);for(const entry of entries)for(const match of entry.nameMatches)findings.push(findingFor(match,`${path}${entry.segment}`,!0));pushReversed(pending,entries.map(entry=>({value:entry.value,path:`${path}${entry.segment}`})))}}return findings}const KEY_NAMED_RULES=SECRET_RULES.filter(rule=>"structured"in rule),NO_KEY_CONTEXT=KEY_NAMED_RULES.map(()=>({named:!1,exact:!1})),CAMEL_BOUNDARY=/(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/gu,CREDENTIAL_SUFFIX_WORDS=3;function keyWords(name){return name.replace(CAMEL_BOUNDARY,"_")}function nameSpellings(name){const suffixSplits=[...name.matchAll(CAMEL_BOUNDARY)].map(match=>match.index).slice(-CREDENTIAL_SUFFIX_WORDS).map(boundary=>`${keyWords(name.slice(0,boundary))}_${name.slice(boundary)}`);return[...new Set([name,keyWords(name),...suffixSplits])]}function memberKeyShapes(name){const spellings=nameSpellings(name);return KEY_NAMED_RULES.map(rule=>{const shapes=spellings.map(spelling=>structuredKeyShape(rule,spelling));return shapes.includes("exact")?"exact":shapes.includes("prefixed")?"prefixed":void 0})}const NO_JUDGMENTS=KEY_NAMED_RULES.map(()=>{});function memberChildSteps(value,path,contexts,cache){const entries=ownEntries(value,cache);if(Array.isArray(value)){const judgments=contexts.map(({named,exact})=>exact?"lenient":named?"compact":void 0);return entries.map(entry=>({value:entry.value,path:`${path}${entry.segment}`,contexts,judgments}))}return entries.map(({name,value:entry,segment})=>{const shapes=memberKeyShapes(name);return{value:entry,path:`${path}${segment}`,contexts:contexts.map(({named,exact},index)=>({named:named||shapes[index]!==void 0,exact:exact||shapes[index]==="exact"})),judgments:shapes.map((shape,index)=>shape==="exact"?"lenient":shape==="prefixed"||contexts[index].named?"compact":void 0)}})}function scanPayloadMembers(payload,cache){const findings=[],visited=new WeakMap,pending=[{value:payload,path:"$",contexts:NO_KEY_CONTEXT,judgments:NO_JUDGMENTS}];for(let step=pending.pop();step!==void 0;step=pending.pop()){const{value,path,contexts,judgments}=step;if(typeof value=="string"){judgments.forEach((judgment,index)=>{const rule=KEY_NAMED_RULES[index];if(judgment===void 0)return;let accepted;try{accepted=acceptsStructuredValue(rule,value,judgment==="compact")}catch(error){judgeTooLarge(error),findings.push({rule:rule.mutationRule,path,normalization_incomplete:!0});return}accepted&&findings.push({rule:rule.mutationRule,path})});continue}if(typeof value!="object"||value===null)continue;const signature=contexts.map(({named,exact})=>exact?"e":named?"n":"-").join(""),signatures=visited.get(value)??new Set;signatures.has(signature)||(visited.set(value,signatures.add(signature)),pushReversed(pending,memberChildSteps(value,path,contexts,cache)))}return findings}function scanMutationSecrets(payload){const reported=new Set,cache={entries:new WeakMap,names:new Map};return[...scanStringLeaves(payload,cache),...scanPayloadMembers(payload,cache)].filter(finding=>{const key=`${finding.rule}\0${finding.path}\0${finding.property_name===!0}`;return reported.has(key)?!1:(reported.add(key),!0)})}function evaluateMutationGuard(options){const author=options.author.trim()||"unknown";if(options.settings.require_attributed_author&&author.toLowerCase()==="unknown")throw new PmCliError("Mutation author is required by workspace policy.",EXIT_CODE.USAGE,{code:"mutation_author_required",required:"Pass --author <id>, set PM_AUTHOR, or configure author_default.",nextSteps:["Retry with --author <stable-agent-id>.","Set PM_AUTHOR for this agent session."]});if(options.settings.secret_guard==="off")return{author,findings:[],warnings:[],override_applied:!1};let findings;try{findings=scanMutationSecrets(options.payload)}catch{return{author,findings:[],warnings:["secret_guard_scan_failed_open"],override_applied:!1}}if(findings.length===0)return{author,findings,warnings:[],override_applied:!1};const ruleSummary=[...new Set(findings.map(finding=>finding.rule))].sort().join(",");if(options.settings.secret_guard==="block"&&options.force!==!0)throw new PmCliError(`Mutation blocked by secret guard (${ruleSummary}). No detected value was logged.`,EXIT_CODE.CONFLICT,{code:"mutation_secret_guard_blocked",required:"Remove the credential-shaped content or retry with --force after explicit review.",nextSteps:["Replace the value with a secret-manager reference.","Use pm history-redact if equivalent content already entered history."],recovery:{recovery_mode:"compact",attempted_command:"pm <mutation> [REDACTED]",normalized_args:["[REDACTED]"],suggested_retry:"Remove credential-shaped content, then retry the mutation."}});return{author,findings,warnings:[`secret_guard_detected:${findings.length}:rules=${ruleSummary}`,...options.settings.secret_guard==="block"&&options.force===!0?["secret_guard_force_override"]:[]],override_applied:options.settings.secret_guard==="block"&&options.force===!0}}const SECRET_GUARD_RULE_CATEGORIES=Object.freeze(Object.fromEntries(SECRET_RULES.map(rule=>[rule.mutationRule,rule.category])));function secretGuardRuleCategory(rule){return Object.hasOwn(SECRET_GUARD_RULE_CATEGORIES,rule)?SECRET_GUARD_RULE_CATEGORIES[rule]:void 0}function ownPolicyEntry(entries,key){return entries!==void 0&&key!==void 0&&Object.hasOwn(entries,key)?entries[key]:void 0}const OBJECT_PROTOTYPE_KEYS=new Set(Reflect.ownKeys(Object.prototype));function isForeignObjectPrototype(prototype){const keys=Reflect.ownKeys(prototype);if(keys.length!==OBJECT_PROTOTYPE_KEYS.size||!keys.every(key=>OBJECT_PROTOTYPE_KEYS.has(key)))return!1;const constructor=Object.getOwnPropertyDescriptor(prototype,"constructor")?.value;return typeof constructor=="function"&&Object.getOwnPropertyDescriptor(constructor,"prototype")?.value===prototype}function isPlainPropertyMap(value){const prototype=Object.getPrototypeOf(value);return prototype===null||prototype===Object.prototype?!0:Object.getPrototypeOf(prototype)!==null?!1:Reflect.ownKeys(prototype).length===0||isForeignObjectPrototype(prototype)}function ownPolicyEntries(policy,field){const entries=Object.hasOwn(policy,field)?policy[field]:void 0;if(entries!==void 0&&(typeof entries!="object"||entries===null||!isPlainPropertyMap(entries)))throw new TypeError(`Secret guard policy ${field} must be an object keyed by ${field==="rules"?"rule":"category"}.`);return entries}function decideSecretGuardFinding(policy,finding){if(typeof policy!="object"||policy===null||Array.isArray(policy))throw new TypeError("Secret guard policy must be an object with a default decision.");const fallback=Object.hasOwn(policy,"default")?policy.default:void 0;if(fallback===void 0)throw new TypeError("Secret guard policy requires a default decision.");const categories=ownPolicyEntries(policy,"categories"),rules=ownPolicyEntries(policy,"rules"),rule=typeof finding=="object"&&finding!==null?finding.rule:void 0;if(typeof rule!="string")throw new TypeError("Secret guard finding must have a string rule.");const ruleDecision=ownPolicyEntry(rules,rule);if(ruleDecision!==void 0)return ruleDecision;const categoryDecision=ownPolicyEntry(categories,secretGuardRuleCategory(rule));return categoryDecision===void 0?fallback:categoryDecision}function isMutationAction(action){return MUTATION_ACTION_CONTRACTS_BY_NAME.has(action.trim().toLowerCase())}function listMutationActions(){return[...MUTATION_ACTION_CONTRACTS_BY_NAME.keys()].sort((left,right)=>left.localeCompare(right))}function getMutationActionContract(action){return MUTATION_ACTION_CONTRACTS_BY_NAME.get(action.trim().toLowerCase())}export{PM_MUTATION_ACTION_CONTRACTS,SECRET_GUARD_RULE_CATEGORIES,decideSecretGuardFinding,evaluateMutationGuard,getMutationActionContract,isMutationAction,listMutationActions,scanMutationSecrets,secretGuardRuleCategory};
|
|
1
|
+
import{SECRET_RULES as _,acceptsStructuredValue as k,findSecretRuleMatches as N,structuredKeyShape as z}from"../core/shared/secret-rules.js";import{EXIT_CODE as w}from"../core/shared/constants.js";import{PmCliError as O}from"../core/shared/errors.js";const P=!0,D=[{action:"append",history_scope:"item"},{action:"claim",history_scope:"item"},{action:"close",history_scope:"item"},{action:"close-many",history_scope:"item"},{action:"close-task",history_scope:"item"},{action:"comments",history_scope:"conditional"},{action:"config",history_scope:"conditional"},{action:"copy",history_scope:"item"},{action:"create",history_scope:"item"},{action:"delete",history_scope:"item"},{action:"deps",history_scope:"conditional"},{action:"discover",history_scope:"item"},{action:"docs",history_scope:"conditional"},{action:"files",history_scope:"conditional"},{action:"focus",history_scope:"conditional"},{action:"gc",history_scope:"conditional"},{action:"history-compact",history_scope:"history"},{action:"history-author-acknowledge",history_scope:"workspace"},{action:"history-redact",history_scope:"history"},{action:"history-repair",history_scope:"history"},{action:"init",history_scope:"workspace"},{action:"install",history_scope:"conditional"},{action:"learnings",history_scope:"conditional"},{action:"notes",history_scope:"conditional"},{action:"package",history_scope:"conditional"},{action:"pause-task",history_scope:"item"},{action:"plan",history_scope:"conditional"},{action:"profile",history_scope:"conditional"},{action:"release",history_scope:"item"},{action:"restore",history_scope:"item"},{action:"schema",history_scope:"conditional"},{action:"start-task",history_scope:"item"},{action:"templates",history_scope:"conditional"},{action:"test",history_scope:"conditional"},{action:"test-all",history_scope:"conditional"},{action:"update",history_scope:"item"},{action:"update-many",history_scope:"item"},{action:"upgrade",history_scope:"conditional"}],y=new Map(D.map(e=>[e.action,e])),U=/^(?:0|[1-9]\d*)$/u,I=2**32-2;function L(e){return U.test(e)&&Number(e)<=I}function E(e){const t=[];for(const n of _){const o=G(n,e);o&&t.push({rule:n,match:o})}return t}function Y(e,t){let n=t.names.get(e);return n===void 0&&(n=E(e),t.names.set(e,n)),n}function b(e,t){let n=t.entries.get(e);return n===void 0&&(n=Array.isArray(e)?Object.getOwnPropertyNames(e).filter(L).map(o=>({name:o,value:e[Number(o)],segment:`[${o}]`,nameMatches:[]})):Object.entries(e).map(([o,r],s)=>{const i=Y(o,t);return{name:o,value:r,segment:i.length>0?`[key ${s}]`:`.${o}`,nameMatches:i}}),t.entries.set(e,n)),n}function R({rule:e,match:t},n,o){const r={rule:e.mutationRule,path:n};return o&&(r.property_name=!0),t.normalizations&&(r.normalizations=t.normalizations),t.normalization_incomplete&&(r.normalization_incomplete=!0),r}function A(e,t){for(let n=t.length-1;n>=0;n-=1)e.push(t[n])}function G(e,t){try{return K(e,t)}catch(n){return S(n)}}function S(e){if(!(e instanceof RangeError))throw e;return{index:0,normalization_incomplete:!0}}function K(e,t){const n=N(e,t),o=n.next().value;if(!o||e.mutationRule!=="absolute_home_path"||o.normalization_incomplete)return o;for(const r of n)if(r.normalization_incomplete)return{...o,normalizations:[...new Set([o.normalizations,r.normalizations].flatMap(s=>s??[]))],normalization_incomplete:!0};return o}function q(e,t){const n=[],o=new WeakSet,r=[{value:e,path:"$"}];for(let s=r.pop();s!==void 0;s=r.pop()){const{value:i,path:c}=s;if(typeof i=="string")for(const u of E(i))n.push(R(u,c,!1));else if(typeof i=="object"&&i!==null&&!o.has(i)){o.add(i);const u=b(i,t);for(const a of u)for(const l of a.nameMatches)n.push(R(l,`${c}${a.segment}`,!0));A(r,u.map(a=>({value:a.value,path:`${c}${a.segment}`})))}}return n}const f=_.filter(e=>"structured"in e),F=f.map(()=>({named:!1,exact:!1})),T=/(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/gu,X=3;function M(e){return e.replace(T,"_")}function W(e){const n=[...e.matchAll(T)].map(o=>o.index).slice(-X).map(o=>`${M(e.slice(0,o))}_${e.slice(o)}`);return[...new Set([e,M(e),...n])]}function B(e){const t=W(e);return f.map(n=>{const o=t.map(r=>z(n,r));return o.includes("exact")?"exact":o.includes("prefixed")?"prefixed":void 0})}const H=f.map(()=>{});function Z(e,t,n,o){const r=b(e,o);if(Array.isArray(e)){const s=n.map(({named:i,exact:c})=>c?"lenient":i?"compact":void 0);return r.map(i=>({value:i.value,path:`${t}${i.segment}`,contexts:n,judgments:s}))}return r.map(({name:s,value:i,segment:c})=>{const u=B(s);return{value:i,path:`${t}${c}`,contexts:n.map(({named:a,exact:l},p)=>({named:a||u[p]!==void 0,exact:l||u[p]==="exact"})),judgments:u.map((a,l)=>a==="exact"?"lenient":a==="prefixed"||n[l].named?"compact":void 0)}})}function J(e,t){const n=[],o=new WeakMap,r=[{value:e,path:"$",contexts:F,judgments:H}];for(let s=r.pop();s!==void 0;s=r.pop()){const{value:i,path:c,contexts:u,judgments:a}=s;if(typeof i=="string"){a.forEach((d,h)=>{const m=f[h];if(d===void 0)return;let g;try{g=k(m,i,d==="compact")}catch($){S($),n.push({rule:m.mutationRule,path:c,normalization_incomplete:!0});return}g&&n.push({rule:m.mutationRule,path:c})});continue}if(typeof i!="object"||i===null)continue;const l=u.map(({named:d,exact:h})=>h?"e":d?"n":"-").join(""),p=o.get(i)??new Set;p.has(l)||(o.set(i,p.add(l)),A(r,Z(i,c,u,t)))}return n}function V(e){const t=new Set,n={entries:new WeakMap,names:new Map};return[...q(e,n),...J(e,n)].filter(o=>{const r=`${o.rule}\0${o.path}\0${o.property_name===!0}`;return t.has(r)?!1:(t.add(r),!0)})}function ie(e){const t=e.author.trim()||"unknown";if(e.settings.require_attributed_author&&t.toLowerCase()==="unknown")throw new O("Mutation author is required by workspace policy.",w.USAGE,{code:"mutation_author_required",required:"Pass --author <id>, set PM_AUTHOR, or configure author_default.",nextSteps:["Retry with --author <stable-agent-id>.","Set PM_AUTHOR for this agent session."]});if(e.settings.secret_guard==="off")return{author:t,findings:[],warnings:[],override_applied:!1};let n;try{n=V(e.payload)}catch{return{author:t,findings:[],warnings:["secret_guard_scan_failed_open"],override_applied:!1}}if(n.length===0)return{author:t,findings:n,warnings:[],override_applied:!1};const o=[...new Set(n.map(r=>r.rule))].sort().join(",");if(e.settings.secret_guard==="block"&&e.force!==!0)throw new O(`Mutation blocked by secret guard (${o}). No detected value was logged.`,w.CONFLICT,{code:"mutation_secret_guard_blocked",required:"Remove the credential-shaped content or retry with --force after explicit review.",nextSteps:["Replace the value with a secret-manager reference.","Use pm history-redact if equivalent content already entered history."],recovery:{recovery_mode:"compact",attempted_command:"pm <mutation> [REDACTED]",normalized_args:["[REDACTED]"],suggested_retry:"Remove credential-shaped content, then retry the mutation."}});return{author:t,findings:n,warnings:[`secret_guard_detected:${n.length}:rules=${o}`,...e.settings.secret_guard==="block"&&e.force===!0?["secret_guard_force_override"]:[]],override_applied:e.settings.secret_guard==="block"&&e.force===!0}}const v=Object.freeze(Object.fromEntries(_.map(e=>[e.mutationRule,e.category])));function Q(e){return Object.hasOwn(v,e)?v[e]:void 0}function j(e,t){return e!==void 0&&t!==void 0&&Object.hasOwn(e,t)?e[t]:void 0}const C=new Set(Reflect.ownKeys(Object.prototype));function ee(e){const t=Reflect.ownKeys(e);if(t.length!==C.size||!t.every(o=>C.has(o)))return!1;const n=Object.getOwnPropertyDescriptor(e,"constructor")?.value;return typeof n=="function"&&Object.getOwnPropertyDescriptor(n,"prototype")?.value===e}function te(e){const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype?!0:Object.getPrototypeOf(t)!==null?!1:Reflect.ownKeys(t).length===0||ee(t)}function x(e,t){const n=Object.hasOwn(e,t)?e[t]:void 0;if(n!==void 0&&(typeof n!="object"||n===null||!te(n)))throw new TypeError(`Secret guard policy ${t} must be an object keyed by ${t==="rules"?"rule":"category"}.`);return n}function se(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw new TypeError("Secret guard policy must be an object with a default decision.");const n=Object.hasOwn(e,"default")?e.default:void 0;if(n===void 0)throw new TypeError("Secret guard policy requires a default decision.");const o=x(e,"categories"),r=x(e,"rules"),s=typeof t=="object"&&t!==null?t.rule:void 0;if(typeof s!="string")throw new TypeError("Secret guard finding must have a string rule.");const i=j(r,s);if(i!==void 0)return i;const c=j(o,Q(s));return c===void 0?n:c}function ce(e){return y.has(e.trim().toLowerCase())}function ae(){return[...y.keys()].sort((e,t)=>e.localeCompare(t))}function ue(e){return y.get(e.trim().toLowerCase())}export{D as PM_MUTATION_ACTION_CONTRACTS,v as SECRET_GUARD_RULE_CATEGORIES,se as decideSecretGuardFinding,ie as evaluateMutationGuard,ue as getMutationActionContract,ce as isMutationAction,ae as listMutationActions,V as scanMutationSecrets,Q as secretGuardRuleCategory};
|
|
2
2
|
//# sourceMappingURL=mutation-guard.js.map
|