@unbrained/pm-cli 2026.10.4 → 2026.10.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +2 -2
- package/CHANGELOG.md +37 -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.d.ts +1 -1
- package/dist/cli/commander-usage.js +7 -4
- package/dist/cli/commands/annotations/comments.js +1 -1
- package/dist/cli/commands/annotations/docs.js +1 -1
- package/dist/cli/commands/annotations/files.js +1 -1
- package/dist/cli/commands/annotations/learnings.js +1 -1
- package/dist/cli/commands/annotations/notes.js +1 -1
- package/dist/cli/commands/extension/describe.js +1 -1
- package/dist/cli/commands/extension/extension.js +1 -1
- package/dist/cli/commands/extension/scaffold.js +1 -1
- package/dist/cli/commands/extension/shared.js +1 -1
- package/dist/cli/commands/governance/gc.js +1 -1
- package/dist/cli/commands/governance/health.js +1 -1
- package/dist/cli/commands/governance/telemetry.js +1 -1
- package/dist/cli/commands/governance/validate.js +1 -1
- package/dist/cli/commands/history/activity.js +1 -1
- package/dist/cli/commands/history/history-compact.js +1 -1
- package/dist/cli/commands/history/history-redact.js +1 -1
- package/dist/cli/commands/history/history-repair.js +1 -1
- package/dist/cli/commands/history/history.js +1 -1
- package/dist/cli/commands/history/restore.js +1 -1
- package/dist/cli/commands/lifecycle/append.js +1 -1
- package/dist/cli/commands/lifecycle/claim.js +1 -1
- package/dist/cli/commands/lifecycle/close-many.js +1 -1
- package/dist/cli/commands/lifecycle/close.js +1 -1
- package/dist/cli/commands/lifecycle/copy.js +1 -1
- package/dist/cli/commands/lifecycle/create.js +1 -1
- package/dist/cli/commands/lifecycle/delete.js +1 -1
- package/dist/cli/commands/lifecycle/focus.js +1 -1
- package/dist/cli/commands/lifecycle/plan.js +1 -1
- package/dist/cli/commands/lifecycle/update-many.js +1 -1
- package/dist/cli/commands/lifecycle/update.js +1 -1
- package/dist/cli/commands/query/aggregate.js +1 -1
- package/dist/cli/commands/query/context.js +1 -1
- package/dist/cli/commands/query/deps.js +1 -1
- package/dist/cli/commands/query/duplicates.js +1 -1
- package/dist/cli/commands/query/eval.js +1 -1
- package/dist/cli/commands/query/get.js +1 -1
- package/dist/cli/commands/query/graph.js +1 -1
- package/dist/cli/commands/query/list.js +1 -1
- package/dist/cli/commands/query/next.js +1 -1
- package/dist/cli/commands/query/search.js +1 -1
- package/dist/cli/commands/query/stats.js +1 -1
- package/dist/cli/commands/test/test-all.js +1 -1
- package/dist/cli/commands/test/test-runs.js +1 -1
- package/dist/cli/commands/test/test.js +1 -1
- package/dist/cli/commands/workspace/config.js +1 -1
- package/dist/cli/commands/workspace/contracts.js +1 -1
- package/dist/cli/commands/workspace/init.js +1 -1
- package/dist/cli/commands/workspace/merge.js +1 -1
- package/dist/cli/commands/workspace/profile.js +1 -1
- package/dist/cli/commands/workspace/schema.js +1 -1
- package/dist/cli/commands/workspace/upgrade.js +1 -1
- package/dist/cli/context-intent-invocation.js +1 -1
- package/dist/cli/description-stdin.js +1 -1
- package/dist/cli/error-guidance.js +3 -1
- package/dist/cli/extension-command-help.js +5 -3
- package/dist/cli/extension-command-options.js +1 -1
- package/dist/cli/extension-recovery.js +1 -1
- package/dist/cli/help-content.js +5 -2
- package/dist/cli/help-json-payload.js +6 -3
- package/dist/cli/invocation-profile.js +2 -2
- package/dist/cli/main.js +5 -5
- package/dist/cli/migration-gates.js +1 -1
- package/dist/cli/option-values.js +1 -1
- package/dist/cli/public.js +1 -1
- package/dist/cli/register-annotations.js +1 -1
- package/dist/cli/register-assurance.js +1 -1
- package/dist/cli/register-files-lookup.js +1 -1
- package/dist/cli/register-history-activity.js +1 -1
- package/dist/cli/register-history-author.js +1 -1
- package/dist/cli/register-history-maintenance.js +2 -2
- package/dist/cli/register-list-query.js +10 -10
- package/dist/cli/register-mutation-options.js +1 -1
- package/dist/cli/register-mutation.js +2 -2
- package/dist/cli/register-operations.js +1 -1
- package/dist/cli/register-setup.js +1 -1
- package/dist/cli/register-structured-mutation.js +1 -1
- package/dist/cli/registration-helpers.js +1 -1
- package/dist/cli/runtime/activation.js +1 -1
- package/dist/cli/runtime/invocation-options.js +1 -1
- package/dist/cli/runtime/projection-retry.js +1 -1
- package/dist/cli/runtime/selection.js +1 -1
- package/dist/cli/runtime/telemetry-outcome.js +1 -1
- package/dist/cli/runtime-compatibility-boundary.js +4 -4
- package/dist/cli/schema/registration.js +2 -2
- package/dist/cli/schema-registration-helpers.js +1 -1
- package/dist/cli/search-refresh.js +1 -1
- package/dist/cli/stats-analytics-json.js +1 -1
- package/dist/cli/telemetry-flush.js +1 -1
- package/dist/cli-bundle/bundle-manifest.json +163 -163
- package/dist/cli-bundle/chunks/{chunk-SMKHR6BM.js → chunk-25EW53VO.js} +89 -88
- package/dist/cli-bundle/chunks/chunk-3CCVTV6Q.js +8 -0
- package/dist/cli-bundle/chunks/chunk-3REXBTST.js +3 -0
- package/dist/cli-bundle/chunks/chunk-4WB55TBC.js +80 -0
- package/dist/cli-bundle/chunks/{chunk-7CE2DJMA.js → chunk-6STTPXOC.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-ATB4ZZBQ.js +20 -0
- package/dist/cli-bundle/chunks/chunk-D4G43LBV.js +238 -0
- package/dist/cli-bundle/chunks/chunk-K6D6DMRT.js +31 -0
- package/dist/cli-bundle/chunks/chunk-KIRHWPZB.js +2 -0
- package/dist/cli-bundle/chunks/chunk-O67BH435.js +6 -0
- package/dist/cli-bundle/chunks/chunk-R7CG2DB7.js +2 -0
- package/dist/cli-bundle/chunks/chunk-RJHLD64E.js +3 -0
- package/dist/cli-bundle/chunks/chunk-TUKO5NF7.js +2 -0
- package/dist/cli-bundle/chunks/chunk-UZ7BIUCI.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-GZMWISWW.js → chunk-XJD47LUH.js} +3 -3
- package/dist/cli-bundle/chunks/{register-list-query-QBGXO5JJ.js → register-list-query-53WYLNZT.js} +11 -11
- package/dist/cli-bundle/chunks/register-mutation-34XXUBVI.js +20 -0
- package/dist/cli-bundle/chunks/register-operations-WANO6EIM.js +2 -0
- package/dist/cli-bundle/chunks/register-setup-WT37UPBQ.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-6KFKQD2D.js +165 -0
- package/dist/cli-bundle/focused-chunks/chunk-FOHRPFIT.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-GRQXL5G5.js +8 -0
- package/dist/cli-bundle/focused-chunks/{chunk-467EW5RL.js → chunk-JZ4WGUVH.js} +3 -3
- package/dist/cli-bundle/focused-chunks/chunk-NM3PM6O6.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-OT7HK7SG.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-Q6DJ5DFQ.js → chunk-PCLU34KB.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-HFAW3FJQ.js → chunk-PSXFFQFT.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-QQIE4L42.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-RPUNVKXK.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-RXSVJPZ7.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-SPN5QTZ3.js +30 -0
- package/dist/cli-bundle/focused-chunks/chunk-SUZJNPGB.js +6 -0
- package/dist/cli-bundle/focused-chunks/chunk-W4BG5HHS.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-Y5HXFDTZ.js +20 -0
- package/dist/cli-bundle/focused-chunks/chunk-ZK5SOOPC.js +75 -0
- package/dist/cli-bundle/focused-chunks/chunk-ZQK2XUSS.js +12 -0
- package/dist/cli-bundle/main.js +25 -25
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +2 -2
- package/dist/cli-bundle/sdk-core.js +25 -24
- package/dist/cli-bundle/sdk-governance.js +1 -1
- package/dist/cli-bundle/sdk-graph.js +1 -1
- package/dist/cli-bundle/sdk-merge.js +55 -55
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +10 -10
- package/dist/cli.js +1 -1
- package/dist/core/checkpoint/checkpoint-gc.js +1 -1
- package/dist/core/checkpoint/mutation-checkpoint.js +2 -2
- package/dist/core/config/nested-settings.js +1 -1
- package/dist/core/config/positional-value.js +1 -1
- package/dist/core/diagnostics/remediation.js +1 -1
- package/dist/core/extensions/activation-summary-markdown.js +2 -1
- package/dist/core/extensions/activation-summary.js +1 -1
- package/dist/core/extensions/activation-transaction.js +1 -1
- package/dist/core/extensions/capability-usage.js +1 -1
- package/dist/core/extensions/command-hook-context.js +1 -1
- package/dist/core/extensions/command-metadata-contract.js +1 -1
- package/dist/core/extensions/command-visibility-tier.js +1 -1
- package/dist/core/extensions/contribution-inventory.js +1 -1
- package/dist/core/extensions/exporter-output-contract.js +1 -1
- package/dist/core/extensions/extension-candidate.js +1 -1
- package/dist/core/extensions/extension-capability-aliases.js +1 -1
- package/dist/core/extensions/extension-hook-runtime.js +1 -1
- package/dist/core/extensions/extension-policy.js +1 -1
- package/dist/core/extensions/extension-registries.js +1 -1
- package/dist/core/extensions/extension-runtime-helpers.js +1 -1
- package/dist/core/extensions/extension-types.d.ts +2 -0
- package/dist/core/extensions/extension-types.js +1 -1
- package/dist/core/extensions/flag-definition-validation.js +1 -1
- package/dist/core/extensions/flag-value-types.js +1 -1
- package/dist/core/extensions/index.js +1 -1
- package/dist/core/extensions/item-field-types.js +1 -1
- package/dist/core/extensions/item-fields.js +1 -1
- package/dist/core/extensions/loader.js +1 -1
- package/dist/core/extensions/manifest-parser.js +1 -1
- package/dist/core/extensions/manifest-schema.js +1 -1
- package/dist/core/extensions/module-graph-snapshot.js +1 -1
- package/dist/core/extensions/preflight-ownership.js +1 -1
- package/dist/core/extensions/registration-contracts.js +1 -1
- package/dist/core/extensions/registration-validation.js +1 -1
- package/dist/core/extensions/registration-values.js +1 -1
- package/dist/core/extensions/reserved-host-flags.js +1 -1
- package/dist/core/extensions/runtime-registrations.js +1 -1
- package/dist/core/extensions/service-ownership.js +1 -1
- package/dist/core/extensions/version-compat.js +1 -1
- package/dist/core/fs/atomic-create.js +1 -1
- package/dist/core/fs/fs-utils.js +2 -2
- package/dist/core/fs/host-environment-errors.js +1 -1
- package/dist/core/fs/index.js +1 -1
- package/dist/core/fs/path-utils.js +1 -1
- package/dist/core/governance/content-fields.js +1 -1
- package/dist/core/governance/issue-codes.js +1 -1
- package/dist/core/governance/metadata-coverage.js +1 -1
- package/dist/core/history/digest.js +1 -1
- package/dist/core/history/drift-cache.js +3 -3
- package/dist/core/history/drift-scan.d.ts +4 -0
- package/dist/core/history/drift-scan.js +1 -1
- package/dist/core/history/event-classification.js +1 -1
- package/dist/core/history/event-index.js +8 -7
- package/dist/core/history/history-compact-bulk.js +1 -1
- package/dist/core/history/history-diff.js +1 -1
- package/dist/core/history/history-rewrite.js +1 -1
- package/dist/core/history/history-storage-stats.js +1 -1
- package/dist/core/history/history-stream-policy.js +1 -1
- package/dist/core/history/history.js +2 -2
- package/dist/core/history/identity.js +1 -1
- package/dist/core/history/index.js +1 -1
- package/dist/core/history/operation-contract.js +1 -1
- package/dist/core/history/projection.js +1 -1
- package/dist/core/history/read.js +1 -1
- package/dist/core/history/replay.js +2 -1
- package/dist/core/history/tombstone.js +1 -1
- package/dist/core/history/version-address.js +1 -1
- package/dist/core/history/workspace-history.js +2 -2
- package/dist/core/io/body-file.js +1 -1
- package/dist/core/io/bulk-ids-input.js +2 -1
- package/dist/core/item/actionability.js +1 -1
- package/dist/core/item/dependency-reference.js +1 -1
- package/dist/core/item/id.js +1 -1
- package/dist/core/item/index.js +1 -1
- package/dist/core/item/item-format-version.js +1 -1
- package/dist/core/item/item-format.js +6 -4
- package/dist/core/item/item-record.js +1 -1
- package/dist/core/item/item-type-definition.js +1 -1
- package/dist/core/item/parent-reference-policy.js +1 -1
- package/dist/core/item/parse.js +8 -2
- package/dist/core/item/plan-lifecycle.js +1 -1
- package/dist/core/item/priority.js +1 -1
- package/dist/core/item/sprint-release-format.js +1 -1
- package/dist/core/item/status-filter.js +1 -1
- package/dist/core/item/status.js +1 -1
- package/dist/core/item/toon-decode.js +1 -1
- package/dist/core/item/type-registry.js +1 -1
- package/dist/core/item/type-synonyms.js +1 -1
- package/dist/core/lock/index.js +1 -1
- package/dist/core/lock/lock-gc.js +1 -1
- package/dist/core/lock/lock.js +3 -3
- package/dist/core/output/mutation-projection.js +1 -1
- package/dist/core/output/output-control.js +1 -1
- package/dist/core/output/output.js +22 -10
- package/dist/core/output/query-summary.js +1 -1
- package/dist/core/output/tabular.js +3 -1
- package/dist/core/packages/manifest.js +1 -1
- package/dist/core/packages/root.js +1 -1
- package/dist/core/policy/workflow-policy-schema.js +1 -1
- package/dist/core/policy/workflow-policy-store.js +1 -1
- package/dist/core/policy/workflow-policy.js +1 -1
- package/dist/core/profile/profile-describe.js +1 -1
- package/dist/core/profile/profile-lint.js +1 -1
- package/dist/core/profile/profile-plan.js +1 -1
- package/dist/core/profile/profile-presets.js +25 -1
- package/dist/core/reproducibility/context.js +1 -1
- package/dist/core/schema/fields-file.js +2 -2
- package/dist/core/schema/item-types-file.js +2 -2
- package/dist/core/schema/runtime-field-filters.js +1 -1
- package/dist/core/schema/runtime-field-values.js +1 -1
- package/dist/core/schema/runtime-schema.js +2 -2
- package/dist/core/schema/status-defs-file.js +2 -2
- package/dist/core/schema/status-token.js +1 -1
- package/dist/core/schema/type-inference.js +1 -1
- package/dist/core/schema/type-presets.js +1 -1
- package/dist/core/schema/type-workflows.js +1 -1
- package/dist/core/search/background-refresh.js +2 -2
- package/dist/core/search/bm25.js +1 -1
- package/dist/core/search/cache.js +2 -2
- package/dist/core/search/corpus.js +1 -1
- package/dist/core/search/embedding-batches.js +1 -1
- package/dist/core/search/eval-thresholds.js +1 -1
- package/dist/core/search/eval.js +1 -1
- package/dist/core/search/http-client.js +1 -1
- package/dist/core/search/providers.js +1 -1
- package/dist/core/search/relevance.js +1 -1
- package/dist/core/search/semantic-defaults.js +1 -1
- package/dist/core/search/staleness.js +1 -1
- package/dist/core/search/vector-stores.js +2 -2
- package/dist/core/search/vectorization-metadata.js +1 -1
- package/dist/core/sentry/helpers.js +1 -1
- package/dist/core/sentry/instrument.js +1 -1
- package/dist/core/session/session-state.js +1 -1
- package/dist/core/shared/agent-session-context.js +1 -1
- package/dist/core/shared/author.js +5 -1
- package/dist/core/shared/command-line.js +1 -1
- package/dist/core/shared/command-types.js +1 -1
- package/dist/core/shared/conflict-markers.js +1 -1
- package/dist/core/shared/constants.js +1 -1
- package/dist/core/shared/errors.js +1 -1
- package/dist/core/shared/html-entity-decode.js +1 -1
- package/dist/core/shared/index.js +1 -1
- package/dist/core/shared/item-metadata-contract.js +1 -1
- package/dist/core/shared/lazy-module.js +1 -1
- package/dist/core/shared/levenshtein.js +1 -1
- package/dist/core/shared/memo.js +1 -1
- package/dist/core/shared/numeric-parsers.js +1 -1
- package/dist/core/shared/option-alias-visibility.js +1 -1
- package/dist/core/shared/primitives.js +1 -1
- package/dist/core/shared/secret-rules.js +1 -1
- package/dist/core/shared/serial-queue.js +1 -1
- package/dist/core/shared/serialization.js +1 -1
- package/dist/core/shared/split-comma-list.js +1 -1
- package/dist/core/shared/text-normalization.js +1 -1
- package/dist/core/shared/time.js +2 -1
- package/dist/core/store/index.js +1 -1
- package/dist/core/store/item-format-migration.js +1 -1
- package/dist/core/store/item-metadata-cache.js +1 -1
- package/dist/core/store/item-metadata-query-index.js +7 -7
- package/dist/core/store/item-metadata-read-work.js +1 -1
- package/dist/core/store/item-store.js +1 -1
- package/dist/core/store/paths.js +1 -1
- package/dist/core/store/settings-concurrency.js +1 -1
- package/dist/core/store/settings-read-cache.js +1 -1
- package/dist/core/store/settings-validator.js +1 -1
- package/dist/core/store/settings.js +3 -3
- package/dist/core/store/tracker-preflight.js +1 -1
- package/dist/core/telemetry/consent.js +2 -2
- package/dist/core/telemetry/observability.js +1 -1
- package/dist/core/telemetry/policy.js +1 -1
- package/dist/core/telemetry/read-sampling.js +2 -2
- package/dist/core/telemetry/runtime.js +9 -5
- package/dist/core/test/background-runs.js +3 -3
- package/dist/core/test/item-test-run-tracking.js +1 -1
- package/dist/core/test/run-selectors.js +1 -1
- package/dist/core/validate/estimate-defaults.js +1 -1
- package/dist/core/validate/fix-planning.js +1 -1
- package/dist/core/validate/linked-artifact-reference.js +1 -1
- package/dist/core/validate/missing-by-type.js +1 -1
- package/dist/core/validate/missing-link-owners.js +1 -1
- package/dist/core/validate/stale-file-classification.js +1 -1
- package/dist/mcp/http-server.js +6 -4
- package/dist/mcp/legacy-adapter.js +1 -1
- package/dist/mcp/runtime-capabilities.js +1 -1
- package/dist/mcp/server.js +4 -4
- package/dist/mcp/tool-definitions.js +1 -1
- package/dist/sdk/actionability.js +1 -1
- package/dist/sdk/agent/closed-domain-contracts.js +1 -1
- package/dist/sdk/agent/command-recovery.js +1 -1
- package/dist/sdk/agent/command-suggestions.js +1 -1
- package/dist/sdk/agent/create-option-policy.js +1 -1
- package/dist/sdk/agent/identity-config.js +1 -1
- package/dist/sdk/agent/item-addressing.js +1 -1
- package/dist/sdk/agent/refusal-closure-census.js +2 -1
- package/dist/sdk/agent/refusal-closure.js +1 -1
- package/dist/sdk/agent/refusal-corpus-contracts.js +1 -1
- package/dist/sdk/agent/refusal-reachability.js +3 -1
- package/dist/sdk/agent/subcommand-recovery.js +1 -1
- package/dist/sdk/agent/task-transcript-contracts.js +1 -1
- package/dist/sdk/agent/tracker-preflight-contracts.js +1 -1
- package/dist/sdk/agent-capability-contracts.js +3 -1
- package/dist/sdk/agent-session-context.js +1 -1
- package/dist/sdk/annotations.js +1 -1
- package/dist/sdk/author-attribution.js +1 -1
- package/dist/sdk/authoring.js +1 -1
- package/dist/sdk/cli-bootstrap.d.ts +5 -1
- package/dist/sdk/cli-bootstrap.js +1 -1
- package/dist/sdk/cli-contracts/agent-output-contracts.js +5 -3
- package/dist/sdk/cli-contracts/bootstrap-command-scanner.js +1 -1
- package/dist/sdk/cli-contracts/command-aliases.js +1 -1
- package/dist/sdk/cli-contracts/command-exit-contracts.js +1 -1
- package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1
- package/dist/sdk/cli-contracts/commander-types.js +1 -1
- package/dist/sdk/cli-contracts/completeness.js +1 -1
- package/dist/sdk/cli-contracts/enum-contracts.js +1 -1
- package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
- package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +2 -1
- package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
- package/dist/sdk/cli-contracts/registration-helpers.js +7 -7
- package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
- package/dist/sdk/cli-contracts/schemas/assurance-definition.js +1 -1
- package/dist/sdk/cli-contracts/string-lists.js +1 -1
- package/dist/sdk/cli-contracts/tool-option-contracts.js +1 -1
- package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
- package/dist/sdk/cli-contracts/tool-schema.d.ts +2 -2
- package/dist/sdk/cli-contracts/tool-schema.js +1 -1
- package/dist/sdk/cli-contracts/typed-action-inputs.js +1 -1
- package/dist/sdk/cli-contracts.js +1 -1
- package/dist/sdk/cli-program.js +1 -1
- package/dist/sdk/command-line.js +1 -1
- package/dist/sdk/comments.js +1 -1
- package/dist/sdk/compile-cache.js +1 -1
- package/dist/sdk/completion/bash.js +2 -1
- package/dist/sdk/completion/fish.js +13 -7
- package/dist/sdk/completion/shared.js +1 -1
- package/dist/sdk/completion/zsh.js +14 -8
- package/dist/sdk/completion.js +1 -1
- package/dist/sdk/compose.js +1 -1
- package/dist/sdk/config.js +1 -1
- package/dist/sdk/context/recency.js +1 -1
- package/dist/sdk/context/semantic-session-attribution.js +1 -1
- package/dist/sdk/context/usage-egress.js +1 -1
- package/dist/sdk/context/usage-ledger.js +6 -3
- package/dist/sdk/context-intent-contracts.js +1 -1
- package/dist/sdk/context-intent-runtime.js +1 -1
- package/dist/sdk/context-packing.js +1 -1
- package/dist/sdk/context-relevance.js +1 -1
- package/dist/sdk/context-signal-store.js +2 -2
- package/dist/sdk/context-usage.js +1 -1
- package/dist/sdk/contracts.js +1 -1
- package/dist/sdk/core-governance.js +1 -1
- package/dist/sdk/core.js +1 -1
- package/dist/sdk/corpus-shape.js +1 -1
- package/dist/sdk/define.js +1 -1
- package/dist/sdk/dependencies.js +1 -1
- package/dist/sdk/dependency-flag-validation.js +1 -1
- package/dist/sdk/dependency-provenance.js +1 -1
- package/dist/sdk/docs.js +1 -1
- package/dist/sdk/duplicates.js +1 -1
- package/dist/sdk/environment/agent-environment.js +1 -1
- package/dist/sdk/environment/host-environment-errors.js +1 -1
- package/dist/sdk/environment/project-runtime-compatibility.js +2 -1
- package/dist/sdk/environment/source-context.js +1 -1
- package/dist/sdk/environment/tracker-preflight.js +1 -1
- package/dist/sdk/error-code-catalog.js +1 -1
- package/dist/sdk/error-runtime.js +1 -1
- package/dist/sdk/errors.js +1 -1
- package/dist/sdk/eval.js +1 -1
- package/dist/sdk/extension/author-manifest.js +1 -1
- package/dist/sdk/extension/bundled-catalog.js +1 -1
- package/dist/sdk/extension/concurrency.js +1 -1
- package/dist/sdk/extension/copy-scope.js +1 -1
- package/dist/sdk/extension/custom-field-collisions.js +1 -1
- package/dist/sdk/extension/describe.js +4 -2
- package/dist/sdk/extension/doctor.js +1 -1
- package/dist/sdk/extension/install-plan.js +1 -1
- package/dist/sdk/extension/install-receipts.js +1 -1
- package/dist/sdk/extension/install-runtime.js +3 -3
- package/dist/sdk/extension/install-snapshot.js +1 -1
- package/dist/sdk/extension/install-sources.js +5 -5
- package/dist/sdk/extension/managed-state.d.ts +2 -0
- package/dist/sdk/extension/managed-state.js +2 -2
- package/dist/sdk/extension/managed-update-status.d.ts +3 -0
- package/dist/sdk/extension/managed-update-status.js +2 -0
- package/dist/sdk/extension/migrations.js +2 -2
- package/dist/sdk/extension/output-ownership.js +1 -1
- package/dist/sdk/extension/runtime-summary.js +1 -1
- package/dist/sdk/extension/scaffold.js +11 -4
- package/dist/sdk/extension/shared.js +1 -1
- package/dist/sdk/extension/source-resolution.d.ts +2 -6
- package/dist/sdk/extension/source-resolution.js +1 -1
- package/dist/sdk/extension/static-inventory.js +1 -1
- package/dist/sdk/extension/update-check.d.ts +10 -0
- package/dist/sdk/extension/update-check.js +1 -1
- package/dist/sdk/extension-command-context.js +2 -1
- package/dist/sdk/extension-contracts.js +1 -1
- package/dist/sdk/extension.d.ts +4 -0
- package/dist/sdk/extension.js +1 -1
- package/dist/sdk/files.js +1 -1
- package/dist/sdk/flag-invocation-contracts.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
- package/dist/sdk/generated-error-code-catalog.js +1 -1
- package/dist/sdk/governance/assurance-action-contracts.js +1 -1
- package/dist/sdk/governance/assurance-action.js +1 -1
- package/dist/sdk/governance/assurance-limits.js +1 -1
- package/dist/sdk/governance/assurance-mutation-error.js +1 -1
- package/dist/sdk/governance/assurance-presets.js +1 -1
- package/dist/sdk/governance/assurance-runtime.js +1 -1
- package/dist/sdk/governance/assurance.js +4 -4
- package/dist/sdk/governance/boundary-fixtures.js +1 -1
- package/dist/sdk/governance/closure-timestamps.js +1 -1
- package/dist/sdk/governance/coverage-assurance.js +1 -1
- package/dist/sdk/governance/defect-recurrence-coverage.js +1 -1
- package/dist/sdk/governance/defect-recurrence-graph.js +1 -1
- package/dist/sdk/governance/defect-recurrence-signals.js +1 -1
- package/dist/sdk/governance/defect-recurrence.js +1 -1
- package/dist/sdk/governance/extension-host-version.js +1 -1
- package/dist/sdk/governance/gc.js +1 -1
- package/dist/sdk/governance/health-merge-evidence.js +1 -1
- package/dist/sdk/governance/health.js +2 -1
- package/dist/sdk/governance/hierarchy-validation.js +1 -1
- package/dist/sdk/governance/linked-file-report.js +1 -1
- package/dist/sdk/governance/merge-receipt-history.js +1 -1
- package/dist/sdk/governance/provenance-health.js +4 -1
- package/dist/sdk/governance/reindex.js +5 -4
- package/dist/sdk/governance/stale-work.js +1 -1
- package/dist/sdk/governance/status-role-diagnostics.js +1 -1
- package/dist/sdk/governance/storage-integrity.js +1 -1
- package/dist/sdk/governance/tracked-runtime-cache.js +1 -1
- package/dist/sdk/governance/upgrade.js +2 -2
- package/dist/sdk/governance/validate-history-drift.js +1 -1
- package/dist/sdk/governance/validate-item-reader.js +1 -1
- package/dist/sdk/governance/validate-normalization.js +1 -1
- package/dist/sdk/governance/validate.js +1 -1
- package/dist/sdk/governance/workflow-completeness.js +1 -1
- package/dist/sdk/governance/workflow-policy.js +3 -3
- package/dist/sdk/governance/workspace-position.js +2 -1
- package/dist/sdk/governance.js +1 -1
- package/dist/sdk/graph/adapter.js +1 -1
- package/dist/sdk/graph/analytics.js +1 -1
- package/dist/sdk/graph/assembly.js +1 -1
- package/dist/sdk/graph/cache.js +1 -1
- package/dist/sdk/graph/centrality.js +1 -1
- package/dist/sdk/graph/conformance.js +1 -1
- package/dist/sdk/graph/deadline-scheduling.js +1 -1
- package/dist/sdk/graph/durable-cache.js +1 -1
- package/dist/sdk/graph/governance-contracts.js +1 -1
- package/dist/sdk/graph/governance.js +1 -1
- package/dist/sdk/graph/hierarchy-integrity.js +1 -1
- package/dist/sdk/graph/index.js +1 -1
- package/dist/sdk/graph/lifecycle-coverage.js +1 -1
- package/dist/sdk/graph/mutation-advisory.js +1 -1
- package/dist/sdk/graph/query-contracts.js +1 -1
- package/dist/sdk/graph/remediation.js +1 -1
- package/dist/sdk/graph/run.js +1 -1
- package/dist/sdk/graph/scheduling.js +1 -1
- package/dist/sdk/graph/traversal.js +1 -1
- package/dist/sdk/graph/workspace-relationship-kind-registry.js +1 -1
- package/dist/sdk/graph.js +1 -1
- package/dist/sdk/guide-topics.js +1 -1
- package/dist/sdk/guide.js +8 -1
- package/dist/sdk/history/attestation-command.js +1 -1
- package/dist/sdk/history/attestation-contract.js +1 -1
- package/dist/sdk/history/attestation-scan.js +1 -1
- package/dist/sdk/history/attestation.js +1 -1
- package/dist/sdk/history/maintenance.js +1 -1
- package/dist/sdk/history/salvage.js +3 -2
- package/dist/sdk/history/subject.js +1 -1
- package/dist/sdk/history-analytics.js +1 -1
- package/dist/sdk/history-compact.js +1 -1
- package/dist/sdk/history-mcp.js +1 -1
- package/dist/sdk/history-provenance.js +1 -1
- package/dist/sdk/history-read.js +1 -1
- package/dist/sdk/history-redact.js +1 -1
- package/dist/sdk/history-repair.js +1 -1
- package/dist/sdk/improvement-ledger-validation.js +1 -1
- package/dist/sdk/improvement-ledger.js +2 -2
- package/dist/sdk/index.js +1 -1
- package/dist/sdk/init-agent-guidance.js +16 -2
- package/dist/sdk/init.js +16 -2
- package/dist/sdk/invocation-author.js +1 -1
- package/dist/sdk/item-children.js +1 -1
- package/dist/sdk/item-metadata-index.js +1 -1
- package/dist/sdk/item-schedule.js +1 -1
- package/dist/sdk/item-transaction.js +1 -1
- package/dist/sdk/learnings.js +1 -1
- package/dist/sdk/lifecycle/append.js +4 -2
- package/dist/sdk/lifecycle/claim.js +1 -1
- package/dist/sdk/lifecycle/close-many.js +1 -1
- package/dist/sdk/lifecycle/close.js +1 -1
- package/dist/sdk/lifecycle/copy.js +1 -1
- package/dist/sdk/lifecycle/create.js +1 -1
- package/dist/sdk/lifecycle/delete.js +1 -1
- package/dist/sdk/lifecycle/event-validation-messages.js +1 -1
- package/dist/sdk/lifecycle/focus.js +1 -1
- package/dist/sdk/lifecycle/hierarchy-mutation-lock.js +1 -1
- package/dist/sdk/lifecycle/legacy-none-tokens.js +1 -1
- package/dist/sdk/lifecycle/lifecycle-transitions.js +1 -1
- package/dist/sdk/lifecycle/mcp-actions.js +1 -1
- package/dist/sdk/lifecycle/metadata-normalizers.js +1 -1
- package/dist/sdk/lifecycle/mutation-command-options.js +1 -1
- package/dist/sdk/lifecycle/plan-mutation-receipt.js +1 -1
- package/dist/sdk/lifecycle/plan.js +1 -1
- package/dist/sdk/lifecycle/recurrence-parsers.js +1 -1
- package/dist/sdk/lifecycle/reopen.js +1 -1
- package/dist/sdk/lifecycle/repeatable-metadata-parsers.js +2 -1
- package/dist/sdk/lifecycle/restore.js +1 -1
- package/dist/sdk/lifecycle/shared-unset-fields.js +1 -1
- package/dist/sdk/lifecycle/task-composition.js +1 -1
- package/dist/sdk/lifecycle/update-many.js +1 -1
- package/dist/sdk/lifecycle/update.js +2 -1
- package/dist/sdk/lifecycle-completion.js +1 -1
- package/dist/sdk/lifecycle-policy.js +1 -1
- package/dist/sdk/linked-artifacts.js +2 -1
- package/dist/sdk/mcp/apps.js +1 -1
- package/dist/sdk/mcp/authorization.js +1 -1
- package/dist/sdk/mcp/discovery.js +1 -1
- package/dist/sdk/mcp/interactions.js +1 -1
- package/dist/sdk/mcp/protocol.js +1 -1
- package/dist/sdk/mcp/skills.js +3 -1
- package/dist/sdk/mcp/subscriptions.js +1 -1
- package/dist/sdk/mcp/tasks.js +2 -2
- package/dist/sdk/mcp/transport.js +1 -1
- package/dist/sdk/merge/abandoned-receipts.js +1 -1
- package/dist/sdk/merge/driver.js +1 -1
- package/dist/sdk/merge/index.js +1 -1
- package/dist/sdk/merge/install.js +4 -2
- package/dist/sdk/merge/receipt-file-boundary.js +1 -1
- package/dist/sdk/merge/receipt-operation.js +1 -1
- package/dist/sdk/merge/receipt-schema.js +1 -1
- package/dist/sdk/merge/receipts.js +4 -4
- package/dist/sdk/merge/reconcile.js +1 -1
- package/dist/sdk/merge/three-way.js +3 -2
- package/dist/sdk/merge/worktree-config.js +1 -1
- package/dist/sdk/merge.js +1 -1
- package/dist/sdk/mutation-events.js +1 -1
- package/dist/sdk/mutation-guard.js +1 -1
- package/dist/sdk/notes.js +1 -1
- package/dist/sdk/output-contracts.js +1 -1
- package/dist/sdk/output-projection.js +1 -1
- package/dist/sdk/output-token-accounting.js +1 -1
- package/dist/sdk/output.js +2 -1
- package/dist/sdk/ownership-source.js +1 -1
- package/dist/sdk/package-import-adapters.js +1 -1
- package/dist/sdk/package-migrations.js +1 -1
- package/dist/sdk/package-runtime-options.js +1 -1
- package/dist/sdk/pagination.js +1 -1
- package/dist/sdk/profile.js +5 -1
- package/dist/sdk/provenance.js +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/query/activity.js +1 -1
- package/dist/sdk/query/aggregate.js +1 -1
- package/dist/sdk/query/calendar.js +4 -1
- package/dist/sdk/query/complete-list.js +1 -1
- package/dist/sdk/query/context.js +2 -1
- package/dist/sdk/query/duplicate-candidates.js +1 -1
- package/dist/sdk/query/get.d.ts +14 -2
- package/dist/sdk/query/get.js +1 -1
- package/dist/sdk/query/history.js +1 -1
- package/dist/sdk/query/item-filter-options.js +1 -1
- package/dist/sdk/query/light-metadata.js +1 -1
- package/dist/sdk/query/list-filter-shared.js +1 -1
- package/dist/sdk/query/list.js +1 -1
- package/dist/sdk/query/multi-value-filters.js +1 -1
- package/dist/sdk/query/next-ready-budget.js +1 -1
- package/dist/sdk/query/next.js +2 -1
- package/dist/sdk/query/parsers.js +1 -1
- package/dist/sdk/query/projection-contracts.js +1 -1
- package/dist/sdk/query/search/corpus.js +2 -1
- package/dist/sdk/query/search/filters.js +1 -1
- package/dist/sdk/query/search/input.js +1 -1
- package/dist/sdk/query/search/lexical.js +1 -1
- package/dist/sdk/query/search/response.js +1 -1
- package/dist/sdk/query/search/semantic.js +3 -2
- package/dist/sdk/query/search/types.js +1 -1
- package/dist/sdk/query/search-contracts.js +1 -1
- package/dist/sdk/query/search-pagination.js +1 -1
- package/dist/sdk/query/search-rendering.js +1 -1
- package/dist/sdk/query/search.js +1 -1
- package/dist/sdk/query/workspace-contracts.js +1 -1
- package/dist/sdk/query.js +1 -1
- package/dist/sdk/read-output/continuation.js +1 -1
- package/dist/sdk/read-output/options.js +1 -1
- package/dist/sdk/read-output/provenance.js +1 -1
- package/dist/sdk/read-output-budget.js +1 -1
- package/dist/sdk/read-output-contracts.js +1 -1
- package/dist/sdk/read-output-rows.js +1 -1
- package/dist/sdk/read-output-session.js +1 -1
- package/dist/sdk/relationship-analytics.js +1 -1
- package/dist/sdk/relationship-context.js +1 -1
- package/dist/sdk/relationship-history.js +7 -4
- package/dist/sdk/relationship-kinds/contract.js +1 -1
- package/dist/sdk/relationship-migration.js +1 -1
- package/dist/sdk/relationships.js +1 -1
- package/dist/sdk/reproducibility/process.js +1 -1
- package/dist/sdk/runtime/actions.js +1 -1
- package/dist/sdk/runtime/context.js +1 -1
- package/dist/sdk/runtime/schema-preview.js +1 -1
- package/dist/sdk/runtime/schema.js +1 -1
- package/dist/sdk/runtime-action-aliases.js +1 -1
- package/dist/sdk/runtime-extended-actions.js +1 -1
- package/dist/sdk/runtime-input.js +1 -1
- package/dist/sdk/runtime-primitives.js +1 -1
- package/dist/sdk/runtime-public-contracts.js +1 -1
- package/dist/sdk/runtime-stats-options.js +1 -1
- package/dist/sdk/runtime.js +1 -1
- package/dist/sdk/scheduling-shortcuts.js +1 -1
- package/dist/sdk/schema-migration.js +4 -3
- package/dist/sdk/schema.js +7 -1
- package/dist/sdk/search-refresh-worker.js +1 -1
- package/dist/sdk/similarity-scoring.js +1 -1
- package/dist/sdk/similarity.js +1 -1
- package/dist/sdk/start-task-status.js +1 -1
- package/dist/sdk/stats.js +1 -1
- package/dist/sdk/structured-mutations.js +1 -1
- package/dist/sdk/telemetry-flush.js +1 -1
- package/dist/sdk/telemetry.js +4 -3
- package/dist/sdk/templates.js +26 -2
- package/dist/sdk/test/batch.js +2 -2
- package/dist/sdk/test/entry.js +1 -1
- package/dist/sdk/test/execution.d.ts +2 -1
- package/dist/sdk/test/execution.js +6 -5
- package/dist/sdk/test/json-path.js +1 -1
- package/dist/sdk/test/linked-command-detection.js +1 -1
- package/dist/sdk/test/measurements.js +1 -1
- package/dist/sdk/test/parsers.js +1 -1
- package/dist/sdk/test/runs.js +1 -1
- package/dist/sdk/test/trust.js +2 -2
- package/dist/sdk/test/workspace-snapshot.js +1 -1
- package/dist/sdk/testing.js +7 -4
- package/dist/sdk/traceability/runtime-files-lookup.js +1 -1
- package/dist/sdk/traceability/source-traceability.js +2 -1
- package/dist/sdk/tracker-root-discovery.js +1 -1
- package/dist/sdk/workspace-contracts-cache.js +1 -1
- package/dist/sdk/workspace-contracts.js +1 -1
- package/dist/sdk/workspace-memory.js +2 -2
- package/dist/sdk/workspace-recipe.js +1 -1
- package/dist/sdk/workspace-snapshot.js +5 -4
- package/dist/sdk/workspace-transaction-gc.js +1 -1
- package/dist/sdk/workspace-transaction.js +2 -2
- package/dist/sdk/workspace.js +3 -2
- package/dist/types/index.js +1 -1
- package/dist/types.js +1 -1
- package/docs/AGENT_EVIDENCE_CONSISTENCY.md +88 -0
- package/docs/DEVELOPMENT_DEPENDENCY_SECURITY.md +36 -0
- package/docs/GET_READ_EVIDENCE.md +84 -0
- package/docs/OUTPUT_PROJECTION_CONTRACTS.md +23 -0
- package/docs/PR_REVIEW_LOOP.md +21 -4
- package/docs/README.md +3 -0
- package/docs/RELEASING.md +18 -0
- package/docs/SDK_CONFIGURATION_SAFETY.md +123 -0
- package/docs/generated/FLAG_LEXICON_BUDGETS.md +3 -3
- package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +4 -3
- package/marketplace.json +2 -2
- package/package.json +3 -3
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/extensions/vcs/index.ts +4 -2
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-claude/package.json +2 -2
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/plugins/pm-codex/package.json +2 -2
- package/plugins/pm-codex/plugin.json +1 -1
- package/scripts/finalize-build.mjs +3 -2
- package/dist/cli-bundle/chunks/chunk-7UVXKI7K.js +0 -2
- package/dist/cli-bundle/chunks/chunk-D7Z2ZMJL.js +0 -3
- package/dist/cli-bundle/chunks/chunk-DEZPZOQ7.js +0 -2
- package/dist/cli-bundle/chunks/chunk-J52QIRRZ.js +0 -80
- package/dist/cli-bundle/chunks/chunk-JDKD3WGG.js +0 -6
- package/dist/cli-bundle/chunks/chunk-JQ7DW663.js +0 -2
- package/dist/cli-bundle/chunks/chunk-QXIDOOWT.js +0 -20
- package/dist/cli-bundle/chunks/chunk-SGFQQXFD.js +0 -2
- package/dist/cli-bundle/chunks/chunk-V3U77H3V.js +0 -31
- package/dist/cli-bundle/chunks/chunk-XZDWAYJC.js +0 -3
- package/dist/cli-bundle/chunks/chunk-Y6VRBTP3.js +0 -238
- package/dist/cli-bundle/chunks/chunk-YAAFYFS4.js +0 -8
- package/dist/cli-bundle/chunks/register-mutation-53ZLT4RX.js +0 -20
- package/dist/cli-bundle/chunks/register-operations-OBK2FXUU.js +0 -2
- package/dist/cli-bundle/chunks/register-setup-HM3OCBH2.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-2JFYR56O.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-32EVUSS4.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-5GUSO2P4.js +0 -20
- package/dist/cli-bundle/focused-chunks/chunk-6XBRADQQ.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-7O4NUJVO.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-CURTIIQT.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-IJUWEEEB.js +0 -6
- package/dist/cli-bundle/focused-chunks/chunk-JCVMOSWQ.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-JMJK2L4Z.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-KG3H4UZZ.js +0 -30
- package/dist/cli-bundle/focused-chunks/chunk-MHQ2XICU.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-RJV6QVJE.js +0 -75
- package/dist/cli-bundle/focused-chunks/chunk-ZE2JZ7R6.js +0 -12
- package/dist/cli-bundle/focused-chunks/chunk-ZLEN4HZD.js +0 -165
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="8c02324c-231c-54ae-8edb-256ac7e04b50")}catch(e2){}})();import jsonPatch from"fast-json-patch";import{normalizeHistoryOperationForWrite}from"./operation-contract.js";import{CURRENT_HISTORY_HASH_ALGORITHM,historyDigest,resolveHistoryHashAlgorithm}from"./digest.js";import fs from"node:fs/promises";import path from"node:path";import{EXIT_CODE,ITEM_METADATA_KEY_ORDER}from"../shared/constants.js";import{runActiveServiceOverride}from"../extensions/index.js";import{appendLineAtomic}from"../fs/fs-utils.js";import{canonicalDocument}from"../item/item-format.js";import{toItemRecord}from"../item/item-record.js";import{orderObject,sha256Hex,stableStringify}from"../shared/serialization.js";import{isMillisecondPrecisionRfc3339DateTime,nowIso}from"../shared/time.js";import{diagnoseAgentIdentity,resolveHistoryAgentIdentity,resolveHistoryAuthorSource}from"../shared/author.js";import{appendHistoryEntryWithEventIndex,removeHistoryEventIndexForHistoryPath}from"./event-index.js";import{classifyHistoryEvent}from"./event-classification.js";import{invalidateHistoryDriftCacheForPath}from"./drift-cache.js";import{PmCliError}from"../shared/errors.js";const EMPTY_LEGACY_HASH_DOCUMENT={front_matter:{},body:""};const CURRENT_HISTORY_ITEM_HASH_VERSION=3;const SUPPORTED_HISTORY_ITEM_HASH_VERSIONS=[1,2,3];const CURRENT_HISTORY_RECORD_HASH_VERSION=1;const SUPPORTED_HISTORY_RECORD_HASH_VERSIONS=[1];function hashHistoryRecord(entry){return historyDigest(stableStringify(entry),entry.hash_algorithm)}function hashHistoryPatch(patch){return sha256Hex(stableStringify(patch))}function hashHistoryStream(entries){return sha256Hex(stableStringify(entries))}function sealHistoryRecord(entry){const sealed={...entry,record_hash_version:CURRENT_HISTORY_RECORD_HASH_VERSION};const{record_hash:_recordHash,...canonical}=sealed;return{...sealed,record_hash:hashHistoryRecord(canonical)}}function verifyHistoryRecordHash(entry){try{resolveHistoryHashAlgorithm(entry.hash_algorithm)}catch{return{ok:false,error:"unsupported_history_hash_algorithm"}}if(entry.record_hash_version===void 0&&entry.record_hash===void 0){return{ok:true,coverage:"item_state_only"}}if(entry.record_hash_version===void 0||entry.record_hash===void 0){return{ok:false,error:"incomplete_record_hash_envelope"}}if(!SUPPORTED_HISTORY_RECORD_HASH_VERSIONS.includes(entry.record_hash_version)){return{ok:false,error:"unsupported_record_hash_version"}}const{record_hash:_recordHash,...canonical}=entry;return hashHistoryRecord(canonical)===entry.record_hash?{ok:true,coverage:"record_and_item_state"}:{ok:false,error:"record_hash_mismatch"}}function createHistoryRewriteEvidence(original,options){const evidence={before_hash:original.before_hash,after_hash:original.after_hash,patch_hash:hashHistoryPatch(original.patch)};if(original.hash_algorithm!==void 0)evidence.hash_algorithm=original.hash_algorithm;if(original.item_hash_version!==void 0){evidence.item_hash_version=original.item_hash_version}if(options.retainOriginalPatch){evidence.patch=structuredClone(original.patch)}if(options.retainPriorRecordHash!==false&&original.record_hash_version!==void 0&&original.record_hash!==void 0){evidence.record_hash_version=original.record_hash_version;evidence.record_hash=original.record_hash;evidence.record=structuredClone(original)}return evidence}function resealHistoryRewrite(original,rewritten,options={}){const originalRecordVerification=verifyHistoryRecordHash(original);if(!originalRecordVerification.ok){throw new TypeError(originalRecordVerification.error)}const originalPatchHash=hashHistoryPatch(original.patch);const retainsRewriteEvidence=options.retainPriorRecord===true||original.before_hash!==rewritten.before_hash||original.after_hash!==rewritten.after_hash||original.item_hash_version!==rewritten.item_hash_version||original.hash_algorithm!==rewritten.hash_algorithm||originalPatchHash!==hashHistoryPatch(rewritten.patch);const sealed=sealHistoryRecord({...rewritten,...retainsRewriteEvidence?{reanchor_evidence:[...rewritten.reanchor_evidence??[],createHistoryRewriteEvidence(original,options)]}:{}});const evidenceVerification=verifyHistoryRewriteEvidence(sealed);if(!evidenceVerification.ok){throw new TypeError(evidenceVerification.error)}return sealed}function isHistoryPatch(value){if(!Array.isArray(value)||Object.keys(value).length!==value.length){return false}return value.every(operation=>{if(!isRecord(operation)||typeof operation.path!=="string"){return false}if(operation.op==="move"||operation.op==="copy"){return typeof operation.from==="string"}if(["add","replace","test"].includes(operation.op)){return Object.hasOwn(operation,"value")}return operation.op==="remove"})}function isRetainedHistoryRecordShape(value){return isRecord(value)&&typeof value.ts==="string"&&typeof value.author==="string"&&typeof value.op==="string"&&typeof value.before_hash==="string"&&typeof value.after_hash==="string"&&isHistoryPatch(value.patch)}function hasCompleteRetainedRecordHashEnvelope(evidence){const hasVersion=evidence.record_hash_version!==void 0;const hasHash=evidence.record_hash!==void 0;return hasVersion===hasHash}function isHistoryReanchorEvidence(evidence){if(!isRecord(evidence)||!hasCompleteRetainedRecordHashEnvelope(evidence)||typeof evidence.before_hash!=="string"||typeof evidence.after_hash!=="string"||typeof evidence.patch_hash!=="string"||!/^[a-f0-9]{64}$/u.test(evidence.patch_hash)||evidence.patch!==void 0&&!isHistoryPatch(evidence.patch)||evidence.record_hash_version!==void 0&&typeof evidence.record_hash_version!=="number"||evidence.record_hash!==void 0&&(typeof evidence.record_hash!=="string"||!/^(?:[a-f0-9]{64}|[a-f0-9]{128})$/u.test(evidence.record_hash))){return false}return evidence.record===void 0||isRetainedHistoryRecordShape(evidence.record)}function isHistoryRewriteEvidenceList(evidenceEntries){try{for(const evidence of evidenceEntries){if(!isHistoryReanchorEvidence(evidence))return false;resolveHistoryHashAlgorithm(evidence.hash_algorithm)}return true}catch{return false}}function matchesRetainedHistoryRecord(evidence){const record=evidence.record;return record!==void 0&&record.before_hash===evidence.before_hash&&record.after_hash===evidence.after_hash&&record.item_hash_version===evidence.item_hash_version&&record.hash_algorithm===evidence.hash_algorithm&&record.record_hash_version===evidence.record_hash_version&&record.record_hash===evidence.record_hash&&hashHistoryPatch(record.patch)===evidence.patch_hash}function reconstructPriorHistoryRecord(current,evidence,priorEvidence){if(evidence.patch&&hashHistoryPatch(evidence.patch)!==evidence.patch_hash){return{kind:"patch_hash_mismatch"}}if(evidence.record){if(!matchesRetainedHistoryRecord(evidence)){return{kind:"record_hash_mismatch"}}return{kind:"record",entry:evidence.record}}const priorPatch=evidence.patch??current.patch;if(hashHistoryPatch(priorPatch)!==evidence.patch_hash){return{kind:"digest_only"}}const priorRecord={...current,before_hash:evidence.before_hash,after_hash:evidence.after_hash,patch:priorPatch,hash_algorithm:evidence.hash_algorithm,...evidence.item_hash_version===void 0?{}:{item_hash_version:evidence.item_hash_version},...evidence.record_hash_version===void 0?{}:{record_hash_version:evidence.record_hash_version},...evidence.record_hash===void 0?{}:{record_hash:evidence.record_hash},...priorEvidence.length===0?{}:{reanchor_evidence:priorEvidence}};if(evidence.hash_algorithm===void 0)delete priorRecord.hash_algorithm;if(priorEvidence.length===0)delete priorRecord.reanchor_evidence;if(evidence.item_hash_version===void 0){delete priorRecord.item_hash_version}return evidence.record_hash_version===void 0||evidence.record_hash===void 0?{kind:"legacy",entry:priorRecord}:{kind:"record",entry:priorRecord}}function verifyHistoryRewriteEvidence(entry){const evidenceEntries=entry.reanchor_evidence;if(evidenceEntries===void 0)return{ok:true,coverage:"none"};if(!Array.isArray(evidenceEntries)||!isHistoryRewriteEvidenceList(evidenceEntries)){return{ok:false,error:"rewrite_evidence_invalid"}}if(evidenceEntries.length===0)return{ok:true,coverage:"none"};let reconstructed=entry;for(let index=evidenceEntries.length-1;index>=0;index-=1){const evidence=evidenceEntries[index];const prior=reconstructPriorHistoryRecord(reconstructed,evidence,evidenceEntries.slice(0,index));if(prior.kind==="patch_hash_mismatch"){return{ok:false,error:"rewrite_evidence_patch_hash_mismatch"}}if(prior.kind==="record_hash_mismatch"){return{ok:false,error:"rewrite_evidence_record_hash_mismatch"}}if(prior.kind==="digest_only"){return{ok:true,coverage:"digest_only"}}if(prior.kind==="legacy"){return{ok:true,coverage:"legacy_anchor_only"}}if(!verifyHistoryRecordHash(prior.entry).ok){return{ok:false,error:"rewrite_evidence_record_hash_mismatch"}}reconstructed=prior.entry}return{ok:true,coverage:"complete"}}function compareOptionalStrings(left,right){return(left??"").localeCompare(right??"")}function compareOptionalNumbers(left,right){return(left??0)-(right??0)}function compareJsonValues(left,right,fallback){return JSON.stringify(left??fallback).localeCompare(JSON.stringify(right??fallback))}function compareLegacyLinkedTests(left,right){const comparisons=[left.scope.localeCompare(right.scope),compareOptionalStrings(left.path,right.path),compareOptionalStrings(left.command,right.command),compareOptionalNumbers(left.timeout_seconds,right.timeout_seconds),compareOptionalStrings(left.pm_context_mode,right.pm_context_mode),Number(Boolean(left.shared_host_safe))-Number(Boolean(right.shared_host_safe)),compareJsonValues(left.env_clear,right.env_clear,[]),compareJsonValues(left.env_set,right.env_set,{}),compareJsonValues(left.assert_stdout_contains,right.assert_stdout_contains,[]),compareJsonValues(left.assert_stdout_regex,right.assert_stdout_regex,[]),compareJsonValues(left.assert_stderr_contains,right.assert_stderr_contains,[]),compareJsonValues(left.assert_stderr_regex,right.assert_stderr_regex,[]),compareOptionalNumbers(left.assert_stdout_min_lines,right.assert_stdout_min_lines),compareJsonValues(left.assert_json_field_equals,right.assert_json_field_equals,{}),compareJsonValues(left.assert_json_field_gte,right.assert_json_field_gte,{}),compareOptionalStrings(left.note,right.note)];return comparisons.find(comparison=>comparison!==0)??0}function decodeJsonPointer(path2){if(!path2||path2==="/"){return[]}if(!path2.startsWith("/")){return[]}return path2.slice(1).split("/").map(segment=>segment.replaceAll("~1","/").replaceAll("~0","~"))}function isDefinedPointerPath(document,path2){const segments=decodeJsonPointer(path2);if(segments.length===0){return true}let cursor=document;for(const segment of segments){const arrayIndex=/^(0|[1-9]\d*)$/.test(segment)?Number(segment):-1;const next=Array.isArray(cursor)?arrayIndex>=0&&arrayIndex<cursor.length?cursor[arrayIndex]:void 0:isRecord(cursor)&&Object.prototype.hasOwnProperty.call(cursor,segment)?cursor[segment]:void 0;if(next===void 0)return false;cursor=next}return true}function normalizeHistoryPatchOps(beforeDocument,patch){const normalized=[];let replayCursor=structuredClone(beforeDocument);for(const operation of patch){const normalizedOperation=operation.op==="replace"&&!isDefinedPointerPath(replayCursor,operation.path)?{...operation,op:"add"}:operation;normalized.push(normalizedOperation);replayCursor=jsonPatch.applyPatch(replayCursor,[normalizedOperation],true,true).newDocument}return normalized}function canonicalHashDocument(document,version,legacyV2Fields=false){const hasMetadata=document.metadata&&Object.keys(document.metadata).length>0;if(!hasMetadata){return{front_matter:{},body:document.body??""}}const canonical=canonicalDocument(document);const usesLegacyFields=version===1||version===2&&legacyV2Fields;const epochMetadata=usesLegacyFields?{...canonical.metadata,...canonical.metadata.dependencies===void 0?{}:{dependencies:canonical.metadata.dependencies.map(dependency=>({...dependency,id:dependency.id.toLowerCase()}))},...canonical.metadata.tests===void 0?{}:{tests:canonical.metadata.tests.map(({workspace_context_mode:_workspaceContextMode,provenance:_provenance,provenance_invalid:_provenanceInvalid,...test})=>test)},...canonical.metadata.test_runs===void 0?{}:{test_runs:canonical.metadata.test_runs.map(({executions:_executions,...testRun})=>testRun)}}:canonical.metadata;const metadata=version===1&&epochMetadata.tests?{...epochMetadata,tests:[...epochMetadata.tests].sort(compareLegacyLinkedTests)}:epochMetadata;const orderedMetadata=orderObject(toItemRecord(metadata),ITEM_METADATA_KEY_ORDER);return{front_matter:orderedMetadata,body:canonical.body}}function canonicalPatchDocument(document){const hasMetadata=document.metadata&&Object.keys(document.metadata).length>0;if(!hasMetadata){return{metadata:{},body:document.body??""}}const canonical=canonicalDocument(document);const orderedMetadata=orderObject(toItemRecord(canonical.metadata),ITEM_METADATA_KEY_ORDER);return{metadata:orderedMetadata,body:canonical.body}}function hashDocument(document){return hashDocumentForVersion(document,CURRENT_HISTORY_ITEM_HASH_VERSION)}function hashDocumentForVersion(document,version,algorithm){if(!SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.some(supportedVersion=>supportedVersion===version)){throw new TypeError(`unsupported_item_hash_version:${String(version)}`)}return historyDigest(stableStringify(canonicalHashDocument(document,version)),algorithm)}function hashDocumentVerificationCandidates(document,version,algorithm){const canonicalHash=hashDocumentForVersion(document,version,algorithm);return version===2?[canonicalHash,historyDigest(stableStringify(canonicalHashDocument(document,version,true)),algorithm)]:[canonicalHash]}function hashEmptyDocument(){return sha256Hex(stableStringify(EMPTY_LEGACY_HASH_DOCUMENT))}function createHistoryEntry(params){const operation=normalizeHistoryOperationForWrite(params.op);const beforeHashCanonical=canonicalHashDocument(params.before,CURRENT_HISTORY_ITEM_HASH_VERSION);const afterHashCanonical=canonicalHashDocument(params.after,CURRENT_HISTORY_ITEM_HASH_VERSION);const beforePatchCanonical=canonicalPatchDocument(params.before);const afterPatchCanonical=canonicalPatchDocument(params.after);const rawPatch=jsonPatch.compare(beforePatchCanonical,afterPatchCanonical);const patch=normalizeHistoryPatchOps(beforePatchCanonical,rawPatch);const agentIdentity=resolveHistoryAgentIdentity(params.author);const provenanceOutcomes=agentIdentity.harness?Object.fromEntries(Object.entries(diagnoseAgentIdentity().provenance_outcomes).filter(([dimension,outcome])=>outcome.resolver!==void 0&&(outcome.status!=="resolved"||agentIdentity.provenance?.[dimension]?.source==="probe"))):void 0;const context=provenanceOutcomes===void 0||Object.keys(provenanceOutcomes).length===0?params.context:{...params.context,agent_provenance_outcomes:provenanceOutcomes};const algorithm=params.hashAlgorithm??CURRENT_HISTORY_HASH_ALGORITHM;const entry={hash_algorithm:algorithm,ts:params.nowIso,author:params.author,author_source:params.authorSource??resolveHistoryAuthorSource(params.author),...agentIdentity.harness?{agent_harness:agentIdentity.harness}:{},...agentIdentity.model?{agent_model:agentIdentity.model}:{},...agentIdentity.model_source?{agent_model_source:agentIdentity.model_source}:{},...agentIdentity.instance?{agent_instance:agentIdentity.instance}:{},...agentIdentity.provenance?{agent_provenance:agentIdentity.provenance}:{},...agentIdentity.episode?{agent_episode:agentIdentity.episode}:{},op:operation,patch,before_hash:historyDigest(stableStringify(beforeHashCanonical),algorithm),after_hash:historyDigest(stableStringify(afterHashCanonical),algorithm),item_hash_version:CURRENT_HISTORY_ITEM_HASH_VERSION,message:params.message===void 0?void 0:params.message,...context===void 0?{}:{context}};return sealHistoryRecord({...entry,event_class:classifyHistoryEvent(entry)})}function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function invalidHistoryTimestamp(message){return new PmCliError(message,EXIT_CODE.GENERIC_FAILURE,{code:"history_timestamp_invalid"})}function fallbackHistoryTimestamp(entry){const ts=entry.ts.trim();if(ts.length===0)return nowIso();if(!isMillisecondPrecisionRfc3339DateTime(ts)){throw invalidHistoryTimestamp("History timestamp must be a valid RFC 3339 date-time with millisecond precision")}if(ts!==entry.ts){throw invalidHistoryTimestamp("History timestamp must not contain surrounding whitespace")}return entry.ts}function withHistoryTimestamp(value,fallbackTs){const ts=value.ts;if(typeof ts==="string"&&ts.trim().length>0){if(!isMillisecondPrecisionRfc3339DateTime(ts)){throw invalidHistoryTimestamp("History timestamp must be a valid RFC 3339 date-time with millisecond precision")}return value}return{...value,ts:fallbackTs}}function serializeHistoryLine(value,fallbackEntry){const fallbackTs=fallbackHistoryTimestamp(fallbackEntry);if(typeof value==="string"){let parsed;try{parsed=JSON.parse(value)}catch{return value}if(isRecord(parsed)){return JSON.stringify(withHistoryTimestamp(parsed,fallbackTs))}return value}if(isRecord(value)){return JSON.stringify(withHistoryTimestamp(value,fallbackTs))}return JSON.stringify(value)}async function applyHistoryAppendOverride(historyPath,entry,result){if(result===false)return true;if(typeof result==="string"){const line2=serializeHistoryLine(result,entry);await appendHistoryLineWithIdentityReservation(historyPath,line2);await invalidateHistoryDriftCacheForPath(historyPath);await removeHistoryEventIndexForHistoryPath(historyPath);return true}if(typeof result!=="object"||result===null)return false;const record=result;if(record.skip===true)return true;const nextHistoryPath=typeof record.history_path==="string"?record.history_path:historyPath;const line=serializeHistoryLine(typeof record.line==="string"?record.line:record.entry??entry,entry);await appendHistoryLineWithIdentityReservation(nextHistoryPath,line);await invalidateHistoryDriftCacheForPath(nextHistoryPath);await removeHistoryEventIndexForHistoryPath(nextHistoryPath);return true}async function appendHistoryLineWithIdentityReservation(historyPath,line){let record;try{record=JSON.parse(line)}catch{record=null}if(!isRecord(record)||record.op!=="create"){await appendLineAtomic(historyPath,line);return}await fs.mkdir(path.dirname(historyPath),{recursive:true});try{await fs.writeFile(historyPath,`${line}
|
|
2
|
-
`,{encoding:"utf8",flag:"wx"})}catch(error){
|
|
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]="4a3c3c82-0398-549c-8910-fdc69d971cb2")}catch{}})();import jsonPatch from"fast-json-patch";import{normalizeHistoryOperationForWrite}from"./operation-contract.js";import{CURRENT_HISTORY_HASH_ALGORITHM,historyDigest,resolveHistoryHashAlgorithm}from"./digest.js";import fs from"node:fs/promises";import path from"node:path";import{EXIT_CODE,ITEM_METADATA_KEY_ORDER}from"../shared/constants.js";import{runActiveServiceOverride}from"../extensions/index.js";import{appendLineAtomic}from"../fs/fs-utils.js";import{canonicalDocument}from"../item/item-format.js";import{toItemRecord}from"../item/item-record.js";import{orderObject,sha256Hex,stableStringify}from"../shared/serialization.js";import{isMillisecondPrecisionRfc3339DateTime,nowIso}from"../shared/time.js";import{diagnoseAgentIdentity,resolveHistoryAgentIdentity,resolveHistoryAuthorSource}from"../shared/author.js";import{appendHistoryEntryWithEventIndex,removeHistoryEventIndexForHistoryPath}from"./event-index.js";import{classifyHistoryEvent}from"./event-classification.js";import{invalidateHistoryDriftCacheForPath}from"./drift-cache.js";import{PmCliError}from"../shared/errors.js";const EMPTY_LEGACY_HASH_DOCUMENT={front_matter:{},body:""},CURRENT_HISTORY_ITEM_HASH_VERSION=3,SUPPORTED_HISTORY_ITEM_HASH_VERSIONS=[1,2,3],CURRENT_HISTORY_RECORD_HASH_VERSION=1,SUPPORTED_HISTORY_RECORD_HASH_VERSIONS=[1];function hashHistoryRecord(entry){return historyDigest(stableStringify(entry),entry.hash_algorithm)}function hashHistoryPatch(patch){return sha256Hex(stableStringify(patch))}function hashHistoryStream(entries){return sha256Hex(stableStringify(entries))}function sealHistoryRecord(entry){const sealed={...entry,record_hash_version:CURRENT_HISTORY_RECORD_HASH_VERSION},{record_hash:_recordHash,...canonical}=sealed;return{...sealed,record_hash:hashHistoryRecord(canonical)}}function verifyHistoryRecordHash(entry){try{resolveHistoryHashAlgorithm(entry.hash_algorithm)}catch{return{ok:!1,error:"unsupported_history_hash_algorithm"}}if(entry.record_hash_version===void 0&&entry.record_hash===void 0)return{ok:!0,coverage:"item_state_only"};if(entry.record_hash_version===void 0||entry.record_hash===void 0)return{ok:!1,error:"incomplete_record_hash_envelope"};if(!SUPPORTED_HISTORY_RECORD_HASH_VERSIONS.includes(entry.record_hash_version))return{ok:!1,error:"unsupported_record_hash_version"};const{record_hash:_recordHash,...canonical}=entry;return hashHistoryRecord(canonical)===entry.record_hash?{ok:!0,coverage:"record_and_item_state"}:{ok:!1,error:"record_hash_mismatch"}}function createHistoryRewriteEvidence(original,options){const evidence={before_hash:original.before_hash,after_hash:original.after_hash,patch_hash:hashHistoryPatch(original.patch)};return original.hash_algorithm!==void 0&&(evidence.hash_algorithm=original.hash_algorithm),original.item_hash_version!==void 0&&(evidence.item_hash_version=original.item_hash_version),options.retainOriginalPatch&&(evidence.patch=structuredClone(original.patch)),options.retainPriorRecordHash!==!1&&original.record_hash_version!==void 0&&original.record_hash!==void 0&&(evidence.record_hash_version=original.record_hash_version,evidence.record_hash=original.record_hash,evidence.record=structuredClone(original)),evidence}function resealHistoryRewrite(original,rewritten,options={}){const originalRecordVerification=verifyHistoryRecordHash(original);if(!originalRecordVerification.ok)throw new TypeError(originalRecordVerification.error);const originalPatchHash=hashHistoryPatch(original.patch),retainsRewriteEvidence=options.retainPriorRecord===!0||original.before_hash!==rewritten.before_hash||original.after_hash!==rewritten.after_hash||original.item_hash_version!==rewritten.item_hash_version||original.hash_algorithm!==rewritten.hash_algorithm||originalPatchHash!==hashHistoryPatch(rewritten.patch),sealed=sealHistoryRecord({...rewritten,...retainsRewriteEvidence?{reanchor_evidence:[...rewritten.reanchor_evidence??[],createHistoryRewriteEvidence(original,options)]}:{}}),evidenceVerification=verifyHistoryRewriteEvidence(sealed);if(!evidenceVerification.ok)throw new TypeError(evidenceVerification.error);return sealed}function isHistoryPatch(value){return!Array.isArray(value)||Object.keys(value).length!==value.length?!1:value.every(operation=>!isRecord(operation)||typeof operation.path!="string"?!1:operation.op==="move"||operation.op==="copy"?typeof operation.from=="string":["add","replace","test"].includes(operation.op)?Object.hasOwn(operation,"value"):operation.op==="remove")}function isRetainedHistoryRecordShape(value){return isRecord(value)&&typeof value.ts=="string"&&typeof value.author=="string"&&typeof value.op=="string"&&typeof value.before_hash=="string"&&typeof value.after_hash=="string"&&isHistoryPatch(value.patch)}function hasCompleteRetainedRecordHashEnvelope(evidence){const hasVersion=evidence.record_hash_version!==void 0,hasHash=evidence.record_hash!==void 0;return hasVersion===hasHash}function isHistoryReanchorEvidence(evidence){return!isRecord(evidence)||!hasCompleteRetainedRecordHashEnvelope(evidence)||typeof evidence.before_hash!="string"||typeof evidence.after_hash!="string"||typeof evidence.patch_hash!="string"||!/^[a-f0-9]{64}$/u.test(evidence.patch_hash)||evidence.patch!==void 0&&!isHistoryPatch(evidence.patch)||evidence.record_hash_version!==void 0&&typeof evidence.record_hash_version!="number"||evidence.record_hash!==void 0&&(typeof evidence.record_hash!="string"||!/^(?:[a-f0-9]{64}|[a-f0-9]{128})$/u.test(evidence.record_hash))?!1:evidence.record===void 0||isRetainedHistoryRecordShape(evidence.record)}function isHistoryRewriteEvidenceList(evidenceEntries){try{for(const evidence of evidenceEntries){if(!isHistoryReanchorEvidence(evidence))return!1;resolveHistoryHashAlgorithm(evidence.hash_algorithm)}return!0}catch{return!1}}function matchesRetainedHistoryRecord(evidence){const record=evidence.record;return record!==void 0&&record.before_hash===evidence.before_hash&&record.after_hash===evidence.after_hash&&record.item_hash_version===evidence.item_hash_version&&record.hash_algorithm===evidence.hash_algorithm&&record.record_hash_version===evidence.record_hash_version&&record.record_hash===evidence.record_hash&&hashHistoryPatch(record.patch)===evidence.patch_hash}function reconstructPriorHistoryRecord(current,evidence,priorEvidence){if(evidence.patch&&hashHistoryPatch(evidence.patch)!==evidence.patch_hash)return{kind:"patch_hash_mismatch"};if(evidence.record)return matchesRetainedHistoryRecord(evidence)?{kind:"record",entry:evidence.record}:{kind:"record_hash_mismatch"};const priorPatch=evidence.patch??current.patch;if(hashHistoryPatch(priorPatch)!==evidence.patch_hash)return{kind:"digest_only"};const priorRecord={...current,before_hash:evidence.before_hash,after_hash:evidence.after_hash,patch:priorPatch,hash_algorithm:evidence.hash_algorithm,...evidence.item_hash_version===void 0?{}:{item_hash_version:evidence.item_hash_version},...evidence.record_hash_version===void 0?{}:{record_hash_version:evidence.record_hash_version},...evidence.record_hash===void 0?{}:{record_hash:evidence.record_hash},...priorEvidence.length===0?{}:{reanchor_evidence:priorEvidence}};return evidence.hash_algorithm===void 0&&delete priorRecord.hash_algorithm,priorEvidence.length===0&&delete priorRecord.reanchor_evidence,evidence.item_hash_version===void 0&&delete priorRecord.item_hash_version,evidence.record_hash_version===void 0||evidence.record_hash===void 0?{kind:"legacy",entry:priorRecord}:{kind:"record",entry:priorRecord}}function verifyHistoryRewriteEvidence(entry){const evidenceEntries=entry.reanchor_evidence;if(evidenceEntries===void 0)return{ok:!0,coverage:"none"};if(!Array.isArray(evidenceEntries)||!isHistoryRewriteEvidenceList(evidenceEntries))return{ok:!1,error:"rewrite_evidence_invalid"};if(evidenceEntries.length===0)return{ok:!0,coverage:"none"};let reconstructed=entry;for(let index=evidenceEntries.length-1;index>=0;index-=1){const evidence=evidenceEntries[index],prior=reconstructPriorHistoryRecord(reconstructed,evidence,evidenceEntries.slice(0,index));if(prior.kind==="patch_hash_mismatch")return{ok:!1,error:"rewrite_evidence_patch_hash_mismatch"};if(prior.kind==="record_hash_mismatch")return{ok:!1,error:"rewrite_evidence_record_hash_mismatch"};if(prior.kind==="digest_only")return{ok:!0,coverage:"digest_only"};if(prior.kind==="legacy")return{ok:!0,coverage:"legacy_anchor_only"};if(!verifyHistoryRecordHash(prior.entry).ok)return{ok:!1,error:"rewrite_evidence_record_hash_mismatch"};reconstructed=prior.entry}return{ok:!0,coverage:"complete"}}function compareOptionalStrings(left,right){return(left??"").localeCompare(right??"")}function compareOptionalNumbers(left,right){return(left??0)-(right??0)}function compareJsonValues(left,right,fallback){return JSON.stringify(left??fallback).localeCompare(JSON.stringify(right??fallback))}function compareLegacyLinkedTests(left,right){return[left.scope.localeCompare(right.scope),compareOptionalStrings(left.path,right.path),compareOptionalStrings(left.command,right.command),compareOptionalNumbers(left.timeout_seconds,right.timeout_seconds),compareOptionalStrings(left.pm_context_mode,right.pm_context_mode),+!!left.shared_host_safe-+!!right.shared_host_safe,compareJsonValues(left.env_clear,right.env_clear,[]),compareJsonValues(left.env_set,right.env_set,{}),compareJsonValues(left.assert_stdout_contains,right.assert_stdout_contains,[]),compareJsonValues(left.assert_stdout_regex,right.assert_stdout_regex,[]),compareJsonValues(left.assert_stderr_contains,right.assert_stderr_contains,[]),compareJsonValues(left.assert_stderr_regex,right.assert_stderr_regex,[]),compareOptionalNumbers(left.assert_stdout_min_lines,right.assert_stdout_min_lines),compareJsonValues(left.assert_json_field_equals,right.assert_json_field_equals,{}),compareJsonValues(left.assert_json_field_gte,right.assert_json_field_gte,{}),compareOptionalStrings(left.note,right.note)].find(comparison=>comparison!==0)??0}function decodeJsonPointer(path2){return!path2||path2==="/"?[]:path2.startsWith("/")?path2.slice(1).split("/").map(segment=>segment.replaceAll("~1","/").replaceAll("~0","~")):[]}function isDefinedPointerPath(document,path2){const segments=decodeJsonPointer(path2);if(segments.length===0)return!0;let cursor=document;for(const segment of segments){const arrayIndex=/^(0|[1-9]\d*)$/.test(segment)?Number(segment):-1,next=Array.isArray(cursor)?arrayIndex>=0&&arrayIndex<cursor.length?cursor[arrayIndex]:void 0:isRecord(cursor)&&Object.prototype.hasOwnProperty.call(cursor,segment)?cursor[segment]:void 0;if(next===void 0)return!1;cursor=next}return!0}function normalizeHistoryPatchOps(beforeDocument,patch){const normalized=[];let replayCursor=structuredClone(beforeDocument);for(const operation of patch){const normalizedOperation=operation.op==="replace"&&!isDefinedPointerPath(replayCursor,operation.path)?{...operation,op:"add"}:operation;normalized.push(normalizedOperation),replayCursor=jsonPatch.applyPatch(replayCursor,[normalizedOperation],!0,!0).newDocument}return normalized}function canonicalHashDocument(document,version,legacyV2Fields=!1){if(!(document.metadata&&Object.keys(document.metadata).length>0))return{front_matter:{},body:document.body??""};const canonical=canonicalDocument(document),epochMetadata=version===1||version===2&&legacyV2Fields?{...canonical.metadata,...canonical.metadata.dependencies===void 0?{}:{dependencies:canonical.metadata.dependencies.map(dependency=>({...dependency,id:dependency.id.toLowerCase()}))},...canonical.metadata.tests===void 0?{}:{tests:canonical.metadata.tests.map(({workspace_context_mode:_workspaceContextMode,provenance:_provenance,provenance_invalid:_provenanceInvalid,...test})=>test)},...canonical.metadata.test_runs===void 0?{}:{test_runs:canonical.metadata.test_runs.map(({executions:_executions,...testRun})=>testRun)}}:canonical.metadata,metadata=version===1&&epochMetadata.tests?{...epochMetadata,tests:[...epochMetadata.tests].sort(compareLegacyLinkedTests)}:epochMetadata;return{front_matter:orderObject(toItemRecord(metadata),ITEM_METADATA_KEY_ORDER),body:canonical.body}}function canonicalPatchDocument(document){if(!(document.metadata&&Object.keys(document.metadata).length>0))return{metadata:{},body:document.body??""};const canonical=canonicalDocument(document);return{metadata:orderObject(toItemRecord(canonical.metadata),ITEM_METADATA_KEY_ORDER),body:canonical.body}}function hashDocument(document){return hashDocumentForVersion(document,CURRENT_HISTORY_ITEM_HASH_VERSION)}function hashDocumentForVersion(document,version,algorithm){if(!SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.some(supportedVersion=>supportedVersion===version))throw new TypeError(`unsupported_item_hash_version:${String(version)}`);return historyDigest(stableStringify(canonicalHashDocument(document,version)),algorithm)}function hashDocumentVerificationCandidates(document,version,algorithm){const canonicalHash=hashDocumentForVersion(document,version,algorithm);return version===2?[canonicalHash,historyDigest(stableStringify(canonicalHashDocument(document,version,!0)),algorithm)]:[canonicalHash]}function hashEmptyDocument(){return sha256Hex(stableStringify(EMPTY_LEGACY_HASH_DOCUMENT))}function createHistoryEntry(params){const operation=normalizeHistoryOperationForWrite(params.op),beforeHashCanonical=canonicalHashDocument(params.before,CURRENT_HISTORY_ITEM_HASH_VERSION),afterHashCanonical=canonicalHashDocument(params.after,CURRENT_HISTORY_ITEM_HASH_VERSION),beforePatchCanonical=canonicalPatchDocument(params.before),afterPatchCanonical=canonicalPatchDocument(params.after),rawPatch=jsonPatch.compare(beforePatchCanonical,afterPatchCanonical),patch=normalizeHistoryPatchOps(beforePatchCanonical,rawPatch),agentIdentity=resolveHistoryAgentIdentity(params.author),provenanceOutcomes=agentIdentity.harness?Object.fromEntries(Object.entries(diagnoseAgentIdentity().provenance_outcomes).filter(([dimension,outcome])=>outcome.resolver!==void 0&&(outcome.status!=="resolved"||agentIdentity.provenance?.[dimension]?.source==="probe"))):void 0,context=provenanceOutcomes===void 0||Object.keys(provenanceOutcomes).length===0?params.context:{...params.context,agent_provenance_outcomes:provenanceOutcomes},algorithm=params.hashAlgorithm??CURRENT_HISTORY_HASH_ALGORITHM,entry={hash_algorithm:algorithm,ts:params.nowIso,author:params.author,author_source:params.authorSource??resolveHistoryAuthorSource(params.author),...agentIdentity.harness?{agent_harness:agentIdentity.harness}:{},...agentIdentity.model?{agent_model:agentIdentity.model}:{},...agentIdentity.model_source?{agent_model_source:agentIdentity.model_source}:{},...agentIdentity.instance?{agent_instance:agentIdentity.instance}:{},...agentIdentity.provenance?{agent_provenance:agentIdentity.provenance}:{},...agentIdentity.episode?{agent_episode:agentIdentity.episode}:{},op:operation,patch,before_hash:historyDigest(stableStringify(beforeHashCanonical),algorithm),after_hash:historyDigest(stableStringify(afterHashCanonical),algorithm),item_hash_version:CURRENT_HISTORY_ITEM_HASH_VERSION,message:params.message===void 0?void 0:params.message,...context===void 0?{}:{context}};return sealHistoryRecord({...entry,event_class:classifyHistoryEvent(entry)})}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function invalidHistoryTimestamp(message){return new PmCliError(message,EXIT_CODE.GENERIC_FAILURE,{code:"history_timestamp_invalid"})}function fallbackHistoryTimestamp(entry){const ts=entry.ts.trim();if(ts.length===0)return nowIso();if(!isMillisecondPrecisionRfc3339DateTime(ts))throw invalidHistoryTimestamp("History timestamp must be a valid RFC 3339 date-time with millisecond precision");if(ts!==entry.ts)throw invalidHistoryTimestamp("History timestamp must not contain surrounding whitespace");return entry.ts}function withHistoryTimestamp(value,fallbackTs){const ts=value.ts;if(typeof ts=="string"&&ts.trim().length>0){if(!isMillisecondPrecisionRfc3339DateTime(ts))throw invalidHistoryTimestamp("History timestamp must be a valid RFC 3339 date-time with millisecond precision");return value}return{...value,ts:fallbackTs}}function serializeHistoryLine(value,fallbackEntry){const fallbackTs=fallbackHistoryTimestamp(fallbackEntry);if(typeof value=="string"){let parsed;try{parsed=JSON.parse(value)}catch{return value}return isRecord(parsed)?JSON.stringify(withHistoryTimestamp(parsed,fallbackTs)):value}return isRecord(value)?JSON.stringify(withHistoryTimestamp(value,fallbackTs)):JSON.stringify(value)}async function applyHistoryAppendOverride(historyPath,entry,result){if(result===!1)return!0;if(typeof result=="string"){const line2=serializeHistoryLine(result,entry);return await appendHistoryLineWithIdentityReservation(historyPath,line2),await invalidateHistoryDriftCacheForPath(historyPath),await removeHistoryEventIndexForHistoryPath(historyPath),!0}if(typeof result!="object"||result===null)return!1;const record=result;if(record.skip===!0)return!0;const nextHistoryPath=typeof record.history_path=="string"?record.history_path:historyPath,line=serializeHistoryLine(typeof record.line=="string"?record.line:record.entry??entry,entry);return await appendHistoryLineWithIdentityReservation(nextHistoryPath,line),await invalidateHistoryDriftCacheForPath(nextHistoryPath),await removeHistoryEventIndexForHistoryPath(nextHistoryPath),!0}async function appendHistoryLineWithIdentityReservation(historyPath,line){let record;try{record=JSON.parse(line)}catch{record=null}if(!isRecord(record)||record.op!=="create"){await appendLineAtomic(historyPath,line);return}await fs.mkdir(path.dirname(historyPath),{recursive:!0});try{await fs.writeFile(historyPath,`${line}
|
|
2
|
+
`,{encoding:"utf8",flag:"wx"})}catch(error){throw error.code!=="EEXIST"?error:new PmCliError("This item identity is reserved by an existing history stream.",EXIT_CODE.CONFLICT,{code:"item_identity_reserved",required:"Choose a new item ID or restore the original item from its history.",nextSteps:["Run pm history <id> --full, then pm restore <id> <version> to recover the original item."]})}}async function appendHistoryEntry(historyPath,entry){const override=await runActiveServiceOverride("history_append",{history_path:historyPath,entry});if(override.handled&&await applyHistoryAppendOverride(historyPath,entry,override.result))return;const timestampedEntry=entry.ts.trim().length>0?entry:{...entry,ts:fallbackHistoryTimestamp(entry)},normalizedEntry=sealHistoryRecord({...timestampedEntry,hash_algorithm:resolveHistoryHashAlgorithm(timestampedEntry.hash_algorithm),event_class:classifyHistoryEvent(timestampedEntry)});await appendHistoryEntryWithEventIndex(historyPath,normalizedEntry,async()=>{await appendHistoryLineWithIdentityReservation(historyPath,serializeHistoryLine(normalizedEntry,normalizedEntry))}),await invalidateHistoryDriftCacheForPath(historyPath)}const _testOnly={decodeJsonPointer,isDefinedPointerPath};export{CURRENT_HISTORY_ITEM_HASH_VERSION,CURRENT_HISTORY_RECORD_HASH_VERSION,SUPPORTED_HISTORY_ITEM_HASH_VERSIONS,SUPPORTED_HISTORY_RECORD_HASH_VERSIONS,_testOnly,appendHistoryEntry,createHistoryEntry,hashDocument,hashDocumentForVersion,hashDocumentVerificationCandidates,hashEmptyDocument,hashHistoryPatch,hashHistoryRecord,hashHistoryStream,resealHistoryRewrite,sealHistoryRecord,verifyHistoryRecordHash,verifyHistoryRewriteEvidence};
|
|
3
3
|
//# sourceMappingURL=history.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="3bfeb8d2-52c2-587a-9611-c4d5817cb47e")}catch{}})();function findHistoryIdentityDiscontinuities(entries){const findings=[],checkpoint=entries[0]?.op==="history_compact_baseline";let genesis=checkpoint?1:void 0,deleted=!1;for(const[index,entry]of entries.entries())entry.op==="delete"&&(deleted=!0),entry.op==="create"&&(genesis!==void 0&&findings.push({prior_genesis_index:genesis,repeated_create_index:index+1,sequence:deleted?"delete_then_create":checkpoint?"checkpoint_then_create":"multiple_creates"}),genesis??=index+1,deleted=!1);return findings}export{findHistoryIdentityDiscontinuities};
|
|
2
2
|
//# sourceMappingURL=identity.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="2a41f316-31f0-5115-be8b-957da9e233ad")}catch{}})();export*from"./history.js";
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="6fd537c2-9d10-5a26-81a9-ac931151017b")}catch{}})();const PM_ITEM_HISTORY_OPERATIONS=["append","cancel","claim","close","comment_add","comment_edit","comment_delete","create","delete","docs_add","docs_remove","files_add","files_remove","files_discover","history_author_acknowledge","history_compact","history_compact_baseline","history_redact","history_repair","history_salvage","import","improvement_observe","learning_add","learning_edit","learning_delete","normalize","note_add","note_edit","note_delete","plan_create_metadata","plan_create_initial_step","plan_add_step","plan_reorder_step","plan_remove_step","plan_link_step","plan_unlink_step","plan_append_decision","plan_append_discovery","plan_append_validation","plan_resume","plan_approve","plan_materialize","plan_update_step","plan_complete_step","plan_block_step","policy_approve","policy_refused","release","reopen","restore","schema_migration","schema_migration_reference","test_run_track","tests_add","tests_remove","tests_update","update","update_audit","update_ownership_bypass","workspace_snapshot_restore","extension_migrations_apply","merge_reconcile"],PM_WORKSPACE_HISTORY_OPERATIONS=["history:author-acknowledge","settings:write","init:type_preset","templates:save","profile:apply-types","profile:apply-statuses","profile:apply-fields","profile:apply-config","schema:add-type","schema:remove-type","schema:add-status","schema:remove-status","schema:add-field","schema:remove-field","schema:apply-preset","schema:infer-types","schema:policy-put","schema:policy-remove","schema:policy-mode","assurance:bundle:apply","assurance:gate:verdict","telemetry:install_id","telemetry:first_run_prompt","telemetry:clear","item_format:auto_select_default"],PM_HISTORY_OPERATION_ALIASES={"init:type-preset":"init:type_preset"},PM_HISTORY_OPERATION_PATTERNS=["^config:(?:set|unset):[a-z][a-z0-9_.:-]*$","^assurance:(?:measurement|invariant|gate):(?:put|remove)$","^schema_(?:rename_type|rename_status|remap_status|rename_field|remove_type|remove_status|remove_field)(?:_compensate)?$","^extension:[a-z][a-z0-9_-]*:[a-z][a-z0-9_]*$"],PM_HISTORY_OPERATION_CONTRACT={version:1,item:PM_ITEM_HISTORY_OPERATIONS,workspace:PM_WORKSPACE_HISTORY_OPERATIONS,aliases:PM_HISTORY_OPERATION_ALIASES,patterns:PM_HISTORY_OPERATION_PATTERNS,read_policy:"preserve_original_operation",custom_operation_grammar:"extension:<package_name>:<snake_case_operation>",legacy_custom_operation_grammar:"lowercase segments separated by underscore, hyphen, colon, or dot; optional opaque colon-suffixed retry key",excluded_surfaces:["json_patch","on_write_hook","telemetry_span"]},declared=new Set([...PM_ITEM_HISTORY_OPERATIONS,...PM_WORKSPACE_HISTORY_OPERATIONS]),patterns=PM_HISTORY_OPERATION_PATTERNS.map(pattern=>new RegExp(pattern,"u"));function resolveHistoryOperation(operation){return Object.hasOwn(PM_HISTORY_OPERATION_ALIASES,operation)?PM_HISTORY_OPERATION_ALIASES[operation]:operation}function requireHistoryOperation(operation){const canonical=resolveHistoryOperation(operation);if(declared.has(canonical)||patterns.some(pattern=>pattern.test(canonical)))return canonical;throw new TypeError("Undeclared history operation; use a native contract identity or extension:<package_name>:<snake_case_operation>.")}function normalizeHistoryOperationForWrite(operation){const canonical=resolveHistoryOperation(operation),colon=canonical.indexOf(":"),prefix=colon<0?canonical:canonical.slice(0,colon),validSuffix=colon<0||colon<canonical.length-1&&!/[\s\p{C}]/u.test(canonical.slice(colon+1));if(/^[a-z][a-z0-9]*(?:[_.-][a-z0-9]+)*$/u.test(prefix)&&validSuffix)return canonical;throw new TypeError("History operation must use lowercase alphanumeric segments with an optional non-whitespace colon-suffixed retry key.")}export{PM_HISTORY_OPERATION_ALIASES,PM_HISTORY_OPERATION_CONTRACT,PM_HISTORY_OPERATION_PATTERNS,PM_ITEM_HISTORY_OPERATIONS,PM_WORKSPACE_HISTORY_OPERATIONS,normalizeHistoryOperationForWrite,requireHistoryOperation,resolveHistoryOperation};
|
|
2
2
|
//# sourceMappingURL=operation-contract.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="ddc5bb8f-83bc-5121-a628-a501e7ed5a73")}catch{}})();import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{historyVersionOffset}from"./version-address.js";import{EMPTY_REPLAY_DOCUMENT,verifyHistoryChain,tryApplyReplayPatch}from"./replay.js";function findHistoryIndexAtTimestamp(history,parsedTarget){let historyIndex=-1;return history.forEach((entry,index)=>{const entryTimestamp=Date.parse(entry.ts);if(!Number.isFinite(entryTimestamp))throw new PmCliError(`History for this item contains invalid timestamp at entry ${index+1}.`,EXIT_CODE.GENERIC_FAILURE);entryTimestamp<=parsedTarget&&(historyIndex=index)}),historyIndex}function buildHistoryTargetGuidance(history,offset){const firstTimestamp=history[0]?.ts??null,lastTimestamp=history.at(-1)?.ts??null,guidance={code:"history_target_out_of_range",required:"Choose a target within the available item history.",why:"Point-in-time reads and restores can only reconstruct recorded versions.",examples:[],nextSteps:["Run pm history <id> to inspect available versions and timestamps."],valid_range:{first_version:null,last_version:null,first_timestamp:firstTimestamp,last_timestamp:lastTimestamp}};return lastTimestamp!==null&&(guidance.examples=[lastTimestamp],offset!==null&&(guidance.examples.unshift(String(offset+1),String(offset+history.length)),guidance.valid_range.first_version=offset+1,guidance.valid_range.last_version=offset+history.length)),{guidance,lastTimestamp}}function extractPatchFailureContext(patch,error){const failure={};if(error instanceof Error&&error.message.trim().length>0&&(failure.reason=error.message.trim()),typeof error!="object"||error===null)return failure;const candidate=error;if(typeof candidate.index=="number"&&Number.isInteger(candidate.index)&&candidate.index>=0&&(failure.patchIndex=candidate.index),typeof candidate.operation=="object"&&candidate.operation!==null){const operation=candidate.operation;Object.assign(failure,Object.fromEntries(["op","path","from"].flatMap(field=>{const value=operation[field];return typeof value=="string"?[[field,value]]:[]})))}if(failure.patchIndex!==void 0){const fallback=patch[failure.patchIndex];fallback&&(failure.op??=fallback.op,failure.path??=fallback.path,failure.from??=fallback.from)}return failure}function resolveHistoryTarget(target,history,options={}){const trimmed=target.trim(),errorSubject=options.errorSubject??"history",errorSubjectTitle=errorSubject==="restore"?"Restore":"History",{guidance,lastTimestamp}=buildHistoryTargetGuidance(history,historyVersionOffset(history,!0));if(!trimmed)throw new PmCliError(`Missing ${errorSubject} target. Use a timestamp or version number.`,EXIT_CODE.USAGE,guidance);if(/^\d+$/.test(trimmed)){const offset=historyVersionOffset(history),version=Number(trimmed);if(version>=1&&version<=offset)throw new PmCliError(`History version ${version} was pruned by compaction.`,EXIT_CODE.USAGE,{...guidance,code:"history_version_pruned"});if(!Number.isSafeInteger(version)||version<1||version>offset+history.length)throw new PmCliError(`${errorSubjectTitle} version must be between ${offset+1} and ${offset+history.length} for this item.`,EXIT_CODE.USAGE,guidance);return{kind:"version",raw:trimmed,historyIndex:version-offset-1}}const parsedTarget=Date.parse(trimmed);if(!Number.isFinite(parsedTarget))throw new PmCliError(`Invalid ${errorSubject} target "${target}". Use a positive version number or ISO timestamp.`,EXIT_CODE.USAGE,guidance);const historyIndex=findHistoryIndexAtTimestamp(history,parsedTarget);if(historyIndex<0||options.allowFutureTimestamp!==!0&&parsedTarget>Date.parse(lastTimestamp))throw new PmCliError(errorSubject==="restore"?`No history entries exist at or before timestamp ${trimmed}.`:`No history entry exists at timestamp ${trimmed}.`,EXIT_CODE.USAGE,guidance);return{kind:"timestamp",raw:trimmed,historyIndex}}function applyHistoryPatch(current,patch,entryNumber,entryOp){const applied=tryApplyReplayPatch(current,patch);if(applied.ok)return applied.document;const failure=extractPatchFailureContext(patch,applied.error),tokens=[`history_op=${entryOp}`,failure.patchIndex===void 0?null:`patch_index=${failure.patchIndex}`,failure.op?`op=${failure.op}`:null,failure.path?`path=${failure.path}`:null,failure.from?`from=${failure.from}`:null].filter(token=>token!==null);throw new PmCliError(`Failed to apply history patch at entry ${entryNumber} (${tokens.join(", ")}). ${failure.reason??String(applied.error)}`,EXIT_CODE.GENERIC_FAILURE)}function replayHistoryToTarget(history,targetIndex){const first=history[0];if(first&&first.op!=="create"&&first.op!=="history_compact_baseline"){const baseline=tryApplyReplayPatch(EMPTY_REPLAY_DOCUMENT,first.patch);if(!baseline.ok||typeof baseline.document.metadata.id!="string")throw new PmCliError("History starts without a reconstructable item baseline.",EXIT_CODE.GENERIC_FAILURE,{code:"history_baseline_unavailable",required:"Recover the original create entry or a complete checkpoint from version control.",nextSteps:["Run pm history <id> --full to inspect the missing baseline."]})}const selected=history.slice(0,targetIndex+1),verification=verifyHistoryChain([...selected]);let document=structuredClone(EMPTY_REPLAY_DOCUMENT);for(let index=0;index<=targetIndex;index+=1){const entry=history[index];if(!entry)throw new PmCliError(`History target entry ${index+1} does not exist.`,EXIT_CODE.USAGE);document=applyHistoryPatch(document,entry.patch,index+1,entry.op)}if(!verification.ok)throw new PmCliError(`History cannot be replayed: ${verification.errors.join(", ")}.`,EXIT_CODE.GENERIC_FAILURE,{code:"history_replay_invalid",verification_errors:verification.errors,required:"Inspect the history integrity findings before attempting recovery.",nextSteps:["Run pm history <id> --verify --full."]});return document}function ensureMaterializedHistoryTarget(replayDocument,target){if(Object.keys(replayDocument.metadata).length>0){if(typeof replayDocument.metadata.id!="string"||!Array.isArray(replayDocument.metadata.tags))throw new PmCliError("History has no complete item baseline for this target.",EXIT_CODE.GENERIC_FAILURE,{code:"history_baseline_unavailable",required:"Recover the original create entry or a complete checkpoint from version control.",nextSteps:["Run pm history <id> --full to inspect the first recorded state."]});return replayDocument}throw new PmCliError(`History target ${target.raw} resolves to a deleted state; choose a version or timestamp where the item exists.`,EXIT_CODE.USAGE)}export{applyHistoryPatch,ensureMaterializedHistoryTarget,extractPatchFailureContext,replayHistoryToTarget,resolveHistoryTarget};
|
|
2
2
|
//# sourceMappingURL=projection.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="cfedb84f-0525-5e02-af0a-d0e5691b5e0a")}catch{}})();import{readFileIfExists}from"../fs/fs-utils.js";import{runActiveOnReadHooks}from"../extensions/index.js";import{EXIT_CODE}from"../shared/constants.js";import{findFirstMergeConflictMarker}from"../shared/conflict-markers.js";import{PmCliError}from"../shared/errors.js";async function readHistorySnapshot(historyPath,itemId){const raw=await readFileIfExists(historyPath);if(raw===null)return{raw,entries:[]};if(await runActiveOnReadHooks({path:historyPath,scope:"project"}),raw.trim()==="")return{raw,entries:[]};const conflictMarker=findFirstMergeConflictMarker(raw);if(conflictMarker)throw new PmCliError(`History for ${itemId} contains merge conflict markers at line ${conflictMarker.line} (${conflictMarker.marker}). Resolve <<<<<<< ======= >>>>>>> markers and retry.`,EXIT_CODE.GENERIC_FAILURE,{code:"history_merge_conflict_markers_detected",required:"Repair the history stream by resolving merge-conflict markers.",why:"Conflict markers break JSONL parsing and invalidate deterministic audit history.",examples:[`pm history ${itemId}`,`pm restore ${itemId} <timestamp-or-version>`],nextSteps:["Resolve or restore the history file, then rerun the command."]});const entries=[];for(const[index,rawLine]of raw.split(/\r?\n/).entries()){const line=rawLine.trim();if(line)try{entries.push(JSON.parse(line))}catch{throw new PmCliError(`History for ${itemId} contains invalid JSON at line ${index+1}. Repair or restore the history stream and retry.`,EXIT_CODE.GENERIC_FAILURE,{code:"history_json_invalid",nextSteps:[`Run pm history-repair ${itemId} --salvage-tail --dry-run to check whether only an invalid suffix is damaged.`]})}}return{raw,entries}}async function readHistoryEntries(historyPath,itemId){return(await readHistorySnapshot(historyPath,itemId)).entries}export{readHistoryEntries,readHistorySnapshot};
|
|
2
2
|
//# sourceMappingURL=read.js.map
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
-
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="8c80fb7b-da68-5bb8-a985-7de2d81aabd7")}catch(e2){}})();import jsonPatch from"fast-json-patch";import{historyDigest,resolveHistoryHashAlgorithm}from"./digest.js";import{findHistoryIdentityDiscontinuities}from"./identity.js";import{ITEM_METADATA_KEY_ORDER}from"../shared/constants.js";import{canonicalDocument}from"../item/item-format.js";import{toItemRecord}from"../item/item-record.js";import{orderObject,stableStringify}from"../shared/serialization.js";import{CURRENT_HISTORY_ITEM_HASH_VERSION,SUPPORTED_HISTORY_ITEM_HASH_VERSIONS,hashDocumentVerificationCandidates,resealHistoryRewrite,verifyHistoryRecordHash,verifyHistoryRewriteEvidence}from"./history.js";const EMPTY_REPLAY_DOCUMENT={metadata:{},body:""};function cloneEmptyReplayDocument(){return structuredClone(EMPTY_REPLAY_DOCUMENT)}function replayHash(document,version=CURRENT_HISTORY_ITEM_HASH_VERSION,algorithm){return replayHashVerificationCandidates(document,version,algorithm)[0]}function replayHashVerificationCandidates(document,version,algorithm){if(Object.keys(document.metadata).length===0||Array.isArray(document.metadata.tags)){try{return hashDocumentVerificationCandidates(replayToItemDocument(document),version,algorithm)}catch{}}const fallback=historyDigest(stableStringify({replay_fallback:true,metadata:document.metadata,body:document.body}),algorithm);return version===2?[fallback,fallback]:[fallback]}function matchReplayHashCandidates(before,after,version,entry,memo){const algorithm=resolveHistoryHashAlgorithm(entry.hash_algorithm);const memoKey=`${version}:${algorithm}`;const beforeHashes=memo?.before.get(memoKey)??replayHashVerificationCandidates(before,version,algorithm);const afterHashes=replayHashVerificationCandidates(after,version,algorithm);memo?.after.set(memoKey,afterHashes);return{beforeHashes,afterHashes,pairIndex:beforeHashes.findIndex((beforeHash,hashIndex)=>beforeHash===entry.before_hash&&afterHashes[hashIndex]===entry.after_hash),beforeIndex:beforeHashes.indexOf(entry.before_hash),afterIndex:afterHashes.indexOf(entry.after_hash)}}function replayToItemDocument(document){return{metadata:document.metadata,body:document.body}}function replayToCanonicalItemDocument(document,options={}){return canonicalDocument(replayToItemDocument(document),options)}function toReplayDocument(document){if(!document.metadata||Object.keys(document.metadata).length===0){return{metadata:{},body:document.body??""}}const canonical=canonicalDocument(document);return{metadata:orderObject(toItemRecord(canonical.metadata),ITEM_METADATA_KEY_ORDER),body:canonical.body}}function normalizeReplayPatchPath(path){if(path==="/front_matter"){return"/metadata"}if(path.startsWith("/front_matter/")){return`/metadata/${path.slice("/front_matter/".length)}`}return path}function isHistoryPatchOp(value){return typeof value==="object"&&value!==null&&typeof value.op==="string"&&typeof value.path==="string"}function normalizeReplayPatchOps(patch){if(!Array.isArray(patch)){return[]}return patch.filter(isHistoryPatchOp).map(operation=>({...operation,path:normalizeReplayPatchPath(operation.path),from:typeof operation.from==="string"?normalizeReplayPatchPath(operation.from):void 0}))}function isReplayDocumentShape(value){return typeof value==="object"&&value!==null&&"metadata"in value&&"body"in value&&typeof value.body==="string"&&typeof value.metadata==="object"&&value.metadata!==null}function tryApplyReplayPatch(current,patch){try{const normalizedPatch=normalizeReplayPatchOps(patch);const applied=jsonPatch.applyPatch(structuredClone(current),normalizedPatch,true,true).newDocument;if(!isReplayDocumentShape(applied)){return{ok:false,error:new Error("history_replay_invalid_document_shape")}}return{ok:true,document:{metadata:applied.metadata,body:applied.body}}}catch(error){return{ok:false,error}}}function supportedExplicitHistoryItemHashVersions(entries){return[...new Set(entries.map(entry=>entry.item_hash_version).filter(version=>version!==void 0&&SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(version)))]}function isUnsupportedExplicitHistoryItemHashVersion(version){return version!==void 0&&!SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(version)}function historyEntryHashCandidates(explicitVersion,authoritativeVersion){if(explicitVersion!==void 0){return[explicitVersion]}return authoritativeVersion===void 0?[...SUPPORTED_HISTORY_ITEM_HASH_VERSIONS]:[authoritativeVersion]}function historyEntryIntegrityError(entry){const recordVerification=verifyHistoryRecordHash(entry);if(!recordVerification.ok)return recordVerification.error;const rewriteVerification=verifyHistoryRewriteEvidence(entry);return rewriteVerification.ok?void 0:rewriteVerification.error}function verifyHistoryEntryInput(entry,replay){const integrityError=historyEntryIntegrityError(entry);if(integrityError)return{ok:false,error:integrityError};const applied=tryApplyReplayPatch(replay,entry.patch);return applied.ok?{ok:true,document:applied.document}:{ok:false,error:"patch_apply_failed"}}function assertHistoryEntryIntegrity(entry,index){const integrityError=historyEntryIntegrityError(entry);if(integrityError){throw new TypeError(`${integrityError}:entry_${index+1}`)}}function matchReplayEpochCandidates(before,after,candidates,entry,memo){const matches=[];for(const version of candidates){const match=matchReplayHashCandidates(before,after,version,entry,memo);matches.push({version,match});if(match.pairIndex>=0)break}return matches}function verifyHistoryChainWithVersion(entries){let replay=cloneEmptyReplayDocument();let beforeHashMemo=new Map;let detectedVersion;let authoritativeExplicitVersion;const errors=findHistoryIdentityDiscontinuities(entries).map(finding=>`verify_failed:duplicate_create:entry_${finding.repeated_create_index}:prior_${finding.prior_genesis_index}`);for(let index=0;index<entries.length;index+=1){const entry=entries[index];const explicitVersion=entry.item_hash_version;const unsupportedVersion=isUnsupportedExplicitHistoryItemHashVersion(explicitVersion);if(unsupportedVersion){errors.push(`verify_failed:unsupported_item_hash_version:${String(explicitVersion)}:entry_${index+1}`)}const input=verifyHistoryEntryInput(entry,replay);if(!input.ok){return{ok:false,errors:[...errors,`verify_failed:${input.error}:entry_${index+1}`]}}if(unsupportedVersion){replay=input.document;beforeHashMemo=new Map;detectedVersion=void 0;authoritativeExplicitVersion=void 0;continue}const candidates=historyEntryHashCandidates(explicitVersion,authoritativeExplicitVersion);const memo={before:beforeHashMemo,after:new Map};const candidateMatches=matchReplayEpochCandidates(replay,input.document,candidates,entry,memo);const matchingVersion=candidateMatches.find(({match})=>match.pairIndex>=0);if(matchingVersion===void 0){const beforeMatches=candidateMatches.some(({match})=>match.beforeIndex>=0);return{ok:false,errors:[...errors,`verify_failed:${beforeMatches?"after":"before"}_hash_mismatch:entry_${index+1}`]}}const version=matchingVersion.version;replay=input.document;beforeHashMemo=memo.after;detectedVersion=version;authoritativeExplicitVersion=explicitVersion??authoritativeExplicitVersion}if(errors.length>0){return{ok:false,errors,...detectedVersion===void 0?{}:{item_hash_version:detectedVersion}}}return{ok:true,errors:[],...detectedVersion===void 0?{}:{item_hash_version:detectedVersion}}}function verifyHistoryChain(entries){const result=verifyHistoryChainWithVersion(entries);return{ok:result.ok,errors:result.errors}}function tryApplySingleOp(document,op){try{const applied=jsonPatch.applyPatch(structuredClone(document),[op],true,false).newDocument;return{ok:true,document:applied}}catch{return{ok:false}}}function lenientApplyReplayPatch(current,patch){let working=structuredClone(current);let convertedReplaceToAdd=0;let skippedOps=0;for(const op of normalizeReplayPatchOps(patch)){const direct=tryApplySingleOp(working,op);if(direct.ok){working=direct.document;continue}if(op.op==="replace"){const asAdd=tryApplySingleOp(working,{...op,op:"add"});if(asAdd.ok){working=asAdd.document;convertedReplaceToAdd+=1;continue}}skippedOps+=1}const candidate=working;const document={metadata:typeof candidate.metadata==="object"&&candidate.metadata!==null?candidate.metadata:{},body:typeof candidate.body==="string"?candidate.body:current.body};return{document,convertedReplaceToAdd,skippedOps}}function resolveHistoryRepairItemHashVersion(entries){const explicitVersions=supportedExplicitHistoryItemHashVersions(entries);if(explicitVersions.length===1){return explicitVersions[0]}const verified=verifyHistoryChainWithVersion(entries);if(verified.ok&&verified.item_hash_version!==void 0){return verified.item_hash_version}if(explicitVersions.length===0){return 1}return CURRENT_HISTORY_ITEM_HASH_VERSION}function applyReanchorPatch(replay,entry){const strict=tryApplyReplayPatch(replay,entry.patch);if(strict.ok){return{next:strict.document,patch:entry.patch,repaired:false,converted:0,skipped:0}}const lenient=lenientApplyReplayPatch(replay,entry.patch);return{next:lenient.document,patch:jsonPatch.compare(replay,lenient.document),repaired:true,converted:lenient.convertedReplaceToAdd,skipped:lenient.skippedOps}}function reanchorHistoryEntries(entries,itemHashVersion=resolveHistoryRepairItemHashVersion(entries),options={}){const unsupportedIndex=entries.findIndex(entry=>isUnsupportedExplicitHistoryItemHashVersion(entry.item_hash_version));if(unsupportedIndex>=0){throw new TypeError(`unsupported_item_hash_version:${String(entries[unsupportedIndex]?.item_hash_version)}:entry_${unsupportedIndex+1}`)}let replay=cloneEmptyReplayDocument();const rewritten=[];const details=[];let entriesRehashed=0;let entriesPatchRepaired=0;let convertedReplaceToAdd=0;let skippedOps=0;let semanticIndex;const explicitItemHashVersion=itemHashVersion!==1||entries.some(entry=>entry.item_hash_version!==void 0);for(let index=0;index<entries.length;index+=1){const entry=entries[index];assertHistoryEntryIntegrity(entry,index);const patchApplication=applyReanchorPatch(replay,entry);const{next,patch:outPatch,repaired:patchRepaired,converted:entryConverted,skipped:entrySkipped}=patchApplication;convertedReplaceToAdd+=entryConverted;skippedOps+=entrySkipped;entriesPatchRepaired+=Number(patchRepaired);const hashMatch=matchReplayHashCandidates(replay,next,itemHashVersion,entry);if(semanticIndex===void 0||options.continuousHashSurface!==true){semanticIndex=[hashMatch.pairIndex,hashMatch.beforeIndex,hashMatch.afterIndex,Math.min(semanticIndex??0,hashMatch.beforeHashes.length-1)].find(candidate=>candidate>=0)}else{semanticIndex=Math.min(semanticIndex,hashMatch.beforeHashes.length-1)}const beforeHash=hashMatch.beforeHashes[semanticIndex];const afterHash=hashMatch.afterHashes[semanticIndex];const rehashed=beforeHash!==entry.before_hash||afterHash!==entry.after_hash;if(rehashed){entriesRehashed+=1}let rewrittenEntry={...entry,patch:outPatch,before_hash:beforeHash,after_hash:afterHash};if(explicitItemHashVersion){rewrittenEntry.item_hash_version=itemHashVersion}else{delete rewrittenEntry.item_hash_version}const versionChanged=rewrittenEntry.item_hash_version!==entry.item_hash_version;if(rehashed||patchRepaired||versionChanged){rewrittenEntry=resealHistoryRewrite(entry,rewrittenEntry,{retainOriginalPatch:patchRepaired})}rewritten.push(rewrittenEntry);details.push({index:index+1,rehashed,patch_repaired:patchRepaired,converted_replace_to_add:entryConverted,skipped_ops:entrySkipped});replay=next}return{entries:rewritten,finalDocument:replay,entriesRehashed,entriesPatchRepaired,convertedReplaceToAdd,skippedOps,details,itemHashVersion,explicitItemHashVersion}}function historyEntriesToRaw(entries){if(entries.length===0){return""}return`${entries.map(entry=>JSON.stringify(entry)).join("\n")}
|
|
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]="3bf5f300-1829-5009-ae96-be7df309b589")}catch{}})();import jsonPatch from"fast-json-patch";import{historyDigest,resolveHistoryHashAlgorithm}from"./digest.js";import{findHistoryIdentityDiscontinuities}from"./identity.js";import{ITEM_METADATA_KEY_ORDER}from"../shared/constants.js";import{canonicalDocument}from"../item/item-format.js";import{toItemRecord}from"../item/item-record.js";import{orderObject,stableStringify}from"../shared/serialization.js";import{CURRENT_HISTORY_ITEM_HASH_VERSION,SUPPORTED_HISTORY_ITEM_HASH_VERSIONS,hashDocumentVerificationCandidates,resealHistoryRewrite,verifyHistoryRecordHash,verifyHistoryRewriteEvidence}from"./history.js";const EMPTY_REPLAY_DOCUMENT={metadata:{},body:""};function cloneEmptyReplayDocument(){return structuredClone(EMPTY_REPLAY_DOCUMENT)}function replayHash(document,version=CURRENT_HISTORY_ITEM_HASH_VERSION,algorithm){return replayHashVerificationCandidates(document,version,algorithm)[0]}function replayHashVerificationCandidates(document,version,algorithm){if(Object.keys(document.metadata).length===0||Array.isArray(document.metadata.tags))try{return hashDocumentVerificationCandidates(replayToItemDocument(document),version,algorithm)}catch{}const fallback=historyDigest(stableStringify({replay_fallback:!0,metadata:document.metadata,body:document.body}),algorithm);return version===2?[fallback,fallback]:[fallback]}function matchReplayHashCandidates(before,after,version,entry,memo){const algorithm=resolveHistoryHashAlgorithm(entry.hash_algorithm),memoKey=`${version}:${algorithm}`,beforeHashes=memo?.before.get(memoKey)??replayHashVerificationCandidates(before,version,algorithm),afterHashes=replayHashVerificationCandidates(after,version,algorithm);return memo?.after.set(memoKey,afterHashes),{beforeHashes,afterHashes,pairIndex:beforeHashes.findIndex((beforeHash,hashIndex)=>beforeHash===entry.before_hash&&afterHashes[hashIndex]===entry.after_hash),beforeIndex:beforeHashes.indexOf(entry.before_hash),afterIndex:afterHashes.indexOf(entry.after_hash)}}function replayToItemDocument(document){return{metadata:document.metadata,body:document.body}}function replayToCanonicalItemDocument(document,options={}){return canonicalDocument(replayToItemDocument(document),options)}function toReplayDocument(document){if(!document.metadata||Object.keys(document.metadata).length===0)return{metadata:{},body:document.body??""};const canonical=canonicalDocument(document);return{metadata:orderObject(toItemRecord(canonical.metadata),ITEM_METADATA_KEY_ORDER),body:canonical.body}}function normalizeReplayPatchPath(path){return path==="/front_matter"?"/metadata":path.startsWith("/front_matter/")?`/metadata/${path.slice(14)}`:path}function isHistoryPatchOp(value){return typeof value=="object"&&value!==null&&typeof value.op=="string"&&typeof value.path=="string"}function normalizeReplayPatchOps(patch){return Array.isArray(patch)?patch.filter(isHistoryPatchOp).map(operation=>({...operation,path:normalizeReplayPatchPath(operation.path),from:typeof operation.from=="string"?normalizeReplayPatchPath(operation.from):void 0})):[]}function isReplayDocumentShape(value){return typeof value=="object"&&value!==null&&"metadata"in value&&"body"in value&&typeof value.body=="string"&&typeof value.metadata=="object"&&value.metadata!==null}function tryApplyReplayPatch(current,patch){try{const normalizedPatch=normalizeReplayPatchOps(patch),applied=jsonPatch.applyPatch(structuredClone(current),normalizedPatch,!0,!0).newDocument;return isReplayDocumentShape(applied)?{ok:!0,document:{metadata:applied.metadata,body:applied.body}}:{ok:!1,error:new Error("history_replay_invalid_document_shape")}}catch(error){return{ok:!1,error}}}function supportedExplicitHistoryItemHashVersions(entries){return[...new Set(entries.map(entry=>entry.item_hash_version).filter(version=>version!==void 0&&SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(version)))]}function isUnsupportedExplicitHistoryItemHashVersion(version){return version!==void 0&&!SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(version)}function historyEntryHashCandidates(explicitVersion,authoritativeVersion){return explicitVersion!==void 0?[explicitVersion]:authoritativeVersion===void 0?[...SUPPORTED_HISTORY_ITEM_HASH_VERSIONS]:[authoritativeVersion]}function historyEntryIntegrityError(entry){const recordVerification=verifyHistoryRecordHash(entry);if(!recordVerification.ok)return recordVerification.error;const rewriteVerification=verifyHistoryRewriteEvidence(entry);return rewriteVerification.ok?void 0:rewriteVerification.error}function verifyHistoryEntryInput(entry,replay){const integrityError=historyEntryIntegrityError(entry);if(integrityError)return{ok:!1,error:integrityError};const applied=tryApplyReplayPatch(replay,entry.patch);return applied.ok?{ok:!0,document:applied.document}:{ok:!1,error:"patch_apply_failed"}}function assertHistoryEntryIntegrity(entry,index){const integrityError=historyEntryIntegrityError(entry);if(integrityError)throw new TypeError(`${integrityError}:entry_${index+1}`)}function matchReplayEpochCandidates(before,after,candidates,entry,memo){const matches=[];for(const version of candidates){const match=matchReplayHashCandidates(before,after,version,entry,memo);if(matches.push({version,match}),match.pairIndex>=0)break}return matches}function verifyHistoryChainWithVersion(entries){let replay=cloneEmptyReplayDocument(),beforeHashMemo=new Map,detectedVersion,authoritativeExplicitVersion;const errors=findHistoryIdentityDiscontinuities(entries).map(finding=>`verify_failed:duplicate_create:entry_${finding.repeated_create_index}:prior_${finding.prior_genesis_index}`);for(let index=0;index<entries.length;index+=1){const entry=entries[index],explicitVersion=entry.item_hash_version,unsupportedVersion=isUnsupportedExplicitHistoryItemHashVersion(explicitVersion);unsupportedVersion&&errors.push(`verify_failed:unsupported_item_hash_version:${String(explicitVersion)}:entry_${index+1}`);const input=verifyHistoryEntryInput(entry,replay);if(!input.ok)return{ok:!1,errors:[...errors,`verify_failed:${input.error}:entry_${index+1}`]};if(unsupportedVersion){replay=input.document,beforeHashMemo=new Map,detectedVersion=void 0,authoritativeExplicitVersion=void 0;continue}const candidates=historyEntryHashCandidates(explicitVersion,authoritativeExplicitVersion),memo={before:beforeHashMemo,after:new Map},candidateMatches=matchReplayEpochCandidates(replay,input.document,candidates,entry,memo),matchingVersion=candidateMatches.find(({match})=>match.pairIndex>=0);if(matchingVersion===void 0){const beforeMatches=candidateMatches.some(({match})=>match.beforeIndex>=0);return{ok:!1,errors:[...errors,`verify_failed:${beforeMatches?"after":"before"}_hash_mismatch:entry_${index+1}`]}}const version=matchingVersion.version;replay=input.document,beforeHashMemo=memo.after,detectedVersion=version,authoritativeExplicitVersion=explicitVersion??authoritativeExplicitVersion}return errors.length>0?{ok:!1,errors,...detectedVersion===void 0?{}:{item_hash_version:detectedVersion}}:{ok:!0,errors:[],...detectedVersion===void 0?{}:{item_hash_version:detectedVersion}}}function verifyHistoryChain(entries){const result=verifyHistoryChainWithVersion(entries);return{ok:result.ok,errors:result.errors}}function tryApplySingleOp(document,op){try{return{ok:!0,document:jsonPatch.applyPatch(structuredClone(document),[op],!0,!1).newDocument}}catch{return{ok:!1}}}function lenientApplyReplayPatch(current,patch){let working=structuredClone(current),convertedReplaceToAdd=0,skippedOps=0;for(const op of normalizeReplayPatchOps(patch)){const direct=tryApplySingleOp(working,op);if(direct.ok){working=direct.document;continue}if(op.op==="replace"){const asAdd=tryApplySingleOp(working,{...op,op:"add"});if(asAdd.ok){working=asAdd.document,convertedReplaceToAdd+=1;continue}}skippedOps+=1}const candidate=working;return{document:{metadata:typeof candidate.metadata=="object"&&candidate.metadata!==null?candidate.metadata:{},body:typeof candidate.body=="string"?candidate.body:current.body},convertedReplaceToAdd,skippedOps}}function resolveHistoryRepairItemHashVersion(entries){const explicitVersions=supportedExplicitHistoryItemHashVersions(entries);if(explicitVersions.length===1)return explicitVersions[0];const verified=verifyHistoryChainWithVersion(entries);return verified.ok&&verified.item_hash_version!==void 0?verified.item_hash_version:explicitVersions.length===0?1:CURRENT_HISTORY_ITEM_HASH_VERSION}function applyReanchorPatch(replay,entry){const strict=tryApplyReplayPatch(replay,entry.patch);if(strict.ok)return{next:strict.document,patch:entry.patch,repaired:!1,converted:0,skipped:0};const lenient=lenientApplyReplayPatch(replay,entry.patch);return{next:lenient.document,patch:jsonPatch.compare(replay,lenient.document),repaired:!0,converted:lenient.convertedReplaceToAdd,skipped:lenient.skippedOps}}function reanchorHistoryEntries(entries,itemHashVersion=resolveHistoryRepairItemHashVersion(entries),options={}){const unsupportedIndex=entries.findIndex(entry=>isUnsupportedExplicitHistoryItemHashVersion(entry.item_hash_version));if(unsupportedIndex>=0)throw new TypeError(`unsupported_item_hash_version:${String(entries[unsupportedIndex]?.item_hash_version)}:entry_${unsupportedIndex+1}`);let replay=cloneEmptyReplayDocument();const rewritten=[],details=[];let entriesRehashed=0,entriesPatchRepaired=0,convertedReplaceToAdd=0,skippedOps=0,semanticIndex;const explicitItemHashVersion=itemHashVersion!==1||entries.some(entry=>entry.item_hash_version!==void 0);for(let index=0;index<entries.length;index+=1){const entry=entries[index];assertHistoryEntryIntegrity(entry,index);const patchApplication=applyReanchorPatch(replay,entry),{next,patch:outPatch,repaired:patchRepaired,converted:entryConverted,skipped:entrySkipped}=patchApplication;convertedReplaceToAdd+=entryConverted,skippedOps+=entrySkipped,entriesPatchRepaired+=Number(patchRepaired);const hashMatch=matchReplayHashCandidates(replay,next,itemHashVersion,entry);semanticIndex===void 0||options.continuousHashSurface!==!0?semanticIndex=[hashMatch.pairIndex,hashMatch.beforeIndex,hashMatch.afterIndex,Math.min(semanticIndex??0,hashMatch.beforeHashes.length-1)].find(candidate=>candidate>=0):semanticIndex=Math.min(semanticIndex,hashMatch.beforeHashes.length-1);const beforeHash=hashMatch.beforeHashes[semanticIndex],afterHash=hashMatch.afterHashes[semanticIndex],rehashed=beforeHash!==entry.before_hash||afterHash!==entry.after_hash;rehashed&&(entriesRehashed+=1);let rewrittenEntry={...entry,patch:outPatch,before_hash:beforeHash,after_hash:afterHash};explicitItemHashVersion?rewrittenEntry.item_hash_version=itemHashVersion:delete rewrittenEntry.item_hash_version;const versionChanged=rewrittenEntry.item_hash_version!==entry.item_hash_version;(rehashed||patchRepaired||versionChanged)&&(rewrittenEntry=resealHistoryRewrite(entry,rewrittenEntry,{retainOriginalPatch:patchRepaired})),rewritten.push(rewrittenEntry),details.push({index:index+1,rehashed,patch_repaired:patchRepaired,converted_replace_to_add:entryConverted,skipped_ops:entrySkipped}),replay=next}return{entries:rewritten,finalDocument:replay,entriesRehashed,entriesPatchRepaired,convertedReplaceToAdd,skippedOps,details,itemHashVersion,explicitItemHashVersion}}function historyEntriesToRaw(entries){return entries.length===0?"":`${entries.map(entry=>JSON.stringify(entry)).join(`
|
|
2
|
+
`)}
|
|
2
3
|
`}export{EMPTY_REPLAY_DOCUMENT,cloneEmptyReplayDocument,historyEntriesToRaw,lenientApplyReplayPatch,normalizeReplayPatchOps,normalizeReplayPatchPath,reanchorHistoryEntries,replayHash,replayHashVerificationCandidates,replayToCanonicalItemDocument,replayToItemDocument,resolveHistoryRepairItemHashVersion,toReplayDocument,tryApplyReplayPatch,verifyHistoryChain,verifyHistoryChainWithVersion};
|
|
3
4
|
//# sourceMappingURL=replay.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="be69f1e8-4543-5cf5-abb0-9d38ca1d0cc6")}catch{}})();import{statSync}from"node:fs";import{normalizeItemId,normalizeRawItemId}from"../item/id.js";import{getHistoryPath}from"../store/paths.js";import{EXIT_CODE}from"../shared/constants.js";import{renderPmCommand}from"../shared/command-line.js";import{PmCliError}from"../shared/errors.js";import{readHistoryEntries}from"./read.js";import{applyHistoryPatch,replayHistoryToTarget,resolveHistoryTarget}from"./projection.js";import{EMPTY_REPLAY_DOCUMENT}from"./replay.js";import{historyVersionOffset}from"./version-address.js";function resolveDeletedRecoveryTarget(entries,id){let materializedIndex=-1,document=structuredClone(EMPTY_REPLAY_DOCUMENT);for(const[index,entry]of entries.entries()){if(document=applyHistoryPatch(document,entry.patch,index+1,entry.op),document.metadata.id!==void 0&&document.metadata.id!==id)throw new PmCliError(`History belongs to item ${String(document.metadata.id)}, expected ${id}.`,EXIT_CODE.GENERIC_FAILURE,{code:"history_replay_invalid",required:"Recover the correct history stream for this item before attempting restoration."});document.metadata.id===id&&Array.isArray(document.metadata.tags)&&(materializedIndex=index)}const offset=historyVersionOffset(entries,!0),version=materializedIndex<0||offset===null?null:offset+materializedIndex+1;let target=version===null?void 0:String(version);if(materializedIndex>=0&&target===void 0){const timestamp=entries[materializedIndex].ts;resolveHistoryTarget(timestamp,entries).historyIndex===materializedIndex&&(target=timestamp)}return{version,target}}async function buildDeletedItemError(pmRoot,rawId,idPrefix){const candidates=new Set([normalizeItemId(rawId,idPrefix),normalizeRawItemId(rawId)]);for(const id of candidates){const historyPath=getHistoryPath(pmRoot,id);if(!statSync(historyPath,{throwIfNoEntry:!1})?.isFile())continue;const entries=await readHistoryEntries(historyPath,id);let deletionIndex=-1;if(entries.forEach((entry,index)=>{entry.op==="delete"&&(deletionIndex=index)}),deletionIndex<0)continue;const final=replayHistoryToTarget(entries,entries.length-1);if(Object.keys(final.metadata).length!==0)continue;const{version,target}=resolveDeletedRecoveryTarget(entries,id),readArgs=target===void 0?["history",id,"--verify"]:["get",id,"--at",target],readCommand=renderPmCommand(readArgs);return new PmCliError(`Item ${id} was deleted at ${entries[deletionIndex].ts}; its history is retained.`,EXIT_CODE.NOT_FOUND,{code:"item_deleted",required:"Read a retained materialized version, then restore it if the item should exist again.",item_id:id,tombstone:{deleted:!0,deleted_at:entries[deletionIndex].ts,recoverable:target!==void 0,last_materialized_version:version},nextSteps:[readCommand,...target===void 0?["Recover the pre-compaction history from version control."]:[renderPmCommand(["restore",id,target])]],recovery:{suggested_retry:readCommand,suggested_retry_args:readArgs}})}}export{buildDeletedItemError};
|
|
2
2
|
//# sourceMappingURL=tombstone.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="5db05e2f-4742-526b-b1c8-b97ff302b40e")}catch{}})();import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";function historyVersionOffset(history,allowUnknown=!1){const first=history[0];if(first?.op!=="history_compact_baseline")return 0;const receipt=first.context?.history_compaction,offset=typeof receipt=="object"&&receipt!==null&&"version_offset"in receipt?receipt.version_offset:void 0;if(typeof offset=="number"&&Number.isSafeInteger(offset)&&offset>=0&&Number.isSafeInteger(offset+history.length))return offset;if(allowUnknown)return null;throw new PmCliError("This compacted stream has no trustworthy version offset; numeric history addresses are unavailable.",EXIT_CODE.USAGE,{code:"history_version_mapping_unavailable",required:"Use a retained timestamp or recover the pre-compaction stream from version control.",nextSteps:["Run pm history <id> --full to inspect the retained timestamps and checkpoint evidence."]})}export{historyVersionOffset};
|
|
2
2
|
//# sourceMappingURL=version-address.js.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="b6012be6-13b6-54b9-91ed-c9093423b1c2")}catch(e2){}})();import fs from"node:fs/promises";import path from"node:path";import{readFileIfExists,writeFileAtomic}from"../fs/fs-utils.js";import{acquireLock}from"../lock/lock.js";import{EMPTY_CANONICAL_DOCUMENT,EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{stableStringify}from"../shared/serialization.js";import{nowIso}from"../shared/time.js";import{appendHistoryEntry,createHistoryEntry}from"./history.js";import{readHistoryEntries}from"./read.js";import{cloneEmptyReplayDocument,replayToItemDocument,tryApplyReplayPatch,verifyHistoryChain}from"./replay.js";const WORKSPACE_HISTORY_ID="_workspace";function getWorkspaceHistoryPath(pmRoot){return path.join(pmRoot,"history",`${WORKSPACE_HISTORY_ID}.jsonl`)}function workspaceDocument(documents,timestamp){const metadata={id:WORKSPACE_HISTORY_ID,title:"Workspace state",description:"Audited singleton workspace document state.",type:"Chore",status:"open",priority:2,tags:["workspace-history"],created_at:timestamp,updated_at:timestamp,documents};return{metadata,body:""}}function replayWorkspaceEntries(entries,count=entries.length){let replay=cloneEmptyReplayDocument();for(const entry of entries.slice(0,count)){const applied=tryApplyReplayPatch(replay,entry.patch);replay=applied.document}return replayToItemDocument(replay)}function workspaceDocuments(document){return"documents"in document.metadata&&typeof document.metadata.documents==="object"&&document.metadata.documents!==null&&!Array.isArray(document.metadata.documents)?document.metadata.documents:{}}function throwWorkspaceHistoryVerificationFailure(errors){throw new PmCliError(`Workspace history verification failed: ${errors.join(", ")}`,EXIT_CODE.CONFLICT,{code:"workspace_history_chain_invalid",reason:"workspace_history_chain_verification_failed",verification_errors:[...errors],required:"Repair the _workspace history chain before reading, reconciling, restoring, or appending audited singleton state.",why:"Continuing against an unverifiable append-only stream could hide or compound workspace state corruption.",examples:["pm history _workspace --verify --json","pm validate --check-history-drift --fix-hints --json"],nextSteps:["Inspect the exact verification_errors and preserve the corrupt stream as evidence.","Use the history-drift remediation returned by validate before retrying the refused operation."],recovery:{recovery_mode:"compact",next_best_command:"pm history _workspace --verify --json"}})}function resolveGovernedDocumentPath(pmRoot,filePath){const absolutePath=path.resolve(filePath);const documentPath=path.relative(pmRoot,absolutePath).replaceAll("\\","/");if(documentPath.length===0||documentPath===".."||documentPath.startsWith("../")||path.isAbsolute(documentPath)){throw new TypeError("Workspace history document path must stay inside the tracker root")}return{documentPath,absolutePath}}async function inspectWorkspaceHistoryState(pmRoot){const entries=await readHistoryEntries(getWorkspaceHistoryPath(pmRoot),WORKSPACE_HISTORY_ID);const verification=verifyHistoryChain(entries);if(!verification.ok){throwWorkspaceHistoryVerificationFailure(verification.errors)}const documents=workspaceDocuments(entries.length===0?EMPTY_CANONICAL_DOCUMENT:replayWorkspaceEntries(entries));const matching=[];const mismatched=[];const missing=[];const unreadable=[];for(const documentPath of Object.keys(documents).sort()){let raw;try{const resolved=resolveGovernedDocumentPath(pmRoot,path.resolve(pmRoot,documentPath));raw=await readFileIfExists(resolved.absolutePath);if(raw===null){missing.push(documentPath);continue}const current=JSON.parse(raw);(stableStringify(current)===stableStringify(documents[documentPath])?matching:mismatched).push(documentPath)}catch{unreadable.push(documentPath)}}return{ok:mismatched.length===0&&missing.length===0&&unreadable.length===0,document_count:Object.keys(documents).length,matching_documents:matching,mismatched_documents:mismatched,missing_documents:missing,unreadable_documents:unreadable}}async function appendWorkspaceHistoryChangeLocked(change){const historyPath=getWorkspaceHistoryPath(change.pmRoot);const entries=await readHistoryEntries(historyPath,WORKSPACE_HISTORY_ID);const verification=verifyHistoryChain(entries);if(!verification.ok){throwWorkspaceHistoryVerificationFailure(verification.errors)}const idempotentEntry=change.idempotencyKey===void 0?void 0:entries.find(entry2=>entry2.op===`${change.op}:${change.idempotencyKey}`);if(idempotentEntry){return{entry:idempotentEntry,historyPath}}const timestamp=nowIso();const beforeDocument=entries.length===0?EMPTY_CANONICAL_DOCUMENT:replayWorkspaceEntries(entries);const priorDocuments=workspaceDocuments(beforeDocument);const recordedBefore=priorDocuments[change.documentPath];if(recordedBefore!==void 0&&stableStringify(recordedBefore)!==stableStringify(change.before)){throw new PmCliError(`Workspace history state for "${change.documentPath}" changed outside the audited mutation path.`,EXIT_CODE.CONFLICT,{code:"workspace_history_state_conflict",reason:"out_of_band_workspace_state",required:"Reconcile the singleton document with its matching _workspace history state before retrying the mutation.",why:"Accepting the write would make the append-only audit stream describe a state that was not actually observed.",examples:["pm history _workspace --verify","pm validate --check-history-drift --fix-hints"],nextSteps:["Review the version-control change that altered the singleton and preserve the intended document plus its matching workspace history.","Rerun the original mutation only after the on-disk singleton agrees with the latest audited workspace state."],recovery:{recovery_mode:"compact",next_best_command:"pm history _workspace --verify"}})}const afterDocument=workspaceDocument({...priorDocuments,[change.documentPath]:change.after},entries.length===0?timestamp:beforeDocument.metadata.created_at);const entry=createHistoryEntry({nowIso:timestamp,author:change.author,op:change.idempotencyKey===void 0?change.op:`${change.op}:${change.idempotencyKey}`,before:beforeDocument,after:afterDocument,message:change.message});await appendHistoryEntry(historyPath,entry);return{entry,historyPath}}async function appendWorkspaceHistoryChange(change){const release=await acquireLock(change.pmRoot,"workspace-history",change.lockTtlSeconds,change.author,false,false,change.lockWaitMs);try{return await appendWorkspaceHistoryChangeLocked(change)}finally{await release()}}async function appendWorkspaceAuditEvent(options){const release=await acquireLock(options.pmRoot,"workspace-history",options.lockTtlSeconds,options.author,false,false,options.lockWaitMs);try{const historyPath=getWorkspaceHistoryPath(options.pmRoot);const entries=await readHistoryEntries(historyPath,WORKSPACE_HISTORY_ID);const verification=verifyHistoryChain(entries);if(!verification.ok){throwWorkspaceHistoryVerificationFailure(verification.errors)}const beforeDocument=entries.length===0?EMPTY_CANONICAL_DOCUMENT:replayWorkspaceEntries(entries);const entry=createHistoryEntry({nowIso:nowIso(),author:options.author,op:options.op,before:beforeDocument,after:beforeDocument,message:options.message,context:options.context});await appendHistoryEntry(historyPath,entry);return{entry,historyPath}}finally{await release()}}async function writeWorkspaceJsonWithHistoryLocked(params,beforeRaw){if(beforeRaw===params.raw)return false;const before=beforeRaw===null?null:JSON.parse(beforeRaw);const after=JSON.parse(params.raw);await writeFileAtomic(params.filePath,params.raw);try{if(beforeRaw!==null||params.recordCreation!==false){await appendWorkspaceHistoryChangeLocked({pmRoot:params.pmRoot,documentPath:path.relative(params.pmRoot,params.filePath).replaceAll("\\","/"),before,after,op:params.op,idempotencyKey:params.idempotencyKey,author:params.author,lockTtlSeconds:params.lockTtlSeconds,lockWaitMs:params.lockWaitMs,message:params.message})}}catch(error){if(beforeRaw===null){await fs.rm(params.filePath,{force:true})}else{await writeFileAtomic(params.filePath,beforeRaw)}throw error}return true}async function mutateWorkspaceJsonWithHistory(params){const{documentPath}=resolveGovernedDocumentPath(params.pmRoot,params.filePath);const release=await acquireLock(params.pmRoot,"workspace-history",params.lockTtlSeconds,params.author,false,false,params.lockWaitMs);try{const beforeRaw=await readFileIfExists(params.filePath);if(params.dryRun===true||params.idempotencyKey!==void 0){const entries=await readHistoryEntries(getWorkspaceHistoryPath(params.pmRoot),WORKSPACE_HISTORY_ID);const verification=verifyHistoryChain(entries);if(!verification.ok)throwWorkspaceHistoryVerificationFailure(verification.errors);const recorded=workspaceDocuments(entries.length===0?EMPTY_CANONICAL_DOCUMENT:replayWorkspaceEntries(entries))[documentPath];if(recorded!==void 0&&stableStringify(recorded)!==stableStringify(beforeRaw===null?null:JSON.parse(beforeRaw))){throw new PmCliError(`Workspace history state for "${documentPath}" changed outside the audited mutation path.`,EXIT_CODE.CONFLICT,{code:"workspace_history_state_conflict"})}if(params.idempotencyKey!==void 0&&entries.some(entry=>entry.op===`${params.op}:${params.idempotencyKey}`)){return{changed:false,result:void 0,replayed:true}}}const mutation=await params.mutate(beforeRaw);JSON.parse(mutation.raw);if(params.dryRun===true){return{changed:beforeRaw!==mutation.raw,result:mutation.result}}return{changed:await writeWorkspaceJsonWithHistoryLocked({...params,raw:mutation.raw},beforeRaw),result:mutation.result}}finally{await release()}}async function writeWorkspaceJsonWithHistory(params){const release=await acquireLock(params.pmRoot,"workspace-history",params.lockTtlSeconds,params.author,false,false,params.lockWaitMs);try{return await writeWorkspaceJsonWithHistoryLocked(params,await readFileIfExists(params.filePath))}finally{await release()}}async function reconcileWorkspaceJsonHistory(options){const authorizationDecision=options.authorizationDecision.trim();if(!authorizationDecision){throw new TypeError("Workspace history reconciliation requires an authorization decision")}const release=await acquireLock(options.pmRoot,"workspace-history",options.lockTtlSeconds,options.author,false,false,options.lockWaitMs);try{const{documentPath,absolutePath}=resolveGovernedDocumentPath(options.pmRoot,options.filePath);const historyPath=getWorkspaceHistoryPath(options.pmRoot);const entries=await readHistoryEntries(historyPath,WORKSPACE_HISTORY_ID);const verification=verifyHistoryChain(entries);if(!verification.ok){throwWorkspaceHistoryVerificationFailure(verification.errors)}const beforeDocument=replayWorkspaceEntries(entries);const priorDocuments=workspaceDocuments(beforeDocument);if(!Object.hasOwn(priorDocuments,documentPath)){throw new TypeError(`Workspace history does not govern document ${documentPath}`)}const raw=await readFileIfExists(absolutePath);if(raw===null){throw new TypeError(`Workspace history document is missing: ${documentPath}`)}const current=JSON.parse(raw);if(stableStringify(priorDocuments[documentPath])===stableStringify(current)){return{changed:false,historyPath}}const timestamp=nowIso();const entry=createHistoryEntry({nowIso:timestamp,author:options.author,op:options.op,before:beforeDocument,after:workspaceDocument({...priorDocuments,[documentPath]:current},beforeDocument.metadata.created_at),message:options.message,context:{reason:"out_of_band_workspace_state_reconciliation",document_path:documentPath,authorization_decision:authorizationDecision}});await appendHistoryEntry(historyPath,entry);return{changed:true,entry,historyPath}}finally{await release()}}async function restoreWorkspaceJsonFromHistory(options){const release=await acquireLock(options.pmRoot,"workspace-history",options.lockTtlSeconds,options.author,false,false,options.lockWaitMs);try{const{documentPath,absolutePath}=resolveGovernedDocumentPath(options.pmRoot,options.filePath);const entries=await readHistoryEntries(getWorkspaceHistoryPath(options.pmRoot),WORKSPACE_HISTORY_ID);const verification=verifyHistoryChain(entries);if(!verification.ok){throwWorkspaceHistoryVerificationFailure(verification.errors)}if(!Number.isInteger(options.targetVersion)||options.targetVersion<1||options.targetVersion>entries.length){throw new TypeError(`Invalid workspace history target version: ${String(options.targetVersion)}`)}const target=workspaceDocuments(replayWorkspaceEntries(entries,options.targetVersion))[documentPath];if(target===void 0){throw new TypeError(`Workspace history version ${options.targetVersion} does not contain ${documentPath}`)}const beforeRaw=await readFileIfExists(absolutePath);const targetRaw=`${JSON.stringify(target,null,2)}
|
|
2
|
-
`;if(beforeRaw===targetRaw)return{document_path:documentPath,restored_from_version:options.targetVersion,changed
|
|
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]="af606b47-d071-5724-b1e7-de4e1e5d7385")}catch{}})();import fs from"node:fs/promises";import path from"node:path";import{readFileIfExists,writeFileAtomic}from"../fs/fs-utils.js";import{acquireLock}from"../lock/lock.js";import{EMPTY_CANONICAL_DOCUMENT,EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{stableStringify}from"../shared/serialization.js";import{nowIso}from"../shared/time.js";import{appendHistoryEntry,createHistoryEntry}from"./history.js";import{readHistoryEntries}from"./read.js";import{cloneEmptyReplayDocument,replayToItemDocument,tryApplyReplayPatch,verifyHistoryChain}from"./replay.js";const WORKSPACE_HISTORY_ID="_workspace";function getWorkspaceHistoryPath(pmRoot){return path.join(pmRoot,"history",`${WORKSPACE_HISTORY_ID}.jsonl`)}function workspaceDocument(documents,timestamp){return{metadata:{id:WORKSPACE_HISTORY_ID,title:"Workspace state",description:"Audited singleton workspace document state.",type:"Chore",status:"open",priority:2,tags:["workspace-history"],created_at:timestamp,updated_at:timestamp,documents},body:""}}function replayWorkspaceEntries(entries,count=entries.length){let replay=cloneEmptyReplayDocument();for(const entry of entries.slice(0,count))replay=tryApplyReplayPatch(replay,entry.patch).document;return replayToItemDocument(replay)}function workspaceDocuments(document){return"documents"in document.metadata&&typeof document.metadata.documents=="object"&&document.metadata.documents!==null&&!Array.isArray(document.metadata.documents)?document.metadata.documents:{}}function throwWorkspaceHistoryVerificationFailure(errors){throw new PmCliError(`Workspace history verification failed: ${errors.join(", ")}`,EXIT_CODE.CONFLICT,{code:"workspace_history_chain_invalid",reason:"workspace_history_chain_verification_failed",verification_errors:[...errors],required:"Repair the _workspace history chain before reading, reconciling, restoring, or appending audited singleton state.",why:"Continuing against an unverifiable append-only stream could hide or compound workspace state corruption.",examples:["pm history _workspace --verify --json","pm validate --check-history-drift --fix-hints --json"],nextSteps:["Inspect the exact verification_errors and preserve the corrupt stream as evidence.","Use the history-drift remediation returned by validate before retrying the refused operation."],recovery:{recovery_mode:"compact",next_best_command:"pm history _workspace --verify --json"}})}function resolveGovernedDocumentPath(pmRoot,filePath){const absolutePath=path.resolve(filePath),documentPath=path.relative(pmRoot,absolutePath).replaceAll("\\","/");if(documentPath.length===0||documentPath===".."||documentPath.startsWith("../")||path.isAbsolute(documentPath))throw new TypeError("Workspace history document path must stay inside the tracker root");return{documentPath,absolutePath}}async function inspectWorkspaceHistoryState(pmRoot){const entries=await readHistoryEntries(getWorkspaceHistoryPath(pmRoot),WORKSPACE_HISTORY_ID),verification=verifyHistoryChain(entries);verification.ok||throwWorkspaceHistoryVerificationFailure(verification.errors);const documents=workspaceDocuments(entries.length===0?EMPTY_CANONICAL_DOCUMENT:replayWorkspaceEntries(entries)),matching=[],mismatched=[],missing=[],unreadable=[];for(const documentPath of Object.keys(documents).sort()){let raw;try{const resolved=resolveGovernedDocumentPath(pmRoot,path.resolve(pmRoot,documentPath));if(raw=await readFileIfExists(resolved.absolutePath),raw===null){missing.push(documentPath);continue}const current=JSON.parse(raw);(stableStringify(current)===stableStringify(documents[documentPath])?matching:mismatched).push(documentPath)}catch{unreadable.push(documentPath)}}return{ok:mismatched.length===0&&missing.length===0&&unreadable.length===0,document_count:Object.keys(documents).length,matching_documents:matching,mismatched_documents:mismatched,missing_documents:missing,unreadable_documents:unreadable}}async function appendWorkspaceHistoryChangeLocked(change){const historyPath=getWorkspaceHistoryPath(change.pmRoot),entries=await readHistoryEntries(historyPath,WORKSPACE_HISTORY_ID),verification=verifyHistoryChain(entries);verification.ok||throwWorkspaceHistoryVerificationFailure(verification.errors);const idempotentEntry=change.idempotencyKey===void 0?void 0:entries.find(entry2=>entry2.op===`${change.op}:${change.idempotencyKey}`);if(idempotentEntry)return{entry:idempotentEntry,historyPath};const timestamp=nowIso(),beforeDocument=entries.length===0?EMPTY_CANONICAL_DOCUMENT:replayWorkspaceEntries(entries),priorDocuments=workspaceDocuments(beforeDocument),recordedBefore=priorDocuments[change.documentPath];if(recordedBefore!==void 0&&stableStringify(recordedBefore)!==stableStringify(change.before))throw new PmCliError(`Workspace history state for "${change.documentPath}" changed outside the audited mutation path.`,EXIT_CODE.CONFLICT,{code:"workspace_history_state_conflict",reason:"out_of_band_workspace_state",required:"Reconcile the singleton document with its matching _workspace history state before retrying the mutation.",why:"Accepting the write would make the append-only audit stream describe a state that was not actually observed.",examples:["pm history _workspace --verify","pm validate --check-history-drift --fix-hints"],nextSteps:["Review the version-control change that altered the singleton and preserve the intended document plus its matching workspace history.","Rerun the original mutation only after the on-disk singleton agrees with the latest audited workspace state."],recovery:{recovery_mode:"compact",next_best_command:"pm history _workspace --verify"}});const afterDocument=workspaceDocument({...priorDocuments,[change.documentPath]:change.after},entries.length===0?timestamp:beforeDocument.metadata.created_at),entry=createHistoryEntry({nowIso:timestamp,author:change.author,op:change.idempotencyKey===void 0?change.op:`${change.op}:${change.idempotencyKey}`,before:beforeDocument,after:afterDocument,message:change.message});return await appendHistoryEntry(historyPath,entry),{entry,historyPath}}async function appendWorkspaceHistoryChange(change){const release=await acquireLock(change.pmRoot,"workspace-history",change.lockTtlSeconds,change.author,!1,!1,change.lockWaitMs);try{return await appendWorkspaceHistoryChangeLocked(change)}finally{await release()}}async function appendWorkspaceAuditEvent(options){const release=await acquireLock(options.pmRoot,"workspace-history",options.lockTtlSeconds,options.author,!1,!1,options.lockWaitMs);try{const historyPath=getWorkspaceHistoryPath(options.pmRoot),entries=await readHistoryEntries(historyPath,WORKSPACE_HISTORY_ID),verification=verifyHistoryChain(entries);verification.ok||throwWorkspaceHistoryVerificationFailure(verification.errors);const beforeDocument=entries.length===0?EMPTY_CANONICAL_DOCUMENT:replayWorkspaceEntries(entries),entry=createHistoryEntry({nowIso:nowIso(),author:options.author,op:options.op,before:beforeDocument,after:beforeDocument,message:options.message,context:options.context});return await appendHistoryEntry(historyPath,entry),{entry,historyPath}}finally{await release()}}async function writeWorkspaceJsonWithHistoryLocked(params,beforeRaw){if(beforeRaw===params.raw)return!1;const before=beforeRaw===null?null:JSON.parse(beforeRaw),after=JSON.parse(params.raw);await writeFileAtomic(params.filePath,params.raw);try{(beforeRaw!==null||params.recordCreation!==!1)&&await appendWorkspaceHistoryChangeLocked({pmRoot:params.pmRoot,documentPath:path.relative(params.pmRoot,params.filePath).replaceAll("\\","/"),before,after,op:params.op,idempotencyKey:params.idempotencyKey,author:params.author,lockTtlSeconds:params.lockTtlSeconds,lockWaitMs:params.lockWaitMs,message:params.message})}catch(error){throw beforeRaw===null?await fs.rm(params.filePath,{force:!0}):await writeFileAtomic(params.filePath,beforeRaw),error}return!0}async function mutateWorkspaceJsonWithHistory(params){const{documentPath}=resolveGovernedDocumentPath(params.pmRoot,params.filePath),release=await acquireLock(params.pmRoot,"workspace-history",params.lockTtlSeconds,params.author,!1,!1,params.lockWaitMs);try{const beforeRaw=await readFileIfExists(params.filePath);if(params.dryRun===!0||params.idempotencyKey!==void 0){const entries=await readHistoryEntries(getWorkspaceHistoryPath(params.pmRoot),WORKSPACE_HISTORY_ID),verification=verifyHistoryChain(entries);verification.ok||throwWorkspaceHistoryVerificationFailure(verification.errors);const recorded=workspaceDocuments(entries.length===0?EMPTY_CANONICAL_DOCUMENT:replayWorkspaceEntries(entries))[documentPath];if(recorded!==void 0&&stableStringify(recorded)!==stableStringify(beforeRaw===null?null:JSON.parse(beforeRaw)))throw new PmCliError(`Workspace history state for "${documentPath}" changed outside the audited mutation path.`,EXIT_CODE.CONFLICT,{code:"workspace_history_state_conflict"});if(params.idempotencyKey!==void 0&&entries.some(entry=>entry.op===`${params.op}:${params.idempotencyKey}`))return{changed:!1,result:void 0,replayed:!0}}const mutation=await params.mutate(beforeRaw);return JSON.parse(mutation.raw),params.dryRun===!0?{changed:beforeRaw!==mutation.raw,result:mutation.result}:{changed:await writeWorkspaceJsonWithHistoryLocked({...params,raw:mutation.raw},beforeRaw),result:mutation.result}}finally{await release()}}async function writeWorkspaceJsonWithHistory(params){const release=await acquireLock(params.pmRoot,"workspace-history",params.lockTtlSeconds,params.author,!1,!1,params.lockWaitMs);try{return await writeWorkspaceJsonWithHistoryLocked(params,await readFileIfExists(params.filePath))}finally{await release()}}async function reconcileWorkspaceJsonHistory(options){const authorizationDecision=options.authorizationDecision.trim();if(!authorizationDecision)throw new TypeError("Workspace history reconciliation requires an authorization decision");const release=await acquireLock(options.pmRoot,"workspace-history",options.lockTtlSeconds,options.author,!1,!1,options.lockWaitMs);try{const{documentPath,absolutePath}=resolveGovernedDocumentPath(options.pmRoot,options.filePath),historyPath=getWorkspaceHistoryPath(options.pmRoot),entries=await readHistoryEntries(historyPath,WORKSPACE_HISTORY_ID),verification=verifyHistoryChain(entries);verification.ok||throwWorkspaceHistoryVerificationFailure(verification.errors);const beforeDocument=replayWorkspaceEntries(entries),priorDocuments=workspaceDocuments(beforeDocument);if(!Object.hasOwn(priorDocuments,documentPath))throw new TypeError(`Workspace history does not govern document ${documentPath}`);const raw=await readFileIfExists(absolutePath);if(raw===null)throw new TypeError(`Workspace history document is missing: ${documentPath}`);const current=JSON.parse(raw);if(stableStringify(priorDocuments[documentPath])===stableStringify(current))return{changed:!1,historyPath};const timestamp=nowIso(),entry=createHistoryEntry({nowIso:timestamp,author:options.author,op:options.op,before:beforeDocument,after:workspaceDocument({...priorDocuments,[documentPath]:current},beforeDocument.metadata.created_at),message:options.message,context:{reason:"out_of_band_workspace_state_reconciliation",document_path:documentPath,authorization_decision:authorizationDecision}});return await appendHistoryEntry(historyPath,entry),{changed:!0,entry,historyPath}}finally{await release()}}async function restoreWorkspaceJsonFromHistory(options){const release=await acquireLock(options.pmRoot,"workspace-history",options.lockTtlSeconds,options.author,!1,!1,options.lockWaitMs);try{const{documentPath,absolutePath}=resolveGovernedDocumentPath(options.pmRoot,options.filePath),entries=await readHistoryEntries(getWorkspaceHistoryPath(options.pmRoot),WORKSPACE_HISTORY_ID),verification=verifyHistoryChain(entries);if(verification.ok||throwWorkspaceHistoryVerificationFailure(verification.errors),!Number.isInteger(options.targetVersion)||options.targetVersion<1||options.targetVersion>entries.length)throw new TypeError(`Invalid workspace history target version: ${String(options.targetVersion)}`);const target=workspaceDocuments(replayWorkspaceEntries(entries,options.targetVersion))[documentPath];if(target===void 0)throw new TypeError(`Workspace history version ${options.targetVersion} does not contain ${documentPath}`);const beforeRaw=await readFileIfExists(absolutePath),targetRaw=`${JSON.stringify(target,null,2)}
|
|
2
|
+
`;if(beforeRaw===targetRaw)return{document_path:documentPath,restored_from_version:options.targetVersion,changed:!1};const beforeDocument=replayWorkspaceEntries(entries),timestamp=nowIso(),entry=createHistoryEntry({nowIso:timestamp,author:options.author,op:options.op,before:beforeDocument,after:workspaceDocument({...workspaceDocuments(beforeDocument),[documentPath]:target},beforeDocument.metadata.created_at),message:options.message,context:{reason:"workspace_state_restore",document_path:documentPath,restored_from_version:options.targetVersion,replaced_out_of_band_state:!0}});await writeFileAtomic(absolutePath,targetRaw);try{await appendHistoryEntry(getWorkspaceHistoryPath(options.pmRoot),entry)}catch(error){throw beforeRaw===null?await fs.rm(absolutePath,{force:!0}):await writeFileAtomic(absolutePath,beforeRaw),error}return{document_path:documentPath,restored_from_version:options.targetVersion,changed:!0}}finally{await release()}}export{WORKSPACE_HISTORY_ID,appendWorkspaceAuditEvent,appendWorkspaceHistoryChange,getWorkspaceHistoryPath,inspectWorkspaceHistoryState,mutateWorkspaceJsonWithHistory,reconcileWorkspaceJsonHistory,restoreWorkspaceJsonFromHistory,writeWorkspaceJsonWithHistory};
|
|
3
3
|
//# sourceMappingURL=workspace-history.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="80805c6b-9b9a-5dad-b94b-d7dbd365fe5e")}catch{}})();import{readFile}from"node:fs/promises";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{createStdinTokenResolver}from"../item/parse.js";const defaultBodyFileReader=path=>readFile(path,"utf8");async function resolveBodyFileContent(bodyFile,inlineBody,readFileImpl=defaultBodyFileReader){if(inlineBody!==void 0)throw new PmCliError("--body and --body-file are mutually exclusive; provide the body inline with --body or from a file with --body-file, not both.",EXIT_CODE.USAGE,{code:"body_file_conflicts_with_body",required:"Choose exactly one body source.",why:"Both --body and --body-file set the item body; allowing both would make the effective body ambiguous.",nextSteps:["Re-run with only --body <text> or only --body-file <path>."]});const path=bodyFile.trim();if(path.length===0)throw new PmCliError("--body-file requires a file path.",EXIT_CODE.USAGE,{code:"body_file_missing_path",required:"Pass a readable file path: --body-file <path>.",why:"An empty --body-file value has no file to read the body from."});if(path==="-")return await createStdinTokenResolver().resolveValue("-","--body-file");try{return await readFileImpl(path)}catch(error){const errno=error?.code,isDirectory=errno==="EISDIR",detail=errno?` (${errno})`:"";throw new PmCliError(isDirectory?`--body-file "${path}" is a directory, not a file. Point it at a readable file.`:`--body-file could not read "${path}"${detail}. Check that the file exists and is readable.`,EXIT_CODE.NOT_FOUND,{code:"body_file_unreadable",required:"Point --body-file at an existing, readable file.",why:`The body content is loaded from the file at the supplied path, so an unreadable path cannot produce a body${errno?` (underlying error: ${errno})`:""}.`,nextSteps:[`Verify the path: ls -l "${path}"`,"Or pipe the body with --body-file -.","Or pass the body inline with --body <text>."]})}}export{resolveBodyFileContent};
|
|
2
2
|
//# sourceMappingURL=body-file.js.map
|
|
@@ -1,2 +1,3 @@
|
|
|
1
|
-
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="4441095d-0acd-5780-8758-7df94396cb8e")}catch{}})();import{readFile}from"node:fs/promises";import{createStdinTokenResolver}from"../item/parse.js";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";const defaultFileReader=path=>readFile(path,"utf8"),defaultStdinReader=async optionName=>await createStdinTokenResolver().resolveValue("-",optionName);function parseBulkIdsText(raw){return[...new Set(raw.split(/[,\r\n]+/).map(entry=>entry.trim()).filter(entry=>entry.length>0))]}function normalizeBulkIdsArray(value){const entries=[];for(const entry of value)if(typeof entry=="string")entries.push(entry);else if(typeof entry=="number"&&Number.isFinite(entry))entries.push(String(entry));else return"";const ids=parseBulkIdsText(entries.join(`
|
|
2
|
+
`));return ids.length>0?ids.join(","):""}function normalizeBulkIdsValue(value){if(value===void 0)return;if(typeof value=="number")return Number.isFinite(value)?String(value):"";if(Array.isArray(value))return normalizeBulkIdsArray(value);if(typeof value!="string")return"";const ids=parseBulkIdsText(value);return ids.length>0?ids.join(","):""}async function resolveCliBulkIdsInput(value,optionName="--ids",readers={}){if(value===void 0)return;const trimmed=value.trim();let raw=value;try{if(trimmed==="-")raw=await(readers.readStdin??defaultStdinReader)(optionName);else if(trimmed.startsWith("@")){const path=trimmed.slice(1).trim();if(path.length===0)throw new PmCliError(`${optionName} @path requires a non-empty file path.`,EXIT_CODE.USAGE,{code:"bulk_ids_input_missing_path",required:`Pass ${optionName} @<path>, ${optionName} -, or inline IDs.`});raw=await(readers.readFile??defaultFileReader)(path)}}catch(error){if(error instanceof PmCliError)throw error;const detail=error instanceof Error?error.message:String(error);throw new PmCliError(`${optionName} could not read ${trimmed==="-"?"stdin":`"${trimmed.slice(1).trim()}"`}: ${detail}`,EXIT_CODE.NOT_FOUND,{code:"bulk_ids_input_unreadable",required:`Provide readable newline/comma-delimited IDs via ${optionName} -, ${optionName} @<path>, or inline argv text.`,nextSteps:[`Retry with inline IDs: ${optionName} pm-a1b2,pm-c3d4`,`Or pipe IDs: pm list --id-only | pm update-many ${optionName} - --dry-run`]})}const normalized=normalizeBulkIdsValue(raw);if(normalized!=="")return normalized;throw new PmCliError(`${optionName} requires at least one non-empty item ID.`,EXIT_CODE.USAGE,{code:"bulk_ids_input_empty",required:"Provide one or more comma- or newline-delimited IDs through argv, stdin, or @path."})}export{normalizeBulkIdsValue,parseBulkIdsText,resolveCliBulkIdsInput};
|
|
2
3
|
//# sourceMappingURL=bulk-ids-input.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="1745a409-0f91-5f5a-8d2a-e5e61ff667a0")}catch{}})();import{isTerminalStatus,normalizeStatusForRegistry}from"./status.js";import{BUILTIN_ITEM_EXECUTION_ROLES,resolveTypeDefinition}from"./type-registry.js";import{isExternalDependencyReference,isExternalDependencySourceKind}from"./dependency-reference.js";function resolveItemExecutionRole(type,registry){return(registry===void 0?void 0:resolveTypeDefinition(type,registry))?.execution_role??BUILTIN_ITEM_EXECUTION_ROLES[type.trim().toLowerCase()]??"agent"}const BLOCKED_BY_DEPENDENCY_KIND="blocked_by",BLOCKS_DEPENDENCY_KIND="blocks",ACTIONABILITY_ORDERING_KINDS=Object.freeze([BLOCKED_BY_DEPENDENCY_KIND,BLOCKS_DEPENDENCY_KIND]),NO_ACTIVE_BLOCKER_SENTINEL="no-active-blocker";function normalizeItemId(id){return id.trim().toLowerCase()}function blockerReferenceKey(id,external){return external?`external:${id}`:`local:${normalizeItemId(id)}`}function collectBlockedByIds(item){const ids=new Map,scalar=typeof item.blocked_by=="string"?item.blocked_by.trim():"";if(scalar.length>0&&normalizeItemId(scalar)!==NO_ACTIVE_BLOCKER_SENTINEL){const external=isExternalDependencyReference(scalar);ids.set(blockerReferenceKey(scalar,external),external?scalar:normalizeItemId(scalar))}for(const dependency of item.dependencies??[]){const dependencyId=typeof dependency.id=="string"?dependency.id.trim():"";if(dependency.kind===BLOCKED_BY_DEPENDENCY_KIND&&dependencyId.length>0&&normalizeItemId(dependencyId)!==NO_ACTIVE_BLOCKER_SENTINEL){const external=isExternalDependencyReference(dependencyId)||isExternalDependencySourceKind(dependency.source_kind);ids.set(blockerReferenceKey(dependencyId,external),external?dependencyId:normalizeItemId(dependencyId))}}return[...ids.values()].sort((left,right)=>left.localeCompare(right))}function indexBlockedByIds(corpus){const idsByItem=new Map;for(const item of corpus){const itemId=normalizeItemId(item.id);itemId.length!==0&&idsByItem.set(itemId,new Set(collectBlockedByIds(item)))}for(const candidate of corpus){const candidateId=normalizeItemId(candidate.id);if(candidateId.length!==0)for(const dependency of candidate.dependencies??[]){const targetId=dependency.kind===BLOCKS_DEPENDENCY_KIND&&typeof dependency.id=="string"?normalizeItemId(dependency.id):"";if(targetId.length===0||targetId===NO_ACTIVE_BLOCKER_SENTINEL)continue;const blockerIds=idsByItem.get(targetId)??new Set;blockerIds.add(candidateId),idsByItem.set(targetId,blockerIds)}}return new Map([...idsByItem].map(([itemId,blockerIds])=>[itemId,[...blockerIds].sort((left,right)=>left.localeCompare(right))]))}function collectBlockedByIdsFromCorpus(item,corpus){const itemId=normalizeItemId(item.id);return itemId.length>0?indexBlockedByIds(corpus).get(itemId)??collectBlockedByIds(item):collectBlockedByIds(item)}function resolveItemBlockersWithIndex(item,itemsById,statusRegistry,blockerIdsByItem){const itemWithId=item,blockerIds=typeof itemWithId.id=="string"?blockerIdsByItem?.get(normalizeItemId(itemWithId.id))??collectBlockedByIdsFromCorpus(itemWithId,[...itemsById.values()]):collectBlockedByIds(item),structuredExternalBlockerIds=new Set((item.dependencies??[]).filter(dependency=>dependency.kind===BLOCKED_BY_DEPENDENCY_KIND&&isExternalDependencySourceKind(dependency.source_kind)&&typeof dependency.id=="string"&&dependency.id.trim().length>0).map(dependency=>blockerReferenceKey(dependency.id.trim(),!0)));return blockerIds.map(id=>{if(isExternalDependencyReference(id)||structuredExternalBlockerIds.has(blockerReferenceKey(id,!0)))return{id,title:null,status:null,resolved:!1,external:!0,...typeof item.updated_at=="string"?{blocked_since:item.updated_at}:{},resolver:null};const blocker=itemsById.get(normalizeItemId(id));return blocker?{id,title:blocker.title,status:blocker.status,resolved:isTerminalStatus(blocker.status,statusRegistry)}:{id,title:null,status:null,resolved:!1}})}function resolveItemBlockers(item,itemsById,statusRegistry){return resolveItemBlockersWithIndex(item,itemsById,statusRegistry)}function collectDependencyBlockedIds(corpus,statusRegistry){const itemsById=new Map(corpus.map(item=>[normalizeItemId(item.id),item])),blockerIdsByItem=indexBlockedByIds(corpus),candidateStatuses=new Set([...resolveActiveStatusSet(statusRegistry),...statusRegistry.blocked_statuses]),blocked=new Set;for(const item of corpus){const normalizedStatus=normalizeStatusForRegistry(item.status,statusRegistry);candidateStatuses.has(normalizedStatus)&&(statusRegistry.blocked_statuses.has(normalizedStatus)||resolveItemBlockersWithIndex(item,itemsById,statusRegistry,blockerIdsByItem).some(blocker=>!blocker.resolved))&&blocked.add(normalizeItemId(item.id))}return blocked}function selectActionableEntries(report,statusRegistry,options={},typeRegistry){const candidates=[...report.ready,...report.decisions,...report.gates];options.includeContainers===!0&&candidates.push(...report.containers.filter(entry=>entry.open_blockers.length===0&&!statusRegistry.blocked_statuses.has(normalizeStatusForRegistry(entry.item.status,statusRegistry))));const selected={ready:[],decisions:[],gates:[]};for(const entry of candidates){const role=resolveItemExecutionRole(entry.item.type,typeRegistry);role==="human"&&options.includeDecisions!==!0?selected.decisions.push(entry):role==="gate"&&options.includeGates!==!0?selected.gates.push(entry):selected.ready.push(entry)}return selected}function resolveActiveStatusSet(statusRegistry){return statusRegistry.active_statuses.size>0?statusRegistry.active_statuses:new Set([statusRegistry.open_status])}function hasOpenDescendant(rootId,childrenByParent,statusRegistry){const stack=[normalizeItemId(rootId)],visited=new Set;for(;stack.length>0;){const current=stack.pop();if(!visited.has(current)){visited.add(current);for(const child of childrenByParent.get(current)??[]){if(!isTerminalStatus(child.status,statusRegistry))return!0;stack.push(normalizeItemId(child.id))}}}return!1}function indexCorpus(corpus){const itemsById=new Map,childrenByParent=new Map,blockedByReverse=new Map,blockerIdsByItem=indexBlockedByIds(corpus);for(const item of corpus){itemsById.set(normalizeItemId(item.id),item);const parent=typeof item.parent=="string"?item.parent.trim():"";if(parent.length>0){const parentKey=normalizeItemId(parent),siblings=childrenByParent.get(parentKey)??[];siblings.push(item),childrenByParent.set(parentKey,siblings)}for(const blockerId of blockerIdsByItem.get(normalizeItemId(item.id))){const blockerKey=normalizeItemId(blockerId),dependents=blockedByReverse.get(blockerKey)??[];dependents.push(item.id),blockedByReverse.set(blockerKey,dependents)}}return{itemsById,childrenByParent,blockedByReverse,blockerIdsByItem}}function computeActionabilityReport(candidates,corpus,statusRegistry,typeRegistry){const{itemsById,childrenByParent,blockedByReverse,blockerIdsByItem}=indexCorpus(corpus),activeStatuses=new Set([...resolveActiveStatusSet(statusRegistry),...statusRegistry.blocked_statuses]),nonTerminalIds=new Set(corpus.filter(entry=>!isTerminalStatus(entry.status,statusRegistry)).map(entry=>normalizeItemId(entry.id))),ready=[],blocked=[],containers=[],decisions=[],gates=[];let activeCount=0;for(const item of candidates){if(!activeStatuses.has(normalizeStatusForRegistry(item.status,statusRegistry)))continue;activeCount+=1;const openBlockers=resolveItemBlockersWithIndex(item,itemsById,statusRegistry,blockerIdsByItem).filter(blocker=>!blocker.resolved),unblocks=(blockedByReverse.get(normalizeItemId(item.id))??[]).filter(dependentId=>nonTerminalIds.has(normalizeItemId(dependentId))).sort((left,right)=>left.localeCompare(right)),entry={item,open_blockers:openBlockers,unblocks};if(hasOpenDescendant(item.id,childrenByParent,statusRegistry)){containers.push(entry);continue}const lifecycleBlocked=statusRegistry.blocked_statuses.has(normalizeStatusForRegistry(item.status,statusRegistry));if(openBlockers.length===0&&!lifecycleBlocked){const role=resolveItemExecutionRole(item.type,typeRegistry);role==="human"?decisions.push(entry):role==="gate"?gates.push(entry):ready.push(entry)}else blocked.push(entry)}return{ready,blocked,containers,decisions,gates,active_count:activeCount,container_count:containers.length}}export{ACTIONABILITY_ORDERING_KINDS,collectBlockedByIds,collectBlockedByIdsFromCorpus,collectDependencyBlockedIds,computeActionabilityReport,indexBlockedByIds,resolveItemBlockers,resolveItemExecutionRole,selectActionableEntries};
|
|
2
2
|
//# sourceMappingURL=actionability.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="e216fd39-09ee-5a04-b0b5-44f518db4f93")}catch{}})();function isExternalDependencyReference(target){const normalized=target?.trim()??"";return/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(normalized)||/^(?:github|gitlab|jira|linear):/iu.test(normalized)}function isExternalDependencySourceKind(sourceKind){const normalized=sourceKind?.trim().toLowerCase();return normalized==="global"||normalized==="external"}export{isExternalDependencyReference,isExternalDependencySourceKind};
|
|
2
2
|
//# sourceMappingURL=dependency-reference.js.map
|
package/dist/core/item/id.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="664124e5-715d-5f86-ae69-89f203db76c3")}catch{}})();import crypto from"node:crypto";import path from"node:path";import{TYPE_TO_FOLDER}from"../shared/constants.js";import{pathExists}from"../fs/fs-utils.js";import{nextReproducibleToken}from"../reproducibility/context.js";function normalizePrefix(input){const normalized=[];let separatorPending=!1;for(const character of(input??"").toLowerCase()){const codePoint=character.charCodeAt(0),isAsciiDigit=codePoint>=48&&codePoint<=57,isAsciiLetter=codePoint>=97&&codePoint<=122;if(!isAsciiDigit&&!isAsciiLetter){separatorPending=normalized.length>0;continue}separatorPending&&(normalized.push("-"),separatorPending=!1),normalized.push(character)}return normalized.length===0?"pm-":`${normalized.join("")}-`}function normalizeRawItemId(input){let normalized=input.trim().toLowerCase();return normalized.startsWith("#")&&(normalized=normalized.slice(1)),normalized}function normalizeItemId(input,prefix){const canonicalPrefix=normalizePrefix(prefix),normalized=normalizeRawItemId(input);return normalized.startsWith(canonicalPrefix)?normalized:`${canonicalPrefix}${normalized}`}function randomToken(length){const reproducibleToken=nextReproducibleToken(length);if(reproducibleToken!==void 0)return reproducibleToken;let token="";for(let index=0;index<length;index+=1)token+=crypto.randomInt(0,36).toString(36);return token}async function idExists(pmRoot,id,typeToFolder){const checks=[...new Set(Object.values(typeToFolder))].flatMap(folder=>[path.join(pmRoot,folder,`${id}.md`),path.join(pmRoot,folder,`${id}.toon`)]);return checks.push(path.join(pmRoot,"history",`${id}.jsonl`)),(await Promise.all(checks.map(target=>pathExists(target)))).some(Boolean)}const ID_TOKEN_LENGTH_MIN=4,ID_TOKEN_LENGTH_MAX=12;function clampIdTokenLength(value){return typeof value!="number"||!Number.isFinite(value)?ID_TOKEN_LENGTH_MIN:Math.min(ID_TOKEN_LENGTH_MAX,Math.max(ID_TOKEN_LENGTH_MIN,Math.trunc(value)))}async function generateItemId(pmRoot,prefix,options={}){let tokenLength=clampIdTokenLength(options.tokenLength);const maxTokenLength=Math.min(tokenLength+6,ID_TOKEN_LENGTH_MAX);let attempts=0;for(;tokenLength<=maxTokenLength;){for(let i=0;i<32;i+=1){const id=`${normalizePrefix(prefix)}${randomToken(tokenLength)}`;if(!await(options.probeExisting===!1?pathExists(path.join(pmRoot,"history",`${id}.jsonl`)):idExists(pmRoot,id,options.typeToFolder??TYPE_TO_FOLDER)))return id;attempts+=1}tokenLength+=1}throw new Error(`Unable to generate unique id after ${attempts} attempts`)}export{ID_TOKEN_LENGTH_MAX,ID_TOKEN_LENGTH_MIN,clampIdTokenLength,generateItemId,normalizeItemId,normalizePrefix,normalizeRawItemId};
|
|
2
2
|
//# sourceMappingURL=id.js.map
|
package/dist/core/item/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="af340813-f1da-5d0d-9ad6-f4be63a6c96f")}catch{}})();export*from"./id.js";export*from"./item-format.js";export*from"./parse.js";export*from"./type-registry.js";
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="13e158d2-14a0-5c14-a11c-a374b3e6ceac")}catch{}})();const BASELINE_ITEM_FORMAT_VERSION=1,CURRENT_ITEM_FORMAT_VERSION=1;function effectiveItemFormatVersion(metadata){const raw=metadata.pm_format_version;return typeof raw=="number"&&Number.isInteger(raw)&&raw>=1?raw:1}function normalizeItemFormatVersion(value){if(!(typeof value!="number"||!Number.isInteger(value)||value<=1))return value}function classifyItemFormatVersion(version,current=1){return version<current?"outdated":version>current?"ahead":"current"}function scanItemFormatVersions(entries,current=1){const outdated=[],ahead=[];for(const entry of entries){const status=classifyItemFormatVersion(entry.version,current);status==="outdated"?outdated.push(entry.ref):status==="ahead"&&ahead.push(entry.ref)}return{outdated:outdated.sort((left,right)=>left.localeCompare(right)),ahead:ahead.sort((left,right)=>left.localeCompare(right))}}export{BASELINE_ITEM_FORMAT_VERSION,CURRENT_ITEM_FORMAT_VERSION,classifyItemFormatVersion,effectiveItemFormatVersion,normalizeItemFormatVersion,scanItemFormatVersions};
|
|
2
2
|
//# sourceMappingURL=item-format-version.js.map
|