@unbrained/pm-cli 2026.9.17 → 2026.9.19

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 (157) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +49 -0
  3. package/dist/cli/invocation-profile.d.ts +26 -0
  4. package/dist/cli/invocation-profile.js +3 -0
  5. package/dist/cli/register-operations.js +1 -1
  6. package/dist/cli-bundle/bundle-manifest.json +149 -149
  7. package/dist/cli-bundle/chunks/{chunk-LD2FH2YE.js → chunk-7CN53F4S.js} +2 -2
  8. package/dist/cli-bundle/chunks/chunk-AACGU5IA.js +3 -0
  9. package/dist/cli-bundle/chunks/{chunk-Q6KPZGMP.js → chunk-CCLWCESZ.js} +2 -2
  10. package/dist/cli-bundle/chunks/{chunk-T526C5DX.js → chunk-J7NP7QLW.js} +2 -2
  11. package/dist/cli-bundle/chunks/{chunk-UF75LUAK.js → chunk-K4VAU4HU.js} +63 -63
  12. package/dist/cli-bundle/chunks/chunk-KHN4NMKT.js +238 -0
  13. package/dist/cli-bundle/chunks/{chunk-YZXB4XGA.js → chunk-KYG2QKNY.js} +29 -29
  14. package/dist/cli-bundle/chunks/{chunk-CPFBDM53.js → chunk-OQS2Y6VN.js} +2 -2
  15. package/dist/cli-bundle/chunks/{chunk-G2IJF244.js → chunk-QA4GUEKJ.js} +20 -20
  16. package/dist/cli-bundle/chunks/chunk-QTHR3LXF.js +20 -0
  17. package/dist/cli-bundle/chunks/{chunk-5ZY4WE3F.js → chunk-RVMDPIGD.js} +2 -2
  18. package/dist/cli-bundle/chunks/chunk-WASMH647.js +8 -0
  19. package/dist/cli-bundle/chunks/{register-list-query-ISM35VIX.js → register-list-query-RMZNHSII.js} +2 -2
  20. package/dist/cli-bundle/chunks/{register-mutation-KHMBJJS6.js → register-mutation-HJGSGX3H.js} +2 -2
  21. package/dist/cli-bundle/chunks/register-operations-LBEMFUMM.js +2 -0
  22. package/dist/cli-bundle/chunks/{register-setup-YAURJMY5.js → register-setup-MU557JAA.js} +2 -2
  23. package/dist/cli-bundle/focused-chunks/{chunk-G4TKJZ4A.js → chunk-5SZ4JSPZ.js} +2 -2
  24. package/dist/cli-bundle/focused-chunks/{chunk-NOK652OP.js → chunk-7Y7PAC56.js} +2 -2
  25. package/dist/cli-bundle/focused-chunks/{chunk-5KYHDFDN.js → chunk-ARK4FIO4.js} +3 -3
  26. package/dist/cli-bundle/focused-chunks/{chunk-LNM3BS45.js → chunk-CJ4QA4RW.js} +2 -2
  27. package/dist/cli-bundle/focused-chunks/chunk-I32L3FWW.js +12 -0
  28. package/dist/cli-bundle/focused-chunks/{chunk-267N774W.js → chunk-I4WDON3K.js} +2 -2
  29. package/dist/cli-bundle/focused-chunks/{chunk-7ZC4CKOX.js → chunk-IKPR4VVN.js} +2 -2
  30. package/dist/cli-bundle/focused-chunks/chunk-J3GN4SQT.js +2 -0
  31. package/dist/cli-bundle/focused-chunks/{chunk-GKSAMNBG.js → chunk-OOZHQFBF.js} +16 -16
  32. package/dist/cli-bundle/focused-chunks/{chunk-JZSLDLR4.js → chunk-P4BA7OX7.js} +27 -26
  33. package/dist/cli-bundle/focused-chunks/chunk-QL4MO5M2.js +30 -0
  34. package/dist/cli-bundle/focused-chunks/chunk-TDHVROGL.js +3 -0
  35. package/dist/cli-bundle/focused-chunks/chunk-V3YMNAO7.js +2 -0
  36. package/dist/cli-bundle/focused-chunks/chunk-YDFEWXXZ.js +59 -0
  37. package/dist/cli-bundle/focused-chunks/{chunk-WUMGGQYN.js → chunk-ZDBKYZFE.js} +2 -2
  38. package/dist/cli-bundle/focused-chunks/{chunk-BFUXTNZU.js → chunk-ZI2YBJFH.js} +2 -2
  39. package/dist/cli-bundle/main.js +2 -2
  40. package/dist/cli-bundle/sdk-authoring.js +1 -1
  41. package/dist/cli-bundle/sdk-contracts.js +2 -2
  42. package/dist/cli-bundle/sdk-core.js +25 -25
  43. package/dist/cli-bundle/sdk-governance.js +1 -1
  44. package/dist/cli-bundle/sdk-graph.js +1 -1
  45. package/dist/cli-bundle/sdk-merge.js +41 -41
  46. package/dist/cli-bundle/sdk-query.js +1 -1
  47. package/dist/cli-bundle/sdk-runtime.js +1 -1
  48. package/dist/cli-bundle/sdk-testing.js +1 -1
  49. package/dist/cli-bundle/sdk.js +8 -8
  50. package/dist/cli.js +1 -1
  51. package/dist/core/checkpoint/mutation-checkpoint.d.ts +1 -1
  52. package/dist/core/checkpoint/mutation-checkpoint.js +2 -2
  53. package/dist/core/config/nested-settings.js +1 -1
  54. package/dist/core/fs/atomic-create.d.ts +7 -0
  55. package/dist/core/fs/atomic-create.js +2 -0
  56. package/dist/core/history/history.js +1 -1
  57. package/dist/core/schema/runtime-schema.d.ts +1 -1
  58. package/dist/core/schema/runtime-schema.js +2 -2
  59. package/dist/core/session/session-state.js +1 -1
  60. package/dist/core/shared/secret-rules.d.ts +110 -0
  61. package/dist/core/shared/secret-rules.js +2 -0
  62. package/dist/core/store/settings-concurrency.d.ts +7 -0
  63. package/dist/core/store/settings-concurrency.js +2 -0
  64. package/dist/core/store/settings.d.ts +8 -1
  65. package/dist/core/store/settings.js +3 -2
  66. package/dist/mcp/server.d.ts +4 -0
  67. package/dist/mcp/server.js +1 -1
  68. package/dist/sdk/cli-contracts/command-aliases.js +1 -1
  69. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  70. package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
  71. package/dist/sdk/cli-program.js +1 -1
  72. package/dist/sdk/context-intent-contracts.js +1 -1
  73. package/dist/sdk/context-relevance.js +1 -1
  74. package/dist/sdk/contracts.d.ts +1 -0
  75. package/dist/sdk/contracts.js +1 -1
  76. package/dist/sdk/extension/install-runtime.d.ts +1 -1
  77. package/dist/sdk/extension/install-runtime.js +2 -2
  78. package/dist/sdk/governance/health.js +1 -1
  79. package/dist/sdk/governance/provenance-health.d.ts +27 -0
  80. package/dist/sdk/governance/provenance-health.js +1 -1
  81. package/dist/sdk/graph/index.d.ts +1 -0
  82. package/dist/sdk/graph/index.js +1 -1
  83. package/dist/sdk/graph/query-contracts.d.ts +18 -0
  84. package/dist/sdk/graph/query-contracts.js +2 -0
  85. package/dist/sdk/graph/run.d.ts +2 -0
  86. package/dist/sdk/graph/run.js +1 -1
  87. package/dist/sdk/graph/traversal.js +1 -1
  88. package/dist/sdk/guide-topics.js +1 -1
  89. package/dist/sdk/lifecycle/event-validation-messages.d.ts +1 -1
  90. package/dist/sdk/lifecycle/event-validation-messages.js +1 -1
  91. package/dist/sdk/lifecycle-policy.js +1 -1
  92. package/dist/sdk/mutation-guard.d.ts +8 -1
  93. package/dist/sdk/mutation-guard.js +1 -1
  94. package/dist/sdk/public-surface.json +1 -1
  95. package/dist/sdk/query/next-ready-budget.d.ts +20 -0
  96. package/dist/sdk/query/next-ready-budget.js +2 -0
  97. package/dist/sdk/query/next.d.ts +7 -2
  98. package/dist/sdk/query/next.js +1 -1
  99. package/dist/sdk/read-output-budget.d.ts +3 -1
  100. package/dist/sdk/read-output-budget.js +1 -1
  101. package/dist/sdk/read-output-contracts.js +1 -1
  102. package/dist/sdk/read-output-session.js +1 -1
  103. package/dist/sdk/test/execution.d.ts +6 -5
  104. package/dist/sdk/test/execution.js +2 -2
  105. package/dist/sdk/test/json-path.d.ts +11 -0
  106. package/dist/sdk/test/json-path.js +2 -0
  107. package/docs/BUILD_AND_RELEASE_ACCEPTANCE.md +66 -0
  108. package/docs/MCP_OPTION_CONFORMANCE.md +41 -0
  109. package/docs/MUTATION_INTEGRITY.md +36 -4
  110. package/docs/NEXT_SELECTION_BUDGETS.md +93 -0
  111. package/docs/OUTPUT_PROJECTION_CONTRACTS.md +18 -2
  112. package/docs/PACKED_FIRST_RUN.md +8 -4
  113. package/docs/PERFORMANCE.md +37 -0
  114. package/docs/README.md +2 -0
  115. package/docs/READ_OUTPUT_CONTRACTS.md +8 -4
  116. package/docs/SDK_AGENT_SESSION_CONTEXT.md +28 -4
  117. package/docs/SDK_LIFECYCLE.md +16 -2
  118. package/docs/WORKSPACE_CONCURRENCY.md +67 -0
  119. package/docs/agent-task-token-baseline.json +7 -7
  120. package/docs/generated/AGENT_CAPABILITY_ROUTING.md +1 -1
  121. package/docs/generated/AGENT_COMMAND_SURFACE.md +3 -0
  122. package/docs/generated/FLAG_LEXICON_BUDGETS.md +3 -0
  123. package/marketplace.json +2 -2
  124. package/package.json +11 -9
  125. package/packages/pm-beads/package.json +1 -1
  126. package/packages/pm-calendar/README.md +43 -2
  127. package/packages/pm-calendar/extensions/calendar/command-definitions.ts +52 -0
  128. package/packages/pm-calendar/extensions/calendar/index.ts +2 -0
  129. package/packages/pm-calendar/extensions/calendar/manifest.json +3 -3
  130. package/packages/pm-calendar/extensions/calendar/shortcuts.ts +15 -0
  131. package/packages/pm-calendar/package.json +1 -1
  132. package/packages/pm-command-kit/package.json +1 -1
  133. package/packages/pm-digital-twin/package.json +1 -1
  134. package/packages/pm-governance-audit/package.json +1 -1
  135. package/packages/pm-guide-shell/package.json +1 -1
  136. package/packages/pm-kanban/package.json +1 -1
  137. package/packages/pm-lifecycle-hooks/package.json +1 -1
  138. package/packages/pm-linked-test-adapters/package.json +1 -1
  139. package/packages/pm-search-advanced/package.json +1 -1
  140. package/packages/pm-templates/package.json +1 -1
  141. package/packages/pm-todos/package.json +1 -1
  142. package/packages/pm-vcs/package.json +1 -1
  143. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  144. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  145. package/scripts/build-lease.mjs +43 -0
  146. package/scripts/build.mjs +40 -0
  147. package/dist/cli-bundle/chunks/chunk-C3MFMGCR.js +0 -20
  148. package/dist/cli-bundle/chunks/chunk-DN2RIHRN.js +0 -3
  149. package/dist/cli-bundle/chunks/chunk-E67MIO3Z.js +0 -8
  150. package/dist/cli-bundle/chunks/chunk-UJSB6NO6.js +0 -237
  151. package/dist/cli-bundle/chunks/register-operations-HHDROJD6.js +0 -2
  152. package/dist/cli-bundle/focused-chunks/chunk-5FSGN4MP.js +0 -12
  153. package/dist/cli-bundle/focused-chunks/chunk-7S7XWMXC.js +0 -2
  154. package/dist/cli-bundle/focused-chunks/chunk-IVWUQE7T.js +0 -59
  155. package/dist/cli-bundle/focused-chunks/chunk-OCTTDZOU.js +0 -3
  156. package/dist/cli-bundle/focused-chunks/chunk-OWDDVMAP.js +0 -2
  157. package/dist/cli-bundle/focused-chunks/chunk-Z4PWEIMX.js +0 -30
