@unbrained/pm-cli 2026.9.27 → 2026.9.29

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.
Files changed (158) hide show
  1. package/.agents/skills/pm-developer/references/GRAPH_AND_RELATIONSHIPS.md +7 -6
  2. package/.agents/skills/pm-user/references/BACKLOG_SHAPING.md +1 -1
  3. package/.agents/skills/pm-user/references/ECOSYSTEM_PLANNING.md +26 -3
  4. package/.claude-plugin/marketplace.json +4 -6
  5. package/CHANGELOG.md +43 -0
  6. package/dist/cli/error-guidance.js +1 -1
  7. package/dist/cli/help-json-payload.js +2 -2
  8. package/dist/cli/main.js +2 -2
  9. package/dist/cli/register-operations.js +1 -1
  10. package/dist/cli/runtime/invocation-options.d.ts +3 -1
  11. package/dist/cli/runtime/invocation-options.js +1 -1
  12. package/dist/cli-bundle/bundle-manifest.json +151 -151
  13. package/dist/cli-bundle/chunks/{chunk-6OJVQ7SW.js → chunk-2AQKVJMW.js} +2 -2
  14. package/dist/cli-bundle/chunks/{chunk-TSF2LPIH.js → chunk-4DOL43PF.js} +2 -2
  15. package/dist/cli-bundle/chunks/{chunk-7TAGYNFP.js → chunk-5KEPG36D.js} +2 -2
  16. package/dist/cli-bundle/chunks/{chunk-IEP3VAT5.js → chunk-D32HVIB2.js} +2 -2
  17. package/dist/cli-bundle/chunks/{chunk-AUS6USO4.js → chunk-GP6QTYSD.js} +2 -2
  18. package/dist/cli-bundle/chunks/chunk-OTLIM22J.js +2 -0
  19. package/dist/cli-bundle/chunks/{chunk-LKGQUZ5M.js → chunk-P75SO5HO.js} +2 -2
  20. package/dist/cli-bundle/chunks/{chunk-4SLLCDFL.js → chunk-PJSQAWWQ.js} +64 -64
  21. package/dist/cli-bundle/chunks/{chunk-V5UGBYHN.js → chunk-S5A2UIRV.js} +62 -62
  22. package/dist/cli-bundle/chunks/chunk-SC6JHXFT.js +31 -0
  23. package/dist/cli-bundle/chunks/{chunk-3BTJ66CB.js → chunk-SEJ53XDN.js} +55 -55
  24. package/dist/cli-bundle/chunks/{chunk-OKVDVERQ.js → chunk-SJI55O65.js} +2 -2
  25. package/dist/cli-bundle/chunks/{chunk-JX6WCCHL.js → chunk-U3QJGJYN.js} +2 -2
  26. package/dist/cli-bundle/chunks/{register-list-query-6PAJ4PBU.js → register-list-query-R3ELWWPY.js} +2 -2
  27. package/dist/cli-bundle/chunks/{register-mutation-RZCXZXYS.js → register-mutation-WHXJXIHJ.js} +2 -2
  28. package/dist/cli-bundle/chunks/{register-operations-GK6VU2H2.js → register-operations-7ASWBYQG.js} +2 -2
  29. package/dist/cli-bundle/chunks/{register-setup-ASEMNMBF.js → register-setup-FDRTUG54.js} +2 -2
  30. package/dist/cli-bundle/focused-chunks/{chunk-QO4MTAEA.js → chunk-2O3QFI3G.js} +2 -2
  31. package/dist/cli-bundle/focused-chunks/{chunk-LBDWUHQD.js → chunk-4A4DO5ZT.js} +2 -2
  32. package/dist/cli-bundle/focused-chunks/chunk-5MC57KRC.js +2 -0
  33. package/dist/cli-bundle/focused-chunks/{chunk-NWRVNHAD.js → chunk-6OXJVE74.js} +17 -17
  34. package/dist/cli-bundle/focused-chunks/{chunk-MILJCOFJ.js → chunk-7URX7FMY.js} +2 -2
  35. package/dist/cli-bundle/focused-chunks/{chunk-OJRX6G22.js → chunk-AVP5C674.js} +2 -2
  36. package/dist/cli-bundle/focused-chunks/{chunk-SMADBUPL.js → chunk-AZE7KUHG.js} +2 -2
  37. package/dist/cli-bundle/focused-chunks/{chunk-GZD4ZYIB.js → chunk-DZVOCJFY.js} +14 -14
  38. package/dist/cli-bundle/focused-chunks/chunk-FBIRNSYP.js +75 -0
  39. package/dist/cli-bundle/focused-chunks/{chunk-NETVXIH5.js → chunk-IFBA3ZAT.js} +2 -2
  40. package/dist/cli-bundle/focused-chunks/{chunk-OJKJFDIG.js → chunk-K3AIMRIK.js} +2 -2
  41. package/dist/cli-bundle/focused-chunks/{chunk-DQ3MB7BO.js → chunk-KLKKCHWM.js} +2 -2
  42. package/dist/cli-bundle/focused-chunks/{chunk-PDVL7QYU.js → chunk-MRH4A542.js} +15 -15
  43. package/dist/cli-bundle/focused-chunks/{chunk-6UNKK3UH.js → chunk-NXQZMKW5.js} +2 -2
  44. package/dist/cli-bundle/focused-chunks/chunk-NY6FLQTN.js +2 -0
  45. package/dist/cli-bundle/focused-chunks/{chunk-NZAG7OKB.js → chunk-T4H6Q44B.js} +2 -2
  46. package/dist/cli-bundle/main.js +22 -22
  47. package/dist/cli-bundle/sdk-authoring.js +1 -1
  48. package/dist/cli-bundle/sdk-contracts.js +1 -1
  49. package/dist/cli-bundle/sdk-core.js +22 -21
  50. package/dist/cli-bundle/sdk-governance.js +1 -1
  51. package/dist/cli-bundle/sdk-graph.js +1 -1
  52. package/dist/cli-bundle/sdk-merge.js +51 -51
  53. package/dist/cli-bundle/sdk-query.js +1 -1
  54. package/dist/cli-bundle/sdk-runtime.js +1 -1
  55. package/dist/cli-bundle/sdk-testing.js +1 -1
  56. package/dist/cli-bundle/sdk.js +2 -2
  57. package/dist/core/diagnostics/remediation.js +1 -1
  58. package/dist/core/history/replay.js +1 -1
  59. package/dist/core/item/item-format.js +1 -1
  60. package/dist/core/output/mutation-projection.js +1 -1
  61. package/dist/core/store/settings.js +3 -3
  62. package/dist/core/telemetry/runtime.js +2 -2
  63. package/dist/sdk/cli-contracts/command-aliases.js +1 -1
  64. package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1
  65. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
  66. package/dist/sdk/completion/fish.js +3 -3
  67. package/dist/sdk/completion/zsh.js +3 -3
  68. package/dist/sdk/extension/copy-scope.d.ts +2 -2
  69. package/dist/sdk/extension/copy-scope.js +1 -1
  70. package/dist/sdk/extension/install-plan.js +1 -1
  71. package/dist/sdk/extension/install-runtime.js +2 -2
  72. package/dist/sdk/extension/static-inventory.js +1 -1
  73. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  74. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  75. package/dist/sdk/governance/health-merge-evidence.d.ts +18 -0
  76. package/dist/sdk/governance/health-merge-evidence.js +2 -0
  77. package/dist/sdk/governance/health.js +1 -1
  78. package/dist/sdk/index.d.ts +1 -0
  79. package/dist/sdk/index.js +1 -1
  80. package/dist/sdk/lifecycle/plan-mutation-receipt.d.ts +53 -0
  81. package/dist/sdk/lifecycle/plan-mutation-receipt.js +2 -0
  82. package/dist/sdk/lifecycle/plan.d.ts +3 -0
  83. package/dist/sdk/lifecycle/plan.js +1 -1
  84. package/dist/sdk/linked-artifacts.js +1 -1
  85. package/dist/sdk/merge/install.js +2 -2
  86. package/dist/sdk/output-projection.d.ts +1 -1
  87. package/dist/sdk/output-projection.js +1 -1
  88. package/dist/sdk/public-surface.json +1 -1
  89. package/dist/sdk/read-output-budget.d.ts +1 -1
  90. package/dist/sdk/read-output-budget.js +1 -1
  91. package/dist/sdk/read-output-contracts.js +1 -1
  92. package/dist/sdk/runtime/actions.js +1 -1
  93. package/dist/sdk/runtime-input.d.ts +2 -0
  94. package/dist/sdk/runtime-input.js +1 -1
  95. package/dist/sdk/runtime.js +1 -1
  96. package/dist/sdk/similarity-scoring.js +1 -1
  97. package/dist/sdk/telemetry.d.ts +2 -0
  98. package/dist/sdk/telemetry.js +3 -1
  99. package/dist/sdk/test/execution.d.ts +11 -0
  100. package/dist/sdk/test/execution.js +2 -2
  101. package/dist/sdk/test/parsers.d.ts +1 -1
  102. package/dist/sdk/test/parsers.js +1 -1
  103. package/dist/types.d.ts +3 -3
  104. package/dist/types.js +1 -1
  105. package/docs/AGENT_READ_AND_TEST_RECEIPTS.md +21 -0
  106. package/docs/CLAUDE_CODE_PLUGIN.md +12 -7
  107. package/docs/CLI_GRAMMAR.md +18 -1
  108. package/docs/CONFIGURATION.md +2 -0
  109. package/docs/ECOSYSTEM_PLANNING_REVIEW.md +270 -0
  110. package/docs/PACKAGE_EVIDENCE.md +18 -7
  111. package/docs/README.md +2 -0
  112. package/docs/SDK_EVIDENCE_TRACEABILITY.md +34 -0
  113. package/docs/TESTING.md +14 -3
  114. package/docs/agent-task-token-baseline.json +28 -2
  115. package/docs/agent-task-transcripts.json +137 -14
  116. package/docs/ecosystem-review-2026-09-28.json +3159 -0
  117. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +7 -3
  118. package/marketplace.json +4 -6
  119. package/package.json +5 -5
  120. package/packages/pm-beads/package.json +1 -1
  121. package/packages/pm-calendar/package.json +1 -1
  122. package/packages/pm-command-kit/package.json +1 -1
  123. package/packages/pm-digital-twin/package.json +1 -1
  124. package/packages/pm-governance-audit/package.json +1 -1
  125. package/packages/pm-guide-shell/package.json +1 -1
  126. package/packages/pm-kanban/package.json +1 -1
  127. package/packages/pm-lifecycle-hooks/package.json +1 -1
  128. package/packages/pm-linked-test-adapters/package.json +1 -1
  129. package/packages/pm-search-advanced/package.json +1 -1
  130. package/packages/pm-templates/package.json +1 -1
  131. package/packages/pm-todos/package.json +1 -1
  132. package/packages/pm-vcs/package.json +1 -1
  133. package/plugins/pm-claude/.claude-plugin/plugin.json +4 -2
  134. package/plugins/pm-claude/.mcp.json +1 -2
  135. package/plugins/pm-claude/README.md +7 -7
  136. package/plugins/pm-claude/package.json +2 -2
  137. package/plugins/pm-claude/{commands/pm-calendar.md → skills/pm-calendar/SKILL.md} +1 -0
  138. package/plugins/pm-claude/{commands/pm-close-task.md → skills/pm-close-task/SKILL.md} +1 -0
  139. package/plugins/pm-claude/{commands/pm-init.md → skills/pm-init/SKILL.md} +2 -1
  140. package/plugins/pm-claude/{commands/pm-list.md → skills/pm-list/SKILL.md} +2 -1
  141. package/plugins/pm-claude/{commands/pm-new.md → skills/pm-new/SKILL.md} +1 -0
  142. package/plugins/pm-claude/{commands/pm-search.md → skills/pm-search/SKILL.md} +1 -0
  143. package/plugins/pm-claude/{commands/pm-start-task.md → skills/pm-start-task/SKILL.md} +1 -0
  144. package/plugins/pm-claude/{commands/pm-status.md → skills/pm-status/SKILL.md} +1 -0
  145. package/plugins/pm-claude/{commands/pm-triage.md → skills/pm-triage/SKILL.md} +1 -0
  146. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  147. package/plugins/pm-codex/package.json +2 -2
  148. package/plugins/pm-codex/plugin.json +1 -1
  149. package/dist/cli-bundle/chunks/chunk-4UPZLUT2.js +0 -29
  150. package/dist/cli-bundle/chunks/chunk-LC6WEA5U.js +0 -2
  151. package/dist/cli-bundle/focused-chunks/chunk-6J2YCGSN.js +0 -75
  152. package/dist/cli-bundle/focused-chunks/chunk-E7LYK7V5.js +0 -2
  153. package/dist/cli-bundle/focused-chunks/chunk-KMPKKSA6.js +0 -2
  154. package/plugins/pm-claude/commands/pm-audit.md +0 -38
  155. package/plugins/pm-claude/commands/pm-developer.md +0 -38
  156. package/plugins/pm-claude/commands/pm-planner.md +0 -54
  157. package/plugins/pm-claude/commands/pm-release.md +0 -41
  158. package/plugins/pm-claude/commands/pm-workflow.md +0 -49
