@unbrained/pm-cli 2026.11.1 → 2026.11.3

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.
Files changed (184) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +32 -0
  3. package/CONTRIBUTING.md +1 -1
  4. package/dist/cli/error-guidance.d.ts +9 -0
  5. package/dist/cli/error-guidance.js +4 -3
  6. package/dist/cli/main.js +1 -1
  7. package/dist/cli/migration-gates.js +1 -1
  8. package/dist/cli/runtime/field-route-retry.d.ts +15 -0
  9. package/dist/cli/runtime/field-route-retry.js +2 -0
  10. package/dist/cli-bundle/bundle-manifest.json +1 -1
  11. package/dist/cli-bundle/chunks/{chunk-2GK2IVU5.js → chunk-2CBHQXYJ.js} +3 -3
  12. package/dist/cli-bundle/chunks/chunk-32BCU6HN.js +115 -0
  13. package/dist/cli-bundle/chunks/{chunk-MTRIGD7M.js → chunk-5IPXDZKU.js} +42 -42
  14. package/dist/cli-bundle/chunks/{chunk-O56O7NIE.js → chunk-5JZMF4M5.js} +2 -2
  15. package/dist/cli-bundle/chunks/{chunk-TYERATXH.js → chunk-7ZEFHFAU.js} +2 -2
  16. package/dist/cli-bundle/chunks/chunk-B6UTLYLM.js +3 -0
  17. package/dist/cli-bundle/chunks/{chunk-N45IXPCA.js → chunk-DEJHTFEF.js} +2 -2
  18. package/dist/cli-bundle/chunks/{chunk-ICT6E4IW.js → chunk-HBKD5HZB.js} +2 -2
  19. package/dist/cli-bundle/chunks/{chunk-6PKWKVS6.js → chunk-JPKIUWLG.js} +2 -2
  20. package/dist/cli-bundle/chunks/{chunk-WFBYKDB2.js → chunk-L6LCLC37.js} +2 -2
  21. package/dist/cli-bundle/chunks/{chunk-Y7CKVU56.js → chunk-MQJXZX3Q.js} +2 -2
  22. package/dist/cli-bundle/chunks/chunk-NR4KABHC.js +31 -0
  23. package/dist/cli-bundle/chunks/{chunk-WX25MU4N.js → chunk-O4ZLEN4T.js} +3 -3
  24. package/dist/cli-bundle/chunks/{chunk-F3ECOBKA.js → chunk-PWD5RY2D.js} +2 -2
  25. package/dist/cli-bundle/chunks/{chunk-SBVX5CMV.js → chunk-RSAN2YUU.js} +2 -2
  26. package/dist/cli-bundle/chunks/{chunk-NILQ2ZMV.js → chunk-TZ3D3DPQ.js} +2 -2
  27. package/dist/cli-bundle/chunks/{chunk-MRUA2Z43.js → chunk-UJMQP2HP.js} +2 -2
  28. package/dist/cli-bundle/chunks/{chunk-TMPO4CTZ.js → chunk-UYNMKUGA.js} +2 -2
  29. package/dist/cli-bundle/chunks/{chunk-UUN3WNMQ.js → chunk-XRMYA4R7.js} +3 -3
  30. package/dist/cli-bundle/chunks/{chunk-UEEG47TU.js → chunk-Y7H55PCY.js} +2 -2
  31. package/dist/cli-bundle/chunks/{chunk-5KW4WUAK.js → chunk-YWS4XV4I.js} +4 -4
  32. package/dist/cli-bundle/chunks/chunk-ZOAJNPBL.js +129 -0
  33. package/dist/cli-bundle/chunks/{indexed-receipt-blobs-KGMJVFH2.js → indexed-receipt-blobs-I6RQGD6Y.js} +2 -2
  34. package/dist/cli-bundle/chunks/item-transaction-ZHLJTBD7.js +2 -0
  35. package/dist/cli-bundle/chunks/{mutation-admission-BOOCJPCU.js → mutation-admission-ZQMRMGIB.js} +2 -2
  36. package/dist/cli-bundle/chunks/{register-list-query-23OX36Q3.js → register-list-query-I6AZA3IX.js} +2 -2
  37. package/dist/cli-bundle/chunks/{register-mutation-JPJ5YNDX.js → register-mutation-3DAXCLXR.js} +2 -2
  38. package/dist/cli-bundle/chunks/{register-operations-IGR7ERY5.js → register-operations-G3QGGQ5Z.js} +2 -2
  39. package/dist/cli-bundle/chunks/{register-setup-BMIFKZZP.js → register-setup-LDXHMNOT.js} +2 -2
  40. package/dist/cli-bundle/chunks/{settlement-hook-YWSWFOZY.js → settlement-hook-JHXLUBEN.js} +2 -2
  41. package/dist/cli-bundle/chunks/{stage-ON7CYYPM.js → stage-7H36OTDJ.js} +2 -2
  42. package/dist/cli-bundle/focused-chunks/chunk-3XGKBVJ3.js +2 -0
  43. package/dist/cli-bundle/focused-chunks/{chunk-WX2RVS2Y.js → chunk-4HY6EGPB.js} +2 -2
  44. package/dist/cli-bundle/focused-chunks/{chunk-3NYWMUX3.js → chunk-D4XQOMG4.js} +3 -3
  45. package/dist/cli-bundle/focused-chunks/{chunk-UQIBGLDR.js → chunk-F3X6UWMI.js} +2 -2
  46. package/dist/cli-bundle/focused-chunks/{chunk-JLXGRDTG.js → chunk-G6ERMFJ5.js} +3 -3
  47. package/dist/cli-bundle/focused-chunks/{chunk-VFQAZLKO.js → chunk-HJ27QLZV.js} +2 -2
  48. package/dist/cli-bundle/focused-chunks/{chunk-5TWS5KOM.js → chunk-HOXIIZEO.js} +2 -2
  49. package/dist/cli-bundle/focused-chunks/chunk-HUXZCPWT.js +26 -0
  50. package/dist/cli-bundle/focused-chunks/{chunk-LVA76N27.js → chunk-I5FODKYB.js} +2 -2
  51. package/dist/cli-bundle/focused-chunks/{chunk-DFUTCKUF.js → chunk-IDAYTYNN.js} +2 -2
  52. package/dist/cli-bundle/focused-chunks/{chunk-2Y77HWIX.js → chunk-IKXJ57XA.js} +2 -2
  53. package/dist/cli-bundle/focused-chunks/{chunk-RPUDOJVB.js → chunk-LKN2WGGB.js} +2 -2
  54. package/dist/cli-bundle/focused-chunks/chunk-MOY6KZGJ.js +44 -0
  55. package/dist/cli-bundle/focused-chunks/{chunk-PAT6QF63.js → chunk-PWUTFKSI.js} +2 -2
  56. package/dist/cli-bundle/focused-chunks/chunk-PZRB7IXH.js +91 -0
  57. package/dist/cli-bundle/focused-chunks/chunk-RY4QEMAE.js +2 -0
  58. package/dist/cli-bundle/focused-chunks/{chunk-6GMYW42K.js → chunk-TYHDZUL4.js} +2 -2
  59. package/dist/cli-bundle/focused-chunks/chunk-WSYPVBKS.js +80 -0
  60. package/dist/cli-bundle/focused-chunks/{chunk-Z7GIVH6B.js → chunk-WXLG7HZ5.js} +2 -2
  61. package/dist/cli-bundle/focused-chunks/{chunk-5WCQFH6D.js → chunk-WZDFCVLX.js} +2 -2
  62. package/dist/cli-bundle/focused-chunks/{chunk-VS2ZFPXD.js → chunk-YGO3FWA2.js} +2 -2
  63. package/dist/cli-bundle/focused-chunks/chunk-YVLAP3BL.js +23 -0
  64. package/dist/cli-bundle/focused-chunks/{chunk-6OKPYCLU.js → chunk-ZQRCVRGS.js} +54 -54
  65. package/dist/cli-bundle/focused-chunks/chunk-ZYXQACPB.js +2 -0
  66. package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-KHWT44EK.js → indexed-receipt-blobs-7XGVHYAO.js} +2 -2
  67. package/dist/cli-bundle/focused-chunks/{item-transaction-7VLPA2SU.js → item-transaction-PZ2FQ6B2.js} +2 -2
  68. package/dist/cli-bundle/focused-chunks/{mutation-admission-2DH27R5Y.js → mutation-admission-XOOK6XFH.js} +2 -2
  69. package/dist/cli-bundle/focused-chunks/{settlement-hook-SJV52ZTV.js → settlement-hook-H56537UV.js} +2 -2
  70. package/dist/cli-bundle/focused-chunks/{stage-FYOBWQA7.js → stage-4SQHVI3O.js} +2 -2
  71. package/dist/cli-bundle/main.js +30 -29
  72. package/dist/cli-bundle/sdk-authoring.js +1 -1
  73. package/dist/cli-bundle/sdk-contracts.js +1 -1
  74. package/dist/cli-bundle/sdk-core.js +1 -1
  75. package/dist/cli-bundle/sdk-governance.js +1 -1
  76. package/dist/cli-bundle/sdk-graph.js +1 -1
  77. package/dist/cli-bundle/sdk-merge.js +57 -57
  78. package/dist/cli-bundle/sdk-query.js +1 -1
  79. package/dist/cli-bundle/sdk-runtime.js +1 -1
  80. package/dist/cli-bundle/sdk-testing.js +1 -1
  81. package/dist/cli-bundle/sdk.js +11 -11
  82. package/dist/core/extensions/extension-hook-runtime.js +1 -1
  83. package/dist/core/extensions/extension-types.d.ts +5 -0
  84. package/dist/core/extensions/extension-types.js +1 -1
  85. package/dist/core/extensions/item-fields.d.ts +1 -1
  86. package/dist/core/extensions/item-fields.js +1 -1
  87. package/dist/core/item/parse.js +2 -2
  88. package/dist/core/lock/lock-confinement.d.ts +55 -0
  89. package/dist/core/lock/lock-confinement.js +2 -0
  90. package/dist/core/lock/lock-gc.js +1 -1
  91. package/dist/core/lock/lock.js +2 -2
  92. package/dist/core/schema/runtime-field-values.d.ts +30 -0
  93. package/dist/core/schema/runtime-field-values.js +1 -1
  94. package/dist/core/sentry/helpers.js +1 -1
  95. package/dist/core/sentry/instrument.js +1 -1
  96. package/dist/core/shared/error-details.d.ts +98 -0
  97. package/dist/core/shared/error-details.js +2 -0
  98. package/dist/core/shared/errors.d.ts +43 -0
  99. package/dist/core/shared/errors.js +1 -1
  100. package/dist/core/store/settings-sections.d.ts +61 -0
  101. package/dist/core/store/settings-sections.js +3 -0
  102. package/dist/core/store/settings-validator.d.ts +4 -0
  103. package/dist/core/store/settings-validator.js +1 -1
  104. package/dist/core/store/settings.d.ts +29 -2
  105. package/dist/core/store/settings.js +4 -3
  106. package/dist/core/telemetry/consent.js +2 -2
  107. package/dist/core/telemetry/runtime.js +2 -2
  108. package/dist/core/test/background-runs.js +3 -3
  109. package/dist/mcp/server.js +2 -2
  110. package/dist/sdk/config.js +1 -1
  111. package/dist/sdk/errors.d.ts +6 -2
  112. package/dist/sdk/errors.js +1 -1
  113. package/dist/sdk/extension-command-context.js +2 -2
  114. package/dist/sdk/generated/error-code-catalog-rows.d.ts +39 -0
  115. package/dist/sdk/generated/error-code-catalog-rows.js +2 -0
  116. package/dist/sdk/generated/generated-error-code-catalog-part-1.d.ts +3 -3
  117. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  118. package/dist/sdk/generated/generated-error-code-catalog-part-2.d.ts +3 -3
  119. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  120. package/dist/sdk/generated-error-code-catalog.js +1 -1
  121. package/dist/sdk/index.d.ts +1 -1
  122. package/dist/sdk/index.js +1 -1
  123. package/dist/sdk/lifecycle/core-field-recovery.d.ts +26 -0
  124. package/dist/sdk/lifecycle/core-field-recovery.js +1 -1
  125. package/dist/sdk/lifecycle/create.js +1 -1
  126. package/dist/sdk/lifecycle/update.js +2 -2
  127. package/dist/sdk/mcp/discovery.js +1 -1
  128. package/dist/sdk/public-surface.json +1 -1
  129. package/dist/sdk/runtime-primitives.d.ts +2 -1
  130. package/dist/sdk/runtime-primitives.js +1 -1
  131. package/dist/sdk/runtime.d.ts +1 -1
  132. package/dist/sdk/runtime.js +1 -1
  133. package/dist/sdk/test/entry.d.ts +5 -0
  134. package/dist/sdk/test/entry.js +2 -2
  135. package/dist/sdk/test/execution.d.ts +1 -2
  136. package/dist/sdk/test/execution.js +2 -2
  137. package/dist/sdk/test/linked-command-detection.d.ts +10 -0
  138. package/dist/sdk/test/linked-command-detection.js +1 -1
  139. package/dist/sdk/test/update.d.ts +2 -0
  140. package/dist/sdk/test/update.js +1 -1
  141. package/docs/AGENT_EVIDENCE_CONSISTENCY.md +10 -0
  142. package/docs/CONFIGURATION.md +9 -0
  143. package/docs/DEVELOPMENT_DEPENDENCY_SECURITY.md +9 -6
  144. package/docs/EXTENSIONS.md +2 -2
  145. package/docs/LINKED_TEST_EDITS.md +38 -5
  146. package/docs/RELEASING.md +22 -2
  147. package/docs/SDK.md +103 -1
  148. package/docs/SDK_CONFIGURATION_SAFETY.md +55 -0
  149. package/docs/TESTING.md +2 -1
  150. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +15 -3
  151. package/marketplace.json +1 -1
  152. package/package.json +9 -3
  153. package/packages/pm-beads/package.json +1 -1
  154. package/packages/pm-calendar/package.json +1 -1
  155. package/packages/pm-command-kit/package.json +1 -1
  156. package/packages/pm-digital-twin/package.json +1 -1
  157. package/packages/pm-governance-audit/package.json +1 -1
  158. package/packages/pm-guide-shell/package.json +1 -1
  159. package/packages/pm-kanban/package.json +1 -1
  160. package/packages/pm-lifecycle-hooks/package.json +1 -1
  161. package/packages/pm-linked-test-adapters/package.json +1 -1
  162. package/packages/pm-search-advanced/package.json +1 -1
  163. package/packages/pm-templates/package.json +1 -1
  164. package/packages/pm-todos/package.json +1 -1
  165. package/packages/pm-vcs/package.json +1 -1
  166. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  167. package/plugins/pm-claude/package.json +1 -1
  168. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  169. package/plugins/pm-codex/package.json +1 -1
  170. package/plugins/pm-codex/plugin.json +1 -1
  171. package/runtime-dependencies.json +1 -1
  172. package/dist/cli-bundle/chunks/chunk-5WVE7XBS.js +0 -114
  173. package/dist/cli-bundle/chunks/chunk-E74BORFX.js +0 -128
  174. package/dist/cli-bundle/chunks/chunk-MP2DQJH2.js +0 -3
  175. package/dist/cli-bundle/chunks/chunk-O6TFUV6M.js +0 -31
  176. package/dist/cli-bundle/chunks/item-transaction-Q5S5YLEJ.js +0 -2
  177. package/dist/cli-bundle/focused-chunks/chunk-3Z53POXU.js +0 -2
  178. package/dist/cli-bundle/focused-chunks/chunk-7WJDRZOR.js +0 -22
  179. package/dist/cli-bundle/focused-chunks/chunk-AL7SOFUL.js +0 -2
  180. package/dist/cli-bundle/focused-chunks/chunk-CIQ6YWCW.js +0 -26
  181. package/dist/cli-bundle/focused-chunks/chunk-GE755ODZ.js +0 -2
  182. package/dist/cli-bundle/focused-chunks/chunk-JCR32IAO.js +0 -91
  183. package/dist/cli-bundle/focused-chunks/chunk-M22TI7LP.js +0 -79
  184. package/dist/cli-bundle/focused-chunks/chunk-SXZM4PSS.js +0 -44