@@ -1,2 +1,2 @@
1
- !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="67c51368-f551-5951-b934-6781e38c69ad")}catch(e2){}})();import{EXIT_CODE,SETTINGS_DEFAULTS,PmCliError,activateExtensions,getActiveExtensionRegistrations,loadExtensions,pathExists,commandOptionFlagLabel,resolveCommandOptionPolicyState,resolveItemTypeRegistry,resolveRuntimeFieldRegistry,resolveRuntimeStatusRegistry,getSettingsPath,resolvePmRoot,readSettings}from"../runtime-primitives.js";import{PM_HISTORY_OPERATION_CONTRACT}from"../../core/history/operation-contract.js";import{buildMcpToolContracts}from"../../mcp/tool-definitions.js";import{ACTIVITY_COMMANDER_STRING_OPTION_CONTRACTS,ACTIVITY_FLAG_CONTRACTS,AGGREGATE_FLAG_CONTRACTS,ASSURANCE_FLAG_CONTRACTS,APPEND_FLAG_CONTRACTS,CALENDAR_COMMANDER_STRING_OPTION_CONTRACTS,CALENDAR_FLAG_CONTRACTS,CLAIM_FLAG_CONTRACTS,CLOSE_TASK_FLAG_CONTRACTS,COMMENTS_FLAG_CONTRACTS,CLOSE_FLAG_CONTRACTS,CLOSE_MANY_FLAG_CONTRACTS,COMPLETION_FLAG_CONTRACTS,CONFIG_FLAG_CONTRACTS,CONTRACTS_FLAG_CONTRACTS,COPY_FLAG_CONTRACTS,CONTEXT_COMMANDER_STRING_OPTION_CONTRACTS,CONTEXT_FLAG_CONTRACTS,CREATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS,CREATE_COMMANDER_STRING_OPTION_CONTRACTS,CREATE_FLAG_CONTRACTS,DELETE_FLAG_CONTRACTS,DEPS_FLAG_CONTRACTS,GRAPH_FLAG_CONTRACTS,DOCS_FLAG_CONTRACTS,EXTENSION_ACTIVATE_FLAG_CONTRACTS,EXTENSION_ADOPT_ALL_FLAG_CONTRACTS,EXTENSION_ADOPT_FLAG_CONTRACTS,EXTENSION_CATALOG_FLAG_CONTRACTS,EXTENSION_DEACTIVATE_FLAG_CONTRACTS,EXTENSION_DESCRIBE_FLAG_CONTRACTS,EXTENSION_DOCTOR_FLAG_CONTRACTS,EXTENSION_EXPLORE_FLAG_CONTRACTS,EXTENSION_FLAG_CONTRACTS,EXTENSION_INIT_FLAG_CONTRACTS,EXTENSION_INSTALL_FLAG_CONTRACTS,EXTENSION_MANAGE_FLAG_CONTRACTS,EXTENSION_MIGRATE_FLAG_CONTRACTS,EXTENSION_RELOAD_FLAG_CONTRACTS,EXTENSION_UNINSTALL_FLAG_CONTRACTS,FILES_FLAG_CONTRACTS,FOCUS_FLAG_CONTRACTS,GC_FLAG_CONTRACTS,GET_FLAG_CONTRACTS,GUIDE_FLAG_CONTRACTS,GLOBAL_FLAG_CONTRACTS,HEALTH_FLAG_CONTRACTS,HISTORY_FLAG_CONTRACTS,HISTORY_COMPACT_FLAG_CONTRACTS,HISTORY_REDACT_FLAG_CONTRACTS,HISTORY_REPAIR_FLAG_CONTRACTS,HISTORY_AUTHOR_ACKNOWLEDGE_FLAG_CONTRACTS,INSTALL_FLAG_CONTRACTS,INIT_FLAG_CONTRACTS,ITEM_COMPLETE_FLAG_CONTRACTS,ITEM_MUTATE_FLAG_CONTRACTS,ITEM_REOPEN_FLAG_CONTRACTS,LEARNINGS_FLAG_CONTRACTS,LIST_COMMANDER_STRING_OPTION_CONTRACTS,LIST_FILTER_FLAG_CONTRACTS,MERGE_FLAG_CONTRACTS,NOTES_FLAG_CONTRACTS,PACKAGE_FLAG_CONTRACTS,PACKAGE_INIT_FLAG_CONTRACTS,PM_EXTENSION_CAPABILITY_CONTRACTS,PM_EXTENSION_POLICY_MODE_CONTRACTS,PM_EXTENSION_POLICY_SURFACE_CONTRACTS,PM_EXTENSION_SANDBOX_PROFILE_CONTRACTS,PM_EXTENSION_SERVICE_NAME_CONTRACTS,PM_EXTENSION_TRUST_MODE_CONTRACTS,PM_OUTPUT_DEGRADATION_STEPS,PLAN_FLAG_CONTRACTS,PM_CORE_COMMAND_NAMES,PM_DEPRECATED_TOOL_ACTIONS,PM_TOOL_ACTIONS,PM_TOOL_PARAMETERS_SCHEMA,REINDEX_FLAG_CONTRACTS,RELEASE_FLAG_CONTRACTS,RESTORE_FLAG_CONTRACTS,SCHEMA_FLAG_CONTRACTS,PROFILE_FLAG_CONTRACTS,SEARCH_COMMANDER_STRING_OPTION_CONTRACTS,EVAL_FLAG_CONTRACTS,EVENTS_FLAG_CONTRACTS,WORKSPACE_FLAG_CONTRACTS,NEXT_FLAG_CONTRACTS,SEARCH_FLAG_CONTRACTS,STATS_FLAG_CONTRACTS,DUPLICATES_FLAG_CONTRACTS,START_TASK_FLAG_CONTRACTS,PAUSE_TASK_FLAG_CONTRACTS,TELEMETRY_FLAG_CONTRACTS,TEST_ALL_FLAG_CONTRACTS,TEST_FLAG_CONTRACTS,TEST_RUNS_FLAG_CONTRACTS,UPDATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS,UPDATE_COMMANDER_STRING_OPTION_CONTRACTS,UPDATE_FLAG_CONTRACTS,UPDATE_MANY_FLAG_CONTRACTS,UPGRADE_FLAG_CONTRACTS,VALIDATE_FLAG_CONTRACTS,compactFlagAliasContracts,PM_COMMAND_ALIAS_CONTRACTS,PM_DIAGNOSTIC_OUTPUT_BUDGET_CONTRACTS,resolvePmCommandOutputBudget}from"../cli-contracts.js";import{PM_NAMESPACED_COMMAND_ALIASES,resolvePmCommandOperation}from"./command-aliases.js";import{HISTORY_ATTEST_FLAG_CONTRACTS,PM_POSITIONAL_ACTION_FLAG_CONTRACTS}from"./flag-contracts.js";import{GOVERNANCE_CLOSE_VALIDATION_DEFAULT_VALUES,GOVERNANCE_CREATE_MODE_DEFAULT_VALUES,GOVERNANCE_OWNERSHIP_ENFORCEMENT_VALUES,GOVERNANCE_WORKFLOW_ENFORCEMENT_VALUES}from"../../types.js";import{BRIEF_LIST_FIELDS,DEFAULT_COMPACT_LIST_FIELDS,LIST_COMMAND_DEFAULT_PROJECTIONS}from"../query/list.js";import{getActiveContextIntentContracts}from"../context-intent-contracts.js";import{readOutputIncludeModeOptions,resolveReadOutputSurface,PM_READ_OUTPUT_SURFACE_CONTRACTS}from"../read-output-contracts.js";import{enrichCliFlagInvocationContracts}from"../flag-invocation-contracts.js";import{resolvePmCommandVisibilityTier}from"../agent-capability-contracts.js";import{PM_ERROR_CODE_CATALOG}from"../generated-error-code-catalog.js";import{resolvePmCommandOutputEnvelope}from"../output-contracts.js";import{PM_COMMAND_EXIT_OUTCOME_CONTRACTS,resolvePmCommandExitContract}from"./command-exit-contracts.js";import{BUILTIN_RELATIONSHIP_KINDS}from"../relationship-kinds/contract.js";import{ASSURANCE_GATE_TRIGGERS,ASSURANCE_MEASUREMENT_SOURCE_KINDS}from"../governance/assurance.js";import{PM_CLI_GRAMMAR_CONTRACT,PM_COMMAND_DESTINATION_CONTRACTS,PM_COMMAND_POSITIONAL_CONTRACTS,PM_POSITIONAL_ACTION_CONTRACTS,positionalShapeKey,resolvePmCommandPositionalContract}from"./grammar-contracts.js";const AGENT_BOOTSTRAP_FLAGS=new Map([["claim",["--if-available","--next","--type","--priority","--token-budget","--explain-ranking"]],["close",["--reason","--validate-close","--resolution","--expected-result","--actual-result","--message"]],["context",["--limit","--after","--depth","--section","--token-budget","--explain-ranking"]],["contracts",["--command","--flags-only","--summary","--runtime-only","--availability-only","--full"]],["create",["--title","--type","--status","--priority","--dep","--comment"]],["get",["--full","--depth","--fields","--tree","--tree-depth","--format"]],["health",["--check-only","--summary","--brief","--check-telemetry","--strict-exit","--full"]],["list",["--status","--type","--limit","--after","--brief","--fields"]],["next",["--limit","--blocked-limit","--ready-only","--token-budget","--explain-ranking","--format"]],["search",["--mode","--status","--type","--limit","--after","--fields"]],["update",["--status","--message","--dep","--comment","--file","--test"]],["validate",["--check-resolution","--check-history-drift","--check-storage-integrity","--counts","--strict-exit","--fix-hints"]]]);const AGENT_BOUNDED_FLAG_PRIORITY=["--limit","--after","--offset","--token-budget","--brief","--summary","--compact","--fields","--full","--format","--since","--until"];const LIST_COMMAND_NAMES=new Set(["list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"]);const PACKAGE_OWNED_ACTIONS=new Set(["calendar","guide","reindex","completion","test-runs-list","test-runs-status","test-runs-logs","test-runs-stop","test-runs-resume","templates-list","templates-save","templates-show"]);const PACKAGE_OWNED_COMMANDS=new Set(["search-advanced","dedupe-audit","dedupe-merge","comments-audit","cal","calendar","completion","completion-statuses","completion-tags","completion-types","guide","reindex","normalize","templates","templates list","templates save","templates show","test-runs","test-runs list","test-runs status","test-runs logs","test-runs stop","test-runs resume"]);const PACKAGE_OWNED_COMMAND_INSTALL_HINTS=new Map([["search-advanced","search-advanced"],["dedupe-audit","governance-audit"],["dedupe-merge","governance-audit"],["comments-audit","governance-audit"],["cal","calendar"],["calendar","calendar"],["completion","guide-shell"],["completion-statuses","guide-shell"],["completion-tags","guide-shell"],["completion-types","guide-shell"],["guide","guide-shell"],["reindex","search-advanced"],["normalize","governance-audit"],["templates","templates"],["templates list","templates"],["templates save","templates"],["templates show","templates"],["test-runs","linked-test-adapters"],["test-runs list","linked-test-adapters"],["test-runs status","linked-test-adapters"],["test-runs logs","linked-test-adapters"],["test-runs stop","linked-test-adapters"],["test-runs resume","linked-test-adapters"]]);const PACKAGE_OWNED_ACTION_COMMAND_PATHS=new Map([["calendar","calendar|cal"],["guide","guide"],["reindex","reindex"],["completion","completion"],["test-runs-list","test-runs|test-runs list"],["test-runs-status","test-runs status"],["test-runs-logs","test-runs logs"],["test-runs-stop","test-runs stop"],["test-runs-resume","test-runs resume"],["templates-list","templates|templates list"],["templates-save","templates save"],["templates-show","templates show"]]);const PACKAGE_OWNED_COMMAND_ACTIONS=new Map([...PACKAGE_OWNED_ACTION_COMMAND_PATHS.entries()].flatMap(([action,commandPaths])=>splitCommandPathAliases(commandPaths).map(commandPath=>[commandPath,action])));const CANONICAL_COMMAND_ALIASES=[{canonical:"context",aliases:["ctx"]},{canonical:"package",aliases:["extension","packages"]}];const COMMAND_ALIAS_TO_CANONICAL=new Map(CANONICAL_COMMAND_ALIASES.flatMap(entry=>entry.aliases.map(alias=>[alias,entry.canonical])));const COMMAND_NAMESPACE_DISPLAY_LIMIT=10;const COMMAND_NAMESPACE_FALLBACK_LIMIT=20;const COMMAND_INTENTS=new Map([["activity","Read activity."],["aggregate","Group counts."],["append","Append body."],["assurance","Evaluate assurance."],["assurance derive","Derive checks."],["assurance risk","Select checks for changes."],["assurance lineages","Measure recurrence coverage."],["beads","Manage Beads interoperability."],["cal","Manage calendar integration."],["calendar","Manage calendar integration."],["changelog","Generate changelog output."],["claim","Claim work."],["close","Close work."],["close-many","Close matching work."],["close-task","Close task work."],["command-kit","Inspect command authoring primitives."],["comments","Manage comments."],["comments-audit","Audit comment governance."],["completion","Generate shell completions."],["config","Manage settings."],["context","Build context."],["contracts","Inspect contracts."],["copy","Copy work."],["create","Create work."],["dedupe-audit","Audit duplicate work."],["dedupe-merge","Merge duplicate work."],["delete","Delete work."],["deps","Manage deps."],["duplicates","Find duplicate clusters."],["docs","Link docs."],["eval","Run evaluations."],["event","Manage events."],["events","Read events."],["files","Link files."],["focus","Manage focus."],["gc","Clean caches."],["get","Read item."],["graph","Query graph."],["guide","Show user guides."],["health","Check health."],["help","Show help."],["history","Inspect history."],["init","Initialize workspace."],["install","Install packages."],["item","Mutate items."],["learnings","Manage learnings."],["list","List work."],["list-all","List work across every status."],["list-blocked","List blocked work."],["list-canceled","List canceled work."],["list-closed","List closed work."],["list-draft","List draft work."],["list-in-progress","List in-progress work."],["list-open","List open work."],["meet","Record meeting context."],["merge","Manage tracker merges."],["next","Pick next work."],["notes","Manage notes."],["normalize","Normalize tracker data."],["ops","Run operations."],["package","Manage packages."],["packages","Manage packages."],["pause-task","Pause task work."],["plan","Manage plans."],["profile","Manage profiles."],["reindex","Refresh search index."],["release","Release claim."],["remind","Manage reminders."],["restore","Restore history."],["schema","Customize schema."],["search","Search work."],["search-advanced","Run advanced search."],["start-task","Start task work."],["stats","Show stats."],["telemetry","Manage telemetry."],["templates","Manage work templates."],["test","Run linked tests."],["test-all","Run all linked tests."],["test-runs","Inspect background test runs."],["todos","Manage source-code todos."],["twin","Manage repository twins."],["update","Update work."],["update-many","Update matching work."],["upgrade","Upgrade packages."],["validate","Validate data."],["vcs","Inspect version-control context."],["workspace","Manage workspaces."],["history-author-acknowledge","Acknowledge reviewed history authors."],["history-compact","Compact history."],["history-attest","Export or verify detached history proof."],["history-redact","Redact sensitive history values."],["history-repair","Repair history integrity."]]);const EXTENSION_LIFECYCLE_FLAG_CONTRACTS=[["init",EXTENSION_INIT_FLAG_CONTRACTS],["install",EXTENSION_INSTALL_FLAG_CONTRACTS],["uninstall",EXTENSION_UNINSTALL_FLAG_CONTRACTS],["explore",EXTENSION_EXPLORE_FLAG_CONTRACTS],["manage",EXTENSION_MANAGE_FLAG_CONTRACTS],["describe",EXTENSION_DESCRIBE_FLAG_CONTRACTS],["reload",EXTENSION_RELOAD_FLAG_CONTRACTS],["doctor",EXTENSION_DOCTOR_FLAG_CONTRACTS],["catalog",EXTENSION_CATALOG_FLAG_CONTRACTS],["adopt",EXTENSION_ADOPT_FLAG_CONTRACTS],["adopt-all",EXTENSION_ADOPT_ALL_FLAG_CONTRACTS],["activate",EXTENSION_ACTIVATE_FLAG_CONTRACTS],["deactivate",EXTENSION_DEACTIVATE_FLAG_CONTRACTS],["migrate",EXTENSION_MIGRATE_FLAG_CONTRACTS]];const PACKAGE_LIFECYCLE_FLAG_CONTRACTS=[...EXTENSION_LIFECYCLE_FLAG_CONTRACTS.map(([subcommand,flags])=>subcommand==="init"?[subcommand,PACKAGE_INIT_FLAG_CONTRACTS]:[subcommand,flags]),["upgrade",UPGRADE_FLAG_CONTRACTS]];const CORE_COMMAND_FLAG_CONTRACT_ENTRIES=[...EXTENSION_LIFECYCLE_FLAG_CONTRACTS.map(([subcommand,flags])=>[`extension ${subcommand}`,flags]),...PACKAGE_LIFECYCLE_FLAG_CONTRACTS.flatMap(([subcommand,flags])=>[[`package ${subcommand}`,flags],[`packages ${subcommand}`,flags]]),["init",INIT_FLAG_CONTRACTS],["config",CONFIG_FLAG_CONTRACTS],["extension",EXTENSION_FLAG_CONTRACTS],["package",PACKAGE_FLAG_CONTRACTS],["packages",PACKAGE_FLAG_CONTRACTS],["install",INSTALL_FLAG_CONTRACTS],["create",CREATE_FLAG_CONTRACTS],["item mutate",ITEM_MUTATE_FLAG_CONTRACTS],["item complete",ITEM_COMPLETE_FLAG_CONTRACTS],["item reopen",ITEM_REOPEN_FLAG_CONTRACTS],["copy",COPY_FLAG_CONTRACTS],["focus",FOCUS_FLAG_CONTRACTS],["update",UPDATE_FLAG_CONTRACTS],["update-many",UPDATE_MANY_FLAG_CONTRACTS],["upgrade",UPGRADE_FLAG_CONTRACTS],["calendar",CALENDAR_FLAG_CONTRACTS],["cal",CALENDAR_FLAG_CONTRACTS],["context",CONTEXT_FLAG_CONTRACTS],["ctx",CONTEXT_FLAG_CONTRACTS],["get",GET_FLAG_CONTRACTS],["search",SEARCH_FLAG_CONTRACTS],["eval",EVAL_FLAG_CONTRACTS],["events",EVENTS_FLAG_CONTRACTS],["workspace",WORKSPACE_FLAG_CONTRACTS],["workspace position",[]],["workspace snapshot",WORKSPACE_FLAG_CONTRACTS],["workspace snapshot create",WORKSPACE_FLAG_CONTRACTS],["workspace snapshot list",WORKSPACE_FLAG_CONTRACTS],["workspace snapshot inspect",WORKSPACE_FLAG_CONTRACTS],["workspace snapshot restore",WORKSPACE_FLAG_CONTRACTS],["workspace snapshot delete",WORKSPACE_FLAG_CONTRACTS],["next",NEXT_FLAG_CONTRACTS],["aggregate",AGGREGATE_FLAG_CONTRACTS],["deps",DEPS_FLAG_CONTRACTS],["graph",GRAPH_FLAG_CONTRACTS],["guide",GUIDE_FLAG_CONTRACTS],["reindex",REINDEX_FLAG_CONTRACTS],["history",HISTORY_FLAG_CONTRACTS],["history-compact",HISTORY_COMPACT_FLAG_CONTRACTS],["history-attest",HISTORY_ATTEST_FLAG_CONTRACTS],["history-redact",HISTORY_REDACT_FLAG_CONTRACTS],["history-repair",HISTORY_REPAIR_FLAG_CONTRACTS],["history-author-acknowledge",HISTORY_AUTHOR_ACKNOWLEDGE_FLAG_CONTRACTS],["merge",MERGE_FLAG_CONTRACTS],["schema",SCHEMA_FLAG_CONTRACTS],["profile",PROFILE_FLAG_CONTRACTS],["plan",PLAN_FLAG_CONTRACTS],["restore",RESTORE_FLAG_CONTRACTS],["delete",DELETE_FLAG_CONTRACTS],["close",CLOSE_FLAG_CONTRACTS],["close-many",CLOSE_MANY_FLAG_CONTRACTS],["append",APPEND_FLAG_CONTRACTS],["claim",CLAIM_FLAG_CONTRACTS],["release",RELEASE_FLAG_CONTRACTS],["start-task",START_TASK_FLAG_CONTRACTS],["pause-task",PAUSE_TASK_FLAG_CONTRACTS],["close-task",CLOSE_TASK_FLAG_CONTRACTS],["comments",COMMENTS_FLAG_CONTRACTS],["notes",NOTES_FLAG_CONTRACTS],["learnings",LEARNINGS_FLAG_CONTRACTS],["files",FILES_FLAG_CONTRACTS],["docs",DOCS_FLAG_CONTRACTS],["test",TEST_FLAG_CONTRACTS],["test-runs-worker",[]],["test-all",TEST_ALL_FLAG_CONTRACTS],["telemetry",TELEMETRY_FLAG_CONTRACTS],["test-runs",TEST_RUNS_FLAG_CONTRACTS],["gc",GC_FLAG_CONTRACTS],["stats",STATS_FLAG_CONTRACTS],["ops",[]],["duplicates",DUPLICATES_FLAG_CONTRACTS],["validate",VALIDATE_FLAG_CONTRACTS],["health",HEALTH_FLAG_CONTRACTS],["assurance",ASSURANCE_FLAG_CONTRACTS],...PM_POSITIONAL_ACTION_FLAG_CONTRACTS,["contracts",CONTRACTS_FLAG_CONTRACTS],["completion",COMPLETION_FLAG_CONTRACTS],["activity",ACTIVITY_FLAG_CONTRACTS],...[...LIST_COMMAND_NAMES].map(command=>[command,LIST_FILTER_FLAG_CONTRACTS])];const CORE_COMMAND_FLAG_CONTRACTS_BY_COMMAND=new Map(CORE_COMMAND_FLAG_CONTRACT_ENTRIES);for(const{alias,canonical}of PM_NAMESPACED_COMMAND_ALIASES){const flags=CORE_COMMAND_FLAG_CONTRACTS_BY_COMMAND.get(alias);if(flags!==void 0)CORE_COMMAND_FLAG_CONTRACTS_BY_COMMAND.set(canonical,flags)}function packageOwnedActionForCommand(command){const exactAction=PACKAGE_OWNED_COMMAND_ACTIONS.get(command);if(exactAction){return exactAction}if(command.startsWith("test-runs ")){return`test-runs-${command.slice("test-runs ".length)}`}if(command.startsWith("templates ")){return`templates-${command.slice("templates ".length)}`}return command}function resolveActionCommandPath(action){const historyAlias=PM_NAMESPACED_COMMAND_ALIASES.find(contract=>contract.alias===action);if(historyAlias)return`${historyAlias.canonical}|${historyAlias.alias}`;if(PM_CORE_COMMAND_NAMES.includes(action)){return normalizeCommandPath(action)}if(action.startsWith("extension-")){return normalizeCommandPath(`extension ${action.slice("extension-".length)}`)}if(action.startsWith("package-")){return normalizeCommandPath(`package ${action.slice("package-".length)}`)}if(action.startsWith("item-")){return normalizeCommandPath(`item ${action.slice("item-".length)}`)}if(action.startsWith("test-runs-")){return normalizeCommandPath(`test-runs ${action.slice("test-runs-".length)}`)}if(action.startsWith("templates-")){return normalizeCommandPath(`templates ${action.slice("templates-".length)}`)}if(PACKAGE_OWNED_ACTIONS.has(action)){return PACKAGE_OWNED_ACTION_COMMAND_PATHS.get(action)??normalizeCommandPath(action)}return null}function actionDescriptorMatchesSelectedCommand(descriptor,selectedCommand){const historyOperation=resolvePmCommandOperation(selectedCommand);if(historyOperation!==selectedCommand||PM_NAMESPACED_COMMAND_ALIASES.some(entry=>entry.alias===selectedCommand))return descriptor.action===historyOperation;if(descriptor.command_path===null){return false}return splitCommandPathAliases(descriptor.command_path).some(commandPath=>{if(commandPath===selectedCommand){return true}return commandPath.startsWith(`${selectedCommand} `)||selectedCommand.startsWith(`${commandPath} `)})}function splitCommandPathAliases(commandPath){return commandPath.split("|").map(entry=>normalizeCommandPath(entry)).filter(entry=>entry.length>0)}function resolveScopedCommandsFromActionDescriptors(descriptors,commandCatalog){const commandSet=new Set(commandCatalog);const scoped=new Set;for(const descriptor of descriptors){if(!descriptor.command_path){continue}for(const commandPath of splitCommandPathAliases(descriptor.command_path)){const tokens=commandPath.split(" ").filter(entry=>entry.length>0);if(tokens.length===0){continue}for(let end=tokens.length;end>0;end-=1){const candidate=tokens.slice(0,end).join(" ");if(!commandSet.has(candidate)){continue}scoped.add(candidate);break}}}return[...scoped].sort((left,right)=>left.localeCompare(right))}function normalizeToken(value){if(typeof value!=="string"){return void 0}const trimmed=value.trim().toLowerCase();return trimmed.length>0?trimmed:void 0}function extractActionBranches(schema){const oneOf=schema.oneOf;if(!Array.isArray(oneOf)){return[]}return oneOf.filter(entry=>typeof entry==="object"&&entry!==null)}function filterSchemaByAction(schema,action){if(!action){return{...schema}}const branches=extractActionBranches(schema);const filtered=branches.filter(entry=>{const properties=entry.properties;if(typeof properties!=="object"||properties===null){return false}const actionProperty=properties.action;if(typeof actionProperty!=="object"||actionProperty===null){return false}return actionProperty.const===action});return{...schema,oneOf:filtered}}function filterSchemaByActions(schema,actions){const branches=extractActionBranches(schema);const filtered=branches.filter(entry=>{const properties=entry.properties;if(typeof properties!=="object"||properties===null){return false}const actionProperty=properties.action;if(typeof actionProperty!=="object"||actionProperty===null){return false}const actionConst=actionProperty.const;return typeof actionConst==="string"&&actions.has(actionConst)});return{...schema,oneOf:filtered}}function normalizeCommandPath(value){return value.trim().toLowerCase().split(/\s+/).filter(entry=>entry.length>0).join(" ")}function normalizeActionNameFromCommand(commandPath){return commandPath.replace(/\s+/g,"-")}function toOptionalTrimmedString(value){if(typeof value!=="string"){return null}const trimmed=value.trim();return trimmed.length>0?trimmed:null}function normalizeStringList(values){if(!Array.isArray(values)){return[]}const normalized=[];const seen=new Set;for(const value of values){const trimmed=toOptionalTrimmedString(value);if(!trimmed||seen.has(trimmed)){continue}seen.add(trimmed);normalized.push(trimmed)}return normalized}function assignExtensionFlagBoolean(contract,key,enabled){if(enabled){contract[key]=true}}function normalizeExtensionFlagName(value,kind){if(value==null){return null}if(typeof value!=="string"){throw new TypeError("Expected string for extension flag name.")}const trimmed=value.trim();if(trimmed.length===0){return null}if(kind==="long"){return trimmed.startsWith("--")&&trimmed.length>2?trimmed:null}return trimmed.startsWith("-")&&!trimmed.startsWith("--")&&trimmed.length>1?trimmed:null}function toExtensionFlagContract(definition){const normalizedLong=normalizeExtensionFlagName(definition.long,"long");const normalizedShort=normalizeExtensionFlagName(definition.short,"short");const flag=normalizedLong??normalizedShort;if(!flag){return null}const contract={flag};if(normalizedShort&&normalizedLong){contract.short=normalizedShort}assignExtensionFlagBoolean(contract,"required",definition.required===true);assignExtensionFlagBoolean(contract,"repeatable",definition.repeatable===true);assignExtensionFlagBoolean(contract,"list",definition.list===true);const description=toOptionalTrimmedString(definition.description);if(description){contract.description=description}const valueName=toOptionalTrimmedString(definition.value_name);if(valueName){contract.value_name=valueName}const rawValueType=[toOptionalTrimmedString(definition.value_type),toOptionalTrimmedString(definition.type),valueName?"string":null].find(candidate=>candidate==="string"||candidate==="number"||candidate==="boolean");if(rawValueType){contract.value_type=rawValueType}return contract}function collectExtensionFlagContractsByCommand(registrations){const grouped=new Map;for(const registration of registrations){const commandPath=normalizeCommandPath(registration.target_command);if(commandPath.length===0){continue}const bucket=grouped.get(commandPath)??{flags:[],sources:[],dedupe:new Set,sourceDedupe:new Set};const sourceKey=`${registration.layer}:${registration.name}`;if(!bucket.sourceDedupe.has(sourceKey)){bucket.sourceDedupe.add(sourceKey);bucket.sources.push({layer:registration.layer,name:registration.name})}for(const definition of registration.flags){const contract=toExtensionFlagContract(definition);if(!contract){continue}const key=`${contract.flag}|${contract.short??""}`;if(bucket.dedupe.has(key)){continue}bucket.dedupe.add(key);bucket.flags.push(contract)}grouped.set(commandPath,bucket)}const normalized=new Map;for(const[commandPath,bucket]of grouped.entries()){normalized.set(commandPath,{flags:bucket.flags,sources:bucket.sources.sort((left,right)=>{const layerOrder=left.layer.localeCompare(right.layer);if(layerOrder!==0){return layerOrder}return(left.name??"").localeCompare(right.name??"")})})}return normalized}function collectExtensionCommandContracts(runtimeProbe){const flagsByCommand=collectExtensionFlagContractsByCommand(runtimeProbe.flagRegistrations);const definitionsByCommand=new Map;for(const definition of runtimeProbe.commandDefinitions){const command=normalizeCommandPath(definition.command);if(command.length===0){continue}const action=toOptionalTrimmedString(definition.action)??normalizeActionNameFromCommand(command);const args=Array.isArray(definition.arguments)?definition.arguments.map(argument=>{const name=toOptionalTrimmedString(argument.name);if(!name){return null}return{name,required:argument.required===true,variadic:argument.variadic===true,description:toOptionalTrimmedString(argument.description)}}).filter(argument=>argument!==null):[];definitionsByCommand.set(command,{...definition.tier===void 0?{}:{tier:definition.tier},command,action,source:{layer:definition.layer,name:definition.name},description:toOptionalTrimmedString(definition.description),intent:toOptionalTrimmedString(definition.intent),arguments:args,flags:flagsByCommand.get(command)?.flags??[],examples:normalizeStringList(definition.examples),failure_hints:normalizeStringList(definition.failure_hints)})}const extensionCommands=new Set;for(const command of runtimeProbe.handlers){extensionCommands.add(normalizeCommandPath(command))}for(const command of definitionsByCommand.keys()){extensionCommands.add(command)}for(const command of flagsByCommand.keys()){extensionCommands.add(command)}const contracts=[];for(const command of[...extensionCommands].sort((left,right)=>left.localeCompare(right))){const definition=definitionsByCommand.get(command);contracts.push(buildCollectedExtensionCommandContract(command,definition,flagsByCommand.get(command)?.flags??[]))}return contracts}function buildCollectedExtensionCommandContract(command,definition,registeredFlags){if(definition){return{...definition,flags:definition.flags.length>0?definition.flags:registeredFlags}}return{command,action:normalizeActionNameFromCommand(command),source:null,description:null,intent:null,arguments:[],flags:registeredFlags,examples:[],failure_hints:[]}}function extensionSchemaPropertyNameFromFlag(flag){const normalized=flag.flag.replace(/^-+/,"").trim();if(normalized.length===0){return null}const camelCased=normalized.replace(/-([a-z0-9])/g,(_match,char)=>char.toUpperCase());const cleaned=camelCased.replace(/[^a-zA-Z0-9]/g,"");return cleaned.length>0?cleaned:null}function buildExtensionArgumentSchema(argument,action){if(argument.variadic){return{type:"array",items:{type:"string"},description:argument.description??`Variadic argument '${argument.name}' for extension action '${action}'.`}}return{type:"string",description:argument.description??`Argument '${argument.name}' for extension action '${action}'.`}}function buildExtensionFlagSchema(flag,action){const valueType=flag.value_type??"boolean";const schemaType=valueType==="boolean"?"boolean":valueType==="number"?["number","string"]:"string";const acceptsMultipleValues=flag.repeatable===true||flag.list===true;return{type:acceptsMultipleValues?"array":schemaType,...acceptsMultipleValues?{items:{type:schemaType}}:{},description:flag.description??`Extension option '${flag.flag}' for action '${action}'.`}}function buildExtensionActionSchemaBranch(contract){const commands=contract.command.split("|").map(command=>command.trim()).filter(command=>command.length>0);const properties={action:{type:"string",const:contract.action,description:contract.intent??contract.description??`Invoke extension command '${contract.command}'.`}};const required=["action"];for(const argument of contract.arguments){properties[argument.name]=buildExtensionArgumentSchema(argument,contract.action);if(argument.required){required.push(argument.name)}}for(const flag of contract.flags){const propertyName=extensionSchemaPropertyNameFromFlag(flag);if(!propertyName||properties[propertyName]!==void 0){continue}properties[propertyName]=buildExtensionFlagSchema(flag,contract.action);if(flag.required===true){required.push(propertyName)}}return{type:"object",properties,required,additionalProperties:true,"x-extension-source":contract.source,"x-extension-command":commands[0]??contract.command,"x-extension-commands":commands}}function mergeExtensionFlagContract(existing,incoming){existing.description??=incoming.description;existing.value_name??=incoming.value_name;existing.value_type??=incoming.value_type;if(incoming.required===true){existing.required=true}if(incoming.repeatable===true){existing.repeatable=true}}function mergeExtensionContractsByAction(contracts){const byAction=new Map;for(const contract of contracts){const existing=byAction.get(contract.action);if(!existing){byAction.set(contract.action,{...contract,flags:[...contract.flags],examples:[...contract.examples],failure_hints:[...contract.failure_hints]});continue}existing.command=[...new Set([existing.command,contract.command])].sort((left,right)=>left.localeCompare(right)).join("|");existing.arguments=existing.arguments.length>=contract.arguments.length?existing.arguments:contract.arguments;const flagKeys=new Set(existing.flags.map(flag=>`${flag.flag}|${flag.short??""}`));for(const flag of contract.flags){const key=`${flag.flag}|${flag.short??""}`;if(!flagKeys.has(key)){flagKeys.add(key);existing.flags.push(flag)}else{const existingFlag=existing.flags.find(candidate=>`${candidate.flag}|${candidate.short??""}`===key);if(existingFlag){mergeExtensionFlagContract(existingFlag,flag)}}}existing.examples=[...new Set([...existing.examples,...contract.examples])];existing.failure_hints=[...new Set([...existing.failure_hints,...contract.failure_hints])]}return[...byAction.values()].sort((left,right)=>left.action.localeCompare(right.action))}async function resolveRuntimeExtensionActionProbe(global2,readSettingsFn=readSettings){const defaultPolicyState={mode:SETTINGS_DEFAULTS.extensions.policy.mode,trust_mode:SETTINGS_DEFAULTS.extensions.policy.trust_mode,default_sandbox_profile:SETTINGS_DEFAULTS.extensions.policy.default_sandbox_profile};if(global2.noExtensions){return{handlers:new Set,disabledReason:"extensions_disabled",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:defaultPolicyState}}const pmRoot=resolvePmRoot(process.cwd(),global2.path);if(!await pathExists(getSettingsPath(pmRoot))){return{handlers:new Set,disabledReason:null,commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:defaultPolicyState}}try{const settings=await readSettingsFn(pmRoot);const loadResult=await loadExtensions({pmRoot,settings,cwd:process.cwd(),noExtensions:false});const activationResult=await activateExtensions({...loadResult,loaded:loadResult.loaded});const handlers=new Set(activationResult.commands.handlers.map(entry=>normalizeCommandPath(entry.command)));return{handlers,disabledReason:null,commandDefinitions:activationResult.registrations.commands,flagRegistrations:activationResult.registrations.flags,registrations:activationResult.registrations,policyState:{mode:loadResult.policy.mode,trust_mode:loadResult.policy.trust_mode,default_sandbox_profile:loadResult.policy.default_sandbox_profile}}}catch{return{handlers:new Set,disabledReason:"extension_runtime_probe_failed",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:defaultPolicyState}}}function collectActionContractDescriptors(extensionContracts,options={}){const descriptors=new Map;for(const action of PM_TOOL_ACTIONS){const packageOwned=PACKAGE_OWNED_ACTIONS.has(action);if(packageOwned&&!options.includePackageOwnedActions){continue}const commandPath=resolveActionCommandPath(action);descriptors.set(action,{action,provider:packageOwned?"extension":"core",requires_extension:packageOwned,command_path:commandPath})}if(options.includePackageOwnedActions){for(const action of PACKAGE_OWNED_ACTIONS){if(descriptors.has(action)){continue}descriptors.set(action,{action,provider:"extension",requires_extension:true,command_path:resolveActionCommandPath(action)})}}for(const contract of extensionContracts){if(descriptors.has(contract.action)){continue}descriptors.set(contract.action,{action:contract.action,provider:"extension",requires_extension:true,command_path:PM_NAMESPACED_COMMAND_ALIASES.find(entry=>entry.alias===contract.command)?.canonical??normalizeCommandPath(contract.command)})}return[...descriptors.values()].sort((left,right)=>(left.action??"").localeCompare(right.action??""))}function resolveActionAvailability(descriptor,runtimeProbe){if(descriptor.provider==="core"&&!descriptor.requires_extension){return{action:descriptor.action,invocable:true,available:true,requires_extension:false,provider:"core",disabled_reason:null,command_path:descriptor.command_path,cli_exposed:descriptor.command_path!==null}}const commandPaths=descriptor.command_path?splitCommandPathAliases(descriptor.command_path):[];const extensionCommandAvailable=commandPaths.some(commandPath=>runtimeProbe.handlers.has(commandPath)||runtimeProbe.handlers.has(resolvePmCommandOperation(commandPath)));const optionalPackageHint=commandPaths.map(commandPath=>PACKAGE_OWNED_COMMAND_INSTALL_HINTS.get(resolvePmCommandOperation(commandPath))).find(hint=>typeof hint==="string");const invocable=runtimeProbe.disabledReason===null&&extensionCommandAvailable;return{action:descriptor.action,invocable,available:invocable,requires_extension:true,provider:"extension",disabled_reason:invocable?null:runtimeProbe.disabledReason??(optionalPackageHint?`optional_package_not_installed:${optionalPackageHint}`:"extension_command_not_registered"),command_path:descriptor.command_path,cli_exposed:extensionCommandAvailable,policy_state:{mode:runtimeProbe.policyState.mode,trust_mode:runtimeProbe.policyState.trust_mode,default_sandbox_profile:runtimeProbe.policyState.default_sandbox_profile}}}function resolveCoreCommandFlags(command){return CORE_COMMAND_FLAG_CONTRACTS_BY_COMMAND.get(command)??GLOBAL_FLAG_CONTRACTS}function isCoreCommandPath(command){if(PACKAGE_OWNED_COMMANDS.has(resolvePmCommandOperation(command))){return false}return CORE_COMMAND_FLAG_CONTRACTS_BY_COMMAND.has(command)}function normalizeCommandForRuntimeFieldFlags(command){if(LIST_COMMAND_NAMES.has(command)){return"list"}if(command==="cal"){return"calendar"}if(command==="ctx"){return"context"}if(command==="update-many"){return"update_many"}return command}function toRuntimeLongFlagToken(token){const trimmed=token.trim();if(!trimmed){return null}if(trimmed.startsWith("--")){return trimmed}if(trimmed.startsWith("-")){return null}return`--${trimmed}`}function toRuntimeShortFlagToken(token){const trimmed=token.trim();if(!trimmed){return null}if(trimmed.startsWith("--")){return null}if(trimmed.startsWith("-")){return trimmed}return null}function buildRuntimeFieldFlagContracts(fieldRegistry){const buckets=new Map;for(const definition of fieldRegistry.definitions){const primaryFlag=toRuntimeLongFlagToken(definition.cli_flag);if(!primaryFlag){continue}const shortAlias=definition.cli_aliases.map(alias=>toRuntimeShortFlagToken(alias)).find(alias=>alias!==null);const longAliases=definition.cli_aliases.map(alias=>toRuntimeLongFlagToken(alias)).filter(alias=>alias!==null&&alias!==primaryFlag);for(const command of definition.commands){const bucket=buckets.get(command)??{flags:[],seen:new Set};const primaryContract=shortAlias?{flag:primaryFlag,short:shortAlias}:{flag:primaryFlag};const primaryKey=`${primaryContract.flag}|${primaryContract.short??""}`;if(!bucket.seen.has(primaryKey)){bucket.seen.add(primaryKey);bucket.flags.push(primaryContract)}for(const alias of longAliases){const key=`${alias}|`;if(bucket.seen.has(key)){continue}bucket.seen.add(key);bucket.flags.push({flag:alias})}buckets.set(command,bucket)}}const result=new Map;for(const[command,bucket]of buckets.entries()){result.set(command,compactFlagAliasContracts(bucket.flags))}return result}function mergeFlagContracts(primary,secondary){const merged=[];const seen=new Set;for(const contract of[...primary,...secondary]){const key=`${contract.flag}|${contract.short??""}`;if(seen.has(key)){continue}seen.add(key);merged.push(contract)}return compactFlagAliasContracts(merged)}function buildCommandFlagSurface(commands,extensionFlagMap,runtimeFieldFlagMap,includeSemanticMetadata,extensionContracts){const flagsByPath=new Map(extensionFlagMap);for(const{alias,canonical}of PM_NAMESPACED_COMMAND_ALIASES){const flags=extensionFlagMap.get(canonical)??extensionFlagMap.get(alias);if(flags){flagsByPath.set(alias,flags);flagsByPath.set(canonical,flags)}}return commands.map(command=>{const isCoreCommand=isCoreCommandPath(command);const coreFlags=isCoreCommand?resolveCoreCommandFlags(command):[];const runtimeFlags=runtimeFieldFlagMap.get(normalizeCommandForRuntimeFieldFlags(command))??[];const extensionFlags=flagsByPath.get(command);const coreWithRuntime=mergeFlagContracts(coreFlags,runtimeFlags);const flags=mergeFlagContracts(coreWithRuntime,extensionFlags?.flags??[]);const provider=coreFlags.length>0&&(extensionFlags?.flags.length??0)>0?"mixed":isCoreCommand?"core":"extension";return{command,flags,...includeSemanticMetadata?{canonical_command:canonicalSummaryCommand(command),visibility:runtimeCommandVisibilityTier(command,extensionContracts),positionals:resolvePmCommandPositionalContract(command)?.slots??[],flag_invocations:enrichCliFlagInvocationContracts(command,flags)}:{},provider,extension_sources:extensionFlags?.sources}}).sort((left,right)=>left.command.localeCompare(right.command))}function buildCommandAliasSurface(commands,aliasContracts=PM_COMMAND_ALIAS_CONTRACTS){const commandSet=new Set(commands);const grouped=new Map;for(const entry of CANONICAL_COMMAND_ALIASES){const aliases=entry.aliases.filter(alias=>commandSet.has(alias));grouped.set(entry.canonical,{canonical:entry.canonical,aliases,contracts:[]})}for(const contract of aliasContracts){if(!commandSet.has(contract.canonical)){continue}if(contract.registration==="commander"&&!commandSet.has(contract.alias)){continue}const entry=grouped.get(contract.canonical)??{canonical:contract.canonical,aliases:[],contracts:[]};if(!entry.aliases.includes(contract.alias)){entry.aliases.push(contract.alias)}entry.contracts.push(contract);grouped.set(contract.canonical,entry)}return[...grouped.values()].map(({contracts,...entry})=>contracts.length===0?entry:{...entry,contracts}).sort((left,right)=>left.canonical.localeCompare(right.canonical))}function buildCommanderAliasSurface(){return{create_string_options:CREATE_COMMANDER_STRING_OPTION_CONTRACTS,create_repeatable_options:CREATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS,update_string_options:UPDATE_COMMANDER_STRING_OPTION_CONTRACTS,update_repeatable_options:UPDATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS,list_string_options:LIST_COMMANDER_STRING_OPTION_CONTRACTS,search_string_options:SEARCH_COMMANDER_STRING_OPTION_CONTRACTS,calendar_string_options:CALENDAR_COMMANDER_STRING_OPTION_CONTRACTS,context_string_options:CONTEXT_COMMANDER_STRING_OPTION_CONTRACTS,activity_string_options:ACTIVITY_COMMANDER_STRING_OPTION_CONTRACTS}}function resolveCreateRequiredOptionContract(typeDefinition,createMode){const baseRequiredOptions=new Set(["title","type"]);if(createMode==="strict"){for(const field of typeDefinition.required_create_fields){baseRequiredOptions.add(field)}for(const field of typeDefinition.required_create_repeatables){baseRequiredOptions.add(field)}}const policyState=resolveCommandOptionPolicyState(typeDefinition,"create",baseRequiredOptions);const requiredOptionKeys=[...new Set(policyState.required)].sort((left,right)=>left.localeCompare(right));const requiredFlags=[...new Set(requiredOptionKeys.map(option=>commandOptionFlagLabel("create",option)))].sort((left,right)=>left.localeCompare(right));const requiredTypeOptions=[...new Set(typeDefinition.options.filter(option=>option.required===true).map(option=>option.key))].sort((left,right)=>left.localeCompare(right));return{required_option_keys:requiredOptionKeys,required_flags:requiredFlags,required_type_options:requiredTypeOptions,policy_errors:[...new Set(policyState.errors)].sort((left,right)=>left.localeCompare(right))}}function buildCreateRequiredOptionContracts(typeRegistry){const byTypeStrict={};const byTypeProgressive={};for(const typeName of[...typeRegistry.types].sort((left,right)=>left.localeCompare(right))){const typeDefinition=typeRegistry.by_type[typeName];byTypeStrict[typeName]=resolveCreateRequiredOptionContract(typeDefinition,"strict");byTypeProgressive[typeName]=resolveCreateRequiredOptionContract(typeDefinition,"progressive")}return{default_create_mode:"strict",by_create_mode:{strict:{by_type:byTypeStrict},progressive:{by_type:byTypeProgressive}}}}function attachCreateRequiredOptionContracts(schema,metadata){const branches=extractActionBranches(schema);if(branches.length===0){return schema}let touched=false;const enrichedBranches=branches.map(branch=>{const properties=branch.properties;if(typeof properties!=="object"||properties===null){return branch}const actionProperty=properties.action;if(typeof actionProperty!=="object"||actionProperty===null){return branch}if(actionProperty.const!=="create"){return branch}touched=true;return{...branch,"x-create-required-options":metadata}});if(!touched){return schema}return{...schema,oneOf:enrichedBranches}}function resolveContractsSelection(options){const explicitlyScoped=normalizeToken(options.action)!==void 0||normalizeToken(options.command)!==void 0;const projectionSelected=options.schemaOnly===true||options.flagsOnly===true||options.availabilityOnly===true;const summary=options.summary===true||options.full!==true&&options.runtimeOnly!==true&&!explicitlyScoped&&!projectionSelected;const schemaOnly=options.schemaOnly===true;const flagsOnly=options.flagsOnly===true;const availabilityOnly=options.availabilityOnly===true;const runtimeOnly=options.runtimeOnly===true;const fullOutput=options.full===true;const selectedAction=normalizeToken(options.action);const selectedCommand=normalizeToken(options.command);const unfilteredDefaultBriefMode=!summary&&!fullOutput&&!schemaOnly&&!flagsOnly&&!availabilityOnly&&!selectedAction&&!selectedCommand;return{selectedAction,selectedCommand,summary,schemaOnly,flagsOnly,availabilityOnly,runtimeOnly,fullOutput,omitUnfilteredSchema:unfilteredDefaultBriefMode,omitUnfilteredCommandFlags:unfilteredDefaultBriefMode,omitUnfilteredCommanderAliases:unfilteredDefaultBriefMode||selectedCommand!==void 0&&!fullOutput}}function assertSingleContractsProjection(selection){const projectionFlagsEnabled=[selection.summary,selection.schemaOnly,selection.flagsOnly,selection.availabilityOnly].filter(value=>value).length;if(projectionFlagsEnabled>1){throw new PmCliError("Choose only one projection flag: --summary, --schema-only, --flags-only, or --availability-only.",EXIT_CODE.USAGE)}}async function readContractsSettings(pmRoot,readSettingsFn=readSettings){try{return await readSettingsFn(pmRoot)}catch{return structuredClone(SETTINGS_DEFAULTS)}}async function resolveContractsRuntimeContext(global2,pmRoot,selection){const settings=await readContractsSettings(pmRoot);const runtimeProbe=await resolveRuntimeExtensionActionProbe(global2);const typeRegistry=resolveItemTypeRegistry(settings,runtimeProbe.registrations??getActiveExtensionRegistrations());const runtimeFieldRegistry=resolveRuntimeFieldRegistry(settings.schema);const extensionContracts=collectExtensionCommandContracts(runtimeProbe);return{settings,runtimeProbe,typeRegistry,statusRegistry:resolveRuntimeStatusRegistry(settings.schema),runtimeFieldRegistry,runtimeFieldFlagMap:buildRuntimeFieldFlagContracts(runtimeFieldRegistry),createRequiredOptionContracts:buildCreateRequiredOptionContracts(typeRegistry),extensionContracts,mergedExtensionContracts:mergeExtensionContractsByAction(extensionContracts.filter(entry=>isCommandDiscoverable(selection,entry.command,extensionContracts))),extensionFlagMap:collectExtensionFlagContractsByCommand(runtimeProbe.flagRegistrations)}}function shouldIncludePackageOwnedActions(selection){return selection.availabilityOnly&&(selection.selectedAction!==void 0&&PACKAGE_OWNED_ACTIONS.has(selection.selectedAction)||selection.selectedCommand!==void 0&&PACKAGE_OWNED_COMMANDS.has(resolvePmCommandOperation(selection.selectedCommand)))}function collectContractsActionDescriptors(selection,mergedExtensionContracts){const actionDescriptors=collectActionContractDescriptors(mergedExtensionContracts,{includePackageOwnedActions:shouldIncludePackageOwnedActions(selection)});if(selection.selectedAction===void 0&&selection.selectedCommand===void 0){const deprecatedActions=new Set(PM_DEPRECATED_TOOL_ACTIONS);return actionDescriptors.filter(descriptor=>!deprecatedActions.has(descriptor.action)&&(selection.fullOutput||(mergedExtensionContracts.find(entry=>entry.action===descriptor.action)?.tier??resolvePmCommandVisibilityTier(descriptor.action))!=="internal"))}if(shouldIncludePackageOwnedActions(selection)&&selection.selectedCommand!==void 0&&PACKAGE_OWNED_COMMANDS.has(resolvePmCommandOperation(selection.selectedCommand))&&!actionDescriptors.some(entry=>entry.command_path===selection.selectedCommand)){actionDescriptors.push({action:packageOwnedActionForCommand(resolvePmCommandOperation(selection.selectedCommand)),provider:"extension",requires_extension:true,command_path:selection.selectedCommand})}return actionDescriptors}function assertKnownContractsAction(selection,actionDescriptors){const actionNames=new Set(actionDescriptors.map(entry=>entry.action));if(selection.selectedAction&&!actionNames.has(selection.selectedAction)){throw new PmCliError(`Unknown action: "${selection.selectedAction}".`,EXIT_CODE.USAGE)}}function buildContractsCommandCatalog(actionDescriptors,mergedExtensionContracts){return[...new Set([...PM_CORE_COMMAND_NAMES.filter(entry=>!PACKAGE_OWNED_COMMANDS.has(resolvePmCommandOperation(entry))),...[...CORE_COMMAND_FLAG_CONTRACTS_BY_COMMAND.keys()].filter(entry=>!PACKAGE_OWNED_COMMANDS.has(resolvePmCommandOperation(entry))),...actionDescriptors.flatMap(entry=>entry.command_path?splitCommandPathAliases(entry.command_path):[]),...mergedExtensionContracts.flatMap(entry=>entry.command.split("|").flatMap(command=>{const alias=PM_NAMESPACED_COMMAND_ALIASES.find(entry2=>entry2.alias===command||entry2.canonical===command);return alias===void 0?[command]:[alias.alias,alias.canonical]}))])].map(entry=>normalizeCommandPath(entry)).filter(entry=>entry.length>0).sort((left,right)=>left.localeCompare(right))}function buildCommandNamespaceError(command,namespaceChildren){const displayedNamespaceChildren=namespaceChildren.slice(0,COMMAND_NAMESPACE_DISPLAY_LIMIT);const hiddenNamespaceChildCount=namespaceChildren.length-displayedNamespaceChildren.length;const displayedChildCommandList=hiddenNamespaceChildCount>0?`${displayedNamespaceChildren.join(", ")}, and ${hiddenNamespaceChildCount} more`:displayedNamespaceChildren.join(", ");const fallbackCandidates=namespaceChildren.slice(0,COMMAND_NAMESPACE_FALLBACK_LIMIT);const childCommandExamples=namespaceChildren.slice(0,5).map(childCommand=>`pm contracts --command "${childCommand}" --flags-only --json`);const suggestedChildCommand=namespaceChildren[0];return new PmCliError(`Command "${command}" is a command namespace. Choose a concrete child command: ${displayedChildCommandList}.`,EXIT_CODE.USAGE,{code:"command_namespace",required:"Use a concrete child command path listed under this namespace.",why:"Command groups expose help at the namespace root, but command flag contracts belong to executable child commands.",examples:childCommandExamples,nextSteps:[`Retry with a child command, for example: ${childCommandExamples[0]}`],recovery:{suggested_retry:`pm contracts --command "${suggestedChildCommand}" --flags-only --json`,fallback_candidates:fallbackCandidates.map(childCommand=>({source:"command_namespace",command:`pm contracts --command "${childCommand}" --flags-only --json`,reason:`Child command under ${command}`}))}})}function buildPackageOwnedCommandError(command,packageHint){return new PmCliError(`Unknown command: "${command}". Command "${command}" is provided by the optional "${packageHint}" package. Run "pm install ${packageHint} --project" and retry.`,EXIT_CODE.USAGE,{code:"unknown_command",required:`Install the optional "${packageHint}" package, or choose a command from pm contracts --flags-only --json.`,why:"Command contracts include core commands plus commands registered by active packages and extensions.",examples:[`pm install ${packageHint} --project`,`pm contracts --command ${command} --flags-only --json`],nextSteps:[`Install the optional package first: pm install ${packageHint} --project`],recovery:{suggested_retry:`pm install ${packageHint} --project`}})}function buildUnknownCommandError(command){return new PmCliError(`Unknown command: "${command}".`,EXIT_CODE.USAGE,{code:"unknown_command",required:"Use a command path listed by pm contracts --flags-only --json.",why:"Command contracts are generated from the active core, package, and extension command registry.",examples:["pm contracts --flags-only --json","pm --help"],nextSteps:["Verify spelling and active packages/extensions, then rerun with a known command path."],recovery:{suggested_retry:"pm contracts --flags-only --json"}})}function assertKnownContractsCommand(selection,commandCatalog){if(!selection.selectedCommand){return}const commandNames=new Set(commandCatalog);if(commandNames.has(selection.selectedCommand)){return}const namespaceChildren=commandCatalog.filter(command=>command.startsWith(`${selection.selectedCommand} `));if(namespaceChildren.length>0){throw buildCommandNamespaceError(selection.selectedCommand,namespaceChildren)}const packageHint=PACKAGE_OWNED_COMMAND_INSTALL_HINTS.get(resolvePmCommandOperation(selection.selectedCommand));if(packageHint){throw buildPackageOwnedCommandError(selection.selectedCommand,packageHint)}throw buildUnknownCommandError(selection.selectedCommand)}function resolveContractsActionContext(selection,runtime){const actionDescriptors=collectContractsActionDescriptors(selection,runtime.mergedExtensionContracts);assertKnownContractsAction(selection,actionDescriptors);const commandCatalog=buildContractsCommandCatalog(actionDescriptors,runtime.mergedExtensionContracts);assertKnownContractsCommand(selection,commandCatalog);const selectedPackageOwnedAction=selection.selectedCommand?PACKAGE_OWNED_COMMAND_ACTIONS.get(resolvePmCommandOperation(selection.selectedCommand)):void 0;const commandScopedDescriptors=selection.selectedCommand?actionDescriptors.filter(descriptor=>selectedPackageOwnedAction?descriptor.action===selectedPackageOwnedAction:actionDescriptorMatchesSelectedCommand(descriptor,selection.selectedCommand)):actionDescriptors;if(selection.selectedCommand&&selection.selectedAction&&!commandScopedDescriptors.some(descriptor=>descriptor.action===selection.selectedAction)){throw new PmCliError(`Action "${selection.selectedAction}" is not mapped to command "${selection.selectedCommand}" in contracts output.`,EXIT_CODE.USAGE)}const scopedActionDescriptors=selection.selectedAction?commandScopedDescriptors.filter(descriptor=>descriptor.action===selection.selectedAction):commandScopedDescriptors;const allActionAvailability=[...new Map(scopedActionDescriptors.map(descriptor=>resolveActionAvailability(descriptor,runtime.runtimeProbe)).map(entry=>[selectedPackageOwnedAction?entry.action:`${entry.action}|${entry.command_path??""}`,entry])).values()];const actionAvailability=selection.runtimeOnly&&!selection.selectedAction&&!selection.availabilityOnly?allActionAvailability.filter(entry=>entry.invocable):allActionAvailability;return{actionDescriptors,commandCatalog,commandScopedDescriptors,scopedActionDescriptors,selectedPackageOwnedAction,actionAvailability,actions:[...new Set(actionAvailability.map(entry=>entry.action))]}}function buildSchemaActionSet(schema){return new Set(extractActionBranches(schema).map(entry=>{const properties=entry.properties;if(typeof properties!=="object"||properties===null){return null}const actionProperty=properties.action;if(typeof actionProperty!=="object"||actionProperty===null){return null}const actionConst=actionProperty.const;return typeof actionConst==="string"?actionConst:null}).filter(entry=>entry!==null))}function buildMergedContractsSchema(mergedExtensionContracts){const schema=PM_TOOL_PARAMETERS_SCHEMA;const schemaBranches=extractActionBranches(schema);const schemaActionSet=buildSchemaActionSet(schema);const extensionBranches=mergedExtensionContracts.filter(contract=>!schemaActionSet.has(contract.action)).map(contract=>buildExtensionActionSchemaBranch(contract));return extensionBranches.length>0?{...schema,oneOf:[...schemaBranches,...extensionBranches]}:schema}function filterContractsSchema(selection,actionContext,mergedSchema){const descriptorActionSet=new Set(actionContext.actionDescriptors.map(descriptor=>descriptor.action));const filteredSchema=selection.selectedAction?filterSchemaByAction(mergedSchema,selection.selectedAction):selection.selectedCommand?filterSchemaByActions(mergedSchema,new Set(actionContext.scopedActionDescriptors.map(descriptor=>descriptor.action))):filterSchemaByActions(mergedSchema,descriptorActionSet);return selection.runtimeOnly&&!selection.selectedAction?filterSchemaByActions(filteredSchema,new Set(actionContext.actions)):filteredSchema}function resolveContractsSchemaContext(selection,runtime,actionContext){const mergedSchema=buildMergedContractsSchema(runtime.mergedExtensionContracts);const includeSchemaSurface=!selection.flagsOnly&&!selection.availabilityOnly;const filteredSchema=includeSchemaSurface?attachCreateRequiredOptionContracts(filterContractsSchema(selection,actionContext,mergedSchema),runtime.createRequiredOptionContracts):filterContractsSchema(selection,actionContext,mergedSchema);return{mergedSchema,filteredSchema}}function resolveContractsCommands(selection,actionContext){if(selection.selectedCommand!==void 0){return[selection.selectedCommand]}if(selection.selectedAction){return resolveScopedCommandsFromActionDescriptors(actionContext.scopedActionDescriptors,actionContext.commandCatalog)}return actionContext.commandCatalog}function runtimeCommandVisibilityTier(command,extensionContracts){return extensionContracts.find(entry=>resolvePmCommandOperation(entry.command)===resolvePmCommandOperation(command))?.tier??resolvePmCommandVisibilityTier(command)}function isCommandDiscoverable(selection,command,extensionContracts){return selection.fullOutput||selection.selectedCommand!==void 0||selection.selectedAction!==void 0||runtimeCommandVisibilityTier(command,extensionContracts)!=="internal"}function resolveOutputCommands(selection,commands,extensionContracts){if(selection.selectedCommand!==void 0||selection.selectedAction!==void 0){return commands}const hiddenAliases=new Set(PM_COMMAND_ALIAS_CONTRACTS.filter(contract=>contract.hidden&&(contract.lifecycle==="deprecated"||!selection.fullOutput&&!selection.availabilityOnly)).map(contract=>contract.alias));if(selection.summary&&!selection.fullOutput){for(const alias of COMMAND_ALIAS_TO_CANONICAL.keys())hiddenAliases.add(alias)}return commands.filter(command=>!hiddenAliases.has(command)&&isCommandDiscoverable(selection,command,extensionContracts))}function canonicalSummaryCommand(command){const historyAlias=PM_NAMESPACED_COMMAND_ALIASES.find(contract=>contract.alias===command||contract.canonical===command);if(historyAlias)return historyAlias.canonical;const rootCommand=command.split(" ")[0];if(rootCommand.startsWith("list-"))return"list";return COMMAND_ALIAS_TO_CANONICAL.get(rootCommand)??rootCommand}const COMMAND_OPERATION_INTENTS=new Map([["activate","Activate"],["adopt","Adopt"],["adopt-all","Adopt all"],["catalog","Catalog"],["complete","Complete"],["create","Create"],["deactivate","Deactivate"],["delete","Delete"],["describe","Describe"],["doctor","Diagnose"],["explore","Explore"],["init","Initialize"],["inspect","Inspect"],["install","Install"],["list","List"],["manage","Manage"],["migrate","Migrate"],["mutate","Mutate"],["reload","Reload"],["restore","Restore"],["run","Run"],["snapshot","Manage snapshots for"],["uninstall","Uninstall"],["upgrade","Upgrade"]]);const COMMAND_INTENT_SUBJECT_OVERRIDES=new Map([["extension adopt-all","extensions"],["package adopt-all","packages"],["workspace snapshot list","workspace snapshots"]]);function summarizeCommandIntent(command,extensionContracts){const declared=COMMAND_INTENTS.get(resolvePmCommandOperation(command))??(command.includes(" ")?void 0:COMMAND_INTENTS.get(canonicalSummaryCommand(command)));if(declared!==void 0){return{intent:declared,intent_source:"command"}}const extensionContract=extensionContracts.find(contract=>splitCommandPathAliases(contract.command).some(path=>resolvePmCommandOperation(path)===resolvePmCommandOperation(command)));if(extensionContract?.intent!==null&&extensionContract?.intent!==void 0){return{intent:extensionContract.intent,intent_source:"command"}}if(extensionContract?.description!==null&&extensionContract?.description!==void 0){return{intent:extensionContract.description,intent_source:"description"}}const tokens=command.split(" ");const operation=tokens.at(-1);const subject=tokens.slice(0,-1).join(" ");const verb=COMMAND_OPERATION_INTENTS.get(operation);const intentSubject=COMMAND_INTENT_SUBJECT_OVERRIDES.get(command)??subject;return{intent:verb===void 0||subject.length===0?`Run ${command}.`:`${verb} ${intentSubject}.`,intent_source:"generated"}}function buildCommandSummarySurface(commands,extensionContracts=[],options={}){const includeFormatBudgets=options.includeFormatBudgets??true;const includeIntentProvenance=options.includeIntentProvenance??true;return[...new Set(commands.map(normalizeCommandPath))].filter(command=>command.length>0).sort((left,right)=>left.localeCompare(right)).map(command=>{const budget=resolvePmCommandOutputBudget(command,{generateFallback:true});const rootCommand=command.split(" ")[0];const canonicalRoot=COMMAND_ALIAS_TO_CANONICAL.get(rootCommand)??(rootCommand.startsWith("list-")?"list":rootCommand.startsWith("history-")?"history":rootCommand);const availableFlags=new Set([...resolveCoreCommandFlags(command).map(contract=>contract.flag),...extensionContracts.filter(contract=>splitCommandPathAliases(contract.command).some(path=>resolvePmCommandOperation(path)===resolvePmCommandOperation(command))).flatMap(contract=>contract.flags.map(flag=>flag.flag))]);const flags=(AGENT_BOOTSTRAP_FLAGS.get(resolvePmCommandOperation(command))??AGENT_BOOTSTRAP_FLAGS.get(canonicalRoot)??AGENT_BOUNDED_FLAG_PRIORITY).filter(flag=>availableFlags.has(flag));const intent=summarizeCommandIntent(command,extensionContracts);return{command,intent:intent.intent,...includeIntentProvenance||intent.intent_source!=="command"?{intent_source:intent.intent_source}:{},...flags.length>0?{flags}:{},default_max_estimated_tokens:budget.default_max_estimated_tokens,...includeFormatBudgets?{default_max_estimated_tokens_by_format:{...budget.default_max_estimated_tokens_by_format}}:{}}})}function buildCommandOutputContracts(commands){return commands.map(command=>({budget:resolvePmCommandOutputBudget(command,{generateFallback:true}),envelope:resolvePmCommandOutputEnvelope(command)}))}function buildCommandExitContractGroups(commands){const groups=new Map;for(const command of commands){const contract=resolvePmCommandExitContract(command);const exitCodes=contract===void 0?[EXIT_CODE.SUCCESS,EXIT_CODE.GENERIC_FAILURE,EXIT_CODE.USAGE,EXIT_CODE.NOT_FOUND,EXIT_CODE.CONFLICT,EXIT_CODE.DEPENDENCY_FAILED]:contract.exit_codes;const key=exitCodes.join(",");const group=groups.get(key)??{commands:[],exit_codes:exitCodes};group.commands.push(command);groups.set(key,group)}return[...groups.values()]}function resolveExtensionCommandContracts(selection,runtime,outputCommands){if(selection.selectedCommand){return runtime.extensionContracts.filter(entry=>splitCommandPathAliases(entry.command).some(path=>resolvePmCommandOperation(path)===resolvePmCommandOperation(selection.selectedCommand)))}if(selection.selectedAction){const outputCommandSet=new Set(outputCommands);return runtime.extensionContracts.filter(entry=>splitCommandPathAliases(entry.command).some(command=>outputCommandSet.has(command)))}return runtime.extensionContracts.filter(entry=>isCommandDiscoverable(selection,entry.command,runtime.extensionContracts))}function createContractsResult(selection,schemaContext,actionContext,outputCommands){return{schema_version:typeof schemaContext.mergedSchema["x-schema-version"]==="string"?schemaContext.mergedSchema["x-schema-version"]:null,schema_id:typeof schemaContext.mergedSchema.$id==="string"?schemaContext.mergedSchema.$id:null,selected:{action:selection.selectedAction??null,command:selection.selectedCommand??null,summary:selection.summary,schema_only:selection.schemaOnly,flags_only:selection.flagsOnly,availability_only:selection.availabilityOnly,runtime_only:selection.runtimeOnly,command_scoped:selection.selectedCommand!==void 0},commands:selection.summary?[]:outputCommands,...!selection.summary&&!selection.flagsOnly?{actions:actionContext.actions,action_availability:actionContext.actionAvailability}:{}}}function attachRuntimeContractsResult(result,runtime,selection){if((selection.selectedCommand==="history"||selection.fullOutput)&&!selection.flagsOnly&&!selection.schemaOnly&&!selection.availabilityOnly){result.history_operations=PM_HISTORY_OPERATION_CONTRACT}const selectedCommand=selection.selectedCommand;result.runtime_schema={statuses:runtime.statusRegistry.definitions.map(definition=>definition.id),open_status:runtime.statusRegistry.open_status,close_status:runtime.statusRegistry.close_status,canceled_status:runtime.statusRegistry.canceled_status,types:[...runtime.typeRegistry.types],fields_by_command:Object.fromEntries([...runtime.runtimeFieldRegistry.command_to_fields.entries()].filter(([command])=>selectedCommand===void 0||command===selectedCommand).map(([command,definitions])=>[command,[...new Set(definitions.map(definition=>`--${definition.cli_flag}`))].sort((left,right)=>left.localeCompare(right))]))};if(selectedCommand!==void 0&&!selection.fullOutput){return}result.extension_contracts={capabilities:[...PM_EXTENSION_CAPABILITY_CONTRACTS],services:[...PM_EXTENSION_SERVICE_NAME_CONTRACTS],policy_modes:[...PM_EXTENSION_POLICY_MODE_CONTRACTS],policy_mode_scope:"extensions.policy.mode",policy_surfaces:[...PM_EXTENSION_POLICY_SURFACE_CONTRACTS],trust_modes:[...PM_EXTENSION_TRUST_MODE_CONTRACTS],trust_mode_scope:"extensions.policy.trust_mode",sandbox_profiles:[...PM_EXTENSION_SANDBOX_PROFILE_CONTRACTS],manifest_versions:[1,2],compatibility:{current:"v2",previous:["v1"],breaking_strategy:"versioned_breaking"}};result.governance_contracts={ownership_enforcement_modes:[...GOVERNANCE_OWNERSHIP_ENFORCEMENT_VALUES],create_modes:[...GOVERNANCE_CREATE_MODE_DEFAULT_VALUES],close_validation_modes:[...GOVERNANCE_CLOSE_VALIDATION_DEFAULT_VALUES],workflow_enforcement_modes:[...GOVERNANCE_WORKFLOW_ENFORCEMENT_VALUES]};result.relationship_kind_contracts=[...BUILTIN_RELATIONSHIP_KINDS,...(runtime.runtimeProbe.registrations?.relationship_kinds??[]).flatMap(registration=>registration.definitions)].sort((left,right)=>left.kind.localeCompare(right.kind)).map(definition=>({canonical:definition.kind,aliases:[...definition.aliases??[]],...definition.inverse===void 0?{}:{inverse:definition.inverse},ordering:definition.ordering,hierarchy:definition.hierarchy}))}function attachSchemaContractsResult(result,selection,schemaContext,extensionCommandContracts){if(selection.flagsOnly||selection.availabilityOnly){return}if(!selection.omitUnfilteredSchema){result.schema=schemaContext.filteredSchema;result.extension_commands=extensionCommandContracts;return}result.schema_omitted_reason="unfiltered_default_brief";result.extension_commands=extensionCommandContracts}function attachFlagContractsResult(result,selection,runtime,outputCommands,commandAliases){if(selection.schemaOnly||selection.availabilityOnly){return}if(!selection.omitUnfilteredCommandFlags){result.command_flags=buildCommandFlagSurface(outputCommands,runtime.extensionFlagMap,runtime.runtimeFieldFlagMap,selection.selectedCommand!==void 0,runtime.extensionContracts);const commandSet=new Set(outputCommands);result.list_projections=Object.entries(LIST_COMMAND_DEFAULT_PROJECTIONS).filter(([command])=>commandSet.has(command)).map(([command,defaultProjection])=>({command,default:defaultProjection,brief_fields:[...BRIEF_LIST_FIELDS],compact_fields:[...DEFAULT_COMPACT_LIST_FIELDS]}))}else{result.command_flags_omitted_reason="unfiltered_default_brief"}result.command_aliases=selection.fullOutput?commandAliases:commandAliases.map(({canonical,aliases})=>({canonical,aliases}));if(!selection.fullOutput){result.command_alias_contracts_omitted_reason="compact_projection; restore with --full"}}function attachCommanderAliasContractsResult(result,selection){if(selection.schemaOnly||selection.flagsOnly||selection.availabilityOnly){return}if(!selection.omitUnfilteredCommanderAliases){result.commander_aliases=buildCommanderAliasSurface();return}result.commander_aliases_omitted_reason=selection.selectedCommand?"command_scoped":"unfiltered_default_brief"}function attachAgentCommandContractsResult(result,outputCommands,extensionCommandContracts,options){result.command_summaries=buildCommandSummarySurface(outputCommands,extensionCommandContracts,{includeFormatBudgets:options.includeFormatBudgets,includeIntentProvenance:options.includeIntentProvenance});result.output_policy={token_estimate:"ceil(utf8_bytes / 4)",degradation_ladder:[...PM_OUTPUT_DEGRADATION_STEPS],allows_unbounded_opt_out:true};result.output_projection_contracts={global_ladder_field:"output_policy.degradation_ladder",global_ladder_scope:"union_not_per_command",discovery:"pm contracts --command <command> --summary",...options.includeProjectionModeMatrix?{commands:[...new Set(outputCommands.map(normalizeCommandPath))].filter(command=>resolveReadOutputSurface(command)!==void 0).sort((left,right)=>left.localeCompare(right)).map(command=>({command,modes:[...readOutputIncludeModeOptions(command).keys()]}))}:{}};result.grammar_contracts={nouns:PM_CLI_GRAMMAR_CONTRACT.nouns,shared_verbs:PM_CLI_GRAMMAR_CONTRACT.shared_verbs,scope_before_verb:PM_CLI_GRAMMAR_CONTRACT.scope_before_verb,visible_top_level_ceiling:PM_CLI_GRAMMAR_CONTRACT.visible_top_level_ceiling,ceiling_raise_requires_pm_item:PM_CLI_GRAMMAR_CONTRACT.ceiling_raise_requires_pm_item,positional_shape_budget:PM_CLI_GRAMMAR_CONTRACT.positional_shape_budget,positional_shape_count:new Set(PM_COMMAND_POSITIONAL_CONTRACTS.map(({slots})=>positionalShapeKey(slots))).size,positional_action_count:PM_POSITIONAL_ACTION_CONTRACTS.length,positional_action_parents:[...new Set(PM_POSITIONAL_ACTION_CONTRACTS.map(({parent})=>parent))].sort((left,right)=>left.localeCompare(right)),...options.includePositionalSignatures?{positional_signatures:PM_COMMAND_POSITIONAL_CONTRACTS}:{}}}async function runContracts(options,global2){const selection=resolveContractsSelection(options);assertSingleContractsProjection(selection);const pmRoot=resolvePmRoot(process.cwd(),global2.path);const runtime=await resolveContractsRuntimeContext(global2,pmRoot,selection);const actionContext=resolveContractsActionContext(selection,runtime);const schemaContext=resolveContractsSchemaContext(selection,runtime,actionContext);const commands=resolveContractsCommands(selection,actionContext);const outputCommands=resolveOutputCommands(selection,commands,runtime.extensionContracts);const result=createContractsResult(selection,schemaContext,actionContext,outputCommands);const extensionCommandContracts=resolveExtensionCommandContracts(selection,runtime,outputCommands);const includeCommandDetails=selection.fullOutput||selection.selectedCommand!==void 0;if(selection.summary||selection.fullOutput){attachAgentCommandContractsResult(result,outputCommands,extensionCommandContracts,{includeFormatBudgets:includeCommandDetails,includeIntentProvenance:includeCommandDetails,includePositionalSignatures:includeCommandDetails,includeProjectionModeMatrix:includeCommandDetails})}if(selection.summary){return result}const commandAliases=buildCommandAliasSurface(actionContext.commandCatalog.filter(command=>isCommandDiscoverable(selection,command,runtime.extensionContracts)));if(!(selection.flagsOnly&&!selection.fullOutput)){attachRuntimeContractsResult(result,runtime,selection)}attachSchemaContractsResult(result,selection,schemaContext,extensionCommandContracts);attachFlagContractsResult(result,selection,runtime,outputCommands,commandAliases);attachCommanderAliasContractsResult(result,selection);if(selection.selectedCommand==="assurance"||selection.fullOutput){result.assurance_contracts={measurement_source_kinds:[...ASSURANCE_MEASUREMENT_SOURCE_KINDS],gate_triggers:[...ASSURANCE_GATE_TRIGGERS]}}if(selection.fullOutput&&result.grammar_contracts){result.grammar_contracts.destinations=PM_COMMAND_DESTINATION_CONTRACTS.map(row=>({...row,reason:row.reason??""}))}if(selection.fullOutput&&!selection.schemaOnly&&!selection.flagsOnly&&!selection.availabilityOnly){result.mcp_tools=buildMcpToolContracts();result.context_intents=getActiveContextIntentContracts();result.read_output_dimensions=PM_READ_OUTPUT_SURFACE_CONTRACTS;result.error_codes=PM_ERROR_CODE_CATALOG;result.command_output_contracts=buildCommandOutputContracts(outputCommands);result.diagnostic_output_contracts=PM_DIAGNOSTIC_OUTPUT_BUDGET_CONTRACTS;result.command_exit_contracts={vocabulary:PM_COMMAND_EXIT_OUTCOME_CONTRACTS,command_sets:buildCommandExitContractGroups(outputCommands)}}return result}const _testOnlyContractsCommand={actionDescriptorMatchesSelectedCommand,attachCreateRequiredOptionContracts,buildExtensionActionSchemaBranch,buildCommandSummarySurface,buildCommandOutputContracts,buildCommandExitContractGroups,buildRuntimeFieldFlagContracts,collectActionContractDescriptors,collectExtensionCommandContracts,collectExtensionFlagContractsByCommand,extractActionBranches,extensionSchemaPropertyNameFromFlag,filterSchemaByAction,filterSchemaByActions,isCoreCommandPath,mergeExtensionContractsByAction,normalizeExtensionFlagName,normalizeActionNameFromCommand,normalizeCommandForRuntimeFieldFlags,normalizeCommandPath,packageOwnedActionForCommand,readContractsSettings,resolveActionCommandPath,resolveActionAvailability,resolveCoreCommandFlags,resolveRuntimeExtensionActionProbe,resolveScopedCommandsFromActionDescriptors,splitCommandPathAliases,toRuntimeLongFlagToken,toRuntimeShortFlagToken};export{_testOnlyContractsCommand,buildCommandAliasSurface,runContracts};
1
+ !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="845638dd-45b8-5057-bed2-2f687591eeaa")}catch(e2){}})();import{EXIT_CODE,SETTINGS_DEFAULTS,PmCliError,activateExtensions,getActiveExtensionRegistrations,loadExtensions,pathExists,commandOptionFlagLabel,resolveCommandOptionPolicyState,resolveItemTypeRegistry,resolveRuntimeFieldRegistry,resolveRuntimeStatusRegistry,getSettingsPath,resolvePmRoot,readSettings}from"../runtime-primitives.js";import{PM_HISTORY_OPERATION_CONTRACT}from"../../core/history/operation-contract.js";import{buildMcpToolContracts}from"../../mcp/tool-definitions.js";import{ACTIVITY_COMMANDER_STRING_OPTION_CONTRACTS,ACTIVITY_FLAG_CONTRACTS,AGGREGATE_FLAG_CONTRACTS,ASSURANCE_FLAG_CONTRACTS,APPEND_FLAG_CONTRACTS,CALENDAR_COMMANDER_STRING_OPTION_CONTRACTS,CALENDAR_FLAG_CONTRACTS,CLAIM_FLAG_CONTRACTS,CLOSE_TASK_FLAG_CONTRACTS,COMMENTS_FLAG_CONTRACTS,CLOSE_FLAG_CONTRACTS,CLOSE_MANY_FLAG_CONTRACTS,COMPLETION_FLAG_CONTRACTS,CONFIG_FLAG_CONTRACTS,CONTRACTS_FLAG_CONTRACTS,COPY_FLAG_CONTRACTS,CONTEXT_COMMANDER_STRING_OPTION_CONTRACTS,CONTEXT_FLAG_CONTRACTS,CREATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS,CREATE_COMMANDER_STRING_OPTION_CONTRACTS,CREATE_FLAG_CONTRACTS,DELETE_FLAG_CONTRACTS,DEPS_FLAG_CONTRACTS,GRAPH_FLAG_CONTRACTS,DOCS_FLAG_CONTRACTS,EXTENSION_ACTIVATE_FLAG_CONTRACTS,EXTENSION_ADOPT_ALL_FLAG_CONTRACTS,EXTENSION_ADOPT_FLAG_CONTRACTS,EXTENSION_CATALOG_FLAG_CONTRACTS,EXTENSION_DEACTIVATE_FLAG_CONTRACTS,EXTENSION_DESCRIBE_FLAG_CONTRACTS,EXTENSION_DOCTOR_FLAG_CONTRACTS,EXTENSION_EXPLORE_FLAG_CONTRACTS,EXTENSION_FLAG_CONTRACTS,EXTENSION_INIT_FLAG_CONTRACTS,EXTENSION_INSTALL_FLAG_CONTRACTS,EXTENSION_MANAGE_FLAG_CONTRACTS,EXTENSION_MIGRATE_FLAG_CONTRACTS,EXTENSION_RELOAD_FLAG_CONTRACTS,EXTENSION_UNINSTALL_FLAG_CONTRACTS,FILES_FLAG_CONTRACTS,FOCUS_FLAG_CONTRACTS,GC_FLAG_CONTRACTS,GET_FLAG_CONTRACTS,GUIDE_FLAG_CONTRACTS,GLOBAL_FLAG_CONTRACTS,HEALTH_FLAG_CONTRACTS,HISTORY_FLAG_CONTRACTS,HISTORY_COMPACT_FLAG_CONTRACTS,HISTORY_REDACT_FLAG_CONTRACTS,HISTORY_REPAIR_FLAG_CONTRACTS,HISTORY_AUTHOR_ACKNOWLEDGE_FLAG_CONTRACTS,INSTALL_FLAG_CONTRACTS,INIT_FLAG_CONTRACTS,ITEM_COMPLETE_FLAG_CONTRACTS,ITEM_MUTATE_FLAG_CONTRACTS,ITEM_REOPEN_FLAG_CONTRACTS,LEARNINGS_FLAG_CONTRACTS,LIST_COMMANDER_STRING_OPTION_CONTRACTS,LIST_FILTER_FLAG_CONTRACTS,MERGE_FLAG_CONTRACTS,NOTES_FLAG_CONTRACTS,PACKAGE_FLAG_CONTRACTS,PACKAGE_INIT_FLAG_CONTRACTS,PM_EXTENSION_CAPABILITY_CONTRACTS,PM_EXTENSION_POLICY_MODE_CONTRACTS,PM_EXTENSION_POLICY_SURFACE_CONTRACTS,PM_EXTENSION_SANDBOX_PROFILE_CONTRACTS,PM_EXTENSION_SERVICE_NAME_CONTRACTS,PM_EXTENSION_TRUST_MODE_CONTRACTS,PM_OUTPUT_DEGRADATION_STEPS,PLAN_FLAG_CONTRACTS,PM_CORE_COMMAND_NAMES,PM_DEPRECATED_TOOL_ACTIONS,PM_TOOL_ACTIONS,PM_TOOL_PARAMETERS_SCHEMA,REINDEX_FLAG_CONTRACTS,RELEASE_FLAG_CONTRACTS,RESTORE_FLAG_CONTRACTS,SCHEMA_FLAG_CONTRACTS,PROFILE_FLAG_CONTRACTS,SEARCH_COMMANDER_STRING_OPTION_CONTRACTS,EVAL_FLAG_CONTRACTS,EVENTS_FLAG_CONTRACTS,WORKSPACE_FLAG_CONTRACTS,NEXT_FLAG_CONTRACTS,SEARCH_FLAG_CONTRACTS,STATS_FLAG_CONTRACTS,DUPLICATES_FLAG_CONTRACTS,START_TASK_FLAG_CONTRACTS,PAUSE_TASK_FLAG_CONTRACTS,TELEMETRY_FLAG_CONTRACTS,TEST_ALL_FLAG_CONTRACTS,TEST_FLAG_CONTRACTS,TEST_RUNS_FLAG_CONTRACTS,UPDATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS,UPDATE_COMMANDER_STRING_OPTION_CONTRACTS,UPDATE_FLAG_CONTRACTS,UPDATE_MANY_FLAG_CONTRACTS,UPGRADE_FLAG_CONTRACTS,VALIDATE_FLAG_CONTRACTS,compactFlagAliasContracts,PM_COMMAND_ALIAS_CONTRACTS,PM_DIAGNOSTIC_OUTPUT_BUDGET_CONTRACTS,resolvePmCommandOutputBudget}from"../cli-contracts.js";import{PM_NAMESPACED_COMMAND_ALIASES,resolvePmCommandOperation}from"./command-aliases.js";import{HISTORY_ATTEST_FLAG_CONTRACTS,PM_POSITIONAL_ACTION_FLAG_CONTRACTS}from"./flag-contracts.js";import{GOVERNANCE_CLOSE_VALIDATION_DEFAULT_VALUES,GOVERNANCE_CREATE_MODE_DEFAULT_VALUES,GOVERNANCE_OWNERSHIP_ENFORCEMENT_VALUES,GOVERNANCE_WORKFLOW_ENFORCEMENT_VALUES}from"../../types.js";import{BRIEF_LIST_FIELDS,DEFAULT_COMPACT_LIST_FIELDS,LIST_COMMAND_DEFAULT_PROJECTIONS}from"../query/list.js";import{getActiveContextIntentContracts}from"../context-intent-contracts.js";import{readOutputIncludeModeOptions,resolveReadOutputSurface,PM_READ_OUTPUT_SURFACE_CONTRACTS}from"../read-output-contracts.js";import{enrichCliFlagInvocationContracts}from"../flag-invocation-contracts.js";import{resolvePmCommandVisibilityTier}from"../agent-capability-contracts.js";import{PM_ERROR_CODE_CATALOG}from"../generated-error-code-catalog.js";import{resolvePmCommandOutputEnvelope}from"../output-contracts.js";import{PM_COMMAND_EXIT_OUTCOME_CONTRACTS,resolvePmCommandExitContract}from"./command-exit-contracts.js";import{BUILTIN_RELATIONSHIP_KINDS}from"../relationship-kinds/contract.js";import{ASSURANCE_GATE_TRIGGERS,ASSURANCE_MEASUREMENT_SOURCE_KINDS}from"../governance/assurance.js";import{PM_CLI_GRAMMAR_CONTRACT,PM_COMMAND_DESTINATION_CONTRACTS,PM_COMMAND_POSITIONAL_CONTRACTS,PM_POSITIONAL_ACTION_CONTRACTS,positionalShapeKey,resolvePmCommandPositionalContract}from"./grammar-contracts.js";const AGENT_BOOTSTRAP_FLAGS=new Map([["claim",["--if-available","--next","--type","--priority","--token-budget","--explain-ranking"]],["close",["--reason","--validate-close","--resolution","--expected-result","--actual-result","--message"]],["context",["--limit","--after","--depth","--section","--token-budget","--explain-ranking"]],["contracts",["--command","--flags-only","--summary","--runtime-only","--availability-only","--full"]],["create",["--title","--type","--status","--priority","--dep","--comment"]],["get",["--full","--depth","--fields","--tree","--tree-depth","--format"]],["health",["--check-only","--summary","--brief","--check-telemetry","--strict-exit","--full"]],["list",["--status","--type","--limit","--after","--brief","--fields"]],["next",["--limit","--blocked-limit","--ready-only","--token-budget","--explain-ranking","--format"]],["search",["--mode","--status","--type","--limit","--after","--fields"]],["update",["--status","--message","--dep","--comment","--file","--test"]],["validate",["--check-resolution","--check-history-drift","--check-storage-integrity","--counts","--strict-exit","--fix-hints"]]]);const AGENT_BOUNDED_FLAG_PRIORITY=["--limit","--after","--offset","--token-budget","--brief","--summary","--compact","--fields","--full","--format","--since","--until"];const LIST_COMMAND_NAMES=new Set(["list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"]);const PACKAGE_OWNED_ACTIONS=new Set(["calendar","guide","reindex","completion","test-runs-list","test-runs-status","test-runs-logs","test-runs-stop","test-runs-resume","templates-list","templates-save","templates-show"]);const PACKAGE_OWNED_COMMANDS=new Set(["meet","event","remind","search-advanced","dedupe-audit","dedupe-merge","comments-audit","cal","calendar","completion","completion-statuses","completion-tags","completion-types","guide","reindex","normalize","templates","templates list","templates save","templates show","test-runs","test-runs list","test-runs status","test-runs logs","test-runs stop","test-runs resume"]);const PACKAGE_OWNED_COMMAND_INSTALL_HINTS=new Map([["meet","calendar"],["event","calendar"],["remind","calendar"],["search-advanced","search-advanced"],["dedupe-audit","governance-audit"],["dedupe-merge","governance-audit"],["comments-audit","governance-audit"],["cal","calendar"],["calendar","calendar"],["completion","guide-shell"],["completion-statuses","guide-shell"],["completion-tags","guide-shell"],["completion-types","guide-shell"],["guide","guide-shell"],["reindex","search-advanced"],["normalize","governance-audit"],["templates","templates"],["templates list","templates"],["templates save","templates"],["templates show","templates"],["test-runs","linked-test-adapters"],["test-runs list","linked-test-adapters"],["test-runs status","linked-test-adapters"],["test-runs logs","linked-test-adapters"],["test-runs stop","linked-test-adapters"],["test-runs resume","linked-test-adapters"]]);const PACKAGE_OWNED_ACTION_COMMAND_PATHS=new Map([["calendar","calendar|cal"],["guide","guide"],["reindex","reindex"],["completion","completion"],["test-runs-list","test-runs|test-runs list"],["test-runs-status","test-runs status"],["test-runs-logs","test-runs logs"],["test-runs-stop","test-runs stop"],["test-runs-resume","test-runs resume"],["templates-list","templates|templates list"],["templates-save","templates save"],["templates-show","templates show"]]);const PACKAGE_OWNED_COMMAND_ACTIONS=new Map([...PACKAGE_OWNED_ACTION_COMMAND_PATHS.entries()].flatMap(([action,commandPaths])=>splitCommandPathAliases(commandPaths).map(commandPath=>[commandPath,action])));const CANONICAL_COMMAND_ALIASES=[{canonical:"context",aliases:["ctx"]},{canonical:"package",aliases:["extension","packages"]}];const COMMAND_ALIAS_TO_CANONICAL=new Map(CANONICAL_COMMAND_ALIASES.flatMap(entry=>entry.aliases.map(alias=>[alias,entry.canonical])));const COMMAND_NAMESPACE_DISPLAY_LIMIT=10;const COMMAND_NAMESPACE_FALLBACK_LIMIT=20;const COMMAND_INTENTS=new Map([["activity","Read activity."],["aggregate","Group counts."],["append","Append body."],["assurance","Evaluate assurance."],["assurance derive","Derive checks."],["assurance risk","Select checks for changes."],["assurance lineages","Measure recurrence coverage."],["beads","Manage Beads interoperability."],["cal","Manage calendar integration."],["calendar","Manage calendar integration."],["changelog","Generate changelog output."],["claim","Claim work."],["close","Close work."],["close-many","Close matching work."],["close-task","Close task work."],["command-kit","Inspect command authoring primitives."],["comments","Manage comments."],["comments-audit","Audit comment governance."],["completion","Generate shell completions."],["config","Manage settings."],["context","Build context."],["contracts","Inspect contracts."],["copy","Copy work."],["create","Create work."],["dedupe-audit","Audit duplicate work."],["dedupe-merge","Merge duplicate work."],["delete","Delete work."],["deps","Manage deps."],["duplicates","Find duplicate clusters."],["docs","Link docs."],["eval","Run evaluations."],["event","Manage events."],["events","Read events."],["files","Link files."],["focus","Manage focus."],["gc","Clean caches."],["get","Read item."],["graph","Query graph."],["guide","Show user guides."],["health","Check health."],["help","Show help."],["history","Inspect history."],["init","Initialize workspace."],["install","Install packages."],["item","Mutate items."],["learnings","Manage learnings."],["list","List work."],["list-all","List work across every status."],["list-blocked","List blocked work."],["list-canceled","List canceled work."],["list-closed","List closed work."],["list-draft","List draft work."],["list-in-progress","List in-progress work."],["list-open","List open work."],["meet","Record meeting context."],["merge","Manage tracker merges."],["next","Pick next work."],["notes","Manage notes."],["normalize","Normalize tracker data."],["ops","Run operations."],["package","Manage packages."],["packages","Manage packages."],["pause-task","Pause task work."],["plan","Manage plans."],["profile","Manage profiles."],["reindex","Refresh search index."],["release","Release claim."],["remind","Manage reminders."],["restore","Restore history."],["schema","Customize schema."],["search","Search work."],["search-advanced","Run advanced search."],["start-task","Start task work."],["stats","Show stats."],["telemetry","Manage telemetry."],["templates","Manage work templates."],["test","Run linked tests."],["test-all","Run all linked tests."],["test-runs","Inspect background test runs."],["todos","Manage source-code todos."],["twin","Manage repository twins."],["update","Update work."],["update-many","Update matching work."],["upgrade","Upgrade packages."],["validate","Validate data."],["vcs","Inspect version-control context."],["workspace","Manage workspaces."],["history-author-acknowledge","Acknowledge reviewed history authors."],["history-compact","Compact history."],["history-attest","Export or verify detached history proof."],["history-redact","Redact sensitive history values."],["history-repair","Repair history integrity."]]);const EXTENSION_LIFECYCLE_FLAG_CONTRACTS=[["init",EXTENSION_INIT_FLAG_CONTRACTS],["install",EXTENSION_INSTALL_FLAG_CONTRACTS],["uninstall",EXTENSION_UNINSTALL_FLAG_CONTRACTS],["explore",EXTENSION_EXPLORE_FLAG_CONTRACTS],["manage",EXTENSION_MANAGE_FLAG_CONTRACTS],["describe",EXTENSION_DESCRIBE_FLAG_CONTRACTS],["reload",EXTENSION_RELOAD_FLAG_CONTRACTS],["doctor",EXTENSION_DOCTOR_FLAG_CONTRACTS],["catalog",EXTENSION_CATALOG_FLAG_CONTRACTS],["adopt",EXTENSION_ADOPT_FLAG_CONTRACTS],["adopt-all",EXTENSION_ADOPT_ALL_FLAG_CONTRACTS],["activate",EXTENSION_ACTIVATE_FLAG_CONTRACTS],["deactivate",EXTENSION_DEACTIVATE_FLAG_CONTRACTS],["migrate",EXTENSION_MIGRATE_FLAG_CONTRACTS]];const PACKAGE_LIFECYCLE_FLAG_CONTRACTS=[...EXTENSION_LIFECYCLE_FLAG_CONTRACTS.map(([subcommand,flags])=>subcommand==="init"?[subcommand,PACKAGE_INIT_FLAG_CONTRACTS]:[subcommand,flags]),["upgrade",UPGRADE_FLAG_CONTRACTS]];const CORE_COMMAND_FLAG_CONTRACT_ENTRIES=[...EXTENSION_LIFECYCLE_FLAG_CONTRACTS.map(([subcommand,flags])=>[`extension ${subcommand}`,flags]),...PACKAGE_LIFECYCLE_FLAG_CONTRACTS.flatMap(([subcommand,flags])=>[[`package ${subcommand}`,flags],[`packages ${subcommand}`,flags]]),["init",INIT_FLAG_CONTRACTS],["config",CONFIG_FLAG_CONTRACTS],["extension",EXTENSION_FLAG_CONTRACTS],["package",PACKAGE_FLAG_CONTRACTS],["packages",PACKAGE_FLAG_CONTRACTS],["install",INSTALL_FLAG_CONTRACTS],["create",CREATE_FLAG_CONTRACTS],["item mutate",ITEM_MUTATE_FLAG_CONTRACTS],["item complete",ITEM_COMPLETE_FLAG_CONTRACTS],["item reopen",ITEM_REOPEN_FLAG_CONTRACTS],["copy",COPY_FLAG_CONTRACTS],["focus",FOCUS_FLAG_CONTRACTS],["update",UPDATE_FLAG_CONTRACTS],["update-many",UPDATE_MANY_FLAG_CONTRACTS],["upgrade",UPGRADE_FLAG_CONTRACTS],["calendar",CALENDAR_FLAG_CONTRACTS],["cal",CALENDAR_FLAG_CONTRACTS],["context",CONTEXT_FLAG_CONTRACTS],["ctx",CONTEXT_FLAG_CONTRACTS],["get",GET_FLAG_CONTRACTS],["search",SEARCH_FLAG_CONTRACTS],["eval",EVAL_FLAG_CONTRACTS],["events",EVENTS_FLAG_CONTRACTS],["workspace",WORKSPACE_FLAG_CONTRACTS],["workspace position",[]],["workspace snapshot",WORKSPACE_FLAG_CONTRACTS],["workspace snapshot create",WORKSPACE_FLAG_CONTRACTS],["workspace snapshot list",WORKSPACE_FLAG_CONTRACTS],["workspace snapshot inspect",WORKSPACE_FLAG_CONTRACTS],["workspace snapshot restore",WORKSPACE_FLAG_CONTRACTS],["workspace snapshot delete",WORKSPACE_FLAG_CONTRACTS],["next",NEXT_FLAG_CONTRACTS],["aggregate",AGGREGATE_FLAG_CONTRACTS],["deps",DEPS_FLAG_CONTRACTS],["graph",GRAPH_FLAG_CONTRACTS],["guide",GUIDE_FLAG_CONTRACTS],["reindex",REINDEX_FLAG_CONTRACTS],["history",HISTORY_FLAG_CONTRACTS],["history-compact",HISTORY_COMPACT_FLAG_CONTRACTS],["history-attest",HISTORY_ATTEST_FLAG_CONTRACTS],["history-redact",HISTORY_REDACT_FLAG_CONTRACTS],["history-repair",HISTORY_REPAIR_FLAG_CONTRACTS],["history-author-acknowledge",HISTORY_AUTHOR_ACKNOWLEDGE_FLAG_CONTRACTS],["merge",MERGE_FLAG_CONTRACTS],["schema",SCHEMA_FLAG_CONTRACTS],["profile",PROFILE_FLAG_CONTRACTS],["plan",PLAN_FLAG_CONTRACTS],["restore",RESTORE_FLAG_CONTRACTS],["delete",DELETE_FLAG_CONTRACTS],["close",CLOSE_FLAG_CONTRACTS],["close-many",CLOSE_MANY_FLAG_CONTRACTS],["append",APPEND_FLAG_CONTRACTS],["claim",CLAIM_FLAG_CONTRACTS],["release",RELEASE_FLAG_CONTRACTS],["start-task",START_TASK_FLAG_CONTRACTS],["pause-task",PAUSE_TASK_FLAG_CONTRACTS],["close-task",CLOSE_TASK_FLAG_CONTRACTS],["comments",COMMENTS_FLAG_CONTRACTS],["notes",NOTES_FLAG_CONTRACTS],["learnings",LEARNINGS_FLAG_CONTRACTS],["files",FILES_FLAG_CONTRACTS],["docs",DOCS_FLAG_CONTRACTS],["test",TEST_FLAG_CONTRACTS],["test-runs-worker",[]],["test-all",TEST_ALL_FLAG_CONTRACTS],["telemetry",TELEMETRY_FLAG_CONTRACTS],["test-runs",TEST_RUNS_FLAG_CONTRACTS],["gc",GC_FLAG_CONTRACTS],["stats",STATS_FLAG_CONTRACTS],["ops",[]],["duplicates",DUPLICATES_FLAG_CONTRACTS],["validate",VALIDATE_FLAG_CONTRACTS],["health",HEALTH_FLAG_CONTRACTS],["assurance",ASSURANCE_FLAG_CONTRACTS],...PM_POSITIONAL_ACTION_FLAG_CONTRACTS,["contracts",CONTRACTS_FLAG_CONTRACTS],["completion",COMPLETION_FLAG_CONTRACTS],["activity",ACTIVITY_FLAG_CONTRACTS],...[...LIST_COMMAND_NAMES].map(command=>[command,LIST_FILTER_FLAG_CONTRACTS])];const CORE_COMMAND_FLAG_CONTRACTS_BY_COMMAND=new Map(CORE_COMMAND_FLAG_CONTRACT_ENTRIES);for(const{alias,canonical}of PM_NAMESPACED_COMMAND_ALIASES){const flags=CORE_COMMAND_FLAG_CONTRACTS_BY_COMMAND.get(alias);if(flags!==void 0)CORE_COMMAND_FLAG_CONTRACTS_BY_COMMAND.set(canonical,flags)}function packageOwnedActionForCommand(command){const exactAction=PACKAGE_OWNED_COMMAND_ACTIONS.get(command);if(exactAction){return exactAction}if(command.startsWith("test-runs ")){return`test-runs-${command.slice("test-runs ".length)}`}if(command.startsWith("templates ")){return`templates-${command.slice("templates ".length)}`}return command}function resolveActionCommandPath(action){const historyAlias=PM_NAMESPACED_COMMAND_ALIASES.find(contract=>contract.alias===action);if(historyAlias)return`${historyAlias.canonical}|${historyAlias.alias}`;if(PM_CORE_COMMAND_NAMES.includes(action)){return normalizeCommandPath(action)}if(action.startsWith("extension-")){return normalizeCommandPath(`extension ${action.slice("extension-".length)}`)}if(action.startsWith("package-")){return normalizeCommandPath(`package ${action.slice("package-".length)}`)}if(action.startsWith("item-")){return normalizeCommandPath(`item ${action.slice("item-".length)}`)}if(action.startsWith("test-runs-")){return normalizeCommandPath(`test-runs ${action.slice("test-runs-".length)}`)}if(action.startsWith("templates-")){return normalizeCommandPath(`templates ${action.slice("templates-".length)}`)}if(PACKAGE_OWNED_ACTIONS.has(action)){return PACKAGE_OWNED_ACTION_COMMAND_PATHS.get(action)??normalizeCommandPath(action)}return null}function actionDescriptorMatchesSelectedCommand(descriptor,selectedCommand){const historyOperation=resolvePmCommandOperation(selectedCommand);if(historyOperation!==selectedCommand||PM_NAMESPACED_COMMAND_ALIASES.some(entry=>entry.alias===selectedCommand))return descriptor.action===historyOperation;if(descriptor.command_path===null){return false}return splitCommandPathAliases(descriptor.command_path).some(commandPath=>{if(commandPath===selectedCommand){return true}return commandPath.startsWith(`${selectedCommand} `)||selectedCommand.startsWith(`${commandPath} `)})}function splitCommandPathAliases(commandPath){return commandPath.split("|").map(entry=>normalizeCommandPath(entry)).filter(entry=>entry.length>0)}function resolveScopedCommandsFromActionDescriptors(descriptors,commandCatalog){const commandSet=new Set(commandCatalog);const scoped=new Set;for(const descriptor of descriptors){if(!descriptor.command_path){continue}for(const commandPath of splitCommandPathAliases(descriptor.command_path)){const tokens=commandPath.split(" ").filter(entry=>entry.length>0);if(tokens.length===0){continue}for(let end=tokens.length;end>0;end-=1){const candidate=tokens.slice(0,end).join(" ");if(!commandSet.has(candidate)){continue}scoped.add(candidate);break}}}return[...scoped].sort((left,right)=>left.localeCompare(right))}function normalizeToken(value){if(typeof value!=="string"){return void 0}const trimmed=value.trim().toLowerCase();return trimmed.length>0?trimmed:void 0}function extractActionBranches(schema){const oneOf=schema.oneOf;if(!Array.isArray(oneOf)){return[]}return oneOf.filter(entry=>typeof entry==="object"&&entry!==null)}function filterSchemaByAction(schema,action){if(!action){return{...schema}}const branches=extractActionBranches(schema);const filtered=branches.filter(entry=>{const properties=entry.properties;if(typeof properties!=="object"||properties===null){return false}const actionProperty=properties.action;if(typeof actionProperty!=="object"||actionProperty===null){return false}return actionProperty.const===action});return{...schema,oneOf:filtered}}function filterSchemaByActions(schema,actions){const branches=extractActionBranches(schema);const filtered=branches.filter(entry=>{const properties=entry.properties;if(typeof properties!=="object"||properties===null){return false}const actionProperty=properties.action;if(typeof actionProperty!=="object"||actionProperty===null){return false}const actionConst=actionProperty.const;return typeof actionConst==="string"&&actions.has(actionConst)});return{...schema,oneOf:filtered}}function normalizeCommandPath(value){return value.trim().toLowerCase().split(/\s+/).filter(entry=>entry.length>0).join(" ")}function normalizeActionNameFromCommand(commandPath){return commandPath.replace(/\s+/g,"-")}function toOptionalTrimmedString(value){if(typeof value!=="string"){return null}const trimmed=value.trim();return trimmed.length>0?trimmed:null}function normalizeStringList(values){if(!Array.isArray(values)){return[]}const normalized=[];const seen=new Set;for(const value of values){const trimmed=toOptionalTrimmedString(value);if(!trimmed||seen.has(trimmed)){continue}seen.add(trimmed);normalized.push(trimmed)}return normalized}function assignExtensionFlagBoolean(contract,key,enabled){if(enabled){contract[key]=true}}function normalizeExtensionFlagName(value,kind){if(value==null){return null}if(typeof value!=="string"){throw new TypeError("Expected string for extension flag name.")}const trimmed=value.trim();if(trimmed.length===0){return null}if(kind==="long"){return trimmed.startsWith("--")&&trimmed.length>2?trimmed:null}return trimmed.startsWith("-")&&!trimmed.startsWith("--")&&trimmed.length>1?trimmed:null}function toExtensionFlagContract(definition){const normalizedLong=normalizeExtensionFlagName(definition.long,"long");const normalizedShort=normalizeExtensionFlagName(definition.short,"short");const flag=normalizedLong??normalizedShort;if(!flag){return null}const contract={flag};if(normalizedShort&&normalizedLong){contract.short=normalizedShort}assignExtensionFlagBoolean(contract,"required",definition.required===true);assignExtensionFlagBoolean(contract,"repeatable",definition.repeatable===true);assignExtensionFlagBoolean(contract,"list",definition.list===true);const description=toOptionalTrimmedString(definition.description);if(description){contract.description=description}const valueName=toOptionalTrimmedString(definition.value_name);if(valueName){contract.value_name=valueName}const rawValueType=[toOptionalTrimmedString(definition.value_type),toOptionalTrimmedString(definition.type),valueName?"string":null].find(candidate=>candidate==="string"||candidate==="number"||candidate==="boolean");if(rawValueType){contract.value_type=rawValueType}return contract}function collectExtensionFlagContractsByCommand(registrations){const grouped=new Map;for(const registration of registrations){const commandPath=normalizeCommandPath(registration.target_command);if(commandPath.length===0){continue}const bucket=grouped.get(commandPath)??{flags:[],sources:[],dedupe:new Set,sourceDedupe:new Set};const sourceKey=`${registration.layer}:${registration.name}`;if(!bucket.sourceDedupe.has(sourceKey)){bucket.sourceDedupe.add(sourceKey);bucket.sources.push({layer:registration.layer,name:registration.name})}for(const definition of registration.flags){const contract=toExtensionFlagContract(definition);if(!contract){continue}const key=`${contract.flag}|${contract.short??""}`;if(bucket.dedupe.has(key)){continue}bucket.dedupe.add(key);bucket.flags.push(contract)}grouped.set(commandPath,bucket)}const normalized=new Map;for(const[commandPath,bucket]of grouped.entries()){normalized.set(commandPath,{flags:bucket.flags,sources:bucket.sources.sort((left,right)=>{const layerOrder=left.layer.localeCompare(right.layer);if(layerOrder!==0){return layerOrder}return(left.name??"").localeCompare(right.name??"")})})}return normalized}function collectExtensionCommandContracts(runtimeProbe){const flagsByCommand=collectExtensionFlagContractsByCommand(runtimeProbe.flagRegistrations);const definitionsByCommand=new Map;for(const definition of runtimeProbe.commandDefinitions){const command=normalizeCommandPath(definition.command);if(command.length===0){continue}const action=toOptionalTrimmedString(definition.action)??normalizeActionNameFromCommand(command);const args=Array.isArray(definition.arguments)?definition.arguments.map(argument=>{const name=toOptionalTrimmedString(argument.name);if(!name){return null}return{name,required:argument.required===true,variadic:argument.variadic===true,description:toOptionalTrimmedString(argument.description)}}).filter(argument=>argument!==null):[];definitionsByCommand.set(command,{...definition.tier===void 0?{}:{tier:definition.tier},command,action,source:{layer:definition.layer,name:definition.name},description:toOptionalTrimmedString(definition.description),intent:toOptionalTrimmedString(definition.intent),arguments:args,flags:flagsByCommand.get(command)?.flags??[],examples:normalizeStringList(definition.examples),failure_hints:normalizeStringList(definition.failure_hints)})}const extensionCommands=new Set;for(const command of runtimeProbe.handlers){extensionCommands.add(normalizeCommandPath(command))}for(const command of definitionsByCommand.keys()){extensionCommands.add(command)}for(const command of flagsByCommand.keys()){extensionCommands.add(command)}const contracts=[];for(const command of[...extensionCommands].sort((left,right)=>left.localeCompare(right))){const definition=definitionsByCommand.get(command);contracts.push(buildCollectedExtensionCommandContract(command,definition,flagsByCommand.get(command)?.flags??[]))}return contracts}function buildCollectedExtensionCommandContract(command,definition,registeredFlags){if(definition){return{...definition,flags:definition.flags.length>0?definition.flags:registeredFlags}}return{command,action:normalizeActionNameFromCommand(command),source:null,description:null,intent:null,arguments:[],flags:registeredFlags,examples:[],failure_hints:[]}}function extensionSchemaPropertyNameFromFlag(flag){const normalized=flag.flag.replace(/^-+/,"").trim();if(normalized.length===0){return null}const camelCased=normalized.replace(/-([a-z0-9])/g,(_match,char)=>char.toUpperCase());const cleaned=camelCased.replace(/[^a-zA-Z0-9]/g,"");return cleaned.length>0?cleaned:null}function buildExtensionArgumentSchema(argument,action){if(argument.variadic){return{type:"array",items:{type:"string"},description:argument.description??`Variadic argument '${argument.name}' for extension action '${action}'.`}}return{type:"string",description:argument.description??`Argument '${argument.name}' for extension action '${action}'.`}}function buildExtensionFlagSchema(flag,action){const valueType=flag.value_type??"boolean";const schemaType=valueType==="boolean"?"boolean":valueType==="number"?["number","string"]:"string";const acceptsMultipleValues=flag.repeatable===true||flag.list===true;return{type:acceptsMultipleValues?"array":schemaType,...acceptsMultipleValues?{items:{type:schemaType}}:{},description:flag.description??`Extension option '${flag.flag}' for action '${action}'.`}}function buildExtensionActionSchemaBranch(contract){const commands=contract.command.split("|").map(command=>command.trim()).filter(command=>command.length>0);const properties={action:{type:"string",const:contract.action,description:contract.intent??contract.description??`Invoke extension command '${contract.command}'.`}};const required=["action"];for(const argument of contract.arguments){properties[argument.name]=buildExtensionArgumentSchema(argument,contract.action);if(argument.required){required.push(argument.name)}}for(const flag of contract.flags){const propertyName=extensionSchemaPropertyNameFromFlag(flag);if(!propertyName||properties[propertyName]!==void 0){continue}properties[propertyName]=buildExtensionFlagSchema(flag,contract.action);if(flag.required===true){required.push(propertyName)}}return{type:"object",properties,required,additionalProperties:true,"x-extension-source":contract.source,"x-extension-command":commands[0]??contract.command,"x-extension-commands":commands}}function mergeExtensionFlagContract(existing,incoming){existing.description??=incoming.description;existing.value_name??=incoming.value_name;existing.value_type??=incoming.value_type;if(incoming.required===true){existing.required=true}if(incoming.repeatable===true){existing.repeatable=true}}function mergeExtensionContractsByAction(contracts){const byAction=new Map;for(const contract of contracts){const existing=byAction.get(contract.action);if(!existing){byAction.set(contract.action,{...contract,flags:[...contract.flags],examples:[...contract.examples],failure_hints:[...contract.failure_hints]});continue}existing.command=[...new Set([existing.command,contract.command])].sort((left,right)=>left.localeCompare(right)).join("|");existing.arguments=existing.arguments.length>=contract.arguments.length?existing.arguments:contract.arguments;const flagKeys=new Set(existing.flags.map(flag=>`${flag.flag}|${flag.short??""}`));for(const flag of contract.flags){const key=`${flag.flag}|${flag.short??""}`;if(!flagKeys.has(key)){flagKeys.add(key);existing.flags.push(flag)}else{const existingFlag=existing.flags.find(candidate=>`${candidate.flag}|${candidate.short??""}`===key);if(existingFlag){mergeExtensionFlagContract(existingFlag,flag)}}}existing.examples=[...new Set([...existing.examples,...contract.examples])];existing.failure_hints=[...new Set([...existing.failure_hints,...contract.failure_hints])]}return[...byAction.values()].sort((left,right)=>left.action.localeCompare(right.action))}async function resolveRuntimeExtensionActionProbe(global2,readSettingsFn=readSettings){const defaultPolicyState={mode:SETTINGS_DEFAULTS.extensions.policy.mode,trust_mode:SETTINGS_DEFAULTS.extensions.policy.trust_mode,default_sandbox_profile:SETTINGS_DEFAULTS.extensions.policy.default_sandbox_profile};if(global2.noExtensions){return{handlers:new Set,disabledReason:"extensions_disabled",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:defaultPolicyState}}const pmRoot=resolvePmRoot(process.cwd(),global2.path);if(!await pathExists(getSettingsPath(pmRoot))){return{handlers:new Set,disabledReason:null,commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:defaultPolicyState}}try{const settings=await readSettingsFn(pmRoot);const loadResult=await loadExtensions({pmRoot,settings,cwd:process.cwd(),noExtensions:false});const activationResult=await activateExtensions({...loadResult,loaded:loadResult.loaded});const handlers=new Set(activationResult.commands.handlers.map(entry=>normalizeCommandPath(entry.command)));return{handlers,disabledReason:null,commandDefinitions:activationResult.registrations.commands,flagRegistrations:activationResult.registrations.flags,registrations:activationResult.registrations,policyState:{mode:loadResult.policy.mode,trust_mode:loadResult.policy.trust_mode,default_sandbox_profile:loadResult.policy.default_sandbox_profile}}}catch{return{handlers:new Set,disabledReason:"extension_runtime_probe_failed",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:defaultPolicyState}}}function collectActionContractDescriptors(extensionContracts,options={}){const descriptors=new Map;for(const action of PM_TOOL_ACTIONS){const packageOwned=PACKAGE_OWNED_ACTIONS.has(action);if(packageOwned&&!options.includePackageOwnedActions){continue}const commandPath=resolveActionCommandPath(action);descriptors.set(action,{action,provider:packageOwned?"extension":"core",requires_extension:packageOwned,command_path:commandPath})}if(options.includePackageOwnedActions){for(const action of PACKAGE_OWNED_ACTIONS){if(descriptors.has(action)){continue}descriptors.set(action,{action,provider:"extension",requires_extension:true,command_path:resolveActionCommandPath(action)})}}for(const contract of extensionContracts){if(descriptors.has(contract.action)){continue}descriptors.set(contract.action,{action:contract.action,provider:"extension",requires_extension:true,command_path:PM_NAMESPACED_COMMAND_ALIASES.find(entry=>entry.alias===contract.command)?.canonical??normalizeCommandPath(contract.command)})}return[...descriptors.values()].sort((left,right)=>(left.action??"").localeCompare(right.action??""))}function resolveActionAvailability(descriptor,runtimeProbe){if(descriptor.provider==="core"&&!descriptor.requires_extension){return{action:descriptor.action,invocable:true,available:true,requires_extension:false,provider:"core",disabled_reason:null,command_path:descriptor.command_path,cli_exposed:descriptor.command_path!==null&&(!PACKAGE_OWNED_COMMANDS.has(descriptor.action)||runtimeProbe.handlers.has(descriptor.action))}}const commandPaths=descriptor.command_path?splitCommandPathAliases(descriptor.command_path):[];const extensionCommandAvailable=commandPaths.some(commandPath=>runtimeProbe.handlers.has(commandPath)||runtimeProbe.handlers.has(resolvePmCommandOperation(commandPath)));const optionalPackageHint=commandPaths.map(commandPath=>PACKAGE_OWNED_COMMAND_INSTALL_HINTS.get(resolvePmCommandOperation(commandPath))).find(hint=>typeof hint==="string");const invocable=runtimeProbe.disabledReason===null&&extensionCommandAvailable;return{action:descriptor.action,invocable,available:invocable,requires_extension:true,provider:"extension",disabled_reason:invocable?null:runtimeProbe.disabledReason??(optionalPackageHint?`optional_package_not_installed:${optionalPackageHint}`:"extension_command_not_registered"),command_path:descriptor.command_path,cli_exposed:extensionCommandAvailable,policy_state:{mode:runtimeProbe.policyState.mode,trust_mode:runtimeProbe.policyState.trust_mode,default_sandbox_profile:runtimeProbe.policyState.default_sandbox_profile}}}function resolveCoreCommandFlags(command){return CORE_COMMAND_FLAG_CONTRACTS_BY_COMMAND.get(command)??GLOBAL_FLAG_CONTRACTS}function isCoreCommandPath(command){if(PACKAGE_OWNED_COMMANDS.has(resolvePmCommandOperation(command))){return false}return CORE_COMMAND_FLAG_CONTRACTS_BY_COMMAND.has(command)}function normalizeCommandForRuntimeFieldFlags(command){if(LIST_COMMAND_NAMES.has(command)){return"list"}if(command==="cal"){return"calendar"}if(command==="ctx"){return"context"}if(command==="update-many"){return"update_many"}return command}function toRuntimeLongFlagToken(token){const trimmed=token.trim();if(!trimmed){return null}if(trimmed.startsWith("--")){return trimmed}if(trimmed.startsWith("-")){return null}return`--${trimmed}`}function toRuntimeShortFlagToken(token){const trimmed=token.trim();if(!trimmed){return null}if(trimmed.startsWith("--")){return null}if(trimmed.startsWith("-")){return trimmed}return null}function buildRuntimeFieldFlagContracts(fieldRegistry){const buckets=new Map;for(const definition of fieldRegistry.definitions){const primaryFlag=toRuntimeLongFlagToken(definition.cli_flag);if(!primaryFlag){continue}const shortAlias=definition.cli_aliases.map(alias=>toRuntimeShortFlagToken(alias)).find(alias=>alias!==null);const longAliases=definition.cli_aliases.map(alias=>toRuntimeLongFlagToken(alias)).filter(alias=>alias!==null&&alias!==primaryFlag);for(const command of definition.commands){const bucket=buckets.get(command)??{flags:[],seen:new Set};const primaryContract=shortAlias?{flag:primaryFlag,short:shortAlias}:{flag:primaryFlag};const primaryKey=`${primaryContract.flag}|${primaryContract.short??""}`;if(!bucket.seen.has(primaryKey)){bucket.seen.add(primaryKey);bucket.flags.push(primaryContract)}for(const alias of longAliases){const key=`${alias}|`;if(bucket.seen.has(key)){continue}bucket.seen.add(key);bucket.flags.push({flag:alias})}buckets.set(command,bucket)}}const result=new Map;for(const[command,bucket]of buckets.entries()){result.set(command,compactFlagAliasContracts(bucket.flags))}return result}function mergeFlagContracts(primary,secondary){const merged=[];const seen=new Set;for(const contract of[...primary,...secondary]){const key=`${contract.flag}|${contract.short??""}`;if(seen.has(key)){continue}seen.add(key);merged.push(contract)}return compactFlagAliasContracts(merged)}function buildCommandFlagSurface(commands,extensionFlagMap,runtimeFieldFlagMap,includeSemanticMetadata,extensionContracts){const flagsByPath=new Map(extensionFlagMap);for(const{alias,canonical}of PM_NAMESPACED_COMMAND_ALIASES){const flags=extensionFlagMap.get(canonical)??extensionFlagMap.get(alias);if(flags){flagsByPath.set(alias,flags);flagsByPath.set(canonical,flags)}}return commands.map(command=>{const isCoreCommand=isCoreCommandPath(command);const coreFlags=isCoreCommand?resolveCoreCommandFlags(command):[];const runtimeFlags=runtimeFieldFlagMap.get(normalizeCommandForRuntimeFieldFlags(command))??[];const extensionFlags=flagsByPath.get(command);const coreWithRuntime=mergeFlagContracts(coreFlags,runtimeFlags);const flags=mergeFlagContracts(coreWithRuntime,extensionFlags?.flags??[]);const provider=coreFlags.length>0&&(extensionFlags?.flags.length??0)>0?"mixed":isCoreCommand?"core":"extension";return{command,flags,...includeSemanticMetadata?{canonical_command:canonicalSummaryCommand(command),visibility:runtimeCommandVisibilityTier(command,extensionContracts),positionals:resolvePmCommandPositionalContract(command)?.slots??[],flag_invocations:enrichCliFlagInvocationContracts(command,flags)}:{},provider,extension_sources:extensionFlags?.sources}}).sort((left,right)=>left.command.localeCompare(right.command))}function buildCommandAliasSurface(commands,aliasContracts=PM_COMMAND_ALIAS_CONTRACTS){const commandSet=new Set(commands);const grouped=new Map;for(const entry of CANONICAL_COMMAND_ALIASES){const aliases=entry.aliases.filter(alias=>commandSet.has(alias));grouped.set(entry.canonical,{canonical:entry.canonical,aliases,contracts:[]})}for(const contract of aliasContracts){if(!commandSet.has(contract.canonical)){continue}if(contract.registration==="commander"&&!commandSet.has(contract.alias)){continue}const entry=grouped.get(contract.canonical)??{canonical:contract.canonical,aliases:[],contracts:[]};if(!entry.aliases.includes(contract.alias)){entry.aliases.push(contract.alias)}entry.contracts.push(contract);grouped.set(contract.canonical,entry)}return[...grouped.values()].map(({contracts,...entry})=>contracts.length===0?entry:{...entry,contracts}).sort((left,right)=>left.canonical.localeCompare(right.canonical))}function buildCommanderAliasSurface(){return{create_string_options:CREATE_COMMANDER_STRING_OPTION_CONTRACTS,create_repeatable_options:CREATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS,update_string_options:UPDATE_COMMANDER_STRING_OPTION_CONTRACTS,update_repeatable_options:UPDATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS,list_string_options:LIST_COMMANDER_STRING_OPTION_CONTRACTS,search_string_options:SEARCH_COMMANDER_STRING_OPTION_CONTRACTS,calendar_string_options:CALENDAR_COMMANDER_STRING_OPTION_CONTRACTS,context_string_options:CONTEXT_COMMANDER_STRING_OPTION_CONTRACTS,activity_string_options:ACTIVITY_COMMANDER_STRING_OPTION_CONTRACTS}}function resolveCreateRequiredOptionContract(typeDefinition,createMode){const baseRequiredOptions=new Set(["title","type"]);if(createMode==="strict"){for(const field of typeDefinition.required_create_fields){baseRequiredOptions.add(field)}for(const field of typeDefinition.required_create_repeatables){baseRequiredOptions.add(field)}}const policyState=resolveCommandOptionPolicyState(typeDefinition,"create",baseRequiredOptions);const requiredOptionKeys=[...new Set(policyState.required)].sort((left,right)=>left.localeCompare(right));const requiredFlags=[...new Set(requiredOptionKeys.map(option=>commandOptionFlagLabel("create",option)))].sort((left,right)=>left.localeCompare(right));const requiredTypeOptions=[...new Set(typeDefinition.options.filter(option=>option.required===true).map(option=>option.key))].sort((left,right)=>left.localeCompare(right));return{required_option_keys:requiredOptionKeys,required_flags:requiredFlags,required_type_options:requiredTypeOptions,policy_errors:[...new Set(policyState.errors)].sort((left,right)=>left.localeCompare(right))}}function buildCreateRequiredOptionContracts(typeRegistry){const byTypeStrict={};const byTypeProgressive={};for(const typeName of[...typeRegistry.types].sort((left,right)=>left.localeCompare(right))){const typeDefinition=typeRegistry.by_type[typeName];byTypeStrict[typeName]=resolveCreateRequiredOptionContract(typeDefinition,"strict");byTypeProgressive[typeName]=resolveCreateRequiredOptionContract(typeDefinition,"progressive")}return{default_create_mode:"strict",by_create_mode:{strict:{by_type:byTypeStrict},progressive:{by_type:byTypeProgressive}}}}function attachCreateRequiredOptionContracts(schema,metadata){const branches=extractActionBranches(schema);if(branches.length===0){return schema}let touched=false;const enrichedBranches=branches.map(branch=>{const properties=branch.properties;if(typeof properties!=="object"||properties===null){return branch}const actionProperty=properties.action;if(typeof actionProperty!=="object"||actionProperty===null){return branch}if(actionProperty.const!=="create"){return branch}touched=true;return{...branch,"x-create-required-options":metadata}});if(!touched){return schema}return{...schema,oneOf:enrichedBranches}}function resolveContractsSelection(options){const explicitlyScoped=normalizeToken(options.action)!==void 0||normalizeToken(options.command)!==void 0;const projectionSelected=options.schemaOnly===true||options.flagsOnly===true||options.availabilityOnly===true;const summary=options.summary===true||options.full!==true&&options.runtimeOnly!==true&&!explicitlyScoped&&!projectionSelected;const schemaOnly=options.schemaOnly===true;const flagsOnly=options.flagsOnly===true;const availabilityOnly=options.availabilityOnly===true;const runtimeOnly=options.runtimeOnly===true;const fullOutput=options.full===true;const selectedAction=normalizeToken(options.action);const selectedCommand=normalizeToken(options.command);const unfilteredDefaultBriefMode=!summary&&!fullOutput&&!schemaOnly&&!flagsOnly&&!availabilityOnly&&!selectedAction&&!selectedCommand;return{selectedAction,selectedCommand,summary,schemaOnly,flagsOnly,availabilityOnly,runtimeOnly,fullOutput,omitUnfilteredSchema:unfilteredDefaultBriefMode,omitUnfilteredCommandFlags:unfilteredDefaultBriefMode,omitUnfilteredCommanderAliases:unfilteredDefaultBriefMode||selectedCommand!==void 0&&!fullOutput}}function assertSingleContractsProjection(selection){const projectionFlagsEnabled=[selection.summary,selection.schemaOnly,selection.flagsOnly,selection.availabilityOnly].filter(value=>value).length;if(projectionFlagsEnabled>1){throw new PmCliError("Choose only one projection flag: --summary, --schema-only, --flags-only, or --availability-only.",EXIT_CODE.USAGE)}}async function readContractsSettings(pmRoot,readSettingsFn=readSettings){try{return await readSettingsFn(pmRoot)}catch{return structuredClone(SETTINGS_DEFAULTS)}}async function resolveContractsRuntimeContext(global2,pmRoot,selection){const settings=await readContractsSettings(pmRoot);const runtimeProbe=await resolveRuntimeExtensionActionProbe(global2);const typeRegistry=resolveItemTypeRegistry(settings,runtimeProbe.registrations??getActiveExtensionRegistrations());const runtimeFieldRegistry=resolveRuntimeFieldRegistry(settings.schema);const extensionContracts=collectExtensionCommandContracts(runtimeProbe);return{settings,runtimeProbe,typeRegistry,statusRegistry:resolveRuntimeStatusRegistry(settings.schema),runtimeFieldRegistry,runtimeFieldFlagMap:buildRuntimeFieldFlagContracts(runtimeFieldRegistry),createRequiredOptionContracts:buildCreateRequiredOptionContracts(typeRegistry),extensionContracts,mergedExtensionContracts:mergeExtensionContractsByAction(extensionContracts.filter(entry=>isCommandDiscoverable(selection,entry.command,extensionContracts))),extensionFlagMap:collectExtensionFlagContractsByCommand(runtimeProbe.flagRegistrations)}}function shouldIncludePackageOwnedActions(selection){return selection.availabilityOnly&&(selection.selectedAction!==void 0&&PACKAGE_OWNED_ACTIONS.has(selection.selectedAction)||selection.selectedCommand!==void 0&&PACKAGE_OWNED_COMMANDS.has(resolvePmCommandOperation(selection.selectedCommand)))}function collectContractsActionDescriptors(selection,mergedExtensionContracts){const actionDescriptors=collectActionContractDescriptors(mergedExtensionContracts,{includePackageOwnedActions:shouldIncludePackageOwnedActions(selection)});if(selection.selectedAction===void 0&&selection.selectedCommand===void 0){const deprecatedActions=new Set(PM_DEPRECATED_TOOL_ACTIONS);return actionDescriptors.filter(descriptor=>!deprecatedActions.has(descriptor.action)&&(selection.fullOutput||(mergedExtensionContracts.find(entry=>entry.action===descriptor.action)?.tier??resolvePmCommandVisibilityTier(descriptor.action))!=="internal"))}if(shouldIncludePackageOwnedActions(selection)&&selection.selectedCommand!==void 0&&PACKAGE_OWNED_COMMANDS.has(resolvePmCommandOperation(selection.selectedCommand))&&!actionDescriptors.some(entry=>entry.command_path===selection.selectedCommand)){actionDescriptors.push({action:packageOwnedActionForCommand(resolvePmCommandOperation(selection.selectedCommand)),provider:"extension",requires_extension:true,command_path:selection.selectedCommand})}return actionDescriptors}function assertKnownContractsAction(selection,actionDescriptors){const actionNames=new Set(actionDescriptors.map(entry=>entry.action));if(selection.selectedAction&&!actionNames.has(selection.selectedAction)){throw new PmCliError(`Unknown action: "${selection.selectedAction}".`,EXIT_CODE.USAGE)}}function buildContractsCommandCatalog(actionDescriptors,mergedExtensionContracts){return[...new Set([...PM_CORE_COMMAND_NAMES.filter(entry=>!PACKAGE_OWNED_COMMANDS.has(resolvePmCommandOperation(entry))),...[...CORE_COMMAND_FLAG_CONTRACTS_BY_COMMAND.keys()].filter(entry=>!PACKAGE_OWNED_COMMANDS.has(resolvePmCommandOperation(entry))),...actionDescriptors.flatMap(entry=>entry.command_path?splitCommandPathAliases(entry.command_path).filter(command=>entry.provider==="extension"||!PACKAGE_OWNED_COMMANDS.has(resolvePmCommandOperation(command))||mergedExtensionContracts.some(contract=>contract.action===entry.action)):[]),...mergedExtensionContracts.flatMap(entry=>entry.command.split("|").flatMap(command=>{const alias=PM_NAMESPACED_COMMAND_ALIASES.find(entry2=>entry2.alias===command||entry2.canonical===command);return alias===void 0?[command]:[alias.alias,alias.canonical]}))])].map(entry=>normalizeCommandPath(entry)).filter(entry=>entry.length>0).sort((left,right)=>left.localeCompare(right))}function buildCommandNamespaceError(command,namespaceChildren){const displayedNamespaceChildren=namespaceChildren.slice(0,COMMAND_NAMESPACE_DISPLAY_LIMIT);const hiddenNamespaceChildCount=namespaceChildren.length-displayedNamespaceChildren.length;const displayedChildCommandList=hiddenNamespaceChildCount>0?`${displayedNamespaceChildren.join(", ")}, and ${hiddenNamespaceChildCount} more`:displayedNamespaceChildren.join(", ");const fallbackCandidates=namespaceChildren.slice(0,COMMAND_NAMESPACE_FALLBACK_LIMIT);const childCommandExamples=namespaceChildren.slice(0,5).map(childCommand=>`pm contracts --command "${childCommand}" --flags-only --json`);const suggestedChildCommand=namespaceChildren[0];return new PmCliError(`Command "${command}" is a command namespace. Choose a concrete child command: ${displayedChildCommandList}.`,EXIT_CODE.USAGE,{code:"command_namespace",required:"Use a concrete child command path listed under this namespace.",why:"Command groups expose help at the namespace root, but command flag contracts belong to executable child commands.",examples:childCommandExamples,nextSteps:[`Retry with a child command, for example: ${childCommandExamples[0]}`],recovery:{suggested_retry:`pm contracts --command "${suggestedChildCommand}" --flags-only --json`,fallback_candidates:fallbackCandidates.map(childCommand=>({source:"command_namespace",command:`pm contracts --command "${childCommand}" --flags-only --json`,reason:`Child command under ${command}`}))}})}function buildPackageOwnedCommandError(command,packageHint){return new PmCliError(`Unknown command: "${command}". Command "${command}" is provided by the optional "${packageHint}" package. Run "pm install ${packageHint} --project" and retry.`,EXIT_CODE.USAGE,{code:"unknown_command",required:`Install the optional "${packageHint}" package, or choose a command from pm contracts --flags-only --json.`,why:"Command contracts include core commands plus commands registered by active packages and extensions.",examples:[`pm install ${packageHint} --project`,`pm contracts --command ${command} --flags-only --json`],nextSteps:[`Install the optional package first: pm install ${packageHint} --project`],recovery:{suggested_retry:`pm install ${packageHint} --project`}})}function buildUnknownCommandError(command){return new PmCliError(`Unknown command: "${command}".`,EXIT_CODE.USAGE,{code:"unknown_command",required:"Use a command path listed by pm contracts --flags-only --json.",why:"Command contracts are generated from the active core, package, and extension command registry.",examples:["pm contracts --flags-only --json","pm --help"],nextSteps:["Verify spelling and active packages/extensions, then rerun with a known command path."],recovery:{suggested_retry:"pm contracts --flags-only --json"}})}function assertKnownContractsCommand(selection,commandCatalog){if(!selection.selectedCommand){return}const commandNames=new Set(commandCatalog);if(commandNames.has(selection.selectedCommand)){return}const namespaceChildren=commandCatalog.filter(command=>command.startsWith(`${selection.selectedCommand} `));if(namespaceChildren.length>0){throw buildCommandNamespaceError(selection.selectedCommand,namespaceChildren)}const packageHint=PACKAGE_OWNED_COMMAND_INSTALL_HINTS.get(resolvePmCommandOperation(selection.selectedCommand));if(packageHint){throw buildPackageOwnedCommandError(selection.selectedCommand,packageHint)}throw buildUnknownCommandError(selection.selectedCommand)}function resolveContractsActionContext(selection,runtime){const actionDescriptors=collectContractsActionDescriptors(selection,runtime.mergedExtensionContracts);assertKnownContractsAction(selection,actionDescriptors);const commandCatalog=buildContractsCommandCatalog(actionDescriptors,runtime.mergedExtensionContracts);assertKnownContractsCommand(selection,commandCatalog);const selectedPackageOwnedAction=selection.selectedCommand?PACKAGE_OWNED_COMMAND_ACTIONS.get(resolvePmCommandOperation(selection.selectedCommand)):void 0;const commandScopedDescriptors=selection.selectedCommand?actionDescriptors.filter(descriptor=>selectedPackageOwnedAction?descriptor.action===selectedPackageOwnedAction:actionDescriptorMatchesSelectedCommand(descriptor,selection.selectedCommand)):actionDescriptors;if(selection.selectedCommand&&selection.selectedAction&&!commandScopedDescriptors.some(descriptor=>descriptor.action===selection.selectedAction)){throw new PmCliError(`Action "${selection.selectedAction}" is not mapped to command "${selection.selectedCommand}" in contracts output.`,EXIT_CODE.USAGE)}const scopedActionDescriptors=selection.selectedAction?commandScopedDescriptors.filter(descriptor=>descriptor.action===selection.selectedAction):commandScopedDescriptors;const allActionAvailability=[...new Map(scopedActionDescriptors.map(descriptor=>resolveActionAvailability(descriptor,runtime.runtimeProbe)).map(entry=>[selectedPackageOwnedAction?entry.action:`${entry.action}|${entry.command_path??""}`,entry])).values()];const actionAvailability=selection.runtimeOnly&&!selection.selectedAction&&!selection.availabilityOnly?allActionAvailability.filter(entry=>entry.invocable):allActionAvailability;return{actionDescriptors,commandCatalog,commandScopedDescriptors,scopedActionDescriptors,selectedPackageOwnedAction,actionAvailability,actions:[...new Set(actionAvailability.map(entry=>entry.action))]}}function buildSchemaActionSet(schema){return new Set(extractActionBranches(schema).map(entry=>{const properties=entry.properties;if(typeof properties!=="object"||properties===null){return null}const actionProperty=properties.action;if(typeof actionProperty!=="object"||actionProperty===null){return null}const actionConst=actionProperty.const;return typeof actionConst==="string"?actionConst:null}).filter(entry=>entry!==null))}function buildMergedContractsSchema(mergedExtensionContracts){const schema=PM_TOOL_PARAMETERS_SCHEMA;const schemaBranches=extractActionBranches(schema);const schemaActionSet=buildSchemaActionSet(schema);const extensionBranches=mergedExtensionContracts.filter(contract=>!schemaActionSet.has(contract.action)).map(contract=>buildExtensionActionSchemaBranch(contract));return extensionBranches.length>0?{...schema,oneOf:[...schemaBranches,...extensionBranches]}:schema}function filterContractsSchema(selection,actionContext,mergedSchema){const descriptorActionSet=new Set(actionContext.actionDescriptors.map(descriptor=>descriptor.action));const filteredSchema=selection.selectedAction?filterSchemaByAction(mergedSchema,selection.selectedAction):selection.selectedCommand?filterSchemaByActions(mergedSchema,new Set(actionContext.scopedActionDescriptors.map(descriptor=>descriptor.action))):filterSchemaByActions(mergedSchema,descriptorActionSet);return selection.runtimeOnly&&!selection.selectedAction?filterSchemaByActions(filteredSchema,new Set(actionContext.actions)):filteredSchema}function resolveContractsSchemaContext(selection,runtime,actionContext){const mergedSchema=buildMergedContractsSchema(runtime.mergedExtensionContracts);const includeSchemaSurface=!selection.flagsOnly&&!selection.availabilityOnly;const filteredSchema=includeSchemaSurface?attachCreateRequiredOptionContracts(filterContractsSchema(selection,actionContext,mergedSchema),runtime.createRequiredOptionContracts):filterContractsSchema(selection,actionContext,mergedSchema);return{mergedSchema,filteredSchema}}function resolveContractsCommands(selection,actionContext){if(selection.selectedCommand!==void 0){return[selection.selectedCommand]}if(selection.selectedAction){return resolveScopedCommandsFromActionDescriptors(actionContext.scopedActionDescriptors,actionContext.commandCatalog)}return actionContext.commandCatalog}function runtimeCommandVisibilityTier(command,extensionContracts){return extensionContracts.find(entry=>resolvePmCommandOperation(entry.command)===resolvePmCommandOperation(command))?.tier??resolvePmCommandVisibilityTier(command)}function isCommandDiscoverable(selection,command,extensionContracts){return selection.fullOutput||selection.selectedCommand!==void 0||selection.selectedAction!==void 0||runtimeCommandVisibilityTier(command,extensionContracts)!=="internal"}function resolveOutputCommands(selection,commands,extensionContracts){if(selection.selectedCommand!==void 0||selection.selectedAction!==void 0){return commands}const hiddenAliases=new Set(PM_COMMAND_ALIAS_CONTRACTS.filter(contract=>contract.hidden&&(contract.lifecycle==="deprecated"||!selection.fullOutput&&!selection.availabilityOnly)).map(contract=>contract.alias));if(selection.summary&&!selection.fullOutput){for(const alias of COMMAND_ALIAS_TO_CANONICAL.keys())hiddenAliases.add(alias)}return commands.filter(command=>!hiddenAliases.has(command)&&isCommandDiscoverable(selection,command,extensionContracts))}function canonicalSummaryCommand(command){const historyAlias=PM_NAMESPACED_COMMAND_ALIASES.find(contract=>contract.alias===command||contract.canonical===command);if(historyAlias)return historyAlias.canonical;const rootCommand=command.split(" ")[0];if(rootCommand.startsWith("list-"))return"list";return COMMAND_ALIAS_TO_CANONICAL.get(rootCommand)??rootCommand}const COMMAND_OPERATION_INTENTS=new Map([["activate","Activate"],["adopt","Adopt"],["adopt-all","Adopt all"],["catalog","Catalog"],["complete","Complete"],["create","Create"],["deactivate","Deactivate"],["delete","Delete"],["describe","Describe"],["doctor","Diagnose"],["explore","Explore"],["init","Initialize"],["inspect","Inspect"],["install","Install"],["list","List"],["manage","Manage"],["migrate","Migrate"],["mutate","Mutate"],["reload","Reload"],["restore","Restore"],["run","Run"],["snapshot","Manage snapshots for"],["uninstall","Uninstall"],["upgrade","Upgrade"]]);const COMMAND_INTENT_SUBJECT_OVERRIDES=new Map([["extension adopt-all","extensions"],["package adopt-all","packages"],["workspace snapshot list","workspace snapshots"]]);function summarizeCommandIntent(command,extensionContracts){const declared=COMMAND_INTENTS.get(resolvePmCommandOperation(command))??(command.includes(" ")?void 0:COMMAND_INTENTS.get(canonicalSummaryCommand(command)));if(declared!==void 0){return{intent:declared,intent_source:"command"}}const extensionContract=extensionContracts.find(contract=>splitCommandPathAliases(contract.command).some(path=>resolvePmCommandOperation(path)===resolvePmCommandOperation(command)));if(extensionContract?.intent!==null&&extensionContract?.intent!==void 0){return{intent:extensionContract.intent,intent_source:"command"}}if(extensionContract?.description!==null&&extensionContract?.description!==void 0){return{intent:extensionContract.description,intent_source:"description"}}const tokens=command.split(" ");const operation=tokens.at(-1);const subject=tokens.slice(0,-1).join(" ");const verb=COMMAND_OPERATION_INTENTS.get(operation);const intentSubject=COMMAND_INTENT_SUBJECT_OVERRIDES.get(command)??subject;return{intent:verb===void 0||subject.length===0?`Run ${command}.`:`${verb} ${intentSubject}.`,intent_source:"generated"}}function buildCommandSummarySurface(commands,extensionContracts=[],options={}){const includeFormatBudgets=options.includeFormatBudgets??true;const includeIntentProvenance=options.includeIntentProvenance??true;return[...new Set(commands.map(normalizeCommandPath))].filter(command=>command.length>0).sort((left,right)=>left.localeCompare(right)).map(command=>{const budget=resolvePmCommandOutputBudget(command,{generateFallback:true});const rootCommand=command.split(" ")[0];const canonicalRoot=COMMAND_ALIAS_TO_CANONICAL.get(rootCommand)??(rootCommand.startsWith("list-")?"list":rootCommand.startsWith("history-")?"history":rootCommand);const availableFlags=new Set([...resolveCoreCommandFlags(command).map(contract=>contract.flag),...extensionContracts.filter(contract=>splitCommandPathAliases(contract.command).some(path=>resolvePmCommandOperation(path)===resolvePmCommandOperation(command))).flatMap(contract=>contract.flags.map(flag=>flag.flag))]);const flags=(AGENT_BOOTSTRAP_FLAGS.get(resolvePmCommandOperation(command))??AGENT_BOOTSTRAP_FLAGS.get(canonicalRoot)??AGENT_BOUNDED_FLAG_PRIORITY).filter(flag=>availableFlags.has(flag));const intent=summarizeCommandIntent(command,extensionContracts);return{command,intent:intent.intent,...includeIntentProvenance||intent.intent_source!=="command"?{intent_source:intent.intent_source}:{},...flags.length>0?{flags}:{},default_max_estimated_tokens:budget.default_max_estimated_tokens,...includeFormatBudgets?{default_max_estimated_tokens_by_format:{...budget.default_max_estimated_tokens_by_format}}:{}}})}function buildCommandOutputContracts(commands){return commands.map(command=>({budget:resolvePmCommandOutputBudget(command,{generateFallback:true}),envelope:resolvePmCommandOutputEnvelope(command)}))}function buildCommandExitContractGroups(commands){const groups=new Map;for(const command of commands){const contract=resolvePmCommandExitContract(command);const exitCodes=contract===void 0?[EXIT_CODE.SUCCESS,EXIT_CODE.GENERIC_FAILURE,EXIT_CODE.USAGE,EXIT_CODE.NOT_FOUND,EXIT_CODE.CONFLICT,EXIT_CODE.DEPENDENCY_FAILED]:contract.exit_codes;const key=exitCodes.join(",");const group=groups.get(key)??{commands:[],exit_codes:exitCodes};group.commands.push(command);groups.set(key,group)}return[...groups.values()]}function resolveExtensionCommandContracts(selection,runtime,outputCommands){if(selection.selectedCommand){return runtime.extensionContracts.filter(entry=>splitCommandPathAliases(entry.command).some(path=>resolvePmCommandOperation(path)===resolvePmCommandOperation(selection.selectedCommand)))}if(selection.selectedAction){const outputCommandSet=new Set(outputCommands);return runtime.extensionContracts.filter(entry=>splitCommandPathAliases(entry.command).some(command=>outputCommandSet.has(command)))}return runtime.extensionContracts.filter(entry=>isCommandDiscoverable(selection,entry.command,runtime.extensionContracts))}function createContractsResult(selection,schemaContext,actionContext,outputCommands){return{schema_version:typeof schemaContext.mergedSchema["x-schema-version"]==="string"?schemaContext.mergedSchema["x-schema-version"]:null,schema_id:typeof schemaContext.mergedSchema.$id==="string"?schemaContext.mergedSchema.$id:null,selected:{action:selection.selectedAction??null,command:selection.selectedCommand??null,summary:selection.summary,schema_only:selection.schemaOnly,flags_only:selection.flagsOnly,availability_only:selection.availabilityOnly,runtime_only:selection.runtimeOnly,command_scoped:selection.selectedCommand!==void 0},commands:selection.summary?[]:outputCommands,...!selection.summary&&!selection.flagsOnly?{actions:actionContext.actions,action_availability:actionContext.actionAvailability}:{}}}function attachRuntimeContractsResult(result,runtime,selection){if((selection.selectedCommand==="history"||selection.fullOutput)&&!selection.flagsOnly&&!selection.schemaOnly&&!selection.availabilityOnly){result.history_operations=PM_HISTORY_OPERATION_CONTRACT}const selectedCommand=selection.selectedCommand;result.runtime_schema={statuses:runtime.statusRegistry.definitions.map(definition=>definition.id),open_status:runtime.statusRegistry.open_status,close_status:runtime.statusRegistry.close_status,canceled_status:runtime.statusRegistry.canceled_status,types:[...runtime.typeRegistry.types],fields_by_command:Object.fromEntries([...runtime.runtimeFieldRegistry.command_to_fields.entries()].filter(([command])=>selectedCommand===void 0||command===selectedCommand).map(([command,definitions])=>[command,[...new Set(definitions.map(definition=>`--${definition.cli_flag}`))].sort((left,right)=>left.localeCompare(right))]))};if(selectedCommand!==void 0&&!selection.fullOutput){return}result.extension_contracts={capabilities:[...PM_EXTENSION_CAPABILITY_CONTRACTS],services:[...PM_EXTENSION_SERVICE_NAME_CONTRACTS],policy_modes:[...PM_EXTENSION_POLICY_MODE_CONTRACTS],policy_mode_scope:"extensions.policy.mode",policy_surfaces:[...PM_EXTENSION_POLICY_SURFACE_CONTRACTS],trust_modes:[...PM_EXTENSION_TRUST_MODE_CONTRACTS],trust_mode_scope:"extensions.policy.trust_mode",sandbox_profiles:[...PM_EXTENSION_SANDBOX_PROFILE_CONTRACTS],manifest_versions:[1,2],compatibility:{current:"v2",previous:["v1"],breaking_strategy:"versioned_breaking"}};result.governance_contracts={ownership_enforcement_modes:[...GOVERNANCE_OWNERSHIP_ENFORCEMENT_VALUES],create_modes:[...GOVERNANCE_CREATE_MODE_DEFAULT_VALUES],close_validation_modes:[...GOVERNANCE_CLOSE_VALIDATION_DEFAULT_VALUES],workflow_enforcement_modes:[...GOVERNANCE_WORKFLOW_ENFORCEMENT_VALUES]};result.relationship_kind_contracts=[...BUILTIN_RELATIONSHIP_KINDS,...(runtime.runtimeProbe.registrations?.relationship_kinds??[]).flatMap(registration=>registration.definitions)].sort((left,right)=>left.kind.localeCompare(right.kind)).map(definition=>({canonical:definition.kind,aliases:[...definition.aliases??[]],...definition.inverse===void 0?{}:{inverse:definition.inverse},ordering:definition.ordering,hierarchy:definition.hierarchy}))}function attachSchemaContractsResult(result,selection,schemaContext,extensionCommandContracts){if(selection.flagsOnly||selection.availabilityOnly){return}if(!selection.omitUnfilteredSchema){result.schema=schemaContext.filteredSchema;result.extension_commands=extensionCommandContracts;return}result.schema_omitted_reason="unfiltered_default_brief";result.extension_commands=extensionCommandContracts}function attachFlagContractsResult(result,selection,runtime,outputCommands,commandAliases){if(selection.schemaOnly||selection.availabilityOnly){return}if(!selection.omitUnfilteredCommandFlags){result.command_flags=buildCommandFlagSurface(outputCommands,runtime.extensionFlagMap,runtime.runtimeFieldFlagMap,selection.selectedCommand!==void 0,runtime.extensionContracts);const commandSet=new Set(outputCommands);result.list_projections=Object.entries(LIST_COMMAND_DEFAULT_PROJECTIONS).filter(([command])=>commandSet.has(command)).map(([command,defaultProjection])=>({command,default:defaultProjection,brief_fields:[...BRIEF_LIST_FIELDS],compact_fields:[...DEFAULT_COMPACT_LIST_FIELDS]}))}else{result.command_flags_omitted_reason="unfiltered_default_brief"}result.command_aliases=selection.fullOutput?commandAliases:commandAliases.map(({canonical,aliases})=>({canonical,aliases}));if(!selection.fullOutput){result.command_alias_contracts_omitted_reason="compact_projection; restore with --full"}}function attachCommanderAliasContractsResult(result,selection){if(selection.schemaOnly||selection.flagsOnly||selection.availabilityOnly){return}if(!selection.omitUnfilteredCommanderAliases){result.commander_aliases=buildCommanderAliasSurface();return}result.commander_aliases_omitted_reason=selection.selectedCommand?"command_scoped":"unfiltered_default_brief"}function attachAgentCommandContractsResult(result,outputCommands,extensionCommandContracts,options){result.command_summaries=buildCommandSummarySurface(outputCommands,extensionCommandContracts,{includeFormatBudgets:options.includeFormatBudgets,includeIntentProvenance:options.includeIntentProvenance});result.output_policy={token_estimate:"ceil(utf8_bytes / 4)",degradation_ladder:[...PM_OUTPUT_DEGRADATION_STEPS],allows_unbounded_opt_out:true};result.output_projection_contracts={global_ladder_field:"output_policy.degradation_ladder",global_ladder_scope:"union_not_per_command",discovery:"pm contracts --command <command> --summary",...options.includeProjectionModeMatrix?{commands:[...new Set(outputCommands.map(normalizeCommandPath))].filter(command=>resolveReadOutputSurface(command)!==void 0).sort((left,right)=>left.localeCompare(right)).map(command=>({command,modes:[...readOutputIncludeModeOptions(command).keys()]}))}:{}};result.grammar_contracts={nouns:PM_CLI_GRAMMAR_CONTRACT.nouns,shared_verbs:PM_CLI_GRAMMAR_CONTRACT.shared_verbs,scope_before_verb:PM_CLI_GRAMMAR_CONTRACT.scope_before_verb,visible_top_level_ceiling:PM_CLI_GRAMMAR_CONTRACT.visible_top_level_ceiling,ceiling_raise_requires_pm_item:PM_CLI_GRAMMAR_CONTRACT.ceiling_raise_requires_pm_item,positional_shape_budget:PM_CLI_GRAMMAR_CONTRACT.positional_shape_budget,positional_shape_count:new Set(PM_COMMAND_POSITIONAL_CONTRACTS.map(({slots})=>positionalShapeKey(slots))).size,positional_action_count:PM_POSITIONAL_ACTION_CONTRACTS.length,positional_action_parents:[...new Set(PM_POSITIONAL_ACTION_CONTRACTS.map(({parent})=>parent))].sort((left,right)=>left.localeCompare(right)),...options.includePositionalSignatures?{positional_signatures:PM_COMMAND_POSITIONAL_CONTRACTS}:{}}}async function runContracts(options,global2){const selection=resolveContractsSelection(options);assertSingleContractsProjection(selection);const pmRoot=resolvePmRoot(process.cwd(),global2.path);const runtime=await resolveContractsRuntimeContext(global2,pmRoot,selection);const actionContext=resolveContractsActionContext(selection,runtime);const schemaContext=resolveContractsSchemaContext(selection,runtime,actionContext);const commands=resolveContractsCommands(selection,actionContext);const outputCommands=resolveOutputCommands(selection,commands,runtime.extensionContracts);const result=createContractsResult(selection,schemaContext,actionContext,outputCommands);const extensionCommandContracts=resolveExtensionCommandContracts(selection,runtime,outputCommands);const includeCommandDetails=selection.fullOutput||selection.selectedCommand!==void 0;if(selection.summary||selection.fullOutput){attachAgentCommandContractsResult(result,outputCommands,extensionCommandContracts,{includeFormatBudgets:includeCommandDetails,includeIntentProvenance:includeCommandDetails,includePositionalSignatures:includeCommandDetails,includeProjectionModeMatrix:includeCommandDetails})}if(selection.summary){return result}const commandAliases=buildCommandAliasSurface(actionContext.commandCatalog.filter(command=>isCommandDiscoverable(selection,command,runtime.extensionContracts)));if(!(selection.flagsOnly&&!selection.fullOutput)){attachRuntimeContractsResult(result,runtime,selection)}attachSchemaContractsResult(result,selection,schemaContext,extensionCommandContracts);attachFlagContractsResult(result,selection,runtime,outputCommands,commandAliases);attachCommanderAliasContractsResult(result,selection);if(selection.selectedCommand==="assurance"||selection.fullOutput){result.assurance_contracts={measurement_source_kinds:[...ASSURANCE_MEASUREMENT_SOURCE_KINDS],gate_triggers:[...ASSURANCE_GATE_TRIGGERS]}}if(selection.fullOutput&&result.grammar_contracts){result.grammar_contracts.destinations=PM_COMMAND_DESTINATION_CONTRACTS.map(row=>({...row,reason:row.reason??""}))}if(selection.fullOutput&&!selection.schemaOnly&&!selection.flagsOnly&&!selection.availabilityOnly){result.mcp_tools=buildMcpToolContracts();result.context_intents=getActiveContextIntentContracts();result.read_output_dimensions=PM_READ_OUTPUT_SURFACE_CONTRACTS;result.error_codes=PM_ERROR_CODE_CATALOG;result.command_output_contracts=buildCommandOutputContracts(outputCommands);result.diagnostic_output_contracts=PM_DIAGNOSTIC_OUTPUT_BUDGET_CONTRACTS;result.command_exit_contracts={vocabulary:PM_COMMAND_EXIT_OUTCOME_CONTRACTS,command_sets:buildCommandExitContractGroups(outputCommands)}}return result}const _testOnlyContractsCommand={actionDescriptorMatchesSelectedCommand,attachCreateRequiredOptionContracts,buildExtensionActionSchemaBranch,buildCommandSummarySurface,buildCommandOutputContracts,buildCommandExitContractGroups,buildRuntimeFieldFlagContracts,collectActionContractDescriptors,collectExtensionCommandContracts,collectExtensionFlagContractsByCommand,extractActionBranches,extensionSchemaPropertyNameFromFlag,filterSchemaByAction,filterSchemaByActions,isCoreCommandPath,mergeExtensionContractsByAction,normalizeExtensionFlagName,normalizeActionNameFromCommand,normalizeCommandForRuntimeFieldFlags,normalizeCommandPath,packageOwnedActionForCommand,readContractsSettings,resolveActionCommandPath,resolveActionAvailability,resolveCoreCommandFlags,resolveRuntimeExtensionActionProbe,resolveScopedCommandsFromActionDescriptors,splitCommandPathAliases,toRuntimeLongFlagToken,toRuntimeShortFlagToken};export{_testOnlyContractsCommand,buildCommandAliasSurface,runContracts};
2
2
  //# sourceMappingURL=runtime-contracts.js.map