@@ -1,2 +1,2 @@
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]="a236314b-1a3b-5499-bed3-364a2cb034a5")}catch(e2){}})();const REMEDIATION_REGISTRY=Object.freeze([{code:"missing_directory",command:"pm init",summary:"Recreate missing tracker directories (pm init is idempotent and restores the scaffold)."},{code:"settings_read_fs_error",command:"pm config list --json",summary:"settings.json could not be read as a regular file and pm fell back to defaults; repair the reported path or permissions, then re-run."},{code:"settings_read_invalid_json",command:"pm config list --json",summary:"settings.json is not valid JSON and pm fell back to defaults; fix the syntax error in the reported path, then re-run."},{code:"settings_read_invalid_schema",command:"pm config list --json",summary:"settings.json failed schema validation and pm fell back to defaults; correct the reported key in the file, then re-run."},{code:"settings_read_merge_failed",command:"pm config list --json",summary:"Global/project settings could not be merged; reconcile the conflicting keys in the reported settings files."},{code:"settings:id_prefix_empty",command:"pm config list --json",summary:'id_prefix is empty; set a non-empty "id_prefix" in settings.json so generated item ids are well-formed.'},{code:"settings:locks_ttl_non_positive",command:"pm config list --json",summary:'locks.ttl_seconds must be positive; set a positive "locks.ttl_seconds" in settings.json.'},{code:"telemetry_state_invalid_json",command:"pm health --check-telemetry",summary:"Local telemetry state file is corrupt; pm recreates it on the next flush. Advisory only."},{code:"telemetry_queue_invalid_rows",command:"pm health --check-telemetry",summary:"The telemetry queue has unparseable rows; they are skipped on the next flush. Advisory only."},{code:"telemetry_queue_pending",command:"pm health --check-telemetry",summary:"Telemetry events are queued; they flush automatically on the next reachable command. Advisory only."},{code:"telemetry_queue_high_retries",command:"pm telemetry flush",summary:"Some queued telemetry events are near retry exhaustion; flush now and verify endpoint reachability before entries are dropped."},{code:"telemetry_endpoint_probe_failed",command:"pm health --check-telemetry",summary:"The telemetry endpoint is unreachable; events stay queued until it recovers. Advisory only."},{code:"telemetry_endpoint_probe_http_status",command:"pm health --check-telemetry",summary:"The telemetry endpoint returned a non-success status; events stay queued until it recovers. Advisory only."},{code:"telemetry_schema_version_behind",command:"pm health --check-telemetry",summary:"Client schema is behind server; upgrade pm-cli to emit the latest event shape."},{code:"telemetry_otel_export_failing",command:"pm health --check-telemetry",summary:"OTLP trace spans are queued but the traces endpoint export is failing; spans retry automatically on the next reachable command, or set PM_TELEMETRY_OTEL_DISABLED=1 to skip OTLP export. Advisory only."},{code:"merge_driver_configuration_missing",command:"pm merge install",summary:"Install the clone-local Git drivers required by the tracker merge fence."},{code:"merge_driver_configuration_drift",command:"pm merge install",summary:"Reinstall clone-local Git drivers after runtime or package paths change."},{code:"validate_merge_driver_configuration",command:"pm merge install",summary:"Restore missing or drifted clone-local Git merge driver commands."},{code:"integrity_item_unreadable",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file could not be read; restore or repair the file at the reported path."},{code:"integrity_item_parse_failed",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file failed to parse; fix the malformed item metadata at the reported path."},{code:"integrity_item_conflict_marker",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file contains Git conflict markers; resolve the <<<<<<< / >>>>>>> markers at the reported line."},{code:"integrity_history_unreadable",command:"pm history-repair <id>",summary:"A history stream could not be read; re-anchor the affected item's history chain."},{code:"integrity_history_invalid_json",command:"pm history-repair <id>",summary:"A history stream contains invalid JSON; re-anchor the affected item's history chain."},{code:"integrity_history_conflict_marker",command:"pm history-repair <id>",summary:"A history stream contains Git conflict markers; resolve the markers, then re-anchor the chain."},{code:"validate_storage_unreadable_items",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"An on-disk item file cannot be parsed (for example a botched merge resolution with stale TOON count headers); repair or restore the file at the reported path \u2014 list commands silently skip it while pm get hard-errors."},{code:"validate_storage_duplicate_item_ids",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"One item id is claimed by multiple item documents \u2014 usually two branches minting the same id for different items before merging (GH-600). Keep one document, recreate the other item under a fresh id (pm copy, then delete the colliding file), and consider raising ids.token_length for concurrent multi-agent work."},{code:"validate_storage_history_conflict_markers",command:"pm merge driver history <base> <ours> <theirs>",summary:"A history stream contains unresolved Git conflict markers; re-merge it with the pm history merge driver (or resolve the markers by hand), then run pm history-repair for the item."},{code:"validate_storage_unparseable_history",command:"pm history-repair <id>",summary:"A history stream's newest line is not valid JSONL; repair or restore the stream before further mutations."},{code:"validate_storage_resurrected_items",command:"pm delete <id>",summary:"A live item's newest history operation is a delete: a delete/modify merge silently resurrected it. Decide the winner \u2014 re-delete the item, or keep it and append a mutation documenting the revival."},{code:"validate_storage_unparseable_config",command:"pm merge driver json <base> <ours> <theirs>",summary:"settings.json or a schema file cannot be parsed, so pm silently falls back to defaults; re-merge it with the pm JSON merge driver or fix the file by hand, then rerun pm validate."},{code:"validate_merge_fence_drift",command:"pm merge install",summary:"The committed .gitattributes merge fence no longer matches the active schema's type folders or tracker JSONL stores; rerun pm merge install (and commit .gitattributes) so every tracker artifact keeps its field-aware merge driver."},{code:"validate_storage_tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command, commit the index-only removals and managed .gitignore fence, then rerun validation."},{code:"integrity_item_outdated_format_version",command:"pm validate --verbose-diagnostics",summary:"An item predates the current storage format version; a pm storage migration rewrites it. Use --verbose-diagnostics to list the affected items."},{code:"integrity_item_ahead_format_version",command:"npm install -g @unbrained/pm-cli@latest",summary:"An item was written by a newer pm format version than this runtime supports; upgrade pm to read and validate it safely."},{code:"tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command from the integrity check, commit the index-only removals, and keep the managed .gitignore fence."},{code:"merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:"Review the pending merge receipts, re-apply any intended discarded values, then run pm merge reconcile; lossy receipts require explicit --force acceptance."},{code:"merge_receipts_pending",command:"pm merge reconcile",summary:"A lossless merge receipt is still pending; run pm merge reconcile to settle it (optionally preview first with --dry-run) so a green health gate certifies receipt settlement, not only intact data."},{code:"merge_receipt_evidence_invalid",command:"pm merge report --include-reconciled --json",summary:"One or more receipt candidates failed bounded-file, schema, identity, or copy-consistency validation; inspect the report's privacy-safe source, receipt id, and reason before repairing only the named evidence."},{code:"merge_receipt_history_reference_missing",command:"pm merge reconcile --dry-run",summary:"Review the bounded coordinates and recover available evidence first; for exact pre-durable clone-local-only references, rerun with --force so pm appends an audited disposition and proves the health finding is cleared without rewriting history."},{code:"validate_merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:"Review the pending merge receipts before reconciliation; history-repair alone does not settle them, and lossy receipts require explicit --force acceptance."},{code:"history_drift_missing_stream",command:"pm history-repair <id>",summary:"The item has no history stream; re-anchor the chain to rebuild it (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_unreadable_stream",command:"pm history-repair <id>",summary:"The item's history stream is unreadable; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_hash_mismatch",command:"pm history-repair <id>",summary:"The item's content hash no longer matches its history; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_chain_mismatch",command:"pm history-repair <id>",summary:"The item's history chain is broken; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_version_skew",command:"npm install -g @unbrained/pm-cli@latest",summary:"A history stream declares an item hash version this runtime does not support; upgrade pm to verify the chain instead of re-anchoring it."},{code:"history_drift_merge_receipt",command:"pm merge reconcile",summary:"Canonical path, changed-field, and merged-value hash evidence attributes this drift to a pending receipt; run reconciliation (optionally preview first with --dry-run) instead of repairing history directly."},{code:"history_stream_over_compact_threshold",command:"pm history-compact <id>",summary:"The history stream exceeds the configured compaction threshold; compact it (pm history-compact --all-streams sweeps every over-threshold stream in one pass)."},{code:"history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"provenance_value_domain_invalid",command:"pm history-repair --all --normalize-provenance",summary:"Remove invalid bounded provenance observations from affected streams and append privacy-safe aggregate repair receipts."},{code:"validate_history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"locks_stale_count",command:"pm gc --scope locks",summary:"Stale item-claim locks (embedded ttl elapsed) can block mutations; sweep them \u2014 gc retains active and unparseable locks."},{code:"locks_unreadable",command:"pm gc --scope locks --dry-run",summary:"Some lock files could not be read; preview the sweep and inspect the unreadable files manually \u2014 gc never deletes what it cannot read."},{code:"extension_update_health_partial_coverage",command:"pm extension --adopt-all --project",summary:"Update-health coverage is partial because unmanaged extensions were skipped; adopt the existing installs into managed metadata so the update scan covers them (use --global for global-scope extensions, or pm package --adopt-all when working with packages)."},{code:"vectorization_stale_items_remaining",command:"pm health --refresh-vectors",summary:"Some items have stale embeddings; refresh vectors so semantic search results stay current."},{code:"vectorization_embedding_identity_changed",command:"pm reindex --mode semantic",summary:"Embedding provider/model changed since the last index; run a semantic reindex to rebuild vectors."},{code:"validate_metadata_missing_closed_at",command:"pm validate --check-metadata --auto-fix --fix-scope timestamps --dry-run",summary:"Preview closure dates proven by verified lifecycle history; inspect residuals and omit --dry-run to apply only proven dates."},{code:"validate_metadata_missing_acceptance_criteria",command:'pm update <id> --acceptance-criteria "<criteria>"',summary:"Backfill the missing acceptance criteria on the reported item(s)."},{code:"validate_metadata_missing_estimate",command:'pm update <id> --estimate "<estimate>"',summary:"Backfill the missing estimate on the reported item(s)."},{code:"validate_metadata_missing_close_reason",command:'pm update <id> --close-reason "<reason>"',summary:"Backfill the missing close reason on the reported closed item(s)."},{code:"validate_metadata_missing_reviewer",command:'pm update <id> --reviewer "<name>"',summary:"Backfill the missing reviewer on the reported item(s)."},{code:"validate_metadata_missing_risk",command:'pm update <id> --risk "<level>"',summary:"Backfill the missing risk on the reported item(s)."},{code:"validate_metadata_missing_confidence",command:'pm update <id> --confidence "<level>"',summary:"Backfill the missing confidence on the reported item(s)."},{code:"validate_metadata_missing_sprint",command:'pm update <id> --sprint "<sprint>"',summary:"Backfill the missing sprint on the reported item(s)."},{code:"validate_metadata_missing_release",command:'pm update <id> --release "<release>"',summary:"Backfill the missing release on the reported item(s)."},{code:"validate_metadata_custom_profile_missing_required_fields",command:'pm config set metadata-required-fields --criterion "<field>"',summary:"Config-driven finding: the custom metadata profile has no required fields configured and falls back to core, so configure the fields rather than mutating items."},{code:"validate_metadata_duplicate_issue_codes",command:'pm update <id> --title "<distinct title>"',summary:"Two or more items share one logical issue code (GH-235); give each a distinct title so the derived code is unique, or close the redundant item with pm close <id> --duplicate-of <canonical-id> (closed-as-duplicate items are excluded from the check)."},{code:"validate_resolution_missing_fields",command:'pm update <id> --resolution "<how resolved>"',summary:"Backfill resolution / expected_result / actual_result on the reported closed item(s)."},{code:"validate_lifecycle_active_closure_like_metadata",command:"pm update <id> --unset <closure-like-field>",summary:"Clear the closure-like field the validator flags on this active item \u2014 the detail row names it (resolution / actual-result / blocked-reason) \u2014 or close the item if it is actually done."},{code:"validate_lifecycle_active_terminal_parent",command:"pm update <id> --parent <active-parent-id>",summary:"Reopen the terminal parent or move the active child under a non-terminal parent."},{code:"validate_lifecycle_stale_blockers",command:"pm update <id> --unset blocked-by --unset blocked-reason",summary:"Resolve the stale blocker the validator flags: clear blocked-by/blocked-reason when they linger on a non-blocked item or report a resolved blocker; if instead a blocked item is missing blocker context, add the context or move it out of a blocked status."},{code:"validate_lifecycle_dependency_cycles_error",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_lifecycle_dependency_cycles",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_hierarchy_parent_cycle_error",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_hierarchy_parent_cycle",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_files_missing_linked_paths",command:"pm <files|docs> <id> --remove <path>",summary:"The check spans both item.files and item.docs under one code: restore the missing linked artifact, or unlink it with pm files (linked file) or pm docs (linked doc)."},{code:"validate_files_orphaned_paths",command:"pm <files|docs> <id> --add <path>",summary:"Link the orphaned artifact with pm files (file) or pm docs (doc), or remove it from the workspace."},{code:"validate_files_tracked_all_strict_forces_pm_internals",command:"pm validate --check-files --include-pm-internals",summary:"tracked-all-strict scan flagged pm internals; re-run with --include-pm-internals or a softer --scan-mode."},{code:"validate_history_drift_missing_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items missing a history stream."},{code:"validate_history_drift_unreadable_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with an unreadable history stream."},{code:"validate_history_drift_hash_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items whose content hash drifted."},{code:"validate_history_drift_chain_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with a broken history chain."},{code:"validate_history_drift_version_skews",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more history streams declare an item hash version this runtime does not support; upgrade pm to verify the chains instead of re-anchoring them."},{code:"validate_command_references_stale_pm_ids",command:'pm update <id> --replace-tests --test "command=<corrected-command>" [--test ...]',summary:"Correct the stale pm-ID inside the item's linked test command (the check scans tests[].command, not the body). --replace-tests overwrites the entire tests list, so re-include the item's other linked tests in the same call."},{code:"validate_format_version_outdated_items",command:"pm validate --verbose-diagnostics",summary:"One or more items predate the current storage format version; a pm storage migration rewrites them. Use --verbose-diagnostics to list the affected items."},{code:"validate_format_version_ahead_items",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more items were written by a newer pm format version than this runtime supports; upgrade pm to read and validate them safely."}]);function resolveRemediation(warning){if(typeof warning!=="string"){return void 0}const normalized=warning.trim();for(const entry of REMEDIATION_REGISTRY){if(normalized===entry.code||normalized.startsWith(`${entry.code}:`)){return entry}}return void 0}function buildRemediationMap(warnings){const map={};for(const warning of warnings){const entry=resolveRemediation(warning);if(entry!==void 0&&!Object.prototype.hasOwnProperty.call(map,entry.code)){map[entry.code]=entry.command}}return map}function buildRemediationCommands(warnings){return Object.values(buildRemediationMap(warnings))}export{REMEDIATION_REGISTRY,buildRemediationCommands,buildRemediationMap,resolveRemediation};
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]="fac6b840-f5f1-51f6-b643-99b48ac864ba")}catch(e2){}})();const REMEDIATION_REGISTRY=Object.freeze([{code:"missing_directory",command:"pm init",summary:"Recreate missing tracker directories (pm init is idempotent and restores the scaffold)."},{code:"settings_read_fs_error",command:"pm config list --json",summary:"settings.json could not be read as a regular file and pm fell back to defaults; repair the reported path or permissions, then re-run."},{code:"settings_read_invalid_json",command:"pm config list --json",summary:"settings.json is not valid JSON and pm fell back to defaults; fix the syntax error in the reported path, then re-run."},{code:"settings_read_invalid_schema",command:"pm config list --json",summary:"settings.json failed schema validation and pm fell back to defaults; correct the reported key in the file, then re-run."},{code:"settings_read_merge_failed",command:"pm config list --json",summary:"Global/project settings could not be merged; reconcile the conflicting keys in the reported settings files."},{code:"settings:id_prefix_empty",command:"pm config list --json",summary:'id_prefix is empty; set a non-empty "id_prefix" in settings.json so generated item ids are well-formed.'},{code:"settings:locks_ttl_non_positive",command:"pm config list --json",summary:'locks.ttl_seconds must be positive; set a positive "locks.ttl_seconds" in settings.json.'},{code:"telemetry_state_invalid_json",command:"pm health --check-telemetry",summary:"Local telemetry state file is corrupt; pm recreates it on the next flush. Advisory only."},{code:"telemetry_queue_invalid_rows",command:"pm health --check-telemetry",summary:"The telemetry queue has unparseable rows; they are skipped on the next flush. Advisory only."},{code:"telemetry_queue_pending",command:"pm health --check-telemetry",summary:"Telemetry events are queued; they flush automatically on the next reachable command. Advisory only."},{code:"telemetry_queue_high_retries",command:"pm telemetry flush",summary:"Some queued telemetry events are near retry exhaustion; flush now and verify endpoint reachability before entries are dropped."},{code:"telemetry_endpoint_probe_failed",command:"pm health --check-telemetry",summary:"The telemetry endpoint is unreachable; events stay queued until it recovers. Advisory only."},{code:"telemetry_endpoint_probe_http_status",command:"pm health --check-telemetry",summary:"The telemetry endpoint returned a non-success status; events stay queued until it recovers. Advisory only."},{code:"telemetry_schema_version_behind",command:"pm health --check-telemetry",summary:"Client schema is behind server; upgrade pm-cli to emit the latest event shape."},{code:"telemetry_otel_export_failing",command:"pm health --check-telemetry",summary:"OTLP trace spans are queued but the traces endpoint export is failing; spans retry automatically on the next reachable command, or set PM_TELEMETRY_OTEL_DISABLED=1 to skip OTLP export. Advisory only."},{code:"merge_driver_configuration_missing",command:"pm merge install",summary:"Install the clone-local Git drivers required by the tracker merge fence."},{code:"merge_driver_configuration_drift",command:"pm merge install",summary:"Reinstall clone-local Git drivers after runtime or package paths change."},{code:"merge_fence_missing",command:"pm merge install",summary:"Install the active tracker's committed Git merge attributes."},{code:"merge_fence_drift",command:"pm merge install",summary:"Restore the active tracker's merge mappings while retaining sibling tracker fences."},{code:"validate_merge_driver_configuration",command:"pm merge install",summary:"Restore missing or drifted clone-local Git merge driver commands."},{code:"integrity_item_unreadable",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file could not be read; restore or repair the file at the reported path."},{code:"integrity_item_parse_failed",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file failed to parse; fix the malformed item metadata at the reported path."},{code:"integrity_item_conflict_marker",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file contains Git conflict markers; resolve the <<<<<<< / >>>>>>> markers at the reported line."},{code:"integrity_history_unreadable",command:"pm history-repair <id>",summary:"A history stream could not be read; re-anchor the affected item's history chain."},{code:"integrity_history_invalid_json",command:"pm history-repair <id>",summary:"A history stream contains invalid JSON; re-anchor the affected item's history chain."},{code:"integrity_history_conflict_marker",command:"pm history-repair <id>",summary:"A history stream contains Git conflict markers; resolve the markers, then re-anchor the chain."},{code:"validate_storage_unreadable_items",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"An on-disk item file cannot be parsed (for example a botched merge resolution with stale TOON count headers); repair or restore the file at the reported path \u2014 list commands silently skip it while pm get hard-errors."},{code:"validate_storage_duplicate_item_ids",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"One item id is claimed by multiple item documents \u2014 usually two branches minting the same id for different items before merging (GH-600). Keep one document, recreate the other item under a fresh id (pm copy, then delete the colliding file), and consider raising ids.token_length for concurrent multi-agent work."},{code:"validate_storage_history_conflict_markers",command:"pm merge driver history <base> <ours> <theirs>",summary:"A history stream contains unresolved Git conflict markers; re-merge it with the pm history merge driver (or resolve the markers by hand), then run pm history-repair for the item."},{code:"validate_storage_unparseable_history",command:"pm history-repair <id>",summary:"A history stream's newest line is not valid JSONL; repair or restore the stream before further mutations."},{code:"validate_storage_resurrected_items",command:"pm delete <id>",summary:"A live item's newest history operation is a delete: a delete/modify merge silently resurrected it. Decide the winner \u2014 re-delete the item, or keep it and append a mutation documenting the revival."},{code:"validate_storage_unparseable_config",command:"pm merge driver json <base> <ours> <theirs>",summary:"settings.json or a schema file cannot be parsed, so pm silently falls back to defaults; re-merge it with the pm JSON merge driver or fix the file by hand, then rerun pm validate."},{code:"validate_merge_fence_drift",command:"pm merge install",summary:"The committed .gitattributes merge fence no longer matches the active schema's type folders or tracker JSONL stores; rerun pm merge install (and commit .gitattributes) so every tracker artifact keeps its field-aware merge driver."},{code:"validate_storage_tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command, commit the index-only removals and managed .gitignore fence, then rerun validation."},{code:"integrity_item_outdated_format_version",command:"pm validate --verbose-diagnostics",summary:"An item predates the current storage format version; a pm storage migration rewrites it. Use --verbose-diagnostics to list the affected items."},{code:"integrity_item_ahead_format_version",command:"npm install -g @unbrained/pm-cli@latest",summary:"An item was written by a newer pm format version than this runtime supports; upgrade pm to read and validate it safely."},{code:"tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command from the integrity check, commit the index-only removals, and keep the managed .gitignore fence."},{code:"merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:"Review the pending merge receipts, re-apply any intended discarded values, then run pm merge reconcile; lossy receipts require explicit --force acceptance."},{code:"merge_receipts_pending",command:"pm merge reconcile",summary:"A lossless merge receipt is still pending; run pm merge reconcile to settle it (optionally preview first with --dry-run) so a green health gate certifies receipt settlement, not only intact data."},{code:"merge_receipt_evidence_invalid",command:"pm merge report --include-reconciled --json",summary:"One or more receipt candidates failed bounded-file, schema, identity, or copy-consistency validation; inspect the report's privacy-safe source, receipt id, and reason before repairing only the named evidence."},{code:"merge_receipt_history_reference_missing",command:"pm merge reconcile --dry-run",summary:"Review the bounded coordinates and recover available evidence first; for exact pre-durable clone-local-only references, rerun with --force so pm appends an audited disposition and proves the health finding is cleared without rewriting history."},{code:"validate_merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:"Review the pending merge receipts before reconciliation; history-repair alone does not settle them, and lossy receipts require explicit --force acceptance."},{code:"history_drift_missing_stream",command:"pm history-repair <id>",summary:"The item has no history stream; re-anchor the chain to rebuild it (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_unreadable_stream",command:"pm history-repair <id>",summary:"The item's history stream is unreadable; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_hash_mismatch",command:"pm history-repair <id>",summary:"The item's content hash no longer matches its history; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_chain_mismatch",command:"pm history-repair <id>",summary:"The item's history chain is broken; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_version_skew",command:"npm install -g @unbrained/pm-cli@latest",summary:"A history stream declares an item hash version this runtime does not support; upgrade pm to verify the chain instead of re-anchoring it."},{code:"history_drift_merge_receipt",command:"pm merge reconcile",summary:"Canonical path, changed-field, and merged-value hash evidence attributes this drift to a pending receipt; run reconciliation (optionally preview first with --dry-run) instead of repairing history directly."},{code:"history_stream_over_compact_threshold",command:"pm history-compact <id>",summary:"The history stream exceeds the configured compaction threshold; compact it (pm history-compact --all-streams sweeps every over-threshold stream in one pass)."},{code:"history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"provenance_value_domain_invalid",command:"pm history-repair --all --normalize-provenance",summary:"Remove invalid bounded provenance observations from affected streams and append privacy-safe aggregate repair receipts."},{code:"validate_history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"locks_stale_count",command:"pm gc --scope locks",summary:"Stale item-claim locks (embedded ttl elapsed) can block mutations; sweep them \u2014 gc retains active and unparseable locks."},{code:"locks_unreadable",command:"pm gc --scope locks --dry-run",summary:"Some lock files could not be read; preview the sweep and inspect the unreadable files manually \u2014 gc never deletes what it cannot read."},{code:"extension_update_health_partial_coverage",command:"pm extension --adopt-all --project",summary:"Update-health coverage is partial because unmanaged extensions were skipped; adopt the existing installs into managed metadata so the update scan covers them (use --global for global-scope extensions, or pm package --adopt-all when working with packages)."},{code:"vectorization_stale_items_remaining",command:"pm health --refresh-vectors",summary:"Some items have stale embeddings; refresh vectors so semantic search results stay current."},{code:"vectorization_embedding_identity_changed",command:"pm reindex --mode semantic",summary:"Embedding provider/model changed since the last index; run a semantic reindex to rebuild vectors."},{code:"validate_metadata_missing_closed_at",command:"pm validate --check-metadata --auto-fix --fix-scope timestamps --dry-run",summary:"Preview closure dates proven by verified lifecycle history; inspect residuals and omit --dry-run to apply only proven dates."},{code:"validate_metadata_missing_acceptance_criteria",command:'pm update <id> --acceptance-criteria "<criteria>"',summary:"Backfill the missing acceptance criteria on the reported item(s)."},{code:"validate_metadata_missing_estimate",command:'pm update <id> --estimate "<estimate>"',summary:"Backfill the missing estimate on the reported item(s)."},{code:"validate_metadata_missing_close_reason",command:'pm update <id> --close-reason "<reason>"',summary:"Backfill the missing close reason on the reported closed item(s)."},{code:"validate_metadata_missing_reviewer",command:'pm update <id> --reviewer "<name>"',summary:"Backfill the missing reviewer on the reported item(s)."},{code:"validate_metadata_missing_risk",command:'pm update <id> --risk "<level>"',summary:"Backfill the missing risk on the reported item(s)."},{code:"validate_metadata_missing_confidence",command:'pm update <id> --confidence "<level>"',summary:"Backfill the missing confidence on the reported item(s)."},{code:"validate_metadata_missing_sprint",command:'pm update <id> --sprint "<sprint>"',summary:"Backfill the missing sprint on the reported item(s)."},{code:"validate_metadata_missing_release",command:'pm update <id> --release "<release>"',summary:"Backfill the missing release on the reported item(s)."},{code:"validate_metadata_custom_profile_missing_required_fields",command:'pm config set metadata-required-fields --criterion "<field>"',summary:"Config-driven finding: the custom metadata profile has no required fields configured and falls back to core, so configure the fields rather than mutating items."},{code:"validate_metadata_duplicate_issue_codes",command:'pm update <id> --title "<distinct title>"',summary:"Two or more items share one logical issue code (GH-235); give each a distinct title so the derived code is unique, or close the redundant item with pm close <id> --duplicate-of <canonical-id> (closed-as-duplicate items are excluded from the check)."},{code:"validate_resolution_missing_fields",command:'pm update <id> --resolution "<how resolved>"',summary:"Backfill resolution / expected_result / actual_result on the reported closed item(s)."},{code:"validate_lifecycle_active_closure_like_metadata",command:"pm update <id> --unset <closure-like-field>",summary:"Clear the closure-like field the validator flags on this active item \u2014 the detail row names it (resolution / actual-result / blocked-reason) \u2014 or close the item if it is actually done."},{code:"validate_lifecycle_active_terminal_parent",command:"pm update <id> --parent <active-parent-id>",summary:"Reopen the terminal parent or move the active child under a non-terminal parent."},{code:"validate_lifecycle_stale_blockers",command:"pm update <id> --unset blocked-by --unset blocked-reason",summary:"Resolve the stale blocker the validator flags: clear blocked-by/blocked-reason when they linger on a non-blocked item or report a resolved blocker; if instead a blocked item is missing blocker context, add the context or move it out of a blocked status."},{code:"validate_lifecycle_dependency_cycles_error",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_lifecycle_dependency_cycles",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_hierarchy_parent_cycle_error",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_hierarchy_parent_cycle",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_files_missing_linked_paths",command:"pm <files|docs> <id> --remove <path>",summary:"The check spans both item.files and item.docs under one code: restore the missing linked artifact, or unlink it with pm files (linked file) or pm docs (linked doc)."},{code:"validate_files_orphaned_paths",command:"pm <files|docs> <id> --add <path>",summary:"Link the orphaned artifact with pm files (file) or pm docs (doc), or remove it from the workspace."},{code:"validate_files_tracked_all_strict_forces_pm_internals",command:"pm validate --check-files --include-pm-internals",summary:"tracked-all-strict scan flagged pm internals; re-run with --include-pm-internals or a softer --scan-mode."},{code:"validate_history_drift_missing_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items missing a history stream."},{code:"validate_history_drift_unreadable_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with an unreadable history stream."},{code:"validate_history_drift_hash_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items whose content hash drifted."},{code:"validate_history_drift_chain_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with a broken history chain."},{code:"validate_history_drift_version_skews",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more history streams declare an item hash version this runtime does not support; upgrade pm to verify the chains instead of re-anchoring them."},{code:"validate_command_references_stale_pm_ids",command:'pm update <id> --replace-tests --test "command=<corrected-command>" [--test ...]',summary:"Correct the stale pm-ID inside the item's linked test command (the check scans tests[].command, not the body). --replace-tests overwrites the entire tests list, so re-include the item's other linked tests in the same call."},{code:"validate_format_version_outdated_items",command:"pm validate --verbose-diagnostics",summary:"One or more items predate the current storage format version; a pm storage migration rewrites them. Use --verbose-diagnostics to list the affected items."},{code:"validate_format_version_ahead_items",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more items were written by a newer pm format version than this runtime supports; upgrade pm to read and validate them safely."}]);function resolveRemediation(warning){if(typeof warning!=="string"){return void 0}const normalized=warning.trim();for(const entry of REMEDIATION_REGISTRY){if(normalized===entry.code||normalized.startsWith(`${entry.code}:`)){return entry}}return void 0}function buildRemediationMap(warnings){const map={};for(const warning of warnings){const entry=resolveRemediation(warning);if(entry!==void 0&&!Object.prototype.hasOwnProperty.call(map,entry.code)){map[entry.code]=entry.command}}return map}function buildRemediationCommands(warnings){return Object.values(buildRemediationMap(warnings))}export{REMEDIATION_REGISTRY,buildRemediationCommands,buildRemediationMap,resolveRemediation};
2
2
  //# sourceMappingURL=remediation.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]="7a0fa585-7e3c-57fd-b29c-c26e9c522cb1")}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){const algorithm=resolveHistoryHashAlgorithm(entry.hash_algorithm);const beforeHashes=replayHashVerificationCandidates(before,version,algorithm);const afterHashes=replayHashVerificationCandidates(after,version,algorithm);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,false).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 verifyHistoryChainWithVersion(entries){let replay=cloneEmptyReplayDocument();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;detectedVersion=void 0;authoritativeExplicitVersion=void 0;continue}const candidates=historyEntryHashCandidates(explicitVersion,authoritativeExplicitVersion);const candidateMatches=candidates.map(version2=>({version:version2,match:matchReplayHashCandidates(replay,input.document,version2,entry)}));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;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="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")}