@@ -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]="16379104-dc20-5034-95ab-ebeb63f54952")}catch{}})();import{createRequire}from"node:module";import{resolvePmCliVersion}from"../packages/root.js";import{resolveTelemetryEnvironmentPolicy,resolveTelemetrySourceAttribution}from"../telemetry/policy.js";import{isPmCliExpectedError}from"../../sdk/errors.js";import{scrubInlineSensitiveAssignments,SENSITIVE_KEY_PATTERN}from"./sensitive-assignments.js";const OPT_OUT_VALUES=new Set(["1","true","yes","on"]);function isSentryDisabled(){return!!(OPT_OUT_VALUES.has((process.env.PM_SENTRY_DISABLED??"").trim().toLowerCase())||resolveTelemetryEnvironmentPolicy().telemetry_disabled||typeof process.env.VITEST=="string"||typeof process.env.VITEST_WORKER_ID=="string")}const ABSOLUTE_PATH_TOKEN_RE=/(^|[\s"'`(=])\/(?:[^\s"'`),;]+)/g,FILE_URL_PATH_RE=/file:\/\/\/?[^\s"'`),;]+/giu,WINDOWS_PATH_TOKEN_RE=/\b[A-Za-z]:\\[^\s"'`),;]+/g,PRIVATE_IP_RE=/\b(?:10\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|172\.(?:1[6-9]|2\d|3[01])\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|192\.168\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d))\b/g,PATH_FIELD_KEY_PATTERN=/(?:^|[_-])(path|filename|file|module|cwd|dir|directory|location|source|script)s?$/i,MAX_KNOWN_NOISY_CONSOLE_MESSAGE_PATTERNS=15,KNOWN_NOISY_CONSOLE_MESSAGE_PATTERNS=["[starter-extension] activating","[starter-extension] all 8 capabilities registered.","[starter-extension] commands:","[starter] preflight check for workspace","[starter] output_format service override active","[pm-ext-ts-starter] activating","[pm-ext-ts-starter] all capabilities registered.","run `pm init` first to initialise a pm workspace"];function looksLikeFilesystemPath(value){const normalized=value.trim();return normalized.length===0?!1:normalized.startsWith("/")||normalized.startsWith("file://")||/^[A-Za-z]:\\/.test(normalized)||normalized.startsWith("\\\\")?!0:normalized.includes("/home/")}function scrubString(value,keyHint){if(keyHint&&PATH_FIELD_KEY_PATTERN.test(keyHint)&&looksLikeFilesystemPath(value))return"[scrubbed_path]";const scrubbed=scrubInlineSensitiveAssignments(value).replaceAll(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/giu,"[scrubbed_email]").replaceAll(/bearer\s+[a-z0-9._=-]+/giu,"bearer [scrubbed]").replaceAll(/sntr[ysu]_[A-Za-z0-9_-]+/g,"[scrubbed_sentry_token]").replaceAll(PRIVATE_IP_RE,"[scrubbed_ip]").replaceAll(FILE_URL_PATH_RE,"[scrubbed_path]").replaceAll(WINDOWS_PATH_TOKEN_RE,"[scrubbed_path]").replaceAll(ABSOLUTE_PATH_TOKEN_RE,(_match,prefix)=>`${prefix}[scrubbed_path]`);return looksLikeFilesystemPath(scrubbed)?"[scrubbed_path]":scrubbed}function scrubEventData(obj){const result={};for(const[key,value]of Object.entries(obj))SENSITIVE_KEY_PATTERN.test(key)||key.startsWith("sentry.message.parameter.")?result[key]="[scrubbed]":typeof value=="string"?result[key]=scrubString(value,key):Array.isArray(value)?result[key]=value.map(entry=>typeof entry=="string"?scrubString(entry,key):entry&&typeof entry=="object"?scrubEventData(entry):entry):value&&typeof value=="object"?result[key]=scrubEventData(value):result[key]=value;return result}function scrubStackFrame(frame){for(const key of["filename","absPath","abs_path","module"]){const rawValue=frame[key];typeof rawValue=="string"&&(frame[key]=scrubString(rawValue,key))}const contextLine=frame.context_line;typeof contextLine=="string"&&(frame.context_line=scrubString(contextLine,"context_line"));for(const key of["pre_context","post_context"]){const context=frame[key];Array.isArray(context)&&(frame[key]=context.map(entry=>typeof entry=="string"?scrubString(entry,key):entry))}frame.vars&&typeof frame.vars=="object"&&(frame.vars=scrubEventData(frame.vars)),frame.data&&typeof frame.data=="object"&&(frame.data=scrubEventData(frame.data))}const requireFromInstrument=createRequire(import.meta.url),defaultSentryLoader=()=>requireFromInstrument("@sentry/node");let _sentry,_initDone=!1,_loadSentry=defaultSentryLoader;const PM_CLI_SENTRY_DSN="https://bf7ad2ec76c0051c2ee94e48e8bd6868@o4510603477712896.ingest.de.sentry.io/4511316775338064";function hasPmCliErrorPrefix(value){return/^\s*PmCliError:/.test(value)}function isKnownNoisyConsoleMessage(value){const normalized=value.trim().toLowerCase();return normalized.length===0?!1:KNOWN_NOISY_CONSOLE_MESSAGE_PATTERNS.some(pattern=>normalized.includes(pattern))}function isKnownNoisyConsoleEvent(event){return event.logger!=="console"?!1:typeof event.message=="string"&&isKnownNoisyConsoleMessage(event.message)?!0:Array.isArray(event.exception?.values)&&event.exception.values.some(entry=>typeof entry.value=="string"&&isKnownNoisyConsoleMessage(entry.value))}function isNodeRuntimeWarningEvent(event){if(event.logger!=="console")return!1;const isRuntimeWarning=value=>typeof value=="string"&&/^\(node:\d+\) MaxListenersExceededWarning: Possible EventEmitter memory leak detected\./.test(value);return isRuntimeWarning(event.message)?!0:Array.isArray(event.exception?.values)&&event.exception.values.some(entry=>isRuntimeWarning(entry.value))}function isExpectedCliErrorEvent(event,originalException){return originalException instanceof Error?isPmCliExpectedError(originalException):!!(event.exception?.values?.some(ex=>ex.type==="PmCliError")||event.exception?.values?.some(ex=>typeof ex.value=="string"&&hasPmCliErrorPrefix(ex.value))||event.logger==="console"&&typeof event.message=="string"&&hasPmCliErrorPrefix(event.message))}function isPmCliErrorBreadcrumb(breadcrumb){return breadcrumb.category==="console"&&typeof breadcrumb.message=="string"&&hasPmCliErrorPrefix(breadcrumb.message)}function isKnownNoisyConsoleBreadcrumb(breadcrumb){return breadcrumb.category==="console"&&typeof breadcrumb.message=="string"&&isKnownNoisyConsoleMessage(breadcrumb.message)}function resolveCliVersion(){return resolvePmCliVersion(import.meta.url,["../../.."])??"0.0.0"}function resolveEnvironment(){const explicit=process.env.SENTRY_ENVIRONMENT?.trim();if(explicit&&explicit.length>0)return explicit;if(process.env.VITEST||process.env.VITEST_WORKER_ID||process.env.NODE_ENV==="test")return"test";if(process.env.CI)return"ci";const source=resolveTelemetrySourceAttribution().source_context;return source==="user"?"production":source}const DEFAULT_TRACES_SAMPLE_RATE=.2;function resolveTracesSampleRate(){const raw=process.env.SENTRY_TRACES_SAMPLE_RATE?.trim();if(!raw)return DEFAULT_TRACES_SAMPLE_RATE;const parsed=Number(raw);return!Number.isFinite(parsed)||parsed<0||parsed>1?DEFAULT_TRACES_SAMPLE_RATE:parsed}function scrubSentryExceptionValues(event){if(event.exception?.values){for(const exception of event.exception.values)if(exception.value&&(exception.value=scrubString(exception.value,"value")),exception.stacktrace?.frames)for(const frame of exception.stacktrace.frames)scrubStackFrame(frame)}}function scrubSentryBreadcrumbs(event){if(event.breadcrumbs)for(const breadcrumb of event.breadcrumbs)breadcrumb.message&&(breadcrumb.message=scrubString(breadcrumb.message)),breadcrumb.data&&typeof breadcrumb.data=="object"&&(breadcrumb.data=scrubEventData(breadcrumb.data))}function scrubSentryContexts(event){if(event.contexts)for(const[ctxKey,ctx]of Object.entries(event.contexts))ctx&&typeof ctx=="object"&&(event.contexts[ctxKey]=scrubEventData(ctx))}function scrubSentryRecordField(event,key){const target=event,value=target[key];value&&typeof value=="object"&&(target[key]=scrubEventData(value))}function sourceContextEnvironment(source){if(!process.env.SENTRY_ENVIRONMENT?.trim()&&(source==="automation"||source==="test"||source==="dogfood"||source==="user"))return source==="user"?"production":source}function applySourceContextEnvironment(event){const environment=sourceContextEnvironment(event.tags?.["pm.source_context"]);environment&&(event.environment=environment)}const beforeSend=(event,hint)=>{if(isExpectedCliErrorEvent(event,hint?.originalException)||isKnownNoisyConsoleEvent(event))return null;applySourceContextEnvironment(event),isNodeRuntimeWarningEvent(event)&&(event.level="warning",event.tags={...event.tags,"pm.diagnostic_class":"node_runtime_warning"}),event.message&&(event.message=scrubString(event.message,"message")),event.transaction&&(event.transaction=scrubString(event.transaction,"transaction")),scrubSentryExceptionValues(event),scrubSentryBreadcrumbs(event),scrubSentryRecordField(event,"extra"),scrubSentryContexts(event);for(const key of["request","user","tags"])scrubSentryRecordField(event,key);return event},beforeSendTransaction=event=>(applySourceContextEnvironment(event),event.breadcrumbs&&(event.breadcrumbs=event.breadcrumbs.filter(breadcrumb=>!isPmCliErrorBreadcrumb(breadcrumb)&&!isKnownNoisyConsoleBreadcrumb(breadcrumb)),scrubSentryBreadcrumbs(event)),scrubSentryContexts(event),event),beforeSendSpan=span=>scrubEventData(span),beforeSendLog=log=>{if(log.message=scrubString(log.message),log.attributes){const environment=sourceContextEnvironment(log.attributes["pm.source_context"]);environment&&(log.attributes["sentry.environment"]=environment),log.attributes=scrubEventData(log.attributes)}return log};function applySerializedLogEnvironment(attributes){const environment=sourceContextEnvironment(attributes["pm.source_context"]?.value);environment&&(attributes["sentry.environment"]={type:"string",value:environment})}function scrubSentryLogEnvelope(envelope){for(const item of envelope[1])if(item[0].type==="log")for(const log of item[1].items){log.body=scrubString(log.body);const attributes=log.attributes;if(attributes){applySerializedLogEnvironment(attributes);for(const[key,attribute]of Object.entries(attributes)){const value=scrubEventData({[key]:attribute.value})[key];typeof value=="string"&&(attributes[key]={type:"string",value})}}}}const beforeBreadcrumb=breadcrumb=>isPmCliErrorBreadcrumb(breadcrumb)||isKnownNoisyConsoleBreadcrumb(breadcrumb)?null:(breadcrumb.message&&(breadcrumb.message=scrubString(breadcrumb.message,"message")),breadcrumb.data&&typeof breadcrumb.data=="object"&&(breadcrumb.data=scrubEventData(breadcrumb.data)),breadcrumb);async function ensureSentryInit(){if(_initDone)return _sentry;if(_initDone=!0,isSentryDisabled())return;const SentryModule=_loadSentry(),dsn=process.env.SENTRY_DSN?.trim()||PM_CLI_SENTRY_DSN,release=resolveCliVersion();SentryModule.init({dsn,release:`pm-cli@${release}`,environment:resolveEnvironment(),tracesSampleRate:resolveTracesSampleRate(),enableLogs:!0,attachStacktrace:!0,normalizeDepth:6,shutdownTimeout:3e3,traceLifecycle:"stream",dataCollection:{userInfo:!1,cookies:!1,httpHeaders:{request:!1,response:!1},httpBodies:[],urlQueryParams:!1,genAI:{inputs:!1,outputs:!1},databaseQueryData:!1,graphQL:{document:!1,variables:!1},stackFrameVariables:!1,frameContextLines:0},serverName:void 0,integrations:[SentryModule.extraErrorDataIntegration({depth:4,captureErrorCause:!1}),SentryModule.captureConsoleIntegration({levels:["warn","error"]})],initialScope:{tags:{"cli.name":"pm-cli","cli.version":release,"runtime.node":process.version,"runtime.platform":process.platform,"runtime.arch":process.arch}},beforeSend,beforeSendTransaction,beforeSendSpan:SentryModule.withStreamedSpan(beforeSendSpan),beforeSendLog,beforeBreadcrumb});const client=SentryModule.getClient();if(!client)return;const attribution=resolveTelemetrySourceAttribution();return SentryModule.setTags({"pm.version":release,"pm.source_context":attribution.source_context,"pm.source_context_source":attribution.source_context_source}),SentryModule.setAttribute("pm.source_context",attribution.source_context),client.on("beforeEnvelope",scrubSentryLogEnvelope),_sentry=SentryModule,SentryModule}async function ensureSentryCommandTracing(telemetryEnabled){if(telemetryEnabled!==!0||!OPT_OUT_VALUES.has((process.env.PM_SENTRY_TRACE_COMMANDS??"").trim().toLowerCase())||resolveTracesSampleRate()===0||isSentryDisabled())return!1;try{return await ensureSentryInit()!==void 0}catch{return _sentry=void 0,!1}}function getSentry(){return _sentry}const _testOnly={isExpectedCliErrorEvent,isKnownNoisyConsoleEvent,isNodeRuntimeWarningEvent,isPmCliErrorBreadcrumb,isKnownNoisyConsoleBreadcrumb,scrubString,scrubEventData,resolveTracesSampleRate,KNOWN_NOISY_CONSOLE_MESSAGE_PATTERNS,MAX_KNOWN_NOISY_CONSOLE_MESSAGE_PATTERNS,defaultSentryLoader,setSentryLoaderForTests(loader){_loadSentry=loader??defaultSentryLoader},resetSentryStateForTests(){_sentry=void 0,_initDone=!1}};export{_testOnly,ensureSentryCommandTracing,ensureSentryInit,getSentry};
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]="93725298-6091-543b-969d-bac38d70be89")}catch{}})();import{createRequire}from"node:module";import{resolvePmCliVersion}from"../packages/root.js";import{resolveTelemetryEnvironmentPolicy,resolveTelemetrySourceAttribution}from"../telemetry/policy.js";import{isPmCliExpectedError}from"../../sdk/errors.js";import{crashReportErrorContext,omitEmbeddedPmCliErrorDetails}from"../shared/error-details.js";import{scrubInlineSensitiveAssignments,SENSITIVE_KEY_PATTERN}from"./sensitive-assignments.js";const OPT_OUT_VALUES=new Set(["1","true","yes","on"]);function isSentryDisabled(){return!!(OPT_OUT_VALUES.has((process.env.PM_SENTRY_DISABLED??"").trim().toLowerCase())||resolveTelemetryEnvironmentPolicy().telemetry_disabled||typeof process.env.VITEST=="string"||typeof process.env.VITEST_WORKER_ID=="string")}const ABSOLUTE_PATH_TOKEN_RE=/(^|[\s"'`(=])\/(?:[^\s"'`),;]+)/g,FILE_URL_PATH_RE=/file:\/\/\/?[^\s"'`),;]+/giu,WINDOWS_PATH_TOKEN_RE=/\b[A-Za-z]:\\[^\s"'`),;]+/g,PRIVATE_IP_RE=/\b(?:10\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|172\.(?:1[6-9]|2\d|3[01])\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|192\.168\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d))\b/g,PATH_FIELD_KEY_PATTERN=/(?:^|[_-])(path|filename|file|module|cwd|dir|directory|location|source|script)s?$/i,MAX_KNOWN_NOISY_CONSOLE_MESSAGE_PATTERNS=15,KNOWN_NOISY_CONSOLE_MESSAGE_PATTERNS=["[starter-extension] activating","[starter-extension] all 8 capabilities registered.","[starter-extension] commands:","[starter] preflight check for workspace","[starter] output_format service override active","[pm-ext-ts-starter] activating","[pm-ext-ts-starter] all capabilities registered.","run `pm init` first to initialise a pm workspace"];function looksLikeFilesystemPath(value){const normalized=value.trim();return normalized.length===0?!1:normalized.startsWith("/")||normalized.startsWith("file://")||/^[A-Za-z]:\\/.test(normalized)||normalized.startsWith("\\\\")?!0:normalized.includes("/home/")}function scrubString(value,keyHint){if(keyHint&&PATH_FIELD_KEY_PATTERN.test(keyHint)&&looksLikeFilesystemPath(value))return"[scrubbed_path]";const scrubbed=scrubInlineSensitiveAssignments(value).replaceAll(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/giu,"[scrubbed_email]").replaceAll(/bearer\s+[a-z0-9._=-]+/giu,"bearer [scrubbed]").replaceAll(/sntr[ysu]_[A-Za-z0-9_-]+/g,"[scrubbed_sentry_token]").replaceAll(PRIVATE_IP_RE,"[scrubbed_ip]").replaceAll(FILE_URL_PATH_RE,"[scrubbed_path]").replaceAll(WINDOWS_PATH_TOKEN_RE,"[scrubbed_path]").replaceAll(ABSOLUTE_PATH_TOKEN_RE,(_match,prefix)=>`${prefix}[scrubbed_path]`);return looksLikeFilesystemPath(scrubbed)?"[scrubbed_path]":scrubbed}function scrubEventData(obj){const result={};for(const[key,value]of Object.entries(obj))SENSITIVE_KEY_PATTERN.test(key)||key.startsWith("sentry.message.parameter.")?result[key]="[scrubbed]":typeof value=="string"?result[key]=scrubString(value,key):Array.isArray(value)?result[key]=value.map(entry=>typeof entry=="string"?scrubString(entry,key):entry&&typeof entry=="object"?scrubEventData(entry):entry):value&&typeof value=="object"?result[key]=scrubEventData(value):result[key]=value;return result}function scrubStackFrame(frame){for(const key of["filename","absPath","abs_path","module"]){const rawValue=frame[key];typeof rawValue=="string"&&(frame[key]=scrubString(rawValue,key))}const contextLine=frame.context_line;typeof contextLine=="string"&&(frame.context_line=scrubString(contextLine,"context_line"));for(const key of["pre_context","post_context"]){const context=frame[key];Array.isArray(context)&&(frame[key]=context.map(entry=>typeof entry=="string"?scrubString(entry,key):entry))}frame.vars&&typeof frame.vars=="object"&&(frame.vars=scrubEventData(frame.vars)),frame.data&&typeof frame.data=="object"&&(frame.data=scrubEventData(frame.data))}const requireFromInstrument=createRequire(import.meta.url),defaultSentryLoader=()=>requireFromInstrument("@sentry/node");let _sentry,_initDone=!1,_loadSentry=defaultSentryLoader;const PM_CLI_SENTRY_DSN="https://bf7ad2ec76c0051c2ee94e48e8bd6868@o4510603477712896.ingest.de.sentry.io/4511316775338064";function hasPmCliErrorPrefix(value){return/^\s*PmCliError:/.test(value)}function isKnownNoisyConsoleMessage(value){const normalized=value.trim().toLowerCase();return normalized.length===0?!1:KNOWN_NOISY_CONSOLE_MESSAGE_PATTERNS.some(pattern=>normalized.includes(pattern))}function isKnownNoisyConsoleEvent(event){return event.logger!=="console"?!1:typeof event.message=="string"&&isKnownNoisyConsoleMessage(event.message)?!0:Array.isArray(event.exception?.values)&&event.exception.values.some(entry=>typeof entry.value=="string"&&isKnownNoisyConsoleMessage(entry.value))}function isNodeRuntimeWarningEvent(event){if(event.logger!=="console")return!1;const isRuntimeWarning=value=>typeof value=="string"&&/^\(node:\d+\) MaxListenersExceededWarning: Possible EventEmitter memory leak detected\./.test(value);return isRuntimeWarning(event.message)?!0:Array.isArray(event.exception?.values)&&event.exception.values.some(entry=>isRuntimeWarning(entry.value))}function isExpectedCliErrorEvent(event,originalException){return originalException instanceof Error?isPmCliExpectedError(originalException):!!(event.exception?.values?.some(ex=>ex.type==="PmCliError")||event.exception?.values?.some(ex=>typeof ex.value=="string"&&hasPmCliErrorPrefix(ex.value))||event.logger==="console"&&typeof event.message=="string"&&hasPmCliErrorPrefix(event.message))}function isPmCliErrorBreadcrumb(breadcrumb){return breadcrumb.category==="console"&&typeof breadcrumb.message=="string"&&hasPmCliErrorPrefix(breadcrumb.message)}function isKnownNoisyConsoleBreadcrumb(breadcrumb){return breadcrumb.category==="console"&&typeof breadcrumb.message=="string"&&isKnownNoisyConsoleMessage(breadcrumb.message)}function resolveCliVersion(){return resolvePmCliVersion(import.meta.url,["../../.."])??"0.0.0"}function resolveEnvironment(){const explicit=process.env.SENTRY_ENVIRONMENT?.trim();if(explicit&&explicit.length>0)return explicit;if(process.env.VITEST||process.env.VITEST_WORKER_ID||process.env.NODE_ENV==="test")return"test";if(process.env.CI)return"ci";const source=resolveTelemetrySourceAttribution().source_context;return source==="user"?"production":source}const DEFAULT_TRACES_SAMPLE_RATE=.2;function resolveTracesSampleRate(){const raw=process.env.SENTRY_TRACES_SAMPLE_RATE?.trim();if(!raw)return DEFAULT_TRACES_SAMPLE_RATE;const parsed=Number(raw);return!Number.isFinite(parsed)||parsed<0||parsed>1?DEFAULT_TRACES_SAMPLE_RATE:parsed}function scrubSentryExceptionValues(event){if(event.exception?.values){for(const exception of event.exception.values)if(exception.value&&(exception.value=scrubString(exception.value,"value")),exception.stacktrace?.frames)for(const frame of exception.stacktrace.frames)scrubStackFrame(frame)}}function scrubSentryBreadcrumbs(event){if(event.breadcrumbs)for(const breadcrumb of event.breadcrumbs)breadcrumb.message&&(breadcrumb.message=scrubString(breadcrumb.message)),breadcrumb.data&&typeof breadcrumb.data=="object"&&(breadcrumb.data=scrubEventData(breadcrumb.data))}function scrubSentryContexts(event){if(event.contexts)for(const[ctxKey,ctx]of Object.entries(event.contexts))ctx&&typeof ctx=="object"&&(event.contexts[ctxKey]=scrubEventData(ctx))}function scrubSentryRecordField(event,key){const target=event,value=target[key];value&&typeof value=="object"&&(target[key]=scrubEventData(value))}function sourceContextEnvironment(source){if(!process.env.SENTRY_ENVIRONMENT?.trim()&&(source==="automation"||source==="test"||source==="dogfood"||source==="user"))return source==="user"?"production":source}function applySourceContextEnvironment(event){const environment=sourceContextEnvironment(event.tags?.["pm.source_context"]);environment&&(event.environment=environment)}function omitProducerDiagnostics(event,originalException){const ownErrorContext=readOwnErrorContextExtra(event.extra);omitEmbeddedPmCliErrorDetails([event.contexts,event.extra,event.breadcrumbs]),rebuildErrorDataContexts(event.contexts,originalException),ownErrorContext!==void 0&&(event.extra.error_context=crashReportErrorContext(ownErrorContext))}function readOwnErrorContextExtra(extra){if(!(typeof extra!="object"||extra===null||!Object.hasOwn(extra,"error_context")))return extra.error_context}function rebuildErrorDataContexts(contexts,originalException){if(typeof contexts!="object"||contexts===null||typeof originalException!="object"||originalException===null)return;const record=contexts,keys=new Set(errorDataContextKeys(originalException)),rebuilt=safeErrorDataEntry(originalException);for(const[key,entry]of Object.entries(record))(keys.has(key)||typeof entry=="object"&&entry!==null&&Object.hasOwn(entry,"context"))&&(record[key]=rebuilt??{})}function errorDataContextKeys(error){try{return[error.name,error.constructor?.name].filter(candidate=>typeof candidate=="string"&&candidate.length>0)}catch{return[]}}function safeErrorDataEntry(error){try{const entry=crashReportErrorContext(error),context=Object.getOwnPropertyDescriptor(error,"context");return context!==void 0&&"value"in context&&(entry.context=crashReportErrorContext(context.value)),entry}catch{return}}const beforeSend=(event,hint)=>{if(isExpectedCliErrorEvent(event,hint?.originalException)||isKnownNoisyConsoleEvent(event))return null;omitProducerDiagnostics(event,hint?.originalException),applySourceContextEnvironment(event),isNodeRuntimeWarningEvent(event)&&(event.level="warning",event.tags={...event.tags,"pm.diagnostic_class":"node_runtime_warning"}),event.message&&(event.message=scrubString(event.message,"message")),event.transaction&&(event.transaction=scrubString(event.transaction,"transaction")),scrubSentryExceptionValues(event),scrubSentryBreadcrumbs(event),scrubSentryRecordField(event,"extra"),scrubSentryContexts(event);for(const key of["request","user","tags"])scrubSentryRecordField(event,key);return event},beforeSendTransaction=event=>(omitProducerDiagnostics(event),applySourceContextEnvironment(event),event.breadcrumbs&&(event.breadcrumbs=event.breadcrumbs.filter(breadcrumb=>!isPmCliErrorBreadcrumb(breadcrumb)&&!isKnownNoisyConsoleBreadcrumb(breadcrumb)),scrubSentryBreadcrumbs(event)),scrubSentryContexts(event),event),beforeSendSpan=span=>scrubEventData(span),beforeSendLog=log=>{if(log.message=scrubString(log.message),log.attributes){const environment=sourceContextEnvironment(log.attributes["pm.source_context"]);environment&&(log.attributes["sentry.environment"]=environment),log.attributes=scrubEventData(log.attributes)}return log};function applySerializedLogEnvironment(attributes){const environment=sourceContextEnvironment(attributes["pm.source_context"]?.value);environment&&(attributes["sentry.environment"]={type:"string",value:environment})}function scrubSentryLogEnvelope(envelope){for(const item of envelope[1])if(item[0].type==="log")for(const log of item[1].items){log.body=scrubString(log.body);const attributes=log.attributes;if(attributes){applySerializedLogEnvironment(attributes);for(const[key,attribute]of Object.entries(attributes)){const value=scrubEventData({[key]:attribute.value})[key];typeof value=="string"&&(attributes[key]={type:"string",value})}}}}const beforeBreadcrumb=breadcrumb=>isPmCliErrorBreadcrumb(breadcrumb)||isKnownNoisyConsoleBreadcrumb(breadcrumb)?null:(breadcrumb.message&&(breadcrumb.message=scrubString(breadcrumb.message,"message")),breadcrumb.data&&typeof breadcrumb.data=="object"&&(breadcrumb.data=scrubEventData(breadcrumb.data)),breadcrumb);async function ensureSentryInit(){if(_initDone)return _sentry;if(_initDone=!0,isSentryDisabled())return;const SentryModule=_loadSentry(),dsn=process.env.SENTRY_DSN?.trim()||PM_CLI_SENTRY_DSN,release=resolveCliVersion();SentryModule.init({dsn,release:`pm-cli@${release}`,environment:resolveEnvironment(),tracesSampleRate:resolveTracesSampleRate(),enableLogs:!0,attachStacktrace:!0,normalizeDepth:6,shutdownTimeout:3e3,traceLifecycle:"stream",dataCollection:{userInfo:!1,cookies:!1,httpHeaders:{request:!1,response:!1},httpBodies:[],urlQueryParams:!1,genAI:{inputs:!1,outputs:!1},databaseQueryData:!1,graphQL:{document:!1,variables:!1},stackFrameVariables:!1,frameContextLines:0},serverName:void 0,integrations:[SentryModule.extraErrorDataIntegration({depth:4,captureErrorCause:!1}),SentryModule.captureConsoleIntegration({levels:["warn","error"]})],initialScope:{tags:{"cli.name":"pm-cli","cli.version":release,"runtime.node":process.version,"runtime.platform":process.platform,"runtime.arch":process.arch}},beforeSend,beforeSendTransaction,beforeSendSpan:SentryModule.withStreamedSpan(beforeSendSpan),beforeSendLog,beforeBreadcrumb});const client=SentryModule.getClient();if(!client)return;const attribution=resolveTelemetrySourceAttribution();return SentryModule.setTags({"pm.version":release,"pm.source_context":attribution.source_context,"pm.source_context_source":attribution.source_context_source}),SentryModule.setAttribute("pm.source_context",attribution.source_context),client.on("beforeEnvelope",scrubSentryLogEnvelope),_sentry=SentryModule,SentryModule}async function ensureSentryCommandTracing(telemetryEnabled){if(telemetryEnabled!==!0||!OPT_OUT_VALUES.has((process.env.PM_SENTRY_TRACE_COMMANDS??"").trim().toLowerCase())||resolveTracesSampleRate()===0||isSentryDisabled())return!1;try{return await ensureSentryInit()!==void 0}catch{return _sentry=void 0,!1}}function getSentry(){return _sentry}const _testOnly={isExpectedCliErrorEvent,isKnownNoisyConsoleEvent,isNodeRuntimeWarningEvent,isPmCliErrorBreadcrumb,isKnownNoisyConsoleBreadcrumb,scrubString,scrubEventData,resolveTracesSampleRate,KNOWN_NOISY_CONSOLE_MESSAGE_PATTERNS,MAX_KNOWN_NOISY_CONSOLE_MESSAGE_PATTERNS,defaultSentryLoader,setSentryLoaderForTests(loader){_loadSentry=loader??defaultSentryLoader},resetSentryStateForTests(){_sentry=void 0,_initDone=!1}};export{_testOnly,ensureSentryCommandTracing,ensureSentryInit,getSentry};
2
2
  //# sourceMappingURL=instrument.js.map
