@unbrained/pm-cli 2026.10.24 → 2026.10.25

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 (156) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +20 -0
  3. package/dist/cli/error-guidance.js +2 -2
  4. package/dist/cli/extension-command-help.js +2 -2
  5. package/dist/cli/register-history-activity.js +1 -1
  6. package/dist/cli-bundle/bundle-manifest.json +1 -1
  7. package/dist/cli-bundle/chunks/{chunk-R7KWBFM2.js → chunk-3CYXE6BV.js} +2 -2
  8. package/dist/cli-bundle/chunks/chunk-444VPGQT.js +20 -0
  9. package/dist/cli-bundle/chunks/{chunk-YEI4N4A6.js → chunk-4GD6QOP6.js} +21 -21
  10. package/dist/cli-bundle/chunks/{chunk-HZNFNETE.js → chunk-5ZPT67NJ.js} +6 -6
  11. package/dist/cli-bundle/chunks/{chunk-KGZGXC7T.js → chunk-7C3GCLOO.js} +29 -29
  12. package/dist/cli-bundle/chunks/{chunk-3VI4XDP2.js → chunk-7T3H24HN.js} +2 -2
  13. package/dist/cli-bundle/chunks/{chunk-MA7SNKYK.js → chunk-EYCVAAIP.js} +2 -2
  14. package/dist/cli-bundle/chunks/{chunk-CDR5ES7Q.js → chunk-FNZT4BTE.js} +38 -34
  15. package/dist/cli-bundle/chunks/{chunk-CNEUJHA4.js → chunk-HMJSFWHK.js} +2 -2
  16. package/dist/cli-bundle/chunks/{chunk-ZDVTXLA6.js → chunk-LNKPH2DD.js} +2 -2
  17. package/dist/cli-bundle/chunks/{chunk-Z62RXNHW.js → chunk-MVJGGCGQ.js} +2 -2
  18. package/dist/cli-bundle/chunks/{chunk-3S5FLCG7.js → chunk-O3ZTGRIH.js} +2 -2
  19. package/dist/cli-bundle/chunks/{chunk-FASDGYQC.js → chunk-RD6UW3MW.js} +3 -3
  20. package/dist/cli-bundle/chunks/{chunk-UY5UHI4I.js → chunk-RLXK2S7P.js} +2 -2
  21. package/dist/cli-bundle/chunks/{chunk-URZB3USE.js → chunk-RQKDANP7.js} +42 -42
  22. package/dist/cli-bundle/chunks/chunk-TLMXSYJA.js +2 -0
  23. package/dist/cli-bundle/chunks/{chunk-4PNAUT2E.js → chunk-UI3FD3DW.js} +2 -2
  24. package/dist/cli-bundle/chunks/{chunk-VSSHB6XI.js → chunk-VAEB6IUQ.js} +2 -2
  25. package/dist/cli-bundle/chunks/{chunk-TZYQ4JDZ.js → chunk-XYLBOXSH.js} +6 -6
  26. package/dist/cli-bundle/chunks/{chunk-CSE47ZAN.js → chunk-YCCGZHOR.js} +2 -2
  27. package/dist/cli-bundle/chunks/{indexed-receipt-blobs-XANVELIV.js → indexed-receipt-blobs-47I6KKDO.js} +2 -2
  28. package/dist/cli-bundle/chunks/{mutation-admission-NVTBZ7DH.js → mutation-admission-747C6IUR.js} +2 -2
  29. package/dist/cli-bundle/chunks/{register-list-query-2FE6K7FQ.js → register-list-query-COST6KRV.js} +3 -3
  30. package/dist/cli-bundle/chunks/{register-mutation-KZXQUZUH.js → register-mutation-JZVVJUHY.js} +2 -2
  31. package/dist/cli-bundle/chunks/register-operations-S4LKLUBJ.js +2 -0
  32. package/dist/cli-bundle/chunks/{register-setup-P3VLCTDY.js → register-setup-3ITZXPOL.js} +2 -2
  33. package/dist/cli-bundle/chunks/{settlement-hook-YUVCO65H.js → settlement-hook-5IVCF6ZY.js} +2 -2
  34. package/dist/cli-bundle/chunks/stage-3UUIYROS.js +2 -0
  35. package/dist/cli-bundle/focused-chunks/{chunk-JYXA4JIP.js → chunk-22727JYL.js} +2 -2
  36. package/dist/cli-bundle/focused-chunks/{chunk-RVUGTIIU.js → chunk-3FM75SBJ.js} +2 -2
  37. package/dist/cli-bundle/focused-chunks/{chunk-RSEGFZTY.js → chunk-3M5FZCMC.js} +54 -54
  38. package/dist/cli-bundle/focused-chunks/{chunk-BUZ2Z4P3.js → chunk-46KDJH3K.js} +2 -2
  39. package/dist/cli-bundle/focused-chunks/chunk-5LBZR6YW.js +2 -0
  40. package/dist/cli-bundle/focused-chunks/{chunk-SHUPX6G2.js → chunk-74KC7FUQ.js} +2 -2
  41. package/dist/cli-bundle/focused-chunks/chunk-77NU7NPN.js +2 -0
  42. package/dist/cli-bundle/focused-chunks/{chunk-NX7TVNUM.js → chunk-7DEZT4JN.js} +2 -2
  43. package/dist/cli-bundle/focused-chunks/{chunk-ES2NGVHZ.js → chunk-B5JOVH5F.js} +2 -2
  44. package/dist/cli-bundle/focused-chunks/chunk-HMYDUEQK.js +8 -0
  45. package/dist/cli-bundle/focused-chunks/chunk-IVLIUPVV.js +12 -0
  46. package/dist/cli-bundle/focused-chunks/{chunk-X5YRJMAY.js → chunk-KIIGME23.js} +2 -2
  47. package/dist/cli-bundle/focused-chunks/{chunk-IUAYTD2S.js → chunk-LWJ2X75I.js} +24 -24
  48. package/dist/cli-bundle/focused-chunks/{chunk-SBJ2IKTH.js → chunk-MT5TYMEU.js} +2 -2
  49. package/dist/cli-bundle/focused-chunks/{chunk-7RQOFHMH.js → chunk-NC5HUGHU.js} +3 -3
  50. package/dist/cli-bundle/focused-chunks/chunk-NI5SG2M2.js +2 -0
  51. package/dist/cli-bundle/focused-chunks/{chunk-ZMWLV2CE.js → chunk-QH5KMIYZ.js} +2 -2
  52. package/dist/cli-bundle/focused-chunks/{chunk-POLMFGPQ.js → chunk-U6HXIF6G.js} +2 -2
  53. package/dist/cli-bundle/focused-chunks/{chunk-6HJCSHBG.js → chunk-URWYYJ7K.js} +2 -2
  54. package/dist/cli-bundle/focused-chunks/{chunk-5MKNVJCM.js → chunk-W7MCCFYV.js} +2 -2
  55. package/dist/cli-bundle/focused-chunks/{chunk-AGCEWJ27.js → chunk-WMPDY5ZU.js} +2 -2
  56. package/dist/cli-bundle/focused-chunks/{chunk-R536272H.js → chunk-Y4JHHY24.js} +2 -2
  57. package/dist/cli-bundle/focused-chunks/{chunk-TAHSXKAT.js → chunk-ZYCOMRFT.js} +2 -2
  58. package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-FVOA3XMI.js → indexed-receipt-blobs-YCLN2ZZG.js} +2 -2
  59. package/dist/cli-bundle/focused-chunks/{mutation-admission-PB6YFY7S.js → mutation-admission-BQBQXILV.js} +2 -2
  60. package/dist/cli-bundle/focused-chunks/{settlement-hook-2VXEB6PP.js → settlement-hook-XVS6P2XI.js} +2 -2
  61. package/dist/cli-bundle/focused-chunks/stage-VSIL4MTZ.js +2 -0
  62. package/dist/cli-bundle/main.js +19 -19
  63. package/dist/cli-bundle/sdk-authoring.js +1 -1
  64. package/dist/cli-bundle/sdk-contracts.js +2 -2
  65. package/dist/cli-bundle/sdk-core.js +15 -15
  66. package/dist/cli-bundle/sdk-governance.js +1 -1
  67. package/dist/cli-bundle/sdk-graph.js +1 -1
  68. package/dist/cli-bundle/sdk-merge.js +55 -56
  69. package/dist/cli-bundle/sdk-query.js +1 -1
  70. package/dist/cli-bundle/sdk-runtime.js +1 -1
  71. package/dist/cli-bundle/sdk-testing.js +1 -1
  72. package/dist/cli-bundle/sdk.js +3 -3
  73. package/dist/core/diagnostics/remediation.js +1 -1
  74. package/dist/core/shared/errors.d.ts +13 -0
  75. package/dist/core/shared/errors.js +1 -1
  76. package/dist/core/store/settings.js +2 -2
  77. package/dist/sdk/agent/command-recovery.js +1 -1
  78. package/dist/sdk/cli-contracts/commander-types.js +1 -1
  79. package/dist/sdk/cli-contracts/flag-contracts.d.ts +2 -0
  80. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  81. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
  82. package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
  83. package/dist/sdk/cli-contracts/registration-helpers.d.ts +2 -0
  84. package/dist/sdk/cli-contracts/registration-helpers.js +2 -2
  85. package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
  86. package/dist/sdk/cli-contracts/tool-option-contracts.js +1 -1
  87. package/dist/sdk/completion/fish.js +3 -1
  88. package/dist/sdk/completion/zsh.js +3 -1
  89. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  90. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  91. package/dist/sdk/governance/health-merge-evidence.d.ts +5 -0
  92. package/dist/sdk/governance/health-merge-evidence.js +1 -1
  93. package/dist/sdk/governance/health.js +1 -1
  94. package/dist/sdk/index.d.ts +1 -1
  95. package/dist/sdk/index.js +1 -1
  96. package/dist/sdk/merge/history-scalar-rebase.d.ts +9 -0
  97. package/dist/sdk/merge/history-scalar-rebase.js +2 -0
  98. package/dist/sdk/merge/ignored-artifacts.d.ts +13 -0
  99. package/dist/sdk/merge/ignored-artifacts.js +2 -0
  100. package/dist/sdk/merge/stage.js +1 -1
  101. package/dist/sdk/merge/three-way.js +1 -1
  102. package/dist/sdk/public-surface.json +1 -1
  103. package/dist/sdk/query/activity.d.ts +14 -2
  104. package/dist/sdk/query/activity.js +1 -1
  105. package/dist/sdk/query/calendar.d.ts +16 -0
  106. package/dist/sdk/query/calendar.js +3 -3
  107. package/dist/sdk/query/context.js +2 -2
  108. package/dist/sdk/query/get.js +1 -1
  109. package/dist/sdk/query/list.js +1 -1
  110. package/dist/sdk/query/search-contracts.js +1 -1
  111. package/dist/sdk/query/window-pagination.d.ts +20 -0
  112. package/dist/sdk/query/window-pagination.js +2 -0
  113. package/dist/sdk/read-output-contracts.js +1 -1
  114. package/dist/sdk/runtime.d.ts +1 -1
  115. package/dist/sdk/runtime.js +1 -1
  116. package/dist/sdk/schema-migration.js +2 -2
  117. package/dist/sdk/templates.d.ts +7 -1
  118. package/dist/sdk/templates.js +2 -2
  119. package/docs/COMMANDS.md +19 -1
  120. package/docs/EXTENSIONS.md +1 -1
  121. package/docs/MERGE_SAFETY.md +28 -0
  122. package/docs/SDK.md +85 -6
  123. package/docs/generated/FLAG_LEXICON_BUDGETS.md +2 -2
  124. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +5 -3
  125. package/marketplace.json +1 -1
  126. package/package.json +1 -1
  127. package/packages/pm-beads/package.json +1 -1
  128. package/packages/pm-calendar/extensions/calendar/index.ts +6 -0
  129. package/packages/pm-calendar/package.json +1 -1
  130. package/packages/pm-command-kit/package.json +1 -1
  131. package/packages/pm-digital-twin/package.json +1 -1
  132. package/packages/pm-governance-audit/package.json +1 -1
  133. package/packages/pm-guide-shell/package.json +1 -1
  134. package/packages/pm-kanban/package.json +1 -1
  135. package/packages/pm-lifecycle-hooks/package.json +1 -1
  136. package/packages/pm-linked-test-adapters/package.json +1 -1
  137. package/packages/pm-search-advanced/package.json +1 -1
  138. package/packages/pm-templates/extensions/templates/runtime.ts +3 -1
  139. package/packages/pm-templates/package.json +1 -1
  140. package/packages/pm-todos/package.json +1 -1
  141. package/packages/pm-vcs/package.json +1 -1
  142. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  143. package/plugins/pm-claude/package.json +1 -1
  144. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  145. package/plugins/pm-codex/package.json +1 -1
  146. package/plugins/pm-codex/plugin.json +1 -1
  147. package/runtime-dependencies.json +1 -1
  148. package/dist/cli-bundle/chunks/chunk-VPMQEVU6.js +0 -20
  149. package/dist/cli-bundle/chunks/register-operations-BOCBWNKJ.js +0 -2
  150. package/dist/cli-bundle/chunks/stage-WRDTMCCF.js +0 -2
  151. package/dist/cli-bundle/focused-chunks/chunk-3QYTS4OY.js +0 -12
  152. package/dist/cli-bundle/focused-chunks/chunk-CEEOWDB7.js +0 -8
  153. package/dist/cli-bundle/focused-chunks/chunk-GXAXDPD4.js +0 -2
  154. package/dist/cli-bundle/focused-chunks/chunk-NFFPNMTH.js +0 -2
  155. package/dist/cli-bundle/focused-chunks/chunk-XTYEASIY.js +0 -2
  156. package/dist/cli-bundle/focused-chunks/stage-MQE4PFWT.js +0 -2
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="270d544f-ac42-559f-ba6a-82f3d3b6c187")}catch{}})();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 pending receipt summaries, re-apply intended discarded values, then run pm merge reconcile. If proof is unavailable or receipt decisions are lossy, explicit review authority is required for pm merge reconcile --force --message "<reviewed receipt disposition and rationale>"; this records acceptance rather than restoring discarded values.'},{code:"merge_receipts_pending",command:"pm merge reconcile",summary:'A lossless receipt is pending; preview with pm merge reconcile --dry-run, then apply. If no receipt set proves the snapshot, review the summaries and only with explicit authority run pm merge reconcile --force --message "<reviewed receipt disposition and rationale>" to record an audited acceptance.'},{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;const normalized=warning.trim();for(const entry of REMEDIATION_REGISTRY)if(normalized===entry.code||normalized.startsWith(`${entry.code}:`))return entry}function buildRemediationMap(warnings){const map={};for(const warning of warnings){const entry=resolveRemediation(warning);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=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="0e576e9d-5aa3-5d54-8acf-23e4f18b432f")}catch{}})();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_artifacts_ignored",command:"pm health --check-only --full",summary:"Remove or narrow the owning ignore rules listed in integrity.ignored_merge_artifacts. Merge receipts must be committed with their audit history; preserve those files, then preview pm merge reconcile --stage --dry-run before applying settlement."},{code:"merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:'Review pending receipt summaries, re-apply intended discarded values, then run pm merge reconcile. If proof is unavailable or receipt decisions are lossy, explicit review authority is required for pm merge reconcile --force --message "<reviewed receipt disposition and rationale>"; this records acceptance rather than restoring discarded values.'},{code:"merge_receipts_pending",command:"pm merge reconcile",summary:'A lossless receipt is pending; preview with pm merge reconcile --dry-run, then apply. If no receipt set proves the snapshot, review the summaries and only with explicit authority run pm merge reconcile --force --message "<reviewed receipt disposition and rationale>" to record an audited acceptance.'},{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;const normalized=warning.trim();for(const entry of REMEDIATION_REGISTRY)if(normalized===entry.code||normalized.startsWith(`${entry.code}:`))return entry}function buildRemediationMap(warnings){const map={};for(const warning of warnings){const entry=resolveRemediation(warning);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
@@ -159,6 +159,19 @@ empty?:boolean;
159
159
  reason?:string;
160
160
  /** Metadata field responsible for a validation failure, when known. */
161
161
  field?:string;
162
+ /** Original branch coordinates of a scalar patch that cannot safely join a history union. */
163
+ history_merge?:{
164
+ /** Side supplying the original event. */
165
+ branch:"ours" | "theirs";
166
+ /** One-based history entry position in that branch. */
167
+ line:number;
168
+ /** Original history operation name. */
169
+ op:string;
170
+ /** Zero-based operation index within the normalized scalar patch. */
171
+ patch_index:number;
172
+ /** JSON pointer of the operation that refused replay. */
173
+ patch_path:string;
174
+ };
162
175
  /** Assurance gate whose evaluation was refused, when known. */
163
176
  gate_id?:string;
164
177
  /** Assurance assertion whose evaluation was refused, when known. */
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="5740fcf4-dad8-5bcc-b68d-99fa81c43655")}catch{}})();class PmCliError extends Error{exitCode;code;context;constructor(message,exitCode,context={}){super(message),this.name="PmCliError",this.exitCode=exitCode,this.context=context,this.code=context.code}}export{PmCliError};
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="72af1939-fe63-50a3-b327-cfd16d9e953c")}catch{}})();class PmCliError extends Error{exitCode;code;context;constructor(message,exitCode,context={}){super(message),this.name="PmCliError",this.exitCode=exitCode,this.context=context,this.code=context.code}}export{PmCliError};
2
2
  //# sourceMappingURL=errors.js.map
