@unbrained/pm-cli 2026.10.20 → 2026.10.22
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 +1 -1
- package/CHANGELOG.md +142 -77
- package/dist/cli/error-guidance.d.ts +8 -0
- package/dist/cli/error-guidance.js +2 -2
- package/dist/cli/main.js +1 -1
- package/dist/cli/register-list-query.js +2 -2
- package/dist/cli/register-operations.js +1 -1
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/{chunk-QMZ73FCW.js → chunk-2B5HAZFK.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-35ISFIPC.js +113 -0
- package/dist/cli-bundle/chunks/chunk-4D25HF3V.js +2 -0
- package/dist/cli-bundle/chunks/chunk-5LSN7K4N.js +2 -0
- package/dist/cli-bundle/chunks/chunk-7OTYULIJ.js +30 -0
- package/dist/cli-bundle/chunks/{chunk-GHJOMRSF.js → chunk-AOAQDCXX.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-ZA3XXHEE.js → chunk-BAIVTLJM.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-LS55VKRK.js → chunk-C37RDYZI.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-YT2Z3JPC.js → chunk-E3JC3WQL.js} +47 -47
- package/dist/cli-bundle/chunks/{chunk-YECCKB4E.js → chunk-GWIGZDRS.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-YTHI5DTH.js → chunk-HC2DCGFA.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-IB7UB5TE.js +2 -0
- package/dist/cli-bundle/chunks/chunk-J444ZX23.js +126 -0
- package/dist/cli-bundle/chunks/{chunk-VLJLWZBO.js → chunk-LIC5EUQS.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-KU4Q3MSI.js → chunk-MV3KYY2A.js} +6 -6
- package/dist/cli-bundle/chunks/chunk-O67N62DT.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-TZU6U5ZE.js → chunk-PCPOTFJP.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-TNU3XVPC.js +20 -0
- package/dist/cli-bundle/chunks/{chunk-7ZOIZ2AZ.js → chunk-URV4VHQ4.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-YW6SIKYP.js → chunk-UYYTV2TX.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-VO3KDIU7.js +9 -0
- package/dist/cli-bundle/chunks/{indexed-receipt-blobs-U7VGKIYC.js → indexed-receipt-blobs-L3BOTMZN.js} +2 -2
- package/dist/cli-bundle/chunks/mutation-admission-TATOFEXF.js +2 -0
- package/dist/cli-bundle/chunks/{register-list-query-NNDV6F6I.js → register-list-query-GULR2IYO.js} +5 -5
- package/dist/cli-bundle/chunks/{register-mutation-3GCBSNQS.js → register-mutation-HLSQ4WVW.js} +4 -4
- package/dist/cli-bundle/chunks/register-operations-FE3GGA7O.js +2 -0
- package/dist/cli-bundle/chunks/register-setup-XUIKAIZA.js +2 -0
- package/dist/cli-bundle/chunks/{settlement-hook-CLRGA6O7.js → settlement-hook-UVFYSBMU.js} +2 -2
- package/dist/cli-bundle/chunks/stage-QCPZBZRC.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-25L3L2PF.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-25NQRZ7J.js +8 -0
- package/dist/cli-bundle/focused-chunks/chunk-2GFTVXKZ.js +8 -0
- package/dist/cli-bundle/focused-chunks/{chunk-HUZAXSIJ.js → chunk-3LWH2RJC.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-46HBJC6J.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-A52W6GLA.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-CB7TSZ7P.js +3 -0
- package/dist/cli-bundle/focused-chunks/{chunk-VLSER3XW.js → chunk-CX5FNEFC.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-DVNUHTVK.js +9 -0
- package/dist/cli-bundle/focused-chunks/{chunk-LJPUJ2KK.js → chunk-EHPRSWJE.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-GC4VMLXL.js +20 -0
- package/dist/cli-bundle/focused-chunks/chunk-GHQVM6K6.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-KKRFSI2N.js → chunk-GVKYTDOH.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-NI6NS44Q.js → chunk-KM77WU5U.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-QGDKWULS.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-QWKCQ5PW.js +91 -0
- package/dist/cli-bundle/focused-chunks/chunk-SOVXHW6Z.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-SVOOGGAK.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-SXVJRLLP.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-E4II2D2B.js → chunk-TMN3RAXZ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-F7FD25TG.js → chunk-UQ5JPBY2.js} +11 -11
- package/dist/cli-bundle/focused-chunks/chunk-UUPJ6OZL.js +26 -0
- package/dist/cli-bundle/focused-chunks/chunk-VYAZND5Q.js +78 -0
- package/dist/cli-bundle/focused-chunks/chunk-W2CND3BD.js +65 -0
- package/dist/cli-bundle/focused-chunks/{chunk-ZGEK57KD.js → chunk-XX5JQCLF.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-H2G6CCGO.js → indexed-receipt-blobs-AAQOKO5B.js} +2 -2
- package/dist/cli-bundle/focused-chunks/mutation-admission-TBKR4KRM.js +2 -0
- package/dist/cli-bundle/focused-chunks/{settlement-hook-5SNBBT7C.js → settlement-hook-MNCHFCAX.js} +2 -2
- package/dist/cli-bundle/focused-chunks/stage-RM6MJIMT.js +2 -0
- package/dist/cli-bundle/main.js +21 -21
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +2 -2
- package/dist/cli-bundle/sdk-core.js +23 -23
- 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 +58 -57
- 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 +7 -7
- package/dist/core/item/actionability.js +1 -1
- package/dist/core/lock/lock-gc.d.ts +12 -5
- package/dist/core/lock/lock-gc.js +1 -1
- package/dist/core/lock/lock-owner.d.ts +33 -0
- package/dist/core/lock/lock-owner.js +2 -0
- package/dist/core/lock/lock.d.ts +11 -22
- package/dist/core/lock/lock.js +4 -3
- package/dist/core/output/output.js +3 -3
- package/dist/core/shared/errors.d.ts +2 -0
- package/dist/core/shared/errors.js +1 -1
- package/dist/mcp/server.d.ts +2 -2
- package/dist/mcp/server.js +1 -1
- package/dist/sdk/agent/command-recovery.d.ts +2 -0
- package/dist/sdk/agent/command-recovery.js +1 -1
- package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
- package/dist/sdk/cli-contracts/tool-option-contracts.d.ts +6 -0
- package/dist/sdk/cli-contracts/tool-option-contracts.js +1 -1
- package/dist/sdk/cli-contracts/tool-schema.js +1 -1
- package/dist/sdk/context-intent-contracts.d.ts +13 -0
- package/dist/sdk/context-intent-contracts.js +1 -1
- package/dist/sdk/contracts.d.ts +1 -1
- package/dist/sdk/contracts.js +1 -1
- package/dist/sdk/core.d.ts +2 -2
- package/dist/sdk/core.js +1 -1
- package/dist/sdk/define.d.ts +15 -16
- package/dist/sdk/define.js +1 -1
- package/dist/sdk/dependencies.js +1 -1
- package/dist/sdk/extension-command-context.js +2 -2
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
- package/dist/sdk/governance/assurance-action.js +1 -1
- package/dist/sdk/governance/assurance.js +1 -1
- package/dist/sdk/governance/health.js +2 -2
- package/dist/sdk/merge/install.js +2 -2
- package/dist/sdk/output/list-envelope.js +1 -1
- package/dist/sdk/pagination.d.ts +3 -3
- package/dist/sdk/pagination.js +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/query/context.d.ts +5 -0
- package/dist/sdk/query/context.js +2 -2
- package/dist/sdk/query/list.d.ts +2 -0
- package/dist/sdk/query/list.js +1 -1
- package/dist/sdk/query/projection-contracts.d.ts +1 -1
- package/dist/sdk/query/projection-contracts.js +1 -1
- package/dist/sdk/read-output/session-result.d.ts +39 -0
- package/dist/sdk/read-output/session-result.js +2 -0
- package/dist/sdk/read-output-contracts.d.ts +18 -5
- package/dist/sdk/read-output-contracts.js +1 -1
- package/dist/sdk/read-output-session.d.ts +2 -0
- package/dist/sdk/read-output-session.js +1 -1
- package/dist/sdk/relationship-context.js +1 -1
- package/dist/sdk/runtime/mutation-admission.d.ts +2 -0
- package/dist/sdk/runtime/mutation-admission.js +2 -0
- package/dist/sdk/runtime-input.d.ts +2 -0
- package/dist/sdk/runtime-input.js +1 -1
- package/dist/sdk/runtime-primitives.d.ts +6 -0
- package/dist/sdk/runtime-primitives.js +1 -1
- package/dist/sdk/runtime.d.ts +10 -8
- package/dist/sdk/runtime.js +1 -1
- package/dist/sdk/test/execution.d.ts +1 -0
- package/dist/sdk/test/execution.js +2 -2
- package/dist/sdk/workspace.d.ts +3 -1
- package/dist/sdk/workspace.js +8 -5
- package/docs/AGENT_RUNTIME_PRIMITIVES.md +9 -0
- package/docs/ASSURANCE.md +17 -2
- package/docs/COMMANDS.md +17 -3
- package/docs/CONFIGURATION.md +38 -0
- package/docs/CONTEXT_RELEVANCE.md +15 -0
- package/docs/DEVELOPMENT_DEPENDENCY_SECURITY.md +56 -3
- package/docs/MCP_OPTION_CONFORMANCE.md +27 -1
- package/docs/MERGE_SAFETY.md +8 -0
- package/docs/READ_OUTPUT_CONTRACTS.md +79 -0
- package/docs/RELATIONSHIP_GRAPH.md +15 -0
- package/docs/RELEASING.md +8 -0
- package/docs/SDK.md +104 -7
- package/docs/TESTING.md +23 -0
- package/docs/agent-task-token-baseline.json +1 -1
- package/marketplace.json +1 -1
- package/package.json +1 -1
- 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-claude/package.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/plugins/pm-codex/package.json +1 -1
- package/plugins/pm-codex/plugin.json +1 -1
- package/runtime-dependencies.json +1 -1
- package/dist/cli-bundle/chunks/chunk-2GGGOD7P.js +0 -30
- package/dist/cli-bundle/chunks/chunk-7NHA5K77.js +0 -126
- package/dist/cli-bundle/chunks/chunk-PNPE2OVJ.js +0 -112
- package/dist/cli-bundle/chunks/chunk-PTL3TBT6.js +0 -20
- package/dist/cli-bundle/chunks/chunk-QETMESEB.js +0 -6
- package/dist/cli-bundle/chunks/chunk-QQYCB2LO.js +0 -2
- package/dist/cli-bundle/chunks/register-operations-YKDGNKUL.js +0 -2
- package/dist/cli-bundle/chunks/register-setup-AOUZQQWB.js +0 -2
- package/dist/cli-bundle/chunks/stage-6QXYRMSU.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-37SU7BZI.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-6IU7BESB.js +0 -65
- package/dist/cli-bundle/focused-chunks/chunk-AS3MOBO3.js +0 -25
- package/dist/cli-bundle/focused-chunks/chunk-AW35RDKA.js +0 -78
- package/dist/cli-bundle/focused-chunks/chunk-GYHZ7W6O.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-H5Q2HUU6.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-J6EYUGAR.js +0 -6
- package/dist/cli-bundle/focused-chunks/chunk-JEXZEIAX.js +0 -91
- package/dist/cli-bundle/focused-chunks/chunk-KDGUIIRU.js +0 -20
- package/dist/cli-bundle/focused-chunks/chunk-MQ42BFGX.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-VAYS754X.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-VS6VTWTZ.js +0 -8
- package/dist/cli-bundle/focused-chunks/stage-EMTISXR7.js +0 -2
package/dist/mcp/server.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="fe904212-6429-55c9-9d7b-39d7e2850fed")}catch{}})();import{realpathSync}from"node:fs";import{readFile}from"node:fs/promises";import path from"node:path";import readline from"node:readline";import{fileURLToPath}from"node:url";import{resolvePmCliVersion,EXIT_CODE,PmCliError,decodeHtmlEntitiesInOptions,levenshteinDistanceWithinLimit,asRecordClone,createSerialQueue,evaluateMutationGuard,getSettingsPath,isMutationAction,pathExists,readSettings,runWithHarnessDetectionSignals,runWithWorkspaceHarnessSignalDescriptors,boundAgentEpisodeIdentity}from"../sdk/runtime-primitives.js";import{pmToolActionNestedOptionKeys}from"../sdk/cli-contracts/tool-schema.js";import{readRequiredString,runAction,runWithActiveExtensions}from"../sdk/runtime.js";import{NARROW_TOOL_ACTIONS,TOOLS}from"./tool-definitions.js";import{normalizeWorkspaceToolArguments,resolveMcpToolAccess,resolveMcpToolSurface}from"./runtime-capabilities.js";import{PM_MCP_PROMPT_CONTRACTS,PM_MCP_RESOURCE_CONTRACTS}from"../sdk/agent-capability-contracts.js";import{PM_MCP_ENTRY_TOOL_NAMES,PM_MCP_PROGRESSIVE_DISCOVERY_EXTENSION,PM_MCP_PROGRESSIVE_DISCOVERY_SERVER_CAPABILITY,discoverPmTools,parsePmToolDiscoveryOptions}from"../sdk/mcp/discovery.js";import{commitItemMutations}from"../sdk/item-transaction.js";import{isRuntimeRecord,markMcpMutationTransportInput}from"../sdk/runtime-input.js";import{attachOutputTokenAccounting}from"../sdk/output-token-accounting.js";import{createReproducibleProcessRunner,runWithReproducibleProcessEnvironment}from"../sdk/reproducibility/process.js";import{parseAtomicMutationControls}from"../sdk/structured-mutations.js";import{planItemMutationDocument,previewItemMutationDocument}from"../sdk/lifecycle/structured-mutation-plan.js";import{resolveAuthor,resolvePmRoot,resolveWorkspaceRoot}from"../sdk/runtime-primitives.js";import{PM_MCP_ERROR_CODES,PM_MCP_META_KEYS,PM_MCP_PROTOCOL_VERSION,PmMcpProtocolError,attachMcpServerInfo,buildMcpCompleteResult,buildMcpDiscoverResult,hasMcpClientExtension,isMcpRecord,resolveMcpRequestContext}from"../sdk/mcp/protocol.js";import{PmMcpInputRequiredError,buildMcpInputRequiredResult,parseMcpInputResponses,validateMcpJsonSchema,withMcpCachePolicy}from"../sdk/mcp/interactions.js";import{PM_MCP_TASKS_EXTENSION,createMcpTaskStore}from"../sdk/mcp/tasks.js";import{PmMcpSubscriptionRegistry}from"../sdk/mcp/subscriptions.js";import{extractMcpTraceContext,runWithMcpTraceContext}from"../sdk/mcp/authorization.js";import{LegacyMcpAdapter}from"./legacy-adapter.js";import{PM_MCP_APP_CONTRACTS,PM_MCP_APP_MIME_TYPE,PM_MCP_APPS_EXTENSION,PM_MCP_APPS_SERVER_CAPABILITY,decoratePmMcpToolsWithApps,findPmMcpAppByUri,hasPmMcpAppsCapability,renderPmMcpAppHtml}from"../sdk/mcp/apps.js";import{PM_MCP_SKILLS_EXTENSION,PM_MCP_SKILLS_SERVER_CAPABILITY,PmMcpSkillRegistry,assertPmMcpSkillsCapability}from"../sdk/mcp/skills.js";function runMcpAction(args){return runAction(markMcpMutationTransportInput(args))}const PM_PACKAGE_ROOT_ENV="PM_CLI_PACKAGE_ROOT";function resolvePmPackageRoot(){return fileURLToPath(new URL("../..",import.meta.url))}(typeof process.env[PM_PACKAGE_ROOT_ENV]!="string"||process.env[PM_PACKAGE_ROOT_ENV]?.trim().length===0)&&(process.env[PM_PACKAGE_ROOT_ENV]=resolvePmPackageRoot());const PM_MCP_SERVER_VERSION=resolvePmCliVersion(import.meta.url,["../.."])??"0.0.0",PM_MCP_SERVER_INFO={name:"pm-mcp",version:PM_MCP_SERVER_VERSION,description:"Stateless project-context management through pm SDK contracts.",websiteUrl:"https://github.com/unbraind/pm-cli"},PM_MCP_SERVER_CAPABILITIES={prompts:{listChanged:!0},resources:{listChanged:!0,subscribe:!0},tools:{listChanged:!0},extensions:{[PM_MCP_TASKS_EXTENSION]:{},[PM_MCP_APPS_EXTENSION]:PM_MCP_APPS_SERVER_CAPABILITY,[PM_MCP_SKILLS_EXTENSION]:PM_MCP_SKILLS_SERVER_CAPABILITY,[PM_MCP_PROGRESSIVE_DISCOVERY_EXTENSION]:PM_MCP_PROGRESSIVE_DISCOVERY_SERVER_CAPABILITY}},PM_MCP_SUBSCRIPTIONS=new Map;function createMcpSubscriptionRegistry(){return new PmMcpSubscriptionRegistry({capabilities:PM_MCP_SERVER_CAPABILITIES,serverInfo:PM_MCP_SERVER_INFO})}function pruneClosedMcpSubscriptionRegistries(){for(const[key,subscription]of PM_MCP_SUBSCRIPTIONS)subscription.registry.size===0&&PM_MCP_SUBSCRIPTIONS.delete(key)}const PM_MCP_CACHE_POLICIES={prompts:{ttlMs:6e4,cacheScope:"public"},resource:{ttlMs:0,cacheScope:"private"},resources:{ttlMs:6e4,cacheScope:"public"},tools:{ttlMs:3e4,cacheScope:"private"}},PM_MCP_DIRECT_TASK_TOOLS=new Set(["pm_graph","pm_health","pm_validate"]),PM_MCP_RUN_TASK_ACTIONS=new Set(["graph","health","import","reindex","test-all","validate"]),PM_MCP_SKILL_METHODS=new Set(["skills/list","skills/get","resources/directory/read"]),PM_MCP_INSTRUCTIONS="You have access to native pm CLI tools for git-based project management. When progressive discovery is negotiated, use pm_discover to expand the small entry catalog by intent and request schemas only when needed. Use pm_next to pick the next actionable item, or pm_context or pm_search before creating new work. Prefer narrow tools (pm_next, pm_context, pm_list, pm_get, pm_search, pm_events, pm_create, pm_mutate, pm_copy, pm_focus, pm_update, pm_append, pm_claim, pm_release, pm_close, pm_comments, pm_files, pm_docs, pm_notes, pm_learnings, pm_deps, pm_graph, pm_test, pm_validate, pm_health, pm_contracts, pm_schema, pm_profile, pm_config, pm_plan) over pm_run when they cover the operation. Use pm_plan for agent harness Plan workflows: it provides Codex/Claude/Cursor-style planning with durable steps, dependencies, decisions, discoveries, validation, and materialization. Use pm_schema and pm_config for workspace configuration: pm_schema manages custom item types/statuses and pm_config reads or writes settings keys. Use pm_run with an explicit action for active package-owned operations, plus activity, aggregate, history, stats, test-all, and gc. Use history-redact for audited history-stream redaction workflows, history-repair to re-anchor a drifted history chain, and history-compact to checkpoint/prune long history streams while preserving replay integrity. Agent harness and model provenance are detected automatically; pass author only for an intentional identity override. Do not pass path during real repository tracking \u2014 only pass path for sandbox or test runs.";function declaredToolKeys(tools=TOOLS){return new Map(tools.map(tool=>{const properties=tool.inputSchema.properties??{};return[tool.name,Object.keys(properties)]}))}function nearestDeclaredKey(unexpected,declared){const limit=Math.max(1,Math.min(3,Math.floor(unexpected.length/4)+1));let best;for(const candidate of declared){const distance=levenshteinDistanceWithinLimit(unexpected,candidate,limit);distance!==null&&(best===void 0||distance<best.distance)&&(best={key:candidate,distance})}return best?.key}const UNEXPECTED_KEY_WARNING_EXEMPT_TOOLS=new Set(["pm_run"]),MCP_RETRY_ARGUMENT_KEYS=new Set(["inputResponses","requestState"]);function resolveMcpDiscoveryCursorIntegrityKey(){const configuredKey=process.env.PM_MCP_DISCOVERY_CURSOR_KEY;if(configuredKey===void 0)return;const key=Buffer.from(configuredKey,"utf8");if(key.byteLength<32)throw new PmCliError("PM_MCP_DISCOVERY_CURSOR_KEY must contain at least 32 UTF-8 bytes.",64);return key}function detectUnexpectedTopLevelKeys(toolName,args,toolDeclaredKeys=declaredToolKeys()){if(typeof args!="object"||args===null||Array.isArray(args))return[];if(UNEXPECTED_KEY_WARNING_EXEMPT_TOOLS.has(toolName))return[];const declared=toolDeclaredKeys.get(toolName);if(declared===void 0)return[];const declaredSet=new Set([...declared,...MCP_RETRY_ARGUMENT_KEYS]),warnings=[];for(const key of Object.keys(args)){if(declaredSet.has(key))continue;const suggestion=nearestDeclaredKey(key,declared);warnings.push(suggestion!==void 0?`Unexpected top-level argument "${key}" for ${toolName} (did you mean "${suggestion}"?). It is not declared and may be ignored; declared arguments are: ${declared.join(", ")}.`:`Unexpected top-level argument "${key}" for ${toolName}. It is not declared and may be ignored; declared arguments are: ${declared.join(", ")}.`)}return warnings}const HANDLERS={pm_run:args=>runMcpAction(args),pm_discover:async args=>{const surface=await resolveMcpToolSurface(TOOLS,args),cursorIntegrityKey=resolveMcpDiscoveryCursorIntegrityKey(),discoveryOptions=parsePmToolDiscoveryOptions(args);return discoverPmTools(surface.tools.map(tool=>({name:tool.name,description:tool.description,inputSchema:tool.inputSchema,authorized:!0,signals:{freshness:1,usage:PM_MCP_ENTRY_TOOL_NAMES.includes(tool.name)?1:0}})),{...discoveryOptions,profile:surface.profile,...cursorIntegrityKey===void 0?{}:{cursorIntegrityKey}})},pm_mutate:async args=>{if(!Array.isArray(args.mutations)||args.mutations.length===0)throw new PmCliError("pm_mutate requires a non-empty mutations array.",EXIT_CODE.USAGE);const explicitTransactionId=args.transactionId===void 0?void 0:readRequiredString(args,"transactionId"),upsertKey=args.upsertKey===void 0?void 0:readRequiredString(args,"upsertKey"),controls=parseAtomicMutationControls(args),cwd=typeof args.cwd=="string"?args.cwd:process.cwd(),pmRoot=resolvePmRoot(cwd,typeof args.path=="string"?args.path:void 0),extensionScope={cwd:typeof args.cwd=="string"?args.cwd:void 0,path:pmRoot,noExtensions:args.noExtensions===!0},plan=await runWithActiveExtensions(extensionScope,()=>planItemMutationDocument({pmRoot,input:JSON.stringify({schema_version:1,mutations:args.mutations}),...explicitTransactionId===void 0?{}:{transactionId:explicitTransactionId},...upsertKey===void 0?{}:{upsertKey}})),{mutations,references,rows}=plan,transactionId=plan.transaction_id,receipt={transaction_id:transactionId,transaction_id_source:plan.transaction_id_source,...plan.upsert_key===void 0?{}:{upsert_key:plan.upsert_key}};if(args.dryRun===!0){const preview=await runWithActiveExtensions(extensionScope,()=>previewItemMutationDocument({pmRoot,author:resolveAuthor(typeof args.author=="string"?args.author:void 0,"unknown"),plan}));return{...receipt,dry_run:!0,validation:preview.validation,mutation_count:mutations.length,mutations,references,rows:preview.rows}}const result=await runWithActiveExtensions(extensionScope,()=>commitItemMutations({pmRoot,transactionId,author:resolveAuthor(typeof args.author=="string"?args.author:void 0,"unknown"),mutations,...controls}));return{...Object.fromEntries(Object.entries(result).filter(([key])=>key!=="transactionId")),...receipt,mutation_count:mutations.length,references,rows}},...Object.fromEntries(Object.entries(NARROW_TOOL_ACTIONS).map(([tool,action])=>[tool,args=>runMcpAction({...args,action})]))};function resolveInvokedAction(toolName,args){return toolName==="pm_run"?typeof args.action=="string"?args.action:void 0:NARROW_TOOL_ACTIONS[toolName]}async function collectMutationGuardWarnings(toolName,action,args){if(toolName!=="pm_mutate"&&!isMutationAction(action??""))return[];const cwd=typeof args.cwd=="string"?args.cwd:process.cwd(),pmRoot=resolvePmRoot(cwd,typeof args.path=="string"?args.path:void 0);if(!await pathExists(getSettingsPath(pmRoot)))return[];const settings=await readSettings(pmRoot),nestedOptions=typeof args.options=="object"&&args.options!==null&&!Array.isArray(args.options)?args.options:{};return evaluateMutationGuard({author:resolveAuthor(typeof args.author=="string"?args.author:typeof nestedOptions.author=="string"?nestedOptions.author:void 0,settings.author_default),payload:Object.fromEntries(Object.entries(args).filter(([key])=>key!=="cwd"&&key!=="path")),settings:settings.mutation_guard,force:args.force===!0||nestedOptions.force===!0}).warnings}function detectUnexpectedOptionKeys(toolName,action,args){const options=args.options;if(action===void 0||typeof options!="object"||options===null||Array.isArray(options))return[];const declared=pmToolActionNestedOptionKeys(action);if(declared===void 0)return[];const declaredSet=new Set(declared),warnings=[];for(const key of Object.keys(options)){if(declaredSet.has(key))continue;const suggestion=nearestDeclaredKey(key,declared);warnings.push(suggestion!==void 0?`Unknown option "${key}" for ${toolName} action "${action}" (did you mean "${suggestion}"?). The ${action} contract does not read it, so it has no effect; declared keys are: ${declared.join(", ")}.`:`Unknown option "${key}" for ${toolName} action "${action}". The ${action} contract does not read it, so it has no effect; declared keys are: ${declared.join(", ")}.`)}return warnings}function resultContent(result,warnings,tokenAccounting=!1,canonicalStructuredResult=!1){const effectiveResult=tokenAccounting?attachOutputTokenAccounting(result,value=>JSON.stringify(value,null,2)):result,structuredContent=warnings!==void 0&&warnings.length>0?{result:effectiveResult,warnings}:{result:effectiveResult};return{content:[{type:"text",text:canonicalStructuredResult?"Canonical result: structuredContent.result":JSON.stringify(effectiveResult,null,2)}],structuredContent}}function errorContent(error,canonicalStructuredResult=!1){const code=error instanceof PmCliError?error.exitCode:1,message=error instanceof Error?error.message:String(error),details=error instanceof PmCliError?error.context:void 0;return{isError:!0,content:[{type:"text",text:canonicalStructuredResult?"Canonical error: structuredContent":JSON.stringify({error:message,code,details},null,2)}],structuredContent:{result:null,error:message,code,details}}}function boundMcpClientProvenance(value){const provenance=isRuntimeRecord(value)?value:{},bounded={};let acceptedCount=0;for(const key in provenance){if(acceptedCount>=32)break;if(!Object.prototype.hasOwnProperty.call(provenance,key))continue;const entry=provenance[key];/^[a-z][a-z0-9_-]{0,63}$/u.test(key)&&typeof entry=="string"&&entry.trim().length>0&&(bounded[key]=entry.trim().slice(0,256),acceptedCount+=1)}return bounded}function readMcpClientInfo(value){const clientInfo=isRuntimeRecord(value)?value:{},clientName=typeof clientInfo.name=="string"?clientInfo.name.trim():"";if(clientName.length===0)return;const optionalValues=[["version",clientInfo.version,128],["model",clientInfo.model,256],["session",clientInfo.session,256]],result={name:clientName.slice(0,128)};for(const[key,value2,limit]of optionalValues)typeof value2=="string"&&value2.trim().length>0&&(result[key]=value2.trim().slice(0,limit));const boundedProvenance=boundMcpClientProvenance(clientInfo.provenance);Object.keys(boundedProvenance).length>0&&(result.provenance=boundedProvenance);const episode=boundAgentEpisodeIdentity(clientInfo.episode,!1);return episode!==void 0&&(result.episode=episode),result}async function emitMcpChangeNotifications(action){isMutationAction(action??"")&&await Promise.all([...PM_MCP_SUBSCRIPTIONS.values()].flatMap(({registry})=>PM_MCP_RESOURCE_CONTRACTS.map(resource=>registry.emitResourceUpdated(resource.uri)))),["extension","install","package","uninstall"].includes(action??"")&&await Promise.all([...PM_MCP_SUBSCRIPTIONS.values()].map(({registry})=>registry.emitListChanged("tools"))),pruneClosedMcpSubscriptionRegistries()}async function handleToolCall(paramsInput,clientInfo,progressiveDiscoveryNegotiated=!1){const clientSignals=clientInfo?{client_info:clientInfo}:{};return runWithHarnessDetectionSignals({env:process.env,argv:process.argv,...clientSignals},async()=>{const params=asRecordClone(paramsInput),name=readRequiredString(params,"name"),handler=Object.prototype.hasOwnProperty.call(HANDLERS,name)?HANDLERS[name]:void 0;if(!handler)throw new PmCliError(`Unknown pm MCP tool: ${name}`,64);const inputResponses=params.inputResponses===void 0?void 0:parseMcpInputResponses(params.inputResponses);validateMcpToolArguments(params.arguments);const requestedArgs={...decodeHtmlEntitiesInOptions(asRecordClone(params.arguments)),...inputResponses?{inputResponses}:{},...typeof params.requestState=="string"?{requestState:params.requestState}:{}},access=await resolveMcpToolAccess(TOOLS,name,requestedArgs),requiredCustomDiscoveryEntry=progressiveDiscoveryNegotiated&&access.profile==="custom"&&name==="pm_discover";if(!access.available&&!requiredCustomDiscoveryEntry)throw new PmCliError(`pm MCP tool "${name}" is unavailable in the ${access.profile} profile.`,64);const args=await normalizeWorkspaceToolArguments(name,requestedArgs),cwd=typeof args.cwd=="string"?args.cwd:process.cwd(),pmRoot=resolvePmRoot(cwd,typeof args.path=="string"?args.path:void 0),workspaceIdentity=await pathExists(getSettingsPath(pmRoot))?(await readSettings(pmRoot)).agent_identity:void 0;return runWithHarnessDetectionSignals({env:{...process.env,PM_PATH:pmRoot},argv:process.argv,cwd,...clientSignals},()=>runWithWorkspaceHarnessSignalDescriptors(workspaceIdentity?.harness_signals??[],async()=>{const action=resolveInvokedAction(name,args),warnings=[...detectUnexpectedTopLevelKeys(name,args,declaredToolKeys()),...detectUnexpectedOptionKeys(name,action,args),...await collectMutationGuardWarnings(name,action,args)];for(const warning of warnings)console.error(`[pm-mcp] ${warning}`);const result=await handler(args);return emitMcpChangeNotifications(action),resultContent(result,warnings,args.tokenAccounting===!0,progressiveDiscoveryNegotiated)},{probesEnabled:workspaceIdentity?.probes_enabled}))})}async function openMcpSubscription(input){if(typeof input.request.id!="string"&&typeof input.request.id!="number"||input.request.method!=="subscriptions/listen")throw new PmMcpProtocolError("Invalid MCP subscriptions/listen request",PM_MCP_ERROR_CODES.invalidParams,{required:["id","method","params.notifications"]});resolveMcpRequestContext(input.request.params);const key=input.key??input.request.id;if(PM_MCP_SUBSCRIPTIONS.has(key))throw new PmMcpProtocolError("MCP subscription id is already active",PM_MCP_ERROR_CODES.invalidParams,{subscriptionId:input.request.id});const registry=createMcpSubscriptionRegistry();await registry.open({id:input.request.id,notifications:input.request.params?.notifications,sink:input.sink}),PM_MCP_SUBSCRIPTIONS.set(key,{id:input.request.id,registry})}function closeMcpSubscription(id,key=id){const subscription=PM_MCP_SUBSCRIPTIONS.get(key);if(!(!subscription||subscription.id!==id))return PM_MCP_SUBSCRIPTIONS.delete(key),subscription.registry.close(id)}function closeStdioMcpSubscriptions(){const closed=[];for(const[key,subscription]of PM_MCP_SUBSCRIPTIONS){if(key!==subscription.id)continue;const result=closeMcpSubscription(subscription.id,key);result&&closed.push({id:subscription.id,result})}return closed}async function resolveMcpToolSchemaForRequest(request){if(request.method!=="tools/call")return;const name=request.params?.name;return typeof name!="string"?void 0:(await resolveMcpToolSurface(TOOLS,requestWorkspaceArgs(request.params))).tools.find(tool=>tool.name===name)?.inputSchema}function buildMcpToolCallErrorResult(request,error){if(request.method!=="tools/call"||error instanceof PmMcpProtocolError)return;const content=errorContent(error,hasMcpProtocolVersionMetadata(request)&&hasMcpClientExtension(resolveMcpRequestContext(request.params),PM_MCP_PROGRESSIVE_DISCOVERY_EXTENSION));return hasMcpProtocolVersionMetadata(request)?buildMcpCompleteResult(content,PM_MCP_SERVER_INFO):content}function requestWorkspaceArgs(params){const paramsRecord=asRecordClone(params);return asRecordClone(paramsRecord.arguments??paramsRecord)}async function readWorkspaceResource(uri,params){const args=requestWorkspaceArgs(params),cwd=typeof args.cwd=="string"?args.cwd:process.cwd(),contract=PM_MCP_RESOURCE_CONTRACTS.find(resource=>resource.uri===uri);if(!contract)throw new PmCliError(`Unknown pm MCP resource: ${uri}`,64);let value;if(uri==="pm://workspace/context")value=await runMcpAction({...args,action:"context",limit:10});else if(uri==="pm://workspace/claims")value=await runMcpAction({...args,action:"list",status:"in_progress",limit:20});else if(uri==="pm://workspace/focus")value=await runMcpAction({...args,action:"focus",subcommand:"show"});else{const guidePath=path.join(cwd,"AGENTS.md");value=await pathExists(guidePath)?(await readFile(guidePath,"utf8")).slice(0,32e3):"No repository-local AGENTS.md was found."}return{contents:[{uri,mimeType:contract.mimeType,text:typeof value=="string"?value:JSON.stringify(value,null,2)}]}}async function loadRequestSkillRegistry(params){const args=requestWorkspaceArgs(params),cwd=typeof args.cwd=="string"?args.cwd:process.cwd(),workspaceRoot=resolveWorkspaceRoot(resolvePmRoot(cwd,typeof args.path=="string"?args.path:void 0));return PmMcpSkillRegistry.load({packageRoot:resolvePmPackageRoot(),workspaceRoot,packageVersion:PM_MCP_SERVER_VERSION})}function renderWorkflowPrompt(params){const paramsRecord=asRecordClone(params),name=readRequiredString(paramsRecord,"name"),prompt=PM_MCP_PROMPT_CONTRACTS.find(candidate=>candidate.name===name);if(!prompt)throw new PmCliError(`Unknown pm MCP prompt: ${name}`,64);const argumentsRecord=asRecordClone(paramsRecord.arguments);let text=prompt.template;for(const argument of prompt.arguments){const value=argumentsRecord[argument.name];if(argument.required&&(typeof value!="string"||value.trim().length===0))throw new PmCliError(`Missing required prompt argument: ${argument.name}`,64);text=text.replaceAll(`{{${argument.name}}}`,typeof value=="string"?value:"")}return{description:prompt.description,messages:[{role:"user",content:{type:"text",text}}]}}const LEGACY_MCP_ADAPTER=new LegacyMcpAdapter({serverInfo:PM_MCP_SERVER_INFO,capabilities:PM_MCP_SERVER_CAPABILITIES,instructions:PM_MCP_INSTRUCTIONS,parseClientInfo:readMcpClientInfo,listTools:async params=>({tools:(await resolveMcpToolSurface(TOOLS,requestWorkspaceArgs(params))).tools}),callTool:handleToolCall,listResources:()=>({resources:PM_MCP_RESOURCE_CONTRACTS}),readResource:params=>readWorkspaceResource(readRequiredString(asRecordClone(params),"uri"),params),listPrompts:()=>({prompts:PM_MCP_PROMPT_CONTRACTS.map(prompt=>({name:prompt.name,description:prompt.description,arguments:prompt.arguments}))}),getPrompt:renderWorkflowPrompt});function deterministicMcpTools(tools){return tools.map(tool=>({...tool,inputSchema:validateMcpJsonSchema(tool.inputSchema)})).sort((left,right)=>left.name.localeCompare(right.name))}function mcpTaskPrincipal(requestContext){return requestContext.clientInfo?`${requestContext.clientInfo.name}@${requestContext.clientInfo.version}`:"anonymous-stdio"}function mcpTaskStore(){return createMcpTaskStore({pmRoot:resolvePmRoot(process.cwd()),owner:"pm-mcp-task-provider"})}function validateMcpToolArguments(value){if(value!==void 0&&!isMcpRecord(value))throw new PmCliError("pm MCP tool arguments must be an object.",64)}function shouldCreateMcpTask(params,requestContext){if(!hasMcpClientExtension(requestContext,PM_MCP_TASKS_EXTENSION))return!1;const requestParams=asRecordClone(params),name=requestParams.name,args=asRecordClone(requestParams.arguments);return PM_MCP_DIRECT_TASK_TOOLS.has(name)||name==="pm_test"&&(args.subcommand==="run"||isMcpRecord(args.options)&&args.options.subcommand==="run")?!0:name!=="pm_run"?!1:typeof args.action=="string"&&PM_MCP_RUN_TASK_ACTIONS.has(args.action)}const PENDING_MCP_TASKS=new Map;async function executeMcpTask(execution,inputResponses){const params={...execution.params,...inputResponses?{inputResponses}:{},...execution.requestState?{requestState:execution.requestState}:{}};try{const result=await handleToolCall(params,execution.context.clientInfo,hasMcpClientExtension(execution.context,PM_MCP_PROGRESSIVE_DISCOVERY_EXTENSION));await execution.store.complete(execution.taskId,execution.principal,buildMcpCompleteResult(result,PM_MCP_SERVER_INFO)),PENDING_MCP_TASKS.delete(execution.taskId)}catch(error){if(error instanceof PmMcpInputRequiredError){execution.requestState=error.requestState,await execution.store.requireInput({taskId:execution.taskId,principal:execution.principal,requestContext:execution.context,inputRequests:error.inputRequests,statusMessage:"Task requires additional client input."});return}error instanceof PmMcpProtocolError?await execution.store.fail(execution.taskId,execution.principal,{code:error.code,message:error.message,data:error.data}):await execution.store.complete(execution.taskId,execution.principal,buildMcpCompleteResult(errorContent(error,hasMcpClientExtension(execution.context,PM_MCP_PROGRESSIVE_DISCOVERY_EXTENSION)),PM_MCP_SERVER_INFO)),PENDING_MCP_TASKS.delete(execution.taskId)}}async function settleMcpTaskExecution(taskId,execution){try{await execution}catch{PENDING_MCP_TASKS.delete(taskId)}}function scheduleMcpTaskExecution(execution,inputResponses){settleMcpTaskExecution(execution.taskId,executeMcpTask(execution,inputResponses))}async function createMcpTaskForToolCall(params,requestContext){const store=mcpTaskStore(),principal=mcpTaskPrincipal(requestContext),task=await store.create({principal,statusMessage:"pm operation accepted for asynchronous execution."}),execution={context:requestContext,params:asRecordClone(params),principal,store,taskId:task.taskId};return PENDING_MCP_TASKS.set(task.taskId,execution),scheduleMcpTaskExecution(execution),attachMcpServerInfo(task,PM_MCP_SERVER_INFO)}async function dispatchMcpTaskMethod(request,requestContext){if(!hasMcpClientExtension(requestContext,PM_MCP_TASKS_EXTENSION))throw new PmMcpProtocolError("Missing required client capability",PM_MCP_ERROR_CODES.missingRequiredClientCapability,{requiredCapabilities:{extensions:{[PM_MCP_TASKS_EXTENSION]:{}}}});const params=asRecordClone(request.params),taskId=readRequiredString(params,"taskId"),principal=mcpTaskPrincipal(requestContext),store=mcpTaskStore();if(request.method==="tasks/get")return buildMcpCompleteResult(await store.get(taskId,principal),PM_MCP_SERVER_INFO);if(request.method==="tasks/update"){const update=await store.update(taskId,principal,params.inputResponses),execution=PENDING_MCP_TASKS.get(taskId);return execution&&update.acceptedKeys.length>0&&update.remainingKeys.length===0&&scheduleMcpTaskExecution(execution,await store.takeInputResponses(taskId,principal)),buildMcpCompleteResult({},PM_MCP_SERVER_INFO)}return await store.cancel(taskId,principal),PENDING_MCP_TASKS.delete(taskId),buildMcpCompleteResult({},PM_MCP_SERVER_INFO)}async function dispatchModernToolMethod(request,requestContext,clientInfo){if(request.method==="tools/list"){const surface=await resolveMcpToolSurface(TOOLS,requestWorkspaceArgs(request.params)),listedTools=hasMcpClientExtension(requestContext,PM_MCP_PROGRESSIVE_DISCOVERY_EXTENSION)?[...surface.tools.filter(tool=>PM_MCP_ENTRY_TOOL_NAMES.includes(tool.name)),...surface.profile==="custom"&&!surface.tools.some(tool=>tool.name==="pm_discover")?TOOLS.filter(tool=>tool.name==="pm_discover"):[]]:surface.tools;return buildMcpCompleteResult(withMcpCachePolicy({tools:hasCompatiblePmMcpAppsCapability(requestContext)?decoratePmMcpToolsWithApps(deterministicMcpTools(listedTools)):deterministicMcpTools(listedTools)},PM_MCP_CACHE_POLICIES.tools),PM_MCP_SERVER_INFO)}if(validateMcpToolArguments(request.params?.arguments),shouldCreateMcpTask(request.params,requestContext))return createMcpTaskForToolCall(request.params,requestContext);try{return buildMcpCompleteResult(await handleToolCall(request.params,clientInfo,hasMcpClientExtension(requestContext,PM_MCP_PROGRESSIVE_DISCOVERY_EXTENSION)),PM_MCP_SERVER_INFO)}catch(error){if(!(error instanceof PmMcpInputRequiredError))throw error;return buildMcpInputRequiredResult({requestContext,serverInfo:PM_MCP_SERVER_INFO,inputRequests:error.inputRequests,requestState:error.requestState})}}async function dispatchModernResourceMethod(request,requestContext){if(request.method==="resources/list"){const resources=[...PM_MCP_RESOURCE_CONTRACTS,...hasCompatiblePmMcpAppsCapability(requestContext)?PM_MCP_APP_CONTRACTS.map(contract=>({uri:contract.uri,name:contract.name,description:contract.description,mimeType:PM_MCP_APP_MIME_TYPE,_meta:{ui:contract.resourceMeta}})):[]].sort((left,right)=>left.uri.localeCompare(right.uri));return buildMcpCompleteResult(withMcpCachePolicy({resources},PM_MCP_CACHE_POLICIES.resources),PM_MCP_SERVER_INFO)}if(request.method==="resources/templates/list")return buildMcpCompleteResult(withMcpCachePolicy({resourceTemplates:[]},PM_MCP_CACHE_POLICIES.resources),PM_MCP_SERVER_INFO);try{const uri=readRequiredString(asRecordClone(request.params),"uri"),app=findPmMcpAppByUri(uri);let resource;if(app){if(!hasPmMcpAppsCapability(requestContext))throw new PmMcpProtocolError("MCP App resource requires negotiated client capability",PM_MCP_ERROR_CODES.missingRequiredClientCapability,{requiredCapabilities:{extensions:{[PM_MCP_APPS_EXTENSION]:PM_MCP_APPS_SERVER_CAPABILITY}}});resource={contents:[{uri,mimeType:PM_MCP_APP_MIME_TYPE,text:renderPmMcpAppHtml(app),_meta:{ui:app.resourceMeta}}]}}else uri.startsWith("skill://")?(assertPmMcpSkillsCapability(requestContext),resource={...(await loadRequestSkillRegistry(request.params)).read(uri)}):resource=await readWorkspaceResource(uri,request.params);return buildMcpCompleteResult(withMcpCachePolicy(resource,PM_MCP_CACHE_POLICIES.resource),PM_MCP_SERVER_INFO)}catch(error){throw!(error instanceof PmCliError)||!error.message.startsWith("Unknown pm MCP resource:")?error:new PmMcpProtocolError(error.message,PM_MCP_ERROR_CODES.invalidParams,{field:"uri"})}}function hasCompatiblePmMcpAppsCapability(requestContext){try{return hasPmMcpAppsCapability(requestContext)}catch(error){if(error instanceof PmMcpProtocolError)return!1;throw error}}function readSkillPageOptions(params){if(params.cursor!==void 0&&typeof params.cursor!="string")throw new PmMcpProtocolError("Skills cursor must be a string",PM_MCP_ERROR_CODES.invalidParams,{field:"cursor"});if(params.limit!==void 0&&typeof params.limit!="number")throw new PmMcpProtocolError("Skills limit must be a number",PM_MCP_ERROR_CODES.invalidParams,{field:"limit"});return{...typeof params.cursor=="string"?{cursor:params.cursor}:{},...typeof params.limit=="number"?{limit:params.limit}:{}}}async function dispatchModernSkillMethod(request,requestContext){const directoryRead=request.method==="resources/directory/read";assertPmMcpSkillsCapability(requestContext,directoryRead);const params=asRecordClone(request.params),registry=await loadRequestSkillRegistry(request.params);let result;return request.method==="skills/list"?result={...registry.list(readSkillPageOptions(params))}:request.method==="skills/get"?result={skill:registry.get(readRequiredString(params,"uri"))}:result={...registry.readDirectory(readRequiredString(params,"uri"),readSkillPageOptions(params))},buildMcpCompleteResult(withMcpCachePolicy(result,PM_MCP_CACHE_POLICIES.resource),PM_MCP_SERVER_INFO)}function dispatchModernPromptMethod(request){const result=request.method==="prompts/list"?withMcpCachePolicy({prompts:PM_MCP_PROMPT_CONTRACTS.map(prompt=>({name:prompt.name,description:prompt.description,arguments:prompt.arguments})).sort((left,right)=>left.name.localeCompare(right.name))},PM_MCP_CACHE_POLICIES.prompts):renderWorkflowPrompt(request.params);return buildMcpCompleteResult(result,PM_MCP_SERVER_INFO)}async function dispatchModernMcpRequest(request,meta){const requestContext=resolveMcpRequestContext(request.params),clientInfo=readMcpClientInfo(meta[PM_MCP_META_KEYS.clientInfo]);if(request.method==="server/discover")return buildMcpDiscoverResult({serverInfo:PM_MCP_SERVER_INFO,capabilities:PM_MCP_SERVER_CAPABILITIES,instructions:PM_MCP_INSTRUCTIONS});if(request.method==="ping")throw new PmMcpProtocolError("MCP method not found: ping",-32601,{removedIn:PM_MCP_PROTOCOL_VERSION});if(PM_MCP_SKILL_METHODS.has(request.method??""))return dispatchModernSkillMethod(request,requestContext);if(request.method==="tasks/get"||request.method==="tasks/update"||request.method==="tasks/cancel")return dispatchMcpTaskMethod(request,requestContext);if(request.method==="tools/list"||request.method==="tools/call")return dispatchModernToolMethod(request,requestContext,clientInfo);if(request.method==="resources/list"||request.method==="resources/templates/list"||request.method==="resources/read")return dispatchModernResourceMethod(request,requestContext);if(request.method==="prompts/list"||request.method==="prompts/get")return dispatchModernPromptMethod(request);throw new PmMcpProtocolError(`MCP method not found: ${request.method??"(missing)"}`,-32601)}async function handleRequestInReproducibleContext(request){if(!(!request.id&&request.method?.startsWith("notifications/"))){if(hasMcpProtocolVersionMetadata(request)){const allowlist=(process.env.PM_MCP_BAGGAGE_ALLOWLIST??"").split(",").map(entry=>entry.trim()).filter(Boolean);return runWithMcpTraceContext(extractMcpTraceContext(request.params,{baggageAllowlist:allowlist}),()=>dispatchModernMcpRequest(request,request.params._meta))}return request.method==="initialize"?LEGACY_MCP_ADAPTER.initialize(request.params):LEGACY_MCP_ADAPTER.dispatch(request)}}function hasMcpProtocolVersionMetadata(request){const meta=isMcpRecord(request.params)?request.params._meta:void 0;return isMcpRecord(meta)&&Object.prototype.hasOwnProperty.call(meta,PM_MCP_META_KEYS.protocolVersion)}async function handleRequest(request){return runWithReproducibleProcessEnvironment(process.env,()=>handleRequestInReproducibleContext(request))}function writeResponse(id,payload){process.stdout.write(`${JSON.stringify({jsonrpc:"2.0",id,result:payload})}
|
|
2
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="d34b1306-8c8b-574d-b240-7cb24e0a678b")}catch{}})();import{realpathSync}from"node:fs";import{readFile}from"node:fs/promises";import path from"node:path";import readline from"node:readline";import{fileURLToPath}from"node:url";import{resolvePmCliVersion,EXIT_CODE,PmCliError,decodeHtmlEntitiesInOptions,levenshteinDistanceWithinLimit,asRecordClone,createSerialQueue,evaluateMutationGuard,getSettingsPath,isMutationAction,pathExists,readSettings,readRuntimeFieldOptionValue,resolveRuntimeFieldRegistry,runWithHarnessDetectionSignals,runWithWorkspaceHarnessSignalDescriptors,boundAgentEpisodeIdentity}from"../sdk/runtime-primitives.js";import{pmToolActionNestedOptionKeys}from"../sdk/cli-contracts/tool-schema.js";import{readRequiredString,runAction,runWithActiveExtensions}from"../sdk/runtime.js";import{NARROW_TOOL_ACTIONS,TOOLS}from"./tool-definitions.js";import{normalizeWorkspaceToolArguments,resolveMcpToolAccess,resolveMcpToolSurface}from"./runtime-capabilities.js";import{PM_MCP_PROMPT_CONTRACTS,PM_MCP_RESOURCE_CONTRACTS}from"../sdk/agent-capability-contracts.js";import{PM_MCP_ENTRY_TOOL_NAMES,PM_MCP_PROGRESSIVE_DISCOVERY_EXTENSION,PM_MCP_PROGRESSIVE_DISCOVERY_SERVER_CAPABILITY,discoverPmTools,parsePmToolDiscoveryOptions}from"../sdk/mcp/discovery.js";import{commitItemMutations}from"../sdk/item-transaction.js";import{isRuntimeRecord,markMcpMutationTransportInput}from"../sdk/runtime-input.js";import{attachOutputTokenAccounting}from"../sdk/output-token-accounting.js";import{createReproducibleProcessRunner,runWithReproducibleProcessEnvironment}from"../sdk/reproducibility/process.js";import{parseAtomicMutationControls}from"../sdk/structured-mutations.js";import{planItemMutationDocument,previewItemMutationDocument}from"../sdk/lifecycle/structured-mutation-plan.js";import{resolveAuthor,resolvePmRoot,resolveWorkspaceRoot}from"../sdk/runtime-primitives.js";import{PM_MCP_ERROR_CODES,PM_MCP_META_KEYS,PM_MCP_PROTOCOL_VERSION,PmMcpProtocolError,attachMcpServerInfo,buildMcpCompleteResult,buildMcpDiscoverResult,hasMcpClientExtension,isMcpRecord,resolveMcpRequestContext}from"../sdk/mcp/protocol.js";import{PmMcpInputRequiredError,buildMcpInputRequiredResult,parseMcpInputResponses,validateMcpJsonSchema,withMcpCachePolicy}from"../sdk/mcp/interactions.js";import{PM_MCP_TASKS_EXTENSION,createMcpTaskStore}from"../sdk/mcp/tasks.js";import{PmMcpSubscriptionRegistry}from"../sdk/mcp/subscriptions.js";import{extractMcpTraceContext,runWithMcpTraceContext}from"../sdk/mcp/authorization.js";import{LegacyMcpAdapter}from"./legacy-adapter.js";import{PM_MCP_APP_CONTRACTS,PM_MCP_APP_MIME_TYPE,PM_MCP_APPS_EXTENSION,PM_MCP_APPS_SERVER_CAPABILITY,decoratePmMcpToolsWithApps,findPmMcpAppByUri,hasPmMcpAppsCapability,renderPmMcpAppHtml}from"../sdk/mcp/apps.js";import{PM_MCP_SKILLS_EXTENSION,PM_MCP_SKILLS_SERVER_CAPABILITY,PmMcpSkillRegistry,assertPmMcpSkillsCapability}from"../sdk/mcp/skills.js";function runMcpAction(args){return runAction(markMcpMutationTransportInput(args))}const PM_PACKAGE_ROOT_ENV="PM_CLI_PACKAGE_ROOT";function resolvePmPackageRoot(){return fileURLToPath(new URL("../..",import.meta.url))}(typeof process.env[PM_PACKAGE_ROOT_ENV]!="string"||process.env[PM_PACKAGE_ROOT_ENV]?.trim().length===0)&&(process.env[PM_PACKAGE_ROOT_ENV]=resolvePmPackageRoot());const PM_MCP_SERVER_VERSION=resolvePmCliVersion(import.meta.url,["../.."])??"0.0.0",PM_MCP_SERVER_INFO={name:"pm-mcp",version:PM_MCP_SERVER_VERSION,description:"Stateless project-context management through pm SDK contracts.",websiteUrl:"https://github.com/unbraind/pm-cli"},PM_MCP_SERVER_CAPABILITIES={prompts:{listChanged:!0},resources:{listChanged:!0,subscribe:!0},tools:{listChanged:!0},extensions:{[PM_MCP_TASKS_EXTENSION]:{},[PM_MCP_APPS_EXTENSION]:PM_MCP_APPS_SERVER_CAPABILITY,[PM_MCP_SKILLS_EXTENSION]:PM_MCP_SKILLS_SERVER_CAPABILITY,[PM_MCP_PROGRESSIVE_DISCOVERY_EXTENSION]:PM_MCP_PROGRESSIVE_DISCOVERY_SERVER_CAPABILITY}},PM_MCP_SUBSCRIPTIONS=new Map;function createMcpSubscriptionRegistry(){return new PmMcpSubscriptionRegistry({capabilities:PM_MCP_SERVER_CAPABILITIES,serverInfo:PM_MCP_SERVER_INFO})}function pruneClosedMcpSubscriptionRegistries(){for(const[key,subscription]of PM_MCP_SUBSCRIPTIONS)subscription.registry.size===0&&PM_MCP_SUBSCRIPTIONS.delete(key)}const PM_MCP_CACHE_POLICIES={prompts:{ttlMs:6e4,cacheScope:"public"},resource:{ttlMs:0,cacheScope:"private"},resources:{ttlMs:6e4,cacheScope:"public"},tools:{ttlMs:3e4,cacheScope:"private"}},PM_MCP_DIRECT_TASK_TOOLS=new Set(["pm_graph","pm_health","pm_validate"]),PM_MCP_RUN_TASK_ACTIONS=new Set(["graph","health","import","reindex","test-all","validate"]),PM_MCP_SKILL_METHODS=new Set(["skills/list","skills/get","resources/directory/read"]),PM_MCP_INSTRUCTIONS="You have access to native pm CLI tools for git-based project management. When progressive discovery is negotiated, use pm_discover to expand the small entry catalog by intent and request schemas only when needed. Use pm_next to pick the next actionable item, or pm_context or pm_search before creating new work. Prefer narrow tools (pm_next, pm_context, pm_list, pm_get, pm_search, pm_events, pm_create, pm_mutate, pm_copy, pm_focus, pm_update, pm_append, pm_claim, pm_release, pm_close, pm_comments, pm_files, pm_docs, pm_notes, pm_learnings, pm_deps, pm_graph, pm_test, pm_validate, pm_health, pm_contracts, pm_schema, pm_profile, pm_config, pm_plan) over pm_run when they cover the operation. Use pm_plan for agent harness Plan workflows: it provides Codex/Claude/Cursor-style planning with durable steps, dependencies, decisions, discoveries, validation, and materialization. Use pm_schema and pm_config for workspace configuration: pm_schema manages custom item types/statuses and pm_config reads or writes settings keys. Use pm_run with an explicit action for active package-owned operations, plus activity, aggregate, history, stats, test-all, and gc. Use history-redact for audited history-stream redaction workflows, history-repair to re-anchor a drifted history chain, and history-compact to checkpoint/prune long history streams while preserving replay integrity. Agent harness and model provenance are detected automatically; pass author only for an intentional identity override. Do not pass path during real repository tracking \u2014 only pass path for sandbox or test runs.";function declaredToolKeys(tools=TOOLS){return new Map(tools.map(tool=>{const properties=tool.inputSchema.properties??{};return[tool.name,Object.keys(properties)]}))}function nearestDeclaredKey(unexpected,declared){const limit=Math.max(1,Math.min(3,Math.floor(unexpected.length/4)+1));let best;for(const candidate of declared){const distance=levenshteinDistanceWithinLimit(unexpected,candidate,limit);distance!==null&&(best===void 0||distance<best.distance)&&(best={key:candidate,distance})}return best?.key}const UNEXPECTED_KEY_WARNING_EXEMPT_TOOLS=new Set(["pm_run"]),MCP_RETRY_ARGUMENT_KEYS=new Set(["inputResponses","requestState"]);function resolveMcpDiscoveryCursorIntegrityKey(){const configuredKey=process.env.PM_MCP_DISCOVERY_CURSOR_KEY;if(configuredKey===void 0)return;const key=Buffer.from(configuredKey,"utf8");if(key.byteLength<32)throw new PmCliError("PM_MCP_DISCOVERY_CURSOR_KEY must contain at least 32 UTF-8 bytes.",64);return key}function detectUnexpectedTopLevelKeys(toolName,args,toolDeclaredKeys=declaredToolKeys()){if(typeof args!="object"||args===null||Array.isArray(args))return[];if(UNEXPECTED_KEY_WARNING_EXEMPT_TOOLS.has(toolName))return[];const declared=toolDeclaredKeys.get(toolName);if(declared===void 0)return[];const declaredSet=new Set([...declared,...MCP_RETRY_ARGUMENT_KEYS]),warnings=[];for(const key of Object.keys(args)){if(declaredSet.has(key))continue;const suggestion=nearestDeclaredKey(key,declared);warnings.push(suggestion!==void 0?`Unexpected top-level argument "${key}" for ${toolName} (did you mean "${suggestion}"?). It is not declared and may be ignored; declared arguments are: ${declared.join(", ")}.`:`Unexpected top-level argument "${key}" for ${toolName}. It is not declared and may be ignored; declared arguments are: ${declared.join(", ")}.`)}return warnings}const HANDLERS={pm_run:args=>runMcpAction(args),pm_discover:async args=>{const surface=await resolveMcpToolSurface(TOOLS,args),cursorIntegrityKey=resolveMcpDiscoveryCursorIntegrityKey(),discoveryOptions=parsePmToolDiscoveryOptions(args);return discoverPmTools(surface.tools.map(tool=>({name:tool.name,description:tool.description,inputSchema:tool.inputSchema,authorized:!0,signals:{freshness:1,usage:PM_MCP_ENTRY_TOOL_NAMES.includes(tool.name)?1:0}})),{...discoveryOptions,profile:surface.profile,...cursorIntegrityKey===void 0?{}:{cursorIntegrityKey}})},pm_mutate:async args=>{if(!Array.isArray(args.mutations)||args.mutations.length===0)throw new PmCliError("pm_mutate requires a non-empty mutations array.",EXIT_CODE.USAGE);const explicitTransactionId=args.transactionId===void 0?void 0:readRequiredString(args,"transactionId"),upsertKey=args.upsertKey===void 0?void 0:readRequiredString(args,"upsertKey"),controls=parseAtomicMutationControls(args),cwd=typeof args.cwd=="string"?args.cwd:process.cwd(),pmRoot=resolvePmRoot(cwd,typeof args.path=="string"?args.path:void 0),extensionScope={cwd:typeof args.cwd=="string"?args.cwd:void 0,path:pmRoot,noExtensions:args.noExtensions===!0},plan=await runWithActiveExtensions(extensionScope,()=>planItemMutationDocument({pmRoot,input:JSON.stringify({schema_version:1,mutations:args.mutations}),...explicitTransactionId===void 0?{}:{transactionId:explicitTransactionId},...upsertKey===void 0?{}:{upsertKey}})),{mutations,references,rows}=plan,transactionId=plan.transaction_id,receipt={transaction_id:transactionId,transaction_id_source:plan.transaction_id_source,...plan.upsert_key===void 0?{}:{upsert_key:plan.upsert_key}};if(args.dryRun===!0){const preview=await runWithActiveExtensions(extensionScope,()=>previewItemMutationDocument({pmRoot,author:resolveAuthor(typeof args.author=="string"?args.author:void 0,"unknown"),plan}));return{...receipt,dry_run:!0,validation:preview.validation,mutation_count:mutations.length,mutations,references,rows:preview.rows}}const result=await runWithActiveExtensions(extensionScope,()=>commitItemMutations({pmRoot,transactionId,author:resolveAuthor(typeof args.author=="string"?args.author:void 0,"unknown"),mutations,...controls}));return{...Object.fromEntries(Object.entries(result).filter(([key])=>key!=="transactionId")),...receipt,mutation_count:mutations.length,references,rows}},...Object.fromEntries(Object.entries(NARROW_TOOL_ACTIONS).map(([tool,action])=>[tool,args=>runMcpAction({...args,action})]))};function resolveInvokedAction(toolName,args){return toolName==="pm_run"?typeof args.action=="string"?args.action:void 0:NARROW_TOOL_ACTIONS[toolName]}async function collectMutationGuardWarnings(toolName,action,args){if(toolName!=="pm_mutate"&&!isMutationAction(action??""))return[];const cwd=typeof args.cwd=="string"?args.cwd:process.cwd(),pmRoot=resolvePmRoot(cwd,typeof args.path=="string"?args.path:void 0);if(!await pathExists(getSettingsPath(pmRoot)))return[];const settings=await readSettings(pmRoot),nestedOptions=typeof args.options=="object"&&args.options!==null&&!Array.isArray(args.options)?args.options:{};return evaluateMutationGuard({author:resolveAuthor(typeof args.author=="string"?args.author:typeof nestedOptions.author=="string"?nestedOptions.author:void 0,settings.author_default),payload:Object.fromEntries(Object.entries(args).filter(([key])=>key!=="cwd"&&key!=="path")),settings:settings.mutation_guard,force:args.force===!0||nestedOptions.force===!0}).warnings}function detectUnexpectedOptionKeys(toolName,action,args,schema){const options=args.options;if(action===void 0||typeof options!="object"||options===null||Array.isArray(options))return[];const declared=pmToolActionNestedOptionKeys(action);if(declared===void 0)return[];const declaredSet=new Set(declared),workspaceFields=schema&&(action==="create"||action==="update")?resolveRuntimeFieldRegistry(schema).command_to_fields.get(action)??[]:[],warnings=[];for(const key of Object.keys(options)){if(declaredSet.has(key)||workspaceFields.some(field=>readRuntimeFieldOptionValue({[key]:!0},field)===!0))continue;const suggestion=nearestDeclaredKey(key,declared);warnings.push(suggestion!==void 0?`Unknown option "${key}" for ${toolName} action "${action}" (did you mean "${suggestion}"?). The ${action} contract does not read it, so it has no effect; declared keys are: ${declared.join(", ")}.`:`Unknown option "${key}" for ${toolName} action "${action}". The ${action} contract does not read it, so it has no effect; declared keys are: ${declared.join(", ")}.`)}return warnings}function resultContent(result,warnings,tokenAccounting=!1,canonicalStructuredResult=!1){const effectiveResult=tokenAccounting?attachOutputTokenAccounting(result,value=>JSON.stringify(value,null,2)):result,structuredContent=warnings!==void 0&&warnings.length>0?{result:effectiveResult,warnings}:{result:effectiveResult};return{content:[{type:"text",text:canonicalStructuredResult?"Canonical result: structuredContent.result":JSON.stringify(effectiveResult,null,2)}],structuredContent}}function errorContent(error,canonicalStructuredResult=!1){const code=error instanceof PmCliError?error.exitCode:1,message=error instanceof Error?error.message:String(error),details=error instanceof PmCliError?error.context:void 0;return{isError:!0,content:[{type:"text",text:canonicalStructuredResult?"Canonical error: structuredContent":JSON.stringify({error:message,code,details},null,2)}],structuredContent:{result:null,error:message,code,details}}}function boundMcpClientProvenance(value){const provenance=isRuntimeRecord(value)?value:{},bounded={};let acceptedCount=0;for(const key in provenance){if(acceptedCount>=32)break;if(!Object.prototype.hasOwnProperty.call(provenance,key))continue;const entry=provenance[key];/^[a-z][a-z0-9_-]{0,63}$/u.test(key)&&typeof entry=="string"&&entry.trim().length>0&&(bounded[key]=entry.trim().slice(0,256),acceptedCount+=1)}return bounded}function readMcpClientInfo(value){const clientInfo=isRuntimeRecord(value)?value:{},clientName=typeof clientInfo.name=="string"?clientInfo.name.trim():"";if(clientName.length===0)return;const optionalValues=[["version",clientInfo.version,128],["model",clientInfo.model,256],["session",clientInfo.session,256]],result={name:clientName.slice(0,128)};for(const[key,value2,limit]of optionalValues)typeof value2=="string"&&value2.trim().length>0&&(result[key]=value2.trim().slice(0,limit));const boundedProvenance=boundMcpClientProvenance(clientInfo.provenance);Object.keys(boundedProvenance).length>0&&(result.provenance=boundedProvenance);const episode=boundAgentEpisodeIdentity(clientInfo.episode,!1);return episode!==void 0&&(result.episode=episode),result}async function emitMcpChangeNotifications(action){isMutationAction(action??"")&&await Promise.all([...PM_MCP_SUBSCRIPTIONS.values()].flatMap(({registry})=>PM_MCP_RESOURCE_CONTRACTS.map(resource=>registry.emitResourceUpdated(resource.uri)))),["extension","install","package","uninstall"].includes(action??"")&&await Promise.all([...PM_MCP_SUBSCRIPTIONS.values()].map(({registry})=>registry.emitListChanged("tools"))),pruneClosedMcpSubscriptionRegistries()}async function handleToolCall(paramsInput,clientInfo,progressiveDiscoveryNegotiated=!1){const clientSignals=clientInfo?{client_info:clientInfo}:{};return runWithHarnessDetectionSignals({env:process.env,argv:process.argv,...clientSignals},async()=>{const params=asRecordClone(paramsInput),name=readRequiredString(params,"name"),handler=Object.prototype.hasOwnProperty.call(HANDLERS,name)?HANDLERS[name]:void 0;if(!handler)throw new PmCliError(`Unknown pm MCP tool: ${name}`,64);const inputResponses=params.inputResponses===void 0?void 0:parseMcpInputResponses(params.inputResponses);validateMcpToolArguments(params.arguments);const requestedArgs={...decodeHtmlEntitiesInOptions(asRecordClone(params.arguments)),...inputResponses?{inputResponses}:{},...typeof params.requestState=="string"?{requestState:params.requestState}:{}},access=await resolveMcpToolAccess(TOOLS,name,requestedArgs),requiredCustomDiscoveryEntry=progressiveDiscoveryNegotiated&&access.profile==="custom"&&name==="pm_discover";if(!access.available&&!requiredCustomDiscoveryEntry)throw new PmCliError(`pm MCP tool "${name}" is unavailable in the ${access.profile} profile.`,64);const args=await normalizeWorkspaceToolArguments(name,requestedArgs),cwd=typeof args.cwd=="string"?args.cwd:process.cwd(),pmRoot=resolvePmRoot(cwd,typeof args.path=="string"?args.path:void 0),workspaceSettings=await pathExists(getSettingsPath(pmRoot))?await readSettings(pmRoot):void 0,workspaceIdentity=workspaceSettings?.agent_identity;return runWithHarnessDetectionSignals({env:{...process.env,PM_PATH:pmRoot},argv:process.argv,cwd,...clientSignals},()=>runWithWorkspaceHarnessSignalDescriptors(workspaceIdentity?.harness_signals??[],async()=>{const action=resolveInvokedAction(name,args),warnings=[...detectUnexpectedTopLevelKeys(name,args,declaredToolKeys()),...detectUnexpectedOptionKeys(name,action,args,workspaceSettings?.schema),...await collectMutationGuardWarnings(name,action,args)];for(const warning of warnings)console.error(`[pm-mcp] ${warning}`);const result=await handler(args);return emitMcpChangeNotifications(action),resultContent(result,warnings,args.tokenAccounting===!0,progressiveDiscoveryNegotiated)},{probesEnabled:workspaceIdentity?.probes_enabled}))})}async function openMcpSubscription(input){if(typeof input.request.id!="string"&&typeof input.request.id!="number"||input.request.method!=="subscriptions/listen")throw new PmMcpProtocolError("Invalid MCP subscriptions/listen request",PM_MCP_ERROR_CODES.invalidParams,{required:["id","method","params.notifications"]});resolveMcpRequestContext(input.request.params);const key=input.key??input.request.id;if(PM_MCP_SUBSCRIPTIONS.has(key))throw new PmMcpProtocolError("MCP subscription id is already active",PM_MCP_ERROR_CODES.invalidParams,{subscriptionId:input.request.id});const registry=createMcpSubscriptionRegistry();await registry.open({id:input.request.id,notifications:input.request.params?.notifications,sink:input.sink}),PM_MCP_SUBSCRIPTIONS.set(key,{id:input.request.id,registry})}function closeMcpSubscription(id,key=id){const subscription=PM_MCP_SUBSCRIPTIONS.get(key);if(!(!subscription||subscription.id!==id))return PM_MCP_SUBSCRIPTIONS.delete(key),subscription.registry.close(id)}function closeStdioMcpSubscriptions(){const closed=[];for(const[key,subscription]of PM_MCP_SUBSCRIPTIONS){if(key!==subscription.id)continue;const result=closeMcpSubscription(subscription.id,key);result&&closed.push({id:subscription.id,result})}return closed}async function resolveMcpToolSchemaForRequest(request){if(request.method!=="tools/call")return;const name=request.params?.name;return typeof name!="string"?void 0:(await resolveMcpToolSurface(TOOLS,requestWorkspaceArgs(request.params))).tools.find(tool=>tool.name===name)?.inputSchema}function buildMcpToolCallErrorResult(request,error){if(request.method!=="tools/call"||error instanceof PmMcpProtocolError)return;const content=errorContent(error,hasMcpProtocolVersionMetadata(request)&&hasMcpClientExtension(resolveMcpRequestContext(request.params),PM_MCP_PROGRESSIVE_DISCOVERY_EXTENSION));return hasMcpProtocolVersionMetadata(request)?buildMcpCompleteResult(content,PM_MCP_SERVER_INFO):content}function requestWorkspaceArgs(params){const paramsRecord=asRecordClone(params);return asRecordClone(paramsRecord.arguments??paramsRecord)}async function readWorkspaceResource(uri,params){const args=requestWorkspaceArgs(params),cwd=typeof args.cwd=="string"?args.cwd:process.cwd(),contract=PM_MCP_RESOURCE_CONTRACTS.find(resource=>resource.uri===uri);if(!contract)throw new PmCliError(`Unknown pm MCP resource: ${uri}`,64);let value;if(uri==="pm://workspace/context")value=await runMcpAction({...args,action:"context",limit:10});else if(uri==="pm://workspace/claims")value=await runMcpAction({...args,action:"list",status:"in_progress",limit:20});else if(uri==="pm://workspace/focus")value=await runMcpAction({...args,action:"focus",subcommand:"show"});else{const guidePath=path.join(cwd,"AGENTS.md");value=await pathExists(guidePath)?(await readFile(guidePath,"utf8")).slice(0,32e3):"No repository-local AGENTS.md was found."}return{contents:[{uri,mimeType:contract.mimeType,text:typeof value=="string"?value:JSON.stringify(value,null,2)}]}}async function loadRequestSkillRegistry(params){const args=requestWorkspaceArgs(params),cwd=typeof args.cwd=="string"?args.cwd:process.cwd(),workspaceRoot=resolveWorkspaceRoot(resolvePmRoot(cwd,typeof args.path=="string"?args.path:void 0));return PmMcpSkillRegistry.load({packageRoot:resolvePmPackageRoot(),workspaceRoot,packageVersion:PM_MCP_SERVER_VERSION})}function renderWorkflowPrompt(params){const paramsRecord=asRecordClone(params),name=readRequiredString(paramsRecord,"name"),prompt=PM_MCP_PROMPT_CONTRACTS.find(candidate=>candidate.name===name);if(!prompt)throw new PmCliError(`Unknown pm MCP prompt: ${name}`,64);const argumentsRecord=asRecordClone(paramsRecord.arguments);let text=prompt.template;for(const argument of prompt.arguments){const value=argumentsRecord[argument.name];if(argument.required&&(typeof value!="string"||value.trim().length===0))throw new PmCliError(`Missing required prompt argument: ${argument.name}`,64);text=text.replaceAll(`{{${argument.name}}}`,typeof value=="string"?value:"")}return{description:prompt.description,messages:[{role:"user",content:{type:"text",text}}]}}const LEGACY_MCP_ADAPTER=new LegacyMcpAdapter({serverInfo:PM_MCP_SERVER_INFO,capabilities:PM_MCP_SERVER_CAPABILITIES,instructions:PM_MCP_INSTRUCTIONS,parseClientInfo:readMcpClientInfo,listTools:async params=>({tools:(await resolveMcpToolSurface(TOOLS,requestWorkspaceArgs(params))).tools}),callTool:handleToolCall,listResources:()=>({resources:PM_MCP_RESOURCE_CONTRACTS}),readResource:params=>readWorkspaceResource(readRequiredString(asRecordClone(params),"uri"),params),listPrompts:()=>({prompts:PM_MCP_PROMPT_CONTRACTS.map(prompt=>({name:prompt.name,description:prompt.description,arguments:prompt.arguments}))}),getPrompt:renderWorkflowPrompt});function deterministicMcpTools(tools){return tools.map(tool=>({...tool,inputSchema:validateMcpJsonSchema(tool.inputSchema)})).sort((left,right)=>left.name.localeCompare(right.name))}function mcpTaskPrincipal(requestContext){return requestContext.clientInfo?`${requestContext.clientInfo.name}@${requestContext.clientInfo.version}`:"anonymous-stdio"}function mcpTaskStore(){return createMcpTaskStore({pmRoot:resolvePmRoot(process.cwd()),owner:"pm-mcp-task-provider"})}function validateMcpToolArguments(value){if(value!==void 0&&!isMcpRecord(value))throw new PmCliError("pm MCP tool arguments must be an object.",64)}function shouldCreateMcpTask(params,requestContext){if(!hasMcpClientExtension(requestContext,PM_MCP_TASKS_EXTENSION))return!1;const requestParams=asRecordClone(params),name=requestParams.name,args=asRecordClone(requestParams.arguments);return PM_MCP_DIRECT_TASK_TOOLS.has(name)||name==="pm_test"&&(args.subcommand==="run"||isMcpRecord(args.options)&&args.options.subcommand==="run")?!0:name!=="pm_run"?!1:typeof args.action=="string"&&PM_MCP_RUN_TASK_ACTIONS.has(args.action)}const PENDING_MCP_TASKS=new Map;async function executeMcpTask(execution,inputResponses){const params={...execution.params,...inputResponses?{inputResponses}:{},...execution.requestState?{requestState:execution.requestState}:{}};try{const result=await handleToolCall(params,execution.context.clientInfo,hasMcpClientExtension(execution.context,PM_MCP_PROGRESSIVE_DISCOVERY_EXTENSION));await execution.store.complete(execution.taskId,execution.principal,buildMcpCompleteResult(result,PM_MCP_SERVER_INFO)),PENDING_MCP_TASKS.delete(execution.taskId)}catch(error){if(error instanceof PmMcpInputRequiredError){execution.requestState=error.requestState,await execution.store.requireInput({taskId:execution.taskId,principal:execution.principal,requestContext:execution.context,inputRequests:error.inputRequests,statusMessage:"Task requires additional client input."});return}error instanceof PmMcpProtocolError?await execution.store.fail(execution.taskId,execution.principal,{code:error.code,message:error.message,data:error.data}):await execution.store.complete(execution.taskId,execution.principal,buildMcpCompleteResult(errorContent(error,hasMcpClientExtension(execution.context,PM_MCP_PROGRESSIVE_DISCOVERY_EXTENSION)),PM_MCP_SERVER_INFO)),PENDING_MCP_TASKS.delete(execution.taskId)}}async function settleMcpTaskExecution(taskId,execution){try{await execution}catch{PENDING_MCP_TASKS.delete(taskId)}}function scheduleMcpTaskExecution(execution,inputResponses){settleMcpTaskExecution(execution.taskId,executeMcpTask(execution,inputResponses))}async function createMcpTaskForToolCall(params,requestContext){const store=mcpTaskStore(),principal=mcpTaskPrincipal(requestContext),task=await store.create({principal,statusMessage:"pm operation accepted for asynchronous execution."}),execution={context:requestContext,params:asRecordClone(params),principal,store,taskId:task.taskId};return PENDING_MCP_TASKS.set(task.taskId,execution),scheduleMcpTaskExecution(execution),attachMcpServerInfo(task,PM_MCP_SERVER_INFO)}async function dispatchMcpTaskMethod(request,requestContext){if(!hasMcpClientExtension(requestContext,PM_MCP_TASKS_EXTENSION))throw new PmMcpProtocolError("Missing required client capability",PM_MCP_ERROR_CODES.missingRequiredClientCapability,{requiredCapabilities:{extensions:{[PM_MCP_TASKS_EXTENSION]:{}}}});const params=asRecordClone(request.params),taskId=readRequiredString(params,"taskId"),principal=mcpTaskPrincipal(requestContext),store=mcpTaskStore();if(request.method==="tasks/get")return buildMcpCompleteResult(await store.get(taskId,principal),PM_MCP_SERVER_INFO);if(request.method==="tasks/update"){const update=await store.update(taskId,principal,params.inputResponses),execution=PENDING_MCP_TASKS.get(taskId);return execution&&update.acceptedKeys.length>0&&update.remainingKeys.length===0&&scheduleMcpTaskExecution(execution,await store.takeInputResponses(taskId,principal)),buildMcpCompleteResult({},PM_MCP_SERVER_INFO)}return await store.cancel(taskId,principal),PENDING_MCP_TASKS.delete(taskId),buildMcpCompleteResult({},PM_MCP_SERVER_INFO)}async function dispatchModernToolMethod(request,requestContext,clientInfo){if(request.method==="tools/list"){const surface=await resolveMcpToolSurface(TOOLS,requestWorkspaceArgs(request.params)),listedTools=hasMcpClientExtension(requestContext,PM_MCP_PROGRESSIVE_DISCOVERY_EXTENSION)?[...surface.tools.filter(tool=>PM_MCP_ENTRY_TOOL_NAMES.includes(tool.name)),...surface.profile==="custom"&&!surface.tools.some(tool=>tool.name==="pm_discover")?TOOLS.filter(tool=>tool.name==="pm_discover"):[]]:surface.tools;return buildMcpCompleteResult(withMcpCachePolicy({tools:hasCompatiblePmMcpAppsCapability(requestContext)?decoratePmMcpToolsWithApps(deterministicMcpTools(listedTools)):deterministicMcpTools(listedTools)},PM_MCP_CACHE_POLICIES.tools),PM_MCP_SERVER_INFO)}if(validateMcpToolArguments(request.params?.arguments),shouldCreateMcpTask(request.params,requestContext))return createMcpTaskForToolCall(request.params,requestContext);try{return buildMcpCompleteResult(await handleToolCall(request.params,clientInfo,hasMcpClientExtension(requestContext,PM_MCP_PROGRESSIVE_DISCOVERY_EXTENSION)),PM_MCP_SERVER_INFO)}catch(error){if(!(error instanceof PmMcpInputRequiredError))throw error;return buildMcpInputRequiredResult({requestContext,serverInfo:PM_MCP_SERVER_INFO,inputRequests:error.inputRequests,requestState:error.requestState})}}async function dispatchModernResourceMethod(request,requestContext){if(request.method==="resources/list"){const resources=[...PM_MCP_RESOURCE_CONTRACTS,...hasCompatiblePmMcpAppsCapability(requestContext)?PM_MCP_APP_CONTRACTS.map(contract=>({uri:contract.uri,name:contract.name,description:contract.description,mimeType:PM_MCP_APP_MIME_TYPE,_meta:{ui:contract.resourceMeta}})):[]].sort((left,right)=>left.uri.localeCompare(right.uri));return buildMcpCompleteResult(withMcpCachePolicy({resources},PM_MCP_CACHE_POLICIES.resources),PM_MCP_SERVER_INFO)}if(request.method==="resources/templates/list")return buildMcpCompleteResult(withMcpCachePolicy({resourceTemplates:[]},PM_MCP_CACHE_POLICIES.resources),PM_MCP_SERVER_INFO);try{const uri=readRequiredString(asRecordClone(request.params),"uri"),app=findPmMcpAppByUri(uri);let resource;if(app){if(!hasPmMcpAppsCapability(requestContext))throw new PmMcpProtocolError("MCP App resource requires negotiated client capability",PM_MCP_ERROR_CODES.missingRequiredClientCapability,{requiredCapabilities:{extensions:{[PM_MCP_APPS_EXTENSION]:PM_MCP_APPS_SERVER_CAPABILITY}}});resource={contents:[{uri,mimeType:PM_MCP_APP_MIME_TYPE,text:renderPmMcpAppHtml(app),_meta:{ui:app.resourceMeta}}]}}else uri.startsWith("skill://")?(assertPmMcpSkillsCapability(requestContext),resource={...(await loadRequestSkillRegistry(request.params)).read(uri)}):resource=await readWorkspaceResource(uri,request.params);return buildMcpCompleteResult(withMcpCachePolicy(resource,PM_MCP_CACHE_POLICIES.resource),PM_MCP_SERVER_INFO)}catch(error){throw!(error instanceof PmCliError)||!error.message.startsWith("Unknown pm MCP resource:")?error:new PmMcpProtocolError(error.message,PM_MCP_ERROR_CODES.invalidParams,{field:"uri"})}}function hasCompatiblePmMcpAppsCapability(requestContext){try{return hasPmMcpAppsCapability(requestContext)}catch(error){if(error instanceof PmMcpProtocolError)return!1;throw error}}function readSkillPageOptions(params){if(params.cursor!==void 0&&typeof params.cursor!="string")throw new PmMcpProtocolError("Skills cursor must be a string",PM_MCP_ERROR_CODES.invalidParams,{field:"cursor"});if(params.limit!==void 0&&typeof params.limit!="number")throw new PmMcpProtocolError("Skills limit must be a number",PM_MCP_ERROR_CODES.invalidParams,{field:"limit"});return{...typeof params.cursor=="string"?{cursor:params.cursor}:{},...typeof params.limit=="number"?{limit:params.limit}:{}}}async function dispatchModernSkillMethod(request,requestContext){const directoryRead=request.method==="resources/directory/read";assertPmMcpSkillsCapability(requestContext,directoryRead);const params=asRecordClone(request.params),registry=await loadRequestSkillRegistry(request.params);let result;return request.method==="skills/list"?result={...registry.list(readSkillPageOptions(params))}:request.method==="skills/get"?result={skill:registry.get(readRequiredString(params,"uri"))}:result={...registry.readDirectory(readRequiredString(params,"uri"),readSkillPageOptions(params))},buildMcpCompleteResult(withMcpCachePolicy(result,PM_MCP_CACHE_POLICIES.resource),PM_MCP_SERVER_INFO)}function dispatchModernPromptMethod(request){const result=request.method==="prompts/list"?withMcpCachePolicy({prompts:PM_MCP_PROMPT_CONTRACTS.map(prompt=>({name:prompt.name,description:prompt.description,arguments:prompt.arguments})).sort((left,right)=>left.name.localeCompare(right.name))},PM_MCP_CACHE_POLICIES.prompts):renderWorkflowPrompt(request.params);return buildMcpCompleteResult(result,PM_MCP_SERVER_INFO)}async function dispatchModernMcpRequest(request,meta){const requestContext=resolveMcpRequestContext(request.params),clientInfo=readMcpClientInfo(meta[PM_MCP_META_KEYS.clientInfo]);if(request.method==="server/discover")return buildMcpDiscoverResult({serverInfo:PM_MCP_SERVER_INFO,capabilities:PM_MCP_SERVER_CAPABILITIES,instructions:PM_MCP_INSTRUCTIONS});if(request.method==="ping")throw new PmMcpProtocolError("MCP method not found: ping",-32601,{removedIn:PM_MCP_PROTOCOL_VERSION});if(PM_MCP_SKILL_METHODS.has(request.method??""))return dispatchModernSkillMethod(request,requestContext);if(request.method==="tasks/get"||request.method==="tasks/update"||request.method==="tasks/cancel")return dispatchMcpTaskMethod(request,requestContext);if(request.method==="tools/list"||request.method==="tools/call")return dispatchModernToolMethod(request,requestContext,clientInfo);if(request.method==="resources/list"||request.method==="resources/templates/list"||request.method==="resources/read")return dispatchModernResourceMethod(request,requestContext);if(request.method==="prompts/list"||request.method==="prompts/get")return dispatchModernPromptMethod(request);throw new PmMcpProtocolError(`MCP method not found: ${request.method??"(missing)"}`,-32601)}async function handleRequestInReproducibleContext(request){if(!(!request.id&&request.method?.startsWith("notifications/"))){if(hasMcpProtocolVersionMetadata(request)){const allowlist=(process.env.PM_MCP_BAGGAGE_ALLOWLIST??"").split(",").map(entry=>entry.trim()).filter(Boolean);return runWithMcpTraceContext(extractMcpTraceContext(request.params,{baggageAllowlist:allowlist}),()=>dispatchModernMcpRequest(request,request.params._meta))}return request.method==="initialize"?LEGACY_MCP_ADAPTER.initialize(request.params):LEGACY_MCP_ADAPTER.dispatch(request)}}function hasMcpProtocolVersionMetadata(request){const meta=isMcpRecord(request.params)?request.params._meta:void 0;return isMcpRecord(meta)&&Object.prototype.hasOwnProperty.call(meta,PM_MCP_META_KEYS.protocolVersion)}async function handleRequest(request){return runWithReproducibleProcessEnvironment(process.env,()=>handleRequestInReproducibleContext(request))}function writeResponse(id,payload){process.stdout.write(`${JSON.stringify({jsonrpc:"2.0",id,result:payload})}
|
|
3
3
|
`)}function writeError(id,error){const code=error instanceof PmMcpProtocolError?error.code:error instanceof PmCliError?error.exitCode:-32603,message=error instanceof Error?error.message:String(error),data=error instanceof PmMcpProtocolError?error.data:error instanceof PmCliError?error.context:void 0;process.stdout.write(`${JSON.stringify({jsonrpc:"2.0",id,error:{code,message,data}})}
|
|
4
4
|
`)}function writeToolCallErrorResponse(request,error){return request.method!=="tools/call"||error instanceof PmMcpProtocolError?!1:(writeResponse(request.id,buildMcpToolCallErrorResult(request,error)),!0)}async function handleStdioTransportControl(request){if(request.method==="subscriptions/listen")return await openMcpSubscription({request,sink:notification=>{process.stdout.write(`${JSON.stringify(notification)}
|
|
5
5
|
`)}}),!0;if(request.method!=="notifications/cancelled")return!1;const requestId=request.params?.requestId;if(typeof requestId=="string"||typeof requestId=="number"){const result=closeMcpSubscription(requestId);result&&writeResponse(requestId,result)}return!0}async function processRpcLineWithHandler(line,requestHandler){if(line.trim().length===0)return;let request;try{request=JSON.parse(line)}catch(error){const message=error instanceof Error?error.message:String(error);writeError(null,new PmCliError(`Parse error: ${message}`,-32700));return}if(typeof request!="object"||request===null||Array.isArray(request)){writeError(null,new PmCliError("Invalid JSON-RPC request: expected an object",-32600));return}const shouldRespond=Object.prototype.hasOwnProperty.call(request,"id");try{if(await handleStdioTransportControl(request))return;const result=await requestHandler(request);shouldRespond&&result!==void 0&&writeResponse(request.id,result)}catch(error){if(!shouldRespond)return;writeToolCallErrorResponse(request,error)||writeError(request.id,error)}}async function processRpcLine(line){await processRpcLineWithHandler(line,handleRequest)}function startMcpServer(){const rl=readline.createInterface({input:process.stdin,crlfDelay:1/0}),queue=createSerialQueue();let processLine;try{const runInProcessContext=createReproducibleProcessRunner(process.env);processLine=line=>runInProcessContext(()=>processRpcLineWithHandler(line,handleRequestInReproducibleContext))}catch{processLine=processRpcLine}rl.on("line",line=>{queue.enqueue(()=>processLine(line))}),rl.on("close",()=>{queue.enqueue(()=>{for(const closed of closeStdioMcpSubscriptions())writeResponse(closed.id,closed.result)})})}function isInvokedAsMcpMainModule(argvPath,moduleUrl){if(!argvPath)return!1;const selfPath=fileURLToPath(moduleUrl);if(argvPath===selfPath)return!0;try{return realpathSync(argvPath)===realpathSync(selfPath)}catch{return!1}}function readRuntimeTestHook(key){const runtimeTestHooks=globalThis.__pmCliActionRunnerTestHooks;if(runtimeTestHooks===void 0)throw new PmCliError(`MCP runtime test hook "${String(key)}" is only available in test environments.`,64);return runtimeTestHooks[key]}const _testOnly={boundMcpClientProvenance,createMcpInputRequiredError:input=>new PmMcpInputRequiredError(input),createMcpProtocolError:(...input)=>new PmMcpProtocolError(...input),get closeManyOptionsFromFlat(){return readRuntimeTestHook("closeManyOptionsFromFlat")},detectUnexpectedOptionKeys,detectUnexpectedTopLevelKeys,collectMutationGuardWarnings,closeStdioMcpSubscriptions,errorContent,emitMcpChangeNotifications,expireMcpSubscriptionRecord:(id,key=id)=>PM_MCP_SUBSCRIPTIONS.get(key).registry.close(id),getMcpClientInfo:()=>LEGACY_MCP_ADAPTER.getClientInfo(),get extensionOptionsFromArgs(){return readRuntimeTestHook("extensionOptionsFromArgs")},get globalOptions(){return readRuntimeTestHook("globalOptions")},get mutationListOptions(){return readRuntimeTestHook("mutationListOptions")},nearestDeclaredKey,mcpTaskPrincipal,resultContent,resolveMcpRequestContext,shouldCreateMcpTask,settleMcpTaskExecution,subscriptionCount:()=>PM_MCP_SUBSCRIPTIONS.size,get normalizeActionName(){return readRuntimeTestHook("normalizeActionName")},get normalizeCommandPath(){return readRuntimeTestHook("normalizeCommandPath")},get normalizeMcpOptionsArrays(){return readRuntimeTestHook("normalizeMcpOptionsArrays")},get normalizeMcpUpdateOptions(){return readRuntimeTestHook("normalizeMcpUpdateOptions")},get optionsWithAuthor(){return readRuntimeTestHook("optionsWithAuthor")},get readRequiredString(){return readRuntimeTestHook("readRequiredString")},get readScalarString(){return readRuntimeTestHook("readScalarString")},get readScalarStringAllowBlank(){return readRuntimeTestHook("readScalarStringAllowBlank")},get readStringArray(){return readRuntimeTestHook("readStringArray")},runAction:runMcpAction,get updateManyOptionsFromFlat(){return readRuntimeTestHook("updateManyOptionsFromFlat")},get withAddNoteOption(){return readRuntimeTestHook("withAddNoteOption")},get withFilesDiscoveryOptions(){return readRuntimeTestHook("withFilesDiscoveryOptions")},get withMutationCompaction(){return readRuntimeTestHook("withMutationCompaction")},writeError};isInvokedAsMcpMainModule(process.argv[1],import.meta.url)&&startMcpServer();export{_testOnly,buildMcpToolCallErrorResult,closeMcpSubscription,handleRequest,isInvokedAsMcpMainModule,openMcpSubscription,processRpcLine,resolveMcpToolSchemaForRequest,startMcpServer};
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
/** Derive a same-command read retry for known completeness and encoding mistakes without discarding intent. */
|
|
2
|
+
export declare function resolveReadOptionRetryArgs(commandName:string,invocationArgv:readonly string[],unknownOption:string):string[] | undefined;
|
|
1
3
|
/** Identify presentation intent that must not be silently dropped from an unknown-option retry. */
|
|
2
4
|
export declare function isReadProjectionRecoveryFlag(flag:string):boolean;
|
|
3
5
|
/** Keep lexical corrections within read projection or mutation receipt semantics. */
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="54d81daa-9e2e-5b4d-b9f2-93f8d11f9fbc")}catch{}})();import{renderPmCommand}from"../command-line.js";import{resolveSubcommandFlagContractsForCommand}from"../cli-contracts/flag-contracts.js";import{parseBootstrapCommandName}from"../cli-contracts/bootstrap-command-scanner.js";import{READ_OUTPUT_DIMENSION_FLAGS,READ_OUTPUT_COMPOSITION_FLAGS}from"../read-output/options.js";import{resolvePmCommandOperation}from"../cli-contracts/command-aliases.js";const READ_PROJECTION_FLAGS=new Set([...Object.values(READ_OUTPUT_DIMENSION_FLAGS),...READ_OUTPUT_COMPOSITION_FLAGS,"--full","--brief","--compact","--summary","--fields","--section","--token-budget"]),MUTATION_RECEIPT_FLAGS=new Set(["--full-changed-fields","--no-changed-fields","--id-only"]);function readOptionCorrection(command,flag,token,next){if(flag==="--full"&&command==="context"&&token===flag)return{consumed:1,replacement:["--depth","full"],conflicts:["--depth","--output-include","--fields","--section","--for"]};if(flag==="--depth"&&["list","search"].includes(command)){const inline=token.includes("=");return(inline?token.slice(token.indexOf("=")+1):next)!=="full"?void 0:{consumed:inline?1:2,replacement:["--full"],conflicts:["--full","--brief","--compact","--output-include","--fields","--for"]}}return flag==="--toon"&&token===flag?{consumed:1,replacement:["--output-format","toon"],conflicts:["--json","--format","--output-format","--stream"]}:void 0}function resolveReadOptionRetryArgs(commandName,invocationArgv,unknownOption){const command=commandName==="ctx"?"context":resolvePmCommandOperation(commandName);if(!["context","list","search","get"].includes(command)||invocationArgv.includes("--"))return;const invoked=parseBootstrapCommandName(invocationArgv);if((invoked==="ctx"?"context":invoked)!==command)return;const flag=unknownOption.split("=",1)[0],indices=invocationArgv.flatMap((token,index2)=>token===flag||token.startsWith(`${flag}=`)?[index2]:[]);if(indices.length!==1)return;const index=indices[0],correction=readOptionCorrection(command,flag,invocationArgv[index],invocationArgv[index+1]);if(!correction)return;const{replacement,consumed,conflicts}=correction;if(!invocationArgv.some(argument=>conflicts.includes(argument.split("=",1)[0])))return[...invocationArgv.slice(0,index),...replacement,...invocationArgv.slice(index+consumed)]}function isReadProjectionRecoveryFlag(flag){const normalized=flag.split("=",1)[0].replaceAll("_","-");return READ_PROJECTION_FLAGS.has(normalized)||normalized.length>=5&&[...READ_PROJECTION_FLAGS].some(candidate=>candidate.startsWith(normalized))}function isCompatibleRecoveryFlag(requested,candidate){const unknownFlag=requested.split("=",1)[0].replaceAll("_","-");return isReadProjectionRecoveryFlag(unknownFlag)?!MUTATION_RECEIPT_FLAGS.has(candidate):MUTATION_RECEIPT_FLAGS.has(unknownFlag)?!isReadProjectionRecoveryFlag(candidate):!0}function normalizeMissingFlag(label){return label.trim().match(/--[a-z0-9][a-z0-9_-]*/i)?.[0]?.replaceAll("_","-").toLowerCase()}function resolveRecoveryCommandName(invocationArgv){if(!(!Array.isArray(invocationArgv)||invocationArgv.length===0))return parseBootstrapCommandName(invocationArgv)}function resolveMissingOptionPlaceholder(commandName,missingLabel){const flag=normalizeMissingFlag(missingLabel);if(!flag)return;const contract=resolveSubcommandFlagContractsForCommand(commandName).find(entry=>entry.flag===flag||entry.aliases?.includes(flag));return contract?contract.value_type==="boolean"?null:`<${contract.value_name??"value"}>`:"<value>"}function renderMissingOptionRetry(invocationArgv,commandName,missingLabels){const retry=[...invocationArgv],terminatorIndex=retry.indexOf("--");let insertionIndex=terminatorIndex<0?retry.length:terminatorIndex;for(const label of missingLabels){const flag=normalizeMissingFlag(label);if(!flag||retry.slice(0,insertionIndex).some(token=>token===flag||token.startsWith(`${flag}=`)))continue;const placeholder=resolveMissingOptionPlaceholder(commandName,flag),recoveredOption=placeholder?[flag,placeholder]:[flag];retry.splice(insertionIndex,0,...recoveredOption),insertionIndex+=recoveredOption.length}return retry.length===invocationArgv.length?void 0:renderPmCommand(retry)}export{isCompatibleRecoveryFlag,isReadProjectionRecoveryFlag,renderMissingOptionRetry,resolveMissingOptionPlaceholder,resolveReadOptionRetryArgs,resolveRecoveryCommandName};
|
|
2
2
|
//# sourceMappingURL=command-recovery.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="58e5d12e-060d-509d-9111-01d82054f4c3")}catch{}})();import{PM_TOOL_PARAMETER_PROPERTIES}from"./tool-parameter-tables.js";import{resolveExtensionFlagValueContract,resolveExtensionLongFlagName,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,SUBCOMMAND_GLOBAL_FLAG_CONTRACTS,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,resolveSubcommandFlagContractsForCommand}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"]]]),AGENT_BOUNDED_FLAG_PRIORITY=["--limit","--after","--offset","--token-budget","--brief","--summary","--compact","--fields","--full","--format","--since","--until"],LIST_COMMAND_NAMES=new Set(["list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"]),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"]),PACKAGE_OWNED_COMMANDS=new Set(["meet","event","remind","search-advanced","dedupe-audit","dedupe-merge","comments-audit","cal","calendar","completion","completion-statuses","completion-tags","completion-types","guide","reindex","normalize","templates","templates list","templates save","templates show","test-runs","test-runs list","test-runs status","test-runs logs","test-runs stop","test-runs resume"]),PACKAGE_OWNED_COMMAND_INSTALL_HINTS=new Map([["meet","calendar"],["event","calendar"],["remind","calendar"],["search-advanced","search-advanced"],["dedupe-audit","governance-audit"],["dedupe-merge","governance-audit"],["comments-audit","governance-audit"],["cal","calendar"],["calendar","calendar"],["completion","guide-shell"],["completion-statuses","guide-shell"],["completion-tags","guide-shell"],["completion-types","guide-shell"],["guide","guide-shell"],["reindex","search-advanced"],["normalize","governance-audit"],["templates","templates"],["templates list","templates"],["templates save","templates"],["templates show","templates"],["test-runs","linked-test-adapters"],["test-runs list","linked-test-adapters"],["test-runs status","linked-test-adapters"],["test-runs logs","linked-test-adapters"],["test-runs stop","linked-test-adapters"],["test-runs resume","linked-test-adapters"]]),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"]]),PACKAGE_OWNED_COMMAND_ACTIONS=new Map([...PACKAGE_OWNED_ACTION_COMMAND_PATHS.entries()].flatMap(([action,commandPaths])=>splitCommandPathAliases(commandPaths).map(commandPath=>[commandPath,action]))),CANONICAL_COMMAND_ALIASES=[{canonical:"context",aliases:["ctx"]},{canonical:"package",aliases:["extension","packages"]}],COMMAND_ALIAS_TO_CANONICAL=new Map(CANONICAL_COMMAND_ALIASES.flatMap(entry=>entry.aliases.map(alias=>[alias,entry.canonical]))),COMMAND_NAMESPACE_DISPLAY_LIMIT=10,COMMAND_NAMESPACE_FALLBACK_LIMIT=20,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."]]),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]],PACKAGE_LIFECYCLE_FLAG_CONTRACTS=[...EXTENSION_LIFECYCLE_FLAG_CONTRACTS.map(([subcommand,flags])=>subcommand==="init"?[subcommand,PACKAGE_INIT_FLAG_CONTRACTS]:[subcommand,flags]),["upgrade",UPGRADE_FLAG_CONTRACTS]],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])],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);flags!==void 0&&CORE_COMMAND_FLAG_CONTRACTS_BY_COMMAND.set(canonical,flags)}function packageOwnedActionForCommand(command){return PACKAGE_OWNED_COMMAND_ACTIONS.get(command)||(command.startsWith("test-runs ")?`test-runs-${command.slice(10)}`:command.startsWith("templates ")?`templates-${command.slice(10)}`:command)}function resolveActionCommandPath(action){const historyAlias=PM_NAMESPACED_COMMAND_ALIASES.find(contract=>contract.alias===action);return historyAlias?`${historyAlias.canonical}|${historyAlias.alias}`:PM_CORE_COMMAND_NAMES.includes(action)?normalizeCommandPath(action):action.startsWith("extension-")?normalizeCommandPath(`extension ${action.slice(10)}`):action.startsWith("package-")?normalizeCommandPath(`package ${action.slice(8)}`):action.startsWith("item-")?normalizeCommandPath(`item ${action.slice(5)}`):action.startsWith("test-runs-")?normalizeCommandPath(`test-runs ${action.slice(10)}`):action.startsWith("templates-")?normalizeCommandPath(`templates ${action.slice(10)}`):PACKAGE_OWNED_ACTIONS.has(action)?PACKAGE_OWNED_ACTION_COMMAND_PATHS.get(action)??normalizeCommandPath(action):null}function actionDescriptorMatchesSelectedCommand(descriptor,selectedCommand){const historyOperation=resolvePmCommandOperation(selectedCommand);return historyOperation!==selectedCommand||PM_NAMESPACED_COMMAND_ALIASES.some(entry=>entry.alias===selectedCommand)?descriptor.action===historyOperation:descriptor.command_path===null?!1:splitCommandPathAliases(descriptor.command_path).some(commandPath=>commandPath===selectedCommand?!0: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),scoped=new Set;for(const descriptor of descriptors)if(descriptor.command_path)for(const commandPath of splitCommandPathAliases(descriptor.command_path)){const tokens=commandPath.split(" ").filter(entry=>entry.length>0);if(tokens.length!==0)for(let end=tokens.length;end>0;end-=1){const candidate=tokens.slice(0,end).join(" ");if(commandSet.has(candidate)){scoped.add(candidate);break}}}return[...scoped].sort((left,right)=>left.localeCompare(right))}function normalizeToken(value){if(typeof value!="string")return;const trimmed=value.trim().toLowerCase();return trimmed.length>0?trimmed:void 0}function extractActionBranches(schema){const oneOf=schema.oneOf;return Array.isArray(oneOf)?oneOf.filter(entry=>typeof entry=="object"&&entry!==null):[]}function filterSchemaByAction(schema,action){if(!action)return{...schema};const filtered=extractActionBranches(schema).filter(entry=>{const properties=entry.properties;if(typeof properties!="object"||properties===null)return!1;const actionProperty=properties.action;return typeof actionProperty!="object"||actionProperty===null?!1:actionProperty.const===action});return{...schema,oneOf:filtered}}function filterSchemaByActions(schema,actions){const filtered=extractActionBranches(schema).filter(entry=>{const properties=entry.properties;if(typeof properties!="object"||properties===null)return!1;const actionProperty=properties.action;if(typeof actionProperty!="object"||actionProperty===null)return!1;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=[],seen=new Set;for(const value of values){const trimmed=toOptionalTrimmedString(value);!trimmed||seen.has(trimmed)||(seen.add(trimmed),normalized.push(trimmed))}return normalized}function assignExtensionFlagBoolean(contract,key,enabled){enabled&&(contract[key]=!0)}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();return trimmed.length===0?null:kind==="long"?trimmed.startsWith("--")&&trimmed.length>2?resolveExtensionLongFlagName(trimmed):null:trimmed.startsWith("-")&&!trimmed.startsWith("--")&&trimmed.length>1?trimmed:null}function toExtensionFlagContract(definition){const normalizedLong=normalizeExtensionFlagName(definition.long,"long"),normalizedShort=normalizeExtensionFlagName(definition.short,"short"),flag=normalizedLong??normalizedShort;if(!flag)return null;const contract={flag};normalizedShort&&normalizedLong&&(contract.short=normalizedShort),assignExtensionFlagBoolean(contract,"required",definition.required===!0),assignExtensionFlagBoolean(contract,"repeatable",definition.repeatable===!0),assignExtensionFlagBoolean(contract,"list",definition.list===!0);const description=toOptionalTrimmedString(definition.description);description&&(contract.description=description);const value=resolveExtensionFlagValueContract(definition);contract.value_arity=value.value_arity;const valueName=toOptionalTrimmedString(definition.value_name)??value.value_name;valueName&&(contract.value_name=valueName);const rawValueType=value.value_type??(value.value_name?"string":null);return rawValueType&&(contract.value_type=rawValueType),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},sourceKey=`${registration.layer}:${registration.name}`;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??""}`;bucket.dedupe.has(key)||(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);return layerOrder!==0?layerOrder:(left.name??"").localeCompare(right.name??"")})});return normalized}function extensionReadOutputDiscovery(definition,flags){return definition.read_output===void 0?{flags}:{read_output:definition.read_output,flags:[...flags,...SUBCOMMAND_GLOBAL_FLAG_CONTRACTS.filter(({flag})=>flag.startsWith("--output-"))]}}function collectExtensionCommandContracts(runtimeProbe){const flagsByCommand=collectExtensionFlagContractsByCommand(runtimeProbe.flagRegistrations),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),args=Array.isArray(definition.arguments)?definition.arguments.map(argument=>{const name=toOptionalTrimmedString(argument.name);return name?{name,required:argument.required===!0,variadic:argument.variadic===!0,description:toOptionalTrimmedString(argument.description)}:null}).filter(argument=>argument!==null):[];definitionsByCommand.set(command,{...definition.tier===void 0?{}:{tier:definition.tier},...extensionReadOutputDiscovery(definition,flagsByCommand.get(command)?.flags??[]),command,action,source:{layer:definition.layer,name:definition.name},description:toOptionalTrimmedString(definition.description),intent:toOptionalTrimmedString(definition.intent),arguments:args,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){return definition?{...definition,flags:definition.flags.length>0?definition.flags:registeredFlags}:{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 cleaned=normalized.replace(/-([a-z0-9])/g,(_match,char)=>char.toUpperCase()).replace(/[^a-zA-Z0-9]/g,"");return cleaned.length>0?cleaned:null}function buildExtensionArgumentSchema(argument,action){return argument.variadic?{type:"array",items:{type:"string"},description:argument.description??`Variadic argument '${argument.name}' for extension action '${action}'.`}:{type:"string",description:argument.description??`Argument '${argument.name}' for extension action '${action}'.`}}function buildExtensionFlagSchema(flag,action){const valueType=flag.value_type??"boolean",schemaType=valueType==="boolean"?"boolean":valueType==="number"?["number","string"]:"string",acceptsMultipleValues=flag.repeatable===!0||flag.list===!0;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),properties={action:{type:"string",const:contract.action,description:contract.intent??contract.description??`Invoke extension command '${contract.command}'.`}},required=["action"];for(const argument of contract.arguments)properties[argument.name]=buildExtensionArgumentSchema(argument,contract.action),argument.required&&required.push(argument.name);for(const flag of contract.flags){const propertyName=extensionSchemaPropertyNameFromFlag(flag);!propertyName||properties[propertyName]!==void 0||(properties[propertyName]=SUBCOMMAND_GLOBAL_FLAG_CONTRACTS.some(host=>host.flag===flag.flag&&host.flag.startsWith("--output-"))?PM_TOOL_PARAMETER_PROPERTIES[propertyName]:buildExtensionFlagSchema(flag,contract.action),flag.required===!0&&required.push(propertyName))}return{type:"object",properties,required,additionalProperties:!0,"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,incoming.required===!0&&(existing.required=!0),incoming.repeatable===!0&&(existing.repeatable=!0)}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);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),loadResult=await loadExtensions({pmRoot,settings,cwd:process.cwd(),noExtensions:!1}),activationResult=await activateExtensions({...loadResult,loaded:loadResult.loaded});return{handlers:new Set(activationResult.commands.handlers.map(entry=>normalizeCommandPath(entry.command))),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)descriptors.has(action)||descriptors.set(action,{action,provider:"extension",requires_extension:!0,command_path:resolveActionCommandPath(action)});for(const contract of extensionContracts)descriptors.has(contract.action)||descriptors.set(contract.action,{action:contract.action,provider:"extension",requires_extension:!0,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:!0,available:!0,requires_extension:!1,provider:"core",disabled_reason:null,command_path:descriptor.command_path,cli_exposed:descriptor.command_path!==null&&(!PACKAGE_OWNED_COMMANDS.has(descriptor.action)||runtimeProbe.handlers.has(descriptor.action))};const commandPaths=descriptor.command_path?splitCommandPathAliases(descriptor.command_path):[],extensionCommandAvailable=commandPaths.some(commandPath=>runtimeProbe.handlers.has(commandPath)||runtimeProbe.handlers.has(resolvePmCommandOperation(commandPath))),optionalPackageHint=commandPaths.map(commandPath=>PACKAGE_OWNED_COMMAND_INSTALL_HINTS.get(resolvePmCommandOperation(commandPath))).find(hint=>typeof hint=="string"),invocable=runtimeProbe.disabledReason===null&&extensionCommandAvailable;return{action:descriptor.action,invocable,available:invocable,requires_extension:!0,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){const flags=CORE_COMMAND_FLAG_CONTRACTS_BY_COMMAND.get(command)??GLOBAL_FLAG_CONTRACTS,encoding=resolveSubcommandFlagContractsForCommand(command).find(contract=>contract.flag==="--output-format"&&contract.aliases?.includes("--format"));return encoding?[...flags,encoding]:flags}function isCoreCommandPath(command){return PACKAGE_OWNED_COMMANDS.has(resolvePmCommandOperation(command))?!1:CORE_COMMAND_FLAG_CONTRACTS_BY_COMMAND.has(command)}function normalizeCommandForRuntimeFieldFlags(command){return LIST_COMMAND_NAMES.has(command)?"list":command==="cal"?"calendar":command==="ctx"?"context":command==="update-many"?"update_many":command}function toRuntimeLongFlagToken(token){const trimmed=token.trim();return trimmed?trimmed.startsWith("--")?trimmed:trimmed.startsWith("-")?null:`--${trimmed}`:null}function toRuntimeShortFlagToken(token){const trimmed=token.trim();return!trimmed||trimmed.startsWith("--")?null:trimmed.startsWith("-")?trimmed: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),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},primaryContract=shortAlias?{flag:primaryFlag,short:shortAlias}:{flag:primaryFlag},primaryKey=`${primaryContract.flag}|${primaryContract.short??""}`;bucket.seen.has(primaryKey)||(bucket.seen.add(primaryKey),bucket.flags.push(primaryContract));for(const alias of longAliases){const key=`${alias}|`;bucket.seen.has(key)||(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=[],seen=new Set;for(const contract of[...primary,...secondary]){const key=`${contract.flag}|${contract.short??""}`;seen.has(key)||(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);flags&&(flagsByPath.set(alias,flags),flagsByPath.set(canonical,flags))}return commands.map(command=>{const isCoreCommand=isCoreCommandPath(command),coreFlags=isCoreCommand?resolveCoreCommandFlags(command):[],runtimeFlags=runtimeFieldFlagMap.get(normalizeCommandForRuntimeFieldFlags(command))??[],extensionFlags=flagsByPath.get(command),coreWithRuntime=mergeFlagContracts(coreFlags,runtimeFlags),flags=mergeFlagContracts(coreWithRuntime,extensionFlags?.flags??[]),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),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)||contract.registration==="commander"&&!commandSet.has(contract.alias))continue;const entry=grouped.get(contract.canonical)??{canonical:contract.canonical,aliases:[],contracts:[]};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),requiredOptionKeys=[...new Set(policyState.required)].sort((left,right)=>left.localeCompare(right)),requiredFlags=[...new Set(requiredOptionKeys.map(option=>commandOptionFlagLabel("create",option)))].sort((left,right)=>left.localeCompare(right)),requiredTypeOptions=[...new Set(typeDefinition.options.filter(option=>option.required===!0).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={},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=!1;const enrichedBranches=branches.map(branch=>{const properties=branch.properties;if(typeof properties!="object"||properties===null)return branch;const actionProperty=properties.action;return typeof actionProperty!="object"||actionProperty===null||actionProperty.const!=="create"?branch:(touched=!0,{...branch,"x-create-required-options":metadata})});return touched?{...schema,oneOf:enrichedBranches}:schema}function resolveContractsSelection(options){const explicitlyScoped=normalizeToken(options.action)!==void 0||normalizeToken(options.command)!==void 0,projectionSelected=options.schemaOnly===!0||options.flagsOnly===!0||options.availabilityOnly===!0,summary=options.summary===!0||options.full!==!0&&options.runtimeOnly!==!0&&!explicitlyScoped&&!projectionSelected,schemaOnly=options.schemaOnly===!0,flagsOnly=options.flagsOnly===!0,availabilityOnly=options.availabilityOnly===!0,runtimeOnly=options.runtimeOnly===!0,fullOutput=options.full===!0,selectedAction=normalizeToken(options.action),selectedCommand=normalizeToken(options.command),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){if([selection.summary,selection.schemaOnly,selection.flagsOnly,selection.availabilityOnly].filter(value=>value).length>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),runtimeProbe=await resolveRuntimeExtensionActionProbe(global2),typeRegistry=resolveItemTypeRegistry(settings,runtimeProbe.registrations??getActiveExtensionRegistrations()),runtimeFieldRegistry=resolveRuntimeFieldRegistry(settings.schema),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"))}return 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:!0,command_path:selection.selectedCommand}),actionDescriptors}function assertKnownContractsAction(selection,actionDescriptors){const actionNames=new Set(actionDescriptors.map(entry=>entry.action));if(selection.selectedAction&&!actionNames.has(selection.selectedAction))throw new PmCliError(`Unknown action: "${selection.selectedAction}".`,EXIT_CODE.USAGE)}function buildContractsCommandCatalog(actionDescriptors,mergedExtensionContracts){return[...new Set([...PM_CORE_COMMAND_NAMES.filter(entry=>!PACKAGE_OWNED_COMMANDS.has(resolvePmCommandOperation(entry))),...[...CORE_COMMAND_FLAG_CONTRACTS_BY_COMMAND.keys()].filter(entry=>!PACKAGE_OWNED_COMMANDS.has(resolvePmCommandOperation(entry))),...actionDescriptors.flatMap(entry=>entry.command_path?splitCommandPathAliases(entry.command_path).filter(command=>entry.provider==="extension"||!PACKAGE_OWNED_COMMANDS.has(resolvePmCommandOperation(command))||mergedExtensionContracts.some(contract=>contract.action===entry.action)):[]),...mergedExtensionContracts.flatMap(entry=>entry.command.split("|").flatMap(command=>{const alias=PM_NAMESPACED_COMMAND_ALIASES.find(entry2=>entry2.alias===command||entry2.canonical===command);return alias===void 0?[command]:[alias.alias,alias.canonical]}))])].map(entry=>normalizeCommandPath(entry)).filter(entry=>entry.length>0).sort((left,right)=>left.localeCompare(right))}function buildCommandNamespaceError(command,namespaceChildren){const displayedNamespaceChildren=namespaceChildren.slice(0,COMMAND_NAMESPACE_DISPLAY_LIMIT),hiddenNamespaceChildCount=namespaceChildren.length-displayedNamespaceChildren.length,displayedChildCommandList=hiddenNamespaceChildCount>0?`${displayedNamespaceChildren.join(", ")}, and ${hiddenNamespaceChildCount} more`:displayedNamespaceChildren.join(", "),fallbackCandidates=namespaceChildren.slice(0,COMMAND_NAMESPACE_FALLBACK_LIMIT),childCommandExamples=namespaceChildren.slice(0,5).map(childCommand=>`pm contracts --command "${childCommand}" --flags-only --json`),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 package 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 package install ${packageHint} --project`,`pm contracts --command ${command} --flags-only --json`],nextSteps:[`Install the optional package first: pm package install ${packageHint} --project`],recovery:{suggested_retry:`pm package 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||new Set(commandCatalog).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));throw packageHint?buildPackageOwnedCommandError(selection.selectedCommand,packageHint):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,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,allActionAvailability=[...new Map(scopedActionDescriptors.map(descriptor=>resolveActionAvailability(descriptor,runtime.runtimeProbe)).map(entry=>[selectedPackageOwnedAction?entry.action:`${entry.action}|${entry.command_path??""}`,entry])).values()],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,schemaBranches=extractActionBranches(schema),schemaActionSet=buildSchemaActionSet(schema),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)),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),filteredSchema=!selection.flagsOnly&&!selection.availabilityOnly?attachCreateRequiredOptionContracts(filterContractsSchema(selection,actionContext,mergedSchema),runtime.createRequiredOptionContracts):filterContractsSchema(selection,actionContext,mergedSchema);return{mergedSchema,filteredSchema}}function resolveContractsCommands(selection,actionContext){return selection.selectedCommand!==void 0?[selection.selectedCommand]:selection.selectedAction?resolveScopedCommandsFromActionDescriptors(actionContext.scopedActionDescriptors,actionContext.commandCatalog):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];return rootCommand.startsWith("list-")?"list":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"]]),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(" "),operation=tokens.at(-1),subject=tokens.slice(0,-1).join(" "),verb=COMMAND_OPERATION_INTENTS.get(operation),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??!0,includeIntentProvenance=options.includeIntentProvenance??!0;return[...new Set(commands.map(normalizeCommandPath))].filter(command=>command.length>0).sort((left,right)=>left.localeCompare(right)).map(command=>{const budget=resolvePmCommandOutputBudget(command,{generateFallback:!0}),rootCommand=command.split(" ")[0],canonicalRoot=COMMAND_ALIAS_TO_CANONICAL.get(rootCommand)??(rootCommand.startsWith("list-")?"list":rootCommand.startsWith("history-")?"history":rootCommand),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))]),flags=(AGENT_BOOTSTRAP_FLAGS.get(resolvePmCommandOperation(command))??AGENT_BOOTSTRAP_FLAGS.get(canonicalRoot)??AGENT_BOUNDED_FLAG_PRIORITY).filter(flag=>availableFlags.has(flag)),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:!0}),envelope:resolvePmCommandOutputEnvelope(command)}))}function buildCommandExitContractGroups(commands){const groups=new Map;for(const command of commands){const contract=resolvePmCommandExitContract(command),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,key=exitCodes.join(","),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){(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))]))},!(selectedCommand!==void 0&&!selection.fullOutput)&&(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)){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)){if(selection.omitUnfilteredCommandFlags)result.command_flags_omitted_reason="unfiltered_default_brief";else{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]}))}result.command_aliases=selection.fullOutput?commandAliases:commandAliases.map(({canonical,aliases})=>({canonical,aliases})),selection.fullOutput||(result.command_alias_contracts_omitted_reason="compact_projection; restore with --full")}}function attachCommanderAliasContractsResult(result,selection){if(!(selection.schemaOnly||selection.flagsOnly||selection.availabilityOnly)){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:!0},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),runtime=await resolveContractsRuntimeContext(global2,pmRoot,selection),actionContext=resolveContractsActionContext(selection,runtime),schemaContext=resolveContractsSchemaContext(selection,runtime,actionContext),commands=resolveContractsCommands(selection,actionContext),outputCommands=resolveOutputCommands(selection,commands,runtime.extensionContracts),result=createContractsResult(selection,schemaContext,actionContext,outputCommands),extensionCommandContracts=resolveExtensionCommandContracts(selection,runtime,outputCommands),includeCommandDetails=selection.fullOutput||selection.selectedCommand!==void 0;if((selection.summary||selection.fullOutput)&&attachAgentCommandContractsResult(result,outputCommands,extensionCommandContracts,{includeFormatBudgets:includeCommandDetails,includeIntentProvenance:includeCommandDetails,includePositionalSignatures:includeCommandDetails,includeProjectionModeMatrix:includeCommandDetails}),selection.summary)return result;const commandAliases=buildCommandAliasSurface(actionContext.commandCatalog.filter(command=>isCommandDiscoverable(selection,command,runtime.extensionContracts)));return selection.flagsOnly&&!selection.fullOutput||attachRuntimeContractsResult(result,runtime,selection),attachSchemaContractsResult(result,selection,schemaContext,extensionCommandContracts),attachFlagContractsResult(result,selection,runtime,outputCommands,commandAliases),attachCommanderAliasContractsResult(result,selection),(selection.selectedCommand==="assurance"||selection.fullOutput)&&(result.assurance_contracts={measurement_source_kinds:[...ASSURANCE_MEASUREMENT_SOURCE_KINDS],gate_triggers:[...ASSURANCE_GATE_TRIGGERS]}),selection.fullOutput&&result.grammar_contracts&&(result.grammar_contracts.destinations=PM_COMMAND_DESTINATION_CONTRACTS.map(row=>({...row,reason:row.reason??""}))),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)}),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=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="0e712e06-ae64-59c2-aea5-2cba11c55447")}catch{}})();import{PM_TOOL_PARAMETER_PROPERTIES}from"./tool-parameter-tables.js";import{resolveExtensionFlagValueContract,resolveExtensionLongFlagName,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,SUBCOMMAND_GLOBAL_FLAG_CONTRACTS,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,resolveSubcommandFlagContractsForCommand}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"]]]),AGENT_BOUNDED_FLAG_PRIORITY=["--limit","--after","--offset","--token-budget","--brief","--summary","--compact","--fields","--full","--format","--since","--until"],LIST_COMMAND_NAMES=new Set(["list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"]),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"]),PACKAGE_OWNED_COMMANDS=new Set(["meet","event","remind","search-advanced","dedupe-audit","dedupe-merge","comments-audit","cal","calendar","completion","completion-statuses","completion-tags","completion-types","guide","reindex","normalize","templates","templates list","templates save","templates show","test-runs","test-runs list","test-runs status","test-runs logs","test-runs stop","test-runs resume"]),PACKAGE_OWNED_COMMAND_INSTALL_HINTS=new Map([["meet","calendar"],["event","calendar"],["remind","calendar"],["search-advanced","search-advanced"],["dedupe-audit","governance-audit"],["dedupe-merge","governance-audit"],["comments-audit","governance-audit"],["cal","calendar"],["calendar","calendar"],["completion","guide-shell"],["completion-statuses","guide-shell"],["completion-tags","guide-shell"],["completion-types","guide-shell"],["guide","guide-shell"],["reindex","search-advanced"],["normalize","governance-audit"],["templates","templates"],["templates list","templates"],["templates save","templates"],["templates show","templates"],["test-runs","linked-test-adapters"],["test-runs list","linked-test-adapters"],["test-runs status","linked-test-adapters"],["test-runs logs","linked-test-adapters"],["test-runs stop","linked-test-adapters"],["test-runs resume","linked-test-adapters"]]),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"]]),PACKAGE_OWNED_COMMAND_ACTIONS=new Map([...PACKAGE_OWNED_ACTION_COMMAND_PATHS.entries()].flatMap(([action,commandPaths])=>splitCommandPathAliases(commandPaths).map(commandPath=>[commandPath,action]))),CANONICAL_COMMAND_ALIASES=[{canonical:"context",aliases:["ctx"]},{canonical:"package",aliases:["extension","packages"]}],COMMAND_ALIAS_TO_CANONICAL=new Map(CANONICAL_COMMAND_ALIASES.flatMap(entry=>entry.aliases.map(alias=>[alias,entry.canonical]))),COMMAND_NAMESPACE_DISPLAY_LIMIT=10,COMMAND_NAMESPACE_FALLBACK_LIMIT=20,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."]]),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]],PACKAGE_LIFECYCLE_FLAG_CONTRACTS=[...EXTENSION_LIFECYCLE_FLAG_CONTRACTS.map(([subcommand,flags])=>subcommand==="init"?[subcommand,PACKAGE_INIT_FLAG_CONTRACTS]:[subcommand,flags]),["upgrade",UPGRADE_FLAG_CONTRACTS]],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])],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);flags!==void 0&&CORE_COMMAND_FLAG_CONTRACTS_BY_COMMAND.set(canonical,flags)}function packageOwnedActionForCommand(command){return PACKAGE_OWNED_COMMAND_ACTIONS.get(command)||(command.startsWith("test-runs ")?`test-runs-${command.slice(10)}`:command.startsWith("templates ")?`templates-${command.slice(10)}`:command)}function resolveActionCommandPath(action){const historyAlias=PM_NAMESPACED_COMMAND_ALIASES.find(contract=>contract.alias===action);return historyAlias?`${historyAlias.canonical}|${historyAlias.alias}`:PM_CORE_COMMAND_NAMES.includes(action)?normalizeCommandPath(action):action.startsWith("extension-")?normalizeCommandPath(`extension ${action.slice(10)}`):action.startsWith("package-")?normalizeCommandPath(`package ${action.slice(8)}`):action.startsWith("item-")?normalizeCommandPath(`item ${action.slice(5)}`):action.startsWith("test-runs-")?normalizeCommandPath(`test-runs ${action.slice(10)}`):action.startsWith("templates-")?normalizeCommandPath(`templates ${action.slice(10)}`):PACKAGE_OWNED_ACTIONS.has(action)?PACKAGE_OWNED_ACTION_COMMAND_PATHS.get(action)??normalizeCommandPath(action):null}function actionDescriptorMatchesSelectedCommand(descriptor,selectedCommand){const historyOperation=resolvePmCommandOperation(selectedCommand);return historyOperation!==selectedCommand||PM_NAMESPACED_COMMAND_ALIASES.some(entry=>entry.alias===selectedCommand)?descriptor.action===historyOperation:descriptor.command_path===null?!1:splitCommandPathAliases(descriptor.command_path).some(commandPath=>commandPath===selectedCommand?!0: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),scoped=new Set;for(const descriptor of descriptors)if(descriptor.command_path)for(const commandPath of splitCommandPathAliases(descriptor.command_path)){const tokens=commandPath.split(" ").filter(entry=>entry.length>0);if(tokens.length!==0)for(let end=tokens.length;end>0;end-=1){const candidate=tokens.slice(0,end).join(" ");if(commandSet.has(candidate)){scoped.add(candidate);break}}}return[...scoped].sort((left,right)=>left.localeCompare(right))}function normalizeToken(value){if(typeof value!="string")return;const trimmed=value.trim().toLowerCase();return trimmed.length>0?trimmed:void 0}function extractActionBranches(schema){const oneOf=schema.oneOf;return Array.isArray(oneOf)?oneOf.filter(entry=>typeof entry=="object"&&entry!==null):[]}function filterSchemaByAction(schema,action){if(!action)return{...schema};const filtered=extractActionBranches(schema).filter(entry=>{const properties=entry.properties;if(typeof properties!="object"||properties===null)return!1;const actionProperty=properties.action;return typeof actionProperty!="object"||actionProperty===null?!1:actionProperty.const===action});return{...schema,oneOf:filtered}}function filterSchemaByActions(schema,actions){const filtered=extractActionBranches(schema).filter(entry=>{const properties=entry.properties;if(typeof properties!="object"||properties===null)return!1;const actionProperty=properties.action;if(typeof actionProperty!="object"||actionProperty===null)return!1;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=[],seen=new Set;for(const value of values){const trimmed=toOptionalTrimmedString(value);!trimmed||seen.has(trimmed)||(seen.add(trimmed),normalized.push(trimmed))}return normalized}function assignExtensionFlagBoolean(contract,key,enabled){enabled&&(contract[key]=!0)}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();return trimmed.length===0?null:kind==="long"?trimmed.startsWith("--")&&trimmed.length>2?resolveExtensionLongFlagName(trimmed):null:trimmed.startsWith("-")&&!trimmed.startsWith("--")&&trimmed.length>1?trimmed:null}function toExtensionFlagContract(definition){const normalizedLong=normalizeExtensionFlagName(definition.long,"long"),normalizedShort=normalizeExtensionFlagName(definition.short,"short"),flag=normalizedLong??normalizedShort;if(!flag)return null;const contract={flag};normalizedShort&&normalizedLong&&(contract.short=normalizedShort),assignExtensionFlagBoolean(contract,"required",definition.required===!0),assignExtensionFlagBoolean(contract,"repeatable",definition.repeatable===!0),assignExtensionFlagBoolean(contract,"list",definition.list===!0);const description=toOptionalTrimmedString(definition.description);description&&(contract.description=description);const value=resolveExtensionFlagValueContract(definition);contract.value_arity=value.value_arity;const valueName=toOptionalTrimmedString(definition.value_name)??value.value_name;valueName&&(contract.value_name=valueName);const rawValueType=value.value_type??(value.value_name?"string":null);return rawValueType&&(contract.value_type=rawValueType),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},sourceKey=`${registration.layer}:${registration.name}`;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??""}`;bucket.dedupe.has(key)||(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);return layerOrder!==0?layerOrder:(left.name??"").localeCompare(right.name??"")})});return normalized}function extensionReadOutputDiscovery(definition,flags){return definition.read_output===void 0?{flags}:{read_output:definition.read_output,flags:[...flags,...SUBCOMMAND_GLOBAL_FLAG_CONTRACTS.filter(({flag})=>flag.startsWith("--output-"))]}}function collectExtensionCommandContracts(runtimeProbe){const flagsByCommand=collectExtensionFlagContractsByCommand(runtimeProbe.flagRegistrations),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),args=Array.isArray(definition.arguments)?definition.arguments.map(argument=>{const name=toOptionalTrimmedString(argument.name);return name?{name,required:argument.required===!0,variadic:argument.variadic===!0,description:toOptionalTrimmedString(argument.description)}:null}).filter(argument=>argument!==null):[];definitionsByCommand.set(command,{...definition.tier===void 0?{}:{tier:definition.tier},...extensionReadOutputDiscovery(definition,flagsByCommand.get(command)?.flags??[]),command,action,source:{layer:definition.layer,name:definition.name},description:toOptionalTrimmedString(definition.description),intent:toOptionalTrimmedString(definition.intent),arguments:args,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){return definition?{...definition,flags:definition.flags.length>0?definition.flags:registeredFlags}:{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 cleaned=normalized.replace(/-([a-z0-9])/g,(_match,char)=>char.toUpperCase()).replace(/[^a-zA-Z0-9]/g,"");return cleaned.length>0?cleaned:null}function buildExtensionArgumentSchema(argument,action){return argument.variadic?{type:"array",items:{type:"string"},description:argument.description??`Variadic argument '${argument.name}' for extension action '${action}'.`}:{type:"string",description:argument.description??`Argument '${argument.name}' for extension action '${action}'.`}}function buildExtensionFlagSchema(flag,action){const valueType=flag.value_type??"boolean",schemaType=valueType==="boolean"?"boolean":valueType==="number"?["number","string"]:"string",acceptsMultipleValues=flag.repeatable===!0||flag.list===!0;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),properties={action:{type:"string",const:contract.action,description:contract.intent??contract.description??`Invoke extension command '${contract.command}'.`}},required=["action"];for(const argument of contract.arguments)properties[argument.name]=buildExtensionArgumentSchema(argument,contract.action),argument.required&&required.push(argument.name);for(const flag of contract.flags){const propertyName=extensionSchemaPropertyNameFromFlag(flag);!propertyName||properties[propertyName]!==void 0||(properties[propertyName]=SUBCOMMAND_GLOBAL_FLAG_CONTRACTS.some(host=>host.flag===flag.flag&&host.flag.startsWith("--output-"))?PM_TOOL_PARAMETER_PROPERTIES[propertyName]:buildExtensionFlagSchema(flag,contract.action),flag.required===!0&&required.push(propertyName))}return{type:"object",properties,required,additionalProperties:!0,"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,incoming.required===!0&&(existing.required=!0),incoming.repeatable===!0&&(existing.repeatable=!0)}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);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),loadResult=await loadExtensions({pmRoot,settings,cwd:process.cwd(),noExtensions:!1}),activationResult=await activateExtensions({...loadResult,loaded:loadResult.loaded});return{handlers:new Set(activationResult.commands.handlers.map(entry=>normalizeCommandPath(entry.command))),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)descriptors.has(action)||descriptors.set(action,{action,provider:"extension",requires_extension:!0,command_path:resolveActionCommandPath(action)});for(const contract of extensionContracts)descriptors.has(contract.action)||descriptors.set(contract.action,{action:contract.action,provider:"extension",requires_extension:!0,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:!0,available:!0,requires_extension:!1,provider:"core",disabled_reason:null,command_path:descriptor.command_path,cli_exposed:descriptor.command_path!==null&&(!PACKAGE_OWNED_COMMANDS.has(descriptor.action)||runtimeProbe.handlers.has(descriptor.action))};const commandPaths=descriptor.command_path?splitCommandPathAliases(descriptor.command_path):[],extensionCommandAvailable=commandPaths.some(commandPath=>runtimeProbe.handlers.has(commandPath)||runtimeProbe.handlers.has(resolvePmCommandOperation(commandPath))),optionalPackageHint=commandPaths.map(commandPath=>PACKAGE_OWNED_COMMAND_INSTALL_HINTS.get(resolvePmCommandOperation(commandPath))).find(hint=>typeof hint=="string"),invocable=runtimeProbe.disabledReason===null&&extensionCommandAvailable;return{action:descriptor.action,invocable,available:invocable,requires_extension:!0,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){const flags=CORE_COMMAND_FLAG_CONTRACTS_BY_COMMAND.get(command)??GLOBAL_FLAG_CONTRACTS,encoding=resolveSubcommandFlagContractsForCommand(command).find(contract=>contract.flag==="--output-format"&&contract.aliases?.includes("--format"));return encoding?[...flags,encoding]:flags}function isCoreCommandPath(command){return PACKAGE_OWNED_COMMANDS.has(resolvePmCommandOperation(command))?!1:CORE_COMMAND_FLAG_CONTRACTS_BY_COMMAND.has(command)}function normalizeCommandForRuntimeFieldFlags(command){return LIST_COMMAND_NAMES.has(command)?"list":command==="cal"?"calendar":command==="ctx"?"context":command==="update-many"?"update_many":command}function toRuntimeLongFlagToken(token){const trimmed=token.trim();return trimmed?trimmed.startsWith("--")?trimmed:trimmed.startsWith("-")?null:`--${trimmed}`:null}function toRuntimeShortFlagToken(token){const trimmed=token.trim();return!trimmed||trimmed.startsWith("--")?null:trimmed.startsWith("-")?trimmed: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),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},primaryContract=shortAlias?{flag:primaryFlag,short:shortAlias}:{flag:primaryFlag},primaryKey=`${primaryContract.flag}|${primaryContract.short??""}`;bucket.seen.has(primaryKey)||(bucket.seen.add(primaryKey),bucket.flags.push(primaryContract));for(const alias of longAliases){const key=`${alias}|`;bucket.seen.has(key)||(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=[],seen=new Set;for(const contract of[...primary,...secondary]){const key=`${contract.flag}|${contract.short??""}`;seen.has(key)||(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);flags&&(flagsByPath.set(alias,flags),flagsByPath.set(canonical,flags))}return commands.map(command=>{const isCoreCommand=isCoreCommandPath(command),coreFlags=isCoreCommand?resolveCoreCommandFlags(command):[],runtimeFlags=runtimeFieldFlagMap.get(normalizeCommandForRuntimeFieldFlags(command))??[],extensionFlags=flagsByPath.get(command),coreWithRuntime=mergeFlagContracts(coreFlags,runtimeFlags),flags=mergeFlagContracts(coreWithRuntime,extensionFlags?.flags??[]),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),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)||contract.registration==="commander"&&!commandSet.has(contract.alias))continue;const entry=grouped.get(contract.canonical)??{canonical:contract.canonical,aliases:[],contracts:[]};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),requiredOptionKeys=[...new Set(policyState.required)].sort((left,right)=>left.localeCompare(right)),requiredFlags=[...new Set(requiredOptionKeys.map(option=>commandOptionFlagLabel("create",option)))].sort((left,right)=>left.localeCompare(right)),requiredTypeOptions=[...new Set(typeDefinition.options.filter(option=>option.required===!0).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={},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=!1;const enrichedBranches=branches.map(branch=>{const properties=branch.properties;if(typeof properties!="object"||properties===null)return branch;const actionProperty=properties.action;return typeof actionProperty!="object"||actionProperty===null||actionProperty.const!=="create"?branch:(touched=!0,{...branch,"x-create-required-options":metadata})});return touched?{...schema,oneOf:enrichedBranches}:schema}function resolveContractsSelection(options){const explicitlyScoped=normalizeToken(options.action)!==void 0||normalizeToken(options.command)!==void 0,projectionSelected=options.schemaOnly===!0||options.flagsOnly===!0||options.availabilityOnly===!0,summary=options.summary===!0||options.full!==!0&&options.runtimeOnly!==!0&&!explicitlyScoped&&!projectionSelected,schemaOnly=options.schemaOnly===!0,flagsOnly=options.flagsOnly===!0,availabilityOnly=options.availabilityOnly===!0,runtimeOnly=options.runtimeOnly===!0,fullOutput=options.full===!0,selectedAction=normalizeToken(options.action),selectedCommand=normalizeToken(options.command),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){if([selection.summary,selection.schemaOnly,selection.flagsOnly,selection.availabilityOnly].filter(value=>value).length>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),runtimeProbe=await resolveRuntimeExtensionActionProbe(global2),typeRegistry=resolveItemTypeRegistry(settings,runtimeProbe.registrations??getActiveExtensionRegistrations()),runtimeFieldRegistry=resolveRuntimeFieldRegistry(settings.schema),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"))}return 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:!0,command_path:selection.selectedCommand}),actionDescriptors}function assertKnownContractsAction(selection,actionDescriptors){const actionNames=new Set(actionDescriptors.map(entry=>entry.action));if(selection.selectedAction&&!actionNames.has(selection.selectedAction))throw new PmCliError(`Unknown action: "${selection.selectedAction}".`,EXIT_CODE.USAGE)}function buildContractsCommandCatalog(actionDescriptors,mergedExtensionContracts){return[...new Set([...PM_CORE_COMMAND_NAMES.filter(entry=>!PACKAGE_OWNED_COMMANDS.has(resolvePmCommandOperation(entry))),...[...CORE_COMMAND_FLAG_CONTRACTS_BY_COMMAND.keys()].filter(entry=>!PACKAGE_OWNED_COMMANDS.has(resolvePmCommandOperation(entry))),...actionDescriptors.flatMap(entry=>entry.command_path?splitCommandPathAliases(entry.command_path).filter(command=>entry.provider==="extension"||!PACKAGE_OWNED_COMMANDS.has(resolvePmCommandOperation(command))||mergedExtensionContracts.some(contract=>contract.action===entry.action)):[]),...mergedExtensionContracts.flatMap(entry=>entry.command.split("|").flatMap(command=>{const alias=PM_NAMESPACED_COMMAND_ALIASES.find(entry2=>entry2.alias===command||entry2.canonical===command);return alias===void 0?[command]:[alias.alias,alias.canonical]}))])].map(entry=>normalizeCommandPath(entry)).filter(entry=>entry.length>0).sort((left,right)=>left.localeCompare(right))}function buildCommandNamespaceError(command,namespaceChildren){const displayedNamespaceChildren=namespaceChildren.slice(0,COMMAND_NAMESPACE_DISPLAY_LIMIT),hiddenNamespaceChildCount=namespaceChildren.length-displayedNamespaceChildren.length,displayedChildCommandList=hiddenNamespaceChildCount>0?`${displayedNamespaceChildren.join(", ")}, and ${hiddenNamespaceChildCount} more`:displayedNamespaceChildren.join(", "),fallbackCandidates=namespaceChildren.slice(0,COMMAND_NAMESPACE_FALLBACK_LIMIT),childCommandExamples=namespaceChildren.slice(0,5).map(childCommand=>`pm contracts --command "${childCommand}" --flags-only --json`),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 package 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 package install ${packageHint} --project`,`pm contracts --command ${command} --flags-only --json`],nextSteps:[`Install the optional package first: pm package install ${packageHint} --project`],recovery:{suggested_retry:`pm package 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||new Set(commandCatalog).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));throw packageHint?buildPackageOwnedCommandError(selection.selectedCommand,packageHint):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,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,allActionAvailability=[...new Map(scopedActionDescriptors.map(descriptor=>resolveActionAvailability(descriptor,runtime.runtimeProbe)).map(entry=>[selectedPackageOwnedAction?entry.action:`${entry.action}|${entry.command_path??""}`,entry])).values()],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,schemaBranches=extractActionBranches(schema),schemaActionSet=buildSchemaActionSet(schema),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)),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),filteredSchema=!selection.flagsOnly&&!selection.availabilityOnly?attachCreateRequiredOptionContracts(filterContractsSchema(selection,actionContext,mergedSchema),runtime.createRequiredOptionContracts):filterContractsSchema(selection,actionContext,mergedSchema);return{mergedSchema,filteredSchema}}function resolveContractsCommands(selection,actionContext){return selection.selectedCommand!==void 0?[selection.selectedCommand]:selection.selectedAction?resolveScopedCommandsFromActionDescriptors(actionContext.scopedActionDescriptors,actionContext.commandCatalog):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];return rootCommand.startsWith("list-")?"list":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"]]),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(" "),operation=tokens.at(-1),subject=tokens.slice(0,-1).join(" "),verb=COMMAND_OPERATION_INTENTS.get(operation),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??!0,includeIntentProvenance=options.includeIntentProvenance??!0;return[...new Set(commands.map(normalizeCommandPath))].filter(command=>command.length>0).sort((left,right)=>left.localeCompare(right)).map(command=>{const budget=resolvePmCommandOutputBudget(command,{generateFallback:!0}),rootCommand=command.split(" ")[0],canonicalRoot=COMMAND_ALIAS_TO_CANONICAL.get(rootCommand)??(rootCommand.startsWith("list-")?"list":rootCommand.startsWith("history-")?"history":rootCommand),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))]),flags=(AGENT_BOOTSTRAP_FLAGS.get(resolvePmCommandOperation(command))??AGENT_BOOTSTRAP_FLAGS.get(canonicalRoot)??AGENT_BOUNDED_FLAG_PRIORITY).filter(flag=>availableFlags.has(flag)),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:!0}),envelope:resolvePmCommandOutputEnvelope(command)}))}function buildCommandExitContractGroups(commands){const groups=new Map;for(const command of commands){const contract=resolvePmCommandExitContract(command),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,key=exitCodes.join(","),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){(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))]))},!(selectedCommand!==void 0&&!selection.fullOutput)&&(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)){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)){if(selection.omitUnfilteredCommandFlags)result.command_flags_omitted_reason="unfiltered_default_brief";else{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,"priority"],compact_fields:[...DEFAULT_COMPACT_LIST_FIELDS]}))}result.command_aliases=selection.fullOutput?commandAliases:commandAliases.map(({canonical,aliases})=>({canonical,aliases})),selection.fullOutput||(result.command_alias_contracts_omitted_reason="compact_projection; restore with --full")}}function attachCommanderAliasContractsResult(result,selection){if(!(selection.schemaOnly||selection.flagsOnly||selection.availabilityOnly)){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:!0},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),runtime=await resolveContractsRuntimeContext(global2,pmRoot,selection),actionContext=resolveContractsActionContext(selection,runtime),schemaContext=resolveContractsSchemaContext(selection,runtime,actionContext),commands=resolveContractsCommands(selection,actionContext),outputCommands=resolveOutputCommands(selection,commands,runtime.extensionContracts),result=createContractsResult(selection,schemaContext,actionContext,outputCommands),extensionCommandContracts=resolveExtensionCommandContracts(selection,runtime,outputCommands),includeCommandDetails=selection.fullOutput||selection.selectedCommand!==void 0;if((selection.summary||selection.fullOutput)&&attachAgentCommandContractsResult(result,outputCommands,extensionCommandContracts,{includeFormatBudgets:includeCommandDetails,includeIntentProvenance:includeCommandDetails,includePositionalSignatures:includeCommandDetails,includeProjectionModeMatrix:includeCommandDetails}),selection.summary)return result;const commandAliases=buildCommandAliasSurface(actionContext.commandCatalog.filter(command=>isCommandDiscoverable(selection,command,runtime.extensionContracts)));return selection.flagsOnly&&!selection.fullOutput||attachRuntimeContractsResult(result,runtime,selection),attachSchemaContractsResult(result,selection,schemaContext,extensionCommandContracts),attachFlagContractsResult(result,selection,runtime,outputCommands,commandAliases),attachCommanderAliasContractsResult(result,selection),(selection.selectedCommand==="assurance"||selection.fullOutput)&&(result.assurance_contracts={measurement_source_kinds:[...ASSURANCE_MEASUREMENT_SOURCE_KINDS],gate_triggers:[...ASSURANCE_GATE_TRIGGERS]}),selection.fullOutput&&result.grammar_contracts&&(result.grammar_contracts.destinations=PM_COMMAND_DESTINATION_CONTRACTS.map(row=>({...row,reason:row.reason??""}))),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)}),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
|