@@ -0,0 +1,98 @@
1
+ /**
2
+ * @module core/shared/error-details
3
+ *
4
+ * Admits and bounds producer-owned structured diagnostics carried on an
5
+ * expected error (`PmCliErrorContext.details`, GH-1631). The host never
6
+ * interprets these values: it checks that they are plain, well-formed JSON,
7
+ * renders them whole within a declared byte ceiling, and otherwise replaces
8
+ * them with an omission receipt. Telemetry and crash reporting never read
9
+ * them.
10
+ *
11
+ * Every traversal reads own data properties only (accessors are refused, never
12
+ * invoked) and counts the compact JSON encoding as it walks, so a shared or
13
+ * deeply repeated structure is abandoned as soon as it crosses the ceiling
14
+ * instead of being expanded first.
15
+ */
16
+ import type { PmCliErrorDetails,PmCliErrorDetailsOmission } from "./errors.js";
17
+ export type { PmCliErrorDetailsOmission,PmCliErrorDetailsRejection } from "./errors.js";
18
+ /** Declared ceilings for producer-owned error diagnostics. */
19
+ export declare const PM_CLI_ERROR_DETAILS_LIMITS:Readonly<{
20
+ /** Largest compact UTF-8 JSON encoding rendered; larger diagnostics are omitted whole. */
21
+ max_bytes:4096;
22
+ /** Deepest container nesting accepted below the `details` object itself. */
23
+ max_depth:8;
24
+ }>;
25
+ /** Outcome of admitting one diagnostics value. */
26
+ export type PmCliErrorDetailsAdmission = {
27
+ ok:true;
28
+ details:PmCliErrorDetails;
29
+ byte_length:number;
30
+ } | {
31
+ ok:false;
32
+ omission:PmCliErrorDetailsOmission;
33
+ };
34
+ /**
35
+ * Admit a diagnostics value: a plain object whose leaves are null, booleans,
36
+ * finite numbers and well-formed strings, nested at most
37
+ * {@link PM_CLI_ERROR_DETAILS_LIMITS}.max_depth containers deep and encoding
38
+ * to at most `max_bytes` of compact UTF-8 JSON. Returns a detached copy so
39
+ * later mutation of the producer's object cannot change a raised refusal.
40
+ * Accessor properties are refused without being invoked, and the walk stops
41
+ * at the byte ceiling, so admission cost is bounded by the ceiling.
42
+ */
43
+ export declare function admitPmCliErrorDetails(value:unknown):PmCliErrorDetailsAdmission;
44
+ /** Check the diagnostics shape and byte ceiling. */
45
+ export declare function isPmCliErrorDetails(value:unknown):value is PmCliErrorDetails;
46
+ /**
47
+ * Project diagnostics for a structured error envelope: render them whole when
48
+ * they are well-formed and fit the byte ceiling, otherwise return only the
49
+ * omission receipt. Partial structures are never emitted.
50
+ */
51
+ export declare function projectPmCliErrorDetails(value:unknown):{
52
+ details:PmCliErrorDetails;
53
+ } | {
54
+ details_omitted:PmCliErrorDetailsOmission;
55
+ } | undefined;
56
+ /**
57
+ * Plain snapshot of a foreign error context, taken once at a host boundary:
58
+ * own enumerable data properties are copied, accessors are never run, a
59
+ * `details` accessor becomes an `unsupported_value` receipt, and a context the
60
+ * host cannot inspect at all (a hostile proxy) becomes an empty object.
61
+ */
62
+ export declare function snapshotPmCliErrorContext(context:unknown):Record<string,unknown>;
63
+ /**
64
+ * Project the diagnostics of an error context: `details` rendered through
65
+ * {@link projectPmCliErrorDetails}, otherwise a valid host-recorded
66
+ * `details_omitted` receipt. Accessors are reported, never run, and an
67
+ * uninspectable context yields an `unsupported_value` receipt.
68
+ */
69
+ export declare function projectPmCliErrorContextDetailsSlot(context:unknown):ReturnType<typeof projectPmCliErrorDetails>;
70
+ /**
71
+ * Bound an error context for a transport that forwards the context as-is
72
+ * (MCP): diagnostics are rendered through {@link projectPmCliErrorContextDetailsSlot},
73
+ * every other host field is left untouched.
74
+ */
75
+ export declare function projectPmCliErrorContextDetails(context:unknown):unknown;
76
+ /**
77
+ * Remove producer diagnostics, and the receipt describing them (its path can
78
+ * echo producer keys), from a context bound for telemetry or crash reporting.
79
+ */
80
+ export declare function omitPmCliErrorDetails(context:unknown):unknown;
81
+ /**
82
+ * The only form of an error context a crash report may carry: a getter-free
83
+ * snapshot reduced to its top-level primitive fields, without producer
84
+ * diagnostics, their receipt or a serializer. Nested values are dropped,
85
+ * because a custom toJSON or a shared reference could carry diagnostics
86
+ * under any other key.
87
+ */
88
+ export declare function crashReportErrorContext(context:unknown):Record<string,unknown>;
89
+ /**
90
+ * Discard every embedded error context (`*.context` and `*.error_context`
91
+ * objects) inside a serialized crash-report payload, in place, replacing each
92
+ * with an empty object. These copies were produced by the reporter's own
93
+ * serializer (which runs custom toJSON hooks) and their originals cannot be
94
+ * recovered, so no projection of them can be proven free of diagnostics.
95
+ * Console captures and breadcrumbs carry them at arbitrary positions, so a
96
+ * shallow scrub is not enough.
97
+ */
98
+ export declare function omitEmbeddedPmCliErrorDetails(payload:unknown):void;
@@ -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]="a483f454-e261-5232-bae0-da3cdb8c0518")}catch{}})();const PM_CLI_ERROR_DETAILS_LIMITS=Object.freeze({max_bytes:4096,max_depth:8}),MAX_OMISSION_PATH_BYTES=160,DETAILS_REJECTIONS=new Set(["not_plain_object","unsupported_value","non_finite_number","malformed_unicode","reserved_key","depth_limit","byte_limit","diagnostic_budget"]),LONE_SURROGATE=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u,RESERVED_KEYS=new Set(["__proto__"]);class DetailsShapeError extends Error{reason;path;constructor(reason,path){super(reason),this.reason=reason,this.path=path}}function isPlainObject(value){if(typeof value!="object"||value===null||Array.isArray(value))return!1;const prototype=Object.getPrototypeOf(value);return prototype===Object.prototype||prototype===null}function childPath(path,key){return/^[A-Za-z_$][\w$]*$/u.test(key)?`${path}.${key}`:`${path}[${JSON.stringify(key)}]`}function boundPath(path){if(Buffer.byteLength(path,"utf8")<=MAX_OMISSION_PATH_BYTES)return path;let bounded="",bytes=Buffer.byteLength("\u2026","utf8");for(const character of path){if(bytes+=Buffer.byteLength(character,"utf8"),bytes>MAX_OMISSION_PATH_BYTES)break;bounded+=character}return`${bounded}\u2026`}function charge(budget,bytes,path){if(budget.bytes+=bytes,!(budget.bytes<=PM_CLI_ERROR_DETAILS_LIMITS.max_bytes))throw new DetailsShapeError("byte_limit",path)}function assertCanFit(budget,minimumBytes,path){if(budget.bytes+minimumBytes>PM_CLI_ERROR_DETAILS_LIMITS.max_bytes)throw new DetailsShapeError("byte_limit",path)}function readOwnDataValue(container,key,path){const descriptor=Object.getOwnPropertyDescriptor(container,key);if(descriptor===void 0||!("value"in descriptor))throw new DetailsShapeError("unsupported_value",path);return descriptor.value}function copyDetailLeaf(value,path,budget){if(typeof value=="number"&&!Number.isFinite(value))throw new DetailsShapeError("non_finite_number",path);if(typeof value=="string"&&(assertCanFit(budget,value.length+2,path),LONE_SURROGATE.test(value)))throw new DetailsShapeError("malformed_unicode",path);if(value!==null&&!["boolean","number","string"].includes(typeof value))throw new DetailsShapeError("unsupported_value",path);return charge(budget,Buffer.byteLength(JSON.stringify(value),"utf8"),path),value}function copyDetailValue(value,path,depth,budget){if(typeof value!="object"||value===null)return copyDetailLeaf(value,path,budget);if(depth>=PM_CLI_ERROR_DETAILS_LIMITS.max_depth)throw new DetailsShapeError("depth_limit",path);if(Array.isArray(value)){const length=readOwnDataValue(value,"length",path);if(typeof length!="number"||!Number.isSafeInteger(length)||length<0)throw new DetailsShapeError("unsupported_value",path);charge(budget,length>0?length+1:2,path);const copy=[];for(let index=0;index<length;index+=1){const entryPath=`${path}[${index}]`;copy.push(copyDetailValue(readOwnDataValue(value,String(index),entryPath),entryPath,depth+1,budget))}return copy}if(!isPlainObject(value))throw new DetailsShapeError("unsupported_value",path);return copyDetailObject(value,path,depth+1,budget)}function copyDetailObject(value,path,depth,budget){const keys=Object.keys(value);charge(budget,keys.length>0?keys.length+1:2,path);const copy={};for(const key of keys){assertCanFit(budget,key.length+3,path);const keyPath=childPath(path,key);if(RESERVED_KEYS.has(key))throw new DetailsShapeError("reserved_key",keyPath);if(LONE_SURROGATE.test(key))throw new DetailsShapeError("malformed_unicode",keyPath);charge(budget,Buffer.byteLength(JSON.stringify(key),"utf8")+1,keyPath),copy[key]=copyDetailValue(readOwnDataValue(value,key,keyPath),keyPath,depth,budget)}return copy}function classifyAdmissionFault(error){try{if(error instanceof DetailsShapeError)return error}catch{}return new DetailsShapeError("unsupported_value","details")}function admitPmCliErrorDetails(value){const byteLimit=PM_CLI_ERROR_DETAILS_LIMITS.max_bytes,budget={bytes:0};try{if(!isPlainObject(value))throw new DetailsShapeError("not_plain_object","details");return{ok:!0,details:copyDetailObject(value,"details",0,budget),byte_length:budget.bytes}}catch(error){const refusal=classifyAdmissionFault(error);return{ok:!1,omission:refusal.reason==="byte_limit"?{reason:"byte_limit",byte_limit:byteLimit}:{reason:refusal.reason,path:boundPath(refusal.path),byte_limit:byteLimit}}}}function isPmCliErrorDetails(value){return admitPmCliErrorDetails(value).ok}function projectPmCliErrorDetails(value){if(value===void 0)return;const admission=admitPmCliErrorDetails(value);return admission.ok?{details:admission.details}:{details_omitted:admission.omission}}function unsupportedDetailsReceipt(){return{reason:"unsupported_value",path:"details",byte_limit:PM_CLI_ERROR_DETAILS_LIMITS.max_bytes}}function ownDataValue(container,key){const descriptor=Object.getOwnPropertyDescriptor(container,key);return descriptor!==void 0&&"value"in descriptor?descriptor.value:void 0}function readRecordedOmission(value){if(!isPlainObject(value))return;const reason=ownDataValue(value,"reason");if(typeof reason!="string"||!DETAILS_REJECTIONS.has(reason))return;const recordedPath=ownDataValue(value,"path"),path=typeof recordedPath=="string"?boundPath(recordedPath):void 0;return{reason,...path===void 0?{}:{path},byte_limit:PM_CLI_ERROR_DETAILS_LIMITS.max_bytes}}function snapshotPmCliErrorContext(context){const snapshot={};try{if(typeof context!="object"||context===null||Array.isArray(context))return snapshot;for(const[key,descriptor]of Object.entries(Object.getOwnPropertyDescriptors(context)))descriptor.enumerable&&("value"in descriptor?Object.defineProperty(snapshot,key,{value:descriptor.value,enumerable:!0,writable:!0,configurable:!0}):key==="details"&&(snapshot.details_omitted=unsupportedDetailsReceipt()));return snapshot}catch{return{}}}function projectPmCliErrorContextDetailsSlot(context){if(!(typeof context!="object"||context===null))try{const descriptor=Object.getOwnPropertyDescriptor(context,"details");if(descriptor!==void 0&&!("value"in descriptor))return{details_omitted:unsupportedDetailsReceipt()};if(descriptor!==void 0&&descriptor.value!==void 0)return projectPmCliErrorDetails(descriptor.value);const recorded=Object.getOwnPropertyDescriptor(context,"details_omitted"),omission=recorded!==void 0&&"value"in recorded?readRecordedOmission(recorded.value):void 0;return omission===void 0?void 0:{details_omitted:omission}}catch{return{details_omitted:unsupportedDetailsReceipt()}}}const DIAGNOSTIC_KEYS=new Set(["details","details_omitted"]);function contextWithoutDiagnostics(context){const rest={};for(const key of Object.keys(context)){if(DIAGNOSTIC_KEYS.has(key)||key==="toJSON")continue;const descriptor=Object.getOwnPropertyDescriptor(context,key);descriptor!==void 0&&"value"in descriptor&&Object.defineProperty(rest,key,{value:descriptor.value,enumerable:!0,writable:!0,configurable:!0})}return rest}function projectPmCliErrorContextDetails(context){if(typeof context!="object"||context===null)return context;try{return Array.isArray(context)?context:{...contextWithoutDiagnostics(context),...projectPmCliErrorContextDetailsSlot(context)}}catch{return{details_omitted:unsupportedDetailsReceipt()}}}function omitPmCliErrorDetails(context){if(typeof context!="object"||context===null)return context;try{return Array.isArray(context)?context:contextWithoutDiagnostics(context)}catch{return{}}}function crashReportErrorContext(context){const safe={};for(const[key,value]of Object.entries(snapshotPmCliErrorContext(context)))DIAGNOSTIC_KEYS.has(key)||key==="toJSON"||(value===null||typeof value=="string"||typeof value=="number"||typeof value=="boolean")&&Object.defineProperty(safe,key,{value,enumerable:!0,writable:!0,configurable:!0});return safe}const MAX_EMBEDDED_CONTEXT_DEPTH=12,EMBEDDED_CONTEXT_KEYS=new Set(["context","error_context"]),SERIALIZED_ARGUMENT_KEYS=new Set(["arguments"]);function omitEmbeddedPmCliErrorDetails(payload){const seen=new WeakSet,visit=(value,depth)=>{if(typeof value!="object"||value===null||depth>MAX_EMBEDDED_CONTEXT_DEPTH||seen.has(value))return;seen.add(value);const record=value;let keys;try{keys=Object.keys(record)}catch{return}for(const key of keys){const descriptor=Object.getOwnPropertyDescriptor(record,key);if(descriptor===void 0||!("value"in descriptor))continue;const entry=descriptor.value,scrubbed=EMBEDDED_CONTEXT_KEYS.has(key)?{}:SERIALIZED_ARGUMENT_KEYS.has(key)?[]:entry;scrubbed!==entry&&(record[key]=scrubbed),visit(scrubbed,depth+1)}};visit(payload,0)}export{PM_CLI_ERROR_DETAILS_LIMITS,admitPmCliErrorDetails,crashReportErrorContext,isPmCliErrorDetails,omitEmbeddedPmCliErrorDetails,omitPmCliErrorDetails,projectPmCliErrorContextDetails,projectPmCliErrorContextDetailsSlot,projectPmCliErrorDetails,snapshotPmCliErrorContext};
2
+ //# sourceMappingURL=error-details.js.map
@@ -91,6 +91,30 @@ reason:string;
91
91
  /** Value that configures or reports next best command for this contract. */
