@unbrained/pm-cli 2026.10.15 → 2026.10.17
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-developer/references/COMMAND_PLAYBOOK.md +1 -1
- package/.claude-plugin/marketplace.json +1 -1
- package/AGENTS.md +1 -0
- package/CHANGELOG.md +20 -0
- package/dist/cli/extension-command-options.d.ts +3 -1
- package/dist/cli/extension-command-options.js +1 -1
- package/dist/cli/help-content.js +2 -2
- package/dist/cli/register-mutation.js +2 -2
- package/dist/cli/register-operations.js +1 -1
- package/dist/cli/register-structured-mutation.d.ts +0 -5
- package/dist/cli/register-structured-mutation.js +1 -1
- package/dist/cli/runtime/invocation-options.js +1 -1
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/{chunk-7VHINXZP.js → chunk-3QKI3XNX.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-4PNPDT2N.js +236 -0
- package/dist/cli-bundle/chunks/{chunk-WBBW3WQX.js → chunk-6ZDKKOKM.js} +28 -28
- package/dist/cli-bundle/chunks/{chunk-LNKLQYBG.js → chunk-B5QVGCZX.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-52EZH2QQ.js → chunk-EA2CG7UM.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-HY7FQ7QX.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-NC3QVGDD.js → chunk-J4LPQCET.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-JGKTOBVB.js → chunk-JS3B2M4D.js} +4 -4
- package/dist/cli-bundle/chunks/chunk-O4YBC3OM.js +30 -0
- package/dist/cli-bundle/chunks/{chunk-N56CAQBU.js → chunk-OZCSXX4D.js} +52 -52
- package/dist/cli-bundle/chunks/chunk-VMCSTFSO.js +2 -0
- package/dist/cli-bundle/chunks/chunk-W3KZ22DW.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-RJ5N44WY.js → chunk-X2ONXFBP.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-7OEGNA4X.js → chunk-X53HM753.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-FKKFQ66D.js → register-list-query-RU3QZSAQ.js} +2 -2
- package/dist/cli-bundle/chunks/register-mutation-EQYMT32A.js +20 -0
- package/dist/cli-bundle/chunks/{register-operations-GEQ2H7PS.js → register-operations-VXBGE4XI.js} +2 -2
- package/dist/cli-bundle/chunks/{register-setup-PSJTQBBO.js → register-setup-UUDEGFRO.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-TYLG5VEB.js → chunk-2IOHHNRT.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-PDYE7QDX.js → chunk-5JEFDEL3.js} +30 -30
- package/dist/cli-bundle/focused-chunks/{chunk-3RNUMVK4.js → chunk-AH6NX6GM.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-N6FUKTZS.js → chunk-E33QA7PK.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-4KQFMOM7.js → chunk-FTUZ3JF2.js} +5 -5
- package/dist/cli-bundle/focused-chunks/{chunk-5OO54BIV.js → chunk-JXR6UKFM.js} +3 -3
- package/dist/cli-bundle/focused-chunks/chunk-LDKX4KYJ.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-H3P77KVU.js → chunk-MBQF6HT6.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-5TBAVZDR.js → chunk-NZO7GOXD.js} +14 -14
- package/dist/cli-bundle/focused-chunks/{chunk-52I2SNKJ.js → chunk-PYC7BF6Z.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-THYQR3ON.js → chunk-QOSVJDOO.js} +59 -59
- package/dist/cli-bundle/focused-chunks/{chunk-FQKPOZKS.js → chunk-RBLSY6ML.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-Q4VNCTR2.js → chunk-RHTH5ILM.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-5KRACGBK.js → chunk-SIGIGZCG.js} +3 -3
- package/dist/cli-bundle/focused-chunks/chunk-TRFVAWF2.js +26 -0
- package/dist/cli-bundle/focused-chunks/{chunk-KIIFVULU.js → chunk-UNTQE37U.js} +2 -2
- package/dist/cli-bundle/main.js +27 -27
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +2 -2
- package/dist/cli-bundle/sdk-core.js +23 -23
- package/dist/cli-bundle/sdk-governance.js +1 -1
- package/dist/cli-bundle/sdk-graph.js +1 -1
- package/dist/cli-bundle/sdk-merge.js +54 -54
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +7 -7
- package/dist/core/extensions/extension-types.d.ts +15 -0
- package/dist/core/extensions/extension-types.js +1 -1
- package/dist/core/extensions/flag-value-types.d.ts +16 -0
- package/dist/core/extensions/flag-value-types.js +1 -1
- package/dist/core/extensions/registration-contracts.js +1 -1
- package/dist/core/item/item-format.js +3 -3
- package/dist/core/output/mutation-projection.d.ts +0 -21
- package/dist/core/output/mutation-projection.js +1 -1
- package/dist/core/schema/type-workflows.d.ts +1 -1
- package/dist/core/schema/type-workflows.js +1 -1
- package/dist/core/shared/text-normalization.d.ts +2 -0
- package/dist/core/shared/text-normalization.js +1 -1
- package/dist/core/store/item-mutation-precondition.d.ts +11 -0
- package/dist/core/store/item-mutation-precondition.js +2 -0
- package/dist/core/store/item-store.js +1 -1
- package/dist/mcp/server.js +1 -1
- package/dist/mcp/tool-definitions.js +1 -1
- package/dist/sdk/cli-contracts/agent-output-contracts.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/registration-helpers.d.ts +1 -1
- package/dist/sdk/cli-contracts/registration-helpers.js +1 -1
- package/dist/sdk/cli-contracts/tool-schema.d.ts +2 -2
- package/dist/sdk/cli-contracts/tool-schema.js +1 -1
- package/dist/sdk/context-intent-contracts.js +1 -1
- package/dist/sdk/core.d.ts +2 -1
- package/dist/sdk/core.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/guide-topics.js +1 -1
- package/dist/sdk/index.d.ts +2 -1
- package/dist/sdk/index.js +1 -1
- package/dist/sdk/item-transaction.d.ts +72 -9
- package/dist/sdk/item-transaction.js +1 -1
- package/dist/sdk/lifecycle/claim.d.ts +15 -1
- package/dist/sdk/lifecycle/claim.js +1 -1
- package/dist/sdk/lifecycle/close.d.ts +2 -8
- package/dist/sdk/lifecycle/close.js +1 -1
- package/dist/sdk/lifecycle/core-item-fields.d.ts +6 -0
- package/dist/sdk/lifecycle/core-item-fields.js +2 -0
- package/dist/sdk/lifecycle/mcp-actions.js +1 -1
- package/dist/sdk/lifecycle/mutation-option-validation.d.ts +2 -0
- package/dist/sdk/lifecycle/mutation-option-validation.js +2 -0
- package/dist/sdk/lifecycle/release-handoff.d.ts +12 -0
- package/dist/sdk/lifecycle/release-handoff.js +2 -0
- package/dist/sdk/lifecycle/structured-mutation-plan.d.ts +33 -0
- package/dist/sdk/lifecycle/structured-mutation-plan.js +2 -0
- package/dist/sdk/lifecycle/task-composition.d.ts +2 -2
- package/dist/sdk/lifecycle/task-composition.js +1 -1
- package/dist/sdk/lifecycle/update.d.ts +3 -11
- package/dist/sdk/lifecycle/update.js +1 -1
- package/dist/sdk/lifecycle/workflow-transition.d.ts +13 -0
- package/dist/sdk/lifecycle/workflow-transition.js +2 -0
- package/dist/sdk/lifecycle-policy.d.ts +12 -2
- package/dist/sdk/lifecycle-policy.js +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/read-output-budget.js +1 -1
- package/dist/sdk/runtime-input.js +1 -1
- package/dist/sdk/runtime-primitives.d.ts +1 -1
- package/dist/sdk/runtime-primitives.js +1 -1
- package/dist/sdk/runtime.d.ts +8 -8
- package/dist/sdk/runtime.js +1 -1
- package/dist/sdk/structured-mutations.d.ts +52 -1
- package/dist/sdk/structured-mutations.js +1 -1
- package/dist/sdk/workspace-transaction.js +2 -2
- package/docs/AGENT_GUIDE.md +33 -4
- package/docs/CLOSE_EVIDENCE_RECOVERY.md +16 -7
- package/docs/COMMANDS.md +85 -10
- package/docs/ECOSYSTEM_PLANNING_REVIEW.md +5 -1
- package/docs/EXTENSIONS.md +1 -1
- package/docs/SDK.md +114 -2
- package/docs/TESTING.md +15 -0
- package/docs/generated/FLAG_LEXICON_BUDGETS.md +1 -1
- package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +16 -3
- package/marketplace.json +1 -1
- package/package.json +2 -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-EMEEHV2Y.js +0 -2
- package/dist/cli-bundle/chunks/chunk-JSUJWIHQ.js +0 -30
- package/dist/cli-bundle/chunks/chunk-VIMQCFCK.js +0 -2
- package/dist/cli-bundle/chunks/chunk-X2H6UR26.js +0 -236
- package/dist/cli-bundle/chunks/register-mutation-EWMMVZJB.js +0 -20
- package/dist/cli-bundle/focused-chunks/chunk-HTA3TNC3.js +0 -26
- package/dist/cli-bundle/focused-chunks/chunk-JKBH7YGX.js +0 -2
- package/docs/ecosystem-review-2026-09-28.json +0 -1
|
@@ -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]="75d742ab-22c4-5a3f-8f63-74c68afa6b3f")}catch{}})();import fs from"node:fs/promises";import{buildDeletedItemError}from"../history/tombstone.js";import{normalizeHistoryOperationForWrite}from"../history/operation-contract.js";import{enforceWorkflowMutation}from"../policy/workflow-policy-store.js";import{recordItemMetadataEnumeration}from"./item-metadata-read-work.js";import path from"node:path";import{getActiveExtensionRegistrations,projectAfterCommandItemSnapshot,recordAfterCommandAffectedItem,runActiveOnReadHooks,runActiveBeforeMutationHooks,runActiveOnWriteHooks,runActiveServiceOverride}from"../extensions/index.js";import{collectRegisteredItemFieldNames}from"../extensions/item-fields.js";import{EMPTY_CANONICAL_DOCUMENT,EXIT_CODE,TYPE_TO_FOLDER}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{levenshteinDistanceWithinLimit}from"../shared/levenshtein.js";import{appendHistoryEntry,createHistoryEntry}from"../history/history.js";import{enforceHistoryStreamPolicyForItem}from"../history/history-stream-policy.js";import{canonicalDocument,parseItemDocument,serializeItemDocument}from"../item/item-format.js";import{resolveItemTypeRegistry}from"../item/type-registry.js";import{effectiveItemFormatVersion,requiredItemFormatVersion}from"../item/item-format-version.js";import{assertProjectRuntimeFormatGuard}from"../../sdk/environment/project-runtime-compatibility.js";import{acquireLock}from"../lock/lock.js";import{writeFileAtomic}from"../fs/fs-utils.js";import{isUtf8}from"node:buffer";import{normalizeItemId,normalizeRawItemId}from"../item/id.js";import{acquireItemMetadataDerivedIndexLock,listAllDocumentCandidatesCached,listAllDocumentsCached,listAllDocumentsCachedLight,refreshItemMetadataDerivedIndex}from"./item-metadata-cache.js";import{getHistoryPath,getItemPath,ITEM_FILE_EXTENSIONS,resolveWorkspaceRoot}from"./paths.js";import{resolveGovernanceKnobs}from"./settings.js";import{assertReadableTrackerRoot}from"./tracker-preflight.js";import{resolveClaimPrincipal}from"../shared/author.js";import{nowIso}from"../shared/time.js";async function fileExists(targetPath){try{return await fs.access(targetPath),!0}catch{return!1}}function isErrno(error,code){return typeof error=="object"&&error!==null&&"code"in error&&error.code===code}function appendWarning(warnings,warning){warnings&&(warnings.includes(warning)||warnings.push(warning))}function resolveActiveExtensionFieldNames(explicit){return explicit??collectRegisteredItemFieldNames(getActiveExtensionRegistrations())}function resolveItemFormatSearchOrder(preferredFormat){return preferredFormat==="toon"?["toon","json_markdown"]:preferredFormat==="json_markdown"?["json_markdown","toon"]:["toon","json_markdown"]}async function locateItem(pmRoot,rawId,idPrefix="pm-",preferredFormat,typeToFolder=TYPE_TO_FOLDER){const trimmedRawId=rawId.trim(),exactRawId=trimmedRawId.startsWith("#")?trimmedRawId.slice(1):trimmedRawId;if(exactRawId.length===0)return null;const normalizedId=normalizeItemId(rawId,idPrefix),rawNormalizedId=normalizeRawItemId(rawId),candidateIds=[...new Set([exactRawId,normalizedId,rawNormalizedId])].filter(candidateId=>candidateId.length>0),entries=Object.entries(typeToFolder),searchOrder=resolveItemFormatSearchOrder(preferredFormat);for(const candidateId of candidateIds){const matches=new Map;for(const[type]of entries)for(const itemFormat of searchOrder){const itemPath=getItemPath(pmRoot,type,candidateId,itemFormat,typeToFolder);await fileExists(itemPath)&&matches.set(itemPath,matches.get(itemPath)??{id:candidateId,type,itemPath,item_format:itemFormat})}if(matches.size>1){const paths=[...matches.keys()].map(itemPath=>path.relative(pmRoot,itemPath).split(path.sep).join("/")).sort();throw new PmCliError(`Item ${candidateId} has ambiguous identity across ${paths.join(", ")}. Preserve both documents and inspect pm ops validate --check-storage-integrity before resolving the collision.`,EXIT_CODE.CONFLICT,{code:"item_identity_ambiguous",item_id:candidateId,paths})}for(const match of matches.values())return match}return null}async function readLocatedItem(item,options={}){const snapshot=await readLocatedItemSnapshot(item,options);if(snapshot.error!==null)throw snapshot.error;return{raw:snapshot.raw,document:snapshot.document}}async function readLocatedItemSnapshot(item,options={}){const bytes=await fs.readFile(item.itemPath);if(!isUtf8(bytes))throw new PmCliError("Item contains invalid UTF-8; preserve a binary backup before recovering it.",EXIT_CODE.CONFLICT,{code:"item_document_encoding_invalid",item_id:item.id,item_path:item.itemPath,byte_length:bytes.length,empty:!1});const raw=bytes.toString("utf8");await runActiveOnReadHooks({path:item.itemPath,scope:"project"});let document;try{document=parseItemDocument(raw,{format:item.item_format,requireSupportedFormat:!0,schema:options.schema,extensionFieldNames:resolveActiveExtensionFieldNames(options.extensionFieldNames),onWarning:warning=>appendWarning(options.warnings,warning)})}catch(error){if(error instanceof PmCliError&&error.code==="item_format_version_unsupported")throw new PmCliError(`Item ${item.id}: ${error.message}`,error.exitCode,{...error.context,item_id:item.id,item_path:item.itemPath});if(error instanceof PmCliError&&error.code==="item_document_invalid")return{raw,document:null,error:new PmCliError(`Cannot read ${item.id} at ${item.itemPath}${bytes.length===0?" (zero-length file)":""}: ${error.message}`,error.exitCode,{...error.context,item_id:item.id,item_path:item.itemPath,byte_length:bytes.length,empty:bytes.length===0,nextSteps:[`Run pm history ${item.id} --full, then pm restore ${item.id} <version> to recover a recorded state.`]})};throw error}return{raw,document,error:null}}async function listAllItemMetadata(pmRoot,preferredFormat,typeToFolder=TYPE_TO_FOLDER,warnings,schema){await assertReadableTrackerRoot(pmRoot);const documents=await listAllDocumentsCached(pmRoot,preferredFormat,typeToFolder,warnings,schema);return recordItemMetadataEnumeration(documents.length),documents.map(document=>document.metadata)}async function listAllItemMetadataLight(pmRoot,preferredFormat,typeToFolder=TYPE_TO_FOLDER,warnings,schema){await assertReadableTrackerRoot(pmRoot);const documents=await listAllDocumentsCachedLight(pmRoot,preferredFormat,typeToFolder,warnings,schema);return recordItemMetadataEnumeration(documents.length),documents.map(document=>document.metadata)}async function listAllItemMetadataWithBody(pmRoot,preferredFormat,typeToFolder=TYPE_TO_FOLDER,warnings,schema,options={}){await assertReadableTrackerRoot(pmRoot);const candidates=await listAllDocumentCandidatesCached(pmRoot,preferredFormat,typeToFolder,warnings,schema,{includeBody:!0,forceSourceScan:options.forceSourceScan});return recordItemMetadataEnumeration(candidates.length),candidates.map(candidate=>({...candidate.metadata,body:candidate.body}))}function createMutationGuardSdk(params){return{async get(id){const located=await locateItem(params.pmRoot,id,params.settings.id_prefix,params.settings.item_format,params.typeToFolder);if(!located)return null;const{document}=await readLocatedItem(located,{schema:params.settings.schema});return{item:document.metadata,body:document.body}},list:()=>listAllItemMetadata(params.pmRoot,params.settings.item_format,params.typeToFolder,void 0,params.settings.schema)}}async function listKnownItemIds(pmRoot,typeToFolder){const folders=new Set(Object.values(typeToFolder)),allIds=[];return await Promise.all([...folders].map(async folder=>{try{const entries=await fs.readdir(path.join(pmRoot,folder));for(const entry of entries)for(const ext of ITEM_FILE_EXTENSIONS)if(entry.toLowerCase().endsWith(ext)){allIds.push(entry.slice(0,-ext.length));break}}catch{}})),allIds}async function buildDidYouMeanSuggestions(pmRoot,badId,idPrefix,typeToFolder){const normalized=normalizeItemId(badId,idPrefix),ids=await listKnownItemIds(pmRoot,typeToFolder);if(ids.length===0)return[];const limit=Math.max(3,Math.floor(normalized.length/2));return ids.map(id=>({id,distance:levenshteinDistanceWithinLimit(id,normalized,limit)})).filter(entry=>entry.distance!==null).sort((left,right)=>left.distance-right.distance).slice(0,3).map(entry=>entry.id)}async function buildItemNotFoundError(pmRoot,badId,idPrefix,typeToFolder){const deleted=await buildDeletedItemError(pmRoot,badId,idPrefix);if(deleted)return deleted;const suggestions=await buildDidYouMeanSuggestions(pmRoot,badId,idPrefix,typeToFolder),nextSteps=["Confirm the active --path/PM_PATH scope, then retry with a valid id."];return suggestions.length>0&&nextSteps.unshift(`Did you mean one of: ${suggestions.join(", ")}?`),new PmCliError(`Item ${badId} not found`,EXIT_CODE.NOT_FOUND,{nextSteps})}function bypassesAssigneeConflict(op,bypassAssigneeConflict){return op==="claim"||bypassAssigneeConflict===!0&&(op==="comment_add"||op==="comment_edit"||op==="comment_delete"||op==="note_add"||op==="learning_add"||op==="release"||op==="update"||op==="update_ownership_bypass"||op==="update_audit")}async function prepareLockedItem(params){const typeToFolder=params.typeToFolder??resolveItemTypeRegistry(params.settings,getActiveExtensionRegistrations()).type_to_folder,located=await locateItem(params.pmRoot,params.id,params.settings.id_prefix,params.settings.item_format,typeToFolder);if(!located)throw await buildItemNotFoundError(params.pmRoot,params.id,params.settings.id_prefix,typeToFolder);const releaseLock=await acquireLock(params.pmRoot,located.id,params.settings.locks.ttl_seconds,params.author,!!params.force,params.settings.governance.force_required_for_stale_lock,params.settings.locks.wait_ms);try{const warnings=[],{raw:originalRaw,document}=await readLocatedItem(located,{schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames,warnings}),assigned=document.metadata.assignee?.trim(),assignedPrincipal=document.metadata.claim_principal?.trim()||assigned,callerPrincipal=resolveClaimPrincipal(params.author),governance=resolveGovernanceKnobs(params.settings);if(assigned&&assignedPrincipal!==callerPrincipal&&!params.force&&!bypassesAssigneeConflict(params.op,params.bypassAssigneeConflict)){if(governance.ownership_enforcement==="strict")throw new PmCliError(`Item ${located.id} is assigned to ${assigned}. Use --force to override.`,EXIT_CODE.CONFLICT);governance.ownership_enforcement==="warn"&&warnings.push(`ownership_warning:assignee_conflict:${located.id}:${assigned}`)}return{typeToFolder,located,originalRaw,document,warnings,releaseLock}}catch(error){throw await releaseLock(),error}}function resolveItemStoreWriteOverride(serviceWriteOverride,targetItemPath,serializedAfter){if(!serviceWriteOverride.handled||typeof serviceWriteOverride.result!="object"||serviceWriteOverride.result===null)return{effectiveTargetItemPath:targetItemPath,effectiveSerializedAfter:serializedAfter,skipItemWrite:!1};const overrideRecord=serviceWriteOverride.result;return{effectiveTargetItemPath:typeof overrideRecord.target_item_path=="string"&&overrideRecord.target_item_path.trim().length>0?overrideRecord.target_item_path:targetItemPath,effectiveSerializedAfter:typeof overrideRecord.contents=="string"?overrideRecord.contents:serializedAfter,skipItemWrite:overrideRecord.skip_write===!0}}async function rollbackMutatedItemWrite(params){if(!params.skipItemWrite){if(params.effectiveTargetItemPath!==params.originalItemPath){await writeFileAtomic(params.originalItemPath,params.originalRaw),await fs.rm(params.effectiveTargetItemPath,{force:!0});return}await writeFileAtomic(params.originalItemPath,params.originalRaw)}}async function mutateItemWithDeferredHistoryContext(params){normalizeHistoryOperationForWrite(params.op);const prepared=await prepareLockedItem({pmRoot:params.pmRoot,settings:params.settings,id:params.id,op:params.op,author:params.author,force:params.force,bypassAssigneeConflict:params.bypassAssigneeConflict,extensionFieldNames:params.extensionFieldNames,typeToFolder:params.typeToFolder}),{typeToFolder,located,originalRaw,document,warnings:parseWarnings,releaseLock}=prepared;try{const beforeDocument=canonicalDocument(document,{schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames}),mutableDocument=canonicalDocument(structuredClone(document),{schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames}),mutation=await params.mutate(mutableDocument);if(params.skipNoop===!0&&mutation.changedFields.length===0)return{item:beforeDocument.metadata,body:beforeDocument.body,changedFields:[],warnings:[...parseWarnings,...mutation.warnings??[]]};const historyContext=params.resolveHistoryContext?.(),requiredFormat=Math.max(requiredItemFormatVersion(beforeDocument.metadata),requiredItemFormatVersion(mutableDocument.metadata));assertProjectRuntimeFormatGuard(resolveWorkspaceRoot(params.pmRoot),requiredFormat),requiredFormat>effectiveItemFormatVersion(mutableDocument.metadata)&&(mutableDocument.metadata.pm_format_version=requiredFormat,mutation.changedFields.push("pm_format_version")),mutableDocument.metadata.updated_at=nowIso();const afterDocument=canonicalDocument(mutableDocument,{schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames}),workflowPolicy=await enforceWorkflowMutation({pmRoot:params.pmRoot,settings:params.settings,operation:params.op,author:params.author,before:beforeDocument,after:afterDocument});await runActiveBeforeMutationHooks({pm_root:params.pmRoot,operation:params.op,before:beforeDocument,after:afterDocument,changed_fields:mutation.changedFields,sdk:createMutationGuardSdk({pmRoot:params.pmRoot,settings:params.settings,typeToFolder})});const historyPolicy=await enforceHistoryStreamPolicyForItem({pmRoot:params.pmRoot,settings:params.settings,itemId:located.id,commandLabel:params.op}),targetItemFormat="toon",serializedAfter=serializeItemDocument(afterDocument,{format:targetItemFormat,schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames}),targetItemPath=getItemPath(params.pmRoot,afterDocument.metadata.type,located.id,targetItemFormat,typeToFolder),historyPath=getHistoryPath(params.pmRoot,located.id),serviceWriteOverride=await runActiveServiceOverride("item_store_write",{op:params.op,pm_root:params.pmRoot,item_id:located.id,source_item_path:located.itemPath,target_item_path:targetItemPath,history_path:historyPath,item_format:targetItemFormat,before:beforeDocument,after:afterDocument,contents:serializedAfter}),{effectiveTargetItemPath,effectiveSerializedAfter,skipItemWrite}=resolveItemStoreWriteOverride(serviceWriteOverride,targetItemPath,serializedAfter),releaseDerivedIndexLock=await acquireItemMetadataDerivedIndexLock(params.pmRoot,params.author);let derivedIndexWarnings=[];try{skipItemWrite||await writeFileAtomic(effectiveTargetItemPath,effectiveSerializedAfter),!skipItemWrite&&effectiveTargetItemPath!==located.itemPath&&await fs.rm(located.itemPath);const entry=createHistoryEntry({nowIso:afterDocument.metadata.updated_at,author:params.author,op:params.op,before:beforeDocument,after:afterDocument,message:params.message,context:workflowPolicy.decisions.length===0?historyContext:{...historyContext,workflow_policies:workflowPolicy.decisions}});try{await appendHistoryEntry(historyPath,entry)}catch(error){throw await rollbackMutatedItemWrite({skipItemWrite,effectiveTargetItemPath,originalItemPath:located.itemPath,originalRaw}),error}skipItemWrite||(derivedIndexWarnings=await refreshItemMetadataDerivedIndex({pmRoot:params.pmRoot,preferredFormat:params.settings.item_format,typeToFolder,schema:params.settings.schema,itemPath:effectiveTargetItemPath,previousItemPath:located.itemPath,document:afterDocument}))}finally{await releaseDerivedIndexLock()}const hookWarnings=[...await runActiveOnWriteHooks({path:effectiveTargetItemPath,scope:"project",op:params.op,item_id:afterDocument.metadata.id,item_type:afterDocument.metadata.type,before:beforeDocument,after:afterDocument,changed_fields:mutation.changedFields}),...await runActiveOnWriteHooks({path:historyPath,scope:"project",op:`${params.op}:history`,item_id:afterDocument.metadata.id,item_type:afterDocument.metadata.type,before:beforeDocument,after:afterDocument,changed_fields:mutation.changedFields})];return recordAfterCommandAffectedItem({id:afterDocument.metadata.id,op:params.op,item_type:afterDocument.metadata.type,previous_status:beforeDocument.metadata.status,status:afterDocument.metadata.status,previous:projectAfterCommandItemSnapshot(beforeDocument.metadata,mutation.changedFields),current:projectAfterCommandItemSnapshot(afterDocument.metadata,mutation.changedFields),changed_fields:mutation.changedFields}),{item:afterDocument.metadata,body:afterDocument.body,changedFields:mutation.changedFields,warnings:[...parseWarnings,...mutation.warnings??[],...workflowPolicy.warnings,...historyPolicy.warnings,...serviceWriteOverride.warnings,...derivedIndexWarnings,...hookWarnings]}}finally{await releaseLock()}}async function mutateItemWithHistoryContext(params){const{historyContext,...mutationParams}=params;return mutateItemWithDeferredHistoryContext({...mutationParams,resolveHistoryContext:()=>historyContext})}async function mutateItemWithHistoryContextResolver(params){return mutateItemWithDeferredHistoryContext(params)}async function mutateItem(params){return mutateItemWithDeferredHistoryContext(params)}const itemStoreTestOnly={appendWarning,bypassesAssigneeConflict,buildDidYouMeanSuggestions,isErrno};async function deleteItem(params){const prepared=await prepareLockedItem({pmRoot:params.pmRoot,settings:params.settings,id:params.id,op:"delete",author:params.author,force:params.force}),{located,originalRaw,document,warnings:parseWarnings,releaseLock}=prepared;try{const extensionFieldNames=resolveActiveExtensionFieldNames(void 0),beforeDocument=canonicalDocument(document,{schema:params.settings.schema,extensionFieldNames}),workflowPolicy=await enforceWorkflowMutation({pmRoot:params.pmRoot,settings:params.settings,operation:"delete",author:params.author,before:beforeDocument,after:null,dryRun:params.dryRun});await runActiveBeforeMutationHooks({pm_root:params.pmRoot,operation:"delete",before:beforeDocument,after:null,changed_fields:["deleted"],sdk:createMutationGuardSdk({pmRoot:params.pmRoot,settings:params.settings,typeToFolder:prepared.typeToFolder})});const historyPolicy=await enforceHistoryStreamPolicyForItem({pmRoot:params.pmRoot,settings:params.settings,itemId:located.id,commandLabel:"delete"}),deletionTimestamp=nowIso(),tombstoneDocument=EMPTY_CANONICAL_DOCUMENT,historyEntry=createHistoryEntry({nowIso:deletionTimestamp,author:params.author,op:"delete",before:beforeDocument,after:tombstoneDocument,message:params.message,context:workflowPolicy.decisions.length===0?void 0:{workflow_policies:workflowPolicy.decisions}}),historyPath=getHistoryPath(params.pmRoot,located.id),serviceDeleteOverride=await runActiveServiceOverride("item_store_delete",{op:"delete",pm_root:params.pmRoot,item_id:located.id,item_path:located.itemPath,history_path:historyPath,before:beforeDocument});let effectiveItemPath=located.itemPath,skipDelete=!1;if(serviceDeleteOverride.handled&&typeof serviceDeleteOverride.result=="object"&&serviceDeleteOverride.result!==null){const overrideRecord=serviceDeleteOverride.result;typeof overrideRecord.item_path=="string"&&overrideRecord.item_path.trim().length>0&&(effectiveItemPath=overrideRecord.item_path),overrideRecord.skip_delete===!0&&(skipDelete=!0)}if(params.dryRun===!0)return{item:beforeDocument.metadata,changedFields:["deleted"],targetPath:effectiveItemPath,warnings:[...parseWarnings,...workflowPolicy.warnings,...historyPolicy.warnings,...serviceDeleteOverride.warnings]};const releaseDerivedIndexLock=await acquireItemMetadataDerivedIndexLock(params.pmRoot,params.author);let derivedIndexWarnings=[];try{skipDelete||await fs.rm(effectiveItemPath);try{await appendHistoryEntry(historyPath,historyEntry)}catch(error){throw skipDelete||await writeFileAtomic(effectiveItemPath,originalRaw),error}skipDelete||(derivedIndexWarnings=await refreshItemMetadataDerivedIndex({pmRoot:params.pmRoot,preferredFormat:params.settings.item_format,typeToFolder:prepared.typeToFolder,schema:params.settings.schema,itemPath:effectiveItemPath,document:null}))}finally{await releaseDerivedIndexLock()}const hookWarnings=[...await runActiveOnWriteHooks({path:effectiveItemPath,scope:"project",op:"delete",item_id:beforeDocument.metadata.id,item_type:beforeDocument.metadata.type,before:beforeDocument,after:tombstoneDocument,changed_fields:["deleted"]}),...await runActiveOnWriteHooks({path:historyPath,scope:"project",op:"delete:history",item_id:beforeDocument.metadata.id,item_type:beforeDocument.metadata.type,before:beforeDocument,after:tombstoneDocument,changed_fields:["deleted"]})];return recordAfterCommandAffectedItem({id:beforeDocument.metadata.id,op:"delete",item_type:beforeDocument.metadata.type,previous_status:beforeDocument.metadata.status,previous:projectAfterCommandItemSnapshot(beforeDocument.metadata,Object.keys(beforeDocument.metadata)),changed_fields:["deleted"]}),{item:beforeDocument.metadata,changedFields:["deleted"],warnings:[...parseWarnings,...workflowPolicy.warnings,...historyPolicy.warnings,...serviceDeleteOverride.warnings,...derivedIndexWarnings,...hookWarnings]}}finally{await releaseLock()}}export{buildItemNotFoundError,createMutationGuardSdk,deleteItem,itemStoreTestOnly,listAllItemMetadata,listAllItemMetadataLight,listAllItemMetadataWithBody,locateItem,mutateItem,mutateItemWithHistoryContext,mutateItemWithHistoryContextResolver,readLocatedItem,readLocatedItemSnapshot};
|
|
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]="018adb6c-4e3c-58d5-b636-04dbf4307d7a")}catch{}})();import fs from"node:fs/promises";import{buildDeletedItemError}from"../history/tombstone.js";import{normalizeHistoryOperationForWrite}from"../history/operation-contract.js";import{enforceWorkflowMutation}from"../policy/workflow-policy-store.js";import{recordItemMetadataEnumeration}from"./item-metadata-read-work.js";import{assertItemMutationPreconditions}from"./item-mutation-precondition.js";import path from"node:path";import{getActiveExtensionRegistrations,projectAfterCommandItemSnapshot,recordAfterCommandAffectedItem,runActiveOnReadHooks,runActiveBeforeMutationHooks,runActiveOnWriteHooks,runActiveServiceOverride}from"../extensions/index.js";import{collectRegisteredItemFieldNames}from"../extensions/item-fields.js";import{EMPTY_CANONICAL_DOCUMENT,EXIT_CODE,TYPE_TO_FOLDER}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{levenshteinDistanceWithinLimit}from"../shared/levenshtein.js";import{appendHistoryEntry,createHistoryEntry}from"../history/history.js";import{enforceHistoryStreamPolicyForItem}from"../history/history-stream-policy.js";import{canonicalDocument,parseItemDocument,serializeItemDocument}from"../item/item-format.js";import{resolveItemTypeRegistry}from"../item/type-registry.js";import{effectiveItemFormatVersion,requiredItemFormatVersion}from"../item/item-format-version.js";import{assertProjectRuntimeFormatGuard}from"../../sdk/environment/project-runtime-compatibility.js";import{acquireLock}from"../lock/lock.js";import{writeFileAtomic}from"../fs/fs-utils.js";import{isUtf8}from"node:buffer";import{normalizeItemId,normalizeRawItemId}from"../item/id.js";import{acquireItemMetadataDerivedIndexLock,listAllDocumentCandidatesCached,listAllDocumentsCached,listAllDocumentsCachedLight,refreshItemMetadataDerivedIndex}from"./item-metadata-cache.js";import{getHistoryPath,getItemPath,ITEM_FILE_EXTENSIONS,resolveWorkspaceRoot}from"./paths.js";import{resolveGovernanceKnobs}from"./settings.js";import{assertReadableTrackerRoot}from"./tracker-preflight.js";import{resolveClaimPrincipal}from"../shared/author.js";import{nowIso}from"../shared/time.js";async function fileExists(targetPath){try{return await fs.access(targetPath),!0}catch{return!1}}function isErrno(error,code){return typeof error=="object"&&error!==null&&"code"in error&&error.code===code}function appendWarning(warnings,warning){warnings&&(warnings.includes(warning)||warnings.push(warning))}function resolveActiveExtensionFieldNames(explicit){return explicit??collectRegisteredItemFieldNames(getActiveExtensionRegistrations())}function resolveItemFormatSearchOrder(preferredFormat){return preferredFormat==="toon"?["toon","json_markdown"]:preferredFormat==="json_markdown"?["json_markdown","toon"]:["toon","json_markdown"]}async function locateItem(pmRoot,rawId,idPrefix="pm-",preferredFormat,typeToFolder=TYPE_TO_FOLDER){const trimmedRawId=rawId.trim(),exactRawId=trimmedRawId.startsWith("#")?trimmedRawId.slice(1):trimmedRawId;if(exactRawId.length===0)return null;const normalizedId=normalizeItemId(rawId,idPrefix),rawNormalizedId=normalizeRawItemId(rawId),candidateIds=[...new Set([exactRawId,normalizedId,rawNormalizedId])].filter(candidateId=>candidateId.length>0),entries=Object.entries(typeToFolder),searchOrder=resolveItemFormatSearchOrder(preferredFormat);for(const candidateId of candidateIds){const matches=new Map;for(const[type]of entries)for(const itemFormat of searchOrder){const itemPath=getItemPath(pmRoot,type,candidateId,itemFormat,typeToFolder);await fileExists(itemPath)&&matches.set(itemPath,matches.get(itemPath)??{id:candidateId,type,itemPath,item_format:itemFormat})}if(matches.size>1){const paths=[...matches.keys()].map(itemPath=>path.relative(pmRoot,itemPath).split(path.sep).join("/")).sort();throw new PmCliError(`Item ${candidateId} has ambiguous identity across ${paths.join(", ")}. Preserve both documents and inspect pm ops validate --check-storage-integrity before resolving the collision.`,EXIT_CODE.CONFLICT,{code:"item_identity_ambiguous",item_id:candidateId,paths})}for(const match of matches.values())return match}return null}async function readLocatedItem(item,options={}){const snapshot=await readLocatedItemSnapshot(item,options);if(snapshot.error!==null)throw snapshot.error;return{raw:snapshot.raw,document:snapshot.document}}async function readLocatedItemSnapshot(item,options={}){const bytes=await fs.readFile(item.itemPath);if(!isUtf8(bytes))throw new PmCliError("Item contains invalid UTF-8; preserve a binary backup before recovering it.",EXIT_CODE.CONFLICT,{code:"item_document_encoding_invalid",item_id:item.id,item_path:item.itemPath,byte_length:bytes.length,empty:!1});const raw=bytes.toString("utf8");await runActiveOnReadHooks({path:item.itemPath,scope:"project"});let document;try{document=parseItemDocument(raw,{format:item.item_format,requireSupportedFormat:!0,schema:options.schema,extensionFieldNames:resolveActiveExtensionFieldNames(options.extensionFieldNames),onWarning:warning=>appendWarning(options.warnings,warning)})}catch(error){if(error instanceof PmCliError&&error.code==="item_format_version_unsupported")throw new PmCliError(`Item ${item.id}: ${error.message}`,error.exitCode,{...error.context,item_id:item.id,item_path:item.itemPath});if(error instanceof PmCliError&&error.code==="item_document_invalid")return{raw,document:null,error:new PmCliError(`Cannot read ${item.id} at ${item.itemPath}${bytes.length===0?" (zero-length file)":""}: ${error.message}`,error.exitCode,{...error.context,item_id:item.id,item_path:item.itemPath,byte_length:bytes.length,empty:bytes.length===0,nextSteps:[`Run pm history ${item.id} --full, then pm restore ${item.id} <version> to recover a recorded state.`]})};throw error}return{raw,document,error:null}}async function listAllItemMetadata(pmRoot,preferredFormat,typeToFolder=TYPE_TO_FOLDER,warnings,schema){await assertReadableTrackerRoot(pmRoot);const documents=await listAllDocumentsCached(pmRoot,preferredFormat,typeToFolder,warnings,schema);return recordItemMetadataEnumeration(documents.length),documents.map(document=>document.metadata)}async function listAllItemMetadataLight(pmRoot,preferredFormat,typeToFolder=TYPE_TO_FOLDER,warnings,schema){await assertReadableTrackerRoot(pmRoot);const documents=await listAllDocumentsCachedLight(pmRoot,preferredFormat,typeToFolder,warnings,schema);return recordItemMetadataEnumeration(documents.length),documents.map(document=>document.metadata)}async function listAllItemMetadataWithBody(pmRoot,preferredFormat,typeToFolder=TYPE_TO_FOLDER,warnings,schema,options={}){await assertReadableTrackerRoot(pmRoot);const candidates=await listAllDocumentCandidatesCached(pmRoot,preferredFormat,typeToFolder,warnings,schema,{includeBody:!0,forceSourceScan:options.forceSourceScan});return recordItemMetadataEnumeration(candidates.length),candidates.map(candidate=>({...candidate.metadata,body:candidate.body}))}function createMutationGuardSdk(params){return{async get(id){const located=await locateItem(params.pmRoot,id,params.settings.id_prefix,params.settings.item_format,params.typeToFolder);if(!located)return null;const{document}=await readLocatedItem(located,{schema:params.settings.schema});return{item:document.metadata,body:document.body}},list:()=>listAllItemMetadata(params.pmRoot,params.settings.item_format,params.typeToFolder,void 0,params.settings.schema)}}async function listKnownItemIds(pmRoot,typeToFolder){const folders=new Set(Object.values(typeToFolder)),allIds=[];return await Promise.all([...folders].map(async folder=>{try{const entries=await fs.readdir(path.join(pmRoot,folder));for(const entry of entries)for(const ext of ITEM_FILE_EXTENSIONS)if(entry.toLowerCase().endsWith(ext)){allIds.push(entry.slice(0,-ext.length));break}}catch{}})),allIds}async function buildDidYouMeanSuggestions(pmRoot,badId,idPrefix,typeToFolder){const normalized=normalizeItemId(badId,idPrefix),ids=await listKnownItemIds(pmRoot,typeToFolder);if(ids.length===0)return[];const limit=Math.max(3,Math.floor(normalized.length/2));return ids.map(id=>({id,distance:levenshteinDistanceWithinLimit(id,normalized,limit)})).filter(entry=>entry.distance!==null).sort((left,right)=>left.distance-right.distance).slice(0,3).map(entry=>entry.id)}async function buildItemNotFoundError(pmRoot,badId,idPrefix,typeToFolder){const deleted=await buildDeletedItemError(pmRoot,badId,idPrefix);if(deleted)return deleted;const suggestions=await buildDidYouMeanSuggestions(pmRoot,badId,idPrefix,typeToFolder),nextSteps=["Confirm the active --path/PM_PATH scope, then retry with a valid id."];return suggestions.length>0&&nextSteps.unshift(`Did you mean one of: ${suggestions.join(", ")}?`),new PmCliError(`Item ${badId} not found`,EXIT_CODE.NOT_FOUND,{nextSteps})}function bypassesAssigneeConflict(op,bypassAssigneeConflict){return op==="claim"||bypassAssigneeConflict===!0&&(op==="comment_add"||op==="comment_edit"||op==="comment_delete"||op==="note_add"||op==="learning_add"||op==="release"||op==="update"||op==="update_ownership_bypass"||op==="update_audit")}async function prepareLockedItem(params){const typeToFolder=params.typeToFolder??resolveItemTypeRegistry(params.settings,getActiveExtensionRegistrations()).type_to_folder,located=await locateItem(params.pmRoot,params.id,params.settings.id_prefix,params.settings.item_format,typeToFolder);if(!located)throw await buildItemNotFoundError(params.pmRoot,params.id,params.settings.id_prefix,typeToFolder);const releaseLock=await acquireLock(params.pmRoot,located.id,params.settings.locks.ttl_seconds,params.author,!!params.force,params.settings.governance.force_required_for_stale_lock,params.settings.locks.wait_ms);try{const warnings=[],{raw:originalRaw,document}=await readLocatedItem(located,{schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames,warnings}),assigned=document.metadata.assignee?.trim(),assignedPrincipal=document.metadata.claim_principal?.trim()||assigned,callerPrincipal=resolveClaimPrincipal(params.author),governance=resolveGovernanceKnobs(params.settings);if(assigned&&assignedPrincipal!==callerPrincipal&&!params.force&&!bypassesAssigneeConflict(params.op,params.bypassAssigneeConflict)){if(governance.ownership_enforcement==="strict")throw new PmCliError(`Item ${located.id} is assigned to ${assigned}. Use --force to override.`,EXIT_CODE.CONFLICT);governance.ownership_enforcement==="warn"&&warnings.push(`ownership_warning:assignee_conflict:${located.id}:${assigned}`)}return{typeToFolder,located,originalRaw,document,warnings,releaseLock}}catch(error){throw await releaseLock(),error}}function resolveItemStoreWriteOverride(serviceWriteOverride,targetItemPath,serializedAfter){if(!serviceWriteOverride.handled||typeof serviceWriteOverride.result!="object"||serviceWriteOverride.result===null)return{effectiveTargetItemPath:targetItemPath,effectiveSerializedAfter:serializedAfter,skipItemWrite:!1};const overrideRecord=serviceWriteOverride.result;return{effectiveTargetItemPath:typeof overrideRecord.target_item_path=="string"&&overrideRecord.target_item_path.trim().length>0?overrideRecord.target_item_path:targetItemPath,effectiveSerializedAfter:typeof overrideRecord.contents=="string"?overrideRecord.contents:serializedAfter,skipItemWrite:overrideRecord.skip_write===!0}}async function rollbackMutatedItemWrite(params){if(!params.skipItemWrite){if(params.effectiveTargetItemPath!==params.originalItemPath){await writeFileAtomic(params.originalItemPath,params.originalRaw),await fs.rm(params.effectiveTargetItemPath,{force:!0});return}await writeFileAtomic(params.originalItemPath,params.originalRaw)}}async function mutateItemWithDeferredHistoryContext(params){normalizeHistoryOperationForWrite(params.op);const prepared=await prepareLockedItem({pmRoot:params.pmRoot,settings:params.settings,id:params.id,op:params.op,author:params.author,force:params.force,bypassAssigneeConflict:params.bypassAssigneeConflict,extensionFieldNames:params.extensionFieldNames,typeToFolder:params.typeToFolder}),{typeToFolder,located,originalRaw,document,warnings:parseWarnings,releaseLock}=prepared;try{assertItemMutationPreconditions(params.pmRoot,document);const beforeDocument=canonicalDocument(document,{schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames}),mutableDocument=canonicalDocument(structuredClone(document),{schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames}),mutation=await params.mutate(mutableDocument);if(params.skipNoop===!0&&mutation.changedFields.length===0)return{item:beforeDocument.metadata,body:beforeDocument.body,changedFields:[],warnings:[...parseWarnings,...mutation.warnings??[]]};const historyContext=params.resolveHistoryContext?.(),requiredFormat=Math.max(requiredItemFormatVersion(beforeDocument.metadata),requiredItemFormatVersion(mutableDocument.metadata));assertProjectRuntimeFormatGuard(resolveWorkspaceRoot(params.pmRoot),requiredFormat),requiredFormat>effectiveItemFormatVersion(mutableDocument.metadata)&&(mutableDocument.metadata.pm_format_version=requiredFormat,mutation.changedFields.push("pm_format_version")),mutableDocument.metadata.updated_at=nowIso();const afterDocument=canonicalDocument(mutableDocument,{schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames}),workflowPolicy=await enforceWorkflowMutation({pmRoot:params.pmRoot,settings:params.settings,operation:params.op,author:params.author,before:beforeDocument,after:afterDocument});await runActiveBeforeMutationHooks({pm_root:params.pmRoot,operation:params.op,before:beforeDocument,after:afterDocument,changed_fields:mutation.changedFields,sdk:createMutationGuardSdk({pmRoot:params.pmRoot,settings:params.settings,typeToFolder})});const historyPolicy=await enforceHistoryStreamPolicyForItem({pmRoot:params.pmRoot,settings:params.settings,itemId:located.id,commandLabel:params.op}),targetItemFormat="toon",serializedAfter=serializeItemDocument(afterDocument,{format:targetItemFormat,schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames}),targetItemPath=getItemPath(params.pmRoot,afterDocument.metadata.type,located.id,targetItemFormat,typeToFolder),historyPath=getHistoryPath(params.pmRoot,located.id),serviceWriteOverride=await runActiveServiceOverride("item_store_write",{op:params.op,pm_root:params.pmRoot,item_id:located.id,source_item_path:located.itemPath,target_item_path:targetItemPath,history_path:historyPath,item_format:targetItemFormat,before:beforeDocument,after:afterDocument,contents:serializedAfter}),{effectiveTargetItemPath,effectiveSerializedAfter,skipItemWrite}=resolveItemStoreWriteOverride(serviceWriteOverride,targetItemPath,serializedAfter),releaseDerivedIndexLock=await acquireItemMetadataDerivedIndexLock(params.pmRoot,params.author);let derivedIndexWarnings=[];try{skipItemWrite||await writeFileAtomic(effectiveTargetItemPath,effectiveSerializedAfter),!skipItemWrite&&effectiveTargetItemPath!==located.itemPath&&await fs.rm(located.itemPath);const entry=createHistoryEntry({nowIso:afterDocument.metadata.updated_at,author:params.author,op:params.op,before:beforeDocument,after:afterDocument,message:params.message,context:workflowPolicy.decisions.length===0?historyContext:{...historyContext,workflow_policies:workflowPolicy.decisions}});try{await appendHistoryEntry(historyPath,entry)}catch(error){throw await rollbackMutatedItemWrite({skipItemWrite,effectiveTargetItemPath,originalItemPath:located.itemPath,originalRaw}),error}skipItemWrite||(derivedIndexWarnings=await refreshItemMetadataDerivedIndex({pmRoot:params.pmRoot,preferredFormat:params.settings.item_format,typeToFolder,schema:params.settings.schema,itemPath:effectiveTargetItemPath,previousItemPath:located.itemPath,document:afterDocument}))}finally{await releaseDerivedIndexLock()}const hookWarnings=[...await runActiveOnWriteHooks({path:effectiveTargetItemPath,scope:"project",op:params.op,item_id:afterDocument.metadata.id,item_type:afterDocument.metadata.type,before:beforeDocument,after:afterDocument,changed_fields:mutation.changedFields}),...await runActiveOnWriteHooks({path:historyPath,scope:"project",op:`${params.op}:history`,item_id:afterDocument.metadata.id,item_type:afterDocument.metadata.type,before:beforeDocument,after:afterDocument,changed_fields:mutation.changedFields})];return recordAfterCommandAffectedItem({id:afterDocument.metadata.id,op:params.op,item_type:afterDocument.metadata.type,previous_status:beforeDocument.metadata.status,status:afterDocument.metadata.status,previous:projectAfterCommandItemSnapshot(beforeDocument.metadata,mutation.changedFields),current:projectAfterCommandItemSnapshot(afterDocument.metadata,mutation.changedFields),changed_fields:mutation.changedFields}),{item:afterDocument.metadata,body:afterDocument.body,changedFields:mutation.changedFields,warnings:[...parseWarnings,...mutation.warnings??[],...workflowPolicy.warnings,...historyPolicy.warnings,...serviceWriteOverride.warnings,...derivedIndexWarnings,...hookWarnings]}}finally{await releaseLock()}}async function mutateItemWithHistoryContext(params){const{historyContext,...mutationParams}=params;return mutateItemWithDeferredHistoryContext({...mutationParams,resolveHistoryContext:()=>historyContext})}async function mutateItemWithHistoryContextResolver(params){return mutateItemWithDeferredHistoryContext(params)}async function mutateItem(params){return mutateItemWithDeferredHistoryContext(params)}const itemStoreTestOnly={appendWarning,bypassesAssigneeConflict,buildDidYouMeanSuggestions,isErrno};async function deleteItem(params){const prepared=await prepareLockedItem({pmRoot:params.pmRoot,settings:params.settings,id:params.id,op:"delete",author:params.author,force:params.force}),{located,originalRaw,document,warnings:parseWarnings,releaseLock}=prepared;try{const extensionFieldNames=resolveActiveExtensionFieldNames(void 0),beforeDocument=canonicalDocument(document,{schema:params.settings.schema,extensionFieldNames}),workflowPolicy=await enforceWorkflowMutation({pmRoot:params.pmRoot,settings:params.settings,operation:"delete",author:params.author,before:beforeDocument,after:null,dryRun:params.dryRun});await runActiveBeforeMutationHooks({pm_root:params.pmRoot,operation:"delete",before:beforeDocument,after:null,changed_fields:["deleted"],sdk:createMutationGuardSdk({pmRoot:params.pmRoot,settings:params.settings,typeToFolder:prepared.typeToFolder})});const historyPolicy=await enforceHistoryStreamPolicyForItem({pmRoot:params.pmRoot,settings:params.settings,itemId:located.id,commandLabel:"delete"}),deletionTimestamp=nowIso(),tombstoneDocument=EMPTY_CANONICAL_DOCUMENT,historyEntry=createHistoryEntry({nowIso:deletionTimestamp,author:params.author,op:"delete",before:beforeDocument,after:tombstoneDocument,message:params.message,context:workflowPolicy.decisions.length===0?void 0:{workflow_policies:workflowPolicy.decisions}}),historyPath=getHistoryPath(params.pmRoot,located.id),serviceDeleteOverride=await runActiveServiceOverride("item_store_delete",{op:"delete",pm_root:params.pmRoot,item_id:located.id,item_path:located.itemPath,history_path:historyPath,before:beforeDocument});let effectiveItemPath=located.itemPath,skipDelete=!1;if(serviceDeleteOverride.handled&&typeof serviceDeleteOverride.result=="object"&&serviceDeleteOverride.result!==null){const overrideRecord=serviceDeleteOverride.result;typeof overrideRecord.item_path=="string"&&overrideRecord.item_path.trim().length>0&&(effectiveItemPath=overrideRecord.item_path),overrideRecord.skip_delete===!0&&(skipDelete=!0)}if(params.dryRun===!0)return{item:beforeDocument.metadata,changedFields:["deleted"],targetPath:effectiveItemPath,warnings:[...parseWarnings,...workflowPolicy.warnings,...historyPolicy.warnings,...serviceDeleteOverride.warnings]};const releaseDerivedIndexLock=await acquireItemMetadataDerivedIndexLock(params.pmRoot,params.author);let derivedIndexWarnings=[];try{skipDelete||await fs.rm(effectiveItemPath);try{await appendHistoryEntry(historyPath,historyEntry)}catch(error){throw skipDelete||await writeFileAtomic(effectiveItemPath,originalRaw),error}skipDelete||(derivedIndexWarnings=await refreshItemMetadataDerivedIndex({pmRoot:params.pmRoot,preferredFormat:params.settings.item_format,typeToFolder:prepared.typeToFolder,schema:params.settings.schema,itemPath:effectiveItemPath,document:null}))}finally{await releaseDerivedIndexLock()}const hookWarnings=[...await runActiveOnWriteHooks({path:effectiveItemPath,scope:"project",op:"delete",item_id:beforeDocument.metadata.id,item_type:beforeDocument.metadata.type,before:beforeDocument,after:tombstoneDocument,changed_fields:["deleted"]}),...await runActiveOnWriteHooks({path:historyPath,scope:"project",op:"delete:history",item_id:beforeDocument.metadata.id,item_type:beforeDocument.metadata.type,before:beforeDocument,after:tombstoneDocument,changed_fields:["deleted"]})];return recordAfterCommandAffectedItem({id:beforeDocument.metadata.id,op:"delete",item_type:beforeDocument.metadata.type,previous_status:beforeDocument.metadata.status,previous:projectAfterCommandItemSnapshot(beforeDocument.metadata,Object.keys(beforeDocument.metadata)),changed_fields:["deleted"]}),{item:beforeDocument.metadata,changedFields:["deleted"],warnings:[...parseWarnings,...workflowPolicy.warnings,...historyPolicy.warnings,...serviceDeleteOverride.warnings,...derivedIndexWarnings,...hookWarnings]}}finally{await releaseLock()}}export{buildItemNotFoundError,createMutationGuardSdk,deleteItem,itemStoreTestOnly,listAllItemMetadata,listAllItemMetadataLight,listAllItemMetadataWithBody,locateItem,mutateItem,mutateItemWithHistoryContext,mutateItemWithHistoryContextResolver,readLocatedItem,readLocatedItemSnapshot};
|
|
2
2
|
//# sourceMappingURL=item-store.js.map
|
package/dist/mcp/server.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="4cb5ad92-68d4-5beb-be5b-28c5e51aae2c")}catch{}})();import{realpathSync}from"node:fs";import{readFile}from"node:fs/promises";import path from"node:path";import readline from"node:readline";import{fileURLToPath}from"node:url";import{resolvePmCliVersion,PmCliError,decodeHtmlEntitiesInOptions,levenshteinDistanceWithinLimit,asRecordClone,createSerialQueue,evaluateMutationGuard,getSettingsPath,isMutationAction,pathExists,readSettings,runWithHarnessDetectionSignals,runWithWorkspaceHarnessSignalDescriptors,boundAgentEpisodeIdentity}from"../sdk/runtime-primitives.js";import{pmToolActionNestedOptionKeys}from"../sdk/cli-contracts/tool-schema.js";import{readRequiredString,runAction,runWithActiveExtensions}from"../sdk/runtime.js";import{NARROW_TOOL_ACTIONS,TOOLS}from"./tool-definitions.js";import{normalizeWorkspaceToolArguments,resolveMcpToolAccess,resolveMcpToolSurface}from"./runtime-capabilities.js";import{PM_MCP_PROMPT_CONTRACTS,PM_MCP_RESOURCE_CONTRACTS}from"../sdk/agent-capability-contracts.js";import{PM_MCP_ENTRY_TOOL_NAMES,PM_MCP_PROGRESSIVE_DISCOVERY_EXTENSION,PM_MCP_PROGRESSIVE_DISCOVERY_SERVER_CAPABILITY,discoverPmTools,parsePmToolDiscoveryOptions}from"../sdk/mcp/discovery.js";import{commitItemMutations,previewItemMutations}from"../sdk/item-transaction.js";import{isRuntimeRecord,markMcpMutationTransportInput}from"../sdk/runtime-input.js";import{attachOutputTokenAccounting}from"../sdk/output-token-accounting.js";import{createReproducibleProcessRunner,runWithReproducibleProcessEnvironment}from"../sdk/reproducibility/process.js";import{parseAtomicMutationControls,resolveItemMutationDocument}from"../sdk/structured-mutations.js";import{resolveAuthor,resolvePmRoot,resolveWorkspaceRoot}from"../sdk/runtime-primitives.js";import{PM_MCP_ERROR_CODES,PM_MCP_META_KEYS,PM_MCP_PROTOCOL_VERSION,PmMcpProtocolError,attachMcpServerInfo,buildMcpCompleteResult,buildMcpDiscoverResult,hasMcpClientExtension,isMcpRecord,resolveMcpRequestContext}from"../sdk/mcp/protocol.js";import{PmMcpInputRequiredError,buildMcpInputRequiredResult,parseMcpInputResponses,validateMcpJsonSchema,withMcpCachePolicy}from"../sdk/mcp/interactions.js";import{PM_MCP_TASKS_EXTENSION,createMcpTaskStore}from"../sdk/mcp/tasks.js";import{PmMcpSubscriptionRegistry}from"../sdk/mcp/subscriptions.js";import{extractMcpTraceContext,runWithMcpTraceContext}from"../sdk/mcp/authorization.js";import{LegacyMcpAdapter}from"./legacy-adapter.js";import{PM_MCP_APP_CONTRACTS,PM_MCP_APP_MIME_TYPE,PM_MCP_APPS_EXTENSION,PM_MCP_APPS_SERVER_CAPABILITY,decoratePmMcpToolsWithApps,findPmMcpAppByUri,hasPmMcpAppsCapability,renderPmMcpAppHtml}from"../sdk/mcp/apps.js";import{PM_MCP_SKILLS_EXTENSION,PM_MCP_SKILLS_SERVER_CAPABILITY,PmMcpSkillRegistry,assertPmMcpSkillsCapability}from"../sdk/mcp/skills.js";function runMcpAction(args){return runAction(markMcpMutationTransportInput(args))}const PM_PACKAGE_ROOT_ENV="PM_CLI_PACKAGE_ROOT";function resolvePmPackageRoot(){return fileURLToPath(new URL("../..",import.meta.url))}(typeof process.env[PM_PACKAGE_ROOT_ENV]!="string"||process.env[PM_PACKAGE_ROOT_ENV]?.trim().length===0)&&(process.env[PM_PACKAGE_ROOT_ENV]=resolvePmPackageRoot());const PM_MCP_SERVER_VERSION=resolvePmCliVersion(import.meta.url,["../.."])??"0.0.0",PM_MCP_SERVER_INFO={name:"pm-mcp",version:PM_MCP_SERVER_VERSION,description:"Stateless project-context management through pm SDK contracts.",websiteUrl:"https://github.com/unbraind/pm-cli"},PM_MCP_SERVER_CAPABILITIES={prompts:{listChanged:!0},resources:{listChanged:!0,subscribe:!0},tools:{listChanged:!0},extensions:{[PM_MCP_TASKS_EXTENSION]:{},[PM_MCP_APPS_EXTENSION]:PM_MCP_APPS_SERVER_CAPABILITY,[PM_MCP_SKILLS_EXTENSION]:PM_MCP_SKILLS_SERVER_CAPABILITY,[PM_MCP_PROGRESSIVE_DISCOVERY_EXTENSION]:PM_MCP_PROGRESSIVE_DISCOVERY_SERVER_CAPABILITY}},PM_MCP_SUBSCRIPTIONS=new Map;function createMcpSubscriptionRegistry(){return new PmMcpSubscriptionRegistry({capabilities:PM_MCP_SERVER_CAPABILITIES,serverInfo:PM_MCP_SERVER_INFO})}function pruneClosedMcpSubscriptionRegistries(){for(const[key,subscription]of PM_MCP_SUBSCRIPTIONS)subscription.registry.size===0&&PM_MCP_SUBSCRIPTIONS.delete(key)}const PM_MCP_CACHE_POLICIES={prompts:{ttlMs:6e4,cacheScope:"public"},resource:{ttlMs:0,cacheScope:"private"},resources:{ttlMs:6e4,cacheScope:"public"},tools:{ttlMs:3e4,cacheScope:"private"}},PM_MCP_DIRECT_TASK_TOOLS=new Set(["pm_graph","pm_health","pm_validate"]),PM_MCP_RUN_TASK_ACTIONS=new Set(["graph","health","import","reindex","test-all","validate"]),PM_MCP_SKILL_METHODS=new Set(["skills/list","skills/get","resources/directory/read"]),PM_MCP_INSTRUCTIONS="You have access to native pm CLI tools for git-based project management. When progressive discovery is negotiated, use pm_discover to expand the small entry catalog by intent and request schemas only when needed. Use pm_next to pick the next actionable item, or pm_context or pm_search before creating new work. Prefer narrow tools (pm_next, pm_context, pm_list, pm_get, pm_search, pm_events, pm_create, pm_mutate, pm_copy, pm_focus, pm_update, pm_append, pm_claim, pm_release, pm_close, pm_comments, pm_files, pm_docs, pm_notes, pm_learnings, pm_deps, pm_graph, pm_test, pm_validate, pm_health, pm_contracts, pm_schema, pm_profile, pm_config, pm_plan) over pm_run when they cover the operation. Use pm_plan for agent harness Plan workflows: it provides Codex/Claude/Cursor-style planning with durable steps, dependencies, decisions, discoveries, validation, and materialization. Use pm_schema and pm_config for workspace configuration: pm_schema manages custom item types/statuses and pm_config reads or writes settings keys. Use pm_run with an explicit action for active package-owned operations, plus activity, aggregate, history, stats, test-all, and gc. Use history-redact for audited history-stream redaction workflows, history-repair to re-anchor a drifted history chain, and history-compact to checkpoint/prune long history streams while preserving replay integrity. Agent harness and model provenance are detected automatically; pass author only for an intentional identity override. Do not pass path during real repository tracking \u2014 only pass path for sandbox or test runs.";function declaredToolKeys(tools=TOOLS){return new Map(tools.map(tool=>{const properties=tool.inputSchema.properties??{};return[tool.name,Object.keys(properties)]}))}function nearestDeclaredKey(unexpected,declared){const limit=Math.max(1,Math.min(3,Math.floor(unexpected.length/4)+1));let best;for(const candidate of declared){const distance=levenshteinDistanceWithinLimit(unexpected,candidate,limit);distance!==null&&(best===void 0||distance<best.distance)&&(best={key:candidate,distance})}return best?.key}const UNEXPECTED_KEY_WARNING_EXEMPT_TOOLS=new Set(["pm_run"]),MCP_RETRY_ARGUMENT_KEYS=new Set(["inputResponses","requestState"]);function resolveMcpDiscoveryCursorIntegrityKey(){const configuredKey=process.env.PM_MCP_DISCOVERY_CURSOR_KEY;if(configuredKey===void 0)return;const key=Buffer.from(configuredKey,"utf8");if(key.byteLength<32)throw new PmCliError("PM_MCP_DISCOVERY_CURSOR_KEY must contain at least 32 UTF-8 bytes.",64);return key}function detectUnexpectedTopLevelKeys(toolName,args,toolDeclaredKeys=declaredToolKeys()){if(typeof args!="object"||args===null||Array.isArray(args))return[];if(UNEXPECTED_KEY_WARNING_EXEMPT_TOOLS.has(toolName))return[];const declared=toolDeclaredKeys.get(toolName);if(declared===void 0)return[];const declaredSet=new Set([...declared,...MCP_RETRY_ARGUMENT_KEYS]),warnings=[];for(const key of Object.keys(args)){if(declaredSet.has(key))continue;const suggestion=nearestDeclaredKey(key,declared);warnings.push(suggestion!==void 0?`Unexpected top-level argument "${key}" for ${toolName} (did you mean "${suggestion}"?). It is not declared and may be ignored; declared arguments are: ${declared.join(", ")}.`:`Unexpected top-level argument "${key}" for ${toolName}. It is not declared and may be ignored; declared arguments are: ${declared.join(", ")}.`)}return warnings}const HANDLERS={pm_run:args=>runMcpAction(args),pm_discover:async args=>{const surface=await resolveMcpToolSurface(TOOLS,args),cursorIntegrityKey=resolveMcpDiscoveryCursorIntegrityKey(),discoveryOptions=parsePmToolDiscoveryOptions(args);return discoverPmTools(surface.tools.map(tool=>({name:tool.name,description:tool.description,inputSchema:tool.inputSchema,authorized:!0,signals:{freshness:1,usage:PM_MCP_ENTRY_TOOL_NAMES.includes(tool.name)?1:0}})),{...discoveryOptions,profile:surface.profile,...cursorIntegrityKey===void 0?{}:{cursorIntegrityKey}})},pm_mutate:async args=>{const transactionId=readRequiredString(args,"transactionId"),controls=parseAtomicMutationControls(args),cwd=typeof args.cwd=="string"?args.cwd:process.cwd(),pmRoot=resolvePmRoot(cwd,typeof args.path=="string"?args.path:void 0),resolved=resolveItemMutationDocument(JSON.stringify({schema_version:1,mutations:args.mutations}),{transactionId,idPrefix:(await readSettings(pmRoot)).id_prefix}),{mutations,references}=resolved;if(args.dryRun===!0){const validation=await runWithActiveExtensions({cwd:typeof args.cwd=="string"?args.cwd:void 0,path:pmRoot,noExtensions:args.noExtensions===!0},()=>previewItemMutations({pmRoot,transactionId,author:resolveAuthor(typeof args.author=="string"?args.author:void 0,"unknown"),mutations}));return{transaction_id:transactionId,dry_run:!0,validation,mutation_count:mutations.length,mutations,references}}const result=await runWithActiveExtensions({cwd:typeof args.cwd=="string"?args.cwd:void 0,path:typeof args.path=="string"?args.path:void 0,noExtensions:args.noExtensions===!0},()=>commitItemMutations({pmRoot,transactionId,author:resolveAuthor(typeof args.author=="string"?args.author:void 0,"unknown"),mutations,...controls})),{transactionId:committedTransactionId,...commitResult}=result;return{...commitResult,transaction_id:committedTransactionId,mutation_count:mutations.length,references}},...Object.fromEntries(Object.entries(NARROW_TOOL_ACTIONS).map(([tool,action])=>[tool,args=>runMcpAction({...args,action})]))};function resolveInvokedAction(toolName,args){return toolName==="pm_run"?typeof args.action=="string"?args.action:void 0:NARROW_TOOL_ACTIONS[toolName]}async function collectMutationGuardWarnings(toolName,action,args){if(toolName!=="pm_mutate"&&!isMutationAction(action??""))return[];const cwd=typeof args.cwd=="string"?args.cwd:process.cwd(),pmRoot=resolvePmRoot(cwd,typeof args.path=="string"?args.path:void 0);if(!await pathExists(getSettingsPath(pmRoot)))return[];const settings=await readSettings(pmRoot),nestedOptions=typeof args.options=="object"&&args.options!==null&&!Array.isArray(args.options)?args.options:{};return evaluateMutationGuard({author:resolveAuthor(typeof args.author=="string"?args.author:typeof nestedOptions.author=="string"?nestedOptions.author:void 0,settings.author_default),payload:Object.fromEntries(Object.entries(args).filter(([key])=>key!=="cwd"&&key!=="path")),settings:settings.mutation_guard,force:args.force===!0||nestedOptions.force===!0}).warnings}function detectUnexpectedOptionKeys(toolName,action,args){const options=args.options;if(action===void 0||typeof options!="object"||options===null||Array.isArray(options))return[];const declared=pmToolActionNestedOptionKeys(action);if(declared===void 0)return[];const declaredSet=new Set(declared),warnings=[];for(const key of Object.keys(options)){if(declaredSet.has(key))continue;const suggestion=nearestDeclaredKey(key,declared);warnings.push(suggestion!==void 0?`Unknown option "${key}" for ${toolName} action "${action}" (did you mean "${suggestion}"?). The ${action} contract does not read it, so it has no effect; declared keys are: ${declared.join(", ")}.`:`Unknown option "${key}" for ${toolName} action "${action}". The ${action} contract does not read it, so it has no effect; declared keys are: ${declared.join(", ")}.`)}return warnings}function resultContent(result,warnings,tokenAccounting=!1,canonicalStructuredResult=!1){const effectiveResult=tokenAccounting?attachOutputTokenAccounting(result,value=>JSON.stringify(value,null,2)):result,structuredContent=warnings!==void 0&&warnings.length>0?{result:effectiveResult,warnings}:{result:effectiveResult};return{content:[{type:"text",text:canonicalStructuredResult?"Canonical result: structuredContent.result":JSON.stringify(effectiveResult,null,2)}],structuredContent}}function errorContent(error,canonicalStructuredResult=!1){const code=error instanceof PmCliError?error.exitCode:1,message=error instanceof Error?error.message:String(error),details=error instanceof PmCliError?error.context:void 0;return{isError:!0,content:[{type:"text",text:canonicalStructuredResult?"Canonical error: structuredContent":JSON.stringify({error:message,code,details},null,2)}],structuredContent:{result:null,error:message,code,details}}}function boundMcpClientProvenance(value){const provenance=isRuntimeRecord(value)?value:{},bounded={};let acceptedCount=0;for(const key in provenance){if(acceptedCount>=32)break;if(!Object.prototype.hasOwnProperty.call(provenance,key))continue;const entry=provenance[key];/^[a-z][a-z0-9_-]{0,63}$/u.test(key)&&typeof entry=="string"&&entry.trim().length>0&&(bounded[key]=entry.trim().slice(0,256),acceptedCount+=1)}return bounded}function readMcpClientInfo(value){const clientInfo=isRuntimeRecord(value)?value:{},clientName=typeof clientInfo.name=="string"?clientInfo.name.trim():"";if(clientName.length===0)return;const optionalValues=[["version",clientInfo.version,128],["model",clientInfo.model,256],["session",clientInfo.session,256]],result={name:clientName.slice(0,128)};for(const[key,value2,limit]of optionalValues)typeof value2=="string"&&value2.trim().length>0&&(result[key]=value2.trim().slice(0,limit));const boundedProvenance=boundMcpClientProvenance(clientInfo.provenance);Object.keys(boundedProvenance).length>0&&(result.provenance=boundedProvenance);const episode=boundAgentEpisodeIdentity(clientInfo.episode,!1);return episode!==void 0&&(result.episode=episode),result}async function emitMcpChangeNotifications(action){isMutationAction(action??"")&&await Promise.all([...PM_MCP_SUBSCRIPTIONS.values()].flatMap(({registry})=>PM_MCP_RESOURCE_CONTRACTS.map(resource=>registry.emitResourceUpdated(resource.uri)))),["extension","install","package","uninstall"].includes(action??"")&&await Promise.all([...PM_MCP_SUBSCRIPTIONS.values()].map(({registry})=>registry.emitListChanged("tools"))),pruneClosedMcpSubscriptionRegistries()}async function handleToolCall(paramsInput,clientInfo,progressiveDiscoveryNegotiated=!1){const clientSignals=clientInfo?{client_info:clientInfo}:{};return runWithHarnessDetectionSignals({env:process.env,argv:process.argv,...clientSignals},async()=>{const params=asRecordClone(paramsInput),name=readRequiredString(params,"name"),handler=Object.prototype.hasOwnProperty.call(HANDLERS,name)?HANDLERS[name]:void 0;if(!handler)throw new PmCliError(`Unknown pm MCP tool: ${name}`,64);const inputResponses=params.inputResponses===void 0?void 0:parseMcpInputResponses(params.inputResponses);validateMcpToolArguments(params.arguments);const requestedArgs={...decodeHtmlEntitiesInOptions(asRecordClone(params.arguments)),...inputResponses?{inputResponses}:{},...typeof params.requestState=="string"?{requestState:params.requestState}:{}},access=await resolveMcpToolAccess(TOOLS,name,requestedArgs),requiredCustomDiscoveryEntry=progressiveDiscoveryNegotiated&&access.profile==="custom"&&name==="pm_discover";if(!access.available&&!requiredCustomDiscoveryEntry)throw new PmCliError(`pm MCP tool "${name}" is unavailable in the ${access.profile} profile.`,64);const args=await normalizeWorkspaceToolArguments(name,requestedArgs),cwd=typeof args.cwd=="string"?args.cwd:process.cwd(),pmRoot=resolvePmRoot(cwd,typeof args.path=="string"?args.path:void 0),workspaceIdentity=await pathExists(getSettingsPath(pmRoot))?(await readSettings(pmRoot)).agent_identity:void 0;return runWithHarnessDetectionSignals({env:{...process.env,PM_PATH:pmRoot},argv:process.argv,cwd,...clientSignals},()=>runWithWorkspaceHarnessSignalDescriptors(workspaceIdentity?.harness_signals??[],async()=>{const action=resolveInvokedAction(name,args),warnings=[...detectUnexpectedTopLevelKeys(name,args,declaredToolKeys()),...detectUnexpectedOptionKeys(name,action,args),...await collectMutationGuardWarnings(name,action,args)];for(const warning of warnings)console.error(`[pm-mcp] ${warning}`);const result=await handler(args);return emitMcpChangeNotifications(action),resultContent(result,warnings,args.tokenAccounting===!0,progressiveDiscoveryNegotiated)},{probesEnabled:workspaceIdentity?.probes_enabled}))})}async function openMcpSubscription(input){if(typeof input.request.id!="string"&&typeof input.request.id!="number"||input.request.method!=="subscriptions/listen")throw new PmMcpProtocolError("Invalid MCP subscriptions/listen request",PM_MCP_ERROR_CODES.invalidParams,{required:["id","method","params.notifications"]});resolveMcpRequestContext(input.request.params);const key=input.key??input.request.id;if(PM_MCP_SUBSCRIPTIONS.has(key))throw new PmMcpProtocolError("MCP subscription id is already active",PM_MCP_ERROR_CODES.invalidParams,{subscriptionId:input.request.id});const registry=createMcpSubscriptionRegistry();await registry.open({id:input.request.id,notifications:input.request.params?.notifications,sink:input.sink}),PM_MCP_SUBSCRIPTIONS.set(key,{id:input.request.id,registry})}function closeMcpSubscription(id,key=id){const subscription=PM_MCP_SUBSCRIPTIONS.get(key);if(!(!subscription||subscription.id!==id))return PM_MCP_SUBSCRIPTIONS.delete(key),subscription.registry.close(id)}function closeStdioMcpSubscriptions(){const closed=[];for(const[key,subscription]of PM_MCP_SUBSCRIPTIONS){if(key!==subscription.id)continue;const result=closeMcpSubscription(subscription.id,key);result&&closed.push({id:subscription.id,result})}return closed}async function resolveMcpToolSchemaForRequest(request){if(request.method!=="tools/call")return;const name=request.params?.name;return typeof name!="string"?void 0:(await resolveMcpToolSurface(TOOLS,requestWorkspaceArgs(request.params))).tools.find(tool=>tool.name===name)?.inputSchema}function buildMcpToolCallErrorResult(request,error){if(request.method!=="tools/call"||error instanceof PmMcpProtocolError)return;const content=errorContent(error,hasMcpProtocolVersionMetadata(request)&&hasMcpClientExtension(resolveMcpRequestContext(request.params),PM_MCP_PROGRESSIVE_DISCOVERY_EXTENSION));return hasMcpProtocolVersionMetadata(request)?buildMcpCompleteResult(content,PM_MCP_SERVER_INFO):content}function requestWorkspaceArgs(params){const paramsRecord=asRecordClone(params);return asRecordClone(paramsRecord.arguments??paramsRecord)}async function readWorkspaceResource(uri,params){const args=requestWorkspaceArgs(params),cwd=typeof args.cwd=="string"?args.cwd:process.cwd(),contract=PM_MCP_RESOURCE_CONTRACTS.find(resource=>resource.uri===uri);if(!contract)throw new PmCliError(`Unknown pm MCP resource: ${uri}`,64);let value;if(uri==="pm://workspace/context")value=await runMcpAction({...args,action:"context",limit:10});else if(uri==="pm://workspace/claims")value=await runMcpAction({...args,action:"list",status:"in_progress",limit:20});else if(uri==="pm://workspace/focus")value=await runMcpAction({...args,action:"focus",subcommand:"show"});else{const guidePath=path.join(cwd,"AGENTS.md");value=await pathExists(guidePath)?(await readFile(guidePath,"utf8")).slice(0,32e3):"No repository-local AGENTS.md was found."}return{contents:[{uri,mimeType:contract.mimeType,text:typeof value=="string"?value:JSON.stringify(value,null,2)}]}}async function loadRequestSkillRegistry(params){const args=requestWorkspaceArgs(params),cwd=typeof args.cwd=="string"?args.cwd:process.cwd(),workspaceRoot=resolveWorkspaceRoot(resolvePmRoot(cwd,typeof args.path=="string"?args.path:void 0));return PmMcpSkillRegistry.load({packageRoot:resolvePmPackageRoot(),workspaceRoot,packageVersion:PM_MCP_SERVER_VERSION})}function renderWorkflowPrompt(params){const paramsRecord=asRecordClone(params),name=readRequiredString(paramsRecord,"name"),prompt=PM_MCP_PROMPT_CONTRACTS.find(candidate=>candidate.name===name);if(!prompt)throw new PmCliError(`Unknown pm MCP prompt: ${name}`,64);const argumentsRecord=asRecordClone(paramsRecord.arguments);let text=prompt.template;for(const argument of prompt.arguments){const value=argumentsRecord[argument.name];if(argument.required&&(typeof value!="string"||value.trim().length===0))throw new PmCliError(`Missing required prompt argument: ${argument.name}`,64);text=text.replaceAll(`{{${argument.name}}}`,typeof value=="string"?value:"")}return{description:prompt.description,messages:[{role:"user",content:{type:"text",text}}]}}const LEGACY_MCP_ADAPTER=new LegacyMcpAdapter({serverInfo:PM_MCP_SERVER_INFO,capabilities:PM_MCP_SERVER_CAPABILITIES,instructions:PM_MCP_INSTRUCTIONS,parseClientInfo:readMcpClientInfo,listTools:async params=>({tools:(await resolveMcpToolSurface(TOOLS,requestWorkspaceArgs(params))).tools}),callTool:handleToolCall,listResources:()=>({resources:PM_MCP_RESOURCE_CONTRACTS}),readResource:params=>readWorkspaceResource(readRequiredString(asRecordClone(params),"uri"),params),listPrompts:()=>({prompts:PM_MCP_PROMPT_CONTRACTS.map(prompt=>({name:prompt.name,description:prompt.description,arguments:prompt.arguments}))}),getPrompt:renderWorkflowPrompt});function deterministicMcpTools(tools){return tools.map(tool=>({...tool,inputSchema:validateMcpJsonSchema(tool.inputSchema)})).sort((left,right)=>left.name.localeCompare(right.name))}function mcpTaskPrincipal(requestContext){return requestContext.clientInfo?`${requestContext.clientInfo.name}@${requestContext.clientInfo.version}`:"anonymous-stdio"}function mcpTaskStore(){return createMcpTaskStore({pmRoot:resolvePmRoot(process.cwd()),owner:"pm-mcp-task-provider"})}function validateMcpToolArguments(value){if(value!==void 0&&!isMcpRecord(value))throw new PmCliError("pm MCP tool arguments must be an object.",64)}function shouldCreateMcpTask(params,requestContext){if(!hasMcpClientExtension(requestContext,PM_MCP_TASKS_EXTENSION))return!1;const requestParams=asRecordClone(params),name=requestParams.name,args=asRecordClone(requestParams.arguments);return PM_MCP_DIRECT_TASK_TOOLS.has(name)||name==="pm_test"&&(args.subcommand==="run"||isMcpRecord(args.options)&&args.options.subcommand==="run")?!0:name!=="pm_run"?!1:typeof args.action=="string"&&PM_MCP_RUN_TASK_ACTIONS.has(args.action)}const PENDING_MCP_TASKS=new Map;async function executeMcpTask(execution,inputResponses){const params={...execution.params,...inputResponses?{inputResponses}:{},...execution.requestState?{requestState:execution.requestState}:{}};try{const result=await handleToolCall(params,execution.context.clientInfo,hasMcpClientExtension(execution.context,PM_MCP_PROGRESSIVE_DISCOVERY_EXTENSION));await execution.store.complete(execution.taskId,execution.principal,buildMcpCompleteResult(result,PM_MCP_SERVER_INFO)),PENDING_MCP_TASKS.delete(execution.taskId)}catch(error){if(error instanceof PmMcpInputRequiredError){execution.requestState=error.requestState,await execution.store.requireInput({taskId:execution.taskId,principal:execution.principal,requestContext:execution.context,inputRequests:error.inputRequests,statusMessage:"Task requires additional client input."});return}error instanceof PmMcpProtocolError?await execution.store.fail(execution.taskId,execution.principal,{code:error.code,message:error.message,data:error.data}):await execution.store.complete(execution.taskId,execution.principal,buildMcpCompleteResult(errorContent(error,hasMcpClientExtension(execution.context,PM_MCP_PROGRESSIVE_DISCOVERY_EXTENSION)),PM_MCP_SERVER_INFO)),PENDING_MCP_TASKS.delete(execution.taskId)}}async function settleMcpTaskExecution(taskId,execution){try{await execution}catch{PENDING_MCP_TASKS.delete(taskId)}}function scheduleMcpTaskExecution(execution,inputResponses){settleMcpTaskExecution(execution.taskId,executeMcpTask(execution,inputResponses))}async function createMcpTaskForToolCall(params,requestContext){const store=mcpTaskStore(),principal=mcpTaskPrincipal(requestContext),task=await store.create({principal,statusMessage:"pm operation accepted for asynchronous execution."}),execution={context:requestContext,params:asRecordClone(params),principal,store,taskId:task.taskId};return PENDING_MCP_TASKS.set(task.taskId,execution),scheduleMcpTaskExecution(execution),attachMcpServerInfo(task,PM_MCP_SERVER_INFO)}async function dispatchMcpTaskMethod(request,requestContext){if(!hasMcpClientExtension(requestContext,PM_MCP_TASKS_EXTENSION))throw new PmMcpProtocolError("Missing required client capability",PM_MCP_ERROR_CODES.missingRequiredClientCapability,{requiredCapabilities:{extensions:{[PM_MCP_TASKS_EXTENSION]:{}}}});const params=asRecordClone(request.params),taskId=readRequiredString(params,"taskId"),principal=mcpTaskPrincipal(requestContext),store=mcpTaskStore();if(request.method==="tasks/get")return buildMcpCompleteResult(await store.get(taskId,principal),PM_MCP_SERVER_INFO);if(request.method==="tasks/update"){const update=await store.update(taskId,principal,params.inputResponses),execution=PENDING_MCP_TASKS.get(taskId);return execution&&update.acceptedKeys.length>0&&update.remainingKeys.length===0&&scheduleMcpTaskExecution(execution,await store.takeInputResponses(taskId,principal)),buildMcpCompleteResult({},PM_MCP_SERVER_INFO)}return await store.cancel(taskId,principal),PENDING_MCP_TASKS.delete(taskId),buildMcpCompleteResult({},PM_MCP_SERVER_INFO)}async function dispatchModernToolMethod(request,requestContext,clientInfo){if(request.method==="tools/list"){const surface=await resolveMcpToolSurface(TOOLS,requestWorkspaceArgs(request.params)),listedTools=hasMcpClientExtension(requestContext,PM_MCP_PROGRESSIVE_DISCOVERY_EXTENSION)?[...surface.tools.filter(tool=>PM_MCP_ENTRY_TOOL_NAMES.includes(tool.name)),...surface.profile==="custom"&&!surface.tools.some(tool=>tool.name==="pm_discover")?TOOLS.filter(tool=>tool.name==="pm_discover"):[]]:surface.tools;return buildMcpCompleteResult(withMcpCachePolicy({tools:hasCompatiblePmMcpAppsCapability(requestContext)?decoratePmMcpToolsWithApps(deterministicMcpTools(listedTools)):deterministicMcpTools(listedTools)},PM_MCP_CACHE_POLICIES.tools),PM_MCP_SERVER_INFO)}if(validateMcpToolArguments(request.params?.arguments),shouldCreateMcpTask(request.params,requestContext))return createMcpTaskForToolCall(request.params,requestContext);try{return buildMcpCompleteResult(await handleToolCall(request.params,clientInfo,hasMcpClientExtension(requestContext,PM_MCP_PROGRESSIVE_DISCOVERY_EXTENSION)),PM_MCP_SERVER_INFO)}catch(error){if(!(error instanceof PmMcpInputRequiredError))throw error;return buildMcpInputRequiredResult({requestContext,serverInfo:PM_MCP_SERVER_INFO,inputRequests:error.inputRequests,requestState:error.requestState})}}async function dispatchModernResourceMethod(request,requestContext){if(request.method==="resources/list"){const resources=[...PM_MCP_RESOURCE_CONTRACTS,...hasCompatiblePmMcpAppsCapability(requestContext)?PM_MCP_APP_CONTRACTS.map(contract=>({uri:contract.uri,name:contract.name,description:contract.description,mimeType:PM_MCP_APP_MIME_TYPE,_meta:{ui:contract.resourceMeta}})):[]].sort((left,right)=>left.uri.localeCompare(right.uri));return buildMcpCompleteResult(withMcpCachePolicy({resources},PM_MCP_CACHE_POLICIES.resources),PM_MCP_SERVER_INFO)}if(request.method==="resources/templates/list")return buildMcpCompleteResult(withMcpCachePolicy({resourceTemplates:[]},PM_MCP_CACHE_POLICIES.resources),PM_MCP_SERVER_INFO);try{const uri=readRequiredString(asRecordClone(request.params),"uri"),app=findPmMcpAppByUri(uri);let resource;if(app){if(!hasPmMcpAppsCapability(requestContext))throw new PmMcpProtocolError("MCP App resource requires negotiated client capability",PM_MCP_ERROR_CODES.missingRequiredClientCapability,{requiredCapabilities:{extensions:{[PM_MCP_APPS_EXTENSION]:PM_MCP_APPS_SERVER_CAPABILITY}}});resource={contents:[{uri,mimeType:PM_MCP_APP_MIME_TYPE,text:renderPmMcpAppHtml(app),_meta:{ui:app.resourceMeta}}]}}else uri.startsWith("skill://")?(assertPmMcpSkillsCapability(requestContext),resource={...(await loadRequestSkillRegistry(request.params)).read(uri)}):resource=await readWorkspaceResource(uri,request.params);return buildMcpCompleteResult(withMcpCachePolicy(resource,PM_MCP_CACHE_POLICIES.resource),PM_MCP_SERVER_INFO)}catch(error){throw!(error instanceof PmCliError)||!error.message.startsWith("Unknown pm MCP resource:")?error:new PmMcpProtocolError(error.message,PM_MCP_ERROR_CODES.invalidParams,{field:"uri"})}}function hasCompatiblePmMcpAppsCapability(requestContext){try{return hasPmMcpAppsCapability(requestContext)}catch(error){if(error instanceof PmMcpProtocolError)return!1;throw error}}function readSkillPageOptions(params){if(params.cursor!==void 0&&typeof params.cursor!="string")throw new PmMcpProtocolError("Skills cursor must be a string",PM_MCP_ERROR_CODES.invalidParams,{field:"cursor"});if(params.limit!==void 0&&typeof params.limit!="number")throw new PmMcpProtocolError("Skills limit must be a number",PM_MCP_ERROR_CODES.invalidParams,{field:"limit"});return{...typeof params.cursor=="string"?{cursor:params.cursor}:{},...typeof params.limit=="number"?{limit:params.limit}:{}}}async function dispatchModernSkillMethod(request,requestContext){const directoryRead=request.method==="resources/directory/read";assertPmMcpSkillsCapability(requestContext,directoryRead);const params=asRecordClone(request.params),registry=await loadRequestSkillRegistry(request.params);let result;return request.method==="skills/list"?result={...registry.list(readSkillPageOptions(params))}:request.method==="skills/get"?result={skill:registry.get(readRequiredString(params,"uri"))}:result={...registry.readDirectory(readRequiredString(params,"uri"),readSkillPageOptions(params))},buildMcpCompleteResult(withMcpCachePolicy(result,PM_MCP_CACHE_POLICIES.resource),PM_MCP_SERVER_INFO)}function dispatchModernPromptMethod(request){const result=request.method==="prompts/list"?withMcpCachePolicy({prompts:PM_MCP_PROMPT_CONTRACTS.map(prompt=>({name:prompt.name,description:prompt.description,arguments:prompt.arguments})).sort((left,right)=>left.name.localeCompare(right.name))},PM_MCP_CACHE_POLICIES.prompts):renderWorkflowPrompt(request.params);return buildMcpCompleteResult(result,PM_MCP_SERVER_INFO)}async function dispatchModernMcpRequest(request,meta){const requestContext=resolveMcpRequestContext(request.params),clientInfo=readMcpClientInfo(meta[PM_MCP_META_KEYS.clientInfo]);if(request.method==="server/discover")return buildMcpDiscoverResult({serverInfo:PM_MCP_SERVER_INFO,capabilities:PM_MCP_SERVER_CAPABILITIES,instructions:PM_MCP_INSTRUCTIONS});if(request.method==="ping")throw new PmMcpProtocolError("MCP method not found: ping",-32601,{removedIn:PM_MCP_PROTOCOL_VERSION});if(PM_MCP_SKILL_METHODS.has(request.method??""))return dispatchModernSkillMethod(request,requestContext);if(request.method==="tasks/get"||request.method==="tasks/update"||request.method==="tasks/cancel")return dispatchMcpTaskMethod(request,requestContext);if(request.method==="tools/list"||request.method==="tools/call")return dispatchModernToolMethod(request,requestContext,clientInfo);if(request.method==="resources/list"||request.method==="resources/templates/list"||request.method==="resources/read")return dispatchModernResourceMethod(request,requestContext);if(request.method==="prompts/list"||request.method==="prompts/get")return dispatchModernPromptMethod(request);throw new PmMcpProtocolError(`MCP method not found: ${request.method??"(missing)"}`,-32601)}async function handleRequestInReproducibleContext(request){if(!(!request.id&&request.method?.startsWith("notifications/"))){if(hasMcpProtocolVersionMetadata(request)){const allowlist=(process.env.PM_MCP_BAGGAGE_ALLOWLIST??"").split(",").map(entry=>entry.trim()).filter(Boolean);return runWithMcpTraceContext(extractMcpTraceContext(request.params,{baggageAllowlist:allowlist}),()=>dispatchModernMcpRequest(request,request.params._meta))}return request.method==="initialize"?LEGACY_MCP_ADAPTER.initialize(request.params):LEGACY_MCP_ADAPTER.dispatch(request)}}function hasMcpProtocolVersionMetadata(request){const meta=isMcpRecord(request.params)?request.params._meta:void 0;return isMcpRecord(meta)&&Object.prototype.hasOwnProperty.call(meta,PM_MCP_META_KEYS.protocolVersion)}async function handleRequest(request){return runWithReproducibleProcessEnvironment(process.env,()=>handleRequestInReproducibleContext(request))}function writeResponse(id,payload){process.stdout.write(`${JSON.stringify({jsonrpc:"2.0",id,result:payload})}
|
|
2
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="4f5b83c9-8f48-5a2c-9058-cd993d25dc98")}catch{}})();import{realpathSync}from"node:fs";import{readFile}from"node:fs/promises";import path from"node:path";import readline from"node:readline";import{fileURLToPath}from"node:url";import{resolvePmCliVersion,EXIT_CODE,PmCliError,decodeHtmlEntitiesInOptions,levenshteinDistanceWithinLimit,asRecordClone,createSerialQueue,evaluateMutationGuard,getSettingsPath,isMutationAction,pathExists,readSettings,runWithHarnessDetectionSignals,runWithWorkspaceHarnessSignalDescriptors,boundAgentEpisodeIdentity}from"../sdk/runtime-primitives.js";import{pmToolActionNestedOptionKeys}from"../sdk/cli-contracts/tool-schema.js";import{readRequiredString,runAction,runWithActiveExtensions}from"../sdk/runtime.js";import{NARROW_TOOL_ACTIONS,TOOLS}from"./tool-definitions.js";import{normalizeWorkspaceToolArguments,resolveMcpToolAccess,resolveMcpToolSurface}from"./runtime-capabilities.js";import{PM_MCP_PROMPT_CONTRACTS,PM_MCP_RESOURCE_CONTRACTS}from"../sdk/agent-capability-contracts.js";import{PM_MCP_ENTRY_TOOL_NAMES,PM_MCP_PROGRESSIVE_DISCOVERY_EXTENSION,PM_MCP_PROGRESSIVE_DISCOVERY_SERVER_CAPABILITY,discoverPmTools,parsePmToolDiscoveryOptions}from"../sdk/mcp/discovery.js";import{commitItemMutations,previewItemMutations}from"../sdk/item-transaction.js";import{isRuntimeRecord,markMcpMutationTransportInput}from"../sdk/runtime-input.js";import{attachOutputTokenAccounting}from"../sdk/output-token-accounting.js";import{createReproducibleProcessRunner,runWithReproducibleProcessEnvironment}from"../sdk/reproducibility/process.js";import{parseAtomicMutationControls}from"../sdk/structured-mutations.js";import{planItemMutationDocument}from"../sdk/lifecycle/structured-mutation-plan.js";import{resolveAuthor,resolvePmRoot,resolveWorkspaceRoot}from"../sdk/runtime-primitives.js";import{PM_MCP_ERROR_CODES,PM_MCP_META_KEYS,PM_MCP_PROTOCOL_VERSION,PmMcpProtocolError,attachMcpServerInfo,buildMcpCompleteResult,buildMcpDiscoverResult,hasMcpClientExtension,isMcpRecord,resolveMcpRequestContext}from"../sdk/mcp/protocol.js";import{PmMcpInputRequiredError,buildMcpInputRequiredResult,parseMcpInputResponses,validateMcpJsonSchema,withMcpCachePolicy}from"../sdk/mcp/interactions.js";import{PM_MCP_TASKS_EXTENSION,createMcpTaskStore}from"../sdk/mcp/tasks.js";import{PmMcpSubscriptionRegistry}from"../sdk/mcp/subscriptions.js";import{extractMcpTraceContext,runWithMcpTraceContext}from"../sdk/mcp/authorization.js";import{LegacyMcpAdapter}from"./legacy-adapter.js";import{PM_MCP_APP_CONTRACTS,PM_MCP_APP_MIME_TYPE,PM_MCP_APPS_EXTENSION,PM_MCP_APPS_SERVER_CAPABILITY,decoratePmMcpToolsWithApps,findPmMcpAppByUri,hasPmMcpAppsCapability,renderPmMcpAppHtml}from"../sdk/mcp/apps.js";import{PM_MCP_SKILLS_EXTENSION,PM_MCP_SKILLS_SERVER_CAPABILITY,PmMcpSkillRegistry,assertPmMcpSkillsCapability}from"../sdk/mcp/skills.js";function runMcpAction(args){return runAction(markMcpMutationTransportInput(args))}const PM_PACKAGE_ROOT_ENV="PM_CLI_PACKAGE_ROOT";function resolvePmPackageRoot(){return fileURLToPath(new URL("../..",import.meta.url))}(typeof process.env[PM_PACKAGE_ROOT_ENV]!="string"||process.env[PM_PACKAGE_ROOT_ENV]?.trim().length===0)&&(process.env[PM_PACKAGE_ROOT_ENV]=resolvePmPackageRoot());const PM_MCP_SERVER_VERSION=resolvePmCliVersion(import.meta.url,["../.."])??"0.0.0",PM_MCP_SERVER_INFO={name:"pm-mcp",version:PM_MCP_SERVER_VERSION,description:"Stateless project-context management through pm SDK contracts.",websiteUrl:"https://github.com/unbraind/pm-cli"},PM_MCP_SERVER_CAPABILITIES={prompts:{listChanged:!0},resources:{listChanged:!0,subscribe:!0},tools:{listChanged:!0},extensions:{[PM_MCP_TASKS_EXTENSION]:{},[PM_MCP_APPS_EXTENSION]:PM_MCP_APPS_SERVER_CAPABILITY,[PM_MCP_SKILLS_EXTENSION]:PM_MCP_SKILLS_SERVER_CAPABILITY,[PM_MCP_PROGRESSIVE_DISCOVERY_EXTENSION]:PM_MCP_PROGRESSIVE_DISCOVERY_SERVER_CAPABILITY}},PM_MCP_SUBSCRIPTIONS=new Map;function createMcpSubscriptionRegistry(){return new PmMcpSubscriptionRegistry({capabilities:PM_MCP_SERVER_CAPABILITIES,serverInfo:PM_MCP_SERVER_INFO})}function pruneClosedMcpSubscriptionRegistries(){for(const[key,subscription]of PM_MCP_SUBSCRIPTIONS)subscription.registry.size===0&&PM_MCP_SUBSCRIPTIONS.delete(key)}const PM_MCP_CACHE_POLICIES={prompts:{ttlMs:6e4,cacheScope:"public"},resource:{ttlMs:0,cacheScope:"private"},resources:{ttlMs:6e4,cacheScope:"public"},tools:{ttlMs:3e4,cacheScope:"private"}},PM_MCP_DIRECT_TASK_TOOLS=new Set(["pm_graph","pm_health","pm_validate"]),PM_MCP_RUN_TASK_ACTIONS=new Set(["graph","health","import","reindex","test-all","validate"]),PM_MCP_SKILL_METHODS=new Set(["skills/list","skills/get","resources/directory/read"]),PM_MCP_INSTRUCTIONS="You have access to native pm CLI tools for git-based project management. When progressive discovery is negotiated, use pm_discover to expand the small entry catalog by intent and request schemas only when needed. Use pm_next to pick the next actionable item, or pm_context or pm_search before creating new work. Prefer narrow tools (pm_next, pm_context, pm_list, pm_get, pm_search, pm_events, pm_create, pm_mutate, pm_copy, pm_focus, pm_update, pm_append, pm_claim, pm_release, pm_close, pm_comments, pm_files, pm_docs, pm_notes, pm_learnings, pm_deps, pm_graph, pm_test, pm_validate, pm_health, pm_contracts, pm_schema, pm_profile, pm_config, pm_plan) over pm_run when they cover the operation. Use pm_plan for agent harness Plan workflows: it provides Codex/Claude/Cursor-style planning with durable steps, dependencies, decisions, discoveries, validation, and materialization. Use pm_schema and pm_config for workspace configuration: pm_schema manages custom item types/statuses and pm_config reads or writes settings keys. Use pm_run with an explicit action for active package-owned operations, plus activity, aggregate, history, stats, test-all, and gc. Use history-redact for audited history-stream redaction workflows, history-repair to re-anchor a drifted history chain, and history-compact to checkpoint/prune long history streams while preserving replay integrity. Agent harness and model provenance are detected automatically; pass author only for an intentional identity override. Do not pass path during real repository tracking \u2014 only pass path for sandbox or test runs.";function declaredToolKeys(tools=TOOLS){return new Map(tools.map(tool=>{const properties=tool.inputSchema.properties??{};return[tool.name,Object.keys(properties)]}))}function nearestDeclaredKey(unexpected,declared){const limit=Math.max(1,Math.min(3,Math.floor(unexpected.length/4)+1));let best;for(const candidate of declared){const distance=levenshteinDistanceWithinLimit(unexpected,candidate,limit);distance!==null&&(best===void 0||distance<best.distance)&&(best={key:candidate,distance})}return best?.key}const UNEXPECTED_KEY_WARNING_EXEMPT_TOOLS=new Set(["pm_run"]),MCP_RETRY_ARGUMENT_KEYS=new Set(["inputResponses","requestState"]);function resolveMcpDiscoveryCursorIntegrityKey(){const configuredKey=process.env.PM_MCP_DISCOVERY_CURSOR_KEY;if(configuredKey===void 0)return;const key=Buffer.from(configuredKey,"utf8");if(key.byteLength<32)throw new PmCliError("PM_MCP_DISCOVERY_CURSOR_KEY must contain at least 32 UTF-8 bytes.",64);return key}function detectUnexpectedTopLevelKeys(toolName,args,toolDeclaredKeys=declaredToolKeys()){if(typeof args!="object"||args===null||Array.isArray(args))return[];if(UNEXPECTED_KEY_WARNING_EXEMPT_TOOLS.has(toolName))return[];const declared=toolDeclaredKeys.get(toolName);if(declared===void 0)return[];const declaredSet=new Set([...declared,...MCP_RETRY_ARGUMENT_KEYS]),warnings=[];for(const key of Object.keys(args)){if(declaredSet.has(key))continue;const suggestion=nearestDeclaredKey(key,declared);warnings.push(suggestion!==void 0?`Unexpected top-level argument "${key}" for ${toolName} (did you mean "${suggestion}"?). It is not declared and may be ignored; declared arguments are: ${declared.join(", ")}.`:`Unexpected top-level argument "${key}" for ${toolName}. It is not declared and may be ignored; declared arguments are: ${declared.join(", ")}.`)}return warnings}const HANDLERS={pm_run:args=>runMcpAction(args),pm_discover:async args=>{const surface=await resolveMcpToolSurface(TOOLS,args),cursorIntegrityKey=resolveMcpDiscoveryCursorIntegrityKey(),discoveryOptions=parsePmToolDiscoveryOptions(args);return discoverPmTools(surface.tools.map(tool=>({name:tool.name,description:tool.description,inputSchema:tool.inputSchema,authorized:!0,signals:{freshness:1,usage:PM_MCP_ENTRY_TOOL_NAMES.includes(tool.name)?1:0}})),{...discoveryOptions,profile:surface.profile,...cursorIntegrityKey===void 0?{}:{cursorIntegrityKey}})},pm_mutate:async args=>{if(!Array.isArray(args.mutations)||args.mutations.length===0)throw new PmCliError("pm_mutate requires a non-empty mutations array.",EXIT_CODE.USAGE);const explicitTransactionId=args.transactionId===void 0?void 0:readRequiredString(args,"transactionId"),upsertKey=args.upsertKey===void 0?void 0:readRequiredString(args,"upsertKey"),controls=parseAtomicMutationControls(args),cwd=typeof args.cwd=="string"?args.cwd:process.cwd(),pmRoot=resolvePmRoot(cwd,typeof args.path=="string"?args.path:void 0),extensionScope={cwd:typeof args.cwd=="string"?args.cwd:void 0,path:pmRoot,noExtensions:args.noExtensions===!0},plan=await runWithActiveExtensions(extensionScope,()=>planItemMutationDocument({pmRoot,input:JSON.stringify({schema_version:1,mutations:args.mutations}),...explicitTransactionId===void 0?{}:{transactionId:explicitTransactionId},...upsertKey===void 0?{}:{upsertKey}})),{mutations,references,rows}=plan,transactionId=plan.transaction_id,receipt={transaction_id:transactionId,transaction_id_source:plan.transaction_id_source,...plan.upsert_key===void 0?{}:{upsert_key:plan.upsert_key}};if(args.dryRun===!0){const validation=await runWithActiveExtensions(extensionScope,()=>previewItemMutations({pmRoot,transactionId,author:resolveAuthor(typeof args.author=="string"?args.author:void 0,"unknown"),mutations}));return{...receipt,dry_run:!0,validation,mutation_count:mutations.length,mutations,references,rows}}const result=await runWithActiveExtensions(extensionScope,()=>commitItemMutations({pmRoot,transactionId,author:resolveAuthor(typeof args.author=="string"?args.author:void 0,"unknown"),mutations,...controls}));return{...Object.fromEntries(Object.entries(result).filter(([key])=>key!=="transactionId")),...receipt,mutation_count:mutations.length,references,rows}},...Object.fromEntries(Object.entries(NARROW_TOOL_ACTIONS).map(([tool,action])=>[tool,args=>runMcpAction({...args,action})]))};function resolveInvokedAction(toolName,args){return toolName==="pm_run"?typeof args.action=="string"?args.action:void 0:NARROW_TOOL_ACTIONS[toolName]}async function collectMutationGuardWarnings(toolName,action,args){if(toolName!=="pm_mutate"&&!isMutationAction(action??""))return[];const cwd=typeof args.cwd=="string"?args.cwd:process.cwd(),pmRoot=resolvePmRoot(cwd,typeof args.path=="string"?args.path:void 0);if(!await pathExists(getSettingsPath(pmRoot)))return[];const settings=await readSettings(pmRoot),nestedOptions=typeof args.options=="object"&&args.options!==null&&!Array.isArray(args.options)?args.options:{};return evaluateMutationGuard({author:resolveAuthor(typeof args.author=="string"?args.author:typeof nestedOptions.author=="string"?nestedOptions.author:void 0,settings.author_default),payload:Object.fromEntries(Object.entries(args).filter(([key])=>key!=="cwd"&&key!=="path")),settings:settings.mutation_guard,force:args.force===!0||nestedOptions.force===!0}).warnings}function detectUnexpectedOptionKeys(toolName,action,args){const options=args.options;if(action===void 0||typeof options!="object"||options===null||Array.isArray(options))return[];const declared=pmToolActionNestedOptionKeys(action);if(declared===void 0)return[];const declaredSet=new Set(declared),warnings=[];for(const key of Object.keys(options)){if(declaredSet.has(key))continue;const suggestion=nearestDeclaredKey(key,declared);warnings.push(suggestion!==void 0?`Unknown option "${key}" for ${toolName} action "${action}" (did you mean "${suggestion}"?). The ${action} contract does not read it, so it has no effect; declared keys are: ${declared.join(", ")}.`:`Unknown option "${key}" for ${toolName} action "${action}". The ${action} contract does not read it, so it has no effect; declared keys are: ${declared.join(", ")}.`)}return warnings}function resultContent(result,warnings,tokenAccounting=!1,canonicalStructuredResult=!1){const effectiveResult=tokenAccounting?attachOutputTokenAccounting(result,value=>JSON.stringify(value,null,2)):result,structuredContent=warnings!==void 0&&warnings.length>0?{result:effectiveResult,warnings}:{result:effectiveResult};return{content:[{type:"text",text:canonicalStructuredResult?"Canonical result: structuredContent.result":JSON.stringify(effectiveResult,null,2)}],structuredContent}}function errorContent(error,canonicalStructuredResult=!1){const code=error instanceof PmCliError?error.exitCode:1,message=error instanceof Error?error.message:String(error),details=error instanceof PmCliError?error.context:void 0;return{isError:!0,content:[{type:"text",text:canonicalStructuredResult?"Canonical error: structuredContent":JSON.stringify({error:message,code,details},null,2)}],structuredContent:{result:null,error:message,code,details}}}function boundMcpClientProvenance(value){const provenance=isRuntimeRecord(value)?value:{},bounded={};let acceptedCount=0;for(const key in provenance){if(acceptedCount>=32)break;if(!Object.prototype.hasOwnProperty.call(provenance,key))continue;const entry=provenance[key];/^[a-z][a-z0-9_-]{0,63}$/u.test(key)&&typeof entry=="string"&&entry.trim().length>0&&(bounded[key]=entry.trim().slice(0,256),acceptedCount+=1)}return bounded}function readMcpClientInfo(value){const clientInfo=isRuntimeRecord(value)?value:{},clientName=typeof clientInfo.name=="string"?clientInfo.name.trim():"";if(clientName.length===0)return;const optionalValues=[["version",clientInfo.version,128],["model",clientInfo.model,256],["session",clientInfo.session,256]],result={name:clientName.slice(0,128)};for(const[key,value2,limit]of optionalValues)typeof value2=="string"&&value2.trim().length>0&&(result[key]=value2.trim().slice(0,limit));const boundedProvenance=boundMcpClientProvenance(clientInfo.provenance);Object.keys(boundedProvenance).length>0&&(result.provenance=boundedProvenance);const episode=boundAgentEpisodeIdentity(clientInfo.episode,!1);return episode!==void 0&&(result.episode=episode),result}async function emitMcpChangeNotifications(action){isMutationAction(action??"")&&await Promise.all([...PM_MCP_SUBSCRIPTIONS.values()].flatMap(({registry})=>PM_MCP_RESOURCE_CONTRACTS.map(resource=>registry.emitResourceUpdated(resource.uri)))),["extension","install","package","uninstall"].includes(action??"")&&await Promise.all([...PM_MCP_SUBSCRIPTIONS.values()].map(({registry})=>registry.emitListChanged("tools"))),pruneClosedMcpSubscriptionRegistries()}async function handleToolCall(paramsInput,clientInfo,progressiveDiscoveryNegotiated=!1){const clientSignals=clientInfo?{client_info:clientInfo}:{};return runWithHarnessDetectionSignals({env:process.env,argv:process.argv,...clientSignals},async()=>{const params=asRecordClone(paramsInput),name=readRequiredString(params,"name"),handler=Object.prototype.hasOwnProperty.call(HANDLERS,name)?HANDLERS[name]:void 0;if(!handler)throw new PmCliError(`Unknown pm MCP tool: ${name}`,64);const inputResponses=params.inputResponses===void 0?void 0:parseMcpInputResponses(params.inputResponses);validateMcpToolArguments(params.arguments);const requestedArgs={...decodeHtmlEntitiesInOptions(asRecordClone(params.arguments)),...inputResponses?{inputResponses}:{},...typeof params.requestState=="string"?{requestState:params.requestState}:{}},access=await resolveMcpToolAccess(TOOLS,name,requestedArgs),requiredCustomDiscoveryEntry=progressiveDiscoveryNegotiated&&access.profile==="custom"&&name==="pm_discover";if(!access.available&&!requiredCustomDiscoveryEntry)throw new PmCliError(`pm MCP tool "${name}" is unavailable in the ${access.profile} profile.`,64);const args=await normalizeWorkspaceToolArguments(name,requestedArgs),cwd=typeof args.cwd=="string"?args.cwd:process.cwd(),pmRoot=resolvePmRoot(cwd,typeof args.path=="string"?args.path:void 0),workspaceIdentity=await pathExists(getSettingsPath(pmRoot))?(await readSettings(pmRoot)).agent_identity:void 0;return runWithHarnessDetectionSignals({env:{...process.env,PM_PATH:pmRoot},argv:process.argv,cwd,...clientSignals},()=>runWithWorkspaceHarnessSignalDescriptors(workspaceIdentity?.harness_signals??[],async()=>{const action=resolveInvokedAction(name,args),warnings=[...detectUnexpectedTopLevelKeys(name,args,declaredToolKeys()),...detectUnexpectedOptionKeys(name,action,args),...await collectMutationGuardWarnings(name,action,args)];for(const warning of warnings)console.error(`[pm-mcp] ${warning}`);const result=await handler(args);return emitMcpChangeNotifications(action),resultContent(result,warnings,args.tokenAccounting===!0,progressiveDiscoveryNegotiated)},{probesEnabled:workspaceIdentity?.probes_enabled}))})}async function openMcpSubscription(input){if(typeof input.request.id!="string"&&typeof input.request.id!="number"||input.request.method!=="subscriptions/listen")throw new PmMcpProtocolError("Invalid MCP subscriptions/listen request",PM_MCP_ERROR_CODES.invalidParams,{required:["id","method","params.notifications"]});resolveMcpRequestContext(input.request.params);const key=input.key??input.request.id;if(PM_MCP_SUBSCRIPTIONS.has(key))throw new PmMcpProtocolError("MCP subscription id is already active",PM_MCP_ERROR_CODES.invalidParams,{subscriptionId:input.request.id});const registry=createMcpSubscriptionRegistry();await registry.open({id:input.request.id,notifications:input.request.params?.notifications,sink:input.sink}),PM_MCP_SUBSCRIPTIONS.set(key,{id:input.request.id,registry})}function closeMcpSubscription(id,key=id){const subscription=PM_MCP_SUBSCRIPTIONS.get(key);if(!(!subscription||subscription.id!==id))return PM_MCP_SUBSCRIPTIONS.delete(key),subscription.registry.close(id)}function closeStdioMcpSubscriptions(){const closed=[];for(const[key,subscription]of PM_MCP_SUBSCRIPTIONS){if(key!==subscription.id)continue;const result=closeMcpSubscription(subscription.id,key);result&&closed.push({id:subscription.id,result})}return closed}async function resolveMcpToolSchemaForRequest(request){if(request.method!=="tools/call")return;const name=request.params?.name;return typeof name!="string"?void 0:(await resolveMcpToolSurface(TOOLS,requestWorkspaceArgs(request.params))).tools.find(tool=>tool.name===name)?.inputSchema}function buildMcpToolCallErrorResult(request,error){if(request.method!=="tools/call"||error instanceof PmMcpProtocolError)return;const content=errorContent(error,hasMcpProtocolVersionMetadata(request)&&hasMcpClientExtension(resolveMcpRequestContext(request.params),PM_MCP_PROGRESSIVE_DISCOVERY_EXTENSION));return hasMcpProtocolVersionMetadata(request)?buildMcpCompleteResult(content,PM_MCP_SERVER_INFO):content}function requestWorkspaceArgs(params){const paramsRecord=asRecordClone(params);return asRecordClone(paramsRecord.arguments??paramsRecord)}async function readWorkspaceResource(uri,params){const args=requestWorkspaceArgs(params),cwd=typeof args.cwd=="string"?args.cwd:process.cwd(),contract=PM_MCP_RESOURCE_CONTRACTS.find(resource=>resource.uri===uri);if(!contract)throw new PmCliError(`Unknown pm MCP resource: ${uri}`,64);let value;if(uri==="pm://workspace/context")value=await runMcpAction({...args,action:"context",limit:10});else if(uri==="pm://workspace/claims")value=await runMcpAction({...args,action:"list",status:"in_progress",limit:20});else if(uri==="pm://workspace/focus")value=await runMcpAction({...args,action:"focus",subcommand:"show"});else{const guidePath=path.join(cwd,"AGENTS.md");value=await pathExists(guidePath)?(await readFile(guidePath,"utf8")).slice(0,32e3):"No repository-local AGENTS.md was found."}return{contents:[{uri,mimeType:contract.mimeType,text:typeof value=="string"?value:JSON.stringify(value,null,2)}]}}async function loadRequestSkillRegistry(params){const args=requestWorkspaceArgs(params),cwd=typeof args.cwd=="string"?args.cwd:process.cwd(),workspaceRoot=resolveWorkspaceRoot(resolvePmRoot(cwd,typeof args.path=="string"?args.path:void 0));return PmMcpSkillRegistry.load({packageRoot:resolvePmPackageRoot(),workspaceRoot,packageVersion:PM_MCP_SERVER_VERSION})}function renderWorkflowPrompt(params){const paramsRecord=asRecordClone(params),name=readRequiredString(paramsRecord,"name"),prompt=PM_MCP_PROMPT_CONTRACTS.find(candidate=>candidate.name===name);if(!prompt)throw new PmCliError(`Unknown pm MCP prompt: ${name}`,64);const argumentsRecord=asRecordClone(paramsRecord.arguments);let text=prompt.template;for(const argument of prompt.arguments){const value=argumentsRecord[argument.name];if(argument.required&&(typeof value!="string"||value.trim().length===0))throw new PmCliError(`Missing required prompt argument: ${argument.name}`,64);text=text.replaceAll(`{{${argument.name}}}`,typeof value=="string"?value:"")}return{description:prompt.description,messages:[{role:"user",content:{type:"text",text}}]}}const LEGACY_MCP_ADAPTER=new LegacyMcpAdapter({serverInfo:PM_MCP_SERVER_INFO,capabilities:PM_MCP_SERVER_CAPABILITIES,instructions:PM_MCP_INSTRUCTIONS,parseClientInfo:readMcpClientInfo,listTools:async params=>({tools:(await resolveMcpToolSurface(TOOLS,requestWorkspaceArgs(params))).tools}),callTool:handleToolCall,listResources:()=>({resources:PM_MCP_RESOURCE_CONTRACTS}),readResource:params=>readWorkspaceResource(readRequiredString(asRecordClone(params),"uri"),params),listPrompts:()=>({prompts:PM_MCP_PROMPT_CONTRACTS.map(prompt=>({name:prompt.name,description:prompt.description,arguments:prompt.arguments}))}),getPrompt:renderWorkflowPrompt});function deterministicMcpTools(tools){return tools.map(tool=>({...tool,inputSchema:validateMcpJsonSchema(tool.inputSchema)})).sort((left,right)=>left.name.localeCompare(right.name))}function mcpTaskPrincipal(requestContext){return requestContext.clientInfo?`${requestContext.clientInfo.name}@${requestContext.clientInfo.version}`:"anonymous-stdio"}function mcpTaskStore(){return createMcpTaskStore({pmRoot:resolvePmRoot(process.cwd()),owner:"pm-mcp-task-provider"})}function validateMcpToolArguments(value){if(value!==void 0&&!isMcpRecord(value))throw new PmCliError("pm MCP tool arguments must be an object.",64)}function shouldCreateMcpTask(params,requestContext){if(!hasMcpClientExtension(requestContext,PM_MCP_TASKS_EXTENSION))return!1;const requestParams=asRecordClone(params),name=requestParams.name,args=asRecordClone(requestParams.arguments);return PM_MCP_DIRECT_TASK_TOOLS.has(name)||name==="pm_test"&&(args.subcommand==="run"||isMcpRecord(args.options)&&args.options.subcommand==="run")?!0:name!=="pm_run"?!1:typeof args.action=="string"&&PM_MCP_RUN_TASK_ACTIONS.has(args.action)}const PENDING_MCP_TASKS=new Map;async function executeMcpTask(execution,inputResponses){const params={...execution.params,...inputResponses?{inputResponses}:{},...execution.requestState?{requestState:execution.requestState}:{}};try{const result=await handleToolCall(params,execution.context.clientInfo,hasMcpClientExtension(execution.context,PM_MCP_PROGRESSIVE_DISCOVERY_EXTENSION));await execution.store.complete(execution.taskId,execution.principal,buildMcpCompleteResult(result,PM_MCP_SERVER_INFO)),PENDING_MCP_TASKS.delete(execution.taskId)}catch(error){if(error instanceof PmMcpInputRequiredError){execution.requestState=error.requestState,await execution.store.requireInput({taskId:execution.taskId,principal:execution.principal,requestContext:execution.context,inputRequests:error.inputRequests,statusMessage:"Task requires additional client input."});return}error instanceof PmMcpProtocolError?await execution.store.fail(execution.taskId,execution.principal,{code:error.code,message:error.message,data:error.data}):await execution.store.complete(execution.taskId,execution.principal,buildMcpCompleteResult(errorContent(error,hasMcpClientExtension(execution.context,PM_MCP_PROGRESSIVE_DISCOVERY_EXTENSION)),PM_MCP_SERVER_INFO)),PENDING_MCP_TASKS.delete(execution.taskId)}}async function settleMcpTaskExecution(taskId,execution){try{await execution}catch{PENDING_MCP_TASKS.delete(taskId)}}function scheduleMcpTaskExecution(execution,inputResponses){settleMcpTaskExecution(execution.taskId,executeMcpTask(execution,inputResponses))}async function createMcpTaskForToolCall(params,requestContext){const store=mcpTaskStore(),principal=mcpTaskPrincipal(requestContext),task=await store.create({principal,statusMessage:"pm operation accepted for asynchronous execution."}),execution={context:requestContext,params:asRecordClone(params),principal,store,taskId:task.taskId};return PENDING_MCP_TASKS.set(task.taskId,execution),scheduleMcpTaskExecution(execution),attachMcpServerInfo(task,PM_MCP_SERVER_INFO)}async function dispatchMcpTaskMethod(request,requestContext){if(!hasMcpClientExtension(requestContext,PM_MCP_TASKS_EXTENSION))throw new PmMcpProtocolError("Missing required client capability",PM_MCP_ERROR_CODES.missingRequiredClientCapability,{requiredCapabilities:{extensions:{[PM_MCP_TASKS_EXTENSION]:{}}}});const params=asRecordClone(request.params),taskId=readRequiredString(params,"taskId"),principal=mcpTaskPrincipal(requestContext),store=mcpTaskStore();if(request.method==="tasks/get")return buildMcpCompleteResult(await store.get(taskId,principal),PM_MCP_SERVER_INFO);if(request.method==="tasks/update"){const update=await store.update(taskId,principal,params.inputResponses),execution=PENDING_MCP_TASKS.get(taskId);return execution&&update.acceptedKeys.length>0&&update.remainingKeys.length===0&&scheduleMcpTaskExecution(execution,await store.takeInputResponses(taskId,principal)),buildMcpCompleteResult({},PM_MCP_SERVER_INFO)}return await store.cancel(taskId,principal),PENDING_MCP_TASKS.delete(taskId),buildMcpCompleteResult({},PM_MCP_SERVER_INFO)}async function dispatchModernToolMethod(request,requestContext,clientInfo){if(request.method==="tools/list"){const surface=await resolveMcpToolSurface(TOOLS,requestWorkspaceArgs(request.params)),listedTools=hasMcpClientExtension(requestContext,PM_MCP_PROGRESSIVE_DISCOVERY_EXTENSION)?[...surface.tools.filter(tool=>PM_MCP_ENTRY_TOOL_NAMES.includes(tool.name)),...surface.profile==="custom"&&!surface.tools.some(tool=>tool.name==="pm_discover")?TOOLS.filter(tool=>tool.name==="pm_discover"):[]]:surface.tools;return buildMcpCompleteResult(withMcpCachePolicy({tools:hasCompatiblePmMcpAppsCapability(requestContext)?decoratePmMcpToolsWithApps(deterministicMcpTools(listedTools)):deterministicMcpTools(listedTools)},PM_MCP_CACHE_POLICIES.tools),PM_MCP_SERVER_INFO)}if(validateMcpToolArguments(request.params?.arguments),shouldCreateMcpTask(request.params,requestContext))return createMcpTaskForToolCall(request.params,requestContext);try{return buildMcpCompleteResult(await handleToolCall(request.params,clientInfo,hasMcpClientExtension(requestContext,PM_MCP_PROGRESSIVE_DISCOVERY_EXTENSION)),PM_MCP_SERVER_INFO)}catch(error){if(!(error instanceof PmMcpInputRequiredError))throw error;return buildMcpInputRequiredResult({requestContext,serverInfo:PM_MCP_SERVER_INFO,inputRequests:error.inputRequests,requestState:error.requestState})}}async function dispatchModernResourceMethod(request,requestContext){if(request.method==="resources/list"){const resources=[...PM_MCP_RESOURCE_CONTRACTS,...hasCompatiblePmMcpAppsCapability(requestContext)?PM_MCP_APP_CONTRACTS.map(contract=>({uri:contract.uri,name:contract.name,description:contract.description,mimeType:PM_MCP_APP_MIME_TYPE,_meta:{ui:contract.resourceMeta}})):[]].sort((left,right)=>left.uri.localeCompare(right.uri));return buildMcpCompleteResult(withMcpCachePolicy({resources},PM_MCP_CACHE_POLICIES.resources),PM_MCP_SERVER_INFO)}if(request.method==="resources/templates/list")return buildMcpCompleteResult(withMcpCachePolicy({resourceTemplates:[]},PM_MCP_CACHE_POLICIES.resources),PM_MCP_SERVER_INFO);try{const uri=readRequiredString(asRecordClone(request.params),"uri"),app=findPmMcpAppByUri(uri);let resource;if(app){if(!hasPmMcpAppsCapability(requestContext))throw new PmMcpProtocolError("MCP App resource requires negotiated client capability",PM_MCP_ERROR_CODES.missingRequiredClientCapability,{requiredCapabilities:{extensions:{[PM_MCP_APPS_EXTENSION]:PM_MCP_APPS_SERVER_CAPABILITY}}});resource={contents:[{uri,mimeType:PM_MCP_APP_MIME_TYPE,text:renderPmMcpAppHtml(app),_meta:{ui:app.resourceMeta}}]}}else uri.startsWith("skill://")?(assertPmMcpSkillsCapability(requestContext),resource={...(await loadRequestSkillRegistry(request.params)).read(uri)}):resource=await readWorkspaceResource(uri,request.params);return buildMcpCompleteResult(withMcpCachePolicy(resource,PM_MCP_CACHE_POLICIES.resource),PM_MCP_SERVER_INFO)}catch(error){throw!(error instanceof PmCliError)||!error.message.startsWith("Unknown pm MCP resource:")?error:new PmMcpProtocolError(error.message,PM_MCP_ERROR_CODES.invalidParams,{field:"uri"})}}function hasCompatiblePmMcpAppsCapability(requestContext){try{return hasPmMcpAppsCapability(requestContext)}catch(error){if(error instanceof PmMcpProtocolError)return!1;throw error}}function readSkillPageOptions(params){if(params.cursor!==void 0&&typeof params.cursor!="string")throw new PmMcpProtocolError("Skills cursor must be a string",PM_MCP_ERROR_CODES.invalidParams,{field:"cursor"});if(params.limit!==void 0&&typeof params.limit!="number")throw new PmMcpProtocolError("Skills limit must be a number",PM_MCP_ERROR_CODES.invalidParams,{field:"limit"});return{...typeof params.cursor=="string"?{cursor:params.cursor}:{},...typeof params.limit=="number"?{limit:params.limit}:{}}}async function dispatchModernSkillMethod(request,requestContext){const directoryRead=request.method==="resources/directory/read";assertPmMcpSkillsCapability(requestContext,directoryRead);const params=asRecordClone(request.params),registry=await loadRequestSkillRegistry(request.params);let result;return request.method==="skills/list"?result={...registry.list(readSkillPageOptions(params))}:request.method==="skills/get"?result={skill:registry.get(readRequiredString(params,"uri"))}:result={...registry.readDirectory(readRequiredString(params,"uri"),readSkillPageOptions(params))},buildMcpCompleteResult(withMcpCachePolicy(result,PM_MCP_CACHE_POLICIES.resource),PM_MCP_SERVER_INFO)}function dispatchModernPromptMethod(request){const result=request.method==="prompts/list"?withMcpCachePolicy({prompts:PM_MCP_PROMPT_CONTRACTS.map(prompt=>({name:prompt.name,description:prompt.description,arguments:prompt.arguments})).sort((left,right)=>left.name.localeCompare(right.name))},PM_MCP_CACHE_POLICIES.prompts):renderWorkflowPrompt(request.params);return buildMcpCompleteResult(result,PM_MCP_SERVER_INFO)}async function dispatchModernMcpRequest(request,meta){const requestContext=resolveMcpRequestContext(request.params),clientInfo=readMcpClientInfo(meta[PM_MCP_META_KEYS.clientInfo]);if(request.method==="server/discover")return buildMcpDiscoverResult({serverInfo:PM_MCP_SERVER_INFO,capabilities:PM_MCP_SERVER_CAPABILITIES,instructions:PM_MCP_INSTRUCTIONS});if(request.method==="ping")throw new PmMcpProtocolError("MCP method not found: ping",-32601,{removedIn:PM_MCP_PROTOCOL_VERSION});if(PM_MCP_SKILL_METHODS.has(request.method??""))return dispatchModernSkillMethod(request,requestContext);if(request.method==="tasks/get"||request.method==="tasks/update"||request.method==="tasks/cancel")return dispatchMcpTaskMethod(request,requestContext);if(request.method==="tools/list"||request.method==="tools/call")return dispatchModernToolMethod(request,requestContext,clientInfo);if(request.method==="resources/list"||request.method==="resources/templates/list"||request.method==="resources/read")return dispatchModernResourceMethod(request,requestContext);if(request.method==="prompts/list"||request.method==="prompts/get")return dispatchModernPromptMethod(request);throw new PmMcpProtocolError(`MCP method not found: ${request.method??"(missing)"}`,-32601)}async function handleRequestInReproducibleContext(request){if(!(!request.id&&request.method?.startsWith("notifications/"))){if(hasMcpProtocolVersionMetadata(request)){const allowlist=(process.env.PM_MCP_BAGGAGE_ALLOWLIST??"").split(",").map(entry=>entry.trim()).filter(Boolean);return runWithMcpTraceContext(extractMcpTraceContext(request.params,{baggageAllowlist:allowlist}),()=>dispatchModernMcpRequest(request,request.params._meta))}return request.method==="initialize"?LEGACY_MCP_ADAPTER.initialize(request.params):LEGACY_MCP_ADAPTER.dispatch(request)}}function hasMcpProtocolVersionMetadata(request){const meta=isMcpRecord(request.params)?request.params._meta:void 0;return isMcpRecord(meta)&&Object.prototype.hasOwnProperty.call(meta,PM_MCP_META_KEYS.protocolVersion)}async function handleRequest(request){return runWithReproducibleProcessEnvironment(process.env,()=>handleRequestInReproducibleContext(request))}function writeResponse(id,payload){process.stdout.write(`${JSON.stringify({jsonrpc:"2.0",id,result:payload})}
|
|
3
3
|
`)}function writeError(id,error){const code=error instanceof PmMcpProtocolError?error.code:error instanceof PmCliError?error.exitCode:-32603,message=error instanceof Error?error.message:String(error),data=error instanceof PmMcpProtocolError?error.data:error instanceof PmCliError?error.context:void 0;process.stdout.write(`${JSON.stringify({jsonrpc:"2.0",id,error:{code,message,data}})}
|
|
4
4
|
`)}function writeToolCallErrorResponse(request,error){return request.method!=="tools/call"||error instanceof PmMcpProtocolError?!1:(writeResponse(request.id,buildMcpToolCallErrorResult(request,error)),!0)}async function handleStdioTransportControl(request){if(request.method==="subscriptions/listen")return await openMcpSubscription({request,sink:notification=>{process.stdout.write(`${JSON.stringify(notification)}
|
|
5
5
|
`)}}),!0;if(request.method!=="notifications/cancelled")return!1;const requestId=request.params?.requestId;if(typeof requestId=="string"||typeof requestId=="number"){const result=closeMcpSubscription(requestId);result&&writeResponse(requestId,result)}return!0}async function processRpcLineWithHandler(line,requestHandler){if(line.trim().length===0)return;let request;try{request=JSON.parse(line)}catch(error){const message=error instanceof Error?error.message:String(error);writeError(null,new PmCliError(`Parse error: ${message}`,-32700));return}if(typeof request!="object"||request===null||Array.isArray(request)){writeError(null,new PmCliError("Invalid JSON-RPC request: expected an object",-32600));return}const shouldRespond=Object.prototype.hasOwnProperty.call(request,"id");try{if(await handleStdioTransportControl(request))return;const result=await requestHandler(request);shouldRespond&&result!==void 0&&writeResponse(request.id,result)}catch(error){if(!shouldRespond)return;writeToolCallErrorResponse(request,error)||writeError(request.id,error)}}async function processRpcLine(line){await processRpcLineWithHandler(line,handleRequest)}function startMcpServer(){const rl=readline.createInterface({input:process.stdin,crlfDelay:1/0}),queue=createSerialQueue();let processLine;try{const runInProcessContext=createReproducibleProcessRunner(process.env);processLine=line=>runInProcessContext(()=>processRpcLineWithHandler(line,handleRequestInReproducibleContext))}catch{processLine=processRpcLine}rl.on("line",line=>{queue.enqueue(()=>processLine(line))}),rl.on("close",()=>{queue.enqueue(()=>{for(const closed of closeStdioMcpSubscriptions())writeResponse(closed.id,closed.result)})})}function isInvokedAsMcpMainModule(argvPath,moduleUrl){if(!argvPath)return!1;const selfPath=fileURLToPath(moduleUrl);if(argvPath===selfPath)return!0;try{return realpathSync(argvPath)===realpathSync(selfPath)}catch{return!1}}function readRuntimeTestHook(key){const runtimeTestHooks=globalThis.__pmCliActionRunnerTestHooks;if(runtimeTestHooks===void 0)throw new PmCliError(`MCP runtime test hook "${String(key)}" is only available in test environments.`,64);return runtimeTestHooks[key]}const _testOnly={boundMcpClientProvenance,createMcpInputRequiredError:input=>new PmMcpInputRequiredError(input),createMcpProtocolError:(...input)=>new PmMcpProtocolError(...input),get closeManyOptionsFromFlat(){return readRuntimeTestHook("closeManyOptionsFromFlat")},detectUnexpectedOptionKeys,detectUnexpectedTopLevelKeys,collectMutationGuardWarnings,closeStdioMcpSubscriptions,errorContent,emitMcpChangeNotifications,expireMcpSubscriptionRecord:(id,key=id)=>PM_MCP_SUBSCRIPTIONS.get(key).registry.close(id),getMcpClientInfo:()=>LEGACY_MCP_ADAPTER.getClientInfo(),get extensionOptionsFromArgs(){return readRuntimeTestHook("extensionOptionsFromArgs")},get globalOptions(){return readRuntimeTestHook("globalOptions")},get mutationListOptions(){return readRuntimeTestHook("mutationListOptions")},nearestDeclaredKey,mcpTaskPrincipal,resultContent,resolveMcpRequestContext,shouldCreateMcpTask,settleMcpTaskExecution,subscriptionCount:()=>PM_MCP_SUBSCRIPTIONS.size,get normalizeActionName(){return readRuntimeTestHook("normalizeActionName")},get normalizeCommandPath(){return readRuntimeTestHook("normalizeCommandPath")},get normalizeMcpOptionsArrays(){return readRuntimeTestHook("normalizeMcpOptionsArrays")},get normalizeMcpUpdateOptions(){return readRuntimeTestHook("normalizeMcpUpdateOptions")},get optionsWithAuthor(){return readRuntimeTestHook("optionsWithAuthor")},get readRequiredString(){return readRuntimeTestHook("readRequiredString")},get readScalarString(){return readRuntimeTestHook("readScalarString")},get readScalarStringAllowBlank(){return readRuntimeTestHook("readScalarStringAllowBlank")},get readStringArray(){return readRuntimeTestHook("readStringArray")},runAction:runMcpAction,get updateManyOptionsFromFlat(){return readRuntimeTestHook("updateManyOptionsFromFlat")},get withAddNoteOption(){return readRuntimeTestHook("withAddNoteOption")},get withFilesDiscoveryOptions(){return readRuntimeTestHook("withFilesDiscoveryOptions")},get withMutationCompaction(){return readRuntimeTestHook("withMutationCompaction")},writeError};isInvokedAsMcpMainModule(process.argv[1],import.meta.url)&&startMcpServer();export{_testOnly,buildMcpToolCallErrorResult,closeMcpSubscription,handleRequest,isInvokedAsMcpMainModule,openMcpSubscription,processRpcLine,resolveMcpToolSchemaForRequest,startMcpServer};
|
|
@@ -1,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]="73dbe40e-f7a2-5aca-85aa-a5775e5e981a")}catch{}})();import{WORKFLOW_POLICY_ACTIONS,GRAPH_SUBCOMMAND_VALUES,PM_DISCOVERABLE_TOOL_ACTIONS}from"../sdk/cli-contracts/enum-contracts.js";import{buildPmActionToolInputSchema}from"../sdk/cli-contracts/tool-schema.js";import{RUNTIME_STATUS_ROLE_VALUES}from"../types.js";const CANONICAL_OUTPUT_SESSION_TOOL_PROPERTY=buildPmActionToolInputSchema("list").properties.outputSession,READ_OUTPUT_TOOL_PROPERTIES={outputInclude:{type:"string",minLength:1,description:"Comma-separated fields or sections retained by any built-in read action."},outputLimit:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}],description:"Universal read row ceiling, or unbounded to disable the shared ceiling."},outputBudget:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}],description:"Universal estimated-token ceiling, or unbounded to return the complete read result."},outputFormat:{type:"string",enum:["json","toon"],description:"Universal read-result encoding selector."},outputSession:{...CANONICAL_OUTPUT_SESSION_TOOL_PROPERTY},outputCursor:{type:"string",minLength:1,description:"Opaque continuation cursor returned after budget compaction of a declared row collection."}},workflowPolicyOptionProperties={definition:{anyOf:[{type:"object"},{type:"string"}],description:"Policy declaration for policy-put, or proposed metadata for policy-check; structured JSON or JSON text."},policy:{type:"string",description:"Approval policy id for policy-approve."},message:{type:"string",description:"History explanation for policy mutations and approvals."},dryRun:{type:"boolean",description:"Preview registry changes without writing; policy-approve rejects previews."}},TOOL_SCHEMA_BASE={type:"object",properties:{cwd:{type:"string",description:"Workspace directory to run the native pm operation in. Defaults to the MCP server process cwd."},path:{type:"string",description:"Optional pm data root, equivalent to PM_PATH/global --path. Leave unset for real repository tracking."},author:{type:"string",description:"Optional mutation author override. Otherwise pm uses PM_AUTHOR, project settings, or detected harness identity."},tokenAccounting:{type:"boolean",description:"Attach the same bounded per-section token-cost receipt emitted by CLI --token-accounting."}},additionalProperties:!0},idSchema={type:"string",description:"pm item id, for example pm-abc1."},PM_RUN_ACTION_DESCRIPTION=`Operation name (one of): ${PM_DISCOVERABLE_TOOL_ACTIONS.join(", ")}. Package-owned actions are available dynamically when their provider package is installed.`,LIST_TOP_LEVEL_OPTION_PROPERTIES={status:{type:"string",description:"Alias for options.status."},type:{type:"string",description:"Alias for options.type."},tag:{type:"string",description:"Alias for options.tag."},priority:{type:"string",description:"Alias for options.priority."},limit:{type:["string","number"],description:"Alias for options.limit."},offset:{type:["string","number"],description:"Alias for options.offset."}},SEARCH_TOP_LEVEL_OPTION_PROPERTIES={mode:{type:"string",description:"Alias for options.mode."},status:{type:"string",description:"Alias for options.status."},type:{type:"string",description:"Alias for options.type."},tag:{type:"string",description:"Alias for options.tag."},priority:{type:"string",description:"Alias for options.priority."},limit:{type:["string","number"],description:"Alias for options.limit."}};function objectSchema(properties,required=[]){return{...TOOL_SCHEMA_BASE,properties:{...TOOL_SCHEMA_BASE.properties,...properties},required}}const RAW_TOOLS=[{name:"pm_run",description:"Run any supported pm operation natively through the pm library. Use this for commands not covered by narrower pm_* tools.",inputSchema:objectSchema({action:{type:"string",enum:[...PM_DISCOVERABLE_TOOL_ACTIONS],description:PM_RUN_ACTION_DESCRIPTION},id:idSchema,query:{type:"string",description:"Search query for action=search."},reason:{type:"string",description:"Close reason for action=close."},force:{type:"boolean",description:"Force ownership/terminal-state override when supported."},subcommand:{type:"string",description:"Subcommand selector for actions that take one (for example telemetry, or schema \u2014 prefer the dedicated pm_schema tool for schema operations)."},options:{type:"object",description:"Underlying pm command options using camelCase keys."},fullChangedFields:{type:"boolean",description:"For mutation actions, return the full changed_fields array instead of the default changed_field_count."},idOnly:{type:"boolean",description:"For single-item mutation actions, return only id and status."},...READ_OUTPUT_TOOL_PROPERTIES},["action"])},{name:"pm_discover",description:"Discover the smallest relevant authorized pm tool catalog under an explicit token budget. Ranking is deterministic and returns public lexical, semantic, graph, permission, freshness, and usage signal explanations. Continue with next_cursor; set includeSchema=true only when complete input schemas are needed.",inputSchema:objectSchema({query:{type:"string",maxLength:4096,description:"Free-text capability intent. Empty text lists by stable policy order."},family:{type:"string",enum:["workspace","intake","context","lifecycle","evidence","graph","quality","automation","extensions","internal"],description:"Optional stable capability-family filter."},tier:{type:"string",enum:["core","standard","full"],description:"Maximum command visibility tier included in results."},limit:{type:"integer",minimum:1,maximum:100,description:"Maximum result rows; defaults to 10."},cursor:{type:"string",minLength:1,maxLength:4096,description:"Opaque next_cursor from an equivalent discovery request."},includeSchema:{type:"boolean",description:"Include complete tool input schemas; false by default."},outputBudget:{anyOf:[{type:"integer",minimum:128},{const:"unbounded"}],description:"Estimated-token ceiling; defaults to 1200."}})},{name:"pm_context",description:"Return the agent-oriented project context snapshot. Pass options.depth=brief|standard|deep|full (full = every section with no per-section row cap), options.parent='<id>' to scope the snapshot to one item's subtree (the item plus all descendants), options.fields='id,title,priority' to project focus rows to a field subset for low-token reads, or options.section=['hierarchy','progress',...] to pick sections.",inputSchema:objectSchema({options:{type:"object"}})},{name:"pm_next",description:"Recommend the next actionable work item: the single highest-priority READY item (active status, no open blockers, no open children; completed containers surface only when no concrete leaf work is ready) plus the ranked ready and blocked queues. The recommended item carries a rationale and each blocked item lists the open blockers gating it. Pass options.parent='<id>' to scope to one subtree, options.limit=N to cap ready rows, options.readyOnly=true to omit the blocked list, or filters (options.type/tag/priority/assignee/sprint/release). The most token-efficient 'what should I do now?' read for agents.",inputSchema:objectSchema({options:{type:"object"}})},{name:"pm_search",description:"Search pm items with keyword, semantic, or hybrid search. Defaults to a compact projection for token efficiency. Pass options.mode=keyword|semantic|hybrid (default follows search.default_mode: auto runs hybrid when semantic search is configured and runnable, else keyword; the result reports mode_source), options.limit=N to cap hits, options.status='all' for no lifecycle restriction, options.fields='id,title,score' for a custom projection, or options.full=true for full item bodies (can be large). The result echoes the applied filters and projection mode in query_summary.",inputSchema:objectSchema({query:{type:"string"},options:{type:"object"},...SEARCH_TOP_LEVEL_OPTION_PROPERTIES},["query"])},{name:"pm_list",description:"List pm items with status/type/tag/priority filters. Defaults to compact projection for token efficiency. options.status accepts CSV (all,open,in_progress). Pass options.compact=false or options.includeBody=true for full bodies/comments. Pass options.brief=true for ultra-terse (id/status/type/title only). Pass options.fields='id,title,priority' for custom projection. Pass options.limit=N to cap row count. The result echoes the applied filters and projection mode in query_summary.",inputSchema:objectSchema({options:{type:"object"},...LIST_TOP_LEVEL_OPTION_PROPERTIES})},{name:"pm_get",description:"Read one pm item with shared SDK projections. Pass options.depth='brief' or options.fields='id,title,status' for low-token inspection, options.fields='id,schedule.start_at' for schedule context, or options.at='7' / an ISO timestamp for a verified mutation-free historical read. Parent results include bounded child counts, samples, and continuation metadata.",inputSchema:objectSchema({id:idSchema,options:{type:"object",description:"Get options such as depth=brief|standard|deep|full, fields=id,title,status, or at=<version|ISO timestamp>."}},["id"])},{name:"pm_events",description:"Read a bounded, cursor-resumable page of committed mutation events across item history streams. Batch cursors are the token-efficient default; pass cursorMode=row for per-event checkpoints.",inputSchema:objectSchema({since:{type:"string",description:"Durable event cursor or ISO timestamp lower bound."},type:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},author:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},item:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},limit:{type:"integer",minimum:0,maximum:1e3},full:{type:"boolean"},cursorMode:{type:"string",enum:["batch","row"],description:"Cursor framing: batch returns one terminal next_cursor (default); row also adds a cursor to every event."}})},{name:"pm_create",description:"Create a pm item natively and write pm history. Output is compact by default (changed_fields replaced with changed_field_count for token efficiency); pass fullChangedFields=true for the full changed_fields array.",inputSchema:objectSchema({fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},allowMissingParent:{type:"boolean",description:"Allow unresolved parent references and emit a validation warning."},allowDuplicate:{type:"boolean",description:"Explicitly create when strict similarity governance finds likely duplicates."},options:{type:"object",description:"Create options. title and description are required."}},["options"])},{name:"pm_mutate",description:"Apply an ordered create/update/close/release batch atomically through the public pm SDK. Create rows may declare ref and omit id; @ref forward references resolve deterministically from the stable transactionId. Set dryRun=true to validate and preview without writes.",inputSchema:objectSchema({transactionId:{type:"string",description:"Stable idempotency key for this atomic mutation batch."},mutations:{type:"array",minItems:1,description:"Ordered rows shaped as {op:create|update|close|release,id?,ref?,options?,reason?}.",items:{type:"object",properties:{op:{type:"string",enum:["create","update","close","release"]},id:idSchema,ref:{type:"string",description:"Batch-local create alias; its deterministic id can be referenced as @alias by any row."},reason:{type:"string"},options:{type:"object"}},required:["op"],additionalProperties:!1}},dryRun:{type:"boolean",description:"Validate and preview without writing."},createCompensation:{type:"string",enum:["close","delete"],description:"How a failed batch compensates created items; defaults to close."},lockTtlSeconds:{type:"number"},lockWaitMs:{type:"number"}},["transactionId","mutations"])},{name:"pm_copy",description:"Copy an existing pm item into a new id while resetting lifecycle fields. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:objectSchema({id:idSchema,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object",description:"Copy options such as title override, author, and message."}},["id"])},{name:"pm_focus",description:"Set, clear, or show the session focused item. When focused, pm_create defaults its parent to the focused item (an explicit parent still overrides). Pass id to focus an item, options.clear=true to clear, or neither to show current focus.",inputSchema:objectSchema({id:idSchema,clear:{type:"boolean",description:"Clear the focused item (cannot be combined with id)."},options:{type:"object",description:"Focus options such as clear (boolean)."}},[])},{name:"pm_update",description:"Update pm item metadata/body/dependencies/log seeds natively. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields delta.",inputSchema:objectSchema({id:idSchema,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object"}},["id","options"])},{name:"pm_append",description:"Append markdown text to a pm item body and write pm history. Useful for seeding evidence/log entries before close. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:objectSchema({id:idSchema,body:{type:"string",description:"Markdown text to append to the item body. Required here or as options.body."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object",description:"Append options such as body, author, and message."}},["id"])},{name:"pm_claim",description:"Claim a pm item.",inputSchema:objectSchema({id:idSchema,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_release",description:"Release a pm item claim.",inputSchema:objectSchema({id:idSchema,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_close",description:"Close a pm item with optional close reason and optional close validation (reason requirement follows governance settings). Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:objectSchema({id:idSchema,reason:{type:"string",description:"Close reason text when provided or required by governance settings."},duplicateOf:{type:"string",description:"Canonical item id when closing this item as a duplicate."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object"}},["id"])},{name:"pm_comments",description:"List, add, edit, or delete comments on a pm item. Use options.add to append, options.edit=<1-based index> with replacement text to fix a comment, or options.delete=<1-based index> to remove one. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. List calls default to the most recent 20 comments with total_count/has_more metadata for token efficiency. Pass options.limit=N to choose a page size, options.limit=0 for summary-only metadata, or options.full=true for full history.",inputSchema:objectSchema({id:idSchema,options:{type:"object"}},["id"])},{name:"pm_files",description:"List, add, remove, or validate linked files for a pm item.",inputSchema:objectSchema({id:idSchema,options:{type:"object"}},["id"])},{name:"pm_docs",description:"List, add, or remove linked docs for a pm item.",inputSchema:objectSchema({id:idSchema,options:{type:"object"}},["id"])},{name:"pm_notes",description:"List, add, edit, or delete structured notes on a pm item. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. Omit mutation options to list existing notes.",inputSchema:objectSchema({id:idSchema,options:{type:"object"}},["id"])},{name:"pm_learnings",description:"List, add, edit, or delete learnings on a pm item. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. Omit mutation options to list existing learnings.",inputSchema:objectSchema({id:idSchema,options:{type:"object"}},["id"])},{name:"pm_deps",description:"Read dependency trees/graphs or one bounded explainable relationship context packet. Use options.format=context with direction, kind, depth, node, edge, token, and cursor bounds; context returns a counts-first summary, per-node roles/reasons, root evidence pointers, and enumerated missing references.",inputSchema:objectSchema({id:idSchema,options:{type:"object"}},["id"])},{name:"pm_graph",description:"Run bounded workspace relationship-graph queries: ancestors/descendants (hierarchy), predecessors/successors (ordering), paths, impact (blast radius), analyze (execution + knowledge analytics), audit (governance findings with change-since-baseline deltas), communities (label-propagation clusters), redundancy (transitively implied edges), dominators (structural bottlenecks), slack (critical-path method float per task), centrality (betweenness/closeness/degree with directed fan-in/out), articulation (cut points and bridges \u2014 single points of failure), plan (dry-run remediation proposals derived from the audit), and index (durable cross-process graph index status/rebuild/clear). Traversals, paths, impact, and dominators require id; paths also requires target. Options support kind, maxDepth, limit, after, direction, maxPaths, sample, exemptIsolate, exemptIsolateType, saveBaseline (audit), rebuild/clear (index), and counts-first summary.",inputSchema:objectSchema({subcommand:{type:"string",enum:[...GRAPH_SUBCOMMAND_VALUES]},id:idSchema,target:idSchema,options:{type:"object"}},["subcommand"])},{name:"pm_test",description:"List, add, remove, or run linked tests for a pm item.",inputSchema:objectSchema({id:idSchema,options:{type:"object"}},["id"])},{name:"pm_validate",description:"Run pm validation checks.",inputSchema:objectSchema({options:{type:"object"}})},{name:"pm_health",description:"Run pm health diagnostics. Pass options.brief=true for compact low-token details, options.skipIntegrity=true, options.skipDrift=true, options.skipVectors=true for a fast status-only check, or options.full=true for the complete deep check.",inputSchema:objectSchema({options:{type:"object"}})},{name:"pm_contracts",description:"Inspect pm command, flag, schema, and availability contracts.",inputSchema:objectSchema({options:{type:"object"}})},{name:"pm_schema",description:"Inspect or modify the workspace item-type/status/field schema (pm schema). subcommand selects the operation; name carries the item type name (show/add-type/remove-type), status id (show-status/add-status/remove-status), or field key (show-field/add-field/remove-field). apply-preset adopts a domain type preset; add-type with infer=true derives types from title-prefix conventions. Policy verbs author declarations, preview changes, set enforcement, and record content-bound approvals. Registry mutations write workspace history; approvals write item history.",inputSchema:objectSchema({...workflowPolicyOptionProperties,subcommand:{type:"string",enum:["list","show","show-status","add-type","remove-type","add-status","remove-status","add-field","remove-field","list-fields","show-field","apply-preset",...WORKFLOW_POLICY_ACTIONS],description:"Schema subcommand to run."},name:{type:"string",description:"Item type name, status id, field key, policy id, or item id for the selected schema verb; policy-mode requires advise|refuse."},description:{type:"string",description:"Custom item type, status, or field description for add-type/add-status/add-field."},defaultStatus:{type:"string",description:"Default status for add-type."},folder:{type:"string",description:"Storage folder for add-type."},alias:{type:"array",items:{type:"string"},description:"Aliases for add-type/add-status, or extra CLI flag aliases for add-field."},role:{type:"array",items:{type:"string",enum:[...RUNTIME_STATUS_ROLE_VALUES]},description:`Lifecycle roles for add-status: ${RUNTIME_STATUS_ROLE_VALUES.join(", ")}.`},order:{type:"number",description:"Display/sort order for add-status."},fieldType:{type:"string",enum:["string","number","boolean","string_array"],description:"Value type for a custom field (add-field)."},commands:{type:"array",items:{type:"string"},description:"Commands a custom field is wired onto (add-field): create, update, update_many, list, search, calendar, context."},cliFlag:{type:"string",description:"Override the auto-derived CLI flag for a custom field (add-field)."},required:{type:"boolean",description:"Mark a custom field as always required (add-field)."},requiredOnCreate:{type:"boolean",description:"Mark a custom field as required at create time (add-field)."},allowUnset:{type:"boolean",description:"Whether a custom field may be cleared via --unset (add-field); defaults to true."},requiredTypes:{type:"array",items:{type:"string"},description:"Restrict a custom field's requirement to specific item types (add-field)."},typePreset:{type:"string",enum:["agile","ops","research"],description:"Domain type preset to adopt (apply-preset)."},infer:{type:"boolean",description:"Infer item types from title-prefix conventions (add-type); previews unless apply is true."},minCount:{type:"number",description:"Minimum items sharing a prefix for add-type inference (default 10)."},apply:{type:"boolean",description:"Register inferred types (add-type infer); without it the call previews only."},force:{type:"boolean",description:"Override removal guardrails for destructive schema changes when supported."},options:{type:"object",description:"Additional schema options using camelCase keys.",properties:workflowPolicyOptionProperties}},["subcommand"])},{name:"pm_profile",description:"List, show, apply, or lint project profiles (pm profile) \u2014 archetype bundles that stage item types, statuses, fields, per-type workflows, config knobs, create templates, and recommended packages. subcommand selects the operation; name carries the profile name (agile, ops, research) for show/apply/lint. apply stages every dimension idempotently; dryRun previews the diff without writing; lint reports author-time consistency findings (graded error/warning) without touching the tracker. Profile staging writes workspace config/schema files, not item history.",inputSchema:objectSchema({subcommand:{type:"string",enum:["list","show","apply","lint"],description:"Profile subcommand to run."},name:{type:"string",description:"Profile name for show/apply/lint. Required for those subcommands. Built-ins are agile, ops, and research; an active extension can contribute additional archetype names that resolve here too."},dryRun:{type:"boolean",description:"Preview the apply diff without writing any files (apply)."},author:{type:"string",description:"Mutation author for apply."},force:{type:"boolean",description:"Force ownership/lock override for apply."},options:{type:"object",description:"Additional profile options using camelCase keys."}},["subcommand"])},{name:"pm_config",description:"Read or write pm workspace configuration (pm config). configAction selects get/set/list/export; key/value address a single setting for get/set. scope chooses the project (default) or global settings file.",inputSchema:objectSchema({configAction:{type:"string",enum:["get","set","list","export"],description:"Config operation to perform. get/set require key; list/export dump the resolved settings surface."},key:{type:"string",description:"Settings key for get/set, for example governance-require-close-reason, telemetry-tracking, or a nested leaf such as search_provider (dash and underscore variants accepted; configAction=get without a key lists supported keys in the error)."},value:{type:"string",description:"New value for configAction=set."},scope:{type:"string",enum:["project","global"],description:"Settings scope to read or write. Defaults to project."},options:{type:"object",description:"Additional config options such as criterion, clearCriteria, format, or policy."}},["configAction"])},{name:"pm_plan",description:"Run agent-optimized Plan workflows. options.subcommand selects: create|show|add-step|update-step|complete-step|block-step|reorder-step|remove-step|link|unlink|decision|discovery|validation|resume|approve|materialize. Provide id for all non-create subcommands; provide stepRef for step lifecycle subcommands. Plans store agent-readable steps with dependencies, decisions, discoveries, validation, and resume context.",inputSchema:objectSchema({id:{type:"string",description:"Plan id (required for all subcommands except create)."},stepRef:{type:"string",description:"Step id or order for step lifecycle subcommands."},options:{type:"object",description:"Plan options including subcommand, stepRef, stepStatus, link, depth, etc."}})}],NARROW_TOOL_ACTIONS={pm_append:"append",pm_claim:"claim",pm_close:"close",pm_comments:"comments",pm_config:"config",pm_context:"context",pm_contracts:"contracts",pm_copy:"copy",pm_create:"create",pm_deps:"deps",pm_docs:"docs",pm_events:"events",pm_files:"files",pm_focus:"focus",pm_get:"get",pm_graph:"graph",pm_health:"health",pm_learnings:"learnings",pm_list:"list",pm_next:"next",pm_notes:"notes",pm_plan:"plan",pm_profile:"profile",pm_release:"release",pm_schema:"schema",pm_search:"search",pm_test:"test",pm_update:"update",pm_validate:"validate"},TOOLS=RAW_TOOLS.map(tool=>{const action=NARROW_TOOL_ACTIONS[tool.name];if(!action)return tool;const properties=tool.inputSchema.properties,required=tool.inputSchema.required.map(String);return{...tool,inputSchema:buildPmActionToolInputSchema(action,{properties,required})}});function buildMcpToolContracts(){return TOOLS.map(tool=>{const schemaRequired=tool.inputSchema.required,required=Array.isArray(schemaRequired)?schemaRequired.map(entry=>String(entry)).sort((left,right)=>left.localeCompare(right)):[];return{name:tool.name,description:tool.description,required,input_schema:tool.inputSchema}}).sort((left,right)=>left.name.localeCompare(right.name))}export{NARROW_TOOL_ACTIONS,TOOLS,TOOL_SCHEMA_BASE,buildMcpToolContracts};
|
|
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]="16979f9d-779a-595a-abe8-94430fb470d5")}catch{}})();import{WORKFLOW_POLICY_ACTIONS,GRAPH_SUBCOMMAND_VALUES,PM_DISCOVERABLE_TOOL_ACTIONS}from"../sdk/cli-contracts/enum-contracts.js";import{buildPmActionToolInputSchema}from"../sdk/cli-contracts/tool-schema.js";import{RUNTIME_STATUS_ROLE_VALUES}from"../types.js";const CANONICAL_OUTPUT_SESSION_TOOL_PROPERTY=buildPmActionToolInputSchema("list").properties.outputSession,READ_OUTPUT_TOOL_PROPERTIES={outputInclude:{type:"string",minLength:1,description:"Comma-separated fields or sections retained by any built-in read action."},outputLimit:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}],description:"Universal read row ceiling, or unbounded to disable the shared ceiling."},outputBudget:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}],description:"Universal estimated-token ceiling, or unbounded to return the complete read result."},outputFormat:{type:"string",enum:["json","toon"],description:"Universal read-result encoding selector."},outputSession:{...CANONICAL_OUTPUT_SESSION_TOOL_PROPERTY},outputCursor:{type:"string",minLength:1,description:"Opaque continuation cursor returned after budget compaction of a declared row collection."}},workflowPolicyOptionProperties={definition:{anyOf:[{type:"object"},{type:"string"}],description:"Policy declaration for policy-put, or proposed metadata for policy-check; structured JSON or JSON text."},policy:{type:"string",description:"Approval policy id for policy-approve."},message:{type:"string",description:"History explanation for policy mutations and approvals."},dryRun:{type:"boolean",description:"Preview registry changes without writing; policy-approve rejects previews."}},TOOL_SCHEMA_BASE={type:"object",properties:{cwd:{type:"string",description:"Workspace directory to run the native pm operation in. Defaults to the MCP server process cwd."},path:{type:"string",description:"Optional pm data root, equivalent to PM_PATH/global --path. Leave unset for real repository tracking."},author:{type:"string",description:"Optional mutation author override. Otherwise pm uses PM_AUTHOR, project settings, or detected harness identity."},tokenAccounting:{type:"boolean",description:"Attach the same bounded per-section token-cost receipt emitted by CLI --token-accounting."}},additionalProperties:!0},idSchema={type:"string",description:"pm item id, for example pm-abc1."},PM_RUN_ACTION_DESCRIPTION=`Operation name (one of): ${PM_DISCOVERABLE_TOOL_ACTIONS.join(", ")}. Package-owned actions are available dynamically when their provider package is installed.`,LIST_TOP_LEVEL_OPTION_PROPERTIES={status:{type:"string",description:"Alias for options.status."},type:{type:"string",description:"Alias for options.type."},tag:{type:"string",description:"Alias for options.tag."},priority:{type:"string",description:"Alias for options.priority."},limit:{type:["string","number"],description:"Alias for options.limit."},offset:{type:["string","number"],description:"Alias for options.offset."}},SEARCH_TOP_LEVEL_OPTION_PROPERTIES={mode:{type:"string",description:"Alias for options.mode."},status:{type:"string",description:"Alias for options.status."},type:{type:"string",description:"Alias for options.type."},tag:{type:"string",description:"Alias for options.tag."},priority:{type:"string",description:"Alias for options.priority."},limit:{type:["string","number"],description:"Alias for options.limit."}};function objectSchema(properties,required=[]){return{...TOOL_SCHEMA_BASE,properties:{...TOOL_SCHEMA_BASE.properties,...properties},required}}const RAW_TOOLS=[{name:"pm_run",description:"Run any supported pm operation natively through the pm library. Use this for commands not covered by narrower pm_* tools.",inputSchema:objectSchema({action:{type:"string",enum:[...PM_DISCOVERABLE_TOOL_ACTIONS],description:PM_RUN_ACTION_DESCRIPTION},id:idSchema,query:{type:"string",description:"Search query for action=search."},reason:{type:"string",description:"Close reason for action=close."},force:{type:"boolean",description:"Force ownership/terminal-state override when supported."},subcommand:{type:"string",description:"Subcommand selector for actions that take one (for example telemetry, or schema \u2014 prefer the dedicated pm_schema tool for schema operations)."},options:{type:"object",description:"Underlying pm command options using camelCase keys."},fullChangedFields:{type:"boolean",description:"For mutation actions, return the full changed_fields array instead of the default changed_field_count."},idOnly:{type:"boolean",description:"For single-item mutation actions, return only id and status."},...READ_OUTPUT_TOOL_PROPERTIES},["action"])},{name:"pm_discover",description:"Discover the smallest relevant authorized pm tool catalog under an explicit token budget. Ranking is deterministic and returns public lexical, semantic, graph, permission, freshness, and usage signal explanations. Continue with next_cursor; set includeSchema=true only when complete input schemas are needed.",inputSchema:objectSchema({query:{type:"string",maxLength:4096,description:"Free-text capability intent. Empty text lists by stable policy order."},family:{type:"string",enum:["workspace","intake","context","lifecycle","evidence","graph","quality","automation","extensions","internal"],description:"Optional stable capability-family filter."},tier:{type:"string",enum:["core","standard","full"],description:"Maximum command visibility tier included in results."},limit:{type:"integer",minimum:1,maximum:100,description:"Maximum result rows; defaults to 10."},cursor:{type:"string",minLength:1,maxLength:4096,description:"Opaque next_cursor from an equivalent discovery request."},includeSchema:{type:"boolean",description:"Include complete tool input schemas; false by default."},outputBudget:{anyOf:[{type:"integer",minimum:128},{const:"unbounded"}],description:"Estimated-token ceiling; defaults to 1200."}})},{name:"pm_context",description:"Return the agent-oriented project context snapshot. Pass options.depth=brief|standard|deep|full (full = every section with no per-section row cap), options.parent='<id>' to scope the snapshot to one item's subtree (the item plus all descendants), options.fields='id,title,priority' to project focus rows to a field subset for low-token reads, or options.section=['hierarchy','progress',...] to pick sections.",inputSchema:objectSchema({options:{type:"object"}})},{name:"pm_next",description:"Recommend the next actionable work item: the single highest-priority READY item (active status, no open blockers, no open children; completed containers surface only when no concrete leaf work is ready) plus the ranked ready and blocked queues. The recommended item carries a rationale and each blocked item lists the open blockers gating it. Pass options.parent='<id>' to scope to one subtree, options.limit=N to cap ready rows, options.readyOnly=true to omit the blocked list, or filters (options.type/tag/priority/assignee/sprint/release). The most token-efficient 'what should I do now?' read for agents.",inputSchema:objectSchema({options:{type:"object"}})},{name:"pm_search",description:"Search pm items with keyword, semantic, or hybrid search. Defaults to a compact projection for token efficiency. Pass options.mode=keyword|semantic|hybrid (default follows search.default_mode: auto runs hybrid when semantic search is configured and runnable, else keyword; the result reports mode_source), options.limit=N to cap hits, options.status='all' for no lifecycle restriction, options.fields='id,title,score' for a custom projection, or options.full=true for full item bodies (can be large). The result echoes the applied filters and projection mode in query_summary.",inputSchema:objectSchema({query:{type:"string"},options:{type:"object"},...SEARCH_TOP_LEVEL_OPTION_PROPERTIES},["query"])},{name:"pm_list",description:"List pm items with status/type/tag/priority filters. Defaults to compact projection for token efficiency. options.status accepts CSV (all,open,in_progress). Pass options.compact=false or options.includeBody=true for full bodies/comments. Pass options.brief=true for ultra-terse (id/status/type/title only). Pass options.fields='id,title,priority' for custom projection. Pass options.limit=N to cap row count. The result echoes the applied filters and projection mode in query_summary.",inputSchema:objectSchema({options:{type:"object"},...LIST_TOP_LEVEL_OPTION_PROPERTIES})},{name:"pm_get",description:"Read one pm item with shared SDK projections. Pass options.depth='brief' or options.fields='id,title,status' for low-token inspection, options.fields='id,schedule.start_at' for schedule context, or options.at='7' / an ISO timestamp for a verified mutation-free historical read. Parent results include bounded child counts, samples, and continuation metadata.",inputSchema:objectSchema({id:idSchema,options:{type:"object",description:"Get options such as depth=brief|standard|deep|full, fields=id,title,status, or at=<version|ISO timestamp>."}},["id"])},{name:"pm_events",description:"Read a bounded, cursor-resumable page of committed mutation events across item history streams. Batch cursors are the token-efficient default; pass cursorMode=row for per-event checkpoints.",inputSchema:objectSchema({since:{type:"string",description:"Durable event cursor or ISO timestamp lower bound."},type:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},author:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},item:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},limit:{type:"integer",minimum:0,maximum:1e3},full:{type:"boolean"},cursorMode:{type:"string",enum:["batch","row"],description:"Cursor framing: batch returns one terminal next_cursor (default); row also adds a cursor to every event."}})},{name:"pm_create",description:"Create a pm item natively and write pm history. Output is compact by default (changed_fields replaced with changed_field_count for token efficiency); pass fullChangedFields=true for the full changed_fields array.",inputSchema:objectSchema({fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},allowMissingParent:{type:"boolean",description:"Allow unresolved parent references and emit a validation warning."},allowDuplicate:{type:"boolean",description:"Explicitly create when strict similarity governance finds likely duplicates."},options:{type:"object",description:"Create options. title and description are required."}},["options"])},{name:"pm_mutate",description:"Apply an ordered create/update/close/release batch atomically through the public pm SDK. Create rows may declare ref and omit id; @ref forward references resolve deterministically from the stable transactionId, which is derived from the batch when omitted. Bulk creation: rows shaped as {item:{title,type,...}} are create documents using pm create field names; upsertKey updates the existing item whose field matches instead of creating a duplicate. Set dryRun=true to validate and preview without writes.",inputSchema:objectSchema({transactionId:{type:"string",description:"Stable idempotency key for this atomic mutation batch; derived from the batch content when omitted."},mutations:{type:"array",minItems:1,description:"Ordered rows shaped as {op:create|update|close|release,id?,ref?,options?,reason?} or create documents {ref?,item:{...}}.",items:{type:"object",properties:{op:{type:"string",enum:["create","update","close","release"],description:"Operation; omitted rows carrying item are creates."},id:idSchema,ref:{type:"string",description:"Batch-local create alias; its deterministic id can be referenced as @alias by any row."},reason:{type:"string"},options:{type:"object"},item:{type:"object",description:"Create document using pm create field names (title, type, description, body, tags, parent, custom fields)."},unique:{type:"object",description:"Create-only guard {key,value} re-checked under the writer lock; keyed upsert sets it on rows that matched nothing at planning time."},match:{type:"object",description:"Update-only guard {key,value} re-read under the writer lock; keyed upsert sets it on rows it converted into updates of a matched item."}},additionalProperties:!1}},upsertKey:{type:"string",description:"Item field whose value identifies an existing item to update instead of creating a duplicate."},dryRun:{type:"boolean",description:"Validate and preview without writing."},createCompensation:{type:"string",enum:["close","delete"],description:"How a failed batch compensates created items; defaults to close."},lockTtlSeconds:{type:"number"},lockWaitMs:{type:"number"}},["mutations"])},{name:"pm_copy",description:"Copy an existing pm item into a new id while resetting lifecycle fields. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:objectSchema({id:idSchema,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object",description:"Copy options such as title override, author, and message."}},["id"])},{name:"pm_focus",description:"Set, clear, or show the session focused item. When focused, pm_create defaults its parent to the focused item (an explicit parent still overrides). Pass id to focus an item, options.clear=true to clear, or neither to show current focus.",inputSchema:objectSchema({id:idSchema,clear:{type:"boolean",description:"Clear the focused item (cannot be combined with id)."},options:{type:"object",description:"Focus options such as clear (boolean)."}},[])},{name:"pm_update",description:"Update pm item metadata/body/dependencies/log seeds natively. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields delta.",inputSchema:objectSchema({id:idSchema,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object"}},["id","options"])},{name:"pm_append",description:"Append markdown text to a pm item body and write pm history. Useful for seeding evidence/log entries before close. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:objectSchema({id:idSchema,body:{type:"string",description:"Markdown text to append to the item body. Required here or as options.body."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object",description:"Append options such as body, author, and message."}},["id"])},{name:"pm_claim",description:"Claim a pm item.",inputSchema:objectSchema({id:idSchema,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_release",description:"Release a pm item claim.",inputSchema:objectSchema({id:idSchema,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_close",description:"Close a pm item with optional close reason and optional close validation (reason requirement follows governance settings). Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:objectSchema({id:idSchema,reason:{type:"string",description:"Close reason text when provided or required by governance settings."},duplicateOf:{type:"string",description:"Canonical item id when closing this item as a duplicate."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object"}},["id"])},{name:"pm_comments",description:"List, add, edit, or delete comments on a pm item. Use options.add to append, options.edit=<1-based index> with replacement text to fix a comment, or options.delete=<1-based index> to remove one. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. List calls default to the most recent 20 comments with total_count/has_more metadata for token efficiency. Pass options.limit=N to choose a page size, options.limit=0 for summary-only metadata, or options.full=true for full history.",inputSchema:objectSchema({id:idSchema,options:{type:"object"}},["id"])},{name:"pm_files",description:"List, add, remove, or validate linked files for a pm item.",inputSchema:objectSchema({id:idSchema,options:{type:"object"}},["id"])},{name:"pm_docs",description:"List, add, or remove linked docs for a pm item.",inputSchema:objectSchema({id:idSchema,options:{type:"object"}},["id"])},{name:"pm_notes",description:"List, add, edit, or delete structured notes on a pm item. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. Omit mutation options to list existing notes.",inputSchema:objectSchema({id:idSchema,options:{type:"object"}},["id"])},{name:"pm_learnings",description:"List, add, edit, or delete learnings on a pm item. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. Omit mutation options to list existing learnings.",inputSchema:objectSchema({id:idSchema,options:{type:"object"}},["id"])},{name:"pm_deps",description:"Read dependency trees/graphs or one bounded explainable relationship context packet. Use options.format=context with direction, kind, depth, node, edge, token, and cursor bounds; context returns a counts-first summary, per-node roles/reasons, root evidence pointers, and enumerated missing references.",inputSchema:objectSchema({id:idSchema,options:{type:"object"}},["id"])},{name:"pm_graph",description:"Run bounded workspace relationship-graph queries: ancestors/descendants (hierarchy), predecessors/successors (ordering), paths, impact (blast radius), analyze (execution + knowledge analytics), audit (governance findings with change-since-baseline deltas), communities (label-propagation clusters), redundancy (transitively implied edges), dominators (structural bottlenecks), slack (critical-path method float per task), centrality (betweenness/closeness/degree with directed fan-in/out), articulation (cut points and bridges \u2014 single points of failure), plan (dry-run remediation proposals derived from the audit), and index (durable cross-process graph index status/rebuild/clear). Traversals, paths, impact, and dominators require id; paths also requires target. Options support kind, maxDepth, limit, after, direction, maxPaths, sample, exemptIsolate, exemptIsolateType, saveBaseline (audit), rebuild/clear (index), and counts-first summary.",inputSchema:objectSchema({subcommand:{type:"string",enum:[...GRAPH_SUBCOMMAND_VALUES]},id:idSchema,target:idSchema,options:{type:"object"}},["subcommand"])},{name:"pm_test",description:"List, add, remove, or run linked tests for a pm item.",inputSchema:objectSchema({id:idSchema,options:{type:"object"}},["id"])},{name:"pm_validate",description:"Run pm validation checks.",inputSchema:objectSchema({options:{type:"object"}})},{name:"pm_health",description:"Run pm health diagnostics. Pass options.brief=true for compact low-token details, options.skipIntegrity=true, options.skipDrift=true, options.skipVectors=true for a fast status-only check, or options.full=true for the complete deep check.",inputSchema:objectSchema({options:{type:"object"}})},{name:"pm_contracts",description:"Inspect pm command, flag, schema, and availability contracts.",inputSchema:objectSchema({options:{type:"object"}})},{name:"pm_schema",description:"Inspect or modify the workspace item-type/status/field schema (pm schema). subcommand selects the operation; name carries the item type name (show/add-type/remove-type), status id (show-status/add-status/remove-status), or field key (show-field/add-field/remove-field). apply-preset adopts a domain type preset; add-type with infer=true derives types from title-prefix conventions. Policy verbs author declarations, preview changes, set enforcement, and record content-bound approvals. Registry mutations write workspace history; approvals write item history.",inputSchema:objectSchema({...workflowPolicyOptionProperties,subcommand:{type:"string",enum:["list","show","show-status","add-type","remove-type","add-status","remove-status","add-field","remove-field","list-fields","show-field","apply-preset",...WORKFLOW_POLICY_ACTIONS],description:"Schema subcommand to run."},name:{type:"string",description:"Item type name, status id, field key, policy id, or item id for the selected schema verb; policy-mode requires advise|refuse."},description:{type:"string",description:"Custom item type, status, or field description for add-type/add-status/add-field."},defaultStatus:{type:"string",description:"Default status for add-type."},folder:{type:"string",description:"Storage folder for add-type."},alias:{type:"array",items:{type:"string"},description:"Aliases for add-type/add-status, or extra CLI flag aliases for add-field."},role:{type:"array",items:{type:"string",enum:[...RUNTIME_STATUS_ROLE_VALUES]},description:`Lifecycle roles for add-status: ${RUNTIME_STATUS_ROLE_VALUES.join(", ")}.`},order:{type:"number",description:"Display/sort order for add-status."},fieldType:{type:"string",enum:["string","number","boolean","string_array"],description:"Value type for a custom field (add-field)."},commands:{type:"array",items:{type:"string"},description:"Commands a custom field is wired onto (add-field): create, update, update_many, list, search, calendar, context."},cliFlag:{type:"string",description:"Override the auto-derived CLI flag for a custom field (add-field)."},required:{type:"boolean",description:"Mark a custom field as always required (add-field)."},requiredOnCreate:{type:"boolean",description:"Mark a custom field as required at create time (add-field)."},allowUnset:{type:"boolean",description:"Whether a custom field may be cleared via --unset (add-field); defaults to true."},requiredTypes:{type:"array",items:{type:"string"},description:"Restrict a custom field's requirement to specific item types (add-field)."},typePreset:{type:"string",enum:["agile","ops","research"],description:"Domain type preset to adopt (apply-preset)."},infer:{type:"boolean",description:"Infer item types from title-prefix conventions (add-type); previews unless apply is true."},minCount:{type:"number",description:"Minimum items sharing a prefix for add-type inference (default 10)."},apply:{type:"boolean",description:"Register inferred types (add-type infer); without it the call previews only."},force:{type:"boolean",description:"Override removal guardrails for destructive schema changes when supported."},options:{type:"object",description:"Additional schema options using camelCase keys.",properties:workflowPolicyOptionProperties}},["subcommand"])},{name:"pm_profile",description:"List, show, apply, or lint project profiles (pm profile) \u2014 archetype bundles that stage item types, statuses, fields, per-type workflows, config knobs, create templates, and recommended packages. subcommand selects the operation; name carries the profile name (agile, ops, research) for show/apply/lint. apply stages every dimension idempotently; dryRun previews the diff without writing; lint reports author-time consistency findings (graded error/warning) without touching the tracker. Profile staging writes workspace config/schema files, not item history.",inputSchema:objectSchema({subcommand:{type:"string",enum:["list","show","apply","lint"],description:"Profile subcommand to run."},name:{type:"string",description:"Profile name for show/apply/lint. Required for those subcommands. Built-ins are agile, ops, and research; an active extension can contribute additional archetype names that resolve here too."},dryRun:{type:"boolean",description:"Preview the apply diff without writing any files (apply)."},author:{type:"string",description:"Mutation author for apply."},force:{type:"boolean",description:"Force ownership/lock override for apply."},options:{type:"object",description:"Additional profile options using camelCase keys."}},["subcommand"])},{name:"pm_config",description:"Read or write pm workspace configuration (pm config). configAction selects get/set/list/export; key/value address a single setting for get/set. scope chooses the project (default) or global settings file.",inputSchema:objectSchema({configAction:{type:"string",enum:["get","set","list","export"],description:"Config operation to perform. get/set require key; list/export dump the resolved settings surface."},key:{type:"string",description:"Settings key for get/set, for example governance-require-close-reason, telemetry-tracking, or a nested leaf such as search_provider (dash and underscore variants accepted; configAction=get without a key lists supported keys in the error)."},value:{type:"string",description:"New value for configAction=set."},scope:{type:"string",enum:["project","global"],description:"Settings scope to read or write. Defaults to project."},options:{type:"object",description:"Additional config options such as criterion, clearCriteria, format, or policy."}},["configAction"])},{name:"pm_plan",description:"Run agent-optimized Plan workflows. options.subcommand selects: create|show|add-step|update-step|complete-step|block-step|reorder-step|remove-step|link|unlink|decision|discovery|validation|resume|approve|materialize. Provide id for all non-create subcommands; provide stepRef for step lifecycle subcommands. Plans store agent-readable steps with dependencies, decisions, discoveries, validation, and resume context.",inputSchema:objectSchema({id:{type:"string",description:"Plan id (required for all subcommands except create)."},stepRef:{type:"string",description:"Step id or order for step lifecycle subcommands."},options:{type:"object",description:"Plan options including subcommand, stepRef, stepStatus, link, depth, etc."}})}],NARROW_TOOL_ACTIONS={pm_append:"append",pm_claim:"claim",pm_close:"close",pm_comments:"comments",pm_config:"config",pm_context:"context",pm_contracts:"contracts",pm_copy:"copy",pm_create:"create",pm_deps:"deps",pm_docs:"docs",pm_events:"events",pm_files:"files",pm_focus:"focus",pm_get:"get",pm_graph:"graph",pm_health:"health",pm_learnings:"learnings",pm_list:"list",pm_next:"next",pm_notes:"notes",pm_plan:"plan",pm_profile:"profile",pm_release:"release",pm_schema:"schema",pm_search:"search",pm_test:"test",pm_update:"update",pm_validate:"validate"},TOOLS=RAW_TOOLS.map(tool=>{const action=NARROW_TOOL_ACTIONS[tool.name];if(!action)return tool;const properties=tool.inputSchema.properties,required=tool.inputSchema.required.map(String);return{...tool,inputSchema:buildPmActionToolInputSchema(action,{properties,required})}});function buildMcpToolContracts(){return TOOLS.map(tool=>{const schemaRequired=tool.inputSchema.required,required=Array.isArray(schemaRequired)?schemaRequired.map(entry=>String(entry)).sort((left,right)=>left.localeCompare(right)):[];return{name:tool.name,description:tool.description,required,input_schema:tool.inputSchema}}).sort((left,right)=>left.name.localeCompare(right.name))}export{NARROW_TOOL_ACTIONS,TOOLS,TOOL_SCHEMA_BASE,buildMcpToolContracts};
|
|
2
2
|
//# sourceMappingURL=tool-definitions.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]="d956e747-cbca-5e3c-925f-e1aeb2ebbfa7")}catch{}})();import{stripVTControlCharacters}from"node:util";import{resolvePmHistoryOperation}from"./command-aliases.js";import{PM_CORE_COMMAND_NAMES}from"./enum-contracts.js";const PM_OUTPUT_DEGRADATION_STEPS=["full","compact","brief","summary","counts"],PM_OUTPUT_BUDGET_CLASSES=["mutation","read","discovery","governance"],PM_DIAGNOSTIC_OUTPUT_CLASSES=["error","warning","validation_summary","recovery_bundle"],PM_DIAGNOSTIC_DEGRADATION_STEPS=["full","omit_explanation","limit_collections","compact_recovery","action_only"],MUTATION_COMMANDS=new Set(["append","claim","close","close-many","close-task","comments","config","copy","create","delete","docs","event","files","focus","history-author-acknowledge","history-compact","history-redact","history-repair","init","item","learnings","meet","notes","pause-task","release","remind","restore","schema","start-task","update","update-many"]),DISCOVERY_COMMANDS=new Set(["contracts","extension","help","install","package","packages","profile","upgrade"]),GOVERNANCE_COMMANDS=new Set(["gc","health","merge","stats","telemetry","test","test-all","validate"]),DEFAULT_MAX_ESTIMATED_TOKENS={mutation:2e3,read:4e3,discovery:3e3,governance:6e3},JSON_BUDGET_NUMERATOR=3,JSON_BUDGET_DENOMINATOR=2,MINIMUM_DIAGNOSTIC_BUDGET=192,DIAGNOSTIC_DEFAULT_BUDGETS={error:{text:768,json:2e3},warning:{text:768,json:2e3},validation_summary:{text:1500,json:3e3},recovery_bundle:{text:768,json:2e3}},PM_DIAGNOSTIC_OUTPUT_BUDGET_CONTRACTS=PM_DIAGNOSTIC_OUTPUT_CLASSES.map(diagnosticClass=>({diagnostic_class:diagnosticClass,default_max_estimated_tokens_by_format:DIAGNOSTIC_DEFAULT_BUDGETS[diagnosticClass],minimum_max_estimated_tokens:MINIMUM_DIAGNOSTIC_BUDGET,degradation_ladder:PM_DIAGNOSTIC_DEGRADATION_STEPS,corrective_action_paths:["required","recovery.suggested_retry","recovery.suggested_retry_args","recovery.next_best_command","next_steps[0]"],token_estimate:"ceil(utf8_bytes / 4)"})),DIAGNOSTIC_BUDGET_BY_CLASS=new Map(PM_DIAGNOSTIC_OUTPUT_BUDGET_CONTRACTS.map(contract=>[contract.diagnostic_class,contract]));function inferPmOutputBudgetClass(command){const[rootCommand=""]=resolvePmHistoryOperation(command).split(/\s+/u);return MUTATION_COMMANDS.has(rootCommand)?"mutation":DISCOVERY_COMMANDS.has(rootCommand)?"discovery":GOVERNANCE_COMMANDS.has(rootCommand)?"governance":"read"}function createPmCommandOutputBudget(command,budgetClass=inferPmOutputBudgetClass(command)){const normalizedCommand=command.trim().replace(/\s+/gu," ");if(normalizedCommand.length===0)throw new TypeError("command must be a non-empty command path");const toonBudget=DEFAULT_MAX_ESTIMATED_TOKENS[budgetClass];return definePmCommandOutputBudget({command:normalizedCommand,budget_class:budgetClass,default_max_estimated_tokens:toonBudget,default_max_estimated_tokens_by_format:{toon:toonBudget,json:Math.ceil(toonBudget*JSON_BUDGET_NUMERATOR/JSON_BUDGET_DENOMINATOR)},degradation_ladder:PM_OUTPUT_DEGRADATION_STEPS,allows_unbounded_opt_out:!0,token_estimate:"ceil(utf8_bytes / 4)"})}function definePmCommandOutputBudget(contract){if(!Number.isSafeInteger(contract.default_max_estimated_tokens)||contract.default_max_estimated_tokens<=0)throw new RangeError("default_max_estimated_tokens must be a positive safe integer");for(const[format,ceiling]of Object.entries(contract.default_max_estimated_tokens_by_format))if(!Number.isSafeInteger(ceiling)||ceiling<=0)throw new RangeError(`default_max_estimated_tokens_by_format.${format} must be a positive safe integer`);return contract}const PM_COMMAND_OUTPUT_BUDGET_CONTRACTS=PM_CORE_COMMAND_NAMES.map(command=>createPmCommandOutputBudget(command)),OUTPUT_BUDGET_BY_COMMAND=new Map(PM_COMMAND_OUTPUT_BUDGET_CONTRACTS.map(contract=>[contract.command,contract]));function resolvePmCommandOutputBudget(command,options={}){const normalizedCommand=command.trim().replace(/\s+/gu," "),[rootCommand]=resolvePmHistoryOperation(normalizedCommand).split(" "),declared=OUTPUT_BUDGET_BY_COMMAND.get(rootCommand);return declared?{...declared,command:normalizedCommand}:options.generateFallback?createPmCommandOutputBudget(normalizedCommand):null}function estimatePmOutputTokens(utf8Bytes){return Math.ceil(Math.max(0,utf8Bytes)/4)}function resolvePmDiagnosticOutputBudget(diagnosticClass){const contract=DIAGNOSTIC_BUDGET_BY_CLASS.get(diagnosticClass);if(contract===void 0)throw new TypeError(`diagnosticClass must be one of: ${PM_DIAGNOSTIC_OUTPUT_CLASSES.join(", ")}`);return contract}function estimateJsonDiagnosticTokens(value){return estimatePmOutputTokens(Buffer.byteLength(JSON.stringify(value,null,2),"utf8"))}function isDiagnosticRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function compactDiagnosticRecovery(value){if(!isDiagnosticRecord(value))return;const compact={};for(const key of["suggested_retry","suggested_retry_args","next_best_command","allowed_values","candidate_commands","missing","missing_required_fields","option_scope","retry_after_ms"]){const candidate=value[key];Array.isArray(candidate)?compact[key]=key==="suggested_retry_args"?candidate:candidate.slice(0,3):candidate!==void 0&&(compact[key]=candidate)}return Object.keys(compact).length>0?compact:void 0}function truncateDiagnosticString(value,maximum){return typeof value!="string"||value.length<=maximum?value:`${value.slice(0,Math.max(1,maximum-3))}...`}function truncateDiagnosticUtf8Text(value,maximumBytes){if(Buffer.byteLength(value,"utf8")<=maximumBytes)return value;const suffix="...",codePoints=Array.from(value);let lower=0,upper=codePoints.length;for(;lower<upper;){const middle=Math.ceil((lower+upper)/2),candidate=`${codePoints.slice(0,middle).join("")}${suffix}`;Buffer.byteLength(candidate,"utf8")<=maximumBytes?lower=middle:upper=middle-1}return`${codePoints.slice(0,lower).join("")}${suffix}`}function prioritizeDiagnosticFields(diagnostic){const prioritized={};for(const key of["code","required","recovery","next_steps","exit_code","type","title","detail","why","examples"])Object.hasOwn(diagnostic,key)&&diagnostic[key]!==void 0&&(prioritized[key]=diagnostic[key]);for(const[key,value]of Object.entries(diagnostic))key!=="__proto__"&&!Object.hasOwn(prioritized,key)&&(prioritized[key]=value);return prioritized}const DIAGNOSTIC_COLLECTION_LIMIT_STAGES=new Set(["limit_collections","compact_recovery","action_only"]),DIAGNOSTIC_RECOVERY_COMPACTION_STAGES=new Set(["compact_recovery","action_only"]);function actionOnlyDiagnostic(candidate){const actionOnly={code:typeof candidate.code=="string"?candidate.code:"diagnostic",required:truncateDiagnosticString(candidate.required,160)??"Inspect the diagnostic code and retry with corrected input."},recovery=compactDiagnosticRecovery(candidate.recovery);return recovery!==void 0?actionOnly.recovery=recovery:Array.isArray(candidate.next_steps)&&(actionOnly.next_steps=candidate.next_steps.slice(0,1)),candidate.exit_code!==void 0&&(actionOnly.exit_code=candidate.exit_code),candidate.type!==void 0&&(actionOnly.type=candidate.type),actionOnly}function diagnosticCandidate(diagnostic,stage){const candidate=structuredClone(diagnostic);if(stage!=="full"&&(delete candidate.why,delete candidate.examples),DIAGNOSTIC_COLLECTION_LIMIT_STAGES.has(stage))for(const[key,value]of Object.entries(candidate))Array.isArray(value)&&(candidate[key]=value.slice(0,3));if(DIAGNOSTIC_RECOVERY_COMPACTION_STAGES.has(stage)){const recovery=compactDiagnosticRecovery(candidate.recovery);recovery?candidate.recovery=recovery:delete candidate.recovery}return stage!=="action_only"?prioritizeDiagnosticFields(candidate):actionOnlyDiagnostic(candidate)}function attachDiagnosticReceipt(candidate,receipt){const projected={...candidate,diagnostic_output:{...receipt,estimated_tokens:0}};for(let attempt=0;attempt<4;attempt+=1){const estimatedTokens=estimateJsonDiagnosticTokens(projected),outputReceipt=projected.diagnostic_output;if(outputReceipt.estimated_tokens===estimatedTokens)break;outputReceipt.estimated_tokens=estimatedTokens}return projected}function shrinkMinimalDiagnosticCandidate(candidate,receipt,budget){let fallback=attachDiagnosticReceipt(candidate,receipt);for(const optionalField of["recovery","exit_code"])estimateJsonDiagnosticTokens(fallback)<=budget||candidate[optionalField]===void 0||(delete candidate[optionalField],fallback=attachDiagnosticReceipt(candidate,receipt));let maximumActionBytes=40;for(;estimateJsonDiagnosticTokens(fallback)>budget&&maximumActionBytes>4;)maximumActionBytes-=4,candidate.code=truncateDiagnosticUtf8Text(String(candidate.code),maximumActionBytes),candidate.required=truncateDiagnosticUtf8Text(String(candidate.required),maximumActionBytes),fallback=attachDiagnosticReceipt(candidate,receipt);return fallback}function createMinimalDiagnosticFallback(projected,budget){const receipt=projected.diagnostic_output,{estimated_tokens:_estimatedTokens,...receiptWithoutEstimate}=receipt,boundedOmittedFields=receiptWithoutEstimate.omitted_fields.slice(0,8).map(field=>truncateDiagnosticUtf8Text(field,32)),boundedReceipt={...receiptWithoutEstimate,omitted_fields:boundedOmittedFields,...receiptWithoutEstimate.omitted_fields.length>boundedOmittedFields.length?{omitted_fields_overflow_count:receiptWithoutEstimate.omitted_fields.length-boundedOmittedFields.length}:{}},recoveryCandidate=compactDiagnosticRecovery(projected.recovery),recovery=recoveryCandidate&&estimateJsonDiagnosticTokens(recoveryCandidate)<=48?recoveryCandidate:void 0,candidate={code:truncateDiagnosticUtf8Text(String(projected.code),320),required:truncateDiagnosticUtf8Text(String(projected.required),320),...recovery?{recovery}:{},...projected.exit_code!==void 0?{exit_code:projected.exit_code}:{}};let fallback=attachDiagnosticReceipt(candidate,boundedReceipt);for(;estimateJsonDiagnosticTokens(fallback)>budget&&boundedReceipt.omitted_fields.length>0;)boundedReceipt.omitted_fields.pop(),boundedReceipt.omitted_fields_overflow_count=receiptWithoutEstimate.omitted_fields.length-boundedReceipt.omitted_fields.length,fallback=attachDiagnosticReceipt(candidate,boundedReceipt);return fallback=shrinkMinimalDiagnosticCandidate(candidate,boundedReceipt,budget),fallback}function projectPmDiagnosticOutput(diagnostic,options={}){const diagnosticRecord=diagnostic,diagnosticClass=options.diagnosticClass??"error",contract=resolvePmDiagnosticOutputBudget(diagnosticClass),explicitBudget=options.maxEstimatedTokens;if(explicitBudget!==void 0&&(!Number.isSafeInteger(explicitBudget)||explicitBudget<contract.minimum_max_estimated_tokens))throw new RangeError(`maxEstimatedTokens must be a safe integer >= ${contract.minimum_max_estimated_tokens}`);const budget=explicitBudget??contract.default_max_estimated_tokens_by_format.json,originalEstimatedTokens=estimateJsonDiagnosticTokens(diagnosticRecord),originalFields=Object.keys(diagnosticRecord);if(originalEstimatedTokens<=budget)return prioritizeDiagnosticFields(structuredClone(diagnosticRecord));let projected;for(const[index,stage]of contract.degradation_ladder.entries()){const candidate=diagnosticCandidate(diagnosticRecord,stage),omittedFields=originalFields.filter(field=>!Object.hasOwn(candidate,field)),withReceipt=attachDiagnosticReceipt(candidate,{diagnostic_class:diagnosticClass,format:"json",budget,budget_source:explicitBudget===void 0?"default":"explicit",original_estimated_tokens:originalEstimatedTokens,truncated:index>0,degradation_steps:contract.degradation_ladder.slice(0,index+1),omitted_fields:omittedFields});if(projected=withReceipt,estimateJsonDiagnosticTokens(withReceipt)<=budget)break}return estimateJsonDiagnosticTokens(projected)>budget&&(projected=createMinimalDiagnosticFallback(projected,budget)),projected}function sanitizeDiagnosticText(text){return stripVTControlCharacters(text).replace(/\r\n/gu,`
|
|
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]="c8a91fc2-57b4-5738-9428-9847ef7afadc")}catch{}})();import{stripVTControlCharacters}from"node:util";import{unicodeSafePrefix}from"../../core/shared/text-normalization.js";import{resolvePmHistoryOperation}from"./command-aliases.js";import{PM_CORE_COMMAND_NAMES}from"./enum-contracts.js";const PM_OUTPUT_DEGRADATION_STEPS=["full","compact","brief","summary","counts"],PM_OUTPUT_BUDGET_CLASSES=["mutation","read","discovery","governance"],PM_DIAGNOSTIC_OUTPUT_CLASSES=["error","warning","validation_summary","recovery_bundle"],PM_DIAGNOSTIC_DEGRADATION_STEPS=["full","omit_explanation","limit_collections","compact_recovery","action_only"],MUTATION_COMMANDS=new Set(["append","claim","close","close-many","close-task","comments","config","copy","create","delete","docs","event","files","focus","history-author-acknowledge","history-compact","history-redact","history-repair","init","item","learnings","meet","notes","pause-task","release","remind","restore","schema","start-task","update","update-many"]),DISCOVERY_COMMANDS=new Set(["contracts","extension","help","install","package","packages","profile","upgrade"]),GOVERNANCE_COMMANDS=new Set(["gc","health","merge","stats","telemetry","test","test-all","validate"]),DEFAULT_MAX_ESTIMATED_TOKENS={mutation:2e3,read:4e3,discovery:3e3,governance:6e3},JSON_BUDGET_NUMERATOR=3,JSON_BUDGET_DENOMINATOR=2,MINIMUM_DIAGNOSTIC_BUDGET=192,DIAGNOSTIC_DEFAULT_BUDGETS={error:{text:768,json:2e3},warning:{text:768,json:2e3},validation_summary:{text:1500,json:3e3},recovery_bundle:{text:768,json:2e3}},PM_DIAGNOSTIC_OUTPUT_BUDGET_CONTRACTS=PM_DIAGNOSTIC_OUTPUT_CLASSES.map(diagnosticClass=>({diagnostic_class:diagnosticClass,default_max_estimated_tokens_by_format:DIAGNOSTIC_DEFAULT_BUDGETS[diagnosticClass],minimum_max_estimated_tokens:MINIMUM_DIAGNOSTIC_BUDGET,degradation_ladder:PM_DIAGNOSTIC_DEGRADATION_STEPS,corrective_action_paths:["required","recovery.suggested_retry","recovery.suggested_retry_args","recovery.next_best_command","next_steps[0]"],token_estimate:"ceil(utf8_bytes / 4)"})),DIAGNOSTIC_BUDGET_BY_CLASS=new Map(PM_DIAGNOSTIC_OUTPUT_BUDGET_CONTRACTS.map(contract=>[contract.diagnostic_class,contract]));function inferPmOutputBudgetClass(command){const[rootCommand=""]=resolvePmHistoryOperation(command).split(/\s+/u);return MUTATION_COMMANDS.has(rootCommand)?"mutation":DISCOVERY_COMMANDS.has(rootCommand)?"discovery":GOVERNANCE_COMMANDS.has(rootCommand)?"governance":"read"}function createPmCommandOutputBudget(command,budgetClass=inferPmOutputBudgetClass(command)){const normalizedCommand=command.trim().replace(/\s+/gu," ");if(normalizedCommand.length===0)throw new TypeError("command must be a non-empty command path");const toonBudget=DEFAULT_MAX_ESTIMATED_TOKENS[budgetClass];return definePmCommandOutputBudget({command:normalizedCommand,budget_class:budgetClass,default_max_estimated_tokens:toonBudget,default_max_estimated_tokens_by_format:{toon:toonBudget,json:Math.ceil(toonBudget*JSON_BUDGET_NUMERATOR/JSON_BUDGET_DENOMINATOR)},degradation_ladder:PM_OUTPUT_DEGRADATION_STEPS,allows_unbounded_opt_out:!0,token_estimate:"ceil(utf8_bytes / 4)"})}function definePmCommandOutputBudget(contract){if(!Number.isSafeInteger(contract.default_max_estimated_tokens)||contract.default_max_estimated_tokens<=0)throw new RangeError("default_max_estimated_tokens must be a positive safe integer");for(const[format,ceiling]of Object.entries(contract.default_max_estimated_tokens_by_format))if(!Number.isSafeInteger(ceiling)||ceiling<=0)throw new RangeError(`default_max_estimated_tokens_by_format.${format} must be a positive safe integer`);return contract}const PM_COMMAND_OUTPUT_BUDGET_CONTRACTS=PM_CORE_COMMAND_NAMES.map(command=>createPmCommandOutputBudget(command)),OUTPUT_BUDGET_BY_COMMAND=new Map(PM_COMMAND_OUTPUT_BUDGET_CONTRACTS.map(contract=>[contract.command,contract]));function resolvePmCommandOutputBudget(command,options={}){const normalizedCommand=command.trim().replace(/\s+/gu," "),[rootCommand]=resolvePmHistoryOperation(normalizedCommand).split(" "),declared=OUTPUT_BUDGET_BY_COMMAND.get(rootCommand);return declared?{...declared,command:normalizedCommand}:options.generateFallback?createPmCommandOutputBudget(normalizedCommand):null}function estimatePmOutputTokens(utf8Bytes){return Math.ceil(Math.max(0,utf8Bytes)/4)}function resolvePmDiagnosticOutputBudget(diagnosticClass){const contract=DIAGNOSTIC_BUDGET_BY_CLASS.get(diagnosticClass);if(contract===void 0)throw new TypeError(`diagnosticClass must be one of: ${PM_DIAGNOSTIC_OUTPUT_CLASSES.join(", ")}`);return contract}function estimateJsonDiagnosticTokens(value){return estimatePmOutputTokens(Buffer.byteLength(JSON.stringify(value,null,2),"utf8"))}function isDiagnosticRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function compactDiagnosticRecovery(value){if(!isDiagnosticRecord(value))return;const compact={};for(const key of["suggested_retry","suggested_retry_args","next_best_command","allowed_values","candidate_commands","missing","missing_required_fields","option_scope","retry_after_ms"]){const candidate=value[key];Array.isArray(candidate)?compact[key]=key==="suggested_retry_args"?candidate:candidate.slice(0,3):candidate!==void 0&&(compact[key]=candidate)}return Object.keys(compact).length>0?compact:void 0}function truncateDiagnosticString(value,maximum){return typeof value!="string"||value.length<=maximum?value:`${unicodeSafePrefix(value,Math.max(1,maximum-3))}...`}function truncateDiagnosticUtf8Text(value,maximumBytes){if(Buffer.byteLength(value,"utf8")<=maximumBytes)return value;const suffix="...",codePoints=Array.from(value);let lower=0,upper=codePoints.length;for(;lower<upper;){const middle=Math.ceil((lower+upper)/2),candidate=`${codePoints.slice(0,middle).join("")}${suffix}`;Buffer.byteLength(candidate,"utf8")<=maximumBytes?lower=middle:upper=middle-1}return`${codePoints.slice(0,lower).join("")}${suffix}`}function prioritizeDiagnosticFields(diagnostic){const prioritized={};for(const key of["code","required","recovery","next_steps","exit_code","type","title","detail","why","examples"])Object.hasOwn(diagnostic,key)&&diagnostic[key]!==void 0&&(prioritized[key]=diagnostic[key]);for(const[key,value]of Object.entries(diagnostic))key!=="__proto__"&&!Object.hasOwn(prioritized,key)&&(prioritized[key]=value);return prioritized}const DIAGNOSTIC_COLLECTION_LIMIT_STAGES=new Set(["limit_collections","compact_recovery","action_only"]),DIAGNOSTIC_RECOVERY_COMPACTION_STAGES=new Set(["compact_recovery","action_only"]);function actionOnlyDiagnostic(candidate){const actionOnly={code:typeof candidate.code=="string"?candidate.code:"diagnostic",required:truncateDiagnosticString(candidate.required,160)??"Inspect the diagnostic code and retry with corrected input."},recovery=compactDiagnosticRecovery(candidate.recovery);return recovery!==void 0?actionOnly.recovery=recovery:Array.isArray(candidate.next_steps)&&(actionOnly.next_steps=candidate.next_steps.slice(0,1)),candidate.exit_code!==void 0&&(actionOnly.exit_code=candidate.exit_code),candidate.type!==void 0&&(actionOnly.type=candidate.type),actionOnly}function diagnosticCandidate(diagnostic,stage){const candidate=structuredClone(diagnostic);if(stage!=="full"&&(delete candidate.why,delete candidate.examples),DIAGNOSTIC_COLLECTION_LIMIT_STAGES.has(stage))for(const[key,value]of Object.entries(candidate))Array.isArray(value)&&(candidate[key]=value.slice(0,3));if(DIAGNOSTIC_RECOVERY_COMPACTION_STAGES.has(stage)){const recovery=compactDiagnosticRecovery(candidate.recovery);recovery?candidate.recovery=recovery:delete candidate.recovery}return stage!=="action_only"?prioritizeDiagnosticFields(candidate):actionOnlyDiagnostic(candidate)}function attachDiagnosticReceipt(candidate,receipt){const projected={...candidate,diagnostic_output:{...receipt,estimated_tokens:0}};for(let attempt=0;attempt<4;attempt+=1){const estimatedTokens=estimateJsonDiagnosticTokens(projected),outputReceipt=projected.diagnostic_output;if(outputReceipt.estimated_tokens===estimatedTokens)break;outputReceipt.estimated_tokens=estimatedTokens}return projected}function shrinkMinimalDiagnosticCandidate(candidate,receipt,budget){let fallback=attachDiagnosticReceipt(candidate,receipt);for(const optionalField of["recovery","exit_code"])estimateJsonDiagnosticTokens(fallback)<=budget||candidate[optionalField]===void 0||(delete candidate[optionalField],fallback=attachDiagnosticReceipt(candidate,receipt));let maximumActionBytes=40;for(;estimateJsonDiagnosticTokens(fallback)>budget&&maximumActionBytes>4;)maximumActionBytes-=4,candidate.code=truncateDiagnosticUtf8Text(String(candidate.code),maximumActionBytes),candidate.required=truncateDiagnosticUtf8Text(String(candidate.required),maximumActionBytes),fallback=attachDiagnosticReceipt(candidate,receipt);return fallback}function createMinimalDiagnosticFallback(projected,budget){const receipt=projected.diagnostic_output,{estimated_tokens:_estimatedTokens,...receiptWithoutEstimate}=receipt,boundedOmittedFields=receiptWithoutEstimate.omitted_fields.slice(0,8).map(field=>truncateDiagnosticUtf8Text(field,32)),boundedReceipt={...receiptWithoutEstimate,omitted_fields:boundedOmittedFields,...receiptWithoutEstimate.omitted_fields.length>boundedOmittedFields.length?{omitted_fields_overflow_count:receiptWithoutEstimate.omitted_fields.length-boundedOmittedFields.length}:{}},recoveryCandidate=compactDiagnosticRecovery(projected.recovery),recovery=recoveryCandidate&&estimateJsonDiagnosticTokens(recoveryCandidate)<=48?recoveryCandidate:void 0,candidate={code:truncateDiagnosticUtf8Text(String(projected.code),320),required:truncateDiagnosticUtf8Text(String(projected.required),320),...recovery?{recovery}:{},...projected.exit_code!==void 0?{exit_code:projected.exit_code}:{}};let fallback=attachDiagnosticReceipt(candidate,boundedReceipt);for(;estimateJsonDiagnosticTokens(fallback)>budget&&boundedReceipt.omitted_fields.length>0;)boundedReceipt.omitted_fields.pop(),boundedReceipt.omitted_fields_overflow_count=receiptWithoutEstimate.omitted_fields.length-boundedReceipt.omitted_fields.length,fallback=attachDiagnosticReceipt(candidate,boundedReceipt);return fallback=shrinkMinimalDiagnosticCandidate(candidate,boundedReceipt,budget),fallback}function projectPmDiagnosticOutput(diagnostic,options={}){const diagnosticRecord=diagnostic,diagnosticClass=options.diagnosticClass??"error",contract=resolvePmDiagnosticOutputBudget(diagnosticClass),explicitBudget=options.maxEstimatedTokens;if(explicitBudget!==void 0&&(!Number.isSafeInteger(explicitBudget)||explicitBudget<contract.minimum_max_estimated_tokens))throw new RangeError(`maxEstimatedTokens must be a safe integer >= ${contract.minimum_max_estimated_tokens}`);const budget=explicitBudget??contract.default_max_estimated_tokens_by_format.json,originalEstimatedTokens=estimateJsonDiagnosticTokens(diagnosticRecord),originalFields=Object.keys(diagnosticRecord);if(originalEstimatedTokens<=budget)return prioritizeDiagnosticFields(structuredClone(diagnosticRecord));let projected;for(const[index,stage]of contract.degradation_ladder.entries()){const candidate=diagnosticCandidate(diagnosticRecord,stage),omittedFields=originalFields.filter(field=>!Object.hasOwn(candidate,field)),withReceipt=attachDiagnosticReceipt(candidate,{diagnostic_class:diagnosticClass,format:"json",budget,budget_source:explicitBudget===void 0?"default":"explicit",original_estimated_tokens:originalEstimatedTokens,truncated:index>0,degradation_steps:contract.degradation_ladder.slice(0,index+1),omitted_fields:omittedFields});if(projected=withReceipt,estimateJsonDiagnosticTokens(withReceipt)<=budget)break}return estimateJsonDiagnosticTokens(projected)>budget&&(projected=createMinimalDiagnosticFallback(projected,budget)),projected}function sanitizeDiagnosticText(text){return stripVTControlCharacters(text).replace(/\r\n/gu,`
|
|
2
2
|
`).replace(/[^\P{Cc}\n]/gu," ")}function projectPmDiagnosticText(output,correctiveAction,options={}){const diagnosticClass=options.diagnosticClass??"error",contract=resolvePmDiagnosticOutputBudget(diagnosticClass),explicitBudget=options.maxEstimatedTokens;if(explicitBudget!==void 0&&(!Number.isSafeInteger(explicitBudget)||explicitBudget<contract.minimum_max_estimated_tokens))throw new RangeError(`maxEstimatedTokens must be a safe integer >= ${contract.minimum_max_estimated_tokens}`);const budget=explicitBudget??contract.default_max_estimated_tokens_by_format.text,sanitizedOutput=sanitizeDiagnosticText(output),originalEstimatedTokens=estimatePmOutputTokens(Buffer.byteLength(sanitizedOutput,"utf8")),truncated=originalEstimatedTokens>budget,actionPrefix=`What is required:
|
|
3
3
|
`,actionSuffix=`
|
|
4
4
|
|