@unbrained/pm-cli 2026.9.13 → 2026.9.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +2 -2
- package/CHANGELOG.md +22 -0
- package/dist/cli/commander-usage.js +2 -2
- package/dist/cli/error-guidance.js +1 -1
- package/dist/cli/extension-command-help.d.ts +2 -2
- package/dist/cli/extension-command-help.js +2 -2
- package/dist/cli-bundle/bundle-manifest.json +152 -152
- package/dist/cli-bundle/chunks/chunk-33PER336.js +236 -0
- package/dist/cli-bundle/chunks/{chunk-KM4XVZR7.js → chunk-5JIJAWIF.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-A2Q64TGR.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-XM7RWQLM.js → chunk-B6W5LIXK.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-YDSV4QIQ.js → chunk-BY3ID7QI.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-YQTJACN5.js → chunk-D5AJQU7F.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-ZZI7IHMM.js → chunk-DBHQIS6Z.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-LA44JECQ.js → chunk-GQMILIC5.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-3DWX3CKN.js → chunk-NYE6EREL.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-XEZOGC3P.js → chunk-O7SRS7Y3.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-GBK5MV6N.js → chunk-XEV7BHH3.js} +26 -26
- package/dist/cli-bundle/chunks/{chunk-GQQR6JAL.js → chunk-ZYRN2OG3.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-WMJTBWNW.js → register-list-query-B2U36YWL.js} +2 -2
- package/dist/cli-bundle/chunks/{register-mutation-EXGOXP3D.js → register-mutation-GX42CQYR.js} +2 -2
- package/dist/cli-bundle/chunks/{register-operations-2H4CDRGU.js → register-operations-ZV34KX5E.js} +2 -2
- package/dist/cli-bundle/chunks/{register-setup-NYBWGPOS.js → register-setup-W4OS7IZW.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-FBCLVOBE.js → chunk-6WZBO4VQ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-OENAWWP4.js → chunk-7BUJABHB.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-F66QJWI4.js → chunk-C5NQVXKE.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-CMCSUANO.js +20 -0
- package/dist/cli-bundle/focused-chunks/{chunk-FPNI4U2B.js → chunk-CPQQIVDL.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-V7PSTKHD.js → chunk-D4FQV6TY.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-TUHRUFID.js → chunk-ENJH7CBZ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-DSJYL4VP.js → chunk-FHQLQOUZ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-B6JAANOH.js → chunk-FNLAQJES.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-GGDO6VBT.js +30 -0
- package/dist/cli-bundle/focused-chunks/{chunk-SDQCJF4H.js → chunk-KWP3QTN7.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-XCCM7P7V.js → chunk-LFGTCEHX.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-KP3N6PVZ.js → chunk-N23WTRCC.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-ZAMG7HBB.js → chunk-O4EROPO3.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-UFSMYVZF.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-LQ67C7ZO.js → chunk-ZFNRD7EN.js} +2 -2
- package/dist/cli-bundle/main.js +19 -19
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +1 -1
- package/dist/cli-bundle/sdk-core.js +24 -24
- package/dist/cli-bundle/sdk-governance.js +1 -1
- package/dist/cli-bundle/sdk-graph.js +1 -1
- package/dist/cli-bundle/sdk-merge.js +15 -15
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +8 -8
- package/dist/core/output/output.js +3 -3
- package/dist/core/telemetry/runtime.d.ts +35 -8
- package/dist/core/telemetry/runtime.js +5 -4
- package/dist/sdk/agent/command-suggestions.d.ts +6 -0
- package/dist/sdk/agent/command-suggestions.js +1 -1
- package/dist/sdk/cli-contracts/command-aliases.js +1 -1
- package/dist/sdk/cli-contracts/grammar-contracts.d.ts +2 -2
- package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
- package/dist/sdk/cli-contracts/runtime-contracts.d.ts +7 -3
- package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/telemetry.js +1 -1
- package/docs/AGENT_UX_CONTRACTS.md +10 -2
- package/docs/CLI_GRAMMAR.md +28 -0
- package/docs/CONFIGURATION.md +35 -1
- package/docs/generated/AGENT_CAPABILITY_ROUTING.md +1 -1
- package/docs/generated/AGENT_COMMAND_SURFACE.md +1 -0
- package/docs/generated/FLAG_LEXICON_BUDGETS.md +1 -0
- package/marketplace.json +2 -2
- package/package.json +5 -5
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/dist/cli-bundle/chunks/chunk-6KHYW3FH.js +0 -235
- package/dist/cli-bundle/chunks/chunk-AKTBOX6U.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-7JR6M2JR.js +0 -30
- package/dist/cli-bundle/focused-chunks/chunk-YUXBHIUV.js +0 -20
- package/dist/cli-bundle/focused-chunks/chunk-ZF5PXK6A.js +0 -2
|
@@ -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]="30908abd-2ac0-5744-8eb3-0c798b917e6d")}catch(e2){}})();import{resolvePmCommandAlias,PM_HISTORY_COMMAND_ALIASES,PM_RELOCATED_COMMAND_ALIASES,resolvePmHistoryOperation}from"./command-aliases.js";const PM_CLI_GRAMMAR_NOUNS=["item","list","context","search","graph","history","workspace","package","ops","plan","contracts","help"];const PM_CLI_SHARED_VERBS=["activate","add","adopt","adopt-all","catalog","compact","complete","create","deactivate","delete","describe","doctor","edit","explore","import","init","inspect","install","list","manage","migrate","mutate","read","redact","reload","remove","reopen","repair","restore","run","show","uninstall","upgrade","verify"];function positionalSlot(name,valueKind,required,options={}){return{name,required,variadic:options.variadic===true,value_kind:valueKind,polymorphic:options.polymorphic===true}}function positionalActionVerb(action){const phrase=action.replaceAll("-"," ");return`${phrase.charAt(0).toUpperCase()}${phrase.slice(1)}`}const ITEM_ID=positionalSlot("id","item_id",true);const OPTIONAL_ITEM_ID=positionalSlot("id","item_id",false);const OPTIONAL_TEXT=positionalSlot("text","string",false);const PLAN_ITEM_ID=positionalSlot("plan-id","item_id",true);const PLAN_STEP=positionalSlot("step","string",true);const PLAN_CREATE_FLAGS=["--acceptance-criteria","--actual-result","--affected-version","--assignee","--blocked-by","--blocked-reason","--blocks","--body","--claim","--comment","--component","--confidence","--create-mode","--customer-impact","--deadline","--definition-of-ready","--description","--doc","--environment","--estimate","--event","--expected-result","--fixed-version","--file","--from-search","--goal","--harness","--impact","--learning","--message","--mode","--note","--objective","--order","--outcome","--parent","--priority","--rank","--related","--release","--reminder","--reporter","--repro-steps","--resolution","--resume-context","--reviewer","--risk","--scope","--severity","--sprint","--status","--step","--step-blocked-reason","--step-body","--step-evidence","--step-owner","--step-replacement","--step-status","--step-title","--tags","--template","--test","--title","--type-option","--unblock-note","--value","--why-now"];const PLAN_STEP_FLAGS=["--allow-multiple-active","--depends-on","--file","--force","--message","--step-blocked-reason","--step-body","--step-evidence","--step-owner","--step-status","--step-title","--test"];const PLAN_STEP_ACTION_DESCRIPTIONS={"update-step":"Update one declared Plan step.","complete-step":"Complete one declared Plan step.","block-step":"Block one declared Plan step.","remove-step":"Remove one declared Plan step.",link:"Link one dependency to a declared Plan step.",unlink:"Unlink one dependency from a declared Plan step."};const PM_POSITIONAL_ACTION_CONTRACTS=[{command:"plan create",parent:"plan",action:"create",slots:[positionalSlot("title","string",false,{polymorphic:true})],accepted_flags:PLAN_CREATE_FLAGS,description:"Create a Plan item and optionally seed its ordered steps.",example:'pm plan create --title "Refactor lock retry"'},{command:"plan show",parent:"plan",action:"show",slots:[PLAN_ITEM_ID],accepted_flags:["--depth","--fields"],description:"Read one Plan item with a bounded plan projection.",example:"pm plan show pm-a1b2 --depth standard"},{command:"plan add-step",parent:"plan",action:"add-step",slots:[PLAN_ITEM_ID],accepted_flags:PLAN_STEP_FLAGS,description:"Append one ordered step to a Plan item.",example:'pm plan add-step pm-a1b2 --step-title "Run tests"'},...Object.entries(PLAN_STEP_ACTION_DESCRIPTIONS).map(([action,description])=>({command:`plan ${action}`,parent:"plan",action,slots:[PLAN_ITEM_ID,PLAN_STEP],accepted_flags:PLAN_STEP_FLAGS,description,example:`pm plan ${action} pm-a1b2 plan-step-001`})),{command:"plan reorder-step",parent:"plan",action:"reorder-step",slots:[PLAN_ITEM_ID,PLAN_STEP,positionalSlot("new-order","integer",true)],accepted_flags:["--force","--message"],description:"Move one Plan step to a declared integer order.",example:"pm plan reorder-step pm-a1b2 plan-step-001 2"},...["decision","discovery","validation","resume","approve","materialize"].map(action=>({command:`plan ${action}`,parent:"plan",action,slots:[PLAN_ITEM_ID],accepted_flags:PLAN_STEP_FLAGS,description:`${positionalActionVerb(action)} for one Plan item.`,example:`pm plan ${action} pm-a1b2`})),...["list","show","put","remove"].map(action=>({command:`assurance ${action}`,parent:"assurance",action,slots:[positionalSlot("kind","string",true),...action==="list"?[]:[positionalSlot("id","string",true)]],accepted_flags:action==="put"?["--author","--definition","--message"]:action==="remove"?["--author","--message"]:[],description:`${positionalActionVerb(action)} assurance declarations by kind.`,example:action==="list"?"pm assurance list measurement":`pm assurance ${action} measurement example-id`})),{command:"assurance run",parent:"assurance",action:"run",slots:[positionalSlot("gate-id","string",true)],accepted_flags:["--dry-run","--trigger","--tree"],description:"Evaluate one assurance gate for a lifecycle trigger.",example:"pm assurance run tracker-context-quality --trigger ci --dry-run"},{command:"assurance verdicts",parent:"assurance",action:"verdicts",slots:[positionalSlot("gate-id","string",false)],accepted_flags:["--gate","--limit"],description:"List bounded assurance verdict history.",example:"pm assurance verdicts --limit 20"},...["presets","apply"].map(action=>({command:`assurance ${action}`,parent:"assurance",action,slots:[positionalSlot("preset","string",action==="apply")],accepted_flags:["--author","--message","--owner"],description:action==="apply"?"Apply one assurance adoption preset.":"List available assurance adoption presets.",example:action==="apply"?"pm assurance apply software-delivery --owner <pm-item-id>":"pm assurance presets"})),{command:"assurance derive",parent:"assurance",action:"derive",slots:[],accepted_flags:["--apply","--author","--message","--owner"],description:"Derive assurance proposals from current project context.",example:"pm assurance derive --owner pm-a1b2"},{command:"assurance promote",parent:"assurance",action:"promote",slots:[positionalSlot("assertion-id","string",true)],accepted_flags:["--author","--enforcement","--message"],description:"Promote one assertion into a warning or blocking gate.",example:"pm assurance promote assertion-id --enforcement warn"},{command:"assurance risk",parent:"assurance",action:"risk",slots:[],accepted_flags:["--definition"],description:"Analyze bounded defect-recurrence risk for a proposed change.",example:`pm assurance risk --definition '{"change":{"files":[]}}'`},{command:"assurance lineages",parent:"assurance",action:"lineages",slots:[],accepted_flags:["--definition"],description:"Measure all recorded recurrence lineages with bounded evidence rows.",example:`pm assurance lineages --definition '{"policy":{"version":1,"evidence_epoch":"2026-01-01T00:00:00.000Z","families":[]}}'`},{command:"workspace position",parent:"workspace",action:"position",slots:[],accepted_flags:[],description:"Read bounded merge-fence, receipt, history-drift, and next-action readiness.",example:"pm workspace position"},{command:"workspace snapshot create",parent:"workspace snapshot",action:"create",slots:[positionalSlot("name","string",false)],accepted_flags:[],description:"Capture authoritative tracker state as an immutable snapshot.",example:"pm workspace snapshot create before-migration"},{command:"workspace snapshot list",parent:"workspace snapshot",action:"list",slots:[],accepted_flags:[],description:"List immutable workspace snapshots and named references.",example:"pm workspace snapshot list"},{command:"workspace snapshot inspect",parent:"workspace snapshot",action:"inspect",slots:[positionalSlot("target","string",true)],accepted_flags:[],description:"Inspect one workspace snapshot target.",example:"pm workspace snapshot inspect before-migration"},{command:"workspace snapshot restore",parent:"workspace snapshot",action:"restore",slots:[positionalSlot("target","string",true)],accepted_flags:["--author","--dry-run","--force","--message"],description:"Restore an immutable workspace snapshot with explicit recovery controls.",example:"pm workspace snapshot restore before-migration --dry-run"},{command:"workspace snapshot delete",parent:"workspace snapshot",action:"delete",slots:[positionalSlot("target","string",true)],accepted_flags:[],description:"Delete one workspace snapshot target.",example:"pm workspace snapshot delete before-migration"}];const POSITIONAL_ACTION_CONTRACTS_BY_SPECIFICITY=[...PM_POSITIONAL_ACTION_CONTRACTS].sort((left,right)=>right.command.length-left.command.length);const EXPLICIT_POSITIONAL_SLOTS=new Map([["append",[ITEM_ID,OPTIONAL_TEXT]],["assurance",[positionalSlot("action","action",true),positionalSlot("kind","string",false),positionalSlot("id","string",false)]],["beads import",[positionalSlot("file","string",false)]],["changelog export",[positionalSlot("file","string",false)]],["claim",[OPTIONAL_ITEM_ID]],["close",[ITEM_ID,OPTIONAL_TEXT]],["close-task",[ITEM_ID,positionalSlot("reason","string",false)]],["comments",[ITEM_ID,OPTIONAL_TEXT]],["completion",[positionalSlot("shell","string",false)]],["config",[positionalSlot("scope","string",false,{polymorphic:true}),positionalSlot("action","action",false),positionalSlot("key","string",false),positionalSlot("value","string",false,{polymorphic:true})]],["copy",[ITEM_ID]],["create",[positionalSlot("type-or-title","string",false,{polymorphic:true}),positionalSlot("title","string",false)]],["delete",[ITEM_ID]],["deps",[ITEM_ID]],["docs",[ITEM_ID]],["event",[positionalSlot("title","string",true)]],["files",[ITEM_ID]],["files discover",[ITEM_ID]],["files lookup",[positionalSlot("paths","string",true,{variadic:true})]],["focus",[OPTIONAL_ITEM_ID]],["get",[ITEM_ID]],["graph",[positionalSlot("subcommand","action",true),OPTIONAL_ITEM_ID,positionalSlot("target","item_id",false)]],["guide",[positionalSlot("topic","string",false)]],["history",[ITEM_ID]],["history-compact",[OPTIONAL_ITEM_ID]],["history-redact",[ITEM_ID]],["history-repair",[OPTIONAL_ITEM_ID]],["init",[positionalSlot("prefix-or-path","string",false,{polymorphic:true})]],["item complete",[ITEM_ID,positionalSlot("reason","string",false)]],["item reopen",[ITEM_ID,positionalSlot("reason","string",true)]],["learnings",[ITEM_ID,OPTIONAL_TEXT]],["meet",[positionalSlot("title","string",true)]],["merge",[positionalSlot("subcommand","action",true),positionalSlot("artifact","string",false),positionalSlot("base","string",false),positionalSlot("ours","string",false),positionalSlot("theirs","string",false)]],["notes",[ITEM_ID,OPTIONAL_TEXT]],["package",[positionalSlot("target","string",false,{polymorphic:true})]],["package list",[]],["package scaffold",[positionalSlot("target","string",true)]],["package upgrade",[positionalSlot("target","string",false)]],["packages",[positionalSlot("target","string",false,{polymorphic:true})]],["packages list",[]],["packages scaffold",[positionalSlot("target","string",true)]],["packages upgrade",[positionalSlot("target","string",false)]],["pause-task",[ITEM_ID]],["plan",[positionalSlot("subcommand","action",true),positionalSlot("id","item_id",false,{polymorphic:true}),positionalSlot("step","string",false),positionalSlot("new-order","integer",false)]],["profile",[positionalSlot("subcommand","action",true),positionalSlot("name","string",false)]],["release",[ITEM_ID]],["remind",[positionalSlot("title","string",true)]],["restore",[ITEM_ID,positionalSlot("target","string",true)]],["schema",[positionalSlot("subcommand","action",true),positionalSlot("name","string",false)]],["search-advanced",[positionalSlot("keywords","string",true,{variadic:true})]],["search",[positionalSlot("keywords","string",true,{variadic:true})]],["start-task",[ITEM_ID]],["telemetry",[positionalSlot("namespace-or-subcommand","action",false,{polymorphic:true}),positionalSlot("subcommand","action",false)]],["test",[ITEM_ID]],["test-runs-worker",[positionalSlot("runId","string",true)]],["update",[ITEM_ID]],["workspace snapshot",[positionalSlot("action","action",true),positionalSlot("target","string",false)]],...["activate","adopt","deactivate","init","uninstall"].flatMap(action=>["extension","package","packages"].map(root=>[`${root} ${action}`,[positionalSlot("target","string",true)]])),...["describe"].flatMap(action=>["extension","package","packages"].map(root=>[`${root} ${action}`,[positionalSlot("target","string",false)]])),...["install"].flatMap(action=>["extension","package","packages"].map(root=>[`${root} ${action}`,[positionalSlot("targets","string",false,{variadic:true})]])),["vcs abandon",[ITEM_ID]],["vcs create",[positionalSlot("title","string",true)]],["vcs merge",[ITEM_ID]],["vcs propose",[ITEM_ID]],["vcs ref-create",[positionalSlot("name","string",true)]],["vcs show",[ITEM_ID]]]);function normalizePositionalCommandPath(command){return command.trim().toLowerCase().replace(/\s+/gu," ")}function resolvePmCommandPositionalContract(command){const normalized=normalizePositionalCommandPath(command);const direct=PM_COMMAND_POSITIONAL_CONTRACTS.find(contract=>contract.command===normalized);if(direct)return direct;const canonical=resolvePmCommandAlias(normalized)?.canonical;if(!canonical)return void 0;return PM_COMMAND_POSITIONAL_CONTRACTS.find(contract=>contract.command===canonical)}function resolvePmPositionalActionContract(command){const normalized=normalizePositionalCommandPath(command);return POSITIONAL_ACTION_CONTRACTS_BY_SPECIFICITY.find(contract=>contract.command===normalized||normalized.startsWith(`${contract.command} `))}function formatPmPositionalActionFlagTip(acceptedFlags){return`Applicable flags: ${acceptedFlags.length>0?acceptedFlags.join(", "):"none"}.`}function destinationRows(noun,target,disposition,owner,commands){return commands.map(command=>({command,noun,target,disposition,owner}))}const PM_COMMAND_DESTINATION_CONTRACTS=[...destinationRows("item","item","target_noun","pm-pbyu",["item","item complete","item mutate","item reopen"]),...destinationRows("item","item","consolidation","pm-yql1",["append","claim","close","close-many","close-task","comments","copy","create","delete","deps","docs","files","get","learnings","notes","pause-task","release","start-task","test","update","update-many"]),...destinationRows("item","item files","consolidation","pm-ya7x55",["files discover","files lookup","item files discover","item files lookup"]),...destinationRows("item","item test worker","consolidation","pm-lp4j",["test-runs-worker"]),...destinationRows("list","list","target_noun","pm-pfqi",["list"]),...destinationRows("list","list --group-by","consolidation","pm-xkgq",["aggregate"]),...destinationRows("context","context","target_noun","pm-pbyu",["context"]),...destinationRows("context","context","consolidation","pm-kcs4",["ctx","focus","next"]),...destinationRows("context","context next","consolidation","pm-kcs4",["ctx next"]),...destinationRows("context","context focus","consolidation","pm-kcs4",["ctx focus"]),...destinationRows("search","search","target_noun","pm-pbyu",["search"]),...destinationRows("search","search","package_owned","package:search-advanced",["reindex","search-advanced"]),...destinationRows("item","item duplicates","consolidation","pm-fmy9ih",["duplicates"]),...destinationRows("item","item duplicates","package_owned","pm-fmy9ih",["dedupe-audit","dedupe-merge","comments-audit"]),...destinationRows("graph","graph","target_noun","pm-pbyu",["graph"]),...destinationRows("history","history","target_noun","pm-pbyu",["history"]),...destinationRows("history","history attest","target_noun","pm-3z0k",["history attest"]),...destinationRows("history","history attest","consolidation","pm-3z0k",["history-attest"]),...PM_HISTORY_COMMAND_ALIASES.flatMap(({alias,canonical})=>[...destinationRows("history",canonical,"target_noun","pm-tqel",[canonical]),...destinationRows("history",canonical,"consolidation","pm-tqel",[alias])]),...destinationRows("history","history","consolidation","pm-tqel",["events","merge"]),...destinationRows("history","history acknowledge","consolidation","pm-djyvbk",["history-author-acknowledge"]),...destinationRows("history","history","package_owned","package:builtin-vcs-exemplar",["vcs abandon","vcs create","vcs log","vcs merge","vcs propose","vcs ref-create","vcs show"]),...destinationRows("workspace","workspace","target_noun","pm-pbyu",["workspace","workspace position","workspace snapshot","workspace snapshot create","workspace snapshot delete","workspace snapshot inspect","workspace snapshot list","workspace snapshot restore"]),...destinationRows("workspace","workspace init","consolidation","pm-npr3",["init"]),...destinationRows("package","package","target_noun","pm-pbyu",["package","package activate","package adopt","package adopt-all","package catalog","package deactivate","package describe","package doctor","package explore","package init","package install","package list","package manage","package migrate","package reload","package scaffold","package uninstall","package upgrade"]),...destinationRows("package","package","consolidation","pm-tnud",["extension activate","extension adopt","extension adopt-all","extension catalog","extension deactivate","extension describe","extension doctor","extension explore","extension init","extension install","extension manage","extension migrate","extension reload","extension uninstall","packages","packages activate","packages adopt","packages adopt-all","packages catalog","packages deactivate","packages describe","packages doctor","packages explore","packages init","packages install","packages list","packages manage","packages migrate","packages reload","packages scaffold","packages uninstall","packages upgrade"]),...destinationRows("package","package","package_owned","package:beads",["beads import"]),...destinationRows("package","package","package_owned","package:pm-changelog",["changelog export","changelog generate"]),...destinationRows("package","package calendar","package_owned","pm-o3fh",["event","meet","remind"]),...destinationRows("ops","ops","target_noun","pm-6apl",["ops"]),...destinationRows("ops","ops normalize","package_owned","package:pm-governance-audit",["normalize"]),...destinationRows("ops","ops","consolidation","pm-6apl",["eval","gc","health","stats","telemetry","test-all","validate"]),...destinationRows("ops","ops","consolidation","pm-npr3",["config","profile","schema"]),...destinationRows("ops","ops assurance","consolidation","pm-djyvbk",["assurance"]),...destinationRows("ops","ops assurance","consolidation","pm-2tan",PM_POSITIONAL_ACTION_CONTRACTS.filter(({parent})=>parent==="assurance").map(({command})=>command)),...destinationRows("plan","plan","target_noun","pm-pbyu",["plan"]),...destinationRows("plan","plan","target_noun","pm-2tan",PM_POSITIONAL_ACTION_CONTRACTS.filter(({parent})=>parent==="plan").map(({command})=>command)),...destinationRows("contracts","contracts","target_noun","pm-pbyu",["contracts"]),...destinationRows("help","help","target_noun","pm-pbyu",["help"]),...destinationRows("help","help","package_owned","package:builtin-guide-shell",["completion","completion-statuses","completion-tags","completion-types","guide"])].flatMap(entry=>{const alias=PM_RELOCATED_COMMAND_ALIASES.find(candidate=>candidate.alias===entry.command);if(!alias)return[entry];const noun=PM_CLI_GRAMMAR_NOUNS.find(candidate=>candidate===alias.canonical_argv[0])??entry.noun;return[{...entry,noun,target:alias.canonical,owner:alias.owner},{...entry,command:alias.canonical,noun,target:alias.canonical,owner:alias.owner,disposition:entry.disposition==="package_owned"?"package_owned":"target_noun"}]});const PM_COMMAND_POSITIONAL_CONTRACTS=[...new Set(PM_COMMAND_DESTINATION_CONTRACTS.map(({command})=>command))].map(command=>({command,slots:resolvePmPositionalActionContract(command)?.slots??EXPLICIT_POSITIONAL_SLOTS.get(resolvePmHistoryOperation(command))??[]}));const PM_CLI_GRAMMAR_CONTRACT={nouns:PM_CLI_GRAMMAR_NOUNS,shared_verbs:PM_CLI_SHARED_VERBS,scope_before_verb:true,visible_top_level_ceiling:69,ceiling_raise_requires_pm_item:true,positional_shape_budget:21};function verifyExplicitPositionalSlotCensus(explicitCommands,destinationCommands){const destinations=new Set(destinationCommands);return[...new Set(explicitCommands)].filter(command=>!destinations.has(command)).map(command=>({code:"positional_signature_mismatch",command,detail:`Positional signature ${command} has no destination declaration.`}))}function positionalShapeKey(slots){return slots.map(({required,variadic,value_kind:valueKind,polymorphic})=>`${required?"r":"o"}:${variadic?"v":"s"}:${valueKind}:${polymorphic?"p":"m"}`).join("|")}function positionalSignatureKey(slots){return slots.map(({name,required,variadic,value_kind:valueKind,polymorphic})=>`${name}:${required?"r":"o"}:${variadic?"v":"s"}:${valueKind}:${polymorphic?"p":"m"}`).join("|")}function duplicatePositionalSignatureFindings(contracts,surface){const counts=new Map;for(const{command}of contracts){const normalized=normalizePositionalCommandPath(command);counts.set(normalized,(counts.get(normalized)??0)+1)}return[...counts.entries()].filter(([,count])=>count>1).map(([command,count])=>({code:"positional_signature_mismatch",command,detail:`${count} ${surface} positional signatures exist for ${command}; exactly one is required.`}))}function verifyPmCommandPositionalContracts(observed,options={}){const declared=options.declared??PM_COMMAND_POSITIONAL_CONTRACTS;const positionalShapeBudget=options.positionalShapeBudget??PM_CLI_GRAMMAR_CONTRACT.positional_shape_budget;const declaredByCommand=new Map(declared.map(contract=>[normalizePositionalCommandPath(contract.command),contract]));const observedByCommand=new Map(observed.map(contract=>[normalizePositionalCommandPath(contract.command),contract]));const findings=[...duplicatePositionalSignatureFindings(declared,"declared"),...duplicatePositionalSignatureFindings(observed,"observed"),...options.declared===void 0?[...verifyExplicitPositionalSlotCensus(EXPLICIT_POSITIONAL_SLOTS.keys(),PM_COMMAND_DESTINATION_CONTRACTS.map(({command})=>command)),...verifyExplicitPositionalSlotCensus(PM_POSITIONAL_ACTION_CONTRACTS.map(({command})=>command),PM_COMMAND_DESTINATION_CONTRACTS.map(({command})=>command))]:[]];for(const contract of declaredByCommand.values()){const normalizedCommand=normalizePositionalCommandPath(contract.command);const actual=observedByCommand.get(normalizedCommand);if(!actual){findings.push({code:"missing_observed_signature",command:contract.command,detail:`No observed positional signature exists for ${contract.command}.`})}else if(positionalSignatureKey(actual.slots)!==positionalSignatureKey(contract.slots)){findings.push({code:"positional_signature_mismatch",command:contract.command,detail:`Observed positional signature for ${contract.command} differs from its declared SDK contract: observed=${positionalSignatureKey(actual.slots)||"<none>"}; declared=${positionalSignatureKey(contract.slots)||"<none>"}.`})}}for(const contract of observedByCommand.values()){if(!declaredByCommand.has(normalizePositionalCommandPath(contract.command))){findings.push({code:"stale_observed_signature",command:contract.command,detail:`Observed positional signature ${contract.command} has no declaration.`})}}const positionalShapeCount=new Set(declared.map(({slots})=>positionalShapeKey(slots))).size;if(positionalShapeCount>positionalShapeBudget){findings.push({code:"positional_shape_budget_exceeded",command:"*",detail:`Distinct positional shape count ${positionalShapeCount} exceeds budget ${positionalShapeBudget}.`})}findings.sort((left,right)=>left.command!==right.command?left.command.localeCompare(right.command):left.code.localeCompare(right.code));return{ok:findings.length===0,declared_command_count:declared.length,observed_command_count:observed.length,positional_shape_count:positionalShapeCount,positional_shape_budget:positionalShapeBudget,findings}}function validateCommandDestinations(commands,destinationsByCommand,nounSet){return commands.flatMap(command=>{const destinations=destinationsByCommand.get(command)??[];if(destinations.length===0){const separatorIndex=command.indexOf(" ");const root=separatorIndex===-1?command:command.slice(0,separatorIndex);return[{code:"missing_destination",spelling:command,message:`Command \`${command}\` has no destination census row.`,nearest_target:nounSet.has(root)?root:`ops ${command}`}]}const duplicateFinding=destinations.length>1?[{code:"duplicate_destination",spelling:command,message:`Command \`${command}\` has ${destinations.length} destination rows.`,nearest_target:destinations[0].target}]:[];return destinations.reduce((findings,destination)=>{if(destination.disposition==="keep_as_is"&&(destination.reason?.trim().length??0)===0){findings.push({code:"missing_destination",spelling:command,message:`Command \`${command}\` is kept as-is without a documented reason.`,nearest_target:destination.target})}if(!nounSet.has(destination.noun)){findings.push({code:"unknown_noun",spelling:command,message:`Command \`${command}\` names undeclared noun \`${destination.noun}\`.`,nearest_target:destination.target})}return findings},duplicateFinding)})}function validateDestinationCensus(commandSet,destinations){return destinations.filter(destination=>destination.disposition!=="package_owned"&&!commandSet.has(destination.command)).map(destination=>({code:"stale_destination",spelling:destination.command,message:`Destination row \`${destination.command}\` is absent from live contracts.`,nearest_target:destination.target}))}function validateAliasTargets(aliases,commandSet){return aliases.filter(alias=>!commandSet.has(alias.canonical)).map(alias=>({code:"alias_target_missing",spelling:alias.alias,message:`Alias \`${alias.alias}\` targets missing canonical command \`${alias.canonical}\`.`,nearest_target:alias.canonical_argv.join(" ")}))}function verifyPmCliGrammar(commands,aliases=[],destinations=PM_COMMAND_DESTINATION_CONTRACTS){const normalizedCommands=[...new Set(commands.map(command=>command.trim()))].filter(command=>command.length>0).sort((left,right)=>left.localeCompare(right));const commandSet=new Set(normalizedCommands);const nounSet=new Set(PM_CLI_GRAMMAR_NOUNS);const destinationsByCommand=new Map;for(const destination of destinations){const entries=destinationsByCommand.get(destination.command)??[];entries.push(destination);destinationsByCommand.set(destination.command,entries)}const findings=[...validateCommandDestinations(normalizedCommands,destinationsByCommand,nounSet),...validateDestinationCensus(commandSet,destinations),...validateAliasTargets(aliases.filter(alias=>commandSet.has(alias.alias)||!(destinationsByCommand.get(alias.canonical)??[]).some(destination=>destination.disposition==="package_owned")),commandSet)];const hiddenAliasNames=new Set(aliases.filter(alias=>alias.hidden).map(alias=>alias.alias));const visibleTopLevelCount=new Set(normalizedCommands.filter(command=>!command.includes(" ")&&!hiddenAliasNames.has(command)&&!(destinationsByCommand.get(command)??[]).some(destination=>destination.disposition==="package_owned"))).size;if(visibleTopLevelCount>PM_CLI_GRAMMAR_CONTRACT.visible_top_level_ceiling){findings.push({code:"visible_surface_ceiling_exceeded",spelling:String(visibleTopLevelCount),message:`Visible non-package top-level command count ${visibleTopLevelCount} exceeds ceiling ${PM_CLI_GRAMMAR_CONTRACT.visible_top_level_ceiling}.`,nearest_target:"Declare the noun placement and tracked waiver before raising the ceiling."})}return{ok:findings.length===0,command_count:normalizedCommands.length,destination_count:destinations.length,hidden_alias_count:aliases.filter(alias=>alias.hidden).length,visible_top_level_count:visibleTopLevelCount,visible_top_level_ceiling:PM_CLI_GRAMMAR_CONTRACT.visible_top_level_ceiling,findings}}export{PM_CLI_GRAMMAR_CONTRACT,PM_CLI_GRAMMAR_NOUNS,PM_CLI_SHARED_VERBS,PM_COMMAND_DESTINATION_CONTRACTS,PM_COMMAND_POSITIONAL_CONTRACTS,PM_POSITIONAL_ACTION_CONTRACTS,formatPmPositionalActionFlagTip,positionalShapeKey,positionalSignatureKey,resolvePmCommandPositionalContract,resolvePmPositionalActionContract,verifyExplicitPositionalSlotCensus,verifyPmCliGrammar,verifyPmCommandPositionalContracts};
|
|
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]="733ce7b1-de7b-53b9-83bb-deefd930d8ec")}catch(e2){}})();import{resolvePmCommandAlias,PM_HISTORY_COMMAND_ALIASES,PM_RELOCATED_COMMAND_ALIASES,resolvePmHistoryOperation}from"./command-aliases.js";const PM_CLI_GRAMMAR_NOUNS=["item","list","context","search","graph","history","workspace","package","ops","plan","contracts","help"];const PM_CLI_SHARED_VERBS=["acknowledge","activate","add","adopt","adopt-all","catalog","compact","complete","create","deactivate","delete","describe","doctor","edit","explore","import","init","inspect","install","list","manage","migrate","mutate","read","redact","reload","remove","reopen","repair","restore","run","show","uninstall","upgrade","verify"];function positionalSlot(name,valueKind,required,options={}){return{name,required,variadic:options.variadic===true,value_kind:valueKind,polymorphic:options.polymorphic===true}}function positionalActionVerb(action){const phrase=action.replaceAll("-"," ");return`${phrase.charAt(0).toUpperCase()}${phrase.slice(1)}`}const ITEM_ID=positionalSlot("id","item_id",true);const OPTIONAL_ITEM_ID=positionalSlot("id","item_id",false);const OPTIONAL_TEXT=positionalSlot("text","string",false);const PLAN_ITEM_ID=positionalSlot("plan-id","item_id",true);const PLAN_STEP=positionalSlot("step","string",true);const PLAN_CREATE_FLAGS=["--acceptance-criteria","--actual-result","--affected-version","--assignee","--blocked-by","--blocked-reason","--blocks","--body","--claim","--comment","--component","--confidence","--create-mode","--customer-impact","--deadline","--definition-of-ready","--description","--doc","--environment","--estimate","--event","--expected-result","--fixed-version","--file","--from-search","--goal","--harness","--impact","--learning","--message","--mode","--note","--objective","--order","--outcome","--parent","--priority","--rank","--related","--release","--reminder","--reporter","--repro-steps","--resolution","--resume-context","--reviewer","--risk","--scope","--severity","--sprint","--status","--step","--step-blocked-reason","--step-body","--step-evidence","--step-owner","--step-replacement","--step-status","--step-title","--tags","--template","--test","--title","--type-option","--unblock-note","--value","--why-now"];const PLAN_STEP_FLAGS=["--allow-multiple-active","--depends-on","--file","--force","--message","--step-blocked-reason","--step-body","--step-evidence","--step-owner","--step-status","--step-title","--test"];const PLAN_STEP_ACTION_DESCRIPTIONS={"update-step":"Update one declared Plan step.","complete-step":"Complete one declared Plan step.","block-step":"Block one declared Plan step.","remove-step":"Remove one declared Plan step.",link:"Link one dependency to a declared Plan step.",unlink:"Unlink one dependency from a declared Plan step."};const PM_POSITIONAL_ACTION_CONTRACTS=[{command:"plan create",parent:"plan",action:"create",slots:[positionalSlot("title","string",false,{polymorphic:true})],accepted_flags:PLAN_CREATE_FLAGS,description:"Create a Plan item and optionally seed its ordered steps.",example:'pm plan create --title "Refactor lock retry"'},{command:"plan show",parent:"plan",action:"show",slots:[PLAN_ITEM_ID],accepted_flags:["--depth","--fields"],description:"Read one Plan item with a bounded plan projection.",example:"pm plan show pm-a1b2 --depth standard"},{command:"plan add-step",parent:"plan",action:"add-step",slots:[PLAN_ITEM_ID],accepted_flags:PLAN_STEP_FLAGS,description:"Append one ordered step to a Plan item.",example:'pm plan add-step pm-a1b2 --step-title "Run tests"'},...Object.entries(PLAN_STEP_ACTION_DESCRIPTIONS).map(([action,description])=>({command:`plan ${action}`,parent:"plan",action,slots:[PLAN_ITEM_ID,PLAN_STEP],accepted_flags:PLAN_STEP_FLAGS,description,example:`pm plan ${action} pm-a1b2 plan-step-001`})),{command:"plan reorder-step",parent:"plan",action:"reorder-step",slots:[PLAN_ITEM_ID,PLAN_STEP,positionalSlot("new-order","integer",true)],accepted_flags:["--force","--message"],description:"Move one Plan step to a declared integer order.",example:"pm plan reorder-step pm-a1b2 plan-step-001 2"},...["decision","discovery","validation","resume","approve","materialize"].map(action=>({command:`plan ${action}`,parent:"plan",action,slots:[PLAN_ITEM_ID],accepted_flags:PLAN_STEP_FLAGS,description:`${positionalActionVerb(action)} for one Plan item.`,example:`pm plan ${action} pm-a1b2`})),...["list","show","put","remove"].map(action=>({command:`assurance ${action}`,parent:"assurance",action,slots:[positionalSlot("kind","string",true),...action==="list"?[]:[positionalSlot("id","string",true)]],accepted_flags:action==="put"?["--author","--definition","--message"]:action==="remove"?["--author","--message"]:[],description:`${positionalActionVerb(action)} assurance declarations by kind.`,example:action==="list"?"pm assurance list measurement":`pm assurance ${action} measurement example-id`})),{command:"assurance run",parent:"assurance",action:"run",slots:[positionalSlot("gate-id","string",true)],accepted_flags:["--dry-run","--trigger","--tree"],description:"Evaluate one assurance gate for a lifecycle trigger.",example:"pm assurance run tracker-context-quality --trigger ci --dry-run"},{command:"assurance verdicts",parent:"assurance",action:"verdicts",slots:[positionalSlot("gate-id","string",false)],accepted_flags:["--gate","--limit"],description:"List bounded assurance verdict history.",example:"pm assurance verdicts --limit 20"},...["presets","apply"].map(action=>({command:`assurance ${action}`,parent:"assurance",action,slots:[positionalSlot("preset","string",action==="apply")],accepted_flags:["--author","--message","--owner"],description:action==="apply"?"Apply one assurance adoption preset.":"List available assurance adoption presets.",example:action==="apply"?"pm assurance apply software-delivery --owner <pm-item-id>":"pm assurance presets"})),{command:"assurance derive",parent:"assurance",action:"derive",slots:[],accepted_flags:["--apply","--author","--message","--owner"],description:"Derive assurance proposals from current project context.",example:"pm assurance derive --owner pm-a1b2"},{command:"assurance promote",parent:"assurance",action:"promote",slots:[positionalSlot("assertion-id","string",true)],accepted_flags:["--author","--enforcement","--message"],description:"Promote one assertion into a warning or blocking gate.",example:"pm assurance promote assertion-id --enforcement warn"},{command:"assurance risk",parent:"assurance",action:"risk",slots:[],accepted_flags:["--definition"],description:"Analyze bounded defect-recurrence risk for a proposed change.",example:`pm assurance risk --definition '{"change":{"files":[]}}'`},{command:"assurance lineages",parent:"assurance",action:"lineages",slots:[],accepted_flags:["--definition"],description:"Measure all recorded recurrence lineages with bounded evidence rows.",example:`pm assurance lineages --definition '{"policy":{"version":1,"evidence_epoch":"2026-01-01T00:00:00.000Z","families":[]}}'`},{command:"workspace position",parent:"workspace",action:"position",slots:[],accepted_flags:[],description:"Read bounded merge-fence, receipt, history-drift, and next-action readiness.",example:"pm workspace position"},{command:"workspace snapshot create",parent:"workspace snapshot",action:"create",slots:[positionalSlot("name","string",false)],accepted_flags:[],description:"Capture authoritative tracker state as an immutable snapshot.",example:"pm workspace snapshot create before-migration"},{command:"workspace snapshot list",parent:"workspace snapshot",action:"list",slots:[],accepted_flags:[],description:"List immutable workspace snapshots and named references.",example:"pm workspace snapshot list"},{command:"workspace snapshot inspect",parent:"workspace snapshot",action:"inspect",slots:[positionalSlot("target","string",true)],accepted_flags:[],description:"Inspect one workspace snapshot target.",example:"pm workspace snapshot inspect before-migration"},{command:"workspace snapshot restore",parent:"workspace snapshot",action:"restore",slots:[positionalSlot("target","string",true)],accepted_flags:["--author","--dry-run","--force","--message"],description:"Restore an immutable workspace snapshot with explicit recovery controls.",example:"pm workspace snapshot restore before-migration --dry-run"},{command:"workspace snapshot delete",parent:"workspace snapshot",action:"delete",slots:[positionalSlot("target","string",true)],accepted_flags:[],description:"Delete one workspace snapshot target.",example:"pm workspace snapshot delete before-migration"}];const POSITIONAL_ACTION_CONTRACTS_BY_SPECIFICITY=[...PM_POSITIONAL_ACTION_CONTRACTS].sort((left,right)=>right.command.length-left.command.length);const EXPLICIT_POSITIONAL_SLOTS=new Map([["append",[ITEM_ID,OPTIONAL_TEXT]],["assurance",[positionalSlot("action","action",true),positionalSlot("kind","string",false),positionalSlot("id","string",false)]],["beads import",[positionalSlot("file","string",false)]],["changelog export",[positionalSlot("file","string",false)]],["claim",[OPTIONAL_ITEM_ID]],["close",[ITEM_ID,OPTIONAL_TEXT]],["close-task",[ITEM_ID,positionalSlot("reason","string",false)]],["comments",[ITEM_ID,OPTIONAL_TEXT]],["completion",[positionalSlot("shell","string",false)]],["config",[positionalSlot("scope","string",false,{polymorphic:true}),positionalSlot("action","action",false),positionalSlot("key","string",false),positionalSlot("value","string",false,{polymorphic:true})]],["copy",[ITEM_ID]],["create",[positionalSlot("type-or-title","string",false,{polymorphic:true}),positionalSlot("title","string",false)]],["delete",[ITEM_ID]],["deps",[ITEM_ID]],["docs",[ITEM_ID]],["event",[positionalSlot("title","string",true)]],["files",[ITEM_ID]],["files discover",[ITEM_ID]],["files lookup",[positionalSlot("paths","string",true,{variadic:true})]],["focus",[OPTIONAL_ITEM_ID]],["get",[ITEM_ID]],["graph",[positionalSlot("subcommand","action",true),OPTIONAL_ITEM_ID,positionalSlot("target","item_id",false)]],["guide",[positionalSlot("topic","string",false)]],["history",[ITEM_ID]],["history-compact",[OPTIONAL_ITEM_ID]],["history-redact",[ITEM_ID]],["history-repair",[OPTIONAL_ITEM_ID]],["init",[positionalSlot("prefix-or-path","string",false,{polymorphic:true})]],["item complete",[ITEM_ID,positionalSlot("reason","string",false)]],["item reopen",[ITEM_ID,positionalSlot("reason","string",true)]],["learnings",[ITEM_ID,OPTIONAL_TEXT]],["meet",[positionalSlot("title","string",true)]],["merge",[positionalSlot("subcommand","action",true),positionalSlot("artifact","string",false),positionalSlot("base","string",false),positionalSlot("ours","string",false),positionalSlot("theirs","string",false)]],["notes",[ITEM_ID,OPTIONAL_TEXT]],["package",[positionalSlot("target","string",false,{polymorphic:true})]],["package list",[]],["package scaffold",[positionalSlot("target","string",true)]],["package upgrade",[positionalSlot("target","string",false)]],["packages",[positionalSlot("target","string",false,{polymorphic:true})]],["packages list",[]],["packages scaffold",[positionalSlot("target","string",true)]],["packages upgrade",[positionalSlot("target","string",false)]],["pause-task",[ITEM_ID]],["plan",[positionalSlot("subcommand","action",true),positionalSlot("id","item_id",false,{polymorphic:true}),positionalSlot("step","string",false),positionalSlot("new-order","integer",false)]],["profile",[positionalSlot("subcommand","action",true),positionalSlot("name","string",false)]],["release",[ITEM_ID]],["remind",[positionalSlot("title","string",true)]],["restore",[ITEM_ID,positionalSlot("target","string",true)]],["schema",[positionalSlot("subcommand","action",true),positionalSlot("name","string",false)]],["search-advanced",[positionalSlot("keywords","string",true,{variadic:true})]],["search",[positionalSlot("keywords","string",true,{variadic:true})]],["start-task",[ITEM_ID]],["telemetry",[positionalSlot("namespace-or-subcommand","action",false,{polymorphic:true}),positionalSlot("subcommand","action",false)]],["test",[ITEM_ID]],["test-runs-worker",[positionalSlot("runId","string",true)]],["update",[ITEM_ID]],["workspace snapshot",[positionalSlot("action","action",true),positionalSlot("target","string",false)]],...["activate","adopt","deactivate","init","uninstall"].flatMap(action=>["extension","package","packages"].map(root=>[`${root} ${action}`,[positionalSlot("target","string",true)]])),...["describe"].flatMap(action=>["extension","package","packages"].map(root=>[`${root} ${action}`,[positionalSlot("target","string",false)]])),...["install"].flatMap(action=>["extension","package","packages"].map(root=>[`${root} ${action}`,[positionalSlot("targets","string",false,{variadic:true})]])),["vcs abandon",[ITEM_ID]],["vcs create",[positionalSlot("title","string",true)]],["vcs merge",[ITEM_ID]],["vcs propose",[ITEM_ID]],["vcs ref-create",[positionalSlot("name","string",true)]],["vcs show",[ITEM_ID]]]);function normalizePositionalCommandPath(command){return command.trim().toLowerCase().replace(/\s+/gu," ")}function resolvePmCommandPositionalContract(command){const normalized=normalizePositionalCommandPath(command);const direct=PM_COMMAND_POSITIONAL_CONTRACTS.find(contract=>contract.command===normalized);if(direct)return direct;const canonical=resolvePmCommandAlias(normalized)?.canonical;if(!canonical)return void 0;return PM_COMMAND_POSITIONAL_CONTRACTS.find(contract=>contract.command===canonical)}function resolvePmPositionalActionContract(command){const normalized=normalizePositionalCommandPath(command);return POSITIONAL_ACTION_CONTRACTS_BY_SPECIFICITY.find(contract=>contract.command===normalized||normalized.startsWith(`${contract.command} `))}function formatPmPositionalActionFlagTip(acceptedFlags){return`Applicable flags: ${acceptedFlags.length>0?acceptedFlags.join(", "):"none"}.`}function destinationRows(noun,target,disposition,owner,commands){return commands.map(command=>({command,noun,target,disposition,owner}))}const PM_COMMAND_DESTINATION_CONTRACTS=[...destinationRows("item","item","target_noun","pm-pbyu",["item","item complete","item mutate","item reopen"]),...destinationRows("item","item","consolidation","pm-yql1",["append","close-many","close-task","comments","copy","delete","deps","docs","files","learnings","notes","pause-task","start-task","test","update-many"]),...["claim","close","create","get","release","update"].map(command=>({command,noun:"item",target:command,disposition:"keep_as_is",owner:"pm-pbyu",reason:"Permanent high-frequency item operations retain concise root spellings under the accepted hot-path grammar policy."})),...destinationRows("item","item files","target_noun","pm-yql1",["files discover","files lookup","item files discover","item files lookup"]),...destinationRows("item","item test worker","consolidation","pm-lp4j",["test-runs-worker"]),...destinationRows("list","list","target_noun","pm-pfqi",["list"]),...destinationRows("list","list --group-by","consolidation","pm-xkgq",["aggregate"]),...destinationRows("context","context","target_noun","pm-pbyu",["context"]),...destinationRows("context","context","consolidation","pm-kcs4",["ctx","focus","next"]),...destinationRows("context","context next","consolidation","pm-kcs4",["ctx next"]),...destinationRows("context","context focus","consolidation","pm-kcs4",["ctx focus"]),...destinationRows("search","search","target_noun","pm-pbyu",["search"]),...destinationRows("search","search","package_owned","package:search-advanced",["reindex","search-advanced"]),...destinationRows("item","item duplicates","consolidation","pm-fmy9ih",["duplicates"]),...destinationRows("item","item duplicates","package_owned","pm-fmy9ih",["dedupe-audit","dedupe-merge","comments-audit"]),...destinationRows("graph","graph","target_noun","pm-pbyu",["graph"]),...destinationRows("history","history","target_noun","pm-pbyu",["history"]),...destinationRows("history","history attest","target_noun","pm-3z0k",["history attest"]),...destinationRows("history","history attest","consolidation","pm-3z0k",["history-attest"]),...PM_HISTORY_COMMAND_ALIASES.flatMap(({alias,canonical})=>[...destinationRows("history",canonical,"target_noun","pm-tqel",[canonical]),...destinationRows("history",canonical,"consolidation","pm-tqel",[alias])]),...destinationRows("history","history","consolidation","pm-tqel",["events","merge"]),...destinationRows("history","history acknowledge","consolidation","pm-djyvbk",["history-author-acknowledge"]),...destinationRows("history","history","package_owned","package:builtin-vcs-exemplar",["vcs abandon","vcs create","vcs log","vcs merge","vcs propose","vcs ref-create","vcs show"]),...destinationRows("workspace","workspace","target_noun","pm-pbyu",["workspace","workspace position","workspace snapshot","workspace snapshot create","workspace snapshot delete","workspace snapshot inspect","workspace snapshot list","workspace snapshot restore"]),...destinationRows("workspace","workspace init","consolidation","pm-npr3",["init"]),...destinationRows("package","package","target_noun","pm-pbyu",["package","package activate","package adopt","package adopt-all","package catalog","package deactivate","package describe","package doctor","package explore","package init","package install","package list","package manage","package migrate","package reload","package scaffold","package uninstall","package upgrade"]),...destinationRows("package","package","consolidation","pm-tnud",["extension activate","extension adopt","extension adopt-all","extension catalog","extension deactivate","extension describe","extension doctor","extension explore","extension init","extension install","extension manage","extension migrate","extension reload","extension uninstall","packages","packages activate","packages adopt","packages adopt-all","packages catalog","packages deactivate","packages describe","packages doctor","packages explore","packages init","packages install","packages list","packages manage","packages migrate","packages reload","packages scaffold","packages uninstall","packages upgrade"]),...destinationRows("package","package","package_owned","package:beads",["beads import"]),...destinationRows("package","package","package_owned","package:pm-changelog",["changelog export","changelog generate"]),...destinationRows("package","package calendar","package_owned","pm-o3fh",["event","meet","remind"]),...destinationRows("ops","ops","target_noun","pm-6apl",["ops"]),...destinationRows("ops","ops normalize","package_owned","package:pm-governance-audit",["normalize"]),...destinationRows("ops","ops","consolidation","pm-6apl",["eval","gc","health","stats","telemetry","test-all","validate"]),...destinationRows("ops","ops","consolidation","pm-npr3",["config","profile","schema"]),...["assurance",...PM_POSITIONAL_ACTION_CONTRACTS.filter(({parent})=>parent==="assurance").map(({command})=>command)].map(command=>({command,noun:"ops",target:command,disposition:"keep_as_is",owner:"pm-djyvbk",reason:"Assurance manages durable measurement, assertion, gate, and verdict data; retain its established domain surface independently of operational diagnostics."})),...destinationRows("plan","plan","target_noun","pm-pbyu",["plan"]),...destinationRows("plan","plan","target_noun","pm-2tan",PM_POSITIONAL_ACTION_CONTRACTS.filter(({parent})=>parent==="plan").map(({command})=>command)),...destinationRows("contracts","contracts","target_noun","pm-pbyu",["contracts"]),...destinationRows("help","help","target_noun","pm-pbyu",["help"]),...destinationRows("help","help","package_owned","package:builtin-guide-shell",["completion","completion-statuses","completion-tags","completion-types","guide"])].flatMap(entry=>{const alias=PM_RELOCATED_COMMAND_ALIASES.find(candidate=>candidate.alias===entry.command);if(!alias)return[entry];const noun=PM_CLI_GRAMMAR_NOUNS.find(candidate=>candidate===alias.canonical_argv[0])??entry.noun;return[{...entry,noun,target:alias.canonical,owner:alias.owner},{...entry,command:alias.canonical,noun,target:alias.canonical,owner:alias.owner,disposition:entry.disposition==="package_owned"?"package_owned":"target_noun"}]});const PM_COMMAND_POSITIONAL_CONTRACTS=[...new Set(PM_COMMAND_DESTINATION_CONTRACTS.map(({command})=>command))].map(command=>({command,slots:resolvePmPositionalActionContract(command)?.slots??EXPLICIT_POSITIONAL_SLOTS.get(resolvePmHistoryOperation(command))??[]}));const PM_CLI_GRAMMAR_CONTRACT={nouns:PM_CLI_GRAMMAR_NOUNS,shared_verbs:PM_CLI_SHARED_VERBS,scope_before_verb:true,visible_top_level_ceiling:69,ceiling_raise_requires_pm_item:true,positional_shape_budget:21};function verifyExplicitPositionalSlotCensus(explicitCommands,destinationCommands){const destinations=new Set(destinationCommands);return[...new Set(explicitCommands)].filter(command=>!destinations.has(command)).map(command=>({code:"positional_signature_mismatch",command,detail:`Positional signature ${command} has no destination declaration.`}))}function positionalShapeKey(slots){return slots.map(({required,variadic,value_kind:valueKind,polymorphic})=>`${required?"r":"o"}:${variadic?"v":"s"}:${valueKind}:${polymorphic?"p":"m"}`).join("|")}function positionalSignatureKey(slots){return slots.map(({name,required,variadic,value_kind:valueKind,polymorphic})=>`${name}:${required?"r":"o"}:${variadic?"v":"s"}:${valueKind}:${polymorphic?"p":"m"}`).join("|")}function duplicatePositionalSignatureFindings(contracts,surface){const counts=new Map;for(const{command}of contracts){const normalized=normalizePositionalCommandPath(command);counts.set(normalized,(counts.get(normalized)??0)+1)}return[...counts.entries()].filter(([,count])=>count>1).map(([command,count])=>({code:"positional_signature_mismatch",command,detail:`${count} ${surface} positional signatures exist for ${command}; exactly one is required.`}))}function verifyPmCommandPositionalContracts(observed,options={}){const declared=options.declared??PM_COMMAND_POSITIONAL_CONTRACTS;const positionalShapeBudget=options.positionalShapeBudget??PM_CLI_GRAMMAR_CONTRACT.positional_shape_budget;const declaredByCommand=new Map(declared.map(contract=>[normalizePositionalCommandPath(contract.command),contract]));const observedByCommand=new Map(observed.map(contract=>[normalizePositionalCommandPath(contract.command),contract]));const findings=[...duplicatePositionalSignatureFindings(declared,"declared"),...duplicatePositionalSignatureFindings(observed,"observed"),...options.declared===void 0?[...verifyExplicitPositionalSlotCensus(EXPLICIT_POSITIONAL_SLOTS.keys(),PM_COMMAND_DESTINATION_CONTRACTS.map(({command})=>command)),...verifyExplicitPositionalSlotCensus(PM_POSITIONAL_ACTION_CONTRACTS.map(({command})=>command),PM_COMMAND_DESTINATION_CONTRACTS.map(({command})=>command))]:[]];for(const contract of declaredByCommand.values()){const normalizedCommand=normalizePositionalCommandPath(contract.command);const actual=observedByCommand.get(normalizedCommand);if(!actual){findings.push({code:"missing_observed_signature",command:contract.command,detail:`No observed positional signature exists for ${contract.command}.`})}else if(positionalSignatureKey(actual.slots)!==positionalSignatureKey(contract.slots)){findings.push({code:"positional_signature_mismatch",command:contract.command,detail:`Observed positional signature for ${contract.command} differs from its declared SDK contract: observed=${positionalSignatureKey(actual.slots)||"<none>"}; declared=${positionalSignatureKey(contract.slots)||"<none>"}.`})}}for(const contract of observedByCommand.values()){if(!declaredByCommand.has(normalizePositionalCommandPath(contract.command))){findings.push({code:"stale_observed_signature",command:contract.command,detail:`Observed positional signature ${contract.command} has no declaration.`})}}const positionalShapeCount=new Set(declared.map(({slots})=>positionalShapeKey(slots))).size;if(positionalShapeCount>positionalShapeBudget){findings.push({code:"positional_shape_budget_exceeded",command:"*",detail:`Distinct positional shape count ${positionalShapeCount} exceeds budget ${positionalShapeBudget}.`})}findings.sort((left,right)=>left.command!==right.command?left.command.localeCompare(right.command):left.code.localeCompare(right.code));return{ok:findings.length===0,declared_command_count:declared.length,observed_command_count:observed.length,positional_shape_count:positionalShapeCount,positional_shape_budget:positionalShapeBudget,findings}}function validateCommandDestinations(commands,destinationsByCommand,nounSet){return commands.flatMap(command=>{const destinations=destinationsByCommand.get(command)??[];if(destinations.length===0){const separatorIndex=command.indexOf(" ");const root=separatorIndex===-1?command:command.slice(0,separatorIndex);return[{code:"missing_destination",spelling:command,message:`Command \`${command}\` has no destination census row.`,nearest_target:nounSet.has(root)?root:`ops ${command}`}]}const duplicateFinding=destinations.length>1?[{code:"duplicate_destination",spelling:command,message:`Command \`${command}\` has ${destinations.length} destination rows.`,nearest_target:destinations[0].target}]:[];return destinations.reduce((findings,destination)=>{if(destination.disposition==="keep_as_is"&&(destination.reason?.trim().length??0)===0){findings.push({code:"missing_destination",spelling:command,message:`Command \`${command}\` is kept as-is without a documented reason.`,nearest_target:destination.target})}if(!nounSet.has(destination.noun)){findings.push({code:"unknown_noun",spelling:command,message:`Command \`${command}\` names undeclared noun \`${destination.noun}\`.`,nearest_target:destination.target})}return findings},duplicateFinding)})}function validateDestinationCensus(commandSet,destinations){return destinations.filter(destination=>destination.disposition!=="package_owned"&&!commandSet.has(destination.command)).map(destination=>({code:"stale_destination",spelling:destination.command,message:`Destination row \`${destination.command}\` is absent from live contracts.`,nearest_target:destination.target}))}function validateAliasTargets(aliases,commandSet){return aliases.filter(alias=>!commandSet.has(alias.canonical)).map(alias=>({code:"alias_target_missing",spelling:alias.alias,message:`Alias \`${alias.alias}\` targets missing canonical command \`${alias.canonical}\`.`,nearest_target:alias.canonical_argv.join(" ")}))}function verifyPmCliGrammar(commands,aliases=[],destinations=PM_COMMAND_DESTINATION_CONTRACTS){const normalizedCommands=[...new Set(commands.map(command=>command.trim()))].filter(command=>command.length>0).sort((left,right)=>left.localeCompare(right));const commandSet=new Set(normalizedCommands);const nounSet=new Set(PM_CLI_GRAMMAR_NOUNS);const destinationsByCommand=new Map;for(const destination of destinations){const entries=destinationsByCommand.get(destination.command)??[];entries.push(destination);destinationsByCommand.set(destination.command,entries)}const findings=[...validateCommandDestinations(normalizedCommands,destinationsByCommand,nounSet),...validateDestinationCensus(commandSet,destinations),...validateAliasTargets(aliases.filter(alias=>commandSet.has(alias.alias)||!(destinationsByCommand.get(alias.canonical)??[]).some(destination=>destination.disposition==="package_owned")),commandSet)];const hiddenAliasNames=new Set(aliases.filter(alias=>alias.hidden).map(alias=>alias.alias));const visibleTopLevelCount=new Set(normalizedCommands.filter(command=>!command.includes(" ")&&!hiddenAliasNames.has(command)&&!(destinationsByCommand.get(command)??[]).some(destination=>destination.disposition==="package_owned"))).size;if(visibleTopLevelCount>PM_CLI_GRAMMAR_CONTRACT.visible_top_level_ceiling){findings.push({code:"visible_surface_ceiling_exceeded",spelling:String(visibleTopLevelCount),message:`Visible non-package top-level command count ${visibleTopLevelCount} exceeds ceiling ${PM_CLI_GRAMMAR_CONTRACT.visible_top_level_ceiling}.`,nearest_target:"Declare the noun placement and tracked waiver before raising the ceiling."})}return{ok:findings.length===0,command_count:normalizedCommands.length,destination_count:destinations.length,hidden_alias_count:aliases.filter(alias=>alias.hidden).length,visible_top_level_count:visibleTopLevelCount,visible_top_level_ceiling:PM_CLI_GRAMMAR_CONTRACT.visible_top_level_ceiling,findings}}export{PM_CLI_GRAMMAR_CONTRACT,PM_CLI_GRAMMAR_NOUNS,PM_CLI_SHARED_VERBS,PM_COMMAND_DESTINATION_CONTRACTS,PM_COMMAND_POSITIONAL_CONTRACTS,PM_POSITIONAL_ACTION_CONTRACTS,formatPmPositionalActionFlagTip,positionalShapeKey,positionalSignatureKey,resolvePmCommandPositionalContract,resolvePmPositionalActionContract,verifyExplicitPositionalSlotCensus,verifyPmCliGrammar,verifyPmCommandPositionalContracts};
|
|
2
2
|
//# sourceMappingURL=grammar-contracts.js.map
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @module cli/
|
|
2
|
+
* @module sdk/cli-contracts/runtime-contracts
|
|
3
3
|
*
|
|
4
|
-
*
|
|
4
|
+
* Assembles executable core and package contracts into bounded discovery
|
|
5
|
+
* projections shared by CLI, SDK, and MCP consumers.
|
|
5
6
|
*/
|
|
6
7
|
import { type GlobalOptions, type ExtensionRegistrationRegistry, type RegisteredExtensionCommandDefinition, type RegisteredExtensionFlagDefinitions, type RuntimeFieldRegistry, readSettings } from "../runtime-primitives.js";
|
|
7
8
|
import { PM_HISTORY_OPERATION_CONTRACT } from "../../core/history/operation-contract.js";
|
|
@@ -252,6 +253,8 @@ interface RuntimeExtensionActionProbe {
|
|
|
252
253
|
};
|
|
253
254
|
}
|
|
254
255
|
interface ExtensionCommandContract {
|
|
256
|
+
/** Package-declared discovery tier, retained for full and scoped inspection. */
|
|
257
|
+
tier?: PmCommandVisibilityTier;
|
|
255
258
|
command: string;
|
|
256
259
|
action: string;
|
|
257
260
|
source: {
|
|
@@ -304,6 +307,7 @@ declare function collectExtensionFlagContractsByCommand(registrations: Registere
|
|
|
304
307
|
name: string;
|
|
305
308
|
}>;
|
|
306
309
|
}>;
|
|
310
|
+
/** Preserve registered package metadata and combine handler, argument, and flag contributions by command path. */
|
|
307
311
|
declare function collectExtensionCommandContracts(runtimeProbe: RuntimeExtensionActionProbe): ExtensionCommandContract[];
|
|
308
312
|
declare function extensionSchemaPropertyNameFromFlag(flag: CliFlagContract): string | null;
|
|
309
313
|
declare function buildExtensionActionSchemaBranch(contract: ExtensionCommandContract): Record<string, unknown>;
|
|
@@ -339,7 +343,7 @@ declare function buildCommandSummarySurface(commands: readonly string[], extensi
|
|
|
339
343
|
}): CommandSummarySurface[];
|
|
340
344
|
declare function buildCommandOutputContracts(commands: readonly string[]): NonNullable<ContractsResult["command_output_contracts"]>;
|
|
341
345
|
declare function buildCommandExitContractGroups(commands: readonly string[]): NonNullable<ContractsResult["command_exit_contracts"]>["command_sets"];
|
|
342
|
-
/**
|
|
346
|
+
/** Assemble the requested command or action projection from the active SDK registry without exposing internal paths in default discovery. */
|
|
343
347
|
export declare function runContracts(options: ContractsCommandOptions, global: GlobalOptions): Promise<ContractsResult>;
|
|
344
348
|
/** Public contract for test only contracts command, shared by SDK and presentation-layer consumers. */
|
|
345
349
|
export declare const _testOnlyContractsCommand: {
|
|
@@ -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]="022370d5-0fa8-5aa2-a148-cdb147657da1")}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,{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){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:resolvePmCommandVisibilityTier(canonicalSummaryCommand(command)),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){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),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||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 isCommandDiscoverable(selection,command){return selection.fullOutput||selection.selectedCommand!==void 0||selection.selectedAction!==void 0||resolvePmCommandVisibilityTier(command)!=="internal"}function resolveOutputCommands(selection,commands){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))}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))}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);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);const actionContext=resolveContractsActionContext(selection,runtime);const schemaContext=resolveContractsSchemaContext(selection,runtime,actionContext);const commands=resolveContractsCommands(selection,actionContext);const outputCommands=resolveOutputCommands(selection,commands);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)));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}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]="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};
|
|
2
2
|
//# sourceMappingURL=runtime-contracts.js.map
|