92
92
  next_best_command?:string;
93
93
  }
94
+ /** One JSON value inside producer-owned error diagnostics. */
95
+ export type PmCliErrorDetailValue = null | boolean | number | string | PmCliErrorDetailValue[] | {
96
+ [key:string]:PmCliErrorDetailValue;
97
+ };
98
+ /**
99
+ * Producer-owned structured diagnostics for an expected error (GH-1631). The
100
+ * host renders them as-is in structured error output, bounded by
101
+ * `PM_CLI_ERROR_DETAILS_LIMITS`, and never sends them to telemetry or crash
102
+ * reporting.
103
+ */
104
+ export type PmCliErrorDetails = {
105
+ [key:string]:PmCliErrorDetailValue;
106
+ };
107
+ /** Why a producer's diagnostics could not be rendered. */
108
+ export type PmCliErrorDetailsRejection = "not_plain_object" | "unsupported_value" | "non_finite_number" | "malformed_unicode" | "reserved_key" | "depth_limit" | "byte_limit" | "diagnostic_budget";
109
+ /** Host-set receipt that replaces diagnostics the host could not render. */
110
+ export interface PmCliErrorDetailsOmission {
111
+ /** Stable reason the diagnostics were withheld. */
112
+ reason:PmCliErrorDetailsRejection;
113
+ /** Bounded JSON path of the first offending value, when the shape was refused. */
114
+ path?:string;
115
+ /** Byte ceiling that applied. */
116
+ byte_limit:number;
117
+ }
94
118
  /** Documents the pm cli error context payload exchanged by command, SDK, and package integrations. */
