@unbrained/pm-cli 2026.10.31 → 2026.11.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.agents/skills/pm-user/references/ECOSYSTEM_PLANNING.md +1 -1
- package/.claude-plugin/marketplace.json +1 -1
- package/AGENTS.md +3 -3
- package/CHANGELOG.md +27 -0
- package/CONTRIBUTING.md +1 -1
- package/README.md +1 -1
- package/dist/cli/migration-gates.js +1 -1
- package/dist/cli/register-operations.d.ts +3 -3
- package/dist/cli/register-operations.js +1 -1
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/{chunk-GMBDZID5.js → chunk-3A4NVHYS.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-VC7TA67O.js → chunk-3ZQQVJT2.js} +19 -19
- package/dist/cli-bundle/chunks/{chunk-XDDPSWIW.js → chunk-4HW253W2.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-4OELCF3O.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-6PSDQ7T7.js → chunk-533L6D2N.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-35Q2B2GJ.js → chunk-ABFFRQRO.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-BFZUJ5QP.js +115 -0
- package/dist/cli-bundle/chunks/{chunk-SBVX5CMV.js → chunk-D52QQ7LP.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-P3LNMWL2.js → chunk-DAZFCSDV.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-43R7UTWV.js → chunk-EN27ZQSV.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-MRUA2Z43.js → chunk-GK2CHAT3.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-BS2KXT24.js → chunk-HOGKWJU5.js} +42 -42
- package/dist/cli-bundle/chunks/{chunk-WX25MU4N.js → chunk-J3JM36EH.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-V6EWBTNH.js → chunk-JRXD7SIL.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-U7JXZMU5.js → chunk-K46GDAKX.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-PT7TS6E7.js → chunk-KJLGBLR3.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-2AHSPMKJ.js → chunk-NGRPD3ZO.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-OJR2YGXF.js +31 -0
- package/dist/cli-bundle/chunks/chunk-QHHFXNSQ.js +3 -0
- package/dist/cli-bundle/chunks/{chunk-TL3O5GZA.js → chunk-RGHLQGEX.js} +4 -4
- package/dist/cli-bundle/chunks/{chunk-24J6TNYE.js → chunk-VEOFWE32.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-ZNWDYDFF.js +129 -0
- package/dist/cli-bundle/chunks/{indexed-receipt-blobs-KGMJVFH2.js → indexed-receipt-blobs-IEJ2QOW3.js} +2 -2
- package/dist/cli-bundle/chunks/item-transaction-JHPBH6N7.js +2 -0
- package/dist/cli-bundle/chunks/{mutation-admission-I4RHIT3Q.js → mutation-admission-QUNQZCZ5.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-MVDL5EXG.js → register-list-query-NZTK3AXA.js} +2 -2
- package/dist/cli-bundle/chunks/{register-mutation-GAF7LXRB.js → register-mutation-2OFAMOVH.js} +2 -2
- package/dist/cli-bundle/chunks/register-operations-RFMM5KZ6.js +2 -0
- package/dist/cli-bundle/chunks/{register-setup-MZN6ONB3.js → register-setup-6B6Q7M5L.js} +2 -2
- package/dist/cli-bundle/chunks/{settlement-hook-YWSWFOZY.js → settlement-hook-UTCEZBFT.js} +2 -2
- package/dist/cli-bundle/chunks/{stage-2ZORTOF6.js → stage-VLI4OBVX.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-4QPGJO2G.js → chunk-3UD6F2KQ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-EA65HVBO.js → chunk-4NVPDZLX.js} +12 -12
- package/dist/cli-bundle/focused-chunks/{chunk-KKRIFBSL.js → chunk-4UUE3YXZ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-NRBUMDLF.js → chunk-5UDDRPYR.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-SFQKCA5K.js → chunk-745IDMTD.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-QFMJGQGO.js → chunk-B6OOKKOX.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{chunk-5MCGYBOQ.js → chunk-EJJWOFP5.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-FUGYXUUL.js +80 -0
- package/dist/cli-bundle/focused-chunks/{chunk-6F6APBCX.js → chunk-HMXVTWIV.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{chunk-HSAEEWSI.js → chunk-I4Z2SCV5.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-JLN5CFYM.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-K4FMZB4Y.js +23 -0
- package/dist/cli-bundle/focused-chunks/{chunk-DFUTCKUF.js → chunk-MQVBWFJF.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-2J7T2UCH.js → chunk-NJFMG3IK.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-HPWT3RBG.js → chunk-PCCZ72C3.js} +54 -54
- package/dist/cli-bundle/focused-chunks/chunk-PF553UVP.js +44 -0
- package/dist/cli-bundle/focused-chunks/{chunk-MW77Q3AQ.js → chunk-Q23K6WLV.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-Y6UYRMVG.js → chunk-QNXXOFLQ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-JLXGRDTG.js → chunk-QVFE5LIX.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{chunk-KH5QJXY7.js → chunk-RUCG6UWN.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-JNKRUCVZ.js → chunk-SGWYNU7T.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-TGS5RXBY.js +26 -0
- package/dist/cli-bundle/focused-chunks/{chunk-PC3R5CJV.js → chunk-WD43E7RU.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-PFBQOZPK.js → chunk-YM4AMP7H.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-KHWT44EK.js → indexed-receipt-blobs-FT3KF6VJ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{item-transaction-LU75EG7D.js → item-transaction-F4SN7TXJ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{mutation-admission-KDJ7SCPA.js → mutation-admission-7R2FXJ5O.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{settlement-hook-SJV52ZTV.js → settlement-hook-KMIBD4F2.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{stage-R4KEBO37.js → stage-6B3O2GZ6.js} +2 -2
- package/dist/cli-bundle/main.js +24 -24
- 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 +57 -57
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +9 -9
- package/dist/core/extensions/extension-types.d.ts +5 -0
- package/dist/core/extensions/extension-types.js +1 -1
- package/dist/core/item/parse.js +2 -2
- package/dist/core/lock/lock-confinement.d.ts +55 -0
- package/dist/core/lock/lock-confinement.js +2 -0
- package/dist/core/lock/lock-gc.js +1 -1
- package/dist/core/lock/lock.js +2 -2
- package/dist/core/output/mutation-projection.js +1 -1
- package/dist/core/output/output.js +2 -2
- package/dist/core/shared/errors.d.ts +6 -0
- package/dist/core/shared/errors.js +1 -1
- package/dist/core/store/settings-sections.d.ts +61 -0
- package/dist/core/store/settings-sections.js +3 -0
- package/dist/core/store/settings-validator.d.ts +4 -0
- package/dist/core/store/settings-validator.js +1 -1
- package/dist/core/store/settings.d.ts +29 -2
- package/dist/core/store/settings.js +4 -3
- package/dist/core/telemetry/consent.js +2 -2
- package/dist/core/telemetry/runtime.js +2 -2
- package/dist/core/test/background-runs.js +3 -3
- package/dist/sdk/cli-contracts/tool-schema.js +1 -1
- package/dist/sdk/config.js +1 -1
- package/dist/sdk/context-intent-contracts.d.ts +17 -0
- package/dist/sdk/context-intent-contracts.js +1 -1
- package/dist/sdk/core.d.ts +1 -1
- package/dist/sdk/core.js +1 -1
- package/dist/sdk/extension-command-context.js +2 -2
- package/dist/sdk/generated/error-code-catalog-rows.d.ts +39 -0
- package/dist/sdk/generated/error-code-catalog-rows.js +2 -0
- package/dist/sdk/generated/generated-error-code-catalog-part-1.d.ts +3 -3
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-2.d.ts +3 -3
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
- package/dist/sdk/generated-error-code-catalog.js +1 -1
- package/dist/sdk/index.d.ts +1 -1
- package/dist/sdk/index.js +1 -1
- package/dist/sdk/init-agent-guidance.js +2 -2
- package/dist/sdk/lifecycle/claim.d.ts +27 -0
- package/dist/sdk/lifecycle/claim.js +1 -1
- package/dist/sdk/lifecycle/mcp-actions.d.ts +1 -1
- package/dist/sdk/lifecycle/mcp-actions.js +1 -1
- package/dist/sdk/lifecycle/task-composition.js +1 -1
- package/dist/sdk/mcp/discovery.js +1 -1
- package/dist/sdk/output/list-envelope.d.ts +8 -0
- package/dist/sdk/output/list-envelope.js +1 -1
- package/dist/sdk/output.d.ts +1 -1
- package/dist/sdk/output.js +2 -2
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/query/context.js +2 -2
- package/dist/sdk/runtime/actions.js +1 -1
- package/dist/sdk/runtime-input.js +1 -1
- package/dist/sdk/runtime-primitives.d.ts +2 -1
- package/dist/sdk/runtime-primitives.js +1 -1
- package/dist/sdk/runtime-public-contracts.d.ts +2 -0
- package/dist/sdk/runtime.d.ts +2 -2
- package/dist/sdk/runtime.js +1 -1
- package/dist/sdk/start-task-status.d.ts +1 -1
- package/dist/sdk/start-task-status.js +1 -1
- package/docs/AGENT_EVIDENCE_CONSISTENCY.md +10 -0
- package/docs/AGENT_GUIDE.md +3 -3
- package/docs/COMMANDS.md +1 -0
- package/docs/COMMAND_NAMESPACES.md +1 -1
- package/docs/CONFIGURATION.md +9 -0
- package/docs/DEVELOPMENT_DEPENDENCY_SECURITY.md +9 -6
- package/docs/LIFECYCLE_COMMANDS.md +19 -4
- package/docs/RELEASING.md +22 -2
- package/docs/SDK.md +37 -2
- package/docs/SDK_ACTION_CONFORMANCE.md +21 -0
- package/docs/SDK_CONFIGURATION_SAFETY.md +55 -0
- package/docs/TESTING.md +2 -1
- package/docs/agent-task-token-baseline.json +1 -1
- package/docs/agent-task-transcripts.json +1 -1
- package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +12 -3
- package/marketplace.json +1 -1
- package/package.json +9 -3
- 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-HSBTITO4.js +0 -3
- package/dist/cli-bundle/chunks/chunk-WNF6FOL7.js +0 -31
- package/dist/cli-bundle/chunks/chunk-WRXQAW7Q.js +0 -114
- package/dist/cli-bundle/chunks/chunk-YT5D5HNG.js +0 -2
- package/dist/cli-bundle/chunks/chunk-ZTJVOBDU.js +0 -128
- package/dist/cli-bundle/chunks/item-transaction-UWV6UNSV.js +0 -2
- package/dist/cli-bundle/chunks/register-operations-JLFRL36Q.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-57HPXGOQ.js +0 -79
- package/dist/cli-bundle/focused-chunks/chunk-AFVN2KCP.js +0 -44
- package/dist/cli-bundle/focused-chunks/chunk-GP2WU43K.js +0 -26
- package/dist/cli-bundle/focused-chunks/chunk-NOKG4RFN.js +0 -22
- package/dist/cli-bundle/focused-chunks/chunk-WHIE2C6Q.js +0 -2
package/dist/sdk/config.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="a4177124-2cf0-52e7-9a8e-8ba7ac702c64")}catch{}})();import{resolveConfigPositionalValue}from"../core/config/positional-value.js";import{NESTED_SETTING_DESCRIPTORS,parseNestedSettingValue,readNestedSettingValue,resolveNestedSettingDescriptor,writeNestedSettingValue}from"../core/config/nested-settings.js";import{getActiveExtensionRegistrations}from"../core/extensions/index.js";import{normalizeParentReferencePolicy}from"../core/item/parent-reference-policy.js";import{normalizeSprintReleaseFormatPolicy}from"../core/item/sprint-release-format.js";import{resolveItemTypeRegistry,resolveTypeName}from"../core/item/type-registry.js";import{buildInvalidTypeError}from"../core/schema/item-types-file.js";import{resolveItemTypesFilePath}from"../core/schema/runtime-schema.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{createUnknownSubcommandError}from"./agent/subcommand-recovery.js";import{planAgentIdentityVocabularyMutation,summarizeAgentIdentityVocabulary}from"./agent/identity-config.js";import{assertInitializedTracker}from"./environment/tracker-preflight.js";import{migrateItemFilesToFormat}from"../core/store/item-format-migration.js";import{getSettingsPath,resolveGlobalPmRoot,resolvePmRoot}from"../core/store/paths.js";import{readSettingsWithMetadata,writeSettings}from"../core/store/settings.js";import{CONTEXT_DEPTH_VALUES}from"../types/index.js";const CONFIG_SCOPE_VALUES=["project","global"],CONFIG_KEY_ALIASES={definition_of_done:["definition-of-done","definition_of_done"],item_format:["item-format","item_format"],history_missing_stream_policy:["history-missing-stream-policy","history_missing_stream_policy"],sprint_release_format_policy:["sprint-release-format-policy","sprint_release_format_policy"],parent_reference_policy:["parent-reference-policy","parent_reference_policy"],metadata_validation_profile:["metadata-validation-profile","metadata_validation_profile"],metadata_required_fields:["metadata-required-fields","metadata_required_fields"],lifecycle_stale_blocker_reason_patterns:["lifecycle-stale-blocker-reason-patterns","lifecycle_stale_blocker_reason_patterns"],lifecycle_closure_like_blocked_reason_patterns:["lifecycle-closure-like-blocked-reason-patterns","lifecycle_closure_like_blocked_reason_patterns"],lifecycle_closure_like_resolution_patterns:["lifecycle-closure-like-resolution-patterns","lifecycle_closure_like_resolution_patterns"],lifecycle_closure_like_actual_result_patterns:["lifecycle-closure-like-actual-result-patterns","lifecycle_closure_like_actual_result_patterns"],governance_preset:["governance-preset","governance_preset"],governance_ownership_enforcement:["governance-ownership-enforcement","governance_ownership_enforcement"],governance_create_mode_default:["governance-create-mode-default","governance_create_mode_default"],governance_close_validation_default:["governance-close-validation-default","governance_close_validation_default"],governance_require_close_reason:["governance-require-close-reason","governance_require_close_reason"],governance_create_default_type:["governance-create-default-type","governance_create_default_type"],governance_workflow_enforcement:["governance-workflow-enforcement","governance_workflow_enforcement"],governance_parent_reference_policy:["governance-parent-reference-policy","governance_parent_reference_policy"],governance_metadata_validation_profile:["governance-metadata-validation-profile","governance_metadata_validation_profile"],governance_force_required_for_stale_lock:["governance-force-required-for-stale-lock","governance_force_required_for_stale_lock"],test_result_tracking:["test-result-tracking","test_result_tracking"],untrusted_linked_test_execution:["untrusted-linked-test-execution","untrusted_linked_test_execution"],telemetry_tracking:["telemetry-tracking","telemetry_tracking"],agent_identity_vocabulary:["agent-identity-vocabulary","agent_identity_vocabulary"],context:["context"]},CANONICAL_CONFIG_KEYS=Object.keys(CONFIG_KEY_ALIASES).map(candidate=>CONFIG_KEY_ALIASES[candidate][0]),CONFIG_KEY_BY_ALIAS=Object.fromEntries(Object.keys(CONFIG_KEY_ALIASES).flatMap(key=>CONFIG_KEY_ALIASES[key].map(alias=>[alias,key]))),CONFIG_KEY_SUMMARIES={definition_of_done:"Definition of Done criteria list.",item_format:"Default item file format.",history_missing_stream_policy:"Missing history stream handling policy.",sprint_release_format_policy:"Sprint/release format validation policy.",parent_reference_policy:"Parent reference validation policy.",metadata_validation_profile:"Validate metadata profile policy (core|strict|custom).",metadata_required_fields:"Validate custom metadata required-fields list.",lifecycle_stale_blocker_reason_patterns:"Validate lifecycle stale-blocker reason substring patterns (criteria list).",lifecycle_closure_like_blocked_reason_patterns:"Validate lifecycle closure-like blocked_reason substring patterns (criteria list).",lifecycle_closure_like_resolution_patterns:"Validate lifecycle closure-like resolution substring patterns (criteria list).",lifecycle_closure_like_actual_result_patterns:"Validate lifecycle closure-like actual_result substring patterns (criteria list).",governance_preset:"Governance preset policy (minimal|default|strict|custom).",governance_ownership_enforcement:"Governance ownership enforcement policy (none|warn|strict).",governance_create_mode_default:"Governance default create mode (progressive|strict).",governance_close_validation_default:"Governance default close validation mode (off|warn|strict).",governance_require_close_reason:"Governance close-reason requirement policy (enabled|disabled).",governance_create_default_type:"Governance default item type for `pm create` when --type is omitted.",governance_workflow_enforcement:"Governance per-type transition enforcement mode (off|warn|strict).",governance_parent_reference_policy:"Governance parent reference policy (warn|strict_error).",governance_metadata_validation_profile:"Governance metadata validation profile (core|strict|custom).",governance_force_required_for_stale_lock:"Governance stale-lock force policy (enabled|disabled).",test_result_tracking:"Item-level linked test result persistence policy.",untrusted_linked_test_execution:"Permit an explicit per-run override for commands not trusted by this clone.",telemetry_tracking:"Telemetry usage reporting policy.",agent_identity_vocabulary:"Versioned exact legacy-author interpretation vocabulary (summary only).",context:"Context command settings (depth, section toggles, limits)."},LIFECYCLE_PATTERN_CONFIG_KEYS=["lifecycle_stale_blocker_reason_patterns","lifecycle_closure_like_blocked_reason_patterns","lifecycle_closure_like_resolution_patterns","lifecycle_closure_like_actual_result_patterns"],CRITERIA_CONFIG_KEYS=new Set(["metadata_required_fields",...LIFECYCLE_PATTERN_CONFIG_KEYS]),TRACKING_CONFIG_KEYS=new Set(["test_result_tracking","untrusted_linked_test_execution","telemetry_tracking"]),GOVERNANCE_BOOLEAN_CONFIG_KEYS=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock"]),GOVERNANCE_POLICY_CONFIG_KEYS=new Set(["governance_ownership_enforcement","governance_create_mode_default","governance_close_validation_default"]),GOVERNANCE_VALIDATION_CONFIG_KEYS=new Set(["governance_parent_reference_policy","governance_metadata_validation_profile","governance_workflow_enforcement"]),GOVERNANCE_PRESET_OR_TYPE_CONFIG_KEYS=new Set(["governance_preset","governance_create_default_type"]),isCriteriaValueConfigKey=key=>CRITERIA_CONFIG_KEYS.has(key),isGovernancePolicyConfigKey=key=>GOVERNANCE_POLICY_CONFIG_KEYS.has(key),isGovernanceValidationConfigKey=key=>GOVERNANCE_VALIDATION_CONFIG_KEYS.has(key),isGovernancePresetOrTypeConfigKey=key=>GOVERNANCE_PRESET_OR_TYPE_CONFIG_KEYS.has(key);function isCriteriaConfigKey(key){return key==="definition_of_done"||isCriteriaValueConfigKey(key)}function normalizeScope(value){if(CONFIG_SCOPE_VALUES.includes(value))return value;throw new PmCliError(`Invalid config scope "${value}". Allowed: ${CONFIG_SCOPE_VALUES.join(", ")}`,EXIT_CODE.USAGE)}function normalizeAction(value){if(value==="get"||value==="set"||value==="list"||value==="export")return value;throw createUnknownSubcommandError({command_path:"config",token:value.trim()||"<empty>",allowed:["export","get","list","set"],token_kind:"action"})}function normalizeKey(value){const key=CONFIG_KEY_BY_ALIAS[value];if(key)return key;const nestedKeys=NESTED_SETTING_DESCRIPTORS.map(descriptor=>descriptor.key).join(", ");throw new PmCliError(`Invalid config key "${value}". Supported: ${CANONICAL_CONFIG_KEYS.join(", ")} (underscore variants also accepted). Nested leaf settings: ${nestedKeys}.`,EXIT_CODE.USAGE)}function normalizeCriteria(values,clearCriteria){const normalized=[...new Set((values??[]).map(value=>value.trim()).filter(value=>value.length>0))].sort((left,right)=>left.localeCompare(right));if(clearCriteria){if(normalized.length>0)throw new PmCliError("Config set definition-of-done cannot combine --clear-criteria with --criterion values",EXIT_CODE.USAGE);return[]}if(normalized.length===0)throw new PmCliError("Config set definition-of-done requires at least one non-empty --criterion value (or --clear-criteria to clear)",EXIT_CODE.USAGE);return normalized}function normalizeItemFormat(value){const normalized=value?.trim().toLowerCase();if(normalized==="toon")return"toon";throw normalized==="json_markdown"?new PmCliError("Config set item-format no longer accepts json_markdown. Markdown item files are legacy read/migration input only.",EXIT_CODE.USAGE):new PmCliError("Config set item-format requires --format toon",EXIT_CODE.USAGE)}function normalizeHistoryMissingStreamPolicy(value){const normalized=value?.trim().toLowerCase().replaceAll("-","_");if(normalized==="auto_create"||normalized==="strict_error")return normalized;throw new PmCliError("Config set history-missing-stream-policy requires --policy with one of: auto_create, strict_error",EXIT_CODE.USAGE)}function normalizeTestResultTrackingPolicy(value){return normalizeEnabledDisabledPolicy(value,"test-result-tracking")}function normalizeEnabledDisabledPolicy(value,key){const normalized=value?.trim().toLowerCase().replaceAll("-","_");if(normalized==="enabled"||normalized==="disabled")return normalized;throw new PmCliError(`Config set ${key} requires --policy with one of: enabled, disabled`,EXIT_CODE.USAGE)}function normalizeTelemetryTrackingPolicy(value){const normalized=value?.trim().toLowerCase().replaceAll("-","_");if(normalized==="enabled"||normalized==="disabled")return normalized;throw new PmCliError("Config set telemetry-tracking requires --policy with one of: enabled, disabled",EXIT_CODE.USAGE)}function normalizeValidateMetadataProfile(value){const normalized=value?.trim().toLowerCase().replaceAll("-","_");if(normalized==="core"||normalized==="strict"||normalized==="custom")return normalized;throw new PmCliError("Config set metadata-validation-profile requires --policy with one of: core, strict, custom",EXIT_CODE.USAGE)}function normalizeGovernancePreset(value){const normalized=value?.trim().toLowerCase().replaceAll("-","_");if(normalized==="minimal"||normalized==="default"||normalized==="strict"||normalized==="custom")return normalized;throw new PmCliError("Config set governance-preset requires --policy with one of: minimal, default, strict, custom",EXIT_CODE.USAGE)}function normalizeGovernanceOwnershipEnforcement(value){const normalized=value?.trim().toLowerCase().replaceAll("-","_");if(normalized==="none"||normalized==="warn"||normalized==="strict")return normalized;throw new PmCliError("Config set governance-ownership-enforcement requires --policy with one of: none, warn, strict",EXIT_CODE.USAGE)}function normalizeGovernanceCreateModeDefault(value){const normalized=value?.trim().toLowerCase().replaceAll("-","_");if(normalized==="progressive"||normalized==="strict")return normalized;throw new PmCliError("Config set governance-create-mode-default requires --policy with one of: progressive, strict",EXIT_CODE.USAGE)}function normalizeGovernanceCloseValidationDefault(value){const normalized=value?.trim().toLowerCase().replaceAll("-","_");if(normalized==="off"||normalized==="warn"||normalized==="strict")return normalized;if(normalized==="none"||normalized==="disabled")return"off";throw new PmCliError("Config set governance-close-validation-default requires --policy with one of: off, warn, strict",EXIT_CODE.USAGE)}function normalizeGovernanceWorkflowEnforcement(value){const normalized=typeof value=="string"?value.trim().toLowerCase().replaceAll("-","_"):void 0;if(normalized==="off"||normalized==="warn"||normalized==="strict")return normalized;if(normalized==="none"||normalized==="disabled")return"off";throw new PmCliError("Config set governance-workflow-enforcement requires one of: off, warn, strict",EXIT_CODE.USAGE)}function normalizeGovernanceForceRequiredForStaleLockPolicy(value){const normalized=value?.trim().toLowerCase().replaceAll("-","_");if(normalized==="enabled"||normalized==="disabled")return normalized;throw new PmCliError("Config set governance-force-required-for-stale-lock requires --policy with one of: enabled, disabled",EXIT_CODE.USAGE)}function normalizeGovernanceRequireCloseReasonPolicy(value){const normalized=value?.trim().toLowerCase().replaceAll("-","_");if(normalized==="enabled"||normalized==="disabled")return normalized;throw new PmCliError("Config set governance-require-close-reason requires --policy with one of: enabled, disabled",EXIT_CODE.USAGE)}const ENABLED_DISABLED_CONFLICT_POLICY_KEYS={test_result_tracking:"test-result-tracking",untrusted_linked_test_execution:"untrusted-linked-test-execution"};function normalizePolicyForConflict(key,value){const enabledDisabledKey=ENABLED_DISABLED_CONFLICT_POLICY_KEYS[key];if(enabledDisabledKey)return normalizeEnabledDisabledPolicy(value,enabledDisabledKey);switch(key){case"history_missing_stream_policy":return normalizeHistoryMissingStreamPolicy(value);case"sprint_release_format_policy":return normalizeSprintReleaseFormatPolicy(value);case"parent_reference_policy":case"governance_parent_reference_policy":return normalizeParentReferencePolicy(value);case"metadata_validation_profile":case"governance_metadata_validation_profile":return normalizeValidateMetadataProfile(value);case"governance_preset":return normalizeGovernancePreset(value);case"governance_ownership_enforcement":return normalizeGovernanceOwnershipEnforcement(value);case"governance_create_mode_default":return normalizeGovernanceCreateModeDefault(value);case"governance_close_validation_default":return normalizeGovernanceCloseValidationDefault(value);case"governance_require_close_reason":return normalizeGovernanceRequireCloseReasonPolicy(value);case"governance_workflow_enforcement":return normalizeGovernanceWorkflowEnforcement(value);case"governance_force_required_for_stale_lock":return normalizeGovernanceForceRequiredForStaleLockPolicy(value);case"telemetry_tracking":return normalizeTelemetryTrackingPolicy(value);default:return value.trim().toLowerCase().replaceAll("-","_")}}const METADATA_REQUIRED_FIELD_ALIAS_MAP={author:"author",acceptance_criteria:"acceptance_criteria","acceptance-criteria":"acceptance_criteria",estimated_minutes:"estimated_minutes","estimated-minutes":"estimated_minutes",estimate:"estimated_minutes",close_reason:"close_reason","close-reason":"close_reason",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release"},METADATA_REQUIRED_FIELD_OPTIONS=["author","acceptance_criteria","estimated_minutes","close_reason","reviewer","risk","confidence","sprint","release"];function normalizeMetadataRequiredFields(values,clearCriteria){const normalized=[...new Set((values??[]).map(value=>value.trim()).filter(value=>value.length>0))];if(clearCriteria){if(normalized.length>0)throw new PmCliError("Config set metadata-required-fields cannot combine --clear-criteria with --criterion values",EXIT_CODE.USAGE);return[]}if(normalized.length===0)throw new PmCliError("Config set metadata-required-fields requires at least one --criterion value (or --clear-criteria to clear)",EXIT_CODE.USAGE);const lowered=normalized.map(value=>value.toLowerCase().replaceAll("-","_")),unsupported=lowered.filter(value=>METADATA_REQUIRED_FIELD_ALIAS_MAP[value]===void 0);if(unsupported.length>0)throw new PmCliError(`Config set metadata-required-fields received unsupported values: ${unsupported.join(", ")}. Supported values: ${METADATA_REQUIRED_FIELD_OPTIONS.join(", ")}`,EXIT_CODE.USAGE);return[...new Set(lowered.map(value=>METADATA_REQUIRED_FIELD_ALIAS_MAP[value]))].sort((left,right)=>left.localeCompare(right))}function normalizeLifecyclePatternCriteria(key,values,clearCriteria){const normalized=[...new Set((values??[]).map(value=>value.trim().toLowerCase()).filter(value=>value.length>0))].sort((left,right)=>left.localeCompare(right));if(clearCriteria){if(normalized.length>0)throw new PmCliError(`Config set ${CONFIG_KEY_ALIASES[key][0]} cannot combine --clear-criteria with --criterion values`,EXIT_CODE.USAGE);return[]}if(normalized.length===0)throw new PmCliError(`Config set ${CONFIG_KEY_ALIASES[key][0]} requires at least one --criterion value (or --clear-criteria to clear)`,EXIT_CODE.USAGE);return normalized}function normalizeWarnings(values){return[...new Set(values)].sort((left,right)=>left.localeCompare(right))}function normalizeKeyForAction(action,value){if(action==="list"||action==="export"){if(typeof value=="string"&&value.trim().length>0)throw new PmCliError(`Config action "${action}" does not accept <key>`,EXIT_CODE.USAGE);return}if(typeof value!="string"||value.trim().length===0)throw new PmCliError(`Config action "${action}" requires <key>`,EXIT_CODE.USAGE);return normalizeKey(value)}function assertConfigKeyDefined(key){if(!key)throw new PmCliError("Config action requires <key>",EXIT_CODE.USAGE)}const CONFIG_VALUE_READERS={definition_of_done:settings=>[...settings.workflow.definition_of_done],item_format:settings=>settings.item_format,history_missing_stream_policy:settings=>settings.history.missing_stream,sprint_release_format_policy:settings=>settings.validation.sprint_release_format,parent_reference_policy:settings=>settings.validation.parent_reference,metadata_validation_profile:settings=>settings.validation.metadata_profile,metadata_required_fields:settings=>[...settings.validation.metadata_required_fields],lifecycle_stale_blocker_reason_patterns:settings=>[...settings.validation.lifecycle_stale_blocker_reason_patterns],lifecycle_closure_like_blocked_reason_patterns:settings=>[...settings.validation.lifecycle_closure_like_blocked_reason_patterns],lifecycle_closure_like_resolution_patterns:settings=>[...settings.validation.lifecycle_closure_like_resolution_patterns],lifecycle_closure_like_actual_result_patterns:settings=>[...settings.validation.lifecycle_closure_like_actual_result_patterns],governance_preset:settings=>settings.governance.preset,governance_ownership_enforcement:settings=>settings.governance.ownership_enforcement,governance_create_mode_default:settings=>settings.governance.create_mode_default,governance_close_validation_default:settings=>settings.governance.close_validation_default,governance_require_close_reason:settings=>settings.governance.require_close_reason?"enabled":"disabled",governance_create_default_type:settings=>settings.governance.create_default_type??"",governance_workflow_enforcement:settings=>settings.governance.workflow_enforcement??"off",governance_parent_reference_policy:settings=>settings.governance.parent_reference,governance_metadata_validation_profile:settings=>settings.governance.metadata_profile,governance_force_required_for_stale_lock:settings=>settings.governance.force_required_for_stale_lock?"enabled":"disabled",test_result_tracking:settings=>settings.testing.record_results_to_items?"enabled":"disabled",untrusted_linked_test_execution:settings=>settings.testing.allow_untrusted_linked_tests?"enabled":"disabled",telemetry_tracking:settings=>settings.telemetry.enabled?"enabled":"disabled",agent_identity_vocabulary:settings=>summarizeAgentIdentityVocabulary(settings.agent_identity?.identity_vocabulary),context:settings=>({default_depth:settings.context.default_depth,activity_limit:settings.context.activity_limit,stale_threshold_days:settings.context.stale_threshold_days,next_ranking_policy:settings.context.next_ranking_policy,sections:{...settings.context.sections}})};function readConfigValue(settings,key){return CONFIG_VALUE_READERS[key](settings)}function withWarnings(result,warnings){return warnings.length===0?result:{...result,warnings}}async function resolveSettingsTarget(scope,global2){const cwd=process.cwd(),pmRoot=scope==="project"?resolvePmRoot(cwd,global2.path):resolveGlobalPmRoot(cwd),settingsPath=getSettingsPath(pmRoot);return scope==="project"&&await assertInitializedTracker(pmRoot),{pmRoot,settingsPath}}function parseSectionToggle(raw){if(raw===void 0)return;const normalized=raw.trim().toLowerCase();if(normalized==="true"||normalized==="enabled"||normalized==="on"||normalized==="1")return!0;if(normalized==="false"||normalized==="disabled"||normalized==="off"||normalized==="0")return!1;throw new PmCliError(`Context section toggle must be true|false|enabled|disabled, got "${raw}"`,EXIT_CODE.USAGE)}function parsePositiveContextInteger(rawValue,option){const raw=rawValue.trim(),parsed=Number(raw);if(/^\d+$/u.test(raw)&&Number.isSafeInteger(parsed)&&parsed>0)return parsed;throw new PmCliError(`Context ${option} must be a positive integer`,EXIT_CODE.USAGE)}async function applyContextConfig(settings,options,target,scope,warnings){let changed=!1;const ctx=settings.context;if(options.defaultDepth!==void 0){const normalized=options.defaultDepth.trim().toLowerCase();if(!CONTEXT_DEPTH_VALUES.includes(normalized))throw new PmCliError(`Context --default-depth must be one of ${CONTEXT_DEPTH_VALUES.join("|")}`,EXIT_CODE.USAGE);ctx.default_depth!==normalized&&(ctx.default_depth=normalized,changed=!0)}if(options.activityLimit!==void 0){const parsed=parsePositiveContextInteger(options.activityLimit,"--activity-limit");ctx.activity_limit!==parsed&&(ctx.activity_limit=parsed,changed=!0)}if(options.staleThresholdDays!==void 0){const parsed=parsePositiveContextInteger(options.staleThresholdDays,"--stale-threshold-days");ctx.stale_threshold_days!==parsed&&(ctx.stale_threshold_days=parsed,changed=!0)}const sectionToggles=[["hierarchy",options.sectionHierarchy],["activity",options.sectionActivity],["progress",options.sectionProgress],["blockers",options.sectionBlockers],["files",options.sectionFiles],["workload",options.sectionWorkload],["staleness",options.sectionStaleness],["tests",options.sectionTests]];for(const[sectionName,rawValue]of sectionToggles){const toggle=parseSectionToggle(rawValue);if(toggle!==void 0){const key=sectionName;ctx.sections[key]!==toggle&&(ctx.sections[key]=toggle,changed=!0)}}return changed&&await writeSettings(target.pmRoot,settings,"config:set:context"),withWarnings({scope,key:"context",context_settings:{default_depth:ctx.default_depth,activity_limit:ctx.activity_limit,stale_threshold_days:ctx.stale_threshold_days,next_ranking_policy:ctx.next_ranking_policy,sections:{...ctx.sections}},settings_path:target.settingsPath,changed},warnings)}function applyNestedSettingPositionalValue(keyValue,valueValue,options){if(options.value!==void 0&&options.value!==valueValue)throw new PmCliError(`Config set ${keyValue} received both positional value "${valueValue}" and --value "${options.value}". Pass only one.`,EXIT_CODE.USAGE);return{...options,value:valueValue}}function applyPositionalValue(action,keyValue,normalizedKey,nestedSetting,valueValue,options){if(valueValue===void 0)return options;if(action!=="set")throw new PmCliError(`Config action "${action}" does not accept a positional value. Only "set" takes <value>.`,EXIT_CODE.USAGE);if(typeof keyValue!="string"||keyValue.trim().length===0)throw new PmCliError('Config action "set" requires <key> before a positional <value>.',EXIT_CODE.USAGE);if(nestedSetting)return applyNestedSettingPositionalValue(keyValue,valueValue,options);assertConfigKeyDefined(normalizedKey);const routed=resolveConfigPositionalValue(normalizedKey,valueValue);if(!routed.routable)throw new PmCliError(routed.reason,EXIT_CODE.USAGE);if(routed.flag==="criterion"){if(options.criterion!==void 0&&options.criterion.length>0)throw new PmCliError(`Config set ${keyValue} received both positional value "${valueValue}" and --criterion. Pass criteria via --criterion only when supplying more than one value.`,EXIT_CODE.USAGE);return{...options,criterion:routed.values}}if(routed.flag==="format")return{...options,format:routed.value};if(options.policy!==void 0&&normalizePolicyForConflict(normalizedKey,options.policy)!==normalizePolicyForConflict(normalizedKey,routed.value))throw new PmCliError(`Config set ${keyValue} received both positional value "${valueValue}" and --policy "${options.policy}". Pass only one.`,EXIT_CODE.USAGE);return{...options,policy:routed.value}}function buildConfigListResult(context){const keys=Object.keys(CONFIG_KEY_ALIASES).map(candidate=>({key:candidate,aliases:CONFIG_KEY_ALIASES[candidate],value_kind:candidate==="context"||candidate==="agent_identity_vocabulary"?"object":isCriteriaConfigKey(candidate)?"string_array":"enum",set_flags:candidate==="context"?["--default-depth","--activity-limit","--stale-threshold-days","--section-<name>"]:candidate==="agent_identity_vocabulary"?["--policy","--value","--criterion"]:isCriteriaConfigKey(candidate)?["--criterion","--clear-criteria"]:candidate==="item_format"?["--format"]:["--policy"],summary:CONFIG_KEY_SUMMARIES[candidate],value:readConfigValue(context.settings,candidate)})),nestedSettings=NESTED_SETTING_DESCRIPTORS.map(descriptor=>({key:descriptor.key,canonical_key:descriptor.key.replaceAll("_","-"),path:descriptor.path,kind:descriptor.kind,value:readNestedSettingValue(context.settings,descriptor),summary:descriptor.summary,...descriptor.choices?{choices:[...descriptor.choices]}:{},...descriptor.min===void 0?{}:{min:descriptor.min},...descriptor.max===void 0?{}:{max:descriptor.max}}));return withWarnings({scope:context.scope,keys,nested_settings:nestedSettings,count:keys.length,settings_path:context.target.settingsPath,changed:!1},context.warnings)}function buildConfigExportResult(context){const values=Object.fromEntries(Object.keys(CONFIG_KEY_ALIASES).map(key=>[key,readConfigValue(context.settings,key)]));return withWarnings({scope:context.scope,values,settings_path:context.target.settingsPath,changed:!1},context.warnings)}function buildConfigGetResult(context,key){const value=readConfigValue(context.settings,key),base={scope:context.scope,key,settings_path:context.target.settingsPath,changed:!1};return key==="item_format"?withWarnings({...base,format:context.settings.item_format,has_explicit_item_format:context.metadata.has_explicit_item_format},context.warnings):key==="context"?withWarnings({...base,context_settings:value},context.warnings):key==="agent_identity_vocabulary"?withWarnings({...base,identity_vocabulary:value},context.warnings):Array.isArray(value)?withWarnings({...base,criteria:value},context.warnings):withWarnings({...base,policy:value},context.warnings)}async function buildNestedSettingResult(context,action,nestedSetting,options){if(action==="get"){const currentValue=readNestedSettingValue(context.settings,nestedSetting);return withWarnings({scope:context.scope,key:nestedSetting.key,nested_setting:{key:nestedSetting.key,path:nestedSetting.path,kind:nestedSetting.kind,value:currentValue},settings_path:context.target.settingsPath,changed:!1},context.warnings)}const rawValue=options.value;if(typeof rawValue!="string")throw new PmCliError(`Config set ${nestedSetting.key} requires a value. Pass it positionally (\`pm config ${context.scope} set ${nestedSetting.key} <value>\`) or via --value.`,EXIT_CODE.USAGE);const parsed=parseNestedSettingValue(nestedSetting,rawValue);if(!parsed.ok)throw new PmCliError(parsed.error.message,EXIT_CODE.USAGE);const changed=writeNestedSettingValue(context.settings,nestedSetting,parsed.parsed.value);return changed&&await writeSettings(context.target.pmRoot,context.settings,`config:set:${nestedSetting.path}`),withWarnings({scope:context.scope,key:nestedSetting.key,nested_setting:{key:nestedSetting.key,path:nestedSetting.path,kind:nestedSetting.kind,value:parsed.parsed.value},settings_path:context.target.settingsPath,changed},context.warnings)}async function writeConfigSettingsIfChanged(context,changed,reason){changed&&await writeSettings(context.target.pmRoot,context.settings,reason)}function hasGovernanceValidationMirrorChange(governanceValue,validationValue,nextPolicy){return governanceValue!==nextPolicy||validationValue!==nextPolicy}function buildPolicyResult(context,key,policy,changed){return withWarnings({scope:context.scope,key,policy,settings_path:context.target.settingsPath,changed},context.warnings)}function buildCriteriaResult(context,key,criteria,changed){return withWarnings({scope:context.scope,key,criteria,settings_path:context.target.settingsPath,changed},context.warnings)}async function setItemFormatConfig(context,options){const nextFormat=normalizeItemFormat(options.format),changed=context.settings.item_format!==nextFormat||!context.metadata.has_explicit_item_format;let migration;if(changed){const typeRegistry=resolveItemTypeRegistry(context.settings,getActiveExtensionRegistrations()),migrated=await migrateItemFilesToFormat(context.target.pmRoot,nextFormat,"config:set:item_format:migrate",typeRegistry.type_to_folder,context.settings.schema);migration={target_format:migrated.target_format,scanned:migrated.scanned,migrated:migrated.migrated,removed:migrated.removed,warnings:migrated.warnings},context.settings.item_format=nextFormat,await writeSettings(context.target.pmRoot,context.settings,"config:set:item_format")}return withWarnings({scope:context.scope,key:"item_format",format:context.settings.item_format,has_explicit_item_format:!0,migration,settings_path:context.target.settingsPath,changed},context.warnings)}async function setValidationConfig(context,key,options){if(key==="history_missing_stream_policy"){const nextPolicy2=normalizeHistoryMissingStreamPolicy(options.policy),changed2=context.settings.history.missing_stream!==nextPolicy2;return context.settings.history.missing_stream=nextPolicy2,await writeConfigSettingsIfChanged(context,changed2,"config:set:history_missing_stream_policy"),buildPolicyResult(context,key,context.settings.history.missing_stream,changed2)}if(key==="sprint_release_format_policy"){const nextPolicy2=normalizeSprintReleaseFormatPolicy(options.policy),changed2=context.settings.validation.sprint_release_format!==nextPolicy2;return context.settings.validation.sprint_release_format=nextPolicy2,await writeConfigSettingsIfChanged(context,changed2,"config:set:sprint_release_format_policy"),buildPolicyResult(context,key,context.settings.validation.sprint_release_format,changed2)}if(key==="parent_reference_policy"){const nextPolicy2=normalizeParentReferencePolicy(options.policy),changed2=context.settings.validation.parent_reference!==nextPolicy2||context.settings.governance.preset!=="custom"||context.settings.governance.parent_reference!==nextPolicy2;return context.settings.validation.parent_reference=nextPolicy2,context.settings.governance.preset="custom",context.settings.governance.parent_reference=nextPolicy2,await writeConfigSettingsIfChanged(context,changed2,"config:set:parent_reference_policy"),buildPolicyResult(context,key,context.settings.validation.parent_reference,changed2)}const nextPolicy=normalizeValidateMetadataProfile(options.policy),changed=context.settings.validation.metadata_profile!==nextPolicy||context.settings.governance.preset!=="custom"||context.settings.governance.metadata_profile!==nextPolicy;return context.settings.validation.metadata_profile=nextPolicy,context.settings.governance.preset="custom",context.settings.governance.metadata_profile=nextPolicy,await writeConfigSettingsIfChanged(context,changed,"config:set:metadata_validation_profile"),buildPolicyResult(context,key,context.settings.validation.metadata_profile,changed)}async function setCriteriaConfig(context,key,options){if(key==="metadata_required_fields"){const nextCriteria2=normalizeMetadataRequiredFields(options.criterion,options.clearCriteria),changed2=nextCriteria2.length!==context.settings.validation.metadata_required_fields.length||nextCriteria2.some((value,index)=>value!==context.settings.validation.metadata_required_fields[index]);return context.settings.validation.metadata_required_fields=nextCriteria2,await writeConfigSettingsIfChanged(context,changed2,"config:set:metadata_required_fields"),buildCriteriaResult(context,key,[...context.settings.validation.metadata_required_fields],changed2)}const currentCriteria={lifecycle_stale_blocker_reason_patterns:context.settings.validation.lifecycle_stale_blocker_reason_patterns,lifecycle_closure_like_blocked_reason_patterns:context.settings.validation.lifecycle_closure_like_blocked_reason_patterns,lifecycle_closure_like_resolution_patterns:context.settings.validation.lifecycle_closure_like_resolution_patterns,lifecycle_closure_like_actual_result_patterns:context.settings.validation.lifecycle_closure_like_actual_result_patterns}[key],nextCriteria=normalizeLifecyclePatternCriteria(key,options.criterion,options.clearCriteria),changed=nextCriteria.length!==currentCriteria.length||nextCriteria.some((value,index)=>value!==currentCriteria[index]);return currentCriteria.splice(0,currentCriteria.length,...nextCriteria),await writeConfigSettingsIfChanged(context,changed,`config:set:${key}`),buildCriteriaResult(context,key,[...currentCriteria],changed)}async function setGovernancePresetOrTypeConfig(context,key,options){if(key==="governance_preset"){const nextPolicy=normalizeGovernancePreset(options.policy),changed2=context.settings.governance.preset!==nextPolicy;return context.settings.governance.preset=nextPolicy,await writeConfigSettingsIfChanged(context,changed2,"config:set:governance_preset"),buildPolicyResult(context,key,context.settings.governance.preset,changed2)}const policyProvided=typeof options.policy=="string",rawType=policyProvided?options.policy.trim():"";if(policyProvided&&rawType.length===0){const changed2=context.settings.governance.create_default_type!==void 0;return delete context.settings.governance.create_default_type,await writeConfigSettingsIfChanged(context,changed2,"config:set:governance_create_default_type"),buildPolicyResult(context,key,context.settings.governance.create_default_type??"",changed2)}if(rawType.length===0)throw new PmCliError('Config set governance-create-default-type requires an item type value (or an empty value "" to clear it)',EXIT_CODE.USAGE);const typeRegistry=resolveItemTypeRegistry(context.settings,getActiveExtensionRegistrations()),resolvedType=resolveTypeName(rawType,typeRegistry);if(!resolvedType)throw new PmCliError(buildInvalidTypeError(rawType,typeRegistry.types,resolveItemTypesFilePath(context.target.pmRoot,context.settings.schema)),EXIT_CODE.USAGE);const changed=context.settings.governance.create_default_type!==resolvedType;return context.settings.governance.create_default_type=resolvedType,await writeConfigSettingsIfChanged(context,changed,"config:set:governance_create_default_type"),buildPolicyResult(context,key,context.settings.governance.create_default_type,changed)}async function setGovernancePolicyConfig(context,key,options){if(key==="governance_ownership_enforcement"){const nextPolicy2=normalizeGovernanceOwnershipEnforcement(options.policy),changed2=context.settings.governance.preset!=="custom"||context.settings.governance.ownership_enforcement!==nextPolicy2;return context.settings.governance.preset="custom",context.settings.governance.ownership_enforcement=nextPolicy2,await writeConfigSettingsIfChanged(context,changed2,"config:set:governance_ownership_enforcement"),buildPolicyResult(context,key,context.settings.governance.ownership_enforcement,changed2)}if(key==="governance_create_mode_default"){const nextPolicy2=normalizeGovernanceCreateModeDefault(options.policy),changed2=context.settings.governance.preset!=="custom"||context.settings.governance.create_mode_default!==nextPolicy2;return context.settings.governance.preset="custom",context.settings.governance.create_mode_default=nextPolicy2,await writeConfigSettingsIfChanged(context,changed2,"config:set:governance_create_mode_default"),buildPolicyResult(context,key,context.settings.governance.create_mode_default,changed2)}const nextPolicy=normalizeGovernanceCloseValidationDefault(options.policy),changed=context.settings.governance.preset!=="custom"||context.settings.governance.close_validation_default!==nextPolicy;return context.settings.governance.preset="custom",context.settings.governance.close_validation_default=nextPolicy,await writeConfigSettingsIfChanged(context,changed,"config:set:governance_close_validation_default"),buildPolicyResult(context,key,context.settings.governance.close_validation_default,changed)}async function setGovernanceValidationConfig(context,key,options){if(key==="governance_parent_reference_policy"){const nextPolicy2=normalizeParentReferencePolicy(options.policy),changed2=context.settings.governance.preset!=="custom"||hasGovernanceValidationMirrorChange(context.settings.governance.parent_reference,context.settings.validation.parent_reference,nextPolicy2);return context.settings.governance.preset="custom",context.settings.governance.parent_reference=nextPolicy2,context.settings.validation.parent_reference=nextPolicy2,await writeConfigSettingsIfChanged(context,changed2,"config:set:governance_parent_reference_policy"),buildPolicyResult(context,key,context.settings.governance.parent_reference,changed2)}if(key==="governance_metadata_validation_profile"){const nextPolicy2=normalizeValidateMetadataProfile(options.policy),changed2=context.settings.governance.preset!=="custom"||hasGovernanceValidationMirrorChange(context.settings.governance.metadata_profile,context.settings.validation.metadata_profile,nextPolicy2);return context.settings.governance.preset="custom",context.settings.governance.metadata_profile=nextPolicy2,context.settings.validation.metadata_profile=nextPolicy2,await writeConfigSettingsIfChanged(context,changed2,"config:set:governance_metadata_validation_profile"),buildPolicyResult(context,key,context.settings.governance.metadata_profile,changed2)}const nextPolicy=normalizeGovernanceWorkflowEnforcement(options.policy),changed=(context.settings.governance.workflow_enforcement??"off")!==nextPolicy;return context.settings.governance.workflow_enforcement=nextPolicy,await writeConfigSettingsIfChanged(context,changed,"config:set:governance_workflow_enforcement"),buildPolicyResult(context,key,context.settings.governance.workflow_enforcement,changed)}async function setGovernanceBooleanConfig(context,key,options){if(key==="governance_require_close_reason"){const nextEnabled2=normalizeGovernanceRequireCloseReasonPolicy(options.policy)==="enabled",changed2=context.settings.governance.require_close_reason!==nextEnabled2;return context.settings.governance.require_close_reason=nextEnabled2,await writeConfigSettingsIfChanged(context,changed2,"config:set:governance_require_close_reason"),buildPolicyResult(context,key,context.settings.governance.require_close_reason?"enabled":"disabled",changed2)}const nextEnabled=normalizeGovernanceForceRequiredForStaleLockPolicy(options.policy)==="enabled",changed=context.settings.governance.preset!=="custom"||context.settings.governance.force_required_for_stale_lock!==nextEnabled;return context.settings.governance.preset="custom",context.settings.governance.force_required_for_stale_lock=nextEnabled,await writeConfigSettingsIfChanged(context,changed,"config:set:governance_force_required_for_stale_lock"),buildPolicyResult(context,key,context.settings.governance.force_required_for_stale_lock?"enabled":"disabled",changed)}async function setTrackingConfig(context,key,options){if(key==="test_result_tracking"){const nextEnabled2=normalizeTestResultTrackingPolicy(options.policy)==="enabled",changed2=context.settings.testing.record_results_to_items!==nextEnabled2;return context.settings.testing.record_results_to_items=nextEnabled2,await writeConfigSettingsIfChanged(context,changed2,"config:set:test_result_tracking"),buildPolicyResult(context,key,context.settings.testing.record_results_to_items?"enabled":"disabled",changed2)}if(key==="untrusted_linked_test_execution"){const nextEnabled2=normalizeEnabledDisabledPolicy(options.policy,"untrusted-linked-test-execution")==="enabled",changed2=context.settings.testing.allow_untrusted_linked_tests!==nextEnabled2;return context.settings.testing.allow_untrusted_linked_tests=nextEnabled2,await writeConfigSettingsIfChanged(context,changed2,"config:set:untrusted_linked_test_execution"),buildPolicyResult(context,key,context.settings.testing.allow_untrusted_linked_tests?"enabled":"disabled",changed2)}const nextEnabled=normalizeTelemetryTrackingPolicy(options.policy)==="enabled",changed=context.settings.telemetry.enabled!==nextEnabled||!context.settings.telemetry.first_run_prompt_completed;return context.settings.telemetry.enabled=nextEnabled,context.settings.telemetry.first_run_prompt_completed=!0,await writeConfigSettingsIfChanged(context,changed,"config:set:telemetry_tracking"),buildPolicyResult(context,key,context.settings.telemetry.enabled?"enabled":"disabled",changed)}async function setDefinitionOfDoneConfig(context,key,options){const nextCriteria=normalizeCriteria(options.criterion,options.clearCriteria),changed=nextCriteria.length!==context.settings.workflow.definition_of_done.length||nextCriteria.some((value,index)=>value!==context.settings.workflow.definition_of_done[index]);return context.settings.workflow.definition_of_done=nextCriteria,await writeConfigSettingsIfChanged(context,changed,"config:set:definition_of_done"),buildCriteriaResult(context,key,[...context.settings.workflow.definition_of_done],changed)}function parseAgentIdentityVocabularyOperation(raw){const policy=raw?.trim().toLowerCase().replaceAll("_","-"),dryRun=policy?.startsWith("preview-")===!0,operation=dryRun?policy.slice(8):policy;if(operation==="add"||operation==="remove"||operation==="clear")return{operation,dryRun};throw new PmCliError("Config set agent-identity-vocabulary requires --policy add|remove|clear|preview-add|preview-remove|preview-clear",EXIT_CODE.USAGE)}function parseAgentIdentityVocabularyMutationValue(operation,value){if(operation==="add"){const separator=value?.lastIndexOf("=")??-1;if(separator<=0||separator===value.length-1)throw new PmCliError('Config set agent-identity-vocabulary --policy add requires --value "<legacy-author>=<canonical-harness>"',EXIT_CODE.USAGE);return{legacy_author:value.slice(0,separator),canonical_harness:value.slice(separator+1)}}if(operation==="remove"){if(value===void 0)throw new PmCliError("Config set agent-identity-vocabulary --policy remove requires --value <legacy-author>",EXIT_CODE.USAGE);return{legacy_author:value}}if(value!==void 0)throw new PmCliError("Config set agent-identity-vocabulary --policy clear does not accept --value",EXIT_CODE.USAGE);return{}}async function setAgentIdentityVocabularyConfig(context,options){const{operation,dryRun}=parseAgentIdentityVocabularyOperation(options.policy),mutationValue=parseAgentIdentityVocabularyMutationValue(operation,options.value);let planned;try{planned=planAgentIdentityVocabularyMutation(context.settings.agent_identity?.identity_vocabulary,{operation,...mutationValue,observed_authors:options.criterion})}catch(error){throw new PmCliError(error.message,EXIT_CODE.USAGE)}return planned.preview.changed&&!dryRun&&(context.settings.agent_identity={...context.settings.agent_identity,identity_vocabulary:planned.vocabulary},await writeConfigSettingsIfChanged(context,!0,`config:set:agent_identity.identity_vocabulary:${operation}:v${planned.preview.version_after}`)),withWarnings({scope:context.scope,key:"agent_identity_vocabulary",identity_vocabulary:summarizeAgentIdentityVocabulary(dryRun?context.settings.agent_identity?.identity_vocabulary:planned.vocabulary),vocabulary_mutation:planned.preview,settings_path:context.target.settingsPath,changed:planned.preview.changed&&!dryRun},context.warnings)}async function setConfigValue(context,key,options){if(options.clearCriteria===!0&&!isCriteriaConfigKey(key))throw new PmCliError("--clear-criteria is only supported with config set criteria-list keys",EXIT_CODE.USAGE);return key==="item_format"?setItemFormatConfig(context,options):key==="context"?applyContextConfig(context.settings,options,context.target,context.scope,context.warnings):key==="agent_identity_vocabulary"?setAgentIdentityVocabularyConfig(context,options):key==="definition_of_done"?setDefinitionOfDoneConfig(context,key,options):isCriteriaValueConfigKey(key)?setCriteriaConfig(context,key,options):TRACKING_CONFIG_KEYS.has(key)?setTrackingConfig(context,key,options):GOVERNANCE_BOOLEAN_CONFIG_KEYS.has(key)?setGovernanceBooleanConfig(context,key,options):isGovernancePolicyConfigKey(key)?setGovernancePolicyConfig(context,key,options):isGovernanceValidationConfigKey(key)?setGovernanceValidationConfig(context,key,options):isGovernancePresetOrTypeConfigKey(key)?setGovernancePresetOrTypeConfig(context,key,options):setValidationConfig(context,key,options)}async function runConfig(scopeValue,actionValue,keyValue,options,global2,valueValue){const scope=normalizeScope(scopeValue),action=normalizeAction(actionValue),nestedSetting=action==="get"||action==="set"?resolveNestedSettingDescriptor(keyValue):void 0,key=nestedSetting?void 0:normalizeKeyForAction(action,keyValue),routedOptions=applyPositionalValue(action,keyValue,key,nestedSetting,valueValue,options),target=await resolveSettingsTarget(scope,global2),{settings,metadata,warnings:settingsReadWarnings}=await readSettingsWithMetadata(target.pmRoot),context={scope,target,settings,metadata,warnings:normalizeWarnings(settingsReadWarnings)};return nestedSetting?buildNestedSettingResult(context,action,nestedSetting,routedOptions):action==="list"?buildConfigListResult(context):action==="export"?buildConfigExportResult(context):(assertConfigKeyDefined(key),action==="get"?buildConfigGetResult(context,key):setConfigValue(context,key,routedOptions))}const _testOnlyConfigCommand={hasGovernanceValidationMirrorChange,applyPositionalValue,normalizeAction,normalizeCriteria,normalizeGovernanceCloseValidationDefault,normalizeGovernanceCreateModeDefault,normalizeGovernanceForceRequiredForStaleLockPolicy,normalizeGovernanceOwnershipEnforcement,normalizeGovernancePreset,normalizeGovernanceRequireCloseReasonPolicy,normalizeGovernanceWorkflowEnforcement,normalizeHistoryMissingStreamPolicy,normalizeItemFormat,normalizeKey,normalizeMetadataRequiredFields,normalizePolicyForConflict,normalizeScope,normalizeTelemetryTrackingPolicy,normalizeTestResultTrackingPolicy,normalizeValidateMetadataProfile,normalizeWarnings};export{_testOnlyConfigCommand,runConfig};
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="e8446c93-c40c-572d-86fa-d78535a6f66e")}catch{}})();import{resolveConfigPositionalValue}from"../core/config/positional-value.js";import{NESTED_SETTING_DESCRIPTORS,parseNestedSettingValue,readNestedSettingValue,resolveNestedSettingDescriptor,writeNestedSettingValue}from"../core/config/nested-settings.js";import{getActiveExtensionRegistrations}from"../core/extensions/index.js";import{normalizeParentReferencePolicy}from"../core/item/parent-reference-policy.js";import{normalizeSprintReleaseFormatPolicy}from"../core/item/sprint-release-format.js";import{resolveItemTypeRegistry,resolveTypeName}from"../core/item/type-registry.js";import{buildInvalidTypeError}from"../core/schema/item-types-file.js";import{resolveItemTypesFilePath}from"../core/schema/runtime-schema.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{createUnknownSubcommandError}from"./agent/subcommand-recovery.js";import{planAgentIdentityVocabularyMutation,summarizeAgentIdentityVocabulary}from"./agent/identity-config.js";import{assertInitializedTracker}from"./environment/tracker-preflight.js";import{migrateItemFilesToFormat}from"../core/store/item-format-migration.js";import{getSettingsPath,resolveGlobalPmRoot,resolvePmRoot}from"../core/store/paths.js";import{isSettingsReadFallback,readSettings,readSettingsWithMetadata,writeSettings}from"../core/store/settings.js";import{CONTEXT_DEPTH_VALUES}from"../types/index.js";const CONFIG_SCOPE_VALUES=["project","global"],CONFIG_KEY_ALIASES={definition_of_done:["definition-of-done","definition_of_done"],item_format:["item-format","item_format"],history_missing_stream_policy:["history-missing-stream-policy","history_missing_stream_policy"],sprint_release_format_policy:["sprint-release-format-policy","sprint_release_format_policy"],parent_reference_policy:["parent-reference-policy","parent_reference_policy"],metadata_validation_profile:["metadata-validation-profile","metadata_validation_profile"],metadata_required_fields:["metadata-required-fields","metadata_required_fields"],lifecycle_stale_blocker_reason_patterns:["lifecycle-stale-blocker-reason-patterns","lifecycle_stale_blocker_reason_patterns"],lifecycle_closure_like_blocked_reason_patterns:["lifecycle-closure-like-blocked-reason-patterns","lifecycle_closure_like_blocked_reason_patterns"],lifecycle_closure_like_resolution_patterns:["lifecycle-closure-like-resolution-patterns","lifecycle_closure_like_resolution_patterns"],lifecycle_closure_like_actual_result_patterns:["lifecycle-closure-like-actual-result-patterns","lifecycle_closure_like_actual_result_patterns"],governance_preset:["governance-preset","governance_preset"],governance_ownership_enforcement:["governance-ownership-enforcement","governance_ownership_enforcement"],governance_create_mode_default:["governance-create-mode-default","governance_create_mode_default"],governance_close_validation_default:["governance-close-validation-default","governance_close_validation_default"],governance_require_close_reason:["governance-require-close-reason","governance_require_close_reason"],governance_create_default_type:["governance-create-default-type","governance_create_default_type"],governance_workflow_enforcement:["governance-workflow-enforcement","governance_workflow_enforcement"],governance_parent_reference_policy:["governance-parent-reference-policy","governance_parent_reference_policy"],governance_metadata_validation_profile:["governance-metadata-validation-profile","governance_metadata_validation_profile"],governance_force_required_for_stale_lock:["governance-force-required-for-stale-lock","governance_force_required_for_stale_lock"],test_result_tracking:["test-result-tracking","test_result_tracking"],untrusted_linked_test_execution:["untrusted-linked-test-execution","untrusted_linked_test_execution"],telemetry_tracking:["telemetry-tracking","telemetry_tracking"],agent_identity_vocabulary:["agent-identity-vocabulary","agent_identity_vocabulary"],context:["context"]},CANONICAL_CONFIG_KEYS=Object.keys(CONFIG_KEY_ALIASES).map(candidate=>CONFIG_KEY_ALIASES[candidate][0]),CONFIG_KEY_BY_ALIAS=Object.fromEntries(Object.keys(CONFIG_KEY_ALIASES).flatMap(key=>CONFIG_KEY_ALIASES[key].map(alias=>[alias,key]))),CONFIG_KEY_SUMMARIES={definition_of_done:"Definition of Done criteria list.",item_format:"Default item file format.",history_missing_stream_policy:"Missing history stream handling policy.",sprint_release_format_policy:"Sprint/release format validation policy.",parent_reference_policy:"Parent reference validation policy.",metadata_validation_profile:"Validate metadata profile policy (core|strict|custom).",metadata_required_fields:"Validate custom metadata required-fields list.",lifecycle_stale_blocker_reason_patterns:"Validate lifecycle stale-blocker reason substring patterns (criteria list).",lifecycle_closure_like_blocked_reason_patterns:"Validate lifecycle closure-like blocked_reason substring patterns (criteria list).",lifecycle_closure_like_resolution_patterns:"Validate lifecycle closure-like resolution substring patterns (criteria list).",lifecycle_closure_like_actual_result_patterns:"Validate lifecycle closure-like actual_result substring patterns (criteria list).",governance_preset:"Governance preset policy (minimal|default|strict|custom).",governance_ownership_enforcement:"Governance ownership enforcement policy (none|warn|strict).",governance_create_mode_default:"Governance default create mode (progressive|strict).",governance_close_validation_default:"Governance default close validation mode (off|warn|strict).",governance_require_close_reason:"Governance close-reason requirement policy (enabled|disabled).",governance_create_default_type:"Governance default item type for `pm create` when --type is omitted.",governance_workflow_enforcement:"Governance per-type transition enforcement mode (off|warn|strict).",governance_parent_reference_policy:"Governance parent reference policy (warn|strict_error).",governance_metadata_validation_profile:"Governance metadata validation profile (core|strict|custom).",governance_force_required_for_stale_lock:"Governance stale-lock force policy (enabled|disabled).",test_result_tracking:"Item-level linked test result persistence policy.",untrusted_linked_test_execution:"Permit an explicit per-run override for commands not trusted by this clone.",telemetry_tracking:"Telemetry usage reporting policy.",agent_identity_vocabulary:"Versioned exact legacy-author interpretation vocabulary (summary only).",context:"Context command settings (depth, section toggles, limits)."},LIFECYCLE_PATTERN_CONFIG_KEYS=["lifecycle_stale_blocker_reason_patterns","lifecycle_closure_like_blocked_reason_patterns","lifecycle_closure_like_resolution_patterns","lifecycle_closure_like_actual_result_patterns"],CRITERIA_CONFIG_KEYS=new Set(["metadata_required_fields",...LIFECYCLE_PATTERN_CONFIG_KEYS]),TRACKING_CONFIG_KEYS=new Set(["test_result_tracking","untrusted_linked_test_execution","telemetry_tracking"]),GOVERNANCE_BOOLEAN_CONFIG_KEYS=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock"]),GOVERNANCE_POLICY_CONFIG_KEYS=new Set(["governance_ownership_enforcement","governance_create_mode_default","governance_close_validation_default"]),GOVERNANCE_VALIDATION_CONFIG_KEYS=new Set(["governance_parent_reference_policy","governance_metadata_validation_profile","governance_workflow_enforcement"]),GOVERNANCE_PRESET_OR_TYPE_CONFIG_KEYS=new Set(["governance_preset","governance_create_default_type"]),isCriteriaValueConfigKey=key=>CRITERIA_CONFIG_KEYS.has(key),isGovernancePolicyConfigKey=key=>GOVERNANCE_POLICY_CONFIG_KEYS.has(key),isGovernanceValidationConfigKey=key=>GOVERNANCE_VALIDATION_CONFIG_KEYS.has(key),isGovernancePresetOrTypeConfigKey=key=>GOVERNANCE_PRESET_OR_TYPE_CONFIG_KEYS.has(key);function isCriteriaConfigKey(key){return key==="definition_of_done"||isCriteriaValueConfigKey(key)}function normalizeScope(value){if(CONFIG_SCOPE_VALUES.includes(value))return value;throw new PmCliError(`Invalid config scope "${value}". Allowed: ${CONFIG_SCOPE_VALUES.join(", ")}`,EXIT_CODE.USAGE)}function normalizeAction(value){if(value==="get"||value==="set"||value==="list"||value==="export")return value;throw createUnknownSubcommandError({command_path:"config",token:value.trim()||"<empty>",allowed:["export","get","list","set"],token_kind:"action"})}function normalizeKey(value){const key=CONFIG_KEY_BY_ALIAS[value];if(key)return key;const nestedKeys=NESTED_SETTING_DESCRIPTORS.map(descriptor=>descriptor.key).join(", ");throw new PmCliError(`Invalid config key "${value}". Supported: ${CANONICAL_CONFIG_KEYS.join(", ")} (underscore variants also accepted). Nested leaf settings: ${nestedKeys}.`,EXIT_CODE.USAGE)}function normalizeCriteria(values,clearCriteria){const normalized=[...new Set((values??[]).map(value=>value.trim()).filter(value=>value.length>0))].sort((left,right)=>left.localeCompare(right));if(clearCriteria){if(normalized.length>0)throw new PmCliError("Config set definition-of-done cannot combine --clear-criteria with --criterion values",EXIT_CODE.USAGE);return[]}if(normalized.length===0)throw new PmCliError("Config set definition-of-done requires at least one non-empty --criterion value (or --clear-criteria to clear)",EXIT_CODE.USAGE);return normalized}function normalizeItemFormat(value){const normalized=value?.trim().toLowerCase();if(normalized==="toon")return"toon";throw normalized==="json_markdown"?new PmCliError("Config set item-format no longer accepts json_markdown. Markdown item files are legacy read/migration input only.",EXIT_CODE.USAGE):new PmCliError("Config set item-format requires --format toon",EXIT_CODE.USAGE)}function normalizeHistoryMissingStreamPolicy(value){const normalized=value?.trim().toLowerCase().replaceAll("-","_");if(normalized==="auto_create"||normalized==="strict_error")return normalized;throw new PmCliError("Config set history-missing-stream-policy requires --policy with one of: auto_create, strict_error",EXIT_CODE.USAGE)}function normalizeTestResultTrackingPolicy(value){return normalizeEnabledDisabledPolicy(value,"test-result-tracking")}function normalizeEnabledDisabledPolicy(value,key){const normalized=value?.trim().toLowerCase().replaceAll("-","_");if(normalized==="enabled"||normalized==="disabled")return normalized;throw new PmCliError(`Config set ${key} requires --policy with one of: enabled, disabled`,EXIT_CODE.USAGE)}function normalizeTelemetryTrackingPolicy(value){const normalized=value?.trim().toLowerCase().replaceAll("-","_");if(normalized==="enabled"||normalized==="disabled")return normalized;throw new PmCliError("Config set telemetry-tracking requires --policy with one of: enabled, disabled",EXIT_CODE.USAGE)}function normalizeValidateMetadataProfile(value){const normalized=value?.trim().toLowerCase().replaceAll("-","_");if(normalized==="core"||normalized==="strict"||normalized==="custom")return normalized;throw new PmCliError("Config set metadata-validation-profile requires --policy with one of: core, strict, custom",EXIT_CODE.USAGE)}function normalizeGovernancePreset(value){const normalized=value?.trim().toLowerCase().replaceAll("-","_");if(normalized==="minimal"||normalized==="default"||normalized==="strict"||normalized==="custom")return normalized;throw new PmCliError("Config set governance-preset requires --policy with one of: minimal, default, strict, custom",EXIT_CODE.USAGE)}function normalizeGovernanceOwnershipEnforcement(value){const normalized=value?.trim().toLowerCase().replaceAll("-","_");if(normalized==="none"||normalized==="warn"||normalized==="strict")return normalized;throw new PmCliError("Config set governance-ownership-enforcement requires --policy with one of: none, warn, strict",EXIT_CODE.USAGE)}function normalizeGovernanceCreateModeDefault(value){const normalized=value?.trim().toLowerCase().replaceAll("-","_");if(normalized==="progressive"||normalized==="strict")return normalized;throw new PmCliError("Config set governance-create-mode-default requires --policy with one of: progressive, strict",EXIT_CODE.USAGE)}function normalizeGovernanceCloseValidationDefault(value){const normalized=value?.trim().toLowerCase().replaceAll("-","_");if(normalized==="off"||normalized==="warn"||normalized==="strict")return normalized;if(normalized==="none"||normalized==="disabled")return"off";throw new PmCliError("Config set governance-close-validation-default requires --policy with one of: off, warn, strict",EXIT_CODE.USAGE)}function normalizeGovernanceWorkflowEnforcement(value){const normalized=typeof value=="string"?value.trim().toLowerCase().replaceAll("-","_"):void 0;if(normalized==="off"||normalized==="warn"||normalized==="strict")return normalized;if(normalized==="none"||normalized==="disabled")return"off";throw new PmCliError("Config set governance-workflow-enforcement requires one of: off, warn, strict",EXIT_CODE.USAGE)}function normalizeGovernanceForceRequiredForStaleLockPolicy(value){const normalized=value?.trim().toLowerCase().replaceAll("-","_");if(normalized==="enabled"||normalized==="disabled")return normalized;throw new PmCliError("Config set governance-force-required-for-stale-lock requires --policy with one of: enabled, disabled",EXIT_CODE.USAGE)}function normalizeGovernanceRequireCloseReasonPolicy(value){const normalized=value?.trim().toLowerCase().replaceAll("-","_");if(normalized==="enabled"||normalized==="disabled")return normalized;throw new PmCliError("Config set governance-require-close-reason requires --policy with one of: enabled, disabled",EXIT_CODE.USAGE)}const ENABLED_DISABLED_CONFLICT_POLICY_KEYS={test_result_tracking:"test-result-tracking",untrusted_linked_test_execution:"untrusted-linked-test-execution"};function normalizePolicyForConflict(key,value){const enabledDisabledKey=ENABLED_DISABLED_CONFLICT_POLICY_KEYS[key];if(enabledDisabledKey)return normalizeEnabledDisabledPolicy(value,enabledDisabledKey);switch(key){case"history_missing_stream_policy":return normalizeHistoryMissingStreamPolicy(value);case"sprint_release_format_policy":return normalizeSprintReleaseFormatPolicy(value);case"parent_reference_policy":case"governance_parent_reference_policy":return normalizeParentReferencePolicy(value);case"metadata_validation_profile":case"governance_metadata_validation_profile":return normalizeValidateMetadataProfile(value);case"governance_preset":return normalizeGovernancePreset(value);case"governance_ownership_enforcement":return normalizeGovernanceOwnershipEnforcement(value);case"governance_create_mode_default":return normalizeGovernanceCreateModeDefault(value);case"governance_close_validation_default":return normalizeGovernanceCloseValidationDefault(value);case"governance_require_close_reason":return normalizeGovernanceRequireCloseReasonPolicy(value);case"governance_workflow_enforcement":return normalizeGovernanceWorkflowEnforcement(value);case"governance_force_required_for_stale_lock":return normalizeGovernanceForceRequiredForStaleLockPolicy(value);case"telemetry_tracking":return normalizeTelemetryTrackingPolicy(value);default:return value.trim().toLowerCase().replaceAll("-","_")}}const METADATA_REQUIRED_FIELD_ALIAS_MAP={author:"author",acceptance_criteria:"acceptance_criteria","acceptance-criteria":"acceptance_criteria",estimated_minutes:"estimated_minutes","estimated-minutes":"estimated_minutes",estimate:"estimated_minutes",close_reason:"close_reason","close-reason":"close_reason",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release"},METADATA_REQUIRED_FIELD_OPTIONS=["author","acceptance_criteria","estimated_minutes","close_reason","reviewer","risk","confidence","sprint","release"];function normalizeMetadataRequiredFields(values,clearCriteria){const normalized=[...new Set((values??[]).map(value=>value.trim()).filter(value=>value.length>0))];if(clearCriteria){if(normalized.length>0)throw new PmCliError("Config set metadata-required-fields cannot combine --clear-criteria with --criterion values",EXIT_CODE.USAGE);return[]}if(normalized.length===0)throw new PmCliError("Config set metadata-required-fields requires at least one --criterion value (or --clear-criteria to clear)",EXIT_CODE.USAGE);const lowered=normalized.map(value=>value.toLowerCase().replaceAll("-","_")),unsupported=lowered.filter(value=>METADATA_REQUIRED_FIELD_ALIAS_MAP[value]===void 0);if(unsupported.length>0)throw new PmCliError(`Config set metadata-required-fields received unsupported values: ${unsupported.join(", ")}. Supported values: ${METADATA_REQUIRED_FIELD_OPTIONS.join(", ")}`,EXIT_CODE.USAGE);return[...new Set(lowered.map(value=>METADATA_REQUIRED_FIELD_ALIAS_MAP[value]))].sort((left,right)=>left.localeCompare(right))}function normalizeLifecyclePatternCriteria(key,values,clearCriteria){const normalized=[...new Set((values??[]).map(value=>value.trim().toLowerCase()).filter(value=>value.length>0))].sort((left,right)=>left.localeCompare(right));if(clearCriteria){if(normalized.length>0)throw new PmCliError(`Config set ${CONFIG_KEY_ALIASES[key][0]} cannot combine --clear-criteria with --criterion values`,EXIT_CODE.USAGE);return[]}if(normalized.length===0)throw new PmCliError(`Config set ${CONFIG_KEY_ALIASES[key][0]} requires at least one --criterion value (or --clear-criteria to clear)`,EXIT_CODE.USAGE);return normalized}function normalizeWarnings(values){return[...new Set(values)].sort((left,right)=>left.localeCompare(right))}function normalizeKeyForAction(action,value){if(action==="list"||action==="export"){if(typeof value=="string"&&value.trim().length>0)throw new PmCliError(`Config action "${action}" does not accept <key>`,EXIT_CODE.USAGE);return}if(typeof value!="string"||value.trim().length===0)throw new PmCliError(`Config action "${action}" requires <key>`,EXIT_CODE.USAGE);return normalizeKey(value)}function assertConfigKeyDefined(key){if(!key)throw new PmCliError("Config action requires <key>",EXIT_CODE.USAGE)}const CONFIG_VALUE_READERS={definition_of_done:settings=>[...settings.workflow.definition_of_done],item_format:settings=>settings.item_format,history_missing_stream_policy:settings=>settings.history.missing_stream,sprint_release_format_policy:settings=>settings.validation.sprint_release_format,parent_reference_policy:settings=>settings.validation.parent_reference,metadata_validation_profile:settings=>settings.validation.metadata_profile,metadata_required_fields:settings=>[...settings.validation.metadata_required_fields],lifecycle_stale_blocker_reason_patterns:settings=>[...settings.validation.lifecycle_stale_blocker_reason_patterns],lifecycle_closure_like_blocked_reason_patterns:settings=>[...settings.validation.lifecycle_closure_like_blocked_reason_patterns],lifecycle_closure_like_resolution_patterns:settings=>[...settings.validation.lifecycle_closure_like_resolution_patterns],lifecycle_closure_like_actual_result_patterns:settings=>[...settings.validation.lifecycle_closure_like_actual_result_patterns],governance_preset:settings=>settings.governance.preset,governance_ownership_enforcement:settings=>settings.governance.ownership_enforcement,governance_create_mode_default:settings=>settings.governance.create_mode_default,governance_close_validation_default:settings=>settings.governance.close_validation_default,governance_require_close_reason:settings=>settings.governance.require_close_reason?"enabled":"disabled",governance_create_default_type:settings=>settings.governance.create_default_type??"",governance_workflow_enforcement:settings=>settings.governance.workflow_enforcement??"off",governance_parent_reference_policy:settings=>settings.governance.parent_reference,governance_metadata_validation_profile:settings=>settings.governance.metadata_profile,governance_force_required_for_stale_lock:settings=>settings.governance.force_required_for_stale_lock?"enabled":"disabled",test_result_tracking:settings=>settings.testing.record_results_to_items?"enabled":"disabled",untrusted_linked_test_execution:settings=>settings.testing.allow_untrusted_linked_tests?"enabled":"disabled",telemetry_tracking:settings=>settings.telemetry.enabled?"enabled":"disabled",agent_identity_vocabulary:settings=>summarizeAgentIdentityVocabulary(settings.agent_identity?.identity_vocabulary),context:settings=>({default_depth:settings.context.default_depth,activity_limit:settings.context.activity_limit,stale_threshold_days:settings.context.stale_threshold_days,next_ranking_policy:settings.context.next_ranking_policy,sections:{...settings.context.sections}})};function readConfigValue(settings,key){return CONFIG_VALUE_READERS[key](settings)}function withWarnings(result,warnings){return warnings.length===0?result:{...result,warnings}}async function resolveSettingsTarget(scope,global2){const cwd=process.cwd(),pmRoot=scope==="project"?resolvePmRoot(cwd,global2.path):resolveGlobalPmRoot(cwd),settingsPath=getSettingsPath(pmRoot);return scope==="project"&&await assertInitializedTracker(pmRoot),{pmRoot,settingsPath}}function parseSectionToggle(raw){if(raw===void 0)return;const normalized=raw.trim().toLowerCase();if(normalized==="true"||normalized==="enabled"||normalized==="on"||normalized==="1")return!0;if(normalized==="false"||normalized==="disabled"||normalized==="off"||normalized==="0")return!1;throw new PmCliError(`Context section toggle must be true|false|enabled|disabled, got "${raw}"`,EXIT_CODE.USAGE)}function parsePositiveContextInteger(rawValue,option){const raw=rawValue.trim(),parsed=Number(raw);if(/^\d+$/u.test(raw)&&Number.isSafeInteger(parsed)&&parsed>0)return parsed;throw new PmCliError(`Context ${option} must be a positive integer`,EXIT_CODE.USAGE)}async function applyContextConfig(settings,options,target,scope,warnings){let changed=!1;const ctx=settings.context,assignedPaths=[];if(options.defaultDepth!==void 0){const normalized=options.defaultDepth.trim().toLowerCase();if(!CONTEXT_DEPTH_VALUES.includes(normalized))throw new PmCliError(`Context --default-depth must be one of ${CONTEXT_DEPTH_VALUES.join("|")}`,EXIT_CODE.USAGE);assignedPaths.push("context.default_depth"),ctx.default_depth!==normalized&&(ctx.default_depth=normalized,changed=!0)}if(options.activityLimit!==void 0){const parsed=parsePositiveContextInteger(options.activityLimit,"--activity-limit");assignedPaths.push("context.activity_limit"),ctx.activity_limit!==parsed&&(ctx.activity_limit=parsed,changed=!0)}if(options.staleThresholdDays!==void 0){const parsed=parsePositiveContextInteger(options.staleThresholdDays,"--stale-threshold-days");assignedPaths.push("context.stale_threshold_days"),ctx.stale_threshold_days!==parsed&&(ctx.stale_threshold_days=parsed,changed=!0)}const sectionToggles=[["hierarchy",options.sectionHierarchy],["activity",options.sectionActivity],["progress",options.sectionProgress],["blockers",options.sectionBlockers],["files",options.sectionFiles],["workload",options.sectionWorkload],["staleness",options.sectionStaleness],["tests",options.sectionTests]];for(const[sectionName,rawValue]of sectionToggles){const toggle=parseSectionToggle(rawValue);if(toggle!==void 0){const key=sectionName;assignedPaths.push(`context.sections.${sectionName}`),ctx.sections[key]!==toggle&&(ctx.sections[key]=toggle,changed=!0)}}return(changed||isSettingsReadFallback(settings))&&(await writeSettings(target.pmRoot,settings,"config:set:context",{assignedPaths}),changed=!0),withWarnings({scope,key:"context",context_settings:{default_depth:ctx.default_depth,activity_limit:ctx.activity_limit,stale_threshold_days:ctx.stale_threshold_days,next_ranking_policy:ctx.next_ranking_policy,sections:{...ctx.sections}},settings_path:target.settingsPath,changed},warnings)}function applyNestedSettingPositionalValue(keyValue,valueValue,options){if(options.value!==void 0&&options.value!==valueValue)throw new PmCliError(`Config set ${keyValue} received both positional value "${valueValue}" and --value "${options.value}". Pass only one.`,EXIT_CODE.USAGE);return{...options,value:valueValue}}function applyPositionalValue(action,keyValue,normalizedKey,nestedSetting,valueValue,options){if(valueValue===void 0)return options;if(action!=="set")throw new PmCliError(`Config action "${action}" does not accept a positional value. Only "set" takes <value>.`,EXIT_CODE.USAGE);if(typeof keyValue!="string"||keyValue.trim().length===0)throw new PmCliError('Config action "set" requires <key> before a positional <value>.',EXIT_CODE.USAGE);if(nestedSetting)return applyNestedSettingPositionalValue(keyValue,valueValue,options);assertConfigKeyDefined(normalizedKey);const routed=resolveConfigPositionalValue(normalizedKey,valueValue);if(!routed.routable)throw new PmCliError(routed.reason,EXIT_CODE.USAGE);if(routed.flag==="criterion"){if(options.criterion!==void 0&&options.criterion.length>0)throw new PmCliError(`Config set ${keyValue} received both positional value "${valueValue}" and --criterion. Pass criteria via --criterion only when supplying more than one value.`,EXIT_CODE.USAGE);return{...options,criterion:routed.values}}if(routed.flag==="format")return{...options,format:routed.value};if(options.policy!==void 0&&normalizePolicyForConflict(normalizedKey,options.policy)!==normalizePolicyForConflict(normalizedKey,routed.value))throw new PmCliError(`Config set ${keyValue} received both positional value "${valueValue}" and --policy "${options.policy}". Pass only one.`,EXIT_CODE.USAGE);return{...options,policy:routed.value}}function buildConfigListResult(context){const keys=Object.keys(CONFIG_KEY_ALIASES).map(candidate=>({key:candidate,aliases:CONFIG_KEY_ALIASES[candidate],value_kind:candidate==="context"||candidate==="agent_identity_vocabulary"?"object":isCriteriaConfigKey(candidate)?"string_array":"enum",set_flags:candidate==="context"?["--default-depth","--activity-limit","--stale-threshold-days","--section-<name>"]:candidate==="agent_identity_vocabulary"?["--policy","--value","--criterion"]:isCriteriaConfigKey(candidate)?["--criterion","--clear-criteria"]:candidate==="item_format"?["--format"]:["--policy"],summary:CONFIG_KEY_SUMMARIES[candidate],value:readConfigValue(context.settings,candidate)})),nestedSettings=NESTED_SETTING_DESCRIPTORS.map(descriptor=>({key:descriptor.key,canonical_key:descriptor.key.replaceAll("_","-"),path:descriptor.path,kind:descriptor.kind,value:readNestedSettingValue(context.settings,descriptor),summary:descriptor.summary,...descriptor.choices?{choices:[...descriptor.choices]}:{},...descriptor.min===void 0?{}:{min:descriptor.min},...descriptor.max===void 0?{}:{max:descriptor.max}}));return withWarnings({scope:context.scope,keys,nested_settings:nestedSettings,count:keys.length,settings_path:context.target.settingsPath,changed:!1},context.warnings)}function buildConfigExportResult(context){const values=Object.fromEntries(Object.keys(CONFIG_KEY_ALIASES).map(key=>[key,readConfigValue(context.settings,key)]));return withWarnings({scope:context.scope,values,settings_path:context.target.settingsPath,changed:!1},context.warnings)}function buildConfigGetResult(context,key){const value=readConfigValue(context.settings,key),base={scope:context.scope,key,settings_path:context.target.settingsPath,changed:!1};return key==="item_format"?withWarnings({...base,format:context.settings.item_format,has_explicit_item_format:context.metadata.has_explicit_item_format},context.warnings):key==="context"?withWarnings({...base,context_settings:value},context.warnings):key==="agent_identity_vocabulary"?withWarnings({...base,identity_vocabulary:value},context.warnings):Array.isArray(value)?withWarnings({...base,criteria:value},context.warnings):withWarnings({...base,policy:value},context.warnings)}async function buildNestedSettingResult(context,action,nestedSetting,options){if(action==="get"){const currentValue=readNestedSettingValue(context.settings,nestedSetting);return withWarnings({scope:context.scope,key:nestedSetting.key,nested_setting:{key:nestedSetting.key,path:nestedSetting.path,kind:nestedSetting.kind,value:currentValue},settings_path:context.target.settingsPath,changed:!1},context.warnings)}const rawValue=options.value;if(typeof rawValue!="string")throw new PmCliError(`Config set ${nestedSetting.key} requires a value. Pass it positionally (\`pm config ${context.scope} set ${nestedSetting.key} <value>\`) or via --value.`,EXIT_CODE.USAGE);const parsed=parseNestedSettingValue(nestedSetting,rawValue);if(!parsed.ok)throw new PmCliError(parsed.error.message,EXIT_CODE.USAGE);const changed=writeNestedSettingValue(context.settings,nestedSetting,parsed.parsed.value)||isSettingsReadFallback(context.settings);return changed&&await writeSettings(context.target.pmRoot,context.settings,`config:set:${nestedSetting.path}`,{assignedPaths:[nestedSetting.path]}),withWarnings({scope:context.scope,key:nestedSetting.key,nested_setting:{key:nestedSetting.key,path:nestedSetting.path,kind:nestedSetting.kind,value:parsed.parsed.value},settings_path:context.target.settingsPath,changed},context.warnings)}async function writeConfigSettingsIfChanged(context,changed,reason,assignedPaths=[]){(changed||isSettingsReadFallback(context.settings))&&(await writeSettings(context.target.pmRoot,context.settings,reason,{assignedPaths}),isSettingsReadFallback(context.settings)&&(context.fallbackRepairWritten=!0))}function hasGovernanceValidationMirrorChange(governanceValue,validationValue,nextPolicy){return governanceValue!==nextPolicy||validationValue!==nextPolicy}function buildPolicyResult(context,key,policy,changed){return withWarnings({scope:context.scope,key,policy,settings_path:context.target.settingsPath,changed},context.warnings)}function buildCriteriaResult(context,key,criteria,changed){return withWarnings({scope:context.scope,key,criteria,settings_path:context.target.settingsPath,changed},context.warnings)}async function migrateItemsForFormatChange(pmRoot,settings,nextFormat){const typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()),migrated=await migrateItemFilesToFormat(pmRoot,nextFormat,"config:set:item_format:migrate",typeRegistry.type_to_folder,settings.schema);return{target_format:migrated.target_format,scanned:migrated.scanned,migrated:migrated.migrated,removed:migrated.removed,warnings:migrated.warnings}}async function setItemFormatConfig(context,options){const nextFormat=normalizeItemFormat(options.format),changed=context.settings.item_format!==nextFormat||!context.metadata.has_explicit_item_format;let migration;if(changed){context.settings.item_format=nextFormat;const writeOptions={assignedPaths:["item_format"]};isSettingsReadFallback(context.settings)?(await writeSettings(context.target.pmRoot,context.settings,"config:set:item_format",writeOptions),context.fallbackRepairWritten=!0,migration=await migrateItemsForFormatChange(context.target.pmRoot,await readSettings(context.target.pmRoot),nextFormat)):(migration=await migrateItemsForFormatChange(context.target.pmRoot,context.settings,nextFormat),await writeSettings(context.target.pmRoot,context.settings,"config:set:item_format",writeOptions))}return withWarnings({scope:context.scope,key:"item_format",format:context.settings.item_format,has_explicit_item_format:!0,migration,settings_path:context.target.settingsPath,changed},context.warnings)}async function setValidationConfig(context,key,options){if(key==="history_missing_stream_policy"){const nextPolicy2=normalizeHistoryMissingStreamPolicy(options.policy),changed2=context.settings.history.missing_stream!==nextPolicy2;return context.settings.history.missing_stream=nextPolicy2,await writeConfigSettingsIfChanged(context,changed2,"config:set:history_missing_stream_policy",["history.missing_stream"]),buildPolicyResult(context,key,context.settings.history.missing_stream,changed2)}if(key==="sprint_release_format_policy"){const nextPolicy2=normalizeSprintReleaseFormatPolicy(options.policy),changed2=context.settings.validation.sprint_release_format!==nextPolicy2;return context.settings.validation.sprint_release_format=nextPolicy2,await writeConfigSettingsIfChanged(context,changed2,"config:set:sprint_release_format_policy",["validation.sprint_release_format"]),buildPolicyResult(context,key,context.settings.validation.sprint_release_format,changed2)}if(key==="parent_reference_policy"){const nextPolicy2=normalizeParentReferencePolicy(options.policy),changed2=context.settings.validation.parent_reference!==nextPolicy2||context.settings.governance.preset!=="custom"||context.settings.governance.parent_reference!==nextPolicy2;return context.settings.validation.parent_reference=nextPolicy2,context.settings.governance.preset="custom",context.settings.governance.parent_reference=nextPolicy2,await writeConfigSettingsIfChanged(context,changed2,"config:set:parent_reference_policy",["validation.parent_reference","governance.preset","governance.parent_reference"]),buildPolicyResult(context,key,context.settings.validation.parent_reference,changed2)}const nextPolicy=normalizeValidateMetadataProfile(options.policy),changed=context.settings.validation.metadata_profile!==nextPolicy||context.settings.governance.preset!=="custom"||context.settings.governance.metadata_profile!==nextPolicy;return context.settings.validation.metadata_profile=nextPolicy,context.settings.governance.preset="custom",context.settings.governance.metadata_profile=nextPolicy,await writeConfigSettingsIfChanged(context,changed,"config:set:metadata_validation_profile",["validation.metadata_profile","governance.preset","governance.metadata_profile"]),buildPolicyResult(context,key,context.settings.validation.metadata_profile,changed)}async function setCriteriaConfig(context,key,options){if(key==="metadata_required_fields"){const nextCriteria2=normalizeMetadataRequiredFields(options.criterion,options.clearCriteria),changed2=nextCriteria2.length!==context.settings.validation.metadata_required_fields.length||nextCriteria2.some((value,index)=>value!==context.settings.validation.metadata_required_fields[index]);return context.settings.validation.metadata_required_fields=nextCriteria2,await writeConfigSettingsIfChanged(context,changed2,"config:set:metadata_required_fields",["validation.metadata_required_fields"]),buildCriteriaResult(context,key,[...context.settings.validation.metadata_required_fields],changed2)}const currentCriteria={lifecycle_stale_blocker_reason_patterns:context.settings.validation.lifecycle_stale_blocker_reason_patterns,lifecycle_closure_like_blocked_reason_patterns:context.settings.validation.lifecycle_closure_like_blocked_reason_patterns,lifecycle_closure_like_resolution_patterns:context.settings.validation.lifecycle_closure_like_resolution_patterns,lifecycle_closure_like_actual_result_patterns:context.settings.validation.lifecycle_closure_like_actual_result_patterns}[key],nextCriteria=normalizeLifecyclePatternCriteria(key,options.criterion,options.clearCriteria),changed=nextCriteria.length!==currentCriteria.length||nextCriteria.some((value,index)=>value!==currentCriteria[index]);return currentCriteria.splice(0,currentCriteria.length,...nextCriteria),await writeConfigSettingsIfChanged(context,changed,`config:set:${key}`,[`validation.${key}`]),buildCriteriaResult(context,key,[...currentCriteria],changed)}async function setGovernancePresetOrTypeConfig(context,key,options){if(key==="governance_preset"){const nextPolicy=normalizeGovernancePreset(options.policy),changed2=context.settings.governance.preset!==nextPolicy;return context.settings.governance.preset=nextPolicy,await writeConfigSettingsIfChanged(context,changed2,"config:set:governance_preset",["governance.preset"]),buildPolicyResult(context,key,context.settings.governance.preset,changed2)}const policyProvided=typeof options.policy=="string",rawType=policyProvided?options.policy.trim():"";if(policyProvided&&rawType.length===0){const changed2=context.settings.governance.create_default_type!==void 0;return delete context.settings.governance.create_default_type,await writeConfigSettingsIfChanged(context,changed2,"config:set:governance_create_default_type",["governance.create_default_type"]),buildPolicyResult(context,key,context.settings.governance.create_default_type??"",changed2)}if(rawType.length===0)throw new PmCliError('Config set governance-create-default-type requires an item type value (or an empty value "" to clear it)',EXIT_CODE.USAGE);const typeRegistry=resolveItemTypeRegistry(context.settings,getActiveExtensionRegistrations()),resolvedType=resolveTypeName(rawType,typeRegistry);if(!resolvedType)throw new PmCliError(buildInvalidTypeError(rawType,typeRegistry.types,resolveItemTypesFilePath(context.target.pmRoot,context.settings.schema)),EXIT_CODE.USAGE);const changed=context.settings.governance.create_default_type!==resolvedType;return context.settings.governance.create_default_type=resolvedType,await writeConfigSettingsIfChanged(context,changed,"config:set:governance_create_default_type",["governance.create_default_type"]),buildPolicyResult(context,key,context.settings.governance.create_default_type,changed)}async function setGovernancePolicyConfig(context,key,options){if(key==="governance_ownership_enforcement"){const nextPolicy2=normalizeGovernanceOwnershipEnforcement(options.policy),changed2=context.settings.governance.preset!=="custom"||context.settings.governance.ownership_enforcement!==nextPolicy2;return context.settings.governance.preset="custom",context.settings.governance.ownership_enforcement=nextPolicy2,await writeConfigSettingsIfChanged(context,changed2,"config:set:governance_ownership_enforcement",["governance.preset","governance.ownership_enforcement"]),buildPolicyResult(context,key,context.settings.governance.ownership_enforcement,changed2)}if(key==="governance_create_mode_default"){const nextPolicy2=normalizeGovernanceCreateModeDefault(options.policy),changed2=context.settings.governance.preset!=="custom"||context.settings.governance.create_mode_default!==nextPolicy2;return context.settings.governance.preset="custom",context.settings.governance.create_mode_default=nextPolicy2,await writeConfigSettingsIfChanged(context,changed2,"config:set:governance_create_mode_default",["governance.preset","governance.create_mode_default"]),buildPolicyResult(context,key,context.settings.governance.create_mode_default,changed2)}const nextPolicy=normalizeGovernanceCloseValidationDefault(options.policy),changed=context.settings.governance.preset!=="custom"||context.settings.governance.close_validation_default!==nextPolicy;return context.settings.governance.preset="custom",context.settings.governance.close_validation_default=nextPolicy,await writeConfigSettingsIfChanged(context,changed,"config:set:governance_close_validation_default",["governance.preset","governance.close_validation_default"]),buildPolicyResult(context,key,context.settings.governance.close_validation_default,changed)}async function setGovernanceValidationConfig(context,key,options){if(key==="governance_parent_reference_policy"){const nextPolicy2=normalizeParentReferencePolicy(options.policy),changed2=context.settings.governance.preset!=="custom"||hasGovernanceValidationMirrorChange(context.settings.governance.parent_reference,context.settings.validation.parent_reference,nextPolicy2);return context.settings.governance.preset="custom",context.settings.governance.parent_reference=nextPolicy2,context.settings.validation.parent_reference=nextPolicy2,await writeConfigSettingsIfChanged(context,changed2,"config:set:governance_parent_reference_policy",["governance.preset","governance.parent_reference","validation.parent_reference"]),buildPolicyResult(context,key,context.settings.governance.parent_reference,changed2)}if(key==="governance_metadata_validation_profile"){const nextPolicy2=normalizeValidateMetadataProfile(options.policy),changed2=context.settings.governance.preset!=="custom"||hasGovernanceValidationMirrorChange(context.settings.governance.metadata_profile,context.settings.validation.metadata_profile,nextPolicy2);return context.settings.governance.preset="custom",context.settings.governance.metadata_profile=nextPolicy2,context.settings.validation.metadata_profile=nextPolicy2,await writeConfigSettingsIfChanged(context,changed2,"config:set:governance_metadata_validation_profile",["governance.preset","governance.metadata_profile","validation.metadata_profile"]),buildPolicyResult(context,key,context.settings.governance.metadata_profile,changed2)}const nextPolicy=normalizeGovernanceWorkflowEnforcement(options.policy),changed=(context.settings.governance.workflow_enforcement??"off")!==nextPolicy;return context.settings.governance.workflow_enforcement=nextPolicy,await writeConfigSettingsIfChanged(context,changed,"config:set:governance_workflow_enforcement",["governance.workflow_enforcement"]),buildPolicyResult(context,key,context.settings.governance.workflow_enforcement,changed)}async function setGovernanceBooleanConfig(context,key,options){if(key==="governance_require_close_reason"){const nextEnabled2=normalizeGovernanceRequireCloseReasonPolicy(options.policy)==="enabled",changed2=context.settings.governance.require_close_reason!==nextEnabled2;return context.settings.governance.require_close_reason=nextEnabled2,await writeConfigSettingsIfChanged(context,changed2,"config:set:governance_require_close_reason",["governance.require_close_reason"]),buildPolicyResult(context,key,context.settings.governance.require_close_reason?"enabled":"disabled",changed2)}const nextEnabled=normalizeGovernanceForceRequiredForStaleLockPolicy(options.policy)==="enabled",changed=context.settings.governance.preset!=="custom"||context.settings.governance.force_required_for_stale_lock!==nextEnabled;return context.settings.governance.preset="custom",context.settings.governance.force_required_for_stale_lock=nextEnabled,await writeConfigSettingsIfChanged(context,changed,"config:set:governance_force_required_for_stale_lock",["governance.preset","governance.force_required_for_stale_lock"]),buildPolicyResult(context,key,context.settings.governance.force_required_for_stale_lock?"enabled":"disabled",changed)}async function setTrackingConfig(context,key,options){if(key==="test_result_tracking"){const nextEnabled2=normalizeTestResultTrackingPolicy(options.policy)==="enabled",changed2=context.settings.testing.record_results_to_items!==nextEnabled2;return context.settings.testing.record_results_to_items=nextEnabled2,await writeConfigSettingsIfChanged(context,changed2,"config:set:test_result_tracking",["testing.record_results_to_items"]),buildPolicyResult(context,key,context.settings.testing.record_results_to_items?"enabled":"disabled",changed2)}if(key==="untrusted_linked_test_execution"){const nextEnabled2=normalizeEnabledDisabledPolicy(options.policy,"untrusted-linked-test-execution")==="enabled",changed2=context.settings.testing.allow_untrusted_linked_tests!==nextEnabled2;return context.settings.testing.allow_untrusted_linked_tests=nextEnabled2,await writeConfigSettingsIfChanged(context,changed2,"config:set:untrusted_linked_test_execution",["testing.allow_untrusted_linked_tests"]),buildPolicyResult(context,key,context.settings.testing.allow_untrusted_linked_tests?"enabled":"disabled",changed2)}const nextEnabled=normalizeTelemetryTrackingPolicy(options.policy)==="enabled",changed=context.settings.telemetry.enabled!==nextEnabled||!context.settings.telemetry.first_run_prompt_completed;return context.settings.telemetry.enabled=nextEnabled,context.settings.telemetry.first_run_prompt_completed=!0,await writeConfigSettingsIfChanged(context,changed,"config:set:telemetry_tracking",["telemetry.enabled","telemetry.first_run_prompt_completed"]),buildPolicyResult(context,key,context.settings.telemetry.enabled?"enabled":"disabled",changed)}async function setDefinitionOfDoneConfig(context,key,options){const nextCriteria=normalizeCriteria(options.criterion,options.clearCriteria),changed=nextCriteria.length!==context.settings.workflow.definition_of_done.length||nextCriteria.some((value,index)=>value!==context.settings.workflow.definition_of_done[index]);return context.settings.workflow.definition_of_done=nextCriteria,await writeConfigSettingsIfChanged(context,changed,"config:set:definition_of_done",["workflow.definition_of_done"]),buildCriteriaResult(context,key,[...context.settings.workflow.definition_of_done],changed)}function parseAgentIdentityVocabularyOperation(raw){const policy=raw?.trim().toLowerCase().replaceAll("_","-"),dryRun=policy?.startsWith("preview-")===!0,operation=dryRun?policy.slice(8):policy;if(operation==="add"||operation==="remove"||operation==="clear")return{operation,dryRun};throw new PmCliError("Config set agent-identity-vocabulary requires --policy add|remove|clear|preview-add|preview-remove|preview-clear",EXIT_CODE.USAGE)}function parseAgentIdentityVocabularyMutationValue(operation,value){if(operation==="add"){const separator=value?.lastIndexOf("=")??-1;if(separator<=0||separator===value.length-1)throw new PmCliError('Config set agent-identity-vocabulary --policy add requires --value "<legacy-author>=<canonical-harness>"',EXIT_CODE.USAGE);return{legacy_author:value.slice(0,separator),canonical_harness:value.slice(separator+1)}}if(operation==="remove"){if(value===void 0)throw new PmCliError("Config set agent-identity-vocabulary --policy remove requires --value <legacy-author>",EXIT_CODE.USAGE);return{legacy_author:value}}if(value!==void 0)throw new PmCliError("Config set agent-identity-vocabulary --policy clear does not accept --value",EXIT_CODE.USAGE);return{}}async function setAgentIdentityVocabularyConfig(context,options){const{operation,dryRun}=parseAgentIdentityVocabularyOperation(options.policy),mutationValue=parseAgentIdentityVocabularyMutationValue(operation,options.value);let planned;try{planned=planAgentIdentityVocabularyMutation(context.settings.agent_identity?.identity_vocabulary,{operation,...mutationValue,observed_authors:options.criterion})}catch(error){throw new PmCliError(error.message,EXIT_CODE.USAGE)}return planned.preview.changed&&!dryRun&&(context.settings.agent_identity={...context.settings.agent_identity,identity_vocabulary:planned.vocabulary},await writeConfigSettingsIfChanged(context,!0,`config:set:agent_identity.identity_vocabulary:${operation}:v${planned.preview.version_after}`,["agent_identity"])),withWarnings({scope:context.scope,key:"agent_identity_vocabulary",identity_vocabulary:summarizeAgentIdentityVocabulary(dryRun?context.settings.agent_identity?.identity_vocabulary:planned.vocabulary),vocabulary_mutation:planned.preview,settings_path:context.target.settingsPath,changed:planned.preview.changed&&!dryRun},context.warnings)}async function setConfigValue(context,key,options){const result=await dispatchConfigSetValue(context,key,options);return context.fallbackRepairWritten===!0?{...result,changed:!0}:result}async function dispatchConfigSetValue(context,key,options){if(options.clearCriteria===!0&&!isCriteriaConfigKey(key))throw new PmCliError("--clear-criteria is only supported with config set criteria-list keys",EXIT_CODE.USAGE);return key==="item_format"?setItemFormatConfig(context,options):key==="context"?applyContextConfig(context.settings,options,context.target,context.scope,context.warnings):key==="agent_identity_vocabulary"?setAgentIdentityVocabularyConfig(context,options):key==="definition_of_done"?setDefinitionOfDoneConfig(context,key,options):isCriteriaValueConfigKey(key)?setCriteriaConfig(context,key,options):TRACKING_CONFIG_KEYS.has(key)?setTrackingConfig(context,key,options):GOVERNANCE_BOOLEAN_CONFIG_KEYS.has(key)?setGovernanceBooleanConfig(context,key,options):isGovernancePolicyConfigKey(key)?setGovernancePolicyConfig(context,key,options):isGovernanceValidationConfigKey(key)?setGovernanceValidationConfig(context,key,options):isGovernancePresetOrTypeConfigKey(key)?setGovernancePresetOrTypeConfig(context,key,options):setValidationConfig(context,key,options)}async function runConfig(scopeValue,actionValue,keyValue,options,global2,valueValue){const scope=normalizeScope(scopeValue),action=normalizeAction(actionValue),nestedSetting=action==="get"||action==="set"?resolveNestedSettingDescriptor(keyValue):void 0,key=nestedSetting?void 0:normalizeKeyForAction(action,keyValue),routedOptions=applyPositionalValue(action,keyValue,key,nestedSetting,valueValue,options),target=await resolveSettingsTarget(scope,global2),{settings,metadata,warnings:settingsReadWarnings}=await readSettingsWithMetadata(target.pmRoot),context={scope,target,settings,metadata,warnings:normalizeWarnings(settingsReadWarnings)};return nestedSetting?buildNestedSettingResult(context,action,nestedSetting,routedOptions):action==="list"?buildConfigListResult(context):action==="export"?buildConfigExportResult(context):(assertConfigKeyDefined(key),action==="get"?buildConfigGetResult(context,key):setConfigValue(context,key,routedOptions))}const _testOnlyConfigCommand={hasGovernanceValidationMirrorChange,applyPositionalValue,normalizeAction,normalizeCriteria,normalizeGovernanceCloseValidationDefault,normalizeGovernanceCreateModeDefault,normalizeGovernanceForceRequiredForStaleLockPolicy,normalizeGovernanceOwnershipEnforcement,normalizeGovernancePreset,normalizeGovernanceRequireCloseReasonPolicy,normalizeGovernanceWorkflowEnforcement,normalizeHistoryMissingStreamPolicy,normalizeItemFormat,normalizeKey,normalizeMetadataRequiredFields,normalizePolicyForConflict,normalizeScope,normalizeTelemetryTrackingPolicy,normalizeTestResultTrackingPolicy,normalizeValidateMetadataProfile,normalizeWarnings};export{_testOnlyConfigCommand,runConfig};
|
|
2
2
|
//# sourceMappingURL=config.js.map
|
|
@@ -49,7 +49,24 @@ budget_derived_limit?:number;
|
|
|
49
49
|
binding_constraint?:"explicit_limit" | "token_budget";
|
|
50
50
|
/** Machine-readable explanation for the selected row ceiling. */
|
|
51
51
|
limit_reason?:string;
|
|
52
|
+
/** Present only when the intent's budget reduced a larger caller-supplied row limit. */
|
|
53
|
+
limit_override?:PmContextIntentLimitOverride;
|
|
52
54
|
}
|
|
55
|
+
/** Evidence that a declared intent budget reduced an explicit row limit, with the retry that keeps it. */
|
|
56
|
+
export interface PmContextIntentLimitOverride {
|
|
57
|
+
/** Flag whose explicit value the intent budget reduced. */
|
|
58
|
+
flag:"--limit";
|
|
59
|
+
/** Row limit the caller supplied. */
|
|
60
|
+
requested:number;
|
|
61
|
+
/** Row limit the intent budget applied. */
|
|
62
|
+
effective:number;
|
|
63
|
+
/** Smallest token budget, never below the current one, whose derived ceiling carries the requested rows; absent when no safe integer budget can. */
|
|
64
|
+
token_budget_for_requested?:number;
|
|
65
|
+
/** Flag to add to (or replace in) the original command so it keeps the requested limit, like an omission receipt's `restore_with`. */
|
|
66
|
+
restore_with?:string;
|
|
67
|
+
}
|
|
68
|
+
/** Stable warning code emitted when an intent budget reduces an explicit row limit. */
|
|
69
|
+
export declare const CONTEXT_INTENT_LIMIT_OVERRIDE_WARNING = "limit_overridden_by_intent";
|
|
53
70
|
/** Built-in intent projections shared by CLI, SDK, MCP, and package authors. */
|
|
54
71
|
export declare const PM_CONTEXT_INTENT_CONTRACTS:readonly PmContextIntentContract[];
|
|
55
72
|
/** Runtime declaration layers applied to one asynchronous SDK or CLI execution. */
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="417afa3c-d34b-53d9-b273-86903e17576f")}catch{}})();import{AsyncLocalStorage}from"node:async_hooks";import{attachExtensionReadOutputRows}from"./read-output/extension.js";import{renderPmCommand}from"./command-line.js";import{attachOutputOmissionReceipt}from"./output-projection.js";import{encodeQueryCursor}from"./pagination.js";import{applyReadOutputDimensions,stabilizeReadOutputReceiptEstimates}from"./read-output-contracts.js";import{propagateContextUsageServingReceipt}from"./context-usage.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{unicodeSafePrefix}from"../core/shared/text-normalization.js";const PM_CONTEXT_INTENT_CONTRACTS=Object.freeze([{command:"context",intent:"orient",description:"Bounded active hierarchy, ownership, blockers, and recent progress.",included_field_groups:["summary","focus","hierarchy","blockers","activity"],token_budget:3e3,source:"core"},{command:"context",intent:"handoff",description:"Active ownership, evidence, decisions, and immediate continuation context.",included_field_groups:["summary","focus","in_progress","decisions","activity"],token_budget:2200,source:"core"},{command:"get",intent:"inspect",description:"Standard-depth item metadata, relationships, evidence, and lifecycle state.",included_field_groups:["item","children","claim_state","linked"],token_budget:3200,source:"core"},{command:"list",intent:"triage",description:"A budget-derived page of compact governance, ownership, priority, and blocker rows for triage.",included_field_groups:["identity","governance","ownership","dependencies"],token_budget:3200,source:"core"},{command:"next",intent:"execute",description:"The highest-ranked actionable work with concise ranking evidence.",included_field_groups:["recommended"],token_budget:1200,source:"core"},{command:"search",intent:"discover",description:"A budget-derived page of ranked canonical lineage candidates with compact match evidence.",included_field_groups:["identity","status","lineage","match"],token_budget:1800,source:"core"}]),activeContextIntentContracts=new AsyncLocalStorage;function getActiveContextIntentContracts(){return activeContextIntentContracts.getStore()??PM_CONTEXT_INTENT_CONTRACTS}function runWithContextIntentContracts(layers,run){return activeContextIntentContracts.run(composeContextIntentContracts(layers.workspaceContracts,layers.packageContracts),run)}function normalizeContextIntentDeclaration(declaration,source){const command=declaration.command.trim().toLowerCase(),intent=declaration.intent.trim().toLowerCase(),key=`${command}:${intent}`;if(!/^[a-z0-9][a-z0-9-]*$/.test(command)||!/^[a-z0-9][a-z0-9-]*$/.test(intent))throw new TypeError(`Invalid context intent command or name: ${key}`);if(declaration.description.trim().length===0)throw new TypeError(`Context intent ${key} requires a non-empty description`);if(!Number.isSafeInteger(declaration.token_budget)||declaration.token_budget<=0)throw new TypeError(`Context intent ${key} requires a positive integer token_budget`);const includedFieldGroups=[...new Set(declaration.included_field_groups.map(field=>field.trim()).filter(Boolean))];if(includedFieldGroups.length===0)throw new TypeError(`Context intent ${key} requires included_field_groups`);return{command,intent,description:declaration.description.trim(),included_field_groups:includedFieldGroups,token_budget:declaration.token_budget,source}}function composeContextIntentContracts(workspaceContracts=[],packageContracts=[]){const layers=[{source:"core",contracts:PM_CONTEXT_INTENT_CONTRACTS,allowOverride:!1},{source:"package",contracts:packageContracts,allowOverride:!1},{source:"workspace",contracts:workspaceContracts,allowOverride:!0}],composed=new Map,keysSeenWithinLayer=new Set;for(const layer of layers){keysSeenWithinLayer.clear();for(const declaration of layer.contracts){const normalized=normalizeContextIntentDeclaration(declaration,layer.source),key=`${normalized.command}:${normalized.intent}`;if(keysSeenWithinLayer.has(key))throw new TypeError(`Duplicate context intent declaration: ${key}`);if(keysSeenWithinLayer.add(key),!layer.allowOverride&&composed.has(key))throw new TypeError(`Duplicate context intent declaration: ${key}`);composed.set(key,normalized)}}return[...composed.values()].sort((left,right)=>left.command.localeCompare(right.command)||left.intent.localeCompare(right.intent))}function resolveContextIntentContract(command,intent,contracts=getActiveContextIntentContracts(),positionalArguments=[]){const normalizedCommand=command.trim().toLowerCase(),normalizedIntent=intent.trim().toLowerCase(),exact=contracts.find(entry=>entry.command===normalizedCommand&&entry.intent===normalizedIntent);if(exact)return{...exact,source:exact.source??"core"};const candidates=contracts.filter(entry=>entry.command===normalizedCommand).map(entry=>entry.intent);if(candidates.length===0)return;const suggestion=candidates.map(candidate=>{const rows=Array.from({length:normalizedIntent.length+1},(_,index)=>index);for(let candidateIndex=1;candidateIndex<=candidate.length;candidateIndex+=1){let previous=rows[0];rows[0]=candidateIndex;for(let intentIndex=1;intentIndex<=normalizedIntent.length;intentIndex+=1){const prior=rows[intentIndex];rows[intentIndex]=Math.min(rows[intentIndex]+1,rows[intentIndex-1]+1,previous+(candidate[candidateIndex-1]===normalizedIntent[intentIndex-1]?0:1)),previous=prior}}return{candidate,distance:rows[normalizedIntent.length]}}).sort((left,right)=>left.distance-right.distance||left.candidate.localeCompare(right.candidate))[0].candidate,attemptedArguments=[normalizedCommand,...positionalArguments,"--for",normalizedIntent],suggestedRetryArguments=[normalizedCommand,...positionalArguments,"--for",suggestion],suggestedCommand=renderPmCommand(suggestedRetryArguments);throw new PmCliError(`Unknown context intent "${normalizedIntent}" for ${normalizedCommand}. Did you mean "${suggestion}"?`,EXIT_CODE.USAGE,{code:"unknown_context_intent",reason:"unknown_intent",field:"for",flag:"--for",value:normalizedIntent,required:`Use a declared ${normalizedCommand} intent.`,why:"Intent names are command-local contracts and cannot be inferred from output section names.",nextSteps:[suggestedCommand],recovery:{recovery_mode:"compact",attempted_command:renderPmCommand(attemptedArguments),allowed_values:[...candidates].sort(),suggested_retry:suggestedCommand,suggested_retry_args:suggestedRetryArguments}})}const CONTEXT_INTENT_DEFAULT_APPLIERS={context:(projected,contract,explicitTokenBudget)=>{projected.section===void 0&&projected.depth===void 0&&(projected.section=contract.intent==="handoff"?["activity","progress","blockers"]:["hierarchy","blockers","activity"]),projected.depth===void 0&&(projected.depth=contract.intent==="handoff"?"deep":"standard");const tokenBudget=resolveIntentTokenBudget(projected.tokenBudget,contract.token_budget),budgetDerivedLimit=resolveIntentRowBudget("context",contract.intent,tokenBudget,explicitTokenBudget),requestedLimit=parsePositiveIntentTokenBudget(projected.limit),derivedLimit=String(requestedLimit===void 0?budgetDerivedLimit:Math.min(requestedLimit,budgetDerivedLimit));(projected.limit===void 0||requestedLimit!==void 0)&&(projected.limit=derivedLimit),projected.activityLimit===void 0&&(projected.activityLimit=derivedLimit)},get:projected=>{projected.depth===void 0&&projected.fields===void 0&&(projected.depth="standard")},list:(projected,contract,explicitTokenBudget)=>{projected.brief===void 0&&projected.compact===void 0&&projected.full===void 0&&projected.fields===void 0&&(projected.fields="id,title,status,type,priority,parent,assignee,risk,blocked_by");const tokenBudget=resolveIntentTokenBudget(projected.tokenBudget,contract.token_budget),budgetDerivedLimit=resolveIntentRowBudget("list",contract.intent,tokenBudget,explicitTokenBudget),requestedLimit=parsePositiveIntentTokenBudget(projected.limit);(projected.limit===void 0||requestedLimit!==void 0)&&(projected.limit=String(requestedLimit===void 0?budgetDerivedLimit:Math.min(requestedLimit,budgetDerivedLimit)))},next:projected=>{projected.readyOnly===void 0&&(projected.readyOnly=!0)},search:(projected,contract,explicitTokenBudget)=>{projected.compact===void 0&&projected.full===void 0&&projected.fields===void 0&&(projected.compact=!0);const tokenBudget=resolveIntentTokenBudget(projected.tokenBudget,contract.token_budget),budgetDerivedLimit=resolveIntentRowBudget("search",contract.intent,tokenBudget,explicitTokenBudget),requestedLimit=parsePositiveIntentTokenBudget(projected.limit);(projected.limit===void 0||requestedLimit!==void 0)&&(projected.limit=String(requestedLimit===void 0?budgetDerivedLimit:Math.min(requestedLimit,budgetDerivedLimit)))}};function applyContextIntentProjection(command,options,positionalArguments=[]){const tokenBudget=options.tokenBudget??options.token_budget;if(typeof options.for!="string"){if(tokenBudget!==void 0&&(command==="get"||command==="list"||command==="search"))throw new PmCliError("--token-budget requires a declared context intent selected with --for",EXIT_CODE.USAGE,{code:"missing_required_option",field:"for",required:"Select a context intent with --for when setting --token-budget.",why:"A token-budget override has no projection contract to constrain without a selected intent.",nextSteps:["Retry with --for <intent> --token-budget <n>, or omit --token-budget."]});if(options.tokenBudget!==void 0||options.token_budget===void 0)return options;const projected2={...options,tokenBudget};return delete projected2.token_budget,projected2}const contract=resolveContextIntentContract(command,options.for,void 0,positionalArguments),explicitTokenBudget=parsePositiveIntentTokenBudget(tokenBudget)!==void 0,projected={...options};return projected.tokenBudget===void 0&&tokenBudget!==void 0&&(projected.tokenBudget=tokenBudget),delete projected.token_budget,projected.tokenBudget===void 0&&(projected.tokenBudget=String(contract.token_budget)),CONTEXT_INTENT_DEFAULT_APPLIERS[command](projected,contract,explicitTokenBudget),projected}const CONTEXT_INTENT_DEGRADATIONS={context:"bounded_sections",get:"standard_item",list:"bounded_fields_and_rows",next:"bounded_ranked_rows",search:"bounded_ranked_rows"},MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET=256;function compactContextIntentValue(value){return Array.isArray(value)?value.map(compactContextIntentValue):value!==null&&typeof value=="object"?Object.fromEntries(Object.entries(value).map(([key,entry])=>[key,compactContextIntentValue(entry)])):typeof value=="string"&&value.length>240?`${unicodeSafePrefix(value,240)}\u2026`:value}function parsePositiveIntentTokenBudget(value){const parsed=typeof value=="number"?value:typeof value=="string"&&/^\d+$/u.test(value.trim())?Number(value):Number.NaN;return Number.isSafeInteger(parsed)&&parsed>0?parsed:void 0}function resolveIntentTokenBudget(value,declaredBudget){const parsed=parsePositiveIntentTokenBudget(value);if(parsed===void 0)return declaredBudget;if(parsed<MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET)throw new PmCliError(`Context intent token budget must be at least ${MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET}`,EXIT_CODE.USAGE,{code:"invalid_argument_value",reason:"below_minimum",field:"tokenBudget",value:String(value),required:`Use an integer token budget of at least ${MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET}.`,why:"Smaller ceilings cannot contain the minimum machine-readable intent receipt.",nextSteps:[`Retry with --token-budget ${MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET} or omit the override.`]});return parsed}function resolveIntentRowBudget(command,intent,tokenBudget,explicitTokenBudget){if(command==="get"||command==="next")return;const contextOrient=command==="context"&&intent==="orient",overhead=command==="context"?contextOrient?1200:800:command==="list"?520:480,rowCost=command==="context"?contextOrient?600:500:16,calculatedLimit=Math.max(command==="context"?1:2,Math.floor((tokenBudget-overhead)/rowCost));return explicitTokenBudget?calculatedLimit:Math.min(command==="context"?20:100,calculatedLimit)}function updateContextIntentEstimate(projected,receipt){let measuredTokens=receipt.estimated_tokens;for(;;){receipt.estimated_tokens=measuredTokens;const nextMeasurement=Math.ceil(Buffer.byteLength(JSON.stringify(projected),"utf8")/4);if(nextMeasurement===measuredTokens)return;measuredTokens=nextMeasurement}}const CONTEXT_INTENT_ROW_KEYS={context:["high_level","low_level","blocked_fallback","recently_created","unparented","hierarchy","activity","blockers"],get:["children"],list:["items"],next:["ready","decision_needed","gate_needed","containers","blocked","held_by_others"],search:["items"]};function decodeContextIntentCursor(cursor){try{const parsed=JSON.parse(Buffer.from(cursor,"base64url").toString("utf8"));return typeof parsed.fingerprint!="string"||!Number.isSafeInteger(parsed.after_index)?void 0:{fingerprint:parsed.fingerprint,after_index:parsed.after_index,...typeof parsed.snapshot=="string"?{snapshot:parsed.snapshot}:{}}}catch{return}}function contextIntentRowId(row){if(row===null||typeof row!="object")return;if(typeof row.id=="string")return row.id;const nestedId=row.item?.id;return typeof nestedId=="string"?nestedId:void 0}function shrinkContextIntentRowsToBudget(projected,receipt,rows){let compacted=!1;for(;;){if(updateContextIntentEstimate(projected,receipt),receipt.estimated_tokens<=receipt.token_budget||rows.length<=1)return compacted;const rowBytes=Buffer.byteLength(JSON.stringify(rows),"utf8"),excessBytes=(receipt.estimated_tokens-receipt.token_budget)*4;rows.splice(-Math.min(rows.length-1,Math.max(1,Math.ceil(excessBytes/Math.max(1,Math.ceil(rowBytes/rows.length)))))),compacted=!0}}function compactPaginatedContextIntentRows(projected,receipt,options){const rows=projected.items,cursorContinuesExistingPage=typeof projected.next_cursor=="string",cursorSource=cursorContinuesExistingPage?projected.next_cursor:options.after;if(!Array.isArray(rows)||typeof cursorSource!="string")return!1;const cursorEnvelope=decodeContextIntentCursor(cursorSource);if(cursorEnvelope===void 0)return!1;const originalRowCount=rows.length,originalRows=[...rows];let compacted=!1;for(;;){if(compacted=shrinkContextIntentRowsToBudget(projected,receipt,rows)||compacted,!compacted)return!1;const lastId=contextIntentRowId(rows.at(-1));if(lastId===void 0)return rows.splice(0,rows.length,...originalRows),updateContextIntentEstimate(projected,receipt),!1;if(projected.next_cursor=encodeQueryCursor(cursorEnvelope.fingerprint,lastId,cursorContinuesExistingPage?cursorEnvelope.after_index-(originalRowCount-rows.length):cursorEnvelope.after_index+rows.length,cursorEnvelope.snapshot),updateContextIntentEstimate(projected,receipt),receipt.estimated_tokens<=receipt.token_budget||rows.length<=1)break}return typeof projected.count=="number"&&(projected.count=rows.length),typeof projected.applied_limit=="number"&&(projected.applied_limit=rows.length),!0}function compactContextIntentRows(command,projected,receipt,options){if(command==="list"||command==="search")return compactPaginatedContextIntentRows(projected,receipt,options);if(command!=="next"||typeof projected.next_cursor=="string")return!1;let compacted=!1;for(;;){if(updateContextIntentEstimate(projected,receipt),receipt.estimated_tokens<=receipt.token_budget)return compacted;const candidate=CONTEXT_INTENT_ROW_KEYS[command].map(key=>({key,rows:Array.isArray(projected[key])?projected[key]:[]})).filter(({rows})=>rows.length>0).sort((left,right)=>right.rows.length-left.rows.length||left.key.localeCompare(right.key))[0];if(candidate===void 0)return compacted;const retainedTotal=CONTEXT_INTENT_ROW_KEYS[command].reduce((total,key)=>total+(Array.isArray(projected[key])?projected[key].length:0),0);if(retainedTotal<=1)return compacted;const removableRows=Math.min(candidate.rows.length,retainedTotal-1),candidateBytes=Buffer.byteLength(JSON.stringify(candidate.rows),"utf8"),estimatedBytesPerRow=Math.max(1,Math.ceil(candidateBytes/candidate.rows.length)),excessBytes=(receipt.estimated_tokens-receipt.token_budget)*4,removalCount=Math.min(removableRows,Math.max(1,Math.ceil(excessBytes/estimatedBytesPerRow)));candidate.rows.splice(-removalCount,removalCount),compacted=!0}}function attachContextIntentReceipt(command,options,result){if(typeof options.for!="string")return result;const normalizedCommand=command.startsWith("list-")?"list":command;if(!(normalizedCommand in CONTEXT_INTENT_DEFAULT_APPLIERS))return result;const builtInCommand=normalizedCommand,contract=resolveContextIntentContract(builtInCommand,options.for),effectiveTokenBudget=resolveIntentTokenBudget(options.tokenBudget??options.token_budget,contract.token_budget),receipt={command:builtInCommand,intent:contract.intent,source:contract.source,included_field_groups:[...contract.included_field_groups],token_budget:effectiveTokenBudget,declared_token_budget:contract.token_budget,token_budget_override:effectiveTokenBudget-contract.token_budget,estimated_tokens:0,within_budget:!0,degradation:CONTEXT_INTENT_DEGRADATIONS[builtInCommand],declaration_feasible:!0,result_omitted:!1},resultWithDiagnostics={...result},budgetDerivedLimit=resolveIntentRowBudget(builtInCommand,contract.intent,receipt.token_budget,parsePositiveIntentTokenBudget(options.tokenBudget??options.token_budget)!==void 0);if(budgetDerivedLimit!==void 0){const effectiveLimit=parsePositiveIntentTokenBudget(options.limit),explicitLimitBinds=effectiveLimit!==void 0&&effectiveLimit<budgetDerivedLimit;receipt.budget_derived_limit=budgetDerivedLimit,receipt.binding_constraint=explicitLimitBinds?"explicit_limit":"token_budget",receipt.limit_reason=explicitLimitBinds?"The caller supplied a smaller row limit than the budget-derived ceiling.":"The selected intent token budget constrains the effective row ceiling.",resultWithDiagnostics.budget_derived_limit=budgetDerivedLimit}let projected={...resultWithDiagnostics,context_intent:receipt};return updateContextIntentEstimate(projected,receipt),receipt.estimated_tokens>receipt.token_budget&&(receipt.degradation="recursive_budget_compaction",projected={...compactContextIntentValue(resultWithDiagnostics),context_intent:receipt},updateContextIntentEstimate(projected,receipt)),receipt.estimated_tokens>receipt.token_budget&&compactContextIntentRows(builtInCommand,projected,receipt,options)&&(receipt.degradation="budget_row_compaction",updateContextIntentEstimate(projected,receipt)),receipt.declaration_feasible=receipt.estimated_tokens<=receipt.declared_token_budget,receipt.estimated_tokens>receipt.token_budget&&(receipt.degradation="budget_receipt_only",receipt.result_omitted=!0,receipt.within_budget=!1,projected={budget_exceeded:{omitted_result:!0,reason:receipt.token_budget_override===0?"declared_budget_infeasible":"effective_budget_infeasible",restore_with:buildContextIntentRecoveryCommand(command,builtInCommand,contract.intent,receipt,resultWithDiagnostics)},context_intent:receipt}),projected}const CONTINUATION_METADATA_KEYS=["applied_limit","completeness","context_intent","count","filters","has_more","now","omission_receipt","projection","row_contract","sorting","total","truncated"];function collapseContinuationMetadata(options,result){if(typeof options.after!="string"||options.after.length===0)return result;const fingerprint=decodeContextIntentCursor(options.after)?.fingerprint??"opaque_cursor",projected={...result};for(const key of CONTINUATION_METADATA_KEYS)delete projected[key];return projected.continuation_contract={fingerprint,metadata:"reference",restore_with:"omit --after"},projected}function isOutputRecord(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function buildContextIntentRecoveryCommand(command,builtInCommand,intent,receipt,result){const recoveryTarget=builtInCommand==="get"&&isOutputRecord(result.item)&&typeof result.item.id=="string"?result.item.id:builtInCommand==="search"&&typeof result.query=="string"?result.query:void 0,recoveryPositional=recoveryTarget===void 0?"":` '${recoveryTarget.replaceAll("'",`'"'"'`)}'`,boundedRowLimit=builtInCommand==="get"?"":` --limit ${receipt.budget_derived_limit??1}`;return`pm ${command}${recoveryPositional} --for ${intent} --token-budget ${Math.ceil(receipt.estimated_tokens/100)*100}${boundedRowLimit}`}function receiptEstimate(value,field){if(isOutputRecord(value))return typeof value[field]=="number"?value[field]:void 0}function stabilizeSuppressedRowContractReceipts(result,options){let finalized=result;for(let iteration=0;iteration<8;iteration+=1){const previousContextEstimate=receiptEstimate(finalized.context_intent,"estimated_tokens"),previousReadEstimate=receiptEstimate(finalized.read_output,"estimated_tokens"),previousSessionEstimate=receiptEstimate(finalized.read_session,"spent_this_call_tokens");if(isOutputRecord(finalized.context_intent)&&updateContextIntentEstimate(finalized,finalized.context_intent),finalized=stabilizeReadOutputReceiptEstimates(finalized,options),receiptEstimate(finalized.context_intent,"estimated_tokens")===previousContextEstimate&&receiptEstimate(finalized.read_output,"estimated_tokens")===previousReadEstimate&&receiptEstimate(finalized.read_session,"spent_this_call_tokens")===previousSessionEstimate)break}return finalized}function attachReadOutputContracts(command,options,result){const disclosedResult=attachOutputOmissionReceipt(command,attachExtensionReadOutputRows(command??"",result)),projected=typeof disclosedResult=="object"&&disclosedResult!==null&&!Array.isArray(disclosedResult)?applyReadOutputDimensions(command??"",{...options,outputRowContract:options.outputRowContract===!0||options.output_row_contract===!0},collapseContinuationMetadata(options,attachContextIntentReceipt(command??"",options,disclosedResult))):disclosedResult;if(propagateContextUsageServingReceipt(result,projected),options.outputRowContract===!0||options.output_row_contract===!0||typeof projected!="object"||projected===null||Array.isArray(projected)||!Object.hasOwn(projected,"row_contract"))return projected;const withoutDiscoveryMetadata=Object.fromEntries(Object.entries(projected).filter(([key])=>key!=="row_contract"));Object.defineProperty(withoutDiscoveryMetadata,"row_contract",{value:projected.row_contract,enumerable:!1,configurable:!0});const suppressed=stabilizeSuppressedRowContractReceipts(withoutDiscoveryMetadata,options);return delete suppressed.row_contract,propagateContextUsageServingReceipt(projected,suppressed),suppressed}export{PM_CONTEXT_INTENT_CONTRACTS,applyContextIntentProjection,attachContextIntentReceipt,attachReadOutputContracts,composeContextIntentContracts,contextIntentRowId,decodeContextIntentCursor,getActiveContextIntentContracts,resolveContextIntentContract,runWithContextIntentContracts};
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="4c8b43ab-cada-5adf-8c00-aed8de1a8bc1")}catch{}})();import{AsyncLocalStorage}from"node:async_hooks";import{attachExtensionReadOutputRows}from"./read-output/extension.js";import{renderPmCommand}from"./command-line.js";import{attachOutputOmissionReceipt}from"./output-projection.js";import{encodeQueryCursor}from"./pagination.js";import{applyReadOutputDimensions,stabilizeReadOutputReceiptEstimates}from"./read-output-contracts.js";import{propagateContextUsageServingReceipt}from"./context-usage.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{unicodeSafePrefix}from"../core/shared/text-normalization.js";const CONTEXT_INTENT_LIMIT_OVERRIDE_WARNING="limit_overridden_by_intent",PM_CONTEXT_INTENT_CONTRACTS=Object.freeze([{command:"context",intent:"orient",description:"Bounded active hierarchy, ownership, blockers, and recent progress.",included_field_groups:["summary","focus","hierarchy","blockers","activity"],token_budget:3e3,source:"core"},{command:"context",intent:"handoff",description:"Active ownership, evidence, decisions, and immediate continuation context.",included_field_groups:["summary","focus","in_progress","decisions","activity"],token_budget:2200,source:"core"},{command:"get",intent:"inspect",description:"Standard-depth item metadata, relationships, evidence, and lifecycle state.",included_field_groups:["item","children","claim_state","linked"],token_budget:3200,source:"core"},{command:"list",intent:"triage",description:"A budget-derived page of compact governance, ownership, priority, and blocker rows for triage.",included_field_groups:["identity","governance","ownership","dependencies"],token_budget:3200,source:"core"},{command:"next",intent:"execute",description:"The highest-ranked actionable work with concise ranking evidence.",included_field_groups:["recommended"],token_budget:1200,source:"core"},{command:"search",intent:"discover",description:"A budget-derived page of ranked canonical lineage candidates with compact match evidence.",included_field_groups:["identity","status","lineage","match"],token_budget:1800,source:"core"}]),activeContextIntentContracts=new AsyncLocalStorage;function getActiveContextIntentContracts(){return activeContextIntentContracts.getStore()??PM_CONTEXT_INTENT_CONTRACTS}function runWithContextIntentContracts(layers,run){return activeContextIntentContracts.run(composeContextIntentContracts(layers.workspaceContracts,layers.packageContracts),run)}function normalizeContextIntentDeclaration(declaration,source){const command=declaration.command.trim().toLowerCase(),intent=declaration.intent.trim().toLowerCase(),key=`${command}:${intent}`;if(!/^[a-z0-9][a-z0-9-]*$/.test(command)||!/^[a-z0-9][a-z0-9-]*$/.test(intent))throw new TypeError(`Invalid context intent command or name: ${key}`);if(declaration.description.trim().length===0)throw new TypeError(`Context intent ${key} requires a non-empty description`);if(!Number.isSafeInteger(declaration.token_budget)||declaration.token_budget<=0)throw new TypeError(`Context intent ${key} requires a positive integer token_budget`);const includedFieldGroups=[...new Set(declaration.included_field_groups.map(field=>field.trim()).filter(Boolean))];if(includedFieldGroups.length===0)throw new TypeError(`Context intent ${key} requires included_field_groups`);return{command,intent,description:declaration.description.trim(),included_field_groups:includedFieldGroups,token_budget:declaration.token_budget,source}}function composeContextIntentContracts(workspaceContracts=[],packageContracts=[]){const layers=[{source:"core",contracts:PM_CONTEXT_INTENT_CONTRACTS,allowOverride:!1},{source:"package",contracts:packageContracts,allowOverride:!1},{source:"workspace",contracts:workspaceContracts,allowOverride:!0}],composed=new Map,keysSeenWithinLayer=new Set;for(const layer of layers){keysSeenWithinLayer.clear();for(const declaration of layer.contracts){const normalized=normalizeContextIntentDeclaration(declaration,layer.source),key=`${normalized.command}:${normalized.intent}`;if(keysSeenWithinLayer.has(key))throw new TypeError(`Duplicate context intent declaration: ${key}`);if(keysSeenWithinLayer.add(key),!layer.allowOverride&&composed.has(key))throw new TypeError(`Duplicate context intent declaration: ${key}`);composed.set(key,normalized)}}return[...composed.values()].sort((left,right)=>left.command.localeCompare(right.command)||left.intent.localeCompare(right.intent))}function resolveContextIntentContract(command,intent,contracts=getActiveContextIntentContracts(),positionalArguments=[]){const normalizedCommand=command.trim().toLowerCase(),normalizedIntent=intent.trim().toLowerCase(),exact=contracts.find(entry=>entry.command===normalizedCommand&&entry.intent===normalizedIntent);if(exact)return{...exact,source:exact.source??"core"};const candidates=contracts.filter(entry=>entry.command===normalizedCommand).map(entry=>entry.intent);if(candidates.length===0)return;const suggestion=candidates.map(candidate=>{const rows=Array.from({length:normalizedIntent.length+1},(_,index)=>index);for(let candidateIndex=1;candidateIndex<=candidate.length;candidateIndex+=1){let previous=rows[0];rows[0]=candidateIndex;for(let intentIndex=1;intentIndex<=normalizedIntent.length;intentIndex+=1){const prior=rows[intentIndex];rows[intentIndex]=Math.min(rows[intentIndex]+1,rows[intentIndex-1]+1,previous+(candidate[candidateIndex-1]===normalizedIntent[intentIndex-1]?0:1)),previous=prior}}return{candidate,distance:rows[normalizedIntent.length]}}).sort((left,right)=>left.distance-right.distance||left.candidate.localeCompare(right.candidate))[0].candidate,attemptedArguments=[normalizedCommand,...positionalArguments,"--for",normalizedIntent],suggestedRetryArguments=[normalizedCommand,...positionalArguments,"--for",suggestion],suggestedCommand=renderPmCommand(suggestedRetryArguments);throw new PmCliError(`Unknown context intent "${normalizedIntent}" for ${normalizedCommand}. Did you mean "${suggestion}"?`,EXIT_CODE.USAGE,{code:"unknown_context_intent",reason:"unknown_intent",field:"for",flag:"--for",value:normalizedIntent,required:`Use a declared ${normalizedCommand} intent.`,why:"Intent names are command-local contracts and cannot be inferred from output section names.",nextSteps:[suggestedCommand],recovery:{recovery_mode:"compact",attempted_command:renderPmCommand(attemptedArguments),allowed_values:[...candidates].sort(),suggested_retry:suggestedCommand,suggested_retry_args:suggestedRetryArguments}})}function applyIntentRowLimit(projected,budgetDerivedLimit){const requestedLimit=parsePositiveIntentTokenBudget(projected.limit),effectiveLimit=String(requestedLimit===void 0?budgetDerivedLimit:Math.min(requestedLimit,budgetDerivedLimit));return(projected.limit===void 0||requestedLimit!==void 0)&&(projected.limit=effectiveLimit),effectiveLimit}const CONTEXT_INTENT_DEFAULT_APPLIERS={context:(projected,contract,explicitTokenBudget)=>{projected.section===void 0&&projected.depth===void 0&&(projected.section=contract.intent==="handoff"?["activity","progress","blockers"]:["hierarchy","blockers","activity"]),projected.depth===void 0&&(projected.depth=contract.intent==="handoff"?"deep":"standard");const tokenBudget=resolveIntentTokenBudget(projected.tokenBudget,contract.token_budget),budgetDerivedLimit=resolveIntentRowBudget("context",contract.intent,tokenBudget,explicitTokenBudget),derivedLimit=applyIntentRowLimit(projected,budgetDerivedLimit);projected.activityLimit===void 0&&(projected.activityLimit=derivedLimit)},get:projected=>{projected.depth===void 0&&projected.fields===void 0&&(projected.depth="standard")},list:(projected,contract,explicitTokenBudget)=>{projected.brief===void 0&&projected.compact===void 0&&projected.full===void 0&&projected.fields===void 0&&(projected.fields="id,title,status,type,priority,parent,assignee,risk,blocked_by");const tokenBudget=resolveIntentTokenBudget(projected.tokenBudget,contract.token_budget),budgetDerivedLimit=resolveIntentRowBudget("list",contract.intent,tokenBudget,explicitTokenBudget);applyIntentRowLimit(projected,budgetDerivedLimit)},next:projected=>{projected.readyOnly===void 0&&(projected.readyOnly=!0)},search:(projected,contract,explicitTokenBudget)=>{projected.compact===void 0&&projected.full===void 0&&projected.fields===void 0&&(projected.compact=!0);const tokenBudget=resolveIntentTokenBudget(projected.tokenBudget,contract.token_budget),budgetDerivedLimit=resolveIntentRowBudget("search",contract.intent,tokenBudget,explicitTokenBudget);applyIntentRowLimit(projected,budgetDerivedLimit)}};function applyContextIntentProjection(command,options,positionalArguments=[]){const tokenBudget=options.tokenBudget??options.token_budget;if(typeof options.for!="string"){if(tokenBudget!==void 0&&(command==="get"||command==="list"||command==="search"))throw new PmCliError("--token-budget requires a declared context intent selected with --for",EXIT_CODE.USAGE,{code:"missing_required_option",field:"for",required:"Select a context intent with --for when setting --token-budget.",why:"A token-budget override has no projection contract to constrain without a selected intent.",nextSteps:["Retry with --for <intent> --token-budget <n>, or omit --token-budget."]});if(options.tokenBudget!==void 0||options.token_budget===void 0)return options;const projected2={...options,tokenBudget};return delete projected2.token_budget,projected2}const contract=resolveContextIntentContract(command,options.for,void 0,positionalArguments),explicitTokenBudget=parsePositiveIntentTokenBudget(tokenBudget)!==void 0,projected={...options};return projected.tokenBudget===void 0&&tokenBudget!==void 0&&(projected.tokenBudget=tokenBudget),delete projected.token_budget,projected.tokenBudget===void 0&&(projected.tokenBudget=String(contract.token_budget)),CONTEXT_INTENT_DEFAULT_APPLIERS[command](projected,contract,explicitTokenBudget),projected}const CONTEXT_INTENT_DEGRADATIONS={context:"bounded_sections",get:"standard_item",list:"bounded_fields_and_rows",next:"bounded_ranked_rows",search:"bounded_ranked_rows"},MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET=256;function compactContextIntentValue(value){return Array.isArray(value)?value.map(compactContextIntentValue):value!==null&&typeof value=="object"?Object.fromEntries(Object.entries(value).map(([key,entry])=>[key,compactContextIntentValue(entry)])):typeof value=="string"&&value.length>240?`${unicodeSafePrefix(value,240)}\u2026`:value}function parsePositiveIntentTokenBudget(value){const parsed=typeof value=="number"?value:typeof value=="string"&&/^\d+$/u.test(value.trim())?Number(value):Number.NaN;return Number.isSafeInteger(parsed)&&parsed>0?parsed:void 0}function resolveIntentTokenBudget(value,declaredBudget){const parsed=parsePositiveIntentTokenBudget(value);if(parsed===void 0)return declaredBudget;if(parsed<MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET)throw new PmCliError(`Context intent token budget must be at least ${MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET}`,EXIT_CODE.USAGE,{code:"invalid_argument_value",reason:"below_minimum",field:"tokenBudget",value:String(value),required:`Use an integer token budget of at least ${MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET}.`,why:"Smaller ceilings cannot contain the minimum machine-readable intent receipt.",nextSteps:[`Retry with --token-budget ${MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET} or omit the override.`]});return parsed}function resolveIntentRowCost(command,intent){return command==="context"?command==="context"&&intent==="orient"?{overhead:1200,rowCost:600}:{overhead:800,rowCost:500}:{overhead:command==="list"?520:480,rowCost:16}}function resolveIntentRowBudget(command,intent,tokenBudget,explicitTokenBudget){if(command==="get"||command==="next")return;const{overhead,rowCost}=resolveIntentRowCost(command,intent),calculatedLimit=Math.max(command==="context"?1:2,Math.floor((tokenBudget-overhead)/rowCost));return explicitTokenBudget?calculatedLimit:Math.min(command==="context"?20:100,calculatedLimit)}function updateContextIntentEstimate(projected,receipt){let measuredTokens=receipt.estimated_tokens;for(;;){receipt.estimated_tokens=measuredTokens;const nextMeasurement=Math.ceil(Buffer.byteLength(JSON.stringify(projected),"utf8")/4);if(nextMeasurement===measuredTokens)return;measuredTokens=nextMeasurement}}const CONTEXT_INTENT_ROW_KEYS={context:["high_level","low_level","blocked_fallback","recently_created","unparented","hierarchy","activity","blockers"],get:["children"],list:["items"],next:["ready","decision_needed","gate_needed","containers","blocked","held_by_others"],search:["items"]};function decodeContextIntentCursor(cursor){try{const parsed=JSON.parse(Buffer.from(cursor,"base64url").toString("utf8"));return typeof parsed.fingerprint!="string"||!Number.isSafeInteger(parsed.after_index)?void 0:{fingerprint:parsed.fingerprint,after_index:parsed.after_index,...typeof parsed.snapshot=="string"?{snapshot:parsed.snapshot}:{}}}catch{return}}function contextIntentRowId(row){if(row===null||typeof row!="object")return;if(typeof row.id=="string")return row.id;const nestedId=row.item?.id;return typeof nestedId=="string"?nestedId:void 0}function shrinkContextIntentRowsToBudget(projected,receipt,rows){let compacted=!1;for(;;){if(updateContextIntentEstimate(projected,receipt),receipt.estimated_tokens<=receipt.token_budget||rows.length<=1)return compacted;const rowBytes=Buffer.byteLength(JSON.stringify(rows),"utf8"),excessBytes=(receipt.estimated_tokens-receipt.token_budget)*4;rows.splice(-Math.min(rows.length-1,Math.max(1,Math.ceil(excessBytes/Math.max(1,Math.ceil(rowBytes/rows.length)))))),compacted=!0}}function compactPaginatedContextIntentRows(projected,receipt,options){const rows=projected.items,cursorContinuesExistingPage=typeof projected.next_cursor=="string",cursorSource=cursorContinuesExistingPage?projected.next_cursor:options.after;if(!Array.isArray(rows)||typeof cursorSource!="string")return!1;const cursorEnvelope=decodeContextIntentCursor(cursorSource);if(cursorEnvelope===void 0)return!1;const originalRowCount=rows.length,originalRows=[...rows];let compacted=!1;for(;;){if(compacted=shrinkContextIntentRowsToBudget(projected,receipt,rows)||compacted,!compacted)return!1;const lastId=contextIntentRowId(rows.at(-1));if(lastId===void 0)return rows.splice(0,rows.length,...originalRows),updateContextIntentEstimate(projected,receipt),!1;if(projected.next_cursor=encodeQueryCursor(cursorEnvelope.fingerprint,lastId,cursorContinuesExistingPage?cursorEnvelope.after_index-(originalRowCount-rows.length):cursorEnvelope.after_index+rows.length,cursorEnvelope.snapshot),updateContextIntentEstimate(projected,receipt),receipt.estimated_tokens<=receipt.token_budget||rows.length<=1)break}return typeof projected.count=="number"&&(projected.count=rows.length),typeof projected.applied_limit=="number"&&(projected.applied_limit=rows.length),!0}function compactContextIntentRows(command,projected,receipt,options){if(command==="list"||command==="search")return compactPaginatedContextIntentRows(projected,receipt,options);if(command!=="next"||typeof projected.next_cursor=="string")return!1;let compacted=!1;for(;;){if(updateContextIntentEstimate(projected,receipt),receipt.estimated_tokens<=receipt.token_budget)return compacted;const candidate=CONTEXT_INTENT_ROW_KEYS[command].map(key=>({key,rows:Array.isArray(projected[key])?projected[key]:[]})).filter(({rows})=>rows.length>0).sort((left,right)=>right.rows.length-left.rows.length||left.key.localeCompare(right.key))[0];if(candidate===void 0)return compacted;const retainedTotal=CONTEXT_INTENT_ROW_KEYS[command].reduce((total,key)=>total+(Array.isArray(projected[key])?projected[key].length:0),0);if(retainedTotal<=1)return compacted;const removableRows=Math.min(candidate.rows.length,retainedTotal-1),candidateBytes=Buffer.byteLength(JSON.stringify(candidate.rows),"utf8"),estimatedBytesPerRow=Math.max(1,Math.ceil(candidateBytes/candidate.rows.length)),excessBytes=(receipt.estimated_tokens-receipt.token_budget)*4,removalCount=Math.min(removableRows,Math.max(1,Math.ceil(excessBytes/estimatedBytesPerRow)));candidate.rows.splice(-removalCount,removalCount),compacted=!0}}function attachContextIntentReceipt(command,options,result){if(typeof options.for!="string")return result;const normalizedCommand=command.startsWith("list-")?"list":command;if(!(normalizedCommand in CONTEXT_INTENT_DEFAULT_APPLIERS))return result;const builtInCommand=normalizedCommand,contract=resolveContextIntentContract(builtInCommand,options.for),effectiveTokenBudget=resolveIntentTokenBudget(options.tokenBudget??options.token_budget,contract.token_budget),receipt={command:builtInCommand,intent:contract.intent,source:contract.source,included_field_groups:[...contract.included_field_groups],token_budget:effectiveTokenBudget,declared_token_budget:contract.token_budget,token_budget_override:effectiveTokenBudget-contract.token_budget,estimated_tokens:0,within_budget:!0,degradation:CONTEXT_INTENT_DEGRADATIONS[builtInCommand],declaration_feasible:!0,result_omitted:!1},resultWithDiagnostics={...result},budgetDerivedLimit=resolveIntentRowBudget(builtInCommand,contract.intent,receipt.token_budget,parsePositiveIntentTokenBudget(options.tokenBudget??options.token_budget)!==void 0);if(budgetDerivedLimit!==void 0){const effectiveLimit=parsePositiveIntentTokenBudget(options.limit),explicitLimitBinds=effectiveLimit!==void 0&&effectiveLimit<budgetDerivedLimit;receipt.budget_derived_limit=budgetDerivedLimit,receipt.binding_constraint=explicitLimitBinds?"explicit_limit":"token_budget",receipt.limit_reason=explicitLimitBinds?"The caller supplied a smaller row limit than the budget-derived ceiling.":"The selected intent token budget constrains the effective row ceiling.",resultWithDiagnostics.budget_derived_limit=budgetDerivedLimit,discloseIntentLimitOverride({builtInCommand,intent:contract.intent},receipt,resultWithDiagnostics,options)}let projected={...resultWithDiagnostics,context_intent:receipt};return updateContextIntentEstimate(projected,receipt),receipt.estimated_tokens>receipt.token_budget&&(receipt.degradation="recursive_budget_compaction",projected={...compactContextIntentValue(resultWithDiagnostics),context_intent:receipt},updateContextIntentEstimate(projected,receipt)),receipt.estimated_tokens>receipt.token_budget&&compactContextIntentRows(builtInCommand,projected,receipt,options)&&(receipt.degradation="budget_row_compaction",updateContextIntentEstimate(projected,receipt)),receipt.declaration_feasible=receipt.estimated_tokens<=receipt.declared_token_budget,receipt.estimated_tokens>receipt.token_budget&&(receipt.degradation="budget_receipt_only",receipt.result_omitted=!0,receipt.within_budget=!1,projected={budget_exceeded:{omitted_result:!0,reason:receipt.token_budget_override===0?"declared_budget_infeasible":"effective_budget_infeasible",restore_with:buildContextIntentRecoveryCommand(command,builtInCommand,contract.intent,receipt,resultWithDiagnostics)},context_intent:receipt}),projected}const CONTINUATION_METADATA_KEYS=["applied_limit","completeness","context_intent","count","filters","has_more","now","omission_receipt","projection","row_contract","sorting","total","truncated"];function collapseContinuationMetadata(options,result){if(typeof options.after!="string"||options.after.length===0)return result;const fingerprint=decodeContextIntentCursor(options.after)?.fingerprint??"opaque_cursor",projected={...result};for(const key of CONTINUATION_METADATA_KEYS)delete projected[key];return projected.continuation_contract={fingerprint,metadata:"reference",restore_with:"omit --after"},projected}function isOutputRecord(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function contextIntentRecoveryPositional(builtInCommand,result){const recoveryTarget=builtInCommand==="get"&&isOutputRecord(result.item)&&typeof result.item.id=="string"?result.item.id:builtInCommand==="search"&&typeof result.query=="string"?result.query:void 0;return recoveryTarget===void 0?"":` '${recoveryTarget.replaceAll("'",`'"'"'`)}'`}function discloseIntentLimitOverride(identity,receipt,result,options){const requested=parsePositiveIntentTokenBudget(options.limit),effective=receipt.budget_derived_limit;if(requested===void 0||requested<=effective)return;const{overhead,rowCost}=resolveIntentRowCost(identity.builtInCommand,identity.intent),sufficientBudget=Math.max(receipt.token_budget,overhead+rowCost*requested);receipt.limit_reason=`The ${receipt.token_budget}-token ${identity.intent} budget carries ${effective} rows, so it reduced the caller's --limit ${requested}.`,receipt.limit_override={flag:"--limit",requested,effective,...Number.isSafeInteger(sufficientBudget)?{token_budget_for_requested:sufficientBudget,restore_with:`--token-budget ${sufficientBudget}`}:{}};const warning=`${CONTEXT_INTENT_LIMIT_OVERRIDE_WARNING}:--limit ${requested}->${effective}`;result.warnings=Array.isArray(result.warnings)?[...result.warnings,warning]:[warning],isOutputRecord(result.filters)&&(result.filters={...result.filters,requested_limit:String(requested)})}function buildContextIntentRecoveryCommand(command,builtInCommand,intent,receipt,result){const recoveryPositional=contextIntentRecoveryPositional(builtInCommand,result),boundedRowLimit=builtInCommand==="get"?"":` --limit ${receipt.budget_derived_limit??1}`;return`pm ${command}${recoveryPositional} --for ${intent} --token-budget ${Math.ceil(receipt.estimated_tokens/100)*100}${boundedRowLimit}`}function receiptEstimate(value,field){if(isOutputRecord(value))return typeof value[field]=="number"?value[field]:void 0}function stabilizeSuppressedRowContractReceipts(result,options){let finalized=result;for(let iteration=0;iteration<8;iteration+=1){const previousContextEstimate=receiptEstimate(finalized.context_intent,"estimated_tokens"),previousReadEstimate=receiptEstimate(finalized.read_output,"estimated_tokens"),previousSessionEstimate=receiptEstimate(finalized.read_session,"spent_this_call_tokens");if(isOutputRecord(finalized.context_intent)&&updateContextIntentEstimate(finalized,finalized.context_intent),finalized=stabilizeReadOutputReceiptEstimates(finalized,options),receiptEstimate(finalized.context_intent,"estimated_tokens")===previousContextEstimate&&receiptEstimate(finalized.read_output,"estimated_tokens")===previousReadEstimate&&receiptEstimate(finalized.read_session,"spent_this_call_tokens")===previousSessionEstimate)break}return finalized}function attachReadOutputContracts(command,options,result){const disclosedResult=attachOutputOmissionReceipt(command,attachExtensionReadOutputRows(command??"",result)),projected=typeof disclosedResult=="object"&&disclosedResult!==null&&!Array.isArray(disclosedResult)?applyReadOutputDimensions(command??"",{...options,outputRowContract:options.outputRowContract===!0||options.output_row_contract===!0},collapseContinuationMetadata(options,attachContextIntentReceipt(command??"",options,disclosedResult))):disclosedResult;if(propagateContextUsageServingReceipt(result,projected),options.outputRowContract===!0||options.output_row_contract===!0||typeof projected!="object"||projected===null||Array.isArray(projected)||!Object.hasOwn(projected,"row_contract"))return projected;const withoutDiscoveryMetadata=Object.fromEntries(Object.entries(projected).filter(([key])=>key!=="row_contract"));Object.defineProperty(withoutDiscoveryMetadata,"row_contract",{value:projected.row_contract,enumerable:!1,configurable:!0});const suppressed=stabilizeSuppressedRowContractReceipts(withoutDiscoveryMetadata,options);return delete suppressed.row_contract,propagateContextUsageServingReceipt(projected,suppressed),suppressed}export{CONTEXT_INTENT_LIMIT_OVERRIDE_WARNING,PM_CONTEXT_INTENT_CONTRACTS,applyContextIntentProjection,attachContextIntentReceipt,attachReadOutputContracts,composeContextIntentContracts,contextIntentRowId,decodeContextIntentCursor,getActiveContextIntentContracts,resolveContextIntentContract,runWithContextIntentContracts};
|
|
2
2
|
//# sourceMappingURL=context-intent-contracts.js.map
|
package/dist/sdk/core.d.ts
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
*
|
|
4
4
|
* Provides the stable item lifecycle client and universal project data types.
|
|
5
5
|
*/
|
|
6
|
-
export { BASELINE_ITEM_FORMAT_VERSION,BUILTIN_ITEM_TYPE_VALUES,CONFIDENCE_TEXT_VALUES,CURRENT_ITEM_FORMAT_VERSION,DEPENDENCY_KIND_VALUES,EXIT_CODE,ISSUE_SEVERITY_VALUES,ITEM_TYPE_VALUES,PM_CLI_EXPECTED_ERROR_NAME,PmCliError,PmClient,RISK_VALUES,STATUS_VALUES,canonicalDocument,classifyItemFormatVersion,createPmCliExpectedError,effectiveItemFormatVersion,emptyImportedDocument,isPmCliExpectedError,normalizeItemFormatVersion,normalizeItemId,normalizeStatusInput,nowIso,runAction,serializeItemDocument,aggregate,append,claim,claimNext,close,comments,context,copy,create,deleteItem,deps,docs,files,filesDiscover,focus,get,graph,learnings,list,next,notes,release,reopen,restore,search,update,type AggregateOptions,type AggregateResult,type AggregateRow,type AssuranceActionInput,type AssuranceActionResult,type AppendCommandOptions,type AppendResult,type ClaimNextOptions,type ClaimResult,type CloseResult,type CommentsCommandOptions,type CommentsResult,type ContextOptions,type ContextResult,type CopyResult,type CreateResult,type Dependency,type DeleteResult,type DepsCommandOptions,type DepsResult,type DocsCommandOptions,type DocsResult,type FilesCommandOptions,type FilesDiscoverOptions,type FilesDiscoverResult,type FilesResult,type FocusResult,type GetOptions,type GetResult,type ItemFormatVersionScanEntry,type ItemFormatVersionScanResult,type ItemFormatVersionStatus,type LearningsCommandOptions,type LearningsResult,type ListOptions,type ListResult,listAllComplete,type PmCompleteListOptions,type PmCompleteListResult,type NextOptions,type NextResult,type NotesCommandOptions,type NotesResult,type PmActionInput,type PmActionName,type PmActionOptions,type PmClientOptions,type ReleaseResult,type ReleaseMutationOptions,type PreviousTerminalEvidence,type RecurrenceReceipt,type ReopenCommandOptions,type ReopenResult,type RestoreResult,type SearchOptions,type SearchResult,type UpdateResult,} from "./runtime.js";
|
|
6
|
+
export { BASELINE_ITEM_FORMAT_VERSION,BUILTIN_ITEM_TYPE_VALUES,CONFIDENCE_TEXT_VALUES,CURRENT_ITEM_FORMAT_VERSION,DEPENDENCY_KIND_VALUES,EXIT_CODE,ISSUE_SEVERITY_VALUES,ITEM_TYPE_VALUES,PM_CLI_EXPECTED_ERROR_NAME,PmCliError,PmClient,RISK_VALUES,STATUS_VALUES,canonicalDocument,classifyItemFormatVersion,createPmCliExpectedError,effectiveItemFormatVersion,emptyImportedDocument,isPmCliExpectedError,normalizeItemFormatVersion,normalizeItemId,normalizeStatusInput,nowIso,runAction,serializeItemDocument,aggregate,append,claim,claimNext,close,comments,context,copy,create,deleteItem,deps,docs,files,filesDiscover,focus,get,graph,learnings,list,next,notes,release,reopen,restore,search,update,type AggregateOptions,type AggregateResult,type AggregateRow,type AssuranceActionInput,type AssuranceActionResult,type AppendCommandOptions,type AppendResult,type ClaimNextOptions,type ClaimResult,type ClaimStartReceipt,type CloseResult,type CommentsCommandOptions,type CommentsResult,type ContextOptions,type ContextResult,type CopyResult,type CreateResult,type Dependency,type DeleteResult,type DepsCommandOptions,type DepsResult,type DocsCommandOptions,type DocsResult,type FilesCommandOptions,type FilesDiscoverOptions,type FilesDiscoverResult,type FilesResult,type FocusResult,type GetOptions,type GetResult,type ItemFormatVersionScanEntry,type ItemFormatVersionScanResult,type ItemFormatVersionStatus,type LearningsCommandOptions,type LearningsResult,type ListOptions,type ListResult,listAllComplete,type PmCompleteListOptions,type PmCompleteListResult,type NextOptions,type NextResult,type NotesCommandOptions,type NotesResult,type PmActionInput,type PmActionName,type PmActionOptions,type PmClientOptions,type ReleaseResult,type ReleaseMutationOptions,type PreviousTerminalEvidence,type RecurrenceReceipt,type ReopenCommandOptions,type ReopenResult,type RestoreResult,type SearchOptions,type SearchResult,type UpdateResult,} from "./runtime.js";
|
|
7
7
|
export * from "./core-governance.js";
|
|
8
8
|
export { updateLinkedTest,type LinkedTestUpdateSelector,type LinkedTestMetadataPatch,type UpdateLinkedTestOptions,type UpdateLinkedTestResult,} from "./test/update.js";
|
|
9
9
|
export { isItemAlreadyExistsError,type PmItemAlreadyExistsError,isPmTokenBudgetRecovery,type PmTokenBudgetRecovery } from "./errors.js";
|
package/dist/sdk/core.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="1b7735e8-a1a3-59bb-a89f-d014b70c34ec")}catch{}})();import{BASELINE_ITEM_FORMAT_VERSION,BUILTIN_ITEM_TYPE_VALUES,CONFIDENCE_TEXT_VALUES,CURRENT_ITEM_FORMAT_VERSION,DEPENDENCY_KIND_VALUES,EXIT_CODE,ISSUE_SEVERITY_VALUES,ITEM_TYPE_VALUES,PM_CLI_EXPECTED_ERROR_NAME,PmCliError,PmClient,RISK_VALUES,STATUS_VALUES,canonicalDocument,classifyItemFormatVersion,createPmCliExpectedError,effectiveItemFormatVersion,emptyImportedDocument,isPmCliExpectedError,normalizeItemFormatVersion,normalizeItemId,normalizeStatusInput,nowIso,runAction,serializeItemDocument,aggregate,append,claim,claimNext,close,comments,context,copy,create,deleteItem,deps,docs,files,filesDiscover,focus,get,graph,learnings,list,next,notes,release,reopen,restore,search,update,listAllComplete}from"./runtime.js";export*from"./core-governance.js";import{updateLinkedTest}from"./test/update.js";import{isItemAlreadyExistsError,isPmTokenBudgetRecovery}from"./errors.js";export*from"./agent-session-context.js";import{isAlreadyClaimedError}from"./lifecycle/claim.js";import{PM_READ_OUTPUT_DIMENSIONS,PM_READ_OUTPUT_OPTION_FLAGS,PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,PM_READ_OUTPUT_SURFACE_CONTRACTS,applyReadOutputDimensions,decodeReadOutputContinuationCursor,encodeReadOutputContinuationCursor,isReadOutputBudgetExceeded,resolveReadOutputDimensions,resolveReadOutputEncoding,resolveReadOutputSurface,validateReadOutputOptions}from"./read-output-contracts.js";import{applyReadOutputSessionReferences,attachReadOutputSessionReceipt,parseReadOutputSession,readOutputSessionRemainingTokens,isReadOutputSessionReference}from"./read-output-session.js";import{assertWellFormedOutputText,toWellFormedText}from"../core/shared/output-unicode.js";export{BASELINE_ITEM_FORMAT_VERSION,BUILTIN_ITEM_TYPE_VALUES,CONFIDENCE_TEXT_VALUES,CURRENT_ITEM_FORMAT_VERSION,DEPENDENCY_KIND_VALUES,EXIT_CODE,ISSUE_SEVERITY_VALUES,ITEM_TYPE_VALUES,PM_CLI_EXPECTED_ERROR_NAME,PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,PM_READ_OUTPUT_DIMENSIONS,PM_READ_OUTPUT_OPTION_FLAGS,PM_READ_OUTPUT_SURFACE_CONTRACTS,PmCliError,PmClient,RISK_VALUES,STATUS_VALUES,aggregate,append,applyReadOutputDimensions,applyReadOutputSessionReferences,assertWellFormedOutputText,attachReadOutputSessionReceipt,canonicalDocument,claim,claimNext,classifyItemFormatVersion,close,comments,context,copy,create,createPmCliExpectedError,decodeReadOutputContinuationCursor,deleteItem,deps,docs,effectiveItemFormatVersion,emptyImportedDocument,encodeReadOutputContinuationCursor,files,filesDiscover,focus,get,graph,isAlreadyClaimedError,isItemAlreadyExistsError,isPmCliExpectedError,isPmTokenBudgetRecovery,isReadOutputBudgetExceeded,isReadOutputSessionReference,learnings,list,listAllComplete,next,normalizeItemFormatVersion,normalizeItemId,normalizeStatusInput,notes,nowIso,parseReadOutputSession,readOutputSessionRemainingTokens,release,reopen,resolveReadOutputDimensions,resolveReadOutputEncoding,resolveReadOutputSurface,restore,runAction,search,serializeItemDocument,toWellFormedText,update,updateLinkedTest,validateReadOutputOptions};
|
|
2
2
|
//# sourceMappingURL=core.js.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
2
|
-
`}function createExtensionCommandSdk(pmRoot,client,invocationAuthor,invocationCommand){return{fitOutputEnvelope,client,isItemNotFoundError:error=>isPmCliExpectedError(error)&&error.exitCode===EXIT_CODE.NOT_FOUND,getItemAt:(id,target)=>getItemAt(id,target,{pmRoot}),openRelationshipEventStore:options=>RelationshipEventStore.open({pmRoot,nodes:options.nodes,registry:buildRelationshipKindRegistry(options.definitions),...options.relativePath===void 0?{}:{relativePath:options.relativePath}}),createRelationshipGraph:options=>new RelationshipGraph(options.nodes,options.edges,buildRelationshipKindRegistry(options.definitions)),analyzeRelationshipImpact:(graph,root,options)=>analyzeGraphImpact(graph,root,options),validateRelationshipEvents:options=>{const log=new RelationshipEventLog(options.nodes,{registry:buildRelationshipKindRegistry(options.definitions)});return options.events.map(event=>log.append({...event,expectedVersion:log.version}))},commitWorkspaceTransaction:options=>commitWorkspaceTransaction({...options,pmRoot}),mutateWorkspaceSettings:async options=>{if(!/^[a-zA-Z0-9._-]{1,128}$/u.test(options.operationId))throw new PmCliError("Workspace settings operationId must be 1-128 letters, digits, dots, underscores, or hyphens.",EXIT_CODE.USAGE);const settings=options.dryRun===!0?await runWithConfigurationOnlySettings(pmRoot,()=>readSettings(pmRoot)):await readSettings(pmRoot);try{const mutation=await mutateWorkspaceJsonWithHistory({pmRoot,filePath:getSettingsPath(pmRoot),op:"extension:pm:settings",idempotencyKey:invocationCommand===void 0?options.operationId:`${createHash("sha256").update(invocationCommand).digest("hex").slice(0,16)}:${options.operationId}`,author:resolveAuthor(invocationAuthor,settings.author_default),lockTtlSeconds:settings.locks.ttl_seconds,lockWaitMs:settings.locks.wait_ms,recordCreation:!1,dryRun:options.dryRun===!0,mutate:async beforeRaw=>{const current=beforeRaw===null?null:JSON.parse(beforeRaw),validatedCurrent=validateSettings(current);if(!validatedCurrent.success)throw new PmCliError("Workspace settings mutation requires a valid initialized settings.json.",EXIT_CODE.USAGE);const currentSettings=mergeSettings(validatedCurrent.data),next=await options.mutate(structuredClone(currentSettings));if(!validateSettings(next).success)throw new PmCliError("Workspace settings mutation returned invalid settings.json.",EXIT_CODE.USAGE);let raw=stableValueEquals(currentSettings,next)?beforeRaw:serializeSettings(next,{source:{raw:current,validated:validatedCurrent.data}});raw=replaceOwnedSettingsSubtrees(raw,next,options.replaceSubtrees);const validatedResult=validateSettings(JSON.parse(raw));if(!validatedResult.success)throw new PmCliError("Workspace settings mutation serialized invalid settings.json.",EXIT_CODE.USAGE);return{raw,result:options.includePreview===!0?mergeSettings(validatedResult.data):void 0}}});return mutation.changed&&options.dryRun!==!0&&await runActiveOnWriteHooks({path:getSettingsPath(pmRoot),scope:"project",op:"extension:pm:settings"}),{changed:mutation.changed,dry_run:options.dryRun===!0,replayed:mutation.replayed===!0,...mutation.result===void 0?{}:{preview:mutation.result}}}finally{clearSettingsReadCache(pmRoot)}}}}export{createExtensionCommandSdk};
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="971103f5-a101-5e45-a607-ebebbaafe7f5")}catch{}})();import{createHash}from"node:crypto";import{runActiveOnWriteHooks}from"../core/extensions/index.js";import{mutateWorkspaceJsonWithHistory}from"../core/history/workspace-history.js";import{resolveAuthor}from"../core/shared/author.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{asRecordOrNull}from"../core/shared/primitives.js";import{stableValueEquals}from"../core/shared/serialization.js";import{getSettingsPath}from"../core/store/paths.js";import{mergeSettings,readSettings,runWithConfigurationOnlySettings,serializeSettings}from"../core/store/settings.js";import{clearSettingsReadCache}from"../core/store/settings-read-cache.js";import{readSettingsSection,writeSettingsSection}from"../core/store/settings-sections.js";import{validateSettings}from"../core/store/settings-validator.js";import{isPmCliExpectedError}from"./errors.js";import{getItemAt}from"./history-read.js";import{fitOutputEnvelope}from"./output/fit-envelope.js";import{RelationshipEventLog,RelationshipEventStore}from"./relationship-history.js";import{analyzeGraphImpact}from"./relationship-analytics.js";import{RelationshipGraph,createRelationshipKindRegistry}from"./relationships.js";import{commitWorkspaceTransaction}from"./workspace-transaction.js";function buildRelationshipKindRegistry(definitions){const registry=createRelationshipKindRegistry();for(const definition of definitions)registry.register(definition);return registry}function replaceOwnedSettingsSubtrees(raw,next,paths=[]){if(paths.length===0)return raw;const persisted=JSON.parse(raw),canonical=JSON.parse(serializeSettings(next));for(const ownedPath of paths){const segments=ownedPath.split(".");let source=canonical;for(const segment of segments){const sourceObject=asRecordOrNull(source);if(!/^[a-zA-Z][a-zA-Z0-9_]*$/u.test(segment)||["constructor","prototype","__proto__"].includes(segment)||sourceObject===null||!Object.hasOwn(sourceObject,segment))throw new PmCliError(`Invalid owned settings subtree: ${ownedPath}. Select a declared inline object path.`,EXIT_CODE.USAGE);source=sourceObject[segment]}if(asRecordOrNull(source)===null)throw new PmCliError(`Invalid owned settings subtree: ${ownedPath}. Select a declared inline object path.`,EXIT_CODE.USAGE);let destination=persisted,canonicalParent=canonical;for(const segment of segments.slice(0,-1)){const value=destination[segment];canonicalParent=canonicalParent[segment],value===void 0&&Object.defineProperty(destination,segment,{value:structuredClone(canonicalParent),enumerable:!0,writable:!0,configurable:!0}),destination=destination[segment]}Object.defineProperty(destination,segments.at(-1),{value:source,enumerable:!0,writable:!0,configurable:!0})}return stableValueEquals(persisted,JSON.parse(raw))?raw:`${JSON.stringify(persisted,null,2)}
|
|
2
|
+
`}function createExtensionCommandSdk(pmRoot,client,invocationAuthor,invocationCommand){return{fitOutputEnvelope,client,isItemNotFoundError:error=>isPmCliExpectedError(error)&&error.exitCode===EXIT_CODE.NOT_FOUND,getItemAt:(id,target)=>getItemAt(id,target,{pmRoot}),readSettingsSection:(section,options)=>readSettingsSection(pmRoot,section,options),writeSettingsSection:(section,value,options)=>writeSettingsSection(pmRoot,section,value,{author:invocationAuthor,...options}),openRelationshipEventStore:options=>RelationshipEventStore.open({pmRoot,nodes:options.nodes,registry:buildRelationshipKindRegistry(options.definitions),...options.relativePath===void 0?{}:{relativePath:options.relativePath}}),createRelationshipGraph:options=>new RelationshipGraph(options.nodes,options.edges,buildRelationshipKindRegistry(options.definitions)),analyzeRelationshipImpact:(graph,root,options)=>analyzeGraphImpact(graph,root,options),validateRelationshipEvents:options=>{const log=new RelationshipEventLog(options.nodes,{registry:buildRelationshipKindRegistry(options.definitions)});return options.events.map(event=>log.append({...event,expectedVersion:log.version}))},commitWorkspaceTransaction:options=>commitWorkspaceTransaction({...options,pmRoot}),mutateWorkspaceSettings:async options=>{if(!/^[a-zA-Z0-9._-]{1,128}$/u.test(options.operationId))throw new PmCliError("Workspace settings operationId must be 1-128 letters, digits, dots, underscores, or hyphens.",EXIT_CODE.USAGE);const settings=options.dryRun===!0?await runWithConfigurationOnlySettings(pmRoot,()=>readSettings(pmRoot)):await readSettings(pmRoot);try{const mutation=await mutateWorkspaceJsonWithHistory({pmRoot,filePath:getSettingsPath(pmRoot),op:"extension:pm:settings",idempotencyKey:invocationCommand===void 0?options.operationId:`${createHash("sha256").update(invocationCommand).digest("hex").slice(0,16)}:${options.operationId}`,author:resolveAuthor(invocationAuthor,settings.author_default),lockTtlSeconds:settings.locks.ttl_seconds,lockWaitMs:settings.locks.wait_ms,recordCreation:!1,dryRun:options.dryRun===!0,mutate:async beforeRaw=>{const current=beforeRaw===null?null:JSON.parse(beforeRaw),validatedCurrent=validateSettings(current);if(!validatedCurrent.success)throw new PmCliError("Workspace settings mutation requires a valid initialized settings.json.",EXIT_CODE.USAGE);const currentSettings=mergeSettings(validatedCurrent.data),next=await options.mutate(structuredClone(currentSettings));if(!validateSettings(next).success)throw new PmCliError("Workspace settings mutation returned invalid settings.json.",EXIT_CODE.USAGE);let raw=stableValueEquals(currentSettings,next)?beforeRaw:serializeSettings(next,{source:{raw:current,validated:validatedCurrent.data}});raw=replaceOwnedSettingsSubtrees(raw,next,options.replaceSubtrees);const validatedResult=validateSettings(JSON.parse(raw));if(!validatedResult.success)throw new PmCliError("Workspace settings mutation serialized invalid settings.json.",EXIT_CODE.USAGE);return{raw,result:options.includePreview===!0?mergeSettings(validatedResult.data):void 0}}});return mutation.changed&&options.dryRun!==!0&&await runActiveOnWriteHooks({path:getSettingsPath(pmRoot),scope:"project",op:"extension:pm:settings"}),{changed:mutation.changed,dry_run:options.dryRun===!0,replayed:mutation.replayed===!0,...mutation.result===void 0?{}:{preview:mutation.result}}}finally{clearSettingsReadCache(pmRoot)}}}}export{createExtensionCommandSdk};
|
|
3
3
|
//# sourceMappingURL=extension-command-context.js.map
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module sdk/generated/error-code-catalog-rows
|
|
3
|
+
*
|
|
4
|
+
* Compact generated error-code catalog rows and their lossless expansion into
|
|
5
|
+
* full contracts. The generator omits every field that is derivable, so the
|
|
6
|
+
* catalog ships once per build output without repeating shared guidance.
|
|
7
|
+
*/
|
|
8
|
+
import { type PmErrorCodeContract } from "../error-code-catalog.js";
|
|
9
|
+
/**
|
|
10
|
+
* One generated catalog row with every derivable field omitted: `meaning`
|
|
11
|
+
* follows from the code, `class` from the exit code, `recovery` is shared,
|
|
12
|
+
* `stability` is provisional unless `stable` is set, and `emitting_commands`
|
|
13
|
+
* defaults to every command. `canonical_code`, `aliases` and `owned_states`
|
|
14
|
+
* default inside definePmErrorCodeCatalog (pm-998juj).
|
|
15
|
+
*/
|
|
16
|
+
export interface PmErrorCodeCatalogRow {
|
|
17
|
+
/** Stable snake_case identifier. */
|
|
18
|
+
code:string;
|
|
19
|
+
/** Process exit code emitted by the CLI transport. */
|
|
20
|
+
exit_code:PmErrorCodeContract["exit_code"];
|
|
21
|
+
/** Subsystems that can emit the code. */
|
|
22
|
+
sources:string[];
|
|
23
|
+
/** Present when the code is in the reviewed stability ledger. */
|
|
24
|
+
stable?:true;
|
|
25
|
+
/** CLI command roots, when narrower than every command. */
|
|
26
|
+
emitting_commands?:string[];
|
|
27
|
+
/** Canonical machine identifier, when the code is an alias. */
|
|
28
|
+
canonical_code?:string;
|
|
29
|
+
/** Compatibility spellings that resolve to this code. */
|
|
30
|
+
aliases?:string[];
|
|
31
|
+
/** Observable states this code claims. */
|
|
32
|
+
owned_states?:PmErrorCodeContract["owned_states"];
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Expand compact generated rows into the full contracts that
|
|
36
|
+
* definePmErrorCodeCatalog validates, keeping the original key order so every
|
|
37
|
+
* serialized catalog projection stays byte-identical.
|
|
38
|
+
*/
|
|
39
|
+
export declare function expandPmErrorCodeCatalogRows(rows:readonly PmErrorCodeCatalogRow[]):PmErrorCodeContract[];
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="1e8c03e6-149a-5819-a000-65e7e3b12f6d")}catch{}})();import{PM_ERROR_CODE_EXIT_CLASS_CONTRACTS}from"../error-code-catalog.js";const GENERATED_ERROR_CODE_RECOVERY="Inspect the structured error guidance and retry the suggested command.",CLASS_BY_EXIT_CODE=new Map(PM_ERROR_CODE_EXIT_CLASS_CONTRACTS.map(contract=>[contract.exit_code,contract.class]));function expandPmErrorCodeCatalogRows(rows){return rows.map(row=>{const meaning=`${row.code.replaceAll("_"," ")} condition.`,contract={code:row.code,meaning:`${meaning.charAt(0).toUpperCase()}${meaning.slice(1)}`,stability:row.stable?"stable":"provisional",exit_code:row.exit_code,class:CLASS_BY_EXIT_CODE.get(row.exit_code),recovery:GENERATED_ERROR_CODE_RECOVERY,sources:row.sources,emitting_commands:row.emitting_commands??["*"],canonical_code:row.canonical_code??row.code,aliases:row.aliases??[]};return row.owned_states&&(contract.owned_states=row.owned_states),contract})}export{expandPmErrorCodeCatalogRows};
|
|
2
|
+
//# sourceMappingURL=error-code-catalog-rows.js.map
|
|
@@ -3,6 +3,6 @@
|
|
|
3
3
|
*
|
|
4
4
|
* Generated by scripts/generate-error-code-catalog.mjs. Do not edit manually.
|
|
5
5
|
*/
|
|
6
|
-
import type {
|
|
7
|
-
/** Generated partition 1 of the exhaustive error-code catalog. */
|
|
8
|
-
export declare const PM_ERROR_CODE_CATALOG_PART_1:
|
|
6
|
+
import type { PmErrorCodeCatalogRow } from "./error-code-catalog-rows.js";
|
|
7
|
+
/** Generated partition 1 of the exhaustive error-code catalog, as compact rows. */
|
|
8
|
+
export declare const PM_ERROR_CODE_CATALOG_PART_1:PmErrorCodeCatalogRow[];
|