@unbrained/pm-cli 2026.10.18 → 2026.10.20
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 +43 -0
- package/dist/cli/error-guidance.d.ts +7 -0
- package/dist/cli/error-guidance.js +2 -2
- package/dist/cli/help-content.js +2 -2
- package/dist/cli/register-mutation.js +2 -2
- package/dist/cli/register-setup.js +1 -1
- package/dist/cli/register-structured-mutation.js +1 -1
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/{chunk-PYRREEUB.js → chunk-2GGGOD7P.js} +28 -28
- package/dist/cli-bundle/chunks/chunk-7NHA5K77.js +126 -0
- package/dist/cli-bundle/chunks/chunk-7ZOIZ2AZ.js +8 -0
- package/dist/cli-bundle/chunks/{chunk-4GA4MUTE.js → chunk-GHJOMRSF.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-KU4Q3MSI.js +8 -0
- package/dist/cli-bundle/chunks/chunk-LS55VKRK.js +3 -0
- package/dist/cli-bundle/chunks/chunk-PNPE2OVJ.js +112 -0
- package/dist/cli-bundle/chunks/chunk-PTL3TBT6.js +20 -0
- package/dist/cli-bundle/chunks/chunk-QETMESEB.js +6 -0
- package/dist/cli-bundle/chunks/{chunk-7WIEAGDS.js → chunk-QMZ73FCW.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-QQYCB2LO.js +2 -0
- package/dist/cli-bundle/chunks/chunk-RUKSEZE7.js +2 -0
- package/dist/cli-bundle/chunks/chunk-TZU6U5ZE.js +3 -0
- package/dist/cli-bundle/chunks/chunk-VLJLWZBO.js +70 -0
- package/dist/cli-bundle/chunks/chunk-VS565KBX.js +2 -0
- package/dist/cli-bundle/chunks/chunk-XAWE4EAK.js +2 -0
- package/dist/cli-bundle/chunks/chunk-YECCKB4E.js +3 -0
- package/dist/cli-bundle/chunks/{chunk-FIJOSX2C.js → chunk-YT2Z3JPC.js} +72 -66
- package/dist/cli-bundle/chunks/chunk-YTHI5DTH.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-6VZKYJW7.js → chunk-YW6SIKYP.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-ZZED447K.js → chunk-ZA3XXHEE.js} +6 -6
- package/dist/cli-bundle/chunks/context-budget-recovery-L2WP5S26.js +2 -0
- package/dist/cli-bundle/chunks/indexed-receipt-blobs-U7VGKIYC.js +4 -0
- package/dist/cli-bundle/chunks/{register-list-query-PUCVYYBD.js → register-list-query-NNDV6F6I.js} +3 -3
- package/dist/cli-bundle/chunks/register-mutation-3GCBSNQS.js +20 -0
- package/dist/cli-bundle/chunks/register-operations-YKDGNKUL.js +2 -0
- package/dist/cli-bundle/chunks/register-setup-AOUZQQWB.js +2 -0
- package/dist/cli-bundle/chunks/settlement-hook-CLRGA6O7.js +7 -0
- package/dist/cli-bundle/chunks/stage-6QXYRMSU.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-37SU7BZI.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-6IU7BESB.js +65 -0
- package/dist/cli-bundle/focused-chunks/chunk-AK2CI2GI.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-AS3MOBO3.js +25 -0
- package/dist/cli-bundle/focused-chunks/chunk-AW35RDKA.js +78 -0
- package/dist/cli-bundle/focused-chunks/chunk-E4II2D2B.js +3 -0
- package/dist/cli-bundle/focused-chunks/{chunk-A4ZHHTEX.js → chunk-F7FD25TG.js} +12 -12
- package/dist/cli-bundle/focused-chunks/chunk-FOA7XKWP.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-TB7F4FCR.js → chunk-GYHZ7W6O.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-H5Q2HUU6.js +8 -0
- package/dist/cli-bundle/focused-chunks/chunk-HUZAXSIJ.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-J6EYUGAR.js +6 -0
- package/dist/cli-bundle/focused-chunks/chunk-JEXZEIAX.js +91 -0
- package/dist/cli-bundle/focused-chunks/{chunk-BFEMT5U3.js → chunk-KDGUIIRU.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{chunk-ZDBS2DCT.js → chunk-KKRFSI2N.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-LJPUJ2KK.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-MQ42BFGX.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-IRVL4UXR.js → chunk-NI6NS44Q.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-VAYS754X.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-Z7YIFCNE.js → chunk-VLSER3XW.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-VS6VTWTZ.js +8 -0
- package/dist/cli-bundle/focused-chunks/chunk-VVRXF4JO.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-ZGEK57KD.js +2 -0
- package/dist/cli-bundle/focused-chunks/context-budget-recovery-5MKOCGY5.js +2 -0
- package/dist/cli-bundle/focused-chunks/indexed-receipt-blobs-H2G6CCGO.js +4 -0
- package/dist/cli-bundle/focused-chunks/settlement-hook-5SNBBT7C.js +7 -0
- package/dist/cli-bundle/focused-chunks/stage-EMTISXR7.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 +28 -22
- 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 +66 -53
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +8 -8
- package/dist/core/fs/fs-utils.d.ts +2 -2
- package/dist/core/fs/fs-utils.js +1 -1
- package/dist/core/history/event-index.js +2 -2
- package/dist/core/output/output.d.ts +7 -2
- package/dist/core/output/output.js +5 -5
- package/dist/core/shared/errors.d.ts +48 -0
- package/dist/core/shared/errors.js +1 -1
- package/dist/core/store/settings.js +2 -2
- package/dist/mcp/server.js +1 -1
- package/dist/sdk/cli-contracts/bootstrap-command-scanner.js +1 -1
- package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
- package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
- package/dist/sdk/cli-contracts/runtime-contracts.d.ts +1 -0
- package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
- package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
- package/dist/sdk/cli-contracts/tool-schema.js +1 -1
- package/dist/sdk/core.d.ts +1 -1
- package/dist/sdk/core.js +1 -1
- package/dist/sdk/dependencies/context-budget-recovery.d.ts +21 -0
- package/dist/sdk/dependencies/context-budget-recovery.js +2 -0
- package/dist/sdk/dependencies.js +1 -1
- package/dist/sdk/errors.d.ts +4 -1
- package/dist/sdk/errors.js +1 -1
- package/dist/sdk/extension/install-sources.js +3 -3
- package/dist/sdk/extension/shared.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
- package/dist/sdk/governance/health.js +1 -1
- package/dist/sdk/history-repair.js +1 -1
- package/dist/sdk/index.d.ts +1 -1
- package/dist/sdk/index.js +1 -1
- package/dist/sdk/item-transaction.d.ts +13 -0
- package/dist/sdk/item-transaction.js +1 -1
- package/dist/sdk/lifecycle/structured-mutation-plan.d.ts +14 -1
- package/dist/sdk/lifecycle/structured-mutation-plan.js +1 -1
- package/dist/sdk/merge/driver.js +7 -1
- package/dist/sdk/merge/indexed-receipt-blobs.d.ts +2 -0
- package/dist/sdk/merge/indexed-receipt-blobs.js +4 -0
- package/dist/sdk/merge/install.d.ts +8 -0
- package/dist/sdk/merge/install.js +3 -3
- package/dist/sdk/merge/receipts.d.ts +6 -0
- package/dist/sdk/merge/receipts.js +2 -2
- package/dist/sdk/merge/reconcile.d.ts +6 -0
- package/dist/sdk/merge/reconcile.js +1 -1
- package/dist/sdk/merge/settlement-hook.d.ts +12 -0
- package/dist/sdk/merge/settlement-hook.js +7 -0
- package/dist/sdk/merge/stage.d.ts +13 -0
- package/dist/sdk/merge/stage.js +2 -0
- package/dist/sdk/output/list-envelope.d.ts +7 -0
- package/dist/sdk/output/list-envelope.js +2 -0
- package/dist/sdk/output.d.ts +1 -0
- package/dist/sdk/output.js +2 -2
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/query/list.js +1 -1
- package/dist/sdk/relationship-context.d.ts +2 -0
- package/dist/sdk/relationship-context.js +1 -1
- package/dist/sdk/runtime-extended-actions.js +1 -1
- package/dist/sdk/structured-mutations.d.ts +2 -0
- package/dist/sdk/structured-mutations.js +1 -1
- package/docs/COMMANDS.md +27 -0
- package/docs/CONFIGURATION.md +14 -0
- package/docs/MERGE_SAFETY.md +88 -5
- package/docs/PR_REVIEW_LOOP.md +32 -12
- package/docs/SCRIPTING.md +10 -0
- package/docs/SDK.md +103 -0
- package/docs/TESTING.md +32 -1
- package/docs/generated/FLAG_LEXICON_BUDGETS.md +2 -2
- package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +6 -3
- 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-4V6ONLI6.js +0 -3
- package/dist/cli-bundle/chunks/chunk-7PATQWTH.js +0 -20
- package/dist/cli-bundle/chunks/chunk-AETP4JEM.js +0 -3
- package/dist/cli-bundle/chunks/chunk-LUKVNL72.js +0 -2
- package/dist/cli-bundle/chunks/chunk-OJ77ZQN3.js +0 -8
- package/dist/cli-bundle/chunks/chunk-RHQJ6VWC.js +0 -237
- package/dist/cli-bundle/chunks/chunk-RNABUEFB.js +0 -80
- package/dist/cli-bundle/chunks/chunk-TO6CIV4C.js +0 -2
- package/dist/cli-bundle/chunks/register-mutation-GGGVBXD5.js +0 -20
- package/dist/cli-bundle/chunks/register-operations-NRZ6Q4QE.js +0 -2
- package/dist/cli-bundle/chunks/register-setup-MV3P3YSF.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-2MPQUMTF.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-5UKCSZWT.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-B4YLP5ZB.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-FW7CSSKL.js +0 -75
- package/dist/cli-bundle/focused-chunks/chunk-HYPRPSYD.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-L55KQ2KT.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-MASIOFPG.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-RJ3EIHDU.js +0 -26
- package/dist/cli-bundle/focused-chunks/chunk-SEL4Z2OO.js +0 -167
- package/dist/cli-bundle/focused-chunks/chunk-TZUIBG3P.js +0 -2
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="099a0266-6392-5997-847e-1e8a0f24f686")}catch{}})();import{normalizeUniqueStringList}from"./string-lists.js";import{PM_TOOL_ACTIONS}from"./enum-contracts.js";import{TOOL_CREATE_OPTION_CONTRACTS,TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACTS,TOOL_UPDATE_OPTION_CONTRACTS,TOOL_UPDATE_MANY_FILTER_OPTION_CONTRACTS,TOOL_CONTEXT_OPTION_CONTRACTS,TOOL_ACTIVITY_OPTION_CONTRACTS,TOOL_LIST_FILTER_OPTION_CONTRACTS,TOOL_AGGREGATE_OPTION_CONTRACTS,TOOL_SEARCH_FILTER_OPTION_CONTRACTS,TOOL_CLOSE_MANY_FILTER_OPTION_CONTRACTS}from"./tool-option-contracts.js";import{PM_TOOL_PARAMETER_PROPERTIES as BASE_TOOL_PARAMETER_PROPERTIES,PM_TOOL_PARAMETER_METADATA as BASE_TOOL_PARAMETER_METADATA,PM_TOOL_ACTION_SCOPED_PARAMETER_PROPERTIES as BASE_ACTION_SCOPED_PARAMETER_PROPERTIES,PM_TOOL_ACTION_SCOPED_PARAMETER_METADATA,PLAN_ACTION_PARAMETER_PROPERTIES,PLAN_ACTION_PARAMETER_METADATA}from"./tool-parameter-tables.js";import{toUniqueFlagContracts,withFlagAliasMetadata}from"./flag-contracts.js";import{resolveReadOutputSurface}from"../read-output-contracts.js";const PM_TOOL_ACTION_SCOPED_PARAMETER_PROPERTIES={...BASE_ACTION_SCOPED_PARAMETER_PROPERTIES,"history-attest":{verify:{type:"object",additionalProperties:!0},output:{not:{}}}},PM_TOOL_PARAMETER_PROPERTIES={...BASE_TOOL_PARAMETER_PROPERTIES,pause:{type:"boolean"},handoff:{type:"string"},releaseAssignment:{type:"boolean"},hashAlgorithm:{type:"string",enum:["sha256","sha512"]}},PM_TOOL_PARAMETER_METADATA={...BASE_TOOL_PARAMETER_METADATA,pause:{description:"Return work to its configured open status before releasing ownership."},handoff:{description:"Release into a configured non-terminal queue with a required evidence message."},releaseAssignment:{description:"Release assignment after recording closure evidence."},hashAlgorithm:{description:"Digest for detached history bundles; defaults to sha256."}},PM_TOOL_GLOBAL_PARAMETER_KEYS=["json","quiet","profile","noExtensions","noPager","tokenAccounting","path","pmExecutable","timeoutMs"],PM_TOOL_READ_OUTPUT_PARAMETER_KEYS=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor","outputRowContract"],PM_TOOL_RESERVED_CUSTOM_FIELD_PROPERTIES=new Set(["action","cwd","options",...Object.keys(PM_TOOL_PARAMETER_PROPERTIES).filter(property=>property!=="severity")]);function resolvePmToolCustomFieldCollision(field){const normalized=field.trim().toLowerCase();let property="";for(let index=0;index<normalized.length;index+=1){const character=normalized[index];if(character!=="-"&&character!=="_"){property+=character;continue}let nextIndex=index+1;for(;normalized[nextIndex]==="-"||normalized[nextIndex]==="_";)nextIndex+=1;const nextCharacter=normalized[nextIndex];if(nextCharacter!==void 0&&(nextCharacter>="a"&&nextCharacter<="z"||nextCharacter>="0"&&nextCharacter<="9")){property+=nextCharacter.toUpperCase(),index=nextIndex;continue}property+=normalized.slice(index,nextIndex),index=nextIndex-1}return PM_TOOL_RESERVED_CUSTOM_FIELD_PROPERTIES.has(property)?{field,property,owner:"mcp_tool_input",nested_path:`options.${property}`}:void 0}const PM_TOOL_ACTION_MUTATION_PARAMETER_KEYS={create:["fullChangedFields","idOnly"],copy:["fullChangedFields","idOnly"],update:["fullChangedFields","idOnly"],"item-reopen":["fullChangedFields","idOnly"],close:["fullChangedFields","idOnly"],claim:["fullChangedFields","idOnly"],release:["fullChangedFields","idOnly"],"start-task":["fullChangedFields","idOnly"],"pause-task":["fullChangedFields","idOnly"],"close-task":["fullChangedFields","idOnly"],restore:["fullChangedFields","idOnly"],append:["fullChangedFields"],"update-many":["fullChangedFields"],"close-many":["fullChangedFields"],assurance:["fullChangedFields","idOnly"]},PLAN_CREATE_METADATA_PARAMETER_KEYS=["createMode","status","deadline","estimate","acceptanceCriteria","definitionOfReady","order","rank","goal","objective","value","impact","outcome","whyNow","assignee","reviewer","risk","confidence","sprint","release","blockedReason","unblockNote","reporter","severity","environment","reproSteps","resolution","expectedResult","actualResult","affectedVersion","fixedVersion","component","regression","customerImpact","comment","note","learning","reminder","event","typeOption"],PM_TOOL_ACTION_NESTED_OPTION_COMPATIBILITY_KEYS=Object.freeze({"close-many":["list","expected_result","expected","actual_result","actual","validate_close","dry_run","checkpoint","no_checkpoint","filterAssignee_filter"],"update-many":["list","update","dry_run","checkpoint","no_checkpoint","filterAssignee_filter"],...Object.fromEntries(PM_TOOL_ACTIONS.filter(action=>action==="upgrade"||action==="install"||action==="extension"||action==="package"||action.startsWith("extension-")||action.startsWith("package-")).map(action=>[action,["project","local","global"]]))});function toSchemaKeyList(values){return normalizeUniqueStringList(values)}const CREATE_CONTRACT_PARAMETER_KEYS=toSchemaKeyList([...TOOL_CREATE_OPTION_CONTRACTS.map(entry=>entry.param),...TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACTS.map(entry=>entry.param),"assignee","closeReason","completedAt"]),UPDATE_CONTRACT_PARAMETER_KEYS=toSchemaKeyList([...TOOL_UPDATE_OPTION_CONTRACTS.map(entry=>entry.param),...TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACTS.map(entry=>entry.param),"force"]),UPDATE_MANY_CONTRACT_PARAMETER_KEYS=toSchemaKeyList([...TOOL_UPDATE_MANY_FILTER_OPTION_CONTRACTS.map(entry=>entry.param),...UPDATE_CONTRACT_PARAMETER_KEYS.filter(key=>key!=="allowMissingParent"&&key!=="completedAt"),"dryRun","rollback","noCheckpoint"]),CLOSE_MANY_CONTRACT_PARAMETER_KEYS=toSchemaKeyList([...TOOL_CLOSE_MANY_FILTER_OPTION_CONTRACTS.map(entry=>entry.param),"reason","completedAt","resolution","expectedResult","actualResult","validateClose","dryRun","rollback","noCheckpoint","author","message","force"]),CONTEXT_CONTRACT_PARAMETER_KEYS=toSchemaKeyList([...TOOL_CONTEXT_OPTION_CONTRACTS.map(entry=>entry.param),"past","section"]),ACTIVITY_CONTRACT_PARAMETER_KEYS=toSchemaKeyList([...TOOL_ACTIVITY_OPTION_CONTRACTS.map(entry=>entry.param),"stream"]),LIST_CONTRACT_PARAMETER_KEYS=toSchemaKeyList([...TOOL_LIST_FILTER_OPTION_CONTRACTS.map(entry=>entry.param),"all","includeBody","noTruncate","strictRead","compact","brief","full"]),FIXED_STATUS_LIST_CONTRACT_PARAMETER_KEYS=LIST_CONTRACT_PARAMETER_KEYS.filter(parameter=>parameter!=="all"&¶meter!=="status"),LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS=[[{property:"today",schema:{const:!0}},{property:"recent",schema:{const:!0}}],[{property:"today",schema:{const:!0}},{property:"updatedAfter",schema:{type:"string",pattern:"\\S"}}],[{property:"recent",schema:{const:!0}},{property:"updatedAfter",schema:{type:"string",pattern:"\\S"}}]],CONTRACTS_PROJECTION_MUTUALLY_EXCLUSIVE_GROUPS=[[{property:"summary",schema:{const:!0}},{property:"schemaOnly",schema:{const:!0}}],[{property:"summary",schema:{const:!0}},{property:"flagsOnly",schema:{const:!0}}],[{property:"summary",schema:{const:!0}},{property:"availabilityOnly",schema:{const:!0}}],[{property:"schemaOnly",schema:{const:!0}},{property:"flagsOnly",schema:{const:!0}}],[{property:"schemaOnly",schema:{const:!0}},{property:"availabilityOnly",schema:{const:!0}}],[{property:"flagsOnly",schema:{const:!0}},{property:"availabilityOnly",schema:{const:!0}}]],AGGREGATE_CONTRACT_PARAMETER_KEYS=toSchemaKeyList([...TOOL_AGGREGATE_OPTION_CONTRACTS.map(entry=>entry.param),"count","completion","includeUnparented"]),SEARCH_CONTRACT_PARAMETER_KEYS=toSchemaKeyList(["query","keywords","mode","semantic","hybrid","includeLinked","titleExact","phraseExact","highlight","compact","full",...TOOL_SEARCH_FILTER_OPTION_CONTRACTS.map(entry=>entry.param)]),NEXT_CONTRACT_PARAMETER_KEYS=toSchemaKeyList(["type","tag","priority","assignee","assigneeFilter","sprint","release","parent","limit","blockedLimit","readyOnly","format","includeDecisions","includeGates","includeContainers","tokenBudget","explainRanking"]),AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS=["author","message","force"],CLOSE_ACTION_OPTION_KEYS=["releaseAssignment","text","reason","closeReason","completedAt","duplicateOf","validateClose","resolution","expectedResult","actualResult"],LIFECYCLE_AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS=["author","assignee","message","force"],MANAGED_EXTENSION_PACKAGE_OPTION_KEYS=["dryRun","target","scope","capability","declarative","github","ref","init","install","uninstall","explore","manage","offline","describe","markdown","output","reload","doctor","catalog","list","adopt","adoptAll","activate","deactivate","runtimeProbe","fixManagedState","isolated","ignoreGlobal","detail","trace","watch","strictExit","failOnWarn"];function managedLifecycleSchemaContracts(prefix){return{[`${prefix}-init`]:{required:["target"],optional:["scope","capability",...prefix==="package"?["declarative"]:[]]},[`${prefix}-install`]:{optional:["target","github","scope","ref","dryRun"],anyOfRequired:[["target"],["github"]]},[`${prefix}-uninstall`]:{required:["target"],optional:["scope"]},[`${prefix}-explore`]:{optional:["scope"]},[`${prefix}-manage`]:{optional:["scope","runtimeProbe","fixManagedState","offline"]},[`${prefix}-describe`]:{optional:["target","scope","markdown","output"]},[`${prefix}-reload`]:{optional:["scope","watch"]},[`${prefix}-doctor`]:{optional:["scope","detail","trace","fixManagedState","isolated","ignoreGlobal","strictExit","failOnWarn"]},[`${prefix}-catalog`]:{optional:["scope","fields"]},[`${prefix}-adopt`]:{required:["target"],optional:["scope","github","ref"]},[`${prefix}-adopt-all`]:{optional:["scope"]},[`${prefix}-activate`]:{required:["target"],optional:["scope"]},[`${prefix}-deactivate`]:{required:["target"],optional:["scope"]},[prefix]:{optional:MANAGED_EXTENSION_PACKAGE_OPTION_KEYS,dependentAnyOfRequired:[{property:"dryRun",value:!0,anyOfRequired:[["install","target"],["install","github"]]}],mutuallyExclusiveWhen:[[{property:"dryRun",schema:{const:!0}},{property:"install",schema:{const:!1}}]]}}}const SCHEDULING_ACTION_SCHEMA_CONTRACT={required:["title"],optional:["start","duration","end","location","timezone","allDay","parent","allowMissingParent","tags","priority","body","description","author","message"]},UPGRADE_ACTION_SCHEMA_CONTRACT={optional:["target","scope","dryRun","cliOnly","packagesOnly","repair","tag","packageName"]},PM_TOOL_ACTION_SCHEMA_CONTRACTS={init:{optional:["prefix","idPrefix","workspace","preset","typePreset","defaults","author","agentGuidance","withPackages","mergeFence","force","verbose"]},config:{required:["scope","configAction"],optional:["key","value","criterion","clearCriteria","format","policy"]},...managedLifecycleSchemaContracts("extension"),...managedLifecycleSchemaContracts("package"),"package-upgrade":UPGRADE_ACTION_SCHEMA_CONTRACT,install:{optional:["target","github","scope","ref","dryRun"],anyOfRequired:[["target"],["github"]]},upgrade:UPGRADE_ACTION_SCHEMA_CONTRACT,create:{required:["title","description","type","status","priority","message"],optional:CREATE_CONTRACT_PARAMETER_KEYS},copy:{required:["id"],optional:["title","author","message","allowDuplicate"]},focus:{optional:["id","clear"],mutuallyExclusive:[["id","clear"]]},list:{optional:LIST_CONTRACT_PARAMETER_KEYS,mutuallyExclusiveWhen:LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS},"list-all":{optional:LIST_CONTRACT_PARAMETER_KEYS,mutuallyExclusiveWhen:LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS},"list-draft":{optional:FIXED_STATUS_LIST_CONTRACT_PARAMETER_KEYS,mutuallyExclusiveWhen:LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS},"list-open":{optional:FIXED_STATUS_LIST_CONTRACT_PARAMETER_KEYS,mutuallyExclusiveWhen:LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS},"list-in-progress":{optional:FIXED_STATUS_LIST_CONTRACT_PARAMETER_KEYS,mutuallyExclusiveWhen:LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS},"list-blocked":{optional:FIXED_STATUS_LIST_CONTRACT_PARAMETER_KEYS,mutuallyExclusiveWhen:LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS},"list-closed":{optional:FIXED_STATUS_LIST_CONTRACT_PARAMETER_KEYS,mutuallyExclusiveWhen:LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS},"list-canceled":{optional:FIXED_STATUS_LIST_CONTRACT_PARAMETER_KEYS,mutuallyExclusiveWhen:LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS},aggregate:{optional:AGGREGATE_CONTRACT_PARAMETER_KEYS},guide:{optional:["list","format","depth"]},context:{optional:CONTEXT_CONTRACT_PARAMETER_KEYS},ctx:{optional:CONTEXT_CONTRACT_PARAMETER_KEYS},get:{required:["id"],optional:["for","tokenBudget","at","depth","full","fields","tree","treeDepth","format"]},search:{optional:SEARCH_CONTRACT_PARAMETER_KEYS,anyOfRequired:[["query"],["keywords"]]},eval:{optional:["mode","k","failUnder","queries","format"]},events:{optional:["since","type","author","item","limit","full","provenance","provenanceSummary","harness","agentInstance","provenanceFilter","cursorMode"]},merge:{required:["subcommand"],optional:["dryRun","author","message","force","includeReconciled","artifact","basePath","oursPath","theirsPath","output","outputPath","itemPath","prefer"]},workspace:{required:["subcommand"],optional:["snapshotAction","name","target","dryRun","force","author","message","lockTtlSeconds","lockWaitMs"],conditionalRequired:[{property:"subcommand",value:"snapshot",required:["snapshotAction"]}]},meet:SCHEDULING_ACTION_SCHEMA_CONTRACT,event:SCHEDULING_ACTION_SCHEMA_CONTRACT,remind:{required:["title"],optional:["at","text","parent","allowMissingParent","tags","priority","body","description","author","message"]},next:{optional:[...NEXT_CONTRACT_PARAMETER_KEYS,"for"]},reindex:{optional:["mode","progress"]},history:{required:["id"],optional:["limit","compact","full","provenance","provenanceSummary","harness","agentInstance","provenanceFilter","diff","verify","field","strictExit","failOnWarn","format"]},"history-attest":{optional:["verify","output","hashAlgorithm"],mutuallyExclusive:[["verify","hashAlgorithm"]]},"history-redact":{required:["id"],optional:["literal","regex","replacement","dryRun",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],anyOfRequired:[["literal"],["regex"]]},"history-repair":{optional:["id","all","dryRun","normalizeProvenance","salvageTail",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],oneOfRequired:[["id"],["all"]],mutuallyExclusiveWhen:[[{property:"salvageTail",schema:{const:!0}},{property:"all",schema:{const:!0}}],[{property:"salvageTail",schema:{const:!0}},{property:"normalizeProvenance",schema:{const:!0}}]]},"history-author-acknowledge":{optional:["historyEvent","allActionable","dryRun","planFingerprint","limit","attributedAuthor","reviewer","reason"],oneOfRequired:[["historyEvent"],["allActionable"]]},"history-compact":{optional:["id","before","ids","allOver","closed","allStreams","minEntries","dryRun",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS]},schema:{mutuallyExclusiveWhen:[[{property:"subcommand",schema:{const:"policy-mode"}},{property:"name",schema:{not:{enum:["advise","refuse"]}}}]],required:["subcommand"],optional:["definition","policy","message","name","description","defaultStatus","folder","alias","role","order","fieldType","commands","cliFlag","required","requiredOnCreate","allowUnset","requiredTypes","typePreset","infer","minCount","apply","to","migrationId","fieldTypeScope","dryRun","author","force"],conditionalRequired:[{property:"subcommand",value:"policy-put",required:["definition"]},{property:"subcommand",value:"policy-remove",required:["name"]},{property:"subcommand",value:"policy-mode",required:["name"]},{property:"subcommand",value:"policy-check",required:["name"]},{property:"subcommand",value:"policy-approve",required:["name","policy"]},{property:"subcommand",value:"show",required:["name"]},{property:"subcommand",value:"show-status",required:["name"]},{property:"subcommand",value:"add-type",required:["name"]},{property:"subcommand",value:"remove-type",required:["name"]},{property:"subcommand",value:"add-status",required:["name"]},{property:"subcommand",value:"remove-status",required:["name"]},{property:"subcommand",value:"add-field",required:["name"]},{property:"subcommand",value:"remove-field",required:["name"]},{property:"subcommand",value:"show-field",required:["name"]},{property:"subcommand",value:"rename-type",required:["name","to"]},{property:"subcommand",value:"rename-field",required:["name","to"]},{property:"subcommand",value:"remap-status",required:["name","to"]},{property:"subcommand",value:"apply-preset",required:["typePreset"]}]},profile:{required:["subcommand"],optional:["name","dryRun","author","force"],conditionalRequired:[{property:"subcommand",value:"show",required:["name"]},{property:"subcommand",value:"apply",required:["name"]},{property:"subcommand",value:"lint",required:["name"]}]},plan:{required:["subcommand"],optional:["id","stepRef","reorderTo","title","description","template","scope","parent","related","blocks","blockedBy","harness","mode","resumeContext","tags","priority",...PLAN_CREATE_METADATA_PARAMETER_KEYS,"body","claim","fromSearch","stepTitle","step","stepBody","stepOwner","stepStatus","stepEvidence","stepBlockedReason","stepReplacement","dependsOn","link","linkKind","linkNote","promoteToItemDep","allowMultipleActive","file","test","doc","decisionText","decision","decisionRationale","decisionEvidence","discoveryText","discovery","validationText","validation","validationCommand","validationExpected","depth","fields","steps","materializeType","materializeParent","materializeTags","field",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS]},activity:{optional:ACTIVITY_CONTRACT_PARAMETER_KEYS},restore:{required:["id","target"],optional:AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS},update:{required:["id"],optional:UPDATE_CONTRACT_PARAMETER_KEYS,mutuallyExclusive:[["acceptanceCriteria","addAc"],["acceptanceCriteria","removeAc"]]},"update-many":{optional:UPDATE_MANY_CONTRACT_PARAMETER_KEYS,mutuallyExclusive:[["acceptanceCriteria","addAc"],["acceptanceCriteria","removeAc"]]},close:{required:["id"],optional:[...CLOSE_ACTION_OPTION_KEYS,...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS]},"close-many":{optional:CLOSE_MANY_CONTRACT_PARAMETER_KEYS},delete:{required:["id"],optional:["dryRun",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS]},append:{required:["id","body"],optional:AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS},comments:{required:["id"],optional:["text","add","stdin","edit","delete","limit","full","ifAbsent",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],mutuallyExclusive:[["edit","ifAbsent"],["delete","ifAbsent"]]},notes:{required:["id"],optional:["text","add","addJson","stdin","edit","delete","limit","since","eventType","includeMeta","full","ifAbsent",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],mutuallyExclusive:[["addJson","add"],["addJson","stdin"],["addJson","file"],["addJson","edit"],["addJson","delete"],["edit","ifAbsent"],["delete","ifAbsent"]]},learnings:{required:["id"],optional:["text","add","stdin","edit","delete","limit","full","ifAbsent",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],mutuallyExclusive:[["edit","ifAbsent"],["delete","ifAbsent"]]},files:{required:[],optional:["id","add","addGlob","remove","migrate","list","addNote","discover","apply","discoveryNote","appendStable","validatePaths","lookupPath","scope","limit","offset","noTruncate","strictRead","explain","lines","decisionDepth",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],anyOfRequired:[["id"],["lookupPath"]],dependentAnyOfRequired:[{property:"addNote",anyOfRequired:[["add"],["addGlob"]]}]},docs:{required:["id"],optional:["add","addGlob","remove","migrate","addNote","list","validatePaths",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],dependentAnyOfRequired:[{property:"addNote",anyOfRequired:[["add"],["addGlob"]]}]},deps:{required:["id"],optional:["format","maxDepth","collapse","summary","full","nodeLimit","edgeLimit","tokenBudget","cursor","direction","kind"]},graph:{required:["subcommand"],optional:["id","target","kind","maxDepth","limit","after","direction","maxPaths","sample","exemptIsolate","exemptIsolateType","saveBaseline","rebuild","clear","summary","full"]},test:{required:["id"],optional:["list","add","addJson","remove","removeIndex","update","updateIndex","setJson","run","match","onlyIndex","onlyLast","background","timeout","progress","envSet","envClear","sharedHostSafe","pmContext","overrideLinkedPmContext","workspaceContext","overrideLinkedWorkspaceContext","allowUntrustedLinkedTests","acknowledgeLinkedTests","failOnContextMismatch","failOnSkipped","failOnEmptyTestRun","requireAssertionsForPm","checkContext","autoPmContext","measure","metricBelow","metricDiff",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],dependentAnyOfRequired:[{property:"update",anyOfRequired:[["setJson"]]},{property:"updateIndex",anyOfRequired:[["setJson"]]},{property:"setJson",anyOfRequired:[["update"],["updateIndex"]]}],mutuallyExclusive:[["update","updateIndex"],["acknowledgeLinkedTests","run"],["acknowledgeLinkedTests","background"]]},"test-all":{optional:["status","limit","offset","background","timeout","progress","envSet","envClear","sharedHostSafe","pmContext","overrideLinkedPmContext","workspaceContext","overrideLinkedWorkspaceContext","allowUntrustedLinkedTests","failOnContextMismatch","failOnSkipped","failOnEmptyTestRun","requireAssertionsForPm","checkContext","autoPmContext"]},telemetry:{optional:["subcommand","limit"]},"test-runs-list":{optional:["status","limit"]},"test-runs-status":{required:["runId"]},"test-runs-logs":{required:["runId"],optional:["stream","tail"]},"test-runs-stop":{required:["runId"],optional:["force"]},"test-runs-resume":{required:["runId"],optional:["author"]},stats:{optional:["includeEmpty","storage","metadataCoverage","fieldUtilization","byAssignee","byTag","byPriority","tagPrefix","measurements","metric","measurementLimit","observe","improvementDirection","measurementSource","measurementItem","measurementRevision","author","message","provenanceCoverage","fleetAttribution","since","eventLimit","minimumSample"]},duplicates:{optional:["status","since","threshold","limit","exhaustive"]},health:{optional:["strictDirectories","requireMergeDrivers","strictExit","failOnWarn","checkOnly","checkTelemetry","noRefresh","refreshVectors","verboseStaleItems","verboseAuthorEvents","brief","summary","skipVectors","skipIntegrity","skipDrift","full"]},validate:{optional:["checkCompleteness","checkStorageIntegrity","checkMetadata","metadataProfile","checkResolution","checkLifecycle","checkStaleBlockers","dependencyCycleSeverity","parentCycleSeverity","checkFiles","scanMode","includePmInternals","verboseFileLists","verboseDiagnostics","allAffectedIds","strictExit","failOnWarn","fixHints","autoFix","dryRun","fixScope","pruneMissing","checkHistoryDrift","checkCommandReferences","counts","full"]},assurance:{required:["subcommand"],optional:["kind","id","definition","trigger","treeId","gate","limit","dryRun","author","message","preset","owner","apply","enforcement"],conditionalRequired:[{property:"subcommand",value:"list",required:["kind"]},{property:"subcommand",value:"show",required:["kind","id"]},{property:"subcommand",value:"put",required:["kind","id","definition"]},{property:"subcommand",value:"remove",required:["kind","id"]},{property:"subcommand",value:"run",required:["id","trigger"]},{property:"subcommand",value:"apply",required:["preset","owner"]},{property:"subcommand",value:"derive",required:["owner"]},{property:"subcommand",value:"risk",required:["definition"]},{property:"subcommand",value:"lineages",required:["definition"]},{property:"subcommand",value:"promote",required:["id","enforcement"]}],mutuallyExclusiveWhen:[[{property:"subcommand",schema:{const:"risk"}},{property:"definition",schema:{not:{required:["policy","change"]}}}],[{property:"subcommand",schema:{const:"lineages"}},{property:"definition",schema:{anyOf:[{required:["change"]},{not:{required:["policy"]}}]}}]]},gc:{optional:["dryRun","gcScope"]},contracts:{optional:["contractAction","command","summary","schemaOnly","flagsOnly","availabilityOnly","runtimeOnly","activeOnly","full"],mutuallyExclusiveWhen:CONTRACTS_PROJECTION_MUTUALLY_EXCLUSIVE_GROUPS},completion:{required:["shell"],optional:["eagerTags"]},claim:{optional:["start","id","next","ifAvailable","maxAttempts","includeDecisions",...NEXT_CONTRACT_PARAMETER_KEYS,...LIFECYCLE_AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],oneOfRequired:[["id"],["next"]],mutuallyExclusiveWhen:[[{property:"start",schema:{const:!0}},{property:"next",schema:{const:!0}}],[{property:"start",schema:{const:!0}},{property:"ifAvailable",schema:{const:!0}}]]},release:{required:["id"],optional:["pause","handoff",...LIFECYCLE_AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],dependentAnyOfRequired:[{property:"handoff",anyOfRequired:[["message"]]}],mutuallyExclusiveWhen:[[{property:"pause",schema:{const:!0}},{property:"handoff",schema:{type:"string"}}]]},"start-task":{required:["id"],optional:LIFECYCLE_AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS},"pause-task":{required:["id"],optional:LIFECYCLE_AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS},"close-task":{required:["id"],optional:["text","validateClose",...LIFECYCLE_AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS]},"item-reopen":{required:["id","reason"],optional:["status","expectedResult","author","message","force"]}},PM_TOOL_ACTION_PARAMETER_CONTRACTS=Object.freeze(Object.fromEntries(PM_TOOL_ACTIONS.map(action=>[action,PM_TOOL_ACTION_SCHEMA_CONTRACTS[action]])));function fallbackToolParameterDescription(key){return key.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]/g," ").trim().replace(/^./,value=>value.toUpperCase()).concat(".")}function decorateToolParameterDefinition(key,definition){const baseDefinition=typeof definition=="object"&&definition!==null?{...definition}:{},metadata=PM_TOOL_PARAMETER_METADATA[key];return{...baseDefinition,description:metadata?.description??fallbackToolParameterDescription(key),...metadata?.examples?{examples:metadata.examples}:{}}}function actionScopedToolParameterMetadata(action,key){if(action==="history-attest"&&key==="verify")return{description:"Compare all retained history streams with a detached JSON proof object. Server-local proof paths are not accepted over MCP."};if(action==="history-attest"&&key==="output")return{description:"Local CLI/SDK only. MCP rejects this field; save the returned JSON bundle on the client."};if(action==="claim"&&key==="start")return{description:"Claim an explicit item and move it to its configured in-progress status."};if((action==="list"||action.startsWith("list-"))&&key==="all")return{description:"Return items from every lifecycle status instead of the default active-status set."};if(action==="plan"&&Object.prototype.hasOwnProperty.call(PLAN_ACTION_PARAMETER_METADATA,key))return PLAN_ACTION_PARAMETER_METADATA[key];const actionOverrides=PM_TOOL_ACTION_SCOPED_PARAMETER_METADATA[action];return actionOverrides&&Object.prototype.hasOwnProperty.call(actionOverrides,key)?actionOverrides[key]:PM_TOOL_PARAMETER_METADATA[key]}function decorateActionScopedToolParameterDefinition(action,key,definition){const baseDefinition=typeof definition=="object"&&definition!==null?{...definition}:{},metadata=actionScopedToolParameterMetadata(action,key);return{...baseDefinition,description:metadata?.description??fallbackToolParameterDescription(key),...metadata?.examples?{examples:metadata.examples}:{}}}function actionScopedToolParameterDefinition(action,key){if(action==="claim"&&key==="start")return{type:"boolean"};const actionProperties=PM_TOOL_ACTION_SCOPED_PARAMETER_PROPERTIES[action];return actionProperties&&Object.prototype.hasOwnProperty.call(actionProperties,key)?actionProperties[key]:action==="plan"&&Object.prototype.hasOwnProperty.call(PLAN_ACTION_PARAMETER_PROPERTIES,key)?PLAN_ACTION_PARAMETER_PROPERTIES[key]:(action==="get"||action==="history"||action==="search")&&key==="format"?{type:"string",enum:["json","toon"]}:key==="pause"||key==="handoff"||key==="releaseAssignment"||key==="hashAlgorithm"?PM_TOOL_PARAMETER_PROPERTIES[key]:BASE_TOOL_PARAMETER_PROPERTIES[key]}function buildActionScopedSchemaProperties(action,allowedKeys){const properties={action:{const:action,description:PM_TOOL_PARAMETER_METADATA.action?.description??"Tool action to execute."}};for(const key of allowedKeys){if(key==="action")continue;const definition=actionScopedToolParameterDefinition(action,key);definition&&(properties[key]=decorateActionScopedToolParameterDefinition(action,key,definition))}return properties}function buildOneOfSchemaEntries(action,oneOfRequiredGroups){const allOneOfFields=oneOfRequiredGroups.flat();return oneOfRequiredGroups.map(requiredFields=>{const otherFields=allOneOfFields.filter(field=>!requiredFields.includes(field));return{required:[...requiredFields],...otherFields.length>0?{not:{anyOf:otherFields.map(field=>({required:[field]}))}}:{},...action==="history-repair"&&requiredFields.includes("all")?{properties:{all:{const:!0}}}:action==="claim"&&requiredFields.includes("next")?{properties:{next:{const:!0}}}:{}}})}function schemaPropertyCondition(property,value){return{...value===void 0?{}:{properties:{[property]:{const:value}}},required:[property]}}function buildActionScopedAllOf(contract){const allOf=[];if(contract.conditionalRequired&&contract.conditionalRequired.length>0)for(const entry of contract.conditionalRequired)allOf.push({if:schemaPropertyCondition(entry.property,entry.value),then:{required:entry.required}});if(contract.dependentAnyOfRequired&&contract.dependentAnyOfRequired.length>0)for(const entry of contract.dependentAnyOfRequired)allOf.push({if:schemaPropertyCondition(entry.property,entry.value),then:{anyOf:entry.anyOfRequired.map(requiredFields=>({required:[...requiredFields]}))}});if(contract.mutuallyExclusive&&contract.mutuallyExclusive.length>0)for(const group of contract.mutuallyExclusive)allOf.push({not:{required:toSchemaKeyList(group)}});if(contract.mutuallyExclusiveWhen&&contract.mutuallyExclusiveWhen.length>0)for(const group of contract.mutuallyExclusiveWhen)allOf.push({not:{allOf:group.map(condition=>({properties:{[condition.property]:condition.schema},required:[condition.property]}))}});return allOf}function pmToolActionParameterKeys(action){if(!Object.prototype.hasOwnProperty.call(PM_TOOL_ACTION_SCHEMA_CONTRACTS,action))return;const contract=PM_TOOL_ACTION_SCHEMA_CONTRACTS[action],mutationParameterKeys=PM_TOOL_ACTION_MUTATION_PARAMETER_KEYS[action]??[];return toSchemaKeyList(["action",...PM_TOOL_GLOBAL_PARAMETER_KEYS,...resolveReadOutputSurface(action)!==void 0?PM_TOOL_READ_OUTPUT_PARAMETER_KEYS:[],...mutationParameterKeys,...contract.required??[],...contract.optional??[]])}function pmToolActionNestedOptionKeys(action){const parameterKeys=pmToolActionParameterKeys(action);if(parameterKeys!==void 0)return toSchemaKeyList([...parameterKeys,...PM_TOOL_ACTION_NESTED_OPTION_COMPATIBILITY_KEYS[action]??[]])}function buildActionScopedToolSchema(action){const contract=PM_TOOL_ACTION_SCHEMA_CONTRACTS[action],required=toSchemaKeyList(contract.required??[]),allowedKeys=pmToolActionParameterKeys(action),schema={type:"object",additionalProperties:!1,required:["action",...required],title:`pm action "${action}" parameters`,properties:buildActionScopedSchemaProperties(action,allowedKeys)};contract.anyOfRequired&&contract.anyOfRequired.length>0&&(schema.anyOf=contract.anyOfRequired.map(requiredFields=>({required:[...requiredFields]}))),contract.oneOfRequired&&contract.oneOfRequired.length>0&&(schema.oneOf=buildOneOfSchemaEntries(action,contract.oneOfRequired));const allOf=buildActionScopedAllOf(contract);return allOf.length>0&&(schema.allOf=allOf),schema}function buildPmActionToolInputSchema(action,options={}){const actionSchema=buildActionScopedToolSchema(action),actionProperties={...actionSchema.properties};delete actionProperties.action;const conditionalBranches=[...actionSchema.anyOf??[],...actionSchema.oneOf??[]],required=(options.required??actionSchema.required.map(String)).filter(key=>key==="action"?!1:options.required===void 0?!0:!conditionalBranches.some(branch=>branch.required?.map(String).includes(key))),schema={type:"object",additionalProperties:options.additionalProperties??!0,properties:{...actionProperties,options:{type:"object",additionalProperties:!0,description:"Advanced command options forwarded to the selected pm action."},...options.properties},required};return actionSchema.anyOf!==void 0&&(schema.anyOf=actionSchema.anyOf),actionSchema.oneOf!==void 0&&(schema.oneOf=actionSchema.oneOf),actionSchema.allOf!==void 0&&(schema.allOf=actionSchema.allOf),schema}function createLazyContractSchema(build){let value;const resolve=()=>value??=build();return new Proxy({},{get:(_target,prop)=>resolve()[prop],has:(_target,prop)=>prop in resolve(),ownKeys:()=>Reflect.ownKeys(resolve()),getOwnPropertyDescriptor:(_target,prop)=>{const descriptor=Reflect.getOwnPropertyDescriptor(resolve(),prop);return descriptor&&(descriptor.configurable=!0),descriptor}})}const PM_TOOL_PARAMETERS_SCHEMA_VERSION="4.22.0",PM_TOOL_PARAMETERS_SCHEMA_MAJOR=PM_TOOL_PARAMETERS_SCHEMA_VERSION.split(".")[0],PM_PROVIDER_TOOL_PARAMETERS_SCHEMA_VERSION="1.11.0",PM_TOOL_PARAMETERS_SCHEMA=createLazyContractSchema(()=>({$schema:"https://json-schema.org/draft/2020-12/schema",$id:`https://schema.unbrained.dev/pm-cli/tool-parameters-v${PM_TOOL_PARAMETERS_SCHEMA_MAJOR}.schema.json`,title:"pm-cli tool parameters (action-scoped strict schema)","x-schema-version":PM_TOOL_PARAMETERS_SCHEMA_VERSION,type:"object",oneOf:PM_TOOL_ACTIONS.map(action=>buildActionScopedToolSchema(action))}));function toProviderCompatibleParameterDefinition(key,definition){const decorated=decorateToolParameterDefinition(key,definition);if(typeof decorated.type=="string")return decorated;const firstTypedVariant=(Array.isArray(decorated.anyOf)?decorated.anyOf:[]).find(variant=>typeof variant.type=="string");if(firstTypedVariant){const{anyOf:_anyOf2,...rest2}=decorated;return{...firstTypedVariant,...rest2}}const{anyOf:_anyOf,...rest}=decorated;return{...rest,type:"string"}}function buildProviderCompatibleToolSchema(){const properties={action:{type:"string",description:PM_TOOL_PARAMETER_METADATA.action?.description??"Tool action to execute."},options:{type:"object",additionalProperties:!0,description:"Advanced command options object forwarded to the selected pm action."}};for(const key of Object.keys(PM_TOOL_PARAMETER_PROPERTIES).sort())properties[key]=toProviderCompatibleParameterDefinition(key,PM_TOOL_PARAMETER_PROPERTIES[key]);return{title:"pm-cli tool parameters (provider-compatible flat schema)","x-schema-version":PM_PROVIDER_TOOL_PARAMETERS_SCHEMA_VERSION,type:"object",additionalProperties:!1,required:["action"],properties}}const PM_PROVIDER_TOOL_PARAMETERS_SCHEMA=createLazyContractSchema(buildProviderCompatibleToolSchema),_testOnlyCliContracts={buildActionScopedToolSchema,buildProviderCompatibleToolSchema,decorateActionScopedToolParameterDefinition,decorateToolParameterDefinition,toolActionSchemaContracts:PM_TOOL_ACTION_SCHEMA_CONTRACTS,toolParameterMetadata:PM_TOOL_PARAMETER_METADATA,toProviderCompatibleParameterDefinition,toUniqueFlagContracts,withFlagAliasMetadata};export{CLOSE_ACTION_OPTION_KEYS,PLAN_CREATE_METADATA_PARAMETER_KEYS,PM_PROVIDER_TOOL_PARAMETERS_SCHEMA,PM_PROVIDER_TOOL_PARAMETERS_SCHEMA_VERSION,PM_TOOL_ACTION_PARAMETER_CONTRACTS,PM_TOOL_PARAMETERS_SCHEMA,PM_TOOL_PARAMETERS_SCHEMA_MAJOR,PM_TOOL_PARAMETERS_SCHEMA_VERSION,PM_TOOL_RESERVED_CUSTOM_FIELD_PROPERTIES,_testOnlyCliContracts,buildPmActionToolInputSchema,pmToolActionNestedOptionKeys,pmToolActionParameterKeys,resolvePmToolCustomFieldCollision};
|
|
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]="1a193d67-f078-5716-93c5-14860e38a008")}catch{}})();import{normalizeUniqueStringList}from"./string-lists.js";import{PM_TOOL_ACTIONS}from"./enum-contracts.js";import{TOOL_CREATE_OPTION_CONTRACTS,TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACTS,TOOL_UPDATE_OPTION_CONTRACTS,TOOL_UPDATE_MANY_FILTER_OPTION_CONTRACTS,TOOL_CONTEXT_OPTION_CONTRACTS,TOOL_ACTIVITY_OPTION_CONTRACTS,TOOL_LIST_FILTER_OPTION_CONTRACTS,TOOL_AGGREGATE_OPTION_CONTRACTS,TOOL_SEARCH_FILTER_OPTION_CONTRACTS,TOOL_CLOSE_MANY_FILTER_OPTION_CONTRACTS}from"./tool-option-contracts.js";import{PM_TOOL_PARAMETER_PROPERTIES as BASE_TOOL_PARAMETER_PROPERTIES,PM_TOOL_PARAMETER_METADATA as BASE_TOOL_PARAMETER_METADATA,PM_TOOL_ACTION_SCOPED_PARAMETER_PROPERTIES as BASE_ACTION_SCOPED_PARAMETER_PROPERTIES,PM_TOOL_ACTION_SCOPED_PARAMETER_METADATA,PLAN_ACTION_PARAMETER_PROPERTIES,PLAN_ACTION_PARAMETER_METADATA}from"./tool-parameter-tables.js";import{toUniqueFlagContracts,withFlagAliasMetadata}from"./flag-contracts.js";import{resolveReadOutputSurface}from"../read-output-contracts.js";const PM_TOOL_ACTION_SCOPED_PARAMETER_PROPERTIES={...BASE_ACTION_SCOPED_PARAMETER_PROPERTIES,"history-attest":{verify:{type:"object",additionalProperties:!0},output:{not:{}}}},PM_TOOL_PARAMETER_PROPERTIES={...BASE_TOOL_PARAMETER_PROPERTIES,pause:{type:"boolean"},handoff:{type:"string"},releaseAssignment:{type:"boolean"},hashAlgorithm:{type:"string",enum:["sha256","sha512"]}},PM_TOOL_PARAMETER_METADATA={...BASE_TOOL_PARAMETER_METADATA,pause:{description:"Return work to its configured open status before releasing ownership."},handoff:{description:"Release into a configured non-terminal queue with a required evidence message."},releaseAssignment:{description:"Release assignment after recording closure evidence."},hashAlgorithm:{description:"Digest for detached history bundles; defaults to sha256."}},PM_TOOL_GLOBAL_PARAMETER_KEYS=["json","quiet","profile","noExtensions","noPager","tokenAccounting","path","pmExecutable","timeoutMs"],PM_TOOL_READ_OUTPUT_PARAMETER_KEYS=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor","outputRowContract"],PM_TOOL_RESERVED_CUSTOM_FIELD_PROPERTIES=new Set(["action","cwd","options",...Object.keys(PM_TOOL_PARAMETER_PROPERTIES).filter(property=>property!=="severity")]);function resolvePmToolCustomFieldCollision(field){const normalized=field.trim().toLowerCase();let property="";for(let index=0;index<normalized.length;index+=1){const character=normalized[index];if(character!=="-"&&character!=="_"){property+=character;continue}let nextIndex=index+1;for(;normalized[nextIndex]==="-"||normalized[nextIndex]==="_";)nextIndex+=1;const nextCharacter=normalized[nextIndex];if(nextCharacter!==void 0&&(nextCharacter>="a"&&nextCharacter<="z"||nextCharacter>="0"&&nextCharacter<="9")){property+=nextCharacter.toUpperCase(),index=nextIndex;continue}property+=normalized.slice(index,nextIndex),index=nextIndex-1}return PM_TOOL_RESERVED_CUSTOM_FIELD_PROPERTIES.has(property)?{field,property,owner:"mcp_tool_input",nested_path:`options.${property}`}:void 0}const PM_TOOL_ACTION_MUTATION_PARAMETER_KEYS={create:["fullChangedFields","idOnly"],copy:["fullChangedFields","idOnly"],update:["fullChangedFields","idOnly"],"item-reopen":["fullChangedFields","idOnly"],close:["fullChangedFields","idOnly"],claim:["fullChangedFields","idOnly"],release:["fullChangedFields","idOnly"],"start-task":["fullChangedFields","idOnly"],"pause-task":["fullChangedFields","idOnly"],"close-task":["fullChangedFields","idOnly"],restore:["fullChangedFields","idOnly"],append:["fullChangedFields"],"update-many":["fullChangedFields"],"close-many":["fullChangedFields"],assurance:["fullChangedFields","idOnly"]},PLAN_CREATE_METADATA_PARAMETER_KEYS=["createMode","status","deadline","estimate","acceptanceCriteria","definitionOfReady","order","rank","goal","objective","value","impact","outcome","whyNow","assignee","reviewer","risk","confidence","sprint","release","blockedReason","unblockNote","reporter","severity","environment","reproSteps","resolution","expectedResult","actualResult","affectedVersion","fixedVersion","component","regression","customerImpact","comment","note","learning","reminder","event","typeOption"],PM_TOOL_ACTION_NESTED_OPTION_COMPATIBILITY_KEYS=Object.freeze({"close-many":["list","expected_result","expected","actual_result","actual","validate_close","dry_run","checkpoint","no_checkpoint","filterAssignee_filter"],"update-many":["list","update","dry_run","checkpoint","no_checkpoint","filterAssignee_filter"],...Object.fromEntries(PM_TOOL_ACTIONS.filter(action=>action==="upgrade"||action==="install"||action==="extension"||action==="package"||action.startsWith("extension-")||action.startsWith("package-")).map(action=>[action,["project","local","global"]]))});function toSchemaKeyList(values){return normalizeUniqueStringList(values)}const CREATE_CONTRACT_PARAMETER_KEYS=toSchemaKeyList([...TOOL_CREATE_OPTION_CONTRACTS.map(entry=>entry.param),...TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACTS.map(entry=>entry.param),"assignee","closeReason","completedAt"]),UPDATE_CONTRACT_PARAMETER_KEYS=toSchemaKeyList([...TOOL_UPDATE_OPTION_CONTRACTS.map(entry=>entry.param),...TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACTS.map(entry=>entry.param),"force"]),UPDATE_MANY_CONTRACT_PARAMETER_KEYS=toSchemaKeyList([...TOOL_UPDATE_MANY_FILTER_OPTION_CONTRACTS.map(entry=>entry.param),...UPDATE_CONTRACT_PARAMETER_KEYS.filter(key=>key!=="allowMissingParent"&&key!=="completedAt"),"dryRun","rollback","noCheckpoint"]),CLOSE_MANY_CONTRACT_PARAMETER_KEYS=toSchemaKeyList([...TOOL_CLOSE_MANY_FILTER_OPTION_CONTRACTS.map(entry=>entry.param),"reason","completedAt","resolution","expectedResult","actualResult","validateClose","dryRun","rollback","noCheckpoint","author","message","force"]),CONTEXT_CONTRACT_PARAMETER_KEYS=toSchemaKeyList([...TOOL_CONTEXT_OPTION_CONTRACTS.map(entry=>entry.param),"past","section"]),ACTIVITY_CONTRACT_PARAMETER_KEYS=toSchemaKeyList([...TOOL_ACTIVITY_OPTION_CONTRACTS.map(entry=>entry.param),"stream"]),LIST_CONTRACT_PARAMETER_KEYS=toSchemaKeyList([...TOOL_LIST_FILTER_OPTION_CONTRACTS.map(entry=>entry.param),"all","includeBody","noTruncate","strictRead","compact","brief","full"]),FIXED_STATUS_LIST_CONTRACT_PARAMETER_KEYS=LIST_CONTRACT_PARAMETER_KEYS.filter(parameter=>parameter!=="all"&¶meter!=="status"),LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS=[[{property:"today",schema:{const:!0}},{property:"recent",schema:{const:!0}}],[{property:"today",schema:{const:!0}},{property:"updatedAfter",schema:{type:"string",pattern:"\\S"}}],[{property:"recent",schema:{const:!0}},{property:"updatedAfter",schema:{type:"string",pattern:"\\S"}}]],CONTRACTS_PROJECTION_MUTUALLY_EXCLUSIVE_GROUPS=[[{property:"summary",schema:{const:!0}},{property:"schemaOnly",schema:{const:!0}}],[{property:"summary",schema:{const:!0}},{property:"flagsOnly",schema:{const:!0}}],[{property:"summary",schema:{const:!0}},{property:"availabilityOnly",schema:{const:!0}}],[{property:"schemaOnly",schema:{const:!0}},{property:"flagsOnly",schema:{const:!0}}],[{property:"schemaOnly",schema:{const:!0}},{property:"availabilityOnly",schema:{const:!0}}],[{property:"flagsOnly",schema:{const:!0}},{property:"availabilityOnly",schema:{const:!0}}]],AGGREGATE_CONTRACT_PARAMETER_KEYS=toSchemaKeyList([...TOOL_AGGREGATE_OPTION_CONTRACTS.map(entry=>entry.param),"count","completion","includeUnparented"]),SEARCH_CONTRACT_PARAMETER_KEYS=toSchemaKeyList(["query","keywords","mode","semantic","hybrid","includeLinked","titleExact","phraseExact","highlight","compact","full",...TOOL_SEARCH_FILTER_OPTION_CONTRACTS.map(entry=>entry.param)]),NEXT_CONTRACT_PARAMETER_KEYS=toSchemaKeyList(["type","tag","priority","assignee","assigneeFilter","sprint","release","parent","limit","blockedLimit","readyOnly","format","includeDecisions","includeGates","includeContainers","tokenBudget","explainRanking"]),AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS=["author","message","force"],CLOSE_ACTION_OPTION_KEYS=["releaseAssignment","text","reason","closeReason","completedAt","duplicateOf","validateClose","resolution","expectedResult","actualResult"],LIFECYCLE_AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS=["author","assignee","message","force"],MANAGED_EXTENSION_PACKAGE_OPTION_KEYS=["dryRun","target","scope","capability","declarative","github","ref","init","install","uninstall","explore","manage","offline","describe","markdown","output","reload","doctor","catalog","list","adopt","adoptAll","activate","deactivate","runtimeProbe","fixManagedState","isolated","ignoreGlobal","detail","trace","watch","strictExit","failOnWarn"];function managedLifecycleSchemaContracts(prefix){return{[`${prefix}-init`]:{required:["target"],optional:["scope","capability",...prefix==="package"?["declarative"]:[]]},[`${prefix}-install`]:{optional:["target","github","scope","ref","dryRun"],anyOfRequired:[["target"],["github"]]},[`${prefix}-uninstall`]:{required:["target"],optional:["scope"]},[`${prefix}-explore`]:{optional:["scope"]},[`${prefix}-manage`]:{optional:["scope","runtimeProbe","fixManagedState","offline"]},[`${prefix}-describe`]:{optional:["target","scope","markdown","output"]},[`${prefix}-reload`]:{optional:["scope","watch"]},[`${prefix}-doctor`]:{optional:["scope","detail","trace","fixManagedState","isolated","ignoreGlobal","strictExit","failOnWarn"]},[`${prefix}-catalog`]:{optional:["scope","fields"]},[`${prefix}-adopt`]:{required:["target"],optional:["scope","github","ref"]},[`${prefix}-adopt-all`]:{optional:["scope"]},[`${prefix}-activate`]:{required:["target"],optional:["scope"]},[`${prefix}-deactivate`]:{required:["target"],optional:["scope"]},[prefix]:{optional:MANAGED_EXTENSION_PACKAGE_OPTION_KEYS,dependentAnyOfRequired:[{property:"dryRun",value:!0,anyOfRequired:[["install","target"],["install","github"]]}],mutuallyExclusiveWhen:[[{property:"dryRun",schema:{const:!0}},{property:"install",schema:{const:!1}}]]}}}const SCHEDULING_ACTION_SCHEMA_CONTRACT={required:["title"],optional:["start","duration","end","location","timezone","allDay","parent","allowMissingParent","tags","priority","body","description","author","message"]},UPGRADE_ACTION_SCHEMA_CONTRACT={optional:["target","scope","dryRun","cliOnly","packagesOnly","repair","tag","packageName"]},PM_TOOL_ACTION_SCHEMA_CONTRACTS={init:{optional:["prefix","idPrefix","workspace","preset","typePreset","defaults","author","agentGuidance","withPackages","mergeFence","force","verbose"]},config:{required:["scope","configAction"],optional:["key","value","criterion","clearCriteria","format","policy"]},...managedLifecycleSchemaContracts("extension"),...managedLifecycleSchemaContracts("package"),"package-upgrade":UPGRADE_ACTION_SCHEMA_CONTRACT,install:{optional:["target","github","scope","ref","dryRun"],anyOfRequired:[["target"],["github"]]},upgrade:UPGRADE_ACTION_SCHEMA_CONTRACT,create:{required:["title","description","type","status","priority","message"],optional:CREATE_CONTRACT_PARAMETER_KEYS},copy:{required:["id"],optional:["title","author","message","allowDuplicate"]},focus:{optional:["id","clear"],mutuallyExclusive:[["id","clear"]]},list:{optional:LIST_CONTRACT_PARAMETER_KEYS,mutuallyExclusiveWhen:LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS},"list-all":{optional:LIST_CONTRACT_PARAMETER_KEYS,mutuallyExclusiveWhen:LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS},"list-draft":{optional:FIXED_STATUS_LIST_CONTRACT_PARAMETER_KEYS,mutuallyExclusiveWhen:LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS},"list-open":{optional:FIXED_STATUS_LIST_CONTRACT_PARAMETER_KEYS,mutuallyExclusiveWhen:LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS},"list-in-progress":{optional:FIXED_STATUS_LIST_CONTRACT_PARAMETER_KEYS,mutuallyExclusiveWhen:LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS},"list-blocked":{optional:FIXED_STATUS_LIST_CONTRACT_PARAMETER_KEYS,mutuallyExclusiveWhen:LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS},"list-closed":{optional:FIXED_STATUS_LIST_CONTRACT_PARAMETER_KEYS,mutuallyExclusiveWhen:LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS},"list-canceled":{optional:FIXED_STATUS_LIST_CONTRACT_PARAMETER_KEYS,mutuallyExclusiveWhen:LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS},aggregate:{optional:AGGREGATE_CONTRACT_PARAMETER_KEYS},guide:{optional:["list","format","depth"]},context:{optional:CONTEXT_CONTRACT_PARAMETER_KEYS},ctx:{optional:CONTEXT_CONTRACT_PARAMETER_KEYS},get:{required:["id"],optional:["for","tokenBudget","at","depth","full","fields","tree","treeDepth","format"]},search:{optional:SEARCH_CONTRACT_PARAMETER_KEYS,anyOfRequired:[["query"],["keywords"]]},eval:{optional:["mode","k","failUnder","queries","format"]},events:{optional:["since","type","author","item","limit","full","provenance","provenanceSummary","harness","agentInstance","provenanceFilter","cursorMode"]},merge:{required:["subcommand"],optional:["dryRun","preCommitHook","stage","author","message","force","includeReconciled","artifact","basePath","oursPath","theirsPath","output","outputPath","itemPath","prefer"]},workspace:{required:["subcommand"],optional:["snapshotAction","name","target","dryRun","force","author","message","lockTtlSeconds","lockWaitMs"],conditionalRequired:[{property:"subcommand",value:"snapshot",required:["snapshotAction"]}]},meet:SCHEDULING_ACTION_SCHEMA_CONTRACT,event:SCHEDULING_ACTION_SCHEMA_CONTRACT,remind:{required:["title"],optional:["at","text","parent","allowMissingParent","tags","priority","body","description","author","message"]},next:{optional:[...NEXT_CONTRACT_PARAMETER_KEYS,"for"]},reindex:{optional:["mode","progress"]},history:{required:["id"],optional:["limit","compact","full","provenance","provenanceSummary","harness","agentInstance","provenanceFilter","diff","verify","field","strictExit","failOnWarn","format"]},"history-attest":{optional:["verify","output","hashAlgorithm"],mutuallyExclusive:[["verify","hashAlgorithm"]]},"history-redact":{required:["id"],optional:["literal","regex","replacement","dryRun",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],anyOfRequired:[["literal"],["regex"]]},"history-repair":{optional:["id","all","dryRun","normalizeProvenance","salvageTail",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],oneOfRequired:[["id"],["all"]],mutuallyExclusiveWhen:[[{property:"salvageTail",schema:{const:!0}},{property:"all",schema:{const:!0}}],[{property:"salvageTail",schema:{const:!0}},{property:"normalizeProvenance",schema:{const:!0}}]]},"history-author-acknowledge":{optional:["historyEvent","allActionable","dryRun","planFingerprint","limit","attributedAuthor","reviewer","reason"],oneOfRequired:[["historyEvent"],["allActionable"]]},"history-compact":{optional:["id","before","ids","allOver","closed","allStreams","minEntries","dryRun",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS]},schema:{mutuallyExclusiveWhen:[[{property:"subcommand",schema:{const:"policy-mode"}},{property:"name",schema:{not:{enum:["advise","refuse"]}}}]],required:["subcommand"],optional:["definition","policy","message","name","description","defaultStatus","folder","alias","role","order","fieldType","commands","cliFlag","required","requiredOnCreate","allowUnset","requiredTypes","typePreset","infer","minCount","apply","to","migrationId","fieldTypeScope","dryRun","author","force"],conditionalRequired:[{property:"subcommand",value:"policy-put",required:["definition"]},{property:"subcommand",value:"policy-remove",required:["name"]},{property:"subcommand",value:"policy-mode",required:["name"]},{property:"subcommand",value:"policy-check",required:["name"]},{property:"subcommand",value:"policy-approve",required:["name","policy"]},{property:"subcommand",value:"show",required:["name"]},{property:"subcommand",value:"show-status",required:["name"]},{property:"subcommand",value:"add-type",required:["name"]},{property:"subcommand",value:"remove-type",required:["name"]},{property:"subcommand",value:"add-status",required:["name"]},{property:"subcommand",value:"remove-status",required:["name"]},{property:"subcommand",value:"add-field",required:["name"]},{property:"subcommand",value:"remove-field",required:["name"]},{property:"subcommand",value:"show-field",required:["name"]},{property:"subcommand",value:"rename-type",required:["name","to"]},{property:"subcommand",value:"rename-field",required:["name","to"]},{property:"subcommand",value:"remap-status",required:["name","to"]},{property:"subcommand",value:"apply-preset",required:["typePreset"]}]},profile:{required:["subcommand"],optional:["name","dryRun","author","force"],conditionalRequired:[{property:"subcommand",value:"show",required:["name"]},{property:"subcommand",value:"apply",required:["name"]},{property:"subcommand",value:"lint",required:["name"]}]},plan:{required:["subcommand"],optional:["id","stepRef","reorderTo","title","description","template","scope","parent","related","blocks","blockedBy","harness","mode","resumeContext","tags","priority",...PLAN_CREATE_METADATA_PARAMETER_KEYS,"body","claim","fromSearch","stepTitle","step","stepBody","stepOwner","stepStatus","stepEvidence","stepBlockedReason","stepReplacement","dependsOn","link","linkKind","linkNote","promoteToItemDep","allowMultipleActive","file","test","doc","decisionText","decision","decisionRationale","decisionEvidence","discoveryText","discovery","validationText","validation","validationCommand","validationExpected","depth","fields","steps","materializeType","materializeParent","materializeTags","field",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS]},activity:{optional:ACTIVITY_CONTRACT_PARAMETER_KEYS},restore:{required:["id","target"],optional:AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS},update:{required:["id"],optional:UPDATE_CONTRACT_PARAMETER_KEYS,mutuallyExclusive:[["acceptanceCriteria","addAc"],["acceptanceCriteria","removeAc"]]},"update-many":{optional:UPDATE_MANY_CONTRACT_PARAMETER_KEYS,mutuallyExclusive:[["acceptanceCriteria","addAc"],["acceptanceCriteria","removeAc"]]},close:{required:["id"],optional:[...CLOSE_ACTION_OPTION_KEYS,...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS]},"close-many":{optional:CLOSE_MANY_CONTRACT_PARAMETER_KEYS},delete:{required:["id"],optional:["dryRun",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS]},append:{required:["id","body"],optional:AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS},comments:{required:["id"],optional:["text","add","stdin","edit","delete","limit","full","ifAbsent",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],mutuallyExclusive:[["edit","ifAbsent"],["delete","ifAbsent"]]},notes:{required:["id"],optional:["text","add","addJson","stdin","edit","delete","limit","since","eventType","includeMeta","full","ifAbsent",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],mutuallyExclusive:[["addJson","add"],["addJson","stdin"],["addJson","file"],["addJson","edit"],["addJson","delete"],["edit","ifAbsent"],["delete","ifAbsent"]]},learnings:{required:["id"],optional:["text","add","stdin","edit","delete","limit","full","ifAbsent",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],mutuallyExclusive:[["edit","ifAbsent"],["delete","ifAbsent"]]},files:{required:[],optional:["id","add","addGlob","remove","migrate","list","addNote","discover","apply","discoveryNote","appendStable","validatePaths","lookupPath","scope","limit","offset","noTruncate","strictRead","explain","lines","decisionDepth",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],anyOfRequired:[["id"],["lookupPath"]],dependentAnyOfRequired:[{property:"addNote",anyOfRequired:[["add"],["addGlob"]]}]},docs:{required:["id"],optional:["add","addGlob","remove","migrate","addNote","list","validatePaths",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],dependentAnyOfRequired:[{property:"addNote",anyOfRequired:[["add"],["addGlob"]]}]},deps:{required:["id"],optional:["format","maxDepth","collapse","summary","full","nodeLimit","edgeLimit","tokenBudget","cursor","direction","kind"]},graph:{required:["subcommand"],optional:["id","target","kind","maxDepth","limit","after","direction","maxPaths","sample","exemptIsolate","exemptIsolateType","saveBaseline","rebuild","clear","summary","full"]},test:{required:["id"],optional:["list","add","addJson","remove","removeIndex","update","updateIndex","setJson","run","match","onlyIndex","onlyLast","background","timeout","progress","envSet","envClear","sharedHostSafe","pmContext","overrideLinkedPmContext","workspaceContext","overrideLinkedWorkspaceContext","allowUntrustedLinkedTests","acknowledgeLinkedTests","failOnContextMismatch","failOnSkipped","failOnEmptyTestRun","requireAssertionsForPm","checkContext","autoPmContext","measure","metricBelow","metricDiff",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],dependentAnyOfRequired:[{property:"update",anyOfRequired:[["setJson"]]},{property:"updateIndex",anyOfRequired:[["setJson"]]},{property:"setJson",anyOfRequired:[["update"],["updateIndex"]]}],mutuallyExclusive:[["update","updateIndex"],["acknowledgeLinkedTests","run"],["acknowledgeLinkedTests","background"]]},"test-all":{optional:["status","limit","offset","background","timeout","progress","envSet","envClear","sharedHostSafe","pmContext","overrideLinkedPmContext","workspaceContext","overrideLinkedWorkspaceContext","allowUntrustedLinkedTests","failOnContextMismatch","failOnSkipped","failOnEmptyTestRun","requireAssertionsForPm","checkContext","autoPmContext"]},telemetry:{optional:["subcommand","limit"]},"test-runs-list":{optional:["status","limit"]},"test-runs-status":{required:["runId"]},"test-runs-logs":{required:["runId"],optional:["stream","tail"]},"test-runs-stop":{required:["runId"],optional:["force"]},"test-runs-resume":{required:["runId"],optional:["author"]},stats:{optional:["includeEmpty","storage","metadataCoverage","fieldUtilization","byAssignee","byTag","byPriority","tagPrefix","measurements","metric","measurementLimit","observe","improvementDirection","measurementSource","measurementItem","measurementRevision","author","message","provenanceCoverage","fleetAttribution","since","eventLimit","minimumSample"]},duplicates:{optional:["status","since","threshold","limit","exhaustive"]},health:{optional:["strictDirectories","requireMergeDrivers","strictExit","failOnWarn","checkOnly","checkTelemetry","noRefresh","refreshVectors","verboseStaleItems","verboseAuthorEvents","brief","summary","skipVectors","skipIntegrity","skipDrift","full"]},validate:{optional:["checkCompleteness","checkStorageIntegrity","checkMetadata","metadataProfile","checkResolution","checkLifecycle","checkStaleBlockers","dependencyCycleSeverity","parentCycleSeverity","checkFiles","scanMode","includePmInternals","verboseFileLists","verboseDiagnostics","allAffectedIds","strictExit","failOnWarn","fixHints","autoFix","dryRun","fixScope","pruneMissing","checkHistoryDrift","checkCommandReferences","counts","full"]},assurance:{required:["subcommand"],optional:["kind","id","definition","trigger","treeId","gate","limit","dryRun","author","message","preset","owner","apply","enforcement"],conditionalRequired:[{property:"subcommand",value:"list",required:["kind"]},{property:"subcommand",value:"show",required:["kind","id"]},{property:"subcommand",value:"put",required:["kind","id","definition"]},{property:"subcommand",value:"remove",required:["kind","id"]},{property:"subcommand",value:"run",required:["id","trigger"]},{property:"subcommand",value:"apply",required:["preset","owner"]},{property:"subcommand",value:"derive",required:["owner"]},{property:"subcommand",value:"risk",required:["definition"]},{property:"subcommand",value:"lineages",required:["definition"]},{property:"subcommand",value:"promote",required:["id","enforcement"]}],mutuallyExclusiveWhen:[[{property:"subcommand",schema:{const:"risk"}},{property:"definition",schema:{not:{required:["policy","change"]}}}],[{property:"subcommand",schema:{const:"lineages"}},{property:"definition",schema:{anyOf:[{required:["change"]},{not:{required:["policy"]}}]}}]]},gc:{optional:["dryRun","gcScope"]},contracts:{optional:["contractAction","command","summary","schemaOnly","flagsOnly","availabilityOnly","runtimeOnly","activeOnly","full"],mutuallyExclusiveWhen:CONTRACTS_PROJECTION_MUTUALLY_EXCLUSIVE_GROUPS},completion:{required:["shell"],optional:["eagerTags"]},claim:{optional:["start","id","next","ifAvailable","maxAttempts","includeDecisions",...NEXT_CONTRACT_PARAMETER_KEYS,...LIFECYCLE_AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],oneOfRequired:[["id"],["next"]],mutuallyExclusiveWhen:[[{property:"start",schema:{const:!0}},{property:"next",schema:{const:!0}}],[{property:"start",schema:{const:!0}},{property:"ifAvailable",schema:{const:!0}}]]},release:{required:["id"],optional:["pause","handoff",...LIFECYCLE_AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],dependentAnyOfRequired:[{property:"handoff",anyOfRequired:[["message"]]}],mutuallyExclusiveWhen:[[{property:"pause",schema:{const:!0}},{property:"handoff",schema:{type:"string"}}]]},"start-task":{required:["id"],optional:LIFECYCLE_AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS},"pause-task":{required:["id"],optional:LIFECYCLE_AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS},"close-task":{required:["id"],optional:["text","validateClose",...LIFECYCLE_AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS]},"item-reopen":{required:["id","reason"],optional:["status","expectedResult","author","message","force"]}},PM_TOOL_ACTION_PARAMETER_CONTRACTS=Object.freeze(Object.fromEntries(PM_TOOL_ACTIONS.map(action=>[action,PM_TOOL_ACTION_SCHEMA_CONTRACTS[action]])));function fallbackToolParameterDescription(key){return key.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]/g," ").trim().replace(/^./,value=>value.toUpperCase()).concat(".")}function decorateToolParameterDefinition(key,definition){const baseDefinition=typeof definition=="object"&&definition!==null?{...definition}:{},metadata=PM_TOOL_PARAMETER_METADATA[key];return{...baseDefinition,description:metadata?.description??fallbackToolParameterDescription(key),...metadata?.examples?{examples:metadata.examples}:{}}}function actionScopedToolParameterMetadata(action,key){if(action==="history-attest"&&key==="verify")return{description:"Compare all retained history streams with a detached JSON proof object. Server-local proof paths are not accepted over MCP."};if(action==="history-attest"&&key==="output")return{description:"Local CLI/SDK only. MCP rejects this field; save the returned JSON bundle on the client."};if(action==="claim"&&key==="start")return{description:"Claim an explicit item and move it to its configured in-progress status."};if((action==="list"||action.startsWith("list-"))&&key==="all")return{description:"Return items from every lifecycle status instead of the default active-status set."};if(action==="plan"&&Object.prototype.hasOwnProperty.call(PLAN_ACTION_PARAMETER_METADATA,key))return PLAN_ACTION_PARAMETER_METADATA[key];const actionOverrides=PM_TOOL_ACTION_SCOPED_PARAMETER_METADATA[action];return actionOverrides&&Object.prototype.hasOwnProperty.call(actionOverrides,key)?actionOverrides[key]:PM_TOOL_PARAMETER_METADATA[key]}function decorateActionScopedToolParameterDefinition(action,key,definition){const baseDefinition=typeof definition=="object"&&definition!==null?{...definition}:{},metadata=actionScopedToolParameterMetadata(action,key);return{...baseDefinition,description:metadata?.description??fallbackToolParameterDescription(key),...metadata?.examples?{examples:metadata.examples}:{}}}function actionScopedToolParameterDefinition(action,key){if(action==="claim"&&key==="start")return{type:"boolean"};const actionProperties=PM_TOOL_ACTION_SCOPED_PARAMETER_PROPERTIES[action];return actionProperties&&Object.prototype.hasOwnProperty.call(actionProperties,key)?actionProperties[key]:action==="plan"&&Object.prototype.hasOwnProperty.call(PLAN_ACTION_PARAMETER_PROPERTIES,key)?PLAN_ACTION_PARAMETER_PROPERTIES[key]:(action==="get"||action==="history"||action==="search")&&key==="format"?{type:"string",enum:["json","toon"]}:key==="pause"||key==="handoff"||key==="releaseAssignment"||key==="hashAlgorithm"?PM_TOOL_PARAMETER_PROPERTIES[key]:BASE_TOOL_PARAMETER_PROPERTIES[key]}function buildActionScopedSchemaProperties(action,allowedKeys){const properties={action:{const:action,description:PM_TOOL_PARAMETER_METADATA.action?.description??"Tool action to execute."}};for(const key of allowedKeys){if(key==="action")continue;const definition=actionScopedToolParameterDefinition(action,key);definition&&(properties[key]=decorateActionScopedToolParameterDefinition(action,key,definition))}return properties}function buildOneOfSchemaEntries(action,oneOfRequiredGroups){const allOneOfFields=oneOfRequiredGroups.flat();return oneOfRequiredGroups.map(requiredFields=>{const otherFields=allOneOfFields.filter(field=>!requiredFields.includes(field));return{required:[...requiredFields],...otherFields.length>0?{not:{anyOf:otherFields.map(field=>({required:[field]}))}}:{},...action==="history-repair"&&requiredFields.includes("all")?{properties:{all:{const:!0}}}:action==="claim"&&requiredFields.includes("next")?{properties:{next:{const:!0}}}:{}}})}function schemaPropertyCondition(property,value){return{...value===void 0?{}:{properties:{[property]:{const:value}}},required:[property]}}function buildActionScopedAllOf(contract){const allOf=[];if(contract.conditionalRequired&&contract.conditionalRequired.length>0)for(const entry of contract.conditionalRequired)allOf.push({if:schemaPropertyCondition(entry.property,entry.value),then:{required:entry.required}});if(contract.dependentAnyOfRequired&&contract.dependentAnyOfRequired.length>0)for(const entry of contract.dependentAnyOfRequired)allOf.push({if:schemaPropertyCondition(entry.property,entry.value),then:{anyOf:entry.anyOfRequired.map(requiredFields=>({required:[...requiredFields]}))}});if(contract.mutuallyExclusive&&contract.mutuallyExclusive.length>0)for(const group of contract.mutuallyExclusive)allOf.push({not:{required:toSchemaKeyList(group)}});if(contract.mutuallyExclusiveWhen&&contract.mutuallyExclusiveWhen.length>0)for(const group of contract.mutuallyExclusiveWhen)allOf.push({not:{allOf:group.map(condition=>({properties:{[condition.property]:condition.schema},required:[condition.property]}))}});return allOf}function pmToolActionParameterKeys(action){if(!Object.prototype.hasOwnProperty.call(PM_TOOL_ACTION_SCHEMA_CONTRACTS,action))return;const contract=PM_TOOL_ACTION_SCHEMA_CONTRACTS[action],mutationParameterKeys=PM_TOOL_ACTION_MUTATION_PARAMETER_KEYS[action]??[];return toSchemaKeyList(["action",...PM_TOOL_GLOBAL_PARAMETER_KEYS,...resolveReadOutputSurface(action)!==void 0?PM_TOOL_READ_OUTPUT_PARAMETER_KEYS:[],...mutationParameterKeys,...contract.required??[],...contract.optional??[]])}function pmToolActionNestedOptionKeys(action){const parameterKeys=pmToolActionParameterKeys(action);if(parameterKeys!==void 0)return toSchemaKeyList([...parameterKeys,...PM_TOOL_ACTION_NESTED_OPTION_COMPATIBILITY_KEYS[action]??[]])}function buildActionScopedToolSchema(action){const contract=PM_TOOL_ACTION_SCHEMA_CONTRACTS[action],required=toSchemaKeyList(contract.required??[]),allowedKeys=pmToolActionParameterKeys(action),schema={type:"object",additionalProperties:!1,required:["action",...required],title:`pm action "${action}" parameters`,properties:buildActionScopedSchemaProperties(action,allowedKeys)};contract.anyOfRequired&&contract.anyOfRequired.length>0&&(schema.anyOf=contract.anyOfRequired.map(requiredFields=>({required:[...requiredFields]}))),contract.oneOfRequired&&contract.oneOfRequired.length>0&&(schema.oneOf=buildOneOfSchemaEntries(action,contract.oneOfRequired));const allOf=buildActionScopedAllOf(contract);return allOf.length>0&&(schema.allOf=allOf),schema}function buildPmActionToolInputSchema(action,options={}){const actionSchema=buildActionScopedToolSchema(action),actionProperties={...actionSchema.properties};delete actionProperties.action;const conditionalBranches=[...actionSchema.anyOf??[],...actionSchema.oneOf??[]],required=(options.required??actionSchema.required.map(String)).filter(key=>key==="action"?!1:options.required===void 0?!0:!conditionalBranches.some(branch=>branch.required?.map(String).includes(key))),schema={type:"object",additionalProperties:options.additionalProperties??!0,properties:{...actionProperties,options:{type:"object",additionalProperties:!0,description:"Advanced command options forwarded to the selected pm action."},...options.properties},required};return actionSchema.anyOf!==void 0&&(schema.anyOf=actionSchema.anyOf),actionSchema.oneOf!==void 0&&(schema.oneOf=actionSchema.oneOf),actionSchema.allOf!==void 0&&(schema.allOf=actionSchema.allOf),schema}function createLazyContractSchema(build){let value;const resolve=()=>value??=build();return new Proxy({},{get:(_target,prop)=>resolve()[prop],has:(_target,prop)=>prop in resolve(),ownKeys:()=>Reflect.ownKeys(resolve()),getOwnPropertyDescriptor:(_target,prop)=>{const descriptor=Reflect.getOwnPropertyDescriptor(resolve(),prop);return descriptor&&(descriptor.configurable=!0),descriptor}})}const PM_TOOL_PARAMETERS_SCHEMA_VERSION="4.22.0",PM_TOOL_PARAMETERS_SCHEMA_MAJOR=PM_TOOL_PARAMETERS_SCHEMA_VERSION.split(".")[0],PM_PROVIDER_TOOL_PARAMETERS_SCHEMA_VERSION="1.11.0",PM_TOOL_PARAMETERS_SCHEMA=createLazyContractSchema(()=>({$schema:"https://json-schema.org/draft/2020-12/schema",$id:`https://schema.unbrained.dev/pm-cli/tool-parameters-v${PM_TOOL_PARAMETERS_SCHEMA_MAJOR}.schema.json`,title:"pm-cli tool parameters (action-scoped strict schema)","x-schema-version":PM_TOOL_PARAMETERS_SCHEMA_VERSION,type:"object",oneOf:PM_TOOL_ACTIONS.map(action=>buildActionScopedToolSchema(action))}));function toProviderCompatibleParameterDefinition(key,definition){const decorated=decorateToolParameterDefinition(key,definition);if(typeof decorated.type=="string")return decorated;const firstTypedVariant=(Array.isArray(decorated.anyOf)?decorated.anyOf:[]).find(variant=>typeof variant.type=="string");if(firstTypedVariant){const{anyOf:_anyOf2,...rest2}=decorated;return{...firstTypedVariant,...rest2}}const{anyOf:_anyOf,...rest}=decorated;return{...rest,type:"string"}}function buildProviderCompatibleToolSchema(){const properties={action:{type:"string",description:PM_TOOL_PARAMETER_METADATA.action?.description??"Tool action to execute."},options:{type:"object",additionalProperties:!0,description:"Advanced command options object forwarded to the selected pm action."}};for(const key of Object.keys(PM_TOOL_PARAMETER_PROPERTIES).sort())properties[key]=toProviderCompatibleParameterDefinition(key,PM_TOOL_PARAMETER_PROPERTIES[key]);return{title:"pm-cli tool parameters (provider-compatible flat schema)","x-schema-version":PM_PROVIDER_TOOL_PARAMETERS_SCHEMA_VERSION,type:"object",additionalProperties:!1,required:["action"],properties}}const PM_PROVIDER_TOOL_PARAMETERS_SCHEMA=createLazyContractSchema(buildProviderCompatibleToolSchema),_testOnlyCliContracts={buildActionScopedToolSchema,buildProviderCompatibleToolSchema,decorateActionScopedToolParameterDefinition,decorateToolParameterDefinition,toolActionSchemaContracts:PM_TOOL_ACTION_SCHEMA_CONTRACTS,toolParameterMetadata:PM_TOOL_PARAMETER_METADATA,toProviderCompatibleParameterDefinition,toUniqueFlagContracts,withFlagAliasMetadata};export{CLOSE_ACTION_OPTION_KEYS,PLAN_CREATE_METADATA_PARAMETER_KEYS,PM_PROVIDER_TOOL_PARAMETERS_SCHEMA,PM_PROVIDER_TOOL_PARAMETERS_SCHEMA_VERSION,PM_TOOL_ACTION_PARAMETER_CONTRACTS,PM_TOOL_PARAMETERS_SCHEMA,PM_TOOL_PARAMETERS_SCHEMA_MAJOR,PM_TOOL_PARAMETERS_SCHEMA_VERSION,PM_TOOL_RESERVED_CUSTOM_FIELD_PROPERTIES,_testOnlyCliContracts,buildPmActionToolInputSchema,pmToolActionNestedOptionKeys,pmToolActionParameterKeys,resolvePmToolCustomFieldCollision};
|
|
2
2
|
//# sourceMappingURL=tool-schema.js.map
|
package/dist/sdk/core.d.ts
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
export { BASELINE_ITEM_FORMAT_VERSION,BUILTIN_ITEM_TYPE_VALUES,CONFIDENCE_TEXT_VALUES,CURRENT_ITEM_FORMAT_VERSION,DEPENDENCY_KIND_VALUES,EXIT_CODE,ISSUE_SEVERITY_VALUES,ITEM_TYPE_VALUES,PM_CLI_EXPECTED_ERROR_NAME,PmCliError,PmClient,RISK_VALUES,STATUS_VALUES,canonicalDocument,classifyItemFormatVersion,createPmCliExpectedError,effectiveItemFormatVersion,emptyImportedDocument,isPmCliExpectedError,normalizeItemFormatVersion,normalizeItemId,normalizeStatusInput,nowIso,runAction,serializeItemDocument,aggregate,append,claim,claimNext,close,comments,context,copy,create,deleteItem,deps,docs,files,filesDiscover,focus,get,graph,learnings,list,next,notes,release,reopen,restore,search,update,type AggregateOptions,type AggregateResult,type AggregateRow,type AssuranceActionInput,type AssuranceActionResult,type AppendCommandOptions,type AppendResult,type ClaimNextOptions,type ClaimResult,type CloseResult,type CommentsCommandOptions,type CommentsResult,type ContextOptions,type ContextResult,type CopyResult,type CreateResult,type Dependency,type DeleteResult,type DepsCommandOptions,type DepsResult,type DocsCommandOptions,type DocsResult,type FilesCommandOptions,type FilesDiscoverOptions,type FilesDiscoverResult,type FilesResult,type FocusResult,type GetOptions,type GetResult,type ItemFormatVersionScanEntry,type ItemFormatVersionScanResult,type ItemFormatVersionStatus,type LearningsCommandOptions,type LearningsResult,type ListOptions,type ListResult,listAllComplete,type PmCompleteListOptions,type PmCompleteListResult,type NextOptions,type NextResult,type NotesCommandOptions,type NotesResult,type PmActionInput,type PmActionName,type PmActionOptions,type PmClientOptions,type ReleaseResult,type ReleaseMutationOptions,type PreviousTerminalEvidence,type RecurrenceReceipt,type ReopenCommandOptions,type ReopenResult,type RestoreResult,type SearchOptions,type SearchResult,type UpdateResult,} from "./runtime.js";
|
|
7
7
|
export * from "./core-governance.js";
|
|
8
8
|
export { updateLinkedTest,type LinkedTestUpdateSelector,type LinkedTestMetadataPatch,type UpdateLinkedTestOptions,type UpdateLinkedTestResult,} from "./test/update.js";
|
|
9
|
-
export { isItemAlreadyExistsError,type PmItemAlreadyExistsError } from "./errors.js";
|
|
9
|
+
export { isItemAlreadyExistsError,type PmItemAlreadyExistsError,isPmTokenBudgetRecovery,type PmTokenBudgetRecovery } from "./errors.js";
|
|
10
10
|
export * from "./agent-session-context.js";
|
|
11
11
|
export { isAlreadyClaimedError } from "./lifecycle/claim.js";
|
|
12
12
|
export { PM_READ_OUTPUT_DIMENSIONS,PM_READ_OUTPUT_OPTION_FLAGS,PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,PM_READ_OUTPUT_SURFACE_CONTRACTS,applyReadOutputDimensions,decodeReadOutputContinuationCursor,encodeReadOutputContinuationCursor,isReadOutputBudgetExceeded,resolveReadOutputDimensions,resolveReadOutputEncoding,resolveReadOutputSurface,validateReadOutputOptions,} from "./read-output-contracts.js";
|
package/dist/sdk/core.js
CHANGED
|
@@ -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]="c311d37b-532b-5eed-b7c1-82ddc829ddaf")}catch{}})();import{BASELINE_ITEM_FORMAT_VERSION,BUILTIN_ITEM_TYPE_VALUES,CONFIDENCE_TEXT_VALUES,CURRENT_ITEM_FORMAT_VERSION,DEPENDENCY_KIND_VALUES,EXIT_CODE,ISSUE_SEVERITY_VALUES,ITEM_TYPE_VALUES,PM_CLI_EXPECTED_ERROR_NAME,PmCliError,PmClient,RISK_VALUES,STATUS_VALUES,canonicalDocument,classifyItemFormatVersion,createPmCliExpectedError,effectiveItemFormatVersion,emptyImportedDocument,isPmCliExpectedError,normalizeItemFormatVersion,normalizeItemId,normalizeStatusInput,nowIso,runAction,serializeItemDocument,aggregate,append,claim,claimNext,close,comments,context,copy,create,deleteItem,deps,docs,files,filesDiscover,focus,get,graph,learnings,list,next,notes,release,reopen,restore,search,update,listAllComplete}from"./runtime.js";export*from"./core-governance.js";import{updateLinkedTest}from"./test/update.js";import{isItemAlreadyExistsError,isPmTokenBudgetRecovery}from"./errors.js";export*from"./agent-session-context.js";import{isAlreadyClaimedError}from"./lifecycle/claim.js";import{PM_READ_OUTPUT_DIMENSIONS,PM_READ_OUTPUT_OPTION_FLAGS,PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,PM_READ_OUTPUT_SURFACE_CONTRACTS,applyReadOutputDimensions,decodeReadOutputContinuationCursor,encodeReadOutputContinuationCursor,isReadOutputBudgetExceeded,resolveReadOutputDimensions,resolveReadOutputEncoding,resolveReadOutputSurface,validateReadOutputOptions}from"./read-output-contracts.js";import{applyReadOutputSessionReferences,attachReadOutputSessionReceipt,parseReadOutputSession,readOutputSessionRemainingTokens}from"./read-output-session.js";export{BASELINE_ITEM_FORMAT_VERSION,BUILTIN_ITEM_TYPE_VALUES,CONFIDENCE_TEXT_VALUES,CURRENT_ITEM_FORMAT_VERSION,DEPENDENCY_KIND_VALUES,EXIT_CODE,ISSUE_SEVERITY_VALUES,ITEM_TYPE_VALUES,PM_CLI_EXPECTED_ERROR_NAME,PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,PM_READ_OUTPUT_DIMENSIONS,PM_READ_OUTPUT_OPTION_FLAGS,PM_READ_OUTPUT_SURFACE_CONTRACTS,PmCliError,PmClient,RISK_VALUES,STATUS_VALUES,aggregate,append,applyReadOutputDimensions,applyReadOutputSessionReferences,attachReadOutputSessionReceipt,canonicalDocument,claim,claimNext,classifyItemFormatVersion,close,comments,context,copy,create,createPmCliExpectedError,decodeReadOutputContinuationCursor,deleteItem,deps,docs,effectiveItemFormatVersion,emptyImportedDocument,encodeReadOutputContinuationCursor,files,filesDiscover,focus,get,graph,isAlreadyClaimedError,isItemAlreadyExistsError,isPmCliExpectedError,isPmTokenBudgetRecovery,isReadOutputBudgetExceeded,learnings,list,listAllComplete,next,normalizeItemFormatVersion,normalizeItemId,normalizeStatusInput,notes,nowIso,parseReadOutputSession,readOutputSessionRemainingTokens,release,reopen,resolveReadOutputDimensions,resolveReadOutputEncoding,resolveReadOutputSurface,restore,runAction,search,serializeItemDocument,update,updateLinkedTest,validateReadOutputOptions};
|
|
2
2
|
//# sourceMappingURL=core.js.map
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module sdk/dependencies/context-budget-recovery
|
|
3
|
+
* Finds verified retry budgets while bounding query work and distinguishing proved minima from partial searches.
|
|
4
|
+
*/
|
|
5
|
+
import type { PmTokenBudgetRecovery } from "../../core/shared/errors.js";
|
|
6
|
+
/** A real packer probe distinguishes its own floor from an independent output constraint. */
|
|
7
|
+
export type ContextBudgetProbe = "fits" | "native_floor" | "output_constraints";
|
|
8
|
+
/** Inputs derived from one immutable relationship assembly and preserved retry options. */
|
|
9
|
+
interface ContextBudgetRecoveryInput {
|
|
10
|
+
/** Failed query's requested token ceiling. */
|
|
11
|
+
requested:number;
|
|
12
|
+
/** Initial upper candidate derived from the kernel's canonical default. */
|
|
13
|
+
initialBudget:number;
|
|
14
|
+
/** Conservative graph and text-size work estimate for each packer evaluation. */
|
|
15
|
+
workUnits:number;
|
|
16
|
+
/** Evaluate the real preserved query at one positive integer budget. */
|
|
17
|
+
probe:(tokens:number) => ContextBudgetProbe;
|
|
18
|
+
}
|
|
19
|
+
/** Establish a working retry and prove a global minimum only after exhaustive lower-budget verification. */
|
|
20
|
+
export declare function findContextBudgetRecovery(input:ContextBudgetRecoveryInput):PmTokenBudgetRecovery;
|
|
21
|
+
export {};
|
|
@@ -0,0 +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]="8a0c0e0d-7d3b-55c6-984b-b6570362cf78")}catch{}})();function unavailable(requested,reason){return{requested_tokens:requested,feasible_tokens:null,minimum_feasible_tokens:null,minimum_status:"unavailable",basis:"canonical_retry",reason}}function nativeUpperBound(input,probe){let upper=Math.min(Number.MAX_SAFE_INTEGER,Math.max(input.initialBudget,input.requested+1));for(let attempt=0;attempt<16;attempt+=1){if(probe(upper)!=="native_floor")return upper;if(upper===Number.MAX_SAFE_INTEGER)return;upper=Math.min(Number.MAX_SAFE_INTEGER,upper*2)}}function findContextBudgetRecovery(input){if(input.workUnits>1e6)return unavailable(input.requested,"query_cost_limit");const cache=new Map;let feasible;const probe=tokens=>{let outcome=cache.get(tokens);return outcome===void 0&&(outcome=input.probe(tokens),cache.set(tokens,outcome)),outcome==="fits"&&(feasible=Math.min(feasible??tokens,tokens)),outcome},upper=nativeUpperBound(input,probe);if(upper===void 0)return unavailable(input.requested,"search_limit");let left=0,right=upper;for(let step=0;step<24&&right-left>1;step+=1){const middle=left+Math.floor((right-left)/2);probe(middle)==="native_floor"?left=middle:right=middle}const verificationLimit=Math.min(feasible??upper,4096,Math.floor(1e5/Math.max(1,input.workUnits)));for(let tokens=1;tokens<=verificationLimit;tokens+=1)if(probe(tokens)==="fits")return{requested_tokens:input.requested,feasible_tokens:tokens,minimum_feasible_tokens:tokens,minimum_status:"exact",basis:"canonical_retry"};return feasible===void 0?unavailable(input.requested,"output_constraints"):{requested_tokens:input.requested,feasible_tokens:feasible,minimum_feasible_tokens:null,minimum_status:"feasible_only",basis:"canonical_retry"}}export{findContextBudgetRecovery};
|
|
2
|
+
//# sourceMappingURL=context-budget-recovery.js.map
|
package/dist/sdk/dependencies.js
CHANGED
|
@@ -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]="620bf4e4-e6d1-5520-89e4-0859f57c7afe")}catch{}})();import{assertInitializedTracker}from"./environment/tracker-preflight.js";import{getActiveExtensionRegistrations}from"../core/extensions/index.js";import{resolveItemTypeRegistry}from"../core/item/type-registry.js";import{isTerminalStatus}from"../core/item/status.js";import{resolveRuntimeStatusRegistry}from"../core/schema/runtime-schema.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{formatBuiltInOutput}from"../core/output/output.js";import{listAllItemMetadataLight,locateItem,readLocatedItem}from"../core/store/item-store.js";import{resolvePmRoot}from"../core/store/paths.js";import{readSettings}from"../core/store/settings.js";import{estimatePmOutputTokens}from"./cli-contracts/agent-output-contracts.js";import{assertProjectionModeChoice,attachOutputOmissionReceipt}from"./output-projection.js";import{assembleWorkspaceRelationshipGraph,collectDanglingDependencyReferences,resolveWorkspaceRelationshipKindRegistry}from"./graph/assembly.js";import{computeWorkspaceGraphFingerprint,workspaceGraphCache}from"./graph/cache.js";import{buildRelationshipContext}from"./relationship-context.js";import{createRelationshipKindRegistry}from"./relationships.js";const DEPS_FORMAT_VALUES=["tree","graph","context"],DEPS_COLLAPSE_VALUES=["none","repeated"],DEPS_DIRECTION_VALUES=["outgoing","incoming","both"],DEFAULT_DEPS_TREE_MAX_DEPTH=32,DEFAULT_DEPS_TREE_NODE_LIMIT=200,DEFAULT_DEPS_TREE_EDGE_LIMIT=400,DEFAULT_DEPS_TREE_TOKEN_BUDGET=16e3;function parseFormat(raw){const candidate=raw?.trim().toLowerCase()??"tree";if(DEPS_FORMAT_VALUES.includes(candidate))return candidate;throw new PmCliError(`Invalid --format value "${raw}". Use "tree", "graph", or "context".`,EXIT_CODE.USAGE)}function parsePositiveInteger(raw,flag){if(raw===void 0)return;const value=typeof raw=="number"?raw:Number(raw.trim());if(!Number.isInteger(value)||value<1)throw new PmCliError(`Invalid --${flag} value "${raw}". Use a positive integer.`,EXIT_CODE.USAGE);return value}function parseMaxDepth(raw){if(raw===void 0)return;const normalized=typeof raw=="number"?raw:Number(raw.trim());if(!Number.isInteger(normalized)||normalized<0)throw new PmCliError(`Invalid --max-depth value "${raw}". Use a non-negative integer.`,EXIT_CODE.USAGE);return normalized}function parseCollapse(raw){const candidate=raw?.trim().toLowerCase()??"none";if(DEPS_COLLAPSE_VALUES.includes(candidate))return candidate;throw new PmCliError(`Invalid --collapse value "${raw}". Use "none" or "repeated".`,EXIT_CODE.USAGE)}function parseDirection(raw){const candidate=raw?.trim().toLowerCase()??"both";if(DEPS_DIRECTION_VALUES.includes(candidate))return candidate;throw new PmCliError(`Invalid --direction value "${raw}". Use "outgoing", "incoming", or "both".`,EXIT_CODE.USAGE)}function parseKinds(raw,registry=createRelationshipKindRegistry()){if(raw===void 0)return;const values=(Array.isArray(raw)?raw:[raw]).flatMap(value=>value.split(",")).map(value=>value.trim()).filter(value=>value.length>0);if(values.length===0)return;const kinds=new Set;for(const value of values){const definition=registry.resolve(value);if(!definition){const known=registry.list().map(entry=>entry.kind).join(", ");throw new PmCliError(`Invalid --kind value "${value}". Registered kinds: ${known}.`,EXIT_CODE.USAGE)}kinds.add(definition.kind)}return[...kinds].sort()}function normalizeDependencies(dependencies){if(!dependencies||dependencies.length===0)return[];const sorted=dependencies.map(({id,kind})=>({id:id.trim(),kind:kind.trim().toLowerCase()})).sort((left,right)=>{const byKind=left.kind.localeCompare(right.kind);return byKind!==0?byKind:left.id.localeCompare(right.id)}),deduped=new Map;for(const dependency of sorted){const key=`${dependency.kind.toLowerCase()}::${dependency.id.toLowerCase()}`;deduped.has(key)||deduped.set(key,{id:dependency.id,kind:dependency.kind})}return[...deduped.values()]}function toIndexedItem(item){return{id:item.id,title:item.title,type:item.type,status:item.status,dependencies:normalizeDependencies(item.dependencies)}}function estimateTreeNodeTokens(node){return estimatePmOutputTokens(new TextEncoder().encode(JSON.stringify({...node,dependencies:void 0})).byteLength)}function appendTreeDependencies(baseNode,item,index,nextLineage,maxDepth,collapse,expanded,budget,depth){for(const dependency of item.dependencies){const edgeTokens=Math.max(1,Math.ceil(JSON.stringify({from:baseNode.id,to:dependency.id,kind:dependency.kind}).length/3));if(budget.nodes>=budget.nodeLimit){baseNode.truncated=!0,budget.reasons.add("node_limit");break}if(budget.edges>=budget.edgeLimit){baseNode.truncated=!0,budget.reasons.add("edge_limit");break}if(budget.estimatedTokens+edgeTokens>=budget.tokenBudget){baseNode.truncated=!0,budget.reasons.add("token_budget");break}budget.edges+=1,budget.estimatedTokens+=edgeTokens,baseNode.dependencies.push(toTreeNode(dependency.id,index,nextLineage,maxDepth,collapse,expanded,budget,depth+1,dependency.kind))}}function shouldStopTreeNodeExpansion(node,item,lookupId,maxDepth,collapse,expanded,budget,depth){return budget.estimatedTokens>=budget.tokenBudget&&item?.dependencies.length?(node.truncated=!0,budget.reasons.add("token_budget"),!0):!item||node.cycle?!0:maxDepth!==void 0&&depth>=maxDepth?(item.dependencies.length>0&&(node.truncated=!0,budget.reasons.add("max_depth")),!0):collapse==="repeated"&&expanded.has(lookupId)?(node.collapsed=!0,!0):!1}function toTreeNode(id,index,lineage,maxDepth,collapse,expanded,budget,depth=0,via){const lookupId=id.trim().toLowerCase(),item=index.get(lookupId),baseNode={id:item?.id??id,title:item?.title,type:item?.type,status:item?.status,via,missing:!item,cycle:lineage.has(lookupId),dependencies:[]};if(budget.nodes+=1,budget.estimatedTokens+=estimateTreeNodeTokens(baseNode),shouldStopTreeNodeExpansion(baseNode,item,lookupId,maxDepth,collapse,expanded,budget,depth))return baseNode;collapse==="repeated"&&expanded.add(lookupId);const nextLineage=new Set(lineage);return nextLineage.add(lookupId),appendTreeDependencies(baseNode,item,index,nextLineage,maxDepth,collapse,expanded,budget,depth),baseNode}function mergeGraphNode(existing,candidate){return!existing||existing.missing&&!candidate.missing?candidate:{...existing,title:existing.title??candidate.title,type:existing.type??candidate.type,status:existing.status??candidate.status}}function toGraph(root){const nodesById=new Map,edgesByKey=new Map,pending=[root];for(;pending.length>0;){const node=pending.pop();nodesById.set(node.id,mergeGraphNode(nodesById.get(node.id),{id:node.id,title:node.title,type:node.type,status:node.status,missing:node.missing}));for(const child of node.dependencies){nodesById.set(child.id,mergeGraphNode(nodesById.get(child.id),{id:child.id,title:child.title,type:child.type,status:child.status,missing:child.missing}));const relationKind=child.via??"related",edgeKey=`${node.id}::${child.id}::${relationKind}`;edgesByKey.has(edgeKey)||edgesByKey.set(edgeKey,{from:node.id,to:child.id,kind:relationKind}),child.cycle||pending.push(child)}}const nodes=[...nodesById.values()].sort((left,right)=>left.id.localeCompare(right.id)),edges=[...edgesByKey.values()].sort((left,right)=>{const byFrom=left.from.localeCompare(right.from);if(byFrom!==0)return byFrom;const byTo=left.to.localeCompare(right.to);return byTo!==0?byTo:left.kind.localeCompare(right.kind)}),missingIds=nodes.filter(node=>node.missing).map(node=>node.id);return{root_id:root.id,nodes,edges,missing_ids:missingIds}}function countDependencyGraph(rootId,index,maxDepth){const nodeIds=new Set,edgeKeys=new Set,missingIds=new Set,expanded=new Set,pending=[{id:rootId,depth:0}];let pendingIndex=0;for(;pendingIndex<pending.length;){const current=pending[pendingIndex++],lookupId=current.id.trim().toLowerCase();nodeIds.add(lookupId);const item=index.get(lookupId);if(!item){missingIds.add(lookupId);continue}if(!(maxDepth!==void 0&¤t.depth>=maxDepth)&&!expanded.has(lookupId)){expanded.add(lookupId);for(const dependency of item.dependencies)edgeKeys.add(`${lookupId}::${dependency.id.trim().toLowerCase()}::${dependency.kind}`),pending.push({id:dependency.id,depth:current.depth+1})}}return{node_count:nodeIds.size,edge_count:edgeKeys.size,edge_basis:"deduplicated_directed",missing_count:missingIds.size}}function parseDepsContextOptions(options,registry=createRelationshipKindRegistry()){const maxDepth=parseMaxDepth(options.maxDepth),nodeLimit=parsePositiveInteger(options.nodeLimit,"node-limit"),edgeLimit=parsePositiveInteger(options.edgeLimit,"edge-limit"),tokenBudget=parsePositiveInteger(options.tokenBudget,"token-budget"),kinds=parseKinds(options.kind,registry);return{direction:parseDirection(options.direction),...kinds===void 0?{}:{kinds},...maxDepth===void 0?{}:{maxDepth},...nodeLimit===void 0?{}:{nodeLimit},...edgeLimit===void 0?{}:{edgeLimit},...tokenBudget===void 0?{}:{tokenBudget},...options.cursor?.trim()?{cursor:options.cursor.trim()}:{}}}function buildContextFromAssembly(assembly,rootId,options,rootEvidence){return buildRelationshipContext(assembly.graph,rootId,assembly.details.map(detail=>detail.id===rootId&&rootEvidence.length>0?{...detail,evidence:rootEvidence}:detail),options)}function buildDepsRelationshipContext(rootId,items,options,rootEvidence=[]){const assembly=assembleWorkspaceRelationshipGraph(items);return buildContextFromAssembly(assembly,rootId,parseDepsContextOptions(options,assembly.graph.registry()),rootEvidence)}function appendEvidencePointers(evidence,label,values,limit){for(const value of values.slice(0,limit)){const trimmed=value?.trim();trimmed&&evidence.push(`${label}:${trimmed}`)}}async function collectRootEvidence(pmRoot,id,settings,typeToFolder){const located=await locateItem(pmRoot,id,settings.id_prefix,settings.item_format,typeToFolder);if(!located)return[];const{document}=await readLocatedItem(located,{schema:settings.schema}),metadata=document.metadata,files=metadata.files??[],tests=metadata.tests??[],docs=metadata.docs??[],counts=[["files",files.length],["tests",tests.length],["docs",docs.length],["comments",(metadata.comments??[]).length],["notes",(metadata.notes??[]).length],["learnings",(metadata.learnings??[]).length]];if(counts.every(([,count])=>count===0))return[];const evidence=[`linked:${counts.map(([key,count])=>`${key}=${count}`).join(",")}`];return appendEvidencePointers(evidence,"file",files.map(file=>file.path),3),appendEvidencePointers(evidence,"test",tests.map(test=>test.command??test.path),2),appendEvidencePointers(evidence,"doc",docs.map(doc=>doc.path),2),evidence}function createContextDepsResult(params){const{canonicalId,context,missingCount,missingReferences,referenceLimit,summaryOnly}=params;return{id:canonicalId,format:"context",node_count:context.nodes.length+1,edge_count:context.edges.length,edge_basis:"deduplicated_directed",missing_count:missingCount,missing_scope:"traversal",missing_reference_count:missingReferences.length,...summaryOnly?{}:{missing_references:missingReferences.slice(0,referenceLimit),context}}}function includesContextMissingReference(params){const{row,missingReachableSet,packetIds,filteredKinds,registry}=params;if(row.no_active_blocker_sentinel||!missingReachableSet.has(row.target_id.trim().toLowerCase())||!packetIds.has(row.holder_id))return!1;if(filteredKinds===void 0)return!0;const definition=registry.resolve(row.kind);return definition!==void 0&&(filteredKinds.has(definition.kind)||definition.inverse!==void 0&&filteredKinds.has(definition.inverse))}function settleRenderedTokenCount(result,outputFormat,assign){let embeddedTokens;for(;;){const measuredTokens=estimatePmOutputTokens(new TextEncoder().encode(formatBuiltInOutput(attachOutputOmissionReceipt("deps",result),outputFormat)).byteLength);if(measuredTokens===embeddedTokens)return measuredTokens;assign(measuredTokens),embeddedTokens=measuredTokens}}function isContextBudgetFloorError(error){return error instanceof TypeError&&error.message.startsWith("Relationship context tokenBudget cannot fit ")}function buildContextAtRenderedBudget(params){try{return buildContextFromAssembly(params.assembly,params.canonicalId,{...params.contextOptions,...params.internalTokenBudget===void 0?{}:{tokenBudget:params.internalTokenBudget}},params.rootEvidence)}catch(error){if(params.smallestResult!==void 0&&isContextBudgetFloorError(error))return params.smallestResult;throw error}}function enforceContextRenderedTokenBudget(params){const{assembly,canonicalId,contextOptions,rootEvidence,summaryOnly,outputFormat,missingCount,missingReferences}=params;let emittedReferenceLimit=contextOptions.edgeLimit??40,internalTokenBudget=contextOptions.tokenBudget,requestedTokenBudget,smallestResult;for(;;){const contextOrFloor=buildContextAtRenderedBudget({assembly,canonicalId,contextOptions,internalTokenBudget,rootEvidence,smallestResult});if("format"in contextOrFloor)return contextOrFloor;const context=contextOrFloor;requestedTokenBudget??=context.meta.tokenBudget,internalTokenBudget??=requestedTokenBudget;const result=createContextDepsResult({canonicalId,context,missingCount,missingReferences,referenceLimit:emittedReferenceLimit,summaryOnly});if(smallestResult=result,summaryOnly||(context.meta.tokenBudget=requestedTokenBudget,context.meta.usedTokens=settleRenderedTokenCount(attachDepsProjection(result,!1),outputFormat,tokens=>{context.meta.usedTokens=tokens}),context.meta.usedTokens<=requestedTokenBudget))return result;if(emittedReferenceLimit>0){emittedReferenceLimit-=1;continue}const currentInternalBudget=internalTokenBudget,scaledInternalBudget=currentInternalBudget*requestedTokenBudget/context.meta.usedTokens;internalTokenBudget=Math.min(currentInternalBudget-1,Math.max(1,Math.floor(scaledInternalBudget*.9)))}}function buildContextDepsResult(params){const{assembly,canonicalId,options,rootEvidence,summaryOnly,outputFormat}=params,contextOptions=parseDepsContextOptions(options,assembly.graph.registry()),reachable=assembly.graph.closure(canonicalId,{direction:contextOptions.direction,...contextOptions.kinds===void 0?{}:{kinds:contextOptions.kinds},maxDepth:contextOptions.maxDepth??3}),missingReachable=reachable.value.filter(nodeId=>assembly.missingIdSet.has(nodeId.toLowerCase())),missingReachableSet=new Set(missingReachable.map(nodeId=>nodeId.toLowerCase())),relationshipRegistry=assembly.graph.registry(),filteredKinds=contextOptions.kinds?new Set(contextOptions.kinds.map(kind=>relationshipRegistry.require(kind).kind)):void 0,packetIds=new Set([canonicalId,...reachable.value]),missingReferences=[...assembly.dangling.active,...assembly.dangling.legacy_terminal].filter(row=>includesContextMissingReference({row,missingReachableSet,packetIds,filteredKinds,registry:relationshipRegistry}));return enforceContextRenderedTokenBudget({assembly,canonicalId,contextOptions,rootEvidence,summaryOnly,outputFormat,missingCount:missingReachable.length,missingReferences})}function trimDeepestDependency(tree){const pending=[tree];let parentToTrim;for(;pending.length>0;){const current=pending.pop();current.dependencies.length>0&&(parentToTrim=current,pending.push(...current.dependencies))}return parentToTrim?(parentToTrim.dependencies.pop(),parentToTrim.truncated=!0,!0):!1}function buildTreeOrGraphDepsResult(id,format,options,index,maxDepth,collapse,outputFormat){const effectiveMaxDepth=maxDepth??DEFAULT_DEPS_TREE_MAX_DEPTH,nodeLimit=parsePositiveInteger(options.nodeLimit,"node-limit")??DEFAULT_DEPS_TREE_NODE_LIMIT,edgeLimit=parsePositiveInteger(options.edgeLimit,"edge-limit")??DEFAULT_DEPS_TREE_EDGE_LIMIT,tokenBudget=parsePositiveInteger(options.tokenBudget,"token-budget")??DEFAULT_DEPS_TREE_TOKEN_BUDGET,budget={nodeLimit,edgeLimit,tokenBudget,nodes:0,edges:0,estimatedTokens:0,reasons:new Set},tree=toTreeNode(id,index,new Set,effectiveMaxDepth,format==="graph"?"repeated":collapse,new Set,budget),totals=countDependencyGraph(id,index,void 0);let result;for(;;){const graph=toGraph(tree),truncation=budget.reasons.size===0?void 0:{reasons:[...budget.reasons].sort(),limits:{max_depth:effectiveMaxDepth,node_limit:nodeLimit,edge_limit:edgeLimit,token_budget:tokenBudget},estimated_tokens:0,total_node_count:totals.node_count,total_edge_count:totals.edge_count,omitted_node_count:Math.max(0,totals.node_count-graph.nodes.length),omitted_edge_count:Math.max(0,totals.edge_count-graph.edges.length)},baseResult={id,format,node_count:graph.nodes.length,edge_count:graph.edges.length,edge_basis:"deduplicated_directed",missing_count:graph.missing_ids.length,...truncation?{truncation}:{}};if(result=format==="tree"?{...baseResult,tree}:{...baseResult,graph},(result.truncation===void 0?estimatePmOutputTokens(new TextEncoder().encode(formatBuiltInOutput(attachOutputOmissionReceipt("deps",attachDepsProjection(result,!1)),outputFormat)).byteLength):settleRenderedTokenCount(attachDepsProjection(result,!1),outputFormat,tokens=>{result.truncation.estimated_tokens=tokens}))<=tokenBudget)return result;if(!trimDeepestDependency(tree))return budget.reasons.add("token_budget"),result;budget.reasons.add("token_budget")}}function attachDepsProjection(result,summaryOnly,legacyAliasCounts={}){const group={name:result.format==="tree"?"dependency_tree":result.format==="graph"?"dependency_graph":"relationship_context",restore_with:"--full"};return{...result,legacy_alias_counts:legacyAliasCounts,projection:{mode:summaryOnly?"summary":"full",declared_field_groups:[group],included_field_groups:summaryOnly?[]:[group.name]}}}async function runDeps(id,options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const format=parseFormat(options.format),maxDepth=parseMaxDepth(options.maxDepth),collapse=parseCollapse(options.collapse);assertProjectionModeChoice(options.summary===!0,options.full===!0,"--summary");const summaryOnly=options.summary===!0,settings=await readSettings(pmRoot),typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()),items=await listAllItemMetadataLight(pmRoot,settings.item_format,typeRegistry.type_to_folder,void 0,settings.schema),statusRegistry=resolveRuntimeStatusRegistry(settings.schema),index=new Map(items.map(item=>[item.id.trim().toLowerCase(),toIndexedItem(item)])),dangling=collectDanglingDependencyReferences(items,status=>isTerminalStatus(status,statusRegistry));for(const reference of[...dangling.active,...dangling.legacy_terminal]){const holder=index.get(reference.holder_id.trim().toLowerCase()),referenceKind=reference.kind.trim().toLowerCase();holder&&!holder.dependencies.some(dependency=>dependency.id.trim().toLowerCase()===reference.target_id.trim().toLowerCase()&&dependency.kind===referenceKind)&&holder.dependencies.push({id:reference.target_id,kind:referenceKind})}if(!index.has(id.trim().toLowerCase()))throw new PmCliError(`Item ${id} not found`,EXIT_CODE.NOT_FOUND);if(format==="context"){const canonicalId=index.get(id.trim().toLowerCase()).id,rootEvidence=summaryOnly?[]:await collectRootEvidence(pmRoot,canonicalId,settings,typeRegistry.type_to_folder),isTerminal=status=>isTerminalStatus(status,statusRegistry),relationshipRegistry=resolveWorkspaceRelationshipKindRegistry(),lookup=workspaceGraphCache().lookup(pmRoot,computeWorkspaceGraphFingerprint(items,isTerminal,relationshipRegistry),()=>assembleWorkspaceRelationshipGraph(items,isTerminal,relationshipRegistry));return attachDepsProjection(buildContextDepsResult({assembly:lookup.assembly,canonicalId,options,rootEvidence,summaryOnly,outputFormat:global2.json===!0?"json":"toon"}),summaryOnly,lookup.assembly.legacyAliasCounts)}return summaryOnly?attachDepsProjection({id,format,...countDependencyGraph(id,index,maxDepth)},!0,Object.fromEntries(Object.entries(assembleWorkspaceRelationshipGraph(items,status=>isTerminalStatus(status,statusRegistry)).legacyAliasCounts))):attachDepsProjection(buildTreeOrGraphDepsResult(id,format,options,index,maxDepth,collapse,global2.json===!0?"json":"toon"),!1,Object.fromEntries(Object.entries(assembleWorkspaceRelationshipGraph(items,status=>isTerminalStatus(status,statusRegistry)).legacyAliasCounts)))}export{DEPS_COLLAPSE_VALUES,DEPS_DIRECTION_VALUES,DEPS_FORMAT_VALUES,buildDepsRelationshipContext,parseDirection,parseKinds,parseMaxDepth,parsePositiveInteger,runDeps};
|
|
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]="e574946e-ad2d-5465-a021-205300ab3596")}catch{}})();import{assertInitializedTracker}from"./environment/tracker-preflight.js";import{getActiveCommandContext,getActiveExtensionRegistrations}from"../core/extensions/index.js";import{resolveItemTypeRegistry}from"../core/item/type-registry.js";import{isTerminalStatus}from"../core/item/status.js";import{resolveRuntimeStatusRegistry}from"../core/schema/runtime-schema.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{formatBuiltInOutput}from"../core/output/output.js";import{listAllItemMetadataLight,locateItem,readLocatedItem}from"../core/store/item-store.js";import{resolvePmRoot}from"../core/store/paths.js";import{readSettings}from"../core/store/settings.js";import{estimatePmOutputTokens}from"./cli-contracts/agent-output-contracts.js";import{renderPmCommand}from"./command-line.js";import{createPmCliExpectedError}from"./errors.js";import{isReadOutputBudgetExceeded,normalizeReadOutputIncludeModeOptions,PM_READ_OUTPUT_SURFACE_CONTRACTS}from"./read-output-contracts.js";import{READ_OUTPUT_INVOCATION_PROVENANCE}from"./read-output/provenance.js";import{attachReadOutputContracts}from"./context-intent-contracts.js";import{attachOutputTokenAccounting}from"./output-token-accounting.js";import{assertProjectionModeChoice}from"./output-projection.js";import{assembleWorkspaceRelationshipGraph,collectDanglingDependencyReferences,resolveWorkspaceRelationshipKindRegistry}from"./graph/assembly.js";import{computeWorkspaceGraphFingerprint,workspaceGraphCache}from"./graph/cache.js";import{buildRelationshipContext,DEFAULT_RELATIONSHIP_CONTEXT_TOKEN_BUDGET}from"./relationship-context.js";import{createRelationshipKindRegistry}from"./relationships.js";const DEPS_FORMAT_VALUES=["tree","graph","context"],DEPS_COLLAPSE_VALUES=["none","repeated"],DEPS_DIRECTION_VALUES=["outgoing","incoming","both"],DEFAULT_DEPS_TREE_MAX_DEPTH=32,DEFAULT_DEPS_TREE_NODE_LIMIT=200,DEFAULT_DEPS_TREE_EDGE_LIMIT=400,DEFAULT_DEPS_TREE_TOKEN_BUDGET=16e3;function parseFormat(raw){const candidate=raw?.trim().toLowerCase()??"tree";if(DEPS_FORMAT_VALUES.includes(candidate))return candidate;throw new PmCliError(`Invalid --format value "${raw}". Use "tree", "graph", or "context".`,EXIT_CODE.USAGE)}function parsePositiveInteger(raw,flag){if(raw===void 0)return;const value=typeof raw=="number"?raw:Number(raw.trim());if(!Number.isInteger(value)||value<1)throw new PmCliError(`Invalid --${flag} value "${raw}". Use a positive integer.`,EXIT_CODE.USAGE);return value}function parseMaxDepth(raw){if(raw===void 0)return;const normalized=typeof raw=="number"?raw:Number(raw.trim());if(!Number.isInteger(normalized)||normalized<0)throw new PmCliError(`Invalid --max-depth value "${raw}". Use a non-negative integer.`,EXIT_CODE.USAGE);return normalized}function parseCollapse(raw){const candidate=raw?.trim().toLowerCase()??"none";if(DEPS_COLLAPSE_VALUES.includes(candidate))return candidate;throw new PmCliError(`Invalid --collapse value "${raw}". Use "none" or "repeated".`,EXIT_CODE.USAGE)}function parseDirection(raw){const candidate=raw?.trim().toLowerCase()??"both";if(DEPS_DIRECTION_VALUES.includes(candidate))return candidate;throw new PmCliError(`Invalid --direction value "${raw}". Use "outgoing", "incoming", or "both".`,EXIT_CODE.USAGE)}function parseKinds(raw,registry=createRelationshipKindRegistry()){if(raw===void 0)return;const values=(Array.isArray(raw)?raw:[raw]).flatMap(value=>value.split(",")).map(value=>value.trim()).filter(value=>value.length>0);if(values.length===0)return;const kinds=new Set;for(const value of values){const definition=registry.resolve(value);if(!definition){const known=registry.list().map(entry=>entry.kind).join(", ");throw new PmCliError(`Invalid --kind value "${value}". Registered kinds: ${known}.`,EXIT_CODE.USAGE)}kinds.add(definition.kind)}return[...kinds].sort()}function normalizeDependencies(dependencies){if(!dependencies||dependencies.length===0)return[];const sorted=dependencies.map(({id,kind})=>({id:id.trim(),kind:kind.trim().toLowerCase()})).sort((left,right)=>{const byKind=left.kind.localeCompare(right.kind);return byKind!==0?byKind:left.id.localeCompare(right.id)}),deduped=new Map;for(const dependency of sorted){const key=`${dependency.kind.toLowerCase()}::${dependency.id.toLowerCase()}`;deduped.has(key)||deduped.set(key,{id:dependency.id,kind:dependency.kind})}return[...deduped.values()]}function toIndexedItem(item){return{id:item.id,title:item.title,type:item.type,status:item.status,dependencies:normalizeDependencies(item.dependencies)}}function estimateTreeNodeTokens(node){return estimatePmOutputTokens(new TextEncoder().encode(JSON.stringify({...node,dependencies:void 0})).byteLength)}function appendTreeDependencies(baseNode,item,index,nextLineage,maxDepth,collapse,expanded,budget,depth){for(const dependency of item.dependencies){const edgeTokens=Math.max(1,Math.ceil(JSON.stringify({from:baseNode.id,to:dependency.id,kind:dependency.kind}).length/3));if(budget.nodes>=budget.nodeLimit){baseNode.truncated=!0,budget.reasons.add("node_limit");break}if(budget.edges>=budget.edgeLimit){baseNode.truncated=!0,budget.reasons.add("edge_limit");break}if(budget.estimatedTokens+edgeTokens>=budget.tokenBudget){baseNode.truncated=!0,budget.reasons.add("token_budget");break}budget.edges+=1,budget.estimatedTokens+=edgeTokens,baseNode.dependencies.push(toTreeNode(dependency.id,index,nextLineage,maxDepth,collapse,expanded,budget,depth+1,dependency.kind))}}function shouldStopTreeNodeExpansion(node,item,lookupId,maxDepth,collapse,expanded,budget,depth){return budget.estimatedTokens>=budget.tokenBudget&&item?.dependencies.length?(node.truncated=!0,budget.reasons.add("token_budget"),!0):!item||node.cycle?!0:maxDepth!==void 0&&depth>=maxDepth?(item.dependencies.length>0&&(node.truncated=!0,budget.reasons.add("max_depth")),!0):collapse==="repeated"&&expanded.has(lookupId)?(node.collapsed=!0,!0):!1}function toTreeNode(id,index,lineage,maxDepth,collapse,expanded,budget,depth=0,via){const lookupId=id.trim().toLowerCase(),item=index.get(lookupId),baseNode={id:item?.id??id,title:item?.title,type:item?.type,status:item?.status,via,missing:!item,cycle:lineage.has(lookupId),dependencies:[]};if(budget.nodes+=1,budget.estimatedTokens+=estimateTreeNodeTokens(baseNode),shouldStopTreeNodeExpansion(baseNode,item,lookupId,maxDepth,collapse,expanded,budget,depth))return baseNode;collapse==="repeated"&&expanded.add(lookupId);const nextLineage=new Set(lineage);return nextLineage.add(lookupId),appendTreeDependencies(baseNode,item,index,nextLineage,maxDepth,collapse,expanded,budget,depth),baseNode}function mergeGraphNode(existing,candidate){return!existing||existing.missing&&!candidate.missing?candidate:{...existing,title:existing.title??candidate.title,type:existing.type??candidate.type,status:existing.status??candidate.status}}function toGraph(root){const nodesById=new Map,edgesByKey=new Map,pending=[root];for(;pending.length>0;){const node=pending.pop();nodesById.set(node.id,mergeGraphNode(nodesById.get(node.id),{id:node.id,title:node.title,type:node.type,status:node.status,missing:node.missing}));for(const child of node.dependencies){nodesById.set(child.id,mergeGraphNode(nodesById.get(child.id),{id:child.id,title:child.title,type:child.type,status:child.status,missing:child.missing}));const relationKind=child.via??"related",edgeKey=`${node.id}::${child.id}::${relationKind}`;edgesByKey.has(edgeKey)||edgesByKey.set(edgeKey,{from:node.id,to:child.id,kind:relationKind}),child.cycle||pending.push(child)}}const nodes=[...nodesById.values()].sort((left,right)=>left.id.localeCompare(right.id)),edges=[...edgesByKey.values()].sort((left,right)=>{const byFrom=left.from.localeCompare(right.from);if(byFrom!==0)return byFrom;const byTo=left.to.localeCompare(right.to);return byTo!==0?byTo:left.kind.localeCompare(right.kind)}),missingIds=nodes.filter(node=>node.missing).map(node=>node.id);return{root_id:root.id,nodes,edges,missing_ids:missingIds}}function countDependencyGraph(rootId,index,maxDepth){const nodeIds=new Set,edgeKeys=new Set,missingIds=new Set,expanded=new Set,pending=[{id:rootId,depth:0}];let pendingIndex=0;for(;pendingIndex<pending.length;){const current=pending[pendingIndex++],lookupId=current.id.trim().toLowerCase();nodeIds.add(lookupId);const item=index.get(lookupId);if(!item){missingIds.add(lookupId);continue}if(!(maxDepth!==void 0&¤t.depth>=maxDepth)&&!expanded.has(lookupId)){expanded.add(lookupId);for(const dependency of item.dependencies)edgeKeys.add(`${lookupId}::${dependency.id.trim().toLowerCase()}::${dependency.kind}`),pending.push({id:dependency.id,depth:current.depth+1})}}return{node_count:nodeIds.size,edge_count:edgeKeys.size,edge_basis:"deduplicated_directed",missing_count:missingIds.size}}function parseDepsContextOptions(options,registry=createRelationshipKindRegistry()){const maxDepth=parseMaxDepth(options.maxDepth),nodeLimit=parsePositiveInteger(options.nodeLimit,"node-limit"),edgeLimit=parsePositiveInteger(options.edgeLimit,"edge-limit"),tokenBudget=parsePositiveInteger(options.tokenBudget,"token-budget"),kinds=parseKinds(options.kind,registry);return{direction:parseDirection(options.direction),...kinds===void 0?{}:{kinds},...maxDepth===void 0?{}:{maxDepth},...nodeLimit===void 0?{}:{nodeLimit},...edgeLimit===void 0?{}:{edgeLimit},...tokenBudget===void 0?{}:{tokenBudget},...options.cursor?.trim()?{cursor:options.cursor.trim()}:{}}}function buildContextFromAssembly(assembly,rootId,options,rootEvidence){return buildRelationshipContext(assembly.graph,rootId,assembly.details.map(detail=>detail.id===rootId&&rootEvidence.length>0?{...detail,evidence:rootEvidence}:detail),options)}function buildDepsRelationshipContext(rootId,items,options,rootEvidence=[]){const assembly=assembleWorkspaceRelationshipGraph(items);return buildContextFromAssembly(assembly,rootId,parseDepsContextOptions(options,assembly.graph.registry()),rootEvidence)}function appendEvidencePointers(evidence,label,values,limit){for(const value of values.slice(0,limit)){const trimmed=value?.trim();trimmed&&evidence.push(`${label}:${trimmed}`)}}async function collectRootEvidence(pmRoot,id,settings,typeToFolder){const located=await locateItem(pmRoot,id,settings.id_prefix,settings.item_format,typeToFolder);if(!located)return[];const{document}=await readLocatedItem(located,{schema:settings.schema}),metadata=document.metadata,files=metadata.files??[],tests=metadata.tests??[],docs=metadata.docs??[],counts=[["files",files.length],["tests",tests.length],["docs",docs.length],["comments",(metadata.comments??[]).length],["notes",(metadata.notes??[]).length],["learnings",(metadata.learnings??[]).length]];if(counts.every(([,count])=>count===0))return[];const evidence=[`linked:${counts.map(([key,count])=>`${key}=${count}`).join(",")}`];return appendEvidencePointers(evidence,"file",files.map(file=>file.path),3),appendEvidencePointers(evidence,"test",tests.map(test=>test.command??test.path),2),appendEvidencePointers(evidence,"doc",docs.map(doc=>doc.path),2),evidence}function createContextDepsResult(params){const{canonicalId,context,missingCount,missingReferences,referenceLimit,summaryOnly}=params;return{id:canonicalId,format:"context",node_count:context.nodes.length+1,edge_count:context.edges.length,edge_basis:"deduplicated_directed",missing_count:missingCount,missing_scope:"traversal",missing_reference_count:missingReferences.length,...summaryOnly?{}:{missing_references:missingReferences.slice(0,referenceLimit),context}}}function includesContextMissingReference(params){const{row,missingReachableSet,packetIds,filteredKinds,registry}=params;if(row.no_active_blocker_sentinel||!missingReachableSet.has(row.target_id.trim().toLowerCase())||!packetIds.has(row.holder_id))return!1;if(filteredKinds===void 0)return!0;const definition=registry.resolve(row.kind);return definition!==void 0&&(filteredKinds.has(definition.kind)||definition.inverse!==void 0&&filteredKinds.has(definition.inverse))}function discloseDepsOutput(result,rendering){const activeCommand=getActiveCommandContext(),commandOptions=rendering.commandOptionsOverride??(activeCommand?.command==="deps"?activeCommand.options:rendering.commandOptions);return attachReadOutputContracts("deps",{...commandOptions,...rendering.global,resolvedOutputFormat:rendering.format},result)}function renderDepsOutput(result,rendering){const disclosed=discloseDepsOutput(result,rendering),render=value=>formatBuiltInOutput(value,rendering.format,rendering.global.lean===!0);return render(rendering.global.tokenAccounting===!0?attachOutputTokenAccounting(disclosed,render):disclosed)}function settleRenderedTokenCount(result,rendering,assign){let embeddedTokens;for(;;){const measuredTokens=estimatePmOutputTokens(new TextEncoder().encode(renderDepsOutput(result,rendering)).byteLength);if(measuredTokens===embeddedTokens)return measuredTokens;assign(measuredTokens),embeddedTokens=measuredTokens}}function isContextBudgetFloorError(error){return error instanceof TypeError&&error.message.startsWith("Relationship context tokenBudget cannot fit ")}function enforceContextRenderedTokenBudget(params){const{assembly,canonicalId,contextOptions,rootEvidence,summaryOnly,rendering,missingCount,missingReferences}=params,referenceLimit=contextOptions.edgeLimit??40;let emittedReferenceLimit=Math.min(referenceLimit,missingReferences.length),internalTokenBudget=contextOptions.tokenBudget,requestedTokenBudget;for(;;){const context=buildContextFromAssembly(assembly,canonicalId,{...contextOptions,...internalTokenBudget===void 0?{}:{tokenBudget:internalTokenBudget}},rootEvidence);requestedTokenBudget??=context.meta.tokenBudget,internalTokenBudget??=requestedTokenBudget;const result=createContextDepsResult({canonicalId,context,missingCount,missingReferences,referenceLimit:emittedReferenceLimit,summaryOnly});if(summaryOnly){if(estimatePmOutputTokens(new TextEncoder().encode(renderDepsOutput(attachDepsProjection(result,!0,rendering.legacyAliasCounts),rendering)).byteLength)>requestedTokenBudget)throw new TypeError("Relationship context tokenBudget cannot fit the rendered summary");return result}if(context.meta.tokenBudget=requestedTokenBudget,context.meta.usedTokens=settleRenderedTokenCount(attachDepsProjection(result,!1,rendering.legacyAliasCounts),rendering,tokens=>{context.meta.usedTokens=tokens}),context.meta.usedTokens<=requestedTokenBudget)return result;if(emittedReferenceLimit>0){emittedReferenceLimit-=1;continue}const currentInternalBudget=internalTokenBudget,scaledInternalBudget=currentInternalBudget*requestedTokenBudget/context.meta.usedTokens;internalTokenBudget=Math.min(currentInternalBudget-1,Math.max(1,Math.floor(scaledInternalBudget*.9)))}}function createContextRetryPlan(params,budget){const options=params.contextOptions,global2={...params.rendering.global,outputFormat:params.rendering.format},args=["--pm-path",params.pmRoot,"item","deps",params.canonicalId,"--format","context","--output-format",params.rendering.format,"--token-budget"],budgetIndex=args.length;args.push(String(budget));const provided=new Set(["--pm-path","--format","--output-format","--token-budget"]),commandOptions={format:"context",tokenBudget:budget,kind:options.kinds},values=[["--max-depth","maxDepth",options.maxDepth],["--node-limit","nodeLimit",options.nodeLimit],["--edge-limit","edgeLimit",options.edgeLimit],["--direction","direction",options.direction],["--cursor","cursor",options.cursor],["--output-include","outputInclude",global2.outputInclude],["--output-limit","outputLimit",global2.outputLimit],["--output-budget","outputBudget",global2.outputBudget],["--output-session","outputSession",global2.outputSession],["--output-cursor","outputCursor",global2.outputCursor]];for(const[flag,key,value]of values)value!==void 0&&(args.push(flag,String(value)),provided.add(flag),commandOptions[key]=value);for(const kind of options.kinds??[])args.push("--kind",kind),provided.add("--kind");const booleans=[["--summary","summary",params.summaryOnly],["--full","full",params.rendering.commandOptions.full],["--json","json",global2.json],["--lean","lean",global2.lean],["--output-row-contract","outputRowContract",global2.outputRowContract],["--token-accounting","tokenAccounting",global2.tokenAccounting],["--no-extensions","noExtensions",global2.noExtensions],["--no-pager","noPager",global2.noPager]];for(const[flag,key,enabled]of booleans)enabled===!0&&(args.push(flag),provided.add(flag),commandOptions[key]=!0);const contract=PM_READ_OUTPUT_SURFACE_CONTRACTS.find(candidate=>candidate.command==="deps");return Reflect.set(commandOptions,READ_OUTPUT_INVOCATION_PROVENANCE,{canonical_include_modes:[],cli_invocation_observed:!0,explicit_legacy_aliases:Object.values(contract.dimensions).flatMap(dimension=>dimension.legacy_aliases.flatMap(alias=>provided.has(alias.flag)?[alias.flag]:[]))}),normalizeReadOutputIncludeModeOptions("deps",commandOptions),assertProjectionModeChoice(commandOptions.summary===!0,commandOptions.full===!0,"--summary"),global2.outputInclude=commandOptions.outputInclude,{args,budgetIndex,summaryOnly:commandOptions.summary===!0,rendering:{...params.rendering,global:global2,commandOptionsOverride:commandOptions}}}function probeContextRetry(params,plan,budget){const rendering={...plan.rendering,commandOptionsOverride:{...plan.rendering.commandOptionsOverride,tokenBudget:budget}};let result;try{result=enforceContextRenderedTokenBudget({...params,contextOptions:{...params.contextOptions,tokenBudget:budget},summaryOnly:plan.summaryOnly,rootEvidence:plan.summaryOnly?[]:params.rootEvidence,rendering})}catch(error){if(!isContextBudgetFloorError(error))throw error;return"native_floor"}const disclosed=discloseDepsOutput(attachDepsProjection(result,plan.summaryOnly,rendering.legacyAliasCounts),rendering);return isReadOutputBudgetExceeded(disclosed)?"output_constraints":"fits"}async function createContextBudgetRefusal(params,cause){const requested=params.contextOptions.tokenBudget??DEFAULT_RELATIONSHIP_CONTEXT_TOKEN_BUDGET,plan=createContextRetryPlan(params,requested),workUnits=(plan.summaryOnly?1:1+Math.min(params.contextOptions.edgeLimit??40,params.missingReferences.length))*(params.assembly.details.reduce((sum,node)=>sum+node.id.length+node.title.length+node.status.length+(node.type?.length??0),params.assembly.graph.edges().length+params.missingReferences.length)+(plan.summaryOnly?[]:params.rootEvidence).reduce((sum,pointer)=>sum+pointer.length,0)),{findContextBudgetRecovery}=await import("./dependencies/context-budget-recovery.js"),bounds=findContextBudgetRecovery({requested,initialBudget:DEFAULT_RELATIONSHIP_CONTEXT_TOKEN_BUDGET,workUnits,probe:budget=>probeContextRetry(params,plan,budget)}),inspectionArgs=["--pm-path",params.pmRoot,"item","deps",params.canonicalId,"--format","tree","--summary"],inspection=renderPmCommand(inspectionArgs),retryArgs=bounds.feasible_tokens===null?inspectionArgs:[...plan.args];bounds.feasible_tokens!==null&&(retryArgs[plan.budgetIndex]=String(bounds.feasible_tokens));const retry=renderPmCommand(retryArgs);return createPmCliExpectedError("Relationship context tokenBudget cannot fit the required rendered packet",{exitCode:EXIT_CODE.USAGE,cause,context:{code:"invalid_argument_value",field:"tokenBudget",value:String(requested),required:bounds.feasible_tokens===null?"Inspect the compact summary and review the output constraints.":"Retry the preserved context query with --token-budget "+bounds.feasible_tokens+".",why:"Budget advice is verified against the current query. A minimum is reported only after every smaller positive budget is checked.",examples:[retry,inspection],nextSteps:[retry],recovery:{recovery_mode:"compact",suggested_flags:["--token-budget"],token_budget:bounds,suggested_retry_args:retryArgs,suggested_retry:retry,next_best_command:inspection,fallback_candidates:[{source:"relationship_summary",command:inspection,reason:"Inspect bounded counts separately from context rows."}]}}})}async function buildContextDepsResult(params){const{pmRoot,assembly,canonicalId,options,rootEvidence,summaryOnly,rendering}=params,contextOptions=parseDepsContextOptions(options,assembly.graph.registry()),reachable=assembly.graph.closure(canonicalId,{direction:contextOptions.direction,...contextOptions.kinds===void 0?{}:{kinds:contextOptions.kinds},maxDepth:contextOptions.maxDepth??3}),missingReachable=reachable.value.filter(nodeId=>assembly.missingIdSet.has(nodeId.toLowerCase())),missingReachableSet=new Set(missingReachable.map(nodeId=>nodeId.toLowerCase())),relationshipRegistry=assembly.graph.registry(),filteredKinds=contextOptions.kinds?new Set(contextOptions.kinds.map(kind=>relationshipRegistry.require(kind).kind)):void 0,packetIds=new Set([canonicalId,...reachable.value]),missingReferences=[...assembly.dangling.active,...assembly.dangling.legacy_terminal].filter(row=>includesContextMissingReference({row,missingReachableSet,packetIds,filteredKinds,registry:relationshipRegistry})),budgetParams={pmRoot,assembly,canonicalId,contextOptions,rootEvidence,summaryOnly,rendering,missingCount:missingReachable.length,missingReferences};try{return enforceContextRenderedTokenBudget(budgetParams)}catch(error){throw isContextBudgetFloorError(error)?await createContextBudgetRefusal(budgetParams,error):error}}function trimDeepestDependency(tree){const pending=[tree];let parentToTrim;for(;pending.length>0;){const current=pending.pop();current.dependencies.length>0&&(parentToTrim=current,pending.push(...current.dependencies))}return parentToTrim?(parentToTrim.dependencies.pop(),parentToTrim.truncated=!0,!0):!1}function buildTreeOrGraphDepsResult(id,format,options,index,maxDepth,collapse,rendering){const effectiveMaxDepth=maxDepth??DEFAULT_DEPS_TREE_MAX_DEPTH,nodeLimit=parsePositiveInteger(options.nodeLimit,"node-limit")??DEFAULT_DEPS_TREE_NODE_LIMIT,edgeLimit=parsePositiveInteger(options.edgeLimit,"edge-limit")??DEFAULT_DEPS_TREE_EDGE_LIMIT,tokenBudget=parsePositiveInteger(options.tokenBudget,"token-budget")??DEFAULT_DEPS_TREE_TOKEN_BUDGET,budget={nodeLimit,edgeLimit,tokenBudget,nodes:0,edges:0,estimatedTokens:0,reasons:new Set},tree=toTreeNode(id,index,new Set,effectiveMaxDepth,format==="graph"?"repeated":collapse,new Set,budget),totals=countDependencyGraph(id,index,void 0);let result;for(;;){const graph=toGraph(tree),truncation=budget.reasons.size===0?void 0:{reasons:[...budget.reasons].sort(),limits:{max_depth:effectiveMaxDepth,node_limit:nodeLimit,edge_limit:edgeLimit,token_budget:tokenBudget},estimated_tokens:0,total_node_count:totals.node_count,total_edge_count:totals.edge_count,omitted_node_count:Math.max(0,totals.node_count-graph.nodes.length),omitted_edge_count:Math.max(0,totals.edge_count-graph.edges.length)},baseResult={id,format,node_count:graph.nodes.length,edge_count:graph.edges.length,edge_basis:"deduplicated_directed",missing_count:graph.missing_ids.length,...truncation?{truncation}:{}};if(result=format==="tree"?{...baseResult,tree}:{...baseResult,graph},(result.truncation===void 0?estimatePmOutputTokens(new TextEncoder().encode(renderDepsOutput(attachDepsProjection(result,!1,rendering.legacyAliasCounts),rendering)).byteLength):settleRenderedTokenCount(attachDepsProjection(result,!1,rendering.legacyAliasCounts),rendering,tokens=>{result.truncation.estimated_tokens=tokens}))<=tokenBudget)return result;if(!trimDeepestDependency(tree))return budget.reasons.add("token_budget"),result;budget.reasons.add("token_budget")}}function attachDepsProjection(result,summaryOnly,legacyAliasCounts={}){const group={name:result.format==="tree"?"dependency_tree":result.format==="graph"?"dependency_graph":"relationship_context",restore_with:"--full"};return{...result,legacy_alias_counts:legacyAliasCounts,projection:{mode:summaryOnly?"summary":"full",declared_field_groups:[group],included_field_groups:summaryOnly?[]:[group.name]}}}async function runDeps(id,options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const format=parseFormat(options.format),maxDepth=parseMaxDepth(options.maxDepth),collapse=parseCollapse(options.collapse);assertProjectionModeChoice(options.summary===!0,options.full===!0,"--summary");const summaryOnly=options.summary===!0,settings=await readSettings(pmRoot),typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()),items=await listAllItemMetadataLight(pmRoot,settings.item_format,typeRegistry.type_to_folder,void 0,settings.schema),statusRegistry=resolveRuntimeStatusRegistry(settings.schema),index=new Map(items.map(item=>[item.id.trim().toLowerCase(),toIndexedItem(item)])),dangling=collectDanglingDependencyReferences(items,status=>isTerminalStatus(status,statusRegistry));for(const reference of[...dangling.active,...dangling.legacy_terminal]){const holder=index.get(reference.holder_id.trim().toLowerCase()),referenceKind=reference.kind.trim().toLowerCase();holder&&!holder.dependencies.some(dependency=>dependency.id.trim().toLowerCase()===reference.target_id.trim().toLowerCase()&&dependency.kind===referenceKind)&&holder.dependencies.push({id:reference.target_id,kind:referenceKind})}if(!index.has(id.trim().toLowerCase()))throw new PmCliError(`Item ${id} not found`,EXIT_CODE.NOT_FOUND);const outputFormat=global2.outputFormat??(global2.json===!0||global2.json===void 0&&global2.defaultOutputFormat==="json"?"json":"toon");if(format==="context"){const canonicalId=index.get(id.trim().toLowerCase()).id,rootEvidence=summaryOnly?[]:await collectRootEvidence(pmRoot,canonicalId,settings,typeRegistry.type_to_folder),isTerminal=status=>isTerminalStatus(status,statusRegistry),relationshipRegistry=resolveWorkspaceRelationshipKindRegistry(),lookup=workspaceGraphCache().lookup(pmRoot,computeWorkspaceGraphFingerprint(items,isTerminal,relationshipRegistry),()=>assembleWorkspaceRelationshipGraph(items,isTerminal,relationshipRegistry));return attachDepsProjection(await buildContextDepsResult({pmRoot,assembly:lookup.assembly,canonicalId,options,rootEvidence,summaryOnly,rendering:{format:outputFormat,global:global2,commandOptions:options,legacyAliasCounts:lookup.assembly.legacyAliasCounts}}),summaryOnly,lookup.assembly.legacyAliasCounts)}const legacyAliasCounts=Object.fromEntries(Object.entries(assembleWorkspaceRelationshipGraph(items,status=>isTerminalStatus(status,statusRegistry)).legacyAliasCounts));return summaryOnly?attachDepsProjection({id,format,...countDependencyGraph(id,index,maxDepth)},!0,legacyAliasCounts):attachDepsProjection(buildTreeOrGraphDepsResult(id,format,options,index,maxDepth,collapse,{format:outputFormat,global:global2,commandOptions:options,legacyAliasCounts}),!1,legacyAliasCounts)}export{DEPS_COLLAPSE_VALUES,DEPS_DIRECTION_VALUES,DEPS_FORMAT_VALUES,buildDepsRelationshipContext,parseDirection,parseKinds,parseMaxDepth,parsePositiveInteger,runDeps};
|
|
2
2
|
//# sourceMappingURL=dependencies.js.map
|
package/dist/sdk/errors.d.ts
CHANGED
|
@@ -4,7 +4,10 @@
|
|
|
4
4
|
* Defines public SDK APIs and package-author helpers for Errors.
|
|
5
5
|
*/
|
|
6
6
|
import { EXIT_CODE } from "../core/shared/constants.js";
|
|
7
|
-
import { type PmCliErrorContext } from "../core/shared/errors.js";
|
|
7
|
+
import { type PmCliErrorContext,type PmTokenBudgetRecovery } from "../core/shared/errors.js";
|
|
8
|
+
export type { PmTokenBudgetRecovery } from "../core/shared/errors.js";
|
|
9
|
+
/** Validate package-carried budget advice without trusting class identity or extra fields. */
|
|
10
|
+
export declare function isPmTokenBudgetRecovery(value:unknown):value is PmTokenBudgetRecovery;
|
|
8
11
|
/**
|
|
9
12
|
* The `Error.name` value carried by every {@link PmCliExpectedError}. The CLI's
|
|
10
13
|
* top-level handler and the Sentry crash filter recognise expected errors by
|
package/dist/sdk/errors.js
CHANGED
|
@@ -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]="cf5a7b37-5b40-52b4-a19c-18b08de649c4")}catch{}})();import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";function isPositiveSafeTokenCount(value){return typeof value=="number"&&Number.isSafeInteger(value)&&value>0}function isPmTokenBudgetRecovery(value){if(typeof value!="object"||value===null||Array.isArray(value))return!1;const candidate=value;if(!isPositiveSafeTokenCount(candidate.requested_tokens)||candidate.basis!=="canonical_retry")return!1;switch(candidate.minimum_status){case"exact":return isPositiveSafeTokenCount(candidate.minimum_feasible_tokens)&&candidate.feasible_tokens===candidate.minimum_feasible_tokens&&candidate.reason===void 0;case"feasible_only":return candidate.minimum_feasible_tokens===null&&isPositiveSafeTokenCount(candidate.feasible_tokens)&&candidate.reason===void 0;case"unavailable":return candidate.minimum_feasible_tokens===null&&candidate.feasible_tokens===null&&["query_cost_limit","search_limit","output_constraints"].includes(candidate.reason);default:return!1}}const PM_CLI_EXPECTED_ERROR_NAME="PmCliError";function isItemAlreadyExistsError(error){if(!isPmCliExpectedError(error)||error.code!=="item_already_exists"||error.exitCode!==EXIT_CODE.CONFLICT)return!1;const context=error.context;return typeof context=="object"&&context!==null&&context.code==="item_already_exists"&&typeof context.id=="string"&&context.id.trim().length>0&&typeof context.path=="string"&&context.path.trim().length>0}function normalizeExpectedErrorExitCode(value){if(!Number.isFinite(value))throw new TypeError("createPmCliExpectedError options.exitCode must be a finite number");const normalized=Math.trunc(value);if(normalized<=EXIT_CODE.SUCCESS)throw new TypeError("createPmCliExpectedError options.exitCode must be a positive exit code");return normalized}function createPmCliExpectedError(message,options={}){if(typeof message!="string"||message.trim().length===0)throw new TypeError("createPmCliExpectedError message must be a non-empty string");const error=new PmCliError(message,normalizeExpectedErrorExitCode(options.exitCode??EXIT_CODE.USAGE),options.context??{});return"cause"in options&&Object.defineProperty(error,"cause",{value:options.cause,enumerable:!1,configurable:!0,writable:!0}),error}function isPmCliExpectedError(error){if(!(error instanceof Error)||error.name!==PM_CLI_EXPECTED_ERROR_NAME)return!1;const candidate=error;return typeof candidate.exitCode=="number"&&Number.isFinite(candidate.exitCode)}export{PM_CLI_EXPECTED_ERROR_NAME,createPmCliExpectedError,isItemAlreadyExistsError,isPmCliExpectedError,isPmTokenBudgetRecovery};
|
|
2
2
|
//# sourceMappingURL=errors.js.map
|