95
119
  export interface PmCliErrorContext {
96
120
  /** Durable writes completed before refusal; paths are relative to the selected tracker. */
@@ -299,8 +323,27 @@ created_at:string;
299
323
  /** Stale-lock lifetime of the current lock generation. */
300
324
  ttl_seconds:number;
301
325
  } | null;
326
+ /** Tracker-relative lock path component that a refused `lock_path_unsafe` acquisition could not prove confined. */
327
+ lock_component?:string;
328
+ /** Revision a refused compare-and-set write expected, or null when it required absence. */
329
+ expected_revision?:string | null;
330
+ /** Revision found at a refused compare-and-set write, or null when the target was absent. */
331
+ current_revision?:string | null;
302
332
  /** Value that configures or reports recovery for this contract. */
303
333
  recovery?:PmCliErrorRecoveryPayload;
334
+ /**
335
+ * Producer-owned structured diagnostics: plain JSON the host renders whole
336
+ * in `--json`, text and MCP error output when it fits the declared ceiling,
337
+ * and otherwise replaces with a `details_omitted` receipt. Never sent to
338
+ * telemetry or crash reporting.
339
+ */
340
+ details?:PmCliErrorDetails;
341
+ /**
342
+ * Host-set receipt recorded instead of `details` when they could not be
343
+ * admitted (for example oversized at construction). Producers set `details`;
344
+ * the host owns this field and never sends it to telemetry or crash reporting.
345
+ */
346
+ details_omitted?:PmCliErrorDetailsOmission;
304
347
  }
305
348
  /** Implements the exported pm cli error runtime abstraction for core/shared/errors.ts. */
306
349
  export declare class PmCliError extends Error {
@@ -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]="277cefd2-1da3-55f6-aa07-9f0d34d02314")}catch{}})();class PmCliError extends Error{exitCode;code;context;constructor(message,exitCode,context={}){super(message),this.name="PmCliError",this.exitCode=exitCode,this.context=context,this.code=context.code}}export{PmCliError};
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]="9896afd0-b833-5b30-b047-4881891d3976")}catch{}})();class PmCliError extends Error{exitCode;code;context;constructor(message,exitCode,context={}){super(message),this.name="PmCliError",this.exitCode=exitCode,this.context=context,this.code=context.code}}export{PmCliError};
2
2
  //# sourceMappingURL=errors.js.map