@@ -1,5 +1,5 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="0caecc9d-687a-5b36-b19c-2f2a9c7a1a8a")}catch{}})();import{AsyncLocalStorage}from"node:async_hooks";import{lstat,realpath}from"node:fs/promises";import path from"node:path";import{validateSettings}from"./settings-validator.js";import{runActiveOnReadHooks,runActiveOnWriteHooks}from"../extensions/index.js";import{EXIT_CODE,GOVERNANCE_PRESET_DEFAULTS,SETTINGS_DEFAULTS}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{resolveAuthor}from"../shared/author.js";import{isFileAbsentError,readFileIfExists,readRegularFile,transactionPreviewNonRegularFileError}from"../fs/fs-utils.js";import{mutateWorkspaceJsonWithHistory}from"../history/workspace-history.js";import{reconcileSettingsSnapshot}from"./settings-concurrency.js";import{DEFAULT_RUNTIME_SCHEMA_FILE_PATHS,ensureRuntimeSchemaFileScaffold,filePathForSchemaSection,loadRuntimeSchemaFromOptionalFiles,normalizeRuntimeSchemaSettings}from"../schema/runtime-schema.js";import{getSettingsPath}from"./paths.js";import{orderObject,stableValueEquals}from"../shared/serialization.js";import{normalizeItemTypeDefinition}from"../item/item-type-definition.js";import{normalizeEstimateDefaultOverrides}from"../validate/estimate-defaults.js";import{clearSettingsReadCache,collectSettingsReadCacheSignatures,getSettingsReadCacheEntry,setSettingsReadCacheEntry,settingsReadCacheSignaturesEqual}from"./settings-read-cache.js";const configurationOnlySettingsRoots=new AsyncLocalStorage;async function runWithConfigurationOnlySettings(pmRoot,run,isEnabled=()=>!0){const roots=new Set([path.resolve(pmRoot)]);try{roots.add(await realpath(pmRoot))}catch{}return configurationOnlySettingsRoots.run([...configurationOnlySettingsRoots.getStore()??[],[roots,isEnabled]],run)}function isConfigurationOnlySettingsRead(pmRoot){const root=path.resolve(pmRoot);return configurationOnlySettingsRoots.getStore()?.some(([roots,isEnabled])=>roots.has(root)&&isEnabled())??!1}const SETTINGS_WRITE_OP="settings:write",SETTINGS_PERSIST_SOURCE_SYMBOL=Symbol("pm.settings.persist_source"),MAX_VECTOR_STORE_COLLECTION_NAME_LENGTH=128,DUPLICATE_DETECTION_MODES=new Set(["off","advisory","strict"]);function resolveGovernanceKnobsFromPreset(preset){return structuredClone(GOVERNANCE_PRESET_DEFAULTS[preset])}function normalizeGovernancePreset(value){return value==="minimal"||value==="default"||value==="strict"||value==="custom"?value:SETTINGS_DEFAULTS.governance.preset}function withGovernanceExtras(base,governance){const createDefaultType=typeof governance.create_default_type=="string"?governance.create_default_type.trim():void 0;return createDefaultType&&createDefaultType.length>0&&(base.create_default_type=createDefaultType),(governance.workflow_enforcement==="off"||governance.workflow_enforcement==="warn"||governance.workflow_enforcement==="strict")&&(base.workflow_enforcement=governance.workflow_enforcement),governance.require_close_reason===!1&&(base.require_close_reason=!1),base.duplicate_detection_mode=governance.duplicate_detection_mode,base.duplicate_detection_threshold=governance.duplicate_detection_threshold,base.duplicate_detection_limit=governance.duplicate_detection_limit,base}function normalizeGovernanceForPersist(governance){return governance.preset==="custom"?withGovernanceExtras({preset:"custom",ownership_enforcement:governance.ownership_enforcement,create_mode_default:governance.create_mode_default,close_validation_default:governance.close_validation_default,parent_reference:governance.parent_reference,metadata_profile:governance.metadata_profile,force_required_for_stale_lock:governance.force_required_for_stale_lock},governance):withGovernanceExtras({preset:governance.preset},governance)}function resolveGovernanceExtras(rawGovernance){const createDefaultType=typeof rawGovernance.create_default_type=="string"?rawGovernance.create_default_type.trim():void 0,extras={};createDefaultType&&createDefaultType.length>0&&(extras.create_default_type=createDefaultType),(rawGovernance.workflow_enforcement==="off"||rawGovernance.workflow_enforcement==="warn"||rawGovernance.workflow_enforcement==="strict")&&(extras.workflow_enforcement=rawGovernance.workflow_enforcement),typeof rawGovernance.require_close_reason=="boolean"&&(extras.require_close_reason=rawGovernance.require_close_reason),DUPLICATE_DETECTION_MODES.has(String(rawGovernance.duplicate_detection_mode))&&(extras.duplicate_detection_mode=rawGovernance.duplicate_detection_mode);const threshold=rawGovernance.duplicate_detection_threshold;[typeof threshold=="number",Number.isFinite(threshold),Number(threshold)>=0,Number(threshold)<=1].every(Boolean)&&(extras.duplicate_detection_threshold=threshold);const limit=rawGovernance.duplicate_detection_limit;return[typeof limit=="number",Number.isSafeInteger(limit),Number(limit)>=0,Number(limit)<=20].every(Boolean)&&(extras.duplicate_detection_limit=limit),extras}function resolveGovernanceKnobs(settings){const rawGovernance=settings.governance??{},preset=normalizeGovernancePreset(rawGovernance.preset),extras=resolveGovernanceExtras(rawGovernance);if(preset==="custom"){const baseline2=resolveGovernanceKnobsFromPreset("default"),requireCloseReason2=extras.require_close_reason??baseline2.require_close_reason;return{preset,ownership_enforcement:rawGovernance.ownership_enforcement??baseline2.ownership_enforcement,create_mode_default:rawGovernance.create_mode_default??baseline2.create_mode_default,close_validation_default:rawGovernance.close_validation_default??baseline2.close_validation_default,parent_reference:rawGovernance.parent_reference??baseline2.parent_reference,metadata_profile:rawGovernance.metadata_profile??baseline2.metadata_profile,force_required_for_stale_lock:rawGovernance.force_required_for_stale_lock??baseline2.force_required_for_stale_lock,...extras,require_close_reason:requireCloseReason2,duplicate_detection_mode:extras.duplicate_detection_mode??baseline2.duplicate_detection_mode,duplicate_detection_threshold:extras.duplicate_detection_threshold??baseline2.duplicate_detection_threshold,duplicate_detection_limit:extras.duplicate_detection_limit??baseline2.duplicate_detection_limit}}const baseline=resolveGovernanceKnobsFromPreset(preset),requireCloseReason=extras.require_close_reason??baseline.require_close_reason;return{preset,...baseline,...extras,require_close_reason:requireCloseReason}}function cloneDefaults(){return structuredClone(SETTINGS_DEFAULTS)}function normalizeSearchMutationRefreshPolicy(value){return value==="cache_only"||value==="semantic_configured"||value==="semantic_auto"?value:SETTINGS_DEFAULTS.search.mutation_refresh_policy}function normalizeSearchDefaultMode(value){return value==="auto"||value==="keyword"||value==="semantic"||value==="hybrid"?value:"auto"}function normalizeSearchQueryExpansionEnabled(value){return typeof value=="boolean"?value:SETTINGS_DEFAULTS.search.query_expansion.enabled}function normalizeSearchQueryExpansionProvider(value){return typeof value!="string"?SETTINGS_DEFAULTS.search.query_expansion.provider:value.trim()}function normalizeSearchRerankEnabled(value){return typeof value=="boolean"?value:SETTINGS_DEFAULTS.search.rerank.enabled}function normalizeSearchRerankModel(value){return typeof value!="string"?SETTINGS_DEFAULTS.search.rerank.model:value.trim()}function normalizeSearchRerankTopK(value){return typeof value=="number"&&Number.isFinite(value)&&Number.isInteger(value)&&value>0?value:SETTINGS_DEFAULTS.search.rerank.top_k}function normalizeVectorStoreCollectionName(value){if(typeof value!="string")return SETTINGS_DEFAULTS.vector_store.collection_name;const truncated=value.trim().replaceAll(/[^a-zA-Z0-9_-]/g,"_").slice(0,MAX_VECTOR_STORE_COLLECTION_NAME_LENGTH);return truncated.length>0?truncated:SETTINGS_DEFAULTS.vector_store.collection_name}function cloneOptionalArray(value){return{present:Array.isArray(value),values:Array.isArray(value)?structuredClone(value):[]}}function buildSettingsPersistSourceSnapshot(parsedSettings,runtimeSettings){const sourceSchema=parsedSettings.schema,sourceStatuses=cloneOptionalArray(sourceSchema?.statuses),sourceFields=cloneOptionalArray(sourceSchema?.fields),sourceTypeWorkflows=cloneOptionalArray(sourceSchema?.type_workflows);return{persisted_settings:structuredClone(parsedSettings),source_settings:structuredClone(parsedSettings),has_source_item_type_definitions:Array.isArray(parsedSettings.item_types?.definitions),source_item_type_definitions:normalizeItemTypeDefinitions(parsedSettings.item_types?.definitions),has_source_schema_statuses:sourceStatuses.present,source_schema_statuses:sourceStatuses.values,has_source_schema_fields:sourceFields.present,source_schema_fields:sourceFields.values,has_source_schema_type_workflows:sourceTypeWorkflows.present,source_schema_type_workflows:sourceTypeWorkflows.values,runtime_item_type_definitions:normalizeItemTypeDefinitions(runtimeSettings.item_types?.definitions),runtime_schema_statuses:structuredClone(runtimeSettings.schema.statuses),runtime_schema_fields:structuredClone(runtimeSettings.schema.fields),runtime_schema_type_workflows:structuredClone(runtimeSettings.schema.type_workflows??[])}}function attachSettingsPersistSourceSnapshot(settings,source){Object.defineProperty(settings,SETTINGS_PERSIST_SOURCE_SYMBOL,{value:source,writable:!0,configurable:!0,enumerable:!1})}function getSettingsPersistSourceSnapshot(settings){const candidate=settings[SETTINGS_PERSIST_SOURCE_SYMBOL];if(!(!candidate||typeof candidate!="object"))return candidate}function persistSelectedItemFormat(settings){const source=getSettingsPersistSourceSnapshot(settings);if(source){const detachedSource=structuredClone(source);detachedSource.source_settings.item_format=settings.item_format,attachSettingsPersistSourceSnapshot(settings,detachedSource)}}function cloneSettingsReadResult(result){const clonedSettings=structuredClone(result.settings),persistSource=getSettingsPersistSourceSnapshot(result.settings);return persistSource&&attachSettingsPersistSourceSnapshot(clonedSettings,persistSource),{settings:clonedSettings,metadata:{has_explicit_item_format:result.metadata.has_explicit_item_format},warnings:[...result.warnings]}}function resolveSettingsReadTrackedPaths(pmRoot,schema,settingsPath){const normalizedSchema=normalizeRuntimeSchemaSettings(schema);return[settingsPath,filePathForSchemaSection(pmRoot,normalizedSchema.files.types,DEFAULT_RUNTIME_SCHEMA_FILE_PATHS.types),filePathForSchemaSection(pmRoot,normalizedSchema.files.statuses,DEFAULT_RUNTIME_SCHEMA_FILE_PATHS.statuses),filePathForSchemaSection(pmRoot,normalizedSchema.files.fields,DEFAULT_RUNTIME_SCHEMA_FILE_PATHS.fields),filePathForSchemaSection(pmRoot,normalizedSchema.files.workflows,DEFAULT_RUNTIME_SCHEMA_FILE_PATHS.workflows)]}async function cacheSettingsReadResult(pmRoot,trackedPaths,result){const signatures=await collectSettingsReadCacheSignatures(trackedPaths);setSettingsReadCacheEntry(pmRoot,{tracked_paths:trackedPaths,signatures,value:cloneSettingsReadResult(result)})}async function cacheSettingsReadResultSafe(pmRoot,trackedPaths,result){try{await cacheSettingsReadResult(pmRoot,trackedPaths,result)}catch{clearSettingsReadCache(pmRoot)}}function findSettingsReadCacheSignature(signatures,targetPath){return signatures.find(signature=>signature.path===targetPath)}function selectedSettingsReadCacheSignaturesEqual(before,after,targetPaths){for(const targetPath of targetPaths){const beforeSignature=findSettingsReadCacheSignature(before,targetPath),afterSignature=findSettingsReadCacheSignature(after,targetPath);if(!beforeSignature||!afterSignature||!settingsReadCacheSignaturesEqual([beforeSignature],[afterSignature]))return!1}return!0}async function cacheSettingsReadResultIfStable(pmRoot,trackedPaths,result,stableSignatures,stablePaths){try{const currentSignatures=await collectSettingsReadCacheSignatures(trackedPaths);if(!selectedSettingsReadCacheSignaturesEqual(stableSignatures,currentSignatures,stablePaths)){clearSettingsReadCache(pmRoot);return}setSettingsReadCacheEntry(pmRoot,{tracked_paths:trackedPaths,signatures:currentSignatures,value:cloneSettingsReadResult(result)})}catch{clearSettingsReadCache(pmRoot)}}function resolvePersistedFileBackedSchemaSections(settings,source){const normalizedSchema=normalizeRuntimeSchemaSettings(settings.schema),currentItemTypeDefinitions=normalizeItemTypeDefinitions(settings.item_types?.definitions);if(!source)return{item_type_definitions:currentItemTypeDefinitions,schema_statuses:normalizedSchema.statuses,schema_fields:normalizedSchema.fields,schema_type_workflows:normalizedSchema.type_workflows};const currentTypeWorkflows=normalizedSchema.type_workflows??[],itemTypeDefinitionsUnchanged=stableValueEquals(currentItemTypeDefinitions,source.runtime_item_type_definitions),schemaStatusesUnchanged=stableValueEquals(normalizedSchema.statuses,source.runtime_schema_statuses),schemaFieldsUnchanged=stableValueEquals(normalizedSchema.fields,source.runtime_schema_fields),schemaTypeWorkflowsUnchanged=stableValueEquals(currentTypeWorkflows,source.runtime_schema_type_workflows);return{item_type_definitions:itemTypeDefinitionsUnchanged?source.has_source_item_type_definitions?normalizeItemTypeDefinitions(source.source_item_type_definitions):[]:currentItemTypeDefinitions,schema_statuses:schemaStatusesUnchanged?source.has_source_schema_statuses?structuredClone(source.source_schema_statuses):[]:normalizedSchema.statuses,schema_fields:schemaFieldsUnchanged?source.has_source_schema_fields?structuredClone(source.source_schema_fields):[]:normalizedSchema.fields,schema_type_workflows:schemaTypeWorkflowsUnchanged?source.has_source_schema_type_workflows?structuredClone(source.source_schema_type_workflows):void 0:normalizedSchema.type_workflows}}function buildFallbackSettingsReadResult(warning){return{settings:cloneDefaults(),metadata:{has_explicit_item_format:!1},warnings:warning?[warning]:[]}}function hasExplicitItemFormat(raw){if(typeof raw!="object"||raw===null||Array.isArray(raw))return!1;const itemFormat=raw.item_format;return itemFormat==="toon"||itemFormat==="json_markdown"}function normalizeStringList(values){return[...new Set((values??[]).map(value=>value.trim()).filter(value=>value.length>0))].sort((left,right)=>left.localeCompare(right))}function normalizeAgentGuidanceSettings(value){const defaults=SETTINGS_DEFAULTS.agent_guidance,templateVersion=value?.template_version;return{prompt_completed:value?.prompt_completed===!0,declined:value?.declined===!0,declined_at:typeof value?.declined_at=="string"?value.declined_at:defaults.declined_at,template_version:typeof templateVersion=="number"&&Number.isInteger(templateVersion)&&templateVersion>0?templateVersion:defaults.template_version,last_checked_files:normalizeStringList(value?.last_checked_files??defaults.last_checked_files)}}function normalizeLowerStringList(values){return[...new Set((values??[]).map(value=>value.trim().toLowerCase()).filter(value=>value.length>0))].sort((left,right)=>left.localeCompare(right))}function normalizeExtensionPolicyMode(value){return value==="off"||value==="warn"||value==="enforce"?value:SETTINGS_DEFAULTS.extensions.policy.mode}function normalizeExtensionTrustMode(value){return value==="off"||value==="warn"||value==="enforce"?value:SETTINGS_DEFAULTS.extensions.policy.trust_mode}function normalizeExtensionSandboxProfile(value){return value==="none"||value==="restricted"||value==="strict"?value:SETTINGS_DEFAULTS.extensions.policy.default_sandbox_profile}function normalizeExtensionPolicyOverride(override){const name=override.name.trim().toLowerCase();if(name.length===0)return null;const normalized={name};override.disabled===!0&&(normalized.disabled=!0),override.require_trusted===!0&&(normalized.require_trusted=!0),override.require_provenance===!0&&(normalized.require_provenance=!0),override.sandbox_profile!==void 0&&(normalized.sandbox_profile=normalizeExtensionSandboxProfile(override.sandbox_profile));const allowedCapabilities=normalizeLowerStringList(override.allowed_capabilities),blockedCapabilities=normalizeLowerStringList(override.blocked_capabilities),allowedSurfaces=normalizeLowerStringList(override.allowed_surfaces),blockedSurfaces=normalizeLowerStringList(override.blocked_surfaces),allowedCommands=normalizeLowerStringList(override.allowed_commands),blockedCommands=normalizeLowerStringList(override.blocked_commands),allowedActions=normalizeLowerStringList(override.allowed_actions),blockedActions=normalizeLowerStringList(override.blocked_actions),allowedServices=normalizeLowerStringList(override.allowed_services),blockedServices=normalizeLowerStringList(override.blocked_services);return allowedCapabilities.length>0&&(normalized.allowed_capabilities=allowedCapabilities),blockedCapabilities.length>0&&(normalized.blocked_capabilities=blockedCapabilities),allowedSurfaces.length>0&&(normalized.allowed_surfaces=allowedSurfaces),blockedSurfaces.length>0&&(normalized.blocked_surfaces=blockedSurfaces),allowedCommands.length>0&&(normalized.allowed_commands=allowedCommands),blockedCommands.length>0&&(normalized.blocked_commands=blockedCommands),allowedActions.length>0&&(normalized.allowed_actions=allowedActions),blockedActions.length>0&&(normalized.blocked_actions=blockedActions),allowedServices.length>0&&(normalized.allowed_services=allowedServices),blockedServices.length>0&&(normalized.blocked_services=blockedServices),normalized}function normalizeExtensionPolicyOverrides(overrides){const dedupedByName=new Map;for(const override of overrides??[]){const normalized=normalizeExtensionPolicyOverride(override);normalized&&dedupedByName.set(normalized.name,normalized)}return[...dedupedByName.values()].sort((left,right)=>left.name.localeCompare(right.name))}function normalizePmMaxVersionExceededModeValue(value){return value==="block"||value==="warn"?value:void 0}function normalizePmMaxVersionExceededModeSetting(value){if(typeof value=="string")return normalizePmMaxVersionExceededModeValue(value);if(typeof value=="object"&&value!==null&&!Array.isArray(value)){const global2=normalizePmMaxVersionExceededModeValue(value.global),project=normalizePmMaxVersionExceededModeValue(value.project);return global2===void 0&&project===void 0?void 0:{...global2!==void 0?{global:global2}:{},...project!==void 0?{project}:{}}}}function normalizeExtensionPolicyList(policy,key){return normalizeLowerStringList(policy?.[key]??SETTINGS_DEFAULTS.extensions.policy[key])}function normalizeExtensionPolicySettings(policy){const pmMaxVersionExceededMode=normalizePmMaxVersionExceededModeSetting(policy?.pm_max_version_exceeded_mode);return{mode:normalizeExtensionPolicyMode(policy?.mode),trust_mode:normalizeExtensionTrustMode(policy?.trust_mode),...pmMaxVersionExceededMode!==void 0?{pm_max_version_exceeded_mode:pmMaxVersionExceededMode}:{},require_provenance:policy?.require_provenance===!0,trusted_extensions:normalizeExtensionPolicyList(policy,"trusted_extensions"),default_sandbox_profile:normalizeExtensionSandboxProfile(policy?.default_sandbox_profile),allowed_extensions:normalizeExtensionPolicyList(policy,"allowed_extensions"),blocked_extensions:normalizeExtensionPolicyList(policy,"blocked_extensions"),allowed_capabilities:normalizeExtensionPolicyList(policy,"allowed_capabilities"),blocked_capabilities:normalizeExtensionPolicyList(policy,"blocked_capabilities"),allowed_surfaces:normalizeExtensionPolicyList(policy,"allowed_surfaces"),blocked_surfaces:normalizeExtensionPolicyList(policy,"blocked_surfaces"),allowed_commands:normalizeExtensionPolicyList(policy,"allowed_commands"),blocked_commands:normalizeExtensionPolicyList(policy,"blocked_commands"),allowed_actions:normalizeExtensionPolicyList(policy,"allowed_actions"),blocked_actions:normalizeExtensionPolicyList(policy,"blocked_actions"),allowed_services:normalizeExtensionPolicyList(policy,"allowed_services"),blocked_services:normalizeExtensionPolicyList(policy,"blocked_services"),extension_overrides:normalizeExtensionPolicyOverrides(policy?.extension_overrides??SETTINGS_DEFAULTS.extensions.policy.extension_overrides)}}function normalizeValidationMetadataRequiredFields(values){return[...new Set((values??[]).map(value=>value.trim().toLowerCase().replaceAll("-","_")))].filter(value=>value.length>0).sort((left,right)=>left.localeCompare(right)).filter(value=>["author","acceptance_criteria","estimated_minutes","close_reason","reviewer","risk","confidence","sprint","release"].includes(value))}function normalizeValidationPatternList(values){return[...new Set((values??[]).map(value=>value.trim().toLowerCase()).filter(value=>value.length>0))].sort((left,right)=>left.localeCompare(right))}function valueOrDefault(value,fallback){return value===void 0?fallback:value}function recordOrEmpty(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)?value:{}}function arrayOrEmpty(value){return Array.isArray(value)?value:[]}function buildValidationSettings(settings,defaults,governance){return{...defaults.validation,...settings.validation,parent_reference:governance.parent_reference,metadata_profile:governance.metadata_profile,metadata_required_fields:normalizeValidationMetadataRequiredFields(settings.validation?.metadata_required_fields),lifecycle_stale_blocker_reason_patterns:normalizeValidationPatternList(settings.validation?.lifecycle_stale_blocker_reason_patterns??defaults.validation.lifecycle_stale_blocker_reason_patterns),lifecycle_closure_like_blocked_reason_patterns:normalizeValidationPatternList(settings.validation?.lifecycle_closure_like_blocked_reason_patterns??defaults.validation.lifecycle_closure_like_blocked_reason_patterns),lifecycle_closure_like_resolution_patterns:normalizeValidationPatternList(settings.validation?.lifecycle_closure_like_resolution_patterns??defaults.validation.lifecycle_closure_like_resolution_patterns),lifecycle_closure_like_actual_result_patterns:normalizeValidationPatternList(settings.validation?.lifecycle_closure_like_actual_result_patterns??defaults.validation.lifecycle_closure_like_actual_result_patterns),estimate_defaults_by_type:normalizeEstimateDefaultOverrides(settings.validation?.estimate_defaults_by_type)}}function buildTelemetrySettings(settings,defaults){return{enabled:settings.telemetry?.enabled??defaults.telemetry.enabled,first_run_prompt_completed:settings.telemetry?.first_run_prompt_completed??defaults.telemetry.first_run_prompt_completed,capture_level:settings.telemetry?.capture_level??defaults.telemetry.capture_level,endpoint:settings.telemetry?.endpoint??defaults.telemetry.endpoint,installation_id:settings.telemetry?.installation_id??defaults.telemetry.installation_id,retention_days:settings.telemetry?.retention_days??defaults.telemetry.retention_days}}function buildSearchSettings(settings,defaults){return{...defaults.search,...settings.search,default_mode:normalizeSearchDefaultMode(settings.search?.default_mode),mutation_refresh_policy:normalizeSearchMutationRefreshPolicy(settings.search?.mutation_refresh_policy),query_expansion:{...defaults.search.query_expansion,...settings.search?.query_expansion,enabled:normalizeSearchQueryExpansionEnabled(settings.search?.query_expansion?.enabled),provider:normalizeSearchQueryExpansionProvider(settings.search?.query_expansion?.provider)},rerank:{...defaults.search.rerank,...settings.search?.rerank,enabled:normalizeSearchRerankEnabled(settings.search?.rerank?.enabled),model:normalizeSearchRerankModel(settings.search?.rerank?.model),top_k:normalizeSearchRerankTopK(settings.search?.rerank?.top_k)}}}function buildVectorStoreSettings(settings,defaults){return{adapter:settings.vector_store.adapter??defaults.vector_store.adapter,collection_name:normalizeVectorStoreCollectionName(settings.vector_store.collection_name),qdrant:{...defaults.vector_store.qdrant,...settings.vector_store.qdrant},lancedb:{...defaults.vector_store.lancedb,...settings.vector_store.lancedb}}}function normalizeSettingsItemFormat(settings,defaults){return settings.item_format==="json_markdown"?"toon":settings.item_format??defaults.item_format}function buildContextSettings(settings,defaults){return{default_depth:settings.context?.default_depth??defaults.context.default_depth,activity_limit:settings.context?.activity_limit??defaults.context.activity_limit,stale_threshold_days:settings.context?.stale_threshold_days??defaults.context.stale_threshold_days,sections:{...defaults.context.sections,...settings.context?.sections}}}function buildProviderSettings(settings,defaults){return{openai:{...defaults.providers.openai,...settings.providers.openai},ollama:{...defaults.providers.ollama,...settings.providers.ollama}}}function normalizeItemTypeDefinitions(definitions){const normalized=(definitions??[]).map(definition=>normalizeItemTypeDefinition(definition)).filter(definition=>definition!==null),dedupedByName=new Map;for(const definition of normalized)dedupedByName.set(definition.name.toLowerCase(),definition);return[...dedupedByName.values()].sort((left,right)=>left.name.localeCompare(right.name))}function mergeSettings(settings){const defaults=cloneDefaults(),governance=resolveGovernanceKnobs({governance:settings.governance??{preset:"default"}});return{...defaults,...settings,item_format:normalizeSettingsItemFormat(settings,defaults),locks:{...defaults.locks,...settings.locks},ids:{...defaults.ids,...settings.ids},agent_identity:structuredClone(settings.agent_identity??defaults.agent_identity),mutation_guard:{...defaults.mutation_guard,...settings.mutation_guard},checkpoints:{...defaults.checkpoints,...settings.checkpoints},output:{...defaults.output,...settings.output},ux:{...defaults.ux,...settings.ux},history:{...defaults.history,...settings.history,compact_policy:{...defaults.history.compact_policy,...settings.history?.compact_policy}},validation:buildValidationSettings(settings,defaults,governance),governance,workflow:{definition_of_done:[...settings.workflow?.definition_of_done??defaults.workflow.definition_of_done]},testing:{record_results_to_items:settings.testing?.record_results_to_items??defaults.testing.record_results_to_items,allow_untrusted_linked_tests:settings.testing?.allow_untrusted_linked_tests??defaults.testing.allow_untrusted_linked_tests},telemetry:buildTelemetrySettings(settings,defaults),agent_guidance:normalizeAgentGuidanceSettings(settings.agent_guidance??defaults.agent_guidance),item_types:{definitions:normalizeItemTypeDefinitions(settings.item_types?.definitions)},schema:normalizeRuntimeSchemaSettings(settings.schema??defaults.schema),context:buildContextSettings(settings,defaults),extensions:{enabled:[...settings.extensions.enabled],disabled:[...settings.extensions.disabled],policy:normalizeExtensionPolicySettings(settings.extensions.policy??defaults.extensions.policy)},search:buildSearchSettings(settings,defaults),providers:buildProviderSettings(settings,defaults),vector_store:buildVectorStoreSettings(settings,defaults)}}function orderSerializedSettingsSections(ordered){ordered.agent_identity=orderObject(ordered.agent_identity,["probes_enabled","identity_vocabulary","harness_signals"]);const orderedAgentIdentity=ordered.agent_identity;Object.hasOwn(orderedAgentIdentity,"identity_vocabulary")&&(orderedAgentIdentity.identity_vocabulary=orderObject(recordOrEmpty(orderedAgentIdentity.identity_vocabulary),["version","aliases"])),ordered.agent_identity.harness_signals=arrayOrEmpty(ordered.agent_identity.harness_signals).map(entry=>orderObject(recordOrEmpty(entry),["harness","environment_keys","model_environment_keys","session_environment_keys","provenance_environment_keys","provenance_resolvers","provenance_unavailable_dimensions","argv_markers","client_names"])),ordered.locks=orderObject(ordered.locks,["ttl_seconds","wait_ms"]),ordered.ids=orderObject(ordered.ids,["token_length"]),ordered.mutation_guard=orderObject(ordered.mutation_guard,["require_attributed_author","secret_guard","stale_in_progress_hours"]),ordered.checkpoints=orderObject(ordered.checkpoints,["retention_days"]),ordered.output=orderObject(ordered.output,["default_format"]),ordered.ux=orderObject(ordered.ux,["deprecation_hints"]),ordered.history=orderObject(ordered.history,["missing_stream","compact_policy"]),ordered.validation=orderObject(ordered.validation,["sprint_release_format","parent_reference","metadata_profile","metadata_required_fields","lifecycle_stale_blocker_reason_patterns","lifecycle_closure_like_blocked_reason_patterns","lifecycle_closure_like_resolution_patterns","lifecycle_closure_like_actual_result_patterns","estimate_defaults_by_type"]),ordered.governance=orderObject(ordered.governance,["preset","ownership_enforcement","create_mode_default","close_validation_default","require_close_reason","parent_reference","metadata_profile","force_required_for_stale_lock","create_default_type","workflow_enforcement","duplicate_detection_mode","duplicate_detection_threshold","duplicate_detection_limit"]),ordered.workflow=orderObject(ordered.workflow,["definition_of_done"]),ordered.testing=orderObject(ordered.testing,["record_results_to_items","allow_untrusted_linked_tests"]),ordered.telemetry=orderObject(ordered.telemetry,["enabled","first_run_prompt_completed","capture_level","endpoint","installation_id","retention_days"]),ordered.agent_guidance=orderObject(ordered.agent_guidance,["prompt_completed","declined","declined_at","template_version","last_checked_files"]),ordered.item_types=orderObject(ordered.item_types,["definitions"]),ordered.schema=orderObject(ordered.schema,["version","files","statuses","fields","workflow","type_workflows","unknown_field_policy"]),ordered.schema.files=orderObject(recordOrEmpty(ordered.schema.files),["types","statuses","fields","workflows"]),ordered.schema.workflow=orderObject(recordOrEmpty(ordered.schema.workflow),["draft_status","open_status","in_progress_status","blocked_status","close_status","canceled_status"]),ordered.context=orderObject(ordered.context,["default_depth","activity_limit","stale_threshold_days","sections"]),ordered.context.sections=orderObject(recordOrEmpty(ordered.context.sections),["hierarchy","activity","progress","blockers","files","workload","staleness","tests"]),ordered.extensions=orderObject(ordered.extensions,["enabled","disabled","policy"]),ordered.extensions.policy=orderObject(recordOrEmpty(ordered.extensions.policy),["mode","trust_mode","pm_max_version_exceeded_mode","require_provenance","trusted_extensions","default_sandbox_profile","allowed_extensions","blocked_extensions","allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services","extension_overrides"]),ordered.extensions.policy.extension_overrides=arrayOrEmpty(ordered.extensions.policy.extension_overrides).map(entry=>orderObject(recordOrEmpty(entry),["name","disabled","require_trusted","require_provenance","sandbox_profile","allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"])),ordered.search=orderObject(ordered.search,["score_threshold","hybrid_semantic_weight","max_results","embedding_model","embedding_corpus_max_characters","embedding_batch_size","embedding_timeout_ms","scanner_max_batch_retries","provider","default_mode","mutation_refresh_policy","query_expansion","rerank"]),ordered.search.query_expansion=orderObject(recordOrEmpty(ordered.search.query_expansion),["enabled","provider"]),ordered.search.rerank=orderObject(recordOrEmpty(ordered.search.rerank),["enabled","model","top_k"]),ordered.providers=orderObject(ordered.providers,["openai","ollama"]),ordered.providers.openai=orderObject(recordOrEmpty(ordered.providers.openai),["base_url","api_key","model"]),ordered.providers.ollama=orderObject(recordOrEmpty(ordered.providers.ollama),["base_url","model"]),ordered.vector_store=orderObject(ordered.vector_store,["adapter","collection_name","qdrant","lancedb"]),ordered.vector_store.qdrant=orderObject(recordOrEmpty(ordered.vector_store.qdrant),["url","api_key"]),ordered.vector_store.lancedb=orderObject(recordOrEmpty(ordered.vector_store.lancedb),["path"])}function buildSerializeBaseSettings(settings){return{...settings,locks:valueOrDefault(settings.locks,SETTINGS_DEFAULTS.locks),ids:valueOrDefault(settings.ids,SETTINGS_DEFAULTS.ids),agent_identity:valueOrDefault(settings.agent_identity,SETTINGS_DEFAULTS.agent_identity),mutation_guard:valueOrDefault(settings.mutation_guard,SETTINGS_DEFAULTS.mutation_guard),checkpoints:valueOrDefault(settings.checkpoints,SETTINGS_DEFAULTS.checkpoints),output:valueOrDefault(settings.output,SETTINGS_DEFAULTS.output),ux:valueOrDefault(settings.ux,SETTINGS_DEFAULTS.ux),history:valueOrDefault(settings.history,SETTINGS_DEFAULTS.history),validation:valueOrDefault(settings.validation,SETTINGS_DEFAULTS.validation),workflow:valueOrDefault(settings.workflow,SETTINGS_DEFAULTS.workflow),testing:valueOrDefault(settings.testing,SETTINGS_DEFAULTS.testing),telemetry:valueOrDefault(settings.telemetry,SETTINGS_DEFAULTS.telemetry),agent_guidance:valueOrDefault(settings.agent_guidance,SETTINGS_DEFAULTS.agent_guidance),item_types:valueOrDefault(settings.item_types,SETTINGS_DEFAULTS.item_types),schema:valueOrDefault(settings.schema,SETTINGS_DEFAULTS.schema),context:valueOrDefault(settings.context,SETTINGS_DEFAULTS.context),extensions:valueOrDefault(settings.extensions,SETTINGS_DEFAULTS.extensions),search:valueOrDefault(settings.search,SETTINGS_DEFAULTS.search),providers:valueOrDefault(settings.providers,SETTINGS_DEFAULTS.providers),vector_store:valueOrDefault(settings.vector_store,SETTINGS_DEFAULTS.vector_store)}}function buildSerializedValidationSettings(baseSettings,governance){return{...baseSettings.validation,parent_reference:governance.parent_reference,metadata_profile:governance.metadata_profile,metadata_required_fields:normalizeValidationMetadataRequiredFields(baseSettings.validation?.metadata_required_fields),lifecycle_stale_blocker_reason_patterns:normalizeValidationPatternList(baseSettings.validation?.lifecycle_stale_blocker_reason_patterns??SETTINGS_DEFAULTS.validation.lifecycle_stale_blocker_reason_patterns),lifecycle_closure_like_blocked_reason_patterns:normalizeValidationPatternList(baseSettings.validation?.lifecycle_closure_like_blocked_reason_patterns??SETTINGS_DEFAULTS.validation.lifecycle_closure_like_blocked_reason_patterns),lifecycle_closure_like_resolution_patterns:normalizeValidationPatternList(baseSettings.validation?.lifecycle_closure_like_resolution_patterns??SETTINGS_DEFAULTS.validation.lifecycle_closure_like_resolution_patterns),lifecycle_closure_like_actual_result_patterns:normalizeValidationPatternList(baseSettings.validation?.lifecycle_closure_like_actual_result_patterns??SETTINGS_DEFAULTS.validation.lifecycle_closure_like_actual_result_patterns),estimate_defaults_by_type:normalizeEstimateDefaultOverrides(baseSettings.validation?.estimate_defaults_by_type)}}function buildSerializedSearchSettings(baseSettings){return{...SETTINGS_DEFAULTS.search,...baseSettings.search,default_mode:normalizeSearchDefaultMode(baseSettings.search?.default_mode),mutation_refresh_policy:normalizeSearchMutationRefreshPolicy(baseSettings.search?.mutation_refresh_policy),query_expansion:{...SETTINGS_DEFAULTS.search.query_expansion,...baseSettings.search?.query_expansion,enabled:normalizeSearchQueryExpansionEnabled(baseSettings.search?.query_expansion?.enabled),provider:normalizeSearchQueryExpansionProvider(baseSettings.search?.query_expansion?.provider)},rerank:{...SETTINGS_DEFAULTS.search.rerank,...baseSettings.search?.rerank,enabled:normalizeSearchRerankEnabled(baseSettings.search?.rerank?.enabled),model:normalizeSearchRerankModel(baseSettings.search?.rerank?.model),top_k:normalizeSearchRerankTopK(baseSettings.search?.rerank?.top_k)}}}function buildSerializedContextSettings(baseSettings){return{default_depth:baseSettings.context?.default_depth??SETTINGS_DEFAULTS.context.default_depth,activity_limit:baseSettings.context?.activity_limit??SETTINGS_DEFAULTS.context.activity_limit,stale_threshold_days:baseSettings.context?.stale_threshold_days??SETTINGS_DEFAULTS.context.stale_threshold_days,sections:{...SETTINGS_DEFAULTS.context.sections,...baseSettings.context?.sections}}}function buildSerializedVectorStoreSettings(baseSettings){return{...baseSettings.vector_store,adapter:baseSettings.vector_store?.adapter??SETTINGS_DEFAULTS.vector_store.adapter,collection_name:normalizeVectorStoreCollectionName(baseSettings.vector_store?.collection_name),qdrant:{...baseSettings.vector_store?.qdrant},lancedb:{...baseSettings.vector_store?.lancedb}}}function buildNormalizedSettingsForSerialization(baseSettings,governance,normalizedSchema,persistedFileBackedSections){return{...baseSettings,item_format:"toon",validation:buildSerializedValidationSettings(baseSettings,governance),governance,agent_guidance:normalizeAgentGuidanceSettings(baseSettings.agent_guidance),item_types:{definitions:persistedFileBackedSections.item_type_definitions},schema:{...normalizedSchema,statuses:persistedFileBackedSections.schema_statuses,fields:persistedFileBackedSections.schema_fields,type_workflows:persistedFileBackedSections.schema_type_workflows},search:buildSerializedSearchSettings(baseSettings),context:buildSerializedContextSettings(baseSettings),extensions:{enabled:normalizeStringList(baseSettings.extensions?.enabled),disabled:normalizeStringList(baseSettings.extensions?.disabled),policy:normalizeExtensionPolicySettings(baseSettings.extensions?.policy)},vector_store:buildSerializedVectorStoreSettings(baseSettings)}}function overlayPresentSettingsSource(target,source){for(const key of Object.keys(source)){const value=Reflect.get(source,key),existing=target[key];typeof value=="object"&&value!==null&&!Array.isArray(value)&&typeof existing=="object"&&existing!==null&&!Array.isArray(existing)?overlayPresentSettingsSource(existing,value):target[key]=structuredClone(value)}}function applySettingsDelta(target,baseline,current){const keys=new Set([...Object.keys(baseline),...Object.keys(current)]);for(const key of keys){const before=baseline[key],after=current[key];if(!stableValueEquals(before,after)){if(after===void 0){delete target[key];continue}if(typeof before=="object"&&before!==null&&!Array.isArray(before)&&typeof after=="object"&&after!==null&&!Array.isArray(after)){const existing=target[key],nestedTarget=typeof existing=="object"&&existing!==null&&!Array.isArray(existing)?existing:{};applySettingsDelta(nestedTarget,before,after),Object.keys(nestedTarget).length>0?target[key]=nestedTarget:delete target[key];continue}target[key]=structuredClone(after)}}}const SETTINGS_TOP_LEVEL_KEY_ORDER=["version","id_prefix","ids","author_default","agent_identity","mutation_guard","item_format","locks","checkpoints","output","ux","history","validation","governance","workflow","testing","telemetry","agent_guidance","item_types","schema","context","extensions","search","providers","vector_store"];function buildOrderedSettingsForSerialization(settings,persistSource){const baseSettings=buildSerializeBaseSettings(settings),governance=resolveGovernanceKnobs(baseSettings),normalizedSchema=normalizeRuntimeSchemaSettings(baseSettings.schema),persistedFileBackedSections=resolvePersistedFileBackedSchemaSections(baseSettings,persistSource),normalizedSettings=buildNormalizedSettingsForSerialization(baseSettings,governance,normalizedSchema,persistedFileBackedSections),ordered=orderObject({...normalizedSettings,governance:normalizeGovernanceForPersist(governance)},SETTINGS_TOP_LEVEL_KEY_ORDER);return orderSerializedSettingsSections(ordered),ordered}function serializeSettings(settings,options={}){const persistSource=options.source===void 0?options.persist_source:buildSettingsPersistSourceSnapshot(options.source.validated,mergeSettings(options.source.validated)),ordered=buildOrderedSettingsForSerialization(settings,persistSource);if(persistSource){const baselineSettings=mergeSettings(persistSource.source_settings);baselineSettings.item_types={definitions:structuredClone(persistSource.runtime_item_type_definitions)},baselineSettings.schema={...baselineSettings.schema,statuses:structuredClone(persistSource.runtime_schema_statuses),fields:structuredClone(persistSource.runtime_schema_fields),type_workflows:structuredClone(persistSource.runtime_schema_type_workflows)};const baseline=buildOrderedSettingsForSerialization(baselineSettings,persistSource);options.source!==void 0&&overlayPresentSettingsSource(baseline,options.source.validated);const sparse=structuredClone(options.source===void 0?persistSource.source_settings:options.source.raw);return applySettingsDelta(sparse,baseline,ordered),`${JSON.stringify(orderObject(sparse,SETTINGS_TOP_LEVEL_KEY_ORDER),null,2)}
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="f4308e20-251e-52d4-81a4-044e910e87fa")}catch{}})();import{AsyncLocalStorage}from"node:async_hooks";import{lstat,realpath}from"node:fs/promises";import path from"node:path";import{validateSettings}from"./settings-validator.js";import{runActiveOnReadHooks,runActiveOnWriteHooks}from"../extensions/index.js";import{EXIT_CODE,GOVERNANCE_PRESET_DEFAULTS,SETTINGS_DEFAULTS}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{resolveAuthor}from"../shared/author.js";import{isFileAbsentError,readFileIfExists,readRegularFile,transactionPreviewNonRegularFileError}from"../fs/fs-utils.js";import{mutateWorkspaceJsonWithHistory}from"../history/workspace-history.js";import{reconcileSettingsSnapshot}from"./settings-concurrency.js";import{DEFAULT_RUNTIME_SCHEMA_FILE_PATHS,filePathForSchemaSection,loadRuntimeSchemaFromOptionalFiles,normalizeRuntimeSchemaSettings}from"../schema/runtime-schema.js";import{getSettingsPath}from"./paths.js";import{orderObject,stableValueEquals}from"../shared/serialization.js";import{normalizeItemTypeDefinition}from"../item/item-type-definition.js";import{normalizeEstimateDefaultOverrides}from"../validate/estimate-defaults.js";import{clearSettingsReadCache,collectSettingsReadCacheSignatures,getSettingsReadCacheEntry,setSettingsReadCacheEntry,settingsReadCacheSignaturesEqual}from"./settings-read-cache.js";const configurationOnlySettingsRoots=new AsyncLocalStorage;async function runWithConfigurationOnlySettings(pmRoot,run,isEnabled=()=>!0){const roots=new Set([path.resolve(pmRoot)]);try{roots.add(await realpath(pmRoot))}catch{}return configurationOnlySettingsRoots.run([...configurationOnlySettingsRoots.getStore()??[],[roots,isEnabled]],run)}function isConfigurationOnlySettingsRead(pmRoot){const root=path.resolve(pmRoot);return configurationOnlySettingsRoots.getStore()?.some(([roots,isEnabled])=>roots.has(root)&&isEnabled())??!1}const SETTINGS_WRITE_OP="settings:write",SETTINGS_PERSIST_SOURCE_SYMBOL=Symbol("pm.settings.persist_source"),MAX_VECTOR_STORE_COLLECTION_NAME_LENGTH=128,DUPLICATE_DETECTION_MODES=new Set(["off","advisory","strict"]);function resolveGovernanceKnobsFromPreset(preset){return structuredClone(GOVERNANCE_PRESET_DEFAULTS[preset])}function normalizeGovernancePreset(value){return value==="minimal"||value==="default"||value==="strict"||value==="custom"?value:SETTINGS_DEFAULTS.governance.preset}function withGovernanceExtras(base,governance){const createDefaultType=typeof governance.create_default_type=="string"?governance.create_default_type.trim():void 0;return createDefaultType&&createDefaultType.length>0&&(base.create_default_type=createDefaultType),(governance.workflow_enforcement==="off"||governance.workflow_enforcement==="warn"||governance.workflow_enforcement==="strict")&&(base.workflow_enforcement=governance.workflow_enforcement),governance.require_close_reason===!1&&(base.require_close_reason=!1),base.duplicate_detection_mode=governance.duplicate_detection_mode,base.duplicate_detection_threshold=governance.duplicate_detection_threshold,base.duplicate_detection_limit=governance.duplicate_detection_limit,base}function normalizeGovernanceForPersist(governance){return governance.preset==="custom"?withGovernanceExtras({preset:"custom",ownership_enforcement:governance.ownership_enforcement,create_mode_default:governance.create_mode_default,close_validation_default:governance.close_validation_default,parent_reference:governance.parent_reference,metadata_profile:governance.metadata_profile,force_required_for_stale_lock:governance.force_required_for_stale_lock},governance):withGovernanceExtras({preset:governance.preset},governance)}function resolveGovernanceExtras(rawGovernance){const createDefaultType=typeof rawGovernance.create_default_type=="string"?rawGovernance.create_default_type.trim():void 0,extras={};createDefaultType&&createDefaultType.length>0&&(extras.create_default_type=createDefaultType),(rawGovernance.workflow_enforcement==="off"||rawGovernance.workflow_enforcement==="warn"||rawGovernance.workflow_enforcement==="strict")&&(extras.workflow_enforcement=rawGovernance.workflow_enforcement),typeof rawGovernance.require_close_reason=="boolean"&&(extras.require_close_reason=rawGovernance.require_close_reason),DUPLICATE_DETECTION_MODES.has(String(rawGovernance.duplicate_detection_mode))&&(extras.duplicate_detection_mode=rawGovernance.duplicate_detection_mode);const threshold=rawGovernance.duplicate_detection_threshold;[typeof threshold=="number",Number.isFinite(threshold),Number(threshold)>=0,Number(threshold)<=1].every(Boolean)&&(extras.duplicate_detection_threshold=threshold);const limit=rawGovernance.duplicate_detection_limit;return[typeof limit=="number",Number.isSafeInteger(limit),Number(limit)>=0,Number(limit)<=20].every(Boolean)&&(extras.duplicate_detection_limit=limit),extras}function resolveGovernanceKnobs(settings){const rawGovernance=settings.governance??{},preset=normalizeGovernancePreset(rawGovernance.preset),extras=resolveGovernanceExtras(rawGovernance);if(preset==="custom"){const baseline2=resolveGovernanceKnobsFromPreset("default"),requireCloseReason2=extras.require_close_reason??baseline2.require_close_reason;return{preset,ownership_enforcement:rawGovernance.ownership_enforcement??baseline2.ownership_enforcement,create_mode_default:rawGovernance.create_mode_default??baseline2.create_mode_default,close_validation_default:rawGovernance.close_validation_default??baseline2.close_validation_default,parent_reference:rawGovernance.parent_reference??baseline2.parent_reference,metadata_profile:rawGovernance.metadata_profile??baseline2.metadata_profile,force_required_for_stale_lock:rawGovernance.force_required_for_stale_lock??baseline2.force_required_for_stale_lock,...extras,require_close_reason:requireCloseReason2,duplicate_detection_mode:extras.duplicate_detection_mode??baseline2.duplicate_detection_mode,duplicate_detection_threshold:extras.duplicate_detection_threshold??baseline2.duplicate_detection_threshold,duplicate_detection_limit:extras.duplicate_detection_limit??baseline2.duplicate_detection_limit}}const baseline=resolveGovernanceKnobsFromPreset(preset),requireCloseReason=extras.require_close_reason??baseline.require_close_reason;return{preset,...baseline,...extras,require_close_reason:requireCloseReason}}function cloneDefaults(){return structuredClone(SETTINGS_DEFAULTS)}function normalizeSearchMutationRefreshPolicy(value){return value==="cache_only"||value==="semantic_configured"||value==="semantic_auto"?value:SETTINGS_DEFAULTS.search.mutation_refresh_policy}function normalizeSearchDefaultMode(value){return value==="auto"||value==="keyword"||value==="semantic"||value==="hybrid"?value:"auto"}function normalizeSearchQueryExpansionEnabled(value){return typeof value=="boolean"?value:SETTINGS_DEFAULTS.search.query_expansion.enabled}function normalizeSearchQueryExpansionProvider(value){return typeof value!="string"?SETTINGS_DEFAULTS.search.query_expansion.provider:value.trim()}function normalizeSearchRerankEnabled(value){return typeof value=="boolean"?value:SETTINGS_DEFAULTS.search.rerank.enabled}function normalizeSearchRerankModel(value){return typeof value!="string"?SETTINGS_DEFAULTS.search.rerank.model:value.trim()}function normalizeSearchRerankTopK(value){return typeof value=="number"&&Number.isFinite(value)&&Number.isInteger(value)&&value>0?value:SETTINGS_DEFAULTS.search.rerank.top_k}function normalizeVectorStoreCollectionName(value){if(typeof value!="string")return SETTINGS_DEFAULTS.vector_store.collection_name;const truncated=value.trim().replaceAll(/[^a-zA-Z0-9_-]/g,"_").slice(0,MAX_VECTOR_STORE_COLLECTION_NAME_LENGTH);return truncated.length>0?truncated:SETTINGS_DEFAULTS.vector_store.collection_name}function cloneOptionalArray(value){return{present:Array.isArray(value),values:Array.isArray(value)?structuredClone(value):[]}}function buildSettingsPersistSourceSnapshot(parsedSettings,runtimeSettings){const sourceSchema=parsedSettings.schema,sourceStatuses=cloneOptionalArray(sourceSchema?.statuses),sourceFields=cloneOptionalArray(sourceSchema?.fields),sourceTypeWorkflows=cloneOptionalArray(sourceSchema?.type_workflows);return{persisted_settings:structuredClone(parsedSettings),source_settings:structuredClone(parsedSettings),has_source_item_type_definitions:Array.isArray(parsedSettings.item_types?.definitions),source_item_type_definitions:normalizeItemTypeDefinitions(parsedSettings.item_types?.definitions),has_source_schema_statuses:sourceStatuses.present,source_schema_statuses:sourceStatuses.values,has_source_schema_fields:sourceFields.present,source_schema_fields:sourceFields.values,has_source_schema_type_workflows:sourceTypeWorkflows.present,source_schema_type_workflows:sourceTypeWorkflows.values,runtime_item_type_definitions:normalizeItemTypeDefinitions(runtimeSettings.item_types?.definitions),runtime_schema_statuses:structuredClone(runtimeSettings.schema.statuses),runtime_schema_fields:structuredClone(runtimeSettings.schema.fields),runtime_schema_type_workflows:structuredClone(runtimeSettings.schema.type_workflows??[])}}function attachSettingsPersistSourceSnapshot(settings,source){Object.defineProperty(settings,SETTINGS_PERSIST_SOURCE_SYMBOL,{value:source,writable:!0,configurable:!0,enumerable:!1})}function getSettingsPersistSourceSnapshot(settings){const candidate=settings[SETTINGS_PERSIST_SOURCE_SYMBOL];if(!(!candidate||typeof candidate!="object"))return candidate}function persistSelectedItemFormat(settings){const source=getSettingsPersistSourceSnapshot(settings);if(source){const detachedSource=structuredClone(source);detachedSource.source_settings.item_format=settings.item_format,attachSettingsPersistSourceSnapshot(settings,detachedSource)}}function cloneSettingsReadResult(result){const clonedSettings=structuredClone(result.settings),persistSource=getSettingsPersistSourceSnapshot(result.settings);return persistSource&&attachSettingsPersistSourceSnapshot(clonedSettings,persistSource),{settings:clonedSettings,metadata:{has_explicit_item_format:result.metadata.has_explicit_item_format},warnings:[...result.warnings]}}function resolveSettingsReadTrackedPaths(pmRoot,schema,settingsPath){const normalizedSchema=normalizeRuntimeSchemaSettings(schema);return[settingsPath,filePathForSchemaSection(pmRoot,normalizedSchema.files.types,DEFAULT_RUNTIME_SCHEMA_FILE_PATHS.types),filePathForSchemaSection(pmRoot,normalizedSchema.files.statuses,DEFAULT_RUNTIME_SCHEMA_FILE_PATHS.statuses),filePathForSchemaSection(pmRoot,normalizedSchema.files.fields,DEFAULT_RUNTIME_SCHEMA_FILE_PATHS.fields),filePathForSchemaSection(pmRoot,normalizedSchema.files.workflows,DEFAULT_RUNTIME_SCHEMA_FILE_PATHS.workflows)]}async function cacheSettingsReadResult(pmRoot,trackedPaths,result){const signatures=await collectSettingsReadCacheSignatures(trackedPaths);setSettingsReadCacheEntry(pmRoot,{tracked_paths:trackedPaths,signatures,value:cloneSettingsReadResult(result)})}async function cacheSettingsReadResultSafe(pmRoot,trackedPaths,result){try{await cacheSettingsReadResult(pmRoot,trackedPaths,result)}catch{clearSettingsReadCache(pmRoot)}}function findSettingsReadCacheSignature(signatures,targetPath){return signatures.find(signature=>signature.path===targetPath)}function selectedSettingsReadCacheSignaturesEqual(before,after,targetPaths){for(const targetPath of targetPaths){const beforeSignature=findSettingsReadCacheSignature(before,targetPath),afterSignature=findSettingsReadCacheSignature(after,targetPath);if(!beforeSignature||!afterSignature||!settingsReadCacheSignaturesEqual([beforeSignature],[afterSignature]))return!1}return!0}async function cacheSettingsReadResultIfStable(pmRoot,trackedPaths,result,stableSignatures,stablePaths){try{const currentSignatures=await collectSettingsReadCacheSignatures(trackedPaths);if(!selectedSettingsReadCacheSignaturesEqual(stableSignatures,currentSignatures,stablePaths)){clearSettingsReadCache(pmRoot);return}setSettingsReadCacheEntry(pmRoot,{tracked_paths:trackedPaths,signatures:currentSignatures,value:cloneSettingsReadResult(result)})}catch{clearSettingsReadCache(pmRoot)}}function resolvePersistedFileBackedSchemaSections(settings,source){const normalizedSchema=normalizeRuntimeSchemaSettings(settings.schema),currentItemTypeDefinitions=normalizeItemTypeDefinitions(settings.item_types?.definitions);if(!source)return{item_type_definitions:currentItemTypeDefinitions,schema_statuses:normalizedSchema.statuses,schema_fields:normalizedSchema.fields,schema_type_workflows:normalizedSchema.type_workflows};const currentTypeWorkflows=normalizedSchema.type_workflows??[],itemTypeDefinitionsUnchanged=stableValueEquals(currentItemTypeDefinitions,source.runtime_item_type_definitions),schemaStatusesUnchanged=stableValueEquals(normalizedSchema.statuses,source.runtime_schema_statuses),schemaFieldsUnchanged=stableValueEquals(normalizedSchema.fields,source.runtime_schema_fields),schemaTypeWorkflowsUnchanged=stableValueEquals(currentTypeWorkflows,source.runtime_schema_type_workflows);return{item_type_definitions:itemTypeDefinitionsUnchanged?source.has_source_item_type_definitions?normalizeItemTypeDefinitions(source.source_item_type_definitions):[]:currentItemTypeDefinitions,schema_statuses:schemaStatusesUnchanged?source.has_source_schema_statuses?structuredClone(source.source_schema_statuses):[]:normalizedSchema.statuses,schema_fields:schemaFieldsUnchanged?source.has_source_schema_fields?structuredClone(source.source_schema_fields):[]:normalizedSchema.fields,schema_type_workflows:schemaTypeWorkflowsUnchanged?source.has_source_schema_type_workflows?structuredClone(source.source_schema_type_workflows):void 0:normalizedSchema.type_workflows}}function buildFallbackSettingsReadResult(warning){return{settings:cloneDefaults(),metadata:{has_explicit_item_format:!1},warnings:warning?[warning]:[]}}function hasExplicitItemFormat(raw){if(typeof raw!="object"||raw===null||Array.isArray(raw))return!1;const itemFormat=raw.item_format;return itemFormat==="toon"||itemFormat==="json_markdown"}function normalizeStringList(values){return[...new Set((values??[]).map(value=>value.trim()).filter(value=>value.length>0))].sort((left,right)=>left.localeCompare(right))}function normalizeAgentGuidanceSettings(value){const defaults=SETTINGS_DEFAULTS.agent_guidance,templateVersion=value?.template_version;return{prompt_completed:value?.prompt_completed===!0,declined:value?.declined===!0,declined_at:typeof value?.declined_at=="string"?value.declined_at:defaults.declined_at,template_version:typeof templateVersion=="number"&&Number.isInteger(templateVersion)&&templateVersion>0?templateVersion:defaults.template_version,last_checked_files:normalizeStringList(value?.last_checked_files??defaults.last_checked_files)}}function normalizeLowerStringList(values){return[...new Set((values??[]).map(value=>value.trim().toLowerCase()).filter(value=>value.length>0))].sort((left,right)=>left.localeCompare(right))}function normalizeExtensionPolicyMode(value){return value==="off"||value==="warn"||value==="enforce"?value:SETTINGS_DEFAULTS.extensions.policy.mode}function normalizeExtensionTrustMode(value){return value==="off"||value==="warn"||value==="enforce"?value:SETTINGS_DEFAULTS.extensions.policy.trust_mode}function normalizeExtensionSandboxProfile(value){return value==="none"||value==="restricted"||value==="strict"?value:SETTINGS_DEFAULTS.extensions.policy.default_sandbox_profile}function normalizeExtensionPolicyOverride(override){const name=override.name.trim().toLowerCase();if(name.length===0)return null;const normalized={name};override.disabled===!0&&(normalized.disabled=!0),override.require_trusted===!0&&(normalized.require_trusted=!0),override.require_provenance===!0&&(normalized.require_provenance=!0),override.sandbox_profile!==void 0&&(normalized.sandbox_profile=normalizeExtensionSandboxProfile(override.sandbox_profile));const allowedCapabilities=normalizeLowerStringList(override.allowed_capabilities),blockedCapabilities=normalizeLowerStringList(override.blocked_capabilities),allowedSurfaces=normalizeLowerStringList(override.allowed_surfaces),blockedSurfaces=normalizeLowerStringList(override.blocked_surfaces),allowedCommands=normalizeLowerStringList(override.allowed_commands),blockedCommands=normalizeLowerStringList(override.blocked_commands),allowedActions=normalizeLowerStringList(override.allowed_actions),blockedActions=normalizeLowerStringList(override.blocked_actions),allowedServices=normalizeLowerStringList(override.allowed_services),blockedServices=normalizeLowerStringList(override.blocked_services);return allowedCapabilities.length>0&&(normalized.allowed_capabilities=allowedCapabilities),blockedCapabilities.length>0&&(normalized.blocked_capabilities=blockedCapabilities),allowedSurfaces.length>0&&(normalized.allowed_surfaces=allowedSurfaces),blockedSurfaces.length>0&&(normalized.blocked_surfaces=blockedSurfaces),allowedCommands.length>0&&(normalized.allowed_commands=allowedCommands),blockedCommands.length>0&&(normalized.blocked_commands=blockedCommands),allowedActions.length>0&&(normalized.allowed_actions=allowedActions),blockedActions.length>0&&(normalized.blocked_actions=blockedActions),allowedServices.length>0&&(normalized.allowed_services=allowedServices),blockedServices.length>0&&(normalized.blocked_services=blockedServices),normalized}function normalizeExtensionPolicyOverrides(overrides){const dedupedByName=new Map;for(const override of overrides??[]){const normalized=normalizeExtensionPolicyOverride(override);normalized&&dedupedByName.set(normalized.name,normalized)}return[...dedupedByName.values()].sort((left,right)=>left.name.localeCompare(right.name))}function normalizePmMaxVersionExceededModeValue(value){return value==="block"||value==="warn"?value:void 0}function normalizePmMaxVersionExceededModeSetting(value){if(typeof value=="string")return normalizePmMaxVersionExceededModeValue(value);if(typeof value=="object"&&value!==null&&!Array.isArray(value)){const global2=normalizePmMaxVersionExceededModeValue(value.global),project=normalizePmMaxVersionExceededModeValue(value.project);return global2===void 0&&project===void 0?void 0:{...global2!==void 0?{global:global2}:{},...project!==void 0?{project}:{}}}}function normalizeExtensionPolicyList(policy,key){return normalizeLowerStringList(policy?.[key]??SETTINGS_DEFAULTS.extensions.policy[key])}function normalizeExtensionPolicySettings(policy){const pmMaxVersionExceededMode=normalizePmMaxVersionExceededModeSetting(policy?.pm_max_version_exceeded_mode);return{mode:normalizeExtensionPolicyMode(policy?.mode),trust_mode:normalizeExtensionTrustMode(policy?.trust_mode),...pmMaxVersionExceededMode!==void 0?{pm_max_version_exceeded_mode:pmMaxVersionExceededMode}:{},require_provenance:policy?.require_provenance===!0,trusted_extensions:normalizeExtensionPolicyList(policy,"trusted_extensions"),default_sandbox_profile:normalizeExtensionSandboxProfile(policy?.default_sandbox_profile),allowed_extensions:normalizeExtensionPolicyList(policy,"allowed_extensions"),blocked_extensions:normalizeExtensionPolicyList(policy,"blocked_extensions"),allowed_capabilities:normalizeExtensionPolicyList(policy,"allowed_capabilities"),blocked_capabilities:normalizeExtensionPolicyList(policy,"blocked_capabilities"),allowed_surfaces:normalizeExtensionPolicyList(policy,"allowed_surfaces"),blocked_surfaces:normalizeExtensionPolicyList(policy,"blocked_surfaces"),allowed_commands:normalizeExtensionPolicyList(policy,"allowed_commands"),blocked_commands:normalizeExtensionPolicyList(policy,"blocked_commands"),allowed_actions:normalizeExtensionPolicyList(policy,"allowed_actions"),blocked_actions:normalizeExtensionPolicyList(policy,"blocked_actions"),allowed_services:normalizeExtensionPolicyList(policy,"allowed_services"),blocked_services:normalizeExtensionPolicyList(policy,"blocked_services"),extension_overrides:normalizeExtensionPolicyOverrides(policy?.extension_overrides??SETTINGS_DEFAULTS.extensions.policy.extension_overrides)}}function normalizeValidationMetadataRequiredFields(values){return[...new Set((values??[]).map(value=>value.trim().toLowerCase().replaceAll("-","_")))].filter(value=>value.length>0).sort((left,right)=>left.localeCompare(right)).filter(value=>["author","acceptance_criteria","estimated_minutes","close_reason","reviewer","risk","confidence","sprint","release"].includes(value))}function normalizeValidationPatternList(values){return[...new Set((values??[]).map(value=>value.trim().toLowerCase()).filter(value=>value.length>0))].sort((left,right)=>left.localeCompare(right))}function valueOrDefault(value,fallback){return value===void 0?fallback:value}function recordOrEmpty(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)?value:{}}function arrayOrEmpty(value){return Array.isArray(value)?value:[]}function buildValidationSettings(settings,defaults,governance){return{...defaults.validation,...settings.validation,parent_reference:governance.parent_reference,metadata_profile:governance.metadata_profile,metadata_required_fields:normalizeValidationMetadataRequiredFields(settings.validation?.metadata_required_fields),lifecycle_stale_blocker_reason_patterns:normalizeValidationPatternList(settings.validation?.lifecycle_stale_blocker_reason_patterns??defaults.validation.lifecycle_stale_blocker_reason_patterns),lifecycle_closure_like_blocked_reason_patterns:normalizeValidationPatternList(settings.validation?.lifecycle_closure_like_blocked_reason_patterns??defaults.validation.lifecycle_closure_like_blocked_reason_patterns),lifecycle_closure_like_resolution_patterns:normalizeValidationPatternList(settings.validation?.lifecycle_closure_like_resolution_patterns??defaults.validation.lifecycle_closure_like_resolution_patterns),lifecycle_closure_like_actual_result_patterns:normalizeValidationPatternList(settings.validation?.lifecycle_closure_like_actual_result_patterns??defaults.validation.lifecycle_closure_like_actual_result_patterns),estimate_defaults_by_type:normalizeEstimateDefaultOverrides(settings.validation?.estimate_defaults_by_type)}}function buildTelemetrySettings(settings,defaults){return{enabled:settings.telemetry?.enabled??defaults.telemetry.enabled,first_run_prompt_completed:settings.telemetry?.first_run_prompt_completed??defaults.telemetry.first_run_prompt_completed,capture_level:settings.telemetry?.capture_level??defaults.telemetry.capture_level,endpoint:settings.telemetry?.endpoint??defaults.telemetry.endpoint,installation_id:settings.telemetry?.installation_id??defaults.telemetry.installation_id,retention_days:settings.telemetry?.retention_days??defaults.telemetry.retention_days}}function buildSearchSettings(settings,defaults){return{...defaults.search,...settings.search,default_mode:normalizeSearchDefaultMode(settings.search?.default_mode),mutation_refresh_policy:normalizeSearchMutationRefreshPolicy(settings.search?.mutation_refresh_policy),query_expansion:{...defaults.search.query_expansion,...settings.search?.query_expansion,enabled:normalizeSearchQueryExpansionEnabled(settings.search?.query_expansion?.enabled),provider:normalizeSearchQueryExpansionProvider(settings.search?.query_expansion?.provider)},rerank:{...defaults.search.rerank,...settings.search?.rerank,enabled:normalizeSearchRerankEnabled(settings.search?.rerank?.enabled),model:normalizeSearchRerankModel(settings.search?.rerank?.model),top_k:normalizeSearchRerankTopK(settings.search?.rerank?.top_k)}}}function buildVectorStoreSettings(settings,defaults){return{adapter:settings.vector_store.adapter??defaults.vector_store.adapter,collection_name:normalizeVectorStoreCollectionName(settings.vector_store.collection_name),qdrant:{...defaults.vector_store.qdrant,...settings.vector_store.qdrant},lancedb:{...defaults.vector_store.lancedb,...settings.vector_store.lancedb}}}function normalizeSettingsItemFormat(settings,defaults){return settings.item_format==="json_markdown"?"toon":settings.item_format??defaults.item_format}function buildContextSettings(settings,defaults){return{default_depth:settings.context?.default_depth??defaults.context.default_depth,activity_limit:settings.context?.activity_limit??defaults.context.activity_limit,stale_threshold_days:settings.context?.stale_threshold_days??defaults.context.stale_threshold_days,sections:{...defaults.context.sections,...settings.context?.sections}}}function buildProviderSettings(settings,defaults){return{openai:{...defaults.providers.openai,...settings.providers.openai},ollama:{...defaults.providers.ollama,...settings.providers.ollama}}}function normalizeItemTypeDefinitions(definitions){const normalized=(definitions??[]).map(definition=>normalizeItemTypeDefinition(definition)).filter(definition=>definition!==null),dedupedByName=new Map;for(const definition of normalized)dedupedByName.set(definition.name.toLowerCase(),definition);return[...dedupedByName.values()].sort((left,right)=>left.name.localeCompare(right.name))}function mergeSettings(settings){const defaults=cloneDefaults(),governance=resolveGovernanceKnobs({governance:settings.governance??{preset:"default"}});return{...defaults,...settings,item_format:normalizeSettingsItemFormat(settings,defaults),locks:{...defaults.locks,...settings.locks},ids:{...defaults.ids,...settings.ids},agent_identity:structuredClone(settings.agent_identity??defaults.agent_identity),mutation_guard:{...defaults.mutation_guard,...settings.mutation_guard},checkpoints:{...defaults.checkpoints,...settings.checkpoints},output:{...defaults.output,...settings.output},ux:{...defaults.ux,...settings.ux},history:{...defaults.history,...settings.history,compact_policy:{...defaults.history.compact_policy,...settings.history?.compact_policy}},validation:buildValidationSettings(settings,defaults,governance),governance,workflow:{definition_of_done:[...settings.workflow?.definition_of_done??defaults.workflow.definition_of_done]},testing:{record_results_to_items:settings.testing?.record_results_to_items??defaults.testing.record_results_to_items,allow_untrusted_linked_tests:settings.testing?.allow_untrusted_linked_tests??defaults.testing.allow_untrusted_linked_tests},telemetry:buildTelemetrySettings(settings,defaults),agent_guidance:normalizeAgentGuidanceSettings(settings.agent_guidance??defaults.agent_guidance),item_types:{definitions:normalizeItemTypeDefinitions(settings.item_types?.definitions)},schema:normalizeRuntimeSchemaSettings(settings.schema??defaults.schema),context:buildContextSettings(settings,defaults),extensions:{enabled:[...settings.extensions.enabled],disabled:[...settings.extensions.disabled],policy:normalizeExtensionPolicySettings(settings.extensions.policy??defaults.extensions.policy)},search:buildSearchSettings(settings,defaults),providers:buildProviderSettings(settings,defaults),vector_store:buildVectorStoreSettings(settings,defaults)}}function orderSerializedSettingsSections(ordered){ordered.agent_identity=orderObject(ordered.agent_identity,["probes_enabled","identity_vocabulary","harness_signals"]);const orderedAgentIdentity=ordered.agent_identity;Object.hasOwn(orderedAgentIdentity,"identity_vocabulary")&&(orderedAgentIdentity.identity_vocabulary=orderObject(recordOrEmpty(orderedAgentIdentity.identity_vocabulary),["version","aliases"])),ordered.agent_identity.harness_signals=arrayOrEmpty(ordered.agent_identity.harness_signals).map(entry=>orderObject(recordOrEmpty(entry),["harness","environment_keys","model_environment_keys","session_environment_keys","provenance_environment_keys","provenance_resolvers","provenance_unavailable_dimensions","argv_markers","client_names"])),ordered.locks=orderObject(ordered.locks,["ttl_seconds","wait_ms"]),ordered.ids=orderObject(ordered.ids,["token_length"]),ordered.mutation_guard=orderObject(ordered.mutation_guard,["require_attributed_author","secret_guard","stale_in_progress_hours"]),ordered.checkpoints=orderObject(ordered.checkpoints,["retention_days"]),ordered.output=orderObject(ordered.output,["default_format"]),ordered.ux=orderObject(ordered.ux,["deprecation_hints"]),ordered.history=orderObject(ordered.history,["missing_stream","compact_policy"]),ordered.validation=orderObject(ordered.validation,["sprint_release_format","parent_reference","metadata_profile","metadata_required_fields","lifecycle_stale_blocker_reason_patterns","lifecycle_closure_like_blocked_reason_patterns","lifecycle_closure_like_resolution_patterns","lifecycle_closure_like_actual_result_patterns","estimate_defaults_by_type"]),ordered.governance=orderObject(ordered.governance,["preset","ownership_enforcement","create_mode_default","close_validation_default","require_close_reason","parent_reference","metadata_profile","force_required_for_stale_lock","create_default_type","workflow_enforcement","duplicate_detection_mode","duplicate_detection_threshold","duplicate_detection_limit"]),ordered.workflow=orderObject(ordered.workflow,["definition_of_done"]),ordered.testing=orderObject(ordered.testing,["record_results_to_items","allow_untrusted_linked_tests"]),ordered.telemetry=orderObject(ordered.telemetry,["enabled","first_run_prompt_completed","capture_level","endpoint","installation_id","retention_days"]),ordered.agent_guidance=orderObject(ordered.agent_guidance,["prompt_completed","declined","declined_at","template_version","last_checked_files"]),ordered.item_types=orderObject(ordered.item_types,["definitions"]),ordered.schema=orderObject(ordered.schema,["version","files","statuses","fields","workflow","type_workflows","unknown_field_policy"]),ordered.schema.files=orderObject(recordOrEmpty(ordered.schema.files),["types","statuses","fields","workflows"]),ordered.schema.workflow=orderObject(recordOrEmpty(ordered.schema.workflow),["draft_status","open_status","in_progress_status","blocked_status","close_status","canceled_status"]),ordered.context=orderObject(ordered.context,["default_depth","activity_limit","stale_threshold_days","sections"]),ordered.context.sections=orderObject(recordOrEmpty(ordered.context.sections),["hierarchy","activity","progress","blockers","files","workload","staleness","tests"]),ordered.extensions=orderObject(ordered.extensions,["enabled","disabled","policy"]),ordered.extensions.policy=orderObject(recordOrEmpty(ordered.extensions.policy),["mode","trust_mode","pm_max_version_exceeded_mode","require_provenance","trusted_extensions","default_sandbox_profile","allowed_extensions","blocked_extensions","allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services","extension_overrides"]),ordered.extensions.policy.extension_overrides=arrayOrEmpty(ordered.extensions.policy.extension_overrides).map(entry=>orderObject(recordOrEmpty(entry),["name","disabled","require_trusted","require_provenance","sandbox_profile","allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"])),ordered.search=orderObject(ordered.search,["score_threshold","hybrid_semantic_weight","max_results","embedding_model","embedding_corpus_max_characters","embedding_batch_size","embedding_timeout_ms","scanner_max_batch_retries","provider","default_mode","mutation_refresh_policy","query_expansion","rerank"]),ordered.search.query_expansion=orderObject(recordOrEmpty(ordered.search.query_expansion),["enabled","provider"]),ordered.search.rerank=orderObject(recordOrEmpty(ordered.search.rerank),["enabled","model","top_k"]),ordered.providers=orderObject(ordered.providers,["openai","ollama"]),ordered.providers.openai=orderObject(recordOrEmpty(ordered.providers.openai),["base_url","api_key","model"]),ordered.providers.ollama=orderObject(recordOrEmpty(ordered.providers.ollama),["base_url","model"]),ordered.vector_store=orderObject(ordered.vector_store,["adapter","collection_name","qdrant","lancedb"]),ordered.vector_store.qdrant=orderObject(recordOrEmpty(ordered.vector_store.qdrant),["url","api_key"]),ordered.vector_store.lancedb=orderObject(recordOrEmpty(ordered.vector_store.lancedb),["path"])}function buildSerializeBaseSettings(settings){return{...settings,locks:valueOrDefault(settings.locks,SETTINGS_DEFAULTS.locks),ids:valueOrDefault(settings.ids,SETTINGS_DEFAULTS.ids),agent_identity:valueOrDefault(settings.agent_identity,SETTINGS_DEFAULTS.agent_identity),mutation_guard:valueOrDefault(settings.mutation_guard,SETTINGS_DEFAULTS.mutation_guard),checkpoints:valueOrDefault(settings.checkpoints,SETTINGS_DEFAULTS.checkpoints),output:valueOrDefault(settings.output,SETTINGS_DEFAULTS.output),ux:valueOrDefault(settings.ux,SETTINGS_DEFAULTS.ux),history:valueOrDefault(settings.history,SETTINGS_DEFAULTS.history),validation:valueOrDefault(settings.validation,SETTINGS_DEFAULTS.validation),workflow:valueOrDefault(settings.workflow,SETTINGS_DEFAULTS.workflow),testing:valueOrDefault(settings.testing,SETTINGS_DEFAULTS.testing),telemetry:valueOrDefault(settings.telemetry,SETTINGS_DEFAULTS.telemetry),agent_guidance:valueOrDefault(settings.agent_guidance,SETTINGS_DEFAULTS.agent_guidance),item_types:valueOrDefault(settings.item_types,SETTINGS_DEFAULTS.item_types),schema:valueOrDefault(settings.schema,SETTINGS_DEFAULTS.schema),context:valueOrDefault(settings.context,SETTINGS_DEFAULTS.context),extensions:valueOrDefault(settings.extensions,SETTINGS_DEFAULTS.extensions),search:valueOrDefault(settings.search,SETTINGS_DEFAULTS.search),providers:valueOrDefault(settings.providers,SETTINGS_DEFAULTS.providers),vector_store:valueOrDefault(settings.vector_store,SETTINGS_DEFAULTS.vector_store)}}function buildSerializedValidationSettings(baseSettings,governance){return{...baseSettings.validation,parent_reference:governance.parent_reference,metadata_profile:governance.metadata_profile,metadata_required_fields:normalizeValidationMetadataRequiredFields(baseSettings.validation?.metadata_required_fields),lifecycle_stale_blocker_reason_patterns:normalizeValidationPatternList(baseSettings.validation?.lifecycle_stale_blocker_reason_patterns??SETTINGS_DEFAULTS.validation.lifecycle_stale_blocker_reason_patterns),lifecycle_closure_like_blocked_reason_patterns:normalizeValidationPatternList(baseSettings.validation?.lifecycle_closure_like_blocked_reason_patterns??SETTINGS_DEFAULTS.validation.lifecycle_closure_like_blocked_reason_patterns),lifecycle_closure_like_resolution_patterns:normalizeValidationPatternList(baseSettings.validation?.lifecycle_closure_like_resolution_patterns??SETTINGS_DEFAULTS.validation.lifecycle_closure_like_resolution_patterns),lifecycle_closure_like_actual_result_patterns:normalizeValidationPatternList(baseSettings.validation?.lifecycle_closure_like_actual_result_patterns??SETTINGS_DEFAULTS.validation.lifecycle_closure_like_actual_result_patterns),estimate_defaults_by_type:normalizeEstimateDefaultOverrides(baseSettings.validation?.estimate_defaults_by_type)}}function buildSerializedSearchSettings(baseSettings){return{...SETTINGS_DEFAULTS.search,...baseSettings.search,default_mode:normalizeSearchDefaultMode(baseSettings.search?.default_mode),mutation_refresh_policy:normalizeSearchMutationRefreshPolicy(baseSettings.search?.mutation_refresh_policy),query_expansion:{...SETTINGS_DEFAULTS.search.query_expansion,...baseSettings.search?.query_expansion,enabled:normalizeSearchQueryExpansionEnabled(baseSettings.search?.query_expansion?.enabled),provider:normalizeSearchQueryExpansionProvider(baseSettings.search?.query_expansion?.provider)},rerank:{...SETTINGS_DEFAULTS.search.rerank,...baseSettings.search?.rerank,enabled:normalizeSearchRerankEnabled(baseSettings.search?.rerank?.enabled),model:normalizeSearchRerankModel(baseSettings.search?.rerank?.model),top_k:normalizeSearchRerankTopK(baseSettings.search?.rerank?.top_k)}}}function buildSerializedContextSettings(baseSettings){return{default_depth:baseSettings.context?.default_depth??SETTINGS_DEFAULTS.context.default_depth,activity_limit:baseSettings.context?.activity_limit??SETTINGS_DEFAULTS.context.activity_limit,stale_threshold_days:baseSettings.context?.stale_threshold_days??SETTINGS_DEFAULTS.context.stale_threshold_days,sections:{...SETTINGS_DEFAULTS.context.sections,...baseSettings.context?.sections}}}function buildSerializedVectorStoreSettings(baseSettings){return{...baseSettings.vector_store,adapter:baseSettings.vector_store?.adapter??SETTINGS_DEFAULTS.vector_store.adapter,collection_name:normalizeVectorStoreCollectionName(baseSettings.vector_store?.collection_name),qdrant:{...baseSettings.vector_store?.qdrant},lancedb:{...baseSettings.vector_store?.lancedb}}}function buildNormalizedSettingsForSerialization(baseSettings,governance,normalizedSchema,persistedFileBackedSections){return{...baseSettings,item_format:"toon",validation:buildSerializedValidationSettings(baseSettings,governance),governance,agent_guidance:normalizeAgentGuidanceSettings(baseSettings.agent_guidance),item_types:{definitions:persistedFileBackedSections.item_type_definitions},schema:{...normalizedSchema,statuses:persistedFileBackedSections.schema_statuses,fields:persistedFileBackedSections.schema_fields,type_workflows:persistedFileBackedSections.schema_type_workflows},search:buildSerializedSearchSettings(baseSettings),context:buildSerializedContextSettings(baseSettings),extensions:{enabled:normalizeStringList(baseSettings.extensions?.enabled),disabled:normalizeStringList(baseSettings.extensions?.disabled),policy:normalizeExtensionPolicySettings(baseSettings.extensions?.policy)},vector_store:buildSerializedVectorStoreSettings(baseSettings)}}function overlayPresentSettingsSource(target,source){for(const key of Object.keys(source)){const value=Reflect.get(source,key),existing=target[key];typeof value=="object"&&value!==null&&!Array.isArray(value)&&typeof existing=="object"&&existing!==null&&!Array.isArray(existing)?overlayPresentSettingsSource(existing,value):target[key]=structuredClone(value)}}function applySettingsDelta(target,baseline,current){const keys=new Set([...Object.keys(baseline),...Object.keys(current)]);for(const key of keys){const before=baseline[key],after=current[key];if(!stableValueEquals(before,after)){if(after===void 0){delete target[key];continue}if(typeof before=="object"&&before!==null&&!Array.isArray(before)&&typeof after=="object"&&after!==null&&!Array.isArray(after)){const existing=target[key],nestedTarget=typeof existing=="object"&&existing!==null&&!Array.isArray(existing)?existing:{};applySettingsDelta(nestedTarget,before,after),Object.keys(nestedTarget).length>0?target[key]=nestedTarget:delete target[key];continue}target[key]=structuredClone(after)}}}const SETTINGS_TOP_LEVEL_KEY_ORDER=["version","id_prefix","ids","author_default","agent_identity","mutation_guard","item_format","locks","checkpoints","output","ux","history","validation","governance","workflow","testing","telemetry","agent_guidance","item_types","schema","context","extensions","search","providers","vector_store"];function buildOrderedSettingsForSerialization(settings,persistSource){const baseSettings=buildSerializeBaseSettings(settings),governance=resolveGovernanceKnobs(baseSettings),normalizedSchema=normalizeRuntimeSchemaSettings(baseSettings.schema),persistedFileBackedSections=resolvePersistedFileBackedSchemaSections(baseSettings,persistSource),normalizedSettings=buildNormalizedSettingsForSerialization(baseSettings,governance,normalizedSchema,persistedFileBackedSections),ordered=orderObject({...normalizedSettings,governance:normalizeGovernanceForPersist(governance)},SETTINGS_TOP_LEVEL_KEY_ORDER);return orderSerializedSettingsSections(ordered),ordered}function serializeSettings(settings,options={}){const persistSource=options.source===void 0?options.persist_source:buildSettingsPersistSourceSnapshot(options.source.validated,mergeSettings(options.source.validated)),ordered=buildOrderedSettingsForSerialization(settings,persistSource);if(persistSource){const baselineSettings=mergeSettings(persistSource.source_settings);baselineSettings.item_types={definitions:structuredClone(persistSource.runtime_item_type_definitions)},baselineSettings.schema={...baselineSettings.schema,statuses:structuredClone(persistSource.runtime_schema_statuses),fields:structuredClone(persistSource.runtime_schema_fields),type_workflows:structuredClone(persistSource.runtime_schema_type_workflows)};const baseline=buildOrderedSettingsForSerialization(baselineSettings,persistSource);options.source!==void 0&&overlayPresentSettingsSource(baseline,options.source.validated);const sparse=structuredClone(options.source===void 0?persistSource.source_settings:options.source.raw);return applySettingsDelta(sparse,baseline,ordered),`${JSON.stringify(orderObject(sparse,SETTINGS_TOP_LEVEL_KEY_ORDER),null,2)}
2
2
  `}return`${JSON.stringify(ordered,null,2)}
3
- `}async function readConfigurationOnlySettings(pmRoot){let root;try{root=await realpath(pmRoot)}catch(error){if(isFileAbsentError(error))return buildFallbackSettingsReadResult();throw error}const file=getSettingsPath(root);let entry;try{entry=await lstat(file)}catch(error){if(isFileAbsentError(error))return buildFallbackSettingsReadResult();throw error}if(!entry.isFile())throw transactionPreviewNonRegularFileError("settings.json");let raw;try{raw=await readRegularFile(file,transactionPreviewNonRegularFileError("settings.json"))}catch(error){if(isFileAbsentError(error))return buildFallbackSettingsReadResult();throw error}let parsed;try{parsed=JSON.parse(raw)}catch{return buildFallbackSettingsReadResult("settings_read_invalid_json")}const validated=validateSettings(parsed);return validated.success?{settings:mergeSettings(validated.data),metadata:{has_explicit_item_format:hasExplicitItemFormat(parsed)},warnings:validated.data.item_format==="json_markdown"?["settings_item_format_legacy_json_markdown_coerced_to_toon"]:[]}:buildFallbackSettingsReadResult("settings_read_invalid_schema")}async function readSettingsWithMetadata(pmRoot){if(isConfigurationOnlySettingsRead(pmRoot))return readConfigurationOnlySettings(pmRoot);const settingsPath=getSettingsPath(pmRoot);let trackedPathsForFailure=[settingsPath];await runActiveOnReadHooks({path:settingsPath,scope:"project"});const cachedResult=getSettingsReadCacheEntry(pmRoot);if(cachedResult){const currentSignatures=await collectSettingsReadCacheSignatures(cachedResult.tracked_paths);if(settingsReadCacheSignaturesEqual(currentSignatures,cachedResult.signatures))return cloneSettingsReadResult(cachedResult.value)}const settingsOnlySignatures=await collectSettingsReadCacheSignatures([settingsPath]);let raw;try{raw=await readFileIfExists(settingsPath)}catch{return buildFallbackSettingsReadResult("settings_read_fs_error")}if(raw===null){const fallback=buildFallbackSettingsReadResult();return await cacheSettingsReadResultIfStable(pmRoot,[settingsPath],fallback,settingsOnlySignatures,[settingsPath]),fallback}const settingsSignaturesAfterRead=await collectSettingsReadCacheSignatures([settingsPath]);if(!settingsReadCacheSignaturesEqual(settingsOnlySignatures,settingsSignaturesAfterRead))return clearSettingsReadCache(pmRoot),readSettingsWithMetadata(pmRoot);let parsed;try{parsed=JSON.parse(raw)}catch{const fallback=buildFallbackSettingsReadResult("settings_read_invalid_json");return await cacheSettingsReadResultIfStable(pmRoot,[settingsPath],fallback,settingsSignaturesAfterRead,[settingsPath]),fallback}const validated=validateSettings(parsed);if(!validated.success){const fallback=buildFallbackSettingsReadResult("settings_read_invalid_schema");return await cacheSettingsReadResultIfStable(pmRoot,[settingsPath],fallback,settingsSignaturesAfterRead,[settingsPath]),fallback}try{const mergedSettings=mergeSettings(validated.data),trackedPaths=resolveSettingsReadTrackedPaths(pmRoot,mergedSettings.schema,settingsPath);trackedPathsForFailure=trackedPaths;const signaturesBeforeSchemaLoad=await collectSettingsReadCacheSignatures(trackedPaths),schemaScaffold=await ensureRuntimeSchemaFileScaffold(pmRoot,mergedSettings.schema),loadedSchemaSections=await loadRuntimeSchemaFromOptionalFiles(pmRoot,mergedSettings.schema),signaturesAfterSchemaLoad=await collectSettingsReadCacheSignatures(trackedPaths),settings={...mergedSettings,item_types:{definitions:normalizeItemTypeDefinitions([...mergedSettings.item_types.definitions,...arrayOrEmpty(loadedSchemaSections.type_definitions_from_file)])},schema:loadedSchemaSections.schema};attachSettingsPersistSourceSnapshot(settings,buildSettingsPersistSourceSnapshot(validated.data,settings));const result={settings,metadata:{has_explicit_item_format:hasExplicitItemFormat(parsed)},warnings:[...validated.data.item_format==="json_markdown"?["settings_item_format_legacy_json_markdown_coerced_to_toon"]:[],...schemaScaffold.created_paths.map(createdPath=>`runtime_schema_bootstrap_created:${createdPath}`),...loadedSchemaSections.warnings]};return schemaScaffold.created_paths.length===0?settingsReadCacheSignaturesEqual(signaturesBeforeSchemaLoad,signaturesAfterSchemaLoad)?setSettingsReadCacheEntry(pmRoot,{tracked_paths:trackedPaths,signatures:signaturesAfterSchemaLoad,value:cloneSettingsReadResult(result)}):clearSettingsReadCache(pmRoot):clearSettingsReadCache(pmRoot),result}catch{const fallback=buildFallbackSettingsReadResult("settings_read_merge_failed");return await cacheSettingsReadResultSafe(pmRoot,trackedPathsForFailure,fallback),fallback}}async function readSettings(pmRoot){return(await readSettingsWithMetadata(pmRoot)).settings}async function writeSettings(pmRoot,settings,op=SETTINGS_WRITE_OP){const settingsPath=getSettingsPath(pmRoot),source=getSettingsPersistSourceSnapshot(settings),afterRaw=serializeSettings(settings,{persist_source:source}),proposed=JSON.parse(afterRaw);try{await mutateWorkspaceJsonWithHistory({pmRoot,filePath:settingsPath,mutate:beforeRaw=>{let current=null;if(beforeRaw!==null)try{current=JSON.parse(beforeRaw)}catch{throw new PmCliError("Existing settings.json is malformed; the settings write was refused.",EXIT_CODE.USAGE,{code:"settings_write_invalid_existing_json",reason:"existing_settings_json_malformed",why:"Writing defaults over malformed settings could destroy intended project configuration.",nextSteps:["Repair the syntax in .agents/pm/settings.json, then retry the original command.","Run pm health to confirm the settings warning has cleared."]})}return{raw:source?`${JSON.stringify(orderObject(reconcileSettingsSnapshot(source.persisted_settings,proposed,current),SETTINGS_TOP_LEVEL_KEY_ORDER),null,2)}
3
+ `}async function readConfigurationOnlySettings(pmRoot){let root;try{root=await realpath(pmRoot)}catch(error){if(isFileAbsentError(error))return buildFallbackSettingsReadResult();throw error}const file=getSettingsPath(root);let entry;try{entry=await lstat(file)}catch(error){if(isFileAbsentError(error))return buildFallbackSettingsReadResult();throw error}if(!entry.isFile())throw transactionPreviewNonRegularFileError("settings.json");let raw;try{raw=await readRegularFile(file,transactionPreviewNonRegularFileError("settings.json"))}catch(error){if(isFileAbsentError(error))return buildFallbackSettingsReadResult();throw error}let parsed;try{parsed=JSON.parse(raw)}catch{return buildFallbackSettingsReadResult("settings_read_invalid_json")}const validated=validateSettings(parsed);return validated.success?{settings:mergeSettings(validated.data),metadata:{has_explicit_item_format:hasExplicitItemFormat(parsed)},warnings:validated.data.item_format==="json_markdown"?["settings_item_format_legacy_json_markdown_coerced_to_toon"]:[]}:buildFallbackSettingsReadResult("settings_read_invalid_schema")}async function readSettingsWithMetadata(pmRoot){if(isConfigurationOnlySettingsRead(pmRoot))return readConfigurationOnlySettings(pmRoot);const settingsPath=getSettingsPath(pmRoot);let trackedPathsForFailure=[settingsPath];await runActiveOnReadHooks({path:settingsPath,scope:"project"});const cachedResult=getSettingsReadCacheEntry(pmRoot);if(cachedResult){const currentSignatures=await collectSettingsReadCacheSignatures(cachedResult.tracked_paths);if(settingsReadCacheSignaturesEqual(currentSignatures,cachedResult.signatures))return cloneSettingsReadResult(cachedResult.value)}const settingsOnlySignatures=await collectSettingsReadCacheSignatures([settingsPath]);let raw;try{raw=await readFileIfExists(settingsPath)}catch{return buildFallbackSettingsReadResult("settings_read_fs_error")}if(raw===null){const fallback=buildFallbackSettingsReadResult();return await cacheSettingsReadResultIfStable(pmRoot,[settingsPath],fallback,settingsOnlySignatures,[settingsPath]),fallback}const settingsSignaturesAfterRead=await collectSettingsReadCacheSignatures([settingsPath]);if(!settingsReadCacheSignaturesEqual(settingsOnlySignatures,settingsSignaturesAfterRead))return clearSettingsReadCache(pmRoot),readSettingsWithMetadata(pmRoot);let parsed;try{parsed=JSON.parse(raw)}catch{const fallback=buildFallbackSettingsReadResult("settings_read_invalid_json");return await cacheSettingsReadResultIfStable(pmRoot,[settingsPath],fallback,settingsSignaturesAfterRead,[settingsPath]),fallback}const validated=validateSettings(parsed);if(!validated.success){const fallback=buildFallbackSettingsReadResult("settings_read_invalid_schema");return await cacheSettingsReadResultIfStable(pmRoot,[settingsPath],fallback,settingsSignaturesAfterRead,[settingsPath]),fallback}try{const mergedSettings=mergeSettings(validated.data),trackedPaths=resolveSettingsReadTrackedPaths(pmRoot,mergedSettings.schema,settingsPath);trackedPathsForFailure=trackedPaths;const signaturesBeforeSchemaLoad=await collectSettingsReadCacheSignatures(trackedPaths),loadedSchemaSections=await loadRuntimeSchemaFromOptionalFiles(pmRoot,mergedSettings.schema),signaturesAfterSchemaLoad=await collectSettingsReadCacheSignatures(trackedPaths),settings={...mergedSettings,item_types:{definitions:normalizeItemTypeDefinitions([...mergedSettings.item_types.definitions,...arrayOrEmpty(loadedSchemaSections.type_definitions_from_file)])},schema:loadedSchemaSections.schema};attachSettingsPersistSourceSnapshot(settings,buildSettingsPersistSourceSnapshot(validated.data,settings));const result={settings,metadata:{has_explicit_item_format:hasExplicitItemFormat(parsed)},warnings:[...validated.data.item_format==="json_markdown"?["settings_item_format_legacy_json_markdown_coerced_to_toon"]:[],...loadedSchemaSections.warnings]};return settingsReadCacheSignaturesEqual(signaturesBeforeSchemaLoad,signaturesAfterSchemaLoad)?setSettingsReadCacheEntry(pmRoot,{tracked_paths:trackedPaths,signatures:signaturesAfterSchemaLoad,value:cloneSettingsReadResult(result)}):clearSettingsReadCache(pmRoot),result}catch{const fallback=buildFallbackSettingsReadResult("settings_read_merge_failed");return await cacheSettingsReadResultSafe(pmRoot,trackedPathsForFailure,fallback),fallback}}async function readSettings(pmRoot){return(await readSettingsWithMetadata(pmRoot)).settings}async function writeSettings(pmRoot,settings,op=SETTINGS_WRITE_OP){const settingsPath=getSettingsPath(pmRoot),source=getSettingsPersistSourceSnapshot(settings),afterRaw=serializeSettings(settings,{persist_source:source}),proposed=JSON.parse(afterRaw);try{await mutateWorkspaceJsonWithHistory({pmRoot,filePath:settingsPath,mutate:beforeRaw=>{let current=null;if(beforeRaw!==null)try{current=JSON.parse(beforeRaw)}catch{throw new PmCliError("Existing settings.json is malformed; the settings write was refused.",EXIT_CODE.USAGE,{code:"settings_write_invalid_existing_json",reason:"existing_settings_json_malformed",why:"Writing defaults over malformed settings could destroy intended project configuration.",nextSteps:["Repair the syntax in .agents/pm/settings.json, then retry the original command.","Run pm health to confirm the settings warning has cleared."]})}return{raw:source?`${JSON.stringify(orderObject(reconcileSettingsSnapshot(source.persisted_settings,proposed,current),SETTINGS_TOP_LEVEL_KEY_ORDER),null,2)}
4
4
  `:afterRaw,result:void 0}},op,author:resolveAuthor(void 0,settings.author_default),lockTtlSeconds:settings.locks.ttl_seconds,lockWaitMs:settings.locks.wait_ms,recordCreation:!1}),source&&attachSettingsPersistSourceSnapshot(settings,{...source,persisted_settings:structuredClone(proposed)}),await runActiveOnWriteHooks({path:settingsPath,scope:"project",op})}finally{clearSettingsReadCache(pmRoot)}}const settingsStoreTestOnly={applySettingsDelta,hasExplicitItemFormat,buildSettingsPersistSourceSnapshot,cacheSettingsReadResultIfStable,cacheSettingsReadResultSafe,mergeSettings,normalizeExtensionPolicySettings,normalizeExtensionPolicyOverride,normalizeExtensionPolicyOverrides,normalizeExtensionPolicyMode,normalizePmMaxVersionExceededModeSetting,normalizeExtensionSandboxProfile,normalizeExtensionTrustMode,normalizeLowerStringList,normalizeStringList,valueOrDefault,arrayOrEmpty,normalizeValidationPatternList,normalizeValidationMetadataRequiredFields,resolveSettingsReadTrackedPaths,resolvePersistedFileBackedSchemaSections,selectedSettingsReadCacheSignaturesEqual};export{isConfigurationOnlySettingsRead,mergeSettings,normalizeItemTypeDefinitions,persistSelectedItemFormat,readSettings,readSettingsWithMetadata,resolveGovernanceKnobs,runWithConfigurationOnlySettings,serializeSettings,settingsStoreTestOnly,writeSettings};
5
5
  //# sourceMappingURL=settings.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="acba78bd-59c7-5bc2-b0ef-1d9d41ff0975")}catch{}})();import{renderPmCommand}from"../command-line.js";import{resolveLinkedResourcePositionalRecovery}from"./linked-resource-recovery.js";import{resolveSubcommandFlagContractsForCommand}from"../cli-contracts/flag-contracts.js";import{parseBootstrapCommandName}from"../cli-contracts/bootstrap-command-scanner.js";import{READ_OUTPUT_DIMENSION_FLAGS,READ_OUTPUT_COMPOSITION_FLAGS}from"../read-output/options.js";import{resolvePmCommandOperation}from"../cli-contracts/command-aliases.js";const READ_PROJECTION_FLAGS=new Set([...Object.values(READ_OUTPUT_DIMENSION_FLAGS),...READ_OUTPUT_COMPOSITION_FLAGS,"--full","--brief","--compact","--summary","--fields","--section","--token-budget"]),MUTATION_RECEIPT_FLAGS=new Set(["--full-changed-fields","--no-changed-fields","--id-only"]);function readOptionCorrection(command,flag,token,next){if(flag==="--full"&&command==="context"&&token===flag)return{consumed:1,replacement:["--depth","full"],conflicts:["--depth","--output-include","--fields","--section","--for"]};if(flag==="--depth"&&["list","search"].includes(command)){const inline=token.includes("=");return(inline?token.slice(token.indexOf("=")+1):next)!=="full"?void 0:{consumed:inline?1:2,replacement:["--full"],conflicts:["--full","--brief","--compact","--output-include","--fields","--for"]}}return flag==="--toon"&&token===flag?{consumed:1,replacement:["--output-format","toon"],conflicts:["--json","--format","--output-format","--stream"]}:void 0}function resolveReadOptionRetryArgs(commandName,invocationArgv,unknownOption){const command=commandName==="ctx"?"context":resolvePmCommandOperation(commandName);if(!["context","list","search","get"].includes(command)||invocationArgv.includes("--"))return;const invoked=parseBootstrapCommandName(invocationArgv);if((invoked==="ctx"?"context":invoked)!==command)return;const flag=unknownOption.split("=",1)[0],indices=invocationArgv.flatMap((token,index2)=>token===flag||token.startsWith(`${flag}=`)?[index2]:[]);if(indices.length!==1)return;const index=indices[0],correction=readOptionCorrection(command,flag,invocationArgv[index],invocationArgv[index+1]);if(!correction)return;const{replacement,consumed,conflicts}=correction;if(!invocationArgv.some(argument=>conflicts.includes(argument.split("=",1)[0])))return[...invocationArgv.slice(0,index),...replacement,...invocationArgv.slice(index+consumed)]}function isReadProjectionRecoveryFlag(flag){const normalized=flag.split("=",1)[0].replaceAll("_","-");return READ_PROJECTION_FLAGS.has(normalized)||normalized.length>=5&&[...READ_PROJECTION_FLAGS].some(candidate=>candidate.startsWith(normalized))}function isCompatibleRecoveryFlag(requested,candidate){const unknownFlag=requested.split("=",1)[0].replaceAll("_","-");return isReadProjectionRecoveryFlag(unknownFlag)?!MUTATION_RECEIPT_FLAGS.has(candidate):MUTATION_RECEIPT_FLAGS.has(unknownFlag)?!isReadProjectionRecoveryFlag(candidate):!0}function normalizeMissingFlag(label){return label.trim().match(/--[a-z0-9][a-z0-9_-]*/i)?.[0]?.replaceAll("_","-").toLowerCase()}function resolveRecoveryCommandName(invocationArgv){if(!(!Array.isArray(invocationArgv)||invocationArgv.length===0))return parseBootstrapCommandName(invocationArgv)}function resolveMissingOptionPlaceholder(commandName,missingLabel){const flag=normalizeMissingFlag(missingLabel);if(!flag)return;const contract=resolveSubcommandFlagContractsForCommand(commandName).find(entry=>entry.flag===flag||entry.aliases?.includes(flag));return contract?contract.value_type==="boolean"?null:`<${contract.value_name??"value"}>`:"<value>"}function renderMissingOptionRetry(invocationArgv,commandName,missingLabels){const retry=[...invocationArgv],terminatorIndex=retry.indexOf("--");let insertionIndex=terminatorIndex<0?retry.length:terminatorIndex;for(const label of missingLabels){const flag=normalizeMissingFlag(label);if(!flag||retry.slice(0,insertionIndex).some(token=>token===flag||token.startsWith(`${flag}=`)))continue;const placeholder=resolveMissingOptionPlaceholder(commandName,flag),recoveredOption=placeholder?[flag,placeholder]:[flag];retry.splice(insertionIndex,0,...recoveredOption),insertionIndex+=recoveredOption.length}return retry.length===invocationArgv.length?void 0:renderPmCommand(retry)}export{isCompatibleRecoveryFlag,isReadProjectionRecoveryFlag,renderMissingOptionRetry,resolveLinkedResourcePositionalRecovery,resolveMissingOptionPlaceholder,resolveReadOptionRetryArgs,resolveRecoveryCommandName};
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="a1730bf5-914a-5031-ae21-56bd358727e2")}catch{}})();import{renderPmCommand}from"../command-line.js";import{resolveLinkedResourcePositionalRecovery}from"./linked-resource-recovery.js";import{resolveSubcommandFlagContractsForCommand}from"../cli-contracts/flag-contracts.js";import{parseBootstrapCommandName}from"../cli-contracts/bootstrap-command-scanner.js";import{READ_OUTPUT_DIMENSION_FLAGS,READ_OUTPUT_COMPOSITION_FLAGS}from"../read-output/options.js";import{resolvePmCommandOperation}from"../cli-contracts/command-aliases.js";const READ_PROJECTION_FLAGS=new Set([...Object.values(READ_OUTPUT_DIMENSION_FLAGS),...READ_OUTPUT_COMPOSITION_FLAGS,"--full","--brief","--compact","--summary","--fields","--section","--token-budget"]),MUTATION_RECEIPT_FLAGS=new Set(["--full-changed-fields","--no-changed-fields","--id-only"]);function activitySinceCorrection(token,next){const inline=token.includes("="),value=inline?token.slice(token.indexOf("=")+1):next;if(!(!value||value.startsWith("--")))return{consumed:inline?1:2,replacement:["--from",value],conflicts:["--from"]}}function readOptionCorrection(command,flag,token,next){if(flag==="--since"&&command==="activity")return activitySinceCorrection(token,next);if(flag==="--full"&&command==="context"&&token===flag)return{consumed:1,replacement:["--depth","full"],conflicts:["--depth","--output-include","--fields","--section","--for"]};if(flag==="--depth"&&["list","search"].includes(command)){const inline=token.includes("=");return(inline?token.slice(token.indexOf("=")+1):next)!=="full"?void 0:{consumed:inline?1:2,replacement:["--full"],conflicts:["--full","--brief","--compact","--output-include","--fields","--for"]}}return flag==="--toon"&&token===flag?{consumed:1,replacement:["--output-format","toon"],conflicts:["--json","--format","--output-format","--stream"]}:void 0}function resolveReadOptionRetryArgs(commandName,invocationArgv,unknownOption){const command=commandName==="ctx"?"context":resolvePmCommandOperation(commandName);if(!["context","list","search","get","activity"].includes(command)||invocationArgv.includes("--"))return;const invoked=parseBootstrapCommandName(invocationArgv);if((invoked==="ctx"?"context":invoked)!==command)return;const flag=unknownOption.split("=",1)[0],indices=invocationArgv.flatMap((token,index2)=>token===flag||token.startsWith(`${flag}=`)?[index2]:[]);if(indices.length!==1)return;const index=indices[0],correction=readOptionCorrection(command,flag,invocationArgv[index],invocationArgv[index+1]);if(!correction)return;const{replacement,consumed,conflicts}=correction;if(!invocationArgv.some(argument=>conflicts.includes(argument.split("=",1)[0])))return[...invocationArgv.slice(0,index),...replacement,...invocationArgv.slice(index+consumed)]}function isReadProjectionRecoveryFlag(flag){const normalized=flag.split("=",1)[0].replaceAll("_","-");return READ_PROJECTION_FLAGS.has(normalized)||normalized.length>=5&&[...READ_PROJECTION_FLAGS].some(candidate=>candidate.startsWith(normalized))}function isCompatibleRecoveryFlag(requested,candidate){const unknownFlag=requested.split("=",1)[0].replaceAll("_","-");return isReadProjectionRecoveryFlag(unknownFlag)?!MUTATION_RECEIPT_FLAGS.has(candidate):MUTATION_RECEIPT_FLAGS.has(unknownFlag)?!isReadProjectionRecoveryFlag(candidate):!0}function normalizeMissingFlag(label){return label.trim().match(/--[a-z0-9][a-z0-9_-]*/i)?.[0]?.replaceAll("_","-").toLowerCase()}function resolveRecoveryCommandName(invocationArgv){if(!(!Array.isArray(invocationArgv)||invocationArgv.length===0))return parseBootstrapCommandName(invocationArgv)}function resolveMissingOptionPlaceholder(commandName,missingLabel){const flag=normalizeMissingFlag(missingLabel);if(!flag)return;const contract=resolveSubcommandFlagContractsForCommand(commandName).find(entry=>entry.flag===flag||entry.aliases?.includes(flag));return contract?contract.value_type==="boolean"?null:`<${contract.value_name??"value"}>`:"<value>"}function renderMissingOptionRetry(invocationArgv,commandName,missingLabels){const retry=[...invocationArgv],terminatorIndex=retry.indexOf("--");let insertionIndex=terminatorIndex<0?retry.length:terminatorIndex;for(const label of missingLabels){const flag=normalizeMissingFlag(label);if(!flag||retry.slice(0,insertionIndex).some(token=>token===flag||token.startsWith(`${flag}=`)))continue;const placeholder=resolveMissingOptionPlaceholder(commandName,flag),recoveredOption=placeholder?[flag,placeholder]:[flag];retry.splice(insertionIndex,0,...recoveredOption),insertionIndex+=recoveredOption.length}return retry.length===invocationArgv.length?void 0:renderPmCommand(retry)}export{isCompatibleRecoveryFlag,isReadProjectionRecoveryFlag,renderMissingOptionRetry,resolveLinkedResourcePositionalRecovery,resolveMissingOptionPlaceholder,resolveReadOptionRetryArgs,resolveRecoveryCommandName};
2
2
  //# sourceMappingURL=command-recovery.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="6f46d7b9-24e8-5794-9b9e-2fa6365498fd")}catch{}})();const LIST_COMMANDER_STRING_OPTION_CONTRACTS=[{target:"status",keys:["status"]},{target:"type",keys:["type"]},{target:"tag",keys:["tag","tags"]},{target:"priority",keys:["priority"]},{target:"deadlineBefore",keys:["deadlineBefore"]},{target:"deadlineAfter",keys:["deadlineAfter"]},{target:"updatedAfter",keys:["updatedAfter"]},{target:"updatedBefore",keys:["updatedBefore"]},{target:"createdAfter",keys:["createdAfter"]},{target:"createdBefore",keys:["createdBefore"]},{target:"ids",keys:["ids"]},{target:"assignee",keys:["assignee"]},{target:"assigneeFilter",keys:["assigneeFilter","assignee_filter"]},{target:"parent",keys:["parent"]},{target:"sprint",keys:["sprint"]},{target:"release",keys:["release"]},{target:"limit",keys:["limit"]},{target:"offset",keys:["offset"]},{target:"after",keys:["after"]},{target:"fields",keys:["fields"]},{target:"sort",keys:["sort"]},{target:"order",keys:["order"]},{target:"treeDepth",keys:["treeDepth","tree_depth"]}],SEARCH_COMMANDER_STRING_OPTION_CONTRACTS=[{target:"mode",keys:["mode"]},{target:"matchMode",keys:["matchMode","match_mode"]},{target:"minScore",keys:["minScore","min_score"]},{target:"semanticWeight",keys:["semanticWeight","semantic_weight"]},{target:"status",keys:["status"]},{target:"type",keys:["type"]},{target:"tag",keys:["tag","tags"]},{target:"priority",keys:["priority"]},{target:"deadlineBefore",keys:["deadlineBefore"]},{target:"deadlineAfter",keys:["deadlineAfter"]},{target:"updatedAfter",keys:["updatedAfter"]},{target:"updatedBefore",keys:["updatedBefore"]},{target:"createdAfter",keys:["createdAfter"]},{target:"createdBefore",keys:["createdBefore"]},{target:"assignee",keys:["assignee"]},{target:"sprint",keys:["sprint"]},{target:"release",keys:["release"]},{target:"parent",keys:["parent"]},{target:"fields",keys:["fields"]},{target:"limit",keys:["limit"]},{target:"after",keys:["after"]}],CALENDAR_COMMANDER_STRING_OPTION_CONTRACTS=[{target:"view",keys:["view"]},{target:"date",keys:["date"]},{target:"from",keys:["from"]},{target:"to",keys:["to"]},{target:"limit",keys:["limit"]},{target:"type",keys:["type"]},{target:"tag",keys:["tag"]},{target:"priority",keys:["priority"]},{target:"status",keys:["status"]},{target:"assignee",keys:["assignee"]},{target:"assigneeFilter",keys:["assigneeFilter","assignee_filter"]},{target:"sprint",keys:["sprint"]},{target:"release",keys:["release"]},{target:"include",keys:["include"]},{target:"recurrenceLookaheadDays",keys:["recurrenceLookaheadDays","recurrence_lookahead_days"]},{target:"recurrenceLookbackDays",keys:["recurrenceLookbackDays","recurrence_lookback_days"]},{target:"occurrenceLimit",keys:["occurrenceLimit","occurrence_limit"]},{target:"format",keys:["format"]}],CONTEXT_COMMANDER_STRING_OPTION_CONTRACTS=[{target:"date",keys:["date"]},{target:"from",keys:["from"]},{target:"to",keys:["to"]},{target:"type",keys:["type"]},{target:"tag",keys:["tag"]},{target:"priority",keys:["priority"]},{target:"assignee",keys:["assignee"]},{target:"assigneeFilter",keys:["assigneeFilter","assignee_filter"]},{target:"sprint",keys:["sprint"]},{target:"release",keys:["release"]},{target:"parent",keys:["parent"]},{target:"limit",keys:["limit","maxItems","max_items"]},{target:"after",keys:["after"]},{target:"format",keys:["format"]},{target:"depth",keys:["depth"]},{target:"fields",keys:["fields"]},{target:"activityLimit",keys:["activityLimit","activity_limit"]},{target:"staleThreshold",keys:["staleThreshold","stale_threshold"]},{target:"tokenBudget",keys:["tokenBudget","token_budget"]}],NEXT_COMMANDER_STRING_OPTION_CONTRACTS=[{target:"type",keys:["type"]},{target:"tag",keys:["tag"]},{target:"priority",keys:["priority"]},{target:"assignee",keys:["assignee"]},{target:"assigneeFilter",keys:["assigneeFilter","assignee_filter"]},{target:"sprint",keys:["sprint"]},{target:"release",keys:["release"]},{target:"parent",keys:["parent"]},{target:"limit",keys:["limit"]},{target:"blockedLimit",keys:["blockedLimit","blocked_limit"]},{target:"format",keys:["format"]},{target:"tokenBudget",keys:["tokenBudget","token_budget"]}],ACTIVITY_COMMANDER_STRING_OPTION_CONTRACTS=[{target:"id",keys:["id"]},{target:"op",keys:["op"]},{target:"author",keys:["author"]},{target:"from",keys:["from"]},{target:"to",keys:["to"]},{target:"limit",keys:["limit"]}];function readFirstStringFromCommanderOptions(options,contract){for(const key of contract.keys){const candidate=options[key];if(typeof candidate=="string")return candidate}}function readFirstValueFromCommanderOptions(options,contract){for(const key of contract.keys)if(Object.hasOwn(options,key))return options[key]}function readStringArrayFromCommanderOptions(options,contract){const values=[];for(const key of contract.keys){const candidate=options[key];Array.isArray(candidate)&&values.push(...candidate.filter(value=>typeof value=="string"))}return values.length>0?values:void 0}export{ACTIVITY_COMMANDER_STRING_OPTION_CONTRACTS,CALENDAR_COMMANDER_STRING_OPTION_CONTRACTS,CONTEXT_COMMANDER_STRING_OPTION_CONTRACTS,LIST_COMMANDER_STRING_OPTION_CONTRACTS,NEXT_COMMANDER_STRING_OPTION_CONTRACTS,SEARCH_COMMANDER_STRING_OPTION_CONTRACTS,readFirstStringFromCommanderOptions,readFirstValueFromCommanderOptions,readStringArrayFromCommanderOptions};
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="3447e1a6-893f-542d-b985-2bd061306204")}catch{}})();const LIST_COMMANDER_STRING_OPTION_CONTRACTS=[{target:"status",keys:["status"]},{target:"type",keys:["type"]},{target:"tag",keys:["tag","tags"]},{target:"priority",keys:["priority"]},{target:"deadlineBefore",keys:["deadlineBefore"]},{target:"deadlineAfter",keys:["deadlineAfter"]},{target:"updatedAfter",keys:["updatedAfter"]},{target:"updatedBefore",keys:["updatedBefore"]},{target:"createdAfter",keys:["createdAfter"]},{target:"createdBefore",keys:["createdBefore"]},{target:"ids",keys:["ids"]},{target:"assignee",keys:["assignee"]},{target:"assigneeFilter",keys:["assigneeFilter","assignee_filter"]},{target:"parent",keys:["parent"]},{target:"sprint",keys:["sprint"]},{target:"release",keys:["release"]},{target:"limit",keys:["limit"]},{target:"offset",keys:["offset"]},{target:"after",keys:["after"]},{target:"fields",keys:["fields"]},{target:"sort",keys:["sort"]},{target:"order",keys:["order"]},{target:"treeDepth",keys:["treeDepth","tree_depth"]}],SEARCH_COMMANDER_STRING_OPTION_CONTRACTS=[{target:"mode",keys:["mode"]},{target:"matchMode",keys:["matchMode","match_mode"]},{target:"minScore",keys:["minScore","min_score"]},{target:"semanticWeight",keys:["semanticWeight","semantic_weight"]},{target:"status",keys:["status"]},{target:"type",keys:["type"]},{target:"tag",keys:["tag","tags"]},{target:"priority",keys:["priority"]},{target:"deadlineBefore",keys:["deadlineBefore"]},{target:"deadlineAfter",keys:["deadlineAfter"]},{target:"updatedAfter",keys:["updatedAfter"]},{target:"updatedBefore",keys:["updatedBefore"]},{target:"createdAfter",keys:["createdAfter"]},{target:"createdBefore",keys:["createdBefore"]},{target:"assignee",keys:["assignee"]},{target:"sprint",keys:["sprint"]},{target:"release",keys:["release"]},{target:"parent",keys:["parent"]},{target:"fields",keys:["fields"]},{target:"limit",keys:["limit"]},{target:"after",keys:["after"]}],CALENDAR_COMMANDER_STRING_OPTION_CONTRACTS=[{target:"view",keys:["view"]},{target:"date",keys:["date"]},{target:"from",keys:["from"]},{target:"to",keys:["to"]},{target:"limit",keys:["limit"]},{target:"type",keys:["type"]},{target:"tag",keys:["tag"]},{target:"priority",keys:["priority"]},{target:"status",keys:["status"]},{target:"assignee",keys:["assignee"]},{target:"assigneeFilter",keys:["assigneeFilter","assignee_filter"]},{target:"sprint",keys:["sprint"]},{target:"release",keys:["release"]},{target:"include",keys:["include"]},{target:"recurrenceLookaheadDays",keys:["recurrenceLookaheadDays","recurrence_lookahead_days"]},{target:"recurrenceLookbackDays",keys:["recurrenceLookbackDays","recurrence_lookback_days"]},{target:"occurrenceLimit",keys:["occurrenceLimit","occurrence_limit"]},{target:"format",keys:["format"]}],CONTEXT_COMMANDER_STRING_OPTION_CONTRACTS=[{target:"date",keys:["date"]},{target:"from",keys:["from"]},{target:"to",keys:["to"]},{target:"type",keys:["type"]},{target:"tag",keys:["tag"]},{target:"priority",keys:["priority"]},{target:"assignee",keys:["assignee"]},{target:"assigneeFilter",keys:["assigneeFilter","assignee_filter"]},{target:"sprint",keys:["sprint"]},{target:"release",keys:["release"]},{target:"parent",keys:["parent"]},{target:"limit",keys:["limit","maxItems","max_items"]},{target:"after",keys:["after"]},{target:"format",keys:["format"]},{target:"depth",keys:["depth"]},{target:"fields",keys:["fields"]},{target:"activityLimit",keys:["activityLimit","activity_limit"]},{target:"staleThreshold",keys:["staleThreshold","stale_threshold"]},{target:"tokenBudget",keys:["tokenBudget","token_budget"]}],NEXT_COMMANDER_STRING_OPTION_CONTRACTS=[{target:"type",keys:["type"]},{target:"tag",keys:["tag"]},{target:"priority",keys:["priority"]},{target:"assignee",keys:["assignee"]},{target:"assigneeFilter",keys:["assigneeFilter","assignee_filter"]},{target:"sprint",keys:["sprint"]},{target:"release",keys:["release"]},{target:"parent",keys:["parent"]},{target:"limit",keys:["limit"]},{target:"blockedLimit",keys:["blockedLimit","blocked_limit"]},{target:"format",keys:["format"]},{target:"tokenBudget",keys:["tokenBudget","token_budget"]}],ACTIVITY_COMMANDER_STRING_OPTION_CONTRACTS=[{target:"id",keys:["id"]},{target:"op",keys:["op"]},{target:"author",keys:["author"]},{target:"from",keys:["from"]},{target:"to",keys:["to"]},{target:"limit",keys:["limit"]},{target:"after",keys:["after"]}];function readFirstStringFromCommanderOptions(options,contract){for(const key of contract.keys){const candidate=options[key];if(typeof candidate=="string")return candidate}}function readFirstValueFromCommanderOptions(options,contract){for(const key of contract.keys)if(Object.hasOwn(options,key))return options[key]}function readStringArrayFromCommanderOptions(options,contract){const values=[];for(const key of contract.keys){const candidate=options[key];Array.isArray(candidate)&&values.push(...candidate.filter(value=>typeof value=="string"))}return values.length>0?values:void 0}export{ACTIVITY_COMMANDER_STRING_OPTION_CONTRACTS,CALENDAR_COMMANDER_STRING_OPTION_CONTRACTS,CONTEXT_COMMANDER_STRING_OPTION_CONTRACTS,LIST_COMMANDER_STRING_OPTION_CONTRACTS,NEXT_COMMANDER_STRING_OPTION_CONTRACTS,SEARCH_COMMANDER_STRING_OPTION_CONTRACTS,readFirstStringFromCommanderOptions,readFirstValueFromCommanderOptions,readStringArrayFromCommanderOptions};
2
2
  //# sourceMappingURL=commander-types.js.map
@@ -19,6 +19,8 @@ list?:boolean;
19
19
  value_name?:string;
20
20
  /** Schema type that determines the shape and validation rules for this value. */
21
21
  value_type?:"string" | "number" | "boolean";
22
+ /** Declared omitted-flag default, preserving scalar and list value types. */
23
+ default?:string | number | boolean | Array<string | number | boolean>;
22
24
  /** Explicit argv value-token grammar. When absent, legacy core vocabulary inference applies. */
23
25
  value_arity?:"none" | "required" | "optional";
24
26
  /** Marks a presentation-only flag that may change paging or rendering without invalidating continuation. Omission means the flag is query-semantic. */