@unbrained/pm-cli 2026.11.10 → 2026.11.12
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/.agents/skills/pm-test-audit/SKILL.md +2 -1
- package/.agents/skills/pm-user/references/ECOSYSTEM_PLANNING.md +2 -1
- package/.claude-plugin/marketplace.json +1 -1
- package/AGENTS.md +2 -2
- package/CHANGELOG.md +31 -0
- package/CONTRIBUTING.md +1 -1
- package/README.md +1 -1
- package/dist/cli/commander-usage.js +2 -2
- package/dist/cli/error-guidance.js +3 -3
- package/dist/cli/help-json-payload.js +1 -1
- package/dist/cli/main.js +4 -4
- package/dist/cli/register-mutation.js +2 -2
- package/dist/cli/register-operations.js +1 -1
- package/dist/cli/runtime/refusal-credential-redaction.js +2 -0
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/{chunk-BSJSGDA3.js → chunk-2DUUL53Z.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-YSWD2NXB.js → chunk-2K6GJUW7.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-TBBWPEF5.js → chunk-3DWEBVIK.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-L4WWG2H6.js → chunk-5NGGI7JC.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-U7LILCUN.js → chunk-5NY6EQSX.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-X7NM5HVQ.js → chunk-6ESY4Y2B.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-CZETQYKO.js → chunk-A7L5IEYV.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-5CAMQHEW.js → chunk-EALO2FPM.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-7NAAW5EX.js → chunk-FJNHTBJ2.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-FOT5K5OM.js +124 -0
- package/dist/cli-bundle/chunks/{chunk-F7P2NZEG.js → chunk-GDS4DC5A.js} +47 -43
- package/dist/cli-bundle/chunks/{chunk-F6FBGLR7.js → chunk-GLPUIQDB.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-4FLAKTZW.js → chunk-KJL42AN5.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-FYD6LSJA.js → chunk-L3SA3354.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-MR3CRLA7.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-NZAFLDSH.js → chunk-OBTU2BHJ.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-4AASUCHO.js → chunk-OFIXSWJS.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-PS2YAPXC.js +9 -0
- package/dist/cli-bundle/chunks/{chunk-WNEUWDUE.js → chunk-PZI6CR24.js} +46 -46
- package/dist/cli-bundle/chunks/{chunk-NNE63MSM.js → chunk-T4UC3ZKL.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-EHDGHFMJ.js → chunk-U7MZIX3D.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-UTNPDAID.js +31 -0
- package/dist/cli-bundle/chunks/{chunk-OJ2KEDUX.js → chunk-UY7Z3ZHQ.js} +2 -2
- package/dist/cli-bundle/chunks/{item-revision-M7KXLQXF.js → item-revision-SYJT6TVZ.js} +2 -2
- package/dist/cli-bundle/chunks/item-transaction-YXZ27UC6.js +2 -0
- package/dist/cli-bundle/chunks/{mutation-admission-374UR7NI.js → mutation-admission-T57TAVWI.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-GSB7PP5P.js → register-list-query-5XZXTPNG.js} +2 -2
- package/dist/cli-bundle/chunks/register-mutation-V6WJFL77.js +20 -0
- package/dist/cli-bundle/chunks/register-operations-5RAWXY2F.js +2 -0
- package/dist/cli-bundle/chunks/{register-setup-QDZ2Y3CI.js → register-setup-HCKCSQWQ.js} +2 -2
- package/dist/cli-bundle/chunks/{stage-67WGPKPH.js → stage-VIDXGF3T.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-PAGW6A2X.js → chunk-3FN4ON2Z.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-5OCUNAQN.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-AIYJHVKV.js +44 -0
- package/dist/cli-bundle/focused-chunks/{chunk-QHGGO7SY.js → chunk-AXPRCCYM.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-BB2GMKRB.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-QCHCEFTO.js → chunk-BHYGUVAU.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-GAXO2UQX.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-3K2MYE7R.js → chunk-GB2N4OM7.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-HTMQDNVC.js → chunk-GBW2EAAG.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-ZBOCYFBE.js → chunk-HIKZYZ26.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-IPIFI4NT.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-KN7RBRRH.js +26 -0
- package/dist/cli-bundle/focused-chunks/{chunk-3DWNH72D.js → chunk-LAIN47EJ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-2SQUWQP3.js → chunk-MK7UQEE5.js} +18 -18
- package/dist/cli-bundle/focused-chunks/{chunk-LY3JXL25.js → chunk-NP5C2TQM.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-RFMKS7VD.js → chunk-NSOXVVQX.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-WJHDUON5.js → chunk-NY65XTX7.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-67M7E2Z3.js → chunk-P6KYUJD4.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-RXY6BFRW.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-2Y4H4LIX.js → chunk-SPAEZKVA.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-TZO6L523.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-BE2GK2G7.js → chunk-VUNX6NBR.js} +53 -53
- package/dist/cli-bundle/focused-chunks/{item-revision-XC4ZJ7MY.js → item-revision-PWJNBW3F.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{item-transaction-CVGK4RJP.js → item-transaction-T6HXC3NS.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{mutation-admission-N27D5H64.js → mutation-admission-CLPOLSXZ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{stage-KPK2UHVO.js → stage-EKYWEU2Y.js} +2 -2
- package/dist/cli-bundle/main.js +32 -32
- 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 +1 -1
- 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 +57 -57
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +12 -12
- package/dist/core/item/parse.d.ts +13 -1
- package/dist/core/item/parse.js +4 -4
- package/dist/core/sentry/instrument.js +1 -1
- package/dist/core/shared/secret-rules.d.ts +18 -2
- package/dist/core/shared/secret-rules.js +4 -2
- package/dist/core/shared/url-credentials.d.ts +37 -0
- package/dist/core/shared/url-credentials.js +2 -0
- package/dist/core/telemetry/runtime.js +2 -2
- package/dist/sdk/agent/command-recovery.js +1 -1
- package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1
- package/dist/sdk/cli-contracts/completeness.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/tool-schema.d.ts +1 -1
- package/dist/sdk/cli-contracts/tool-schema.js +1 -1
- package/dist/sdk/command-line.d.ts +1 -1
- package/dist/sdk/command-line.js +1 -1
- package/dist/sdk/completion/bash.js +1 -1
- package/dist/sdk/completion/fish.js +3 -1
- package/dist/sdk/completion/zsh.js +3 -1
- package/dist/sdk/docs.d.ts +14 -2
- package/dist/sdk/docs.js +1 -1
- package/dist/sdk/files.d.ts +14 -2
- package/dist/sdk/files.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/boundary-fixtures.d.ts +25 -0
- package/dist/sdk/governance/boundary-fixtures.js +1 -1
- package/dist/sdk/governance/defect-recurrence.d.ts +8 -1
- package/dist/sdk/governance/defect-recurrence.js +2 -2
- package/dist/sdk/guide-topics.js +1 -1
- package/dist/sdk/index.d.ts +1 -1
- package/dist/sdk/index.js +1 -1
- package/dist/sdk/lifecycle/dependency-removal.js +2 -0
- package/dist/sdk/lifecycle/item-revision.js +1 -1
- package/dist/sdk/lifecycle/start-blockers.d.ts +9 -0
- package/dist/sdk/lifecycle/start-blockers.js +1 -1
- package/dist/sdk/lifecycle/update.d.ts +10 -4
- package/dist/sdk/lifecycle/update.js +2 -2
- package/dist/sdk/linked-artifacts.d.ts +73 -3
- package/dist/sdk/linked-artifacts.js +2 -2
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/runtime/actions.js +1 -1
- package/dist/sdk/test/command-args.js +1 -1
- package/dist/sdk/test/execution.d.ts +15 -3
- package/dist/sdk/test/execution.js +2 -2
- package/docs/AGENT_GUIDE.md +2 -2
- package/docs/AGENT_UX_CONTRACTS.md +7 -1
- package/docs/BUILD_AND_RELEASE_ACCEPTANCE.md +1 -1
- package/docs/CODEX_PLUGIN.md +2 -1
- package/docs/COMMANDS.md +16 -9
- package/docs/CONFIGURATION.md +16 -0
- package/docs/CORPUS_SHAPES.md +1 -1
- package/docs/DEFECT_RECURRENCE.md +20 -1
- package/docs/MUTATION_INTEGRITY.md +65 -0
- package/docs/ONBOARDING.md +1 -1
- package/docs/README.md +8 -8
- package/docs/SDK.md +46 -0
- package/docs/SDK_CONTEXT_INTEGRITY.md +2 -0
- package/docs/TESTING.md +1 -1
- package/docs/generated/FLAG_LEXICON_BUDGETS.md +6 -6
- package/marketplace.json +1 -1
- package/package.json +9 -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-D727C4RO.js +0 -122
- package/dist/cli-bundle/chunks/chunk-T2MNRM3S.js +0 -9
- package/dist/cli-bundle/chunks/chunk-UFPLZ6LZ.js +0 -2
- package/dist/cli-bundle/chunks/chunk-UL64P6MR.js +0 -31
- package/dist/cli-bundle/chunks/item-transaction-4N5P34GO.js +0 -2
- package/dist/cli-bundle/chunks/register-mutation-ZBF6ITYK.js +0 -20
- package/dist/cli-bundle/chunks/register-operations-PWF6GOHE.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-56MIAFEN.js +0 -24
- package/dist/cli-bundle/focused-chunks/chunk-ALLOWZSH.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-LWMPQRJT.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-NZQYHPUN.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-QK7FX4O5.js +0 -44
- package/dist/cli-bundle/focused-chunks/chunk-U7HWWEJ2.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-UIZVD36C.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-WK773UVA.js +0 -2
- package/docs/CHATGPT_CODEX_PLUGIN_IMPLEMENTATION.md +0 -776
- package/docs/CONTEXT_ALGORITHM_PORTFOLIO.md +0 -167
- package/docs/DEVELOPMENT_DEPENDENCY_SECURITY.md +0 -246
- package/docs/PR_REVIEW_LOOP.md +0 -96
- package/docs/RELEASE_LEDGER_RECONCILIATION.md +0 -148
- package/docs/RELEASE_RELIABILITY.md +0 -147
- package/docs/RELEASING.md +0 -805
- package/docs/performance/corpus-shape-comparison.json +0 -1
- package/docs/performance/latest-scale-report.json +0 -1
- package/docs/performance/scale-100k-report.json +0 -1
|
@@ -76,7 +76,7 @@ additionalProperties?:boolean;}
|
|
|
76
76
|
*/
|
|
77
77
|
export declare function buildPmActionToolInputSchema(action:PmToolAction,options?:PmActionToolInputSchemaOptions):Record<string,unknown>;
|
|
78
78
|
/** Canonical version of the action-scoped strict MCP tool-parameters schema (`PM_TOOL_PARAMETERS_SCHEMA`). Exported as the single source of truth so the MCP server, the `pm contracts` command, SDK consumers, and contract tests bind to one version constant. Bump the patch/minor for additive, backward-compatible schema changes; bump the MAJOR for breaking changes — the major also drives the `$id` `tool-parameters-v{major}` slug, so the two never drift. */
|
|
79
|
-
export declare const PM_TOOL_PARAMETERS_SCHEMA_VERSION:"4.
|
|
79
|
+
export declare const PM_TOOL_PARAMETERS_SCHEMA_VERSION:"4.24.0";
|
|
80
80
|
/**
|
|
81
81
|
* Major component of {@link PM_TOOL_PARAMETERS_SCHEMA_VERSION}, used to build the
|
|
82
82
|
* schema `$id` slug so a breaking version bump renames the document in lockstep.
|
|
@@ -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]="d21c1722-1e9d-5091-ba42-7c283c3671cc")}catch{}})();import{normalizeUniqueStringList}from"./string-lists.js";import{PM_EXPECT_HASH_ACTIONS,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";import{CREATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS,UPDATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS}from"./commander-mutation-options.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:property==="expectHash"?`options.field (${field}=<value>)`:`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)]),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","inheritFocus","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:["verify","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","inheritFocus","allowMissingParent","tags","priority","body","description","author","message"]},next:{optional:[...NEXT_CONTRACT_PARAMETER_KEYS,"for"]},reindex:{optional:["mode","progress"]},history:{required:["id"],optional:["limit","order","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","inheritFocus","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","expectAt",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],mutuallyExclusive:[["edit","ifAbsent"],["delete","ifAbsent"],["expectAt","ifAbsent"]]},notes:{required:["id"],optional:["text","add","addJson","stdin","edit","delete","limit","since","eventType","includeMeta","full","ifAbsent","expectAt",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],mutuallyExclusive:[["addJson","add"],["addJson","stdin"],["addJson","file"],["addJson","edit"],["addJson","delete"],["edit","ifAbsent"],["delete","ifAbsent"],["expectAt","ifAbsent"]]},learnings:{required:["id"],optional:["text","add","stdin","edit","delete","limit","full","ifAbsent","expectAt",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],mutuallyExclusive:[["edit","ifAbsent"],["delete","ifAbsent"],["expectAt","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:"ifAvailable",schema:{const:!0}},{property:"id",schema:{type:"string"}}]]},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:"Move the claimed item to its configured in-progress status; with next, the selected item is claimed and started in one locked write."};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,...PM_EXPECT_HASH_ACTIONS.has(action)?["expectHash"]:[],...contract.required??[],...contract.optional??[]])}function pmToolActionNestedOptionKeys(action){const parameterKeys=pmToolActionParameterKeys(action);if(parameterKeys===void 0)return;const mutationContracts=action==="create"?CREATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS:action==="update"?UPDATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS:[];return toSchemaKeyList([...parameterKeys,...mutationContracts.flatMap(({keys,target})=>[target,...keys]),...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.23.0",PM_TOOL_PARAMETERS_SCHEMA_MAJOR=PM_TOOL_PARAMETERS_SCHEMA_VERSION.split(".")[0],PM_PROVIDER_TOOL_PARAMETERS_SCHEMA_VERSION="1.12.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]="68c3cf19-3ee0-5f8e-a945-80420cbb0415")}catch{}})();import{normalizeUniqueStringList}from"./string-lists.js";import{PM_EXPECT_HASH_ACTIONS,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";import{CREATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS,UPDATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS}from"./commander-mutation-options.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:property==="expectHash"?`options.field (${field}=<value>)`:`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)]),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","inheritFocus","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:["verify","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","inheritFocus","allowMissingParent","tags","priority","body","description","author","message"]},next:{optional:[...NEXT_CONTRACT_PARAMETER_KEYS,"for"]},reindex:{optional:["mode","progress"]},history:{required:["id"],optional:["limit","order","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","inheritFocus","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","expectAt",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],mutuallyExclusive:[["edit","ifAbsent"],["delete","ifAbsent"],["expectAt","ifAbsent"]]},notes:{required:["id"],optional:["text","add","addJson","stdin","edit","delete","limit","since","eventType","includeMeta","full","ifAbsent","expectAt",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],mutuallyExclusive:[["addJson","add"],["addJson","stdin"],["addJson","file"],["addJson","edit"],["addJson","delete"],["edit","ifAbsent"],["delete","ifAbsent"],["expectAt","ifAbsent"]]},learnings:{required:["id"],optional:["text","add","stdin","edit","delete","limit","full","ifAbsent","expectAt",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],mutuallyExclusive:[["edit","ifAbsent"],["delete","ifAbsent"],["expectAt","ifAbsent"]]},files:{required:[],optional:["id","add","addGlob","remove","migrate","list","addNote","discover","apply","discoveryNote","appendStable","validatePaths","full","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","full",...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","full","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:"ifAvailable",schema:{const:!0}},{property:"id",schema:{type:"string"}}]]},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:"Move the claimed item to its configured in-progress status; with next, the selected item is claimed and started in one locked write."};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,...PM_EXPECT_HASH_ACTIONS.has(action)?["expectHash"]:[],...contract.required??[],...contract.optional??[]])}function pmToolActionNestedOptionKeys(action){const parameterKeys=pmToolActionParameterKeys(action);if(parameterKeys===void 0)return;const mutationContracts=action==="create"?CREATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS:action==="update"?UPDATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS:[];return toSchemaKeyList([...parameterKeys,...mutationContracts.flatMap(({keys,target})=>[target,...keys]),...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.24.0",PM_TOOL_PARAMETERS_SCHEMA_MAJOR=PM_TOOL_PARAMETERS_SCHEMA_VERSION.split(".")[0],PM_PROVIDER_TOOL_PARAMETERS_SCHEMA_VERSION="1.12.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
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type{GlobalOptions}from "../core/shared/command-types.js";export{quoteWindowsCommandArg,quoteCommandArg,renderPmCommand}from "../core/shared/command-line.js";
|
|
1
|
+
import type{GlobalOptions}from "../core/shared/command-types.js";export{quoteWindowsCommandArg,quoteCommandArg,renderPmCommand}from "../core/shared/command-line.js";export{URL_CREDENTIAL_PLACEHOLDER,invocationCarriesUrlCredentials,redactUrlCredentialsInText,redactUrlCredentialsInToken,runWithUrlCredentialInvocation,}from "../core/shared/url-credentials.js";
|
|
2
2
|
/** Tracker selection a rendered recovery command must preserve: the requested path and extension isolation. */
|
|
3
3
|
export type CommandScope=Pick<GlobalOptions,"path"|"noExtensions">;
|
|
4
4
|
/** Retain caller scope before runtime dispatch resolves its working storage path. */
|
package/dist/sdk/command-line.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]="7f08c44a-dfdf-5c23-8f68-0e3ed73582b0")}catch{}})();import{findBootstrapCommandTokenIndex}from"./cli-contracts/bootstrap-command-scanner.js";import path from"node:path";import{resolveImplicitPmRoot,resolvePmRoot,resolveWorkspaceRoot}from"../core/store/paths.js";import{isPathWithinDirectory}from"../core/fs/path-utils.js";import{quoteWindowsCommandArg,quoteCommandArg,renderPmCommand}from"../core/shared/command-line.js";import{URL_CREDENTIAL_PLACEHOLDER,invocationCarriesUrlCredentials,redactUrlCredentialsInText,redactUrlCredentialsInToken,runWithUrlCredentialInvocation}from"../core/shared/url-credentials.js";const requestedPaths=new WeakMap;function capturePmCommandScope(options){requestedPaths.set(options,options.path)}function environmentCommandScope(cwd){if(!process.env.PM_PATH?.trim())return;const resolved=resolvePmRoot(cwd);return isPathWithinDirectory(resolveWorkspaceRoot(resolved),cwd)&&resolved===resolveImplicitPmRoot(cwd)?void 0:path.relative(cwd,resolved)||"."}function resolvePmCommandScopeArgs(options,cwd=process.cwd()){const requested=requestedPaths.has(options)?requestedPaths.get(options):options.path,selected=requested?.trim()?requested:environmentCommandScope(cwd),args=selected?["--pm-path",selected]:[];return options.noExtensions&&args.push("--no-extensions"),args}const HISTORY_REDACT_SENSITIVE_FLAGS=new Set(["--literal","--regex","--replacement"]);function isHistoryRedactInvocation(argv){const rootIndex=findBootstrapCommandTokenIndex(argv);if(rootIndex===void 0)return!1;if(argv[rootIndex]==="history-redact")return!0;if(argv[rootIndex]!=="history")return!1;const operationArgs=argv.slice(rootIndex+1),operationIndex=findBootstrapCommandTokenIndex(operationArgs);return operationIndex!==void 0&&operationArgs[operationIndex]==="redact"}function redactSensitiveCommandArgs(argv){if(!isHistoryRedactInvocation(argv))return[...argv];const redacted=[];let redactNext=!1;for(const token of argv){if(redactNext){redacted.push("[redacted]"),redactNext=!1;continue}redactNext=!1;const equalsIndex=token.indexOf("="),flag=equalsIndex>=0?token.slice(0,equalsIndex):token;if(!HISTORY_REDACT_SENSITIVE_FLAGS.has(flag)){redacted.push(token);continue}if(equalsIndex>=0){redacted.push(`${flag}=[redacted]`);continue}redacted.push(flag),redactNext=!0}return redacted}export{URL_CREDENTIAL_PLACEHOLDER,capturePmCommandScope,invocationCarriesUrlCredentials,isHistoryRedactInvocation,quoteCommandArg,quoteWindowsCommandArg,redactSensitiveCommandArgs,redactUrlCredentialsInText,redactUrlCredentialsInToken,renderPmCommand,resolvePmCommandScopeArgs,runWithUrlCredentialInvocation};
|
|
2
2
|
//# sourceMappingURL=command-line.js.map
|
|
@@ -1,3 +1,3 @@
|
|
|
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]="dd896f8b-8a4a-54b2-854b-3a8653ed4d18")}catch{}})();import{PM_NAMESPACED_COMMAND_ALIASES}from"../cli-contracts.js";import{AGGREGATE_FLAGS,ALL_COMMANDS,APPEND_FLAGS,CALENDAR_FLAGS,CLAIM_MUTATION_FLAGS,CLOSE_MANY_FLAGS,CLOSE_MUTATION_FLAGS,CLOSE_TASK_MUTATION_FLAGS,COMPLETION_SHELL_CHOICES,CONTEXT_FLAGS,CONTRACTS_FLAGS,COPY_FLAGS,CREATE_FLAGS,DELETE_MUTATION_FLAGS,DEPS_FLAGS,DUPLICATES_FLAGS,EVENTS_FLAGS,EXTENSION_LIFECYCLE_ACTIONS,EXTENSION_LIFECYCLE_FLAGS,FOCUS_FLAGS,GET_FLAGS,GLOBAL_COMPLETION_INLINE_PATTERNS,GLOBAL_COMPLETION_SWITCH_PATTERNS,GLOBAL_COMPLETION_VALUE_PATTERNS,GLOBAL_FLAGS,GRAPH_FLAGS,GUIDE_FLAGS,GUIDE_TOPIC_CHOICES,HEALTH_FLAGS,HISTORY_AUTHOR_ACKNOWLEDGE_FLAGS,HISTORY_FLAGS,HISTORY_LEAVES,HISTORY_OPERATION_FLAGS,INIT_FLAGS,LIST_FLAGS,MEET_FLAGS,MUTATION_FLAGS,NAMESPACE_NOUNS,NAMESPACE_PREFIXES,NEXT_FLAGS,PACKAGE_LIFECYCLE_ACTIONS,PACKAGE_LIFECYCLE_FLAGS,PLAN_FLAGS,PLAN_SUBCOMMANDS_LIST,RELEASE_MUTATION_FLAGS,REMIND_FLAGS,SCHEMA_SUBCOMMAND_CHOICES,SEARCH_FLAGS,STATS_FLAGS,UPDATE_FLAGS,UPDATE_MANY_FLAGS,UPGRADE_FLAGS,completionNamespaceLeaves,completionStatusValues,completionTypeValues,joinCompletionValues,mergeFlagStrings,shellDoubleQuote}from"./shared.js";function renderBashDynamicChoiceResolver(kind,command,fallback){const envKind=kind.toUpperCase(),cacheVar=`PM_COMPLETION_${envKind}_CACHE`,cacheTsVar=`PM_COMPLETION_${envKind}_CACHE_TS`,ttlVar=`PM_COMPLETION_${envKind}_TTL`,escapedFallback=shellDoubleQuote(fallback);return[`_pm_completion_${kind}_choices() {`," local now ttl cache_ts resolved",' now="$(date +%s 2>/dev/null || echo 0)"',` ttl="\${${ttlVar}:-120}"`,` cache_ts="\${${cacheTsVar}:-0}"`,` if [[ -n "\${${cacheVar}:-}" && "$now" -ne 0 && $((now - cache_ts)) -lt "$ttl" ]]; then`,` printf '%s\\n' "$${cacheVar}"`," return 0"," fi",` resolved="$(pm ${command} 2>/dev/null)"`,' if [[ -z "$resolved" ]]; then',` resolved="${escapedFallback}"`," fi",` ${cacheVar}="$resolved"`,` ${cacheTsVar}="$now"`,` printf '%s\\n' "$${cacheVar}"`,"}"]}function generateBashScript(itemTypes=[],tags=[],eagerTagExpansion=!1,runtime={}){const namespaceLeaves=completionNamespaceLeaves(runtime),cmds=ALL_COMMANDS.join(" "),useDynamicTypeExpansion=itemTypes.length===0,typeValues=completionTypeValues(itemTypes,runtime),statusValues=completionStatusValues(runtime),tagValues=joinCompletionValues(tags),listFlags=mergeFlagStrings(LIST_FLAGS,runtime.command_flags?.list),createFlags=mergeFlagStrings(CREATE_FLAGS,runtime.command_flags?.create),updateFlags=mergeFlagStrings(UPDATE_FLAGS,runtime.command_flags?.update),updateManyFlags=mergeFlagStrings(UPDATE_MANY_FLAGS,runtime.command_flags?.["update-many"]),searchFlags=mergeFlagStrings(SEARCH_FLAGS,runtime.command_flags?.search),calendarFlags=mergeFlagStrings(CALENDAR_FLAGS,runtime.command_flags?.calendar),contextFlags=mergeFlagStrings(CONTEXT_FLAGS,runtime.command_flags?.context),useEagerTagExpansion=eagerTagExpansion||tags.length>0,matchWords=values=>`_pm_completion_add_matches "${shellDoubleQuote(values)}"`;return["# bash completion for pm",`# Source this file or add 'eval "$(pm completion bash)"' to ~/.bashrc`,"",...useDynamicTypeExpansion?[...renderBashDynamicChoiceResolver("type","completion-types",typeValues),""]:[],...renderBashDynamicChoiceResolver("status","completion-statuses",statusValues),"","# Treat choices as data: no eval, compgen expansion, or filename globbing.","_pm_completion_add_matches() {"," local line value quoted parse_char parse_index"," local -a values"," while IFS= read -r line; do",' read -r -a values <<< "$line"',' for value in "${values[@]}"; do',' [[ "$value" == "$cur"* ]] || continue',' case "$quote_mode" in'," single)"," quoted=${value//\\'/\\'\\\\\\'\\'}",` COMPREPLY+=("$quoted'")`," ;;"," double)"," quoted="," for (( parse_index=0; parse_index<${#value}; parse_index++ )); do",' parse_char="${value:parse_index:1}"',' case "$parse_char" in'," '\"'|'\\'|'$'|'`') quoted=\"${quoted}\\\\${parse_char}\" ;;",` '!') quoted="\${quoted}\\"'!'\\"" ;;`,' *) quoted="${quoted}${parse_char}" ;;'," esac"," done",' COMPREPLY+=("$quoted\\"")'," ;;"," *)",' case "$value" in'," *[!a-zA-Z0-9_.,:/@%+=-]*)"," quoted=${value//\\'/\\'\\\\\\'\\'}",` COMPREPLY+=("'$quoted'")`," ;;",' *) COMPREPLY+=("$value") ;;'," esac"," ;;"," esac"," done",' done <<< "$1"',"}","","_pm_completion() {"," local cur prev words cword raw_prefix quote_mode parse_char next_char parse_index quote_start escaped"," COMPREPLY=()",' raw_prefix="${COMP_WORDS[COMP_CWORD]}"'," _init_completion 2>/dev/null || {",' cur="${COMP_WORDS[COMP_CWORD]}"',' prev="${COMP_WORDS[COMP_CWORD-1]}"'," cword=$COMP_CWORD"," }"," # Decode only the current Readline word. Never evaluate or expand it."," quote_mode=plain escaped=0 quote_start=0 cur="," for (( parse_index=0; parse_index<${#raw_prefix}; parse_index++ )); do",' parse_char="${raw_prefix:parse_index:1}"',' if (( escaped )); then cur="${cur}${parse_char}"; escaped=0; continue; fi',' case "$quote_mode" in'," single)",' if [[ "$parse_char" == "\'" ]]; then quote_mode=plain; else cur="${cur}${parse_char}"; fi'," ;;"," double)",' case "$parse_char" in',` '"') quote_mode=plain ;;`," '\\')",' next_char="${raw_prefix:parse_index+1:1}"',' case "$next_char" in'," '\"'|'\\'|'$'|'`') escaped=1 ;;",' *) cur="${cur}\\\\" ;;'," esac"," ;;"," '`') return 0 ;;",' *) cur="${cur}${parse_char}" ;;'," esac"," ;;"," *)",' case "$parse_char" in',` "'") quote_mode=single; quote_start=$parse_index ;;`,` '"') quote_mode=double; quote_start=$parse_index ;;`," '\\') escaped=1 ;;"," '`') return 0 ;;",' *) cur="${cur}${parse_char}" ;;'," esac"," ;;"," esac"," done"," # A mixed quoted segment has a different replacement span; keep it conservative.",' [[ "$quote_mode" != plain && $quote_start -ne 0 ]] && return 0',""," if [[ $cword -eq 1 ]]; then",` ${matchWords(cmds)}`," return 0"," fi","",' if [[ "$prev" == "--type" ]]; then',useDynamicTypeExpansion?' _pm_completion_add_matches "$(_pm_completion_type_choices)"':` ${matchWords(typeValues)}`," return 0"," fi","",' if [[ "$prev" == "--status" ]]; then',' _pm_completion_add_matches "$(_pm_completion_status_choices)"'," return 0"," fi","",...useEagerTagExpansion?[' if [[ ( "$prev" == "--tag" || "$prev" == "--tags" ) && ! ( ( "${COMP_WORDS[1]}" == "package" || "${COMP_WORDS[1]}" == "packages" ) && "${COMP_WORDS[2]}" == "upgrade" ) ]]; then',` ${matchWords(tagValues)}`," return 0"," fi"]:[' if [[ ( "$prev" == "--tag" || "$prev" == "--tags" ) && ! ( ( "${COMP_WORDS[1]}" == "package" || "${COMP_WORDS[1]}" == "packages" ) && "${COMP_WORDS[2]}" == "upgrade" ) ]]; then'," local now ttl cache_ts tag_values",' now="$(date +%s 2>/dev/null || echo 0)"',' ttl="${PM_COMPLETION_TAG_TTL:-120}"',' cache_ts="${PM_COMPLETION_TAG_CACHE_TS:-0}"',' tag_values="${PM_COMPLETION_TAG_CACHE:-}"',' if [[ -z "$tag_values" || "$now" -eq 0 || $((now - cache_ts)) -ge "$ttl" ]]; then',' tag_values="$(pm completion-tags 2>/dev/null)"',' PM_COMPLETION_TAG_CACHE="$tag_values"',' PM_COMPLETION_TAG_CACHE_TS="$now"'," fi",' _pm_completion_add_matches "$tag_values"'," return 0"," fi"],"",' if [[ "$prev" == "--tag" && ( ( "${COMP_WORDS[1]}" == "package" || "${COMP_WORDS[1]}" == "packages" ) && "${COMP_WORDS[2]}" == "upgrade" ) ]]; then'," COMPREPLY=()"," return 0"," fi","",' local cmd="" command_path="" word_index=1 word'," while (( word_index < cword )); do",' word="${COMP_WORDS[word_index]}"',' case "${word//_/-}" in',` ${GLOBAL_COMPLETION_VALUE_PATTERNS}) (( word_index += 2 )); continue ;;`,` ${GLOBAL_COMPLETION_INLINE_PATTERNS}|${GLOBAL_COMPLETION_SWITCH_PATTERNS}) (( word_index++ )); continue ;;`," --) break ;;"," esac",' if [[ -z "$cmd" ]]; then',' cmd="$word"',' [[ "$cmd" == "ctx" ]] && cmd="context"',' command_path="$cmd"',` case "$cmd" in ${NAMESPACE_NOUNS.join("|")}) ;; *) break ;; esac`," else",' case "$command_path $word" in',...PM_NAMESPACED_COMMAND_ALIASES.map(entry=>` "${entry.canonical}") cmd="${entry.alias}"; command_path="${entry.canonical}" ;;`)," *) break ;;"," esac",` case "$command_path" in ${NAMESPACE_PREFIXES.map(prefix=>`"${prefix}"`).join("|")}) ;; *) (( word_index++ )); break ;; esac`," fi"," (( word_index++ ))"," done",' case "$cmd" in',...HISTORY_OPERATION_FLAGS.flatMap(entry=>[` ${entry.alias})`,` ${matchWords(entry.flags)}`," return 0"," ;;"])," list)",` ${matchWords(listFlags)}`," ;;"," aggregate)",` ${matchWords(AGGREGATE_FLAGS)}`," ;;"," duplicates)",` ${matchWords(DUPLICATES_FLAGS)}`," ;;"," create)",` ${matchWords(createFlags)}`," ;;"," copy)",` ${matchWords(COPY_FLAGS)}`," ;;"," focus)",` ${matchWords(FOCUS_FLAGS)}`," ;;"," update)",` ${matchWords(updateFlags)}`," if [[ $word_index -eq $cword ]]; then",` ${matchWords(namespaceLeaves.update)}`," fi"," ;;"," update-many)",` ${matchWords(updateManyFlags)}`," ;;"," calendar|cal)",` ${matchWords(calendarFlags)}`," ;;"," context|ctx)",` ${matchWords(contextFlags)}`," if [[ $word_index -eq $cword ]]; then",` ${matchWords(namespaceLeaves.context)}`," fi"," ;;"," ops)",` ${matchWords(`${GLOBAL_FLAGS} ${namespaceLeaves.ops}`)}`," ;;"," next)",` ${matchWords(NEXT_FLAGS)}`," ;;"," guide)",` ${matchWords(`${GUIDE_FLAGS} ${GUIDE_TOPIC_CHOICES}`)}`," ;;"," search)",` ${matchWords(searchFlags)}`," ;;"," reindex)",` ${matchWords("--mode --progress --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")}`," ;;"," init)",` ${matchWords(`${INIT_FLAGS} --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help`)}`," ;;"," config)",` ${matchWords("--criterion --clear-criteria --format --policy --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")}`," ;;"," extension)",` ${matchWords(`${EXTENSION_LIFECYCLE_ACTIONS} ${EXTENSION_LIFECYCLE_FLAGS}`)}`," ;;"," package|packages)",` ${matchWords(`${PACKAGE_LIFECYCLE_ACTIONS} ${PACKAGE_LIFECYCLE_FLAGS} ${UPGRADE_FLAGS}`)}`," ;;"," comments)",` ${matchWords("--add --body --stdin --file --edit --delete --expect-at --limit --full-history --if-absent --author --message --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")}`," ;;"," notes)",` ${matchWords("--add --add-json --stdin --file --edit --delete --expect-at --limit --since --event-type --include-meta --full-history --if-absent --author --message --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")}`," ;;"," learnings)",` ${matchWords("--add --stdin --file --edit --delete --expect-at --limit --full-history --if-absent --author --message --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")}`," ;;"," files)",` ${matchWords("discover lookup --add --add-glob --remove --migrate --list --apply --note --append-stable --validate-paths --scope --limit --offset --no-truncate --strict-read --explain --lines --decision-depth --author --message --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")}`," ;;"," docs)",` ${matchWords("--add --add-glob --remove --migrate --note --validate-paths --author --message --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")}`," ;;"," append)",` ${matchWords(APPEND_FLAGS)}`," ;;"," deps)",` ${matchWords(DEPS_FLAGS)}`," ;;"," graph)",` ${matchWords(`ancestors descendants predecessors successors paths impact analyze audit communities redundancy dominators slack centrality articulation plan index ${GRAPH_FLAGS}`)}`," ;;"," test)",` ${matchWords("--add --add-json --remove --remove-index --list --run --match --only-index --only-last --background --timeout --progress --env-set --env-clear --shared-host-safe --pm-context --override-linked-pm-context --fail-on-context-mismatch --fail-on-skipped --fail-on-empty-test-run --require-assertions-for-pm --check-context --auto-pm-context --author --message --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")}`," ;;"," test-all)",` ${matchWords("--status --limit --offset --background --timeout --progress --env-set --env-clear --shared-host-safe --pm-context --override-linked-pm-context --fail-on-context-mismatch --fail-on-skipped --fail-on-empty-test-run --require-assertions-for-pm --check-context --auto-pm-context --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")}`," ;;"," test-runs)",` ${matchWords("list status logs stop resume --status --limit --stream --tail --force --author --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")}`," ;;"," validate)",` ${matchWords("--check-completeness --check-metadata --metadata-profile --check-resolution --check-lifecycle --check-stale-blockers --dependency-cycle-severity --parent-cycle-severity --check-files --scan-mode --include-pm-internals --verbose-file-lists --verbose-diagnostics --all-affected-ids --strict-exit --fail-on-warn --fix-hints --auto-fix --dry-run --fix-scope --prune-missing --check-history-drift --check-command-references --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")}`," ;;"," health)",` ${matchWords(HEALTH_FLAGS)}`," ;;"," history)"," if [[ $word_index -eq $cword ]]; then",` ${matchWords(`${HISTORY_FLAGS} ${HISTORY_LEAVES}`)}`," else",` ${matchWords(HISTORY_FLAGS)}`," fi"," ;;"," events)",` ${matchWords(EVENTS_FLAGS)}`," ;;"," history-author-acknowledge)",` ${matchWords(`${HISTORY_AUTHOR_ACKNOWLEDGE_FLAGS} --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help`)}`," ;;"," get)",` ${matchWords(GET_FLAGS)}`," ;;"," schema)",' if [[ "$prev" == "policy-mode" ]]; then',` ${matchWords("advise refuse")}`," return"," fi",` ${matchWords(`${SCHEMA_SUBCOMMAND_CHOICES} --definition --policy --message --description --default-status --folder --alias --role --order --type --commands --cli-flag --required --required-on-create --no-allow-unset --required-types --infer --min-count --apply --to --migration-id --dry-run --author --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help`)}`," ;;"," profile)",` ${matchWords("list show apply lint agile ops research --dry-run --author --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")}`," ;;"," plan)",` ${matchWords(`${PLAN_SUBCOMMANDS_LIST} ${PLAN_FLAGS}`)}`," ;;"," contracts)",` ${matchWords(CONTRACTS_FLAGS)}`," ;;"," gc)",` ${matchWords("--dry-run --scope --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")}`," ;;"," stats)",` ${matchWords(STATS_FLAGS)}`," ;;"," close-task)",` ${matchWords(CLOSE_TASK_MUTATION_FLAGS)}`," ;;"," close)",` ${matchWords(CLOSE_MUTATION_FLAGS)}`,' if [[ "$cmd" == "close" && $word_index -eq $cword ]]; then',` ${matchWords(namespaceLeaves.close)}`," fi"," ;;"," close-many)",` ${matchWords(CLOSE_MANY_FLAGS)}`," ;;"," release)",` ${matchWords(RELEASE_MUTATION_FLAGS)}`," ;;"," delete)",` ${matchWords(DELETE_MUTATION_FLAGS)}`," ;;"," claim)",` ${matchWords(CLAIM_MUTATION_FLAGS)}`," ;;"," start-task|pause-task)",` ${matchWords(MUTATION_FLAGS)}`," ;;"," meet|event)",` ${matchWords(MEET_FLAGS)}`," ;;"," remind)",` ${matchWords(REMIND_FLAGS)}`," ;;"," completion)",` ${matchWords(COMPLETION_SHELL_CHOICES)}`," ;;"," templates)",` ${matchWords("save list show")}`," ;;"," *)",` ${matchWords(GLOBAL_FLAGS)}`," ;;"," esac"," if [[ $word_index -eq $cword ]]; then",' case "$command_path" in',...Object.entries(namespaceLeaves).filter(([prefix])=>["item","workspace","search"].includes(prefix.split(" ")[0])).map(([prefix,leaves])=>` "${prefix}") ${matchWords(leaves)} ;;`)," esac"," fi",' if [[ "$cmd" == "comments" || "$cmd" == "notes" || "$cmd" == "learnings" ]]; then',` ${matchWords("--text")}`," fi"," return 0","}","","complete -F _pm_completion pm"].join(`
|
|
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]="ff36e43b-1ca1-516b-b375-f941269ff51c")}catch{}})();import{PM_NAMESPACED_COMMAND_ALIASES}from"../cli-contracts.js";import{AGGREGATE_FLAGS,ALL_COMMANDS,APPEND_FLAGS,CALENDAR_FLAGS,CLAIM_MUTATION_FLAGS,CLOSE_MANY_FLAGS,CLOSE_MUTATION_FLAGS,CLOSE_TASK_MUTATION_FLAGS,COMPLETION_SHELL_CHOICES,CONTEXT_FLAGS,CONTRACTS_FLAGS,COPY_FLAGS,CREATE_FLAGS,DELETE_MUTATION_FLAGS,DEPS_FLAGS,DUPLICATES_FLAGS,EVENTS_FLAGS,EXTENSION_LIFECYCLE_ACTIONS,EXTENSION_LIFECYCLE_FLAGS,FOCUS_FLAGS,GET_FLAGS,GLOBAL_COMPLETION_INLINE_PATTERNS,GLOBAL_COMPLETION_SWITCH_PATTERNS,GLOBAL_COMPLETION_VALUE_PATTERNS,GLOBAL_FLAGS,GRAPH_FLAGS,GUIDE_FLAGS,GUIDE_TOPIC_CHOICES,HEALTH_FLAGS,HISTORY_AUTHOR_ACKNOWLEDGE_FLAGS,HISTORY_FLAGS,HISTORY_LEAVES,HISTORY_OPERATION_FLAGS,INIT_FLAGS,LIST_FLAGS,MEET_FLAGS,MUTATION_FLAGS,NAMESPACE_NOUNS,NAMESPACE_PREFIXES,NEXT_FLAGS,PACKAGE_LIFECYCLE_ACTIONS,PACKAGE_LIFECYCLE_FLAGS,PLAN_FLAGS,PLAN_SUBCOMMANDS_LIST,RELEASE_MUTATION_FLAGS,REMIND_FLAGS,SCHEMA_SUBCOMMAND_CHOICES,SEARCH_FLAGS,STATS_FLAGS,UPDATE_FLAGS,UPDATE_MANY_FLAGS,UPGRADE_FLAGS,completionNamespaceLeaves,completionStatusValues,completionTypeValues,joinCompletionValues,mergeFlagStrings,shellDoubleQuote}from"./shared.js";function renderBashDynamicChoiceResolver(kind,command,fallback){const envKind=kind.toUpperCase(),cacheVar=`PM_COMPLETION_${envKind}_CACHE`,cacheTsVar=`PM_COMPLETION_${envKind}_CACHE_TS`,ttlVar=`PM_COMPLETION_${envKind}_TTL`,escapedFallback=shellDoubleQuote(fallback);return[`_pm_completion_${kind}_choices() {`," local now ttl cache_ts resolved",' now="$(date +%s 2>/dev/null || echo 0)"',` ttl="\${${ttlVar}:-120}"`,` cache_ts="\${${cacheTsVar}:-0}"`,` if [[ -n "\${${cacheVar}:-}" && "$now" -ne 0 && $((now - cache_ts)) -lt "$ttl" ]]; then`,` printf '%s\\n' "$${cacheVar}"`," return 0"," fi",` resolved="$(pm ${command} 2>/dev/null)"`,' if [[ -z "$resolved" ]]; then',` resolved="${escapedFallback}"`," fi",` ${cacheVar}="$resolved"`,` ${cacheTsVar}="$now"`,` printf '%s\\n' "$${cacheVar}"`,"}"]}function generateBashScript(itemTypes=[],tags=[],eagerTagExpansion=!1,runtime={}){const namespaceLeaves=completionNamespaceLeaves(runtime),cmds=ALL_COMMANDS.join(" "),useDynamicTypeExpansion=itemTypes.length===0,typeValues=completionTypeValues(itemTypes,runtime),statusValues=completionStatusValues(runtime),tagValues=joinCompletionValues(tags),listFlags=mergeFlagStrings(LIST_FLAGS,runtime.command_flags?.list),createFlags=mergeFlagStrings(CREATE_FLAGS,runtime.command_flags?.create),updateFlags=mergeFlagStrings(UPDATE_FLAGS,runtime.command_flags?.update),updateManyFlags=mergeFlagStrings(UPDATE_MANY_FLAGS,runtime.command_flags?.["update-many"]),searchFlags=mergeFlagStrings(SEARCH_FLAGS,runtime.command_flags?.search),calendarFlags=mergeFlagStrings(CALENDAR_FLAGS,runtime.command_flags?.calendar),contextFlags=mergeFlagStrings(CONTEXT_FLAGS,runtime.command_flags?.context),useEagerTagExpansion=eagerTagExpansion||tags.length>0,matchWords=values=>`_pm_completion_add_matches "${shellDoubleQuote(values)}"`;return["# bash completion for pm",`# Source this file or add 'eval "$(pm completion bash)"' to ~/.bashrc`,"",...useDynamicTypeExpansion?[...renderBashDynamicChoiceResolver("type","completion-types",typeValues),""]:[],...renderBashDynamicChoiceResolver("status","completion-statuses",statusValues),"","# Treat choices as data: no eval, compgen expansion, or filename globbing.","_pm_completion_add_matches() {"," local line value quoted parse_char parse_index"," local -a values"," while IFS= read -r line; do",' read -r -a values <<< "$line"',' for value in "${values[@]}"; do',' [[ "$value" == "$cur"* ]] || continue',' case "$quote_mode" in'," single)"," quoted=${value//\\'/\\'\\\\\\'\\'}",` COMPREPLY+=("$quoted'")`," ;;"," double)"," quoted="," for (( parse_index=0; parse_index<${#value}; parse_index++ )); do",' parse_char="${value:parse_index:1}"',' case "$parse_char" in'," '\"'|'\\'|'$'|'`') quoted=\"${quoted}\\\\${parse_char}\" ;;",` '!') quoted="\${quoted}\\"'!'\\"" ;;`,' *) quoted="${quoted}${parse_char}" ;;'," esac"," done",' COMPREPLY+=("$quoted\\"")'," ;;"," *)",' case "$value" in'," *[!a-zA-Z0-9_.,:/@%+=-]*)"," quoted=${value//\\'/\\'\\\\\\'\\'}",` COMPREPLY+=("'$quoted'")`," ;;",' *) COMPREPLY+=("$value") ;;'," esac"," ;;"," esac"," done",' done <<< "$1"',"}","","_pm_completion() {"," local cur prev words cword raw_prefix quote_mode parse_char next_char parse_index quote_start escaped"," COMPREPLY=()",' raw_prefix="${COMP_WORDS[COMP_CWORD]}"'," _init_completion 2>/dev/null || {",' cur="${COMP_WORDS[COMP_CWORD]}"',' prev="${COMP_WORDS[COMP_CWORD-1]}"'," cword=$COMP_CWORD"," }"," # Decode only the current Readline word. Never evaluate or expand it."," quote_mode=plain escaped=0 quote_start=0 cur="," for (( parse_index=0; parse_index<${#raw_prefix}; parse_index++ )); do",' parse_char="${raw_prefix:parse_index:1}"',' if (( escaped )); then cur="${cur}${parse_char}"; escaped=0; continue; fi',' case "$quote_mode" in'," single)",' if [[ "$parse_char" == "\'" ]]; then quote_mode=plain; else cur="${cur}${parse_char}"; fi'," ;;"," double)",' case "$parse_char" in',` '"') quote_mode=plain ;;`," '\\')",' next_char="${raw_prefix:parse_index+1:1}"',' case "$next_char" in'," '\"'|'\\'|'$'|'`') escaped=1 ;;",' *) cur="${cur}\\\\" ;;'," esac"," ;;"," '`') return 0 ;;",' *) cur="${cur}${parse_char}" ;;'," esac"," ;;"," *)",' case "$parse_char" in',` "'") quote_mode=single; quote_start=$parse_index ;;`,` '"') quote_mode=double; quote_start=$parse_index ;;`," '\\') escaped=1 ;;"," '`') return 0 ;;",' *) cur="${cur}${parse_char}" ;;'," esac"," ;;"," esac"," done"," # A mixed quoted segment has a different replacement span; keep it conservative.",' [[ "$quote_mode" != plain && $quote_start -ne 0 ]] && return 0',""," if [[ $cword -eq 1 ]]; then",` ${matchWords(cmds)}`," return 0"," fi","",' if [[ "$prev" == "--type" ]]; then',useDynamicTypeExpansion?' _pm_completion_add_matches "$(_pm_completion_type_choices)"':` ${matchWords(typeValues)}`," return 0"," fi","",' if [[ "$prev" == "--status" ]]; then',' _pm_completion_add_matches "$(_pm_completion_status_choices)"'," return 0"," fi","",...useEagerTagExpansion?[' if [[ ( "$prev" == "--tag" || "$prev" == "--tags" ) && ! ( ( "${COMP_WORDS[1]}" == "package" || "${COMP_WORDS[1]}" == "packages" ) && "${COMP_WORDS[2]}" == "upgrade" ) ]]; then',` ${matchWords(tagValues)}`," return 0"," fi"]:[' if [[ ( "$prev" == "--tag" || "$prev" == "--tags" ) && ! ( ( "${COMP_WORDS[1]}" == "package" || "${COMP_WORDS[1]}" == "packages" ) && "${COMP_WORDS[2]}" == "upgrade" ) ]]; then'," local now ttl cache_ts tag_values",' now="$(date +%s 2>/dev/null || echo 0)"',' ttl="${PM_COMPLETION_TAG_TTL:-120}"',' cache_ts="${PM_COMPLETION_TAG_CACHE_TS:-0}"',' tag_values="${PM_COMPLETION_TAG_CACHE:-}"',' if [[ -z "$tag_values" || "$now" -eq 0 || $((now - cache_ts)) -ge "$ttl" ]]; then',' tag_values="$(pm completion-tags 2>/dev/null)"',' PM_COMPLETION_TAG_CACHE="$tag_values"',' PM_COMPLETION_TAG_CACHE_TS="$now"'," fi",' _pm_completion_add_matches "$tag_values"'," return 0"," fi"],"",' if [[ "$prev" == "--tag" && ( ( "${COMP_WORDS[1]}" == "package" || "${COMP_WORDS[1]}" == "packages" ) && "${COMP_WORDS[2]}" == "upgrade" ) ]]; then'," COMPREPLY=()"," return 0"," fi","",' local cmd="" command_path="" word_index=1 word'," while (( word_index < cword )); do",' word="${COMP_WORDS[word_index]}"',' case "${word//_/-}" in',` ${GLOBAL_COMPLETION_VALUE_PATTERNS}) (( word_index += 2 )); continue ;;`,` ${GLOBAL_COMPLETION_INLINE_PATTERNS}|${GLOBAL_COMPLETION_SWITCH_PATTERNS}) (( word_index++ )); continue ;;`," --) break ;;"," esac",' if [[ -z "$cmd" ]]; then',' cmd="$word"',' [[ "$cmd" == "ctx" ]] && cmd="context"',' command_path="$cmd"',` case "$cmd" in ${NAMESPACE_NOUNS.join("|")}) ;; *) break ;; esac`," else",' case "$command_path $word" in',...PM_NAMESPACED_COMMAND_ALIASES.map(entry=>` "${entry.canonical}") cmd="${entry.alias}"; command_path="${entry.canonical}" ;;`)," *) break ;;"," esac",` case "$command_path" in ${NAMESPACE_PREFIXES.map(prefix=>`"${prefix}"`).join("|")}) ;; *) (( word_index++ )); break ;; esac`," fi"," (( word_index++ ))"," done",' case "$cmd" in',...HISTORY_OPERATION_FLAGS.flatMap(entry=>[` ${entry.alias})`,` ${matchWords(entry.flags)}`," return 0"," ;;"])," list)",` ${matchWords(listFlags)}`," ;;"," aggregate)",` ${matchWords(AGGREGATE_FLAGS)}`," ;;"," duplicates)",` ${matchWords(DUPLICATES_FLAGS)}`," ;;"," create)",` ${matchWords(createFlags)}`," ;;"," copy)",` ${matchWords(COPY_FLAGS)}`," ;;"," focus)",` ${matchWords(FOCUS_FLAGS)}`," ;;"," update)",` ${matchWords(updateFlags)}`," if [[ $word_index -eq $cword ]]; then",` ${matchWords(namespaceLeaves.update)}`," fi"," ;;"," update-many)",` ${matchWords(updateManyFlags)}`," ;;"," calendar|cal)",` ${matchWords(calendarFlags)}`," ;;"," context|ctx)",` ${matchWords(contextFlags)}`," if [[ $word_index -eq $cword ]]; then",` ${matchWords(namespaceLeaves.context)}`," fi"," ;;"," ops)",` ${matchWords(`${GLOBAL_FLAGS} ${namespaceLeaves.ops}`)}`," ;;"," next)",` ${matchWords(NEXT_FLAGS)}`," ;;"," guide)",` ${matchWords(`${GUIDE_FLAGS} ${GUIDE_TOPIC_CHOICES}`)}`," ;;"," search)",` ${matchWords(searchFlags)}`," ;;"," reindex)",` ${matchWords("--mode --progress --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")}`," ;;"," init)",` ${matchWords(`${INIT_FLAGS} --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help`)}`," ;;"," config)",` ${matchWords("--criterion --clear-criteria --format --policy --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")}`," ;;"," extension)",` ${matchWords(`${EXTENSION_LIFECYCLE_ACTIONS} ${EXTENSION_LIFECYCLE_FLAGS}`)}`," ;;"," package|packages)",` ${matchWords(`${PACKAGE_LIFECYCLE_ACTIONS} ${PACKAGE_LIFECYCLE_FLAGS} ${UPGRADE_FLAGS}`)}`," ;;"," comments)",` ${matchWords("--add --body --stdin --file --edit --delete --expect-at --limit --full-history --if-absent --author --message --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")}`," ;;"," notes)",` ${matchWords("--add --add-json --stdin --file --edit --delete --expect-at --limit --since --event-type --include-meta --full-history --if-absent --author --message --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")}`," ;;"," learnings)",` ${matchWords("--add --stdin --file --edit --delete --expect-at --limit --full-history --if-absent --author --message --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")}`," ;;"," files)",` ${matchWords("discover lookup --add --add-glob --remove --migrate --list --apply --note --append-stable --validate-paths --full-history --scope --limit --offset --no-truncate --strict-read --explain --lines --decision-depth --author --message --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")}`," ;;"," docs)",` ${matchWords("--add --add-glob --remove --migrate --note --validate-paths --full-history --author --message --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")}`," ;;"," append)",` ${matchWords(APPEND_FLAGS)}`," ;;"," deps)",` ${matchWords(DEPS_FLAGS)}`," ;;"," graph)",` ${matchWords(`ancestors descendants predecessors successors paths impact analyze audit communities redundancy dominators slack centrality articulation plan index ${GRAPH_FLAGS}`)}`," ;;"," test)",` ${matchWords("--add --add-json --remove --remove-index --list --run --match --only-index --only-last --full-history --background --timeout --progress --env-set --env-clear --shared-host-safe --pm-context --override-linked-pm-context --fail-on-context-mismatch --fail-on-skipped --fail-on-empty-test-run --require-assertions-for-pm --check-context --auto-pm-context --author --message --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")}`," ;;"," test-all)",` ${matchWords("--status --limit --offset --background --timeout --progress --env-set --env-clear --shared-host-safe --pm-context --override-linked-pm-context --fail-on-context-mismatch --fail-on-skipped --fail-on-empty-test-run --require-assertions-for-pm --check-context --auto-pm-context --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")}`," ;;"," test-runs)",` ${matchWords("list status logs stop resume --status --limit --stream --tail --force --author --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")}`," ;;"," validate)",` ${matchWords("--check-completeness --check-metadata --metadata-profile --check-resolution --check-lifecycle --check-stale-blockers --dependency-cycle-severity --parent-cycle-severity --check-files --scan-mode --include-pm-internals --verbose-file-lists --verbose-diagnostics --all-affected-ids --strict-exit --fail-on-warn --fix-hints --auto-fix --dry-run --fix-scope --prune-missing --check-history-drift --check-command-references --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")}`," ;;"," health)",` ${matchWords(HEALTH_FLAGS)}`," ;;"," history)"," if [[ $word_index -eq $cword ]]; then",` ${matchWords(`${HISTORY_FLAGS} ${HISTORY_LEAVES}`)}`," else",` ${matchWords(HISTORY_FLAGS)}`," fi"," ;;"," events)",` ${matchWords(EVENTS_FLAGS)}`," ;;"," history-author-acknowledge)",` ${matchWords(`${HISTORY_AUTHOR_ACKNOWLEDGE_FLAGS} --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help`)}`," ;;"," get)",` ${matchWords(GET_FLAGS)}`," ;;"," schema)",' if [[ "$prev" == "policy-mode" ]]; then',` ${matchWords("advise refuse")}`," return"," fi",` ${matchWords(`${SCHEMA_SUBCOMMAND_CHOICES} --definition --policy --message --description --default-status --folder --alias --role --order --type --commands --cli-flag --required --required-on-create --no-allow-unset --required-types --infer --min-count --apply --to --migration-id --dry-run --author --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help`)}`," ;;"," profile)",` ${matchWords("list show apply lint agile ops research --dry-run --author --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")}`," ;;"," plan)",` ${matchWords(`${PLAN_SUBCOMMANDS_LIST} ${PLAN_FLAGS}`)}`," ;;"," contracts)",` ${matchWords(CONTRACTS_FLAGS)}`," ;;"," gc)",` ${matchWords("--dry-run --scope --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")}`," ;;"," stats)",` ${matchWords(STATS_FLAGS)}`," ;;"," close-task)",` ${matchWords(CLOSE_TASK_MUTATION_FLAGS)}`," ;;"," close)",` ${matchWords(CLOSE_MUTATION_FLAGS)}`,' if [[ "$cmd" == "close" && $word_index -eq $cword ]]; then',` ${matchWords(namespaceLeaves.close)}`," fi"," ;;"," close-many)",` ${matchWords(CLOSE_MANY_FLAGS)}`," ;;"," release)",` ${matchWords(RELEASE_MUTATION_FLAGS)}`," ;;"," delete)",` ${matchWords(DELETE_MUTATION_FLAGS)}`," ;;"," claim)",` ${matchWords(CLAIM_MUTATION_FLAGS)}`," ;;"," start-task|pause-task)",` ${matchWords(MUTATION_FLAGS)}`," ;;"," meet|event)",` ${matchWords(MEET_FLAGS)}`," ;;"," remind)",` ${matchWords(REMIND_FLAGS)}`," ;;"," completion)",` ${matchWords(COMPLETION_SHELL_CHOICES)}`," ;;"," templates)",` ${matchWords("save list show")}`," ;;"," *)",` ${matchWords(GLOBAL_FLAGS)}`," ;;"," esac"," if [[ $word_index -eq $cword ]]; then",' case "$command_path" in',...Object.entries(namespaceLeaves).filter(([prefix])=>["item","workspace","search"].includes(prefix.split(" ")[0])).map(([prefix,leaves])=>` "${prefix}") ${matchWords(leaves)} ;;`)," esac"," fi",' if [[ "$cmd" == "comments" || "$cmd" == "notes" || "$cmd" == "learnings" ]]; then',` ${matchWords("--text")}`," fi"," return 0","}","","complete -F _pm_completion pm"].join(`
|
|
2
2
|
`)}export{generateBashScript};
|
|
3
3
|
//# sourceMappingURL=bash.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
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]="ce5d0314-ead1-5a87-9358-2a1ea6ccf160")}catch{}})();import{PM_NAMESPACED_COMMAND_ALIASES}from"../cli-contracts.js";import{SCAFFOLD_CAPABILITIES}from"../extension/scaffold.js";import{ALL_COMMANDS,ATTEST_INVOCATIONS,COMMAND_COMPLETION_DESCRIPTIONS,EXTENSION_LIFECYCLE_ACTIONS,GLOBAL_COMPLETION_INLINE_PATTERNS,GLOBAL_COMPLETION_SWITCH_PATTERNS,GLOBAL_COMPLETION_VALUE_PATTERNS,GUIDE_TOPIC_CHOICES,HIDDEN_COMMAND_ALIASES,NAMESPACE_NOUNS,NAMESPACE_PREFIXES,PACKAGE_LIFECYCLE_ACTIONS,RESTORE_INVOCATIONS,SCHEMA_SUBCOMMAND_CHOICES,completionNamespaceLeaves,completionStatusValues,completionTypeValues,joinCompletionValues,normalizeRuntimeCompletionFlags}from"./shared.js";function escapeFishSource(value){return value.replaceAll("\\","\\\\").replaceAll("'","\\'")}function escapeFishChoices(value){return escapeFishSource(value.replace(/([^a-zA-Z0-9_:./\s-])/gu,"\\$1"))}const FISH_COMMAND_DESCRIPTION_OVERRIDES=new Map([["calendar","Show deadline/reminder calendar views"],["schema","Inspect and manage runtime schema"],["profile","List, show, apply, and lint project profiles (archetype bundles)"],["plan","Agent-optimized Plan workflow (create/show/add-step/update-step/complete-step/link/approve/materialize)"],["start-task","Lifecycle alias to claim and set in-progress"]]);function renderFishCommandDescriptions(){return[...COMMAND_COMPLETION_DESCRIPTIONS,["ops","Workspace maintenance and diagnostics"]].filter(([command])=>command!=="help"&&!HIDDEN_COMMAND_ALIASES.has(command)).map(([command,description])=>{const fishDescription=FISH_COMMAND_DESCRIPTION_OVERRIDES.get(command)??description;return`complete -c pm -n __pm_no_subcommand -a ${command.padEnd(16)} -d '${fishDescription}'`}).join(`
|
|
2
2
|
`)}function renderFishRuntimeFieldFlagSpecs(commands,runtimeFlags){const normalizedFlags=normalizeRuntimeCompletionFlags(runtimeFlags).map(flag=>flag.slice(2));if(commands.length===0||normalizedFlags.length===0)return"";const lines=[];for(const command of commands){const predicate=NAMESPACE_NOUNS.includes(command)||PM_NAMESPACED_COMMAND_ALIASES.some(entry=>entry.alias===command)?"__pm_history_operation":"__fish_seen_subcommand_from";for(const flag of normalizedFlags)lines.push(`complete -c pm -n '${predicate} ${command}' -l '${escapeFishSource(flag)}' -d 'Runtime schema field flag' -r`)}return`${lines.join(`
|
|
3
3
|
`)}
|
|
4
4
|
`}function renderFishDynamicChoiceResolver(kind,command,fallback){const envKind=kind.toUpperCase(),escapedFallback=escapeFishSource(fallback);return`
|
|
@@ -384,6 +384,7 @@ complete -c pm -n '__fish_seen_subcommand_from files' -l apply -d 'Apply discove
|
|
|
384
384
|
complete -c pm -n '__fish_seen_subcommand_from files' -l note -d 'Linked-file note' -r
|
|
385
385
|
complete -c pm -n '__fish_seen_subcommand_from files' -l append-stable -d 'Preserve stable append ordering'
|
|
386
386
|
complete -c pm -n '__fish_seen_subcommand_from files' -l validate-paths -d 'Validate linked-file paths'
|
|
387
|
+
complete -c pm -n '__fish_seen_subcommand_from files' -l full-history -d 'Return every linked file after a write'
|
|
387
388
|
complete -c pm -n '__fish_seen_subcommand_from files' -l scope -d 'Filter lookup by evidence scope' -r -a 'project global'
|
|
388
389
|
complete -c pm -n '__fish_seen_subcommand_from files' -l limit -d 'Maximum lookup matches' -r
|
|
389
390
|
complete -c pm -n '__fish_seen_subcommand_from files' -l offset -d 'Skip the first lookup matches' -r
|
|
@@ -764,6 +765,7 @@ complete -c pm -n '__fish_seen_subcommand_from test' -l run -d 'Run linked tests
|
|
|
764
765
|
complete -c pm -n '__fish_seen_subcommand_from test' -l match -d 'Run linked tests whose command/path contains substring' -r
|
|
765
766
|
complete -c pm -n '__fish_seen_subcommand_from test' -l only-index -d 'Run one linked test by 1-based index' -r
|
|
766
767
|
complete -c pm -n '__fish_seen_subcommand_from test' -l only-last -d 'Run the most recently added linked test'
|
|
768
|
+
complete -c pm -n '__fish_seen_subcommand_from test' -l full-history -d 'Return every linked test after a write'
|
|
767
769
|
complete -c pm -n '__fish_seen_subcommand_from test' -l background -d 'Run linked tests in managed background mode'
|
|
768
770
|
complete -c pm -n '__fish_seen_subcommand_from test' -l timeout -d 'Default timeout seconds' -r
|
|
769
771
|
complete -c pm -n '__fish_seen_subcommand_from test' -l progress -d 'Emit linked-test progress to stderr'
|
|
@@ -1,4 +1,4 @@
|
|
|
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]="d0904776-3a38-5f70-8d95-cd31e0b120e2")}catch{}})();import{PM_NAMESPACED_COMMAND_ALIASES}from"../cli-contracts.js";import{SCAFFOLD_CAPABILITIES}from"../extension/scaffold.js";import{ATTEST_INVOCATIONS,COMMAND_COMPLETION_DESCRIPTIONS,EXTENSION_LIFECYCLE_ACTIONS,GLOBAL_COMPLETION_INLINE_PATTERNS,GLOBAL_COMPLETION_SWITCH_PATTERNS,GLOBAL_COMPLETION_VALUE_PATTERNS,GUIDE_TOPIC_CHOICES,HIDDEN_COMMAND_ALIASES,NAMESPACE_NOUNS,PACKAGE_LIFECYCLE_ACTIONS,RESTORE_INVOCATIONS,SCHEMA_SUBCOMMAND_CHOICES,completionNamespaceLeaves,completionStatusValues,completionTypeValues,joinCompletionValues,normalizeRuntimeCompletionFlags,shellDoubleQuote}from"./shared.js";function escapeZshStaticChoices(value){return value.replace(/([^a-zA-Z0-9_./\s-])/gu,"\\$1").replaceAll("'","'\\''")}function renderZshRuntimeFieldFlagSpecs(runtimeFlags){const normalized=normalizeRuntimeCompletionFlags(runtimeFlags);return normalized.length===0?"":`${normalized.map(flag=>` '${escapeZshStaticChoices(flag)}[Runtime schema field flag]:value' \\`).join(`
|
|
2
2
|
`)}
|
|
3
3
|
`}function renderZshArgumentSpecs(specs,options={}){const trailingContinuation=options.trailingContinuation??!0,lastSpecIndex=specs.length-1;return specs.map((spec,index)=>` ${spec}${trailingContinuation||index!==lastSpecIndex?" \\":""}`).join(`
|
|
4
4
|
`)}function renderZshCommandDescriptions(){return[...COMMAND_COMPLETION_DESCRIPTIONS,["ops","Workspace maintenance and diagnostics"]].filter(([command])=>!HIDDEN_COMMAND_ALIASES.has(command)).map(([command,description])=>` '${command}:${description}'`).join(`
|
|
@@ -756,6 +756,7 @@ ${renderZshArgumentSpecs(ATTEST_INVOCATIONS.map(flag=>`'${flag.flag}[${flag.desc
|
|
|
756
756
|
'--note[Linked-file note]:note' \\
|
|
757
757
|
'--append-stable[Preserve stable append ordering]' \\
|
|
758
758
|
'--validate-paths[Validate linked-file paths]' \\
|
|
759
|
+
'--full-history[Return every linked file after a write]' \\
|
|
759
760
|
'--scope[Filter lookup by evidence scope]:(project global)' \\
|
|
760
761
|
'--limit[Maximum lookup matches]:number' \\
|
|
761
762
|
'--offset[Skip the first lookup matches]:number' \\
|
|
@@ -815,6 +816,7 @@ ${renderZshArgumentSpecs(ATTEST_INVOCATIONS.map(flag=>`'${flag.flag}[${flag.desc
|
|
|
815
816
|
'--match[Run linked tests whose command/path contains substring]:substring' \\
|
|
816
817
|
'--only-index[Run one linked test by 1-based index]:number' \\
|
|
817
818
|
'--only-last[Run the most recently added linked test]' \\
|
|
819
|
+
'--full-history[Return every linked test after a write]' \\
|
|
818
820
|
'--background[Run linked tests in managed background mode]' \\
|
|
819
821
|
'--timeout[Default timeout seconds]:seconds' \\
|
|
820
822
|
'--progress[Emit linked-test progress to stderr]' \\
|
package/dist/sdk/docs.d.ts
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
*
|
|
4
4
|
* Implements the pm docs command surface and its agent-facing runtime behavior.
|
|
5
5
|
*/
|
|
6
|
-
import type{GlobalOptions}from "../core/shared/command-types.js";import type{LinkedDoc}from "../types/index.js";import{type LinkedPathValidation}from "./linked-artifacts.js";
|
|
6
|
+
import type{GlobalOptions}from "../core/shared/command-types.js";import type{LinkedDoc}from "../types/index.js";import{type LinkedCollectionMutationReceipt,type LinkedPathValidation}from "./linked-artifacts.js";import type{AnnotationOmissionReceipt}from "./annotations.js";
|
|
7
7
|
/** Documents the docs command options payload exchanged by command, SDK, and package integrations. */
|
|
8
8
|
export interface DocsCommandOptions{
|
|
9
9
|
/** Value that configures or reports add for this contract. */
|
|
@@ -20,6 +20,8 @@ note?:string;
|
|
|
20
20
|
list?:boolean;
|
|
21
21
|
/** Value that configures or reports validate paths for this contract. */
|
|
22
22
|
validatePaths?:boolean;
|
|
23
|
+
/** Return the complete linked collection after a write instead of the bounded mutation receipt (pm-gh1700). */
|
|
24
|
+
fullHistory?:boolean;
|
|
23
25
|
/** Value that configures or reports author for this contract. */
|
|
24
26
|
author?:string;
|
|
25
27
|
/** Human-readable explanation suitable for logs and agent-facing output. */
|
|
@@ -39,6 +41,16 @@ count:number;
|
|
|
39
41
|
/** Value that configures or reports migrations applied for this contract. */
|
|
40
42
|
migrations_applied?:number;
|
|
41
43
|
/** Value that configures or reports validation for this contract. */
|
|
42
|
-
validation?:LinkedPathValidation;
|
|
44
|
+
validation?:LinkedPathValidation;
|
|
45
|
+
/** Mutations only: entries stored after the write (pm-gh1700). */
|
|
46
|
+
total_count?:number;
|
|
47
|
+
/** Mutations only: entries this response carries. */
|
|
48
|
+
returned_count?:number;
|
|
49
|
+
/** Mutations only: whether stored entries exist beyond the ones returned. */
|
|
50
|
+
has_more?:boolean;
|
|
51
|
+
/** Mutations only: what the write changed. */
|
|
52
|
+
mutation_receipt?:LinkedCollectionMutationReceipt;
|
|
53
|
+
/** Mutations only: withheld entries and the selector that restores them. */
|
|
54
|
+
omission_receipt?:AnnotationOmissionReceipt;}
|
|
43
55
|
/** Implements run docs for the public runtime surface of this module. */
|
|
44
56
|
export declare function runDocs(id:string,options:DocsCommandOptions,global:GlobalOptions):Promise<DocsResult>;
|
package/dist/sdk/docs.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]="cd9a6f91-bfd8-5d14-a409-985bc9abfd31")}catch{}})();import{renameArtifactsResultKey,runLinkedArtifacts}from"./linked-artifacts.js";async function runDocs(id,options,global2){const result=await runLinkedArtifacts(id,options,global2,{metadataKey:"docs",op:"docs_add",bareNoun:"doc",supportsAppendStable:!1});return renameArtifactsResultKey(result,"docs")}export{runDocs};
|
|
2
2
|
//# sourceMappingURL=docs.js.map
|
package/dist/sdk/files.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type{GlobalOptions}from "../core/shared/command-types.js";import type{ItemDocument,LinkedFile,LinkScope}from "../types/index.js";import{type LinkedPathValidation}from "./linked-artifacts.js";import{type SourceLineRange,type SourceTraceabilityExplanation,type SourceTraceabilityReceipt}from "./traceability/source-traceability.js";
|
|
1
|
+
import type{GlobalOptions}from "../core/shared/command-types.js";import type{ItemDocument,LinkedFile,LinkScope}from "../types/index.js";import{type LinkedCollectionMutationReceipt,type LinkedPathValidation}from "./linked-artifacts.js";import type{AnnotationOmissionReceipt}from "./annotations.js";import{type SourceLineRange,type SourceTraceabilityExplanation,type SourceTraceabilityReceipt}from "./traceability/source-traceability.js";
|
|
2
2
|
/** Documents the files command options payload exchanged by command, SDK, and package integrations. */
|
|
3
3
|
export interface FilesCommandOptions{
|
|
4
4
|
/** Value that configures or reports add for this contract. */
|
|
@@ -17,6 +17,8 @@ list?:boolean;
|
|
|
17
17
|
appendStable?:boolean;
|
|
18
18
|
/** Value that configures or reports validate paths for this contract. */
|
|
19
19
|
validatePaths?:boolean;
|
|
20
|
+
/** Return the complete linked collection after a write instead of the bounded mutation receipt (pm-gh1700). */
|
|
21
|
+
fullHistory?:boolean;
|
|
20
22
|
/** Value that configures or reports author for this contract. */
|
|
21
23
|
author?:string;
|
|
22
24
|
/** Human-readable explanation suitable for logs and agent-facing output. */
|
|
@@ -64,7 +66,17 @@ count:number;
|
|
|
64
66
|
/** Value that configures or reports migrations applied for this contract. */
|
|
65
67
|
migrations_applied?:number;
|
|
66
68
|
/** Value that configures or reports validation for this contract. */
|
|
67
|
-
validation?:LinkedPathValidation;
|
|
69
|
+
validation?:LinkedPathValidation;
|
|
70
|
+
/** Mutations only: entries stored after the write (pm-gh1700). */
|
|
71
|
+
total_count?:number;
|
|
72
|
+
/** Mutations only: entries this response carries. */
|
|
73
|
+
returned_count?:number;
|
|
74
|
+
/** Mutations only: whether stored entries exist beyond the ones returned. */
|
|
75
|
+
has_more?:boolean;
|
|
76
|
+
/** Mutations only: what the write changed. */
|
|
77
|
+
mutation_receipt?:LinkedCollectionMutationReceipt;
|
|
78
|
+
/** Mutations only: withheld entries and the selector that restores them. */
|
|
79
|
+
omission_receipt?:AnnotationOmissionReceipt;}
|
|
68
80
|
/** Documents the files discover result payload exchanged by command, SDK, and package integrations. */
|
|
69
81
|
export interface FilesDiscoverResult{
|
|
70
82
|
/** Stable identifier used to reference this record across commands and storage. */
|
package/dist/sdk/files.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]="06b0bd73-d282-5473-a1da-f11c61a0a086")}catch{}})();import{assertInitializedTracker}from"./environment/tracker-preflight.js";import fs from"node:fs/promises";import path from"node:path";import{getActiveExtensionRegistrations,hasActiveOnReadHooks}from"../core/extensions/index.js";import{resolveItemTypeRegistry}from"../core/item/type-registry.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{locateItem,listAllItemMetadata,mutateItem,readLocatedItem}from"../core/store/item-store.js";import{readItemMetadataDerivedIndexState}from"../core/store/item-metadata-cache.js";import{queryLinkedFileMetadataIndex}from"../core/store/item-metadata-query-index.js";import{resolvePmRoot,resolveWorkspaceRoot}from"../core/store/paths.js";import{readSettings}from"../core/store/settings.js";import{resolveAuthor}from"../core/shared/author.js";import{isPathWithinDirectory}from"../core/fs/path-utils.js";import{dedupeLinkedArtifacts,normalizeLinkedPath,renameArtifactsResultKey,runLinkedArtifacts,sortLinkedArtifacts}from"./linked-artifacts.js";import{explainSourceTraceability}from"./traceability/source-traceability.js";const RELATIVE_REFERENCE_SCAN_MAX_CHARS=32768;function normalizeCandidatePathForOutput(value){return normalizeLinkedPath(path.normalize(value))}async function realpathForContainment(inputPath){try{return await fs.realpath(inputPath)}catch{return path.resolve(inputPath)}}function linkedFileResolvedKey(linkedFile,projectRoot){const resolvedPath=path.isAbsolute(linkedFile.path)?path.resolve(linkedFile.path):path.resolve(projectRoot,linkedFile.path);return`${normalizeCandidatePathForOutput(resolvedPath)}::${linkedFile.scope}`}function collectTextReferences(value,fieldPath,references){if(typeof value=="string"){const trimmed=value.trim();trimmed.length>0&&references.push({field:fieldPath,value:trimmed});return}if(Array.isArray(value)){value.forEach((entry,index)=>collectTextReferences(entry,`${fieldPath}[${index}]`,references));return}if(typeof value=="object"&&value!==null)for(const[key,nested]of Object.entries(value))collectTextReferences(nested,fieldPath?`${fieldPath}.${key}`:key,references)}function collectItemTextReferences(document){const references=[];return collectTextReferences(document.metadata,"metadata",references),collectTextReferences(document.body,"body",references),references}function cleanupPathToken(value){let next=value.trim();return next=next.replace(/^[`"'<([{]+/u,""),next=next.replace(/[`"'>)\]},;!?]+$/u,""),next=next.replace(/[.]+$/u,""),next=next.replace(/:(?:\d+)(?::\d+)?$/u,""),next=next.replace(/[.]+$/u,""),next}function extractRawPathReferences(references){const rawReferences=[],absolutePattern=/(?:[A-Za-z]:[\\/]|\/)[^\s"'`<>()[\]{},;]+/gu,relativePattern=/(?:\.{1,2}[\\/])?(?:(?:[A-Za-z0-9_.@-]+[\\/])+[A-Za-z0-9_.@-]+|[A-Za-z0-9_.@-]+\.[A-Za-z0-9][A-Za-z0-9._-]*)/gu;for(const reference of references){const seenInField=new Set,boundedRelativeValue=reference.value.slice(0,RELATIVE_REFERENCE_SCAN_MAX_CHARS);for(const[pattern,input]of[[absolutePattern,reference.value],[relativePattern,boundedRelativeValue]]){pattern.lastIndex=0;for(const match of input.matchAll(pattern)){const token=cleanupPathToken(match[0]);!token||seenInField.has(token)||(seenInField.add(token),rawReferences.push({field:reference.field,value:token}))}}}return rawReferences}async function resolveDiscoveredFile(rawPath,workspaceRoot,invocationRoot=workspaceRoot){const absolutePath=path.isAbsolute(rawPath)?path.resolve(rawPath):path.resolve(invocationRoot,rawPath);let stats;try{stats=await fs.stat(absolutePath)}catch{return}if(!stats.isFile())return;const[canonicalProjectRoot,canonicalAbsolutePath]=await Promise.all([realpathForContainment(workspaceRoot),realpathForContainment(absolutePath)]);if(isPathWithinDirectory(canonicalProjectRoot,canonicalAbsolutePath)){const relativePath=path.relative(canonicalProjectRoot,canonicalAbsolutePath);return!relativePath||relativePath.startsWith("..")||path.isAbsolute(relativePath)?void 0:{path:normalizeCandidatePathForOutput(relativePath),scope:"project"}}return{path:normalizeCandidatePathForOutput(absolutePath),scope:"global"}}async function discoverReferencedFiles(document,workspaceRoot,invocationRoot=workspaceRoot){const existingResolvedKeys=new Set((document.metadata.files??[]).map(entry=>linkedFileResolvedKey(entry,workspaceRoot))),grouped=new Map,rawReferences=extractRawPathReferences(collectItemTextReferences(document)),resolvedByValue=new Map;await Promise.all([...new Set(rawReferences.map(reference=>reference.value))].map(async value=>{resolvedByValue.set(value,await resolveDiscoveredFile(value,workspaceRoot,invocationRoot))}));const resolvedReferences=rawReferences.map(reference=>({reference,resolved:resolvedByValue.get(reference.value)}));for(const{reference,resolved}of resolvedReferences){if(!resolved)continue;const key=linkedFileResolvedKey(resolved,workspaceRoot),existing=grouped.get(key)??{path:resolved.path,scope:resolved.scope,sourceFields:new Set,originalPaths:new Set,sourceCount:0};existing.sourceFields.add(reference.field),existing.originalPaths.add(reference.value),existing.sourceCount+=1,grouped.set(key,existing)}return[...grouped.entries()].map(([key,entry])=>({path:entry.path,scope:entry.scope,status:existingResolvedKeys.has(key)?"already_linked":"addable",source_count:entry.sourceCount,source_fields:[...entry.sourceFields].sort((left,right)=>left.localeCompare(right)),original_paths:[...entry.originalPaths].sort((left,right)=>left.localeCompare(right))})).sort((left,right)=>{const byStatus=left.status.localeCompare(right.status);if(byStatus!==0)return byStatus;const byPath=left.path.localeCompare(right.path);return byPath!==0?byPath:left.scope.localeCompare(right.scope)})}const _testOnly={relativeReferenceScanMaxChars:RELATIVE_REFERENCE_SCAN_MAX_CHARS,normalizeCandidatePathForOutput,realpathForContainment,linkedFileResolvedKey,collectTextReferences,collectItemTextReferences,cleanupPathToken,extractRawPathReferences,resolveDiscoveredFile,discoverReferencedFiles};async function runFiles(id,options,global2){const result=await runLinkedArtifacts(id,options,global2,{metadataKey:"files",op:"files_add",bareNoun:"file",supportsAppendStable:!0});return renameArtifactsResultKey(result,"files")}async function normalizeFilesLookupPaths(values,workspaceRoot){const canonicalWorkspaceRoot=await realpathForContainment(workspaceRoot),paths=await Promise.all(values.map(async value=>{const trimmed=value.trim();if(!trimmed)throw new PmCliError("Files lookup paths must not be empty.",EXIT_CODE.USAGE);if(!path.isAbsolute(trimmed))return normalizeLinkedPath(trimmed);const canonicalAbsolutePath=await realpathForContainment(trimmed);return isPathWithinDirectory(canonicalWorkspaceRoot,canonicalAbsolutePath)?normalizeLinkedPath(path.relative(canonicalWorkspaceRoot,canonicalAbsolutePath)):normalizeLinkedPath(canonicalAbsolutePath)})),uniquePaths=[...new Set(paths)].sort((left,right)=>left.localeCompare(right));if(uniquePaths.length===0)throw new PmCliError("Files lookup requires at least one path.",EXIT_CODE.USAGE);return uniquePaths}function resolveFilesLookupWindow(options){for(const[label,value]of[["limit",options.limit],["offset",options.offset]])if(value!==void 0&&(!Number.isInteger(value)||value<0))throw new PmCliError(`Files lookup ${label} must be a non-negative integer.`,EXIT_CODE.USAGE);const{offset=0,limit=50}=options;return{offset:Math.max(0,Math.floor(offset)),limit:options.noTruncate?void 0:Math.max(0,Math.floor(limit))}}function projectFilesLookupItem(item){return{id:item.id,title:item.title,type:item.type,status:item.status,priority:item.priority,updated_at:item.updated_at}}function compareFilesLookupCandidates(left,right){const byPriority=left.item.priority-right.item.priority;if(byPriority!==0)return byPriority;const byUpdated=right.item.updated_at.localeCompare(left.item.updated_at);return byUpdated===0?left.item.id.localeCompare(right.item.id):byUpdated}function matchingFilesLookupCandidates(params){return params.metadata.map(item=>({item,files:(item.files??[]).filter(file=>params.paths.includes(normalizeLinkedPath(file.path))&&(params.scope===void 0||file.scope===params.scope)).sort((left,right)=>{const byPath=left.path.localeCompare(right.path);return byPath===0?left.scope.localeCompare(right.scope):byPath})})).filter(match=>match.files.length>0).sort(compareFilesLookupCandidates)}async function resolveFilesLookupTraceability(params){if(params.explain)return explainSourceTraceability({workspaceRoot:params.workspaceRoot,paths:params.paths,candidates:params.matching,corpus:params.metadata,...params.lineRange?{lineRange:params.lineRange}:{},...params.decisionDepth===void 0?{}:{decisionDepth:params.decisionDepth}})}async function queryFilesLookupIndex(params){if([params.strictRead,params.noTruncate,params.explain,hasActiveOnReadHooks()].includes(!0))return null;const indexState=await readItemMetadataDerivedIndexState(params.pmRoot,[...new Set(Object.values(params.typeToFolder))]);return indexState?queryLinkedFileMetadataIndex({pmRoot:params.pmRoot,expectedSourceCursor:indexState.source_cursor,paths:params.paths,scope:params.scope,limit:params.limit,offset:params.offset}):null}async function queryFilesLookupSource(params){const warnings=[],metadata=await listAllItemMetadata(params.pmRoot,params.settings.item_format,params.typeToFolder,warnings,params.settings.schema),matching=matchingFilesLookupCandidates({metadata,paths:params.paths,scope:params.scope}),readWarnings=warnings.filter(warning=>/^item_list_(?:item|directory)_read_failed:/u.test(warning));if(params.strictRead&&readWarnings.length>0)throw new PmCliError(`Files lookup could not read every item: ${readWarnings.join("; ")}`,EXIT_CODE.GENERIC_FAILURE);const traceability=await resolveFilesLookupTraceability({explain:params.explain,workspaceRoot:params.workspaceRoot,paths:params.paths,matching,metadata,lineRange:params.lineRange,decisionDepth:params.decisionDepth}),page=(traceability?[...matching].sort((left,right)=>{const byScore=traceability.explanations.get(right.item.id).score-traceability.explanations.get(left.item.id).score;return byScore!==0?byScore:compareFilesLookupCandidates(left,right)}):matching).slice(params.offset,params.limit===void 0?void 0:params.offset+params.limit);return{paths:params.paths,total:matching.length,count:page.length,offset:params.offset,limit:params.limit??null,has_more:params.offset+page.length<matching.length,truncated:params.offset+page.length<matching.length,completeness:{status:readWarnings.length===0?"complete":"partial",source:"source_scan"},warnings,matches:page.map(match=>({item:projectFilesLookupItem(match.item),files:match.files,...traceability?{traceability:traceability.explanations.get(match.item.id)}:{}})),...traceability?{traceability_receipt:traceability.receipt}:{}}}async function runFilesLookup(options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path),workspaceRoot=resolveWorkspaceRoot(pmRoot);await assertInitializedTracker(pmRoot);const paths=await normalizeFilesLookupPaths(options.paths,workspaceRoot);if(options.lineRange&&paths.length!==1)throw new PmCliError("Files lookup line attribution requires exactly one source path.",EXIT_CODE.USAGE);const settings=await readSettings(pmRoot),typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()),{offset,limit}=resolveFilesLookupWindow(options),indexed=await queryFilesLookupIndex({pmRoot,typeToFolder:typeRegistry.type_to_folder,paths,scope:options.scope,limit,offset,strictRead:options.strictRead===!0,noTruncate:options.noTruncate===!0,explain:options.explain===!0||options.lineRange!==void 0});return indexed?{paths,total:indexed.total,count:indexed.matches.length,offset,limit,has_more:offset+indexed.matches.length<indexed.total,truncated:offset+indexed.matches.length<indexed.total,completeness:{status:"unchecked",source:"index"},warnings:[],matches:indexed.matches.map(match=>({item:projectFilesLookupItem(match.item),files:match.files}))}:queryFilesLookupSource({pmRoot,settings,typeToFolder:typeRegistry.type_to_folder,paths,scope:options.scope,limit,offset,strictRead:options.strictRead===!0,workspaceRoot,explain:options.explain===!0||options.lineRange!==void 0,lineRange:options.lineRange,decisionDepth:options.decisionDepth})}async function runFilesDiscover(id,options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path),workspaceRoot=resolveWorkspaceRoot(pmRoot);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot),typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()),located=await locateItem(pmRoot,id,settings.id_prefix,settings.item_format,typeRegistry.type_to_folder);if(!located)throw new PmCliError(`Item ${id} not found`,EXIT_CODE.NOT_FOUND);const loaded=await readLocatedItem(located,{schema:settings.schema}),candidates=await discoverReferencedFiles(loaded.document,workspaceRoot,process.cwd()),addableCandidates=candidates.filter(candidate=>candidate.status==="addable"),skippedExisting=candidates.filter(candidate=>candidate.status==="already_linked"),requestedApply=options.apply===!0,note=options.note?.trim()||"discovered from item text";if(!requestedApply||addableCandidates.length===0){const files2=loaded.document.metadata.files??[];return{id:located.id,files:files2,changed:!1,apply:requestedApply,count:files2.length,candidate_count:candidates.length,addable_count:addableCandidates.length,added_count:0,skipped_existing_count:skippedExisting.length,candidates,added:[],skipped_existing:skippedExisting}}const author=resolveAuthor(options.author,settings.author_default),discoveredAdds=addableCandidates.map(candidate=>({path:candidate.path,scope:candidate.scope,note}));let appliedAdds=[];const appliedCandidateIndices=new Set,result=await mutateItem({pmRoot,settings,id,op:"files_discover",author,message:options.message??"Discover referenced file links",force:options.force,mutate(document){const next=[...document.metadata.files??[]],existingResolvedKeys=new Set(next.map(entry=>linkedFileResolvedKey(entry,workspaceRoot)));appliedAdds=[],appliedCandidateIndices.clear();for(const[index,add]of discoveredAdds.entries()){const resolvedKey=linkedFileResolvedKey(add,workspaceRoot);existingResolvedKeys.has(resolvedKey)||(next.push(add),existingResolvedKeys.add(resolvedKey),appliedAdds.push(add),appliedCandidateIndices.add(index))}const deduped=dedupeLinkedArtifacts(next),normalized=options.appendStable?deduped:sortLinkedArtifacts(deduped);return normalized.length>0?document.metadata.files=normalized:delete document.metadata.files,{changedFields:appliedAdds.length>0?["files"]:[],warnings:appliedAdds.length!==discoveredAdds.length?[`files_discover_skipped_existing:${discoveredAdds.length-appliedAdds.length}`]:[]}}}),files=result.item.files??[],addedResolvedKeys=new Set(appliedAdds.map(entry=>linkedFileResolvedKey(entry,workspaceRoot))),added=files.filter(entry=>addedResolvedKeys.has(linkedFileResolvedKey(entry,workspaceRoot))),skippedDuringApply=addableCandidates.filter((_candidate,index)=>!appliedCandidateIndices.has(index)),allSkippedExisting=[...skippedExisting,...skippedDuringApply];return{id:result.item.id,files,changed:added.length>0,apply:!0,count:files.length,candidate_count:candidates.length,addable_count:addableCandidates.length,added_count:added.length,skipped_existing_count:allSkippedExisting.length,candidates,added,skipped_existing:allSkippedExisting}}export{_testOnly,runFiles,runFilesDiscover,runFilesLookup};
|
|
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]="b78d1abc-716f-51a6-a6c2-ab8382eb12e4")}catch{}})();import{assertInitializedTracker}from"./environment/tracker-preflight.js";import fs from"node:fs/promises";import path from"node:path";import{getActiveExtensionRegistrations,hasActiveOnReadHooks}from"../core/extensions/index.js";import{resolveItemTypeRegistry}from"../core/item/type-registry.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{locateItem,listAllItemMetadata,mutateItem,readLocatedItem}from"../core/store/item-store.js";import{readItemMetadataDerivedIndexState}from"../core/store/item-metadata-cache.js";import{queryLinkedFileMetadataIndex}from"../core/store/item-metadata-query-index.js";import{resolvePmRoot,resolveWorkspaceRoot}from"../core/store/paths.js";import{readSettings}from"../core/store/settings.js";import{resolveAuthor}from"../core/shared/author.js";import{isPathWithinDirectory}from"../core/fs/path-utils.js";import{dedupeLinkedArtifacts,normalizeLinkedPath,renameArtifactsResultKey,runLinkedArtifacts,sortLinkedArtifacts}from"./linked-artifacts.js";import{explainSourceTraceability}from"./traceability/source-traceability.js";const RELATIVE_REFERENCE_SCAN_MAX_CHARS=32768;function normalizeCandidatePathForOutput(value){return normalizeLinkedPath(path.normalize(value))}async function realpathForContainment(inputPath){try{return await fs.realpath(inputPath)}catch{return path.resolve(inputPath)}}function linkedFileResolvedKey(linkedFile,projectRoot){const resolvedPath=path.isAbsolute(linkedFile.path)?path.resolve(linkedFile.path):path.resolve(projectRoot,linkedFile.path);return`${normalizeCandidatePathForOutput(resolvedPath)}::${linkedFile.scope}`}function collectTextReferences(value,fieldPath,references){if(typeof value=="string"){const trimmed=value.trim();trimmed.length>0&&references.push({field:fieldPath,value:trimmed});return}if(Array.isArray(value)){value.forEach((entry,index)=>collectTextReferences(entry,`${fieldPath}[${index}]`,references));return}if(typeof value=="object"&&value!==null)for(const[key,nested]of Object.entries(value))collectTextReferences(nested,fieldPath?`${fieldPath}.${key}`:key,references)}function collectItemTextReferences(document){const references=[];return collectTextReferences(document.metadata,"metadata",references),collectTextReferences(document.body,"body",references),references}function cleanupPathToken(value){let next=value.trim();return next=next.replace(/^[`"'<([{]+/u,""),next=next.replace(/[`"'>)\]},;!?]+$/u,""),next=next.replace(/[.]+$/u,""),next=next.replace(/:(?:\d+)(?::\d+)?$/u,""),next=next.replace(/[.]+$/u,""),next}function extractRawPathReferences(references){const rawReferences=[],absolutePattern=/(?:[A-Za-z]:[\\/]|\/)[^\s"'`<>()[\]{},;]+/gu,relativePattern=/(?:\.{1,2}[\\/])?(?:(?:[A-Za-z0-9_.@-]+[\\/])+[A-Za-z0-9_.@-]+|[A-Za-z0-9_.@-]+\.[A-Za-z0-9][A-Za-z0-9._-]*)/gu;for(const reference of references){const seenInField=new Set,boundedRelativeValue=reference.value.slice(0,RELATIVE_REFERENCE_SCAN_MAX_CHARS);for(const[pattern,input]of[[absolutePattern,reference.value],[relativePattern,boundedRelativeValue]]){pattern.lastIndex=0;for(const match of input.matchAll(pattern)){const token=cleanupPathToken(match[0]);!token||seenInField.has(token)||(seenInField.add(token),rawReferences.push({field:reference.field,value:token}))}}}return rawReferences}async function resolveDiscoveredFile(rawPath,workspaceRoot,invocationRoot=workspaceRoot){const absolutePath=path.isAbsolute(rawPath)?path.resolve(rawPath):path.resolve(invocationRoot,rawPath);let stats;try{stats=await fs.stat(absolutePath)}catch{return}if(!stats.isFile())return;const[canonicalProjectRoot,canonicalAbsolutePath]=await Promise.all([realpathForContainment(workspaceRoot),realpathForContainment(absolutePath)]);if(isPathWithinDirectory(canonicalProjectRoot,canonicalAbsolutePath)){const relativePath=path.relative(canonicalProjectRoot,canonicalAbsolutePath);return!relativePath||relativePath.startsWith("..")||path.isAbsolute(relativePath)?void 0:{path:normalizeCandidatePathForOutput(relativePath),scope:"project"}}return{path:normalizeCandidatePathForOutput(absolutePath),scope:"global"}}async function discoverReferencedFiles(document,workspaceRoot,invocationRoot=workspaceRoot){const existingResolvedKeys=new Set((document.metadata.files??[]).map(entry=>linkedFileResolvedKey(entry,workspaceRoot))),grouped=new Map,rawReferences=extractRawPathReferences(collectItemTextReferences(document)),resolvedByValue=new Map;await Promise.all([...new Set(rawReferences.map(reference=>reference.value))].map(async value=>{resolvedByValue.set(value,await resolveDiscoveredFile(value,workspaceRoot,invocationRoot))}));const resolvedReferences=rawReferences.map(reference=>({reference,resolved:resolvedByValue.get(reference.value)}));for(const{reference,resolved}of resolvedReferences){if(!resolved)continue;const key=linkedFileResolvedKey(resolved,workspaceRoot),existing=grouped.get(key)??{path:resolved.path,scope:resolved.scope,sourceFields:new Set,originalPaths:new Set,sourceCount:0};existing.sourceFields.add(reference.field),existing.originalPaths.add(reference.value),existing.sourceCount+=1,grouped.set(key,existing)}return[...grouped.entries()].map(([key,entry])=>({path:entry.path,scope:entry.scope,status:existingResolvedKeys.has(key)?"already_linked":"addable",source_count:entry.sourceCount,source_fields:[...entry.sourceFields].sort((left,right)=>left.localeCompare(right)),original_paths:[...entry.originalPaths].sort((left,right)=>left.localeCompare(right))})).sort((left,right)=>{const byStatus=left.status.localeCompare(right.status);if(byStatus!==0)return byStatus;const byPath=left.path.localeCompare(right.path);return byPath!==0?byPath:left.scope.localeCompare(right.scope)})}const _testOnly={relativeReferenceScanMaxChars:RELATIVE_REFERENCE_SCAN_MAX_CHARS,normalizeCandidatePathForOutput,realpathForContainment,linkedFileResolvedKey,collectTextReferences,collectItemTextReferences,cleanupPathToken,extractRawPathReferences,resolveDiscoveredFile,discoverReferencedFiles};async function runFiles(id,options,global2){const result=await runLinkedArtifacts(id,options,global2,{metadataKey:"files",op:"files_add",bareNoun:"file",supportsAppendStable:!0});return renameArtifactsResultKey(result,"files")}async function normalizeFilesLookupPaths(values,workspaceRoot){const canonicalWorkspaceRoot=await realpathForContainment(workspaceRoot),paths=await Promise.all(values.map(async value=>{const trimmed=value.trim();if(!trimmed)throw new PmCliError("Files lookup paths must not be empty.",EXIT_CODE.USAGE);if(!path.isAbsolute(trimmed))return normalizeLinkedPath(trimmed);const canonicalAbsolutePath=await realpathForContainment(trimmed);return isPathWithinDirectory(canonicalWorkspaceRoot,canonicalAbsolutePath)?normalizeLinkedPath(path.relative(canonicalWorkspaceRoot,canonicalAbsolutePath)):normalizeLinkedPath(canonicalAbsolutePath)})),uniquePaths=[...new Set(paths)].sort((left,right)=>left.localeCompare(right));if(uniquePaths.length===0)throw new PmCliError("Files lookup requires at least one path.",EXIT_CODE.USAGE);return uniquePaths}function resolveFilesLookupWindow(options){for(const[label,value]of[["limit",options.limit],["offset",options.offset]])if(value!==void 0&&(!Number.isInteger(value)||value<0))throw new PmCliError(`Files lookup ${label} must be a non-negative integer.`,EXIT_CODE.USAGE);const{offset=0,limit=50}=options;return{offset:Math.max(0,Math.floor(offset)),limit:options.noTruncate?void 0:Math.max(0,Math.floor(limit))}}function projectFilesLookupItem(item){return{id:item.id,title:item.title,type:item.type,status:item.status,priority:item.priority,updated_at:item.updated_at}}function compareFilesLookupCandidates(left,right){const byPriority=left.item.priority-right.item.priority;if(byPriority!==0)return byPriority;const byUpdated=right.item.updated_at.localeCompare(left.item.updated_at);return byUpdated===0?left.item.id.localeCompare(right.item.id):byUpdated}function matchingFilesLookupCandidates(params){return params.metadata.map(item=>({item,files:(item.files??[]).filter(file=>params.paths.includes(normalizeLinkedPath(file.path))&&(params.scope===void 0||file.scope===params.scope)).sort((left,right)=>{const byPath=left.path.localeCompare(right.path);return byPath===0?left.scope.localeCompare(right.scope):byPath})})).filter(match=>match.files.length>0).sort(compareFilesLookupCandidates)}async function resolveFilesLookupTraceability(params){if(params.explain)return explainSourceTraceability({workspaceRoot:params.workspaceRoot,paths:params.paths,candidates:params.matching,corpus:params.metadata,...params.lineRange?{lineRange:params.lineRange}:{},...params.decisionDepth===void 0?{}:{decisionDepth:params.decisionDepth}})}async function queryFilesLookupIndex(params){if([params.strictRead,params.noTruncate,params.explain,hasActiveOnReadHooks()].includes(!0))return null;const indexState=await readItemMetadataDerivedIndexState(params.pmRoot,[...new Set(Object.values(params.typeToFolder))]);return indexState?queryLinkedFileMetadataIndex({pmRoot:params.pmRoot,expectedSourceCursor:indexState.source_cursor,paths:params.paths,scope:params.scope,limit:params.limit,offset:params.offset}):null}async function queryFilesLookupSource(params){const warnings=[],metadata=await listAllItemMetadata(params.pmRoot,params.settings.item_format,params.typeToFolder,warnings,params.settings.schema),matching=matchingFilesLookupCandidates({metadata,paths:params.paths,scope:params.scope}),readWarnings=warnings.filter(warning=>/^item_list_(?:item|directory)_read_failed:/u.test(warning));if(params.strictRead&&readWarnings.length>0)throw new PmCliError(`Files lookup could not read every item: ${readWarnings.join("; ")}`,EXIT_CODE.GENERIC_FAILURE);const traceability=await resolveFilesLookupTraceability({explain:params.explain,workspaceRoot:params.workspaceRoot,paths:params.paths,matching,metadata,lineRange:params.lineRange,decisionDepth:params.decisionDepth}),page=(traceability?[...matching].sort((left,right)=>{const byScore=traceability.explanations.get(right.item.id).score-traceability.explanations.get(left.item.id).score;return byScore!==0?byScore:compareFilesLookupCandidates(left,right)}):matching).slice(params.offset,params.limit===void 0?void 0:params.offset+params.limit);return{paths:params.paths,total:matching.length,count:page.length,offset:params.offset,limit:params.limit??null,has_more:params.offset+page.length<matching.length,truncated:params.offset+page.length<matching.length,completeness:{status:readWarnings.length===0?"complete":"partial",source:"source_scan"},warnings,matches:page.map(match=>({item:projectFilesLookupItem(match.item),files:match.files,...traceability?{traceability:traceability.explanations.get(match.item.id)}:{}})),...traceability?{traceability_receipt:traceability.receipt}:{}}}async function runFilesLookup(options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path),workspaceRoot=resolveWorkspaceRoot(pmRoot);await assertInitializedTracker(pmRoot);const paths=await normalizeFilesLookupPaths(options.paths,workspaceRoot);if(options.lineRange&&paths.length!==1)throw new PmCliError("Files lookup line attribution requires exactly one source path.",EXIT_CODE.USAGE);const settings=await readSettings(pmRoot),typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()),{offset,limit}=resolveFilesLookupWindow(options),indexed=await queryFilesLookupIndex({pmRoot,typeToFolder:typeRegistry.type_to_folder,paths,scope:options.scope,limit,offset,strictRead:options.strictRead===!0,noTruncate:options.noTruncate===!0,explain:options.explain===!0||options.lineRange!==void 0});return indexed?{paths,total:indexed.total,count:indexed.matches.length,offset,limit,has_more:offset+indexed.matches.length<indexed.total,truncated:offset+indexed.matches.length<indexed.total,completeness:{status:"unchecked",source:"index"},warnings:[],matches:indexed.matches.map(match=>({item:projectFilesLookupItem(match.item),files:match.files}))}:queryFilesLookupSource({pmRoot,settings,typeToFolder:typeRegistry.type_to_folder,paths,scope:options.scope,limit,offset,strictRead:options.strictRead===!0,workspaceRoot,explain:options.explain===!0||options.lineRange!==void 0,lineRange:options.lineRange,decisionDepth:options.decisionDepth})}async function runFilesDiscover(id,options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path),workspaceRoot=resolveWorkspaceRoot(pmRoot);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot),typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()),located=await locateItem(pmRoot,id,settings.id_prefix,settings.item_format,typeRegistry.type_to_folder);if(!located)throw new PmCliError(`Item ${id} not found`,EXIT_CODE.NOT_FOUND);const loaded=await readLocatedItem(located,{schema:settings.schema}),candidates=await discoverReferencedFiles(loaded.document,workspaceRoot,process.cwd()),addableCandidates=candidates.filter(candidate=>candidate.status==="addable"),skippedExisting=candidates.filter(candidate=>candidate.status==="already_linked"),requestedApply=options.apply===!0,note=options.note?.trim()||"discovered from item text";if(!requestedApply||addableCandidates.length===0){const files2=loaded.document.metadata.files??[];return{id:located.id,files:files2,changed:!1,apply:requestedApply,count:files2.length,candidate_count:candidates.length,addable_count:addableCandidates.length,added_count:0,skipped_existing_count:skippedExisting.length,candidates,added:[],skipped_existing:skippedExisting}}const author=resolveAuthor(options.author,settings.author_default),discoveredAdds=addableCandidates.map(candidate=>({path:candidate.path,scope:candidate.scope,note}));let appliedAdds=[];const appliedCandidateIndices=new Set,result=await mutateItem({pmRoot,settings,id,op:"files_discover",author,message:options.message??"Discover referenced file links",force:options.force,mutate(document){const next=[...document.metadata.files??[]],existingResolvedKeys=new Set(next.map(entry=>linkedFileResolvedKey(entry,workspaceRoot)));appliedAdds=[],appliedCandidateIndices.clear();for(const[index,add]of discoveredAdds.entries()){const resolvedKey=linkedFileResolvedKey(add,workspaceRoot);existingResolvedKeys.has(resolvedKey)||(next.push(add),existingResolvedKeys.add(resolvedKey),appliedAdds.push(add),appliedCandidateIndices.add(index))}const deduped=dedupeLinkedArtifacts(next),normalized=options.appendStable?deduped:sortLinkedArtifacts(deduped);return normalized.length>0?document.metadata.files=normalized:delete document.metadata.files,{changedFields:appliedAdds.length>0?["files"]:[],warnings:appliedAdds.length!==discoveredAdds.length?[`files_discover_skipped_existing:${discoveredAdds.length-appliedAdds.length}`]:[]}}}),files=result.item.files??[],addedResolvedKeys=new Set(appliedAdds.map(entry=>linkedFileResolvedKey(entry,workspaceRoot))),added=files.filter(entry=>addedResolvedKeys.has(linkedFileResolvedKey(entry,workspaceRoot))),skippedDuringApply=addableCandidates.filter((_candidate,index)=>!appliedCandidateIndices.has(index)),allSkippedExisting=[...skippedExisting,...skippedDuringApply];return{id:result.item.id,files,changed:added.length>0,apply:!0,count:files.length,candidate_count:candidates.length,addable_count:addableCandidates.length,added_count:added.length,skipped_existing_count:allSkippedExisting.length,candidates,added,skipped_existing:allSkippedExisting}}export{_testOnly,runFiles,runFilesDiscover,runFilesLookup};
|
|
2
2
|
//# sourceMappingURL=files.js.map
|