@@ -0,0 +1,61 @@
1
+ /** Validate and normalize a stored section value; throw to refuse it. */
2
+ export type SettingsSectionValidator<T> = (raw:unknown) => T;
3
+ /** Options for reading one extension-owned settings section. */
4
+ export interface ReadSettingsSectionOptions<T> {
5
+ /** Validate the stored value; a throw becomes a typed `settings_section_invalid` refusal. */
6
+ validate?:SettingsSectionValidator<T>;
7
+ /** Value returned, unvalidated, when the section is absent. */
8
+ defaultValue?:T;
9
+ }
10
+ /** One extension-owned settings section as the host resolved it. */
11
+ export interface SettingsSectionReadResult<T> {
12
+ /** Top-level settings key that holds the section. */
13
+ section:string;
14
+ /** `stored` when settings.json holds the section, `default` when it is absent. */
15
+ source:"stored" | "default";
16
+ /** Validated stored value, or the default (undefined when none was given). */
17
+ value:T | undefined;
18
+ /** Content revision of the stored section (`sha256:<hex>`), or null when absent. */
19
+ revision:string | null;
20
+ }
21
+ /** Options for a revision-safe write of one extension-owned settings section. */
22
+ export interface WriteSettingsSectionOptions<T> {
23
+ /** Refuse unless the stored section still has this revision; null requires it to be absent. */
24
+ expectedRevision?:string | null;
25
+ /** Validate and normalize the value before it is stored. */
26
+ validate?:SettingsSectionValidator<T>;
27
+ /**
28
+ * Mutation author for the history event; omitted, the workspace default and
29
+ * detected identity apply. The host-bound `context.sdk` writer passes the
30
+ * invocation author.
31
+ */
32
+ author?:string;
33
+ }
34
+ /** Receipt of a settings-section write. */
35
+ export interface SettingsSectionWriteResult {
36
+ /** Top-level settings key that holds the section. */
37
+ section:string;
38
+ /** Whether settings.json changed. */
39
+ changed:boolean;
40
+ /** Revision before the write, or null when the section was absent. */
41
+ previous_revision:string | null;
42
+ /** Revision after the write, or null when the section was removed. */
43
+ revision:string | null;
44
+ }
45
+ /** Content revision of a stored section value. */
46
+ export declare function settingsSectionRevision(value:unknown):string;
47
+ /**
48
+ * Read one extension-owned top-level section of the tracker's settings through
49
+ * the host. Absent sections resolve to the default; malformed documents and
50
+ * values the validator refuses become typed refusals instead of thrown parse
51
+ * errors.
52
+ */
53
+ export declare function readSettingsSection<T = unknown>(pmRoot:string,section:string,options?:ReadSettingsSectionOptions<T>):Promise<SettingsSectionReadResult<T>>;
54
+ /**
55
+ * Replace (or, with `undefined`, remove) one extension-owned settings section
56
+ * under the workspace-history lock. Every other key of settings.json is kept
57
+ * byte-for-byte in value. `expectedRevision` makes the write compare-and-set:
58
+ * a section changed since it was read refuses with
59
+ * `settings_section_revision_conflict` and nothing is written.
60
+ */
61
+ export declare function writeSettingsSection<T>(pmRoot:string,section:string,value:T | undefined,options?:WriteSettingsSectionOptions<T>):Promise<SettingsSectionWriteResult>;
@@ -0,0 +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]="7cbbb50d-e9bc-5940-9ae6-6270e9c2fcbf")}catch{}})();import{createHash}from"node:crypto";import{readFileIfExists}from"../fs/fs-utils.js";import{runActiveOnReadHooks,runActiveOnWriteHooks}from"../extensions/index.js";import{mutateWorkspaceJsonWithHistory}from"../history/workspace-history.js";import{resolveAuthor}from"../shared/author.js";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{toErrorMessage}from"../shared/primitives.js";import{stableValueEquals}from"../shared/serialization.js";import{getSettingsPath}from"./paths.js";import{readSettings}from"./settings.js";import{clearSettingsReadCache}from"./settings-read-cache.js";import{CORE_SETTINGS_SECTION_KEYS}from"./settings-validator.js";const SETTINGS_SECTION_NAME_PATTERN=/^[a-z][a-z0-9_-]{0,63}$/u,RESERVED_SECTION_NAMES=new Set(["constructor","prototype"]),SETTINGS_SECTION_WRITE_OP="settings:section:write",MAX_VALIDATION_MESSAGE_LENGTH=240;function settingsSectionRevision(value){return`sha256:${createHash("sha256").update(canonicalSectionJson(value)).digest("hex")}`}function canonicalSectionJson(value){return Array.isArray(value)?`[${value.map(entry=>canonicalSectionJson(entry)).join(",")}]`:typeof value=="object"&&value!==null?`{${Object.keys(value).sort().map(key=>`${JSON.stringify(key)}:${canonicalSectionJson(Object.getOwnPropertyDescriptor(value,key)?.value)}`).join(",")}}`:String(JSON.stringify(value))}function assertSettingsSectionName(section){if(!SETTINGS_SECTION_NAME_PATTERN.test(section)||RESERVED_SECTION_NAMES.has(section))throw new PmCliError(`Invalid settings section name "${section.slice(0,80)}". Use 1-64 lowercase letters, digits, underscores or hyphens, starting with a letter.`,EXIT_CODE.USAGE,{code:"settings_section_name_invalid",field:"section",required:"Name the section after the package, for example lint or jev."});if(CORE_SETTINGS_SECTION_KEYS.includes(section))throw new PmCliError(`Settings section "${section}" is owned by core settings; extension sections must use another name.`,EXIT_CODE.USAGE,{code:"settings_section_reserved",field:"section",value:section,required:"Read core settings with readSettings and change them with writeSettings or pm config."})}function parseSettingsDocument(raw){let parsed;try{parsed=JSON.parse(raw)}catch{parsed=void 0}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))throw new PmCliError("settings.json is not a JSON object, so no settings section can be read or written.",EXIT_CODE.USAGE,{code:"settings_section_document_malformed",reason:parsed===void 0?"settings_json_malformed":"settings_json_not_object",nextSteps:["Repair .agents/pm/settings.json so it is a JSON object, then retry.","Run pm health to confirm the settings warning has cleared."]});return parsed}function validateSectionValue(section,raw,validate){let value;try{value=validate===void 0?raw:validate(raw)}catch(error){throw new PmCliError(`Settings section "${section}" is invalid: ${toErrorMessage(error).slice(0,MAX_VALIDATION_MESSAGE_LENGTH)}`,EXIT_CODE.USAGE,{code:"settings_section_invalid",field:section,required:`Fix the "${section}" section of .agents/pm/settings.json so the owning package accepts it, then retry.`})}return value}function hasJsonHook(value){return typeof Reflect.get(value,"toJSON")=="function"}function describeJsonPath(segments){return segments.length===0?"the value":segments.join(".")}function hasOnlyDataProperties(value,requireEnumerable){return Object.values(Object.getOwnPropertyDescriptors(value)).every(descriptor=>"value"in descriptor&&(!requireEnumerable||descriptor.enumerable===!0))}function isPlainJsonArray(value){if(Object.getPrototypeOf(value)!==Array.prototype||!hasOnlyDataProperties(value,!1))return!1;const keys=Object.keys(value);return keys.length===value.length&&keys.every((key,index)=>key===String(index))&&Object.getOwnPropertyNames(value).length===value.length+1&&Object.getOwnPropertySymbols(value).length===0&&!hasJsonHook(value)}function isPlainJsonObject(value){const prototype=Object.getPrototypeOf(value);return(prototype===Object.prototype||prototype===null)&&hasOnlyDataProperties(value,!0)&&Object.getOwnPropertySymbols(value).length===0&&!hasJsonHook(value)}function findScalarDrift(value,segments){if(value===null||typeof value=="string"||typeof value=="boolean")return null;const where=describeJsonPath(segments);return typeof value=="number"?Number.isFinite(value)?null:{detail:`${where} is a non-finite number`,representable:!0}:{detail:`${where} is ${typeof value}`,representable:typeof value!="bigint"&&segments.length>0}}function findJsonDrift(value,segments=[],ancestors=new Set){if(typeof value!="object"||value===null)return findScalarDrift(value,segments);const where=describeJsonPath(segments);if(ancestors.has(value))return{detail:`${where} is a circular reference`,representable:!1};if(!(Array.isArray(value)?isPlainJsonArray(value):isPlainJsonObject(value)))return{detail:`${where} is not a plain JSON ${Array.isArray(value)?"array":"object"}`,representable:!0};ancestors.add(value);for(const[key,entry]of Object.entries(value)){const drift=findJsonDrift(entry,[...segments,key],ancestors);if(drift!==null)return drift}return ancestors.delete(value),null}function findReservedJsonKey(value,segments=[]){if(typeof value!="object"||value===null)return null;for(const[key,entry]of Object.entries(value)){const keyPath=[...segments,key];if(key==="__proto__"||key==="prototype"&&segments.at(-1)==="constructor")return describeJsonPath(keyPath);const nested=findReservedJsonKey(entry,keyPath);if(nested!==null)return nested}return null}function refuseSectionValue(section,value,reason){return validateSectionValue(section,value,()=>{throw new Error(reason)})}function toStoredSectionValue(section,value){const drift=findJsonDrift(value);if(drift!==null){const reason=drift.representable?`the value would change when stored as JSON: ${drift.detail}`:`the value is not representable as JSON: ${drift.detail}`;return refuseSectionValue(section,value,reason)}const reserved=findReservedJsonKey(value);return reserved!==null?refuseSectionValue(section,value,`${reserved} is a reserved key that settings history cannot record`):JSON.parse(JSON.stringify(value))}function readSectionEntry(document,section){return Object.hasOwn(document,section)?document[section]:void 0}async function readSettingsSection(pmRoot,section,options={}){assertSettingsSectionName(section);const settingsPath=getSettingsPath(pmRoot);await runActiveOnReadHooks({path:settingsPath,scope:"project"});const raw=await readFileIfExists(settingsPath),stored=raw===null?void 0:readSectionEntry(parseSettingsDocument(raw),section);if(stored===void 0)return{section,source:"default",value:options.defaultValue,revision:null};const revision=settingsSectionRevision(stored);return{section,source:"stored",value:validateSectionValue(section,structuredClone(stored),options.validate),revision}}async function writeSettingsSection(pmRoot,section,value,options={}){assertSettingsSectionName(section);const next=value===void 0?void 0:toStoredSectionValue(section,validateSectionValue(section,value,options.validate)),settingsPath=getSettingsPath(pmRoot),settings=await readSettings(pmRoot);try{const mutation=await mutateWorkspaceJsonWithHistory({pmRoot,filePath:settingsPath,op:SETTINGS_SECTION_WRITE_OP,author:resolveAuthor(options.author,settings.author_default),lockTtlSeconds:settings.locks.ttl_seconds,lockWaitMs:settings.locks.wait_ms,recordCreation:!1,mutate:beforeRaw=>{if(beforeRaw===null)throw new PmCliError("settings.json does not exist, so no settings section can be written.",EXIT_CODE.NOT_FOUND,{code:"settings_section_document_missing",required:"Initialize the tracker with pm init, then retry."});const document=parseSettingsDocument(beforeRaw),current=readSectionEntry(document,section),previousRevision=current===void 0?null:settingsSectionRevision(current);if(options.expectedRevision!==void 0&&options.expectedRevision!==previousRevision)throw new PmCliError(`Settings section "${section}" changed since it was read; read it again and reapply the change.`,EXIT_CODE.CONFLICT,{code:"settings_section_revision_conflict",field:section,expected_revision:options.expectedRevision,current_revision:previousRevision,required:"Read the section again with readSettingsSection, then retry with its current revision."});const receipt={section,changed:!1,previous_revision:previousRevision,revision:next===void 0?null:settingsSectionRevision(next)};return stableValueEquals(current,next)?{raw:beforeRaw,result:receipt}:(next===void 0?delete document[section]:document[section]=next,{raw:`${JSON.stringify(document,null,2)}
2
+ `,result:{...receipt,changed:!0}})}});return mutation.changed&&await runActiveOnWriteHooks({path:settingsPath,scope:"project",op:SETTINGS_SECTION_WRITE_OP}),mutation.result}finally{clearSettingsReadCache(pmRoot)}}export{readSettingsSection,settingsSectionRevision,writeSettingsSection};
3
+ //# sourceMappingURL=settings-sections.js.map
@@ -172,6 +172,10 @@ success:true;
172
172
  data:ParsedSettings;
173
173
  } | {
174
174
  success:false;
175
+ /** Dotted path of the first invalid setting; empty when the document root is not an object. */
176
+ path:string;
175
177
  };
178
+ /** Top-level settings keys owned and validated by core; extension sections must use other names. */
179
+ export declare const CORE_SETTINGS_SECTION_KEYS:readonly string[];
176
180
  /** Validate raw settings, returning stripped, type-checked data or failure (matching the legacy zod safeParse). */
177
181
  export declare function validateSettings(raw:unknown):SettingsValidationResult;