2
2
  `}export{EMPTY_REPLAY_DOCUMENT,cloneEmptyReplayDocument,historyEntriesToRaw,lenientApplyReplayPatch,normalizeReplayPatchOps,normalizeReplayPatchPath,reanchorHistoryEntries,replayHash,replayHashVerificationCandidates,replayToCanonicalItemDocument,replayToItemDocument,resolveHistoryRepairItemHashVersion,toReplayDocument,tryApplyReplayPatch,verifyHistoryChain,verifyHistoryChainWithVersion};
3
3
  //# sourceMappingURL=replay.js.map
@@ -1,4 +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]="48df511d-df81-56f7-bb1d-f10230b43cfa")}catch(e2){}})();import{encode as encodeToon}from"@toon-format/toon";import{isDeepStrictEqual}from"node:util";import{CONFIDENCE_TEXT_VALUES,ISSUE_SEVERITY_VALUES,PLAN_STEP_STATUS_VALUES,RECURRENCE_FREQUENCY_VALUES,RECURRENCE_WEEKDAY_VALUES,STATUS_VALUES,weekdayOrderIndex}from"../../types/index.js";import{coerceRuntimeFieldValue}from"../schema/runtime-field-values.js";import{resolveRuntimeFieldRegistry,resolveRuntimeStatusRegistry}from"../schema/runtime-schema.js";import{BASELINE_ITEM_FORMAT_VERSION,normalizeItemFormatVersion}from"./item-format-version.js";import{normalizeStatusInput}from"./status.js";import{decodeToonItemContent}from"./toon-decode.js";import{EXIT_CODE,ITEM_METADATA_KEY_ORDER}from"../shared/constants.js";import{findFirstMergeConflictMarker}from"../shared/conflict-markers.js";import{PmCliError}from"../shared/errors.js";import{orderObject}from"../shared/serialization.js";import{compareTimestampStrings,isTimestampLiteral}from"../shared/time.js";import{coerceFiniteNumber}from"../shared/primitives.js";const LINKED_TEST_PM_CONTEXT_MODE_VALUES=new Set(["schema","tracker","auto"]);const LINKED_TEST_WORKSPACE_CONTEXT_MODE_VALUES=new Set(["source","isolated","snapshot"]);const LINKED_TEST_TRUST_REASON_VALUES=new Set(["legacy","local_mutation","local_source_ref","acknowledged","invalid_provenance","foreign_source_ref"]);const ITEM_TEST_RUN_STATUS_VALUES=new Set(["passed","failed","stopped","canceled"]);const PLAN_STEP_STATUS_SET=new Set(PLAN_STEP_STATUS_VALUES);function normalizePathValue(value){return value.replaceAll("\\","/")}function firstNonZeroComparison(comparisons){for(const comparison of comparisons){if(comparison!==0){return comparison}}return 0}function deleteUndefinedFields(record){for(const[key,value]of Object.entries(record)){if(value===void 0){delete record[key]}}}const REQUIRED_STRING_FIELDS=["id","title","description","created_at","updated_at"];const STATIC_ITEM_METADATA_FIELD_SET=new Set(ITEM_METADATA_KEY_ORDER);function resolveRuntimeSchemaValidationContext(options){if(!options?.schema){return void 0}return{statusRegistry:resolveRuntimeStatusRegistry(options.schema),fieldRegistry:resolveRuntimeFieldRegistry(options.schema),unknownFieldPolicy:options.schema.unknown_field_policy??"allow",extensionFieldNames:new Set(options.extensionFieldNames??[]),onWarning:options.onWarning}}function runtimeFieldRequiredForType(definition,typeName){if(!definition.required){return false}if(definition.required_types.length===0){return true}return definition.required_types.map(value=>value.toLowerCase()).includes(typeName.trim().toLowerCase())}function validationError(message){const field=message.match(/^([a-z_][\w.]*)\s/u)?.[1];throw new PmCliError(`Invalid item metadata: ${message}`,EXIT_CODE.GENERIC_FAILURE,{code:"item_document_invalid",reason:message.includes("required")?"missing_required_field":"schema_validation_error",...field?{field}:{},required:"Provide an item document whose metadata satisfies the active runtime schema.",why:message})}function documentSyntaxError(format,message){throw new PmCliError(message,EXIT_CODE.GENERIC_FAILURE,{code:"item_document_invalid",reason:"syntax_error",format,required:`Provide a syntactically valid ${format==="toon"?"TOON":"JSON Markdown"} item document.`,why:"The document could not be decoded far enough to validate item metadata."})}function buildKnownItemMetadataKeys(runtimeContext){const knownKeys=new Set(STATIC_ITEM_METADATA_FIELD_SET);for(const definition of runtimeContext.fieldRegistry?.definitions??[]){knownKeys.add(definition.metadata_key)}for(const fieldName of runtimeContext.extensionFieldNames){knownKeys.add(fieldName)}return knownKeys}function assertItemMetadataCondition(condition,message){if(!condition){validationError(message)}}function requireItemMetadataRecord(value,message){if(typeof value!=="object"||value===null||Array.isArray(value)){validationError(message)}return value}function assertTimestampField(record,fieldName){const rawValue=record[fieldName];assertItemMetadataCondition(typeof rawValue==="string",`${fieldName} must be a string`);const timestamp=rawValue;assertItemMetadataCondition(isTimestampLiteral(timestamp),`${fieldName} must be a valid ISO timestamp`)}function assertPositiveIntegerField(record,fieldName,messagePrefix){const value=record[fieldName];if(value===void 0){return}assertItemMetadataCondition(typeof value==="number"&&Number.isInteger(value)&&value>=1,`${messagePrefix} must be an integer >= 1`)}function assertOptionalTimestampString(record,fieldName,messagePrefix){const value=record[fieldName];if(value===void 0){return}assertItemMetadataCondition(typeof value==="string",`${messagePrefix} must be a string`);assertItemMetadataCondition(isTimestampLiteral(value),`${messagePrefix} must be a valid ISO timestamp`)}function assertRecurrenceWeekdays(value){if(value===void 0){return}assertItemMetadataCondition(Array.isArray(value),"event.recurrence.by_weekday must be an array");for(const weekday of value){assertItemMetadataCondition(typeof weekday==="string","event.recurrence.by_weekday entries must be strings");const normalizedWeekday=weekday.trim().toLowerCase();assertItemMetadataCondition(RECURRENCE_WEEKDAY_VALUES.includes(normalizedWeekday),`event.recurrence.by_weekday entries must be one of: ${RECURRENCE_WEEKDAY_VALUES.join(", ")}`)}}function assertRecurrenceMonthDays(value){if(value===void 0){return}assertItemMetadataCondition(Array.isArray(value),"event.recurrence.by_month_day must be an array");for(const day of value){assertItemMetadataCondition(typeof day==="number"&&Number.isInteger(day)&&day>=1&&day<=31,"event.recurrence.by_month_day entries must be integers 1..31")}}function assertRecurrenceExdates(value){if(value===void 0){return}assertItemMetadataCondition(Array.isArray(value),"event.recurrence.exdates must be an array");for(const exdate of value){assertItemMetadataCondition(typeof exdate==="string","event.recurrence.exdates entries must be strings");assertItemMetadataCondition(isTimestampLiteral(exdate),"event.recurrence.exdates entries must be valid ISO timestamps")}}function assertValidRecurrenceRule(recurrence){const recurrenceRecord=requireItemMetadataRecord(recurrence,"event.recurrence must be an object");assertItemMetadataCondition(typeof recurrenceRecord.freq==="string","event.recurrence.freq must be a string");const frequency=recurrenceRecord.freq.trim().toLowerCase();assertItemMetadataCondition(RECURRENCE_FREQUENCY_VALUES.includes(frequency),`event.recurrence.freq must be one of: ${RECURRENCE_FREQUENCY_VALUES.join(", ")}`);assertPositiveIntegerField(recurrenceRecord,"interval","event.recurrence.interval");assertPositiveIntegerField(recurrenceRecord,"count","event.recurrence.count");assertOptionalTimestampString(recurrenceRecord,"until","event.recurrence.until");assertRecurrenceWeekdays(recurrenceRecord.by_weekday);assertRecurrenceMonthDays(recurrenceRecord.by_month_day);assertRecurrenceExdates(recurrenceRecord.exdates)}function assertRequiredItemMetadataFields(record){for(const fieldName of REQUIRED_STRING_FIELDS){assertItemMetadataCondition(typeof record[fieldName]==="string",`${fieldName} is required and must be a string`)}const itemType=record.type;assertItemMetadataCondition(typeof itemType==="string"&&itemType.trim().length>0,"type must be a non-empty string");const formatVersion=record.pm_format_version;if(formatVersion!==void 0){assertItemMetadataCondition(typeof formatVersion==="number"&&Number.isInteger(formatVersion)&&formatVersion>=BASELINE_ITEM_FORMAT_VERSION,`pm_format_version must be an integer >= ${BASELINE_ITEM_FORMAT_VERSION}`)}return itemType}function assertStatusItemMetadataField(record,runtimeContext){const status=record.status;assertItemMetadataCondition(typeof status==="string"&&status.trim().length>0,"status must be a non-empty string");const statusRegistry=runtimeContext?.statusRegistry;const normalizedStatus=normalizeStatusInput(status,statusRegistry);const statusDomain=statusRegistry?statusRegistry.definitions.map(definition=>definition.id):[...STATUS_VALUES];assertItemMetadataCondition(normalizedStatus!==void 0,`status must be one of: ${statusDomain.join(", ")}`)}function assertPriorityAndTags(record){const priority=record.priority;assertItemMetadataCondition(typeof priority==="number"&&Number.isInteger(priority)&&[0,1,2,3,4].includes(priority),"priority must be an integer 0..4");const tags=record.tags;assertItemMetadataCondition(Array.isArray(tags),"tags must be an array");for(const tag of tags){assertItemMetadataCondition(typeof tag==="string","tags entries must be strings")}}function assertConfidenceItemMetadataField(record){const confidence=record.confidence;if(confidence===void 0){return}if(typeof confidence==="number"){assertItemMetadataCondition(Number.isInteger(confidence)&&confidence>=0&&confidence<=100,"confidence number value must be an integer 0..100");return}if(typeof confidence==="string"){const normalizedConfidence=confidence.trim().toLowerCase();const isKnownTextConfidence=normalizedConfidence==="med"||CONFIDENCE_TEXT_VALUES.includes(normalizedConfidence);assertItemMetadataCondition(isKnownTextConfidence,`confidence string value must be one of: ${[...CONFIDENCE_TEXT_VALUES,"med"].join(", ")}`);return}assertItemMetadataCondition(false,"confidence must be a number or string")}function assertSeverityItemMetadataField(record){const severity=record.severity;if(severity===void 0){return}if(typeof severity!=="string"){validationError("severity must be a string")}const normalizedSeverity=severity.trim().toLowerCase();const isKnownSeverity=normalizedSeverity==="med"||ISSUE_SEVERITY_VALUES.includes(normalizedSeverity);assertItemMetadataCondition(isKnownSeverity,`severity value must be one of: ${[...ISSUE_SEVERITY_VALUES,"med"].join(", ")}`)}function assertRegressionItemMetadataField(record){if(record.regression!==void 0&&typeof record.regression!=="boolean"){validationError("regression must be a boolean")}}function assertReminderEntries(record){const reminders=record.reminders;if(reminders===void 0){return}assertItemMetadataCondition(Array.isArray(reminders),"reminders must be an array");for(const reminder of reminders){const reminderRecord=requireItemMetadataRecord(reminder,"reminders entries must be objects");assertItemMetadataCondition(typeof reminderRecord.at==="string","reminder.at must be a string");assertItemMetadataCondition(isTimestampLiteral(reminderRecord.at),"reminder.at must be a valid ISO timestamp");assertItemMetadataCondition(typeof reminderRecord.text==="string","reminder.text must be a string");assertItemMetadataCondition(reminderRecord.text.trim().length>0,"reminder.text must not be empty")}}function assertEventStringFields(eventRecord){for(const stringField of["title","description","location","timezone"]){if(eventRecord[stringField]!==void 0){assertItemMetadataCondition(typeof eventRecord[stringField]==="string",`event.${stringField} must be a string`);assertItemMetadataCondition(eventRecord[stringField].trim().length>0,`event.${stringField} must not be empty`)}}}function assertEventRecurrence(eventRecord){if(eventRecord.recurrence===void 0){return}assertValidRecurrenceRule(eventRecord.recurrence);if(eventRecord.recurrence.until!==void 0){assertItemMetadataCondition(compareTimestampStrings(eventRecord.recurrence.until,eventRecord.start_at)>=0,"event.recurrence.until must be at or after event.start_at")}}function assertCalendarEventEntry(event){const eventRecord=requireItemMetadataRecord(event,"events entries must be objects");assertItemMetadataCondition(typeof eventRecord.start_at==="string","event.start_at must be a string");assertItemMetadataCondition(isTimestampLiteral(eventRecord.start_at),"event.start_at must be a valid ISO timestamp");if(eventRecord.end_at!==void 0){assertItemMetadataCondition(typeof eventRecord.end_at==="string","event.end_at must be a string");assertItemMetadataCondition(isTimestampLiteral(eventRecord.end_at),"event.end_at must be a valid ISO timestamp");assertItemMetadataCondition(compareTimestampStrings(eventRecord.end_at,eventRecord.start_at)>0,"event.end_at must be after event.start_at")}assertEventStringFields(eventRecord);if(eventRecord.all_day!==void 0){assertItemMetadataCondition(typeof eventRecord.all_day==="boolean","event.all_day must be a boolean")}assertEventRecurrence(eventRecord)}function assertCalendarEvents(record){const events=record.events;if(events===void 0){return}assertItemMetadataCondition(Array.isArray(events),"events must be an array");for(const event of events){assertCalendarEventEntry(event)}}function assertOptionalStringFields(record){for(const fieldName of["source_type","source_owner","design","external_ref"]){const value=record[fieldName];if(value!==void 0){assertItemMetadataCondition(typeof value==="string",`${fieldName} must be a string`)}}}function assertTypeOptionsField(record){const typeOptions=record.type_options;if(typeOptions===void 0){return}const typeOptionsRecord=requireItemMetadataRecord(typeOptions,"type_options must be an object");for(const[optionKey,optionValue]of Object.entries(typeOptionsRecord)){assertItemMetadataCondition(optionKey.trim().length>0,"type_options keys must be non-empty");assertItemMetadataCondition(typeof optionValue==="string","type_options values must be strings");const optionText=optionValue;assertItemMetadataCondition(optionText.trim().length>0,"type_options values must be non-empty strings")}}function coerceRuntimeItemMetadataFields(record,itemType,runtimeContext){if(!runtimeContext?.fieldRegistry){return}for(const definition of runtimeContext.fieldRegistry.definitions){const fieldValue=record[definition.metadata_key];if(fieldValue===void 0){if(runtimeFieldRequiredForType(definition,itemType)){validationError(`missing required schema field: ${definition.metadata_key}`)}continue}try{record[definition.metadata_key]=coerceRuntimeFieldValue(definition,fieldValue,`metadata field "${definition.metadata_key}"`)}catch(error){validationError(String(error?.message).replace(/^Invalid\s+/u,""))}}}function assertRuntimeUnknownItemMetadataFields(record,runtimeContext){if(!runtimeContext||runtimeContext.unknownFieldPolicy==="allow"){return}const knownKeys=buildKnownItemMetadataKeys(runtimeContext);const unknownKeys=Object.keys(record).filter(key=>!knownKeys.has(key)).sort((left,right)=>left.localeCompare(right));if(unknownKeys.length===0){return}if(runtimeContext.unknownFieldPolicy==="reject"){validationError(`unknown schema fields are not allowed: ${unknownKeys.join(", ")}`)}else{runtimeContext.onWarning?.(`item_unknown_schema_fields:${unknownKeys.join(",")}`)}}function assertValidItemMetadata(itemMetadata,runtimeContext){const record=requireItemMetadataRecord(itemMetadata,"item metadata must be an object");const itemType=assertRequiredItemMetadataFields(record);assertStatusItemMetadataField(record,runtimeContext);assertPriorityAndTags(record);assertConfidenceItemMetadataField(record);assertSeverityItemMetadataField(record);assertRegressionItemMetadataField(record);assertTimestampField(record,"created_at");assertTimestampField(record,"updated_at");if(record.deadline!==void 0){assertTimestampField(record,"deadline")}assertReminderEntries(record);assertCalendarEvents(record);assertOptionalTimestampString(record,"closed_at","closed_at");assertOptionalTimestampString(record,"completed_at","completed_at");assertOptionalStringFields(record);assertTypeOptionsField(record);coerceRuntimeItemMetadataFields(record,itemType,runtimeContext);assertRuntimeUnknownItemMetadataFields(record,runtimeContext)}function sortDependencies(values){if(!values||values.length===0)return void 0;return[...values].map(value=>({id:value.id.trim(),kind:value.kind,created_at:value.created_at,author:value.author?.trim()||void 0,source_kind:value.source_kind?.trim()||void 0,author_source:value.author_source})).sort((a,b)=>{const byCreated=compareTimestampStrings(a.created_at,b.created_at);if(byCreated!==0)return byCreated;const byId=a.id.localeCompare(b.id);if(byId!==0)return byId;const byKind=a.kind.localeCompare(b.kind);if(byKind!==0)return byKind;return(a.source_kind??"").localeCompare(b.source_kind??"")})}function sortLogValues(values){if(!values||values.length===0)return void 0;return[...values].sort((a,b)=>{const byCreated=compareTimestampStrings(a.created_at,b.created_at);if(byCreated!==0)return byCreated;const byText=a.text.localeCompare(b.text);if(byText!==0)return byText;return a.author.localeCompare(b.author)})}function sortReminders(values){if(!values||values.length===0)return void 0;const normalized=[...values].map(value=>({at:value.at,text:value.text.trim()})).filter(value=>value.text.length>0).sort((a,b)=>{const byAt=compareTimestampStrings(a.at,b.at);if(byAt!==0)return byAt;return a.text.localeCompare(b.text)});return normalized.length===0?void 0:normalized}function normalizeRecurrenceRule(value){if(!value){return void 0}const normalizedFrequency=value.freq.trim().toLowerCase();if(!RECURRENCE_FREQUENCY_VALUES.includes(normalizedFrequency)){return void 0}const byWeekday=Array.from(new Set((value.by_weekday??[]).map(weekday=>weekday.trim().toLowerCase()).filter(weekday=>RECURRENCE_WEEKDAY_VALUES.includes(weekday)))).sort((a,b)=>weekdayOrderIndex(a)-weekdayOrderIndex(b));const byMonthDay=Array.from(new Set((value.by_month_day??[]).filter(day=>Number.isInteger(day)&&day>=1&&day<=31).map(day=>day))).sort((a,b)=>a-b);const exdates=Array.from(new Set((value.exdates??[]).map(timestamp=>timestamp.trim()).filter(timestamp=>isTimestampLiteral(timestamp)))).sort((a,b)=>compareTimestampStrings(a,b));const normalized={freq:normalizedFrequency,interval:value.interval!==void 0&&value.interval>1?value.interval:void 0,count:value.count,until:value.until?.trim()||void 0,by_weekday:byWeekday.length>0?byWeekday:void 0,by_month_day:byMonthDay.length>0?byMonthDay:void 0,exdates:exdates.length>0?exdates:void 0};for(const[key,fieldValue]of Object.entries(normalized)){if(fieldValue===void 0){delete normalized[key]}}return normalized}function sortEvents(values){if(!Array.isArray(values)||values.length===0){return void 0}const normalized=[...values].map(normalizeCalendarEvent).sort(compareCalendarEvents);return normalized}function normalizeCalendarEvent(value){const event={start_at:value.start_at,end_at:value.end_at||void 0,title:value.title?.trim()||void 0,description:value.description?.trim()||void 0,location:value.location?.trim()||void 0,all_day:value.all_day,timezone:value.timezone?.trim()||void 0,recurrence:normalizeRecurrenceRule(value.recurrence)};deleteUndefinedFields(event);return event}function compareCalendarEvents(a,b){return firstNonZeroComparison([compareTimestampStrings(a.start_at,b.start_at),(a.end_at??"").localeCompare(b.end_at??""),(a.title??"").localeCompare(b.title??""),Number(Boolean(a.all_day))-Number(Boolean(b.all_day)),(a.timezone??"").localeCompare(b.timezone??""),(a.location??"").localeCompare(b.location??""),(a.description??"").localeCompare(b.description??""),JSON.stringify(a.recurrence??{}).localeCompare(JSON.stringify(b.recurrence??{}))])}function normalizeFiles(values){if(!values||values.length===0)return void 0;return values.map(value=>({path:normalizePathValue(value.path),scope:value.scope,note:value.note?.trim()||void 0}))}function normalizeTestRunSummaries(values){if(!values||values.length===0)return void 0;const normalized=values.map(normalizeTestRunSummary).filter(value=>value.run_id.length>0&&value.started_at.length>0&&value.finished_at.length>0&&value.recorded_at.length>0).sort((a,b)=>firstNonZeroComparison([compareTimestampStrings(a.recorded_at,b.recorded_at),a.run_id.localeCompare(b.run_id),a.kind.localeCompare(b.kind)]));return normalized.length>0?normalized:void 0}function normalizeNonNegativeInteger(value){return typeof value==="number"&&Number.isFinite(value)&&value>=0?Math.floor(value):void 0}function normalizePositiveInteger(value){return typeof value==="number"&&Number.isFinite(value)&&value>=1?Math.floor(value):void 0}function stringOrEmpty(value){return typeof value==="string"?value:""}function normalizeTestRunMeasurements(value){if(!Array.isArray(value))return void 0;const normalized=value.filter(measurement=>measurement!==null&&typeof measurement==="object"&&typeof measurement.name==="string"&&measurement.name.trim().length>0&&typeof measurement.value==="number"&&Number.isFinite(measurement.value)&&typeof measurement.recorded_at==="string"&&measurement.recorded_at.trim().length>0).map(measurement=>({name:measurement.name.trim(),value:measurement.value,unit:typeof measurement.unit==="string"?measurement.unit.trim()||void 0:void 0,threshold:typeof measurement.threshold==="number"&&Number.isFinite(measurement.threshold)?measurement.threshold:void 0,recorded_at:measurement.recorded_at.trim()}));const deduplicated=[...new Map(normalized.map(measurement=>[measurement.name,measurement])).values()].sort((left,right)=>left.name.localeCompare(right.name)).slice(0,32);return deduplicated.length>0?deduplicated:void 0}function normalizeTestRunEnum(value,allowedValues){return typeof value==="string"&&allowedValues.has(value)?value:void 0}function normalizeTestRunExecutions(values){if(!Array.isArray(values))return void 0;const executions=values.filter(execution=>execution&&typeof execution.command==="string"&&execution.command.trim().length>0).slice(0,32).map(execution=>({command:execution.command.trim(),requested_pm_context_mode:normalizeTestRunEnum(execution.requested_pm_context_mode,LINKED_TEST_PM_CONTEXT_MODE_VALUES),pm_context_mode:normalizeTestRunEnum(execution.pm_context_mode,LINKED_TEST_PM_CONTEXT_MODE_VALUES),workspace_context_mode:normalizeTestRunEnum(execution.workspace_context_mode,LINKED_TEST_WORKSPACE_CONTEXT_MODE_VALUES),trust_reason:normalizeTestRunEnum(execution.trust_reason,LINKED_TEST_TRUST_REASON_VALUES)}));return executions.length>0?executions:void 0}function normalizeTestRunSummary(value){const runId=typeof value.run_id==="string"?value.run_id.trim():"";const kind=value.kind==="test"||value.kind==="test-all"?value.kind:"test";const status=ITEM_TEST_RUN_STATUS_VALUES.has(value.status)?value.status:"failed";const summary={run_id:runId,kind,status,started_at:stringOrEmpty(value.started_at),finished_at:stringOrEmpty(value.finished_at),recorded_at:stringOrEmpty(value.recorded_at),attempt:normalizePositiveInteger(value.attempt),resumed_from:value.resumed_from?.trim()||void 0,passed:normalizeNonNegativeInteger(value.passed)??0,failed:normalizeNonNegativeInteger(value.failed)??0,skipped:normalizeNonNegativeInteger(value.skipped)??0,items:normalizeNonNegativeInteger(value.items),linked_tests:normalizeNonNegativeInteger(value.linked_tests),fail_on_skipped_triggered:value.fail_on_skipped_triggered===true?true:void 0,measurements:normalizeTestRunMeasurements(value.measurements),executions:normalizeTestRunExecutions(value.executions)};deleteUndefinedFields(summary);return summary}function sortTests(values){if(!Array.isArray(values)||values.length===0)return void 0;return values.map(normalizeLinkedTest)}function normalizeTrimmedStringList(value){if(!Array.isArray(value)){return void 0}const normalized=[...new Set(value.filter(entry=>typeof entry==="string").map(entry=>entry.trim()).filter(entry=>entry.length>0))].sort((a,b)=>a.localeCompare(b));return normalized.length>0?normalized:void 0}function isPlainObjectRecord(value){if(!value||typeof value!=="object"||Array.isArray(value)){return false}const prototype=Object.getPrototypeOf(value);return prototype===Object.prototype||prototype===null}function isUnsafeObjectKey(key){return key==="__proto__"||key==="constructor"||key==="prototype"}function normalizeStringRecord(value){if(!isPlainObjectRecord(value)){return void 0}const entries=Object.entries(value).map(([key,recordValue])=>[key.trim(),String(recordValue).trim()]).filter(([key,recordValue])=>key.length>0&&!isUnsafeObjectKey(key)&&recordValue.length>0).sort(([left],[right])=>left.localeCompare(right));return entries.length>0?Object.fromEntries(entries):void 0}function normalizeNumericRecord(value){if(!isPlainObjectRecord(value)){return void 0}const entries=Object.entries(value).map(([key,recordValue])=>[key.trim(),Number(recordValue)]).filter(([key,recordValue])=>key.length>0&&!isUnsafeObjectKey(key)&&Number.isFinite(recordValue)).sort(([left],[right])=>left.localeCompare(right));return entries.length>0?Object.fromEntries(entries):void 0}function normalizeLinkedTestContextMode(value){const normalized=value?.trim().toLowerCase();if(!normalized||!LINKED_TEST_PM_CONTEXT_MODE_VALUES.has(normalized)){return void 0}return normalized}function normalizeLinkedTestWorkspaceContextMode(value){const normalized=value?.trim().toLowerCase();if(!normalized||!LINKED_TEST_WORKSPACE_CONTEXT_MODE_VALUES.has(normalized)){return void 0}return normalized}function normalizeLinkedTestProvenance(value,invalid){if(invalid===true){return{provenance_invalid:true}}if(value===void 0){return{}}if(!isPlainObjectRecord(value)){return{provenance_invalid:true}}const author=trimStringOrUndefined(value.author);const createdAt=trimStringOrUndefined(value.created_at);const sourceKind=value.source_kind;if(!author||!createdAt||!isTimestampLiteral(createdAt)||sourceKind!=="local_mutation"&&sourceKind!=="merge_union"){return{provenance_invalid:true}}return{provenance:{author,created_at:createdAt,source_kind:sourceKind,source_ref:trimStringOrUndefined(value.source_ref)}}}function normalizeLinkedTest(value){const test={command:value.command?.trim()||void 0,path:value.path?normalizePathValue(value.path):void 0,scope:value.scope,timeout_seconds:typeof value.timeout_seconds==="number"&&Number.isFinite(value.timeout_seconds)&&value.timeout_seconds>0?value.timeout_seconds:void 0,pm_context_mode:normalizeLinkedTestContextMode(value.pm_context_mode),workspace_context_mode:normalizeLinkedTestWorkspaceContextMode(value.workspace_context_mode),...normalizeLinkedTestProvenance(value.provenance,value.provenance_invalid),env_set:normalizeStringRecord(value.env_set),env_clear:normalizeTrimmedStringList(value.env_clear),shared_host_safe:value.shared_host_safe===true?true:void 0,assert_stdout_contains:normalizeTrimmedStringList(value.assert_stdout_contains),assert_stdout_regex:normalizeTrimmedStringList(value.assert_stdout_regex),assert_stderr_contains:normalizeTrimmedStringList(value.assert_stderr_contains),assert_stderr_regex:normalizeTrimmedStringList(value.assert_stderr_regex),assert_stdout_min_lines:normalizeNonNegativeInteger(value.assert_stdout_min_lines),assert_json_field_equals:normalizeStringRecord(value.assert_json_field_equals),assert_json_field_gte:normalizeNumericRecord(value.assert_json_field_gte),note:value.note?.trim()||void 0};deleteUndefinedFields(test);return test}function sortDocs(values){if(!values||values.length===0)return void 0;return[...values].map(value=>({path:normalizePathValue(value.path),scope:value.scope,note:value.note?.trim()||void 0})).sort((a,b)=>{const byScope=a.scope.localeCompare(b.scope);if(byScope!==0)return byScope;const byPath=a.path.localeCompare(b.path);if(byPath!==0)return byPath;return(a.note??"").localeCompare(b.note??"")})}function trimStringOrUndefined(value){if(typeof value!=="string")return void 0;const trimmed=value.trim();return trimmed.length>0?trimmed:void 0}function normalizePlanStepLinks(value){if(!Array.isArray(value))return void 0;const out=[];for(const entry of value){if(entry===null||typeof entry!=="object")continue;const record=entry;const id=trimStringOrUndefined(record.id);const kind=trimStringOrUndefined(record.kind);if(!id||!kind)continue;const link={id,kind};const note=trimStringOrUndefined(record.note);if(note)link.note=note;if(record.required_before_step===true)link.required_before_step=true;out.push(link)}return out.length>0?out:void 0}function normalizePlanStepFiles(value){if(!Array.isArray(value))return void 0;const out=[];for(const entry of value){if(entry===null||typeof entry!=="object")continue;const record=entry;const path=trimStringOrUndefined(record.path);if(!path)continue;const file={path:normalizePathValue(path)};if(record.scope==="project"||record.scope==="global")file.scope=record.scope;const note=trimStringOrUndefined(record.note);if(note)file.note=note;out.push(file)}return out.length>0?out:void 0}function normalizePlanStepTests(value){if(!Array.isArray(value))return void 0;const out=[];for(const entry of value){if(entry===null||typeof entry!=="object")continue;const record=entry;const command=trimStringOrUndefined(record.command);const path=trimStringOrUndefined(record.path);if(!command&&!path)continue;const test={};if(command)test.command=command;if(path)test.path=normalizePathValue(path);const note=trimStringOrUndefined(record.note);if(note)test.note=note;out.push(test)}return out.length>0?out:void 0}function normalizePlanStepDocs(value){if(!Array.isArray(value))return void 0;const out=[];for(const entry of value){if(entry===null||typeof entry!=="object")continue;const record=entry;const path=trimStringOrUndefined(record.path);if(!path)continue;const doc={path:normalizePathValue(path)};if(record.scope==="project"||record.scope==="global")doc.scope=record.scope;const note=trimStringOrUndefined(record.note);if(note)doc.note=note;out.push(doc)}return out.length>0?out:void 0}function normalizePlanStepEntry(entry){if(entry===null||typeof entry!=="object"){return void 0}const record=entry;const id=trimStringOrUndefined(record.id);const title=trimStringOrUndefined(record.title);const statusRaw=trimStringOrUndefined(record.status);const status=statusRaw&&PLAN_STEP_STATUS_SET.has(statusRaw)?statusRaw:void 0;const order=coerceFiniteNumber(record.order)??Number.NaN;const created_at=typeof record.created_at==="string"?record.created_at:"";const updated_at=typeof record.updated_at==="string"?record.updated_at:"";if(!id||!title||!status||!Number.isFinite(order)||!created_at||!updated_at){return void 0}const step={id,order,title,status,created_at,updated_at};applyPlanStepOptionalFields(step,record);return step}function applyPlanStepOptionalFields(step,record){const stringFields=[["body","body"],["owner","owner"],["evidence","evidence"],["blocked_reason","blocked_reason"],["superseded_by","superseded_by"]];for(const[target,source]of stringFields){const value=trimStringOrUndefined(record[source]);if(value){step[target]=value}}const completedAt=typeof record.completed_at==="string"?record.completed_at:void 0;if(completedAt&&completedAt.length>0){step.completed_at=completedAt}const collectionFields=[["linked_items","linked_items",normalizePlanStepLinks],["files","files",normalizePlanStepFiles],["tests","tests",normalizePlanStepTests],["docs","docs",normalizePlanStepDocs]];for(const[target,source,normalize]of collectionFields){const value=normalize(record[source]);if(value){step[target]=value}}}function normalizePlanSteps(value){if(!Array.isArray(value))return void 0;const out=value.flatMap(entry=>{const step=normalizePlanStepEntry(entry);return step?[step]:[]});out.sort((left,right)=>left.order-right.order);return out.length>0?out:void 0}function normalizePlanDecisions(value){if(!Array.isArray(value))return void 0;const out=[];for(const entry of value){if(entry===null||typeof entry!=="object")continue;const record=entry;const ts=typeof record.ts==="string"?record.ts:"";const author=typeof record.author==="string"?record.author:"";const decision=trimStringOrUndefined(record.decision);if(!ts||!author||!decision)continue;const item={ts,author,decision};const rationale=trimStringOrUndefined(record.rationale);if(rationale)item.rationale=rationale;const evidence=trimStringOrUndefined(record.evidence);if(evidence)item.evidence=evidence;const stepId=trimStringOrUndefined(record.step_id);if(stepId)item.step_id=stepId;out.push(item)}return out.length>0?out:void 0}function normalizePlanDiscoveries(value){if(!Array.isArray(value))return void 0;const out=[];for(const entry of value){if(entry===null||typeof entry!=="object")continue;const record=entry;const ts=typeof record.ts==="string"?record.ts:"";const author=typeof record.author==="string"?record.author:"";const text=trimStringOrUndefined(record.text);if(!ts||!author||!text)continue;const item={ts,author,text};const stepId=trimStringOrUndefined(record.step_id);if(stepId)item.step_id=stepId;out.push(item)}return out.length>0?out:void 0}function normalizePlanValidation(value){if(!Array.isArray(value))return void 0;const out=[];for(const entry of value){if(entry===null||typeof entry!=="object")continue;const record=entry;const text=trimStringOrUndefined(record.text);if(!text)continue;const item={text};const command=trimStringOrUndefined(record.command);if(command)item.command=command;const expected=trimStringOrUndefined(record.expected);if(expected)item.expected=expected;out.push(item)}return out.length>0?out:void 0}function normalizeTypeOptions(values){if(!values){return void 0}const normalizedEntries=Object.entries(values).map(([key,value])=>[key.trim(),value.trim()]).filter(([key,value])=>key.length>0&&value.length>0).sort((left,right)=>left[0].localeCompare(right[0]));if(normalizedEntries.length===0){return void 0}return Object.fromEntries(normalizedEntries)}function normalizeBody(body){let start=0;while(start<body.length&&body[start]==="\n"){start+=1}return body.slice(start).trimEnd()}function normalizeConfidenceValue(value){if(value===void 0){return void 0}if(typeof value==="number"){return value}const normalized=value.trim().toLowerCase();if(normalized==="med"){return"medium"}if(CONFIDENCE_TEXT_VALUES.includes(normalized)){return normalized}return void 0}function normalizeSeverityValue(value){if(value===void 0){return void 0}const normalized=value.trim().toLowerCase();if(normalized==="med"){return"medium"}if(ISSUE_SEVERITY_VALUES.includes(normalized)){return normalized}return void 0}function emptyStringToUndefined(value){return value||void 0}function copyExtensionItemMetadataFields(normalized,source){const targetRecord=normalized;const sourceRecord=source;for(const[key,value]of Object.entries(sourceRecord)){if(isUnsafeObjectKey(key)||Object.prototype.hasOwnProperty.call(targetRecord,key)||value===void 0){continue}targetRecord[key]=value}}function coerceNormalizedRuntimeFields(normalized,runtimeContext){if(!runtimeContext?.fieldRegistry){return}const record=normalized;for(const definition of runtimeContext.fieldRegistry.definitions){const currentValue=record[definition.metadata_key];if(currentValue===void 0){continue}record[definition.metadata_key]=coerceRuntimeFieldValue(definition,currentValue,`metadata field "${definition.metadata_key}"`)}}function assertNormalizedUnknownFields(normalized,runtimeContext){if(!runtimeContext||runtimeContext.unknownFieldPolicy==="allow"){return}const knownKeys=buildKnownItemMetadataKeys(runtimeContext);const record=normalized;const unknownKeys=Object.keys(record).filter(key=>!knownKeys.has(key)).sort((left,right)=>left.localeCompare(right));if(unknownKeys.length>0&&runtimeContext.unknownFieldPolicy==="reject"){validationError(`unknown schema fields are not allowed: ${unknownKeys.join(", ")}`)}if(unknownKeys.length>0){runtimeContext.onWarning?.(`item_unknown_schema_fields:${unknownKeys.join(",")}`)}}function normalizeItemMetadata(itemMetadata,options={}){const runtimeContext=resolveRuntimeSchemaValidationContext(options);const normalizedStatus=normalizeStatusInput(itemMetadata.status,runtimeContext?.statusRegistry)??itemMetadata.status;const tags=Array.from(new Set((Array.isArray(itemMetadata.tags)?itemMetadata.tags:[]).filter(tag=>typeof tag==="string").map(tag=>tag.trim().toLowerCase()).filter(Boolean))).sort((a,b)=>a.localeCompare(b));const normalized={id:itemMetadata.id,title:itemMetadata.title,description:itemMetadata.description,type:itemMetadata.type,pm_format_version:normalizeItemFormatVersion(itemMetadata.pm_format_version),source_type:trimStringOrUndefined(itemMetadata.source_type),type_options:normalizeTypeOptions(itemMetadata.type_options),status:normalizedStatus,priority:itemMetadata.priority,tags,created_at:itemMetadata.created_at,updated_at:itemMetadata.updated_at,dependencies:sortDependencies(itemMetadata.dependencies),comments:sortLogValues(itemMetadata.comments),notes:sortLogValues(itemMetadata.notes),learnings:sortLogValues(itemMetadata.learnings),files:normalizeFiles(itemMetadata.files),tests:sortTests(itemMetadata.tests),test_runs:normalizeTestRunSummaries(itemMetadata.test_runs),docs:sortDocs(itemMetadata.docs),deadline:emptyStringToUndefined(itemMetadata.deadline),reminders:sortReminders(itemMetadata.reminders),events:sortEvents(itemMetadata.events),closed_at:emptyStringToUndefined(itemMetadata.closed_at),completed_at:emptyStringToUndefined(itemMetadata.completed_at),assignee:trimStringOrUndefined(itemMetadata.assignee),claim_principal:trimStringOrUndefined(itemMetadata.claim_principal),source_owner:trimStringOrUndefined(itemMetadata.source_owner),author:emptyStringToUndefined(itemMetadata.author),estimated_minutes:itemMetadata.estimated_minutes,acceptance_criteria:itemMetadata.acceptance_criteria??void 0,design:itemMetadata.design??void 0,external_ref:itemMetadata.external_ref??void 0,definition_of_ready:trimStringOrUndefined(itemMetadata.definition_of_ready),order:itemMetadata.order,goal:trimStringOrUndefined(itemMetadata.goal),objective:trimStringOrUndefined(itemMetadata.objective),value:trimStringOrUndefined(itemMetadata.value),impact:trimStringOrUndefined(itemMetadata.impact),outcome:trimStringOrUndefined(itemMetadata.outcome),why_now:trimStringOrUndefined(itemMetadata.why_now),parent:trimStringOrUndefined(itemMetadata.parent),reviewer:trimStringOrUndefined(itemMetadata.reviewer),risk:itemMetadata.risk??void 0,confidence:normalizeConfidenceValue(itemMetadata.confidence),sprint:trimStringOrUndefined(itemMetadata.sprint),release:trimStringOrUndefined(itemMetadata.release),blocked_by:trimStringOrUndefined(itemMetadata.blocked_by),blocked_reason:trimStringOrUndefined(itemMetadata.blocked_reason),unblock_note:trimStringOrUndefined(itemMetadata.unblock_note),reporter:trimStringOrUndefined(itemMetadata.reporter),severity:normalizeSeverityValue(itemMetadata.severity),environment:trimStringOrUndefined(itemMetadata.environment),repro_steps:trimStringOrUndefined(itemMetadata.repro_steps),resolution:trimStringOrUndefined(itemMetadata.resolution),expected_result:trimStringOrUndefined(itemMetadata.expected_result),actual_result:trimStringOrUndefined(itemMetadata.actual_result),affected_version:trimStringOrUndefined(itemMetadata.affected_version),fixed_version:trimStringOrUndefined(itemMetadata.fixed_version),component:trimStringOrUndefined(itemMetadata.component),regression:itemMetadata.regression,customer_impact:trimStringOrUndefined(itemMetadata.customer_impact),close_reason:emptyStringToUndefined(itemMetadata.close_reason),plan_mode:trimStringOrUndefined(itemMetadata.plan_mode),plan_scope:trimStringOrUndefined(itemMetadata.plan_scope),plan_harness:trimStringOrUndefined(itemMetadata.plan_harness),plan_resume_context:trimStringOrUndefined(itemMetadata.plan_resume_context),plan_steps:normalizePlanSteps(itemMetadata.plan_steps),plan_decisions:normalizePlanDecisions(itemMetadata.plan_decisions),plan_discoveries:normalizePlanDiscoveries(itemMetadata.plan_discoveries),plan_validation:normalizePlanValidation(itemMetadata.plan_validation)};copyExtensionItemMetadataFields(normalized,itemMetadata);coerceNormalizedRuntimeFields(normalized,runtimeContext);assertNormalizedUnknownFields(normalized,runtimeContext);deleteUndefinedFields(normalized);return normalized}function orderItemMetadata(itemMetadata){return orderObject(itemMetadata,ITEM_METADATA_KEY_ORDER)}function findJsonObjectEnd(content){let depth=0;let inString=false;let escaped=false;for(let i=0;i<content.length;i+=1){const char=content[i];if(inString){if(escaped){escaped=false;continue}if(char==="\\"){escaped=true;continue}if(char==='"'){inString=false}continue}if(char==='"'){inString=true;continue}if(char==="{"){depth+=1;continue}if(char==="}"){depth-=1;if(depth===0){return i}}}return-1}function splitFrontMatter(content){if(!content.startsWith("{")){return{frontMatter:"",body:content}}const end=findJsonObjectEnd(content);if(end<0){return{frontMatter:"",body:content}}const frontMatter=content.slice(0,end+1);const body=content.slice(end+1).replace(/^\r?\n+/,"");return{frontMatter,body}}function stripLeadingYamlDocument(content){const normalizedContent=content.charCodeAt(0)===65279?content.slice(1):content;const opener=normalizedContent.match(/^[ \t]*---[ \t]*(?:\r?\n|$)/);if(!opener){return{content:normalizedContent,stripped:false}}let cursor=opener[0].length;while(cursor<normalizedContent.length){const nextNewline=normalizedContent.indexOf("\n",cursor);const lineEnd=nextNewline===-1?normalizedContent.length:nextNewline;const line=normalizedContent.slice(cursor,lineEnd).replace(/\r$/,"");const afterLine=nextNewline===-1?lineEnd:lineEnd+1;if(line.trim()==="---"){return{content:normalizedContent.slice(afterLine).replace(/^\s+/,""),stripped:true}}cursor=afterLine}return{content:normalizedContent,stripped:false}}function normalizeParsedItemMetadata(itemMetadata,options){return normalizeItemMetadata(itemMetadata,{...options,onWarning:void 0})}function parseJsonMarkdownItemDocument(content,runtimeContext,options={}){const normalized=stripLeadingYamlDocument(content);if(normalized.stripped){options.onWarning?.("json_markdown_leading_yaml_frontmatter_ignored")}const{frontMatter,body}=splitFrontMatter(normalized.content);if(!frontMatter){const trimmed=content.trimStart();if(trimmed.startsWith("{")){documentSyntaxError("json_markdown","JSON front matter is not valid JSON")}documentSyntaxError("json_markdown","JSON Markdown item document is missing JSON front matter")}let parsed;try{parsed=JSON.parse(frontMatter)}catch{documentSyntaxError("json_markdown","JSON front matter is not valid JSON")}assertValidItemMetadata(parsed,runtimeContext);return{metadata:normalizeParsedItemMetadata(parsed,options),body:normalizeBody(body)}}function parseToonItemDocument(content,runtimeContext,options={}){let parsed;try{parsed=decodeToonItemContent(content).value}catch{documentSyntaxError("toon","TOON item document is not valid TOON")}assertItemMetadataCondition(typeof parsed==="object"&&parsed!==null&&!Array.isArray(parsed),"TOON item document must be an object");const record=parsed;if(!REQUIRED_STRING_FIELDS.some(fieldName=>Object.prototype.hasOwnProperty.call(record,fieldName))&&!Object.prototype.hasOwnProperty.call(record,"front_matter")){documentSyntaxError("toon","TOON input does not have the shape of an item document")}if(Object.prototype.hasOwnProperty.call(record,"front_matter")){assertValidItemMetadata(record.front_matter,runtimeContext);assertItemMetadataCondition(record.body===void 0||typeof record.body==="string","TOON item document body must be a string");return{metadata:normalizeParsedItemMetadata(record.front_matter,options),body:normalizeBody(typeof record.body==="string"?record.body:"")}}const{body,...itemMetadataRecord}=record;assertItemMetadataCondition(body===void 0||typeof body==="string","TOON item document body must be a string");assertValidItemMetadata(itemMetadataRecord,runtimeContext);return{metadata:normalizeParsedItemMetadata(itemMetadataRecord,options),body:normalizeBody(typeof body==="string"?body:"")}}function serializeJsonMarkdownItemDocument(document,options={}){const normalizedMetadata=normalizeItemMetadata(document.metadata,options);const orderedMetadata=orderItemMetadata(normalizedMetadata);const serializedMetadata=JSON.stringify(orderedMetadata,null,2);const normalizedBody=normalizeBody(document.body??"");if(!normalizedBody){return`${serializedMetadata}
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]="24554781-3fa2-53de-98b1-467843de8560")}catch(e2){}})();import{encode as encodeToon}from"@toon-format/toon";import{isDeepStrictEqual}from"node:util";import{CONFIDENCE_TEXT_VALUES,ISSUE_SEVERITY_VALUES,PLAN_STEP_STATUS_VALUES,RECURRENCE_FREQUENCY_VALUES,RECURRENCE_WEEKDAY_VALUES,STATUS_VALUES,weekdayOrderIndex}from"../../types/index.js";import{coerceRuntimeFieldValue}from"../schema/runtime-field-values.js";import{resolveRuntimeFieldRegistry,resolveRuntimeStatusRegistry}from"../schema/runtime-schema.js";import{BASELINE_ITEM_FORMAT_VERSION,normalizeItemFormatVersion}from"./item-format-version.js";import{normalizeStatusInput}from"./status.js";import{decodeToonItemContent}from"./toon-decode.js";import{EXIT_CODE,ITEM_METADATA_KEY_ORDER}from"../shared/constants.js";import{findFirstMergeConflictMarker}from"../shared/conflict-markers.js";import{PmCliError}from"../shared/errors.js";import{orderObject}from"../shared/serialization.js";import{compareTimestampStrings,isTimestampLiteral}from"../shared/time.js";import{coerceFiniteNumber}from"../shared/primitives.js";const LINKED_TEST_PM_CONTEXT_MODE_VALUES=new Set(["schema","tracker","auto","none"]);const LINKED_TEST_WORKSPACE_CONTEXT_MODE_VALUES=new Set(["source","isolated","snapshot"]);const LINKED_TEST_TRUST_REASON_VALUES=new Set(["legacy","local_mutation","local_source_ref","acknowledged","invalid_provenance","foreign_source_ref"]);const ITEM_TEST_RUN_STATUS_VALUES=new Set(["passed","failed","stopped","canceled"]);const PLAN_STEP_STATUS_SET=new Set(PLAN_STEP_STATUS_VALUES);function normalizePathValue(value){return value.replaceAll("\\","/")}function firstNonZeroComparison(comparisons){for(const comparison of comparisons){if(comparison!==0){return comparison}}return 0}function deleteUndefinedFields(record){for(const[key,value]of Object.entries(record)){if(value===void 0){delete record[key]}}}const REQUIRED_STRING_FIELDS=["id","title","description","created_at","updated_at"];const STATIC_ITEM_METADATA_FIELD_SET=new Set(ITEM_METADATA_KEY_ORDER);function resolveRuntimeSchemaValidationContext(options){if(!options?.schema){return void 0}return{statusRegistry:resolveRuntimeStatusRegistry(options.schema),fieldRegistry:resolveRuntimeFieldRegistry(options.schema),unknownFieldPolicy:options.schema.unknown_field_policy??"allow",extensionFieldNames:new Set(options.extensionFieldNames??[]),onWarning:options.onWarning}}function runtimeFieldRequiredForType(definition,typeName){if(!definition.required){return false}if(definition.required_types.length===0){return true}return definition.required_types.map(value=>value.toLowerCase()).includes(typeName.trim().toLowerCase())}function validationError(message){const field=message.match(/^([a-z_][\w.]*)\s/u)?.[1];throw new PmCliError(`Invalid item metadata: ${message}`,EXIT_CODE.GENERIC_FAILURE,{code:"item_document_invalid",reason:message.includes("required")?"missing_required_field":"schema_validation_error",...field?{field}:{},required:"Provide an item document whose metadata satisfies the active runtime schema.",why:message})}function documentSyntaxError(format,message){throw new PmCliError(message,EXIT_CODE.GENERIC_FAILURE,{code:"item_document_invalid",reason:"syntax_error",format,required:`Provide a syntactically valid ${format==="toon"?"TOON":"JSON Markdown"} item document.`,why:"The document could not be decoded far enough to validate item metadata."})}function buildKnownItemMetadataKeys(runtimeContext){const knownKeys=new Set(STATIC_ITEM_METADATA_FIELD_SET);for(const definition of runtimeContext.fieldRegistry?.definitions??[]){knownKeys.add(definition.metadata_key)}for(const fieldName of runtimeContext.extensionFieldNames){knownKeys.add(fieldName)}return knownKeys}function assertItemMetadataCondition(condition,message){if(!condition){validationError(message)}}function requireItemMetadataRecord(value,message){if(typeof value!=="object"||value===null||Array.isArray(value)){validationError(message)}return value}function assertTimestampField(record,fieldName){const rawValue=record[fieldName];assertItemMetadataCondition(typeof rawValue==="string",`${fieldName} must be a string`);const timestamp=rawValue;assertItemMetadataCondition(isTimestampLiteral(timestamp),`${fieldName} must be a valid ISO timestamp`)}function assertPositiveIntegerField(record,fieldName,messagePrefix){const value=record[fieldName];if(value===void 0){return}assertItemMetadataCondition(typeof value==="number"&&Number.isInteger(value)&&value>=1,`${messagePrefix} must be an integer >= 1`)}function assertOptionalTimestampString(record,fieldName,messagePrefix){const value=record[fieldName];if(value===void 0){return}assertItemMetadataCondition(typeof value==="string",`${messagePrefix} must be a string`);assertItemMetadataCondition(isTimestampLiteral(value),`${messagePrefix} must be a valid ISO timestamp`)}function assertRecurrenceWeekdays(value){if(value===void 0){return}assertItemMetadataCondition(Array.isArray(value),"event.recurrence.by_weekday must be an array");for(const weekday of value){assertItemMetadataCondition(typeof weekday==="string","event.recurrence.by_weekday entries must be strings");const normalizedWeekday=weekday.trim().toLowerCase();assertItemMetadataCondition(RECURRENCE_WEEKDAY_VALUES.includes(normalizedWeekday),`event.recurrence.by_weekday entries must be one of: ${RECURRENCE_WEEKDAY_VALUES.join(", ")}`)}}function assertRecurrenceMonthDays(value){if(value===void 0){return}assertItemMetadataCondition(Array.isArray(value),"event.recurrence.by_month_day must be an array");for(const day of value){assertItemMetadataCondition(typeof day==="number"&&Number.isInteger(day)&&day>=1&&day<=31,"event.recurrence.by_month_day entries must be integers 1..31")}}function assertRecurrenceExdates(value){if(value===void 0){return}assertItemMetadataCondition(Array.isArray(value),"event.recurrence.exdates must be an array");for(const exdate of value){assertItemMetadataCondition(typeof exdate==="string","event.recurrence.exdates entries must be strings");assertItemMetadataCondition(isTimestampLiteral(exdate),"event.recurrence.exdates entries must be valid ISO timestamps")}}function assertValidRecurrenceRule(recurrence){const recurrenceRecord=requireItemMetadataRecord(recurrence,"event.recurrence must be an object");assertItemMetadataCondition(typeof recurrenceRecord.freq==="string","event.recurrence.freq must be a string");const frequency=recurrenceRecord.freq.trim().toLowerCase();assertItemMetadataCondition(RECURRENCE_FREQUENCY_VALUES.includes(frequency),`event.recurrence.freq must be one of: ${RECURRENCE_FREQUENCY_VALUES.join(", ")}`);assertPositiveIntegerField(recurrenceRecord,"interval","event.recurrence.interval");assertPositiveIntegerField(recurrenceRecord,"count","event.recurrence.count");assertOptionalTimestampString(recurrenceRecord,"until","event.recurrence.until");assertRecurrenceWeekdays(recurrenceRecord.by_weekday);assertRecurrenceMonthDays(recurrenceRecord.by_month_day);assertRecurrenceExdates(recurrenceRecord.exdates)}function assertRequiredItemMetadataFields(record){for(const fieldName of REQUIRED_STRING_FIELDS){assertItemMetadataCondition(typeof record[fieldName]==="string",`${fieldName} is required and must be a string`)}const itemType=record.type;assertItemMetadataCondition(typeof itemType==="string"&&itemType.trim().length>0,"type must be a non-empty string");const formatVersion=record.pm_format_version;if(formatVersion!==void 0){assertItemMetadataCondition(typeof formatVersion==="number"&&Number.isInteger(formatVersion)&&formatVersion>=BASELINE_ITEM_FORMAT_VERSION,`pm_format_version must be an integer >= ${BASELINE_ITEM_FORMAT_VERSION}`)}return itemType}function assertStatusItemMetadataField(record,runtimeContext){const status=record.status;assertItemMetadataCondition(typeof status==="string"&&status.trim().length>0,"status must be a non-empty string");const statusRegistry=runtimeContext?.statusRegistry;const normalizedStatus=normalizeStatusInput(status,statusRegistry);const statusDomain=statusRegistry?statusRegistry.definitions.map(definition=>definition.id):[...STATUS_VALUES];assertItemMetadataCondition(normalizedStatus!==void 0,`status must be one of: ${statusDomain.join(", ")}`)}function assertPriorityAndTags(record){const priority=record.priority;assertItemMetadataCondition(typeof priority==="number"&&Number.isInteger(priority)&&[0,1,2,3,4].includes(priority),"priority must be an integer 0..4");const tags=record.tags;assertItemMetadataCondition(Array.isArray(tags),"tags must be an array");for(const tag of tags){assertItemMetadataCondition(typeof tag==="string","tags entries must be strings")}}function assertConfidenceItemMetadataField(record){const confidence=record.confidence;if(confidence===void 0){return}if(typeof confidence==="number"){assertItemMetadataCondition(Number.isInteger(confidence)&&confidence>=0&&confidence<=100,"confidence number value must be an integer 0..100");return}if(typeof confidence==="string"){const normalizedConfidence=confidence.trim().toLowerCase();const isKnownTextConfidence=normalizedConfidence==="med"||CONFIDENCE_TEXT_VALUES.includes(normalizedConfidence);assertItemMetadataCondition(isKnownTextConfidence,`confidence string value must be one of: ${[...CONFIDENCE_TEXT_VALUES,"med"].join(", ")}`);return}assertItemMetadataCondition(false,"confidence must be a number or string")}function assertSeverityItemMetadataField(record){const severity=record.severity;if(severity===void 0){return}if(typeof severity!=="string"){validationError("severity must be a string")}const normalizedSeverity=severity.trim().toLowerCase();const isKnownSeverity=normalizedSeverity==="med"||ISSUE_SEVERITY_VALUES.includes(normalizedSeverity);assertItemMetadataCondition(isKnownSeverity,`severity value must be one of: ${[...ISSUE_SEVERITY_VALUES,"med"].join(", ")}`)}function assertRegressionItemMetadataField(record){if(record.regression!==void 0&&typeof record.regression!=="boolean"){validationError("regression must be a boolean")}}function assertReminderEntries(record){const reminders=record.reminders;if(reminders===void 0){return}assertItemMetadataCondition(Array.isArray(reminders),"reminders must be an array");for(const reminder of reminders){const reminderRecord=requireItemMetadataRecord(reminder,"reminders entries must be objects");assertItemMetadataCondition(typeof reminderRecord.at==="string","reminder.at must be a string");assertItemMetadataCondition(isTimestampLiteral(reminderRecord.at),"reminder.at must be a valid ISO timestamp");assertItemMetadataCondition(typeof reminderRecord.text==="string","reminder.text must be a string");assertItemMetadataCondition(reminderRecord.text.trim().length>0,"reminder.text must not be empty")}}function assertEventStringFields(eventRecord){for(const stringField of["title","description","location","timezone"]){if(eventRecord[stringField]!==void 0){assertItemMetadataCondition(typeof eventRecord[stringField]==="string",`event.${stringField} must be a string`);assertItemMetadataCondition(eventRecord[stringField].trim().length>0,`event.${stringField} must not be empty`)}}}function assertEventRecurrence(eventRecord){if(eventRecord.recurrence===void 0){return}assertValidRecurrenceRule(eventRecord.recurrence);if(eventRecord.recurrence.until!==void 0){assertItemMetadataCondition(compareTimestampStrings(eventRecord.recurrence.until,eventRecord.start_at)>=0,"event.recurrence.until must be at or after event.start_at")}}function assertCalendarEventEntry(event){const eventRecord=requireItemMetadataRecord(event,"events entries must be objects");assertItemMetadataCondition(typeof eventRecord.start_at==="string","event.start_at must be a string");assertItemMetadataCondition(isTimestampLiteral(eventRecord.start_at),"event.start_at must be a valid ISO timestamp");if(eventRecord.end_at!==void 0){assertItemMetadataCondition(typeof eventRecord.end_at==="string","event.end_at must be a string");assertItemMetadataCondition(isTimestampLiteral(eventRecord.end_at),"event.end_at must be a valid ISO timestamp");assertItemMetadataCondition(compareTimestampStrings(eventRecord.end_at,eventRecord.start_at)>0,"event.end_at must be after event.start_at")}assertEventStringFields(eventRecord);if(eventRecord.all_day!==void 0){assertItemMetadataCondition(typeof eventRecord.all_day==="boolean","event.all_day must be a boolean")}assertEventRecurrence(eventRecord)}function assertCalendarEvents(record){const events=record.events;if(events===void 0){return}assertItemMetadataCondition(Array.isArray(events),"events must be an array");for(const event of events){assertCalendarEventEntry(event)}}function assertOptionalStringFields(record){for(const fieldName of["source_type","source_owner","design","external_ref"]){const value=record[fieldName];if(value!==void 0){assertItemMetadataCondition(typeof value==="string",`${fieldName} must be a string`)}}}function assertTypeOptionsField(record){const typeOptions=record.type_options;if(typeOptions===void 0){return}const typeOptionsRecord=requireItemMetadataRecord(typeOptions,"type_options must be an object");for(const[optionKey,optionValue]of Object.entries(typeOptionsRecord)){assertItemMetadataCondition(optionKey.trim().length>0,"type_options keys must be non-empty");assertItemMetadataCondition(typeof optionValue==="string","type_options values must be strings");const optionText=optionValue;assertItemMetadataCondition(optionText.trim().length>0,"type_options values must be non-empty strings")}}function coerceRuntimeItemMetadataFields(record,itemType,runtimeContext){if(!runtimeContext?.fieldRegistry){return}for(const definition of runtimeContext.fieldRegistry.definitions){const fieldValue=record[definition.metadata_key];if(fieldValue===void 0){if(runtimeFieldRequiredForType(definition,itemType)){validationError(`missing required schema field: ${definition.metadata_key}`)}continue}try{record[definition.metadata_key]=coerceRuntimeFieldValue(definition,fieldValue,`metadata field "${definition.metadata_key}"`)}catch(error){validationError(String(error?.message).replace(/^Invalid\s+/u,""))}}}function assertRuntimeUnknownItemMetadataFields(record,runtimeContext){if(!runtimeContext||runtimeContext.unknownFieldPolicy==="allow"){return}const knownKeys=buildKnownItemMetadataKeys(runtimeContext);const unknownKeys=Object.keys(record).filter(key=>!knownKeys.has(key)).sort((left,right)=>left.localeCompare(right));if(unknownKeys.length===0){return}if(runtimeContext.unknownFieldPolicy==="reject"){validationError(`unknown schema fields are not allowed: ${unknownKeys.join(", ")}`)}else{runtimeContext.onWarning?.(`item_unknown_schema_fields:${unknownKeys.join(",")}`)}}function assertValidItemMetadata(itemMetadata,runtimeContext){const record=requireItemMetadataRecord(itemMetadata,"item metadata must be an object");const itemType=assertRequiredItemMetadataFields(record);assertStatusItemMetadataField(record,runtimeContext);assertPriorityAndTags(record);assertConfidenceItemMetadataField(record);assertSeverityItemMetadataField(record);assertRegressionItemMetadataField(record);assertTimestampField(record,"created_at");assertTimestampField(record,"updated_at");if(record.deadline!==void 0){assertTimestampField(record,"deadline")}assertReminderEntries(record);assertCalendarEvents(record);assertOptionalTimestampString(record,"closed_at","closed_at");assertOptionalTimestampString(record,"completed_at","completed_at");assertOptionalStringFields(record);assertTypeOptionsField(record);coerceRuntimeItemMetadataFields(record,itemType,runtimeContext);assertRuntimeUnknownItemMetadataFields(record,runtimeContext)}function sortDependencies(values){if(!values||values.length===0)return void 0;return[...values].map(value=>({id:value.id.trim(),kind:value.kind,created_at:value.created_at,author:value.author?.trim()||void 0,source_kind:value.source_kind?.trim()||void 0,author_source:value.author_source})).sort((a,b)=>{const byCreated=compareTimestampStrings(a.created_at,b.created_at);if(byCreated!==0)return byCreated;const byId=a.id.localeCompare(b.id);if(byId!==0)return byId;const byKind=a.kind.localeCompare(b.kind);if(byKind!==0)return byKind;return(a.source_kind??"").localeCompare(b.source_kind??"")})}function sortLogValues(values){if(!values||values.length===0)return void 0;return[...values].sort((a,b)=>{const byCreated=compareTimestampStrings(a.created_at,b.created_at);if(byCreated!==0)return byCreated;const byText=a.text.localeCompare(b.text);if(byText!==0)return byText;return a.author.localeCompare(b.author)})}function sortReminders(values){if(!values||values.length===0)return void 0;const normalized=[...values].map(value=>({at:value.at,text:value.text.trim()})).filter(value=>value.text.length>0).sort((a,b)=>{const byAt=compareTimestampStrings(a.at,b.at);if(byAt!==0)return byAt;return a.text.localeCompare(b.text)});return normalized.length===0?void 0:normalized}function normalizeRecurrenceRule(value){if(!value){return void 0}const normalizedFrequency=value.freq.trim().toLowerCase();if(!RECURRENCE_FREQUENCY_VALUES.includes(normalizedFrequency)){return void 0}const byWeekday=Array.from(new Set((value.by_weekday??[]).map(weekday=>weekday.trim().toLowerCase()).filter(weekday=>RECURRENCE_WEEKDAY_VALUES.includes(weekday)))).sort((a,b)=>weekdayOrderIndex(a)-weekdayOrderIndex(b));const byMonthDay=Array.from(new Set((value.by_month_day??[]).filter(day=>Number.isInteger(day)&&day>=1&&day<=31).map(day=>day))).sort((a,b)=>a-b);const exdates=Array.from(new Set((value.exdates??[]).map(timestamp=>timestamp.trim()).filter(timestamp=>isTimestampLiteral(timestamp)))).sort((a,b)=>compareTimestampStrings(a,b));const normalized={freq:normalizedFrequency,interval:value.interval!==void 0&&value.interval>1?value.interval:void 0,count:value.count,until:value.until?.trim()||void 0,by_weekday:byWeekday.length>0?byWeekday:void 0,by_month_day:byMonthDay.length>0?byMonthDay:void 0,exdates:exdates.length>0?exdates:void 0};for(const[key,fieldValue]of Object.entries(normalized)){if(fieldValue===void 0){delete normalized[key]}}return normalized}function sortEvents(values){if(!Array.isArray(values)||values.length===0){return void 0}const normalized=[...values].map(normalizeCalendarEvent).sort(compareCalendarEvents);return normalized}function normalizeCalendarEvent(value){const event={start_at:value.start_at,end_at:value.end_at||void 0,title:value.title?.trim()||void 0,description:value.description?.trim()||void 0,location:value.location?.trim()||void 0,all_day:value.all_day,timezone:value.timezone?.trim()||void 0,recurrence:normalizeRecurrenceRule(value.recurrence)};deleteUndefinedFields(event);return event}function compareCalendarEvents(a,b){return firstNonZeroComparison([compareTimestampStrings(a.start_at,b.start_at),(a.end_at??"").localeCompare(b.end_at??""),(a.title??"").localeCompare(b.title??""),Number(Boolean(a.all_day))-Number(Boolean(b.all_day)),(a.timezone??"").localeCompare(b.timezone??""),(a.location??"").localeCompare(b.location??""),(a.description??"").localeCompare(b.description??""),JSON.stringify(a.recurrence??{}).localeCompare(JSON.stringify(b.recurrence??{}))])}function normalizeFiles(values){if(!values||values.length===0)return void 0;return values.map(value=>({path:normalizePathValue(value.path),scope:value.scope,note:value.note?.trim()||void 0}))}function normalizeTestRunSummaries(values){if(!values||values.length===0)return void 0;const normalized=values.map(normalizeTestRunSummary).filter(value=>value.run_id.length>0&&value.started_at.length>0&&value.finished_at.length>0&&value.recorded_at.length>0).sort((a,b)=>firstNonZeroComparison([compareTimestampStrings(a.recorded_at,b.recorded_at),a.run_id.localeCompare(b.run_id),a.kind.localeCompare(b.kind)]));return normalized.length>0?normalized:void 0}function normalizeNonNegativeInteger(value){return typeof value==="number"&&Number.isFinite(value)&&value>=0?Math.floor(value):void 0}function normalizePositiveInteger(value){return typeof value==="number"&&Number.isFinite(value)&&value>=1?Math.floor(value):void 0}function stringOrEmpty(value){return typeof value==="string"?value:""}function normalizeTestRunMeasurements(value){if(!Array.isArray(value))return void 0;const normalized=value.filter(measurement=>measurement!==null&&typeof measurement==="object"&&typeof measurement.name==="string"&&measurement.name.trim().length>0&&typeof measurement.value==="number"&&Number.isFinite(measurement.value)&&typeof measurement.recorded_at==="string"&&measurement.recorded_at.trim().length>0).map(measurement=>({name:measurement.name.trim(),value:measurement.value,unit:typeof measurement.unit==="string"?measurement.unit.trim()||void 0:void 0,threshold:typeof measurement.threshold==="number"&&Number.isFinite(measurement.threshold)?measurement.threshold:void 0,recorded_at:measurement.recorded_at.trim()}));const deduplicated=[...new Map(normalized.map(measurement=>[measurement.name,measurement])).values()].sort((left,right)=>left.name.localeCompare(right.name)).slice(0,32);return deduplicated.length>0?deduplicated:void 0}function normalizeTestRunEnum(value,allowedValues){return typeof value==="string"&&allowedValues.has(value)?value:void 0}function normalizeTestRunExecutions(values){if(!Array.isArray(values))return void 0;const executions=values.filter(execution=>execution&&typeof execution.command==="string"&&execution.command.trim().length>0).slice(0,32).map(execution=>({command:execution.command.trim(),requested_pm_context_mode:normalizeTestRunEnum(execution.requested_pm_context_mode,LINKED_TEST_PM_CONTEXT_MODE_VALUES),pm_context_mode:normalizeTestRunEnum(execution.pm_context_mode,LINKED_TEST_PM_CONTEXT_MODE_VALUES),workspace_context_mode:normalizeTestRunEnum(execution.workspace_context_mode,LINKED_TEST_WORKSPACE_CONTEXT_MODE_VALUES),trust_reason:normalizeTestRunEnum(execution.trust_reason,LINKED_TEST_TRUST_REASON_VALUES)}));return executions.length>0?executions:void 0}function normalizeTestRunSummary(value){const runId=typeof value.run_id==="string"?value.run_id.trim():"";const kind=value.kind==="test"||value.kind==="test-all"?value.kind:"test";const status=ITEM_TEST_RUN_STATUS_VALUES.has(value.status)?value.status:"failed";const summary={run_id:runId,kind,status,started_at:stringOrEmpty(value.started_at),finished_at:stringOrEmpty(value.finished_at),recorded_at:stringOrEmpty(value.recorded_at),attempt:normalizePositiveInteger(value.attempt),resumed_from:value.resumed_from?.trim()||void 0,passed:normalizeNonNegativeInteger(value.passed)??0,failed:normalizeNonNegativeInteger(value.failed)??0,skipped:normalizeNonNegativeInteger(value.skipped)??0,items:normalizeNonNegativeInteger(value.items),linked_tests:normalizeNonNegativeInteger(value.linked_tests),fail_on_skipped_triggered:value.fail_on_skipped_triggered===true?true:void 0,measurements:normalizeTestRunMeasurements(value.measurements),executions:normalizeTestRunExecutions(value.executions)};deleteUndefinedFields(summary);return summary}function sortTests(values){if(!Array.isArray(values)||values.length===0)return void 0;return values.map(normalizeLinkedTest)}function normalizeTrimmedStringList(value){if(!Array.isArray(value)){return void 0}const normalized=[...new Set(value.filter(entry=>typeof entry==="string").map(entry=>entry.trim()).filter(entry=>entry.length>0))].sort((a,b)=>a.localeCompare(b));return normalized.length>0?normalized:void 0}function isPlainObjectRecord(value){if(!value||typeof value!=="object"||Array.isArray(value)){return false}const prototype=Object.getPrototypeOf(value);return prototype===Object.prototype||prototype===null}function isUnsafeObjectKey(key){return key==="__proto__"||key==="constructor"||key==="prototype"}function normalizeStringRecord(value){if(!isPlainObjectRecord(value)){return void 0}const entries=Object.entries(value).map(([key,recordValue])=>[key.trim(),String(recordValue).trim()]).filter(([key,recordValue])=>key.length>0&&!isUnsafeObjectKey(key)&&recordValue.length>0).sort(([left],[right])=>left.localeCompare(right));return entries.length>0?Object.fromEntries(entries):void 0}function normalizeNumericRecord(value){if(!isPlainObjectRecord(value)){return void 0}const entries=Object.entries(value).map(([key,recordValue])=>[key.trim(),Number(recordValue)]).filter(([key,recordValue])=>key.length>0&&!isUnsafeObjectKey(key)&&Number.isFinite(recordValue)).sort(([left],[right])=>left.localeCompare(right));return entries.length>0?Object.fromEntries(entries):void 0}function normalizeLinkedTestContextMode(value){const normalized=value?.trim().toLowerCase();if(!normalized||!LINKED_TEST_PM_CONTEXT_MODE_VALUES.has(normalized)){return void 0}return normalized}function normalizeLinkedTestWorkspaceContextMode(value){const normalized=value?.trim().toLowerCase();if(!normalized||!LINKED_TEST_WORKSPACE_CONTEXT_MODE_VALUES.has(normalized)){return void 0}return normalized}function normalizeLinkedTestProvenance(value,invalid){if(invalid===true){return{provenance_invalid:true}}if(value===void 0){return{}}if(!isPlainObjectRecord(value)){return{provenance_invalid:true}}const author=trimStringOrUndefined(value.author);const createdAt=trimStringOrUndefined(value.created_at);const sourceKind=value.source_kind;if(!author||!createdAt||!isTimestampLiteral(createdAt)||sourceKind!=="local_mutation"&&sourceKind!=="merge_union"){return{provenance_invalid:true}}return{provenance:{author,created_at:createdAt,source_kind:sourceKind,source_ref:trimStringOrUndefined(value.source_ref)}}}function normalizeLinkedTest(value){const test={command:value.command?.trim()||void 0,path:value.path?normalizePathValue(value.path):void 0,scope:value.scope,timeout_seconds:typeof value.timeout_seconds==="number"&&Number.isFinite(value.timeout_seconds)&&value.timeout_seconds>0?value.timeout_seconds:void 0,pm_context_mode:normalizeLinkedTestContextMode(value.pm_context_mode),workspace_context_mode:normalizeLinkedTestWorkspaceContextMode(value.workspace_context_mode),...normalizeLinkedTestProvenance(value.provenance,value.provenance_invalid),env_set:normalizeStringRecord(value.env_set),env_clear:normalizeTrimmedStringList(value.env_clear),shared_host_safe:value.shared_host_safe===true?true:void 0,assert_stdout_contains:normalizeTrimmedStringList(value.assert_stdout_contains),assert_stdout_regex:normalizeTrimmedStringList(value.assert_stdout_regex),assert_stderr_contains:normalizeTrimmedStringList(value.assert_stderr_contains),assert_stderr_regex:normalizeTrimmedStringList(value.assert_stderr_regex),assert_stdout_min_lines:normalizeNonNegativeInteger(value.assert_stdout_min_lines),assert_json_field_equals:normalizeStringRecord(value.assert_json_field_equals),assert_json_field_gte:normalizeNumericRecord(value.assert_json_field_gte),note:value.note?.trim()||void 0};deleteUndefinedFields(test);return test}function sortDocs(values){if(!values||values.length===0)return void 0;return[...values].map(value=>({path:normalizePathValue(value.path),scope:value.scope,note:value.note?.trim()||void 0})).sort((a,b)=>{const byScope=a.scope.localeCompare(b.scope);if(byScope!==0)return byScope;const byPath=a.path.localeCompare(b.path);if(byPath!==0)return byPath;return(a.note??"").localeCompare(b.note??"")})}function trimStringOrUndefined(value){if(typeof value!=="string")return void 0;const trimmed=value.trim();return trimmed.length>0?trimmed:void 0}function normalizePlanStepLinks(value){if(!Array.isArray(value))return void 0;const out=[];for(const entry of value){if(entry===null||typeof entry!=="object")continue;const record=entry;const id=trimStringOrUndefined(record.id);const kind=trimStringOrUndefined(record.kind);if(!id||!kind)continue;const link={id,kind};const note=trimStringOrUndefined(record.note);if(note)link.note=note;if(record.required_before_step===true)link.required_before_step=true;out.push(link)}return out.length>0?out:void 0}function normalizePlanStepFiles(value){if(!Array.isArray(value))return void 0;const out=[];for(const entry of value){if(entry===null||typeof entry!=="object")continue;const record=entry;const path=trimStringOrUndefined(record.path);if(!path)continue;const file={path:normalizePathValue(path)};if(record.scope==="project"||record.scope==="global")file.scope=record.scope;const note=trimStringOrUndefined(record.note);if(note)file.note=note;out.push(file)}return out.length>0?out:void 0}function normalizePlanStepTests(value){if(!Array.isArray(value))return void 0;const out=[];for(const entry of value){if(entry===null||typeof entry!=="object")continue;const record=entry;const command=trimStringOrUndefined(record.command);const path=trimStringOrUndefined(record.path);if(!command&&!path)continue;const test={};if(command)test.command=command;if(path)test.path=normalizePathValue(path);const note=trimStringOrUndefined(record.note);if(note)test.note=note;out.push(test)}return out.length>0?out:void 0}function normalizePlanStepDocs(value){if(!Array.isArray(value))return void 0;const out=[];for(const entry of value){if(entry===null||typeof entry!=="object")continue;const record=entry;const path=trimStringOrUndefined(record.path);if(!path)continue;const doc={path:normalizePathValue(path)};if(record.scope==="project"||record.scope==="global")doc.scope=record.scope;const note=trimStringOrUndefined(record.note);if(note)doc.note=note;out.push(doc)}return out.length>0?out:void 0}function normalizePlanStepEntry(entry){if(entry===null||typeof entry!=="object"){return void 0}const record=entry;const id=trimStringOrUndefined(record.id);const title=trimStringOrUndefined(record.title);const statusRaw=trimStringOrUndefined(record.status);const status=statusRaw&&PLAN_STEP_STATUS_SET.has(statusRaw)?statusRaw:void 0;const order=coerceFiniteNumber(record.order)??Number.NaN;const created_at=typeof record.created_at==="string"?record.created_at:"";const updated_at=typeof record.updated_at==="string"?record.updated_at:"";if(!id||!title||!status||!Number.isFinite(order)||!created_at||!updated_at){return void 0}const step={id,order,title,status,created_at,updated_at};applyPlanStepOptionalFields(step,record);return step}function applyPlanStepOptionalFields(step,record){const stringFields=[["body","body"],["owner","owner"],["evidence","evidence"],["blocked_reason","blocked_reason"],["superseded_by","superseded_by"]];for(const[target,source]of stringFields){const value=trimStringOrUndefined(record[source]);if(value){step[target]=value}}const completedAt=typeof record.completed_at==="string"?record.completed_at:void 0;if(completedAt&&completedAt.length>0){step.completed_at=completedAt}const collectionFields=[["linked_items","linked_items",normalizePlanStepLinks],["files","files",normalizePlanStepFiles],["tests","tests",normalizePlanStepTests],["docs","docs",normalizePlanStepDocs]];for(const[target,source,normalize]of collectionFields){const value=normalize(record[source]);if(value){step[target]=value}}}function normalizePlanSteps(value){if(!Array.isArray(value))return void 0;const out=value.flatMap(entry=>{const step=normalizePlanStepEntry(entry);return step?[step]:[]});out.sort((left,right)=>left.order-right.order);return out.length>0?out:void 0}function normalizePlanDecisions(value){if(!Array.isArray(value))return void 0;const out=[];for(const entry of value){if(entry===null||typeof entry!=="object")continue;const record=entry;const ts=typeof record.ts==="string"?record.ts:"";const author=typeof record.author==="string"?record.author:"";const decision=trimStringOrUndefined(record.decision);if(!ts||!author||!decision)continue;const item={ts,author,decision};const rationale=trimStringOrUndefined(record.rationale);if(rationale)item.rationale=rationale;const evidence=trimStringOrUndefined(record.evidence);if(evidence)item.evidence=evidence;const stepId=trimStringOrUndefined(record.step_id);if(stepId)item.step_id=stepId;out.push(item)}return out.length>0?out:void 0}function normalizePlanDiscoveries(value){if(!Array.isArray(value))return void 0;const out=[];for(const entry of value){if(entry===null||typeof entry!=="object")continue;const record=entry;const ts=typeof record.ts==="string"?record.ts:"";const author=typeof record.author==="string"?record.author:"";const text=trimStringOrUndefined(record.text);if(!ts||!author||!text)continue;const item={ts,author,text};const stepId=trimStringOrUndefined(record.step_id);if(stepId)item.step_id=stepId;out.push(item)}return out.length>0?out:void 0}function normalizePlanValidation(value){if(!Array.isArray(value))return void 0;const out=[];for(const entry of value){if(entry===null||typeof entry!=="object")continue;const record=entry;const text=trimStringOrUndefined(record.text);if(!text)continue;const item={text};const command=trimStringOrUndefined(record.command);if(command)item.command=command;const expected=trimStringOrUndefined(record.expected);if(expected)item.expected=expected;out.push(item)}return out.length>0?out:void 0}function normalizeTypeOptions(values){if(!values){return void 0}const normalizedEntries=Object.entries(values).map(([key,value])=>[key.trim(),value.trim()]).filter(([key,value])=>key.length>0&&value.length>0).sort((left,right)=>left[0].localeCompare(right[0]));if(normalizedEntries.length===0){return void 0}return Object.fromEntries(normalizedEntries)}function normalizeBody(body){let start=0;while(start<body.length&&body[start]==="\n"){start+=1}return body.slice(start).trimEnd()}function normalizeConfidenceValue(value){if(value===void 0){return void 0}if(typeof value==="number"){return value}const normalized=value.trim().toLowerCase();if(normalized==="med"){return"medium"}if(CONFIDENCE_TEXT_VALUES.includes(normalized)){return normalized}return void 0}function normalizeSeverityValue(value){if(value===void 0){return void 0}const normalized=value.trim().toLowerCase();if(normalized==="med"){return"medium"}if(ISSUE_SEVERITY_VALUES.includes(normalized)){return normalized}return void 0}function emptyStringToUndefined(value){return value||void 0}function copyExtensionItemMetadataFields(normalized,source){const targetRecord=normalized;const sourceRecord=source;for(const[key,value]of Object.entries(sourceRecord)){if(isUnsafeObjectKey(key)||Object.prototype.hasOwnProperty.call(targetRecord,key)||value===void 0){continue}targetRecord[key]=value}}function coerceNormalizedRuntimeFields(normalized,runtimeContext){if(!runtimeContext?.fieldRegistry){return}const record=normalized;for(const definition of runtimeContext.fieldRegistry.definitions){const currentValue=record[definition.metadata_key];if(currentValue===void 0){continue}record[definition.metadata_key]=coerceRuntimeFieldValue(definition,currentValue,`metadata field "${definition.metadata_key}"`)}}function assertNormalizedUnknownFields(normalized,runtimeContext){if(!runtimeContext||runtimeContext.unknownFieldPolicy==="allow"){return}const knownKeys=buildKnownItemMetadataKeys(runtimeContext);const record=normalized;const unknownKeys=Object.keys(record).filter(key=>!knownKeys.has(key)).sort((left,right)=>left.localeCompare(right));if(unknownKeys.length>0&&runtimeContext.unknownFieldPolicy==="reject"){validationError(`unknown schema fields are not allowed: ${unknownKeys.join(", ")}`)}if(unknownKeys.length>0){runtimeContext.onWarning?.(`item_unknown_schema_fields:${unknownKeys.join(",")}`)}}function normalizeItemMetadata(itemMetadata,options={}){const runtimeContext=resolveRuntimeSchemaValidationContext(options);const normalizedStatus=normalizeStatusInput(itemMetadata.status,runtimeContext?.statusRegistry)??itemMetadata.status;const tags=Array.from(new Set((Array.isArray(itemMetadata.tags)?itemMetadata.tags:[]).filter(tag=>typeof tag==="string").map(tag=>tag.trim().toLowerCase()).filter(Boolean))).sort((a,b)=>a.localeCompare(b));const normalized={id:itemMetadata.id,title:itemMetadata.title,description:itemMetadata.description,type:itemMetadata.type,pm_format_version:normalizeItemFormatVersion(itemMetadata.pm_format_version),source_type:trimStringOrUndefined(itemMetadata.source_type),type_options:normalizeTypeOptions(itemMetadata.type_options),status:normalizedStatus,priority:itemMetadata.priority,tags,created_at:itemMetadata.created_at,updated_at:itemMetadata.updated_at,dependencies:sortDependencies(itemMetadata.dependencies),comments:sortLogValues(itemMetadata.comments),notes:sortLogValues(itemMetadata.notes),learnings:sortLogValues(itemMetadata.learnings),files:normalizeFiles(itemMetadata.files),tests:sortTests(itemMetadata.tests),test_runs:normalizeTestRunSummaries(itemMetadata.test_runs),docs:sortDocs(itemMetadata.docs),deadline:emptyStringToUndefined(itemMetadata.deadline),reminders:sortReminders(itemMetadata.reminders),events:sortEvents(itemMetadata.events),closed_at:emptyStringToUndefined(itemMetadata.closed_at),completed_at:emptyStringToUndefined(itemMetadata.completed_at),assignee:trimStringOrUndefined(itemMetadata.assignee),claim_principal:trimStringOrUndefined(itemMetadata.claim_principal),source_owner:trimStringOrUndefined(itemMetadata.source_owner),author:emptyStringToUndefined(itemMetadata.author),estimated_minutes:itemMetadata.estimated_minutes,acceptance_criteria:itemMetadata.acceptance_criteria??void 0,design:itemMetadata.design??void 0,external_ref:itemMetadata.external_ref??void 0,definition_of_ready:trimStringOrUndefined(itemMetadata.definition_of_ready),order:itemMetadata.order,goal:trimStringOrUndefined(itemMetadata.goal),objective:trimStringOrUndefined(itemMetadata.objective),value:trimStringOrUndefined(itemMetadata.value),impact:trimStringOrUndefined(itemMetadata.impact),outcome:trimStringOrUndefined(itemMetadata.outcome),why_now:trimStringOrUndefined(itemMetadata.why_now),parent:trimStringOrUndefined(itemMetadata.parent),reviewer:trimStringOrUndefined(itemMetadata.reviewer),risk:itemMetadata.risk??void 0,confidence:normalizeConfidenceValue(itemMetadata.confidence),sprint:trimStringOrUndefined(itemMetadata.sprint),release:trimStringOrUndefined(itemMetadata.release),blocked_by:trimStringOrUndefined(itemMetadata.blocked_by),blocked_reason:trimStringOrUndefined(itemMetadata.blocked_reason),unblock_note:trimStringOrUndefined(itemMetadata.unblock_note),reporter:trimStringOrUndefined(itemMetadata.reporter),severity:normalizeSeverityValue(itemMetadata.severity),environment:trimStringOrUndefined(itemMetadata.environment),repro_steps:trimStringOrUndefined(itemMetadata.repro_steps),resolution:trimStringOrUndefined(itemMetadata.resolution),expected_result:trimStringOrUndefined(itemMetadata.expected_result),actual_result:trimStringOrUndefined(itemMetadata.actual_result),affected_version:trimStringOrUndefined(itemMetadata.affected_version),fixed_version:trimStringOrUndefined(itemMetadata.fixed_version),component:trimStringOrUndefined(itemMetadata.component),regression:itemMetadata.regression,customer_impact:trimStringOrUndefined(itemMetadata.customer_impact),close_reason:emptyStringToUndefined(itemMetadata.close_reason),plan_mode:trimStringOrUndefined(itemMetadata.plan_mode),plan_scope:trimStringOrUndefined(itemMetadata.plan_scope),plan_harness:trimStringOrUndefined(itemMetadata.plan_harness),plan_resume_context:trimStringOrUndefined(itemMetadata.plan_resume_context),plan_steps:normalizePlanSteps(itemMetadata.plan_steps),plan_decisions:normalizePlanDecisions(itemMetadata.plan_decisions),plan_discoveries:normalizePlanDiscoveries(itemMetadata.plan_discoveries),plan_validation:normalizePlanValidation(itemMetadata.plan_validation)};copyExtensionItemMetadataFields(normalized,itemMetadata);coerceNormalizedRuntimeFields(normalized,runtimeContext);assertNormalizedUnknownFields(normalized,runtimeContext);deleteUndefinedFields(normalized);return normalized}function orderItemMetadata(itemMetadata){return orderObject(itemMetadata,ITEM_METADATA_KEY_ORDER)}function findJsonObjectEnd(content){let depth=0;let inString=false;let escaped=false;for(let i=0;i<content.length;i+=1){const char=content[i];if(inString){if(escaped){escaped=false;continue}if(char==="\\"){escaped=true;continue}if(char==='"'){inString=false}continue}if(char==='"'){inString=true;continue}if(char==="{"){depth+=1;continue}if(char==="}"){depth-=1;if(depth===0){return i}}}return-1}function splitFrontMatter(content){if(!content.startsWith("{")){return{frontMatter:"",body:content}}const end=findJsonObjectEnd(content);if(end<0){return{frontMatter:"",body:content}}const frontMatter=content.slice(0,end+1);const body=content.slice(end+1).replace(/^\r?\n+/,"");return{frontMatter,body}}function stripLeadingYamlDocument(content){const normalizedContent=content.charCodeAt(0)===65279?content.slice(1):content;const opener=normalizedContent.match(/^[ \t]*---[ \t]*(?:\r?\n|$)/);if(!opener){return{content:normalizedContent,stripped:false}}let cursor=opener[0].length;while(cursor<normalizedContent.length){const nextNewline=normalizedContent.indexOf("\n",cursor);const lineEnd=nextNewline===-1?normalizedContent.length:nextNewline;const line=normalizedContent.slice(cursor,lineEnd).replace(/\r$/,"");const afterLine=nextNewline===-1?lineEnd:lineEnd+1;if(line.trim()==="---"){return{content:normalizedContent.slice(afterLine).replace(/^\s+/,""),stripped:true}}cursor=afterLine}return{content:normalizedContent,stripped:false}}function normalizeParsedItemMetadata(itemMetadata,options){return normalizeItemMetadata(itemMetadata,{...options,onWarning:void 0})}function parseJsonMarkdownItemDocument(content,runtimeContext,options={}){const normalized=stripLeadingYamlDocument(content);if(normalized.stripped){options.onWarning?.("json_markdown_leading_yaml_frontmatter_ignored")}const{frontMatter,body}=splitFrontMatter(normalized.content);if(!frontMatter){const trimmed=content.trimStart();if(trimmed.startsWith("{")){documentSyntaxError("json_markdown","JSON front matter is not valid JSON")}documentSyntaxError("json_markdown","JSON Markdown item document is missing JSON front matter")}let parsed;try{parsed=JSON.parse(frontMatter)}catch{documentSyntaxError("json_markdown","JSON front matter is not valid JSON")}assertValidItemMetadata(parsed,runtimeContext);return{metadata:normalizeParsedItemMetadata(parsed,options),body:normalizeBody(body)}}function parseToonItemDocument(content,runtimeContext,options={}){let parsed;try{parsed=decodeToonItemContent(content).value}catch{documentSyntaxError("toon","TOON item document is not valid TOON")}assertItemMetadataCondition(typeof parsed==="object"&&parsed!==null&&!Array.isArray(parsed),"TOON item document must be an object");const record=parsed;if(!REQUIRED_STRING_FIELDS.some(fieldName=>Object.prototype.hasOwnProperty.call(record,fieldName))&&!Object.prototype.hasOwnProperty.call(record,"front_matter")){documentSyntaxError("toon","TOON input does not have the shape of an item document")}if(Object.prototype.hasOwnProperty.call(record,"front_matter")){assertValidItemMetadata(record.front_matter,runtimeContext);assertItemMetadataCondition(record.body===void 0||typeof record.body==="string","TOON item document body must be a string");return{metadata:normalizeParsedItemMetadata(record.front_matter,options),body:normalizeBody(typeof record.body==="string"?record.body:"")}}const{body,...itemMetadataRecord}=record;assertItemMetadataCondition(body===void 0||typeof body==="string","TOON item document body must be a string");assertValidItemMetadata(itemMetadataRecord,runtimeContext);return{metadata:normalizeParsedItemMetadata(itemMetadataRecord,options),body:normalizeBody(typeof body==="string"?body:"")}}function serializeJsonMarkdownItemDocument(document,options={}){const normalizedMetadata=normalizeItemMetadata(document.metadata,options);const orderedMetadata=orderItemMetadata(normalizedMetadata);const serializedMetadata=JSON.stringify(orderedMetadata,null,2);const normalizedBody=normalizeBody(document.body??"");if(!normalizedBody){return`${serializedMetadata}
2
2
  `}return`${serializedMetadata}
3
3
 
4
4
  ${normalizedBody}
@@ -1,2 +1,2 @@
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]="6e88d6b7-aa5f-5515-8ea4-481916b12ef1")}catch(e2){}})();const CHANGED_FIELDS_KEY="changed_fields";const CHANGED_FIELD_COUNT_KEY="changed_field_count";const ROWS_KEY="rows";const UPDATE_MANY_MUTATION_MODES=new Set(["apply","rollback"]);const DELETE_OUTCOMES=new Set(["deleted","would_delete"]);const COMPACT_RECURRENCE_TEXT_LIMIT=256;const COMPOUND_MUTATION_STEPS={start_task:["claim","update"],pause_task:["update","release"],close_task:["close","release"]};function projectCompoundMutation(result,options){if(!isPlainObject(result)||typeof result.action!=="string"||typeof result.id!=="string"||result.id.length===0)return null;const steps=Object.hasOwn(COMPOUND_MUTATION_STEPS,result.action)?COMPOUND_MUTATION_STEPS[result.action]:void 0;if(!steps||!steps.every(step=>{const value=result[step];return isPlainObject(value)&&isPlainObject(value.item)&&value.item.id===result.id&&Array.isArray(value.changed_fields)&&value.changed_fields.every(field=>typeof field==="string")}))return null;const final=result[steps.at(-1)];const identity=projectIdOnlyResult(final);if(options.idOnly)return identity;if(!options.compactEnvelope&&options.changedFields!=="compact")return null;return{...result,...options.compactEnvelope?{...identity,changed_field_count:new Set(steps.flatMap(step=>result[step].changed_fields)).size}:{},...Object.fromEntries(steps.map(step=>[step,projectMutationResult(result[step],options)]))}}function truncateCompactRecurrenceText(value){if(typeof value!=="string"||value.length<=COMPACT_RECURRENCE_TEXT_LIMIT){return value}return`${value.slice(0,COMPACT_RECURRENCE_TEXT_LIMIT-1)}\u2026`}function projectCompactRecurrence(value){if(!isPlainObject(value))return null;const recurrence={...value};recurrence.reason=truncateCompactRecurrenceText(recurrence.reason);if(isPlainObject(recurrence.previous_terminal)){recurrence.previous_terminal=Object.fromEntries(Object.entries(recurrence.previous_terminal).map(([key,entry])=>[key,truncateCompactRecurrenceText(entry)]))}return recurrence}function isPlainObject(value){if(typeof value!=="object"||value===null||Array.isArray(value)){return false}const proto=Object.getPrototypeOf(value);return proto===null||proto===Object.prototype}function compactOwnChangedFields(envelope){const changedFields=envelope[CHANGED_FIELDS_KEY];if(!Array.isArray(changedFields)){return null}const projected=Object.getPrototypeOf(envelope)===null?Object.create(null):{};for(const[key,value]of Object.entries(envelope)){if(key!==CHANGED_FIELDS_KEY){projected[key]=value}}projected[CHANGED_FIELD_COUNT_KEY]=changedFields.length;return projected}function isMutationEnvelope(value){return"item"in value&&Array.isArray(value[CHANGED_FIELDS_KEY])}function isUpdateManyMutationEnvelope(value){return typeof value.mode==="string"&&UPDATE_MANY_MUTATION_MODES.has(value.mode)&&Array.isArray(value[ROWS_KEY])}function replaceRows(envelope,rows){const projected=Object.getPrototypeOf(envelope)===null?Object.create(null):{};Object.assign(projected,envelope);projected[ROWS_KEY]=rows;return projected}function projectIdOnlyResult(result){if(!isPlainObject(result)){return null}const subject=isPlainObject(result.item)?result.item:isPlainObject(result.plan)?result.plan:null;if(subject===null){return null}const id=typeof subject.id==="string"?subject.id:void 0;const status=typeof result.outcome==="string"&&DELETE_OUTCOMES.has(result.outcome)?result.outcome:typeof subject.status==="string"?subject.status:void 0;if(!id){return null}return status?{id,status,...typeof result.deleted==="boolean"?{deleted:result.deleted}:{}}:{id}}function projectCompactMutationEnvelope(result){if(!isPlainObject(result)||!isPlainObject(result.item))return null;if(typeof result.item.id!=="string")return null;const changedFields=result[CHANGED_FIELDS_KEY];if(!Array.isArray(changedFields))return null;const compact={id:result.item.id,...typeof result.outcome==="string"&&DELETE_OUTCOMES.has(result.outcome)?{status:result.outcome}:typeof result.item.status==="string"?{status:result.item.status}:{},...typeof result.deleted==="boolean"?{deleted:result.deleted}:{},...typeof result.previous_status==="string"?{previous_status:result.previous_status}:{},changed_field_count:changedFields.length};appendCompactMutationEvidence(result,result.item,compact);return compact}function appendCompactMutationEvidence(result,item,compact){const closeReason=typeof result.close_reason==="string"?result.close_reason:typeof item.close_reason==="string"?item.close_reason:void 0;if(closeReason!==void 0)compact.close_reason=closeReason;const recurrence=projectCompactRecurrence(result.recurrence);if(recurrence!==null)compact.recurrence=recurrence;if(Array.isArray(result.warnings)&&result.warnings.length>0)compact.warnings=result.warnings;if(isPlainObject(result.recovery))compact.recovery=result.recovery;if(typeof result.claimed_by==="string"||typeof result.released_by==="string"){for(const key of["claimed_by","released_by","previous_assignee","forced","skipped","available","attempts","suggestions"]){if(Object.hasOwn(result,key))compact[key]=result[key]}}}function compactUpdateManyRows(envelope){const rows=isUpdateManyMutationEnvelope(envelope)?envelope[ROWS_KEY]:void 0;if(!Array.isArray(rows)){return{projected:envelope,changed:false}}let rowsChanged=false;const nextRows=rows.map(row=>{if(!isPlainObject(row)){return row}const compactedRow=compactOwnChangedFields(row);if(compactedRow){rowsChanged=true;return compactedRow}return row});return rowsChanged?{projected:replaceRows(envelope,nextRows),changed:true}:{projected:envelope,changed:false}}function projectMutationResult(result,options={}){const compound=projectCompoundMutation(result,options);if(compound!==null)return compound;if(options.idOnly===true){const idOnly=projectIdOnlyResult(result);if(idOnly!==null){return idOnly}}if(options.compactEnvelope===true){const compact=projectCompactMutationEnvelope(result);if(compact!==null)return compact}const mode=options.changedFields??"full";if(mode==="full"||!isPlainObject(result)){return result}let changed=false;let projected=result;const compactedTop=isMutationEnvelope(result)?compactOwnChangedFields(result):null;if(compactedTop!==null){projected=compactedTop;changed=true}const rowProjection=compactUpdateManyRows(projected);if(rowProjection.changed){projected=rowProjection.projected;changed=true}return changed?projected:result}export{projectMutationResult};
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]="fd8576c5-0011-5aa2-ad8c-f6ec5715e419")}catch(e2){}})();const CHANGED_FIELDS_KEY="changed_fields";const CHANGED_FIELD_COUNT_KEY="changed_field_count";const ROWS_KEY="rows";const UPDATE_MANY_MUTATION_MODES=new Set(["apply","rollback"]);const DELETE_OUTCOMES=new Set(["deleted","would_delete"]);const COMPACT_RECURRENCE_TEXT_LIMIT=256;const COMPOUND_MUTATION_STEPS={start_task:["claim","update"],pause_task:["update","release"],close_task:["close","release"]};function projectCompoundMutation(result,options){if(!isPlainObject(result)||typeof result.action!=="string"||typeof result.id!=="string"||result.id.length===0)return null;const steps=Object.hasOwn(COMPOUND_MUTATION_STEPS,result.action)?COMPOUND_MUTATION_STEPS[result.action]:void 0;if(!steps||!steps.every(step=>{const value=result[step];return isPlainObject(value)&&isPlainObject(value.item)&&value.item.id===result.id&&Array.isArray(value.changed_fields)&&value.changed_fields.every(field=>typeof field==="string")}))return null;const final=result[steps.at(-1)];const identity=projectIdOnlyResult(final);if(options.idOnly)return identity;if(!options.compactEnvelope&&options.changedFields!=="compact")return null;return{...result,...options.compactEnvelope?{...identity,changed_field_count:new Set(steps.flatMap(step=>result[step].changed_fields)).size}:{},...Object.fromEntries(steps.map(step=>[step,projectMutationResult(result[step],options)]))}}function truncateCompactRecurrenceText(value){if(typeof value!=="string"||value.length<=COMPACT_RECURRENCE_TEXT_LIMIT){return value}return`${value.slice(0,COMPACT_RECURRENCE_TEXT_LIMIT-1)}\u2026`}function projectCompactRecurrence(value){if(!isPlainObject(value))return null;const recurrence={...value};recurrence.reason=truncateCompactRecurrenceText(recurrence.reason);if(isPlainObject(recurrence.previous_terminal)){recurrence.previous_terminal=Object.fromEntries(Object.entries(recurrence.previous_terminal).map(([key,entry])=>[key,truncateCompactRecurrenceText(entry)]))}return recurrence}function isPlainObject(value){if(typeof value!=="object"||value===null||Array.isArray(value)){return false}const proto=Object.getPrototypeOf(value);return proto===null||proto===Object.prototype}function compactOwnChangedFields(envelope){const changedFields=envelope[CHANGED_FIELDS_KEY];if(!Array.isArray(changedFields)){return null}const projected=Object.getPrototypeOf(envelope)===null?Object.create(null):{};for(const[key,value]of Object.entries(envelope)){if(key!==CHANGED_FIELDS_KEY){projected[key]=value}}projected[CHANGED_FIELD_COUNT_KEY]=changedFields.length;return projected}function isMutationEnvelope(value){return"item"in value&&Array.isArray(value[CHANGED_FIELDS_KEY])}function isUpdateManyMutationEnvelope(value){return typeof value.mode==="string"&&UPDATE_MANY_MUTATION_MODES.has(value.mode)&&Array.isArray(value[ROWS_KEY])}function replaceRows(envelope,rows){const projected=Object.getPrototypeOf(envelope)===null?Object.create(null):{};Object.assign(projected,envelope);projected[ROWS_KEY]=rows;return projected}function projectIdOnlyResult(result){if(!isPlainObject(result)){return null}const subject=isPlainObject(result.item)?result.item:isPlainObject(result.plan)?result.plan:null;if(subject===null){return null}const id=typeof subject.id==="string"?subject.id:void 0;const status=typeof result.outcome==="string"&&DELETE_OUTCOMES.has(result.outcome)?result.outcome:typeof subject.status==="string"?subject.status:void 0;if(!id){return null}return status?{id,status,...typeof result.deleted==="boolean"?{deleted:result.deleted}:{}}:{id}}function projectCompactMutationEnvelope(result,includeItem){if(!isPlainObject(result))return null;if(isPlainObject(result.plan)&&isPlainObject(result.mutation_receipt)&&result.mutation_receipt.kind==="plan_mutation"&&result.mutation_receipt.id===result.plan.id&&result.mutation_receipt.action===result.action)return result.mutation_receipt;if(!includeItem||!isPlainObject(result.item))return null;if(typeof result.item.id!=="string")return null;const changedFields=result[CHANGED_FIELDS_KEY];if(!Array.isArray(changedFields))return null;const compact={id:result.item.id,...typeof result.outcome==="string"&&DELETE_OUTCOMES.has(result.outcome)?{status:result.outcome}:typeof result.item.status==="string"?{status:result.item.status}:{},...typeof result.deleted==="boolean"?{deleted:result.deleted}:{},...typeof result.previous_status==="string"?{previous_status:result.previous_status}:{},changed_field_count:changedFields.length};appendCompactMutationEvidence(result,result.item,compact);return compact}function appendCompactMutationEvidence(result,item,compact){const closeReason=typeof result.close_reason==="string"?result.close_reason:typeof item.close_reason==="string"?item.close_reason:void 0;if(closeReason!==void 0)compact.close_reason=closeReason;const recurrence=projectCompactRecurrence(result.recurrence);if(recurrence!==null)compact.recurrence=recurrence;if(Array.isArray(result.warnings)&&result.warnings.length>0)compact.warnings=result.warnings;if(isPlainObject(result.recovery))compact.recovery=result.recovery;if(typeof result.claimed_by==="string"||typeof result.released_by==="string"){for(const key of["claimed_by","released_by","previous_assignee","forced","skipped","available","attempts","suggestions"]){if(Object.hasOwn(result,key))compact[key]=result[key]}}}function compactUpdateManyRows(envelope){const rows=isUpdateManyMutationEnvelope(envelope)?envelope[ROWS_KEY]:void 0;if(!Array.isArray(rows)){return{projected:envelope,changed:false}}let rowsChanged=false;const nextRows=rows.map(row=>{if(!isPlainObject(row)){return row}const compactedRow=compactOwnChangedFields(row);if(compactedRow){rowsChanged=true;return compactedRow}return row});return rowsChanged?{projected:replaceRows(envelope,nextRows),changed:true}:{projected:envelope,changed:false}}function projectMutationResult(result,options={}){const compound=projectCompoundMutation(result,options);if(compound!==null)return compound;if(options.idOnly===true){const idOnly=projectIdOnlyResult(result);if(idOnly!==null){return idOnly}}if(options.compactEnvelope===true||options.changedFields==="compact"){const compact=projectCompactMutationEnvelope(result,options.compactEnvelope===true);if(compact!==null)return compact}const mode=options.changedFields??"full";if(mode==="full"||!isPlainObject(result)){return result}let changed=false;let projected=result;const compactedTop=isMutationEnvelope(result)?compactOwnChangedFields(result):null;if(compactedTop!==null){projected=compactedTop;changed=true}const rowProjection=compactUpdateManyRows(projected);if(rowProjection.changed){projected=rowProjection.projected;changed=true}return changed?projected:result}export{projectMutationResult};
2
2
  //# sourceMappingURL=mutation-projection.js.map