@@ -1,2 +1,2 @@
1
- !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="a8da6368-489f-579a-8a64-a9bb025f95e7")}catch(e2){}})();import{Command}from"commander";import{writeStdout}from"../core/output/output.js";function createPmCliProgram(version){return new Command().name("pm").description("Universal, flexible, extensible, agent-optimized project management CLI for any project or programming language.").version(version).showHelpAfterError(false).allowExcessArguments(false).allowUnknownOption(false).configureOutput({writeOut:value=>{writeStdout(value)},writeErr:()=>{}}).option("--json","Output JSON instead of TOON; mutations emit a flat receipt with top-level id/status/changed_field_count while reads use documented entity or collection envelopes").option("--lean","Omit null and empty containers from JSON output").option("--token-accounting","Attach a bounded per-section token-cost receipt to command output").option("--output-include <fields>","Retain comma-separated fields or sections in read output").option("--output-limit <count>","Bound rows in read output").option("--output-budget <tokens|unbounded>","Bound estimated tokens in read output or explicitly disable the default ceiling").option("--output-format <toon|json>","Select the read-output encoding").option("--output-session <state>","Carry a JSON session budget and served-item ledger across read calls").option("--output-cursor <cursor>","Resume a budget-compacted declared row collection").option("--output-row-contract","Include the machine-readable row selector and TOON encoding contract").option("--quiet","Suppress stdout output").option("--no-changed-fields","Omit the changed_fields array from mutation output (keeps changed_field_count)").option("--full-changed-fields","Restore the legacy full mutation envelope and changed_fields array").option("--id-only","Print only id and status for single-item mutation output").option("--pm-path <dir>","Explicit tracker storage path for this command (preferred over --path)").option("--path <dir>","Backward-compatible alias for --pm-path; this is the tracker storage path, not a workspace cwd").option("--no-extensions","Disable extension loading").option("--no-pager","Disable pager integration for help and long output").option("--explain","Render extended rationale and examples in help output").option("--all","Reveal every public command and compatibility alias").option("--profile","Print deterministic timing diagnostics").option("--author <id>","Override mutation author for this invocation").exitOverride()}export{createPmCliProgram};
1
+ !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="59132bc6-2d45-5049-981f-fadcf0c75091")}catch(e2){}})();import{Command}from"commander";import{writeStdout}from"../core/output/output.js";function createPmCliProgram(version){return new Command().name("pm").description("Universal, flexible, extensible, agent-optimized project management CLI for any project or programming language.").version(version).showHelpAfterError(false).allowExcessArguments(false).allowUnknownOption(false).configureOutput({writeOut:value=>{writeStdout(value)},writeErr:()=>{}}).option("--json","Output JSON instead of TOON; mutations emit a flat receipt with top-level id/status/changed_field_count while reads use documented entity or collection envelopes").option("--lean","Omit null and empty containers from JSON output").option("--token-accounting","Attach a bounded per-section token-cost receipt to command output").option("--output-include <fields>","Retain comma-separated fields or sections in read output").option("--output-limit <count>","Bound rows in read output").option("--output-budget <tokens|unbounded>","Bound estimated tokens in read output or explicitly disable the default ceiling").option("--output-format <toon|json>","Select the result encoding for reads and mutations").option("--output-session <state>","Carry a JSON session budget and served-item ledger across read calls").option("--output-cursor <cursor>","Resume a budget-compacted declared row collection").option("--output-row-contract","Include row selectors, encoding metadata, and read-output receipts").option("--quiet","Suppress stdout output").option("--no-changed-fields","Omit the changed_fields array from mutation output (keeps changed_field_count)").option("--full-changed-fields","Restore the legacy full mutation envelope and changed_fields array").option("--id-only","Print only id and status for single-item mutation output").option("--pm-path <dir>","Explicit tracker storage path for this command (preferred over --path)").option("--path <dir>","Backward-compatible alias for --pm-path; this is the tracker storage path, not a workspace cwd").option("--no-extensions","Disable extension loading").option("--no-pager","Disable pager integration for help and long output").option("--explain","Render extended rationale and examples in help output").option("--all","Reveal every public command and compatibility alias").option("--profile","Print deterministic timing diagnostics").option("--author <id>","Override mutation author for this invocation").exitOverride()}export{createPmCliProgram};
2
2
  //# sourceMappingURL=cli-program.js.map