@@ -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]="405e7bd1-25c0-5e04-b313-d9871efce4f5")}catch{}})();import{GOVERNANCE_PRESET_VALUES,RUNTIME_FIELD_COMMAND_VALUES,RUNTIME_FIELD_TYPE_VALUES,RUNTIME_STATUS_ROLE_VALUES,RUNTIME_UNKNOWN_FIELD_POLICY_VALUES}from"../../types.js";const FAIL={ok:!1},vString=input=>typeof input=="string"?{ok:!0,value:input}:FAIL,vBoolean=input=>typeof input=="boolean"?{ok:!0,value:input}:FAIL;function vNumber(options={}){return input=>typeof input!="number"||!Number.isFinite(input)||options.int&&(!Number.isInteger(input)||!Number.isSafeInteger(input))||options.positive&&input<=0||typeof options.min=="number"&&input<options.min||typeof options.max=="number"&&input>options.max?FAIL:{ok:!0,value:input}}function vLiteral(...allowed){return input=>typeof input=="string"&&allowed.includes(input)?{ok:!0,value:input}:FAIL}function vArray(item,maxLength){return input=>{if(!Array.isArray(input)||maxLength!==void 0&&input.length>maxLength)return FAIL;const value=[];for(const element of input){const result=item(element);if(!result.ok)return FAIL;value.push(result.value)}return{ok:!0,value}}}function vBoundedNormalizedString(maxLength,pattern){return input=>typeof input=="string"&&input.length>0&&input.length<=maxLength&&input===input.trim()&&(pattern===void 0||pattern.test(input))?{ok:!0,value:input}:FAIL}function vOptional(inner){return input=>input===void 0?{ok:!0,value:void 0}:inner(input)}function vRecordOf(valueCheck){return input=>{if(typeof input!="object"||input===null||Array.isArray(input))return FAIL;const value={};for(const[key,raw]of Object.entries(input)){const result=valueCheck(raw);if(!result.ok)return FAIL;value[key]=result.value}return{ok:!0,value}}}function vObject(shape){return input=>{if(typeof input!="object"||input===null||Array.isArray(input))return FAIL;const record=input,value={};for(const[key,check]of Object.entries(shape)){const result=check(record[key]);if(!result.ok)return FAIL;result.value!==void 0&&(value[key]=result.value)}return{ok:!0,value}}}const itemTypeOption=vObject({key:vString,values:vArray(vString),required:vOptional(vBoolean),aliases:vOptional(vArray(vString)),description:vOptional(vString)}),itemTypeCommandOptionPolicy=vObject({command:vLiteral("create","update"),option:vString,required:vOptional(vBoolean),visible:vOptional(vBoolean),enabled:vOptional(vBoolean)}),itemTypeDefinition=vObject({name:vString,description:vOptional(vString),default_status:vOptional(vString),execution_role:vOptional(vLiteral("agent","human","gate")),folder:vOptional(vString),aliases:vOptional(vArray(vString)),required_create_fields:vOptional(vArray(vString)),required_create_repeatables:vOptional(vArray(vString)),options:vOptional(vArray(itemTypeOption)),command_option_policies:vOptional(vArray(itemTypeCommandOptionPolicy))}),runtimeStatusDefinition=vObject({id:vString,aliases:vOptional(vArray(vString)),roles:vOptional(vArray(vLiteral(...RUNTIME_STATUS_ROLE_VALUES))),description:vOptional(vString),order:vOptional(vNumber())}),runtimeFieldDefinition=vObject({key:vString,metadata_key:vOptional(vString),front_matter_key:vOptional(vString),cli_flag:vOptional(vString),cli_aliases:vOptional(vArray(vString)),description:vOptional(vString),type:vOptional(vLiteral(...RUNTIME_FIELD_TYPE_VALUES)),commands:vOptional(vArray(vLiteral(...RUNTIME_FIELD_COMMAND_VALUES))),repeatable:vOptional(vBoolean),required:vOptional(vBoolean),required_on_create:vOptional(vBoolean),required_types:vOptional(vArray(vString)),allow_unset:vOptional(vBoolean)}),statusTransitionPair=input=>{if(!Array.isArray(input)||input.length!==2)return FAIL;const[from,to]=input;return typeof from!="string"||typeof to!="string"?FAIL:{ok:!0,value:[from,to]}},typeWorkflowDefinition=vObject({type:vString,allowed_transitions:vArray(statusTransitionPair)}),runtimeSchemaSettings=vOptional(vObject({version:vOptional(vNumber({int:!0})),files:vOptional(vObject({types:vOptional(vString),statuses:vOptional(vString),fields:vOptional(vString),workflows:vOptional(vString)})),statuses:vOptional(vArray(runtimeStatusDefinition)),fields:vOptional(vArray(runtimeFieldDefinition)),workflow:vOptional(vObject({draft_status:vOptional(vString),open_status:vOptional(vString),in_progress_status:vOptional(vString),blocked_status:vOptional(vString),close_status:vOptional(vString),canceled_status:vOptional(vString)})),type_workflows:vOptional(vArray(typeWorkflowDefinition)),unknown_field_policy:vOptional(vLiteral(...RUNTIME_UNKNOWN_FIELD_POLICY_VALUES))})),governanceSettings=vOptional(vObject({preset:vOptional(vLiteral(...GOVERNANCE_PRESET_VALUES)),ownership_enforcement:vOptional(vLiteral("none","warn","strict")),create_mode_default:vOptional(vLiteral("progressive","strict")),close_validation_default:vOptional(vLiteral("off","warn","strict")),require_close_reason:vOptional(vBoolean),parent_reference:vOptional(vLiteral("warn","strict_error")),metadata_profile:vOptional(vLiteral("core","strict","custom")),force_required_for_stale_lock:vOptional(vBoolean),create_default_type:vOptional(vString),workflow_enforcement:vOptional(vLiteral("off","warn","strict")),duplicate_detection_mode:vOptional(vLiteral("off","advisory","strict")),duplicate_detection_threshold:vOptional(vNumber({min:0,max:1})),duplicate_detection_limit:vOptional(vNumber({int:!0,min:0,max:20}))})),extensionPolicyOverride=vObject({name:vString,disabled:vOptional(vBoolean),require_trusted:vOptional(vBoolean),require_provenance:vOptional(vBoolean),sandbox_profile:vOptional(vLiteral("none","restricted","strict")),allowed_capabilities:vOptional(vArray(vString)),blocked_capabilities:vOptional(vArray(vString)),allowed_surfaces:vOptional(vArray(vString)),blocked_surfaces:vOptional(vArray(vString)),allowed_commands:vOptional(vArray(vString)),blocked_commands:vOptional(vArray(vString)),allowed_actions:vOptional(vArray(vString)),blocked_actions:vOptional(vArray(vString)),allowed_services:vOptional(vArray(vString)),blocked_services:vOptional(vArray(vString))}),pmMaxVersionExceededModeLiteral=vLiteral("block","warn"),pmMaxVersionExceededMode=input=>typeof input=="string"?pmMaxVersionExceededModeLiteral(input):vObject({global:vOptional(pmMaxVersionExceededModeLiteral),project:vOptional(pmMaxVersionExceededModeLiteral)})(input),extensionPolicy=vOptional(vObject({mode:vOptional(vLiteral("off","warn","enforce")),trust_mode:vOptional(vLiteral("off","warn","enforce")),pm_max_version_exceeded_mode:vOptional(pmMaxVersionExceededMode),require_provenance:vOptional(vBoolean),trusted_extensions:vOptional(vArray(vString)),default_sandbox_profile:vOptional(vLiteral("none","restricted","strict")),allowed_extensions:vOptional(vArray(vString)),blocked_extensions:vOptional(vArray(vString)),allowed_capabilities:vOptional(vArray(vString)),blocked_capabilities:vOptional(vArray(vString)),allowed_surfaces:vOptional(vArray(vString)),blocked_surfaces:vOptional(vArray(vString)),allowed_commands:vOptional(vArray(vString)),blocked_commands:vOptional(vArray(vString)),allowed_actions:vOptional(vArray(vString)),blocked_actions:vOptional(vArray(vString)),allowed_services:vOptional(vArray(vString)),blocked_services:vOptional(vArray(vString)),extension_overrides:vOptional(vArray(extensionPolicyOverride))})),harnessSignalLiteral=vBoundedNormalizedString(128),harnessSignalDescriptor=vObject({harness:vBoundedNormalizedString(128,/^[a-z0-9]+(?:-[a-z0-9]+)*$/u),environment_keys:vOptional(vArray(harnessSignalLiteral,64)),model_environment_keys:vOptional(vArray(harnessSignalLiteral,64)),session_environment_keys:vOptional(vArray(harnessSignalLiteral,64)),provenance_environment_keys:vOptional(vRecordOf(vArray(harnessSignalLiteral,64))),provenance_resolvers:vOptional(vRecordOf(vLiteral("ai_agent_version","claude_session_file"))),provenance_unavailable_dimensions:vOptional(vArray(harnessSignalLiteral,64)),argv_markers:vOptional(vArray(harnessSignalLiteral,64)),client_names:vOptional(vArray(harnessSignalLiteral,64))}),settingsCheck=vObject({version:vNumber({int:!0}),id_prefix:vString,ids:vOptional(vObject({token_length:vOptional(vNumber({int:!0,min:4,max:12}))})),author_default:vString,agent_identity:vOptional(vObject({probes_enabled:vOptional(vBoolean),identity_vocabulary:vOptional(vObject({version:vNumber({int:!0,positive:!0}),aliases:vRecordOf(vBoundedNormalizedString(128,/^[a-z0-9]+(?:-[a-z0-9]+)*$/u))})),harness_signals:vArray(harnessSignalDescriptor)})),mutation_guard:vOptional(vObject({require_attributed_author:vOptional(vBoolean),secret_guard:vOptional(vLiteral("off","advise","block")),stale_in_progress_hours:vOptional(vNumber({int:!0,positive:!0}))})),item_format:vOptional(vLiteral("toon","json_markdown")),locks:vObject({ttl_seconds:vNumber({int:!0}),wait_ms:vOptional(vNumber({int:!0,min:0}))}),checkpoints:vOptional(vObject({retention_days:vOptional(vNumber({int:!0,positive:!0}))})),output:vObject({default_format:vLiteral("toon","json")}),ux:vOptional(vObject({deprecation_hints:vOptional(vBoolean)})),history:vOptional(vObject({missing_stream:vLiteral("auto_create","strict_error"),compact_policy:vOptional(vObject({enabled:vOptional(vBoolean),max_entries:vOptional(vNumber({int:!0,positive:!0})),trigger:vOptional(vLiteral("health_warn","auto"))}))})),validation:vOptional(vObject({sprint_release_format:vLiteral("warn","strict_error"),parent_reference:vOptional(vLiteral("warn","strict_error")),metadata_profile:vOptional(vLiteral("core","strict","custom")),metadata_required_fields:vOptional(vArray(vString)),lifecycle_stale_blocker_reason_patterns:vOptional(vArray(vString)),lifecycle_closure_like_blocked_reason_patterns:vOptional(vArray(vString)),lifecycle_closure_like_resolution_patterns:vOptional(vArray(vString)),lifecycle_closure_like_actual_result_patterns:vOptional(vArray(vString)),estimate_defaults_by_type:vOptional(vRecordOf(vNumber({int:!0,positive:!0})))})),governance:governanceSettings,workflow:vOptional(vObject({definition_of_done:vArray(vString)})),testing:vOptional(vObject({record_results_to_items:vBoolean,allow_untrusted_linked_tests:vOptional(vBoolean)})),telemetry:vOptional(vObject({enabled:vBoolean,first_run_prompt_completed:vOptional(vBoolean),capture_level:vOptional(vLiteral("minimal","redacted","max")),endpoint:vOptional(vString),installation_id:vOptional(vString),retention_days:vOptional(vNumber({int:!0,positive:!0}))})),agent_guidance:vOptional(vObject({prompt_completed:vOptional(vBoolean),declined:vOptional(vBoolean),declined_at:vOptional(vString),template_version:vOptional(vNumber({int:!0,positive:!0})),last_checked_files:vOptional(vArray(vString))})),item_types:vOptional(vObject({definitions:vArray(itemTypeDefinition)})),schema:runtimeSchemaSettings,context:vOptional(vObject({default_depth:vOptional(vLiteral("brief","standard","deep")),activity_limit:vOptional(vNumber({int:!0,positive:!0})),stale_threshold_days:vOptional(vNumber({int:!0,positive:!0})),next_ranking_policy:vOptional(vLiteral("priority_floor","weighted")),sections:vOptional(vObject({hierarchy:vOptional(vBoolean),activity:vOptional(vBoolean),progress:vOptional(vBoolean),recently_created:vOptional(vBoolean),unparented:vOptional(vBoolean),blockers:vOptional(vBoolean),files:vOptional(vBoolean),workload:vOptional(vBoolean),staleness:vOptional(vBoolean),tests:vOptional(vBoolean)}))})),extensions:vObject({enabled:vArray(vString),disabled:vArray(vString),policy:extensionPolicy}),search:vObject({score_threshold:vNumber(),hybrid_semantic_weight:vOptional(vNumber()),max_results:vNumber({int:!0}),embedding_model:vString,embedding_corpus_max_characters:vOptional(vNumber()),embedding_batch_size:vNumber({int:!0}),embedding_timeout_ms:vOptional(vNumber({int:!0})),scanner_max_batch_retries:vNumber({int:!0}),provider:vOptional(vString),default_mode:vOptional(vLiteral("auto","keyword","semantic","hybrid")),corpus_fields:vOptional(vArray(vString)),mutation_refresh_policy:vOptional(vLiteral("cache_only","semantic_configured","semantic_auto")),query_expansion:vOptional(vObject({enabled:vOptional(vBoolean),provider:vOptional(vString)})),rerank:vOptional(vObject({enabled:vOptional(vBoolean),model:vOptional(vString),top_k:vOptional(vNumber({int:!0,positive:!0}))})),bm25:vOptional(vObject({k1:vOptional(vNumber()),b:vOptional(vNumber())}))}),providers:vObject({openai:vObject({base_url:vString,api_key:vString,model:vString}),ollama:vObject({base_url:vString,model:vString})}),vector_store:vObject({adapter:vOptional(vString),collection_name:vOptional(vString),qdrant:vObject({url:vString,api_key:vString}),lancedb:vObject({path:vString})})});function validateSettings(raw){const result=settingsCheck(raw);return result.ok?{success:!0,data:result.value}:{success:!1}}export{validateSettings};
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]="c7f9d249-e2c2-5edd-afbd-b14ac1c12e81")}catch{}})();import{GOVERNANCE_PRESET_VALUES,RUNTIME_FIELD_COMMAND_VALUES,RUNTIME_FIELD_TYPE_VALUES,RUNTIME_STATUS_ROLE_VALUES,RUNTIME_UNKNOWN_FIELD_POLICY_VALUES}from"../../types.js";const FAIL={ok:!1,path:[]};function failAt(segment,failure){return{ok:!1,path:[segment,...failure.path]}}const vString=input=>typeof input=="string"?{ok:!0,value:input}:FAIL,vBoolean=input=>typeof input=="boolean"?{ok:!0,value:input}:FAIL;function vNumber(options={}){return input=>typeof input!="number"||!Number.isFinite(input)||options.int&&(!Number.isInteger(input)||!Number.isSafeInteger(input))||options.positive&&input<=0||typeof options.min=="number"&&input<options.min||typeof options.max=="number"&&input>options.max?FAIL:{ok:!0,value:input}}function vLiteral(...allowed){return input=>typeof input=="string"&&allowed.includes(input)?{ok:!0,value:input}:FAIL}function vArray(item,maxLength){return input=>{if(!Array.isArray(input)||maxLength!==void 0&&input.length>maxLength)return FAIL;const value=[];for(const[index,element]of input.entries()){const result=item(element);if(!result.ok)return failAt(String(index),result);value.push(result.value)}return{ok:!0,value}}}function vBoundedNormalizedString(maxLength,pattern){return input=>typeof input=="string"&&input.length>0&&input.length<=maxLength&&input===input.trim()&&(pattern===void 0||pattern.test(input))?{ok:!0,value:input}:FAIL}function vOptional(inner){return input=>input===void 0?{ok:!0,value:void 0}:inner(input)}function vRecordOf(valueCheck){return input=>{if(typeof input!="object"||input===null||Array.isArray(input))return FAIL;const value={};for(const[key,raw]of Object.entries(input)){const result=valueCheck(raw);if(!result.ok)return failAt(key,result);value[key]=result.value}return{ok:!0,value}}}function vObject(shape){return input=>{if(typeof input!="object"||input===null||Array.isArray(input))return FAIL;const record=input,value={};for(const[key,check]of Object.entries(shape)){const result=check(record[key]);if(!result.ok)return failAt(key,result);result.value!==void 0&&(value[key]=result.value)}return{ok:!0,value}}}const itemTypeOption=vObject({key:vString,values:vArray(vString),required:vOptional(vBoolean),aliases:vOptional(vArray(vString)),description:vOptional(vString)}),itemTypeCommandOptionPolicy=vObject({command:vLiteral("create","update"),option:vString,required:vOptional(vBoolean),visible:vOptional(vBoolean),enabled:vOptional(vBoolean)}),itemTypeDefinition=vObject({name:vString,description:vOptional(vString),default_status:vOptional(vString),execution_role:vOptional(vLiteral("agent","human","gate")),folder:vOptional(vString),aliases:vOptional(vArray(vString)),required_create_fields:vOptional(vArray(vString)),required_create_repeatables:vOptional(vArray(vString)),options:vOptional(vArray(itemTypeOption)),command_option_policies:vOptional(vArray(itemTypeCommandOptionPolicy))}),runtimeStatusDefinition=vObject({id:vString,aliases:vOptional(vArray(vString)),roles:vOptional(vArray(vLiteral(...RUNTIME_STATUS_ROLE_VALUES))),description:vOptional(vString),order:vOptional(vNumber())}),runtimeFieldDefinition=vObject({key:vString,metadata_key:vOptional(vString),front_matter_key:vOptional(vString),cli_flag:vOptional(vString),cli_aliases:vOptional(vArray(vString)),description:vOptional(vString),type:vOptional(vLiteral(...RUNTIME_FIELD_TYPE_VALUES)),commands:vOptional(vArray(vLiteral(...RUNTIME_FIELD_COMMAND_VALUES))),repeatable:vOptional(vBoolean),required:vOptional(vBoolean),required_on_create:vOptional(vBoolean),required_types:vOptional(vArray(vString)),allow_unset:vOptional(vBoolean)}),statusTransitionPair=input=>{if(!Array.isArray(input)||input.length!==2)return FAIL;const[from,to]=input;return typeof from!="string"||typeof to!="string"?FAIL:{ok:!0,value:[from,to]}},typeWorkflowDefinition=vObject({type:vString,allowed_transitions:vArray(statusTransitionPair)}),runtimeSchemaSettings=vOptional(vObject({version:vOptional(vNumber({int:!0})),files:vOptional(vObject({types:vOptional(vString),statuses:vOptional(vString),fields:vOptional(vString),workflows:vOptional(vString)})),statuses:vOptional(vArray(runtimeStatusDefinition)),fields:vOptional(vArray(runtimeFieldDefinition)),workflow:vOptional(vObject({draft_status:vOptional(vString),open_status:vOptional(vString),in_progress_status:vOptional(vString),blocked_status:vOptional(vString),close_status:vOptional(vString),canceled_status:vOptional(vString)})),type_workflows:vOptional(vArray(typeWorkflowDefinition)),unknown_field_policy:vOptional(vLiteral(...RUNTIME_UNKNOWN_FIELD_POLICY_VALUES))})),governanceSettings=vOptional(vObject({preset:vOptional(vLiteral(...GOVERNANCE_PRESET_VALUES)),ownership_enforcement:vOptional(vLiteral("none","warn","strict")),create_mode_default:vOptional(vLiteral("progressive","strict")),close_validation_default:vOptional(vLiteral("off","warn","strict")),require_close_reason:vOptional(vBoolean),parent_reference:vOptional(vLiteral("warn","strict_error")),metadata_profile:vOptional(vLiteral("core","strict","custom")),force_required_for_stale_lock:vOptional(vBoolean),create_default_type:vOptional(vString),workflow_enforcement:vOptional(vLiteral("off","warn","strict")),duplicate_detection_mode:vOptional(vLiteral("off","advisory","strict")),duplicate_detection_threshold:vOptional(vNumber({min:0,max:1})),duplicate_detection_limit:vOptional(vNumber({int:!0,min:0,max:20}))})),extensionPolicyOverride=vObject({name:vString,disabled:vOptional(vBoolean),require_trusted:vOptional(vBoolean),require_provenance:vOptional(vBoolean),sandbox_profile:vOptional(vLiteral("none","restricted","strict")),allowed_capabilities:vOptional(vArray(vString)),blocked_capabilities:vOptional(vArray(vString)),allowed_surfaces:vOptional(vArray(vString)),blocked_surfaces:vOptional(vArray(vString)),allowed_commands:vOptional(vArray(vString)),blocked_commands:vOptional(vArray(vString)),allowed_actions:vOptional(vArray(vString)),blocked_actions:vOptional(vArray(vString)),allowed_services:vOptional(vArray(vString)),blocked_services:vOptional(vArray(vString))}),pmMaxVersionExceededModeLiteral=vLiteral("block","warn"),pmMaxVersionExceededMode=input=>typeof input=="string"?pmMaxVersionExceededModeLiteral(input):vObject({global:vOptional(pmMaxVersionExceededModeLiteral),project:vOptional(pmMaxVersionExceededModeLiteral)})(input),extensionPolicy=vOptional(vObject({mode:vOptional(vLiteral("off","warn","enforce")),trust_mode:vOptional(vLiteral("off","warn","enforce")),pm_max_version_exceeded_mode:vOptional(pmMaxVersionExceededMode),require_provenance:vOptional(vBoolean),trusted_extensions:vOptional(vArray(vString)),default_sandbox_profile:vOptional(vLiteral("none","restricted","strict")),allowed_extensions:vOptional(vArray(vString)),blocked_extensions:vOptional(vArray(vString)),allowed_capabilities:vOptional(vArray(vString)),blocked_capabilities:vOptional(vArray(vString)),allowed_surfaces:vOptional(vArray(vString)),blocked_surfaces:vOptional(vArray(vString)),allowed_commands:vOptional(vArray(vString)),blocked_commands:vOptional(vArray(vString)),allowed_actions:vOptional(vArray(vString)),blocked_actions:vOptional(vArray(vString)),allowed_services:vOptional(vArray(vString)),blocked_services:vOptional(vArray(vString)),extension_overrides:vOptional(vArray(extensionPolicyOverride))})),harnessSignalLiteral=vBoundedNormalizedString(128),harnessSignalDescriptor=vObject({harness:vBoundedNormalizedString(128,/^[a-z0-9]+(?:-[a-z0-9]+)*$/u),environment_keys:vOptional(vArray(harnessSignalLiteral,64)),model_environment_keys:vOptional(vArray(harnessSignalLiteral,64)),session_environment_keys:vOptional(vArray(harnessSignalLiteral,64)),provenance_environment_keys:vOptional(vRecordOf(vArray(harnessSignalLiteral,64))),provenance_resolvers:vOptional(vRecordOf(vLiteral("ai_agent_version","claude_session_file"))),provenance_unavailable_dimensions:vOptional(vArray(harnessSignalLiteral,64)),argv_markers:vOptional(vArray(harnessSignalLiteral,64)),client_names:vOptional(vArray(harnessSignalLiteral,64))}),SETTINGS_SHAPE={version:vNumber({int:!0}),id_prefix:vString,ids:vOptional(vObject({token_length:vOptional(vNumber({int:!0,min:4,max:12}))})),author_default:vString,agent_identity:vOptional(vObject({probes_enabled:vOptional(vBoolean),identity_vocabulary:vOptional(vObject({version:vNumber({int:!0,positive:!0}),aliases:vRecordOf(vBoundedNormalizedString(128,/^[a-z0-9]+(?:-[a-z0-9]+)*$/u))})),harness_signals:vArray(harnessSignalDescriptor)})),mutation_guard:vOptional(vObject({require_attributed_author:vOptional(vBoolean),secret_guard:vOptional(vLiteral("off","advise","block")),stale_in_progress_hours:vOptional(vNumber({int:!0,positive:!0}))})),item_format:vOptional(vLiteral("toon","json_markdown")),locks:vObject({ttl_seconds:vNumber({int:!0}),wait_ms:vOptional(vNumber({int:!0,min:0}))}),checkpoints:vOptional(vObject({retention_days:vOptional(vNumber({int:!0,positive:!0}))})),output:vObject({default_format:vLiteral("toon","json")}),ux:vOptional(vObject({deprecation_hints:vOptional(vBoolean)})),history:vOptional(vObject({missing_stream:vLiteral("auto_create","strict_error"),compact_policy:vOptional(vObject({enabled:vOptional(vBoolean),max_entries:vOptional(vNumber({int:!0,positive:!0})),trigger:vOptional(vLiteral("health_warn","auto"))}))})),validation:vOptional(vObject({sprint_release_format:vLiteral("warn","strict_error"),parent_reference:vOptional(vLiteral("warn","strict_error")),metadata_profile:vOptional(vLiteral("core","strict","custom")),metadata_required_fields:vOptional(vArray(vString)),lifecycle_stale_blocker_reason_patterns:vOptional(vArray(vString)),lifecycle_closure_like_blocked_reason_patterns:vOptional(vArray(vString)),lifecycle_closure_like_resolution_patterns:vOptional(vArray(vString)),lifecycle_closure_like_actual_result_patterns:vOptional(vArray(vString)),estimate_defaults_by_type:vOptional(vRecordOf(vNumber({int:!0,positive:!0})))})),governance:governanceSettings,workflow:vOptional(vObject({definition_of_done:vArray(vString)})),testing:vOptional(vObject({record_results_to_items:vBoolean,allow_untrusted_linked_tests:vOptional(vBoolean)})),telemetry:vOptional(vObject({enabled:vBoolean,first_run_prompt_completed:vOptional(vBoolean),capture_level:vOptional(vLiteral("minimal","redacted","max")),endpoint:vOptional(vString),installation_id:vOptional(vString),retention_days:vOptional(vNumber({int:!0,positive:!0}))})),agent_guidance:vOptional(vObject({prompt_completed:vOptional(vBoolean),declined:vOptional(vBoolean),declined_at:vOptional(vString),template_version:vOptional(vNumber({int:!0,positive:!0})),last_checked_files:vOptional(vArray(vString))})),item_types:vOptional(vObject({definitions:vArray(itemTypeDefinition)})),schema:runtimeSchemaSettings,context:vOptional(vObject({default_depth:vOptional(vLiteral("brief","standard","deep")),activity_limit:vOptional(vNumber({int:!0,positive:!0})),stale_threshold_days:vOptional(vNumber({int:!0,positive:!0})),next_ranking_policy:vOptional(vLiteral("priority_floor","weighted")),sections:vOptional(vObject({hierarchy:vOptional(vBoolean),activity:vOptional(vBoolean),progress:vOptional(vBoolean),recently_created:vOptional(vBoolean),unparented:vOptional(vBoolean),blockers:vOptional(vBoolean),files:vOptional(vBoolean),workload:vOptional(vBoolean),staleness:vOptional(vBoolean),tests:vOptional(vBoolean)}))})),extensions:vObject({enabled:vArray(vString),disabled:vArray(vString),policy:extensionPolicy}),search:vObject({score_threshold:vNumber(),hybrid_semantic_weight:vOptional(vNumber()),max_results:vNumber({int:!0}),embedding_model:vString,embedding_corpus_max_characters:vOptional(vNumber()),embedding_batch_size:vNumber({int:!0}),embedding_timeout_ms:vOptional(vNumber({int:!0})),scanner_max_batch_retries:vNumber({int:!0}),provider:vOptional(vString),default_mode:vOptional(vLiteral("auto","keyword","semantic","hybrid")),corpus_fields:vOptional(vArray(vString)),mutation_refresh_policy:vOptional(vLiteral("cache_only","semantic_configured","semantic_auto")),query_expansion:vOptional(vObject({enabled:vOptional(vBoolean),provider:vOptional(vString)})),rerank:vOptional(vObject({enabled:vOptional(vBoolean),model:vOptional(vString),top_k:vOptional(vNumber({int:!0,positive:!0}))})),bm25:vOptional(vObject({k1:vOptional(vNumber()),b:vOptional(vNumber())}))}),providers:vObject({openai:vObject({base_url:vString,api_key:vString,model:vString}),ollama:vObject({base_url:vString,model:vString})}),vector_store:vObject({adapter:vOptional(vString),collection_name:vOptional(vString),qdrant:vObject({url:vString,api_key:vString}),lancedb:vObject({path:vString})})},settingsCheck=vObject(SETTINGS_SHAPE),CORE_SETTINGS_SECTION_KEYS=Object.freeze(Object.keys(SETTINGS_SHAPE));function validateSettings(raw){const result=settingsCheck(raw);return result.ok?{success:!0,data:result.value}:{success:!1,path:result.path.join(".")}}export{CORE_SETTINGS_SECTION_KEYS,validateSettings};
2
2
  //# sourceMappingURL=settings-validator.js.map
