@unbrained/pm-cli 2026.11.23 → 2026.11.25
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +1 -1
- package/dist/cli/error-guidance.js +5 -5
- package/dist/cli/main.js +5 -5
- package/dist/cli/register-annotations.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-4FZH5BTV.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-YYT3MIRF.js → chunk-6OIHST4I.js} +1 -1
- package/dist/cli-bundle/chunks/chunk-7EPYCU7U.js +9 -0
- package/dist/cli-bundle/chunks/{chunk-AEOHUSUI.js → chunk-BVJMVU4Z.js} +68 -68
- package/dist/cli-bundle/chunks/{chunk-2UQU7HRR.js → chunk-C4KIZQHW.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-CNUFU454.js +113 -0
- package/dist/cli-bundle/chunks/chunk-CONBVY2O.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-BSRIVYTM.js → chunk-CZEMEPPQ.js} +3 -3
- package/dist/cli-bundle/chunks/chunk-DF6A7C32.js +2 -0
- package/dist/cli-bundle/chunks/chunk-FHLOGAGA.js +8 -0
- package/dist/cli-bundle/chunks/chunk-FVY7U3SU.js +125 -0
- package/dist/cli-bundle/chunks/{chunk-F2Z6XLZB.js → chunk-GBVF2ZB3.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-GZI7ZAB7.js +2 -0
- package/dist/cli-bundle/chunks/chunk-HZZLSBIJ.js +2 -0
- package/dist/cli-bundle/chunks/chunk-K34FR5CO.js +3 -0
- package/dist/cli-bundle/chunks/{chunk-D6PDUKUG.js → chunk-KHFUHGL3.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-L6VS7F3R.js +2 -0
- package/dist/cli-bundle/chunks/chunk-LOX3VY4T.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-H7JEXRIN.js → chunk-LPW7S5KA.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-5DUP4AZA.js → chunk-MGJMQSN4.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-OS5W4ZG2.js +31 -0
- package/dist/cli-bundle/chunks/{chunk-O7JHS64G.js → chunk-OWK2JL4I.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-SCIPT7WF.js +2 -0
- package/dist/cli-bundle/chunks/chunk-SX76UGEY.js +3 -0
- package/dist/cli-bundle/chunks/{chunk-CFWLQFJM.js → chunk-VA4T37Q4.js} +50 -51
- package/dist/cli-bundle/chunks/chunk-WQOEVGLQ.js +2 -0
- package/dist/cli-bundle/chunks/chunk-XHCIOLJP.js +3 -0
- package/dist/cli-bundle/chunks/{chunk-J2PDAVBC.js → chunk-XKWJONAO.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-YIGBEY7K.js +2 -0
- package/dist/cli-bundle/chunks/chunk-ZBOQEZ2H.js +33 -0
- package/dist/cli-bundle/chunks/chunk-ZLICQPRG.js +3 -0
- package/dist/cli-bundle/chunks/field-option-collisions-QE65APSD.js +2 -0
- package/dist/cli-bundle/chunks/{indexed-receipt-blobs-BPYKN5Q7.js → indexed-receipt-blobs-H3MMNXXG.js} +2 -2
- package/dist/cli-bundle/{focused-chunks/item-revision-YDACCDVY.js → chunks/item-revision-INDHJV6X.js} +2 -2
- package/dist/cli-bundle/chunks/item-transaction-LCKK4XXB.js +2 -0
- package/dist/cli-bundle/chunks/mutation-actor-KU7BMLUN.js +2 -0
- package/dist/cli-bundle/chunks/mutation-admission-3OMCTQD4.js +2 -0
- package/dist/cli-bundle/chunks/{register-list-query-L4IBU64P.js → register-list-query-3GV3LBOT.js} +2 -2
- package/dist/cli-bundle/chunks/register-mutation-GZLF47SX.js +21 -0
- package/dist/cli-bundle/chunks/register-operations-PBJZGCAL.js +2 -0
- package/dist/cli-bundle/chunks/register-setup-ZLJEF6NZ.js +2 -0
- package/dist/cli-bundle/chunks/runtime-schema-Y4SHTEXL.js +2 -0
- package/dist/cli-bundle/chunks/{settlement-hook-6MR32OOC.js → settlement-hook-ESAAEBRM.js} +2 -2
- package/dist/cli-bundle/chunks/stage-3WIZBD4N.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-3Y5PTQ2F.js +27 -0
- package/dist/cli-bundle/focused-chunks/{chunk-Y2ESLKCF.js → chunk-4LQL4EO6.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{chunk-RIE3SJSE.js → chunk-4SX2BN4V.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-ZHWPCVQL.js → chunk-5RBC4WSE.js} +39 -39
- package/dist/cli-bundle/focused-chunks/chunk-7SSGTGZO.js +91 -0
- package/dist/cli-bundle/focused-chunks/chunk-A4R57E4K.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-BOIMP2AR.js +5 -0
- package/dist/cli-bundle/focused-chunks/chunk-BYQK5DGH.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-C3FEDTSD.js +44 -0
- package/dist/cli-bundle/focused-chunks/chunk-IAOKVKWW.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-JOKRDFMQ.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-MB56Y4M6.js +8 -0
- package/dist/cli-bundle/focused-chunks/{chunk-A6VEMCRR.js → chunk-NGFDPEP7.js} +1 -1
- package/dist/cli-bundle/focused-chunks/chunk-OCKKIECS.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-PKX2EHE3.js +26 -0
- package/dist/cli-bundle/focused-chunks/chunk-SXC2EO3E.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-TQIKDFOD.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-TRL4JDWX.js +8 -0
- package/dist/cli-bundle/focused-chunks/{chunk-IROZDIDX.js → chunk-UWWAVXG4.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-VMYVN36N.js +13 -0
- package/dist/cli-bundle/focused-chunks/chunk-VU2PH4PF.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-WL2R7T5G.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-WVA5KOXF.js +3 -0
- package/dist/cli-bundle/focused-chunks/{chunk-QQIIMMFU.js → chunk-X4EWD6TL.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-XKLBTDJ7.js +100 -0
- package/dist/cli-bundle/focused-chunks/chunk-YYEWIKNI.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-ZLRRII55.js +2 -0
- package/dist/cli-bundle/focused-chunks/field-option-collisions-5ROXGUME.js +2 -0
- package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-EGEJMG3G.js → indexed-receipt-blobs-PG2VJ3MB.js} +2 -2
- package/dist/cli-bundle/focused-chunks/item-revision-KYMSQVZE.js +2 -0
- package/dist/cli-bundle/focused-chunks/item-transaction-I4HLVHEJ.js +2 -0
- package/dist/cli-bundle/focused-chunks/mutation-actor-GGOQKAE6.js +2 -0
- package/dist/cli-bundle/focused-chunks/mutation-admission-OS36ZCMH.js +2 -0
- package/dist/cli-bundle/focused-chunks/runtime-schema-YXPYDD2C.js +2 -0
- package/dist/cli-bundle/focused-chunks/{settlement-hook-FMLGKG7J.js → settlement-hook-4MGRERCT.js} +2 -2
- package/dist/cli-bundle/focused-chunks/stage-4ZFWJUKO.js +2 -0
- package/dist/cli-bundle/main.js +26 -26
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +4 -4
- package/dist/cli-bundle/sdk-core.js +1 -1
- package/dist/cli-bundle/sdk-governance.js +1 -1
- package/dist/cli-bundle/sdk-graph.js +1 -1
- package/dist/cli-bundle/sdk-merge.js +63 -63
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +12 -12
- package/dist/core/profile/profile-lint.d.ts +1 -1
- package/dist/core/profile/profile-lint.js +1 -1
- package/dist/core/schema/fields-file.js +2 -2
- package/dist/core/schema/runtime-field-values.js +1 -1
- package/dist/core/schema/runtime-schema.d.ts +2 -0
- package/dist/core/schema/runtime-schema.js +1 -1
- package/dist/core/shared/command-line.d.ts +54 -4
- package/dist/core/shared/command-line.js +1 -1
- package/dist/core/shared/errors.d.ts +9 -0
- package/dist/core/shared/secret-rules.js +5 -5
- package/dist/core/shared/url-credentials.d.ts +16 -3
- package/dist/core/shared/url-credentials.js +1 -1
- package/dist/core/store/item-store.d.ts +26 -4
- package/dist/core/store/item-store.js +1 -1
- package/dist/sdk/command-line.d.ts +1 -1
- package/dist/sdk/command-line.js +1 -1
- package/dist/sdk/context-intent-contracts.js +1 -1
- package/dist/sdk/extension/command-options.d.ts +26 -1
- package/dist/sdk/extension/command-options.js +1 -1
- package/dist/sdk/extension-command-context.js +2 -2
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
- package/dist/sdk/governance/tracked-runtime-cache.js +1 -1
- package/dist/sdk/index.d.ts +1 -1
- package/dist/sdk/lifecycle/claim.d.ts +21 -1
- package/dist/sdk/lifecycle/claim.js +1 -1
- package/dist/sdk/lifecycle/task-composition.js +1 -1
- package/dist/sdk/ownership-source.d.ts +15 -1
- package/dist/sdk/ownership-source.js +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/read-output-contracts.d.ts +11 -0
- package/dist/sdk/read-output-contracts.js +1 -1
- package/dist/sdk/runtime-primitives.d.ts +1 -1
- package/dist/sdk/schema/field-flag-spelling.d.ts +22 -0
- package/dist/sdk/schema/field-flag-spelling.js +2 -0
- package/dist/sdk/schema/field-option-collisions.js +1 -1
- package/docs/AGENT_GUIDE.md +2 -2
- package/docs/COMMANDS.md +1 -1
- package/docs/CONFIGURATION.md +1 -0
- package/docs/EXTENSIONS.md +1 -1
- package/docs/MUTATION_INTEGRITY.md +97 -8
- package/docs/READ_OUTPUT_CONTRACTS.md +2 -0
- package/docs/SDK.md +60 -4
- package/docs/SDK_AUDITED_MUTATIONS.md +11 -0
- package/docs/WORKSPACE_POSITION_AND_LIFECYCLE.md +17 -4
- package/marketplace.json +1 -1
- package/package.json +1 -1
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-claude/package.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/plugins/pm-codex/package.json +1 -1
- package/plugins/pm-codex/plugin.json +1 -1
- package/runtime-dependencies.json +1 -1
- package/dist/cli-bundle/chunks/chunk-5WZZ5XEN.js +0 -3
- package/dist/cli-bundle/chunks/chunk-6MYJLOSG.js +0 -2
- package/dist/cli-bundle/chunks/chunk-ENKXRSFZ.js +0 -31
- package/dist/cli-bundle/chunks/chunk-FJOEL75F.js +0 -2
- package/dist/cli-bundle/chunks/chunk-GDXCAC52.js +0 -2
- package/dist/cli-bundle/chunks/chunk-KE7HMBEW.js +0 -2
- package/dist/cli-bundle/chunks/chunk-KZHIBEJL.js +0 -33
- package/dist/cli-bundle/chunks/chunk-NGJ5ERBF.js +0 -115
- package/dist/cli-bundle/chunks/chunk-NQ54T7T2.js +0 -2
- package/dist/cli-bundle/chunks/chunk-OKEZF7HU.js +0 -2
- package/dist/cli-bundle/chunks/chunk-OKIKF4FD.js +0 -2
- package/dist/cli-bundle/chunks/chunk-OPJF254V.js +0 -9
- package/dist/cli-bundle/chunks/chunk-RWA5YZ5X.js +0 -2
- package/dist/cli-bundle/chunks/chunk-S32NGRQM.js +0 -2
- package/dist/cli-bundle/chunks/chunk-TZY5MVJF.js +0 -125
- package/dist/cli-bundle/chunks/chunk-ZPS4B6SI.js +0 -8
- package/dist/cli-bundle/chunks/item-revision-FMD4KWBB.js +0 -2
- package/dist/cli-bundle/chunks/item-transaction-SEHTH7N2.js +0 -2
- package/dist/cli-bundle/chunks/mutation-actor-SFGYIRPW.js +0 -2
- package/dist/cli-bundle/chunks/mutation-admission-57LBSKQI.js +0 -2
- package/dist/cli-bundle/chunks/register-mutation-6NUOPHZ3.js +0 -21
- package/dist/cli-bundle/chunks/register-operations-JGYVORNN.js +0 -2
- package/dist/cli-bundle/chunks/register-setup-C44SIXEH.js +0 -2
- package/dist/cli-bundle/chunks/stage-PQ7AB63N.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-6LKTEKHS.js +0 -6
- package/dist/cli-bundle/focused-chunks/chunk-6LPXMFLM.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-HMDQDRV2.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-I66IKYKP.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-IR2J3NOT.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-ITKDHSBR.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-LQYYPXUK.js +0 -26
- package/dist/cli-bundle/focused-chunks/chunk-NQTEE66P.js +0 -13
- package/dist/cli-bundle/focused-chunks/chunk-O7Z73ALG.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-OTMMOKPM.js +0 -91
- package/dist/cli-bundle/focused-chunks/chunk-OXOCZJC6.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-QLAHEDT6.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-TD544C74.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-UFTUNBMY.js +0 -27
- package/dist/cli-bundle/focused-chunks/chunk-XRS3VNC6.js +0 -44
- package/dist/cli-bundle/focused-chunks/chunk-XYPEZGTR.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-YSJKQLFR.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-Z2X7HH3C.js +0 -102
- package/dist/cli-bundle/focused-chunks/item-transaction-UKEQCTKB.js +0 -2
- package/dist/cli-bundle/focused-chunks/mutation-actor-AS465LRX.js +0 -2
- package/dist/cli-bundle/focused-chunks/mutation-admission-E5UHJZFE.js +0 -2
- package/dist/cli-bundle/focused-chunks/stage-36J7YLGI.js +0 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"name":"pm","owner":{"name":"unbrained","url":"https://github.com/unbraind/pm-cli"},"description":"Official marketplace for pm CLI — native git-based project management for Claude Code and AI coding agents.","version":"2026.11.
|
|
1
|
+
{"name":"pm","owner":{"name":"unbrained","url":"https://github.com/unbraind/pm-cli"},"description":"Official marketplace for pm CLI — native git-based project management for Claude Code and AI coding agents.","version":"2026.11.25","plugins":[{"name":"pm-claude","source":"./plugins/pm-claude","description":"Native pm CLI integration for Claude Code — 32 MCP tools, 14 workflow skills with slash invocations, 4 subagents, hybrid TUI task tracking, session context injection, and coordination subagents for git-based project management without leaving Claude Code.","version":"2026.11.25","author":{"name":"unbrained","url":"https://github.com/unbraind/pm-cli"},"homepage":"https://github.com/unbraind/pm-cli","repository":"https://github.com/unbraind/pm-cli","license":"MIT","keywords":["pm-cli","project-management","mcp","tasks","agents","workflows","git-native","task-tracker","ai"],"category":"productivity"}]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{describeReadCompletenessControls as me,isReadProjectionRecoveryFlag as pe,resolveReadCompletenessControls as fe,resolveReadOptionRetryArgs as he,resolveLinkedResourcePositionalRecovery as _e}from"../sdk/agent/command-recovery.js";import{PM_CLI_ERROR_DETAILS_LIMITS as ge,isPmTokenBudgetRecovery as ye,projectPmCliErrorContextDetailsSlot as ve}from"../sdk/errors.js";import{resolveRecoveryCommandName as G}from"../sdk/agent/command-recovery.js";import{estimatePmOutputTokens as
|
|
2
|
-
`).map(r=>` ${r}`)];const
|
|
3
|
-
`)}const
|
|
1
|
+
import{describeReadCompletenessControls as me,isReadProjectionRecoveryFlag as pe,resolveReadCompletenessControls as fe,resolveReadOptionRetryArgs as he,resolveLinkedResourcePositionalRecovery as _e}from"../sdk/agent/command-recovery.js";import{PM_CLI_ERROR_DETAILS_LIMITS as ge,isPmTokenBudgetRecovery as ye,projectPmCliErrorContextDetailsSlot as ve}from"../sdk/errors.js";import{resolveRecoveryCommandName as G}from"../sdk/agent/command-recovery.js";import{estimatePmOutputTokens as N,isGenericRefusalRequired as U,isGenericRefusalWhy as M,projectLeanRecoveryPayload as W,projectPmDiagnosticOutput as we,projectPmDiagnosticText as be,resolvePmDiagnosticOutputBudget as F,withoutGenericRefusalExamples as B}from"../sdk/cli-contracts/agent-output-contracts.js";import{renderPmCommand as f}from"./argv-utils.js";import{discoverNearbyPmRoot as ke}from"../sdk/tracker-root-discovery.js";import{stripGlobalBootstrapTokens as R}from"../sdk/cli-bootstrap.js";import{findPmNamespacedCommand as $e,resolvePmCommandAlias as V}from"../sdk/cli-contracts/command-aliases.js";import{redactGuidanceCredentials as T}from"./runtime/refusal-credential-redaction.js";function Zn(e){const{title:n,...t}=e;M(t.why)&&delete t.why,U(t.required)&&delete t.required;const i=B(t.examples);i.length>0?t.examples=i:delete t.examples;const r=W(t.recovery);return r===void 0?delete t.recovery:t.recovery=r,t}const Ce=new Set(["unknown_command","unknown_option","missing_required_option","missing_required_argument","invalid_argument_value","invalid_command_usage","command_failed"]);function Ae(e){return!e.why||e.recovery?.recovery_mode==="compact"?!1:!Ce.has(e.code)}function H(e){return`urn:pm-cli:error:${e}`}function u(e){return{...e,type:H(e.code)}}const k={packageName:"@unbrained/pm-guide-shell",installCommand:"pm install guide-shell"},K={packageName:"@unbrained/pm-calendar",installCommand:"pm install calendar"},J={packageName:"@unbrained/pm-search-advanced",installCommand:"pm install search-advanced"},S={packageName:"@unbrained/pm-governance-audit",installCommand:"pm install audit"},Re={guide:k,shell:k,completion:k,"completion-statuses":k,"completion-tags":k,"completion-types":k,templates:{packageName:"@unbrained/pm-templates",installCommand:"pm install templates"},calendar:K,cal:K,reindex:J,"search-advanced":J,"test-runs":{packageName:"@unbrained/pm-linked-test-adapters",installCommand:"pm install linked-test-adapters"},"comments-audit":S,"dedupe-audit":S,"dedupe-merge":S,normalize:S};function X(e){const n=e.trim().split(/\s+/)[0]?.toLowerCase();if(n)return Re[n]}function x(e,n){return n.length===0?[]:[e,...n.map(t=>` - ${t}`)]}function Se(e){if(!Array.isArray(e))return;const n=e.filter(t=>typeof t=="string").map(t=>t.trim()).filter(t=>t.length>0);return n.length>0?n:void 0}function xe(e){if(!Array.isArray(e))return;const n=e.map(t=>({source:typeof t?.source=="string"?t.source.trim():"",command:typeof t?.command=="string"?t.command.trim():"",reason:typeof t?.reason=="string"?t.reason.trim():""})).filter(t=>t.source.length>0&&t.command.length>0&&t.reason.length>0);return n.length>0?n:void 0}function O(e,n,t){typeof t=="string"&&t.trim().length>0&&(e[n]=t.trim())}function Y(e){return Array.isArray(e)&&e.length>0&&e.every(n=>typeof n=="string")?[...e]:void 0}function _(e,n,t){if(n==="normalized_args"||n==="suggested_retry_args"||n==="allowed_values"){const r=Y(t);r&&(e[n]=r);return}if(n==="parsed_positionals"){if(!Array.isArray(t))return;const r=t.map(o=>({role:typeof o?.role=="string"?o.role.trim():"",value:typeof o?.value=="string"?o.value.trim():""})).filter(o=>o.role.length>0&&o.value.length>0);r.length>0&&(e.parsed_positionals=r);return}const i=Se(t);i&&(e[n]=i)}function Ee(e,n){if(!ye(n))return;const{requested_tokens:t,feasible_tokens:i,minimum_feasible_tokens:r,minimum_status:o,basis:a,reason:s}=n;e.token_budget={requested_tokens:t,feasible_tokens:i,minimum_feasible_tokens:r,minimum_status:o,basis:a,reason:s}}const Z=["retry_after_ms","waited_ms","owner_handoffs"];function Ie(e,n){for(const t of Z)typeof n[t]=="number"&&e.push(` ${t}: ${n[t]}`)}function Te(e,n){for(const t of Z){const i=n[t];typeof i=="number"&&Number.isSafeInteger(i)&&i>=0&&(e[t]=i)}}function y(e){if(!e||typeof e!="object")return;const n={};Ee(n,e.token_budget),e.recovery_mode==="compact"&&(n.recovery_mode="compact"),O(n,"attempted_command",e.attempted_command),_(n,"normalized_args",e.normalized_args),_(n,"parsed_positionals",e.parsed_positionals),_(n,"provided_fields",e.provided_fields),_(n,"missing",e.missing),_(n,"missing_required_fields",e.missing_required_fields),_(n,"suggested_flags",e.suggested_flags),_(n,"allowed_values",e.allowed_values),_(n,"candidate_commands",e.candidate_commands),typeof e.candidate_commands_total=="number"&&Number.isSafeInteger(e.candidate_commands_total)&&e.candidate_commands_total>=0&&(n.candidate_commands_total=e.candidate_commands_total),e.candidate_commands_truncated===!0&&(n.candidate_commands_truncated=!0),(e.option_scope==="declared_on_path"||e.option_scope==="declared_elsewhere"||e.option_scope==="declared_nowhere")&&(n.option_scope=e.option_scope),O(n,"suggested_retry",e.suggested_retry),_(n,"suggested_retry_args",e.suggested_retry_args),Te(n,e);const t=xe(e.fallback_candidates);return t&&(n.fallback_candidates=t),O(n,"next_best_command",e.next_best_command),Object.keys(n).length>0?n:void 0}function q(e,n,t){t&&e.push(` ${n}: ${t}`)}function v(e,n,t,i){t&&t.length>0&&e.push(` ${n}: ${t.join(i)}`)}function Oe(e,n,t){const i=n?.slice(0,t).map(r=>/^[\p{L}\p{N}._:/@=-]+$/u.test(r)?r:JSON.stringify(r));v(e,"allowed_values",i,", "),n&&n.length>t&&e.push(` allowed_values_omitted: ${n.length-t} (complete domain via SDK error.context.recovery.allowed_values; JSON diagnostics may be budgeted)`)}function qe(e,n){const t=y(e);if(!t)return[];const i=["Recovery bundle:"];if(t.token_budget){const r=t.token_budget;i.push(` requested_token_budget: ${r.requested_tokens}`,` feasible_token_budget: ${r.feasible_tokens??"unavailable"}`,` minimum_token_budget: ${r.minimum_feasible_tokens??"not established"}`)}if(q(i,"suggested_retry",t.suggested_retry),q(i,"attempted_command",t.attempted_command),v(i,"normalized_args",t.attempted_command?void 0:t.normalized_args," "),t.parsed_positionals&&t.parsed_positionals.length>0){i.push(" parsed_positionals:");for(const r of t.parsed_positionals)i.push(` - ${r.role}: ${r.value}`)}if(v(i,"provided_fields",t.provided_fields,", "),v(i,"missing",t.missing,", "),v(i,"missing_required_fields",t.missing_required_fields,", "),v(i,"suggested_flags",t.suggested_flags,", "),Oe(i,t.allowed_values,n),v(i,"candidate_commands",t.candidate_commands,", "),typeof t.candidate_commands_total=="number"&&i.push(` candidate_commands_total: ${String(t.candidate_commands_total)}`),t.candidate_commands_truncated===!0&&i.push(" candidate_commands_truncated: true"),t.option_scope!==void 0&&i.push(` option_scope: ${t.option_scope}`),Ie(i,t),q(i,"next_best_command",t.next_best_command),t.fallback_candidates&&t.fallback_candidates.length>0){i.push(" fallback_candidates:");for(const r of t.fallback_candidates)i.push(` - ${r.source}: ${r.command} (${r.reason})`)}return i}const Q=120;function Le(e){if(e.claimedBy===void 0)return;const n=e.claimedAt?` since ${e.claimedAt}`:"",t=Array.from(e.claimedBy);return`Held by: ${t.length>Q?`${t.slice(0,Q).join("")}...`:e.claimedBy} (${e.claimSource??"unknown"}${n})${ze(e.claimActivity)}`}function De(e){return e.history_unreadable===!0?"history unreadable":e.unproven_activity!==void 0?`idleness unproven: ${e.unproven_activity}`:e.last_activity_at===null?"no valid activity time":"idle time not measurable"}function Pe(e){return e.state!==void 0?e.state:e.history_unreadable===!0||e.unproven_activity!==void 0||!Number.isFinite(e.idle_hours)?"unknown":e.stale_policy.stale?"stale":"active"}function ze(e){if(e===void 0)return"";const n=`${e.stale_policy.setting}=${e.stale_policy.threshold_hours}`,t=Pe(e);if(t==="unknown"){const i=Number.isFinite(e.idle_hours)?`, last recorded activity ${e.idle_hours}h ago`:"";return`; activity unknown under ${n} (${De(e)}${i})`}return`; idle ${e.idle_hours}h, ${t} under ${n}`}function je(e,n){const t=[`Error: ${e.title}`];e.code==="close_validation_missing_fields"&&e.recovery?.suggested_retry&&t.push(`Run: ${e.recovery.suggested_retry}`,"Template: replace every placeholder with real evidence before running."),(!n||!U(e.required))&&t.push("","What is required:",` ${e.required}`),e.nextSteps&&e.nextSteps.length>0&&(t.push(""),t.push(...x("Next steps:",e.nextSteps))),e.happened!==e.title&&t.push("","What happened:",` ${e.happened}`);const i=Le(e);return i!==void 0&&t.push("",i),t}function Ge(e,n){const t=[];e.why&&!(n&&M(e.why))&&t.push("","Why:",` ${e.why}`);const i=n?B(e.examples):e.examples??[];i.length>0&&t.push("",...x("Examples:",i));const r=e.verificationErrors??[];return r.length>0&&t.push("",...x("Verification errors:",r)),t.push(...Ne(e)),t}function Ne(e){if(e.details!==void 0&&Object.keys(e.details).length>0)return["","Details:",...JSON.stringify(e.details,null,2).split(`
|
|
2
|
+
`).map(r=>` ${r}`)];const n=e.detailsOmitted;if(n===void 0)return[];const t=n.path===void 0?` (over ${n.byte_limit} bytes)`:` at ${n.path}`;return["",`Details omitted: ${n.reason}${t}`]}function Ue(e,n={}){return ee(e,n,8)}function ee(e,n,t){const i=n.lean===!0,r=[...je(e,i),...Ge(e,i||e.code==="close_validation_missing_fields")],o=e.code==="close_validation_missing_fields"&&e.recovery?{...e.recovery,suggested_retry:void 0}:e.recovery,a=qe(i?W(o):o,t);return a.length>0&&(r.push(""),r.push(...a)),r.join(`
|
|
3
|
+
`)}const Me="Some guidance was omitted to fit the diagnostic token ceiling; rerun with --json for structured recovery within its own budget.",We=400,ne=320;function Fe(e){const n=y(e);if(!n)return;const t={};n.suggested_retry&&Buffer.byteLength(n.suggested_retry,"utf8")<=We&&(t.suggested_retry=n.suggested_retry);for(const i of["missing","missing_required_fields"]){const r=n[i];r&&r.length>0&&(t[i]=r.slice(0,3))}return n.allowed_values&&(t.allowed_values=n.allowed_values),n.next_best_command&&(t.next_best_command=n.next_best_command),Object.keys(t).length>0?t:void 0}function te(e,n){if(e.code!=="close_validation_missing_fields"||!e.recovery?.suggested_retry||n.recovery?.suggested_retry)return n.nextSteps;const t=n.recovery?.next_best_command?["Run recovery.next_best_command with real evidence, then repeat the original close."]:[...n.nextSteps,"Retrieve the complete retry from SDK error.context.recovery.suggested_retry; replace placeholders with real evidence before executing it."];return b(t,e.partialLegalDomainNotice)}function Be(e,n={}){const t=Ue(e,n),i=F("error").default_max_estimated_tokens_by_format.text,r=g=>N(Buffer.byteLength(g,"utf8"))<=i;if(r(t))return t;const o={...e,why:void 0},a=b(e.nextSteps?.slice(0,1)??[],e.partialLegalDomainNotice),s={...o,details:void 0,examples:e.examples?.slice(0,1),nextSteps:a,verificationErrors:e.verificationErrors?.slice(0,3)},d={...s,recovery:Fe(e.recovery)};d.nextSteps=te(e,d);const c=Array.from(e.happened),l={...d,examples:void 0,happened:c.length>ne?`${c.slice(0,ne).join("")}...`:e.happened},m={code:e.code,type:e.type,title:e.title,happened:l.happened,required:e.required,nextSteps:b([],e.partialLegalDomainNotice)};m.nextSteps=te(e,m);for(const[g,C]of[[o,8],[s,8],[d,3],[l,3],...e.partialLegalDomainNotice?[[m,3],[{...m,happened:e.title},3],[{...m,required:"Correct the producer metadata before relying on a complete legal domain."},3]]:[]]){const A=`${ee(g,n,C)}
|
|
4
4
|
|
|
5
|
-
${Ge}`;if(r(A))return A}return n}function We(e,t){t.tombstone!==void 0&&(e.tombstone=t.tombstone,e.item_id=t.itemId),t.lease!==void 0&&(e.lease=t.lease,e.current_owner=t.currentOwner??null,e.item_id=t.itemId),t.claimedBy!==void 0&&(e.claimed_by=t.claimedBy,e.claimed_at=t.claimedAt??null,e.claim_source=t.claimSource??"unknown",t.claimActivity!==void 0&&(e.claim_activity=t.claimActivity),e.item_id=t.itemId),t.currentRevision!==void 0&&(e.expected_revision=t.expectedRevision??null,e.current_revision=t.currentRevision,t.itemId!==void 0&&(e.item_id=t.itemId))}function ie(e,t){return t.sideEffects!==void 0&&(e.side_effects=t.sideEffects),t.previewStorage!==void 0&&(e.preview_storage=t.previewStorage),t.transactionOperation!==void 0&&(e.transaction_operation=t.transactionOperation),We(e,t),Ae(t)&&(e.why=t.why),t.examples&&t.examples.length>0&&(e.examples=t.examples),t.nextSteps&&t.nextSteps.length>0&&(e.next_steps=t.nextSteps),t.verificationErrors&&t.verificationErrors.length>0&&(e.verification_errors=t.verificationErrors),t.flag!==void 0&&(e.flag=t.flag),t.value!==void 0&&(e.value=t.value),t.unmatchedSelectors!==void 0&&(e.unmatched_selectors=t.unmatchedSelectors),t.availableDependencies!==void 0&&(e.available_dependencies=t.availableDependencies),t.recovery&&(e.recovery=t.recovery),e}function Fe(e,t){if(e.flag)return e.flag;const n=r=>{const o=r.split("=",1)[0];return R([o]).length>0&&!["--help","--no-changed-fields","--version"].includes(o)&&t.some(a=>a===o||a.startsWith(`${o}=`))};return[...`${e.title} ${e.happened}`.matchAll(/--[A-Za-z0-9][A-Za-z0-9_-]*/gu)].map(r=>r[0]).find(r=>n(r))}function Be(e,t,n){if(e.value!==void 0)return e.value;if(e.flag===void 0&&n){const i=t.find(o=>o===n||o.startsWith(`${n}=`));if(i?.startsWith(`${n}=`))return i.slice(n.length+1);const r=t.indexOf(n);return t[r+1]}}function Ve(e,t){if(e.policyViolations?.length)return{surface:`policy:${e.policyViolations.map(s=>s.policy_id).join(",")}`,policies:e.policyViolations,policy_violation_count:e.policyViolationCount,missing_fields:[...new Set(e.policyViolations.flatMap(s=>s.missing_fields))],exit_code:t};const n=R(e.recovery?.normalized_args??[]),i=Ce(n),r=i?[i.alias,...n.slice(i.canonical_argv.length)]:n,o=Fe(e,r),a=Be(e,r,o);return{surface:o??e.recovery?.missing?.[0]??G(r)??"command",...a!==void 0?{rejected_value:a}:{},...e.recovery?.allowed_values?.length?{legal_domain:e.recovery.allowed_values}:{},exit_code:t}}function re(e,t){const n=ie({type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required,exit_code:t,refusal:Ve(e,t),...e.changed===!1?{changed:!1}:{}},e);return e.details!==void 0&&(n.details=e.details),e.detailsOmitted!==void 0&&(n.details_omitted=e.detailsOmitted),n}function L(e,t){const n=T(e),i=n.recovery,o=!!i?.suggested_retry||!!i?.suggested_retry_args?.length||!!i?.allowed_values?.length||!!i?.candidate_commands?.length||!!n.nextSteps?.length?"recovery_bundle":"error";return we(He(re(n,t),o),{diagnosticClass:o})}function He(e,t){if(e.details===void 0)return e;const n=F(t).default_max_estimated_tokens_by_format.json;if(U(Buffer.byteLength(JSON.stringify(e,null,2),"utf8"))<=n)return e;const{details:i,...r}=e;return{...r,details_omitted:{reason:"diagnostic_budget",byte_limit:ge.max_bytes}}}function E(e){return ie({type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required,...e.changed===!1?{changed:!1}:{}},e)}function I(e){return e.replace(/\(outputHelp\)/g,"").trim()}function Ke(e){const t=e.toLowerCase();return t.includes("cannot find module")||t.includes("cannot find package")||t.includes("err_module_not_found")||t.includes("module_not_found")}function w(e){if(!Array.isArray(e))return;const t=e.map(n=>n.trim()).filter(n=>n.length>0);return t.length>0?t:void 0}function D(e){const t=new Set,n=[];for(const i of e)t.has(i)||(t.add(i),n.push(i));return n}function Je(e){return G(e?.normalized_args)}function Xe(e){const t=e.match(/\bmust be one of:?\s+([A-Za-z0-9_.|,\- ]+)/i);return t?t[1].split(/[|,]/).map(n=>n.trim()).filter(n=>/^[A-Za-z0-9_.-]+$/.test(n)):[]}function Ye(e,t){const n=e?.normalized_args,i=e?.provided_fields,r=t[0];if(!(!Array.isArray(n)||!Array.isArray(i)||!r))for(const o of i){const a=n.findIndex(s=>s===o);if(a>=0&&a<n.length-1&&!n[a+1]?.startsWith("-")){const s=[...n];return s[a+1]=r,f(s)}}}function oe(e){const t=e.split(/\r?\n/)[0].trim();if(t.length===0)return;const n=Array.from(t);return n.length<=120?t:`${n.slice(0,117).join("")}...`}function C(e,t){return typeof e=="string"&&e.trim().length>0?e.trim():t}function Ze(e,t){if(e.flag!==void 0)return e.flag;if(e.field===void 0)return;const n=e.field.startsWith("--")?e.field:`--${e.field.replaceAll(/([A-Z])([A-Z][a-z])/gu,"$1-$2").replaceAll(/([a-z0-9])([A-Z])/gu,"$1-$2").replaceAll("_","-").toLowerCase()}`;return t?.normalized_args?.some(i=>i===n||i.startsWith(`${n}=`))?n:void 0}function Qe(e,t,n,i){if(t==="close_validation_missing_fields")return"Close is missing required evidence";const r=e.code==="command_failed"||e.code==="invalid_argument_value"&&t!==e.code;return(n.code&&r?oe(i):void 0)??e.title}function et(e){const t=ve(e);return t===void 0?{}:"details"in t?{details:t.details}:{detailsOmitted:t.details_omitted}}const tt=400;function nt(e){const t=[];for(const n of e.slice(0,8)){const i=JSON.stringify(n);Buffer.byteLength([...t,i].join(", "),"utf8")<=tt&&t.push(i)}return t}function it(e){const t=e?.allowed_values;if(t===void 0||Array.isArray(t)&&t.every(a=>typeof a=="string"))return;const n=Array.isArray(t)?t.filter(a=>typeof a=="string"):[],i=nt(n),r=i.join(", ")||"none shown",o=n.length>i.length?` (${n.length-i.length} additional valid choices omitted)`:"";return`Incomplete legal domain from malformed producer metadata. Usable choices shown: ${r}${o}. Correct the producer metadata before relying on a complete domain.`}function rt(e,t,n){const i=y(t),r=i&&e?y({...e,...i}):i??e;if(!n)return r;const{allowed_values:o,...a}=r??{};return Object.keys(a).length>0?a:void 0}function h(e,t,n){if(!n)return e;const i=I(t),r=C(n.code,e.code),o=C(n.type,H(r)),a=w(n.examples)??e.examples,s=w(n.nextSteps)??e.nextSteps,d=it(n.recovery),c=d?[...s?.slice(0,1)??[],d,...s?.slice(1)??[]]:s,l=w(n.verification_errors)??e.verificationErrors,m=rt(e.recovery,n.recovery,d!==void 0);return{...e,code:r,changed:n.changed,sideEffects:n.side_effects,type:o,title:Qe(e,r,n,i),happened:i.length>0?i:e.happened,required:C(n.required,e.required),why:C(n.why,e.why),examples:a,nextSteps:c,urlCredentialsRejected:n.url_credentials_rejected??e.urlCredentialsRejected,partialLegalDomainNotice:d,verificationErrors:l,policyViolations:n.policy_violations,policyViolationCount:n.policy_violation_count,flag:Ze(n,m)??e.flag,value:n.value??e.value,unmatchedSelectors:n.unmatched_selectors,itemId:n.item_id,transactionOperation:n.transaction_operation,previewStorage:n.preview_storage,tombstone:n.tombstone,lease:n.lease,currentOwner:n.current_owner,claimedBy:n.claimed_by,claimedAt:n.claimed_at,claimSource:n.claim_source,claimActivity:n.claim_activity,expectedRevision:n.expected_revision,currentRevision:n.current_revision,availableDependencies:n.available_dependencies,recovery:m,...et(n)}}function ot(e,t,n){const i=t.match(/^Tracker is not initialized at (.+)\. (?:Run pm init first|Tracker root does not exist\. Run pm init first)\.$/);if(!i)return null;const r=i[1],o=ke(process.cwd(),r);return h(u(o?{code:"tracker_not_initialized",title:"Tracker exists at a custom path",happened:`pm did not find initialized metadata at ${r}, but found a tracker at ${o}.`,required:"Select the existing tracker root explicitly.",why:"Implicit discovery checks the default .agents/pm layout and ancestor root-layout trackers, while custom nested roots require an explicit path.",examples:[`pm --pm-path ${o} <command>`,`PM_PATH=${o} pm <command>`],nextSteps:[`Re-run with "--pm-path ${o}" or export PM_PATH=${o}.`]}:{code:"tracker_not_initialized",title:"Tracker is not initialized",happened:`pm data path does not contain initialized tracker metadata (${i[1]}).`,required:"Select an existing tracker with --pm-path/PM_PATH, or initialize the default .agents/pm storage.",why:"Most commands require settings in an explicitly selected root, an ancestor root-layout tracker, or the default .agents/pm directory.",examples:["pm init","pm init acme"],nextSteps:['Run "pm init", then rerun your original command.']}),e,n)}function at(e,t,n){const i=t.match(/^Item ([^ ]+) not found$/);if(!i)return null;const r=i[1],o=/^(undefined|null|<.*>|\[.*\]|{.*}|)$/.test(r),a=o?`The item ID "${r}" looks like a placeholder or unresolved variable. Ensure the ID argument is resolved before calling pm.`:`No item with id "${r}" exists in the active tracker scope.`;return h(u({code:"item_not_found",title:"Item ID not found",flag:"id",value:r,happened:a,required:"Use an existing item ID from current tracker data.",why:"Mutation and read commands operate only on known IDs.",examples:["pm list --status open --limit 20",'pm search "<keyword>" --limit 10'],nextSteps:o?["Check that the variable holding the item ID is defined before passing it to pm.",'Use "pm list --status open --limit 20" to find valid IDs.']:["Confirm the active --path/PM_PATH scope, then retry with a valid id."]}),e,n)}function st(e,t,n){return!t.includes("is assigned to")||!t.includes("Use --force to override")?null:h(u({code:"ownership_conflict",title:"Ownership conflict",happened:t,required:"Run as the assigned owner, claim the item when appropriate, or use --force only for an approved override.",why:"Ownership checks prevent accidental concurrent mutations on claimed items and protect against conflicting writes.",examples:["pm claim pm-a1b2","pm update pm-a1b2 --status in_progress --force"],nextSteps:["Use --force for approved systematic metadata updates performed by leads or maintainers.","Use --force when correcting known stale metadata after coordinating ownership changes.",'For non-terminal reassignment, prefer "pm claim <ID>" before running other mutations.']}),e,n)}function dt(e,t,n){if(!t.includes("is locked"))return null;const i=Y(n?.recovery?.normalized_args),r=i?f(i):void 0,o=h(u({code:"lock_conflict",title:"Lock conflict",happened:t,required:"Wait for lock release, then retry the same operation. Set PM_LOCK_WAIT_MS to a larger bounded millisecond budget for expected contention.",why:"Locking protects item files from concurrent write races.",examples:r?[r]:["pm gc --scope locks --dry-run"]}),e,n);return i&&(o.recovery={...o.recovery,suggested_retry:r,suggested_retry_args:[...i]}),o}function ct(e,t,n){const i=t.match(/^Missing required option /),r=t.match(/^Missing required options /);if(!i&&!r)return null;const o=!!r,a=o?null:t.replace(/^Missing required option\s+/,"").trim(),s=a??"",d=a?`Pass ${a} with a valid value before running the command.`:"Provide the required option for this command invocation.";return h(u({code:"missing_required_option",title:o?"Missing required options":`Missing required option ${s}`,happened:t,required:o?"Provide every required option for this command invocation.":d,why:"Required options define command intent and enforce deterministic write contracts.",examples:['pm create --title "Task title" --description "Task details" --type Task --create-mode progressive','pm create --title "Task title" --description "Task details" --type Task --status open --priority 1 --message "Create task" --dep "id=pm-epic01,kind=parent,created_at=now" --comment "created_at=now,text=Why this task exists." --note "created_at=now,text=Initial implementation note." --learning "created_at=now,text=Durable lesson placeholder." --file "path=src/example.ts,scope=project" --test "command=node scripts/run-tests.mjs test,scope=project,timeout_seconds=240" --doc "path=README.md,scope=project"'],nextSteps:['Run "pm <command> --help" to view required and recommended flags.',"For staged triage without placeholder linkage values, use --create-mode progressive."]}),e,n)}function lt(e,t,n){return t.startsWith("No update flags provided")?h(u({code:"no_update_fields",title:"No update fields supplied",happened:"The update command was called without any field-changing flags.",required:"Provide at least one field-changing flag such as --status, --priority, --title, --tags, --description, or --body. Use --message only to label a real mutation.",why:"pm update mutates existing item fields; no-op invocations are rejected to avoid ambiguous history.",examples:['pm update pm-a1b2 --status in_progress --message "Start implementation"','pm update pm-a1b2 --description "Clarified implementation scope" --message "Clarify task intent"','pm append pm-a1b2 --body "Detailed progress notes" --message "Append progress notes"'],nextSteps:["Choose the item field you intend to change, then pair that change with --message for history context.","Use pm comments, pm notes, pm learnings, or pm append when you only need to add narrative context."]}),e,n):null}function ut(e,t){if(e.startsWith("Invalid "))return!0;if(!e.includes(" must be ")&&!e.includes(" requires "))return!1;const n=C(t?.code,void 0);return n===void 0||n==="invalid_argument_value"||t?.allowed!==void 0}function mt(e,t,n){if(!ut(t,n))return null;const i=y(n?.recovery),r=Je(i),o=r?`pm ${r} --help`:"pm <command> --help",a=n?.recovery?.allowed_values!==void 0?[]:n?.allowed??Xe(t),s=y({...i,allowed_values:i?.allowed_values??a}),d=Ye(i,a),c=d?[d,o]:[o,"pm contracts --command <command> --flags-only --json"],l=a.length>0?[`Allowed values: ${a.join("|")}`,`Run "${o}" to confirm command-specific constraints.`]:["Check allowed values in command help, then rerun with corrected input."];return h(u({code:"invalid_argument_value",title:"Invalid argument value",happened:t,required:"Use values that match documented command constraints.",why:"Validation protects data consistency and deterministic behavior across commands.",examples:c,nextSteps:l,recovery:s}),e,n)}function P(e,t){const n=I(e),i=ot(e,n,t)??at(e,n,t)??st(e,n,t)??dt(e,n,t)??ct(e,n,t)??lt(e,n,t)??mt(e,n,t);return i||h(u({code:"command_failed",title:"Command failed",happened:n,required:"Adjust command input or tracker state and retry.",why:"pm enforces explicit, deterministic contracts for data and command semantics.",examples:["pm --help","pm <command> --help"]}),e,t)}function ae(e,t,n){return e==="create"&&t.startsWith("--type")?[`pm create --title "Example title" --description "Example description" --type ${n.split("|")[0]||"Task"} --status open --priority 1 --message "Create item" --create-mode progressive`]:e==="update"?['pm update pm-a1b2 --status in_progress --message "Start implementation"']:[`pm ${e??"<command>"} --help`]}function pt(e){const t=e.trim();return t.match(/--[A-Za-z0-9][A-Za-z0-9_-]*/)?.[0]??t}function ft(e){if(!(!Array.isArray(e)||e.length===0))return f(e)}function z(e){if(!Array.isArray(e))return;const t=e.map(n=>n.trim()).filter(n=>n.length>0);return t.length>0?t:void 0}function p(e,t={}){const n=z(e?.providedOptionFlags),i=Array.isArray(e?.normalizedInvocationArgs)&&e?.normalizedInvocationArgs.length>0?e.normalizedInvocationArgs:void 0,r=typeof e?.attemptedCommand=="string"?e.attemptedCommand:ft(i),o=typeof e?.suggestedRetryCommand=="string"?e.suggestedRetryCommand:void 0;return y({attempted_command:r,normalized_args:i,provided_fields:n,suggested_retry:o,suggested_retry_args:e?.suggestedRetryArgs,...t})}function b(e,t){return!t||e.includes(t)?e:[...e,t]}const ht=new Set(["--add","--add-json","--remove"]),_t=new Set(["command","cmd","path"]);function gt(e){if(Array.isArray(e))for(const t of e){if(!t.startsWith("--"))continue;const n=t.indexOf("="),i=n>=0?t.slice(0,n):t;if(ht.has(i))return i}}function yt(e){if(!Array.isArray(e))return;const t=e.indexOf("test");if(t<0)return;const n=e[t+1];if(!(typeof n!="string"||n.startsWith("-")))for(let i=t+2;i<e.length;i+=1){const r=e[i];if(r!=="--add"&&r!=="--remove")continue;const o=e[i+1];if(typeof o!="string"||!_t.has(o))return;const a=[];for(let c=i+2;c<e.length;c+=1){const l=e[c];if(l.startsWith("--")&&l.length>2)break;a.push(l)}if(a.length<2)return;const s=`${o}=${a.join(" ")}`,d=[...e.slice(0,i+1),s,...e.slice(i+2+a.length)];return f(d)}}function vt(e,t,n,i){const r=e.match(/required option '([^']+)' not specified/);if(!r)return null;const o=pt(r[1]),a=o.startsWith("--type"),s=i?.suggestedRetryCommand,d=z(i?.providedOptionFlags),c=[o],l=ae(t,o,n),m=s?b(l,s):l,g=a?[`Allowed type values: ${n}`,`Run "pm ${t??"create"} --help --type <value>" for type-aware policy details.`]:[`Run "pm ${t??"<command>"} --help" for required option guidance.`],$=s?b(g,`Replay with preserved arguments: ${s}`):g,A=d&&d.length>0?b($,`Already provided options: ${d.join(", ")}`):$;return u({code:"missing_required_option",title:`Missing required option ${o}`,happened:`Commander rejected the command because ${o} was not provided.`,required:`Pass ${o} with a valid value before running the command.`,why:a?"--type selects item contract and policy routing, including required/disabled option rules.":"Required flags define mandatory command intent and prevent ambiguous execution.",examples:m,nextSteps:A,recovery:p(i,{missing:c})})}function wt(e,t,n){const i=e.match(/missing required argument '([^']+)'/);if(!i)return null;const r=i[1];return u({code:"missing_required_argument",title:`Missing required argument ${r}`,happened:`Command invocation omitted positional argument ${r}.`,required:`Provide ${r} in the expected command position.`,why:"Positional arguments identify the target entity or action context for the command.",examples:[`pm ${t??"<command>"} --help`],recovery:p(n,{missing:[r]})})}function bt(e,t,n){return u({code:"unsupported_update_option",title:`Unsupported option ${e} for update`,happened:`pm update does not accept ${e} for linked artifact mutations.`,required:"Use dedicated linked-artifact commands instead of pm update for files/docs changes.",why:"pm update manages scalar item metadata, while linked files/docs are managed by pm files and pm docs.",examples:['pm files pm-a1b2 --add "path=src/cli/main.ts,scope=project,note=implementation surface"','pm docs pm-a1b2 --add "path=README.md,scope=project,note=user-facing contract"'],nextSteps:['Run "pm files --help" and "pm docs --help" for add/remove payload formats.'],recovery:p(t,{suggested_flags:n})})}const kt={declared_elsewhere:"Use an option declared on this path, or move the declared option to one of its accepting command paths.",declared_on_path:"Use the option with the value and syntax declared by this command path.",declared_nowhere:"Use a declared option on this command path; this spelling exists nowhere in the command lexicon."};function Ct(e){const t=w(e.unknownOptionOtherCommands)??[];return{otherCommands:t,optionScope:e.unknownOptionScope??(t.length>0?"declared_elsewhere":"declared_nowhere"),candidateTotal:e.unknownOptionOtherCommandsTotal??t.length}}function $t(e,t,n,i,r){const o=i.otherCommands.slice(0,3),a=i.candidateTotal-o.length,s=a>0?` and ${String(a)} more command path(s)`:"";return["Run command help to confirm the exact option contracts for this command path.",n.length?`Nearest supported options: ${n.join(", ")}`:void 0,r?void 0:At(e,t),o.length?`${e} is accepted by ${o.join(", ")}${s}. Inspect those command contracts only if you intended a different operation.`:void 0,de(e)?`"${e}" contains spaces, so it is a value that starts with --, not an option. Pass it after a -- separator at the end of the command, or through the command's named value flag.`:i.optionScope==="declared_nowhere"?`${e} is not declared on any command path. Use a nearest supported option on ${t??"the attempted command"}, or inspect that command's help.`:void 0,r?`Replay with suggested correction: ${r}`:void 0].filter(d=>typeof d=="string")}const se=["--brief","--compact","--standard","--deep","--full","--summary","--depth"];function At(e,t){if(t===void 0||!se.includes(e.split("=",1)[0]))return;const n=fe(t);return n===void 0?void 0:`Completeness controls accepted by pm ${n.command}: ${me(n)}.`}function Rt(e,t,n){const i=he(n??"",e.normalizedInvocationArgs??[],t);return i?{retryCommand:f(i),suggestedRetryArgs:i}:[...se,"--toon",...n==="activity"?["--since"]:[]].includes(t.split("=",1)[0])?{}:void 0}function de(e){return/\s/u.test(e)}function St(e,t){const n=e?.indexOf(t)??-1;if(e===void 0||n<0||e.includes("--")||e.lastIndexOf(t)!==n)return{};if(e.slice(n+1).some(r=>!r.startsWith("-")))return{};const i=[...R(e.filter((r,o)=>o!==n)),"--",t];return{retryCommand:f(i),suggestedRetryArgs:i}}function xt(e,t,n){if(de(t))return St(e.normalizedInvocationArgs,t);if(["--dry-run","--check","--check-only","--plan","--preview"].includes(t.split("=",1)[0]))return{};const i=Rt(e,t,n);if(i)return i;if(e.suggestedRetryCommand!==void 0)return{retryCommand:e.suggestedRetryCommand};if(pe(t))return{};const r=e.normalizedInvocationArgs;if(r===void 0)return{};if(r.filter(s=>s===t||s.startsWith(`${t}=`)).length!==1)return{};const o=r.findIndex(s=>s===t||s.startsWith(`${t}=`));if(o<0||r.includes("--")||!r[o]?.includes("=")&&o!==r.length-1&&r[o+1]?.startsWith("-")!==!0)return{};const a=R(r.filter((s,d)=>d!==o));return{retryCommand:f(a),suggestedRetryArgs:a}}function Et(e,t,n){const i=e.match(/unknown option '([^']+)'/);if(!i)return null;const r=n??{},o=i[1],a=z(r.unknownOptionSuggestions)??[],{retryCommand:s,suggestedRetryArgs:d}=xt(r,o,t);if(t==="update"&&(o==="--file"||o==="--doc"))return bt(o,n,a);const c=Ct(r),l=$t(o,t,a,c,s);["--dry-run","--check","--check-only","--plan","--preview"].includes(o.split("=",1)[0])&&l.push("The requested preview is unavailable on this path. Inspect the item with a read-only command or use a command that declares this option; do not replay this mutation without preview intent.");const m=[s,t?`pm ${V(t)?.canonical??t} --help`:"pm --help --all"].filter(g=>typeof g=="string");return u({code:"unknown_option",title:`Unknown option ${o}`,happened:`Commander does not recognize option ${o} for this command path.`,required:kt[c.optionScope],why:"Option contracts are command-specific and intentionally validated.",flag:o,value:o,examples:m,nextSteps:l,recovery:p(n,{suggested_flags:a.length>0?a:void 0,suggested_retry:s,suggested_retry_args:d,candidate_commands:c.otherCommands,candidate_commands_total:c.candidateTotal||void 0,candidate_commands_truncated:r.unknownOptionOtherCommandsTruncated,option_scope:c.optionScope})})}function It(e,t,n,i,r){const o=`"${e}" is provided by the ${t.packageName} package. Install it with: ${t.installCommand}`,a=i.filter(s=>!s.endsWith(`: ${t.installCommand}`));return u({code:"unknown_command",title:`Unknown command ${e}`,happened:`pm does not expose command path "${e}" in current runtime configuration. It is shipped by the optional ${t.packageName} package.`,required:`Install the ${t.packageName} package, or use a valid command name or subcommand path.`,why:"Command registry includes core commands plus active extension command handlers; package-provided commands appear only after the package is installed.",examples:D([t.installCommand,...n]),nextSteps:D([o,...a]),recovery:p(r)})}function Tt(e,t){const n=e.match(/unknown command '([^']+)'/);if(!n)return null;const i=n[1],r=w(t?.unknownCommandExamples),o=w(t?.unknownCommandNextSteps),a=X(i),s=r??["pm --help"],d=o??["Verify spelling and active extensions, then rerun."],c=new Set(t?.failedExtensions?.map(m=>m.name.trim().toLowerCase())),l=a?.packageName.replace(/^@unbrained\/pm-/,"").toLowerCase();return a&&(!l||!c.has(l))?It(i,a,s,d,t):u({code:"unknown_command",title:`Unknown command ${i}`,happened:`pm does not expose command path "${i}" in current runtime configuration.`,required:"Use a valid command name or subcommand path.",why:"Command registry includes core commands plus active extension command handlers.",examples:s,nextSteps:d,recovery:p(t)})}function Ot(e){const t=e?.unknownSubcommandPath?.trim(),n=e?.unknownSubcommandToken?.trim(),i=w(e?.unknownSubcommandAllowedValues);if(!t||!n||!i)return null;const r=e?.suggestedRetryCommand;return u({code:"unknown_subcommand",title:`Unknown ${t} subcommand ${n}`,value:n,happened:`The positional token sequence "${n}" is not a declared ${t} subcommand.`,required:`Use one of: ${i.join(", ")}.`,why:"Subcommands are single positional tokens; multi-word action names use hyphens.",examples:[...r?[r]:[],`pm ${V(t)?.canonical??t} --help`],nextSteps:r?[`Retry with the declared hyphenated action: ${r}`]:["Choose one value from recovery.allowed_values."],recovery:p(e,{allowed_values:i,suggested_retry:r})})}function qt(e,t,n){if(!/too many arguments/i.test(e)||t!=="test")return null;const i=n?.normalizedInvocationArgs,r=gt(i);if(!r)return null;const o=yt(i);return u({code:"linked_test_value_not_quoted",title:`Linked-test ${r} value must be one argument`,happened:`Commander saw extra positional tokens after the item id \u2014 usually a ${r} value containing spaces (for example a command with " -- ") that the shell split into multiple tokens.`,required:`Quote the whole ${r} value as a single argument. Accepted forms: --add "command=npm test -- parser", --add command "npm test -- parser" (two-token form with the value quoted), or --add-json for complex commands.`,why:"The shell splits unquoted values before pm can see them, so pm cannot reassemble the intended command unambiguously.",examples:[...o?[o]:[],'pm test pm-a1b2 --add "command=npm test -- parser"','pm test pm-a1b2 --add command "npm test -- parser"',`pm test pm-a1b2 --add-json '{"command":"npm test -- parser"}'`],nextSteps:[...o?[`Replay with the value re-joined into one argument: ${o}`]:[],"Prefer --add-json for commands containing commas, equals signs, or quotes.",'Run "pm test --help" for linked-test entry contracts.'],recovery:p(n,o?{suggested_retry:o}:{})})}const Lt=new Set(["comments","docs","files","learnings","notes","test"]);function Dt(e,t,n){if(!/too many arguments/i.test(e))return null;const i=_e(t,n?.normalizedInvocationArgs??[]);if(!i)return null;const r=i.retryArgs?f(i.retryArgs):void 0,o=f(i.templateArgs??["test",i.itemId,"--add",`command=<actual command>,${i.value}`]);return u({code:"linked_resource_positional_value",title:"Linked-resource values require an explicit --add option",happened:`The value after the item id is not a positional argument of ${t}.`,required:r?`Retry the explicit collection mutation: ${r}`:`Supply the actual command and its metadata together, for example ${o}.`,examples:[r??o],recovery:p(n,{suggested_retry:r,suggested_retry_args:i.retryArgs})})}function Pt(e,t,n){if(!/too many arguments/i.test(e)||!Lt.has(t??""))return null;const i=n?.normalizedInvocationArgs??[],r=i.findIndex(c=>c===t),o=i[r+1],a=i[r+2],s=n?.verifiedCollectionItemId?.trim();if(o?.toLowerCase()!=="add"||!a||a.startsWith("-")||!s||s.toLowerCase()!==a.toLowerCase())return null;const d=`pm ${t} ${s} --add <value>`;return u({code:"collection_transposed_subcommand",title:`Transposed ${t} add syntax`,happened:`The positional token "add" occupied the item-id role and "${s}" occupied the next positional role. pm ${t} does not use an add subcommand.`,required:`Place the item id immediately after ${t}, then use --add for the value.`,why:"Collection mutations use object-first grammar: pm <collection> <item-id> --add <value>.",examples:[d,`pm ${t} --help`],recovery:p(n,{parsed_positionals:[{role:"transposed_subcommand",value:o},{role:"item_id",value:s}],suggested_retry:d})})}const zt=new Set(["--activity-limit","--assignee","--assignee-filter","--date","--depth","--fields","--format","--from","--limit","--parent","--path","--pm-path","--priority","--release","--section","--sprint","--stale-threshold","--tag","--to","--type"]),ce=new Set(["context","ctx"]);function jt(e,t,n){if(!/too many arguments/i.test(e)||!ce.has(t??""))return null;const i=n?.normalizedInvocationArgs??[],r=i.findIndex(c=>ce.has(c)),o=r===-1?1:r+1,a=e.match(/got \d+:\s*(\S+)/i);let s=a?a[1].replace(/\.$/,""):void 0;if(s===void 0){let c=!1;for(const l of i.slice(o)){if(c){c=!1;continue}const m=l.split("=")[0];if(zt.has(m)){c=!l.includes("=");continue}if(!l.startsWith("-")){s=l;break}}}if(!s)return null;const d=`pm get ${s}`;return u({code:"context_takes_no_item_argument",title:"pm context takes no item argument",happened:`pm context renders a workspace-level snapshot and received the positional argument "${s}".`,required:`Use ${d} for one item's full details, or pm context --parent ${s} to scope the snapshot to that item's subtree.`,why:"Item-level detail (pm get) and workspace-level context (pm context) are separate projections.",examples:[d,`pm context --parent ${s}`],recovery:p(n,{suggested_retry:d})})}function j(e,t,n,i){const r=I(e),o=vt(r,t,n,i)??wt(r,t,i)??Et(r,t,i)??Tt(r,i)??Ot(i)??Pt(r,t,i)??qt(r,t,i)??Dt(r,t,i)??jt(r,t,i);return o||u({code:"invalid_command_usage",title:"Invalid command usage",happened:r,required:"Use the command with valid arguments and options.",why:"Commander validates CLI contracts before execution.",examples:["pm --help",`pm ${t??"<command>"} --help`],recovery:p(i)})}function Jt(e,t,n={}){const i=T(P(e,t));return(t?.code==="tracker_root_missing"||t?.code==="tracker_not_initialized")&&i.title==="Tracker is not initialized"&&i.recovery?.suggested_retry_args?[`Error: ${i.title}`,`Run: ${f(i.recovery.suggested_retry_args)}`,"Use --json for full recovery details."].join(`
|
|
6
|
-
`):le(i,
|
|
5
|
+
${Me}`;if(r(A))return A}return t}function Ve(e,n){n.tombstone!==void 0&&(e.tombstone=n.tombstone,e.item_id=n.itemId),n.lease!==void 0&&(e.lease=n.lease,e.current_owner=n.currentOwner??null,e.item_id=n.itemId),n.claimedBy!==void 0&&(e.claimed_by=n.claimedBy,e.claimed_at=n.claimedAt??null,e.claim_source=n.claimSource??"unknown",n.claimActivity!==void 0&&(e.claim_activity=n.claimActivity),e.item_id=n.itemId),n.currentRevision!==void 0&&(e.expected_revision=n.expectedRevision??null,e.current_revision=n.currentRevision,n.itemId!==void 0&&(e.item_id=n.itemId))}function ie(e,n){return n.sideEffects!==void 0&&(e.side_effects=n.sideEffects),n.previewStorage!==void 0&&(e.preview_storage=n.previewStorage),n.transactionOperation!==void 0&&(e.transaction_operation=n.transactionOperation),Ve(e,n),Ae(n)&&(e.why=n.why),n.examples&&n.examples.length>0&&(e.examples=n.examples),n.nextSteps&&n.nextSteps.length>0&&(e.next_steps=n.nextSteps),n.verificationErrors&&n.verificationErrors.length>0&&(e.verification_errors=n.verificationErrors),n.flag!==void 0&&(e.flag=n.flag),n.value!==void 0&&(e.value=n.value),n.unmatchedSelectors!==void 0&&(e.unmatched_selectors=n.unmatchedSelectors),n.availableDependencies!==void 0&&(e.available_dependencies=n.availableDependencies),n.recovery&&(e.recovery=n.recovery),e}function He(e,n){if(e.flag)return e.flag;const t=r=>{const o=r.split("=",1)[0];return R([o]).length>0&&!["--help","--no-changed-fields","--version"].includes(o)&&n.some(a=>a===o||a.startsWith(`${o}=`))};return[...`${e.title} ${e.happened}`.matchAll(/--[A-Za-z0-9][A-Za-z0-9_-]*/gu)].map(r=>r[0]).find(r=>t(r))}function Ke(e,n,t){if(e.value!==void 0)return e.value;if(e.flag===void 0&&t){const i=n.find(o=>o===t||o.startsWith(`${t}=`));if(i?.startsWith(`${t}=`))return i.slice(t.length+1);const r=n.indexOf(t);return n[r+1]}}function Je(e,n){if(e.policyViolations?.length)return{surface:`policy:${e.policyViolations.map(s=>s.policy_id).join(",")}`,policies:e.policyViolations,policy_violation_count:e.policyViolationCount,missing_fields:[...new Set(e.policyViolations.flatMap(s=>s.missing_fields))],exit_code:n};const t=R(e.recovery?.normalized_args??[]),i=$e(t),r=i?[i.alias,...t.slice(i.canonical_argv.length)]:t,o=He(e,r),a=Ke(e,r,o);return{surface:o??e.recovery?.missing?.[0]??G(r)??"command",...a!==void 0?{rejected_value:a}:{},...e.recovery?.allowed_values?.length?{legal_domain:e.recovery.allowed_values}:{},exit_code:n}}function re(e,n){const t=ie({type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required,exit_code:n,refusal:Je(e,n),...e.changed===!1?{changed:!1}:{}},e);return e.details!==void 0&&(t.details=e.details),e.detailsOmitted!==void 0&&(t.details_omitted=e.detailsOmitted),t}function L(e,n){const t=T(e),i=t.recovery,o=!!i?.suggested_retry||!!i?.suggested_retry_args?.length||!!i?.allowed_values?.length||!!i?.candidate_commands?.length||!!t.nextSteps?.length?"recovery_bundle":"error";return we(Xe(re(t,n),o),{diagnosticClass:o})}function Xe(e,n){if(e.details===void 0)return e;const t=F(n).default_max_estimated_tokens_by_format.json;if(N(Buffer.byteLength(JSON.stringify(e,null,2),"utf8"))<=t)return e;const{details:i,...r}=e;return{...r,details_omitted:{reason:"diagnostic_budget",byte_limit:ge.max_bytes}}}function E(e){return ie({type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required,...e.changed===!1?{changed:!1}:{}},e)}function I(e){return e.replace(/\(outputHelp\)/g,"").trim()}function Ye(e){const n=e.toLowerCase();return n.includes("cannot find module")||n.includes("cannot find package")||n.includes("err_module_not_found")||n.includes("module_not_found")}function w(e){if(!Array.isArray(e))return;const n=e.map(t=>t.trim()).filter(t=>t.length>0);return n.length>0?n:void 0}function D(e){const n=new Set,t=[];for(const i of e)n.has(i)||(n.add(i),t.push(i));return t}function Ze(e){return G(e?.normalized_args)}function Qe(e){const n=e.match(/\bmust be one of:?\s+([A-Za-z0-9_.|,\- ]+)/i);return n?n[1].split(/[|,]/).map(t=>t.trim()).filter(t=>/^[A-Za-z0-9_.-]+$/.test(t)):[]}function en(e,n){const t=e?.normalized_args,i=e?.provided_fields,r=n[0];if(!(!Array.isArray(t)||!Array.isArray(i)||!r))for(const o of i){const a=t.findIndex(s=>s===o);if(a>=0&&a<t.length-1&&!t[a+1]?.startsWith("-")){const s=[...t];return s[a+1]=r,f(s)}}}function oe(e){const n=e.split(/\r?\n/)[0].trim();if(n.length===0)return;const t=Array.from(n);return t.length<=120?n:`${t.slice(0,117).join("")}...`}function $(e,n){return typeof e=="string"&&e.trim().length>0?e.trim():n}function nn(e,n){if(e.flag!==void 0)return e.flag;if(e.field===void 0)return;const t=e.field.startsWith("--")?e.field:`--${e.field.replaceAll(/([A-Z])([A-Z][a-z])/gu,"$1-$2").replaceAll(/([a-z0-9])([A-Z])/gu,"$1-$2").replaceAll("_","-").toLowerCase()}`;return n?.normalized_args?.some(i=>i===t||i.startsWith(`${t}=`))?t:void 0}function tn(e,n,t,i){if(n==="close_validation_missing_fields")return"Close is missing required evidence";const r=e.code==="command_failed"||e.code==="invalid_argument_value"&&n!==e.code;return(t.code&&r?oe(i):void 0)??e.title}function rn(e){const n=ve(e);return n===void 0?{}:"details"in n?{details:n.details}:{detailsOmitted:n.details_omitted}}const on=400;function an(e){const n=[];for(const t of e.slice(0,8)){const i=JSON.stringify(t);Buffer.byteLength([...n,i].join(", "),"utf8")<=on&&n.push(i)}return n}function sn(e){const n=e?.allowed_values;if(n===void 0||Array.isArray(n)&&n.every(a=>typeof a=="string"))return;const t=Array.isArray(n)?n.filter(a=>typeof a=="string"):[],i=an(t),r=i.join(", ")||"none shown",o=t.length>i.length?` (${t.length-i.length} additional valid choices omitted)`:"";return`Incomplete legal domain from malformed producer metadata. Usable choices shown: ${r}${o}. Correct the producer metadata before relying on a complete domain.`}function dn(e,n,t){const i=y(n),r=i&&e?y({...e,...i}):i??e;if(!t)return r;const{allowed_values:o,...a}=r??{};return Object.keys(a).length>0?a:void 0}function h(e,n,t){if(!t)return e;const i=I(n),r=$(t.code,e.code),o=$(t.type,H(r)),a=w(t.examples)??e.examples,s=w(t.nextSteps)??e.nextSteps,d=sn(t.recovery),c=d?[...s?.slice(0,1)??[],d,...s?.slice(1)??[]]:s,l=w(t.verification_errors)??e.verificationErrors,m=dn(e.recovery,t.recovery,d!==void 0);return{...e,code:r,changed:t.changed,sideEffects:t.side_effects,type:o,title:tn(e,r,t,i),happened:i.length>0?i:e.happened,required:$(t.required,e.required),why:$(t.why,e.why),examples:a,nextSteps:c,urlCredentialsRejected:t.url_credentials_rejected??e.urlCredentialsRejected,partialLegalDomainNotice:d,verificationErrors:l,policyViolations:t.policy_violations,policyViolationCount:t.policy_violation_count,flag:nn(t,m)??e.flag,value:t.value??e.value,unmatchedSelectors:t.unmatched_selectors,itemId:t.item_id,transactionOperation:t.transaction_operation,previewStorage:t.preview_storage,tombstone:t.tombstone,lease:t.lease,currentOwner:t.current_owner,claimedBy:t.claimed_by,claimedAt:t.claimed_at,claimSource:t.claim_source,claimActivity:t.claim_activity,expectedRevision:t.expected_revision,currentRevision:t.current_revision,availableDependencies:t.available_dependencies,recovery:m,...rn(t)}}function cn(e,n,t){const i=n.match(/^Tracker is not initialized at (.+)\. (?:Run pm init first|Tracker root does not exist\. Run pm init first)\.$/);if(!i)return null;const r=i[1],o=ke(process.cwd(),r);return h(u(o?{code:"tracker_not_initialized",title:"Tracker exists at a custom path",happened:`pm did not find initialized metadata at ${r}, but found a tracker at ${o}.`,required:"Select the existing tracker root explicitly.",why:"Implicit discovery checks the default .agents/pm layout and ancestor root-layout trackers, while custom nested roots require an explicit path.",examples:[`pm --pm-path ${o} <command>`,`PM_PATH=${o} pm <command>`],nextSteps:[`Re-run with "--pm-path ${o}" or export PM_PATH=${o}.`]}:{code:"tracker_not_initialized",title:"Tracker is not initialized",happened:`pm data path does not contain initialized tracker metadata (${i[1]}).`,required:"Select an existing tracker with --pm-path/PM_PATH, or initialize the default .agents/pm storage.",why:"Most commands require settings in an explicitly selected root, an ancestor root-layout tracker, or the default .agents/pm directory.",examples:["pm init","pm init acme"],nextSteps:['Run "pm init", then rerun your original command.']}),e,t)}function ln(e,n,t){const i=n.match(/^Item ([^ ]+) not found$/);if(!i)return null;const r=i[1],o=/^(undefined|null|<.*>|\[.*\]|{.*}|)$/.test(r),a=o?`The item ID "${r}" looks like a placeholder or unresolved variable. Ensure the ID argument is resolved before calling pm.`:`No item with id "${r}" exists in the active tracker scope.`;return h(u({code:"item_not_found",title:"Item ID not found",flag:"id",value:r,happened:a,required:"Use an existing item ID from current tracker data.",why:"Mutation and read commands operate only on known IDs.",examples:["pm list --status open --limit 20",'pm search "<keyword>" --limit 10'],nextSteps:o?["Check that the variable holding the item ID is defined before passing it to pm.",'Use "pm list --status open --limit 20" to find valid IDs.']:["Confirm the active --path/PM_PATH scope, then retry with a valid id."]}),e,t)}function un(e,n,t){return!n.includes("is assigned to")||!n.includes("Use --force to override")?null:h(u({code:"ownership_conflict",title:"Ownership conflict",happened:n,required:"Run as the assigned owner, claim the item when appropriate, or use --force only for an approved override.",why:"Ownership checks prevent accidental concurrent mutations on claimed items and protect against conflicting writes.",examples:["pm claim pm-a1b2","pm update pm-a1b2 --status in_progress --force"],nextSteps:["Use --force for approved systematic metadata updates performed by leads or maintainers.","Use --force when correcting known stale metadata after coordinating ownership changes.",'For non-terminal reassignment, prefer "pm claim <ID>" before running other mutations.']}),e,t)}function mn(e,n,t){if(!n.includes("is locked"))return null;const i=Y(t?.recovery?.normalized_args),r=i?f(i):void 0,o=h(u({code:"lock_conflict",title:"Lock conflict",happened:n,required:"Wait for lock release, then retry the same operation. Set PM_LOCK_WAIT_MS to a larger bounded millisecond budget for expected contention.",why:"Locking protects item files from concurrent write races.",examples:r?[r]:["pm gc --scope locks --dry-run"]}),e,t);return i&&(o.recovery={...o.recovery,suggested_retry:r,suggested_retry_args:[...i]}),o}function pn(e,n,t){const i=n.match(/^Missing required option /),r=n.match(/^Missing required options /);if(!i&&!r)return null;const o=!!r,a=o?null:n.replace(/^Missing required option\s+/,"").trim(),s=a??"",d=a?`Pass ${a} with a valid value before running the command.`:"Provide the required option for this command invocation.";return h(u({code:"missing_required_option",title:o?"Missing required options":`Missing required option ${s}`,happened:n,required:o?"Provide every required option for this command invocation.":d,why:"Required options define command intent and enforce deterministic write contracts.",examples:['pm create --title "Task title" --description "Task details" --type Task --create-mode progressive','pm create --title "Task title" --description "Task details" --type Task --status open --priority 1 --message "Create task" --dep "id=pm-epic01,kind=parent,created_at=now" --comment "created_at=now,text=Why this task exists." --note "created_at=now,text=Initial implementation note." --learning "created_at=now,text=Durable lesson placeholder." --file "path=src/example.ts,scope=project" --test "command=node scripts/run-tests.mjs test,scope=project,timeout_seconds=240" --doc "path=README.md,scope=project"'],nextSteps:['Run "pm <command> --help" to view required and recommended flags.',"For staged triage without placeholder linkage values, use --create-mode progressive."]}),e,t)}function fn(e,n,t){return n.startsWith("No update flags provided")?h(u({code:"no_update_fields",title:"No update fields supplied",happened:"The update command was called without any field-changing flags.",required:"Provide at least one field-changing flag such as --status, --priority, --title, --tags, --description, or --body. Use --message only to label a real mutation.",why:"pm update mutates existing item fields; no-op invocations are rejected to avoid ambiguous history.",examples:['pm update pm-a1b2 --status in_progress --message "Start implementation"','pm update pm-a1b2 --description "Clarified implementation scope" --message "Clarify task intent"','pm append pm-a1b2 --body "Detailed progress notes" --message "Append progress notes"'],nextSteps:["Choose the item field you intend to change, then pair that change with --message for history context.","Use pm comments, pm notes, pm learnings, or pm append when you only need to add narrative context."]}),e,t):null}function hn(e,n){if(e.startsWith("Invalid "))return!0;if(!e.includes(" must be ")&&!e.includes(" requires "))return!1;const t=$(n?.code,void 0);return t===void 0||t==="invalid_argument_value"||n?.allowed!==void 0}function _n(e,n,t){if(!hn(n,t))return null;const i=y(t?.recovery),r=Ze(i),o=r?`pm ${r} --help`:"pm <command> --help",a=t?.recovery?.allowed_values!==void 0?[]:t?.allowed??Qe(n),s=y({...i,allowed_values:i?.allowed_values??a}),d=en(i,a),c=d?[d,o]:[o,"pm contracts --command <command> --flags-only --json"],l=a.length>0?[`Allowed values: ${a.join("|")}`,`Run "${o}" to confirm command-specific constraints.`]:["Check allowed values in command help, then rerun with corrected input."];return h(u({code:"invalid_argument_value",title:"Invalid argument value",happened:n,required:"Use values that match documented command constraints.",why:"Validation protects data consistency and deterministic behavior across commands.",examples:c,nextSteps:l,recovery:s}),e,t)}function P(e,n){const t=I(e),i=cn(e,t,n)??ln(e,t,n)??un(e,t,n)??mn(e,t,n)??pn(e,t,n)??fn(e,t,n)??_n(e,t,n);return i||h(u({code:"command_failed",title:"Command failed",happened:t,required:"Adjust command input or tracker state and retry.",why:"pm enforces explicit, deterministic contracts for data and command semantics.",examples:["pm --help","pm <command> --help"]}),e,n)}function ae(e,n,t){return e==="create"&&n.startsWith("--type")?[`pm create --title "Example title" --description "Example description" --type ${t.split("|")[0]||"Task"} --status open --priority 1 --message "Create item" --create-mode progressive`]:e==="update"?['pm update pm-a1b2 --status in_progress --message "Start implementation"']:[`pm ${e??"<command>"} --help`]}function gn(e){const n=e.trim();return n.match(/--[A-Za-z0-9][A-Za-z0-9_-]*/)?.[0]??n}function yn(e){if(!(!Array.isArray(e)||e.length===0))return f(e)}function z(e){if(!Array.isArray(e))return;const n=e.map(t=>t.trim()).filter(t=>t.length>0);return n.length>0?n:void 0}function p(e,n={}){const t=z(e?.providedOptionFlags),i=Array.isArray(e?.normalizedInvocationArgs)&&e?.normalizedInvocationArgs.length>0?e.normalizedInvocationArgs:void 0,r=typeof e?.attemptedCommand=="string"?e.attemptedCommand:yn(i),o=typeof e?.suggestedRetryCommand=="string"?e.suggestedRetryCommand:void 0;return y({attempted_command:r,normalized_args:i,provided_fields:t,suggested_retry:o,suggested_retry_args:e?.suggestedRetryArgs,...n})}function b(e,n){return!n||e.includes(n)?e:[...e,n]}const vn=new Set(["--add","--add-json","--remove"]),wn=new Set(["command","cmd","path"]);function bn(e){if(Array.isArray(e))for(const n of e){if(!n.startsWith("--"))continue;const t=n.indexOf("="),i=t>=0?n.slice(0,t):n;if(vn.has(i))return i}}function kn(e){if(!Array.isArray(e))return;const n=e.indexOf("test");if(n<0)return;const t=e[n+1];if(!(typeof t!="string"||t.startsWith("-")))for(let i=n+2;i<e.length;i+=1){const r=e[i];if(r!=="--add"&&r!=="--remove")continue;const o=e[i+1];if(typeof o!="string"||!wn.has(o))return;const a=[];for(let c=i+2;c<e.length;c+=1){const l=e[c];if(l.startsWith("--")&&l.length>2)break;a.push(l)}if(a.length<2)return;const s=`${o}=${a.join(" ")}`,d=[...e.slice(0,i+1),s,...e.slice(i+2+a.length)];return f(d)}}function $n(e,n,t,i){const r=e.match(/required option '([^']+)' not specified/);if(!r)return null;const o=gn(r[1]),a=o.startsWith("--type"),s=i?.suggestedRetryCommand,d=z(i?.providedOptionFlags),c=[o],l=ae(n,o,t),m=s?b(l,s):l,g=a?[`Allowed type values: ${t}`,`Run "pm ${n??"create"} --help --type <value>" for type-aware policy details.`]:[`Run "pm ${n??"<command>"} --help" for required option guidance.`],C=s?b(g,`Replay with preserved arguments: ${s}`):g,A=d&&d.length>0?b(C,`Already provided options: ${d.join(", ")}`):C;return u({code:"missing_required_option",title:`Missing required option ${o}`,happened:`Commander rejected the command because ${o} was not provided.`,required:`Pass ${o} with a valid value before running the command.`,why:a?"--type selects item contract and policy routing, including required/disabled option rules.":"Required flags define mandatory command intent and prevent ambiguous execution.",examples:m,nextSteps:A,recovery:p(i,{missing:c})})}function Cn(e,n,t){const i=e.match(/missing required argument '([^']+)'/);if(!i)return null;const r=i[1];return u({code:"missing_required_argument",title:`Missing required argument ${r}`,happened:`Command invocation omitted positional argument ${r}.`,required:`Provide ${r} in the expected command position.`,why:"Positional arguments identify the target entity or action context for the command.",examples:[`pm ${n??"<command>"} --help`],recovery:p(t,{missing:[r]})})}function An(e,n,t){return u({code:"unsupported_update_option",title:`Unsupported option ${e} for update`,happened:`pm update does not accept ${e} for linked artifact mutations.`,required:"Use dedicated linked-artifact commands instead of pm update for files/docs changes.",why:"pm update manages scalar item metadata, while linked files/docs are managed by pm files and pm docs.",examples:['pm files pm-a1b2 --add "path=src/cli/main.ts,scope=project,note=implementation surface"','pm docs pm-a1b2 --add "path=README.md,scope=project,note=user-facing contract"'],nextSteps:['Run "pm files --help" and "pm docs --help" for add/remove payload formats.'],recovery:p(n,{suggested_flags:t})})}const Rn={declared_elsewhere:"Use an option declared on this path, or move the declared option to one of its accepting command paths.",declared_on_path:"Use the option with the value and syntax declared by this command path.",declared_nowhere:"Use a declared option on this command path; this spelling exists nowhere in the command lexicon."};function Sn(e){const n=w(e.unknownOptionOtherCommands)??[];return{otherCommands:n,optionScope:e.unknownOptionScope??(n.length>0?"declared_elsewhere":"declared_nowhere"),candidateTotal:e.unknownOptionOtherCommandsTotal??n.length}}function xn(e,n,t,i,r){const o=i.otherCommands.slice(0,3),a=i.candidateTotal-o.length,s=a>0?` and ${String(a)} more command path(s)`:"";return["Run command help to confirm the exact option contracts for this command path.",t.length?`Nearest supported options: ${t.join(", ")}`:void 0,r?void 0:En(e,n),o.length?`${e} is accepted by ${o.join(", ")}${s}. Inspect those command contracts only if you intended a different operation.`:void 0,de(e)?`"${e}" contains spaces, so it is a value that starts with --, not an option. Pass it after a -- separator at the end of the command, or through the command's named value flag.`:i.optionScope==="declared_nowhere"?`${e} is not declared on any command path. Use a nearest supported option on ${n??"the attempted command"}, or inspect that command's help.`:void 0,r?`Replay with suggested correction: ${r}`:void 0].filter(d=>typeof d=="string")}const se=["--brief","--compact","--standard","--deep","--full","--summary","--depth"];function En(e,n){if(n===void 0||!se.includes(e.split("=",1)[0]))return;const t=fe(n);return t===void 0?void 0:`Completeness controls accepted by pm ${t.command}: ${me(t)}.`}function In(e,n,t){const i=he(t??"",e.normalizedInvocationArgs??[],n);return i?{retryCommand:f(i),suggestedRetryArgs:i}:[...se,"--toon",...t==="activity"?["--since"]:[]].includes(n.split("=",1)[0])?{}:void 0}function de(e){return/\s/u.test(e)}function Tn(e,n){const t=e?.indexOf(n)??-1;if(e===void 0||t<0||e.includes("--")||e.lastIndexOf(n)!==t)return{};if(e.slice(t+1).some(r=>!r.startsWith("-")))return{};const i=[...R(e.filter((r,o)=>o!==t)),"--",n];return{retryCommand:f(i),suggestedRetryArgs:i}}function On(e,n,t){if(de(n))return Tn(e.normalizedInvocationArgs,n);if(["--dry-run","--check","--check-only","--plan","--preview"].includes(n.split("=",1)[0]))return{};const i=In(e,n,t);if(i)return i;if(e.suggestedRetryCommand!==void 0)return{retryCommand:e.suggestedRetryCommand};if(pe(n))return{};const r=e.normalizedInvocationArgs;if(r===void 0)return{};if(r.filter(s=>s===n||s.startsWith(`${n}=`)).length!==1)return{};const o=r.findIndex(s=>s===n||s.startsWith(`${n}=`));if(o<0||r.includes("--")||!r[o]?.includes("=")&&o!==r.length-1&&r[o+1]?.startsWith("-")!==!0)return{};const a=R(r.filter((s,d)=>d!==o));return{retryCommand:f(a),suggestedRetryArgs:a}}function qn(e,n,t){const i=e.match(/unknown option '([^']+)'/);if(!i)return null;const r=t??{},o=i[1],a=z(r.unknownOptionSuggestions)??[],{retryCommand:s,suggestedRetryArgs:d}=On(r,o,n);if(n==="update"&&(o==="--file"||o==="--doc"))return An(o,t,a);const c=Sn(r),l=xn(o,n,a,c,s);["--dry-run","--check","--check-only","--plan","--preview"].includes(o.split("=",1)[0])&&l.push("The requested preview is unavailable on this path. Inspect the item with a read-only command or use a command that declares this option; do not replay this mutation without preview intent.");const m=[s,n?`pm ${V(n)?.canonical??n} --help`:"pm --help --all"].filter(g=>typeof g=="string");return u({code:"unknown_option",title:`Unknown option ${o}`,happened:`Commander does not recognize option ${o} for this command path.`,required:Rn[c.optionScope],why:"Option contracts are command-specific and intentionally validated.",flag:o,value:o,examples:m,nextSteps:l,recovery:p(t,{suggested_flags:a.length>0?a:void 0,suggested_retry:s,suggested_retry_args:d,candidate_commands:c.otherCommands,candidate_commands_total:c.candidateTotal||void 0,candidate_commands_truncated:r.unknownOptionOtherCommandsTruncated,option_scope:c.optionScope})})}function Ln(e,n,t,i,r){const o=`"${e}" is provided by the ${n.packageName} package. Install it with: ${n.installCommand}`,a=i.filter(s=>!s.endsWith(`: ${n.installCommand}`));return u({code:"unknown_command",title:`Unknown command ${e}`,happened:`pm does not expose command path "${e}" in current runtime configuration. It is shipped by the optional ${n.packageName} package.`,required:`Install the ${n.packageName} package, or use a valid command name or subcommand path.`,why:"Command registry includes core commands plus active extension command handlers; package-provided commands appear only after the package is installed.",examples:D([n.installCommand,...t]),nextSteps:D([o,...a]),recovery:p(r)})}function Dn(e,n){const t=e.match(/unknown command '([^']+)'/);if(!t)return null;const i=t[1],r=w(n?.unknownCommandExamples),o=w(n?.unknownCommandNextSteps),a=X(i),s=r??["pm --help"],d=o??["Verify spelling and active extensions, then rerun."],c=new Set(n?.failedExtensions?.map(m=>m.name.trim().toLowerCase())),l=a?.packageName.replace(/^@unbrained\/pm-/,"").toLowerCase();return a&&(!l||!c.has(l))?Ln(i,a,s,d,n):u({code:"unknown_command",title:`Unknown command ${i}`,happened:`pm does not expose command path "${i}" in current runtime configuration.`,required:"Use a valid command name or subcommand path.",why:"Command registry includes core commands plus active extension command handlers.",examples:s,nextSteps:d,recovery:p(n)})}function Pn(e){const n=e?.unknownSubcommandPath?.trim(),t=e?.unknownSubcommandToken?.trim(),i=w(e?.unknownSubcommandAllowedValues);if(!n||!t||!i)return null;const r=e?.suggestedRetryCommand;return u({code:"unknown_subcommand",title:`Unknown ${n} subcommand ${t}`,value:t,happened:`The positional token sequence "${t}" is not a declared ${n} subcommand.`,required:`Use one of: ${i.join(", ")}.`,why:"Subcommands are single positional tokens; multi-word action names use hyphens.",examples:[...r?[r]:[],`pm ${V(n)?.canonical??n} --help`],nextSteps:r?[`Retry with the declared hyphenated action: ${r}`]:["Choose one value from recovery.allowed_values."],recovery:p(e,{allowed_values:i,suggested_retry:r})})}function zn(e,n,t){if(!/too many arguments/i.test(e)||n!=="test")return null;const i=t?.normalizedInvocationArgs,r=bn(i);if(!r)return null;const o=kn(i);return u({code:"linked_test_value_not_quoted",title:`Linked-test ${r} value must be one argument`,happened:`Commander saw extra positional tokens after the item id \u2014 usually a ${r} value containing spaces (for example a command with " -- ") that the shell split into multiple tokens.`,required:`Quote the whole ${r} value as a single argument. Accepted forms: --add "command=npm test -- parser", --add command "npm test -- parser" (two-token form with the value quoted), or --add-json for complex commands.`,why:"The shell splits unquoted values before pm can see them, so pm cannot reassemble the intended command unambiguously.",examples:[...o?[o]:[],'pm test pm-a1b2 --add "command=npm test -- parser"','pm test pm-a1b2 --add command "npm test -- parser"',`pm test pm-a1b2 --add-json '{"command":"npm test -- parser"}'`],nextSteps:[...o?[`Replay with the value re-joined into one argument: ${o}`]:[],"Prefer --add-json for commands containing commas, equals signs, or quotes.",'Run "pm test --help" for linked-test entry contracts.'],recovery:p(t,o?{suggested_retry:o}:{})})}const jn=new Set(["comments","docs","files","learnings","notes","test"]);function Gn(e,n,t){if(!/too many arguments/i.test(e))return null;const i=_e(n,t?.normalizedInvocationArgs??[]);if(!i)return null;const r=i.retryArgs?f(i.retryArgs):void 0,o=f(i.templateArgs??["test",i.itemId,"--add",`command=<actual command>,${i.value}`]);return u({code:"linked_resource_positional_value",title:"Linked-resource values require an explicit --add option",happened:`The value after the item id is not a positional argument of ${n}.`,required:r?`Retry the explicit collection mutation: ${r}`:`Supply the actual command and its metadata together, for example ${o}.`,examples:[r??o],recovery:p(t,{suggested_retry:r,suggested_retry_args:i.retryArgs})})}function Nn(e,n,t){if(!/too many arguments/i.test(e)||!jn.has(n??""))return null;const i=t?.normalizedInvocationArgs??[],r=i.findIndex(c=>c===n),o=i[r+1],a=i[r+2],s=t?.verifiedCollectionItemId?.trim();if(o?.toLowerCase()!=="add"||!a||a.startsWith("-")||!s||s.toLowerCase()!==a.toLowerCase())return null;const d=`pm ${n} ${s} --add <value>`;return u({code:"collection_transposed_subcommand",title:`Transposed ${n} add syntax`,happened:`The positional token "add" occupied the item-id role and "${s}" occupied the next positional role. pm ${n} does not use an add subcommand.`,required:`Place the item id immediately after ${n}, then use --add for the value.`,why:"Collection mutations use object-first grammar: pm <collection> <item-id> --add <value>.",examples:[d,`pm ${n} --help`],recovery:p(t,{parsed_positionals:[{role:"transposed_subcommand",value:o},{role:"item_id",value:s}],suggested_retry:d})})}const Un=new Set(["--activity-limit","--assignee","--assignee-filter","--date","--depth","--fields","--format","--from","--limit","--parent","--path","--pm-path","--priority","--release","--section","--sprint","--stale-threshold","--tag","--to","--type"]),ce=new Set(["context","ctx"]);function Mn(e,n,t){if(!/too many arguments/i.test(e)||!ce.has(n??""))return null;const i=t?.normalizedInvocationArgs??[],r=i.findIndex(c=>ce.has(c)),o=r===-1?1:r+1,a=e.match(/got \d+:\s*(\S+)/i);let s=a?a[1].replace(/\.$/,""):void 0;if(s===void 0){let c=!1;for(const l of i.slice(o)){if(c){c=!1;continue}const m=l.split("=")[0];if(Un.has(m)){c=!l.includes("=");continue}if(!l.startsWith("-")){s=l;break}}}if(!s)return null;const d=`pm get ${s}`;return u({code:"context_takes_no_item_argument",title:"pm context takes no item argument",happened:`pm context renders a workspace-level snapshot and received the positional argument "${s}".`,required:`Use ${d} for one item's full details, or pm context --parent ${s} to scope the snapshot to that item's subtree.`,why:"Item-level detail (pm get) and workspace-level context (pm context) are separate projections.",examples:[d,`pm context --parent ${s}`],recovery:p(t,{suggested_retry:d})})}function j(e,n,t,i){const r=I(e),o=$n(r,n,t,i)??Cn(r,n,i)??qn(r,n,i)??Dn(r,i)??Pn(i)??Nn(r,n,i)??zn(r,n,i)??Gn(r,n,i)??Mn(r,n,i);return o||u({code:"invalid_command_usage",title:"Invalid command usage",happened:r,required:"Use the command with valid arguments and options.",why:"Commander validates CLI contracts before execution.",examples:["pm --help",`pm ${n??"<command>"} --help`],recovery:p(i)})}function Qn(e,n,t={}){const i=T(P(e,n));return(n?.code==="tracker_root_missing"||n?.code==="tracker_not_initialized")&&i.title==="Tracker is not initialized"&&i.recovery?.suggested_retry_args?[`Error: ${i.title}`,`Run: ${f(i.recovery.suggested_retry_args)}`,"Use --json for full recovery details."].join(`
|
|
6
|
+
`):le(i,t)}function le(e,n){const t=T(e),i=a=>be(Be(t,a),t.required).output,r=i(n);if(n.lean!==!0)return r;const o=i({});return Buffer.byteLength(o,"utf8")<Buffer.byteLength(r,"utf8")?o:r}function et(e,n){return E(P(e,n))}function nt(e,n,t){return L(P(e,t),n)}function tt(e,n,t,i,r={}){const o=j(e,n,t,i);return le(o,r)}function it(e,n,t,i){return E(j(e,n,t,i))}function rt(e,n,t,i,r){return L(j(e,n,t,r),i)}function ot(e,n){const t=ue(e);return L(t,n)}function ue(e){const n=I(e);return Ye(n)?u({code:"module_import_failed",title:"Module import failed",happened:n,required:"Ensure the active checkout is built and any package or extension entry file exists before retrying.",why:"Node could not resolve an imported module. In pm this usually means an extension/package entrypoint, build artifact, or dependency is missing from the active runtime.",examples:["pnpm build","pm package manage --doctor --project","pm health --check-only --json"],nextSteps:["Rebuild the checkout or package that provides the missing module.","Run package doctor for installed extensions when the failure follows package installation or activation.","Rerun the original pm command after the runtime files are present."]}):u({code:"unknown_error",title:"Unhandled error",happened:n,required:"Inspect command input and runtime state, then retry.",why:"Unexpected runtime failures can occur from environment or extension-level issues.",examples:["pm --help","pm health --json"]})}function at(e){return E(ue(e))}const st={applyPmCliErrorContext:h,appendIfMissing:b,buildCommanderRecoveryPayload:p,buildFallbackTitleFromMessage:oe,commandExampleForRequiredOption:ae,dedupeStrings:D,guidanceToClassification:E,guidanceToJsonEnvelope:re,normalizeRecoveryPayload:y,renderList:x,resolveKnownPackageCommandHint:X};export{st as _testOnly,kn as buildLinkedTestQuotedRetryCommand,it as classifyCommanderError,et as classifyPmCliError,at as classifyUnknownError,tt as formatCommanderErrorForDisplay,rt as formatCommanderErrorForJson,Qn as formatPmCliErrorForDisplay,nt as formatPmCliErrorForJson,ot as formatUnknownErrorForJson,Zn as projectLeanErrorEnvelope,Ue as renderGuidanceMessage};
|
|
7
7
|
//# sourceMappingURL=error-guidance.js.map
|
package/dist/cli/main.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{attachPreflightWarnings as Le,attachSerializedPreflightWarnings as We,emitPreflightWarning as kt,runWithPreflightWarnings as Pt}from"./preflight-warnings.js";import{assertGuardedDispatchUnchanged as je,bindInvocationExpectedRevisions as Be,invocationRewritten as Ot,parseWithInvocationRevisionScope as Ft,refuseInventoryExpectHash as Tt}from"./expected-revisions.js";import{Command as ae,CommanderError as ze}from"commander";import{PM_COMMAND_ALIAS_CONTRACTS as Dt,findPmNamespacedCommand as It,resolvePmCommandOperation as ce}from"../sdk/cli-contracts/command-aliases.js";import{createPmCliProgram as qe}from"../sdk/cli-program.js";import{runWithDiscoveredContextIntentContracts as Ht}from"../sdk/context-intent-runtime.js";import{createExtensionCommandError as Mt,describeUnknownError as D,isCommanderError as Ve,normalizeThrownExitCode as Ke,readThrownExitCode as Je,wrapThrownErrorForSentry as Ye}from"../sdk/error-runtime.js";import{createExtensionCommandSdk as Nt}from"../sdk/extension-command-context.js";import{isPmCliExpectedError as $t,snapshotPmCliErrorContext as Gt}from"../sdk/errors.js";import{runExtensionMigrations as Ut}from"../sdk/extension/migrations.js";import{repairProjectionRecovery as Lt}from"./runtime/projection-retry.js";import{repairReadOutputMutationRecovery as Wt}from"./runtime/read-output-mutation-retry.js";import{redactRefusalArgv as jt}from"./runtime/refusal-credential-redaction.js";import{redactUrlCredentialsInText as Qe,runWithUrlCredentialInvocation as Bt}from"../sdk/command-line.js";import{isTrackerRevisionGuarded as zt}from"../sdk/lifecycle/item-revision.js";import{repairSchemaFieldRecovery as qt}from"./runtime/field-route-retry.js";import{ANNOTATION_OPTION_REFUSAL_CODE as Vt,repairAnnotationOptionRecovery as Kt}from"./runtime/annotation-option-retry.js";import{annotationPositionalMutationOptions as Jt}from"./register-annotations.js";import{CLOSE_FIELDS_REFUSAL_CODE as Yt,repairCloseFieldsRecovery as Qt}from"./runtime/close-fields-retry.js";import{resolvePmCommandScopeArgs as Xt}from"../sdk/command-line.js";import{applyInvocationAuthorOverride as Zt}from"../sdk/invocation-author.js";import{attachOutputTokenAccounting as en}from"../sdk/output-token-accounting.js";import{validateReadOutputOptions as on}from"../sdk/read-output-contracts.js";import{runWithReproducibleProcessEnvironment as tn}from"../sdk/reproducibility/process.js";import{resolveTelemetrySourceAttribution as Xe,EXIT_CODE as h,PmCliError as G,activateExtensions as nn,clearActiveExtensionHooks as le,consumeAfterCommandAffectedItems as rn,createCoreCommandHookContext as sn,createEmptyExtensionRegistrationRegistry as an,createLazyModule as K,deriveTelemetryCommandResolution as cn,discoverExtensions as ln,emitTelemetryErrorEvent as dn,ensureSentryInit as mn,ensureSentryCommandTracing as Ze,getActiveCommandResult as un,getActiveExtensionRegistrations as pn,getSettingsPath as de,loadExtensions as gn,maybeRunFirstUseTelemetryPrompt as fn,pathExists as me,printError as y,printResult as eo,readSettings as I,readSettingsWithMetadata as oo,resetActiveExtensionRuntimeState as hn,resolveGlobalPmRoot as yn,resolveItemTypeRegistry as Cn,resolvePmCliVersion as _n,resolvePmPackageRootFromModule as vn,resolvePmRoot as R,resolveRuntimeFieldRegistry as to,resolveTelemetryErrorCategory as wn,runActiveCommandHandler as no,runActiveParserOverride as ue,runActivePreflightOverride as En,runAfterCommandHooks as Rn,runBeforeCommandHooks as xn,runWithConfigurationOnlySettings as pe,runWithHarnessDetectionSignals as bn,runWithWorkspaceHarnessSignalDescriptors as Sn,sentryCaptureCliError as ro,sentryDiscardCommandSpan as An,sentryFinishCommandSpan as kn,sentryFlush as U,sentryLogCliUsageError as Pn,sentrySetCommandContext as io,sentryStartCommandSpan as On,setActiveCommandContext as ge,setActiveCommandResult as L,setActiveExtensionCommands as Fn,setActiveExtensionHooks as Tn,setActiveExtensionParsers as Dn,setActiveExtensionPreflight as In,setActiveExtensionRegistrations as so,setActiveExtensionRenderers as Hn,setActiveExtensionServices as O,startTelemetryCommand as ao,writeStderr as fe}from"../sdk/runtime-primitives.js";import{PmClient as Mn}from"../sdk/runtime.js";import{recordDeprecatedAliasUsage as Nn}from"../sdk/telemetry.js";import{finishActiveTelemetryCommand as $n,recordAfterCommandContextUsage as Gn}from"./after-command-context-usage.js";import{extractProvidedOptionFlags as co,normalizeLongOptionFlag as W,redactSensitiveCommandArgs as Un,renderPmCommand as Ln}from"./argv-utils.js";import{applyBootstrapPagerPolicy as Wn,findBootstrapCommandTokenIndex as he,normalizeBootstrapInvocation as lo,parseBootstrapCommandName as ye,parseBootstrapGlobalOptions as k,parseBootstrapHelpRequest as Ce,stripGlobalBootstrapTokens as mo}from"./bootstrap-args.js";import{installCommandNamespaces as uo}from"./command-namespaces.js";import{appendCommanderExtensionFailures as po,formatCommanderUsageJson as go,formatCommanderUsageMessage as fo,isKnownHelpCommandPath as _e,resolveCommanderUsageContext as ho,resolveUnknownCommanderToken as yo}from"./commander-usage.js";import{loadContextIntentSnapshotForInvocation as jn}from"./context-intent-invocation.js";import{classifyCommanderError as Co,classifyPmCliError as Bn,classifyUnknownError as zn,formatPmCliErrorForDisplay as qn,formatPmCliErrorForJson as _o,formatUnknownErrorForJson as Vn,projectLeanErrorEnvelope as Kn}from"./error-guidance.js";import{applyDynamicExtensionArguments as Jn,applyDynamicExtensionFlagOptions as vo,buildCanonicalExtensionAliases as Yn,buildDynamicExtensionCommandMetadataHelp as Qn,buildExtensionInheritedFlagHelp as wo,isExtensionCreatedCommand as Eo,buildResidualDynamicExtensionFlagHelp as Ro,collectDynamicExtensionFlagHelpByCommand as Xn,collectExtensionCommandHelpDescriptors as Zn,collectSafeExtensionCommandPaths as er,ensureCommandPath as or,extensionFlagTakesValueForInvocation as xo,findCommandByPath as ve,normalizeExtensionCommandPath as P,reportExtensionCommandCollision as tr}from"./extension-command-help.js";import{collectLoosePositionalArgs as nr,stripLooseCommandOptionTokens as bo}from"../sdk/extension/command-options.js";import{loadExtensionRecoveryFailures as rr,loadUnknownCommandRecoveryFailures as ir}from"./extension-recovery.js";import{attachRichHelpText as sr,isFullHelpDiscovery as ar,setPmCommandHelpVisibilityTier as cr}from"./help-content.js";import{attachCreateUpdatePolicyHelpText as lr,maybeRenderBootstrapJsonHelp as dr}from"./help-json-payload.js";import{collectMandatoryMigrationBlockers as mr,enforceItemFormatWriteGateAndPreflightMigration as So,enforceMandatoryMigrationWriteGate as ur,enforceMutationGuardPreflight as Ao}from"./migration-gates.js";import{applyDefaultOutputFormat as pr,clearResolvedGlobalOptions as ko,collect as Po,formatHookWarnings as S,getCommandPath as H,getGlobalOptions as J,invalidateSearchCachesForMutation as gr,setResolvedGlobalOptions as fr,syncCommanderActionOptions as we}from"./registration-helpers.js";import{activationCommandMatchesProbe as hr,buildBootstrapActivationProbe as j,buildRuntimeExtensionActivationScope as Oo,buildRuntimeExtensionFilterForProbe as Fo,collectActivationCommandCandidates as Ee,collectLeadingCommandArgs as yr,collectParsedActivationCommandArgs as To,commandPathNeedsSearchExtensions as Cr,commandPathNeedsTemplateExtensions as _r,discoveryNeedsActivationForProbe as Y,extensionActivationCommands as vr,extensionCapabilities as wr,extensionNeedsActivationForProbe as Er,extensionProvidesTemplatesRuntime as Rr,hasAnyCapability as xr,hasGlobalExtensionContributions as br,matchesStaticExtensionCommand as Sr,probeUsesAnyFlag as Ar,resolveStaticExtensionActivationDecision as kr}from"./runtime/activation.js";import{captureCommandOptionTokens as Pr,refuseConflictingCommandOptionSpellings as Or,resolveExtensionCommandRefusalListing as Fr,collectExtensionFlagDefinitionsForCommand as Tr,collectExtensionFlagDefinitionsForInvocation as Q,copyReadOutputInvocationProvenance as Re,dynamicCommandArguments as Dr,extractCommandScopedOptions as B,forwardReadOutputIncludeModes as Do,isImporterOrExporterCommandPath as Io,recordCliReadOutputInvocationProvenance as Ir,refuseUndeclaredRootOnlyOptions as Hr,validateDynamicExtensionCommandArgs as Mr,validateDynamicExtensionCommandInvocation as Ho}from"./runtime/invocation-options.js";import{LIST_QUERY_COMMAND_NAMES as Nr,enforceExplicitRetryForFlagTypos as Mo,invocationRequestsVersion as $r,isStaticExtensionInventoryInvocation as xe,resolveStructuredMutationPreviewInvocation as Gr,resolveCoreCommandRegistrationSelection as No,shouldAttachRichHelpTextForInvocation as $o,shouldRegisterDynamicExtensionPaths as Go,shouldRegisterRuntimeSchemaFlags as Uo}from"./runtime/selection.js";import{recordInvocationPromotions as Ur}from"./runtime/invocation-rewrites.js";import{buildPostActionTelemetryOutcome as Lo,inferPostActionErrorCode as Lr,inferPostActionFailureMessage as Wr,normalizeTelemetryCommandResolution as jr,normalizeTelemetryErrorCategory as Br,normalizeTelemetryResolutionStage as zr,readRecordBoolean as qr,readRecordNumber as Vr,readRecordString as Kr}from"./runtime/telemetry-outcome.js";const be="PM_CLI_PACKAGE_ROOT",Wo=Symbol("pm.deprecatedAliasInvocation"),X=new Map;for(const e of Dt){const o=e.alias.split(" ")[0],t=X.get(o)??[];t.push(e),X.set(o,t)}for(const e of X.values())e.sort((o,t)=>t.alias.split(" ").length-o.alias.split(" ").length);function Jr(){return vn(import.meta.url,["../.."])}(typeof process.env[be]!="string"||process.env[be]?.trim().length===0)&&(process.env[be]=Jr());let F=null,x=null,Z=null;function Yr(e){F=e}function Qr(e){v=e}let z=null,T=null,v=new Map;const Se=250,Xr=new Set([h.USAGE,h.NOT_FOUND,h.CONFLICT]),Zr=new Set(["1","true","yes","on"]),ei=K(()=>import("./register-setup.js")),oi=K(()=>import("./register-list-query.js")),ti=K(()=>import("./register-mutation.js")),ni=K(()=>import("./register-operations.js"));function ee(e){return Ln(e)}function jo(e){const o=e.match(/--[a-zA-Z0-9][a-zA-Z0-9_-]*/g);if(!o||o.length===0)return;const t=[...new Set(o.map(n=>W(n)??n))];return t.length>0?t:void 0}function ri(e,o,t,n){if(t?.suggested_retry||n===Yt||n===Vt||e.includes("failed in extension handler (")||!/\b(?:missing|required|requires)\b/i.test(e))return;const r=co(o),s=new Set(r.map(m=>W(m)??m)),i=jo(e),c=o.find(m=>p.commands.some(d=>d.name()===m)),u=c?p.commands.find(m=>m.name()===c):void 0,l=new Set([...p.options,...u?.options??[]].flatMap(m=>m.flags.split(/[ ,|]+/).map(d=>W(d)).filter(d=>d!==void 0))),a=i?.filter(m=>{const d=W(m)??m;return s.has(d)?!1:l.has(d)||xo(o,c,d,v)!==void 0});return a&&a.length>0?a:void 0}function ii(e,o,t,n){if(n?.suggested_retry)return n.suggested_retry;const r=t?.[0],s=r?W(r):void 0,i=e.find(d=>p.commands.some(g=>g.name()===d)),c=i?p.commands.find(d=>d.name()===i):void 0,u=s?c?.options.find(d=>d.flags.split(/[ ,|]+/).includes(s)):void 0,l=xo(e,i,s,v),a=s?u?.isBoolean()===!0||l===!1?[s]:[s,"<value>"]:[],m=s?ee([...e,...a]):o;return m===o?void 0:m}function si(e){if(!e)return{};const o=["recovery_mode","missing_required_fields","suggested_flags","suggested_retry_args","allowed_values","candidate_commands","candidate_commands_total","candidate_commands_truncated","fallback_candidates","next_best_command"],t={};for(const n of o){const r=e[n];r!==void 0&&(n==="allowed_values"||r!==null)&&(t[n]=r)}return t}function ai(e){const o=e.existingRecovery;return{attempted_command:o?.attempted_command??e.attemptedCommand,normalized_args:o?.normalized_args??[...e.invocationArgv],provided_fields:o?.provided_fields??(e.providedFields.length>0?e.providedFields:void 0),missing:o?.missing??e.inferredMissing,...si(o),...e.suggestedRetry?{suggested_retry:e.suggestedRetry}:{}}}function Bo(e,o){return{...e,recovery:o}}function ci(e,o){if(o===void 0)return;const t=qt(e,o.code,o.field,Lt(e,o.code,o.recovery)),n=li(e),r=Kt(e,o.code,o.field,t,n),s=Wt(e,o.code,r,n,()=>zt(R(process.cwd(),k(e).path)));return Qt(e,o.code,s,n)}const zo=" ";function li(e){const o=e.map(r=>r===""?zo:/^--(?:pm-)?path=$/u.test(r)?`${r}${zo}`:r),t=k(o).path;if(t!==void 0&&t.trim()!=="")return[];const n=Xt({});return t!==void 0&&n.length>0?null:n}function qo(e,o,t){const n=Un(o),r=mo(n),s=he(r),[i,c]=s===void 0?[]:r.slice(s,s+2),u=n.includes("--explain");e=e===void 0?void 0:Gt(e);const l=ci(n,e),a=l&&(i==="history-redact"||i==="history"&&c==="redact")?{...l,...l.attempted_command?{attempted_command:ee(n)}:{},...l.normalized_args?{normalized_args:[...n]}:{},...l.suggested_retry?{suggested_retry:ee(n)}:{},...l.suggested_retry_args?{suggested_retry_args:[...n]}:{}}:l;if(a?.recovery_mode==="compact"&&!u)return Bo(e,a);const m=ee(n),d=co(n),g=ri(t,n,a,e?.code),f=ii(n,m,g,a),E=ai({invocationArgv:n,attemptedCommand:m,providedFields:d,inferredMissing:g,suggestedRetry:f,existingRecovery:a});return Bo(e,E)}async function q(e){const o=x;x=null,await $n(o,e);const t=F;if(F=null,!t){le();return}let n=[];const r=rn();try{await Gn({pmRoot:t.pmRoot,author:t.globalOptions.author,itemIds:e.ok?r?.map(s=>s.id)??[]:[],intent:t.commandName})}catch{n.push("context_usage_feedback_write_failed")}try{n.push(...await Rn(t.hooks,{command:t.commandName,args:t.commandArgs,options:{...t.commandOptions},global:{...t.globalOptions},pm_root:t.pmRoot,ok:e.ok,error:e.error,result:un(),affected:r}))}catch(s){n=[`afterCommand hooks failed: ${s instanceof Error?s.message:String(s)}`]}finally{le()}!t.globalOptions.json&&n.length>0&&y(`[pm] warning: afterCommand hook_warnings=${S(n)}`),t.profileEnabled&&n.length>0&&y(`profile:extensions hook_warnings=${S(n)}`)}async function Vo(e,o){await mn();const t=x,n=F,r=t?.command??n?.commandName??e,s=t??Xe(n?.globalOptions??o),i=v.get(P(r))?.source;io(r,n?.commandArgs??[],{...n?.commandOptions,...n?.globalOptions},{source_context:s.source_context,source_context_source:s.source_context_source,pm_version:t?.pm_version??N,extension:i})}function Ko(e){return Zr.has((process.env[e]??"").trim().toLowerCase())}function Jo(e){return Ko("PM_SENTRY_CAPTURE_EXPECTED_ERRORS")?!0:!Xr.has(Math.trunc(e))}async function oe(e,o){return Jo(e.exit_code)?(await Vo(e.command,o),Pn({...e,source_context:e.source_context??Xe(o).source_context}),!0):!1}async function Yo(e){const o=Qe(D(e.error)),t=zn(o);e.bootstrapGlobal.json?y(JSON.stringify(Le(Vn(o,h.GENERIC_FAILURE)),null,2)):y(o),process.exitCode=h.GENERIC_FAILURE;let n="runtime",r="runtime_failed";try{await Vo(e.attemptedCommand,e.bootstrapGlobal),ro(e.error);const s=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:t.code,errorMessage:t.detail,exitCode:h.GENERIC_FAILURE,options:{bootstrap_global_options:e.bootstrapGlobal},resolutionStage:"execute"});n=s.errorCategory,r=s.commandResolution,await ie(!1,o,{error_code:t.code,error_category:n,exit_code:h.GENERIC_FAILURE,command_resolution:r,resolution_stage:"execute"})}catch(s){e.bootstrapGlobal.json||y(`Failed to report error: ${D(s)}`)}try{await q({ok:!1,error:o,exit_code:h.GENERIC_FAILURE,error_code:t.code,error_category:n,command_resolution:r,resolution_stage:"execute"})}catch(s){e.bootstrapGlobal.json||y(`Failed to run error hooks: ${D(s)}`)}try{await U()}catch(s){e.bootstrapGlobal.json||y(`Failed to flush error reporting: ${D(s)}`)}}const di={create:"create",update:"update","update-many":"update_many",list:"list","list-all":"list","list-draft":"list","list-open":"list","list-in-progress":"list","list-blocked":"list","list-closed":"list","list-canceled":"list",search:"search",calendar:"calendar",context:"context","templates save":"create"},Ae=new Map;function ke(e){return e==="number"?"number":e==="boolean"?"boolean":"string"}function Qo(e,o){return e.options.some(t=>t.long===o)}function Xo(e,o){return e.options.some(t=>t.short===o)}function Pe(e,o,t,n){const r=o.trim();if(!r)return;const s=t.length>0?t:`Runtime schema field (${o})`;if(r.startsWith("-")&&!r.startsWith("--")){if(Xo(e,r))return;if(n){e.option(`${r} <value>`,`${s} (repeatable)`,Po);return}e.option(`${r} <value>`,s);return}const i=r.startsWith("--")?r:`--${r}`;if(!Qo(e,i)){if(n){e.option(`${i} <value>`,`${s} (repeatable)`,Po);return}e.option(`${i} <value>`,s)}}async function Zo(e,o){const t=di[e];if(!t)return[];const n=`${o}:${t}`,r=Ae.get(n);if(r)return r;if(!await me(de(o)))return Ae.set(n,[]),[];const s=await I(o),c=(to(s.schema).command_to_fields.get(t)??[]).flatMap(u=>[u.cli_flag,...u.cli_aliases].map(a=>({long:`--${a}`,type:ke(u.type),value_type:ke(u.type)})));return Ae.set(n,c),c}async function et(e,o){const t=k(o),n=R(process.cwd(),t.path);if(!await me(de(n)))return;const r=T?.key===De(n)?T.snapshot:null,s=r===null?await I(n):r.settings,i=to(s.schema),c=[{path:"create",command:"create"},{path:"update",command:"update"},{path:"update-many",command:"update_many"},{path:"list",command:"list"},{path:"list-all",command:"list"},{path:"list-draft",command:"list"},{path:"list-open",command:"list"},{path:"list-in-progress",command:"list"},{path:"list-blocked",command:"list"},{path:"list-closed",command:"list"},{path:"list-canceled",command:"list"},{path:"search",command:"search"},{path:"calendar",command:"calendar"},{path:"context",command:"context"},{path:"templates save",command:"create"}];for(const u of c){const l=ve(e,u.path.split(" "));if(l)for(const a of i.command_to_fields.get(u.command)??[]){const m=a.description??"";Pe(l,a.cli_flag,m,a.repeatable);for(const d of a.cli_aliases)Pe(l,d,`Alias for --${a.cli_flag}`,a.repeatable)}}}async function Oe(e,o,t,n,r){const s=ye(t);if(!(s!=="create"&&s!=="update"))try{const i=r??await I(o),c=Cn(i,n);lr(e,c,t)}catch{}}function Fe(){return{enforce_item_format_gate:!0,run_preflight_item_format_sync:!0,run_extension_migrations:!0,enforce_mandatory_migration_gate:!0}}function ot(e,o="all"){return o==="all"?`pm-root:${e}`:`pm-root:${e}:activation:${o}`}function Te(e){return e.some(o=>o==="--profile")}function De(e){return`pm-root:${e}`}function Ie(e){for(const o of e)o.startsWith("settings_read_")&&kt(o,`[pm] warning: ${o} \u2014 settings.json could not be loaded and pm fell back to defaults; run pm health for remediation.`)}function tt(e,o){e.profile&&(y(`profile:extensions loaded=${o.loadedCount} failed=${o.loadFailedCount} warnings=${o.loadWarnings.length} activation_failed=${o.activationFailedCount} hook_counts=before:${o.hooks.beforeCommand.length}|after:${o.hooks.afterCommand.length}|write:${o.hooks.onWrite.length}|read:${o.hooks.onRead.length}|index:${o.hooks.onIndex.length} command_overrides=${o.commands.overrides.length} command_handlers=${o.commands.handlers.length} parser_overrides=${o.parsers.overrides.length} preflight_overrides=${o.preflight.overrides.length} service_overrides=${o.services.overrides.length} renderer_overrides=${o.renderers.overrides.length}`),o.activationWarnings.length>0&&y(`profile:extensions activation_warnings=${S(o.activationWarnings)}`))}function te(e,o,t){if(!e)return;const n=P(t.commandPath??"")||"<none>";y(`profile:extensions activation=skipped command=${n} effective=${o.discovery.effective.length} warnings=${o.discovery.warnings.length} discovery_ms=${o.discoveryMs}`)}async function ne(e,o=oo){const t=De(e);if(T?.key===t)return T.snapshot;try{const n=Date.now(),{settings:r,warnings:s}=await o(e),i=await ln({pmRoot:e,settings:r,cwd:process.cwd(),noExtensions:!1}),c={pmRoot:e,settings:r,discovery:i,discoveryMs:Date.now()-n,settingsReadWarnings:[...s]};return T={key:t,snapshot:c},c}catch{return T={key:t,snapshot:null},null}}async function M(e,o,t=I){const n=o?Oo(o):"all",r=ot(e,n);if(z?.key===r)return z.snapshot;try{const s=await t(e),i=await gn({pmRoot:e,settings:s,cwd:process.cwd(),noExtensions:!1,extensionFilter:o?Fo(o):void 0}),c=await nn({...i,loaded:i.loaded}),u=[...new Set(c.commands.handlers.map(g=>P(g.command)))].filter(g=>g.length>0).sort((g,f)=>g.localeCompare(f)),l=Xn(c.registrations.flags),a=Yn(c.commands.handlers,c.registrations.commands),m=Zn(u,c.registrations.commands,c.registrations.flags,a),d={hooks:c.hooks,commands:c.commands,parsers:c.parsers,preflight:c.preflight,services:c.services,renderers:c.renderers,registrations:c.registrations,pmRoot:e,settings:s,commandHandlers:u,commandFlagHelp:l,commandDescriptors:m,commandAliases:a,loadWarnings:[...i.warnings],activationWarnings:[...c.warnings],loadedCount:i.loaded.length,loadFailedCount:i.failed.length,activationFailedCount:c.failed.length,contextIntentPackages:i.loaded.map(({name:g,module:f})=>({name:g,module:f}))};return z={key:r,snapshot:d},d}catch{return z={key:r,snapshot:null},null}}async function nt(e){const o=J(e);if(o.noExtensions){const i=R(process.cwd(),o.path);return await me(de(i))&&Ie((await oo(i)).warnings),null}const t=R(process.cwd(),o.path),n=await ne(t);if(!n)return null;Ie(n.settingsReadWarnings);const r={commandPath:H(e),commandArgs:To(e)};if(!Y(n.discovery,r))return te(o.profile,n,r),null;const s=await M(t,r);return s?(tt(o,s),{hooks:s.hooks,commands:s.commands,parsers:s.parsers,preflight:s.preflight,services:s.services,renderers:s.renderers,registrations:s.registrations,pmRoot:t}):null}async function He(e){const o=await M(e);return o?new Map(o.commandDescriptors):v}async function mi(e,o){return!e.requested||o.noExtensions||_e(p,e.commandPathTokens)?v:He(R(process.cwd(),o.path))}async function rt(e,o){return(await Ut({pmRoot:o,migrations:e,author:"pm-extension-migration"})).migrations.filter(n=>n.outcome==="failed").map(n=>`extension_migration_failed:${n.layer}:${n.extension}:${n.id}`)}function it(e,o,t){const n=o.author;return Nt(e,Mn.forActiveExtensionHost({pmRoot:e,author:n}),n,P(t))}async function st(e,o,t,n=[]){const r=H(e);let s=bo(e.args.map(String),n),i={...o};delete i.author;let c={...t};const u=R(process.cwd(),t.path),l={args:[...s],path:t.path},a=await ue({command:r,args:s,options:i,global:c,pm_root:u});t.profile&&a.warnings.length>0&&y(`profile:extensions parser_warnings=${S(a.warnings)}`),s=a.context.args,i=a.context.options,c=a.context.global,je(l,{args:s,path:c.path},i),Ho(v.get(P(r)),s,i,n),L(void 0),ge({command:r,args:s,options:{...i},global:{...c},pm_root:u});const m=await no({command:r,args:s,options:i,global:c,pm_root:u,sdk:it(u,c,r)});if(c.profile&&m.warnings.length>0&&y(`profile:extensions command_handler_warnings=${S(m.warnings)}`),!m.handled)throw m.warnings.length>0?Mt(r,m):new G(`Command "${r}" is provided by extensions and is not currently available.`,h.NOT_FOUND);return m.exitCode!==void 0&&(process.exitCode=m.exitCode),L(m.result),m.result}const at=Symbol("pm.wrappedActionHandler");function ui(e,o){const t=e[e.length-1];return t instanceof ae?t:o}function ct(e,o,t){e&&t.length>0&&y(`profile:extensions ${o}=${S(t)}`)}function pi(e){const o=v.get(P(e.commandPath));if(!o||!Io(e.activeRegistrations,e.commandPath))return;const t=Dr(o).length===0?nr(e.commandArgs):bo(e.commandArgs,e.extensionFlagDefinitions);Mr(o,t)}function gi(e,o,t){e.args=[...t],"_processArguments"in e&&typeof e._processArguments=="function"&&e._processArguments(),o.length>0&&Array.isArray(o[0])&&(o[0]=[...e.processedArgs])}function Me(e,o,t){if(!Eo(e))return;const n=v.get(P(o))?.read_output_declared===!0;return Fr(t,n)}function lt(e){const o=t=>{const n=t;if(Pr(t),typeof n._actionHandler=="function"&&n[at]!==!0){const r=n._actionHandler;n._actionHandler=async function(...i){const c=ui(i,t),u=Date.now();ko(c);let l=J(c);const a=ce(H(c));if(["package inventory","packages inventory","extension inventory"].includes(a))return Tt(a,l.expectHash),await r.apply(this,i);const m=R(process.cwd(),l.path);let d=c.args.map(String);const g=pn(),f=g?Q(g,a,d):[],E=await Zo(a,m),C=Me(c,a,f);let _=B(c,d,[...f,...E],C);Or(c,f,a),v.has(P(a))&&delete _.author,C!==void 0&&Hr(_,f,a);const A={args:[...d],path:l.path},b=await ue({command:a,args:d,options:_,global:l,pm_root:m});ct(l.profile,"parser_warnings",b.warnings),d=b.context.args,_=b.context.options,Re(c,_),l=b.context.global,je(A,{args:d,path:l.path},_),pi({activeRegistrations:g,commandPath:a,commandArgs:d,extensionFlagDefinitions:f}),l=await pr(l),fr(c,l),gi(c,i,d),we(c,_),L(void 0),ge({command:a,args:d,options:{..._},global:{...l},pm_root:m});const w=await no({command:a,args:d,options:_,global:l,pm_root:m,sdk:it(m,l,a)});if(ct(l.profile,"command_handler_warnings",w.warnings),w.handled){L(w.result),eo(w.result,{...l,command:a,commandArgs:d,commandOptions:_,pmRoot:m}),l.profile&&y(`profile:command=${a} took_ms=${Date.now()-u}`);return}return await r.apply(this,i)},n[at]=!0}for(const r of t.commands)o(r)};o(e)}async function re(e){v=new Map,O({overrides:[]}),e&&await Oe(e.rootProgram,e.pmRoot,e.invocationArgv,an(),e.settings)}function fi(e,o,t,n){if(o?.flags&&o.flags.length>0){vo(e,o.flags);const r=Ro(e,o.flags);r&&e.addHelpText("after",r)}else t&&e.addHelpText("after",t);o&&Eo(e)&&e.addHelpText("after",wo(o)),n&&e.addHelpText("after",n)}function hi(e,o,t,n){o&&e.addHelpText("after",o),t&&e.addHelpText("after",wo(t)),n&&e.addHelpText("after",n)}function dt(e,o,t){const n={core:0,standard:1,full:2,internal:3},r=(s,i)=>{const c=i.join(" "),u=[...t.entries()].filter(([a])=>a===c||a.startsWith(`${c} `)).map(([,a])=>a),l=u.length===0?"standard":u.reduce((a,m)=>n[m.tier]<n[a]?m.tier:a,"internal");cr(s,l);for(const a of s.commands)r(a,[...i,a.name()])};for(const s of e.commands)o.has(s.name())||r(s,[s.name()])}async function mt(e,o){const t=k(o),n=R(process.cwd(),t.path);if(t.noExtensions){await re({rootProgram:e,pmRoot:n,invocationArgv:o});return}const r=await ne(n),s=j(o);if(!r){await re();return}if(!Y(r.discovery,s)){await re({rootProgram:e,pmRoot:n,invocationArgv:o,settings:r.settings}),te(Te(o),r,s);return}const i=await M(n,s);if(!i){await re({rootProgram:e,pmRoot:n,invocationArgv:o,settings:r.settings});return}O(i.services),v=new Map(i.commandDescriptors),await Oe(e,n,o,i.registrations,i.settings);const c=er(e,i.commandHandlers,i.commandDescriptors,i.commandAliases,a=>tr(i.activationWarnings,y,a)),u=new Set(e.commands.map(a=>a.name())),l=a=>{const m=a.split(" ").filter(A=>A.length>0),d=i.commandDescriptors.get(a),g=ve(e,m),f=i.commandFlagHelp.get(a),E=d?Qn(d):null;if(g){fi(g,d,f,E);return}const C=or(e,m);d?.description&&C.description(d.description);let _=f;d&&(Jn(C,d),d.flags.length>0&&(vo(C,d.flags),_=Ro(C,d.flags)??void 0)),hi(C,_,d,E),C.allowUnknownOption(!0).allowExcessArguments(!0).action(async(...A)=>{const b=A[A.length-1],w=b instanceof ae?b:C,V=J(w),At=Date.now(),se=Q(i.registrations,a,w.args.map(String)),Ge=B(w,w.args.map(String),se,Me(w,a,se)),Ue=await st(w,Ge,V,se);await gr(V,Ue),eo(Ue,{...V,command:a,commandArgs:w.args.map(String),commandOptions:Ge,pmRoot:n}),V.profile&&y(`profile:command=${a} took_ms=${Date.now()-At}`)})};for(const a of c)l(a);dt(e,u,i.commandDescriptors)}const N=_n(import.meta.url,["../.."])??"0.0.0";let p=qe(N);async function ut(e){if(!x)return;const o=Reflect.get(e,Wo);typeof o=="string"&&await Nn(o)}async function pt(e,o,t){const n=H(e);return["item mutate","item complete"].includes(n)&&e.optsWithGlobals().dryRun===!0?o:t()}async function gt(e,o,t){!x||!await Ze(!0)||(io(e,o,t,{source_context:x.source_context,source_context_source:x.source_context_source}),On(e),Z=x)}async function ie(e,o,t){const n=Z;if(!n)return;Z=null;let r=!1;try{const s=await I(n.global_pm_root);r=s.telemetry.enabled&&s.telemetry.installation_id===n.installation_id}catch{}await Ze(r)?kn(e,o,t):An()}async function yi(e){const o=await nt(e);return so(o?.registrations??null),o}function ft(e,o){o&&xe(o)||(e.hook("preAction",async(t,n)=>{F=null,x=null,Z=null,le(),ko(n);const r=n.optsWithGlobals(),s=J(n),i=ce(H(n));let c=n.args.map(String);const u={args:[...c],path:s.path};let l=B(n,c),a={...s};const m=R(process.cwd(),s.path),d=await yi(n);if(on(i,{...l,...Jt(i,n.processedArgs),outputInclude:r.outputInclude,outputLimit:r.outputLimit,outputBudget:r.outputBudget,outputFormat:r.outputFormat,outputSession:r.outputSession,outputCursor:r.outputCursor}),Do(n,i,a,l),await pt(n,void 0,()=>fn(i,a)),!d){F=sn({commandName:i,commandArgs:c,commandOptions:l,globalOptions:a,pmRoot:m}),x=await ao({command:i,pm_version:N,args:c,options:l,global:a,pm_root:m}),await ut(e),await gt(i,c,l),await So(i,l,m,Fe()),await Ao(i,c,l,a,m),await Be({command:n,commandPath:i,commandArgs:c,commandOptions:l,expectHash:s.expectHash,pmRoot:m,globalOptions:a});return}Tn(d.hooks),Fn(d.commands),Dn(d.parsers),In(d.preflight),O(d.services),Hn(d.renderers),so(d.registrations);const g=Q(d.registrations,i,c);l=B(n,c,g,Me(n,i,g)),Do(n,i,a,l);const f=await ue({command:i,args:c,options:l,global:a,pm_root:d.pmRoot});a.profile&&f.warnings.length>0&&y(`profile:extensions parser_warnings=${S(f.warnings)}`),c=f.context.args,l=f.context.options,Re(n,l),a=f.context.global;const E={args:[...c],path:a.path};we(n,l);const C=await En({command:i,args:c,options:l,global:a,pm_root:d.pmRoot,decision:Fe()});a.profile&&C.warnings.length>0&&y(`profile:extensions preflight_warnings=${S(C.warnings)}`),c=C.context.args,l=C.context.options,Re(n,l),a=C.context.global,we(n,l);const _=C.decision;await So(i,l,d.pmRoot,_),await Ao(i,c,l,a,d.pmRoot),await Be({command:n,commandPath:i,commandArgs:u.args,commandOptions:l,expectHash:s.expectHash,pmRoot:d.pmRoot,rewritten:Ot(u,[E,{args:c,path:a.path}]),globalOptions:{...a,path:s.path,noExtensions:s.noExtensions}});const A=_.run_extension_migrations?await pt(n,[],()=>rt(d.registrations.migrations,d.pmRoot)):[];a.profile&&A.length>0&&y(`profile:extensions migration_warnings=${S(A)}`);const b=mr(d.registrations.migrations);F={hooks:d.hooks,commandName:i,commandArgs:c,commandOptions:{...l},globalOptions:{...a},pmRoot:d.pmRoot,profileEnabled:!!a.profile,migrationBlockers:b},L(void 0),ge({command:i,args:c,options:{...l},global:{...a},pm_root:d.pmRoot}),x=await ao({command:i,pm_version:N,args:c,options:l,global:a,pm_root:d.pmRoot}),await ut(e),await gt(i,c,l);const w=await xn(d.hooks,{command:i,args:c,options:{...l},global:{...a},pm_root:d.pmRoot});a.profile&&w.length>0&&y(`profile:extensions hook_warnings=${S(w)}`),_.enforce_mandatory_migration_gate&&ur(i,l,b)}),e.hook("postAction",async()=>{const t=Lo();await ie(t.ok,t.error,{error_code:t.error_code,error_category:t.error_category,exit_code:t.exit_code,command_resolution:t.command_resolution,resolution_stage:t.resolution_stage}),await q(t),await U()}))}ft(p);const ht=Symbol("pmCliIdempotentTopLevelRegistration");function yt(e){const o=e;if(o[ht])return;o[ht]=!0;const t=e.command.bind(e);e.command=((n,...r)=>{const s=n.split(/\s+/u)[0];return e.commands.some(i=>i.name()===s||i.aliases().includes(s))?new ae(s):t(n,...r)})}async function Ci(e,o){if(yt(e),o.setup){const{registerSetupCommands:t}=await ei();t(e)}if(o.listQuery){const{registerListQueryCommands:t}=await oi(),n=typeof o.targetCommandName=="string"&&Nr.has(o.targetCommandName)?new Set([o.targetCommandName]):void 0;t(e,n?{commandFilter:n}:void 0)}if(o.mutation){const{registerMutationCommands:t}=await ti();t(e,{targetCommandName:o.targetCommandName})}if(o.operation){const{registerOperationCommands:t}=await ni();t(e)}}function $(e){return e.rawInvocationArgv??e.invocationArgv}function _i(e){return async o=>{const t=wn(o.errorCode),n=cn({ok:!1,errorCode:o.errorCode,errorCategory:t});return await dn({command:o.command,args:e.invocationArgv,options:o.options,global:e.bootstrapGlobal,pm_version:N,pm_root:e.bootstrapPmRoot,error_code:o.errorCode,error_message:o.errorMessage,exit_code:o.exitCode,error_category:t,command_resolution:n,resolution_stage:o.resolutionStage}),{errorCategory:t,commandResolution:n}}}async function Ct(e){if(e.bootstrapGlobal.noExtensions||xe(e.invocationArgv))return;const o=j(e.invocationArgv),t=await ne(e.bootstrapPmRoot);if(t&&Y(t.discovery,o)){const n=await M(e.bootstrapPmRoot,o);_t(n);return}t&&te(Te(e.invocationArgv),t,o),O({overrides:[]})}function _t(e){if(!e){O({overrides:[]});return}O(e.services)}async function Ne(e){await ie(!1,e.errorMessage,{error_code:e.classificationCode,error_category:e.errorCategory,exit_code:e.exitCode,command_resolution:e.commandResolution,resolution_stage:e.resolutionStage}),await q({ok:!1,error:e.errorMessage,exit_code:e.exitCode,error_code:e.classificationCode,error_category:e.errorCategory,command_resolution:e.commandResolution,resolution_stage:e.resolutionStage})}async function vt(){await ie(!0,void 0,{exit_code:h.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),await q({ok:!0,exit_code:h.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),process.exitCode=h.SUCCESS}async function wt(e,o){const t=typeof o=="number"&&Number.isFinite(o);if(!(e.error instanceof G)&&(Ve(e.error)||!t))return!1;const n=Qe(D(e.error)),r=e.error instanceof G?e.error.exitCode:Ke(o),s=e.error instanceof G||$t(e.error)?e.error.context:void 0,i=qo(s,e.invocationArgv,n),c=Bn(n,i),u=Le(e.bootstrapGlobal.lean?Kn(_o(n,r,i)):_o(n,r,i)),l=e.jsonErrors?JSON.stringify(e.bootstrapGlobal.tokenAccounting?en(u,g=>`${JSON.stringify(g,null,2)}
|
|
2
|
-
`):u,null,2):
|
|
3
|
-
`):y(l);const{errorCategory:a,commandResolution:m}=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:c.code,errorMessage:c.detail,exitCode:r,options:{bootstrap_global_options:e.bootstrapGlobal},resolutionStage:"execute"}),d=await oe({command:e.attemptedCommand,error_code:c.code,error_category:a,exit_code:r,error_message:c.detail,command_resolution:m,resolution_stage:"execute",source_context:x?.source_context},e.bootstrapGlobal);return await Ne({errorMessage:n,exitCode:r,classificationCode:c.code,errorCategory:a,commandResolution:m,resolutionStage:"execute"}),d&&(ro(Ye(e.error,n)),await U(Se)),process.exitCode=r,!0}async function Et(e,o){const t=Ce(e.invocationArgv).commandPathTokens.join(" ")||yo(e.invocationArgv),n=ce(t),r=`unknown command '${t}'`,s=R(process.cwd(),e.bootstrapGlobal.path),i=e.bootstrapGlobal.noExtensions?v:await He(s),c=j(e.invocationArgv),u=e.bootstrapGlobal.noExtensions?[]:await
|
|
4
|
-
`):y(E),g&&await U(Se),process.exitCode=h.USAGE}async function Rt(e,o,t){if(!(o==="commander.helpDisplayed"||o==="commander.help"||o==="commander.helpCommand")&&!t.includes("(outputHelp)"))return!1;const r=Ce(e.invocationArgv);return r.requested&&!_e(p,r.commandPathTokens)?(await Et(e,o),!0):(await vt(),!0)}async function xt(e,o){const t=await ho(e.error,p,v,{},$(e)),n=Co(t.message,t.commandName,t.allowedTypes,{unknownCommandExamples:t.unknownCommandExamples,unknownCommandNextSteps:t.unknownCommandNextSteps,attemptedCommand:t.attemptedCommand,normalizedInvocationArgs:t.normalizedInvocationArgs,providedOptionFlags:t.providedOptionFlags,unknownOptionSuggestions:t.unknownOptionSuggestions,suggestedRetryCommand:t.suggestedRetryCommand}),{errorCategory:r,commandResolution:s}=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:n.code,errorMessage:n.detail,exitCode:h.USAGE,options:{bootstrap_global_options:e.bootstrapGlobal,commander_code:o},resolutionStage:"parse"}),i=await oe({command:e.attemptedCommand,error_code:n.code,error_category:r,exit_code:h.USAGE,error_message:n.detail,command_resolution:s,resolution_stage:"parse",source_context:x?.source_context},e.bootstrapGlobal),c=e.jsonErrors?await go(e.error,p,v,e.bootstrapGlobal.lean===!0,{},$(e)):await fo(e.error,p,v,{},$(e)),u=await
|
|
5
|
-
`):y(l),i&&await U(Se),process.exitCode=h.USAGE}function bt(e){if(typeof e!="object"||e===null||!("code"in e))return!1;const o=e.code;return typeof o=="string"&&(o==="commander.version"||o.startsWith("commander."))?!0:String(e.message??"").includes("(outputHelp)")}async function St(e){const o=e.error.code,t=String(e.error.message??"");if(!await Rt(e,o,t)){if(o==="commander.version"){await vt();return}await xt(e,o)}}async function $e(e){const o=k(e.invocationArgv),t=R(process.cwd(),o.path),n=jt(e.invocationArgv),r={error:e.error,invocationArgv:n,rawInvocationArgv:e.invocationArgv,bootstrapGlobal:o,jsonErrors:o.json,bootstrapPmRoot:t,attemptedCommand:ye(n)??"<unknown>",emitTelemetryCommandError:
|
|
1
|
+
import{attachPreflightWarnings as Le,attachSerializedPreflightWarnings as We,emitPreflightWarning as kt,runWithPreflightWarnings as Pt}from"./preflight-warnings.js";import{assertGuardedDispatchUnchanged as je,bindInvocationExpectedRevisions as Be,invocationRewritten as Ot,parseWithInvocationRevisionScope as Ft,refuseInventoryExpectHash as Tt}from"./expected-revisions.js";import{Command as ae,CommanderError as ze}from"commander";import{PM_COMMAND_ALIAS_CONTRACTS as Dt,findPmNamespacedCommand as It,resolvePmCommandOperation as ce}from"../sdk/cli-contracts/command-aliases.js";import{createPmCliProgram as qe}from"../sdk/cli-program.js";import{runWithDiscoveredContextIntentContracts as Ht}from"../sdk/context-intent-runtime.js";import{createExtensionCommandError as Mt,describeUnknownError as D,isCommanderError as Ve,normalizeThrownExitCode as Ke,readThrownExitCode as Je,wrapThrownErrorForSentry as Ye}from"../sdk/error-runtime.js";import{createExtensionCommandSdk as Nt}from"../sdk/extension-command-context.js";import{isPmCliExpectedError as $t,snapshotPmCliErrorContext as Gt}from"../sdk/errors.js";import{runExtensionMigrations as Ut}from"../sdk/extension/migrations.js";import{repairProjectionRecovery as Lt}from"./runtime/projection-retry.js";import{repairReadOutputMutationRecovery as Wt}from"./runtime/read-output-mutation-retry.js";import{redactRefusalArgv as jt}from"./runtime/refusal-credential-redaction.js";import{redactUrlCredentialsInText as Qe,runWithUrlCredentialInvocation as Bt}from"../sdk/command-line.js";import{isTrackerRevisionGuarded as zt}from"../sdk/lifecycle/item-revision.js";import{repairSchemaFieldRecovery as qt}from"./runtime/field-route-retry.js";import{isRegistrableFieldFlagSpelling as Vt}from"../sdk/schema/field-flag-spelling.js";import{ANNOTATION_OPTION_REFUSAL_CODE as Kt,repairAnnotationOptionRecovery as Jt}from"./runtime/annotation-option-retry.js";import{CLOSE_FIELDS_REFUSAL_CODE as Yt,repairCloseFieldsRecovery as Qt}from"./runtime/close-fields-retry.js";import{resolvePmCommandScopeArgs as Xt}from"../sdk/command-line.js";import{applyInvocationAuthorOverride as Zt}from"../sdk/invocation-author.js";import{attachOutputTokenAccounting as en}from"../sdk/output-token-accounting.js";import{annotationPositionalMutationOptions as on,validateReadOutputOptions as tn}from"../sdk/read-output-contracts.js";import{runWithReproducibleProcessEnvironment as nn}from"../sdk/reproducibility/process.js";import{resolveTelemetrySourceAttribution as Xe,EXIT_CODE as h,PmCliError as G,activateExtensions as rn,clearActiveExtensionHooks as le,consumeAfterCommandAffectedItems as sn,createCoreCommandHookContext as an,createEmptyExtensionRegistrationRegistry as cn,createLazyModule as K,deriveTelemetryCommandResolution as ln,discoverExtensions as dn,emitTelemetryErrorEvent as mn,ensureSentryInit as un,ensureSentryCommandTracing as Ze,getActiveCommandResult as pn,getActiveExtensionRegistrations as gn,getSettingsPath as de,loadExtensions as fn,maybeRunFirstUseTelemetryPrompt as hn,pathExists as me,printError as y,printResult as eo,readSettings as I,readSettingsWithMetadata as oo,resetActiveExtensionRuntimeState as yn,resolveGlobalPmRoot as Cn,resolveItemTypeRegistry as _n,resolvePmCliVersion as vn,resolvePmPackageRootFromModule as wn,resolvePmRoot as R,resolveRuntimeFieldRegistry as to,resolveTelemetryErrorCategory as En,runActiveCommandHandler as no,runActiveParserOverride as ue,runActivePreflightOverride as Rn,runAfterCommandHooks as xn,runBeforeCommandHooks as bn,runWithConfigurationOnlySettings as pe,runWithHarnessDetectionSignals as Sn,runWithWorkspaceHarnessSignalDescriptors as An,sentryCaptureCliError as ro,sentryDiscardCommandSpan as kn,sentryFinishCommandSpan as Pn,sentryFlush as U,sentryLogCliUsageError as On,sentrySetCommandContext as io,sentryStartCommandSpan as Fn,setActiveCommandContext as ge,setActiveCommandResult as L,setActiveExtensionCommands as Tn,setActiveExtensionHooks as Dn,setActiveExtensionParsers as In,setActiveExtensionPreflight as Hn,setActiveExtensionRegistrations as so,setActiveExtensionRenderers as Mn,setActiveExtensionServices as O,startTelemetryCommand as ao,writeStderr as fe}from"../sdk/runtime-primitives.js";import{PmClient as Nn}from"../sdk/runtime.js";import{recordDeprecatedAliasUsage as $n}from"../sdk/telemetry.js";import{finishActiveTelemetryCommand as Gn,recordAfterCommandContextUsage as Un}from"./after-command-context-usage.js";import{extractProvidedOptionFlags as co,normalizeLongOptionFlag as W,redactSensitiveCommandArgs as Ln,renderPmCommand as Wn}from"./argv-utils.js";import{applyBootstrapPagerPolicy as jn,findBootstrapCommandTokenIndex as he,normalizeBootstrapInvocation as lo,parseBootstrapCommandName as ye,parseBootstrapGlobalOptions as k,parseBootstrapHelpRequest as Ce,stripGlobalBootstrapTokens as mo}from"./bootstrap-args.js";import{installCommandNamespaces as uo}from"./command-namespaces.js";import{appendCommanderExtensionFailures as po,formatCommanderUsageJson as go,formatCommanderUsageMessage as fo,isKnownHelpCommandPath as _e,resolveCommanderUsageContext as ho,resolveUnknownCommanderToken as yo}from"./commander-usage.js";import{loadContextIntentSnapshotForInvocation as Bn}from"./context-intent-invocation.js";import{classifyCommanderError as Co,classifyPmCliError as zn,classifyUnknownError as qn,formatPmCliErrorForDisplay as Vn,formatPmCliErrorForJson as _o,formatUnknownErrorForJson as Kn,projectLeanErrorEnvelope as Jn}from"./error-guidance.js";import{applyDynamicExtensionArguments as Yn,applyDynamicExtensionFlagOptions as vo,buildCanonicalExtensionAliases as Qn,buildDynamicExtensionCommandMetadataHelp as Xn,buildExtensionInheritedFlagHelp as wo,isExtensionCreatedCommand as Eo,buildResidualDynamicExtensionFlagHelp as Ro,collectDynamicExtensionFlagHelpByCommand as Zn,collectExtensionCommandHelpDescriptors as er,collectSafeExtensionCommandPaths as or,ensureCommandPath as tr,extensionFlagTakesValueForInvocation as xo,findCommandByPath as ve,normalizeExtensionCommandPath as P,reportExtensionCommandCollision as nr}from"./extension-command-help.js";import{collectLoosePositionalArgs as rr,stripLooseCommandOptionTokens as bo}from"../sdk/extension/command-options.js";import{loadExtensionRecoveryFailures as ir,loadUnknownCommandRecoveryFailures as sr}from"./extension-recovery.js";import{attachRichHelpText as ar,isFullHelpDiscovery as cr,setPmCommandHelpVisibilityTier as lr}from"./help-content.js";import{attachCreateUpdatePolicyHelpText as dr,maybeRenderBootstrapJsonHelp as mr}from"./help-json-payload.js";import{collectMandatoryMigrationBlockers as ur,enforceItemFormatWriteGateAndPreflightMigration as So,enforceMandatoryMigrationWriteGate as pr,enforceMutationGuardPreflight as Ao}from"./migration-gates.js";import{applyDefaultOutputFormat as gr,clearResolvedGlobalOptions as ko,collect as Po,formatHookWarnings as S,getCommandPath as H,getGlobalOptions as J,invalidateSearchCachesForMutation as fr,setResolvedGlobalOptions as hr,syncCommanderActionOptions as we}from"./registration-helpers.js";import{activationCommandMatchesProbe as yr,buildBootstrapActivationProbe as j,buildRuntimeExtensionActivationScope as Oo,buildRuntimeExtensionFilterForProbe as Fo,collectActivationCommandCandidates as Ee,collectLeadingCommandArgs as Cr,collectParsedActivationCommandArgs as To,commandPathNeedsSearchExtensions as _r,commandPathNeedsTemplateExtensions as vr,discoveryNeedsActivationForProbe as Y,extensionActivationCommands as wr,extensionCapabilities as Er,extensionNeedsActivationForProbe as Rr,extensionProvidesTemplatesRuntime as xr,hasAnyCapability as br,hasGlobalExtensionContributions as Sr,matchesStaticExtensionCommand as Ar,probeUsesAnyFlag as kr,resolveStaticExtensionActivationDecision as Pr}from"./runtime/activation.js";import{captureCommandOptionTokens as Or,refuseConflictingCommandOptionSpellings as Fr,resolveExtensionCommandRefusalListing as Tr,collectExtensionFlagDefinitionsForCommand as Dr,collectExtensionFlagDefinitionsForInvocation as Q,copyReadOutputInvocationProvenance as Re,dynamicCommandArguments as Ir,extractCommandScopedOptions as B,forwardReadOutputIncludeModes as Do,isImporterOrExporterCommandPath as Io,recordCliReadOutputInvocationProvenance as Hr,refuseUndeclaredRootOnlyOptions as Mr,validateDynamicExtensionCommandArgs as Nr,validateDynamicExtensionCommandInvocation as Ho}from"./runtime/invocation-options.js";import{LIST_QUERY_COMMAND_NAMES as $r,enforceExplicitRetryForFlagTypos as Mo,invocationRequestsVersion as Gr,isStaticExtensionInventoryInvocation as xe,resolveStructuredMutationPreviewInvocation as Ur,resolveCoreCommandRegistrationSelection as No,shouldAttachRichHelpTextForInvocation as $o,shouldRegisterDynamicExtensionPaths as Go,shouldRegisterRuntimeSchemaFlags as Uo}from"./runtime/selection.js";import{recordInvocationPromotions as Lr}from"./runtime/invocation-rewrites.js";import{buildPostActionTelemetryOutcome as Lo,inferPostActionErrorCode as Wr,inferPostActionFailureMessage as jr,normalizeTelemetryCommandResolution as Br,normalizeTelemetryErrorCategory as zr,normalizeTelemetryResolutionStage as qr,readRecordBoolean as Vr,readRecordNumber as Kr,readRecordString as Jr}from"./runtime/telemetry-outcome.js";const be="PM_CLI_PACKAGE_ROOT",Wo=Symbol("pm.deprecatedAliasInvocation"),X=new Map;for(const e of Dt){const o=e.alias.split(" ")[0],t=X.get(o)??[];t.push(e),X.set(o,t)}for(const e of X.values())e.sort((o,t)=>t.alias.split(" ").length-o.alias.split(" ").length);function Yr(){return wn(import.meta.url,["../.."])}(typeof process.env[be]!="string"||process.env[be]?.trim().length===0)&&(process.env[be]=Yr());let F=null,x=null,Z=null;function Qr(e){F=e}function Xr(e){v=e}let z=null,T=null,v=new Map;const Se=250,Zr=new Set([h.USAGE,h.NOT_FOUND,h.CONFLICT]),ei=new Set(["1","true","yes","on"]),oi=K(()=>import("./register-setup.js")),ti=K(()=>import("./register-list-query.js")),ni=K(()=>import("./register-mutation.js")),ri=K(()=>import("./register-operations.js"));function ee(e){return Wn(e)}function jo(e){const o=e.match(/--[a-zA-Z0-9][a-zA-Z0-9_-]*/g);if(!o||o.length===0)return;const t=[...new Set(o.map(n=>W(n)??n))];return t.length>0?t:void 0}function ii(e,o,t,n){if(t?.suggested_retry||n===Yt||n===Kt||e.includes("failed in extension handler (")||!/\b(?:missing|required|requires)\b/i.test(e))return;const r=co(o),s=new Set(r.map(m=>W(m)??m)),i=jo(e),c=o.find(m=>p.commands.some(d=>d.name()===m)),u=c?p.commands.find(m=>m.name()===c):void 0,l=new Set([...p.options,...u?.options??[]].flatMap(m=>m.flags.split(/[ ,|]+/).map(d=>W(d)).filter(d=>d!==void 0))),a=i?.filter(m=>{const d=W(m)??m;return s.has(d)?!1:l.has(d)||xo(o,c,d,v)!==void 0});return a&&a.length>0?a:void 0}function si(e,o,t,n){if(n?.suggested_retry)return n.suggested_retry;const r=t?.[0],s=r?W(r):void 0,i=e.find(d=>p.commands.some(g=>g.name()===d)),c=i?p.commands.find(d=>d.name()===i):void 0,u=s?c?.options.find(d=>d.flags.split(/[ ,|]+/).includes(s)):void 0,l=xo(e,i,s,v),a=s?u?.isBoolean()===!0||l===!1?[s]:[s,"<value>"]:[],m=s?ee([...e,...a]):o;return m===o?void 0:m}function ai(e){if(!e)return{};const o=["recovery_mode","missing_required_fields","suggested_flags","suggested_retry_args","allowed_values","candidate_commands","candidate_commands_total","candidate_commands_truncated","fallback_candidates","next_best_command"],t={};for(const n of o){const r=e[n];r!==void 0&&(n==="allowed_values"||r!==null)&&(t[n]=r)}return t}function ci(e){const o=e.existingRecovery;return{attempted_command:o?.attempted_command??e.attemptedCommand,normalized_args:o?.normalized_args??[...e.invocationArgv],provided_fields:o?.provided_fields??(e.providedFields.length>0?e.providedFields:void 0),missing:o?.missing??e.inferredMissing,...ai(o),...e.suggestedRetry?{suggested_retry:e.suggestedRetry}:{}}}function Bo(e,o){return{...e,recovery:o}}function li(e,o){if(o===void 0)return;const t=qt(e,o.code,o.field,Lt(e,o.code,o.recovery)),n=di(e),r=Jt(e,o.code,o.field,t,n),s=Wt(e,o.code,r,n,()=>zt(R(process.cwd(),k(e).path)));return Qt(e,o.code,s,n)}const zo=" ";function di(e){const o=e.map(r=>r===""?zo:/^--(?:pm-)?path=$/u.test(r)?`${r}${zo}`:r),t=k(o).path;if(t!==void 0&&t.trim()!=="")return[];const n=Xt({});return t!==void 0&&n.length>0?null:n}function qo(e,o,t){const n=Ln(o),r=mo(n),s=he(r),[i,c]=s===void 0?[]:r.slice(s,s+2),u=n.includes("--explain");e=e===void 0?void 0:Gt(e);const l=li(n,e),a=l&&(i==="history-redact"||i==="history"&&c==="redact")?{...l,...l.attempted_command?{attempted_command:ee(n)}:{},...l.normalized_args?{normalized_args:[...n]}:{},...l.suggested_retry?{suggested_retry:ee(n)}:{},...l.suggested_retry_args?{suggested_retry_args:[...n]}:{}}:l;if(a?.recovery_mode==="compact"&&!u)return Bo(e,a);const m=ee(n),d=co(n),g=ii(t,n,a,e?.code),f=si(n,m,g,a),E=ci({invocationArgv:n,attemptedCommand:m,providedFields:d,inferredMissing:g,suggestedRetry:f,existingRecovery:a});return Bo(e,E)}async function q(e){const o=x;x=null,await Gn(o,e);const t=F;if(F=null,!t){le();return}let n=[];const r=sn();try{await Un({pmRoot:t.pmRoot,author:t.globalOptions.author,itemIds:e.ok?r?.map(s=>s.id)??[]:[],intent:t.commandName})}catch{n.push("context_usage_feedback_write_failed")}try{n.push(...await xn(t.hooks,{command:t.commandName,args:t.commandArgs,options:{...t.commandOptions},global:{...t.globalOptions},pm_root:t.pmRoot,ok:e.ok,error:e.error,result:pn(),affected:r}))}catch(s){n=[`afterCommand hooks failed: ${s instanceof Error?s.message:String(s)}`]}finally{le()}!t.globalOptions.json&&n.length>0&&y(`[pm] warning: afterCommand hook_warnings=${S(n)}`),t.profileEnabled&&n.length>0&&y(`profile:extensions hook_warnings=${S(n)}`)}async function Vo(e,o){await un();const t=x,n=F,r=t?.command??n?.commandName??e,s=t??Xe(n?.globalOptions??o),i=v.get(P(r))?.source;io(r,n?.commandArgs??[],{...n?.commandOptions,...n?.globalOptions},{source_context:s.source_context,source_context_source:s.source_context_source,pm_version:t?.pm_version??N,extension:i})}function Ko(e){return ei.has((process.env[e]??"").trim().toLowerCase())}function Jo(e){return Ko("PM_SENTRY_CAPTURE_EXPECTED_ERRORS")?!0:!Zr.has(Math.trunc(e))}async function oe(e,o){return Jo(e.exit_code)?(await Vo(e.command,o),On({...e,source_context:e.source_context??Xe(o).source_context}),!0):!1}async function Yo(e){const o=Qe(D(e.error)),t=qn(o);e.bootstrapGlobal.json?y(JSON.stringify(Le(Kn(o,h.GENERIC_FAILURE)),null,2)):y(o),process.exitCode=h.GENERIC_FAILURE;let n="runtime",r="runtime_failed";try{await Vo(e.attemptedCommand,e.bootstrapGlobal),ro(e.error);const s=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:t.code,errorMessage:t.detail,exitCode:h.GENERIC_FAILURE,options:{bootstrap_global_options:e.bootstrapGlobal},resolutionStage:"execute"});n=s.errorCategory,r=s.commandResolution,await ie(!1,o,{error_code:t.code,error_category:n,exit_code:h.GENERIC_FAILURE,command_resolution:r,resolution_stage:"execute"})}catch(s){e.bootstrapGlobal.json||y(`Failed to report error: ${D(s)}`)}try{await q({ok:!1,error:o,exit_code:h.GENERIC_FAILURE,error_code:t.code,error_category:n,command_resolution:r,resolution_stage:"execute"})}catch(s){e.bootstrapGlobal.json||y(`Failed to run error hooks: ${D(s)}`)}try{await U()}catch(s){e.bootstrapGlobal.json||y(`Failed to flush error reporting: ${D(s)}`)}}const mi={create:"create",update:"update","update-many":"update_many",list:"list","list-all":"list","list-draft":"list","list-open":"list","list-in-progress":"list","list-blocked":"list","list-closed":"list","list-canceled":"list",search:"search",calendar:"calendar",context:"context","templates save":"create"},Ae=new Map;function ke(e){return e==="number"?"number":e==="boolean"?"boolean":"string"}function Qo(e,o){return e.options.some(t=>t.long===o)}function Xo(e,o){return e.options.some(t=>t.short===o)}function Pe(e,o,t,n){const r=o.trim();if(!r||!Vt(r))return;const s=t.length>0?t:`Runtime schema field (${o})`;if(r.startsWith("-")&&!r.startsWith("--")){if(Xo(e,r))return;if(n){e.option(`${r} <value>`,`${s} (repeatable)`,Po);return}e.option(`${r} <value>`,s);return}const i=r.startsWith("--")?r:`--${r}`;if(!Qo(e,i)){if(n){e.option(`${i} <value>`,`${s} (repeatable)`,Po);return}e.option(`${i} <value>`,s)}}async function Zo(e,o){const t=mi[e];if(!t)return[];const n=`${o}:${t}`,r=Ae.get(n);if(r)return r;if(!await me(de(o)))return Ae.set(n,[]),[];const s=await I(o),c=(to(s.schema).command_to_fields.get(t)??[]).flatMap(u=>[u.cli_flag,...u.cli_aliases].map(a=>({long:`--${a}`,type:ke(u.type),value_type:ke(u.type)})));return Ae.set(n,c),c}async function et(e,o){const t=k(o),n=R(process.cwd(),t.path);if(!await me(de(n)))return;const r=T?.key===De(n)?T.snapshot:null,s=r===null?await I(n):r.settings,i=to(s.schema),c=[{path:"create",command:"create"},{path:"update",command:"update"},{path:"update-many",command:"update_many"},{path:"list",command:"list"},{path:"list-all",command:"list"},{path:"list-draft",command:"list"},{path:"list-open",command:"list"},{path:"list-in-progress",command:"list"},{path:"list-blocked",command:"list"},{path:"list-closed",command:"list"},{path:"list-canceled",command:"list"},{path:"search",command:"search"},{path:"calendar",command:"calendar"},{path:"context",command:"context"},{path:"templates save",command:"create"}];for(const u of c){const l=ve(e,u.path.split(" "));if(l)for(const a of i.command_to_fields.get(u.command)??[]){const m=a.description??"";Pe(l,a.cli_flag,m,a.repeatable);for(const d of a.cli_aliases)Pe(l,d,`Alias for --${a.cli_flag}`,a.repeatable)}}}async function Oe(e,o,t,n,r){const s=ye(t);if(!(s!=="create"&&s!=="update"))try{const i=r??await I(o),c=_n(i,n);dr(e,c,t)}catch{}}function Fe(){return{enforce_item_format_gate:!0,run_preflight_item_format_sync:!0,run_extension_migrations:!0,enforce_mandatory_migration_gate:!0}}function ot(e,o="all"){return o==="all"?`pm-root:${e}`:`pm-root:${e}:activation:${o}`}function Te(e){return e.some(o=>o==="--profile")}function De(e){return`pm-root:${e}`}function Ie(e){for(const o of e)o.startsWith("settings_read_")&&kt(o,`[pm] warning: ${o} \u2014 settings.json could not be loaded and pm fell back to defaults; run pm health for remediation.`)}function tt(e,o){e.profile&&(y(`profile:extensions loaded=${o.loadedCount} failed=${o.loadFailedCount} warnings=${o.loadWarnings.length} activation_failed=${o.activationFailedCount} hook_counts=before:${o.hooks.beforeCommand.length}|after:${o.hooks.afterCommand.length}|write:${o.hooks.onWrite.length}|read:${o.hooks.onRead.length}|index:${o.hooks.onIndex.length} command_overrides=${o.commands.overrides.length} command_handlers=${o.commands.handlers.length} parser_overrides=${o.parsers.overrides.length} preflight_overrides=${o.preflight.overrides.length} service_overrides=${o.services.overrides.length} renderer_overrides=${o.renderers.overrides.length}`),o.activationWarnings.length>0&&y(`profile:extensions activation_warnings=${S(o.activationWarnings)}`))}function te(e,o,t){if(!e)return;const n=P(t.commandPath??"")||"<none>";y(`profile:extensions activation=skipped command=${n} effective=${o.discovery.effective.length} warnings=${o.discovery.warnings.length} discovery_ms=${o.discoveryMs}`)}async function ne(e,o=oo){const t=De(e);if(T?.key===t)return T.snapshot;try{const n=Date.now(),{settings:r,warnings:s}=await o(e),i=await dn({pmRoot:e,settings:r,cwd:process.cwd(),noExtensions:!1}),c={pmRoot:e,settings:r,discovery:i,discoveryMs:Date.now()-n,settingsReadWarnings:[...s]};return T={key:t,snapshot:c},c}catch{return T={key:t,snapshot:null},null}}async function M(e,o,t=I){const n=o?Oo(o):"all",r=ot(e,n);if(z?.key===r)return z.snapshot;try{const s=await t(e),i=await fn({pmRoot:e,settings:s,cwd:process.cwd(),noExtensions:!1,extensionFilter:o?Fo(o):void 0}),c=await rn({...i,loaded:i.loaded}),u=[...new Set(c.commands.handlers.map(g=>P(g.command)))].filter(g=>g.length>0).sort((g,f)=>g.localeCompare(f)),l=Zn(c.registrations.flags),a=Qn(c.commands.handlers,c.registrations.commands),m=er(u,c.registrations.commands,c.registrations.flags,a),d={hooks:c.hooks,commands:c.commands,parsers:c.parsers,preflight:c.preflight,services:c.services,renderers:c.renderers,registrations:c.registrations,pmRoot:e,settings:s,commandHandlers:u,commandFlagHelp:l,commandDescriptors:m,commandAliases:a,loadWarnings:[...i.warnings],activationWarnings:[...c.warnings],loadedCount:i.loaded.length,loadFailedCount:i.failed.length,activationFailedCount:c.failed.length,contextIntentPackages:i.loaded.map(({name:g,module:f})=>({name:g,module:f}))};return z={key:r,snapshot:d},d}catch{return z={key:r,snapshot:null},null}}async function nt(e){const o=J(e);if(o.noExtensions){const i=R(process.cwd(),o.path);return await me(de(i))&&Ie((await oo(i)).warnings),null}const t=R(process.cwd(),o.path),n=await ne(t);if(!n)return null;Ie(n.settingsReadWarnings);const r={commandPath:H(e),commandArgs:To(e)};if(!Y(n.discovery,r))return te(o.profile,n,r),null;const s=await M(t,r);return s?(tt(o,s),{hooks:s.hooks,commands:s.commands,parsers:s.parsers,preflight:s.preflight,services:s.services,renderers:s.renderers,registrations:s.registrations,pmRoot:t}):null}async function He(e){const o=await M(e);return o?new Map(o.commandDescriptors):v}async function ui(e,o){return!e.requested||o.noExtensions||_e(p,e.commandPathTokens)?v:He(R(process.cwd(),o.path))}async function rt(e,o){return(await Ut({pmRoot:o,migrations:e,author:"pm-extension-migration"})).migrations.filter(n=>n.outcome==="failed").map(n=>`extension_migration_failed:${n.layer}:${n.extension}:${n.id}`)}function it(e,o,t){const n=o.author;return Nt(e,Nn.forActiveExtensionHost({pmRoot:e,author:n}),n,P(t))}async function st(e,o,t,n=[]){const r=H(e);let s=bo(e.args.map(String),n),i={...o};delete i.author;let c={...t};const u=R(process.cwd(),t.path),l={args:[...s],path:t.path},a=await ue({command:r,args:s,options:i,global:c,pm_root:u});t.profile&&a.warnings.length>0&&y(`profile:extensions parser_warnings=${S(a.warnings)}`),s=a.context.args,i=a.context.options,c=a.context.global,je(l,{args:s,path:c.path},i),Ho(v.get(P(r)),s,i,n),L(void 0),ge({command:r,args:s,options:{...i},global:{...c},pm_root:u});const m=await no({command:r,args:s,options:i,global:c,pm_root:u,sdk:it(u,c,r)});if(c.profile&&m.warnings.length>0&&y(`profile:extensions command_handler_warnings=${S(m.warnings)}`),!m.handled)throw m.warnings.length>0?Mt(r,m):new G(`Command "${r}" is provided by extensions and is not currently available.`,h.NOT_FOUND);return m.exitCode!==void 0&&(process.exitCode=m.exitCode),L(m.result),m.result}const at=Symbol("pm.wrappedActionHandler");function pi(e,o){const t=e[e.length-1];return t instanceof ae?t:o}function ct(e,o,t){e&&t.length>0&&y(`profile:extensions ${o}=${S(t)}`)}function gi(e){const o=v.get(P(e.commandPath));if(!o||!Io(e.activeRegistrations,e.commandPath))return;const t=Ir(o).length===0?rr(e.commandArgs):bo(e.commandArgs,e.extensionFlagDefinitions);Nr(o,t)}function fi(e,o,t){e.args=[...t],"_processArguments"in e&&typeof e._processArguments=="function"&&e._processArguments(),o.length>0&&Array.isArray(o[0])&&(o[0]=[...e.processedArgs])}function Me(e,o,t){if(!Eo(e))return;const n=v.get(P(o))?.read_output_declared===!0;return Tr(t,n)}function lt(e){const o=t=>{const n=t;if(Or(t),typeof n._actionHandler=="function"&&n[at]!==!0){const r=n._actionHandler;n._actionHandler=async function(...i){const c=pi(i,t),u=Date.now();ko(c);let l=J(c);const a=ce(H(c));if(["package inventory","packages inventory","extension inventory"].includes(a))return Tt(a,l.expectHash),await r.apply(this,i);const m=R(process.cwd(),l.path);let d=c.args.map(String);const g=gn(),f=g?Q(g,a,d):[],E=await Zo(a,m),C=Me(c,a,f);let _=B(c,d,[...f,...E],C);Fr(c,f,a),v.has(P(a))&&delete _.author,C!==void 0&&Mr(_,f,a);const A={args:[...d],path:l.path},b=await ue({command:a,args:d,options:_,global:l,pm_root:m});ct(l.profile,"parser_warnings",b.warnings),d=b.context.args,_=b.context.options,Re(c,_),l=b.context.global,je(A,{args:d,path:l.path},_),gi({activeRegistrations:g,commandPath:a,commandArgs:d,extensionFlagDefinitions:f}),l=await gr(l),hr(c,l),fi(c,i,d),we(c,_),L(void 0),ge({command:a,args:d,options:{..._},global:{...l},pm_root:m});const w=await no({command:a,args:d,options:_,global:l,pm_root:m,sdk:it(m,l,a)});if(ct(l.profile,"command_handler_warnings",w.warnings),w.handled){L(w.result),eo(w.result,{...l,command:a,commandArgs:d,commandOptions:_,pmRoot:m}),l.profile&&y(`profile:command=${a} took_ms=${Date.now()-u}`);return}return await r.apply(this,i)},n[at]=!0}for(const r of t.commands)o(r)};o(e)}async function re(e){v=new Map,O({overrides:[]}),e&&await Oe(e.rootProgram,e.pmRoot,e.invocationArgv,cn(),e.settings)}function hi(e,o,t,n){if(o?.flags&&o.flags.length>0){vo(e,o.flags);const r=Ro(e,o.flags);r&&e.addHelpText("after",r)}else t&&e.addHelpText("after",t);o&&Eo(e)&&e.addHelpText("after",wo(o)),n&&e.addHelpText("after",n)}function yi(e,o,t,n){o&&e.addHelpText("after",o),t&&e.addHelpText("after",wo(t)),n&&e.addHelpText("after",n)}function dt(e,o,t){const n={core:0,standard:1,full:2,internal:3},r=(s,i)=>{const c=i.join(" "),u=[...t.entries()].filter(([a])=>a===c||a.startsWith(`${c} `)).map(([,a])=>a),l=u.length===0?"standard":u.reduce((a,m)=>n[m.tier]<n[a]?m.tier:a,"internal");lr(s,l);for(const a of s.commands)r(a,[...i,a.name()])};for(const s of e.commands)o.has(s.name())||r(s,[s.name()])}async function mt(e,o){const t=k(o),n=R(process.cwd(),t.path);if(t.noExtensions){await re({rootProgram:e,pmRoot:n,invocationArgv:o});return}const r=await ne(n),s=j(o);if(!r){await re();return}if(!Y(r.discovery,s)){await re({rootProgram:e,pmRoot:n,invocationArgv:o,settings:r.settings}),te(Te(o),r,s);return}const i=await M(n,s);if(!i){await re({rootProgram:e,pmRoot:n,invocationArgv:o,settings:r.settings});return}O(i.services),v=new Map(i.commandDescriptors),await Oe(e,n,o,i.registrations,i.settings);const c=or(e,i.commandHandlers,i.commandDescriptors,i.commandAliases,a=>nr(i.activationWarnings,y,a)),u=new Set(e.commands.map(a=>a.name())),l=a=>{const m=a.split(" ").filter(A=>A.length>0),d=i.commandDescriptors.get(a),g=ve(e,m),f=i.commandFlagHelp.get(a),E=d?Xn(d):null;if(g){hi(g,d,f,E);return}const C=tr(e,m);d?.description&&C.description(d.description);let _=f;d&&(Yn(C,d),d.flags.length>0&&(vo(C,d.flags),_=Ro(C,d.flags)??void 0)),yi(C,_,d,E),C.allowUnknownOption(!0).allowExcessArguments(!0).action(async(...A)=>{const b=A[A.length-1],w=b instanceof ae?b:C,V=J(w),At=Date.now(),se=Q(i.registrations,a,w.args.map(String)),Ge=B(w,w.args.map(String),se,Me(w,a,se)),Ue=await st(w,Ge,V,se);await fr(V,Ue),eo(Ue,{...V,command:a,commandArgs:w.args.map(String),commandOptions:Ge,pmRoot:n}),V.profile&&y(`profile:command=${a} took_ms=${Date.now()-At}`)})};for(const a of c)l(a);dt(e,u,i.commandDescriptors)}const N=vn(import.meta.url,["../.."])??"0.0.0";let p=qe(N);async function ut(e){if(!x)return;const o=Reflect.get(e,Wo);typeof o=="string"&&await $n(o)}async function pt(e,o,t){const n=H(e);return["item mutate","item complete"].includes(n)&&e.optsWithGlobals().dryRun===!0?o:t()}async function gt(e,o,t){!x||!await Ze(!0)||(io(e,o,t,{source_context:x.source_context,source_context_source:x.source_context_source}),Fn(e),Z=x)}async function ie(e,o,t){const n=Z;if(!n)return;Z=null;let r=!1;try{const s=await I(n.global_pm_root);r=s.telemetry.enabled&&s.telemetry.installation_id===n.installation_id}catch{}await Ze(r)?Pn(e,o,t):kn()}async function Ci(e){const o=await nt(e);return so(o?.registrations??null),o}function ft(e,o){o&&xe(o)||(e.hook("preAction",async(t,n)=>{F=null,x=null,Z=null,le(),ko(n);const r=n.optsWithGlobals(),s=J(n),i=ce(H(n));let c=n.args.map(String);const u={args:[...c],path:s.path};let l=B(n,c),a={...s};const m=R(process.cwd(),s.path),d=await Ci(n);if(tn(i,{...l,...on(i,n.processedArgs),outputInclude:r.outputInclude,outputLimit:r.outputLimit,outputBudget:r.outputBudget,outputFormat:r.outputFormat,outputSession:r.outputSession,outputCursor:r.outputCursor}),Do(n,i,a,l),await pt(n,void 0,()=>hn(i,a)),!d){F=an({commandName:i,commandArgs:c,commandOptions:l,globalOptions:a,pmRoot:m}),x=await ao({command:i,pm_version:N,args:c,options:l,global:a,pm_root:m}),await ut(e),await gt(i,c,l),await So(i,l,m,Fe()),await Ao(i,c,l,a,m),await Be({command:n,commandPath:i,commandArgs:c,commandOptions:l,expectHash:s.expectHash,pmRoot:m,globalOptions:a});return}Dn(d.hooks),Tn(d.commands),In(d.parsers),Hn(d.preflight),O(d.services),Mn(d.renderers),so(d.registrations);const g=Q(d.registrations,i,c);l=B(n,c,g,Me(n,i,g)),Do(n,i,a,l);const f=await ue({command:i,args:c,options:l,global:a,pm_root:d.pmRoot});a.profile&&f.warnings.length>0&&y(`profile:extensions parser_warnings=${S(f.warnings)}`),c=f.context.args,l=f.context.options,Re(n,l),a=f.context.global;const E={args:[...c],path:a.path};we(n,l);const C=await Rn({command:i,args:c,options:l,global:a,pm_root:d.pmRoot,decision:Fe()});a.profile&&C.warnings.length>0&&y(`profile:extensions preflight_warnings=${S(C.warnings)}`),c=C.context.args,l=C.context.options,Re(n,l),a=C.context.global,we(n,l);const _=C.decision;await So(i,l,d.pmRoot,_),await Ao(i,c,l,a,d.pmRoot),await Be({command:n,commandPath:i,commandArgs:u.args,commandOptions:l,expectHash:s.expectHash,pmRoot:d.pmRoot,rewritten:Ot(u,[E,{args:c,path:a.path}]),globalOptions:{...a,path:s.path,noExtensions:s.noExtensions}});const A=_.run_extension_migrations?await pt(n,[],()=>rt(d.registrations.migrations,d.pmRoot)):[];a.profile&&A.length>0&&y(`profile:extensions migration_warnings=${S(A)}`);const b=ur(d.registrations.migrations);F={hooks:d.hooks,commandName:i,commandArgs:c,commandOptions:{...l},globalOptions:{...a},pmRoot:d.pmRoot,profileEnabled:!!a.profile,migrationBlockers:b},L(void 0),ge({command:i,args:c,options:{...l},global:{...a},pm_root:d.pmRoot}),x=await ao({command:i,pm_version:N,args:c,options:l,global:a,pm_root:d.pmRoot}),await ut(e),await gt(i,c,l);const w=await bn(d.hooks,{command:i,args:c,options:{...l},global:{...a},pm_root:d.pmRoot});a.profile&&w.length>0&&y(`profile:extensions hook_warnings=${S(w)}`),_.enforce_mandatory_migration_gate&&pr(i,l,b)}),e.hook("postAction",async()=>{const t=Lo();await ie(t.ok,t.error,{error_code:t.error_code,error_category:t.error_category,exit_code:t.exit_code,command_resolution:t.command_resolution,resolution_stage:t.resolution_stage}),await q(t),await U()}))}ft(p);const ht=Symbol("pmCliIdempotentTopLevelRegistration");function yt(e){const o=e;if(o[ht])return;o[ht]=!0;const t=e.command.bind(e);e.command=((n,...r)=>{const s=n.split(/\s+/u)[0];return e.commands.some(i=>i.name()===s||i.aliases().includes(s))?new ae(s):t(n,...r)})}async function _i(e,o){if(yt(e),o.setup){const{registerSetupCommands:t}=await oi();t(e)}if(o.listQuery){const{registerListQueryCommands:t}=await ti(),n=typeof o.targetCommandName=="string"&&$r.has(o.targetCommandName)?new Set([o.targetCommandName]):void 0;t(e,n?{commandFilter:n}:void 0)}if(o.mutation){const{registerMutationCommands:t}=await ni();t(e,{targetCommandName:o.targetCommandName})}if(o.operation){const{registerOperationCommands:t}=await ri();t(e)}}function $(e){return e.rawInvocationArgv??e.invocationArgv}function vi(e){return async o=>{const t=En(o.errorCode),n=ln({ok:!1,errorCode:o.errorCode,errorCategory:t});return await mn({command:o.command,args:e.invocationArgv,options:o.options,global:e.bootstrapGlobal,pm_version:N,pm_root:e.bootstrapPmRoot,error_code:o.errorCode,error_message:o.errorMessage,exit_code:o.exitCode,error_category:t,command_resolution:n,resolution_stage:o.resolutionStage}),{errorCategory:t,commandResolution:n}}}async function Ct(e){if(e.bootstrapGlobal.noExtensions||xe(e.invocationArgv))return;const o=j(e.invocationArgv),t=await ne(e.bootstrapPmRoot);if(t&&Y(t.discovery,o)){const n=await M(e.bootstrapPmRoot,o);_t(n);return}t&&te(Te(e.invocationArgv),t,o),O({overrides:[]})}function _t(e){if(!e){O({overrides:[]});return}O(e.services)}async function Ne(e){await ie(!1,e.errorMessage,{error_code:e.classificationCode,error_category:e.errorCategory,exit_code:e.exitCode,command_resolution:e.commandResolution,resolution_stage:e.resolutionStage}),await q({ok:!1,error:e.errorMessage,exit_code:e.exitCode,error_code:e.classificationCode,error_category:e.errorCategory,command_resolution:e.commandResolution,resolution_stage:e.resolutionStage})}async function vt(){await ie(!0,void 0,{exit_code:h.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),await q({ok:!0,exit_code:h.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),process.exitCode=h.SUCCESS}async function wt(e,o){const t=typeof o=="number"&&Number.isFinite(o);if(!(e.error instanceof G)&&(Ve(e.error)||!t))return!1;const n=Qe(D(e.error)),r=e.error instanceof G?e.error.exitCode:Ke(o),s=e.error instanceof G||$t(e.error)?e.error.context:void 0,i=qo(s,e.invocationArgv,n),c=zn(n,i),u=Le(e.bootstrapGlobal.lean?Jn(_o(n,r,i)):_o(n,r,i)),l=e.jsonErrors?JSON.stringify(e.bootstrapGlobal.tokenAccounting?en(u,g=>`${JSON.stringify(g,null,2)}
|
|
2
|
+
`):u,null,2):Vn(n,i,{lean:e.bootstrapGlobal.lean===!0});e.jsonErrors?fe(`${l}
|
|
3
|
+
`):y(l);const{errorCategory:a,commandResolution:m}=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:c.code,errorMessage:c.detail,exitCode:r,options:{bootstrap_global_options:e.bootstrapGlobal},resolutionStage:"execute"}),d=await oe({command:e.attemptedCommand,error_code:c.code,error_category:a,exit_code:r,error_message:c.detail,command_resolution:m,resolution_stage:"execute",source_context:x?.source_context},e.bootstrapGlobal);return await Ne({errorMessage:n,exitCode:r,classificationCode:c.code,errorCategory:a,commandResolution:m,resolutionStage:"execute"}),d&&(ro(Ye(e.error,n)),await U(Se)),process.exitCode=r,!0}async function Et(e,o){const t=Ce(e.invocationArgv).commandPathTokens.join(" ")||yo(e.invocationArgv),n=ce(t),r=`unknown command '${t}'`,s=R(process.cwd(),e.bootstrapGlobal.path),i=e.bootstrapGlobal.noExtensions?v:await He(s),c=j(e.invocationArgv),u=e.bootstrapGlobal.noExtensions?[]:await ir(s,{},Ee(c)),l=await ho({message:r},p,i,{failedExtensions:u},$(e)),a=Co(l.message,l.commandName,l.allowedTypes,{unknownCommandExamples:l.unknownCommandExamples,unknownCommandNextSteps:l.unknownCommandNextSteps,attemptedCommand:l.attemptedCommand,normalizedInvocationArgs:l.normalizedInvocationArgs,providedOptionFlags:l.providedOptionFlags,unknownOptionSuggestions:l.unknownOptionSuggestions,suggestedRetryCommand:l.suggestedRetryCommand,failedExtensions:u}),{errorCategory:m,commandResolution:d}=await e.emitTelemetryCommandError({command:n,errorCode:a.code,errorMessage:a.detail,exitCode:h.USAGE,options:{bootstrap_global_options:e.bootstrapGlobal,commander_code:o??"commander.helpDisplayed"},resolutionStage:"parse"}),g=await oe({command:n,error_code:a.code,error_category:m,exit_code:h.USAGE,error_message:a.detail,command_resolution:d,resolution_stage:"parse"},e.bootstrapGlobal),f=e.jsonErrors?await go({message:r},p,i,e.bootstrapGlobal.lean===!0,{failedExtensions:u},$(e)):await fo({message:r},p,i,{failedExtensions:u},$(e)),E=po(f,e.jsonErrors,u);await Ne({errorMessage:r,exitCode:h.USAGE,classificationCode:a.code,errorCategory:m,commandResolution:d,resolutionStage:"parse"}),e.jsonErrors?fe(`${We(E)}
|
|
4
|
+
`):y(E),g&&await U(Se),process.exitCode=h.USAGE}async function Rt(e,o,t){if(!(o==="commander.helpDisplayed"||o==="commander.help"||o==="commander.helpCommand")&&!t.includes("(outputHelp)"))return!1;const r=Ce(e.invocationArgv);return r.requested&&!_e(p,r.commandPathTokens)?(await Et(e,o),!0):(await vt(),!0)}async function xt(e,o){const t=await ho(e.error,p,v,{},$(e)),n=Co(t.message,t.commandName,t.allowedTypes,{unknownCommandExamples:t.unknownCommandExamples,unknownCommandNextSteps:t.unknownCommandNextSteps,attemptedCommand:t.attemptedCommand,normalizedInvocationArgs:t.normalizedInvocationArgs,providedOptionFlags:t.providedOptionFlags,unknownOptionSuggestions:t.unknownOptionSuggestions,suggestedRetryCommand:t.suggestedRetryCommand}),{errorCategory:r,commandResolution:s}=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:n.code,errorMessage:n.detail,exitCode:h.USAGE,options:{bootstrap_global_options:e.bootstrapGlobal,commander_code:o},resolutionStage:"parse"}),i=await oe({command:e.attemptedCommand,error_code:n.code,error_category:r,exit_code:h.USAGE,error_message:n.detail,command_resolution:s,resolution_stage:"parse",source_context:x?.source_context},e.bootstrapGlobal),c=e.jsonErrors?await go(e.error,p,v,e.bootstrapGlobal.lean===!0,{},$(e)):await fo(e.error,p,v,{},$(e)),u=await sr(n.code,e.bootstrapPmRoot,{},Ee(j(e.invocationArgv))),l=po(c,e.jsonErrors,u);await Ne({errorMessage:t.message,exitCode:h.USAGE,classificationCode:n.code,errorCategory:r,commandResolution:s,resolutionStage:"parse"}),e.jsonErrors?fe(`${We(l)}
|
|
5
|
+
`):y(l),i&&await U(Se),process.exitCode=h.USAGE}function bt(e){if(typeof e!="object"||e===null||!("code"in e))return!1;const o=e.code;return typeof o=="string"&&(o==="commander.version"||o.startsWith("commander."))?!0:String(e.message??"").includes("(outputHelp)")}async function St(e){const o=e.error.code,t=String(e.error.message??"");if(!await Rt(e,o,t)){if(o==="commander.version"){await vt();return}await xt(e,o)}}async function $e(e){const o=k(e.invocationArgv),t=R(process.cwd(),o.path),n=jt(e.invocationArgv),r={error:e.error,invocationArgv:n,rawInvocationArgv:e.invocationArgv,bootstrapGlobal:o,jsonErrors:o.json,bootstrapPmRoot:t,attemptedCommand:ye(n)??"<unknown>",emitTelemetryCommandError:vi({invocationArgv:n,bootstrapGlobal:o,bootstrapPmRoot:t})};if(await Ct({invocationArgv:e.invocationArgv,bootstrapGlobal:o,bootstrapPmRoot:t}),!await wt(r,Je(e.error))){if(bt(e.error)){await St(r);return}await Yo({error:e.error,attemptedCommand:r.attemptedCommand,bootstrapGlobal:o,emitTelemetryCommandError:r.emitTelemetryCommandError})}}function wi(e,o,t){const n=t.requested?t.commandPathTokens:mo(o),r=It(n);if(r&&!ve(e,[...r.canonical_argv]))throw new ze(h.USAGE,"commander.unknownCommand",`unknown command '${r.alias}'`)}function Ei(e,o){let t=he(o);if(t===void 0)return;if(["pm","pm-cli"].includes(o[t]?.trim().toLowerCase())){const i=he(o.slice(t+1));if(i===void 0)return;t+=i+1}const n=X.get(o[t]),r=o.slice(t).filter(i=>!["--global","--project","--local"].includes(i)),s=n?.find(i=>i.alias.split(" ").every((c,u)=>r[u]===c));s?.lifecycle==="deprecated"&&Reflect.set(e,Wo,s.alias)}function Ri(e){return[process.argv[0],process.argv[1]??"pm",...e]}async function xi(e,o){p=qe(N),p.hook("preAction",(s,i)=>{o.configurationOnly=["item mutate","item complete"].includes(H(i))&&i.optsWithGlobals().dryRun===!0}),ft(p,e),z=null,T=null,v=new Map,yn();let t=[...e],n,r;try{const s=lo(e);t=s.argv,Lr(s.trace),Ei(p,e);const i=Ri(t),c=t.length===0,u=k(t);if(u.authorMissingValue)throw new G("--author requires a non-empty value.",h.USAGE,{code:"missing_required_argument",nextSteps:["Pass an explicit author identifier with --author <id>."]});n=Zt(u.author),Mo(s),r=jn(t);const l=No(t);await _i(p,l),uo(p,!0),Go(p,t)?await mt(p,t):(v=new Map,O({overrides:[]})),Uo(t)&&await et(p,t),uo(p);const m=Ce(t);wi(p,t,m),$o(t)&&ar(p,t),lt(p);const d=await ui(m,u);if(await mr(p,t,d,e))return;if(m.requested&&!_e(p,m.commandPathTokens))throw new ze(h.USAGE,"commander.helpDisplayed","(outputHelp)");if(c||cr(t)&&ye(t)===void 0){p.outputHelp();return}if(xe(t)){await p.parseAsync(i);return}const f=R(process.cwd(),u.path),E=await I(f),C=await Bn(t,f,u.noExtensions,M);await Ft(_=>Ht({pmRoot:f,packages:C?.contextIntentPackages},()=>Sn({env:{...process.env,PM_PATH:f},argv:i,cwd:process.cwd()},()=>An(E.agent_identity.harness_signals,()=>_(()=>p.parseAsync(i)),{probesEnabled:E.agent_identity?.probes_enabled}))))}catch(s){await $e({error:s,invocationArgv:t})}finally{r?.(),n?.()}}async function Cs(e=process.argv.slice(2)){let o=e;try{o=lo(e).argv}catch{}await Bt([...e,...o],()=>bi(e,o))}async function bi(e,o){const t=Ur(o),n={configurationOnly:t!==void 0},r=()=>n.configurationOnly,s=()=>Pt(k(o).json,async()=>{try{await nn(process.env,()=>xi(e,n))}catch(i){await $e({error:i,invocationArgv:[...e]})}});if(t!==void 0){const i=R(process.cwd(),k(o).path),c=R(process.cwd(),t.path),u=Cn(process.cwd());await pe(i,()=>pe(c,()=>pe(u,s,r),r),r)}else await s()}const _s={activationCommandMatchesProbe:yr,applyDynamicExtensionRootHelpVisibility:dt,bootstrapProfileEnabled:Te,buildBootstrapActivationProbe:j,buildPostActionTelemetryOutcome:Lo,buildPmCliRecoveryContext:qo,buildRuntimeExtensionDiscoverySnapshotCacheKey:De,buildRuntimeExtensionActivationScope:Oo,buildRuntimeExtensionSnapshotCacheKey:ot,buildRuntimeExtensionFilterForProbe:Fo,addRuntimeFieldOption:Pe,collectActivationCommandCandidates:Ee,collectExtensionFlagDefinitionsForCommand:Dr,collectExtensionFlagDefinitionsForInvocation:Q,collectLeadingCommandArgs:Cr,collectParsedActivationCommandArgs:To,collectRuntimeFieldLooseFlagDefinitionsForCommand:Zo,commandHasLongOption:Qo,commandHasShortOption:Xo,commandPathNeedsSearchExtensions:_r,commandPathNeedsTemplateExtensions:vr,describeUnknownError:D,defaultPreflightDecision:Fe,discoveryNeedsActivationForProbe:Y,emitExtensionProfile:tt,emitExtensionSkippedProfile:te,emitSettingsReadWarnings:Ie,ensureIdempotentTopLevelCommandRegistration:yt,enforceExplicitRetryForFlagTypos:Mo,envFlagEnabled:Ko,executeRegisteredRuntimeMigrations:rt,extractCommandScopedOptions:B,extensionActivationCommands:wr,extensionCapabilities:Er,extensionNeedsActivationForProbe:Rr,extensionProvidesTemplatesRuntime:xr,hasAnyCapability:br,hasGlobalExtensionContributions:Sr,handleGenericRunPmCliError:Yo,handleRunPmCliCommanderError:St,handleRunPmCliError:$e,handleRunPmCliHelpDisplayError:Rt,handleRunPmCliKnownError:wt,handleRunPmCliCommanderUsageError:xt,handleUnknownHelpCommandError:Et,inferMissingFieldsFromErrorMessage:jo,inferPostActionErrorCode:Wr,inferPostActionFailureMessage:jr,invocationRequestsVersion:Gr,isCommanderError:Ve,loadRuntimeExtensionCommandDescriptorsForRecovery:He,loadRuntimeExtensionDiscoverySnapshot:ne,loadRuntimeExtensionSnapshot:M,maybeLoadRuntimeExtensions:nt,maybeAttachCreateUpdatePolicyHelpText:Oe,maybeLogHandledCliErrorToSentry:oe,matchesStaticExtensionCommand:Ar,normalizeTelemetryCommandResolution:Br,normalizeTelemetryErrorCategory:zr,normalizeTelemetryResolutionStage:qr,normalizeThrownExitCode:Ke,probeUsesAnyFlag:kr,prepareExtensionServicesForRunPmCliError:Ct,readRecordBoolean:Vr,readRecordNumber:Kr,readRecordString:Jr,recordCliReadOutputInvocationProvenance:Hr,registerDynamicExtensionCommandPaths:mt,registerRuntimeSchemaFieldFlags:et,resolveCoreCommandRegistrationSelection:No,resolveStaticExtensionActivationDecision:Pr,resolveUnknownHelpToken:yo,readThrownExitCode:Je,runAndClearAfterCommandHooks:q,runRequiredExtensionCommand:st,shouldAttachRichHelpTextForInvocation:$o,shouldLogHandledErrorToSentry:Jo,shouldRegisterDynamicExtensionPaths:Go,shouldRegisterRuntimeSchemaFlags:Uo,shouldHandleRunPmCliCommanderError:bt,setActiveExtensionHookContextForTest:Qr,setActiveRuntimeExtensionCommandDescriptorsForTest:Xr,setRecoveredExtensionServices:_t,toLooseFieldDefinitionType:ke,isImporterOrExporterCommandPath:Io,validateDynamicExtensionCommandInvocation:Ho,wrapProgramActionsForExtensionHandlers:lt,wrapThrownErrorForSentry:Ye};export{_s as _testOnly,Cs as runPmCli};
|
|
6
6
|
//# sourceMappingURL=main.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{EXIT_CODE as m,PmCliError as f}from"../sdk/runtime-primitives.js";import{createFlagLikeAnnotationValueRefusal as O,isFlagLikeAnnotationValue as
|
|
1
|
+
import{EXIT_CODE as m,PmCliError as f}from"../sdk/runtime-primitives.js";import{createFlagLikeAnnotationValueRefusal as O,isFlagLikeAnnotationValue as R}from"../sdk/annotations.js";import{renderPmCommand as p}from"../sdk/command-line.js";import{runComments as _}from"./commands/annotations/comments.js";import{runLearnings as C}from"./commands/annotations/learnings.js";import{runNotes as T}from"./commands/annotations/notes.js";import{addHiddenOption as c,getGlobalOptions as h,invalidateSearchCachesForMutation as x,printError as N,printResult as E,readOptionString as s}from"./registration-helpers.js";function g(t,d,e,o){if(d.trim().toLowerCase()!=="add"||!e?.trim())return;const i=s(o,"add")??s(o,"text")??s(o,"note")??s(o,"body")??s(o,"comment"),r=s(o,"file"),n=[t,e.trim()];i!==void 0?n.push("--add",i):o.stdin===!0?n.push("--stdin"):r!==void 0?n.push("--file",r):n.push("--add","-");const a=p(n),l=p([t,e.trim(),"--add","-"]);throw new f(`The positional token "add" was parsed as the item id, while "${e.trim()}" was parsed as annotation text. ${t} does not use an add subcommand.`,m.USAGE,{code:"annotation_transposed_subcommand",reason:"noun_verb_object_transposition",required:`Place the item id immediately after ${t}, then use --add for annotation text.`,examples:[...new Set([a,l])],recovery:{attempted_command:`pm ${t} add ${e.trim()}`,normalized_args:[t,"add",e.trim()],parsed_positionals:[{role:"transposed_subcommand",value:"add"},{role:"item_id",value:e.trim()}],suggested_retry:a}})}const b={comments:["add","text","body","comment"],notes:["add","text","note"],learnings:["add","text"]};function M(t,d,e,o,i){const r=b[t].some(a=>`--${a}`!==d&&s(i,a)!==void 0),n=i.delete!==void 0||i.edit!==void 0&&i.ifAbsent===!0;if(!(r||n||i.stdin===!0||s(i,"file")!==void 0||s(i,"addJson")!==void 0)){if(e==="--file")return o===void 0?void 0:["--file",o];if(e==="--stdin"||e.startsWith("--file="))return o===void 0?[e]:void 0}}function y(t,d,e,o){const i=b[t].map(a=>({flag:`--${a}`,value:s(o,a)?.trim()})).find(a=>a.value!==void 0&&R(a.value));if(i===void 0)return;const r=[t,d,...typeof o.edit=="number"?["--edit",String(o.edit)]:[]],n=M(t,i.flag,i.value,e,o);throw O({collectionKey:t,textFlag:i.flag,value:i.value,commandPrefix:p(r),...n===void 0?{}:{retryArgs:[...r,...n]},...n===void 0&&e!==void 0&&i.value!=="--file"?{conflictingOperand:e}:{}})}function S(t,d,e){const o=e.flatMap(r=>{const n=s(d,r);return n===void 0?[]:[{alias:r,value:n}]});if([...new Set(o.map(({value:r})=>r))].length>1)throw new f(`Specify ${t} text with one alias or the same value across aliases: ${o.map(({alias:r})=>`--${r}`).join(", ")}`,m.USAGE,{code:"annotation_alias_conflict"});return o[0]?.value}function I(t,d){const e=typeof d.edit=="number"?d.edit:void 0,o=typeof d.delete=="number"?d.delete:void 0,i=S("comment",d,["add","text","body","comment"]),r=typeof t=="string"?t:void 0,n=d.stdin===!0,a=s(d,"file");if(+(i!==void 0)+ +(r!==void 0)+Number(n)+ +(a!==void 0)>1)throw i!==void 0&&r!==void 0&&!n&&a===void 0?new f("Specify comment text either as positional [text] or with --add, not both",m.USAGE):new f("Specify comment text with exactly one source: positional [text], --add, --stdin, or --file",m.USAGE);const u=i??r;return{add:u,readFromStdin:n,readFromFile:a,editIndex:e,deleteIndex:o,isMutation:typeof u=="string"||n||a!==void 0||e!==void 0||o!==void 0}}function F(t,d,e){const o=S(t,e,t==="note"?["add","text","note"]:["add","text"]),i=typeof d=="string"?d:void 0;if(o!==void 0&&i!==void 0)throw new f(`Specify ${t} text either as positional [text] or with --add, not both`,m.USAGE);const r=o??i,n=t==="note"?s(e,"addJson"):void 0,a=e.stdin===!0,l=s(e,"file"),u=typeof e.edit=="number"?e.edit:void 0,v=typeof e.delete=="number"?e.delete:void 0;return{add:r,addJson:n,readFromStdin:a,readFromFile:l,editIndex:u,deleteIndex:v,isMutation:typeof r=="string"||n!==void 0||a||l!==void 0||u!==void 0||v!==void 0}}function A(t){return{fullHistory:t.fullHistory===!0,ifAbsent:t.ifAbsent===!0,expectAt:s(t,"expectAt"),author:s(t,"author"),message:s(t,"message"),ownershipAppendBypass:t.ownershipAppendBypass===!0,force:!!t.force}}async function $(t,d,e,o){const i=h(o),r=Date.now();g("comments",t,d,e),y("comments",t,d,e);const n=I(d,e),a=await _(t,{add:n.add,stdin:n.readFromStdin,file:n.readFromFile,edit:n.editIndex,delete:n.deleteIndex,limit:s(e,"limit"),...A(e)},i);n.isMutation&&a.changed!==!1&&await x(i,a),w("comments",a,i,r)}async function H(t,d,e,o){const i=h(o),r=Date.now();g("notes",t,d,e),y("notes",t,d,e);const n=F("note",d,e),a=await T(t,{add:n.add,addJson:n.addJson,stdin:n.readFromStdin,file:n.readFromFile,edit:n.editIndex,delete:n.deleteIndex,limit:s(e,"limit"),since:s(e,"since"),eventType:s(e,"eventType"),includeMeta:e.includeMeta===!0,...A(e)},i);n.isMutation&&a.changed!==!1&&await x(i,a),w("notes",a,i,r)}async function J(t,d,e,o){const i=h(o),r=Date.now();g("learnings",t,d,e),y("learnings",t,d,e);const n=F("learning",d,e),a=await C(t,{add:n.add,stdin:n.readFromStdin,file:n.readFromFile,edit:n.editIndex,delete:n.deleteIndex,limit:s(e,"limit"),...A(e)},i);n.isMutation&&a.changed!==!1&&await x(i,a),w("learnings",a,i,r)}function w(t,d,e,o){E(d,e),e.profile&&N(`profile:command=${t} took_ms=${Date.now()-o}`)}function k(t,d){const e=t.command("comments").argument("<id>","Item id").argument("[text]","Optional comment text shorthand (equivalent to --add)").option("--add <text>","Append comment text; use text=<value> for structured input or - for stdin").option("--stdin","Read comment text from stdin (supports multiline markdown)").option("--file <path>","Read comment text from a file or stdin (-)").option("--edit <index>","Replace one comment using positional text, --add, --stdin, or --file",d("--edit")).option("--delete <index>","Delete the comment at 1-based <index>",d("--delete")).option("--expect-at <ts>","Edit/delete only if the entry's created_at is <ts>").option("--limit <n>","Return only latest n comments").option("--full-history","Return complete comment history instead of a bounded mutation receipt").option("--if-absent","Append only when resolved author and text are absent").option("--author [value]","Comment author; defaults to PM_AUTHOR or settings").option("--message <value>","History message").option("--force","Force ownership override").description("List, add, edit, or delete comments for an item.").action($);c(e,"--body <text>","Alias for --add",!1),c(e,"--text <text>","Alias for --add",!1),c(e,"--comment <text>","Alias for --add",!1);const o=t.command("notes").argument("<id>","Item id").argument("[text]","Optional note text shorthand for --add").option("--add <text>","Add a text note (- reads stdin)").option("--note <text>","Alias for --add").option("--add-json <json>","Append a JSON event").option("--stdin","Read note text from stdin").option("--file <path>","Read note from file or stdin (-)").option("--edit <index>","Replace a 1-based note using the selected text input",d("--edit")).option("--delete <index>","Delete the note at 1-based <index>",d("--delete")).option("--expect-at <ts>","Edit/delete only if the entry's created_at is <ts>").option("--limit <n>","Return only latest n notes").option("--since <timestamp>","Filter JSON events from this ISO time").option("--event-type <value>","Filter JSON events by top-level type").option("--include-meta","Include count and truncation metadata").option("--full-history","Return complete note history instead of a bounded receipt").option("--if-absent","Append only when resolved author and text are absent").option("--author [value]","Author; defaults to PM_AUTHOR/settings").option("--message <value>","History message").option("--force","Force ownership override").description("Manage merge-safe text notes and JSON context events.").action(H);c(o,"--text <text>","Alias for --add",!1);const i=t.command("learnings").argument("<id>","Item id").argument("[text]","Optional learning text shorthand for --add").option("--add <text>","Append learning text; use text=<value> or - for stdin").option("--stdin","Read learning text from stdin").option("--file <path>","Read learning text from a file or stdin (-)").option("--edit <index>","Replace one learning using positional text, --add, --stdin, or --file",d("--edit")).option("--delete <index>","Delete the learning at 1-based <index>",d("--delete")).option("--expect-at <ts>","Edit/delete only if the entry's created_at is <ts>").option("--limit <n>","Return only latest n learnings").option("--full-history","Return complete learning history instead of a bounded receipt").option("--if-absent","Append only when resolved author and text are absent").option("--author [value]","Learning author (optional; falls back to PM_AUTHOR/settings)").option("--message <value>","History message").option("--force","Force ownership override").description("List, add, edit, or delete learnings for an item.").action(J);c(i,"--text <text>","Alias for --add",!1)}export{k as registerAnnotationCommands};
|
|
2
2
|
//# sourceMappingURL=register-annotations.js.map
|