@@ -1,2 +1,2 @@
1
- !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="6436107d-eedc-5c97-9d8f-6f119c9bbe29")}catch(e2){}})();import{AsyncLocalStorage}from"node:async_hooks";import{renderPmCommand}from"./command-line.js";import{attachOutputOmissionReceipt}from"./output-projection.js";import{encodeQueryCursor}from"./pagination.js";import{applyReadOutputDimensions,stabilizeReadOutputReceiptEstimates}from"./read-output-contracts.js";import{propagateContextUsageServingReceipt}from"./context-usage.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";const PM_CONTEXT_INTENT_CONTRACTS=Object.freeze([{command:"context",intent:"orient",description:"Bounded active hierarchy, ownership, blockers, and recent progress.",included_field_groups:["summary","focus","hierarchy","blockers","activity"],token_budget:3e3,source:"core"},{command:"context",intent:"handoff",description:"Active ownership, evidence, decisions, and immediate continuation context.",included_field_groups:["summary","focus","in_progress","decisions","activity"],token_budget:2200,source:"core"},{command:"get",intent:"inspect",description:"Standard-depth item metadata, relationships, evidence, and lifecycle state.",included_field_groups:["item","children","claim_state","linked"],token_budget:3200,source:"core"},{command:"list",intent:"triage",description:"A budget-derived page of compact governance, ownership, priority, and blocker rows for triage.",included_field_groups:["identity","governance","ownership","dependencies"],token_budget:3200,source:"core"},{command:"next",intent:"execute",description:"The highest-ranked actionable work with concise ranking evidence.",included_field_groups:["recommended"],token_budget:1200,source:"core"},{command:"search",intent:"discover",description:"A budget-derived page of ranked canonical lineage candidates with compact match evidence.",included_field_groups:["identity","status","lineage","match"],token_budget:1800,source:"core"}]);const activeContextIntentContracts=new AsyncLocalStorage;function getActiveContextIntentContracts(){return activeContextIntentContracts.getStore()??PM_CONTEXT_INTENT_CONTRACTS}function runWithContextIntentContracts(layers,run){return activeContextIntentContracts.run(composeContextIntentContracts(layers.workspaceContracts,layers.packageContracts),run)}function normalizeContextIntentDeclaration(declaration,source){const command=declaration.command.trim().toLowerCase();const intent=declaration.intent.trim().toLowerCase();const key=`${command}:${intent}`;if(!/^[a-z0-9][a-z0-9-]*$/.test(command)||!/^[a-z0-9][a-z0-9-]*$/.test(intent)){throw new TypeError(`Invalid context intent command or name: ${key}`)}if(declaration.description.trim().length===0){throw new TypeError(`Context intent ${key} requires a non-empty description`)}if(!Number.isSafeInteger(declaration.token_budget)||declaration.token_budget<=0){throw new TypeError(`Context intent ${key} requires a positive integer token_budget`)}const includedFieldGroups=[...new Set(declaration.included_field_groups.map(field=>field.trim()).filter(Boolean))];if(includedFieldGroups.length===0){throw new TypeError(`Context intent ${key} requires included_field_groups`)}return{command,intent,description:declaration.description.trim(),included_field_groups:includedFieldGroups,token_budget:declaration.token_budget,source}}function composeContextIntentContracts(workspaceContracts=[],packageContracts=[]){const layers=[{source:"core",contracts:PM_CONTEXT_INTENT_CONTRACTS,allowOverride:false},{source:"package",contracts:packageContracts,allowOverride:false},{source:"workspace",contracts:workspaceContracts,allowOverride:true}];const composed=new Map;const keysSeenWithinLayer=new Set;for(const layer of layers){keysSeenWithinLayer.clear();for(const declaration of layer.contracts){const normalized=normalizeContextIntentDeclaration(declaration,layer.source);const key=`${normalized.command}:${normalized.intent}`;if(keysSeenWithinLayer.has(key)){throw new TypeError(`Duplicate context intent declaration: ${key}`)}keysSeenWithinLayer.add(key);if(!layer.allowOverride&&composed.has(key)){throw new TypeError(`Duplicate context intent declaration: ${key}`)}composed.set(key,normalized)}}return[...composed.values()].sort((left,right)=>left.command.localeCompare(right.command)||left.intent.localeCompare(right.intent))}function resolveContextIntentContract(command,intent,contracts=getActiveContextIntentContracts(),positionalArguments=[]){const normalizedCommand=command.trim().toLowerCase();const normalizedIntent=intent.trim().toLowerCase();const exact=contracts.find(entry=>entry.command===normalizedCommand&&entry.intent===normalizedIntent);if(exact)return{...exact,source:exact.source??"core"};const candidates=contracts.filter(entry=>entry.command===normalizedCommand).map(entry=>entry.intent);if(candidates.length===0)return void 0;const suggestion=candidates.map(candidate=>{const rows=Array.from({length:normalizedIntent.length+1},(_,index)=>index);for(let candidateIndex=1;candidateIndex<=candidate.length;candidateIndex+=1){let previous=rows[0];rows[0]=candidateIndex;for(let intentIndex=1;intentIndex<=normalizedIntent.length;intentIndex+=1){const prior=rows[intentIndex];rows[intentIndex]=Math.min(rows[intentIndex]+1,rows[intentIndex-1]+1,previous+(candidate[candidateIndex-1]===normalizedIntent[intentIndex-1]?0:1));previous=prior}}return{candidate,distance:rows[normalizedIntent.length]}}).sort((left,right)=>left.distance-right.distance||left.candidate.localeCompare(right.candidate))[0].candidate;const attemptedArguments=[normalizedCommand,...positionalArguments,"--for",normalizedIntent];const suggestedRetryArguments=[normalizedCommand,...positionalArguments,"--for",suggestion];const suggestedCommand=renderPmCommand(suggestedRetryArguments);throw new PmCliError(`Unknown context intent "${normalizedIntent}" for ${normalizedCommand}. Did you mean "${suggestion}"?`,EXIT_CODE.USAGE,{code:"unknown_context_intent",reason:"unknown_intent",field:"for",flag:"--for",value:normalizedIntent,required:`Use a declared ${normalizedCommand} intent.`,why:"Intent names are command-local contracts and cannot be inferred from output section names.",nextSteps:[suggestedCommand],recovery:{recovery_mode:"compact",attempted_command:renderPmCommand(attemptedArguments),allowed_values:[...candidates].sort(),suggested_retry:suggestedCommand,suggested_retry_args:suggestedRetryArguments}})}const CONTEXT_INTENT_DEFAULT_APPLIERS={context:(projected,contract,explicitTokenBudget)=>{if(projected.depth===void 0){projected.depth=contract.intent==="handoff"?"deep":"standard"}if(projected.section===void 0){projected.section=contract.intent==="handoff"?["activity","progress","blockers"]:["hierarchy","blockers","activity"]}const tokenBudget=resolveIntentTokenBudget(projected.tokenBudget,contract.token_budget);const budgetDerivedLimit=resolveIntentRowBudget("context",contract.intent,tokenBudget,explicitTokenBudget);const requestedLimit=parsePositiveIntentTokenBudget(projected.limit);const derivedLimit=String(requestedLimit===void 0?budgetDerivedLimit:Math.min(requestedLimit,budgetDerivedLimit));if(projected.limit===void 0||requestedLimit!==void 0){projected.limit=derivedLimit}if(projected.activityLimit===void 0){projected.activityLimit=derivedLimit}},get:projected=>{if(projected.depth===void 0&&projected.fields===void 0){projected.depth="standard"}},list:(projected,contract,explicitTokenBudget)=>{if(projected.brief===void 0&&projected.compact===void 0&&projected.full===void 0&&projected.fields===void 0){projected.fields="id,title,status,type,priority,parent,assignee,risk,blocked_by"}const tokenBudget=resolveIntentTokenBudget(projected.tokenBudget,contract.token_budget);const budgetDerivedLimit=resolveIntentRowBudget("list",contract.intent,tokenBudget,explicitTokenBudget);const requestedLimit=parsePositiveIntentTokenBudget(projected.limit);if(projected.limit===void 0||requestedLimit!==void 0){projected.limit=String(requestedLimit===void 0?budgetDerivedLimit:Math.min(requestedLimit,budgetDerivedLimit))}},next:projected=>{if(projected.readyOnly===void 0)projected.readyOnly=true},search:(projected,contract,explicitTokenBudget)=>{if(projected.compact===void 0&&projected.full===void 0&&projected.fields===void 0){projected.compact=true}const tokenBudget=resolveIntentTokenBudget(projected.tokenBudget,contract.token_budget);const budgetDerivedLimit=resolveIntentRowBudget("search",contract.intent,tokenBudget,explicitTokenBudget);const requestedLimit=parsePositiveIntentTokenBudget(projected.limit);if(projected.limit===void 0||requestedLimit!==void 0){projected.limit=String(requestedLimit===void 0?budgetDerivedLimit:Math.min(requestedLimit,budgetDerivedLimit))}}};function applyContextIntentProjection(command,options,positionalArguments=[]){const tokenBudget=options.tokenBudget??options.token_budget;if(typeof options.for!=="string"){if(tokenBudget!==void 0&&(command==="get"||command==="list"||command==="search")){throw new PmCliError("--token-budget requires a declared context intent selected with --for",EXIT_CODE.USAGE,{code:"missing_required_option",field:"for",required:"Select a context intent with --for when setting --token-budget.",why:"A token-budget override has no projection contract to constrain without a selected intent.",nextSteps:["Retry with --for <intent> --token-budget <n>, or omit --token-budget."]})}if(options.tokenBudget!==void 0||options.token_budget===void 0){return options}const projected2={...options,tokenBudget};delete projected2.token_budget;return projected2}const contract=resolveContextIntentContract(command,options.for,void 0,positionalArguments);const explicitTokenBudget=parsePositiveIntentTokenBudget(tokenBudget)!==void 0;const projected={...options};if(projected.tokenBudget===void 0&&tokenBudget!==void 0){projected.tokenBudget=tokenBudget}delete projected.token_budget;if(projected.tokenBudget===void 0){projected.tokenBudget=String(contract.token_budget)}CONTEXT_INTENT_DEFAULT_APPLIERS[command](projected,contract,explicitTokenBudget);return projected}const CONTEXT_INTENT_DEGRADATIONS={context:"bounded_sections",get:"standard_item",list:"bounded_fields_and_rows",next:"bounded_ranked_rows",search:"bounded_ranked_rows"};const MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET=256;function compactContextIntentValue(value){if(Array.isArray(value)){return value.map(compactContextIntentValue)}if(value!==null&&typeof value==="object"){return Object.fromEntries(Object.entries(value).map(([key,entry])=>[key,compactContextIntentValue(entry)]))}return typeof value==="string"&&value.length>240?`${value.slice(0,240)}\u2026`:value}function parsePositiveIntentTokenBudget(value){const parsed=typeof value==="number"?value:typeof value==="string"&&/^\d+$/u.test(value.trim())?Number(value):Number.NaN;return Number.isSafeInteger(parsed)&&parsed>0?parsed:void 0}function resolveIntentTokenBudget(value,declaredBudget){const parsed=parsePositiveIntentTokenBudget(value);if(parsed===void 0)return declaredBudget;if(parsed<MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET){throw new PmCliError(`Context intent token budget must be at least ${MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET}`,EXIT_CODE.USAGE,{code:"invalid_argument_value",reason:"below_minimum",field:"tokenBudget",required:`Use an integer token budget of at least ${MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET}.`,why:"Smaller ceilings cannot contain the minimum machine-readable intent receipt.",nextSteps:[`Retry with --token-budget ${MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET} or omit the override.`]})}return parsed}function resolveIntentRowBudget(command,intent,tokenBudget,explicitTokenBudget){if(command==="get"||command==="next")return void 0;const contextOrient=command==="context"&&intent==="orient";const overhead=command==="context"?contextOrient?1200:800:command==="list"?520:480;const rowCost=command==="context"?contextOrient?600:500:16;const calculatedLimit=Math.max(command==="context"?1:2,Math.floor((tokenBudget-overhead)/rowCost));return explicitTokenBudget?calculatedLimit:Math.min(command==="context"?20:100,calculatedLimit)}function updateContextIntentEstimate(projected,receipt){let measuredTokens=receipt.estimated_tokens;for(;;){receipt.estimated_tokens=measuredTokens;const nextMeasurement=Math.ceil(Buffer.byteLength(JSON.stringify(projected),"utf8")/4);if(nextMeasurement===measuredTokens)return;measuredTokens=nextMeasurement}}const CONTEXT_INTENT_ROW_KEYS={context:["high_level","low_level","blocked_fallback","recently_created","unparented","hierarchy","activity","blockers"],get:["children"],list:["items"],next:["ready","decision_needed","gate_needed","containers","blocked","held_by_others"],search:["items"]};function decodeContextIntentCursor(cursor){try{const parsed=JSON.parse(Buffer.from(cursor,"base64url").toString("utf8"));if(typeof parsed.fingerprint!=="string"||!Number.isSafeInteger(parsed.after_index)){return void 0}return{fingerprint:parsed.fingerprint,after_index:parsed.after_index,...typeof parsed.snapshot==="string"?{snapshot:parsed.snapshot}:{}}}catch{return void 0}}function contextIntentRowId(row){if(row===null||typeof row!=="object")return void 0;if(typeof row.id==="string"){return row.id}const nestedId=row.item?.id;return typeof nestedId==="string"?nestedId:void 0}function shrinkContextIntentRowsToBudget(projected,receipt,rows){let compacted=false;for(;;){updateContextIntentEstimate(projected,receipt);if(receipt.estimated_tokens<=receipt.token_budget||rows.length<=1){return compacted}const rowBytes=Buffer.byteLength(JSON.stringify(rows),"utf8");const excessBytes=(receipt.estimated_tokens-receipt.token_budget)*4;rows.splice(-Math.min(rows.length-1,Math.max(1,Math.ceil(excessBytes/Math.max(1,Math.ceil(rowBytes/rows.length))))));compacted=true}}function compactPaginatedContextIntentRows(projected,receipt,options){const rows=projected.items;const cursorContinuesExistingPage=typeof projected.next_cursor==="string";const cursorSource=cursorContinuesExistingPage?projected.next_cursor:options.after;if(!Array.isArray(rows)||typeof cursorSource!=="string")return false;const cursorEnvelope=decodeContextIntentCursor(cursorSource);if(cursorEnvelope===void 0)return false;const originalRowCount=rows.length;const originalRows=[...rows];let compacted=false;for(;;){compacted=shrinkContextIntentRowsToBudget(projected,receipt,rows)||compacted;if(!compacted)return false;const lastId=contextIntentRowId(rows.at(-1));if(lastId===void 0){rows.splice(0,rows.length,...originalRows);updateContextIntentEstimate(projected,receipt);return false}projected.next_cursor=encodeQueryCursor(cursorEnvelope.fingerprint,lastId,cursorContinuesExistingPage?cursorEnvelope.after_index-(originalRowCount-rows.length):cursorEnvelope.after_index+rows.length,cursorEnvelope.snapshot);updateContextIntentEstimate(projected,receipt);if(receipt.estimated_tokens<=receipt.token_budget||rows.length<=1){break}}if(typeof projected.count==="number")projected.count=rows.length;if(typeof projected.applied_limit==="number"){projected.applied_limit=rows.length}return true}function compactContextIntentRows(command,projected,receipt,options){if(command==="list"||command==="search"){return compactPaginatedContextIntentRows(projected,receipt,options)}if(command!=="next"||typeof projected.next_cursor==="string"){return false}let compacted=false;for(;;){updateContextIntentEstimate(projected,receipt);if(receipt.estimated_tokens<=receipt.token_budget)return compacted;const candidate=CONTEXT_INTENT_ROW_KEYS[command].map(key=>({key,rows:Array.isArray(projected[key])?projected[key]:[]})).filter(({rows})=>rows.length>0).sort((left,right)=>right.rows.length-left.rows.length||left.key.localeCompare(right.key))[0];if(candidate===void 0)return compacted;const retainedTotal=CONTEXT_INTENT_ROW_KEYS[command].reduce((total,key)=>total+(Array.isArray(projected[key])?projected[key].length:0),0);if(retainedTotal<=1)return compacted;const removableRows=Math.min(candidate.rows.length,retainedTotal-1);const candidateBytes=Buffer.byteLength(JSON.stringify(candidate.rows),"utf8");const estimatedBytesPerRow=Math.max(1,Math.ceil(candidateBytes/candidate.rows.length));const excessBytes=(receipt.estimated_tokens-receipt.token_budget)*4;const removalCount=Math.min(removableRows,Math.max(1,Math.ceil(excessBytes/estimatedBytesPerRow)));candidate.rows.splice(-removalCount,removalCount);compacted=true}}function attachContextIntentReceipt(command,options,result){if(typeof options.for!=="string")return result;const normalizedCommand=command.startsWith("list-")?"list":command;if(!(normalizedCommand in CONTEXT_INTENT_DEFAULT_APPLIERS))return result;const builtInCommand=normalizedCommand;const contract=resolveContextIntentContract(builtInCommand,options.for);const effectiveTokenBudget=resolveIntentTokenBudget(options.tokenBudget??options.token_budget,contract.token_budget);const receipt={command:builtInCommand,intent:contract.intent,source:contract.source,included_field_groups:[...contract.included_field_groups],token_budget:effectiveTokenBudget,declared_token_budget:contract.token_budget,token_budget_override:effectiveTokenBudget-contract.token_budget,estimated_tokens:0,within_budget:true,degradation:CONTEXT_INTENT_DEGRADATIONS[builtInCommand],declaration_feasible:true,result_omitted:false};const resultWithDiagnostics={...result};const budgetDerivedLimit=resolveIntentRowBudget(builtInCommand,contract.intent,receipt.token_budget,parsePositiveIntentTokenBudget(options.tokenBudget??options.token_budget)!==void 0);if(budgetDerivedLimit!==void 0){const effectiveLimit=parsePositiveIntentTokenBudget(options.limit);const explicitLimitBinds=effectiveLimit!==void 0&&effectiveLimit<budgetDerivedLimit;receipt.budget_derived_limit=budgetDerivedLimit;receipt.binding_constraint=explicitLimitBinds?"explicit_limit":"token_budget";receipt.limit_reason=explicitLimitBinds?"The caller supplied a smaller row limit than the budget-derived ceiling.":"The selected intent token budget constrains the effective row ceiling.";resultWithDiagnostics.budget_derived_limit=budgetDerivedLimit}let projected={...resultWithDiagnostics,context_intent:receipt};updateContextIntentEstimate(projected,receipt);if(receipt.estimated_tokens>receipt.token_budget){receipt.degradation="recursive_budget_compaction";projected={...compactContextIntentValue(resultWithDiagnostics),context_intent:receipt};updateContextIntentEstimate(projected,receipt)}if(receipt.estimated_tokens>receipt.token_budget&&compactContextIntentRows(builtInCommand,projected,receipt,options)){receipt.degradation="budget_row_compaction";updateContextIntentEstimate(projected,receipt)}receipt.declaration_feasible=receipt.estimated_tokens<=receipt.declared_token_budget;if(receipt.estimated_tokens>receipt.token_budget){receipt.degradation="budget_receipt_only";receipt.result_omitted=true;receipt.within_budget=false;projected={budget_exceeded:{omitted_result:true,reason:receipt.token_budget_override===0?"declared_budget_infeasible":"effective_budget_infeasible",restore_with:buildContextIntentRecoveryCommand(command,builtInCommand,contract.intent,receipt,resultWithDiagnostics)},context_intent:receipt}}return projected}function collapseContinuationMetadata(options,result){if(typeof options.after!=="string"||options.after.length===0){return result}const fingerprint=decodeContextIntentCursor(options.after)?.fingerprint??"opaque_cursor";const projected={...result};for(const key of["applied_limit","completeness","context_intent","count","filters","has_more","now","omission_receipt","projection","row_contract","sorting","total","truncated"]){delete projected[key]}projected.continuation_contract={fingerprint,metadata:"reference",restore_with:"omit --after"};return projected}function isOutputRecord(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}function buildContextIntentRecoveryCommand(command,builtInCommand,intent,receipt,result){const recoveryTarget=builtInCommand==="get"&&isOutputRecord(result.item)&&typeof result.item.id==="string"?result.item.id:builtInCommand==="search"&&typeof result.query==="string"?result.query:void 0;const recoveryPositional=recoveryTarget===void 0?"":` '${recoveryTarget.replaceAll("'",`'"'"'`)}'`;const boundedRowLimit=builtInCommand==="get"?"":` --limit ${receipt.budget_derived_limit??1}`;return`pm ${command}${recoveryPositional} --for ${intent} --token-budget ${Math.ceil(receipt.estimated_tokens/100)*100}${boundedRowLimit}`}function receiptEstimate(value,field){if(!isOutputRecord(value))return void 0;return typeof value[field]==="number"?value[field]:void 0}function stabilizeSuppressedRowContractReceipts(result,options){let finalized=result;for(let iteration=0;iteration<8;iteration+=1){const previousContextEstimate=receiptEstimate(finalized.context_intent,"estimated_tokens");const previousReadEstimate=receiptEstimate(finalized.read_output,"estimated_tokens");const previousSessionEstimate=receiptEstimate(finalized.read_session,"spent_this_call_tokens");if(isOutputRecord(finalized.context_intent)){updateContextIntentEstimate(finalized,finalized.context_intent)}finalized=stabilizeReadOutputReceiptEstimates(finalized,options);if(receiptEstimate(finalized.context_intent,"estimated_tokens")===previousContextEstimate&&receiptEstimate(finalized.read_output,"estimated_tokens")===previousReadEstimate&&receiptEstimate(finalized.read_session,"spent_this_call_tokens")===previousSessionEstimate){break}}return finalized}function attachReadOutputContracts(command,options,result){const disclosedResult=attachOutputOmissionReceipt(command,result);const projected=typeof disclosedResult==="object"&&disclosedResult!==null&&!Array.isArray(disclosedResult)?applyReadOutputDimensions(command??"",options,collapseContinuationMetadata(options,attachContextIntentReceipt(command??"",options,disclosedResult))):disclosedResult;propagateContextUsageServingReceipt(result,projected);if(options.outputRowContract===true||options.output_row_contract===true||typeof projected!=="object"||projected===null||Array.isArray(projected)||!Object.hasOwn(projected,"row_contract")){return projected}const suppressed=stabilizeSuppressedRowContractReceipts(Object.fromEntries(Object.entries(projected).filter(([key])=>key!=="row_contract")),options);propagateContextUsageServingReceipt(projected,suppressed);return suppressed}export{PM_CONTEXT_INTENT_CONTRACTS,applyContextIntentProjection,attachContextIntentReceipt,attachReadOutputContracts,composeContextIntentContracts,contextIntentRowId,decodeContextIntentCursor,getActiveContextIntentContracts,resolveContextIntentContract,runWithContextIntentContracts};
1
+ !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="8bf25242-1b7a-501d-9540-7559cb97bcc6")}catch(e2){}})();import{AsyncLocalStorage}from"node:async_hooks";import{renderPmCommand}from"./command-line.js";import{attachOutputOmissionReceipt}from"./output-projection.js";import{encodeQueryCursor}from"./pagination.js";import{applyReadOutputDimensions,stabilizeReadOutputReceiptEstimates}from"./read-output-contracts.js";import{propagateContextUsageServingReceipt}from"./context-usage.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";const PM_CONTEXT_INTENT_CONTRACTS=Object.freeze([{command:"context",intent:"orient",description:"Bounded active hierarchy, ownership, blockers, and recent progress.",included_field_groups:["summary","focus","hierarchy","blockers","activity"],token_budget:3e3,source:"core"},{command:"context",intent:"handoff",description:"Active ownership, evidence, decisions, and immediate continuation context.",included_field_groups:["summary","focus","in_progress","decisions","activity"],token_budget:2200,source:"core"},{command:"get",intent:"inspect",description:"Standard-depth item metadata, relationships, evidence, and lifecycle state.",included_field_groups:["item","children","claim_state","linked"],token_budget:3200,source:"core"},{command:"list",intent:"triage",description:"A budget-derived page of compact governance, ownership, priority, and blocker rows for triage.",included_field_groups:["identity","governance","ownership","dependencies"],token_budget:3200,source:"core"},{command:"next",intent:"execute",description:"The highest-ranked actionable work with concise ranking evidence.",included_field_groups:["recommended"],token_budget:1200,source:"core"},{command:"search",intent:"discover",description:"A budget-derived page of ranked canonical lineage candidates with compact match evidence.",included_field_groups:["identity","status","lineage","match"],token_budget:1800,source:"core"}]);const activeContextIntentContracts=new AsyncLocalStorage;function getActiveContextIntentContracts(){return activeContextIntentContracts.getStore()??PM_CONTEXT_INTENT_CONTRACTS}function runWithContextIntentContracts(layers,run){return activeContextIntentContracts.run(composeContextIntentContracts(layers.workspaceContracts,layers.packageContracts),run)}function normalizeContextIntentDeclaration(declaration,source){const command=declaration.command.trim().toLowerCase();const intent=declaration.intent.trim().toLowerCase();const key=`${command}:${intent}`;if(!/^[a-z0-9][a-z0-9-]*$/.test(command)||!/^[a-z0-9][a-z0-9-]*$/.test(intent)){throw new TypeError(`Invalid context intent command or name: ${key}`)}if(declaration.description.trim().length===0){throw new TypeError(`Context intent ${key} requires a non-empty description`)}if(!Number.isSafeInteger(declaration.token_budget)||declaration.token_budget<=0){throw new TypeError(`Context intent ${key} requires a positive integer token_budget`)}const includedFieldGroups=[...new Set(declaration.included_field_groups.map(field=>field.trim()).filter(Boolean))];if(includedFieldGroups.length===0){throw new TypeError(`Context intent ${key} requires included_field_groups`)}return{command,intent,description:declaration.description.trim(),included_field_groups:includedFieldGroups,token_budget:declaration.token_budget,source}}function composeContextIntentContracts(workspaceContracts=[],packageContracts=[]){const layers=[{source:"core",contracts:PM_CONTEXT_INTENT_CONTRACTS,allowOverride:false},{source:"package",contracts:packageContracts,allowOverride:false},{source:"workspace",contracts:workspaceContracts,allowOverride:true}];const composed=new Map;const keysSeenWithinLayer=new Set;for(const layer of layers){keysSeenWithinLayer.clear();for(const declaration of layer.contracts){const normalized=normalizeContextIntentDeclaration(declaration,layer.source);const key=`${normalized.command}:${normalized.intent}`;if(keysSeenWithinLayer.has(key)){throw new TypeError(`Duplicate context intent declaration: ${key}`)}keysSeenWithinLayer.add(key);if(!layer.allowOverride&&composed.has(key)){throw new TypeError(`Duplicate context intent declaration: ${key}`)}composed.set(key,normalized)}}return[...composed.values()].sort((left,right)=>left.command.localeCompare(right.command)||left.intent.localeCompare(right.intent))}function resolveContextIntentContract(command,intent,contracts=getActiveContextIntentContracts(),positionalArguments=[]){const normalizedCommand=command.trim().toLowerCase();const normalizedIntent=intent.trim().toLowerCase();const exact=contracts.find(entry=>entry.command===normalizedCommand&&entry.intent===normalizedIntent);if(exact)return{...exact,source:exact.source??"core"};const candidates=contracts.filter(entry=>entry.command===normalizedCommand).map(entry=>entry.intent);if(candidates.length===0)return void 0;const suggestion=candidates.map(candidate=>{const rows=Array.from({length:normalizedIntent.length+1},(_,index)=>index);for(let candidateIndex=1;candidateIndex<=candidate.length;candidateIndex+=1){let previous=rows[0];rows[0]=candidateIndex;for(let intentIndex=1;intentIndex<=normalizedIntent.length;intentIndex+=1){const prior=rows[intentIndex];rows[intentIndex]=Math.min(rows[intentIndex]+1,rows[intentIndex-1]+1,previous+(candidate[candidateIndex-1]===normalizedIntent[intentIndex-1]?0:1));previous=prior}}return{candidate,distance:rows[normalizedIntent.length]}}).sort((left,right)=>left.distance-right.distance||left.candidate.localeCompare(right.candidate))[0].candidate;const attemptedArguments=[normalizedCommand,...positionalArguments,"--for",normalizedIntent];const suggestedRetryArguments=[normalizedCommand,...positionalArguments,"--for",suggestion];const suggestedCommand=renderPmCommand(suggestedRetryArguments);throw new PmCliError(`Unknown context intent "${normalizedIntent}" for ${normalizedCommand}. Did you mean "${suggestion}"?`,EXIT_CODE.USAGE,{code:"unknown_context_intent",reason:"unknown_intent",field:"for",flag:"--for",value:normalizedIntent,required:`Use a declared ${normalizedCommand} intent.`,why:"Intent names are command-local contracts and cannot be inferred from output section names.",nextSteps:[suggestedCommand],recovery:{recovery_mode:"compact",attempted_command:renderPmCommand(attemptedArguments),allowed_values:[...candidates].sort(),suggested_retry:suggestedCommand,suggested_retry_args:suggestedRetryArguments}})}const CONTEXT_INTENT_DEFAULT_APPLIERS={context:(projected,contract,explicitTokenBudget)=>{if(projected.depth===void 0){projected.depth=contract.intent==="handoff"?"deep":"standard"}if(projected.section===void 0){projected.section=contract.intent==="handoff"?["activity","progress","blockers"]:["hierarchy","blockers","activity"]}const tokenBudget=resolveIntentTokenBudget(projected.tokenBudget,contract.token_budget);const budgetDerivedLimit=resolveIntentRowBudget("context",contract.intent,tokenBudget,explicitTokenBudget);const requestedLimit=parsePositiveIntentTokenBudget(projected.limit);const derivedLimit=String(requestedLimit===void 0?budgetDerivedLimit:Math.min(requestedLimit,budgetDerivedLimit));if(projected.limit===void 0||requestedLimit!==void 0){projected.limit=derivedLimit}if(projected.activityLimit===void 0){projected.activityLimit=derivedLimit}},get:projected=>{if(projected.depth===void 0&&projected.fields===void 0){projected.depth="standard"}},list:(projected,contract,explicitTokenBudget)=>{if(projected.brief===void 0&&projected.compact===void 0&&projected.full===void 0&&projected.fields===void 0){projected.fields="id,title,status,type,priority,parent,assignee,risk,blocked_by"}const tokenBudget=resolveIntentTokenBudget(projected.tokenBudget,contract.token_budget);const budgetDerivedLimit=resolveIntentRowBudget("list",contract.intent,tokenBudget,explicitTokenBudget);const requestedLimit=parsePositiveIntentTokenBudget(projected.limit);if(projected.limit===void 0||requestedLimit!==void 0){projected.limit=String(requestedLimit===void 0?budgetDerivedLimit:Math.min(requestedLimit,budgetDerivedLimit))}},next:projected=>{if(projected.readyOnly===void 0)projected.readyOnly=true},search:(projected,contract,explicitTokenBudget)=>{if(projected.compact===void 0&&projected.full===void 0&&projected.fields===void 0){projected.compact=true}const tokenBudget=resolveIntentTokenBudget(projected.tokenBudget,contract.token_budget);const budgetDerivedLimit=resolveIntentRowBudget("search",contract.intent,tokenBudget,explicitTokenBudget);const requestedLimit=parsePositiveIntentTokenBudget(projected.limit);if(projected.limit===void 0||requestedLimit!==void 0){projected.limit=String(requestedLimit===void 0?budgetDerivedLimit:Math.min(requestedLimit,budgetDerivedLimit))}}};function applyContextIntentProjection(command,options,positionalArguments=[]){const tokenBudget=options.tokenBudget??options.token_budget;if(typeof options.for!=="string"){if(tokenBudget!==void 0&&(command==="get"||command==="list"||command==="search")){throw new PmCliError("--token-budget requires a declared context intent selected with --for",EXIT_CODE.USAGE,{code:"missing_required_option",field:"for",required:"Select a context intent with --for when setting --token-budget.",why:"A token-budget override has no projection contract to constrain without a selected intent.",nextSteps:["Retry with --for <intent> --token-budget <n>, or omit --token-budget."]})}if(options.tokenBudget!==void 0||options.token_budget===void 0){return options}const projected2={...options,tokenBudget};delete projected2.token_budget;return projected2}const contract=resolveContextIntentContract(command,options.for,void 0,positionalArguments);const explicitTokenBudget=parsePositiveIntentTokenBudget(tokenBudget)!==void 0;const projected={...options};if(projected.tokenBudget===void 0&&tokenBudget!==void 0){projected.tokenBudget=tokenBudget}delete projected.token_budget;if(projected.tokenBudget===void 0){projected.tokenBudget=String(contract.token_budget)}CONTEXT_INTENT_DEFAULT_APPLIERS[command](projected,contract,explicitTokenBudget);return projected}const CONTEXT_INTENT_DEGRADATIONS={context:"bounded_sections",get:"standard_item",list:"bounded_fields_and_rows",next:"bounded_ranked_rows",search:"bounded_ranked_rows"};const MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET=256;function compactContextIntentValue(value){if(Array.isArray(value)){return value.map(compactContextIntentValue)}if(value!==null&&typeof value==="object"){return Object.fromEntries(Object.entries(value).map(([key,entry])=>[key,compactContextIntentValue(entry)]))}return typeof value==="string"&&value.length>240?`${value.slice(0,240)}\u2026`:value}function parsePositiveIntentTokenBudget(value){const parsed=typeof value==="number"?value:typeof value==="string"&&/^\d+$/u.test(value.trim())?Number(value):Number.NaN;return Number.isSafeInteger(parsed)&&parsed>0?parsed:void 0}function resolveIntentTokenBudget(value,declaredBudget){const parsed=parsePositiveIntentTokenBudget(value);if(parsed===void 0)return declaredBudget;if(parsed<MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET){throw new PmCliError(`Context intent token budget must be at least ${MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET}`,EXIT_CODE.USAGE,{code:"invalid_argument_value",reason:"below_minimum",field:"tokenBudget",required:`Use an integer token budget of at least ${MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET}.`,why:"Smaller ceilings cannot contain the minimum machine-readable intent receipt.",nextSteps:[`Retry with --token-budget ${MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET} or omit the override.`]})}return parsed}function resolveIntentRowBudget(command,intent,tokenBudget,explicitTokenBudget){if(command==="get"||command==="next")return void 0;const contextOrient=command==="context"&&intent==="orient";const overhead=command==="context"?contextOrient?1200:800:command==="list"?520:480;const rowCost=command==="context"?contextOrient?600:500:16;const calculatedLimit=Math.max(command==="context"?1:2,Math.floor((tokenBudget-overhead)/rowCost));return explicitTokenBudget?calculatedLimit:Math.min(command==="context"?20:100,calculatedLimit)}function updateContextIntentEstimate(projected,receipt){let measuredTokens=receipt.estimated_tokens;for(;;){receipt.estimated_tokens=measuredTokens;const nextMeasurement=Math.ceil(Buffer.byteLength(JSON.stringify(projected),"utf8")/4);if(nextMeasurement===measuredTokens)return;measuredTokens=nextMeasurement}}const CONTEXT_INTENT_ROW_KEYS={context:["high_level","low_level","blocked_fallback","recently_created","unparented","hierarchy","activity","blockers"],get:["children"],list:["items"],next:["ready","decision_needed","gate_needed","containers","blocked","held_by_others"],search:["items"]};function decodeContextIntentCursor(cursor){try{const parsed=JSON.parse(Buffer.from(cursor,"base64url").toString("utf8"));if(typeof parsed.fingerprint!=="string"||!Number.isSafeInteger(parsed.after_index)){return void 0}return{fingerprint:parsed.fingerprint,after_index:parsed.after_index,...typeof parsed.snapshot==="string"?{snapshot:parsed.snapshot}:{}}}catch{return void 0}}function contextIntentRowId(row){if(row===null||typeof row!=="object")return void 0;if(typeof row.id==="string"){return row.id}const nestedId=row.item?.id;return typeof nestedId==="string"?nestedId:void 0}function shrinkContextIntentRowsToBudget(projected,receipt,rows){let compacted=false;for(;;){updateContextIntentEstimate(projected,receipt);if(receipt.estimated_tokens<=receipt.token_budget||rows.length<=1){return compacted}const rowBytes=Buffer.byteLength(JSON.stringify(rows),"utf8");const excessBytes=(receipt.estimated_tokens-receipt.token_budget)*4;rows.splice(-Math.min(rows.length-1,Math.max(1,Math.ceil(excessBytes/Math.max(1,Math.ceil(rowBytes/rows.length))))));compacted=true}}function compactPaginatedContextIntentRows(projected,receipt,options){const rows=projected.items;const cursorContinuesExistingPage=typeof projected.next_cursor==="string";const cursorSource=cursorContinuesExistingPage?projected.next_cursor:options.after;if(!Array.isArray(rows)||typeof cursorSource!=="string")return false;const cursorEnvelope=decodeContextIntentCursor(cursorSource);if(cursorEnvelope===void 0)return false;const originalRowCount=rows.length;const originalRows=[...rows];let compacted=false;for(;;){compacted=shrinkContextIntentRowsToBudget(projected,receipt,rows)||compacted;if(!compacted)return false;const lastId=contextIntentRowId(rows.at(-1));if(lastId===void 0){rows.splice(0,rows.length,...originalRows);updateContextIntentEstimate(projected,receipt);return false}projected.next_cursor=encodeQueryCursor(cursorEnvelope.fingerprint,lastId,cursorContinuesExistingPage?cursorEnvelope.after_index-(originalRowCount-rows.length):cursorEnvelope.after_index+rows.length,cursorEnvelope.snapshot);updateContextIntentEstimate(projected,receipt);if(receipt.estimated_tokens<=receipt.token_budget||rows.length<=1){break}}if(typeof projected.count==="number")projected.count=rows.length;if(typeof projected.applied_limit==="number"){projected.applied_limit=rows.length}return true}function compactContextIntentRows(command,projected,receipt,options){if(command==="list"||command==="search"){return compactPaginatedContextIntentRows(projected,receipt,options)}if(command!=="next"||typeof projected.next_cursor==="string"){return false}let compacted=false;for(;;){updateContextIntentEstimate(projected,receipt);if(receipt.estimated_tokens<=receipt.token_budget)return compacted;const candidate=CONTEXT_INTENT_ROW_KEYS[command].map(key=>({key,rows:Array.isArray(projected[key])?projected[key]:[]})).filter(({rows})=>rows.length>0).sort((left,right)=>right.rows.length-left.rows.length||left.key.localeCompare(right.key))[0];if(candidate===void 0)return compacted;const retainedTotal=CONTEXT_INTENT_ROW_KEYS[command].reduce((total,key)=>total+(Array.isArray(projected[key])?projected[key].length:0),0);if(retainedTotal<=1)return compacted;const removableRows=Math.min(candidate.rows.length,retainedTotal-1);const candidateBytes=Buffer.byteLength(JSON.stringify(candidate.rows),"utf8");const estimatedBytesPerRow=Math.max(1,Math.ceil(candidateBytes/candidate.rows.length));const excessBytes=(receipt.estimated_tokens-receipt.token_budget)*4;const removalCount=Math.min(removableRows,Math.max(1,Math.ceil(excessBytes/estimatedBytesPerRow)));candidate.rows.splice(-removalCount,removalCount);compacted=true}}function attachContextIntentReceipt(command,options,result){if(typeof options.for!=="string")return result;const normalizedCommand=command.startsWith("list-")?"list":command;if(!(normalizedCommand in CONTEXT_INTENT_DEFAULT_APPLIERS))return result;const builtInCommand=normalizedCommand;const contract=resolveContextIntentContract(builtInCommand,options.for);const effectiveTokenBudget=resolveIntentTokenBudget(options.tokenBudget??options.token_budget,contract.token_budget);const receipt={command:builtInCommand,intent:contract.intent,source:contract.source,included_field_groups:[...contract.included_field_groups],token_budget:effectiveTokenBudget,declared_token_budget:contract.token_budget,token_budget_override:effectiveTokenBudget-contract.token_budget,estimated_tokens:0,within_budget:true,degradation:CONTEXT_INTENT_DEGRADATIONS[builtInCommand],declaration_feasible:true,result_omitted:false};const resultWithDiagnostics={...result};const budgetDerivedLimit=resolveIntentRowBudget(builtInCommand,contract.intent,receipt.token_budget,parsePositiveIntentTokenBudget(options.tokenBudget??options.token_budget)!==void 0);if(budgetDerivedLimit!==void 0){const effectiveLimit=parsePositiveIntentTokenBudget(options.limit);const explicitLimitBinds=effectiveLimit!==void 0&&effectiveLimit<budgetDerivedLimit;receipt.budget_derived_limit=budgetDerivedLimit;receipt.binding_constraint=explicitLimitBinds?"explicit_limit":"token_budget";receipt.limit_reason=explicitLimitBinds?"The caller supplied a smaller row limit than the budget-derived ceiling.":"The selected intent token budget constrains the effective row ceiling.";resultWithDiagnostics.budget_derived_limit=budgetDerivedLimit}let projected={...resultWithDiagnostics,context_intent:receipt};updateContextIntentEstimate(projected,receipt);if(receipt.estimated_tokens>receipt.token_budget){receipt.degradation="recursive_budget_compaction";projected={...compactContextIntentValue(resultWithDiagnostics),context_intent:receipt};updateContextIntentEstimate(projected,receipt)}if(receipt.estimated_tokens>receipt.token_budget&&compactContextIntentRows(builtInCommand,projected,receipt,options)){receipt.degradation="budget_row_compaction";updateContextIntentEstimate(projected,receipt)}receipt.declaration_feasible=receipt.estimated_tokens<=receipt.declared_token_budget;if(receipt.estimated_tokens>receipt.token_budget){receipt.degradation="budget_receipt_only";receipt.result_omitted=true;receipt.within_budget=false;projected={budget_exceeded:{omitted_result:true,reason:receipt.token_budget_override===0?"declared_budget_infeasible":"effective_budget_infeasible",restore_with:buildContextIntentRecoveryCommand(command,builtInCommand,contract.intent,receipt,resultWithDiagnostics)},context_intent:receipt}}return projected}function collapseContinuationMetadata(options,result){if(typeof options.after!=="string"||options.after.length===0){return result}const fingerprint=decodeContextIntentCursor(options.after)?.fingerprint??"opaque_cursor";const projected={...result};for(const key of["applied_limit","completeness","context_intent","count","filters","has_more","now","omission_receipt","projection","row_contract","sorting","total","truncated"]){delete projected[key]}projected.continuation_contract={fingerprint,metadata:"reference",restore_with:"omit --after"};return projected}function isOutputRecord(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}function buildContextIntentRecoveryCommand(command,builtInCommand,intent,receipt,result){const recoveryTarget=builtInCommand==="get"&&isOutputRecord(result.item)&&typeof result.item.id==="string"?result.item.id:builtInCommand==="search"&&typeof result.query==="string"?result.query:void 0;const recoveryPositional=recoveryTarget===void 0?"":` '${recoveryTarget.replaceAll("'",`'"'"'`)}'`;const boundedRowLimit=builtInCommand==="get"?"":` --limit ${receipt.budget_derived_limit??1}`;return`pm ${command}${recoveryPositional} --for ${intent} --token-budget ${Math.ceil(receipt.estimated_tokens/100)*100}${boundedRowLimit}`}function receiptEstimate(value,field){if(!isOutputRecord(value))return void 0;return typeof value[field]==="number"?value[field]:void 0}function stabilizeSuppressedRowContractReceipts(result,options){let finalized=result;for(let iteration=0;iteration<8;iteration+=1){const previousContextEstimate=receiptEstimate(finalized.context_intent,"estimated_tokens");const previousReadEstimate=receiptEstimate(finalized.read_output,"estimated_tokens");const previousSessionEstimate=receiptEstimate(finalized.read_session,"spent_this_call_tokens");if(isOutputRecord(finalized.context_intent)){updateContextIntentEstimate(finalized,finalized.context_intent)}finalized=stabilizeReadOutputReceiptEstimates(finalized,options);if(receiptEstimate(finalized.context_intent,"estimated_tokens")===previousContextEstimate&&receiptEstimate(finalized.read_output,"estimated_tokens")===previousReadEstimate&&receiptEstimate(finalized.read_session,"spent_this_call_tokens")===previousSessionEstimate){break}}return finalized}function attachReadOutputContracts(command,options,result){const disclosedResult=attachOutputOmissionReceipt(command,result);const projected=typeof disclosedResult==="object"&&disclosedResult!==null&&!Array.isArray(disclosedResult)?applyReadOutputDimensions(command??"",{...options,outputRowContract:options.outputRowContract===true||options.output_row_contract===true},collapseContinuationMetadata(options,attachContextIntentReceipt(command??"",options,disclosedResult))):disclosedResult;propagateContextUsageServingReceipt(result,projected);if(options.outputRowContract===true||options.output_row_contract===true||typeof projected!=="object"||projected===null||Array.isArray(projected)||!Object.hasOwn(projected,"row_contract")){return projected}const withoutDiscoveryMetadata=Object.fromEntries(Object.entries(projected).filter(([key])=>key!=="row_contract"));Object.defineProperty(withoutDiscoveryMetadata,"row_contract",{value:projected.row_contract,enumerable:false,configurable:true});const suppressed=stabilizeSuppressedRowContractReceipts(withoutDiscoveryMetadata,options);delete suppressed.row_contract;propagateContextUsageServingReceipt(projected,suppressed);return suppressed}export{PM_CONTEXT_INTENT_CONTRACTS,applyContextIntentProjection,attachContextIntentReceipt,attachReadOutputContracts,composeContextIntentContracts,contextIntentRowId,decodeContextIntentCursor,getActiveContextIntentContracts,resolveContextIntentContract,runWithContextIntentContracts};
2
2
  //# sourceMappingURL=context-intent-contracts.js.map
@@ -1,2 +1,2 @@
1
- !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="dffb5f26-d8b4-5861-a7ea-0436bd4a22a6")}catch(e2){}})();import{runActiveServiceOverride}from"../core/extensions/index.js";import{normalizeStatusForRegistry,normalizeStatusInput}from"../core/item/status.js";import{compareTimestampStrings}from"../core/shared/time.js";import{canonicalizeContextRecencyCoordinate,CONTEXT_RECENCY_EPOCH}from"./context/recency.js";const CONTEXT_RELEVANCE_SIGNAL_NAMES=["structural","recency","activity_density","graph_proximity","claim_focus","priority_pressure","risk_pressure","deadline_pressure","knowledge_density","author_affinity","usage_affinity","semantic_similarity"];const NO_CONTEXT_AUTHOR=Symbol("no-context-author");const NO_ITEM_ASSIGNEE=Symbol("no-item-assignee");function normalizeContextActor(value,missingValue){if(typeof value!=="string")return missingValue;const normalized=value.trim().toLowerCase();return normalized.length>0?normalized:missingValue}function releaseCohortCoordinate(value){if(typeof value!=="string")return void 0;const match=/^v?(\d{4})\.(\d{1,2})\.(\d{1,2})(?:$|[-+])/u.exec(value.trim());if(!match)return void 0;const year=Number(match[1]);const month=Number(match[2]);const day=Number(match[3]);const date=new Date(Date.UTC(year,month-1,day));return date.getUTCFullYear()===year&&date.getUTCMonth()===month-1&&date.getUTCDate()===day?date.toISOString():void 0}function fallbackRecencyEvidence(item){const releaseCoordinate=releaseCohortCoordinate(item.release);if(releaseCoordinate!==void 0){return{source:"release_cohort",coordinate:releaseCoordinate}}return{source:"created_at",coordinate:canonicalizeContextRecencyCoordinate(item.created_at)??CONTEXT_RECENCY_EPOCH}}function canonicalizeRecencyEvidence(evidence){if(!["substantive_history","release_cohort","created_at"].includes(evidence.source)||(evidence.source==="substantive_history"?evidence.history_op!==void 0&&typeof evidence.history_op!=="string"||evidence.event_class!==void 0&&evidence.event_class!=="substantive":evidence.history_op!==void 0||evidence.event_class!==void 0)){throw new TypeError("Context signal recency provenance must match its source")}const coordinate=canonicalizeContextRecencyCoordinate(evidence.coordinate);if(coordinate===null){throw new TypeError("Context signal recency coordinate must be a valid absolute timestamp with millisecond precision")}return{...evidence,coordinate}}function normalizedPressure(value,maximum){const parsed=typeof value==="number"?value:typeof value==="string"?Number.parseFloat(value):Number.NaN;return Number.isFinite(parsed)?1-Math.min(Math.max(parsed,0),maximum)/maximum:0}function deadlinePressure(deadline,nowMs){const deadlineMs=typeof deadline==="string"?Date.parse(deadline):deadline instanceof Date?deadline.getTime():typeof deadline==="number"?deadline:Number.NaN;if(!Number.isFinite(deadlineMs)||!Number.isFinite(nowMs))return 0;const days=(deadlineMs-nowMs)/864e5;return days<=0?1:1/(1+days/30)}function riskPressure(risk){const normalized=typeof risk==="string"?risk.trim().toLowerCase():void 0;if(normalized==="critical"||normalized==="high")return 1;if(normalized==="medium")return .5;return normalized==="low"?.1:0}function derivedSignalOrFallback(values,id,fallback){return values?.[id]??fallback}function buildItemContextRelevanceCandidates(items,options){const recencyEvidence=new Map(items.map(item=>{const suppliedEvidence=options.recencyEvidence?.[item.id];return[item.id,suppliedEvidence===void 0?fallbackRecencyEvidence(item):canonicalizeRecencyEvidence(suppliedEvidence)]}));const recencyOrder=[...items].sort((left,right)=>{const leftTime=recencyEvidence.get(left.id).coordinate;const rightTime=recencyEvidence.get(right.id).coordinate;return compareTimestampStrings(rightTime,leftTime)||left.id.localeCompare(right.id)});const recencyRank=new Map(recencyOrder.map((item,index)=>[item.id,index]));const denominator=Math.max(items.length-1,1);const normalizedAuthor=normalizeContextActor(options.author,NO_CONTEXT_AUTHOR);const inProgressStatus=normalizeStatusInput("in_progress",options.statusRegistry);const nowMs=Date.parse(options.now);return items.map(item=>{const assigned=normalizeContextActor(item.assignee,NO_ITEM_ASSIGNEE)===normalizedAuthor;const knowledgeEntries=(item.comments?.length??0)+(item.notes?.length??0)+(item.learnings?.length??0);return{id:item.id,item,signal_provenance:{recency:recencyEvidence.get(item.id)},signals:{recency:items.length===1?1:1-recencyRank.get(item.id)/denominator,activity_density:options.activityDensity?.[item.id],graph_proximity:derivedSignalOrFallback(options.graphProximity,item.id,item.parent?.3:0),claim_focus:derivedSignalOrFallback(options.claimFocus,item.id,normalizeStatusForRegistry(item.status,options.statusRegistry)===inProgressStatus?1:assigned?.75:0),priority_pressure:normalizedPressure(item.priority,4),risk_pressure:riskPressure(item.risk),deadline_pressure:deadlinePressure(item.deadline,nowMs),knowledge_density:derivedSignalOrFallback(options.knowledgeDensity,item.id,Math.min(knowledgeEntries/5,1)),author_affinity:derivedSignalOrFallback(options.authorAffinity,item.id,assigned?1:0),usage_affinity:options.usageAffinity?.[item.id],semantic_similarity:options.semanticSimilarity?.[item.id]}}})}const CONTEXT_RELEVANCE_SERVICE="context_relevance";const DEFAULT_CONTEXT_RELEVANCE_WEIGHTS={structural:.4,recency:.35,activity_density:.25,graph_proximity:.15,claim_focus:.6,priority_pressure:.35,risk_pressure:.2,deadline_pressure:.45,knowledge_density:.25,author_affinity:.2,usage_affinity:.3,semantic_similarity:.5};const JSON_TOKEN_ENCODER=new TextEncoder;function assertCandidates(candidates){const ids=new Set;for(const candidate of candidates){if(typeof candidate.id!=="string"||candidate.id.trim().length===0||ids.has(candidate.id)){throw new TypeError("Context relevance candidates require unique non-empty ids")}ids.add(candidate.id);for(const[signal,value]of Object.entries(candidate.signals??{})){if(signal==="structural"||!CONTEXT_RELEVANCE_SIGNAL_NAMES.includes(signal)){throw new TypeError(`Unknown context relevance signal: ${signal}`)}if(value===void 0)continue;if(!Number.isFinite(value)||value<0||value>1){throw new TypeError(`Context relevance signal ${signal} must be a finite number from 0 to 1`)}}}}function resolveWeights(overrides){const weights={...DEFAULT_CONTEXT_RELEVANCE_WEIGHTS};for(const[signal,weight]of Object.entries(overrides??{})){if(weight!==void 0&&CONTEXT_RELEVANCE_SIGNAL_NAMES.includes(signal)){weights[signal]=weight}}for(const[signal,weight]of Object.entries(weights)){if(!Number.isFinite(weight)||weight<0){throw new TypeError(`Context relevance weight ${signal} must be a finite non-negative number`)}}return weights}function defaultScoreContextCandidates(candidates,options={}){assertCandidates(candidates);const weights=resolveWeights(options.weights);const denominator=Math.max(candidates.length-1,1);const available=new Set(["structural"]);for(const candidate of candidates){for(const[signal,value]of Object.entries(candidate.signals??{})){if(value!==void 0)available.add(signal)}}const availableSignals=CONTEXT_RELEVANCE_SIGNAL_NAMES.filter(signal=>available.has(signal));const scored=candidates.map((candidate,index)=>{const signalValues={structural:candidates.length===1?1:1-index/denominator,...candidate.signals};const contributions={};let weightedScore=0;let totalWeight=0;for(const signal of availableSignals){const value=signalValues[signal];if(value===void 0)continue;const contribution=value*weights[signal];contributions[signal]=contribution;weightedScore+=contribution;totalWeight+=weights[signal]}return{...candidate,baseline_rank:index+1,rank:0,score:totalWeight===0?0:weightedScore/totalWeight,contributions}});scored.sort((left,right)=>right.score-left.score||left.baseline_rank-right.baseline_rank);scored.forEach((entry,index)=>{entry.rank=index+1});return{model:"default-weighted-v1",available_signals:availableSignals,ranked:scored}}async function scoreContextCandidates(candidates,options={}){const defaultReport=defaultScoreContextCandidates(candidates,options);if(!options.scorer)return defaultReport;const customScores=await options.scorer({candidates,default_report:defaultReport});const scoreById=new Map;for(const entry of customScores){if(scoreById.has(entry.id)||!Number.isFinite(entry.score)){throw new TypeError("Context relevance scorer must return one finite score for every candidate")}scoreById.set(entry.id,entry.score)}if(scoreById.size!==candidates.length||candidates.some(candidate=>!scoreById.has(candidate.id))){throw new TypeError("Context relevance scorer must return one finite score for every candidate")}const ranked=defaultReport.ranked.map(entry=>{const score=scoreById.get(entry.id);return{...entry,score,contributions:{custom:score}}});ranked.sort((left,right)=>right.score-left.score||left.baseline_rank-right.baseline_rank);ranked.forEach((entry,index)=>{entry.rank=index+1});return{model:"custom",available_signals:defaultReport.available_signals,ranked}}async function scoreContextCandidatesWithActiveExtensions(surface,candidates,options={}){const defaultReport=defaultScoreContextCandidates(candidates,options);const override=await runActiveServiceOverride(CONTEXT_RELEVANCE_SERVICE,{surface,candidates,default_report:defaultReport});if(!override.handled){return override.warnings.length>0?{...defaultReport,warnings:override.warnings}:defaultReport}if(!Array.isArray(override.result)||!override.result.every(entry=>typeof entry==="object"&&entry!==null&&typeof entry.id==="string"&&typeof entry.score==="number"&&Number.isFinite(entry.score))){return{...defaultReport,warnings:[...override.warnings,"extension_context_relevance_invalid_result"]}}try{const report=await scoreContextCandidates(candidates,{...options,scorer:()=>override.result});return override.warnings.length>0?{...report,warnings:override.warnings}:report}catch{return{...defaultReport,warnings:[...override.warnings,"extension_context_relevance_invalid_result"]}}}const CONTEXT_EVALUATION_METRIC_NAMES=["ndcg","reciprocal_rank","required_recall","continuity_coverage","token_budget_adherence"];function ratioOfPresent(expected,actual){if(expected.length===0)return 1;return expected.filter(id=>actual.has(id)).length/expected.length}function evaluateContextRanking(input){if(!Number.isFinite(input.actual_tokens)||input.actual_tokens<0||!Number.isFinite(input.token_budget)||input.token_budget<=0){throw new TypeError("Context ranking token counts require actual_tokens >= 0 and token_budget > 0")}const judgments=input.judgments??{};const gains=input.ranked_ids.map(id=>Math.max(0,judgments[id]??0));const idealGains=Object.values(judgments).map(grade=>Math.max(0,grade)).sort((left,right)=>right-left).slice(0,gains.length||1);const discountedGain=values=>values.reduce((total,grade,index)=>total+(2**grade-1)/Math.log2(index+2),0);const ideal=discountedGain(idealGains);const firstRelevant=gains.findIndex(grade=>grade>0);const actualIds=new Set(input.ranked_ids);const withinBudget=input.actual_tokens<=input.token_budget;return{ndcg:ideal===0?1:discountedGain(gains)/ideal,reciprocal_rank:firstRelevant<0?0:1/(firstRelevant+1),required_recall:ratioOfPresent(input.required_ids??[],actualIds),continuity_coverage:ratioOfPresent(input.continuity_ids??[],actualIds),token_budget_adherence:withinBudget?1:input.token_budget/input.actual_tokens,within_token_budget:withinBudget}}function estimateJsonTokens(value){return Math.ceil(JSON_TOKEN_ENCODER.encode(JSON.stringify(value)).byteLength/4)}function roundEvaluationMetric(value){return Math.round(value*1e4)/1e4}function rankingPayloadForScenario(result,surface){const rankedIds=surface==="context"?[...result.high_level??[],...result.low_level??[],...result.blocked_fallback??[]].map(item=>item.id):[...result.recommended?[result.recommended]:[],...result.ready??[]].map(item=>item.id);const servedIds=new Set(rankedIds);const attribution=(result.ranking?.items??[]).filter(item=>servedIds.has(item.id)).map(item=>({id:item.id,contributions:item.contributions}));return{rankedIds,attribution}}async function runContextEvaluationScenario(scenario,reader){if(scenario.id.trim().length===0||scenario.rationale.trim().length===0){throw new TypeError("Context evaluation scenarios require non-empty id and rationale values")}const result=scenario.surface==="context"?await reader.context({...scenario.options,explainRanking:true,outputBudget:"unbounded"}):await reader.next({...scenario.options,explainRanking:true,outputBudget:"unbounded"});const{rankedIds,attribution}=rankingPayloadForScenario(result,scenario.surface);const packet={...result,ranking:void 0};const actualTokens=estimateJsonTokens(packet);return{id:scenario.id,surface:scenario.surface,rationale:scenario.rationale,ranked_ids:rankedIds,actual_tokens:actualTokens,metrics:evaluateContextRanking({ranked_ids:rankedIds,judgments:scenario.judgments,required_ids:scenario.required_ids,continuity_ids:scenario.continuity_ids,actual_tokens:actualTokens,token_budget:scenario.token_budget}),attribution}}function summarizeContextEvaluationReports(reports,thresholds){if(reports.length===0){throw new TypeError("Context evaluation requires at least one scenario report")}const metrics=CONTEXT_EVALUATION_METRIC_NAMES;for(const metric of metrics){if(!Number.isFinite(thresholds[metric])){throw new TypeError(`Context evaluation threshold ${metric} must be a finite number`)}}const aggregate=Object.fromEntries(metrics.map(metric=>[metric,roundEvaluationMetric(reports.reduce((total,report)=>total+report.metrics[metric],0)/reports.length)]));const failures=metrics.filter(metric=>aggregate[metric]<thresholds[metric]).map(metric=>`${metric}:${aggregate[metric]}<${thresholds[metric]}`);return{scenario_count:reports.length,aggregate,scenarios:[...reports],passed:failures.length===0,failures}}async function runContextEvaluationCorpus(scenarios,reader,thresholds){const reports=[];for(const scenario of scenarios){reports.push(await runContextEvaluationScenario(scenario,reader))}return summarizeContextEvaluationReports(reports,thresholds)}export{CONTEXT_EVALUATION_METRIC_NAMES,CONTEXT_RELEVANCE_SERVICE,CONTEXT_RELEVANCE_SIGNAL_NAMES,buildItemContextRelevanceCandidates,defaultScoreContextCandidates,evaluateContextRanking,runContextEvaluationCorpus,runContextEvaluationScenario,scoreContextCandidates,scoreContextCandidatesWithActiveExtensions,summarizeContextEvaluationReports};
1
+ !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="33841a67-2bd5-5cbd-a9d4-14833ddcf9d2")}catch(e2){}})();import{runActiveServiceOverride}from"../core/extensions/index.js";import{normalizeStatusForRegistry,normalizeStatusInput}from"../core/item/status.js";import{compareTimestampStrings}from"../core/shared/time.js";import{canonicalizeContextRecencyCoordinate,CONTEXT_RECENCY_EPOCH}from"./context/recency.js";const CONTEXT_RELEVANCE_SIGNAL_NAMES=["structural","recency","activity_density","graph_proximity","claim_focus","priority_pressure","risk_pressure","deadline_pressure","knowledge_density","author_affinity","usage_affinity","semantic_similarity"];const NO_CONTEXT_AUTHOR=Symbol("no-context-author");const NO_ITEM_ASSIGNEE=Symbol("no-item-assignee");function normalizeContextActor(value,missingValue){if(typeof value!=="string")return missingValue;const normalized=value.trim().toLowerCase();return normalized.length>0?normalized:missingValue}function releaseCohortCoordinate(value){if(typeof value!=="string")return void 0;const match=/^v?(\d{4})\.(\d{1,2})\.(\d{1,2})(?:$|[-+])/u.exec(value.trim());if(!match)return void 0;const year=Number(match[1]);const month=Number(match[2]);const day=Number(match[3]);const date=new Date(Date.UTC(year,month-1,day));return date.getUTCFullYear()===year&&date.getUTCMonth()===month-1&&date.getUTCDate()===day?date.toISOString():void 0}function fallbackRecencyEvidence(item){const releaseCoordinate=releaseCohortCoordinate(item.release);if(releaseCoordinate!==void 0){return{source:"release_cohort",coordinate:releaseCoordinate}}return{source:"created_at",coordinate:canonicalizeContextRecencyCoordinate(item.created_at)??CONTEXT_RECENCY_EPOCH}}function canonicalizeRecencyEvidence(evidence){if(!["substantive_history","release_cohort","created_at"].includes(evidence.source)||(evidence.source==="substantive_history"?evidence.history_op!==void 0&&typeof evidence.history_op!=="string"||evidence.event_class!==void 0&&evidence.event_class!=="substantive":evidence.history_op!==void 0||evidence.event_class!==void 0)){throw new TypeError("Context signal recency provenance must match its source")}const coordinate=canonicalizeContextRecencyCoordinate(evidence.coordinate);if(coordinate===null){throw new TypeError("Context signal recency coordinate must be a valid absolute timestamp with millisecond precision")}return{...evidence,coordinate}}function normalizedPressure(value,maximum){const parsed=typeof value==="number"?value:typeof value==="string"?Number.parseFloat(value):Number.NaN;return Number.isFinite(parsed)?1-Math.min(Math.max(parsed,0),maximum)/maximum:0}function deadlinePressure(deadline,nowMs){const deadlineMs=typeof deadline==="string"?Date.parse(deadline):deadline instanceof Date?deadline.getTime():typeof deadline==="number"?deadline:Number.NaN;if(!Number.isFinite(deadlineMs)||!Number.isFinite(nowMs))return 0;const days=(deadlineMs-nowMs)/864e5;return days<=0?1:1/(1+days/30)}function riskPressure(risk){const normalized=typeof risk==="string"?risk.trim().toLowerCase():void 0;if(normalized==="critical"||normalized==="high")return 1;if(normalized==="medium")return .5;return normalized==="low"?.1:0}function derivedSignalOrFallback(values,id,fallback){return values?.[id]??fallback}function buildItemContextRelevanceCandidates(items,options){const recencyEvidence=new Map(items.map(item=>{const suppliedEvidence=options.recencyEvidence?.[item.id];return[item.id,suppliedEvidence===void 0?fallbackRecencyEvidence(item):canonicalizeRecencyEvidence(suppliedEvidence)]}));const recencyOrder=[...items].sort((left,right)=>{const leftTime=recencyEvidence.get(left.id).coordinate;const rightTime=recencyEvidence.get(right.id).coordinate;return compareTimestampStrings(rightTime,leftTime)||left.id.localeCompare(right.id)});const recencyRank=new Map(recencyOrder.map((item,index)=>[item.id,index]));const denominator=Math.max(items.length-1,1);const normalizedAuthor=normalizeContextActor(options.author,NO_CONTEXT_AUTHOR);const inProgressStatus=normalizeStatusInput("in_progress",options.statusRegistry);const nowMs=Date.parse(options.now);return items.map(item=>{const assigned=normalizeContextActor(item.assignee,NO_ITEM_ASSIGNEE)===normalizedAuthor;const knowledgeEntries=(item.comments?.length??0)+(item.notes?.length??0)+(item.learnings?.length??0);return{id:item.id,item,signal_provenance:{recency:recencyEvidence.get(item.id)},signals:{recency:items.length===1?1:1-recencyRank.get(item.id)/denominator,activity_density:options.activityDensity?.[item.id],graph_proximity:derivedSignalOrFallback(options.graphProximity,item.id,item.parent?.3:0),claim_focus:derivedSignalOrFallback(options.claimFocus,item.id,normalizeStatusForRegistry(item.status,options.statusRegistry)===inProgressStatus?1:assigned?.75:0),priority_pressure:normalizedPressure(item.priority,4),risk_pressure:riskPressure(item.risk),deadline_pressure:deadlinePressure(item.deadline,nowMs),knowledge_density:derivedSignalOrFallback(options.knowledgeDensity,item.id,Math.min(knowledgeEntries/5,1)),author_affinity:derivedSignalOrFallback(options.authorAffinity,item.id,assigned?1:0),usage_affinity:options.usageAffinity?.[item.id],semantic_similarity:options.semanticSimilarity?.[item.id]}}})}const CONTEXT_RELEVANCE_SERVICE="context_relevance";const DEFAULT_CONTEXT_RELEVANCE_WEIGHTS={structural:.4,recency:.35,activity_density:.25,graph_proximity:.15,claim_focus:.6,priority_pressure:.35,risk_pressure:.2,deadline_pressure:.45,knowledge_density:.25,author_affinity:.2,usage_affinity:.3,semantic_similarity:.5};const JSON_TOKEN_ENCODER=new TextEncoder;function assertCandidates(candidates){const ids=new Set;for(const candidate of candidates){if(typeof candidate.id!=="string"||candidate.id.trim().length===0||ids.has(candidate.id)){throw new TypeError("Context relevance candidates require unique non-empty ids")}ids.add(candidate.id);for(const[signal,value]of Object.entries(candidate.signals??{})){if(signal==="structural"||!CONTEXT_RELEVANCE_SIGNAL_NAMES.includes(signal)){throw new TypeError(`Unknown context relevance signal: ${signal}`)}if(value===void 0)continue;if(!Number.isFinite(value)||value<0||value>1){throw new TypeError(`Context relevance signal ${signal} must be a finite number from 0 to 1`)}}}}function resolveWeights(overrides){const weights={...DEFAULT_CONTEXT_RELEVANCE_WEIGHTS};for(const[signal,weight]of Object.entries(overrides??{})){if(weight!==void 0&&CONTEXT_RELEVANCE_SIGNAL_NAMES.includes(signal)){weights[signal]=weight}}for(const[signal,weight]of Object.entries(weights)){if(!Number.isFinite(weight)||weight<0){throw new TypeError(`Context relevance weight ${signal} must be a finite non-negative number`)}}return weights}function defaultScoreContextCandidates(candidates,options={}){assertCandidates(candidates);const weights=resolveWeights(options.weights);const denominator=Math.max(candidates.length-1,1);const available=new Set(["structural"]);for(const candidate of candidates){for(const[signal,value]of Object.entries(candidate.signals??{})){if(value!==void 0)available.add(signal)}}const availableSignals=CONTEXT_RELEVANCE_SIGNAL_NAMES.filter(signal=>available.has(signal));const scored=candidates.map((candidate,index)=>{const signalValues={structural:candidates.length===1?1:1-index/denominator,...candidate.signals};const contributions={};let weightedScore=0;let totalWeight=0;for(const signal of availableSignals){const value=signalValues[signal];if(value===void 0)continue;const contribution=value*weights[signal];contributions[signal]=contribution;weightedScore+=contribution;totalWeight+=weights[signal]}return{...candidate,baseline_rank:index+1,rank:0,score:totalWeight===0?0:weightedScore/totalWeight,contributions}});scored.sort((left,right)=>right.score-left.score||left.baseline_rank-right.baseline_rank);scored.forEach((entry,index)=>{entry.rank=index+1});return{model:"default-weighted-v1",available_signals:availableSignals,ranked:scored}}async function scoreContextCandidates(candidates,options={}){const defaultReport=defaultScoreContextCandidates(candidates,options);if(!options.scorer)return defaultReport;const customScores=await options.scorer({candidates,default_report:defaultReport});const scoreById=new Map;for(const entry of customScores){if(scoreById.has(entry.id)||!Number.isFinite(entry.score)){throw new TypeError("Context relevance scorer must return one finite score for every candidate")}scoreById.set(entry.id,entry.score)}if(scoreById.size!==candidates.length||candidates.some(candidate=>!scoreById.has(candidate.id))){throw new TypeError("Context relevance scorer must return one finite score for every candidate")}const ranked=defaultReport.ranked.map(entry=>{const score=scoreById.get(entry.id);return{...entry,score,contributions:{custom:score}}});ranked.sort((left,right)=>right.score-left.score||left.baseline_rank-right.baseline_rank);ranked.forEach((entry,index)=>{entry.rank=index+1});return{model:"custom",available_signals:defaultReport.available_signals,ranked}}async function scoreContextCandidatesWithActiveExtensions(surface,candidates,options={}){const defaultReport=defaultScoreContextCandidates(candidates,options);const override=await runActiveServiceOverride(CONTEXT_RELEVANCE_SERVICE,{surface,candidates,default_report:defaultReport});if(!override.handled){return override.warnings.length>0?{...defaultReport,warnings:override.warnings}:defaultReport}if(!Array.isArray(override.result)||!override.result.every(entry=>typeof entry==="object"&&entry!==null&&typeof entry.id==="string"&&typeof entry.score==="number"&&Number.isFinite(entry.score))){return{...defaultReport,warnings:[...override.warnings,"extension_context_relevance_invalid_result"]}}try{const report=await scoreContextCandidates(candidates,{...options,scorer:()=>override.result});return override.warnings.length>0?{...report,warnings:override.warnings}:report}catch{return{...defaultReport,warnings:[...override.warnings,"extension_context_relevance_invalid_result"]}}}const CONTEXT_EVALUATION_METRIC_NAMES=["ndcg","reciprocal_rank","required_recall","continuity_coverage","token_budget_adherence"];function ratioOfPresent(expected,actual){if(expected.length===0)return 1;return expected.filter(id=>actual.has(id)).length/expected.length}function evaluateContextRanking(input){if(!Number.isFinite(input.actual_tokens)||input.actual_tokens<0||!Number.isFinite(input.token_budget)||input.token_budget<=0){throw new TypeError("Context ranking token counts require actual_tokens >= 0 and token_budget > 0")}const judgments=input.judgments??{};const gains=input.ranked_ids.map(id=>Math.max(0,judgments[id]??0));const idealGains=Object.values(judgments).map(grade=>Math.max(0,grade)).sort((left,right)=>right-left).slice(0,gains.length||1);const discountedGain=values=>values.reduce((total,grade,index)=>total+(2**grade-1)/Math.log2(index+2),0);const ideal=discountedGain(idealGains);const firstRelevant=gains.findIndex(grade=>grade>0);const actualIds=new Set(input.ranked_ids);const withinBudget=input.actual_tokens<=input.token_budget;return{ndcg:ideal===0?1:discountedGain(gains)/ideal,reciprocal_rank:firstRelevant<0?0:1/(firstRelevant+1),required_recall:ratioOfPresent(input.required_ids??[],actualIds),continuity_coverage:ratioOfPresent(input.continuity_ids??[],actualIds),token_budget_adherence:withinBudget?1:input.token_budget/input.actual_tokens,within_token_budget:withinBudget}}function estimateJsonTokens(value){return Math.ceil(JSON_TOKEN_ENCODER.encode(JSON.stringify(value)).byteLength/4)}function roundEvaluationMetric(value){return Math.round(value*1e4)/1e4}function rankingPayloadForScenario(result,surface){const rankedIds=surface==="context"?[...result.high_level??[],...result.low_level??[],...result.blocked_fallback??[]].map(item=>item.id):[...result.recommended?[result.recommended]:[],...result.ready??[]].map(item=>item.id);const servedIds=new Set(rankedIds);const attribution=(result.ranking?.items??[]).filter(item=>servedIds.has(item.id)).map(item=>({id:item.id,contributions:item.contributions}));return{rankedIds,attribution}}async function runContextEvaluationScenario(scenario,reader){if(scenario.id.trim().length===0||scenario.rationale.trim().length===0){throw new TypeError("Context evaluation scenarios require non-empty id and rationale values")}const result=scenario.surface==="context"?await reader.context({...scenario.options,explainRanking:true,outputBudget:scenario.options?.outputBudget??"unbounded"}):await reader.next({...scenario.options,explainRanking:true,outputBudget:scenario.options?.outputBudget??"unbounded"});const{rankedIds,attribution}=rankingPayloadForScenario(result,scenario.surface);const packet={...result,ranking:void 0};const actualTokens=estimateJsonTokens(packet);return{id:scenario.id,surface:scenario.surface,rationale:scenario.rationale,ranked_ids:rankedIds,actual_tokens:actualTokens,metrics:evaluateContextRanking({ranked_ids:rankedIds,judgments:scenario.judgments,required_ids:scenario.required_ids,continuity_ids:scenario.continuity_ids,actual_tokens:actualTokens,token_budget:scenario.token_budget}),attribution}}function summarizeContextEvaluationReports(reports,thresholds){if(reports.length===0){throw new TypeError("Context evaluation requires at least one scenario report")}const metrics=CONTEXT_EVALUATION_METRIC_NAMES;for(const metric of metrics){if(!Number.isFinite(thresholds[metric])){throw new TypeError(`Context evaluation threshold ${metric} must be a finite number`)}}const aggregate=Object.fromEntries(metrics.map(metric=>[metric,roundEvaluationMetric(reports.reduce((total,report)=>total+report.metrics[metric],0)/reports.length)]));const failures=metrics.filter(metric=>aggregate[metric]<thresholds[metric]).map(metric=>`${metric}:${aggregate[metric]}<${thresholds[metric]}`);return{scenario_count:reports.length,aggregate,scenarios:[...reports],passed:failures.length===0,failures}}async function runContextEvaluationCorpus(scenarios,reader,thresholds){const reports=[];for(const scenario of scenarios){reports.push(await runContextEvaluationScenario(scenario,reader))}return summarizeContextEvaluationReports(reports,thresholds)}export{CONTEXT_EVALUATION_METRIC_NAMES,CONTEXT_RELEVANCE_SERVICE,CONTEXT_RELEVANCE_SIGNAL_NAMES,buildItemContextRelevanceCandidates,defaultScoreContextCandidates,evaluateContextRanking,runContextEvaluationCorpus,runContextEvaluationScenario,scoreContextCandidates,scoreContextCandidatesWithActiveExtensions,summarizeContextEvaluationReports};
2
2
  //# sourceMappingURL=context-relevance.js.map
@@ -4,6 +4,7 @@
4
4
  * Exposes command and action contract data without loading SDK runtime code.
5
5
  */
6
6
  export * from "./cli-contracts.js";
7
+ export * from "./graph/query-contracts.js";
7
8
  export * from "./cli-contracts/grammar-contracts.js";
8
9
  export * from "./cli-contracts/command-exit-contracts.js";
9
10
  export * from "./context-intent-contracts.js";