@@ -80,6 +80,12 @@ schema_statuses:PmSettings["schema"]["statuses"];
80
80
  schema_fields:PmSettings["schema"]["fields"];
81
81
  schema_type_workflows:PmSettings["schema"]["type_workflows"];
82
82
  };
83
+ /**
84
+ * Whether these settings are the defaults fallback for a stored document that
85
+ * could not be read. Automatic writers (format pinning, telemetry identity,
86
+ * consent) must skip their write instead of acting on the fallback.
87
+ */
88
+ export declare function isSettingsReadFallback(settings:PmSettings):boolean;
83
89
  declare function hasExplicitItemFormat(raw:unknown):boolean;
84
90
  declare function normalizeStringList(values:string[] | undefined):string[];
85
91
  declare function normalizeLowerStringList(values:string[] | undefined):string[];
@@ -104,15 +110,36 @@ declare function applySettingsDelta(target:Record<string,unknown>,baseline:Recor
104
110
  export declare function serializeSettings(settings:PmSettings,options?:SerializeSettingsOptions):string;
105
111
  /** Implements read settings with metadata for the public runtime surface of this module. */
106
112
  export declare function readSettingsWithMetadata(pmRoot:string):Promise<SettingsReadResult>;
113
+ /** Options for {@link writeSettings}. */
114
+ export interface WriteSettingsOptions {
115
+ /**
116
+ * Dotted settings paths (for example `context.next_ranking_policy`) the
117
+ * caller assigned explicitly. A snapshot cannot tell an assignment equal to
118
+ * the default from an untouched field, so over a defaults fallback returned
119
+ * for an unreadable document these paths are applied even when their value
120
+ * equals the default; that is how an explicit repair to the default value
121
+ * takes effect. A core-section path whose parent the proposed settings carry
122
+ * but whose value they omit (a default-valued optional key or a cleared key)
123
+ * is removed from the stored document; any other path the proposed settings
124
+ * do not carry is left to the delta. A record key that itself contains a dot
125
+ * cannot be addressed;
126
+ * repair such an entry in settings.json. Readable documents ignore the
127
+ * option (pm-4zpq71).
128
+ */
129
+ assignedPaths?:readonly string[];
130
+ }
107
131
  /** Implements read settings for the public runtime surface of this module. */
108
132
  export declare function readSettings(pmRoot:string):Promise<PmSettings>;
109
133
  /**
110
134
  * Persist edits to a readSettings snapshot under the workspace-history lock.
111
135
  * Disjoint concurrent edits survive; overlapping stale edits fail before any
112
136
  * write. Caller-constructed settings without a read snapshot replace the whole
113
- * document. History append failures compensate the document before unlocking.
137
+ * document. A default fallback returned for an unreadable document applies only
138
+ * its own change, plus `options.assignedPaths`, to the stored document and
139
+ * refuses when the result is still schema-invalid. History append failures
140
+ * compensate the document before unlocking.
114
141
  */
115
- export declare function writeSettings(pmRoot:string,settings:PmSettings,op?:string):Promise<void>;
142
+ export declare function writeSettings(pmRoot:string,settings:PmSettings,op?:string,options?:WriteSettingsOptions):Promise<void>;
116
143
  /** Public contract for settings store test only, shared by SDK and presentation-layer consumers. */
117
144
  export declare const settingsStoreTestOnly:{
118
145
  applySettingsDelta:typeof applySettingsDelta;