@unbrained/pm-cli 2026.11.16 → 2026.11.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +1 -1
- package/dist/cli/main.js +2 -2
- package/dist/cli/register-mutation.js +3 -2
- package/dist/cli/runtime/invocation-rewrites.js +2 -0
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/{chunk-ERD2RYWM.js → chunk-2WHXFKMY.js} +31 -31
- package/dist/cli-bundle/chunks/{chunk-VJLZHOTP.js → chunk-36R3JTAD.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-FZ4XWWLO.js → chunk-3IU2S5UQ.js} +43 -43
- package/dist/cli-bundle/chunks/chunk-4FIN2XWC.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-NHNM3GIP.js → chunk-5OFMWP3Q.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-2WNORBVN.js → chunk-77MGDTK4.js} +83 -83
- package/dist/cli-bundle/chunks/{chunk-F7P42FL5.js → chunk-7K2RUKMK.js} +4 -4
- package/dist/cli-bundle/chunks/chunk-7UUPLMCU.js +115 -0
- package/dist/cli-bundle/chunks/chunk-ABFHWRLE.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-KGOGLKL2.js → chunk-ACLBUVQG.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-DZWRNL6R.js → chunk-ADKDFCVT.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-AM26RAG7.js +124 -0
- package/dist/cli-bundle/chunks/chunk-CR5GC3VO.js +9 -0
- package/dist/cli-bundle/chunks/chunk-DXSZL3T6.js +3 -0
- package/dist/cli-bundle/chunks/chunk-FXSLODOK.js +2 -0
- package/dist/cli-bundle/chunks/chunk-H64BNM4A.js +8 -0
- package/dist/cli-bundle/chunks/{chunk-2D26HRXB.js → chunk-HQYIKAC6.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-I3T2FVUA.js → chunk-KIQNEOKJ.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-O4ZSIMNC.js +8 -0
- package/dist/cli-bundle/chunks/chunk-QANUQMDL.js +6 -0
- package/dist/cli-bundle/chunks/{chunk-4I7YG3VZ.js → chunk-QZNL5XDT.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-RXNBNF6O.js +2 -0
- package/dist/cli-bundle/chunks/chunk-VLKCFZY6.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-J257NZRD.js → chunk-X5TFNFTS.js} +11 -11
- package/dist/cli-bundle/chunks/chunk-XP35IEHT.js +2 -0
- package/dist/cli-bundle/chunks/chunk-XPBADEUK.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-NYN5OR2T.js → chunk-Y4LXVPA5.js} +2 -2
- package/dist/cli-bundle/chunks/{indexed-receipt-blobs-HNLN6UXH.js → indexed-receipt-blobs-ELEMA7IW.js} +2 -2
- package/dist/cli-bundle/chunks/{item-revision-PSOL5I4H.js → item-revision-7RVMVXTE.js} +2 -2
- package/dist/cli-bundle/chunks/item-transaction-NVX6P3FK.js +2 -0
- package/dist/cli-bundle/chunks/{mutation-actor-BDBBH3ZS.js → mutation-actor-DDYJW5B4.js} +2 -2
- package/dist/cli-bundle/chunks/mutation-admission-3PKQOAYK.js +2 -0
- package/dist/cli-bundle/chunks/{register-list-query-AESCVO6H.js → register-list-query-TPZLHFHQ.js} +2 -2
- package/dist/cli-bundle/chunks/register-mutation-JG5AEBRJ.js +21 -0
- package/dist/cli-bundle/chunks/register-operations-3CNXP46P.js +2 -0
- package/dist/cli-bundle/chunks/register-setup-4N56VL2P.js +2 -0
- package/dist/cli-bundle/chunks/{settlement-hook-MVVVUIVZ.js → settlement-hook-E5LHZ4RD.js} +2 -2
- package/dist/cli-bundle/chunks/{stage-RMU3JAWM.js → stage-XGWW3T64.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-2MQNIDKG.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-DFBHW7HP.js → chunk-5JVB42Z7.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{chunk-SFATIM77.js → chunk-6JQXDGHM.js} +9 -9
- package/dist/cli-bundle/focused-chunks/{chunk-HHMMIHZP.js → chunk-7RF2YPZ5.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-7Z2NYAK4.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-A2CLYPDA.js +102 -0
- package/dist/cli-bundle/focused-chunks/chunk-BNLLST32.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-7SEPCQV2.js → chunk-DH4DHL6V.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-EZXLY6S4.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-KRNF3WTC.js → chunk-FPPYE6CY.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-ONM2R32I.js → chunk-GD2YWUAD.js} +50 -50
- package/dist/cli-bundle/focused-chunks/chunk-HO2YUD4P.js +91 -0
- package/dist/cli-bundle/focused-chunks/{chunk-BEHIMEV2.js → chunk-ICEHI4SN.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-PDXSMSO5.js → chunk-IXYBN6D2.js} +3 -3
- package/dist/cli-bundle/focused-chunks/chunk-MTBC32ZR.js +8 -0
- package/dist/cli-bundle/focused-chunks/chunk-OAIAZHRG.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-OPY43DNJ.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-DZMP3VYQ.js → chunk-SESMRMEE.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-PEL4SQXV.js → chunk-VBA4BIHN.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-UBBTBNUY.js → chunk-XJS4COL2.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-XS2YZCT5.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-YWPLBFPC.js +44 -0
- package/dist/cli-bundle/focused-chunks/{chunk-6E4X7MQA.js → chunk-ZDY5L2C2.js} +7 -7
- package/dist/cli-bundle/focused-chunks/chunk-ZFUZ4YYN.js +8 -0
- package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-ADMQXF3N.js → indexed-receipt-blobs-ZTRFCPH7.js} +2 -2
- package/dist/cli-bundle/focused-chunks/item-revision-U7GDVAH7.js +2 -0
- package/dist/cli-bundle/focused-chunks/item-transaction-7C4BH47O.js +2 -0
- package/dist/cli-bundle/focused-chunks/mutation-actor-2SVBO324.js +2 -0
- package/dist/cli-bundle/focused-chunks/mutation-admission-SKXVITP5.js +2 -0
- package/dist/cli-bundle/focused-chunks/{settlement-hook-5U2M75BY.js → settlement-hook-OUBUN45C.js} +2 -2
- package/dist/cli-bundle/focused-chunks/stage-LVAGKCEE.js +2 -0
- package/dist/cli-bundle/main.js +27 -27
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +2 -2
- package/dist/cli-bundle/sdk-core.js +1 -1
- package/dist/cli-bundle/sdk-governance.js +1 -1
- package/dist/cli-bundle/sdk-graph.js +1 -1
- package/dist/cli-bundle/sdk-merge.js +57 -57
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +4 -4
- package/dist/core/extensions/extension-hook-runtime.d.ts +14 -2
- package/dist/core/extensions/extension-hook-runtime.js +1 -1
- package/dist/core/extensions/extension-types.d.ts +14 -0
- package/dist/core/extensions/extension-types.js +1 -1
- package/dist/core/extensions/index.d.ts +1 -1
- package/dist/core/extensions/index.js +1 -1
- package/dist/core/policy/workflow-policy-store.js +1 -1
- package/dist/core/store/item-mutation-precondition.d.ts +32 -1
- package/dist/core/store/item-mutation-precondition.js +1 -1
- package/dist/core/store/item-store.js +1 -1
- package/dist/core/store/transaction-coordinator-scope.js +2 -0
- package/dist/sdk/authoring.d.ts +1 -1
- package/dist/sdk/authoring.js +1 -1
- package/dist/sdk/cli-bootstrap.js +1 -1
- package/dist/sdk/item-transaction.js +1 -1
- package/dist/sdk/lifecycle/copy.js +1 -1
- package/dist/sdk/lifecycle/create.js +1 -1
- package/dist/sdk/lifecycle/restore.js +1 -1
- package/dist/sdk/package-import-adapters.d.ts +14 -1
- package/dist/sdk/package-import-adapters.js +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/testing.d.ts +21 -3
- package/dist/sdk/testing.js +2 -2
- package/dist/sdk/workspace-transaction.js +2 -2
- package/docs/EXTENSIONS.md +1 -1
- package/docs/MIGRATION_CLI_SIMPLIFICATION.md +1 -1
- package/docs/SDK.md +40 -3
- package/docs/WORKFLOW_POLICIES.md +23 -0
- package/marketplace.json +1 -1
- package/node_modules/@opentelemetry/core/build/esm/version.d.ts +1 -1
- package/node_modules/@opentelemetry/core/build/esm/version.js +1 -1
- package/node_modules/@opentelemetry/core/build/esnext/version.d.ts +1 -1
- package/node_modules/@opentelemetry/core/build/esnext/version.js +1 -1
- package/node_modules/@opentelemetry/core/build/src/version.d.ts +1 -1
- package/node_modules/@opentelemetry/core/build/src/version.js +1 -1
- package/node_modules/@opentelemetry/core/package.json +2 -2
- package/node_modules/@opentelemetry/resources/build/esm/detectors/platform/node/machine-id/execAsync.d.ts +1 -0
- package/node_modules/@opentelemetry/resources/build/esm/detectors/platform/node/machine-id/execAsync.js +1 -0
- package/node_modules/@opentelemetry/resources/build/esm/detectors/platform/node/machine-id/getMachineId-bsd.js +3 -2
- package/node_modules/@opentelemetry/resources/build/esm/detectors/platform/node/machine-id/getMachineId-darwin.js +3 -2
- package/node_modules/@opentelemetry/resources/build/esm/version.d.ts +1 -1
- package/node_modules/@opentelemetry/resources/build/esm/version.js +1 -1
- package/node_modules/@opentelemetry/resources/build/esnext/detectors/platform/node/machine-id/execAsync.d.ts +1 -0
- package/node_modules/@opentelemetry/resources/build/esnext/detectors/platform/node/machine-id/execAsync.js +1 -0
- package/node_modules/@opentelemetry/resources/build/esnext/detectors/platform/node/machine-id/getMachineId-bsd.js +3 -2
- package/node_modules/@opentelemetry/resources/build/esnext/detectors/platform/node/machine-id/getMachineId-darwin.js +3 -2
- package/node_modules/@opentelemetry/resources/build/esnext/version.d.ts +1 -1
- package/node_modules/@opentelemetry/resources/build/esnext/version.js +1 -1
- package/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/execAsync.d.ts +1 -0
- package/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/execAsync.js +2 -1
- package/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-bsd.js +2 -1
- package/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-darwin.js +2 -1
- package/node_modules/@opentelemetry/resources/build/src/version.d.ts +1 -1
- package/node_modules/@opentelemetry/resources/build/src/version.js +1 -1
- package/node_modules/@opentelemetry/resources/package.json +3 -3
- package/node_modules/@opentelemetry/sdk-trace/build/esm/version.d.ts +1 -1
- package/node_modules/@opentelemetry/sdk-trace/build/esm/version.js +1 -1
- package/node_modules/@opentelemetry/sdk-trace/build/esnext/version.d.ts +1 -1
- package/node_modules/@opentelemetry/sdk-trace/build/esnext/version.js +1 -1
- package/node_modules/@opentelemetry/sdk-trace/build/src/version.d.ts +1 -1
- package/node_modules/@opentelemetry/sdk-trace/build/src/version.js +1 -1
- package/node_modules/@opentelemetry/sdk-trace/package.json +5 -5
- package/node_modules/@opentelemetry/sdk-trace-base/build/esm/version.d.ts +1 -1
- package/node_modules/@opentelemetry/sdk-trace-base/build/esm/version.js +1 -1
- package/node_modules/@opentelemetry/sdk-trace-base/build/esnext/version.d.ts +1 -1
- package/node_modules/@opentelemetry/sdk-trace-base/build/esnext/version.js +1 -1
- package/node_modules/@opentelemetry/sdk-trace-base/build/src/version.d.ts +1 -1
- package/node_modules/@opentelemetry/sdk-trace-base/build/src/version.js +1 -1
- package/node_modules/@opentelemetry/sdk-trace-base/package.json +7 -7
- package/node_modules/@opentelemetry/semantic-conventions/dist/experimental_attributes.cjs +18202 -0
- package/node_modules/@opentelemetry/semantic-conventions/{build/src/experimental_attributes.js → dist/experimental_attributes.d.cts} +3328 -1993
- package/node_modules/@opentelemetry/semantic-conventions/{build/esnext/experimental_attributes.js → dist/experimental_attributes.d.mts} +3328 -1935
- package/node_modules/@opentelemetry/semantic-conventions/dist/experimental_attributes.mjs +16385 -0
- package/node_modules/@opentelemetry/semantic-conventions/dist/experimental_events.cjs +325 -0
- package/node_modules/@opentelemetry/semantic-conventions/{build/esnext/experimental_events.js → dist/experimental_events.d.cts} +37 -41
- package/node_modules/@opentelemetry/semantic-conventions/{build/esm/experimental_events.js → dist/experimental_events.d.mts} +37 -41
- package/node_modules/@opentelemetry/semantic-conventions/dist/experimental_events.mjs +295 -0
- package/node_modules/@opentelemetry/semantic-conventions/dist/experimental_metrics.cjs +4929 -0
- package/node_modules/@opentelemetry/semantic-conventions/{build/esnext/experimental_metrics.js → dist/experimental_metrics.d.cts} +955 -597
- package/node_modules/@opentelemetry/semantic-conventions/{build/esm/experimental_metrics.js → dist/experimental_metrics.d.mts} +955 -597
- package/node_modules/@opentelemetry/semantic-conventions/dist/experimental_metrics.mjs +4419 -0
- package/node_modules/@opentelemetry/semantic-conventions/dist/index-incubating.cjs +2619 -0
- package/node_modules/@opentelemetry/semantic-conventions/dist/index-incubating.d.cts +7 -0
- package/node_modules/@opentelemetry/semantic-conventions/dist/index-incubating.d.mts +7 -0
- package/node_modules/@opentelemetry/semantic-conventions/dist/index-incubating.mjs +7 -0
- package/node_modules/@opentelemetry/semantic-conventions/dist/index.cjs +670 -0
- package/node_modules/@opentelemetry/semantic-conventions/dist/index.d.cts +6 -0
- package/node_modules/@opentelemetry/semantic-conventions/dist/index.d.mts +6 -0
- package/node_modules/@opentelemetry/semantic-conventions/dist/index.mjs +6 -0
- package/node_modules/@opentelemetry/semantic-conventions/dist/internal/utils.cjs +20 -0
- package/node_modules/@opentelemetry/semantic-conventions/dist/internal/utils.mjs +20 -0
- package/node_modules/@opentelemetry/semantic-conventions/dist/resource/SemanticResourceAttributes.cjs +1326 -0
- package/node_modules/@opentelemetry/semantic-conventions/{build/esnext/resource/SemanticResourceAttributes.d.ts → dist/resource/SemanticResourceAttributes.d.cts} +600 -597
- package/node_modules/@opentelemetry/semantic-conventions/{build/src/resource/SemanticResourceAttributes.d.ts → dist/resource/SemanticResourceAttributes.d.mts} +600 -597
- package/node_modules/@opentelemetry/semantic-conventions/dist/resource/SemanticResourceAttributes.mjs +1188 -0
- package/node_modules/@opentelemetry/semantic-conventions/dist/stable_attributes.cjs +2038 -0
- package/node_modules/@opentelemetry/semantic-conventions/{build/esm/stable_attributes.js → dist/stable_attributes.d.cts} +327 -220
- package/node_modules/@opentelemetry/semantic-conventions/{build/esnext/stable_attributes.js → dist/stable_attributes.d.mts} +327 -220
- package/node_modules/@opentelemetry/semantic-conventions/dist/stable_attributes.mjs +1841 -0
- package/node_modules/@opentelemetry/semantic-conventions/dist/stable_events.cjs +9 -0
- package/node_modules/@opentelemetry/semantic-conventions/dist/stable_events.d.cts +8 -0
- package/node_modules/@opentelemetry/semantic-conventions/dist/stable_events.d.mts +8 -0
- package/node_modules/@opentelemetry/semantic-conventions/dist/stable_events.mjs +9 -0
- package/node_modules/@opentelemetry/semantic-conventions/dist/stable_metrics.cjs +378 -0
- package/node_modules/@opentelemetry/semantic-conventions/{build/src/stable_metrics.js → dist/stable_metrics.d.cts} +69 -63
- package/node_modules/@opentelemetry/semantic-conventions/{build/esm/stable_metrics.js → dist/stable_metrics.d.mts} +69 -59
- package/node_modules/@opentelemetry/semantic-conventions/dist/stable_metrics.mjs +326 -0
- package/node_modules/@opentelemetry/semantic-conventions/dist/trace/SemanticAttributes.cjs +2508 -0
- package/node_modules/@opentelemetry/semantic-conventions/{build/esnext/trace/SemanticAttributes.d.ts → dist/trace/SemanticAttributes.d.cts} +1097 -1094
- package/node_modules/@opentelemetry/semantic-conventions/{build/src/trace/SemanticAttributes.d.ts → dist/trace/SemanticAttributes.d.mts} +1097 -1094
- package/node_modules/@opentelemetry/semantic-conventions/dist/trace/SemanticAttributes.mjs +2236 -0
- package/node_modules/@opentelemetry/semantic-conventions/package.json +27 -42
- package/node_modules/@sentry/core/build/cjs/client.js +14 -5
- package/node_modules/@sentry/core/build/cjs/integrations/express/patch-layer.js +15 -1
- package/node_modules/@sentry/core/build/cjs/integrations/http/client-subscriptions.js +10 -1
- package/node_modules/@sentry/core/build/cjs/scope.js +0 -1
- package/node_modules/@sentry/core/build/cjs/tracing/openai/utils.js +1 -7
- package/node_modules/@sentry/core/build/cjs/tracing/sentrySpan.js +11 -0
- package/node_modules/@sentry/core/build/cjs/utils/envelope.js +1 -1
- package/node_modules/@sentry/core/build/cjs/utils/sql.js +1 -1
- package/node_modules/@sentry/core/build/cjs/utils/tunnel.js +9 -0
- package/node_modules/@sentry/core/build/cjs/utils/version.js +1 -1
- package/node_modules/@sentry/core/build/esm/client.js +14 -5
- package/node_modules/@sentry/core/build/esm/integrations/express/patch-layer.js +15 -1
- package/node_modules/@sentry/core/build/esm/integrations/http/client-subscriptions.js +10 -1
- package/node_modules/@sentry/core/build/esm/package.json +1 -1
- package/node_modules/@sentry/core/build/esm/scope.js +0 -1
- package/node_modules/@sentry/core/build/esm/tracing/openai/utils.js +1 -7
- package/node_modules/@sentry/core/build/esm/tracing/sentrySpan.js +11 -0
- package/node_modules/@sentry/core/build/esm/utils/envelope.js +1 -1
- package/node_modules/@sentry/core/build/esm/utils/sql.js +1 -1
- package/node_modules/@sentry/core/build/esm/utils/tunnel.js +9 -1
- package/node_modules/@sentry/core/build/esm/utils/version.js +1 -1
- package/node_modules/@sentry/core/build/types/types/datacategory.d.ts +1 -1
- package/node_modules/@sentry/core/build/types/utils/tunnel.d.ts +1 -0
- package/node_modules/@sentry/core/build/types-ts3.8/types/datacategory.d.ts +1 -1
- package/node_modules/@sentry/core/build/types-ts3.8/utils/tunnel.d.ts +1 -0
- package/node_modules/@sentry/core/package.json +1 -1
- package/node_modules/@sentry/node/build/cjs/integrations/tracing/redis/index.js +1 -1
- package/node_modules/@sentry/node/build/esm/package.json +1 -1
- package/node_modules/@sentry/node/package.json +6 -6
- package/node_modules/@sentry/node-core/build/cjs/integrations/anr/index.js +1 -1
- package/node_modules/@sentry/node-core/build/cjs/integrations/contextlines.js +6 -4
- package/node_modules/@sentry/node-core/build/cjs/integrations/local-variables/local-variables-async.js +1 -1
- package/node_modules/@sentry/node-core/build/cjs/integrations/modules.js +21 -2
- package/node_modules/@sentry/node-core/build/cjs/integrations/node-fetch/undici-instrumentation.js +8 -0
- package/node_modules/@sentry/node-core/build/esm/integrations/anr/index.js +1 -1
- package/node_modules/@sentry/node-core/build/esm/integrations/anr/worker-script.js +2 -2
- package/node_modules/@sentry/node-core/build/esm/integrations/contextlines.js +7 -5
- package/node_modules/@sentry/node-core/build/esm/integrations/local-variables/local-variables-async.js +1 -1
- package/node_modules/@sentry/node-core/build/esm/integrations/local-variables/worker-script.js +1 -1
- package/node_modules/@sentry/node-core/build/esm/integrations/node-fetch/undici-instrumentation.js +8 -0
- package/node_modules/@sentry/node-core/build/esm/package.json +1 -1
- package/node_modules/@sentry/node-core/package.json +9 -9
- package/node_modules/@sentry/opentelemetry/build/esm/package.json +1 -1
- package/node_modules/@sentry/opentelemetry/package.json +6 -6
- package/node_modules/@sentry/server-utils/build/THIRD-PARTY-LICENSES.txt +32 -32
- package/node_modules/@sentry/server-utils/build/cjs/integrations/tracing-channel/express/instrumentation.js +12 -1
- package/node_modules/@sentry/server-utils/build/esm/integrations/tracing-channel/express/instrumentation.js +13 -2
- package/node_modules/@sentry/server-utils/build/esm/package.json +1 -1
- package/node_modules/@sentry/server-utils/build/types/integrations/tracing-channel/express/types.d.ts +1 -1
- package/node_modules/@sentry/server-utils/build/types-ts3.8/integrations/tracing-channel/express/types.d.ts +1 -1
- package/node_modules/@sentry/server-utils/package.json +2 -2
- package/node_modules/debug/package.json +1 -1
- package/node_modules/es-module-lexer/dist/lexer.asm.js +2 -2
- package/node_modules/es-module-lexer/dist/lexer.cjs +1 -1
- package/node_modules/es-module-lexer/dist/lexer.js +2 -2
- package/node_modules/es-module-lexer/dist/lexer.minimal.asm.js +2 -2
- package/node_modules/es-module-lexer/dist/lexer.minimal.cjs +1 -1
- package/node_modules/es-module-lexer/dist/lexer.minimal.js +2 -2
- package/node_modules/es-module-lexer/package.json +1 -1
- package/node_modules/import-in-the-middle/CHANGELOG.md +35 -0
- package/node_modules/import-in-the-middle/README.md +15 -1
- package/node_modules/import-in-the-middle/create-hook.mjs +370 -155
- package/node_modules/import-in-the-middle/index.d.ts +8 -2
- package/node_modules/import-in-the-middle/index.js +80 -53
- package/node_modules/import-in-the-middle/lib/get-esm-exports.mjs +37 -3
- package/node_modules/import-in-the-middle/lib/get-exports.mjs +33 -40
- package/node_modules/import-in-the-middle/lib/register.js +81 -16
- package/node_modules/import-in-the-middle/package.json +9 -5
- package/node_modules/supports-color/browser.js +21 -2
- package/node_modules/supports-color/index.js +41 -24
- package/node_modules/supports-color/license +1 -1
- package/node_modules/supports-color/package.json +11 -6
- package/node_modules/supports-color/readme.md +8 -7
- package/package.json +4 -4
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-claude/package.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/plugins/pm-codex/package.json +1 -1
- package/plugins/pm-codex/plugin.json +1 -1
- package/runtime-dependencies.json +1 -1
- package/dist/cli-bundle/chunks/chunk-4WIVCOA7.js +0 -2
- package/dist/cli-bundle/chunks/chunk-A3WCP4TU.js +0 -6
- package/dist/cli-bundle/chunks/chunk-AB5S6TWE.js +0 -124
- package/dist/cli-bundle/chunks/chunk-BV7J3LRH.js +0 -114
- package/dist/cli-bundle/chunks/chunk-E4BQRZF2.js +0 -10
- package/dist/cli-bundle/chunks/chunk-IGEBFNWE.js +0 -2
- package/dist/cli-bundle/chunks/chunk-IYICNCK2.js +0 -2
- package/dist/cli-bundle/chunks/chunk-JD3XWF66.js +0 -3
- package/dist/cli-bundle/chunks/chunk-JLHD7OQ2.js +0 -2
- package/dist/cli-bundle/chunks/chunk-LC4DJVXR.js +0 -2
- package/dist/cli-bundle/chunks/chunk-OFZQEQ6X.js +0 -2
- package/dist/cli-bundle/chunks/chunk-QGL5IAP4.js +0 -8
- package/dist/cli-bundle/chunks/chunk-R24NZ2TB.js +0 -8
- package/dist/cli-bundle/chunks/chunk-VO2HSB5F.js +0 -2
- package/dist/cli-bundle/chunks/item-transaction-55QTCU2M.js +0 -2
- package/dist/cli-bundle/chunks/mutation-admission-WUN7JYVJ.js +0 -2
- package/dist/cli-bundle/chunks/register-mutation-SKCEP5QU.js +0 -20
- package/dist/cli-bundle/chunks/register-operations-ZT4OYCF3.js +0 -2
- package/dist/cli-bundle/chunks/register-setup-JVWNS2TY.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-3WVMEA2A.js +0 -6
- package/dist/cli-bundle/focused-chunks/chunk-5UVJOAUP.js +0 -91
- package/dist/cli-bundle/focused-chunks/chunk-5WQ3LNUK.js +0 -78
- package/dist/cli-bundle/focused-chunks/chunk-7XHE335U.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-CZFZCSOX.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-HPC2M6JD.js +0 -6
- package/dist/cli-bundle/focused-chunks/chunk-HR5FEUUL.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-J7ESCE7M.js +0 -24
- package/dist/cli-bundle/focused-chunks/chunk-KWZLY35A.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-M4IA4LC6.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-NASE6JC2.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-QJ647CQE.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-ZCN35TCK.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-ZSQ2FT22.js +0 -44
- package/dist/cli-bundle/focused-chunks/item-revision-GNKYO6GZ.js +0 -2
- package/dist/cli-bundle/focused-chunks/item-transaction-AUUQHR5Z.js +0 -2
- package/dist/cli-bundle/focused-chunks/mutation-actor-OBRD7HFZ.js +0 -2
- package/dist/cli-bundle/focused-chunks/mutation-admission-6TX3EOJX.js +0 -2
- package/dist/cli-bundle/focused-chunks/stage-LERF2YJU.js +0 -2
- package/node_modules/@opentelemetry/semantic-conventions/build/esm/experimental_attributes.d.ts +0 -14984
- package/node_modules/@opentelemetry/semantic-conventions/build/esm/experimental_attributes.js +0 -14991
- package/node_modules/@opentelemetry/semantic-conventions/build/esm/experimental_events.d.ts +0 -291
- package/node_modules/@opentelemetry/semantic-conventions/build/esm/experimental_metrics.d.ts +0 -4053
- package/node_modules/@opentelemetry/semantic-conventions/build/esm/index-incubating.d.ts +0 -7
- package/node_modules/@opentelemetry/semantic-conventions/build/esm/index-incubating.js +0 -13
- package/node_modules/@opentelemetry/semantic-conventions/build/esm/index.d.ts +0 -6
- package/node_modules/@opentelemetry/semantic-conventions/build/esm/index.js +0 -16
- package/node_modules/@opentelemetry/semantic-conventions/build/esm/internal/utils.d.ts +0 -7
- package/node_modules/@opentelemetry/semantic-conventions/build/esm/internal/utils.js +0 -23
- package/node_modules/@opentelemetry/semantic-conventions/build/esm/resource/SemanticResourceAttributes.d.ts +0 -1453
- package/node_modules/@opentelemetry/semantic-conventions/build/esm/resource/SemanticResourceAttributes.js +0 -1250
- package/node_modules/@opentelemetry/semantic-conventions/build/esm/resource/index.d.ts +0 -2
- package/node_modules/@opentelemetry/semantic-conventions/build/esm/resource/index.js +0 -10
- package/node_modules/@opentelemetry/semantic-conventions/build/esm/stable_attributes.d.ts +0 -1726
- package/node_modules/@opentelemetry/semantic-conventions/build/esm/stable_events.d.ts +0 -5
- package/node_modules/@opentelemetry/semantic-conventions/build/esm/stable_events.js +0 -12
- package/node_modules/@opentelemetry/semantic-conventions/build/esm/stable_metrics.d.ts +0 -308
- package/node_modules/@opentelemetry/semantic-conventions/build/esm/trace/SemanticAttributes.d.ts +0 -2664
- package/node_modules/@opentelemetry/semantic-conventions/build/esm/trace/SemanticAttributes.js +0 -2360
- package/node_modules/@opentelemetry/semantic-conventions/build/esm/trace/index.d.ts +0 -2
- package/node_modules/@opentelemetry/semantic-conventions/build/esm/trace/index.js +0 -10
- package/node_modules/@opentelemetry/semantic-conventions/build/esm/version.d.ts +0 -2
- package/node_modules/@opentelemetry/semantic-conventions/build/esm/version.js +0 -7
- package/node_modules/@opentelemetry/semantic-conventions/build/esnext/experimental_attributes.d.ts +0 -14984
- package/node_modules/@opentelemetry/semantic-conventions/build/esnext/experimental_events.d.ts +0 -291
- package/node_modules/@opentelemetry/semantic-conventions/build/esnext/experimental_metrics.d.ts +0 -4053
- package/node_modules/@opentelemetry/semantic-conventions/build/esnext/index-incubating.d.ts +0 -7
- package/node_modules/@opentelemetry/semantic-conventions/build/esnext/index-incubating.js +0 -13
- package/node_modules/@opentelemetry/semantic-conventions/build/esnext/index.d.ts +0 -6
- package/node_modules/@opentelemetry/semantic-conventions/build/esnext/index.js +0 -16
- package/node_modules/@opentelemetry/semantic-conventions/build/esnext/internal/utils.d.ts +0 -7
- package/node_modules/@opentelemetry/semantic-conventions/build/esnext/internal/utils.js +0 -23
- package/node_modules/@opentelemetry/semantic-conventions/build/esnext/resource/SemanticResourceAttributes.js +0 -1250
- package/node_modules/@opentelemetry/semantic-conventions/build/esnext/resource/index.d.ts +0 -2
- package/node_modules/@opentelemetry/semantic-conventions/build/esnext/resource/index.js +0 -10
- package/node_modules/@opentelemetry/semantic-conventions/build/esnext/stable_attributes.d.ts +0 -1726
- package/node_modules/@opentelemetry/semantic-conventions/build/esnext/stable_events.d.ts +0 -5
- package/node_modules/@opentelemetry/semantic-conventions/build/esnext/stable_events.js +0 -12
- package/node_modules/@opentelemetry/semantic-conventions/build/esnext/stable_metrics.d.ts +0 -308
- package/node_modules/@opentelemetry/semantic-conventions/build/esnext/stable_metrics.js +0 -315
- package/node_modules/@opentelemetry/semantic-conventions/build/esnext/trace/SemanticAttributes.js +0 -2360
- package/node_modules/@opentelemetry/semantic-conventions/build/esnext/trace/index.d.ts +0 -2
- package/node_modules/@opentelemetry/semantic-conventions/build/esnext/trace/index.js +0 -10
- package/node_modules/@opentelemetry/semantic-conventions/build/esnext/version.d.ts +0 -2
- package/node_modules/@opentelemetry/semantic-conventions/build/esnext/version.js +0 -7
- package/node_modules/@opentelemetry/semantic-conventions/build/src/experimental_attributes.d.ts +0 -14984
- package/node_modules/@opentelemetry/semantic-conventions/build/src/experimental_events.d.ts +0 -291
- package/node_modules/@opentelemetry/semantic-conventions/build/src/experimental_events.js +0 -301
- package/node_modules/@opentelemetry/semantic-conventions/build/src/experimental_metrics.d.ts +0 -4053
- package/node_modules/@opentelemetry/semantic-conventions/build/src/experimental_metrics.js +0 -4072
- package/node_modules/@opentelemetry/semantic-conventions/build/src/index-incubating.d.ts +0 -7
- package/node_modules/@opentelemetry/semantic-conventions/build/src/index-incubating.js +0 -29
- package/node_modules/@opentelemetry/semantic-conventions/build/src/index.d.ts +0 -6
- package/node_modules/@opentelemetry/semantic-conventions/build/src/index.js +0 -32
- package/node_modules/@opentelemetry/semantic-conventions/build/src/internal/utils.d.ts +0 -7
- package/node_modules/@opentelemetry/semantic-conventions/build/src/internal/utils.js +0 -27
- package/node_modules/@opentelemetry/semantic-conventions/build/src/resource/SemanticResourceAttributes.js +0 -1255
- package/node_modules/@opentelemetry/semantic-conventions/build/src/resource/index.d.ts +0 -2
- package/node_modules/@opentelemetry/semantic-conventions/build/src/resource/index.js +0 -26
- package/node_modules/@opentelemetry/semantic-conventions/build/src/stable_attributes.d.ts +0 -1726
- package/node_modules/@opentelemetry/semantic-conventions/build/src/stable_attributes.js +0 -1759
- package/node_modules/@opentelemetry/semantic-conventions/build/src/stable_events.d.ts +0 -5
- package/node_modules/@opentelemetry/semantic-conventions/build/src/stable_events.js +0 -15
- package/node_modules/@opentelemetry/semantic-conventions/build/src/stable_metrics.d.ts +0 -308
- package/node_modules/@opentelemetry/semantic-conventions/build/src/trace/SemanticAttributes.js +0 -2368
- package/node_modules/@opentelemetry/semantic-conventions/build/src/trace/index.d.ts +0 -2
- package/node_modules/@opentelemetry/semantic-conventions/build/src/trace/index.js +0 -26
- package/node_modules/@opentelemetry/semantic-conventions/build/src/version.d.ts +0 -2
- package/node_modules/@opentelemetry/semantic-conventions/build/src/version.js +0 -10
- /package/node_modules/import-in-the-middle/{register-hooks.d.ts → register-hooks.d.mts} +0 -0
|
@@ -1,31 +1,31 @@
|
|
|
1
|
-
import{a as Th}from"./chunk-2D26HRXB.js";import{J as ih,a as vo,b as Rr,c as bo,d as Oe,e as ko,f as eh,g as th,h as So,i as Ir,j as nh,k as rh,l as fc,m as hc,n as Or,r as Lr,t as Eo,u as te,y as gc}from"./chunk-VJLZHOTP.js";import{Aa as yh,Fa as wh,Ja as Sc,i as i_,ka as wc,ua as vc,va as gh,wa as bc,x as hh,xa as kc}from"./chunk-FZ4XWWLO.js";import{a as Mr,b as ph,i as Dt,k as $n,l as Nn,m as Mn}from"./chunk-QGL5IAP4.js";import{c as mh}from"./chunk-NYN5OR2T.js";import{A as Dn,B as de,D as To,G as Co,H as ch,Ha as kh,Ia as Sh,J as yc,Ja as Pr,K as dh,Ka as Ec,M as lh,Mc as Ih,Na as Eh,Pc as Oh,U as uh,_a as Fr,bb as Pn,eb as Fn,l as oh,lb as Ch,o as sh,oa as vh,p as Dr,pa as bh,pb as Ah,qb as xh,s as ah,wb as Rh,y as $r,z as Nr}from"./chunk-J257NZRD.js";import{a as r_}from"./chunk-JLHD7OQ2.js";import{$ as ac,$a as Af,$b as yo,Aa as of,Ab as Kf,B as oc,Bb as Wf,C as sc,D as u_,E as go,Ea as sf,F as m_,Fa as af,G as p_,Ga as cf,H as __,Ha as df,I as f_,Ia as lf,J as h_,Ja as uf,K as g_,Ka as mf,L as y_,La as pf,M as w_,Ma as _f,N as v_,Na as ff,O as b_,Oa as hf,P as k_,Pa as gf,Q as S_,Qa as yf,R as E_,Ra as wf,S as T_,Sa as vf,T as C_,Ta as bf,U as A_,Ua as kf,V as x_,Va as Sf,W as R_,Wa as dc,X as I_,Xa as Ef,Y as O_,Ya as Tf,Za as lc,_ as L_,_a as Cf,_b as zf,aa as D_,ab as xf,ac as Bf,b as o_,ba as $_,bb as Rf,bc as pc,c as s_,ca as N_,cb as If,d as a_,da as M_,db as Lt,dc as Hf,ea as P_,eb as Of,ec as Vf,fa as F_,fb as Lf,ga as j_,gb as Df,gc as Yf,ha as U_,hb as $f,hc as Jf,ia as G_,ic as wo,ja as q_,jb as Nf,jc as Xf,ka as K_,la as W_,lb as xr,ma as z_,na as B_,nb as Mf,o as rc,oa as H_,ob as Pf,p as c_,pa as cc,pb as Ff,pc as _c,qa as V_,qb as jf,ra as Y_,s as d_,sa as J_,sb as Uf,t as ic,ta as X_,tc as Qf,u as tn,ua as Q_,va as Z_,w as l_,wa as ef,wb as uc,wc as Zf,xa as tf,xb as Gf,ya as nf,yb as qf,za as rf,zb as mc}from"./chunk-F7P42FL5.js";import{d as Qp,j as Zp,r as e_,s as en,t as t_,w as n_}from"./chunk-LC4DJVXR.js";import{A as En,Ab as Lp,B as we,Ba as Tr,C as Mi,Cd as nc,D as Ua,Db as Dp,E as hr,Eb as po,F as gr,Fb as $p,Fd as Hp,G as yr,Gc as Wp,H as ft,Hb as V,I as gm,Ib as pe,J as Ki,Kb as _o,Kc as zp,Kd as Vp,La as mo,Lb as Te,Ld as Yp,Mb as gt,Md as fo,Nb as Np,Nd as Jp,Oa as Ln,Ob as Qt,Pa as vp,Qa as bp,Qb as Rt,R as Hi,Ra as Tp,Rb as he,Rd as ho,Sd as Xp,T as At,Tb as Ja,U as Ji,Ub as Mp,V as Xi,Y as Km,Ya as Cp,c as at,cc as Pp,dd as Qa,e as ct,eb as Ap,ed as Za,f as kn,fd as ec,g as Ia,ga as oo,gb as xp,gd as tc,h as Bu,hc as Fp,i as Li,j as Di,jc as jp,k as Hu,ka as Xe,l as $i,la as gp,lb as Cr,m as Vu,mc as Xa,n as Yu,na as so,o as ee,oa as yp,oc as Up,p as Sn,pa as ao,q as pr,qa as co,qb as Rp,qc as Gp,r as ke,ra as lo,rc as It,sc as qp,tc as Ot,uc as Ar,v as dt,va as uo,vc as Zt,x as Wt,xc as Kp,xd as Bp,ya as wp,z as Ni,zb as Op}from"./chunk-AB5S6TWE.js";import{$ as ro,A as Vt,C as xt,Cd as Xt,D as zm,Dd as Er,E as Wa,F as Bm,G as za,Gd as In,H as Hm,Hd as On,I as Zi,Id as Ya,K as Vm,Ka as sp,L as Ym,M as Jm,Mb as dp,N as eo,Nb as lp,Nd as kp,O as Sr,Q as to,Rb as up,T as no,U as ce,V as Yt,W as fe,Wc as pp,Wd as Sp,X as Ba,Xd as x,Y as Ha,Yd as Ep,Z as Xm,ba as Qm,ca as Rn,ce as Ip,da as Zm,ea as ep,eb as ap,fa as tp,ga as np,h as Ie,ia as io,ib as cp,ie as j,ja as rp,ka as ip,md as _p,nb as Va,nd as fp,pd as hp,q as Wm,qa as op,v as Qi,va as Jt,y as W,yc as mp,z as Je}from"./chunk-BV7J3LRH.js";import{$ as Oa,$a as um,Aa as _r,B as Pu,Ba as xe,Bb as Wi,Bd as Rm,C as Fu,Ce as ht,D as ju,Dd as Im,E as Uu,Ea as P,Ed as Om,F as Gu,Fa as _t,Fd as Lm,Fe as jm,G as qu,Ga as ji,Gd as xn,Ge as We,H as st,Ha as Cn,Hd as Dm,He as Um,I as Ku,Ia as fr,Ie as Gm,Ja as zt,Kc as vr,Ke as qm,Ma as R,Na as lt,O as Wu,Oa as Ye,Ob as I,Oc as Cm,Od as $m,P as zu,Pa as Re,Pb as wm,Q as Ra,Qa as im,Qb as Ga,Ra as om,Rb as vm,Rc as Am,Rd as br,Sa as Bt,Sb as zi,Sd as kr,Ta as Ui,Ua as sm,Ub as me,Va as am,Vb as bm,Wa as Na,Wb as An,Xa as Ma,Xb as qa,Ya as cm,Yb as Bi,Za as dm,_a as lm,_b as km,a as Z,ab as mm,ac as Sm,ae as Nm,b as Fe,bb as pm,c as Nu,cb as Pa,cc as wr,da as La,e as Mu,ea as Ke,eb as _m,ec as Em,fa as Pi,fb as L,ga as Fi,ge as Ka,ha as Xu,he as U,ib as Gi,ja as Qu,jb as Fa,je as Mm,ka as Zu,kb as fm,kc as Tm,kd as Vi,la as em,lb as qi,ma as tm,mb as hm,md as Yi,nb as ja,oa as nm,pa as rm,qa as Da,re as N,sb as ym,t as ot,ub as Ht,v as K,w as Oi,x as Kt,yb as oe,yd as xm,ye as Pm,za as $a,ze as Fm}from"./chunk-E4BQRZF2.js";import{b as _h}from"./chunk-VS565KBX.js";import{a as fh}from"./chunk-SPPHDVZE.js";import{A as m,C as p,D as Ct,E as ie,F as Tn,G,H as Q,K as je,M as Ju,a as Ru,m as Iu,p as Ou,s as Lu,u as Du,w as $u,x as Ii,y as qt}from"./chunk-NHNM3GIP.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="11e0a702-31a9-577b-a9c3-464830765883")}catch{}})();var sE=Object.freeze({"--body":"Set the item body.","--body-file":"Read the item body from a file, or from stdin when set to -.","--description":"Set the item description.","--stdin":"Read the value from stdin.","--stdin-json":"Read a complete JSON document from stdin."}),aE=new Set(["--add","--body","--comment","--dep","--dep-remove","--description","--doc","--event","--field","--file","--learning","--note","--remove","--reminder","--test","--type-option"]),cE=new Set(["append","comments","create","docs","files","learnings","notes","test","update","update-many"]),dE=new Set(["close-many:--ids","comments:--file","create:--body-file","history-compact:--ids","learnings:--file","notes:--file","update:--body-file","update-many:--ids"]),lE=new Set(["close-many:--ids","history-compact:--ids","update-many:--ids"]),uE=["--allow-","--check-","--dry-run","--explain","--fail-","--fix-","--full","--has-","--include-","--json","--no-","--prune-","--quiet","--refresh-","--require-","--runtime-only","--schema-only","--skip-","--stream","--strict-","--summary","--today","--verbose"],mE=new Set(["--activate","--active-only","--adopt","--adopt-all","--all","--all-actionable","--all-affected-ids","--all-day","--all-streams","--acknowledge-linked-tests","--append-stable","--auto-fix","--auto-pm-context","--availability-only","--background","--brief","--by-assignee","--by-priority","--by-tag","--catalog","--claim","--clear","--clear-comments","--clear-criteria","--clear-deps","--clear-docs","--clear-events","--clear-files","--clear-learnings","--clear-notes","--clear-reminders","--clear-tests","--clear-type-options","--cli-only","--closed","--compact","--completion","--count","--counts","--deactivate","--declarative","--defaults","--describe","--diff","--doctor","--empty-body","--explore","--field-utilization","--filter-empty-body","--flags-only","--follow","--force","--global","--highlight","--hybrid","--id-only","--if-available","--ignore-global","--include_unparented","--infer","--init","--install","--isolated","--lean","--list","--local","--manage","--markdown","--metadata-coverage","--next","--normalize-provenance","--only","--only-last","--output-row-contract","--override-linked-pm-context","--override-linked-workspace-context","--packages-only","--past","--phrase-exact","--profile","--progress","--project","--promote-to-item-dep","--provenance","--provenance-summary","--raw","--ready-only","--ready_only","--rebuild","--recent","--reload","--repair","--replace-deps","--replace-docs","--replace-files","--replace-tests","--required","--required-on-create","--run","--runtime-probe","--save-baseline","--scaffold","--semantic","--shared-host-safe","--storage","--takeover-stale","--title-exact","--token-accounting","--trace","--tree","--unbounded","--uninstall","--validate-paths","--verify","--watch","--with-packages"]),pE=new Set(["--only-index"]),_E=new Set(["activity:--stream","eval:--fail-under","validate:--fix-scope"]),fE=new Set(["activity:--stream","close:--validate-close","close-many:--validate-close","comments:--author","learnings:--author","notes:--author"]),hE=new Set(["--regression"]);function gE(e,t){return t==="--stdin"||t==="--stdin-json"?["stdin"]:dE.has(`${e}:${t}`)?["argv","file","stdin"]:t.endsWith("-file")?["argv","file"]:aE.has(t)&&cE.has(e)?["argv","stdin"]:["argv"]}function yE(e,t){let n=_E.has(`${e}:${t.flag}`)||t.value_name!==void 0||t.value_type==="string"||t.value_type==="number"||t.list===!0||t.repeatable===!0,r=t.value_type==="boolean"||t.flag==="--stdin"||t.flag==="--stdin-json"||t.flag.startsWith("--filter-")&&(t.flag.endsWith("-missing")||t.flag.startsWith("--filter-has-")||t.flag.startsWith("--filter-no-"))||uE.some(i=>t.flag.startsWith(i));return n||pE.has(t.flag)||!mE.has(t.flag)&&!r}function wE(e,t){return t.value_arity!==void 0?t.value_arity:yE(e,t)?hE.has(t.flag)||fE.has(`${e}:${t.flag}`)?"optional":"required":"none"}function vE(e,t){let n=Oi(e),r=wE(n,t),i=r!=="none",o=gE(n,t.flag),s=t.description??sE[t.flag]??`${i?"Set":"Enable"} ${t.flag.slice(2).replaceAll("-"," ")}.`;return{...t,description:s,takes_value:i,value_required:r==="required",...i?{value_name:t.value_name??"value"}:{},value_type:i?t.value_type??"string":"boolean",required:t.required===!0,repeatable:t.repeatable===!0||t.list===!0,input_sources:o,...o.includes("stdin")&&t.flag!=="--stdin"&&t.flag!=="--stdin-json"?{stdin_token:"-"}:{},...lE.has(`${n}:${t.flag}`)?{file_token_prefix:"@"}:{}}}function Lh(e,t){return t.map(n=>vE(e,n))}function rG(e,t,n){let r=e.trim().toLowerCase(),i=[],o=new Map,s=0;for(let c of n)if(c.command.trim().toLowerCase()===r){if(s+=1,o.has(c.flag)){i.push({code:"duplicate_observation",command:r,flag:c.flag,detail:`${r} ${c.flag} was observed more than once.`});continue}o.set(c.flag,c)}let a=new Set(t.map(({flag:c})=>c));for(let c of t){let d=o.get(c.flag);if(!d){i.push({code:"missing_observation",command:r,flag:c.flag,detail:`${r} ${c.flag} has no executable option observation.`});continue}for(let[l,u]of[["takes_value","takes_value_mismatch"],["value_required","value_required_mismatch"],["repeatable","repeatable_mismatch"]])c[l]!==d[l]&&i.push({code:u,command:r,flag:c.flag,detail:`${r} ${c.flag} declares ${l}=${String(c[l])} but the executable option reports ${String(d[l])}.`})}for(let c of o.values())a.has(c.flag)||i.push({code:"undeclared_observation",command:r,flag:c.flag,detail:`${r} ${c.flag} is executable but absent from invocation contracts.`});return i.sort((c,d)=>c.flag.localeCompare(d.flag)||c.code.localeCompare(d.code)),{ok:i.length===0,declared_count:t.length,observed_count:s,findings:i}}import{readFile as bE}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="59163d45-c136-5ead-adf1-b08ebb9c27ae")}catch{}})();function SG(e){let t={...e,...e.full===!0?{fullHistory:!0}:{}};return delete t.full,dt(e,t)}function Fh(e){return Object.prototype.toString.call(e)==="[object Object]"}function kE(e,t,n,r){let i=I();if(!Fh(e))return{...r({created_at:i,author:n,text:t}),text:t,edited_at:i};let o=s=>typeof s=="string"&&s!=="";return{...e,...o(e.created_at)?{}:{created_at:i},...o(e.author)?{}:{author:n},text:t,edited_at:i}}function Dh(e,t){if(typeof e=="object"&&e!==null&&"format"in e&&e.format==="json")throw new p(`Structured context events are append-only and cannot be ${t}.`,m.USAGE,{code:"structured_event_immutable"})}function SE(e,t){return t===void 0?e:t===0?[]:e.slice(Math.max(0,e.length-t))}function nn(e,t){let n=e[t];return Array.isArray(n)?n:[]}function EG(e,t={}){let n=e.trim();if(!n)return"";let r=/^(?:[-*+]\s*)?text\s*[:=]/i.exec(n);if(t.stripPlainTextPrefix===!0&&r&&!n.startsWith("```"))return n.slice(r[0].length).trim()||n;if(!(/^(?:[-*+]\s*)?text\s*[:=]/im.test(n)||n.startsWith("```")))return n;try{let i=ee(n,"--add");return Object.keys(i).map(o=>o.trim().toLowerCase()).some(o=>o!=="text")?n:i.text?.trim()||n}catch{return n}}function EE(e){return typeof e=="object"&&e!==null&&"code"in e}function $h(e,t){if(!Wt(e))throw new p(`${t} cannot read process stdin through the MCP JSON-RPC transport. Pass annotation text in options.add instead.`,m.USAGE,{code:"mcp_stdin_unavailable",required:"Pass annotation text as JSON data; the MCP protocol already owns process stdin."})}async function TE(e,t){if(+(e.add!==void 0)+ +(e.stdin===!0)+ +(typeof e.file=="string")>1)throw new p(`Specify ${t} text using only one input source: --add, --stdin, or --file`,m.USAGE);let n=En(),r=Wt(e);if(e.add!==void 0)return{value:await n.resolveValue(e.add,"--add",r)??"",rawValue:e.add,emptyFlag:"--add"};if(e.stdin===!0)return $h(e,"--stdin"),{value:await n.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};if(typeof e.file!="string")return;let i=e.file.trim();if(!i)throw new p("--file path cannot be empty",m.USAGE);if(i==="-")return $h(e,"--file -"),{value:await n.resolveValue("-","--file")??"",emptyFlag:"--file"};try{return{value:await bE(i,"utf8"),emptyFlag:"--file"}}catch(o){if(EE(o)&&Tn(o))throw new p(`--file path not found: ${i}. Use --file - to read stdin.`,m.USAGE);let s=o instanceof Error?o.message:String(o);throw new p(`Failed to read --file path "${i}": ${s}. Use --file - to read stdin.`,m.USAGE)}}async function TG(e,t){if(e.edit!==void 0&&e.delete!==void 0)throw new p("Specify only one of --edit or --delete",m.USAGE);if(e.delete!==void 0){if(e.add!==void 0||e.stdin===!0||typeof e.file=="string")throw new p("--delete cannot be combined with replacement text",m.USAGE);if(!Number.isInteger(e.delete)||e.delete<1)throw new p("--delete must be a positive integer",m.USAGE);return{mode:"delete",index:e.delete}}if(e.edit!==void 0&&(!Number.isInteger(e.edit)||e.edit<1))throw new p("--edit must be a positive integer",m.USAGE);let n=await TE(e,t);if(e.edit!==void 0){if(!n)throw new p("--edit requires replacement text from --add, --stdin, or --file",m.USAGE);return{mode:"edit",index:e.edit,...n}}return n?{mode:"add",...n}:{mode:"list"}}function jr(e,t){throw e instanceof p&&e.exitCode===m.CONFLICT&&e.message.includes("is assigned to")&&e.message.includes("Use --force to override")?new p(e.message,e.exitCode,{code:"ownership_conflict",required:t.required,examples:t.examples,nextSteps:t.nextSteps}):e}function jh(e){return e==="comments"?"--stdin":"--add -"}var CG="annotation_flag_like_value";function CE(e){return/^-{1,2}[A-Za-z][\w-]*(?:=.*)?$/.test(e.trim())}function AE(e){return e==="--file"?"--file <path>":e.startsWith("--file=")?e:e==="--stdin"?"--stdin":void 0}function xE(e){let t=e.value.trim(),n=e.collectionKey.replace(/s$/,""),r=AE(t),i=jh(e.collectionKey),o=e.retryArgs===void 0?{}:{field:e.textFlag,recovery:{suggested_flags:[t],suggested_retry:L(e.retryArgs),suggested_retry_args:[...e.retryArgs]}};if(r!==void 0){let s=r.split(/[ =]/,1)[0],a=s==="--file"?"that file":"stdin",c=e.conflictingOperand===void 0?"":` "${e.conflictingOperand}" was read as positional text, which ${s} cannot be combined with: drop it, or pass it as the text without ${s}.`;return new p(`${e.textFlag} value "${t}" looks like an option, not annotation text: ${e.textFlag} took ${s} as its value. Drop ${e.textFlag} and pass ${r} on its own.${c}`,m.USAGE,{code:"annotation_flag_like_value",required:`Drop ${e.textFlag}: ${r} reads the ${n} text from ${a} by itself. Use ${e.textFlag} text=${t} only when the text really is "${t}".`,examples:[`${e.commandPrefix} ${r}`,`${e.commandPrefix} ${e.textFlag} text=${t}`],...o})}return new p(`${e.textFlag} value "${t}" looks like an option, not annotation text. Use ${i} to read stdin, or use text=${t} for literal dash-leading text.`,m.USAGE,{code:"annotation_flag_like_value",required:`Use ${i} for stdin input, pass plain text, or use text=${t} when the text really starts with "-".`,examples:[`${e.commandPrefix} ${i}`,`${e.commandPrefix} ${e.textFlag} text=${t}`],...o})}function RE(e,t){if(!((t.input.emptyFlag??"--add")!=="--add"||!CE(e)))throw xE({collectionKey:t.collectionKey,textFlag:"--add",value:e,commandPrefix:t.input.mode==="edit"?`pm ${t.collectionKey} <id> --edit <index>`:`pm ${t.collectionKey} <id>`})}function IE(e,t,n,r,i){if(n.input.mode!=="edit")return;let o=Am(t);if(o===void 0)return;let s=n.collectionKey.replace(/s$/,""),a=n.input.index,c=Ie(r)[0]==="--pm-path"?["--pm-path",i]:[];throw new p(`Replacement text for ${s} ${a} on ${e} ends with the read-output compaction marker, so it was copied from a compacted read that left out ${o} characters. Nothing was written.`,m.USAGE,{code:"annotation_text_compacted",item_id:e,details:{collection:n.collectionKey,entry_index:a,omitted_characters:o},required:`Read the whole ${s} with --output-budget unbounded, apply the change to the full text, and retry the edit without the trailing marker.`,why:"A budgeted read shortens long entries to a prefix plus a marker naming how many characters it left out; editing from that text would replace the stored entry with the shortened prefix.",examples:[L([...c,n.collectionKey,e,"--output-budget","unbounded","--json"]),`${L([...c,n.collectionKey,e,"--edit",String(a),"--file"])} <full-text-file>`]})}function OE(e,t){if(t.ifAbsent===!0&&!["add","stdin","file"].includes(e.input.mode))throw new p(`--if-absent requires a ${e.collectionKey.replace(/s$/,"")} append`,m.USAGE,{code:"annotation_if_absent_without_append",required:"Combine --if-absent with one append text source; omit it for list, edit, and delete operations."});if(LE(e,t),e.input.mode!=="list"||t.message===void 0)return;let n=e.collectionKey.replace(/s$/,"");throw new p(`--message labels a ${n} mutation but does not provide ${n} text. Pass text positionally or with --add, --stdin, or --file.`,m.USAGE,{code:"annotation_message_without_text",required:`Provide ${n} text through a content source; --message only annotates the history entry of a mutation.`,examples:[`pm ${e.collectionKey} <id> --add "text" --message "why"`,`pm ${e.collectionKey} <id> ${jh(e.collectionKey)}`]})}function LE(e,t){if(t.expectAt!==void 0){if(e.input.mode!=="edit"&&e.input.mode!=="delete")throw new p(`--expect-at guards an --edit or --delete of one ${e.collectionKey.replace(/s$/,"")}`,m.USAGE,{code:"annotation_expectation_without_target",required:"Combine --expect-at with --edit <index> or --delete <index>; omit it for list and append operations.",examples:[`pm ${e.collectionKey} <id> --edit <index> --expect-at <created_at> --add "<text>"`,`pm ${e.collectionKey} <id> --delete <index> --expect-at <created_at>`]});if(typeof t.expectAt!="string"||t.expectAt.trim().length===0)throw new p("--expect-at must be the non-empty created_at timestamp of the entry you read",m.USAGE,{code:"annotation_expectation_invalid",required:"Pass the created_at value of the row you read at that index, as a string."})}}function Nh(e,t,n,r,i){if(i===void 0)return;let o=t[n]?.created_at,s=typeof o=="string"?o:null;if(s===i)return;let a=t.flatMap((_,h)=>_?.created_at===i?[h+1]:[]),c=r.collectionKey.replace(/s$/,""),d=r.input.mode==="delete"?"--delete":"--edit",l=n+1,u=a.length===1?` The ${c} created at ${i} is at index ${a[0]}.`:a.length>1?` ${a.length} ${r.collectionKey} were created at ${i}: indexes ${a.join(", ")}.`:` No ${c} on ${e} was created at ${i}.`;throw new p(`${c.charAt(0).toUpperCase()}${c.slice(1)} ${l} on ${e} was created at ${s||"an unrecorded time (malformed entry)"}, not ${i}; refusing ${d} of an entry the caller did not read. Nothing was written.${u}`,m.CONFLICT,{code:"annotation_entry_mismatch",item_id:e,details:{collection:r.collectionKey,entry_index:l,expected_created_at:i,actual_created_at:s,matching_indexes:a},required:`Address the ${c} by the index its listing row reports and keep --expect-at set to that row's created_at. When several indexes share the timestamp, inspect those rows before retrying, because the guard compares timestamps, not entry identities.`,why:"A listing page's position or count is not an entry address; only the row's index is, and the expectation checks that the entry at that index still carries the created_at that was read.",examples:[`pm ${r.collectionKey} ${e} --limit 5`,`pm ${r.collectionKey} ${e} ${d} ${a.length===1?a[0]:"<index>"} --expect-at ${i}${d==="--edit"?' --add "<text>"':""}`]})}function DE(e,t,n,r,i,o){let s=nn(e.metadata,t),a=i?s.findIndex(c=>Fh(c)&&c.author===n&&c.text===r):-1;return a>=0?{changedFields:[],written:s,position:a}:(s.push(o({created_at:I(),author:n,text:r})),e.metadata[t]=s,{changedFields:[t],written:s,position:s.length-1})}function Mh(e,t,n){return Zm.has(e)?t.map((r,i)=>i).sort((r,i)=>ep(t[r],t[i])||r-i).indexOf(n)+1:n+1}async function AG(e,t,n,r){OE(r,t);let i=R(process.cwd(),n.path);await j(i);let o=await x(i),s=P(o,N()),a=Tr(t.limit);if(r.input.mode==="list"){let f=await V(i,e,o.id_prefix,o.item_format,s.type_to_folder);if(!f)throw new p(`Item ${e} not found`,m.NOT_FOUND);let g=await pe(f,{schema:o.schema}),y=nn(g.document.metadata,r.collectionKey);return Ao(f.id,r.collectionKey,y,a,t.includeMeta===!0)}let c=U(t.author,o.author_default);if(r.input.mode==="delete"){let f=r.deleteOp??r.op,g;try{g=await he({pmRoot:i,settings:o,id:e,op:f,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(w){let v=nn(w.metadata,r.collectionKey),k=Ph(r.input.index,v.length,r.collectionKey);return Nh(e,v,k,r,t.expectAt),Dh(v[k],"deleted"),v.splice(k,1),w.metadata[r.collectionKey]=v,{changedFields:[r.collectionKey]}}})}catch(w){jr(w,r.conflictGuidance)}let y=nn(g.item,r.collectionKey);return Ao(g.item.id,r.collectionKey,y,a,t.includeMeta===!0,{action:"delete",entryIndex:r.input.index},t.fullHistory===!0)}let d=r.input.rawValue??r.input.value??"";RE(d,r);let l=r.parseText(r.input.value??"");if(!l.trim())throw new p(`${r.input.emptyFlag??"--add"} text cannot be empty`,m.USAGE);if(IE(e,l,r,n,i),r.input.mode==="edit"){let f=r.editOp??r.op,g,y=0;try{g=await he({pmRoot:i,settings:o,id:e,op:f,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(k){let S=nn(k.metadata,r.collectionKey),b=Ph(r.input.index,S.length,r.collectionKey);Nh(e,S,b,r,t.expectAt);let A=S[b];return Dh(A,"edited"),S[b]=kE(A,l,c,r.createEntry),y=Mh(r.collectionKey,S,b),k.metadata[r.collectionKey]=S,{changedFields:[r.collectionKey]}}})}catch(k){jr(k,r.conflictGuidance)}let w=nn(g.item,r.collectionKey),v=y;return Ao(g.item.id,r.collectionKey,w,a,t.includeMeta===!0,{action:"edit",entryIndex:v,entry:w[v-1]},t.fullHistory===!0)}let u,_=0;try{u=await he({pmRoot:i,settings:o,id:e,op:r.op,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,skipNoop:t.ifAbsent===!0,mutate(f){let g=DE(f,r.collectionKey,c,l,t.ifAbsent===!0,r.createEntry);return _=Mh(r.collectionKey,g.written,g.position),{changedFields:g.changedFields}}})}catch(f){jr(f,r.conflictGuidance)}let h=nn(u.item,r.collectionKey);return Ao(u.item.id,r.collectionKey,h,a,t.includeMeta===!0,{action:"add",entryIndex:_,entry:h[_-1],changedCount:t.ifAbsent===!0?Math.min(u.changedFields.length,1):void 0},t.fullHistory===!0)}function Ph(e,t,n){if(e===void 0||!Number.isInteger(e)||e<1||e>t){let r=n.replace(/s$/,""),i=`${r.charAt(0).toUpperCase()}${r.slice(1)}`,o=t===1?`1 ${r}`:`${t} ${n}`;throw new p(`${i} index ${e??"(missing)"} out of range (item has ${o})`,m.USAGE)}return e-1}function $E(e,t,n){return t===void 0?{}:{mutation_receipt:{action:t.action,entry_index:t.entryIndex,changed_count:t.changedCount??1,full_history_included:!n},omission_receipt:{has_omissions:n,omitted_field_group_count:n?1:0,omitted_field_groups:n?[{name:`${e}_history`,restore_with:{selector:"full_history",cli_flag:"--full-history",sdk_option:"fullHistory",mcp_option:"full"}}]:[]}}}function Uh(e,t){if(Object.prototype.toString.call(e)!=="[object Object]")return e;let n={index:t,...e};return n.index=t,n}function NE(e,t){let n=e.length-t.length;return t.map((r,i)=>Uh(r,n+i+1))}function Ao(e,t,n,r,i,o,s=!1){let a=o===void 0||s?NE(n,SE(n,o!==void 0&&s?void 0:r)):o.entry===void 0?[]:[Uh(o.entry,o.entryIndex)],c=o!==void 0&&a.length<n.length;return{id:e,[t]:a,count:a.length,...o?.changedCount===void 0?{}:{changed:o.changedCount===1},...[i,o!==void 0].includes(!0)?{total_count:n.length,returned_count:a.length,has_more:c||a.length<n.length,...r!==void 0?{limit:r}:{}}:{},...$E(t,o,c)}}import{isDeepStrictEqual as zh}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ab4e2ed3-e7e8-5a7a-a13e-7b8dce750dc4")}catch{}})();var ME=new Set(["__proto__","prototype","constructor"]),Cc=Symbol("looseOptionOccurrences");function $t(e){return e.trim().toLowerCase().replaceAll(/-([a-z0-9])/g,(t,n)=>n.toUpperCase())}function PE(e,t,n){let r=e[t];if(r===void 0){e[t]=n;return}if(Array.isArray(r)){r.push(n),e[t]=r;return}e[t]=[r,n]}function Ac(e,t){let n=e[t];if(!n.startsWith("-")||n==="-"||n==="--")return null;if(!n.startsWith("--")){let s=n.indexOf("=");if(s>=0)return{consumed:1,key:n.slice(1,s).trim(),value:n.slice(s+1),attached:!0};let a=n.slice(1).trim(),c=e[t+1];return typeof c=="string"&&!c.startsWith("-")?{consumed:2,key:a,value:c}:{consumed:1,key:a,value:!0}}let r=n.indexOf("=");if(r>=0)return{consumed:1,key:n.slice(2,r).trim(),value:n.slice(r+1),attached:!0};if(n.startsWith("--no-"))return{consumed:1,key:n.slice(5).trim(),value:!1};let i=n.slice(2).trim(),o=e[t+1];return typeof o=="string"&&!o.startsWith("-")?{consumed:2,key:i,value:o}:{consumed:1,key:i,value:!0}}function Ro(e){return ME.has(e)}function Io(e){let t=(typeof e.value_type=="string"?e.value_type:void 0)??(typeof e.type=="string"?e.type:void 0);return bm(t)}function Ur(e){let t=[],n=Ht(e.long)??"",r=typeof e.short=="string"?e.short.trim():"";if(n.startsWith("--")){let i=$t(n.slice(2));i.length>0&&!Ro(i)&&t.push(i)}if(r.startsWith("-")&&!r.startsWith("--")){let i=$t(r.slice(1));i.length>0&&!Ro(i)&&t.push(i)}return[...new Set(t)]}function DG(e){let t=new Set;for(let n of e)for(let r of Ur(n))t.add(r);return t}function jn(e){let t=Ht(e.long)??"";if(t.startsWith("--")){let n=$t(t.slice(2));if(n.length>0&&!Ro(n))return n}return Ur(e)[0]??null}function Un(e){let t=Ht(e.long)??"";if(t.startsWith("--")&&t.length>2)return t;let n=typeof e.short=="string"?e.short.trim():"";return n.startsWith("-")&&!n.startsWith("--")&&n.length>1?n:null}function Bh(e,t){return[...(t.definitions??e).map(n=>Un(n)).filter(n=>n!==null),...t.inheritedFlags??[]]}function $G(e,t,n,r={}){if(t.length===0)return;let i=new Set,o=new Map,s=[],a=Bh(t,r);for(let c of t){let d=Ur(c),l=Un(c);for(let u of d)i.add(u),c.enabled===!1&&o.set(u,l);c.required===!0&&c.enabled!==!1&&d.length>0&&s.push({keys:d,label:l,definition:c})}for(let c of Object.keys(e)){i.has(c)||Hh(`--${c}`,`--${c}`,n,a);let d=o.get(c);d&&Vh(d,n)}for(let c of s){let d=l=>Object.hasOwn(e,l)&&(c.definition.list!==!0||Xh(c.definition,e[l]));c.keys.some(d)||Yh(c.definition,c.keys[0],c.label,n)}}function Hh(e,t,n,r){let i=r.length>0?` Expected one of: ${[...new Set(r)].join(", ")}.`:"";throw new p(`Unknown option '${e}' for extension command '${n}'.${i}`,m.USAGE,{code:"unknown_option",flag:t,required:`Use a flag the command accepts; run pm contracts --command ${n} --flags-only --json to list them.`})}function Vh(e,t){throw new p(`Option '${e}' is disabled for extension command '${t}'.`,m.USAGE,{code:"extension_option_disabled",flag:e,required:`Remove ${e}; the command declares it with enabled: false.`,why:"A disabled declaration keeps the flag in the contract while refusing every value for it.",examples:[`pm ${t} --help`],nextSteps:[`Run pm contracts --command ${t} --flags-only --json to list the flags this command accepts.`]})}function Yh(e,t,n,r){let i=An(e),o=i.value_arity==="none"?n:i.value_arity==="optional"?`${n} [${i.value_name}]`:`${n} <${i.value_name}>`;throw new p(`Missing required option '${n}' for extension command '${r}'.`,m.USAGE,{code:"missing_required_option",flag:n,field:t,required:`Pass ${o}.`,why:"The command declares this flag as required, so pm refuses the invocation before the extension handler runs.",examples:[`pm ${r} ${o}`],nextSteps:[`Run pm contracts --command ${r} --flags-only --json to read each flag's sdk_option key.`],recovery:{missing:[n]}})}function FE(e){return typeof e=="string"||e==null?e:String(e)}function jE(e){if(typeof e=="number")return e;if(typeof e=="string"&&e.trim().length>0){let t=Number(e);return Number.isFinite(t)?t:e}return e}function Jh(e){if(typeof e=="boolean")return e;if(typeof e=="string"){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1}return e}var UE={string:FE,number:jE,boolean:Jh};function rn(e,t){return Array.isArray(e)?e.map(n=>rn(n,t)):UE[t](e)}function xc(e,t,n){let r=n?(Array.isArray(e)?e.flat(1/0):[e]).filter(i=>i!=null&&i!==""):qa(e);return t?r.map(i=>rn(i,t)):r}function Xh(e,t){return xc(t,null,e.repeatable===!0).length>0}function GE(e,t,n,r){return n?xc(e,t,r):t?rn(e,t):e}function qE(e,t,n){let r=Zh(e,t);return r.length===0?n:r.map(i=>i.value)}function Qh(e){return An(e).value_arity==="none"}function Rc(e,t,n,r,i){let o=Un(e),s=i?` for extension command '${i}'`:"",a=n===!0?"no value":JSON.stringify(n);throw new p(`Option '${o}'${s} expects ${r}; received ${a}.`,m.USAGE,{code:"extension_flag_value_invalid",flag:o,required:`Pass ${o} ${t==="number"?"<number>":"<true|false|1|0>"}.`,why:`The flag declares value_type ${t} with value_validation strict, so a malformed token is refused before the extension handler runs.`,nextSteps:[`Re-run with a valid ${t} value for ${o}.`,`Run pm ${i??"<command>"} --help to review the declared flag contract.`]})}function Ic(e,t){return e.value_validation==="strict"&&t!=="string"}function Zh(e,t){let n=e[Cc];if(!n)return[];let r=new Set(t);return n.filter(i=>r.has(i.key))}function KE(e,t,n,r){if(Qh(e))for(let i of Zh(n,t)){if(i.attached!==!0)continue;let o=e.list===!0&&e.repeatable!==!0?qa(i.value):[i.value];for(let s of o){let a=Bi(rn(s,"boolean"),"boolean");a!==null&&Rc(e,"boolean",s,a.expected,r)}}}function WE(e,t,n,r,i){let o=Array.isArray(n)?n.flat(1/0):[n],s=r?o:o.flatMap(a=>typeof a=="string"?a.split(","):[a]);for(let a of s)if(typeof a=="string"&&a.trim().length===0){let c=Bi(a,t);Rc(e,t,a,c.expected,i)}}function Oc(e,t,n,r){if(!Ic(e,n))return t;let i=n==="boolean"&&Qh(e),o=s=>{let a=Bi(s,n);return a===null?s:i&&typeof s=="string"?!0:Rc(e,n,s,a.expected,r)};return Array.isArray(t)?t.map(o):o(t)}function zE(e,t,n,r){for(let i of n)if(!(i===t||!Object.hasOwn(e,i))){if(Object.hasOwn(e,t)){if(r){let o=e[t],s=e[i];e[t]=[...Array.isArray(o)?o:[o],...Array.isArray(s)?s:[s]].filter(a=>a!=null)}delete e[i];continue}e[t]=e[i],delete e[i]}}function eg(e,t,n=e,r){if(t.length===0)return e;let i=Object.create(null);for(let[s,a]of Object.entries(e))i[s]=a;let o=new Set(t.map(s=>jn(s)).filter(s=>s!==null));for(let s of t){let a=jn(s);if(a){let c=Ur(s).filter(d=>d===a||!o.has(d));BE(i,s,a,c,n,r)}}return i}function BE(e,t,n,r,i,o){let s=t.list===!0,a=Io(t);a&&!s&&HE(e,t,n,r,a,o),zE(e,n,r,s);let c=t.repeatable===!0;if(!Object.hasOwn(e,n)){t.default!==void 0&&(e[n]=GE(t.default,a,s,c));return}if(a==="boolean"&&Ic(t,a)&&KE(t,r,i,o),s){e[n]=VE(t,r,i,e[n],a,c,o);return}a&&(e[n]=Oc(t,rn(e[n],a),a,o))}function HE(e,t,n,r,i,o){for(let s of r)s!==n&&Object.hasOwn(e,s)&&Oc(t,rn(e[s],i),i,o)}function VE(e,t,n,r,i,o,s){let a=qE(n,t,r);i&&Ic(e,i)&&WE(e,i,a,o,s);let c=xc(a,i,o);return i?Oc(e,c,i,s):c}function NG(e){let t=Object.create(null),n=[];Object.defineProperty(t,Cc,{value:n});let r=0;for(;r<e.length;){let i=Ac(e,r);if(!i){r+=1;continue}let o=$t(i.key);if(o.length===0||Ro(o)){r+=i.consumed;continue}PE(t,o,i.value),n.push({...i,key:o}),r+=i.consumed}return t}function MG(e){let t=[],n=0;for(;n<e.length;){if(e[n]==="--"){t.push(...e.slice(n+1));break}let r=Ac(e,n);if(r){n+=Math.max(1,r.consumed);continue}t.push(e[n]),n+=1}return t}function PG(e,t){if(t.length===0)return[...e];let n=new Set,r=new Set;for(let s of t){let a=Io(s);for(let c of Ur(s))n.add(c),a==="boolean"&&r.add(c)}if(n.size===0)return[...e];let i=[],o=0;for(;o<e.length;){if(e[o]==="--"){i.push(...e.slice(o+1));break}let s=Ac(e,o);if(s){let a=$t(s.key);if(n.has(a)){let c=e[o],d=r.has(a)&&!c.includes("=")?1:s.consumed;o+=d;continue}}i.push(e[o]),o+=1}return i}function Lc(e){return jn(e)}function Gh(e){return e.trim().toLowerCase().split(/\s+/u).filter(t=>t.length>0).join(" ")}function FG(e,t){let n=Gh(t);if(n.length===0)return[];let r=K(n);return e.flags.filter(i=>K(Gh(i.target_command))===r).flatMap(i=>[...i.flags])}function tg(e,t,n,r){let i=Un(e),[o,s]=n;throw new p(`Options '${o}' and '${s}' both set ${i} for extension command '${r}' with different values.`,m.USAGE,{code:"extension_option_spelling_conflict",required:`Pass ${i} once, under the handler key '${t}'.`,why:`'${o}' and '${s}' are spellings of the same declared flag, and pm refuses to choose between two different values.`,nextSteps:[`Remove '${o}' or '${s}' and pass one value as '${t}'.`,`Run pm contracts --command ${r} --flags-only --json to read each flag's sdk_option key.`]})}function jG(e,t,n,r={}){if(t.length===0)return e;let i=t.map(l=>l.repeatable===!0&&l.list!==!0?{...l,list:!0}:l),o=QE(i),s=tT(e,o,n),a=new Set([...o.long.values()].map(({handlerKey:l})=>l)),c=Object.create(null),d=Object.create(null);for(let[l,u]of Object.entries(s))a.has(l)?c[l]=u:u===void 0||r.undeclaredKeys==="pass"||JE(l)?d[l]=u:Hh(l,XE(l),n,Bh(i,{}));return rg(c,i,n),Object.assign(d,eg(c,i,ng(c,o),n))}function ng(e,t){let n=new Set([...t.long.values()].map(({handlerKey:o})=>o)),r=Object.entries(e).filter(([o])=>n.has(o)).flatMap(([o,s])=>(Array.isArray(s)?s.flat(1/0):[s]).map(a=>({consumed:1,key:o,value:a,attached:!0}))),i=Object.create(null);return Object.defineProperty(i,Cc,{value:r}),i}function rg(e,t,n){for(let r of t){let i=jn(r);if(i===null)continue;let o=Un(r),s=e[i],a=Object.hasOwn(e,i);r.enabled===!1&&a&&Vh(o,n);let c=a&&(r.list!==!0||Xh(r,s));r.required===!0&&r.enabled!==!1&&!c&&Yh(r,i,o,n),r.list!==!0&&Array.isArray(s)&&YE(o,n)}}function YE(e,t){throw new p(`Option '${e}' for extension command '${t}' takes one value; received an array.`,m.USAGE,{code:"extension_flag_value_invalid",flag:e,required:`Pass one value for ${e}, or ask the package to declare it with list: true or repeatable: true.`,why:"The flag is not declared list or repeatable, so pm refuses an array before the extension handler runs instead of handing it a value of the wrong shape.",nextSteps:[`Run pm contracts --command ${t} --flags-only --json to read each flag's value contract.`]})}var qh=new Set([...[...ym].flatMap(e=>{let t=e.replace(/^--/u,"");return[t,...t.startsWith("no-")?[t.slice(3)]:[]].flatMap(n=>[$t(n),n.replaceAll("-","_")])}),"force","subcommand","inputResponses","requestState"]);function JE(e){return qh.has(e)||qh.has($t(e.replace(/^-{1,2}/u,"")))}function XE(e){return`--${e.replace(/^-+/u,"").replace(/([a-z0-9])([A-Z])/gu,"$1-$2").replaceAll("_","-").toLowerCase()}`}function QE(e){let t={long:new Map,short:new Map},n=(r,i,o)=>{i.length>0&&!r.has(i)&&r.set(i,o)};for(let r of e){let i=jn(r);if(i===null)continue;let o={handlerKey:i,definition:r};n(t.long,i,o);let s=typeof r.short=="string"?r.short.trim():"";s.startsWith("-")&&!s.startsWith("--")&&n(t.short,s.slice(1),o)}return t}function Tc(e,t){return e.long.get(t)??e.short.get(t.replace(/^-(?!-)/u,""))??e.long.get($t(t.replace(/^-{1,2}/u,"")))}function ZE(e,t,n,r){let i=/^(?:--)?no-(.+)$/u.exec(t)?.[1];if(i===void 0||Tc(e,t)!==void 0)return{spelling:t,value:n};let o=Tc(e,i);return o===void 0||Io(o.definition)!=="boolean"?{spelling:t,value:n}:(o.definition.list===!0||o.definition.repeatable===!0)&&Array.isArray(n)?{spelling:i,value:n.flat(1/0).map(s=>Kh(t,o.definition,s,r))}:o.definition.list===!0&&n!==void 0?{spelling:i,value:Kh(t,o.definition,n,r)}:{spelling:i,value:n===void 0?n:xo(t,o.definition,n,r)}}function Kh(e,t,n,r){let i=o=>o.trim().length===0?o:String(xo(e,t,o.trim(),r));return n==null?n:typeof n!="string"?xo(e,t,n,r):n.trim().length===0?n:t.repeatable===!0||!n.includes(",")?xo(e,t,n,r):n.split(",").map(i).join(",")}function xo(e,t,n,r){let i=Jh(n);return typeof i=="boolean"?!i:eT(e,t,n,r)}function eT(e,t,n,r){let i=Un(t);throw new p(`Option '${e}' for extension command '${r}' negates ${i} and expects true, false, 1, or 0; received ${JSON.stringify(n)}.`,m.USAGE,{code:"extension_flag_value_invalid",flag:i,required:`Pass ${i} as true or false, or '${e}' as true.`,why:`'${e}' is the negated spelling of the boolean ${i}, so only a boolean value can be inverted before the extension handler runs.`,nextSteps:[`Run pm contracts --command ${r} --flags-only --json to read each flag's value contract.`]})}function tT(e,t,n){let r=Object.create(null),i=new Map;for(let[o,s]of Object.entries(e)){let{spelling:a,value:c}=ZE(t,o,s,n),d=Tc(t,a);if(d===void 0)r[a]=c;else if(c!==void 0){let l=i.get(d.handlerKey);l===void 0?(i.set(d.handlerKey,a),r[d.handlerKey]=c):zh(Wh(d.definition,d.handlerKey,r[d.handlerKey],t,n),Wh(d.definition,d.handlerKey,c,t,n))||tg(d.definition,d.handlerKey,[l,a],n)}}return r}function Wh(e,t,n,r,i){let o={[t]:n};return rg(o,[e],i),eg(o,[e],ng(o,r),i)[t]}function nT(e){let t=new Map;for(let n of e){let r=jn(n);if(r===null)continue;let i={definition:n,handlerKey:r,kind:Io(n),arity:An(n).value_arity,scalar:n.list!==!0},o=[Ht(n.long),typeof n.short=="string"?n.short.trim():""];for(let s of o.filter(a=>a?.startsWith("-")===!0))t.has(s)||t.set(s,i)}return t}function rT(e,t,n){let r=e.optionOf(n),i=t.get(n),o=i?.scalar===!0?i:void 0;if(r!==void 0){let s={arity:r.arity,...r.variadic===!0?{variadic:!0}:{}};if(o?.handlerKey===r.key)return{...s,declared:o};let a=i===void 0&&n.startsWith("--no-")?t.get(`--${n.slice(5)}`):void 0;return a?.scalar===!0&&a.kind==="boolean"&&a.handlerKey===r.key?{...s,declared:a,negates:!0}:s}if(!(!e.includesLooseFlags||i===void 0))return o===void 0?{arity:i.arity,loose:!0}:{arity:i.arity,declared:o,loose:!0}}function Dc(e){return e.length>1&&e.startsWith("-")}var ig=/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/u;function iT(e,t,n){let{tokens:r}=e,i=0,o,s=!1,a=!1;for(;i<r.length||o!==void 0;){let c=o??r[i++];if(c==="--")return;if(a&&o===void 0&&oT(e,c))continue;let d=Dc(c)?aT(e,c,r[i],t,n):{consumedByCommander:!1,consumed:0};if(i+=d.consumed,o=d.group,a=d.variadic===!0,!d.consumedByCommander){if(sT(e.stop,c,s))return;s=!0}}}function oT(e,t){return!Dc(t)||e.negativeNumbersAreValues&&ig.test(t)}function sT(e,t,n){return e!==void 0&&(e.atFirstUnrecognized||!n&&e.atSubcommand(t))}function aT(e,t,n,r,i){let o=cT(t,n,r);if(o!==void 0)return i(o.spelling,o.entry,o.value),{consumedByCommander:!1,consumed:o.consumed};let s=r(t);if(s!==void 0){let a=s.arity==="required"||s.arity==="optional"&&n!==void 0&&(!Dc(n)||e.negativeNumbersAreValues&&ig.test(n));return i(t,s,s.negates===!0?!1:a?n:!0),{consumedByCommander:!0,consumed:a?1:0,variadic:s.variadic===!0}}return t[1]!=="-"?{consumed:0,...dT(t,r,i)}:{consumedByCommander:lT(t,r,i,e.includesLooseFlags?i:()=>{}),consumed:0}}function cT(e,t,n){let r=e.indexOf("="),i=r>1?e.slice(0,r):e,o=n(i);if(o?.loose===!0)return r>1?{spelling:i,entry:o,value:e.slice(r+1),consumed:0}:t!==void 0&&!t.startsWith("-")?{spelling:i,entry:o,value:t,consumed:1}:{spelling:i,entry:o,value:!0,consumed:0};let s=r<0&&e.startsWith("--no-")?n(`--${e.slice(5)}`):void 0;return s?.loose===!0&&s.declared?.kind==="boolean"?{spelling:e,entry:s,value:!1,consumed:0}:void 0}function dT(e,t,n){let r=e.slice(0,2),i=e.length>2?t(r):void 0;return i===void 0||i.loose===!0?{consumedByCommander:!1}:i.arity!=="none"?(n(r,i,e.slice(2)),{consumedByCommander:!0}):(n(r,i,!0),{consumedByCommander:!0,group:`-${e.slice(2)}`})}function lT(e,t,n,r){let i=e.indexOf("=");if(i>2){let s=e.slice(0,i),a=t(s);return a!==void 0&&a.arity!=="none"?(n(s,a,e.slice(i+1)),!0):(a?.declared?.kind==="boolean"&&r(s,a,e.slice(i+1)),!1)}let o=e.startsWith("--no-")?t(`--${e.slice(5)}`):void 0;return o?.declared?.kind==="boolean"&&r(e,o,!1),!1}function UG(e,t,n){let r=nT(t),i=new Map;for(let o of e)iT(o,s=>rT(o,r,s),(s,a,c)=>{a.declared!==void 0&&uT(i,a.declared,s,c,n)})}function uT(e,t,n,r,i){let{definition:o,handlerKey:s,kind:a}=t,c=a?rn(r,a):r,d=e.get(s)??new Map,l=[...d].find(([u,_])=>u!==n&&!zh(_,c));l!==void 0&&tg(o,s,[l[0],n],i),d.set(n,c),e.set(s,d)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0c0bb7ab-6157-5861-ad7e-a63ae62220f4")}catch{}})();var mT=new Set(["claim","close","context","create","get","help","init","list","next","plan","release","search","update","validate","workspace"]),pT=new Set(["append","comments","config","contracts","deps","docs","events","files","focus","graph","health","history","learnings","list-all","list-blocked","list-closed","list-in-progress","list-open","notes","profile","schema","test"]),_T=Object.freeze({workspace:new Set(["config","gc","health","init","merge","profile","schema","telemetry","workspace"]),intake:new Set(["copy","create","focus","item","restore"]),context:new Set(["activity","aggregate","context","ctx","duplicates","eval","get","help","list","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","next","search","stats"]),lifecycle:new Set(["claim","close","close-many","close-task","delete","pause-task","item-reopen","release","start-task","update","update-many"]),evidence:new Set(["append","comments","docs","events","files","history","history-attest","history-author-acknowledge","history-compact","history-redact","history-repair","learnings","notes"]),graph:new Set(["deps","graph","plan"]),quality:new Set(["assurance","contracts","test","test-all","validate"]),automation:new Set(["event","meet","remind"])}),fT=new Set(["extension","install","package","packages","upgrade"]);function hT(e){let t=K(e.trim().toLowerCase());if(t==="ops")return"quality";for(let[n,r]of Object.entries(_T))if(r.has(t))return n;return fT.has(t)?"extensions":"internal"}var Gn=Object.freeze([...st.flatMap(e=>e==="item"?["item","item-reopen"]:[e,...ot.filter(t=>t.alias===e).map(t=>t.canonical)]).map(e=>({command:e,tier:mT.has(K(e))?"core":pT.has(K(e))?"standard":"full",family:hT(e)})),{command:"ops",tier:"core",family:"quality"},{command:"completion-statuses",tier:"internal",family:"internal"},{command:"completion-tags",tier:"internal",family:"internal"},{command:"completion-types",tier:"internal",family:"internal"},{command:"test-runs-worker",tier:"internal",family:"internal"},{command:"item test worker",tier:"internal",family:"internal"}]),gT=Gn,og=Object.freeze({max_lines:50,max_utf8_bytes:6e3}),WG=Object.freeze(["-V, --version","--all","--json","--output-include <fields>","--output-limit <count>","--output-budget <tokens|unbounded>","--output-cursor <cursor>","--pm-path <dir>","--no-extensions","--no-pager","--explain","-h, --help"]);function zG(e){let t=e===""?0:e.split(/\r?\n/).length,n=Buffer.byteLength(e,"utf8");return{lines:t,utf8_bytes:n,within_budget:t<=og.max_lines&&n<=og.max_utf8_bytes}}var sg={core:0,standard:1,full:2,internal:3},ag=new Map(gT.map(({command:e,tier:t})=>[e,t]));function $c(e,t="standard"){return ag.get(e.trim().toLowerCase())??ag.get(K(e.trim().toLowerCase()))??t}function BG(e){return cg(e,Gn)}function cg(e,t){let n=sg[e];return t.filter(r=>r.tier!=="internal"&&sg[r.tier]<=n).map(r=>r.command)}function HG(e){return dg(e,Gn)}function dg(e,t){return t.filter(n=>n.family===e).map(n=>n.command)}var yT=["workspace","intake","context","lifecycle","evidence","graph","quality","automation","extensions","internal"],wT=new Set([...Kt.filter(e=>e.hidden).map(e=>e.alias),"ctx","extension","install","item-reopen","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","packages","upgrade"]);function VG(e=Gn){return yT.map(t=>({family:t,commands:dg(t,e).filter(n=>e.find(r=>r.command===n)?.tier!=="internal"&&!wT.has(n))})).filter(({commands:t})=>t.length>0)}var vT=Object.freeze({pm_append:"append",pm_claim:"claim",pm_close:"close",pm_comments:"comments",pm_config:"config",pm_context:"context",pm_contracts:"contracts",pm_copy:"copy",pm_create:"create",pm_deps:"deps",pm_discover:"help",pm_docs:"docs",pm_events:"history",pm_files:"files",pm_focus:"focus",pm_get:"get",pm_graph:"graph",pm_health:"health",pm_learnings:"learnings",pm_list:"list",pm_mutate:"update",pm_next:"next",pm_notes:"notes",pm_plan:"plan",pm_profile:"profile",pm_release:"release",pm_run:"package",pm_schema:"schema",pm_search:"search",pm_test:"test",pm_update:"update",pm_validate:"validate"});function YG(e,t){return bT(e,t,Gn)}function bT(e,t,n){if(t==="full")return[...e];let r=new Set(cg(t,n));return e.filter(i=>{let o=vT[i];return o!==void 0&&r.has(o)})}var JG=Object.freeze([{uri:"pm://workspace/context",name:"Workspace context",description:"Bounded project context for orientation, including active hierarchy and progress.",mimeType:"application/json"},{uri:"pm://workspace/focus",name:"Active focus",description:"The session focus that supplies the default create parent.",mimeType:"application/json"},{uri:"pm://workspace/claims",name:"Active claims",description:"Bounded in-progress work and active ownership context.",mimeType:"application/json"},{uri:"pm://workspace/agent-guide",name:"Agent guidance",description:"Repository-local AGENTS.md instructions, bounded for safe host attachment.",mimeType:"text/markdown"}]),XG=Object.freeze([{name:"orient",description:"Build bounded live context, search all statuses, and select canonical work without creating duplicates.",arguments:[{name:"request",description:"The user's requested outcome or topic.",required:!0},{name:"scope",description:"Optional bounded workspace or subsystem scope.",required:!1}],template:"Orient to the live pm workspace for: {{request}}. Scope hint: {{scope}}. Read context, search all statuses, inspect full metadata for relevant items, and select canonical lineage before any mutation."},{name:"claim-and-start",description:"Claim one canonical item and begin implementation with linked context.",arguments:[{name:"id",description:"Canonical pm item id.",required:!0}],template:"Read {{id}} in full, claim it, set it in_progress, then implement only its acceptance scope while linking files, docs, tests, and evidence."},{name:"record-evidence-and-close",description:"Record exact verification evidence, close the item, and release ownership.",arguments:[{name:"id",description:"Canonical pm item id.",required:!0},{name:"evidence",description:"Exact verification and outcome evidence.",required:!0}],template:"For {{id}}, record this evidence: {{evidence}}. Verify linked tests, close only if acceptance is met, then release the claim."}]);function QG(){return kT(Gn)}function kT(e){return["# Generated agent command surface","","This file is generated from `PM_COMMAND_CAPABILITY_CONTRACTS`. Do not edit it manually.","","| Command | Minimum visibility tier | Capability family |","| --- | --- | --- |",...e.map(({command:t,tier:n,family:r})=>`| \`${t}\` | ${n} | ${r} |`),""].join(`
|
|
2
|
-
`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7df4fe91-e8a4-540f-8737-c67f2efa460e")}catch{}})();var Nc=[{exit_code:1,class:"generic_failure"},{exit_code:2,class:"usage"},{exit_code:3,class:"not_found"},{exit_code:4,class:"conflict"},{exit_code:5,class:"dependency_failed"}],ST=new Map(Nc.map(e=>[e.exit_code,e.class]));function Oo(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))].sort()}function ET(e){if(!e)return[];let t=new Set,n=new Set;return e.map(r=>{let i=r.state.trim(),o=r.probe_id.trim(),s=Oo(r.entrypoints);if(!/^[a-z][a-z0-9_]*$/.test(i)||!/^[a-z][a-z0-9-]*$/.test(o)||s.length===0||t.has(i)||n.has(o))throw new TypeError("Invalid pm refusal state contract");return t.add(i),n.add(o),{state:i,probe_id:o,entrypoints:s,expected_exit_class:r.expected_exit_class}}).sort((r,i)=>r.state.localeCompare(i.state))}function TT(e,t,n,r,i){return![[1,2,3,4,5].includes(e.exit_code),e.meaning.trim().length>0,e.recovery.trim().length>0,t.length>0,n.length>0,/^[a-z][a-z0-9_]*$/.test(r),i.every(o=>/^[a-z][a-z0-9_]*$/.test(o)),ST.get(e.exit_code)===e.class].includes(!1)}function CT(e,t){let n=e,r=new Set;for(;n.canonical_code!==n.code;){if(r.has(n.code))throw new TypeError(`Alias cycle in pm error code catalog: ${e.code}`);r.add(n.code);let i=t.get(n.canonical_code);if(!i)throw new TypeError(`Invalid pm error code contract: ${e.code}`);n=i}return n}function AT(e){let t=new Map(e.map(n=>[n.code,n]));for(let n of e){let r=CT(n,t);if(r.exit_code!==n.exit_code||r.class!==n.class)throw new TypeError(`Alias transport mismatch for pm error code: ${n.code}`);let i=e.filter(o=>o.code!==r.code&&o.canonical_code===r.code).map(o=>o.code).sort();if(n.code===r.code?JSON.stringify(n.aliases)!==JSON.stringify(i):n.aliases.length>0)throw new TypeError(`Invalid pm error code contract: ${n.code}`)}}function ug(e){let t=new Set,n=e.map(r=>{let i=r.code.trim();if(!/^[a-z][a-z0-9_]*$/.test(i))throw new TypeError(`Invalid pm error code: ${JSON.stringify(r.code)}`);if(t.has(i))throw new TypeError(`Duplicate pm error code: ${i}`);t.add(i);let o=Oo(r.sources),s=Oo(r.emitting_commands),a=(r.canonical_code??i).trim(),c=Oo(r.aliases??[]),d=ET(r.owned_states);if(!TT(r,o,s,a,c))throw new TypeError(`Invalid pm error code contract: ${i}`);if(d.some(l=>l.expected_exit_class!==r.class))throw new TypeError(`Invalid pm refusal state exit class: ${i}`);return Object.freeze({...r,code:i,meaning:r.meaning.trim(),recovery:r.recovery.trim(),sources:o,emitting_commands:s,canonical_code:a,aliases:c,owned_states:d})});return AT(n),Object.freeze(n.sort((r,i)=>r.code.localeCompare(i.code)))}function eq(e,t){let n=lg(e,t);return lg(n.canonical_code??n.code,t)}function lg(e,t){let n=e.trim(),r=t.find(i=>i.code===n);if(!r)throw new TypeError(`Unknown pm error code "${n}"`);return r}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0b0d726a-0fd5-5196-bee1-d34c433c0016")}catch{}})();var xT="Inspect the structured error guidance, then retry the suggested command when one is present.",RT=new Map(Nc.map(e=>[e.exit_code,e.class]));function mg(e){return e.map(t=>{let n=`${t.code.replaceAll("_"," ")} condition.`,r={code:t.code,meaning:`${n.charAt(0).toUpperCase()}${n.slice(1)}`,stability:t.stable?"stable":"provisional",exit_code:t.exit_code,class:RT.get(t.exit_code),recovery:xT,sources:t.sources,emitting_commands:t.emitting_commands??["*"],canonical_code:t.canonical_code??t.code,aliases:t.aliases??[]};return t.owned_states&&(r.owned_states=t.owned_states),r})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1cc13594-afb5-5125-bc33-490d0d1c15a4")}catch{}})();var pg=[{code:"acceptance_criteria_mutation_conflict",exit_code:2,sources:["sdk/lifecycle/update.ts"],emitting_commands:["update","update-many"]},{code:"acceptance_criteria_remove_unmatched",exit_code:3,sources:["sdk/lifecycle/update-many.ts","sdk/lifecycle/update.ts"],emitting_commands:["update","update-many"]},{code:"acceptance_criteria_semicolon_forbidden",exit_code:2,stable:!0,sources:["core/item/parse.ts"]},{code:"accepted_rejected_value",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"alias_collision",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"alias_target_missing",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"already_claimed_by",exit_code:4,stable:!0,sources:["sdk/lifecycle/claim.ts"],emitting_commands:["claim"]},{code:"ambiguous_option_combination",exit_code:2,stable:!0,sources:["sdk/lifecycle/claim.ts","sdk/lifecycle/plan.ts"],emitting_commands:["claim","plan"]},{code:"annotation_alias_conflict",exit_code:2,sources:["cli/register-annotations.ts"]},{code:"annotation_entry_mismatch",exit_code:4,sources:["sdk/annotations.ts"]},{code:"annotation_expectation_invalid",exit_code:2,sources:["sdk/annotations.ts"]},{code:"annotation_expectation_without_target",exit_code:2,sources:["sdk/annotations.ts"]},{code:"annotation_flag_like_value",exit_code:2,stable:!0,sources:["sdk/annotations.ts"]},{code:"annotation_if_absent_without_append",exit_code:2,sources:["sdk/annotations.ts"]},{code:"annotation_message_without_text",exit_code:2,stable:!0,sources:["sdk/annotations.ts"]},{code:"annotation_text_compacted",exit_code:2,sources:["sdk/annotations.ts"]},{code:"annotation_text_source_conflict",exit_code:2,sources:["sdk/runtime-input.ts"]},{code:"annotation_transposed_subcommand",exit_code:2,sources:["cli/register-annotations.ts"]},{code:"append_empty_body",exit_code:2,stable:!0,sources:["sdk/lifecycle/append.ts"],emitting_commands:["append"]},{code:"assurance_registry_invalid",exit_code:1,sources:["sdk/governance/assurance.ts"]},{code:"bare_comma_entry_ambiguous",exit_code:2,sources:["core/item/parse.ts"]},{code:"blocker_identity_read_failed",exit_code:1,sources:["sdk/query/declared-blockers.ts"]},{code:"body_file_conflicts_with_body",exit_code:2,stable:!0,sources:["core/io/body-file.ts"]},{code:"body_file_missing_path",exit_code:2,stable:!0,sources:["core/io/body-file.ts"]},{code:"body_file_unreadable",exit_code:3,stable:!0,sources:["core/io/body-file.ts"]},{code:"budget_exceeded",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"bulk_create_route",exit_code:2,sources:["cli/register-mutation.ts"]},{code:"bulk_ids_input_empty",exit_code:2,sources:["core/io/bulk-ids-input.ts","sdk/history-compact.ts","sdk/history-mcp.ts"],owned_states:[{state:"bulk_ids_stdin_contains_no_nonempty_ids",probe_id:"bulk-ids-stdin-empty",entrypoints:["update-many"],expected_exit_class:"usage"}]},{code:"bulk_ids_input_missing_path",exit_code:2,sources:["core/io/bulk-ids-input.ts"],owned_states:[{state:"bulk_ids_file_token_omits_its_path",probe_id:"bulk-ids-file-path-missing",entrypoints:["update-many"],expected_exit_class:"usage"}]},{code:"bulk_ids_input_unreadable",exit_code:3,sources:["core/io/bulk-ids-input.ts"],owned_states:[{state:"bulk_ids_file_path_cannot_be_read",probe_id:"bulk-ids-file-unreadable",entrypoints:["update-many"],expected_exit_class:"not_found"}]},{code:"bundle_integrity_torn_install",exit_code:1,stable:!0,sources:["cli/bundle-integrity.ts"]},{code:"capability_undeclared",exit_code:1,stable:!0,sources:["sdk/compose.ts"]},{code:"capability_unused",exit_code:1,stable:!0,sources:["sdk/compose.ts"]},{code:"child_projection_item_bound_exceeded",exit_code:1,stable:!0,sources:["sdk/item-children.ts"]},{code:"close_reason_required",exit_code:2,stable:!0,sources:["sdk/lifecycle-policy.ts","sdk/lifecycle/close-many.ts"],emitting_commands:["*","close-many"]},{code:"close_through_update",exit_code:1,stable:!0,sources:["core/telemetry/observability.ts"]},{code:"close_validation_deferred_fields",exit_code:2,sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"]},{code:"close_validation_missing_fields",exit_code:2,stable:!0,sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"]},{code:"collected_zero_items",exit_code:1,stable:!0,sources:["sdk/test/execution-receipts.ts"]},{code:"collection_transposed_subcommand",exit_code:2,sources:["cli/error-guidance.ts"]},{code:"command_failed",exit_code:1,stable:!0,sources:["cli/error-guidance.ts"]},{code:"command_namespace",exit_code:2,stable:!0,sources:["sdk/cli-contracts/runtime-contracts.ts"]},{code:"command_override_conflict",exit_code:4,stable:!0,sources:["sdk/compose.ts"]},{code:"config_duplicate",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"config_key_unknown",exit_code:2,stable:!0,sources:["core/profile/profile-lint.ts","sdk/config.ts"]},{code:"config_value_invalid",exit_code:2,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"conflicting_lifecycle_owner",exit_code:2,stable:!0,sources:["cli/register-operations.ts"]},{code:"context_evaluation_read_incomplete",exit_code:2,sources:["sdk/context-relevance.ts"]},{code:"context_signal_store_invalid",exit_code:2,sources:["sdk/context-signal-store.ts"]},{code:"context_signal_store_stale",exit_code:1,sources:["sdk/context-signal-store.ts"]},{code:"context_signal_store_write_failed",exit_code:1,sources:["sdk/context-signal-store.ts"]},{code:"context_takes_no_item_argument",exit_code:1,stable:!0,sources:["cli/error-guidance.ts"]},{code:"core_item_field_requires_dedicated_flag",exit_code:2,stable:!0,sources:["core/extensions/item-fields.ts"]},{code:"create_deferral_conflict",exit_code:2,sources:["sdk/lifecycle/create-deferrals.ts"],emitting_commands:["create"]},{code:"create_deferral_field_unsupported",exit_code:2,sources:["sdk/lifecycle/create-deferrals.ts"],emitting_commands:["create"]},{code:"create_deferral_fields_required",exit_code:2,sources:["sdk/lifecycle/create-deferrals.ts"],emitting_commands:["create"]},{code:"create_deferral_reason_required",exit_code:2,sources:["sdk/lifecycle/create-deferrals.ts"],emitting_commands:["create"]},{code:"create_positional_type_without_title",exit_code:2,stable:!0,sources:["cli/register-mutation.ts"]},{code:"dependency_cardinality_created",exit_code:2,sources:["sdk/graph/cardinality-integrity.ts"]},{code:"dependency_edge_not_allowed",exit_code:2,stable:!0,sources:["sdk/dependency-flag-validation.ts"]},{code:"dependency_flag_value_invalid",exit_code:2,sources:["sdk/dependency-flag-validation.ts"]},{code:"dependency_remove_no_match",exit_code:3,sources:["sdk/lifecycle/dependency-removal.ts"],emitting_commands:["update"]},{code:"dependency_target_not_found",exit_code:3,sources:["sdk/dependency-flag-validation.ts"]},{code:"dependency_temporal_order_invalid",exit_code:2,sources:["sdk/dependency-flag-validation.ts"]},{code:"duplicate_canonical_flag",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"duplicate_command",exit_code:1,stable:!0,sources:["sdk/compose.ts"]},{code:"duplicate_destination",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"duplicate_edge",exit_code:1,stable:!0,sources:["sdk/graph/remediation.ts"]},{code:"duplicate_observation",exit_code:1,sources:["sdk/flag-invocation-contracts.ts"]},{code:"duplicate_probe",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"duplicate_sweep_cost_limit",exit_code:4,stable:!0,sources:["sdk/query/duplicate-candidates.ts"],emitting_commands:["duplicate-candidates"]},{code:"duplicate_target_circular",exit_code:2,stable:!0,sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"]},{code:"duplicate_target_is_duplicate",exit_code:2,stable:!0,sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"]},{code:"duplicate_target_missing",exit_code:2,stable:!0,sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"]},{code:"duplicate_target_self",exit_code:2,stable:!0,sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"]},{code:"empty_corpus",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"empty_surface",exit_code:1,stable:!0,sources:["sdk/compose.ts"]},{code:"error_code_mismatch",exit_code:1,sources:["sdk/agent/refusal-closure.ts","sdk/agent/tracker-preflight-contracts.ts"]},{code:"event_cursor_query_mismatch",exit_code:2,stable:!0,sources:["sdk/mutation-events.ts"]},{code:"event_history_integrity_failed",exit_code:1,sources:["core/history/event-index.ts"]},{code:"event_index_unavailable",exit_code:1,stable:!0,sources:["sdk/mutation-events.ts"]},{code:"exit_code_mismatch",exit_code:1,sources:["sdk/agent/tracker-preflight-contracts.ts"]},{code:"expect_hash_background_unsupported",exit_code:2,sources:["sdk/lifecycle/item-revision.ts"]},{code:"expect_hash_invalid",exit_code:2,sources:["sdk/lifecycle/item-revision.ts"]},{code:"expect_hash_invocation_rewritten",exit_code:2,sources:["sdk/lifecycle/item-revision.ts"]},{code:"expect_hash_requires_mutation",exit_code:2,sources:["sdk/lifecycle/item-revision.ts"]},{code:"expect_hash_target_required",exit_code:2,sources:["sdk/lifecycle/item-revision.ts"]},{code:"expected_revision_duplicate",exit_code:2,sources:["core/store/item-mutation-precondition.ts"]},{code:"expected_revision_scope_conflict",exit_code:2,sources:["core/store/item-mutation-precondition.ts"]},{code:"extension_command_activation_failed",exit_code:1,stable:!0,sources:["cli/commander-usage.ts"]},{code:"extension_dependency_name_unsafe",exit_code:2,stable:!0,sources:["sdk/extension/install-sources.ts"]},{code:"extension_dependency_spec_invalid",exit_code:2,stable:!0,sources:["sdk/extension/install-sources.ts"]},{code:"extension_dependency_version_unsafe",exit_code:2,stable:!0,sources:["sdk/extension/install-sources.ts"]},{code:"extension_flag_value_invalid",exit_code:2,sources:["sdk/extension/command-options.ts"]},{code:"extension_install_incomplete_source_scan",exit_code:2,sources:["sdk/extension/install-plan.ts"]},{code:"extension_install_rollback_failed",exit_code:1,sources:["sdk/extension/install-snapshot.ts"]},{code:"extension_install_soft_failed",exit_code:1,stable:!0,sources:["cli/register-setup.ts"]},{code:"extension_install_source_contains_destination",exit_code:2,stable:!0,sources:["sdk/extension/install-runtime.ts"]},{code:"extension_item_field_reserved",exit_code:2,stable:!0,sources:["core/extensions/item-fields.ts"]},{code:"extension_item_field_type_conflict",exit_code:2,stable:!0,sources:["core/extensions/item-fields.ts"]},{code:"extension_item_field_unknown",exit_code:2,stable:!0,sources:["core/extensions/item-fields.ts"]},{code:"extension_mutation_guard_failed",exit_code:4,stable:!0,sources:["core/extensions/extension-hook-runtime.ts"]},{code:"extension_mutation_guard_invalid_decision",exit_code:4,stable:!0,sources:["core/extensions/extension-hook-runtime.ts"]},{code:"extension_mutation_guard_invalid_denial",exit_code:4,stable:!0,sources:["core/extensions/extension-hook-runtime.ts"]},{code:"extension_mutation_guard_timed_out",exit_code:4,stable:!0,sources:["core/extensions/extension-hook-runtime.ts"]},{code:"extension_option_disabled",exit_code:2,sources:["sdk/extension/command-options.ts"]},{code:"extension_option_spelling_conflict",exit_code:2,sources:["sdk/extension/command-options.ts"]},{code:"extension_read_output_invalid",exit_code:2,sources:["sdk/read-output/extension.ts"]},{code:"extension_update_health_partial_coverage",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"extensions_unreadable",exit_code:1,sources:["sdk/extension/static-inventory.ts"]},{code:"field_duplicate",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"field_invalid",exit_code:2,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"field_mcp_input_collision",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"github_source_entry_unbuilt",exit_code:2,stable:!0,sources:["sdk/extension/shared.ts"]},{code:"hierarchy_cardinality_created",exit_code:4,sources:["sdk/graph/hierarchy-integrity.ts"]},{code:"hierarchy_cycle_created",exit_code:4,sources:["sdk/graph/hierarchy-integrity.ts"]},{code:"hierarchy_parent_divergence_created",exit_code:4,sources:["sdk/graph/hierarchy-integrity.ts"]},{code:"history_author_acknowledge_plan_conflict",exit_code:4,sources:["sdk/author-attribution.ts"]},{code:"history_author_acknowledge_plan_fingerprint_required",exit_code:2,sources:["sdk/author-attribution.ts"]},{code:"history_author_acknowledge_preview_limit_invalid",exit_code:2,sources:["sdk/author-attribution.ts"]},{code:"history_author_acknowledge_required_values_missing",exit_code:2,sources:["sdk/author-attribution.ts"]},{code:"history_author_acknowledge_selector_conflict",exit_code:2,sources:["sdk/author-attribution.ts"]},{code:"history_author_acknowledge_selector_required",exit_code:2,stable:!0,sources:["sdk/author-attribution.ts"]},{code:"history_author_acknowledge_target_not_actionable",exit_code:2,sources:["sdk/author-attribution.ts"]},{code:"history_author_acknowledge_target_unreadable",exit_code:2,sources:["sdk/author-attribution.ts"]},{code:"history_baseline_unavailable",exit_code:1,sources:["core/history/projection.ts"]},{code:"history_drift_chain_mismatch",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_history_drift_chain_mismatches"]},{code:"history_drift_hash_mismatch",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_history_drift_hash_mismatches"]},{code:"history_drift_merge_receipt",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"history_drift_missing_stream",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_history_drift_missing_streams"]},{code:"history_drift_unreadable_stream",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_history_drift_unreadable_streams"]},{code:"history_drift_version_skew",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_history_drift_version_skews"]},{code:"history_json_invalid",exit_code:1,sources:["core/history/read.ts"]},{code:"history_merge_conflict_markers_detected",exit_code:1,stable:!0,sources:["core/history/read.ts"],canonical_code:"merge_conflict_markers_detected"},{code:"history_replay_invalid",exit_code:1,sources:["core/history/projection.ts","core/history/tombstone.ts"]},{code:"history_salvage_refused",exit_code:4,sources:["sdk/history/salvage.ts"]},{code:"history_stream_over_compact_threshold",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"history_target_out_of_range",exit_code:1,stable:!0,sources:["core/history/projection.ts"]},{code:"history_timestamp_invalid",exit_code:1,sources:["core/history/event-index.ts","core/history/history.ts"]},{code:"history_union_rebase_conflict",exit_code:4,sources:["sdk/merge/history-scalar-rebase.ts"]},{code:"history_unknown_author_events",exit_code:2,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_history_unknown_author_events"]},{code:"history_version_mapping_unavailable",exit_code:2,sources:["core/history/version-address.ts"]},{code:"history_version_pruned",exit_code:2,sources:["core/history/projection.ts"]},{code:"host_environment_capacity_fault",exit_code:1,sources:["core/fs/host-environment-errors.ts"]},{code:"host_environment_operation_invalid",exit_code:2,sources:["core/fs/host-environment-errors.ts"]},{code:"host_environment_permission_fault",exit_code:1,sources:["core/fs/host-environment-errors.ts"]},{code:"host_environment_resource_fault",exit_code:1,sources:["core/fs/host-environment-errors.ts"]},{code:"improvement_metric_contract_conflict",exit_code:4,sources:["sdk/improvement-ledger.ts"]},{code:"improvement_observation_conflict",exit_code:4,sources:["sdk/improvement-ledger.ts"]},{code:"in_progress_idle",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"in_progress_unowned",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"incomplete_allowed_values",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"inconsistent_concept_kind",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"init_existing_settings_requires_force",exit_code:2,stable:!0,sources:["sdk/init.ts"]},{code:"init_gitignore_unwritable",exit_code:1,stable:!0,sources:["sdk/workspace.ts"]},{code:"init_id_prefix_conflict",exit_code:2,stable:!0,sources:["sdk/init.ts"]},{code:"init_id_prefix_path_like",exit_code:2,stable:!0,sources:["sdk/init.ts"]},{code:"integrity_history_conflict_marker",exit_code:4,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_storage_history_conflict_markers"]},{code:"integrity_history_invalid_json",exit_code:2,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"integrity_history_unreadable",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"integrity_item_ahead_format_version",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_format_version_ahead_items"]},{code:"integrity_item_conflict_marker",exit_code:4,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"integrity_item_outdated_format_version",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_format_version_outdated_items"]},{code:"integrity_item_parse_failed",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"integrity_item_unreadable",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"invalid_argument_value",exit_code:2,stable:!0,sources:["cli/error-guidance.ts","core/item/priority.ts","core/shared/url-credentials.ts","core/telemetry/observability.ts","sdk/config.ts","sdk/context-intent-contracts.ts","sdk/dependencies.ts","sdk/governance/assurance-mutation-error.ts","sdk/history-redact.ts","sdk/lifecycle/create.ts","sdk/lifecycle/task-composition.ts","sdk/lifecycle/update-many.ts","sdk/lifecycle/update.ts","sdk/linked-artifacts.ts","sdk/query/next.ts","sdk/runtime-input.ts","sdk/runtime/mutation-admission.ts","sdk/runtime/mutation-value-validation.ts","sdk/runtime/schema-preview.ts","sdk/test/run-phases.ts","sdk/workspace.ts"],emitting_commands:["*","create","next","task-composition","update","update-many"]},{code:"invalid_command_usage",exit_code:2,stable:!0,sources:["cli/error-guidance.ts","core/telemetry/observability.ts"]},{code:"invalid_event_cursor",exit_code:2,stable:!0,sources:["sdk/mutation-events.ts"]},{code:"invalid_event_cursor_mode",exit_code:2,sources:["cli/register-list-query.ts","sdk/mutation-events.ts","sdk/runtime-extended-actions.ts"]},{code:"invalid_event_follow_interval",exit_code:2,stable:!0,sources:["sdk/mutation-events.ts"]},{code:"invalid_event_limit",exit_code:2,stable:!0,sources:["sdk/mutation-events.ts"]},{code:"invalid_event_since",exit_code:2,stable:!0,sources:["sdk/mutation-events.ts"]},{code:"invalid_history_analytics_limit",exit_code:2,sources:["sdk/history-analytics.ts"]},{code:"invalid_history_analytics_minimum_sample",exit_code:2,sources:["sdk/history-analytics.ts"]},{code:"invalid_history_analytics_since",exit_code:2,sources:["sdk/history-analytics.ts"]},{code:"invalid_improvement_ledger",exit_code:1,sources:["sdk/improvement-ledger-validation.ts"]},{code:"invalid_improvement_metric",exit_code:2,sources:["sdk/improvement-ledger.ts"]},{code:"invalid_improvement_observation",exit_code:2,sources:["sdk/improvement-ledger.ts"]},{code:"invalid_improvement_observation_limit",exit_code:2,sources:["sdk/improvement-ledger.ts"]},{code:"invalid_improvement_observation_timestamp",exit_code:2,sources:["sdk/improvement-ledger.ts"]},{code:"invalid_provenance_predicate",exit_code:2,stable:!0,sources:["sdk/history-provenance.ts"]},{code:"invalid_query_cursor",exit_code:2,stable:!0,sources:["sdk/pagination.ts","sdk/query/window-pagination.ts"]},{code:"invalid_read_output_session",exit_code:2,sources:["sdk/read-output-session.ts"]},{code:"invalid_reproducible_process_environment",exit_code:2,sources:["sdk/reproducibility/process.ts"]},{code:"invalid_workspace_snapshot_target",exit_code:2,sources:["sdk/workspace-snapshot.ts"]},{code:"item_already_active",exit_code:4,sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"]},{code:"item_already_exists",exit_code:4,stable:!0,sources:["sdk/lifecycle/create.ts"],emitting_commands:["create"]},{code:"item_deleted",exit_code:3,sources:["core/history/tombstone.ts"]},{code:"item_document_encoding_invalid",exit_code:4,sources:["core/store/item-store.ts"]},{code:"item_document_invalid",exit_code:1,stable:!0,sources:["core/item/item-format.ts"]},{code:"item_document_roundtrip_failed",exit_code:1,stable:!0,sources:["core/item/item-format.ts"]},{code:"item_format_version_unsupported",exit_code:4,sources:["core/item/item-format.ts"]},{code:"item_id_collision",exit_code:4,stable:!0,sources:["sdk/lifecycle/copy.ts"],emitting_commands:["copy"]},{code:"item_identity_ambiguous",exit_code:4,sources:["core/store/item-store.ts"]},{code:"item_identity_conflict",exit_code:4,sources:["sdk/governance/validate-history-drift.ts","sdk/lifecycle/item-revision.ts","sdk/merge/three-way.ts","sdk/query/declared-blockers.ts"]},{code:"item_identity_reserved",exit_code:4,sources:["core/history/history.ts"]},{code:"item_not_found",exit_code:3,stable:!0,sources:["cli/error-guidance.ts","core/store/item-store.ts","core/telemetry/observability.ts","sdk/governance/validate-history-drift.ts"]},{code:"item_revision_conflict",exit_code:4,sources:["core/store/item-mutation-precondition.ts"]},{code:"likely_duplicate",exit_code:4,stable:!0,sources:["sdk/similarity.ts"]},{code:"linked_artifact_mutation_conflict",exit_code:2,sources:["sdk/linked-artifacts.ts"]},{code:"linked_artifact_note_conflict",exit_code:4,sources:["sdk/linked-artifacts.ts"]},{code:"linked_artifact_note_key_misread",exit_code:2,sources:["sdk/linked-artifacts.ts"]},{code:"linked_resource_positional_value",exit_code:2,sources:["cli/error-guidance.ts"]},{code:"linked_test_command_immutable",exit_code:2,sources:["sdk/test/update.ts"]},{code:"linked_test_command_not_executable",exit_code:2,sources:["sdk/test/entry.ts"]},{code:"linked_test_context_invalid",exit_code:2,sources:["sdk/test/entry.ts"]},{code:"linked_test_patch_fields_unsupported",exit_code:2,sources:["sdk/test/update.ts"]},{code:"linked_test_remove_no_match",exit_code:3,sources:["sdk/test/execution.ts"]},{code:"linked_test_update_ambiguous",exit_code:2,sources:["sdk/test/update.ts"]},{code:"linked_test_update_no_match",exit_code:3,sources:["sdk/test/update.ts"]},{code:"linked_test_value_not_quoted",exit_code:1,stable:!0,sources:["cli/error-guidance.ts"]},{code:"list_source_incomplete",exit_code:1,stable:!0,sources:["sdk/query/list.ts"],emitting_commands:["list"]},{code:"local_package_archive_unsafe",exit_code:2,stable:!0,sources:["sdk/extension/install-sources.ts"]},{code:"local_source_not_found_bare_name",exit_code:3,stable:!0,sources:["sdk/extension/install-sources.ts"]},{code:"lock_conflict",exit_code:4,stable:!0,sources:["cli/error-guidance.ts","core/lock/lock.ts","core/telemetry/observability.ts"]},{code:"lock_lost",exit_code:4,sources:["core/lock/lock.ts"]},{code:"lock_path_unsafe",exit_code:4,sources:["core/lock/lock-confinement.ts"]},{code:"locks_stale_count",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"locks_unreadable",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"malformed_plan_step_evidence",exit_code:2,stable:!0,sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"]},{code:"managed_state_invalid",exit_code:2,sources:["sdk/extension/static-inventory.ts"]},{code:"managed_state_unreadable",exit_code:1,sources:["sdk/extension/static-inventory.ts"]},{code:"manifest_capabilities_absent",exit_code:1,stable:!0,sources:["sdk/compose.ts"]},{code:"manifest_invalid",exit_code:2,sources:["sdk/extension/static-inventory.ts"]},{code:"manifest_unknown_key",exit_code:1,sources:["core/extensions/manifest-schema.ts"],owned_states:[{state:"author_workspace_manifest_declares_an_unknown_top_level_key",probe_id:"author-manifest-unknown-key",entrypoints:["health"],expected_exit_class:"generic_failure"}]},{code:"manifest_unreadable",exit_code:1,sources:["sdk/extension/static-inventory.ts"]},{code:"mcp_annotation_file_unavailable",exit_code:2,sources:["sdk/runtime-input.ts"]},{code:"mcp_stdin_unavailable",exit_code:2,sources:["sdk/annotations.ts"]},{code:"mcp_task_not_found_or_not_authorized",exit_code:3,sources:["sdk/mcp/tasks.ts"]},{code:"merge_artifacts_ignored",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"merge_bun_launcher_unavailable",exit_code:5,sources:["sdk/merge/install.ts"]},{code:"merge_conflict_markers_detected",exit_code:1,stable:!0,sources:["core/item/item-format.ts"],aliases:["history_merge_conflict_markers_detected"]},{code:"merge_decisions_unreviewed",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"merge_driver_configuration_drift",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"merge_driver_configuration_missing",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"merge_fence_drift",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"merge_fence_missing",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"merge_git_config_unwritable",exit_code:5,stable:!0,sources:["sdk/merge/install.ts"]},{code:"merge_receipt_evidence_invalid",exit_code:4,sources:["core/diagnostics/remediation.ts","sdk/merge/reconcile.ts"]}];(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1295716e-cbc9-5497-9a14-30274f1f7086")}catch{}})();var _g=[{code:"merge_receipt_history_reference_missing",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"merge_receipt_not_portable",exit_code:4,sources:["sdk/merge/receipts.ts"]},{code:"merge_receipts_pending",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"merge_reconcile_receipt_evidence_untrusted",exit_code:4,sources:["sdk/history-repair.ts"]},{code:"merge_root_not_found",exit_code:3,stable:!0,sources:["sdk/merge/install.ts"]},{code:"merge_settlement_hook_conflict",exit_code:4,sources:["sdk/merge/settlement-hook.ts"]},{code:"merge_settlement_review_required",exit_code:4,sources:["sdk/merge/ignored-artifacts.ts","sdk/merge/reconcile.ts","sdk/merge/stage.ts"]},{code:"missing_allowed_values",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"missing_budget",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"missing_cli_flag",exit_code:1,sources:["sdk/cli-contracts/tool-option-contracts.ts"]},{code:"missing_destination",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"missing_directory",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"missing_init_recovery",exit_code:1,sources:["sdk/agent/tracker-preflight-contracts.ts"]},{code:"missing_lifecycle_target",exit_code:2,stable:!0,sources:["sdk/extension.ts"]},{code:"missing_observation",exit_code:1,sources:["sdk/flag-invocation-contracts.ts"]},{code:"missing_observed_signature",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"missing_parameter_alias",exit_code:1,sources:["sdk/cli-contracts/tool-option-contracts.ts"]},{code:"missing_positive_execution_receipt",exit_code:1,sources:["sdk/test/execution.ts"]},{code:"missing_probe",exit_code:1,sources:["sdk/agent/tracker-preflight-contracts.ts"]},{code:"missing_required_argument",exit_code:2,stable:!0,sources:["cli/error-guidance.ts","cli/main.ts","cli/register-mutation.ts","cli/schema/registration.ts","core/telemetry/observability.ts","sdk/governance/assurance-action.ts","sdk/history-redact.ts","sdk/invocation-author.ts","sdk/lifecycle/claim.ts","sdk/linked-artifacts.ts"],emitting_commands:["*","claim"]},{code:"missing_required_option",exit_code:2,stable:!0,sources:["cli/error-guidance.ts","core/telemetry/observability.ts","sdk/context-intent-contracts.ts","sdk/extension/command-options.ts","sdk/lifecycle/create.ts","sdk/lifecycle/plan.ts"],emitting_commands:["*","create","plan"]},{code:"missing_suggested_retry",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"missing_suggested_retry_args",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"module_import_failed",exit_code:1,stable:!0,sources:["cli/error-guidance.ts"]},{code:"multi_target_github_install_ambiguous",exit_code:2,stable:!0,sources:["cli/register-setup.ts"]},{code:"mutation_author_required",exit_code:2,stable:!0,sources:["sdk/mutation-guard.ts"]},{code:"mutation_document_unreadable",exit_code:2,sources:["cli/register-structured-mutation.ts"]},{code:"mutation_option_value_invalid",exit_code:2,sources:["sdk/lifecycle/mutation-option-validation.ts"],emitting_commands:["item mutate"]},{code:"mutation_secret_guard_blocked",exit_code:4,stable:!0,sources:["sdk/mutation-guard.ts"]},{code:"no_matching_tests",exit_code:1,stable:!0,sources:["sdk/test/execution-receipts.ts"]},{code:"no_projects_matched_filters",exit_code:1,stable:!0,sources:["sdk/test/execution-receipts.ts"]},{code:"no_test_files_found",exit_code:1,stable:!0,sources:["sdk/test/execution-receipts.ts"]},{code:"no_tests_found",exit_code:1,stable:!0,sources:["sdk/test/execution-receipts.ts"]},{code:"no_update_fields",exit_code:1,stable:!0,sources:["cli/error-guidance.ts","core/telemetry/observability.ts"]},{code:"no_version_bounds_declared",exit_code:1,sources:["core/extensions/manifest-schema.ts"],owned_states:[{state:"author_workspace_manifest_omits_canonical_pm_version_bounds",probe_id:"author-manifest-version-bounds-missing",entrypoints:["health"],expected_exit_class:"generic_failure"}]},{code:"non_refusal_exit",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"npm_pack_json_shape_unsupported",exit_code:1,sources:["sdk/extension/install-sources.ts"]},{code:"npm_package_archive_missing",exit_code:1,sources:["sdk/extension/install-sources.ts"]},{code:"npm_package_archive_unsafe",exit_code:1,sources:["sdk/extension/install-sources.ts"]},{code:"npm_package_not_found",exit_code:3,stable:!0,sources:["sdk/extension/install-sources.ts"]},{code:"output_budget_exceeded",exit_code:2,sources:["sdk/testing.ts"]},{code:"ownership_conflict",exit_code:4,stable:!0,sources:["cli/error-guidance.ts","core/telemetry/observability.ts","sdk/annotations.ts"]},{code:"ownership_dependency_bypass_restricted_options",exit_code:1,stable:!0,sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"]},{code:"ownership_metadata_bypass_restricted_options",exit_code:1,stable:!0,sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"]},{code:"package_spec_empty",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"package_upgrade_modes_mutually_exclusive",exit_code:2,sources:["sdk/governance/upgrade.ts"]},{code:"positional_shape_budget_exceeded",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"positional_signature_mismatch",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"profile_name_empty",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"profile_name_not_normalized",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"profile_summary_empty",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"profile_title_empty",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"project_runtime_history_epoch_incompatible",exit_code:4,sources:["sdk/environment/project-runtime-compatibility.ts"]},{code:"project_runtime_item_format_incompatible",exit_code:4,sources:["sdk/environment/project-runtime-compatibility.ts"]},{code:"project_runtime_stale_mutation",exit_code:4,sources:["sdk/environment/project-runtime-compatibility.ts"]},{code:"project_runtime_stale_read",exit_code:1,sources:["sdk/environment/project-runtime-compatibility.ts"]},{code:"project_schema_field_requires_declared_flag",exit_code:2,sources:["core/extensions/item-fields.ts"]},{code:"projection_options_mutually_exclusive",exit_code:2,sources:["sdk/query/get.ts","sdk/query/list.ts","sdk/query/search-contracts.ts"],emitting_commands:["get","list","search"]},{code:"provenance_value_domain_invalid",exit_code:2,sources:["core/diagnostics/remediation.ts"]},{code:"read_output_cursor_command_mismatch",exit_code:2,sources:["sdk/read-output/continuation.ts"]},{code:"read_output_cursor_invalid",exit_code:2,sources:["sdk/read-output/continuation.ts"]},{code:"read_output_cursor_stale",exit_code:2,sources:["sdk/read-output/continuation.ts"]},{code:"read_output_mutation_conflict",exit_code:2,sources:["sdk/read-output-contracts.ts"]},{code:"recovery_kind_mismatch",exit_code:1,sources:["sdk/agent/tracker-preflight-contracts.ts"]},{code:"redundant_edge",exit_code:1,stable:!0,sources:["sdk/graph/remediation.ts"]},{code:"refusal_allowed_values_mismatch",exit_code:1,sources:["sdk/agent/refusal-corpus-contracts.ts"]},{code:"refusal_error_code_mismatch",exit_code:1,sources:["sdk/agent/refusal-corpus-contracts.ts"]},{code:"refusal_exit_code_mismatch",exit_code:1,sources:["sdk/agent/refusal-corpus-contracts.ts"]},{code:"refusal_mutated_state",exit_code:1,sources:["sdk/agent/refusal-corpus-contracts.ts"]},{code:"refusal_probe_missing",exit_code:1,sources:["sdk/agent/refusal-corpus-contracts.ts"]},{code:"refusal_recovery_failed",exit_code:1,sources:["sdk/agent/refusal-corpus-contracts.ts"]},{code:"reindex_already_running",exit_code:4,stable:!0,sources:["sdk/governance/reindex.ts"]},{code:"removed_canonical_spelling",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"removed_compatibility_spelling",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"reopen_reason_required",exit_code:2,sources:["sdk/lifecycle/reopen.ts"],emitting_commands:["item reopen"]},{code:"reopen_receipt_missing",exit_code:1,sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"]},{code:"reopen_target_status_invalid",exit_code:2,sources:["sdk/lifecycle/reopen.ts"],emitting_commands:["item reopen"]},{code:"reported_zero_passes",exit_code:1,sources:["sdk/test/execution-receipts.ts"]},{code:"reported_zero_tests",exit_code:1,sources:["sdk/test/execution-receipts.ts"]},{code:"reserved_item_field",exit_code:1,stable:!0,sources:["sdk/compose.ts"]},{code:"retry_failed",exit_code:1,sources:["sdk/agent/refusal-closure.ts","sdk/agent/tracker-preflight-contracts.ts"]},{code:"schema_migration_input_required",exit_code:2,stable:!0,sources:["cli/migration-gates.ts"]},{code:"semantic_spelling_collision",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"settings_invalid",exit_code:2,sources:["sdk/extension/static-inventory.ts"]},{code:"settings_read_fs_error",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"settings_read_invalid_json",exit_code:2,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"settings_read_invalid_schema",exit_code:2,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"settings_read_merge_failed",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"settings_section_document_malformed",exit_code:2,sources:["core/store/settings-sections.ts"]},{code:"settings_section_document_missing",exit_code:3,sources:["core/store/settings-sections.ts"]},{code:"settings_section_invalid",exit_code:2,sources:["core/store/settings-sections.ts"]},{code:"settings_section_name_invalid",exit_code:2,sources:["core/store/settings-sections.ts"]},{code:"settings_section_reserved",exit_code:2,sources:["core/store/settings-sections.ts"]},{code:"settings_section_revision_conflict",exit_code:4,sources:["core/store/settings-sections.ts"]},{code:"settings_unreadable",exit_code:1,sources:["sdk/extension/static-inventory.ts"]},{code:"settings_write_assigned_path_invalid",exit_code:2,sources:["core/store/settings.ts"]},{code:"settings_write_invalid_existing_json",exit_code:2,sources:["core/store/settings.ts"]},{code:"settings_write_invalid_existing_schema",exit_code:2,sources:["core/store/settings.ts"]},{code:"stale_budget",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"stale_claim_takeover_refused",exit_code:4,sources:["sdk/lifecycle/claim.ts"],emitting_commands:["claim"]},{code:"stale_destination",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"stale_in_progress_items",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"stale_lock_requires_override",exit_code:4,sources:["core/lock/lock.ts"]},{code:"stale_observed_signature",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"stale_revision",exit_code:4,sources:["core/store/item-store.ts"]},{code:"start_blocked_by_open_dependency",exit_code:4,sources:["sdk/lifecycle/start-blockers.ts"],emitting_commands:["claim","start-task","update"]},{code:"status_duplicate",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"status_invalid",exit_code:2,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"status_lifecycle_role_required",exit_code:2,sources:["sdk/schema.ts"]},{code:"stdin_json_invalid",exit_code:2,stable:!0,sources:["sdk/structured-mutations.ts"]},{code:"stdin_json_persisted_annotation_changed",exit_code:2,sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"]},{code:"stdin_json_unknown_key",exit_code:2,stable:!0,sources:["sdk/structured-mutations.ts"]},{code:"structured_entry_key_repeated",exit_code:2,sources:["core/item/parse.ts"]},{code:"structured_event_immutable",exit_code:2,stable:!0,sources:["sdk/annotations.ts"]},{code:"structured_event_input_conflict",exit_code:2,stable:!0,sources:["sdk/notes.ts"]},{code:"structured_event_json_empty",exit_code:2,stable:!0,sources:["sdk/notes.ts"]},{code:"structured_event_json_invalid",exit_code:2,stable:!0,sources:["sdk/notes.ts"]},{code:"structured_event_since_invalid",exit_code:2,stable:!0,sources:["sdk/notes.ts"]},{code:"suggested_retry_args_mismatch",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"telemetry_endpoint_probe_failed",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"telemetry_endpoint_probe_http_status",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"telemetry_otel_export_failing",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"telemetry_queue_high_retries",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"telemetry_queue_invalid_rows",exit_code:2,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"telemetry_queue_pending",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"telemetry_schema_version_behind",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"telemetry_state_invalid_json",exit_code:2,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"template_type_unknown",exit_code:2,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"terminal_plan_mutation",exit_code:4,stable:!0,sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"]},{code:"terminal_state_conflict",exit_code:4,stable:!0,sources:["core/telemetry/observability.ts","sdk/lifecycle/claim.ts"],emitting_commands:["*","claim"]},{code:"test_measure_requires_execution",exit_code:2,sources:["sdk/test/prerequisites.ts"]},{code:"test_measure_requires_run",exit_code:2,sources:["sdk/test/prerequisites.ts"]},{code:"text_unpaired_surrogate",exit_code:2,sources:["core/item/item-format.ts","core/shared/output-unicode.ts"]},{code:"tracked_runtime_cache_files",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_storage_tracked_runtime_cache_files"]},{code:"tracker_not_initialized",exit_code:3,stable:!0,sources:["cli/error-guidance.ts","core/store/tracker-preflight.ts","core/telemetry/observability.ts"],owned_states:[{state:"selected_tracker_root_exists_without_settings",probe_id:"tracker-root-settings-missing",entrypoints:["list"],expected_exit_class:"not_found"}]},{code:"tracker_root_missing",exit_code:3,stable:!0,sources:["core/store/tracker-preflight.ts"],owned_states:[{state:"selected_tracker_root_does_not_exist",probe_id:"tracker-root-missing",entrypoints:["list"],expected_exit_class:"not_found"}]},{code:"tracker_root_not_directory",exit_code:2,stable:!0,sources:["core/store/tracker-preflight.ts"],owned_states:[{state:"selected_tracker_root_is_a_regular_file",probe_id:"tracker-root-not-directory",entrypoints:["list"],expected_exit_class:"usage"}]},{code:"tracker_root_unreadable",exit_code:1,sources:["core/store/tracker-preflight.ts"],owned_states:[{state:"selected_tracker_root_is_not_readable",probe_id:"tracker-root-unreadable",entrypoints:["list"],expected_exit_class:"generic_failure"}]},{code:"transaction_abandoned",exit_code:4,sources:["sdk/workspace-transaction.ts"]},{code:"transaction_committed",exit_code:4,sources:["sdk/workspace-transaction.ts"]},{code:"transaction_create_compensated",exit_code:4,sources:["sdk/item-transaction.ts"]},{code:"transaction_journal_invalid",exit_code:4,sources:["sdk/workspace-transaction.ts"]},{code:"transaction_partial_mutation",exit_code:4,sources:["sdk/item-transaction.ts"]},{code:"transaction_plan_mismatch",exit_code:4,sources:["sdk/workspace-transaction.ts"]},{code:"transaction_preview_external_schema",exit_code:2,sources:["sdk/item-transaction.ts"]},{code:"transaction_preview_non_regular_file",exit_code:2,sources:["core/fs/fs-utils.ts"]},{code:"transaction_preview_snapshot_changed",exit_code:4,sources:["sdk/item-transaction.ts"]},{code:"transaction_recovery_plan_missing",exit_code:4,sources:["sdk/item-transaction.ts"]},{code:"type_duplicate",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"type_invalid",exit_code:2,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"undeclared_observation",exit_code:1,sources:["sdk/flag-invocation-contracts.ts"]},{code:"unexpected_refusal_probe",exit_code:1,sources:["sdk/agent/refusal-corpus-contracts.ts"]},{code:"unknown_command",exit_code:2,stable:!0,sources:["cli/error-guidance.ts","core/telemetry/observability.ts","sdk/cli-contracts/runtime-contracts.ts"]},{code:"unknown_context_intent",exit_code:2,stable:!0,sources:["sdk/context-intent-contracts.ts"]},{code:"unknown_error",exit_code:1,stable:!0,sources:["cli/error-guidance.ts"]},{code:"unknown_field",exit_code:3,stable:!0,sources:["sdk/schema.ts"]},{code:"unknown_field_projection",exit_code:2,stable:!0,sources:["sdk/query/get.ts","sdk/query/list.ts","sdk/query/search-contracts.ts"],emitting_commands:["get","list","search"]},{code:"unknown_item_type",exit_code:3,stable:!0,sources:["sdk/schema.ts"]},{code:"unknown_lifecycle_action",exit_code:2,stable:!0,sources:["sdk/agent/subcommand-recovery.ts"],canonical_code:"unknown_subcommand"},{code:"unknown_noun",exit_code:2,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"unknown_option",exit_code:2,stable:!0,sources:["cli/error-guidance.ts","cli/runtime/invocation-options.ts","core/telemetry/observability.ts","sdk/extension/command-options.ts"],owned_states:[{state:"declared_option_is_rejected_on_the_selected_command_path",probe_id:"cross-command-unknown-option",entrypoints:["deps"],expected_exit_class:"usage"}]},{code:"unknown_plan_template",exit_code:2,stable:!0,sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"]},{code:"unknown_provenance_dimension",exit_code:2,stable:!0,sources:["sdk/history-provenance.ts"]},{code:"unknown_status",exit_code:3,stable:!0,sources:["sdk/schema.ts"]},{code:"unknown_subcommand",exit_code:2,stable:!0,sources:["cli/error-guidance.ts","sdk/agent/subcommand-recovery.ts"],aliases:["unknown_lifecycle_action"],owned_states:[{state:"config_action_token_is_not_declared",probe_id:"config-unknown-action",entrypoints:["config"],expected_exit_class:"usage"},{state:"graph_command_token_is_not_declared",probe_id:"graph-unknown-subcommand",entrypoints:["graph"],expected_exit_class:"usage"},{state:"nested_command_token_is_not_declared_by_its_family",probe_id:"schema-unknown-subcommand",entrypoints:["schema"],expected_exit_class:"usage"},{state:"package_lifecycle_token_is_not_declared",probe_id:"package-unknown-action",entrypoints:["package"],expected_exit_class:"usage"}]},{code:"unsafe_init_recovery",exit_code:1,sources:["sdk/agent/tracker-preflight-contracts.ts"]},{code:"unsupported_update_option",exit_code:1,stable:!0,sources:["cli/error-guidance.ts"]},{code:"upsert_key_ambiguous",exit_code:4,sources:["sdk/structured-mutations.ts"]},{code:"upsert_key_conflict",exit_code:4,sources:["sdk/item-transaction.ts"]},{code:"upsert_key_duplicate",exit_code:2,sources:["sdk/item-transaction.ts","sdk/structured-mutations.ts"]},{code:"upsert_key_missing",exit_code:2,sources:["sdk/structured-mutations.ts"]},{code:"upsert_match_changed",exit_code:4,sources:["sdk/item-transaction.ts"]},{code:"validate_command_references_stale_pm_ids",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_files_missing_linked_paths",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_files_orphaned_paths",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_files_tracked_all_strict_forces_pm_internals",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_format_version_ahead_items",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"integrity_item_ahead_format_version"},{code:"validate_format_version_outdated_items",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"integrity_item_outdated_format_version"},{code:"validate_hierarchy_parent_cycle",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_hierarchy_parent_cycle_error",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_history_drift_chain_mismatches",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"history_drift_chain_mismatch"},{code:"validate_history_drift_hash_mismatches",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"history_drift_hash_mismatch"},{code:"validate_history_drift_missing_streams",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"history_drift_missing_stream"},{code:"validate_history_drift_unreadable_streams",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"history_drift_unreadable_stream"},{code:"validate_history_drift_version_skews",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"history_drift_version_skew"},{code:"validate_history_unknown_author_events",exit_code:2,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"history_unknown_author_events"},{code:"validate_lifecycle_active_closure_like_metadata",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_lifecycle_active_terminal_parent",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_lifecycle_dependency_cycles",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_lifecycle_dependency_cycles_error",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_lifecycle_stale_blockers",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_merge_decisions_unreviewed",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"validate_merge_driver_configuration",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"validate_merge_fence_drift",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_custom_profile_missing_required_fields",exit_code:2,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_duplicate_issue_codes",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_acceptance_criteria",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_close_reason",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_closed_at",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_confidence",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_estimate",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_release",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_reviewer",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_risk",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_sprint",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_resolution_missing_fields",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_storage_duplicate_item_ids",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_storage_history_conflict_markers",exit_code:4,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"integrity_history_conflict_marker"},{code:"validate_storage_resurrected_items",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_storage_tracked_runtime_cache_files",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"tracked_runtime_cache_files"},{code:"validate_storage_unparseable_config",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_storage_unparseable_history",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_storage_unreadable_items",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"vectorization_embedding_identity_changed",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"vectorization_stale_items_remaining",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"visible_surface_ceiling_exceeded",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"workflow_duplicate_type",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"workflow_policy_approval_history_invalid",exit_code:4,sources:["core/policy/workflow-policy-store.ts"]},{code:"workflow_policy_audit_failed",exit_code:4,sources:["core/policy/workflow-policy-store.ts"]},{code:"workflow_policy_input_unreadable",exit_code:4,sources:["core/policy/workflow-policy-store.ts"]},{code:"workflow_policy_invalid",exit_code:2,sources:["core/policy/workflow-policy.ts"]},{code:"workflow_policy_refused",exit_code:4,sources:["core/policy/workflow-policy-store.ts"]},{code:"workflow_policy_registry_invalid",exit_code:4,sources:["core/policy/workflow-policy-store.ts"]},{code:"workflow_status_unknown",exit_code:2,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"workflow_transition_malformed",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"workflow_type_empty",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"workflow_type_unknown",exit_code:2,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"workspace_history_chain_invalid",exit_code:4,sources:["core/history/workspace-history.ts"]},{code:"workspace_history_state_conflict",exit_code:4,stable:!0,sources:["core/history/workspace-history.ts"]},{code:"workspace_root_pm_path",exit_code:2,stable:!0,sources:["sdk/init.ts"]},{code:"workspace_snapshot_force_required",exit_code:2,sources:["sdk/workspace-snapshot.ts"]},{code:"workspace_snapshot_manifest_mismatch",exit_code:4,sources:["sdk/workspace-snapshot.ts"]},{code:"workspace_snapshot_name_reserved_fingerprint",exit_code:2,sources:["sdk/workspace-snapshot.ts"]},{code:"workspace_snapshot_not_found",exit_code:3,sources:["sdk/workspace-snapshot.ts"]},{code:"workspace_snapshot_permission_denied",exit_code:1,sources:["sdk/workspace-snapshot.ts"]},{code:"workspace_snapshot_resource_exhausted",exit_code:1,sources:["sdk/workspace-snapshot.ts"]},{code:"workspace_snapshot_storage_exhausted",exit_code:1,sources:["sdk/workspace-snapshot.ts"]},{code:"wrong_item_type",exit_code:2,stable:!0,sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"]}];(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b525d8c8-3a70-52bd-83db-c956aba0c6fb")}catch{}})();var fg=ug(mg([...pg,..._g]));(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="76c420db-b520-5fde-bd43-16a7324feb0a")}catch{}})();var IT=["mutation_receipt","entity","collection","diagnostic","stream"],OT=new Set(["append","claim","close","close-task","copy","create","delete","focus","pause-task","release","restore","start-task","update"]),LT=new Set(["close-many","update-many"]),DT=new Set(["activity","comments","contracts","events","history","learnings","list","notes","search"]),$T=new Set(["aggregate","deps","graph","health","history-redact","history-repair","history-compact","stats","validate"]);function Gr(e){if(e.command.trim().length===0)throw new TypeError("command must be a non-empty command path");if(!IT.includes(e.kind))throw new TypeError(`Unsupported output envelope kind: ${e.kind}`);return e}function hg(e){let t=e.trim().replace(/\s+/gu," "),[n=t]=t.split(" ");return LT.has(n)?Gr({command:t,kind:"collection",wrapper_key:"rows",cardinality:"many",format_flag:"--json"}):OT.has(n)?Gr({command:t,kind:"mutation_receipt",wrapper_key:null,cardinality:"one",format_flag:"--json"}):DT.has(n)?Gr({command:t,kind:"collection",wrapper_key:n==="contracts"?null:"items",cardinality:"many",format_flag:"--json"}):$T.has(n)?Gr({command:t,kind:"diagnostic",wrapper_key:null,cardinality:"none",format_flag:"--json"}):Gr({command:t,kind:n==="get"?"entity":"diagnostic",wrapper_key:n==="get"?"item":null,cardinality:n==="get"?"one":"none",format_flag:"--json"})}var NT=st.map(e=>hg(e)),MT=new Map(NT.map(e=>[e.command,e]));function gg(e){let t=e.trim().replace(/\s+/gu," ");if(t.length===0)throw new TypeError("command must be a non-empty command path");let[n=t]=Oi(t).split(" "),r=MT.get(n);return r?{...r,command:t}:hg(t)}function PT(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function FT(e){return PT(e)&&typeof e.id=="string"&&e.id.length>0&&typeof e.status=="string"&&e.status.length>0&&Number.isSafeInteger(e.changed_field_count)&&Number(e.changed_field_count)>=0&&(e.close_reason===void 0||typeof e.close_reason=="string")&&(e.deleted===void 0||typeof e.deleted=="boolean")&&(e.previous_status===void 0||typeof e.previous_status=="string")&&(e.warnings===void 0||Array.isArray(e.warnings))}function pq(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch(n){throw new TypeError(`Mutation receipt must be valid JSON: ${String(n)}`,{cause:n})}if(!FT(t))throw new TypeError("Mutation receipt must be a flat object with top-level id, status, and changed_field_count fields");return{id:t.id,status:t.status,changedFieldCount:t.changed_field_count,...typeof t.close_reason=="string"?{closeReason:t.close_reason}:{},...typeof t.deleted=="boolean"?{deleted:t.deleted}:{},...typeof t.previous_status=="string"?{previousStatus:t.previous_status}:{},...Array.isArray(t.warnings)?{warnings:t.warnings}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7c95b311-b408-50f7-87e8-2c2fa2323092")}catch{}})();var Mc=[{exit_code:m.SUCCESS,outcome:"effect",success:!0,meaning:"The requested operation completed with its intended effect."},{exit_code:m.GENERIC_FAILURE,outcome:"internal_failure",success:!1,meaning:"An unexpected runtime or internal failure prevented completion."},{exit_code:m.USAGE,outcome:"refused_input",success:!1,meaning:"The invocation was refused because its input or composition was invalid."},{exit_code:m.NOT_FOUND,outcome:"refused_tracker_state",success:!1,meaning:"The requested tracker, item, or resource was not present."},{exit_code:m.CONFLICT,outcome:"conflict",success:!1,meaning:"Current state or concurrency prevented the requested effect."},{exit_code:m.DEPENDENCY_FAILED,outcome:"dependency_failed",success:!1,meaning:"A required dependency operation failed."},{exit_code:m.NO_EFFECT,outcome:"no_effect",success:!0,meaning:"The request was valid and completed, but matched nothing to change."},{exit_code:m.PARTIAL_EFFECT,outcome:"partial_effect",success:!0,meaning:"The request completed and changed some, but not all, selected targets."}],yg=[m.SUCCESS,m.GENERIC_FAILURE,m.USAGE,m.NOT_FOUND,m.CONFLICT,m.DEPENDENCY_FAILED],jT=new Set(["close-many","update-many"]),vg=st.map(e=>({command:e,exit_codes:jT.has(e)?[...yg,m.NO_EFFECT,m.PARTIAL_EFFECT]:[...yg]})),wg=new Map(vg.map(e=>[e.command,e])),UT=[m.SUCCESS,m.NO_EFFECT,m.PARTIAL_EFFECT];function gq(e){return UT.includes(e)}function yq(e){return Mc.some(t=>t.exit_code===e)}function bg(e){let t=e.trim().toLowerCase().split(/\s+/u).filter(Boolean).join(" ");return wg.get(t)??wg.get(t.split(" ")[0])}function wq(e,t=st,n=vg){let r=new Map(n.map(c=>[c.command,c])),i=t.filter(c=>!r.has(c)),o=e.filter(c=>{let d=r.get(c.command)??r.get(c.command.split(" ")[0]);return d===void 0||!d.exit_codes.includes(c.exit_code)}),s=new Set(e.map(c=>c.exit_code)),a=[...new Set(n.flatMap(c=>c.exit_codes))].filter(c=>!s.has(c)).sort((c,d)=>c-d);return{ok:i.length===0&&o.length===0&&a.length===0,missing_commands:i,undeclared_observations:o,unreachable_exit_codes:a}}function vq(e){return e.applied===0&&e.failed>0?{outcome:"dependency_failed",exit_code:m.DEPENDENCY_FAILED}:e.applied===0?{outcome:"no_effect",exit_code:m.NO_EFFECT}:e.skipped>0||e.failed>0||e.unmatched>0?{outcome:"partial_effect",exit_code:m.PARTIAL_EFFECT}:{outcome:"effect",exit_code:m.SUCCESS}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="081bf1eb-4b9a-5fa9-a272-34ae781d250c")}catch{}})();var D=class extends TypeError{constructor(t){super(t),this.name="AssuranceMutationRefusalError"}},Le=class extends TypeError{context;constructor(t,n={}){super(t),this.name="AssuranceEvaluationRefusalError",this.context=n}},ut=class extends TypeError{measurement_id;source_kind;field;check;constructor(t,n){super(t),this.name="AssuranceSourceResolutionError",this.measurement_id=n.measurement_id,this.source_kind=n.source_kind,this.field=n.field,this.check=n.check}};async function qn(e){try{return await e()}catch(t){throw t instanceof D?new p(t.message,m.USAGE,{code:"invalid_argument_value",reason:"assurance_mutation_refused"}):t}}async function Pc(e){try{return await e()}catch(t){throw t instanceof Le?new p(t.message,m.USAGE,{code:"invalid_argument_value",reason:"assurance_evaluation_refused",...t.context}):t}}import{createHash as GT}from"node:crypto";import qT from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b00dcab2-22c6-55b7-b93d-f6f5413d4b04")}catch{}})();var Kn=1e3;(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="eaede7d4-43ae-5551-915e-19befefc29d0")}catch{}})();var Sg=1,yt=["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"],qr=["items","dependency_kind","prose_edge_gap","graph","validate","health","history","links","provider","derived"],KT=["ceiling","floor","equals","zero","monotone_nondecreasing","monotone_nonincreasing","subset_of"],WT=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,Lo=30,Do=5e3,Eg=4,zT=50;function wt(e,t){if(!WT.test(e))throw new D(`${t} must be a stable lowercase id`)}function BT(e,t){if(!Number.isFinite(e)||e<0)throw new D(`${t} must be a finite non-negative number`)}function Kr(e){let t=KT.filter(i=>e[i]!==void 0);if(t.length!==1)throw new D(`assertion ${e.id} must declare exactly one polarity`);let n=t[0],r=e[n];return{polarity:n,value:n==="zero"?0:r}}function jc(e,t){return Z(e)===Z(t)}function Tg(e,t){if(t.polarity==="equals")return jc(e,t.value);if(t.polarity==="subset_of"){if(!Array.isArray(e)||!Array.isArray(t.value))return!1;let r=t.value;return e.every(i=>r.includes(i))}if(typeof e!="number")return!1;let n=t.value;return t.polarity==="ceiling"||t.polarity==="monotone_nonincreasing"?e<=n:t.polarity==="floor"||t.polarity==="monotone_nondecreasing"?e>=n:e===0}function Cg(e){let t=Kr(e),n=e.negative_control.cases;return n.some(r=>r.expected==="pass")&&n.some(r=>r.expected==="fail")&&n.every(r=>Tg(r.observed,t)===(r.expected==="pass"))}function HT(e,t){if(e.polarity!==t.polarity)return!0;if(typeof e.value=="number"&&typeof t.value=="number")return e.polarity==="ceiling"||e.polarity==="monotone_nonincreasing"?t.value>e.value:e.polarity==="floor"||e.polarity==="monotone_nondecreasing"?t.value<e.value:t.value!==e.value;if(e.polarity==="subset_of"){let n=e.value,r=t.value;return!Array.isArray(n)||!Array.isArray(r)||r.some(i=>!n.includes(i))}return!jc(e.value,t.value)}function VT(e,t){if(e.measurement_id!==t.measurement_id||e.owner_item_id!==t.owner_item_id||Z(e.scope)!==Z(t.scope))return!0;let n={observe:0,warn:1,block:2},r=(e.lifetime??"hold")==="hold"&&(t.lifetime??"hold")==="retire";return HT(Kr(e),Kr(t))||n[t.enforcement]<n[e.enforcement]||r}function YT(e){if(e.state!==void 0&&!(e.state==="present"||e.state==="missing"))throw new D("items source state must be present or missing");let t=Object.hasOwn(e,"equals"),n=e.state!==void 0,r=Number(t)+Number(n);if(e.field!==void 0&&r!==1)throw new D("items source with field requires exactly one of equals or state");if(e.field===void 0&&r!==0)throw new D("items source equals/state requires field")}function JT(e){if(typeof e.dependency_kind!="string"||e.dependency_kind.trim().length===0)throw new D("dependency_kind source requires dependency_kind");if([e.source_kind,e.source_kind_prefix,e.source_kind_state].filter(t=>t!==void 0).length>1)throw new D("dependency_kind source accepts at most one source_kind predicate");if(e.source_kind!==void 0&&e.source_kind.trim().length===0||e.source_kind_prefix!==void 0&&e.source_kind_prefix.trim().length===0)throw new D("dependency_kind source provenance values must not be empty");if(e.source_kind_state!==void 0&&e.source_kind_state!=="present"&&e.source_kind_state!=="missing")throw new D("dependency_kind source source_kind_state must be present or missing")}function XT(e){if(e.sample_limit!==void 0&&(!Number.isInteger(e.sample_limit)||e.sample_limit<1))throw new D("prose_edge_gap sample_limit must be a positive integer");for(let t of e.exemptions??[]){if(typeof t.holder_id!="string"||t.holder_id.trim().length===0||typeof t.reason!="string"||t.reason.trim().length===0)throw new D("prose_edge_gap exemptions require holder_id and reason");if(t.target_id!==void 0&&t.target_id.trim().length===0||t.text_contains!==void 0&&t.text_contains.trim().length===0)throw new D("prose_edge_gap exemption selectors must not be empty")}}function Uc(e){wt(e.id,"measurement.id"),e.max_cost!==void 0&&BT(e.max_cost,"measurement.max_cost");let t=e.source;if(Object.prototype.toString.call(t)!=="[object Object]")throw new D(`measurement.source.kind must be one of ${qr.join(", ")}`);let n=Reflect.get(t,"kind");if(!qr.includes(n))throw new D(`measurement.source.kind must be one of ${qr.join(", ")}`);let r=t;if(r.kind==="items"&&YT(r),r.kind==="dependency_kind"&&JT(r),r.kind==="prose_edge_gap"&&XT(r),(r.kind==="graph"||r.kind==="validate"||r.kind==="health")&&(typeof r.field!="string"||r.field.trim().length===0))throw new D(`${r.kind} source requires field`);return r.kind==="provider"&&(wt(r.provider,"provider source provider"),wt(r.key,"provider source key")),e}function Gc(e){if(wt(e.id,"assertion.id"),wt(e.measurement_id,"assertion.measurement_id"),typeof e.owner_item_id!="string"||e.owner_item_id.trim().length===0)throw new D("assertion.owner_item_id is required");let t=Kr(e);if(typeof t.value=="number"&&!Number.isFinite(t.value))throw new D(`assertion.${t.polarity} must be a finite number`);if(e.lifetime==="retire"&&(typeof e.retire_reason!="string"||e.retire_reason.trim().length===0))throw new D("retired assertion requires retire_reason");e.scope.kind==="filter"&&wt(e.scope.measurement_id,"assertion.scope.measurement_id");let n=e.negative_control?.cases;if(!Array.isArray(n)||!n.some(r=>r.expected==="pass")||!n.some(r=>r.expected==="fail"))throw new D("assertion negative control requires pass and fail cases");if(!Cg(e))throw new D(`assertion ${e.id} negative control does not prove its bound`);return e}function QT(e){if(!Array.isArray(e.allowed_providers))throw new D("gate provider_policy.allowed_providers must be an array");for(let t of e.allowed_providers)wt(t,"gate.provider_policy.allowed_provider");if(typeof e.triggers!="object"||e.triggers===null||Array.isArray(e.triggers))throw new D("gate provider_policy.triggers must be an object");for(let[t,n]of Object.entries(e.triggers)){if(!yt.includes(t))throw new D(`gate provider policy has unknown trigger ${t}`);if(typeof n!="object"||n===null||!["low","medium","high"].includes(n.max_cost_class)||typeof n.allow_network!="boolean")throw new D(`gate provider policy trigger ${t} is invalid`)}}function Ag(e){if(wt(e.id,"gate.id"),!Array.isArray(e.assertion_ids))throw new D("gate.assertion_ids is required and must be an array");if(e.assertion_ids.length===0)throw new D("gate requires at least one assertion");for(let t of e.assertion_ids)wt(t,"gate.assertion_id");if(!Array.isArray(e.triggers))throw new D(`gate.triggers is required and must be an array of ${yt.join(", ")}`);if(e.triggers.length===0)throw new D("gate requires at least one trigger");for(let t of e.triggers)if(!yt.includes(t))throw new D(`gate trigger must be one of ${yt.join(", ")}`);return e.provider_policy&&QT(e.provider_policy),e}function Wn(e){if(e.version!==Sg)throw new D(`unsupported assurance document version ${String(e.version)}`);let t=new Set;for(let r of e.measurements){if(Uc(r),t.has(`measurement:${r.id}`))throw new D(`duplicate measurement ${r.id}`);t.add(`measurement:${r.id}`)}for(let r of e.assertions){if(Gc(r),t.has(`assertion:${r.id}`))throw new D(`duplicate assertion ${r.id}`);t.add(`assertion:${r.id}`)}for(let r of e.gates){Ag(r);let i=r.assertion_ids.filter(o=>!e.assertions.some(s=>s.id===o));if(i.length>0)throw new D(`gate ${r.id} references missing assertions: ${i.join(", ")}`);if(t.has(`gate:${r.id}`))throw new D(`duplicate gate ${r.id}`);t.add(`gate:${r.id}`)}let n=new Set(e.measurements.map(r=>r.id));for(let[r,i]of xg(e))if(!n.has(r))throw new D(`${i.join(", ")} references missing measurement ${r}`);return e}function qc(e,t){if("measurement"in e){t.push(e.measurement);return}if("operator"in e)for(let n of e.operands)qc(n,t)}function xg(e){let t=new Map,n=(r,i)=>{let o=t.get(r)??[];o.push(i),t.set(r,o)};for(let r of e.assertions)n(r.measurement_id,`assertion ${r.id}`),r.scope.kind==="filter"&&n(r.scope.measurement_id,`assertion ${r.id} scope`);for(let r of e.measurements){if(r.source.kind!=="derived")continue;let i=[];qc(r.source.expression,i);for(let o of i)n(o,`derived measurement ${r.id}`)}return t}function ZT(e,t){let n=e.assertion_ids.flatMap(o=>{let s=t.assertions.find(a=>a.id===o);return[s.measurement_id,...s.scope.kind==="filter"?[s.scope.measurement_id]:[]]}),r=new Set,i=new Set;for(;n.length>0;){let o=n.pop();if(r.has(o))continue;r.add(o);let s=t.measurements.find(a=>a.id===o);s.source.kind==="provider"?i.add(s.source.provider):s.source.kind==="derived"&&qc(s.source.expression,n)}return i}function Wr(){return{version:Sg,measurements:[],assertions:[],gates:[]}}function eC(e,t){let n=t.items.filter(r=>(e.statuses===void 0||e.statuses.includes(r.status))&&(e.types===void 0||e.types.includes(r.type))&&(e.tags===void 0||e.tags.every(i=>r.tags?.includes(i)))&&(e.field===void 0||(()=>{let i=r[e.field];if(e.state!==void 0){let o=i==null||i===""||Array.isArray(i)&&i.length===0;return e.state==="missing"?o:!o}return jc(i,e.equals)})()));return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(r=>r.id)}}function tC(e,t){return e.source_kind!==void 0?t?.toLowerCase()===e.source_kind.trim().toLowerCase():e.source_kind_prefix!==void 0?t?.toLowerCase().startsWith(e.source_kind_prefix.trim().toLowerCase())===!0:e.source_kind_state==="present"?t!==void 0&&t.length>0:e.source_kind_state==="missing"?t===void 0||t.length===0:!0}function nC(e,t){let n=[],r=wr(e.dependency_kind)??e.dependency_kind.trim().toLowerCase();for(let i of t.items)for(let o of i.dependencies??[]){let s=wr(o.kind)??o.kind.trim().toLowerCase(),a=o.source_kind?.trim();s===r&&tC(e,a)&&n.push(`${i.id}->${o.id}${a?`@${a}`:""}`)}return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n}}function rC(e){let t=[e.description,e.body].filter(n=>typeof n=="string").map(n=>n.trim()).filter(Boolean);for(let n of["comments","notes","learnings"]){let r=e[n];if(Array.isArray(r)){for(let i of r)if(typeof i=="string")t.push(i);else if(typeof i=="object"&&i!==null){let o=Reflect.get(i,"text");typeof o=="string"&&t.push(o)}}}return t}function iC(e,t,n,r){return e.some(i=>i.holder_id.trim().toLowerCase()===t.toLowerCase()&&(i.target_id===void 0||i.target_id.trim().toLowerCase()===n.toLowerCase())&&(i.text_contains===void 0||r.toLowerCase().includes(i.text_contains.trim().toLowerCase())))}function Fc(e,t){return[e.toLowerCase(),t.toLowerCase()].sort().join("\0")}function oC(e){let t=new Map,n=new Set,r=[],i=/(?<![\w-])[a-z0-9]+(?:-+[a-z0-9]+)+(?![\w-])/giu,o=0;for(let s of e){t.set(s.id.toLowerCase(),s.id);for(let a of s.dependencies??[])n.add(Fc(s.id,a.id));for(let a of[s.parent,s.blocked_by])typeof a=="string"&&n.add(Fc(s.id,a));for(let a of rC(s)){let c=[...a.matchAll(i)].map(d=>d[0]);o+=c.length,r.push({holder_id:s.id,segment:a,mentioned_ids:c})}}return{canonical_ids:t,linked_pairs:n,prose_mentions:r,mention_count:o}}function sC(e,t){let n=oC(t.items),r=new Map;for(let s of n.prose_mentions){let a=s.mentioned_ids.map(d=>n.canonical_ids.get(d.toLowerCase())).filter(d=>d!==void 0&&d!==s.holder_id),c=[...new Set(a)];for(let d of c){let l=Fc(s.holder_id,d);if(n.linked_pairs.has(l)||iC(e.exemptions??[],s.holder_id,d,s.segment))continue;let u=c.some(_=>_!==d);r.get(l)?.explicit===!0&&!u||r.set(l,{contributor:`${s.holder_id}->${d}|subject=${u?"explicit":"implicit"}`,explicit:u})}}let i=[...r.values()],o=i.map(s=>s.contributor).sort();return{value:o.length,population_size:n.canonical_ids.size,cost:t.items.length+n.linked_pairs.size+n.mention_count,contributors:o.slice(0,e.sample_limit??25),partitions:{explicit_subject:i.filter(s=>s.explicit).length,implicit_subject:i.filter(s=>!s.explicit).length}}}function aC(e,t){return{value:t.history.filter(n=>(e.op===void 0||n.op===e.op)&&(e.author===void 0||n.author===e.author)&&(e.harness===void 0||n.agent_harness===e.harness)&&(e.model===void 0||n.agent_model===e.model)).length,population_size:t.history.length,cost:t.history.length}}function cC(e,t){let n=t.items.filter(r=>{let i=r[e.link],o=Array.isArray(i)&&i.length>0;return e.state==="present"?o:!o});return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(r=>r.id)}}function dC(e,t){let n=e.source;return n.kind==="items"?eC(n,t):n.kind==="dependency_kind"?nC(n,t):n.kind==="prose_edge_gap"?sC(n,t):n.kind==="history"?aC(n,t):n.kind==="links"?cC(n,t):null}function Rg(e,t){return e.reduce((n,r)=>({units:n.units+r.units,items_scanned:n.items_scanned+r.items_scanned,history_entries:n.history_entries+r.history_entries,provider_calls:n.provider_calls+r.provider_calls,duration_ms:t}),{units:0,items_scanned:0,history_entries:0,provider_calls:0,duration_ms:t})}function lC(e,t){if(t.length===0)throw new TypeError(`derived ${e} requires operands`);if(e==="add")return t.reduce((n,r)=>n+r,0);if(e==="subtract")return t.slice(1).reduce((n,r)=>n-r,t[0]);if(e==="multiply")return t.reduce((n,r)=>n*r,1);if(e==="divide"){if(t.slice(1).includes(0))throw new TypeError("derived divide cannot divide by zero");return t.slice(1).reduce((n,r)=>n/r,t[0])}return e==="min"?Math.min(...t):Math.max(...t)}async function Ig(e,t,n){let r=new Array(e.length),i=0,o=Array.from({length:Math.min(t,e.length)},async()=>{for(;i<e.length;){let s=i;i+=1,r[s]=await n(e[s],s)}});return await Promise.all(o),r}async function Og(e,t,n,r,i){if("literal"in e)return{value:e.literal,costs:[],population_size:0,contributors:[]};if("measurement"in e){let s=n.find(d=>d.id===e.measurement);if(!s)throw new TypeError(`derived measurement references missing ${e.measurement}`);let a=await Lg(s,t,n,r,i);if(typeof a.value!="number")throw new TypeError(`derived measurement ${s.id} is not numeric`);let c=i.charged.has(s.id)?[]:[a.cost];return i.charged.add(s.id),{value:a.value,costs:c,population_size:a.population_size,contributors:a.contributors}}let o=await Ig(e.operands,Eg,s=>Og(s,t,n,r,i));return{value:lC(e.operator,o.map(s=>s.value)),costs:o.flatMap(s=>s.costs),population_size:Math.max(0,...o.map(s=>s.population_size)),contributors:[...new Set(o.flatMap(s=>s.contributors))]}}async function uC(e,t,n,r,i){Uc(e);let o=Date.now(),s,a=[],c=0;if(e.source.kind==="derived"){let u=await Og(e.source.expression,t,n,[...r,e.id],i);s={value:u.value,population_size:u.population_size,cost:0,contributors:u.contributors},a=u.costs}else{let u=dC(e,t);u!==null?s=u:(s=await t.external(e.source),c=1)}let d={units:s.cost,items_scanned:e.source.kind==="items"||e.source.kind==="dependency_kind"||e.source.kind==="prose_edge_gap"||e.source.kind==="links"?t.items.length:0,history_entries:e.source.kind==="history"?t.history.length:0,provider_calls:c,duration_ms:Date.now()-o},l=Rg([...a,d],Date.now()-o);if(e.max_cost!==void 0&&l.units>e.max_cost)throw new Le(`measurement ${e.id} exceeded cost ceiling ${e.max_cost} with ${l.units}`);return{id:e.id,definition_fingerprint:`sha256:${GT("sha256").update(Z(e)).digest("hex")}`,value:s.value,population_size:s.population_size,cost:l,contributors:s.contributors??[],...s.partitions?{partitions:s.partitions}:{}}}function Lg(e,t,n,r,i){if(r.includes(e.id))throw new TypeError(`derived measurement cycle: ${[...r,e.id].join(" -> ")}`);let o=i.cache.get(e.id);if(o)return o;let s=uC(e,t,n,r,i).catch(a=>{if(a instanceof ut&&a.measurement_id===void 0){let c={measurement_id:e.id,source_kind:a.source_kind,field:a.field,...a.check?{check:a.check}:{}},d=new ut(a.message,c);throw d.cause=a,d}throw a});return i.cache.set(e.id,s),s}async function Kc(e,t,n=[e]){return Lg(e,t,n,[],{cache:new Map,charged:new Set})}function mC(e,t){return typeof e!="number"||typeof t.value!="number"?null:t.polarity==="ceiling"||t.polarity==="monotone_nonincreasing"?t.value-e:(t.polarity==="floor"||t.polarity,e-t.value)}function pC(e,t,n={}){Gc(e);let r=Kr(e),i=e.lifetime==="retire"&&n.owner_terminal===!0;return{assertion_id:e.id,measurement_id:e.measurement_id,measurement_definition_fingerprint:t.definition_fingerprint,scope:e.scope,population_size:t.population_size,observed:t.value,bound:r,distance:mC(t.value,r),verdict:i?"retired":Tg(t.value,r)?"pass":"fail",enforcement:e.enforcement,negative_control_proven:Cg(e),cost:t.cost,contributors:t.contributors,...t.partitions?{partitions:t.partitions}:{}}}function _C(e,t,n,r){let i=ZT(e,t);if(i.size===0)return;let o=e.provider_policy,s=o?.triggers[r];if(!o||!s)throw new Le(`assurance gate ${e.id} refuses provider execution at trigger ${r} without an explicit provider policy`);let a=new Set(o.allowed_providers),c={low:0,medium:1,high:2};for(let d of i){if(!a.has(d))throw new Le(`assurance gate ${e.id} refuses provider ${d}`);let l=n.provider_capabilities?.[d];if(!l)throw new Le(`assurance provider ${d} has no declared capabilities`);if(c[l.cost_class]>c[s.max_cost_class])throw new Le(`assurance gate ${e.id} refuses ${l.cost_class}-cost provider ${d} at trigger ${r}`);if(l.network&&!s.allow_network)throw new Le(`assurance gate ${e.id} refuses network provider ${d} at trigger ${r}`)}}async function kg(e,t,n,r,i){try{return await Kc(n,r,i)}catch(o){if(o instanceof ut){let s=o.check?` check ${o.check}`:"",a=o.measurement_id??n.id,c=new Le(`assurance gate ${e} assertion ${t} measurement ${a} source ${o.source_kind}${s} field ${o.field} could not resolve: ${o.message}`,{gate_id:e,assertion_id:t,measurement_id:a,source_kind:o.source_kind,field:o.field,...o.check?{check:o.check}:{}});throw c.cause=o,c}throw o}}async function Dg(e,t,n,r){Wn(t);let i=t.gates.find(c=>c.id===e);if(!i)throw new Le(`assurance gate ${e} not found`);if(!i.triggers.includes(r.trigger))throw new Le(`assurance gate ${e} does not declare trigger ${r.trigger}`);_C(i,t,n,r.trigger);let o=await Ig(i.assertion_ids,Eg,async c=>{let d=t.assertions.find(f=>f.id===c),l=t.measurements.find(f=>f.id===d.measurement_id),u=n;if(d.scope.kind==="active"){let f=new Set(n.terminal_statuses??["closed","canceled"]);u={...n,items:n.items.filter(g=>!f.has(g.status))}}else if(d.scope.kind==="filter"){let f=d.scope.measurement_id,g=t.measurements.find(v=>v.id===f),y=await kg(i.id,d.id,g,n,t.measurements),w=new Set(y.contributors);u={...n,items:n.items.filter(v=>w.has(v.id))}}let _=n.items.find(f=>f.id===d.owner_item_id),h=_!==void 0&&new Set(n.terminal_statuses??["closed","canceled"]).has(_.status);return pC(d,await kg(i.id,d.id,l,u,t.measurements),{owner_terminal:h})}),s=o.some(c=>c.verdict==="fail"&&c.enforcement==="block"),a=o.some(c=>c.verdict==="fail"&&c.enforcement==="warn");return{gate_id:i.id,tree_id:n.tree_id,trigger:r.trigger,dry_run:r.dry_run===!0,evaluated_at:new Date().toISOString(),verdict:s?"block":a?"warn":"pass",exit_code:s?1:0,assertions:o,assertions_total:o.length,row_contract:{row_keys:["assertions"],jq_selector:".assertions[]"},cost:Rg(o.map(c=>c.cost),Math.max(0,...o.map(c=>c.cost.duration_ms)))}}function $o(e){return qT.join(e,"assurance.json")}async function $g(e){let t=await Q($o(e));return t===null?Wr():No(t)}function No(e){try{return Wn(JSON.parse(e))}catch(t){throw new p("The assurance registry is invalid. Repair or restore .agents/pm/assurance.json and retry.",m.GENERIC_FAILURE,{code:"assurance_registry_invalid",reason:String(t),nextSteps:["Restore a valid assurance.json from version control or repair its declaration references.","Run pm assurance list measurement after the repair."]})}}function Mo(e,t){return t==="measurement"?e.measurements:t==="assertion"?e.assertions:e.gates}function fC(e,t){e==="measurement"?Uc(t):e==="assertion"?Gc(t):Ag(t)}async function zr(e,t){let n=structuredClone(Mo(await $g(e),t));return{items:n,count:n.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function Ng(e,t,n){let r=Mo(await $g(e),t).find(i=>i.id===n);if(!r)throw new Le(`assurance ${t} ${n} not found`);return structuredClone(r)}async function Po(e,t,n,r={}){fC(t,n);let i=await x(e),o=U(r.author,i.author_default),s=await On({pmRoot:e,filePath:$o(e),op:`assurance:${t}:put`,author:o,message:r.message,lockTtlSeconds:Lo,lockWaitMs:Do,mutate:a=>{let c=a===null?Wr():No(a),d=Mo(c,t),l=d.findIndex(_=>_.id===n.id),u=l<0?"created":"updated";if(t==="assertion"&&l>=0&&VT(d[l],n)){let _=n.authorization_decision;if(!_||!r.authorized_decision_ids?.includes(_))throw new D(`loosening assertion ${n.id} requires a verified authorization_decision`)}return l<0?d.push(structuredClone(n)):d[l]=structuredClone(n),Wn(c),{raw:`${JSON.stringify(c,null,2)}
|
|
3
|
-
`,result:{changed:!0,action:u,kind:t,id:n.id}}}});return{...s.result,changed:s.changed}}async function
|
|
4
|
-
`,result:{changed:d.length>0,created_ids:d,unchanged_ids:l}}}});return{...s.result,changed:s.changed}}async function Mg(e,t,n,r={}){let i=await x(e),o=U(r.author,i.author_default),s=await
|
|
5
|
-
`,result:{changed:!0,action:"removed",kind:t,id:n}}}});return{...s.result,changed:s.changed}}async function Pg(e,t,n={}){if(t.dry_run)throw new TypeError("dry-run assurance verdicts are not persisted");let r=await x(e);await In({pmRoot:e,op:"assurance:gate:verdict",author:U(n.author,r.author_default),context:{assurance_verdict:t},message:n.message??`Assurance gate ${t.gate_id} returned ${t.verdict}`,lockTtlSeconds:Lo,lockWaitMs:Do})}async function Fg(e,t={}){let n=t.limit??zT;if(!Number.isInteger(n)||n<1||n>Kn)throw new TypeError(`assurance verdict limit must be an integer from 1 through ${Kn}`);return(await Jt(Er(e),Xt)).reverse().filter(r=>r.op==="assurance:gate:verdict").map(r=>r.context?.assurance_verdict).filter(r=>typeof r=="object"&&r!==null&&"gate_id"in r).filter(r=>t.gate_id===void 0||r.gate_id===t.gate_id).slice(0,n)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="78b20f7a-4ae7-5811-9ab7-049a07d844e5")}catch{}})();var hC=_c("list").properties.outputSession,gC={outputInclude:{type:"string",minLength:1,description:"Comma-separated fields or sections retained by any built-in read action."},outputLimit:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}],description:"Universal read row ceiling, or unbounded to disable the shared ceiling."},outputBudget:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}],description:"Universal estimated-token ceiling, or unbounded to return the complete read result."},outputFormat:{type:"string",enum:["json","toon"],description:"Universal read-result encoding selector."},outputSession:{...hC},outputCursor:{type:"string",minLength:1,description:"Opaque continuation cursor returned after budget compaction of a declared row collection."}},jg={definition:{anyOf:[{type:"object"},{type:"string"}],description:"Policy declaration for policy-put, or proposed metadata for policy-check; structured JSON or JSON text."},policy:{type:"string",description:"Approval policy id for policy-approve."},message:{type:"string",description:"History explanation for policy mutations and approvals."},dryRun:{type:"boolean",description:"Preview registry changes without writing; policy-approve rejects previews."}},Ug={type:"object",properties:{cwd:{type:"string",description:"Workspace directory to run the native pm operation in. Defaults to the MCP server process cwd."},path:{type:"string",description:"Optional pm data root, equivalent to PM_PATH/global --path. Leave unset for real repository tracking."},author:{type:"string",description:"Optional mutation author override. Otherwise pm uses PM_AUTHOR, project settings, or detected harness identity."},tokenAccounting:{type:"boolean",description:"Attach the same bounded per-section token-cost receipt emitted by CLI --token-accounting."}},additionalProperties:!0},_e={type:"string",description:"pm item id, for example pm-abc1."},yC=`Operation name (one of): ${Ra.join(", ")}. Package-owned actions are available dynamically when their provider package is installed.`,wC={status:{type:"string",description:"Alias for options.status."},type:{type:"string",description:"Alias for options.type."},tag:{type:"string",description:"Alias for options.tag."},priority:{type:"string",description:"Alias for options.priority."},limit:{type:["string","number"],description:"Alias for options.limit."},offset:{type:["string","number"],description:"Alias for options.offset."}},vC={mode:{type:"string",description:"Alias for options.mode."},status:{type:"string",description:"Alias for options.status."},type:{type:"string",description:"Alias for options.type."},tag:{type:"string",description:"Alias for options.tag."},priority:{type:"string",description:"Alias for options.priority."},limit:{type:["string","number"],description:"Alias for options.limit."}};function z(e,t=[]){return{...Ug,properties:{...Ug.properties,...e},required:t}}var bC=[{name:"pm_run",description:"Run any supported pm operation natively through the pm library. Use this for commands not covered by narrower pm_* tools.",inputSchema:z({action:{type:"string",enum:[...Ra],description:yC},id:_e,query:{type:"string",description:"Search query for action=search."},reason:{type:"string",description:"Close reason for action=close."},force:{type:"boolean",description:"Force ownership/terminal-state override when supported."},subcommand:{type:"string",description:"Subcommand selector for actions that take one (for example telemetry, or schema \u2014 prefer the dedicated pm_schema tool for schema operations)."},options:{type:"object",description:"Underlying pm command options using camelCase keys."},fullChangedFields:{type:"boolean",description:"For mutation actions, return the full changed_fields array instead of the default changed_field_count."},idOnly:{type:"boolean",description:"For single-item mutation actions, return only id and status."},...gC},["action"])},{name:"pm_discover",description:"Discover the smallest relevant authorized pm tool catalog under an explicit token budget. Ranking is deterministic and returns public lexical, semantic, graph, permission, freshness, and usage signal explanations. Continue with next_cursor; set includeSchema=true only when complete input schemas are needed.",inputSchema:z({query:{type:"string",maxLength:4096,description:"Free-text capability intent. Empty text lists by stable policy order."},family:{type:"string",enum:["workspace","intake","context","lifecycle","evidence","graph","quality","automation","extensions","internal"],description:"Optional stable capability-family filter."},tier:{type:"string",enum:["core","standard","full"],description:"Maximum command visibility tier included in results."},limit:{type:"integer",minimum:1,maximum:100,description:"Maximum result rows; defaults to 10."},cursor:{type:"string",minLength:1,maxLength:4096,description:"Opaque next_cursor from an equivalent discovery request."},includeSchema:{type:"boolean",description:"Include complete tool input schemas; false by default."},outputBudget:{anyOf:[{type:"integer",minimum:128},{const:"unbounded"}],description:"Estimated-token ceiling; defaults to 1200."}})},{name:"pm_context",description:"Return the agent-oriented project context snapshot. Pass options.depth=brief|standard|deep|full (full = every section with no per-section row cap), options.parent='<id>' to scope the snapshot to one item's subtree (the item plus all descendants), options.fields='id,title,priority' to project focus rows to a field subset for low-token reads, or options.section=['hierarchy','progress',...] to pick sections.",inputSchema:z({options:{type:"object"}})},{name:"pm_next",description:"Recommend the next actionable work item: the single highest-priority READY item (active status, no open blockers, no open children; completed containers surface only when no concrete leaf work is ready) plus the ranked ready and blocked queues. The recommended item carries a rationale and each blocked item lists the open blockers gating it. Pass options.parent='<id>' to scope to one subtree, options.limit=N to cap ready rows, options.readyOnly=true to omit the blocked list, or filters (options.type/tag/priority/assignee/sprint/release). The most token-efficient 'what should I do now?' read for agents.",inputSchema:z({options:{type:"object"}})},{name:"pm_search",description:"Search pm items with keyword, semantic, or hybrid search. Defaults to a compact projection for token efficiency. Pass options.mode=keyword|semantic|hybrid (default follows search.default_mode: auto runs hybrid when semantic search is configured and runnable, else keyword; the result reports mode_source), options.limit=N to cap hits, options.status='all' for no lifecycle restriction, options.fields='id,title,score' for a custom projection, or options.full=true for full item bodies (can be large). The result echoes the applied filters and projection mode in query_summary.",inputSchema:z({query:{type:"string"},options:{type:"object"},...vC},["query"])},{name:"pm_list",description:"List pm items with status/type/tag/priority filters. Defaults to compact projection for token efficiency. options.status accepts CSV (all,open,in_progress). Pass options.compact=false or options.includeBody=true for full bodies/comments. Pass options.brief=true for ultra-terse (id/status/type/title only). Pass options.fields='id,title,priority' for custom projection. Pass options.limit=N to cap row count. The result echoes the applied filters and projection mode in query_summary.",inputSchema:z({options:{type:"object"},...wC})},{name:"pm_get",description:"Read one pm item with shared SDK projections. Pass options.depth='brief' or options.fields='id,title,status' for low-token inspection, options.fields='id,schedule.start_at' for schedule context, or options.at='7' / an ISO timestamp for a verified mutation-free historical read. Parent results include bounded child counts, samples, and continuation metadata.",inputSchema:z({id:_e,options:{type:"object",description:"Get options such as depth=brief|standard|deep|full, fields=id,title,status, or at=<version|ISO timestamp>."}},["id"])},{name:"pm_events",description:"Read a bounded, cursor-resumable page of committed mutation events across item history streams. Batch cursors are the token-efficient default; pass cursorMode=row for per-event checkpoints.",inputSchema:z({verify:{type:"boolean",description:"Verify complete selected authoritative history chains."},since:{type:"string",description:"Durable event cursor or ISO timestamp lower bound."},type:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},author:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},item:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},limit:{type:"integer",minimum:0,maximum:1e3},full:{type:"boolean"},cursorMode:{type:"string",enum:["batch","row"],description:"Cursor framing: batch returns one terminal next_cursor (default); row also adds a cursor to every event."}})},{name:"pm_create",description:"Create a pm item natively and write pm history. Output is compact by default (changed_fields replaced with changed_field_count for token efficiency); pass fullChangedFields=true for the full changed_fields array.",inputSchema:z({fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},allowMissingParent:{type:"boolean",description:"Allow unresolved parent references and emit a validation warning."},allowDuplicate:{type:"boolean",description:"Explicitly create when strict similarity governance finds likely duplicates."},options:{type:"object",description:"Create options. title and description are required."}},["options"])},{name:"pm_mutate",description:"Apply an ordered create/update/close/release batch atomically through the public pm SDK. Create rows may declare ref and omit id; @ref forward references resolve deterministically from the stable transactionId, which is derived from the batch when omitted. Bulk creation: rows shaped as {item:{title,type,...}} are create documents using pm create field names; upsertKey updates the existing item whose field matches instead of creating a duplicate. Set dryRun=true to validate and preview without writes.",inputSchema:z({transactionId:{type:"string",description:"Stable idempotency key for this atomic mutation batch; derived from the batch content when omitted."},mutations:{type:"array",minItems:1,description:"Ordered rows shaped as {op:create|update|close|release,id?,ref?,options?,reason?} or create documents {ref?,item:{...}}.",items:{type:"object",properties:{op:{type:"string",enum:["create","update","close","release"],description:"Operation; omitted rows carrying item are creates."},id:_e,ref:{type:"string",description:"Batch-local create alias; its deterministic id can be referenced as @alias by any row."},reason:{type:"string"},options:{type:"object"},item:{type:"object",description:"Create document using pm create field names (title, type, description, body, tags, parent, custom fields)."},unique:{type:"object",description:"Create-only guard {key,value} re-checked under the writer lock; keyed upsert sets it on rows that matched nothing at planning time."},match:{type:"object",description:"Update-only guard {key,value} re-read under the writer lock; keyed upsert sets it on rows it converted into updates of a matched item."}},additionalProperties:!1}},upsertKey:{type:"string",description:"Item field whose value identifies an existing item to update instead of creating a duplicate."},dryRun:{type:"boolean",description:"Validate and preview without writing."},createCompensation:{type:"string",enum:["close","delete"],description:"How a failed batch compensates created items; defaults to close."},lockTtlSeconds:{type:"number"},lockWaitMs:{type:"number"}},["mutations"])},{name:"pm_copy",description:"Copy an existing pm item into a new id while resetting lifecycle fields. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:z({id:_e,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object",description:"Copy options such as title override, author, and message."}},["id"])},{name:"pm_focus",description:"Set, clear, or show the session focused item. When focused, pm_create defaults its parent to the focused item (an explicit parent still overrides). Pass id to focus an item, options.clear=true to clear, or neither to show current focus.",inputSchema:z({id:_e,clear:{type:"boolean",description:"Clear the focused item (cannot be combined with id)."},options:{type:"object",description:"Focus options such as clear (boolean)."}},[])},{name:"pm_update",description:"Update pm item metadata/body/dependencies/log seeds natively. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields delta.",inputSchema:z({id:_e,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object"}},["id","options"])},{name:"pm_append",description:"Append markdown text to a pm item body and write pm history. Useful for seeding evidence/log entries before close. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:z({id:_e,body:{type:"string",description:"Markdown text to append to the item body. Required here or as options.body."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object",description:"Append options such as body, author, and message."}},["id"])},{name:"pm_claim",description:"Claim a pm item.",inputSchema:z({id:_e,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_release",description:"Release a pm item claim.",inputSchema:z({id:_e,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_close",description:"Close a pm item with optional close reason and optional close validation (reason requirement follows governance settings). Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:z({id:_e,reason:{type:"string",description:"Close reason text when provided or required by governance settings."},duplicateOf:{type:"string",description:"Canonical item id when closing this item as a duplicate."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object"}},["id"])},{name:"pm_comments",description:'List, add, edit, or delete comments on a pm item. Use options.add to append, options.edit=<1-based index> with replacement text to fix a comment, or options.delete=<1-based index> to remove one. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. List calls return the newest comments that fit the output budget, with total_count/has_more metadata and a next_cursor that pages back to older comments through outputCursor; without options.limit or outputLimit, outputBudget "unbounded" returns the complete listing at once. Pass options.limit=N for only the newest N comments (next_cursor pages within that window when the budget trims it; has_more reports older comments beyond it without a cursor) or options.limit=0 for summary-only metadata; options.full=true returns the complete history after a write. Rows carry their absolute index; pair edit/delete with options.expectAt to refuse a different entry.',inputSchema:z({id:_e,options:{type:"object"}},["id"])},{name:"pm_files",description:"List, add, remove, or validate linked files for a pm item.",inputSchema:z({id:_e,options:{type:"object"}},["id"])},{name:"pm_docs",description:"List, add, or remove linked docs for a pm item.",inputSchema:z({id:_e,options:{type:"object"}},["id"])},{name:"pm_notes",description:"List, add, edit, or delete structured notes on a pm item. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. Omit mutation options to list existing notes; rows carry their absolute index, and options.expectAt guards edit/delete.",inputSchema:z({id:_e,options:{type:"object"}},["id"])},{name:"pm_learnings",description:"List, add, edit, or delete learnings on a pm item. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. Omit mutation options to list existing learnings; rows carry their absolute index, and options.expectAt guards edit/delete.",inputSchema:z({id:_e,options:{type:"object"}},["id"])},{name:"pm_deps",description:"Read dependency trees/graphs or one bounded explainable relationship context packet. Use options.format=context with direction, kind, depth, node, edge, token, and cursor bounds; context returns a counts-first summary, per-node roles/reasons, root evidence pointers, and enumerated missing references.",inputSchema:z({id:_e,options:{type:"object"}},["id"])},{name:"pm_graph",description:"Run bounded workspace relationship-graph queries: ancestors/descendants (hierarchy), predecessors/successors (ordering), paths, impact (blast radius), analyze (execution + knowledge analytics), audit (governance findings with change-since-baseline deltas), communities (label-propagation clusters), redundancy (transitively implied edges), dominators (structural bottlenecks), slack (critical-path method float per task), centrality (betweenness/closeness/degree with directed fan-in/out), articulation (cut points and bridges \u2014 single points of failure), plan (dry-run remediation proposals derived from the audit), and index (durable cross-process graph index status/rebuild/clear). Traversals, paths, impact, and dominators require id; paths also requires target. Options support kind, maxDepth, limit, after, direction, maxPaths, sample, exemptIsolate, exemptIsolateType, saveBaseline (audit), rebuild/clear (index), and counts-first summary.",inputSchema:z({subcommand:{type:"string",enum:[...Ku]},id:_e,target:_e,options:{type:"object"}},["subcommand"])},{name:"pm_test",description:"List, add, remove, or run linked tests for a pm item.",inputSchema:z({id:_e,options:{type:"object"}},["id"])},{name:"pm_validate",description:"Run pm validation checks.",inputSchema:z({options:{type:"object"}})},{name:"pm_health",description:"Run pm health diagnostics. Pass options.brief=true for compact low-token details, options.skipIntegrity=true, options.skipDrift=true, options.skipVectors=true for a fast status-only check, or options.full=true for the complete deep check.",inputSchema:z({options:{type:"object"}})},{name:"pm_contracts",description:"Inspect pm command, flag, schema, and availability contracts.",inputSchema:z({options:{type:"object"}})},{name:"pm_schema",description:"Inspect or modify the workspace item-type/status/field schema (pm schema). subcommand selects the operation; name carries the item type name (show/add-type/remove-type), status id (show-status/add-status/remove-status), or field key (show-field/add-field/remove-field). apply-preset adopts a domain type preset; add-type with infer=true derives types from title-prefix conventions. Policy verbs author declarations, preview changes, set enforcement, and record content-bound approvals. Registry mutations write workspace history; approvals write item history.",inputSchema:z({...jg,subcommand:{type:"string",enum:["list","show","show-status","add-type","remove-type","add-status","remove-status","add-field","remove-field","list-fields","show-field","apply-preset",...Mu],description:"Schema subcommand to run."},name:{type:"string",description:"Item type name, status id, field key, policy id, or item id for the selected schema verb; policy-mode requires advise|refuse."},description:{type:"string",description:"Custom item type, status, or field description for add-type/add-status/add-field."},defaultStatus:{type:"string",description:"Default status for add-type."},folder:{type:"string",description:"Storage folder for add-type."},alias:{type:"array",items:{type:"string"},description:"Aliases for add-type/add-status, or extra CLI flag aliases for add-field."},role:{type:"array",items:{type:"string",enum:[...Oa]},description:`Lifecycle roles for add-status: ${Oa.join(", ")}.`},order:{type:"number",description:"Display/sort order for add-status."},fieldType:{type:"string",enum:["string","number","boolean","string_array"],description:"Value type for a custom field (add-field)."},commands:{type:"array",items:{type:"string"},description:"Commands a custom field is wired onto (add-field): create, update, update_many, list, search, calendar, context."},cliFlag:{type:"string",description:"Override the auto-derived CLI flag for a custom field (add-field)."},required:{type:"boolean",description:"Mark a custom field as always required (add-field)."},requiredOnCreate:{type:"boolean",description:"Mark a custom field as required at create time (add-field)."},allowUnset:{type:"boolean",description:"Whether a custom field may be cleared via --unset (add-field); defaults to true."},requiredTypes:{type:"array",items:{type:"string"},description:"Restrict a custom field's requirement to specific item types (add-field)."},typePreset:{type:"string",enum:["agile","ops","research"],description:"Domain type preset to adopt (apply-preset)."},infer:{type:"boolean",description:"Infer item types from title-prefix conventions (add-type); previews unless apply is true."},minCount:{type:"number",description:"Minimum items sharing a prefix for add-type inference (default 10)."},apply:{type:"boolean",description:"Register inferred types (add-type infer); without it the call previews only."},force:{type:"boolean",description:"Override removal guardrails for destructive schema changes when supported."},options:{type:"object",description:"Additional schema options using camelCase keys.",properties:jg}},["subcommand"])},{name:"pm_profile",description:"List, show, apply, or lint project profiles (pm profile) \u2014 archetype bundles that stage item types, statuses, fields, per-type workflows, config knobs, create templates, and recommended packages. subcommand selects the operation; name carries the profile name (agile, ops, research) for show/apply/lint. apply stages every dimension idempotently; dryRun previews the diff without writing; lint reports author-time consistency findings (graded error/warning) without touching the tracker. Profile staging writes workspace config/schema files, not item history.",inputSchema:z({subcommand:{type:"string",enum:["list","show","apply","lint"],description:"Profile subcommand to run."},name:{type:"string",description:"Profile name for show/apply/lint. Required for those subcommands. Built-ins are agile, ops, and research; an active extension can contribute additional archetype names that resolve here too."},dryRun:{type:"boolean",description:"Preview the apply diff without writing any files (apply)."},author:{type:"string",description:"Mutation author for apply."},force:{type:"boolean",description:"Force ownership/lock override for apply."},options:{type:"object",description:"Additional profile options using camelCase keys."}},["subcommand"])},{name:"pm_config",description:"Read or write pm workspace configuration (pm config). configAction selects get/set/list/export; key/value address a single setting for get/set. scope chooses the project (default) or global settings file.",inputSchema:z({configAction:{type:"string",enum:["get","set","list","export"],description:"Config operation to perform. get/set require key; list/export dump the resolved settings surface."},key:{type:"string",description:"Settings key for get/set, for example governance-require-close-reason, telemetry-tracking, or a nested leaf such as search_provider (dash and underscore variants accepted; configAction=get without a key lists supported keys in the error)."},value:{type:"string",description:"New value for configAction=set."},scope:{type:"string",enum:["project","global"],description:"Settings scope to read or write. Defaults to project."},options:{type:"object",description:"Additional config options such as criterion, clearCriteria, format, or policy."}},["configAction"])},{name:"pm_plan",description:"Run agent-optimized Plan workflows. options.subcommand selects: create|show|add-step|update-step|complete-step|block-step|reorder-step|remove-step|link|unlink|decision|discovery|validation|resume|approve|materialize. Provide id for all non-create subcommands; provide stepRef for step lifecycle subcommands. Plans store agent-readable steps with dependencies, decisions, discoveries, validation, and resume context.",inputSchema:z({id:{type:"string",description:"Plan id (required for all subcommands except create)."},stepRef:{type:"string",description:"Step id or order for step lifecycle subcommands."},options:{type:"object",description:"Plan options including subcommand, stepRef, stepStatus, link, depth, etc."}})}],kC={pm_append:"append",pm_claim:"claim",pm_close:"close",pm_comments:"comments",pm_config:"config",pm_context:"context",pm_contracts:"contracts",pm_copy:"copy",pm_create:"create",pm_deps:"deps",pm_docs:"docs",pm_events:"events",pm_files:"files",pm_focus:"focus",pm_get:"get",pm_graph:"graph",pm_health:"health",pm_learnings:"learnings",pm_list:"list",pm_next:"next",pm_notes:"notes",pm_plan:"plan",pm_profile:"profile",pm_release:"release",pm_schema:"schema",pm_search:"search",pm_test:"test",pm_update:"update",pm_validate:"validate"},SC=bC.map(e=>{let t=kC[e.name];if(!t)return e;let n=e.inputSchema.properties,r=e.inputSchema.required.map(String);return{...e,inputSchema:_c(t,{properties:n,required:r})}});function Gg(){return SC.map(e=>{let t=e.inputSchema.required,n=Array.isArray(t)?t.map(r=>String(r)).sort((r,i)=>r.localeCompare(i)):[];return{name:e.name,description:e.description,required:n,input_schema:e.inputSchema}}).sort((e,t)=>e.name.localeCompare(t.name))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="208db30b-9299-52bf-902b-14c6a63b08f5")}catch{}})();var qg=new Map([["activity",["--limit","--after","--full"]],["claim",["--if-available","--next","--type","--priority","--token-budget","--explain-ranking"]],["close",["--reason","--validate-close","--resolution","--expected-result","--actual-result","--message"]],["context",["--limit","--after","--depth","--section","--token-budget","--explain-ranking"]],["contracts",["--command","--flags-only","--summary","--runtime-only","--availability-only","--full"]],["create",["--title","--type","--status","--priority","--dep","--comment"]],["get",["--full","--depth","--fields","--tree","--tree-depth","--format"]],["health",["--check-only","--summary","--brief","--check-telemetry","--strict-exit","--full"]],["list",["--status","--type","--limit","--after","--brief","--fields"]],["next",["--limit","--blocked-limit","--ready-only","--token-budget","--explain-ranking","--format"]],["search",["--mode","--status","--type","--limit","--after","--fields"]],["update",["--status","--message","--dep","--comment","--file","--test"]],["validate",["--check-resolution","--check-history-drift","--check-storage-integrity","--counts","--strict-exit","--fix-hints"]]]),EC=["--limit","--after","--offset","--token-budget","--brief","--summary","--compact","--fields","--full","--format","--since","--until"],Qg=new Set(["list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"]),jo=new Set(["calendar","guide","reindex","completion","test-runs-list","test-runs-status","test-runs-logs","test-runs-stop","test-runs-resume","templates-list","templates-save","templates-show"]),on=new Set(["meet","event","remind","search-advanced","dedupe-audit","dedupe-merge","comments-audit","cal","calendar","completion","completion-statuses","completion-tags","completion-types","guide","reindex","normalize","templates","templates list","templates save","templates show","test-runs","test-runs list","test-runs status","test-runs logs","test-runs stop","test-runs resume"]),Zg=new Map([["meet","calendar"],["event","calendar"],["remind","calendar"],["search-advanced","search-advanced"],["dedupe-audit","governance-audit"],["dedupe-merge","governance-audit"],["comments-audit","governance-audit"],["cal","calendar"],["calendar","calendar"],["completion","guide-shell"],["completion-statuses","guide-shell"],["completion-tags","guide-shell"],["completion-types","guide-shell"],["guide","guide-shell"],["reindex","search-advanced"],["normalize","governance-audit"],["templates","templates"],["templates list","templates"],["templates save","templates"],["templates show","templates"],["test-runs","linked-test-adapters"],["test-runs list","linked-test-adapters"],["test-runs status","linked-test-adapters"],["test-runs logs","linked-test-adapters"],["test-runs stop","linked-test-adapters"],["test-runs resume","linked-test-adapters"]]),ey=new Map([["calendar","calendar|cal"],["guide","guide"],["reindex","reindex"],["completion","completion"],["test-runs-list","test-runs|test-runs list"],["test-runs-status","test-runs status"],["test-runs-logs","test-runs logs"],["test-runs-stop","test-runs stop"],["test-runs-resume","test-runs resume"],["templates-list","templates|templates list"],["templates-save","templates save"],["templates-show","templates show"]]),ty=new Map([...ey.entries()].flatMap(([e,t])=>vt(t).map(n=>[n,e]))),ny=[{canonical:"context",aliases:["ctx"]},{canonical:"package",aliases:["extension","packages"]}],Hc=new Map(ny.flatMap(e=>e.aliases.map(t=>[t,e.canonical]))),TC=10,CC=20,Kg=new Map([["activity","Read activity."],["aggregate","Group counts."],["append","Append body."],["assurance","Evaluate assurance."],["assurance derive","Derive checks."],["assurance risk","Select checks for changes."],["assurance lineages","Measure recurrence coverage."],["beads","Manage Beads interoperability."],["cal","Manage calendar integration."],["calendar","Manage calendar integration."],["changelog","Generate changelog output."],["claim","Claim work."],["close","Close work."],["close-many","Close matching work."],["close-task","Close task work."],["command-kit","Inspect command authoring primitives."],["comments","Manage comments."],["comments-audit","Audit comment governance."],["completion","Generate shell completions."],["config","Manage settings."],["context","Build context."],["contracts","Inspect contracts."],["copy","Copy work."],["create","Create work."],["dedupe-audit","Audit duplicate work."],["dedupe-merge","Merge duplicate work."],["delete","Delete work."],["deps","Manage deps."],["duplicates","Find duplicate clusters."],["docs","Link docs."],["eval","Run evaluations."],["event","Manage events."],["events","Read events."],["files","Link files."],["focus","Manage focus."],["gc","Clean caches."],["get","Read item."],["graph","Query graph."],["guide","Show user guides."],["health","Check health."],["help","Show help."],["history","Inspect history."],["init","Initialize workspace."],["install","Install packages."],["item","Mutate items."],["learnings","Manage learnings."],["list","List work."],["list-all","List work across every status."],["list-blocked","List blocked work."],["list-canceled","List canceled work."],["list-closed","List closed work."],["list-draft","List draft work."],["list-in-progress","List in-progress work."],["list-open","List open work."],["meet","Record meeting context."],["merge","Manage tracker merges."],["next","Pick next work."],["notes","Manage notes."],["normalize","Normalize tracker data."],["ops","Run operations."],["package","Manage packages."],["packages","Manage packages."],["pause-task","Pause task work."],["plan","Manage plans."],["profile","Manage profiles."],["reindex","Refresh search index."],["release","Release claim."],["remind","Manage reminders."],["restore","Restore history."],["schema","Customize schema."],["search","Search work."],["search-advanced","Run advanced search."],["start-task","Start task work."],["stats","Show stats."],["telemetry","Manage telemetry."],["templates","Manage work templates."],["test","Run linked tests."],["test-all","Run all linked tests."],["test-runs","Inspect background test runs."],["todos","Manage source-code todos."],["twin","Manage repository twins."],["update","Update work."],["update-many","Update matching work."],["upgrade","Upgrade packages."],["validate","Validate data."],["vcs","Inspect version-control context."],["workspace","Manage workspaces."],["history-author-acknowledge","Acknowledge reviewed history authors."],["history-compact","Compact history."],["history-attest","Export or verify detached history proof."],["history-redact","Redact sensitive history values."],["history-repair","Repair history integrity."]]),ry=[["init",L_],["install",$_],["uninstall",N_],["explore",M_],["manage",q_],["describe",P_],["reload",K_],["doctor",W_],["catalog",z_],["adopt",B_],["adopt-all",F_],["activate",j_],["deactivate",U_],["migrate",G_]],AC=[...ry.map(([e,t])=>e==="init"?[e,D_]:[e,t]),["upgrade",cc]],xC=[...ry.map(([e,t])=>[`extension ${e}`,t]),...AC.flatMap(([e,t])=>[[`package ${e}`,t],[`packages ${e}`,t]]),["init",R_],["config",I_],["extension",O_],["package",ac],["packages",ac],["install",H_],["create",hf],["item mutate",gf],["item complete",yf],["item reopen",wf],["copy",vf],["focus",bf],["update",kf],["update-many",Sf],["upgrade",cc],["calendar",dc],["cal",dc],["context",lc],["ctx",lc],["get",Cf],["search",Lf],["eval",If],["events",Tf],["workspace",Lt],["workspace position",[]],["workspace snapshot",Lt],["workspace snapshot create",Lt],["workspace snapshot list",Lt],["workspace snapshot inspect",Lt],["workspace snapshot restore",Lt],["workspace snapshot delete",Lt],["next",Of],["aggregate",p_],["deps",xf],["graph",Rf],["guide",Af],["reindex",V_],["history",w_],["history-compact",E_],["history-attest",T_],["history-redact",b_],["history-repair",k_],["history-author-acknowledge",S_],["merge",v_],["schema",C_],["profile",A_],["plan",x_],["restore",Z_],["delete",ef],["close",Y_],["close-many",J_],["append",X_],["claim",Q_],["release",tf],["start-task",nf],["pause-task",rf],["close-task",of],["comments",__],["notes",f_],["learnings",h_],["files",g_],["docs",y_],["test",sf],["test-runs-worker",[]],["test-all",af],["telemetry",cf],["test-runs",df],["gc",lf],["stats",uf],["ops",[]],["duplicates",mf],["validate",_f],["health",pf],["assurance",ff],...Nf,["contracts",Df],["completion",$f],["activity",Ef],...[...Qg].map(e=>[e,m_])],Br=new Map(xC);for(let{alias:e,canonical:t}of ot){let n=Br.get(e);n!==void 0&&Br.set(t,n)}function RC(e){return ty.get(e)||(e.startsWith("test-runs ")?`test-runs-${e.slice(10)}`:e.startsWith("templates ")?`templates-${e.slice(10)}`:e)}function Wg(e){let t=ot.find(n=>n.alias===e);return t?`${t.canonical}|${t.alias}`:st.includes(e)?Se(e):e.startsWith("extension-")?Se(`extension ${e.slice(10)}`):e.startsWith("package-")?Se(`package ${e.slice(8)}`):e.startsWith("item-")?Se(`item ${e.slice(5)}`):e.startsWith("test-runs-")?Se(`test-runs ${e.slice(10)}`):e.startsWith("templates-")?Se(`templates ${e.slice(10)}`):jo.has(e)?ey.get(e)??Se(e):null}function IC(e,t){let n=K(t);return n!==t||ot.some(r=>r.alias===t)?e.action===n:e.command_path===null?!1:vt(e.command_path).some(r=>r===t?!0:r.startsWith(`${t} `)||t.startsWith(`${r} `))}function vt(e){return e.split("|").map(t=>Se(t)).filter(t=>t.length>0)}function OC(e,t){let n=new Set(t),r=new Set;for(let i of e)if(i.command_path)for(let o of vt(i.command_path)){let s=o.split(" ").filter(a=>a.length>0);if(s.length!==0)for(let a=s.length;a>0;a-=1){let c=s.slice(0,a).join(" ");if(n.has(c)){r.add(c);break}}}return[...r].sort((i,o)=>i.localeCompare(o))}function Fo(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function Hr(e){let t=e.oneOf;return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null):[]}function LC(e,t){if(!t)return{...e};let n=Hr(e).filter(r=>{let i=r.properties;if(typeof i!="object"||i===null)return!1;let o=i.action;return typeof o!="object"||o===null?!1:o.const===t});return{...e,oneOf:n}}function zc(e,t){let n=Hr(e).filter(r=>{let i=r.properties;if(typeof i!="object"||i===null)return!1;let o=i.action;if(typeof o!="object"||o===null)return!1;let s=o.const;return typeof s=="string"&&t.has(s)});return{...e,oneOf:n}}function Se(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function iy(e){return e.replace(/\s+/g,"-")}function Nt(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function zg(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let i=Nt(r);!i||n.has(i)||(n.add(i),t.push(i))}return t}function Bc(e,t,n){n&&(e[t]=!0)}function Bg(e,t){if(e==null)return null;if(typeof e!="string")throw new TypeError("Expected string for extension flag name.");let n=e.trim();return n.length===0?null:t==="long"?n.startsWith("--")&&n.length>2?Ht(n):null:n.startsWith("-")&&!n.startsWith("--")&&n.length>1?n:null}function DC(e){let t=Bg(e.long,"long"),n=Bg(e.short,"short"),r=t??n;if(!r)return null;let i={flag:r};n&&t&&(i.short=n),Bc(i,"required",e.required===!0),Bc(i,"repeatable",e.repeatable===!0),Bc(i,"list",e.list===!0),e.default!==void 0&&(i.default=e.default);let o=Nt(e.description);o&&(i.description=o);let s=An(e);i.value_arity=s.value_arity;let a=Nt(e.value_name)??s.value_name;a&&(i.value_name=a);let c=s.value_type??(s.value_name?"string":null);return c&&(i.value_type=c),i}function oy(e){let t=new Map;for(let r of e){let i=Se(r.target_command);if(i.length===0)continue;let o=t.get(i)??{flags:[],sources:[],dedupe:new Set,sourceDedupe:new Set},s=`${r.layer}:${r.name}`;o.sourceDedupe.has(s)||(o.sourceDedupe.add(s),o.sources.push({layer:r.layer,name:r.name}));for(let a of r.flags){let c=DC(a);if(!c)continue;let d=`${c.flag}|${c.short??""}`;o.dedupe.has(d)||(o.dedupe.add(d),o.flags.push(c))}t.set(i,o)}let n=new Map;for(let[r,i]of t.entries())n.set(r,{flags:i.flags,sources:i.sources.sort((o,s)=>{let a=o.layer.localeCompare(s.layer);return a!==0?a:(o.name??"").localeCompare(s.name??"")})});return n}function $C(e,t){return e.read_output===void 0?{flags:t}:{read_output:e.read_output,flags:[...t,...sc.filter(({flag:n})=>n.startsWith("--output-"))]}}function NC(e){let t=oy(e.flagRegistrations),n=new Map;for(let o of e.commandDefinitions){let s=Se(o.command);if(s.length===0)continue;let a=Nt(o.action)??iy(s),c=Array.isArray(o.arguments)?o.arguments.map(d=>{let l=Nt(d.name);return l?{name:l,required:d.required===!0,variadic:d.variadic===!0,description:Nt(d.description)}:null}).filter(d=>d!==null):[];n.set(s,{...o.tier===void 0?{}:{tier:o.tier},...$C(o,t.get(s)?.flags??[]),command:s,action:a,source:{layer:o.layer,name:o.name},description:Nt(o.description),intent:Nt(o.intent),arguments:c,examples:zg(o.examples),failure_hints:zg(o.failure_hints)})}let r=new Set;for(let o of e.handlers)r.add(Se(o));for(let o of n.keys())r.add(o);for(let o of t.keys())r.add(o);let i=[];for(let o of[...r].sort((s,a)=>s.localeCompare(a))){let s=n.get(o);i.push(MC(o,s,t.get(o)?.flags??[]))}return i}function MC(e,t,n){return t?{...t,flags:t.flags.length>0?t.flags:n}:{command:e,action:iy(e),source:null,description:null,intent:null,arguments:[],flags:n,examples:[],failure_hints:[]}}function PC(e){let t=e.flag.startsWith("--")?e.flag:void 0,n=Lc({long:t,short:t===void 0?e.flag:void 0});return n!==null&&/[a-z0-9]/iu.test(n)?n:null}function FC(e,t){return e.variadic?{type:"array",items:{type:"string"},description:e.description??`Variadic argument '${e.name}' for extension action '${t}'.`}:{type:"string",description:e.description??`Argument '${e.name}' for extension action '${t}'.`}}function jC(e,t){let n=e.value_type??"boolean",r=n==="boolean"?"boolean":n==="number"?["number","string"]:"string",i=e.repeatable===!0||e.list===!0;return{type:i?"array":r,...i?{items:{type:r}}:{},...e.default!==void 0?{default:e.default}:{},description:e.description??`Extension option '${e.flag}' for action '${t}'.`}}function UC(e){let t=e.command.split("|").map(i=>i.trim()).filter(i=>i.length>0),n={action:{type:"string",const:e.action,description:e.intent??e.description??`Invoke extension command '${e.command}'.`}},r=["action"];for(let i of e.arguments)n[i.name]=FC(i,e.action),i.required&&r.push(i.name);for(let i of e.flags){let o=PC(i);!o||n[o]!==void 0||(n[o]=sc.some(s=>s.flag===i.flag&&s.flag.startsWith("--output-"))?Xf[o]:jC(i,e.action),i.required===!0&&r.push(o))}return{type:"object",properties:n,required:r,additionalProperties:!0,"x-extension-source":e.source,"x-extension-command":t[0]??e.command,"x-extension-commands":t}}function GC(e,t){e.description??=t.description,e.value_name??=t.value_name,e.value_type??=t.value_type,t.required===!0&&(e.required=!0),t.repeatable===!0&&(e.repeatable=!0)}function qC(e){let t=new Map;for(let n of e){let r=t.get(n.action);if(!r){t.set(n.action,{...n,flags:[...n.flags],examples:[...n.examples],failure_hints:[...n.failure_hints]});continue}r.command=[...new Set([r.command,n.command])].sort((o,s)=>o.localeCompare(s)).join("|"),r.arguments=r.arguments.length>=n.arguments.length?r.arguments:n.arguments;let i=new Set(r.flags.map(o=>`${o.flag}|${o.short??""}`));for(let o of n.flags){let s=`${o.flag}|${o.short??""}`;if(!i.has(s))i.add(s),r.flags.push(o);else{let a=r.flags.find(c=>`${c.flag}|${c.short??""}`===s);a&&GC(a,o)}}r.examples=[...new Set([...r.examples,...n.examples])],r.failure_hints=[...new Set([...r.failure_hints,...n.failure_hints])]}return[...t.values()].sort((n,r)=>n.action.localeCompare(r.action))}async function KC(e,t=x){let n={mode:qt.extensions.policy.mode,trust_mode:qt.extensions.policy.trust_mode,default_sandbox_profile:qt.extensions.policy.default_sandbox_profile};if(e.noExtensions)return{handlers:new Set,disabledReason:"extensions_disabled",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};let r=R(process.cwd(),e.path);if(!await ie(Re(r)))return{handlers:new Set,disabledReason:null,commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};try{let i=await t(r),o=await Vi({pmRoot:r,settings:i,cwd:process.cwd(),noExtensions:!1}),s=await Yi({...o,loaded:o.loaded});return{handlers:new Set(s.commands.handlers.map(a=>Se(a.command))),disabledReason:null,commandDefinitions:s.registrations.commands,flagRegistrations:s.registrations.flags,registrations:s.registrations,policyState:{mode:o.policy.mode,trust_mode:o.policy.trust_mode,default_sandbox_profile:o.policy.default_sandbox_profile}}}catch{return{handlers:new Set,disabledReason:"extension_runtime_probe_failed",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n}}}function WC(e,t={}){let n=new Map;for(let r of Wu){let i=jo.has(r);if(i&&!t.includePackageOwnedActions)continue;let o=Wg(r);n.set(r,{action:r,provider:i?"extension":"core",requires_extension:i,command_path:o})}if(t.includePackageOwnedActions)for(let r of jo)n.has(r)||n.set(r,{action:r,provider:"extension",requires_extension:!0,command_path:Wg(r)});for(let r of e)n.has(r.action)||n.set(r.action,{action:r.action,provider:"extension",requires_extension:!0,command_path:ot.find(i=>i.alias===r.command)?.canonical??Se(r.command)});return[...n.values()].sort((r,i)=>(r.action??"").localeCompare(i.action??""))}function zC(e,t){if(e.provider==="core"&&!e.requires_extension)return{action:e.action,invocable:!0,available:!0,requires_extension:!1,provider:"core",disabled_reason:null,command_path:e.command_path,cli_exposed:e.command_path!==null&&(!on.has(e.action)||t.handlers.has(e.action))};let n=e.command_path?vt(e.command_path):[],r=n.some(s=>t.handlers.has(s)||t.handlers.has(K(s))),i=n.map(s=>Zg.get(K(s))).find(s=>typeof s=="string"),o=t.disabledReason===null&&r;return{action:e.action,invocable:o,available:o,requires_extension:!0,provider:"extension",disabled_reason:o?null:t.disabledReason??(i?`optional_package_not_installed:${i}`:"extension_command_not_registered"),command_path:e.command_path,cli_exposed:r,policy_state:{mode:t.policyState.mode,trust_mode:t.policyState.trust_mode,default_sandbox_profile:t.policyState.default_sandbox_profile}}}function sy(e){let t=Br.get(e)??go,n=xr(e).find(r=>r.flag==="--output-format"&&r.aliases?.includes("--format"));return n?[...t,n]:t}function BC(e){return on.has(K(e))?!1:Br.has(e)}function HC(e){return Qg.has(e)?"list":e==="cal"?"calendar":e==="ctx"?"context":e==="update-many"?"update_many":e}function Hg(e){let t=e.trim();return t?t.startsWith("--")?t:t.startsWith("-")?null:`--${t}`:null}function VC(e){let t=e.trim();return!t||t.startsWith("--")?null:t.startsWith("-")?t:null}function YC(e){let t=new Map;for(let r of e.definitions){let i=Hg(r.cli_flag);if(!i)continue;let o=r.cli_aliases.map(a=>VC(a)).find(a=>a!==null),s=r.cli_aliases.map(a=>Hg(a)).filter(a=>a!==null&&a!==i);for(let a of r.commands){let c=t.get(a)??{flags:[],seen:new Set},d=o?{flag:i,short:o}:{flag:i},l=`${d.flag}|${d.short??""}`;c.seen.has(l)||(c.seen.add(l),c.flags.push(d));for(let u of s){let _=`${u}|`;c.seen.has(_)||(c.seen.add(_),c.flags.push({flag:u}))}t.set(a,c)}}let n=new Map;for(let[r,i]of t.entries())n.set(r,oc(i.flags));return n}function Vg(e,t){let n=[],r=new Set;for(let i of[...e,...t]){let o=`${i.flag}|${i.short??""}`;r.has(o)||(r.add(o),n.push(i))}return oc(n)}function JC(e){let t=Lc(e.flag.startsWith("--")?{long:e.flag}:{short:e.flag});return{...e,owner:"extension",...t===null?{}:{sdk_option:t}}}function XC(e,t,n,r){let i=(n??[]).map(JC),o=t==="extension"&&(n!==void 0||QC(e,r));return{flags:i,inherited:o?{inherited_flags:u_({readOutput:ZC(e,r)})}:{}}}function ay(e,t){let n=K(e);return t.find(r=>K(r.command)===n)}function QC(e,t){return ay(e,t)!==void 0}function ZC(e,t){return ay(e,t)?.read_output!==void 0}function eA(e,t,n,r,i){let o=new Map(t);for(let{alias:s,canonical:a}of ot){let c=t.get(a)??t.get(s);c&&(o.set(s,c),o.set(a,c))}return e.map(s=>{let a=BC(s),c=a?sy(s):[],d=n.get(HC(s))??[],l=o.get(s),u=Vg(c,d),_=c.length>0&&(l?.flags.length??0)>0?"mixed":a?"core":"extension",h=XC(s,_,l?.flags,i),f=Vg(u,h.flags);return{command:s,flags:f,...h.inherited,...r?{canonical_command:dy(s),visibility:cy(s,i),positionals:c_(s)?.slots??[],flag_invocations:Lh(s,f)}:{},provider:_,extension_sources:l?.sources}}).sort((s,a)=>s.command.localeCompare(a.command))}function tA(e,t=Kt){let n=new Set(e),r=new Map;for(let i of ny){let o=i.aliases.filter(s=>n.has(s));r.set(i.canonical,{canonical:i.canonical,aliases:o,contracts:[]})}for(let i of t){if(!n.has(i.canonical)||i.registration==="commander"&&!n.has(i.alias))continue;let o=r.get(i.canonical)??{canonical:i.canonical,aliases:[],contracts:[]};o.aliases.includes(i.alias)||o.aliases.push(i.alias),o.contracts.push(i),r.set(i.canonical,o)}return[...r.values()].map(({contracts:i,...o})=>i.length===0?o:{...o,contracts:i}).sort((i,o)=>i.canonical.localeCompare(o.canonical))}function nA(){return{create_string_options:Gf,create_repeatable_options:qf,update_string_options:Kf,update_repeatable_options:Wf,list_string_options:Mf,search_string_options:Pf,calendar_string_options:Ff,context_string_options:jf,activity_string_options:Uf}}function Yg(e,t){let n=new Set(["title","type"]);if(t==="strict"){for(let a of e.required_create_fields)n.add(a);for(let a of e.required_create_repeatables)n.add(a)}let r=Cn(e,"create",n),i=[...new Set(r.required)].sort((a,c)=>a.localeCompare(c)),o=[...new Set(i.map(a=>xe("create",a)))].sort((a,c)=>a.localeCompare(c)),s=[...new Set(e.options.filter(a=>a.required===!0).map(a=>a.key))].sort((a,c)=>a.localeCompare(c));return{required_option_keys:i,required_flags:o,required_type_options:s,policy_errors:[...new Set(r.errors)].sort((a,c)=>a.localeCompare(c))}}function rA(e){let t={},n={};for(let r of[...e.types].sort((i,o)=>i.localeCompare(o))){let i=e.by_type[r];t[r]=Yg(i,"strict"),n[r]=Yg(i,"progressive")}return{default_create_mode:"strict",by_create_mode:{strict:{by_type:t},progressive:{by_type:n}}}}function iA(e,t){let n=Hr(e);if(n.length===0)return e;let r=!1,i=n.map(o=>{let s=o.properties;if(typeof s!="object"||s===null)return o;let a=s.action;return typeof a!="object"||a===null||a.const!=="create"?o:(r=!0,{...o,"x-create-required-options":t})});return r?{...e,oneOf:i}:e}function oA(e){let t=Fo(e.action)!==void 0||Fo(e.command)!==void 0,n=e.schemaOnly===!0||e.flagsOnly===!0||e.availabilityOnly===!0,r=e.summary===!0||e.full!==!0&&e.runtimeOnly!==!0&&!t&&!n,i=e.schemaOnly===!0,o=e.flagsOnly===!0,s=e.availabilityOnly===!0,a=e.runtimeOnly===!0,c=e.full===!0,d=Fo(e.action),l=Fo(e.command),u=!r&&!c&&!i&&!o&&!s&&!d&&!l;return{selectedAction:d,selectedCommand:l,summary:r,schemaOnly:i,flagsOnly:o,availabilityOnly:s,runtimeOnly:a,fullOutput:c,omitUnfilteredSchema:u,omitUnfilteredCommandFlags:u,omitUnfilteredCommanderAliases:u||l!==void 0&&!c}}function sA(e){if([e.summary,e.schemaOnly,e.flagsOnly,e.availabilityOnly].filter(t=>t).length>1)throw new p("Choose only one projection flag: --summary, --schema-only, --flags-only, or --availability-only.",m.USAGE)}async function aA(e,t=x){try{return await t(e)}catch{return structuredClone(qt)}}async function cA(e,t,n){let r=await aA(t),i=await KC(e),o=P(r,i.registrations??N()),s=Vt(r.schema),a=NC(i);return{settings:r,runtimeProbe:i,typeRegistry:o,statusRegistry:W(r.schema),runtimeFieldRegistry:s,runtimeFieldFlagMap:YC(s),createRequiredOptionContracts:rA(o),extensionContracts:a,mergedExtensionContracts:qC(a.filter(c=>Uo(n,c.command,a))),extensionFlagMap:oy(i.flagRegistrations)}}function Jg(e){return e.availabilityOnly&&(e.selectedAction!==void 0&&jo.has(e.selectedAction)||e.selectedCommand!==void 0&&on.has(K(e.selectedCommand)))}function dA(e,t){let n=WC(t,{includePackageOwnedActions:Jg(e)});if(e.selectedAction===void 0&&e.selectedCommand===void 0){let r=new Set(zu);return n.filter(i=>!r.has(i.action)&&(e.fullOutput||(t.find(o=>o.action===i.action)?.tier??$c(i.action))!=="internal"))}return Jg(e)&&e.selectedCommand!==void 0&&on.has(K(e.selectedCommand))&&!n.some(r=>r.command_path===e.selectedCommand)&&n.push({action:RC(K(e.selectedCommand)),provider:"extension",requires_extension:!0,command_path:e.selectedCommand}),n}function lA(e,t){let n=new Set(t.map(r=>r.action));if(e.selectedAction&&!n.has(e.selectedAction))throw new p(`Unknown action: "${e.selectedAction}".`,m.USAGE)}function uA(e,t){return[...new Set([...st.filter(n=>!on.has(K(n))),...[...Br.keys()].filter(n=>!on.has(K(n))),...e.flatMap(n=>n.command_path?vt(n.command_path).filter(r=>n.provider==="extension"||!on.has(K(r))||t.some(i=>i.action===n.action)):[]),...t.flatMap(n=>n.command.split("|").flatMap(r=>{let i=ot.find(o=>o.alias===r||o.canonical===r);return i===void 0?[r]:[i.alias,i.canonical]}))])].map(n=>Se(n)).filter(n=>n.length>0).sort((n,r)=>n.localeCompare(r))}function mA(e,t){let n=t.slice(0,TC),r=t.length-n.length,i=r>0?`${n.join(", ")}, and ${r} more`:n.join(", "),o=t.slice(0,CC),s=t.slice(0,5).map(c=>`pm contracts --command "${c}" --flags-only --json`),a=t[0];return new p(`Command "${e}" is a command namespace. Choose a concrete child command: ${i}.`,m.USAGE,{code:"command_namespace",required:"Use a concrete child command path listed under this namespace.",why:"Command groups expose help at the namespace root, but command flag contracts belong to executable child commands.",examples:s,nextSteps:[`Retry with a child command, for example: ${s[0]}`],recovery:{suggested_retry:`pm contracts --command "${a}" --flags-only --json`,fallback_candidates:o.map(c=>({source:"command_namespace",command:`pm contracts --command "${c}" --flags-only --json`,reason:`Child command under ${e}`}))}})}function pA(e,t){return new p(`Unknown command: "${e}". Command "${e}" is provided by the optional "${t}" package. Run "pm package install ${t} --project" and retry.`,m.USAGE,{code:"unknown_command",required:`Install the optional "${t}" package, or choose a command from pm contracts --flags-only --json.`,why:"Command contracts include core commands plus commands registered by active packages and extensions.",examples:[`pm package install ${t} --project`,`pm contracts --command ${e} --flags-only --json`],nextSteps:[`Install the optional package first: pm package install ${t} --project`],recovery:{suggested_retry:`pm package install ${t} --project`}})}function _A(e){return new p(`Unknown command: "${e}".`,m.USAGE,{code:"unknown_command",required:"Use a command path listed by pm contracts --flags-only --json.",why:"Command contracts are generated from the active core, package, and extension command registry.",examples:["pm contracts --flags-only --json","pm --help"],nextSteps:["Verify spelling and active packages/extensions, then rerun with a known command path."],recovery:{suggested_retry:"pm contracts --flags-only --json"}})}function fA(e,t){if(!e.selectedCommand||new Set(t).has(e.selectedCommand))return;let n=t.filter(i=>i.startsWith(`${e.selectedCommand} `));if(n.length>0)throw mA(e.selectedCommand,n);let r=Zg.get(K(e.selectedCommand));throw r?pA(e.selectedCommand,r):_A(e.selectedCommand)}function hA(e,t){let n=dA(e,t.mergedExtensionContracts);lA(e,n);let r=uA(n,t.mergedExtensionContracts);fA(e,r);let i=e.selectedCommand?ty.get(K(e.selectedCommand)):void 0,o=e.selectedCommand?n.filter(d=>i?d.action===i:IC(d,e.selectedCommand)):n;if(e.selectedCommand&&e.selectedAction&&!o.some(d=>d.action===e.selectedAction))throw new p(`Action "${e.selectedAction}" is not mapped to command "${e.selectedCommand}" in contracts output.`,m.USAGE);let s=e.selectedAction?o.filter(d=>d.action===e.selectedAction):o,a=[...new Map(s.map(d=>zC(d,t.runtimeProbe)).map(d=>[i?d.action:`${d.action}|${d.command_path??""}`,d])).values()],c=e.runtimeOnly&&!e.selectedAction&&!e.availabilityOnly?a.filter(d=>d.invocable):a;return{actionDescriptors:n,commandCatalog:r,commandScopedDescriptors:o,scopedActionDescriptors:s,selectedPackageOwnedAction:i,actionAvailability:c,actions:[...new Set(c.map(d=>d.action))]}}function gA(e){return new Set(Hr(e).map(t=>{let n=t.properties;if(typeof n!="object"||n===null)return null;let r=n.action;if(typeof r!="object"||r===null)return null;let i=r.const;return typeof i=="string"?i:null}).filter(t=>t!==null))}function yA(e){let t=Qf,n=Hr(t),r=gA(t),i=e.filter(o=>!r.has(o.action)).map(o=>UC(o));return i.length>0?{...t,oneOf:[...n,...i]}:t}function Xg(e,t,n){let r=new Set(t.actionDescriptors.map(o=>o.action)),i=e.selectedAction?LC(n,e.selectedAction):e.selectedCommand?zc(n,new Set(t.scopedActionDescriptors.map(o=>o.action))):zc(n,r);return e.runtimeOnly&&!e.selectedAction?zc(i,new Set(t.actions)):i}function wA(e,t,n){let r=yA(t.mergedExtensionContracts),i=!e.flagsOnly&&!e.availabilityOnly?iA(Xg(e,n,r),t.createRequiredOptionContracts):Xg(e,n,r);return{mergedSchema:r,filteredSchema:i}}function vA(e,t){return e.selectedCommand!==void 0?[e.selectedCommand]:e.selectedAction?OC(t.scopedActionDescriptors,t.commandCatalog):t.commandCatalog}function cy(e,t){return t.find(n=>K(n.command)===K(e))?.tier??$c(e)}function Uo(e,t,n){return e.fullOutput||e.selectedCommand!==void 0||e.selectedAction!==void 0||cy(t,n)!=="internal"}function bA(e,t,n){if(e.selectedCommand!==void 0||e.selectedAction!==void 0)return t;let r=new Set(Kt.filter(i=>i.hidden&&(i.lifecycle==="deprecated"||!e.fullOutput&&!e.availabilityOnly)).map(i=>i.alias));if(e.summary&&!e.fullOutput)for(let i of Hc.keys())r.add(i);return t.filter(i=>!r.has(i)&&Uo(e,i,n))}function dy(e){let t=ot.find(r=>r.alias===e||r.canonical===e);if(t)return t.canonical;let n=e.split(" ")[0];return n.startsWith("list-")?"list":Hc.get(n)??n}var kA=new Map([["activate","Activate"],["adopt","Adopt"],["adopt-all","Adopt all"],["catalog","Catalog"],["complete","Complete"],["create","Create"],["deactivate","Deactivate"],["delete","Delete"],["describe","Describe"],["doctor","Diagnose"],["explore","Explore"],["init","Initialize"],["inspect","Inspect"],["install","Install"],["list","List"],["manage","Manage"],["migrate","Migrate"],["mutate","Mutate"],["reload","Reload"],["restore","Restore"],["run","Run"],["snapshot","Manage snapshots for"],["uninstall","Uninstall"],["upgrade","Upgrade"]]),SA=new Map([["extension adopt-all","extensions"],["package adopt-all","packages"],["workspace snapshot list","workspace snapshots"]]);function EA(e,t){let n=Kg.get(K(e))??(e.includes(" ")?void 0:Kg.get(dy(e)));if(n!==void 0)return{intent:n,intent_source:"command"};let r=t.find(d=>vt(d.command).some(l=>K(l)===K(e)));if(r?.intent!==null&&r?.intent!==void 0)return{intent:r.intent,intent_source:"command"};if(r?.description!==null&&r?.description!==void 0)return{intent:r.description,intent_source:"description"};let i=e.split(" "),o=i.at(-1),s=i.slice(0,-1).join(" "),a=kA.get(o),c=SA.get(e)??s;return{intent:a===void 0||s.length===0?`Run ${e}.`:`${a} ${c}.`,intent_source:"generated"}}function TA(e,t=[],n={}){let r=n.includeFormatBudgets??!0,i=n.includeIntentProvenance??!0;return[...new Set(e.map(Se))].filter(o=>o.length>0).sort((o,s)=>o.localeCompare(s)).map(o=>{let s=Va(o,{generateFallback:!0}),a=o.split(" ")[0],c=Hc.get(a)??(a.startsWith("list-")?"list":a.startsWith("history-")?"history":a),d=new Set([...sy(o).map(_=>_.flag),...t.filter(_=>vt(_.command).some(h=>K(h)===K(o))).flatMap(_=>_.flags.map(h=>h.flag))]),l=(qg.get(K(o))??qg.get(c)??EC).filter(_=>d.has(_)),u=EA(o,t);return{command:o,intent:u.intent,...i||u.intent_source!=="command"?{intent_source:u.intent_source}:{},...l.length>0?{flags:l}:{},default_max_estimated_tokens:s.default_max_estimated_tokens,...r?{default_max_estimated_tokens_by_format:{...s.default_max_estimated_tokens_by_format}}:{}}})}function CA(e){return e.map(t=>({budget:Va(t,{generateFallback:!0}),envelope:gg(t)}))}function AA(e){let t=new Map;for(let n of e){let r=bg(n),i=r===void 0?[m.SUCCESS,m.GENERIC_FAILURE,m.USAGE,m.NOT_FOUND,m.CONFLICT,m.DEPENDENCY_FAILED]:r.exit_codes,o=i.join(","),s=t.get(o)??{commands:[],exit_codes:i};s.commands.push(n),t.set(o,s)}return[...t.values()]}function xA(e,t,n){if(e.selectedCommand)return t.extensionContracts.filter(r=>vt(r.command).some(i=>K(i)===K(e.selectedCommand)));if(e.selectedAction){let r=new Set(n);return t.extensionContracts.filter(i=>vt(i.command).some(o=>r.has(o)))}return t.extensionContracts.filter(r=>Uo(e,r.command,t.extensionContracts))}function RA(e,t,n,r){return{schema_version:typeof t.mergedSchema["x-schema-version"]=="string"?t.mergedSchema["x-schema-version"]:null,schema_id:typeof t.mergedSchema.$id=="string"?t.mergedSchema.$id:null,selected:{action:e.selectedAction??null,command:e.selectedCommand??null,summary:e.summary,schema_only:e.schemaOnly,flags_only:e.flagsOnly,availability_only:e.availabilityOnly,runtime_only:e.runtimeOnly,command_scoped:e.selectedCommand!==void 0},commands:e.summary?[]:r,...!e.summary&&!e.flagsOnly?{actions:n.actions,action_availability:n.actionAvailability}:{}}}function IA(e,t,n){(n.selectedCommand==="history"||n.fullOutput)&&!n.flagsOnly&&!n.schemaOnly&&!n.availabilityOnly&&(e.history_operations=op);let r=n.selectedCommand;e.runtime_schema={statuses:t.statusRegistry.definitions.map(i=>i.id),open_status:t.statusRegistry.open_status,close_status:t.statusRegistry.close_status,canceled_status:t.statusRegistry.canceled_status,types:[...t.typeRegistry.types],fields_by_command:Object.fromEntries([...t.runtimeFieldRegistry.command_to_fields.entries()].filter(([i])=>r===void 0||i===r).map(([i,o])=>[i,[...new Set(o.map(s=>`--${s.cli_flag}`))].sort((s,a)=>s.localeCompare(a))]))},!(r!==void 0&&!n.fullOutput)&&(e.extension_contracts={capabilities:[...Pu],services:[...Fu],policy_modes:[...ju],policy_mode_scope:"extensions.policy.mode",policy_surfaces:[...qu],trust_modes:[...Uu],trust_mode_scope:"extensions.policy.trust_mode",sandbox_profiles:[...Gu],manifest_versions:[1,2],compatibility:{current:"v2",previous:["v1"],breaking_strategy:"versioned_breaking"}},e.governance_contracts={ownership_enforcement_modes:[...Qu],create_modes:[...Zu],close_validation_modes:[...em],workflow_enforcement_modes:[...tm]},e.relationship_kind_contracts=[...km,...(t.runtimeProbe.registrations?.relationship_kinds??[]).flatMap(i=>i.definitions)].sort((i,o)=>i.kind.localeCompare(o.kind)).map(i=>({canonical:i.kind,aliases:[...i.aliases??[]],...i.inverse===void 0?{}:{inverse:i.inverse},ordering:i.ordering,hierarchy:i.hierarchy})))}function OA(e,t,n,r){if(!(t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredSchema){e.schema=n.filteredSchema,e.extension_commands=r;return}e.schema_omitted_reason="unfiltered_default_brief",e.extension_commands=r}}function LA(e,t,n,r,i){if(!(t.schemaOnly||t.availabilityOnly)){if(t.omitUnfilteredCommandFlags)e.command_flags_omitted_reason="unfiltered_default_brief";else{e.command_flags=eA(r,n.extensionFlagMap,n.runtimeFieldFlagMap,t.selectedCommand!==void 0,n.extensionContracts);let o=new Set(r);e.list_projections=Object.entries(a_).filter(([s])=>o.has(s)).map(([s,a])=>({command:s,default:a,brief_fields:[...s_,"priority"],compact_fields:[...o_]}))}e.command_aliases=t.fullOutput?i:i.map(({canonical:o,aliases:s})=>({canonical:o,aliases:s})),t.fullOutput||(e.command_alias_contracts_omitted_reason="compact_projection; restore with --full")}}function DA(e,t){if(!(t.schemaOnly||t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredCommanderAliases){e.commander_aliases=nA();return}e.commander_aliases_omitted_reason=t.selectedCommand?"command_scoped":"unfiltered_default_brief"}}function $A(e,t,n,r){e.command_summaries=TA(t,n,{includeFormatBudgets:r.includeFormatBudgets,includeIntentProvenance:r.includeIntentProvenance}),e.output_policy={token_estimate:"ceil(utf8_bytes / 4)",degradation_ladder:[...ap],allows_unbounded_opt_out:!0},e.output_projection_contracts={global_ladder_field:"output_policy.degradation_ladder",global_ladder_scope:"union_not_per_command",discovery:"pm contracts --command <command> --summary",...r.includeProjectionModeMatrix?{commands:[...new Set(t.map(Se))].filter(i=>lp(i)!==void 0).sort((i,o)=>i.localeCompare(o)).map(i=>({command:i,modes:[...up(i).keys()]}))}:{}},e.grammar_contracts={nouns:tn.nouns,shared_verbs:tn.shared_verbs,scope_before_verb:tn.scope_before_verb,visible_top_level_ceiling:tn.visible_top_level_ceiling,ceiling_raise_requires_pm_item:tn.ceiling_raise_requires_pm_item,positional_shape_budget:tn.positional_shape_budget,positional_shape_count:new Set(ic.map(({slots:i})=>l_(i))).size,positional_action_count:rc.length,positional_action_parents:[...new Set(rc.map(({parent:i})=>i))].sort((i,o)=>i.localeCompare(o)),...r.includePositionalSignatures?{positional_signatures:ic}:{}}}async function o2(e,t){let n=oA(e);sA(n);let r=R(process.cwd(),t.path),i=await cA(t,r,n),o=hA(n,i),s=wA(n,i,o),a=vA(n,o),c=bA(n,a,i.extensionContracts),d=RA(n,s,o,c),l=xA(n,i,c),u=n.fullOutput||n.selectedCommand!==void 0;if((n.summary||n.fullOutput)&&$A(d,c,l,{includeFormatBudgets:u,includeIntentProvenance:u,includePositionalSignatures:u,includeProjectionModeMatrix:u}),n.summary)return d;let _=tA(o.commandCatalog.filter(h=>Uo(n,h,i.extensionContracts)));return n.flagsOnly&&!n.fullOutput||IA(d,i,n),OA(d,n,s,l),LA(d,n,i,c,_),DA(d,n),(n.selectedCommand==="assurance"||n.fullOutput)&&(d.assurance_contracts={measurement_source_kinds:[...qr],gate_triggers:[...yt]}),n.fullOutput&&d.grammar_contracts&&(d.grammar_contracts.destinations=d_.map(h=>({...h,reason:h.reason??""}))),n.fullOutput&&!n.schemaOnly&&!n.flagsOnly&&!n.availabilityOnly&&(d.mcp_tools=Gg(),d.context_intents=mp(),d.read_output_dimensions=dp,d.error_codes=fg,d.command_output_contracts=CA(c),d.diagnostic_output_contracts=cp,d.command_exit_contracts={vocabulary:Mc,command_sets:AA(c)}),d}import{createHash as uy}from"node:crypto";import Vr from"node:fs/promises";import Yr from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="69bf315a-01aa-56d9-bd56-196d6792dea2")}catch{}})();function ze(e,t){throw new p(e,m.USAGE,t)}var NA="2026-07-15T06:22:12.276Z",MA=Date.parse(NA),PA=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],ly=e=>typeof e=="string"?e:"",my=e=>{let t=e??{},n=ly(t.author).trim().toLowerCase(),r=Number(["","unknown"].includes(n)),i=+(Date.parse(ly(t.ts))>=MA);return PA[r][i]};function py(e,t,n=20,r=new Set,i=!1){let o=[],s=[],a={legacy_unknown:0,actionable_unknown:0},c=Math.max(0,n),d=0,l=0,u=0;for(let[_,h]of t.split(/\r?\n/).entries()){let f;try{f=JSON.parse(h)}catch{continue}d+=1;let g=my(f);if(g!=="attributed"){if(l+=1,g==="actionable_unknown"&&r.has(`${e}:${_+1}`)){u+=1;continue}a[g]+=1,i&&g==="actionable_unknown"&&s.push({item_id:e,line:_+1}),o.length<c&&o.push({item_id:e,line:_+1})}}return{checked_events:d,unknown_event_count:l,legacy_unknown_event_count:a.legacy_unknown,actionable_unknown_event_count:a.actionable_unknown,acknowledged_actionable_event_count:u,samples:o,samples_truncated:a.legacy_unknown+a.actionable_unknown>o.length,actionable_events:s}}var f2=(e,t,n=20,r=new Set)=>py(e,t,n,r);function _y(e){let t=new Set;for(let n of e.split(/\r?\n/)){let r;try{r=JSON.parse(n)}catch{continue}let i=(typeof r=="object"&&r!==null&&typeof r.context=="object"&&r.context!==null?r.context:{}).author_acknowledgment;if(!(typeof i!="object"||i===null||!Array.isArray(i.events)))for(let o of i.events)typeof o=="object"&&o!==null&&typeof o.item_id=="string"&&Number.isSafeInteger(o.line)&&t.add(`${o.item_id}:${String(o.line)}`)}return t}var Jr=async(e,t=20,n=!1)=>{let r=Yr.join(e,"history"),i;try{i=(await Vr.readdir(r)).filter(w=>w.endsWith(".jsonl")).sort((w,v)=>w.localeCompare(v))}catch{i=[]}let o=new Set,s=[],a=[],c=0,d=0,l=0,u=0,_=0,h=0,f="_workspace.jsonl",g=new Set;if(i.includes(f))try{g=_y(await Vr.readFile(Yr.join(r,f),"utf8"))}catch{g=new Set}for(let w of i){let v;try{v=await Vr.readFile(Yr.join(r,w),"utf8")}catch{continue}let k=w.slice(0,-6),S=py(k,v,t-s.length,g,n);c+=1,d+=S.checked_events,l+=S.unknown_event_count,u+=S.legacy_unknown_event_count,_+=S.actionable_unknown_event_count,h+=S.acknowledged_actionable_event_count,S.unknown_event_count>0&&o.add(k),s.push(...S.samples),n&&a.push(...S.actionable_events)}let y=u+_;return{checked_streams:c,checked_events:d,unknown_event_count:l,legacy_unknown_event_count:u,actionable_unknown_event_count:_,acknowledged_actionable_event_count:h,affected_item_ids:[...o].sort((w,v)=>w.localeCompare(v)),samples:s,samples_truncated:y>s.length,...n?{actionable_events:a}:{}}};function FA(e){return[...new Map(e.map(t=>[`${t.item_id}:${t.line}`,{item_id:t.item_id,line:t.line}])).values()].sort((t,n)=>t.item_id.localeCompare(n.item_id)||t.line-n.line)}async function jA(e){try{return _y(await Vr.readFile(Yr.join(e,"history","_workspace.jsonl"),"utf8"))}catch{return new Set}}function UA(e){return(e.item_id===Xt||/^[a-z0-9][a-z0-9-]*$/iu.test(e.item_id))&&Number.isSafeInteger(e.line)&&e.line>=1}function GA(e,t,n){let r=n[e.line-1]??"",i;try{i=JSON.parse(r)}catch{ze(`Unknown-author acknowledgment target ${e.item_id}:${e.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}return my(i)!=="actionable_unknown"&&ze(`Author acknowledgment target ${e.item_id}:${e.line} is not an actionable unknown-author event.`,{code:"history_author_acknowledge_target_not_actionable"}),{...e,source_event_hash:uy("sha256").update(r).digest("hex"),disposition:t.has(`${e.item_id}:${e.line}`)?"already_acknowledged":"actionable"}}async function fy(e,t,n){let r=t.events??[],i=+(t.all_actionable===!0)+ +(r.length>0);i===0&&ze("Specify exactly one selector: events or all_actionable.",{code:"history_author_acknowledge_selector_required"}),i>1&&ze("Author acknowledgment accepts either explicit events or all_actionable, not both.",{code:"history_author_acknowledge_selector_conflict"}),(!Number.isSafeInteger(n)||n<0)&&ze("Author acknowledgment coordinate_limit must be a non-negative integer.",{code:"history_author_acknowledge_preview_limit_invalid"});let o=FA(t.all_actionable===!0?(await Jr(e,0,!0)).actionable_events:r),s=await jA(e),a=new Map;for(let _ of o)if(UA(_)||ze(`Unknown-author acknowledgment target ${_.item_id}:${_.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"}),!a.has(_.item_id))try{a.set(_.item_id,(await Vr.readFile(Yr.join(e,"history",`${_.item_id}.jsonl`),"utf8")).split(/\r?\n/u))}catch{ze(`Unknown-author acknowledgment target ${_.item_id}:${_.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}let c=o.map(_=>GA(_,s,a.get(_.item_id))),d=t.all_actionable===!0?"all_actionable":"events",l=uy("sha256").update(JSON.stringify({version:1,selection:d,coordinates:c})).digest("hex"),u=c.filter(({disposition:_})=>_==="actionable").length;return{plan:{selection:{kind:d},selected_count:c.length,actionable_count:u,already_acknowledged_count:c.length-u,omitted_count:Math.max(0,c.length-n),coordinates:c.slice(0,n),plan_fingerprint:l},completeCoordinates:c}}async function h2(e,t,n=50){return(await fy(e,t,n)).plan}function qA(e,t){let n=e.length>0;return n&&t&&ze("Specify exactly one selector: repeat --event or pass --all-actionable.",{code:"history_author_acknowledge_selector_conflict",required:"Exactly one of --event or --all-actionable",examples:['pm history-author-acknowledge --event pm-a1b2:4 --attributed-author agent --reviewer maintainer --reason "Verified provenance"','pm history-author-acknowledge --all-actionable --attributed-author import-agent --reviewer maintainer --reason "Reviewed the complete actionable set"']}),!n&&!t&&ze("Specify exactly one selector: repeat --event or pass --all-actionable.",{code:"history_author_acknowledge_selector_required",required:"Exactly one of --event or --all-actionable",examples:['pm history-author-acknowledge --event pm-a1b2:4 --attributed-author agent --reviewer maintainer --reason "Verified provenance"','pm history-author-acknowledge --all-actionable --attributed-author import-agent --reviewer maintainer --reason "Reviewed the complete actionable set"']}),{events:KA(e),all_actionable:t}}function KA(e){return e.map(t=>{let n=t.lastIndexOf(":"),r=t.slice(0,n).trim(),i=Number(t.slice(n+1)),o=r===Xt||/^[a-z0-9][a-z0-9-]*$/iu.test(r);return(n<1||!o||!Number.isSafeInteger(i)||i<1)&&ze(`history-author-acknowledge --event expects <item-id>:<one-based-line>, received "${t}".`,{code:"history_author_acknowledge_target_unreadable"}),{item_id:r,line:i}})}function g2(e,t){let n=qA(ih(t.historyEvent),t.allActionable===!0||t.all_actionable===!0);return WA(e,{events:n.events,all_actionable:n.all_actionable,dry_run:t.dryRun===!0||t.dry_run===!0,plan_fingerprint:te(t,"planFingerprint")??te(t,"plan_fingerprint"),coordinate_limit:typeof t.limit=="number"?t.limit:typeof t.limit=="string"?Number(t.limit):void 0,attributed_author:te(t,"attributedAuthor")??te(t,"attributed_author")??void 0,reviewer:te(t,"reviewer"),reason:te(t,"reason")})}async function WA(e,t){let n=t.reviewer?.trim()??"",r=t.attributed_author?.trim()??"",i=t.reason?.trim()??"",o=await fy(e,t,t.coordinate_limit??50);if(t.dry_run===!0)return{dry_run:!0,mutated:!1,acknowledged:0,outcome:"preview",exit_code:m.SUCCESS,plan:o.plan};if([n.length>0,n.toLowerCase()!=="unknown",r.length>0,r.toLowerCase()!=="unknown",i.length>0].includes(!1)&&ze("Author acknowledgment requires events, reviewer, attributed_author, and reason.",{code:"history_author_acknowledge_required_values_missing"}),t.plan_fingerprint?.trim()||ze("Author acknowledgment apply requires plan_fingerprint from a fresh dry-run preview.",{code:"history_author_acknowledge_plan_fingerprint_required",recovery:{suggested_retry:"Rerun history-author-acknowledge with --dry-run, then pass --plan-fingerprint <value>."}}),t.plan_fingerprint.trim()!==o.plan.plan_fingerprint)throw new p("Author acknowledgment selection changed after preview; no history was mutated.",m.CONFLICT,{code:"history_author_acknowledge_plan_conflict",recovery:{suggested_retry:"Rerun history-author-acknowledge with --dry-run and apply the fresh plan_fingerprint."}});let s=o.completeCoordinates.filter(({disposition:l})=>o.plan.selection.kind==="events"||l==="actionable").map(({item_id:l,line:u})=>({item_id:l,line:u}));if(s.length===0)return{dry_run:!1,mutated:!1,acknowledged:0,outcome:"no_effect",exit_code:m.NO_EFFECT,plan:o.plan};let a=await x(e),c=await In({pmRoot:e,op:"history:author-acknowledge",author:n,context:{author_acknowledgment:{events:s,attributed_author:r}},message:i,lockTtlSeconds:a.locks.ttl_seconds,lockWaitMs:a.locks.wait_ms}),d=o.plan.actionable_count>0&&o.plan.already_acknowledged_count>0?{outcome:"partial_effect",exit_code:m.PARTIAL_EFFECT}:{outcome:"effect",exit_code:m.SUCCESS};return{dry_run:!1,mutated:!0,acknowledged:s.length,...d,plan:o.plan,history_path:c.historyPath}}import BA from"node:fs/promises";import De from"node:path";import{glob as HA}from"tinyglobby";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6f94fb3c-3d6c-5543-a2f0-e12680459e71")}catch{}})();var zA=/^[a-z][a-z0-9+.-]+:\/\//i;function Xr(e){return zA.test(e.trim())}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6c72ddef-c0fa-5d0b-9e35-20e3ba3c8d73")}catch{}})();var Vc=["refuse","replace","append"],Jc="; ";function VA(e,t){if(e===void 0)return"refuse";let n=e.trim().toLowerCase();if(!Vc.some(r=>r===n))throw new p(`--note-conflict must be one of ${Vc.join(", ")}; got "${e}"`,m.USAGE,{code:"invalid_argument_value",flag:"--note-conflict",value:e,required:`Pass --note-conflict ${Vc.join("|")}.`});if(!t)throw new p("--note-conflict requires --add or --add-glob in the same invocation (it decides how those links treat an existing note)",m.USAGE,{code:"missing_required_argument",flag:"--note-conflict",required:"Pass --add or --add-glob with --note-conflict."});return n}function YA(e,t,n){if(t===void 0||t===e)return{note:e,outcome:"unchanged",conflict:!1};if(e===void 0)return{note:t,outcome:"note_added",conflict:!1};if(n==="replace")return{note:t,outcome:"note_replaced",conflict:!1};if(n==="append"){let r=Jc;return`${r}${e}${r}`.includes(`${r}${t}${r}`)?{note:e,outcome:"unchanged",conflict:!1}:{note:`${e}${Jc}${t}`,outcome:"note_appended",conflict:!1}}return{note:e,outcome:"unchanged",conflict:!0}}function JA(e){let t=e.conflicts[0],n=e.conflicts.length>1?` and ${e.conflicts.length-1} more`:"",r=e.retryArgs("append"),i=e.retryArgs("replace"),o=t.source==="stored"?`${e.itemId} already links ${e.noun} ${t.path} with the note "${t.existing_note}"${n}; the add was refused so that note is kept`:`The add names ${e.noun} ${t.path} on ${e.itemId} with two notes, "${t.existing_note}" and then "${t.requested_note}"${n}; the add was refused because they disagree`;return new p(o,m.CONFLICT,{code:"linked_artifact_note_conflict",item_id:e.itemId,why:"A different stored note is usually another agent's rationale, so --add never overwrites it silently.",required:"Re-run with --note-conflict append to keep both notes, or --note-conflict replace to overwrite the stored note.",...r===void 0||i===void 0?{}:{nextSteps:[e.render(r),e.render(i)],recovery:{suggested_retry:e.render(r),suggested_retry_args:r}},details:{conflicts:e.conflicts.map(s=>({...s}))}})}var Xc=["path","scope","note"],XA=["pattern","glob","path","scope","note"],QA=["path"],ZA=["from","to"],ex=new Set(["note","scope"]);function hy(e){return JSON.parse(JSON.stringify(e))}function td(e,t){let n=e.map(hy);return t.filter(r=>{let i=hy(r),o=n.findIndex(s=>Fe(s,i));return o>=0&&n.splice(o,1),o<0})}function Qr(e){let t=e.fullHistory?[...e.stored]:[...e.written],n=t.length<e.stored.length;return{entries:t,total_count:e.stored.length,returned_count:t.length,has_more:n,mutation_receipt:{changed_count:e.written.length,removed_count:e.removedCount,full_history_included:!n,...e.linkOutcomes&&e.linkOutcomes.length>0?{link_outcomes:[...e.linkOutcomes]}:{}},omission_receipt:{has_omissions:n,omitted_field_group_count:n?1:0,omitted_field_groups:n?[{name:`${e.collectionKey}_history`,restore_with:{selector:"full_history",cli_flag:"--full-history",sdk_option:"fullHistory",mcp_option:"full"}}]:[]}}}function gy(e){let t=e??"project";if(!Ke.includes(t))throw new p(`Invalid scope "${e}". Valid scopes: ${Ke.join(", ")} (default: project).`,m.USAGE);return t}function Qc(e){if(e.startsWith("```")||e.includes(`
|
|
6
|
-
`)||/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(e))return!0;let t=e.indexOf(","),n=e.slice(0,t>=0?t:e.length),r=n.indexOf("=");return r>=0&&!/\s/u.test(e)&&(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)||/^(?:[A-Za-z]:[\\/]|[\\/]{1,2}|\.\.?(?:[\\/]))/u.test(e)||[e.indexOf("/"),e.indexOf("\\")].some(i=>i>=0&&i<r))?!1:n.includes("=")||Sn(e)}function tx(e){let t=0;for(let n of e)if(n==="("&&(t+=1),n===")"&&(t-=1),t<0)return!1;return t===0}function nx(e){if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)&&!Qc(e))return{path:e,scope:"project",note:void 0};let t=e.indexOf("](");if(e.startsWith("[")&&t>0&&e.endsWith(")")){let o=e.slice(t+2,-1).trim();if(o.length>0&&tx(o))return{path:o,scope:"project",note:e.slice(1,t).trim()||void 0}}let n=e.indexOf(",");if(n<0)return;let r=e.slice(0,n).trim(),i=e.slice(n+1).trim();if(!(r.length===0||!/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(i)))return{path:i,scope:"project",note:r}}function nd(e,t){return e?e.flatMap(n=>{let r=n.trim();if(t==="doc"){let o=nx(r);if(o!==void 0)return[o]}pr(r,"--add",`${t} path`,Qc(r));let i=Qc(r)?ee(n,"--add"):{path:r};if(ke(i,"--add",Xc),!i.path)throw new p(`--add requires path=<value> or a bare ${t} path`,m.USAGE);return[{path:i.path,scope:gy(i.scope),note:i.note?.trim()||void 0}]}):[]}function rx(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new p("--add-glob requires a glob pattern value",m.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?(?:pattern|glob|path)\s*[:=]/i.test(n)||n.startsWith("```")){let r=ee(n,"--add-glob");ke(r,"--add-glob",XA);let i=r.pattern?.trim()||r.glob?.trim()||r.path?.trim();if(!i)throw new p("--add-glob key/value form requires pattern=<glob>",m.USAGE);return{pattern:i,scope:gy(r.scope),note:r.note?.trim()||void 0}}return{pattern:n,scope:"project"}}):[]}function ix(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new p("--remove requires a path value",m.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?path\s*[:=]/i.test(n)||n.startsWith("```")){let r=ee(n,"--remove"),i=Object.keys(r).filter(o=>ex.has(o.toLowerCase()));if(i.length>0)throw new p(`--remove identifies a linked artifact by path only and does not accept ${i.map(o=>`"${o}"`).join(", ")}. Pass just the path (path=<value>, path:<value>, or a bare path); record removal context with --message "<why removed>".`,m.USAGE);if(ke(r,"--remove",QA),!r.path)throw new p("--remove key/value form requires path=<value>",m.USAGE);return r.path}return n}):[]}function ox(e){return e?e.map(t=>{let n=ee(t,"--migrate");ke(n,"--migrate",ZA);let r=n.from?.trim(),i=n.to?.trim();if(!r||!i)throw new p("--migrate requires from=<value> and to=<value>",m.USAGE);return{from:r,to:i}}):[]}function zn(e,t){let n=e;for(let r of t)n.startsWith(r.from)&&(n=`${r.to}${n.slice(r.from.length)}`);return n}function sx(e,t,n=[]){if(e.length===0||t.length===0)return;let r=new Set(e.map(o=>Mt(zn(o.path,n)))),i=[...new Set(t.map(o=>Mt(zn(o,n))).filter(o=>r.has(o)))].sort((o,s)=>o.localeCompare(s));if(i.length!==0)throw new p(`Linked artifact mutation cannot add and remove the same normalized path in one transaction: ${i.join(", ")}. Split the replacement into separate commands so each history event has one unambiguous intent.`,m.USAGE,{code:"linked_artifact_mutation_conflict",reason:"same_path_added_and_removed",required:"Use distinct normalized paths for --add and --remove in one invocation.",why:"Conflicting batch intent cannot be applied deterministically without silently discarding metadata or a removal.",nextSteps:["Run the removal and addition as separate commands with a --message describing each intent."]})}function bt(e){return e.split(De.sep).join("/")}function Zc(e,t,n=process.cwd()){let r=e.trim();if(Xr(r))return r;if(De.isAbsolute(r)||/^[A-Za-z]:[\\/]/.test(r))return bt(r.replaceAll("\\",De.sep));let i=De.relative(t,n);return i.startsWith(`..${De.sep}`)||i===".."||De.isAbsolute(i)?bt(De.normalize(r)):bt(De.relative(t,De.resolve(n,r)))}async function ax(e,t=process.cwd(),n=process.cwd()){let r=[];for(let i of e){if(De.resolve(n,i.pattern)===De.resolve(n))continue;let o=De.isAbsolute(i.pattern),s=await HA(i.pattern,{cwd:n,absolute:o,onlyFiles:!0,dot:!0,expandDirectories:!1,followSymbolicLinks:!0}),a=[...new Set(s.map(c=>Zc(c,t,n)))].sort((c,d)=>c.localeCompare(d));for(let c of a)r.push({path:c,scope:i.scope,note:i.note})}return r}function cx(e,t,n){if(t===void 0)return e;if(!n)throw new p("--note requires --add or --add-glob in the same invocation (the note annotates the links being added)",m.USAGE);let r=t.trim();return r.length===0?e:e.map(i=>i.note===void 0?{...i,note:r}:i)}function ed(e){return`${e.path}::${e.scope}`}function rd(e){return[...e].sort((t,n)=>{let r=t.path.localeCompare(n.path);return r!==0?r:t.scope.localeCompare(n.scope)})}function id(e){return[...new Map(e.map(t=>[ed(t),t])).values()].map(t=>({...t,note:t.note?.trim()||void 0}))}async function dx(e,t=process.cwd()){let n=[...new Set(e)].sort((a,c)=>a.localeCompare(c)),r=[],i=[],o=[],s=[];for(let a of n){if(Xr(a)){s.push(a.trim());continue}let c=De.isAbsolute(a)?a:De.resolve(t,a);try{(await BA.stat(c)).isFile()?r.push(a):o.push(a)}catch(d){if(typeof d=="object"&&d!==null&&"code"in d&&Tn(d)){i.push(a);continue}o.push(a)}}return{checked:n.length,existing_files:r,missing_paths:i,non_file_paths:o,remote_references:s}}function lx(e,t,n,r){let i=0;for(let o=0;o<e.length;o+=1){let s=zn(e[o].path,r);s!==e[o].path&&(i+=1);let a=Mt(s);a!==e[o].path&&(e[o]={...e[o],path:a})}return{adds:t.map(o=>{let s=zn(o.path,r);return s!==o.path&&(i+=1),{...o,path:Mt(s)}}),removes:n.map(o=>Mt(zn(o,r))),count:i}}function Mt(e){return e.replaceAll("\\","/")}function Yc(e){return`${e.scope}\0${Mt(e.path)}`}function ux(e,t,n){let r=new Map(e.map(s=>[Yc(s),s.note])),i=new Map(t.map(s=>[Yc(s),s.note])),o=new Map;for(let s of n){let a=Yc(s);o.has(a)||o.set(a,{path:Mt(s.path),scope:s.scope,outcome:mx(r.has(a),r.get(a),i.get(a))})}return[...o.values()]}function mx(e,t,n){return e?n===t?"unchanged":t===void 0?"note_added":n?.startsWith(`${t}${Jc}`)?"note_appended":"note_replaced":"added"}function px(e,t,n){let r=e.merged.findIndex(s=>s.path===t.path&&s.scope===t.scope),i=e.merged[r];if(i===void 0){e.merged.push(t),t.note!==void 0&&e.notedHere.add(t);return}let o=YA(i.note,t.note,n);if(o.conflict)e.conflicts.push({path:t.path,scope:t.scope,existing_note:i.note,requested_note:t.note,source:e.notedHere.has(i)?"this_write":"stored"});else if(o.note!==i.note){let s={...i,note:o.note};e.merged[r]=s,e.notedHere.add(s)}}function _x(e,t,n,r,i){let o=id(e),s={merged:[...o],notedHere:new Set,conflicts:[]};for(let d of t)px(s,d,i);let{merged:a}=s,c=ux(o,a,t);if(n.length>0)for(let d=a.length-1;d>=0;d-=1)n.includes(a[d].path)&&a.splice(d,1);return{entries:r?a:rd(a),outcomes:c,conflicts:s.conflicts}}async function yy(e){let t=e.mutation?.entries??e.artifacts,n=e.options.validatePaths?e.artifacts:t,{counts:r,receipts:i}=qo(e.mutation);return{id:e.id,artifacts:t,changed:e.changed,count:t.length,...r,migrations_applied:e.migrationsApplied&&e.migrationsApplied>0?e.migrationsApplied:void 0,validation:e.options.validatePaths||e.changed&&n.length>0?await dx(n.map(o=>o.path),e.workspaceRoot):void 0,...i}}function fx(e,t,n){let r=new Map;for(let o of t){let s=ed(o);r.set(s,(r.get(s)??0)+1)}let i=0;for(let o of e){let s=ed({...o,path:Mt(zn(o.path,n))}),a=r.get(s)??0;a>0?r.set(s,a-1):i+=1}return i}function hx(e,t){let n=/[\n\r]|^\s*[-*+`]/u.test(e)?[]:Yu(e),r=n.findIndex(l=>l.key?.toLowerCase()==="note");if(r<0)return;let i=n.slice(0,r).map(l=>l.raw.trim()),o=new Set(n.slice(0,r).map(l=>l.key?.toLowerCase())),s=[n[r].value],a;for(let l of n.slice(r+1)){let u=l.key?.toLowerCase();if((u==="path"||u==="scope")&&!o.has(u)){i.push(l.raw.trim()),o.add(u);continue}a??=l.key===void 0?void 0:{segment:l.text.trim(),key:l.key},s.push(l.text)}if(a===void 0)return;let c=s.join(",").trim(),d=[...i,`note=${JSON.stringify(c)}`].join(",");try{nd([d],t)}catch{return}return{entry:d,note:c,...a}}function gx(e,t){return e.findIndex(n=>{try{return nd([n],t),!1}catch{return!0}})+1}function Go(e,t,n){return(t??[]).flatMap(r=>[e,n!==void 0&&r.trim()==="-"?`${n}=-`:r])}function wy(e){let{options:t}=e,n=e.noteConflict??t.noteConflict;return[...Ie(e.global),...e.guards.map(r=>`--expect-hash=${r}`),e.config.metadataKey,e.id,...Go("--add",e.entries.map((r,i)=>i===e.position-1?e.rewritten:r),"path"),...Go("--add-glob",e.resolved.addGlob,"pattern"),...Go("--remove",e.resolved.remove,"path"),...Go("--migrate",e.resolved.migrate),...t.note===void 0?[]:["--note",t.note],...n===void 0?[]:["--note-conflict",n],...e.config.supportsAppendStable&&t.appendStable===!0?["--append-stable"]:[],...t.validatePaths===!0?["--validate-paths"]:[],...t.fullHistory===!0?["--full-history"]:[],...t.author?["--author",t.author]:[],...t.message?["--message",t.message]:[],...t.force===!0?["--force"]:[]]}function yx(e){return Xc.some(t=>t===e.toLowerCase())?`If "${e}" was meant as a key, give it once per entry.`:`If "${e}" was meant as a key, it is not one of: ${Xc.join(", ")}.`}function wx(e){try{return nd(e.entries,e.config.bareNoun)}catch(t){let n=e.entries,r=t,i=gx(n,e.config.bareNoun),o=hx(n[i-1],e.config.bareNoun);if(o===void 0)throw t;let s=Cr(e.pmRoot),a=s===void 0?void 0:wy({...e,entries:n,position:i,rewritten:o.entry,guards:s});throw new p(`--add read the note segment "${o.segment}" as a new key "${o.key}", so the ${e.config.bareNoun} link was refused (${r.message})`,m.USAGE,{code:"linked_artifact_note_key_misread",flag:"--add",value:n[i-1],required:`Retry with the note quoted so its commas stay prose (${a===void 0?`as ${o.entry}; its revision guards cannot be replayed as typed, so no executable retry is offered`:"recovery.suggested_retry_args replays the whole invocation that way"}), or pass the prose through --note in a single-entry call. ${yx(o.key)}`,why:"After a comma, an identifier followed by = or : opens a new key, so that a typo such as lable=main is refused instead of being stored as note text (GH-258).",...a===void 0?{}:{nextSteps:[L(a)]},details:{entry_index:i,misread_segment:o.segment,misread_key:o.key,note:o.note,rewritten_entry:o.entry,cause:r.context.code??"invalid_argument_value"},...a===void 0?{}:{recovery:{suggested_retry:L(a),suggested_retry_args:a}}})}}function qo(e){return e===void 0?{counts:{},receipts:{}}:{counts:{total_count:e.total_count,returned_count:e.returned_count,has_more:e.has_more},receipts:{mutation_receipt:e.mutation_receipt,omission_receipt:e.omission_receipt}}}async function vx(e){let{settings:t,config:n}=e,r=await V(e.pmRoot,e.id,t.id_prefix,t.item_format,e.typeToFolder);if(!r)throw new p(`Item ${e.id} not found`,m.NOT_FOUND);let i=(await pe(r,{schema:t.schema})).document.metadata[n.metadataKey]??[],o=e.writeRequested?Qr({collectionKey:n.metadataKey,stored:i,written:[],removedCount:0,fullHistory:e.options.fullHistory===!0}):void 0;return yy({id:r.id,artifacts:i,changed:!1,options:e.options,workspaceRoot:e.workspaceRoot,mutation:o})}async function Ko(e,t,n,r){let{metadataKey:i}=r,o=En(),s=R(process.cwd(),n.path),a=lt(s),c=process.cwd();await j(s);let d=await x(s),l=P(d,N()),u=await o.resolveList(t.add,"--add"),_=await o.resolveList(t.addGlob,"--add-glob"),h=await o.resolveList(t.remove,"--remove"),f=await o.resolveList(t.migrate,"--migrate"),g=wx({id:e,pmRoot:s,entries:u,resolved:{addGlob:_,remove:h,migrate:f},options:t,global:n,config:r}).map(J=>({...J,path:Zc(J.path,a,c)})),y=rx(_),w=await ax(y,a,c),v=g.length>0||y.length>0,k=cx([...g,...w],t.note,v),S=VA(t.noteConflict,v),b=ix(h).map(J=>Zc(J,a,c)),A=ox(f);if(sx(k,b,A),!(k.length>0||b.length>0||A.length>0))return vx({id:e,pmRoot:s,settings:d,typeToFolder:l.type_to_folder,options:t,workspaceRoot:a,config:r,writeRequested:y.length>0});let E=U(t.author,d.author_default),C=[],O=0,M=[],T=await he({pmRoot:s,settings:d,id:e,op:r.op,author:E,message:t.message,force:t.force,skipNoop:!0,mutate(J){let Me=J.metadata,Pe=Me[i]??[],qe=[...Pe],re=lx(qe,k,b,A),be=_x(qe,re.adds,re.removes,r.supportsAppendStable&&t.appendStable===!0,S);if(be.conflicts.length>0){let rt=Cr(s);throw JA({itemId:J.metadata.id,noun:r.bareNoun,conflicts:be.conflicts,retryArgs:it=>rt===void 0?void 0:wy({id:J.metadata.id,entries:u??[],position:0,rewritten:"",resolved:{addGlob:_,remove:h,migrate:f},options:t,global:n,config:r,guards:rt,noteConflict:it}),render:L})}let Ee=be.entries;M=be.outcomes,Ee.length>0?Me[i]=Ee:delete Me[i];let nt=!Fe(Pe,Ee);return C=Pe,O=fx(Pe,Ee,A),{changedFields:nt?[i]:[],warnings:nt&&re.count>0?[`path_migrations_applied:${re.count}`]:[]}}}),F=T.item[i]??[],ue=T.warnings.find(J=>J.startsWith("path_migrations_applied:")),Ne=ue?Number(ue.slice(24)):0;return yy({id:T.item.id,artifacts:F,changed:T.changedFields.includes(i),migrationsApplied:Ne,options:t,workspaceRoot:a,mutation:Qr({collectionKey:i,stored:F,written:td(C,F),removedCount:O,fullHistory:t.fullHistory===!0,linkOutcomes:M})})}function Wo(e,t){let n={};for(let[r,i]of Object.entries(e))n[r==="artifacts"?t:r]=i;return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b1de9573-b582-502d-8fb1-9e6ba3a521b0")}catch{}})();async function vy(e,t,n){let r=await Ko(e,t,n,{metadataKey:"docs",op:"docs_add",bareNoun:"doc",supportsAppendStable:!1});return Wo(r,"docs")}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="67d97df8-6551-52ed-9307-8b573a087831")}catch{}})();var zo=1e6;function od(e,t=zo,n=.8,r=!1){let i=new Set,o=(l,u)=>{if(i.add(`${l}:${u}`),i.size>t)throw new p(`Duplicate sweep exceeded ${t} candidate pairs; narrow it with statuses or since.`,m.CONFLICT,{code:"duplicate_sweep_cost_limit",required:"Narrow the duplicate query or increase its similarity threshold. No partial result was returned."})};if(r||n===0){for(let l=0;l<e.length;l+=1)for(let u=0;u<l;u+=1)o(u,l);return i}let s=new Map;for(let{prepared:l}of e)for(let u of l.tokens)s.set(u,(s.get(u)??0)+1);let a=new Map,c=new Map,d=new Map;for(let[l,{prepared:u}]of e.entries()){let _=[...u.tokens].sort((g,y)=>s.get(g)-s.get(y)||g.localeCompare(y)),h=_.length-Math.ceil(n*_.length-1e-12)+1,f=[{index:a,keys:[u.normalized],lengthFilter:!1},{index:c,keys:n<=.99?u.issueCodes:[],lengthFilter:!1},{index:d,keys:_.length===0?[""]:_.slice(0,h),lengthFilter:!0}];for(let g of f)bx(e,l,g,n,o)}return i}function bx(e,t,n,r,i){let o=e[t].prepared.tokens.length;for(let s of n.keys){let a=n.index.get(s)??[];for(let c of a){let d=e[c].prepared.tokens.length;n.lengthFilter&&Math.min(d,o)/Math.max(d,o)+1e-12<r||i(c,t)}a.push(t),n.index.set(s,a)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a5f450bd-8970-5b1b-8250-b76b7818e6e1")}catch{}})();var kx=3,by=20,Sx=.8,Ex=100,ky=1e3;function Sy(e){return e===void 0?[]:[`likely_duplicates:${e.result.items.map(t=>t.id).join(",")}`,`likely_duplicate_recovery:${e.recovery.action}:${e.recovery.item_id}`]}async function Tx(e,t){let n=e.items[0],r=R(t.cwd??process.cwd(),t.pmRoot),i=W((await x(r)).schema);return fe(n.status,i)?{action:"reopen",item_id:n.id,command:`pm item reopen ${n.id} "<recurrence reason>"`,args:["item","reopen",n.id,"<recurrence reason>"]}:{action:"reuse",item_id:n.id,command:`pm get ${n.id} --full`,args:["get",n.id,"--full"]}}function sd(e){let t=e.limit??kx,n=e.threshold??Sx;if(!Number.isSafeInteger(t)||t<0||t>by)throw new p(`Similarity limit must be an integer from 0 to ${by}.`,m.USAGE);if(!Number.isFinite(n)||n<0||n>1)throw new p("Similarity threshold must be a number from 0 to 1.",m.USAGE);return{limit:t,threshold:n}}function Ey(e){let t=e.limit??Ex;if(!Number.isSafeInteger(t)||t<0||t>ky)throw new p(`Duplicate cluster limit must be an integer from 0 to ${ky}.`,m.USAGE);let n=e.since===void 0?void 0:new Date(e.since);if(n&&Number.isNaN(n.getTime()))throw new p("Duplicate cluster --since must be a valid ISO timestamp.",m.USAGE);return{limit:t,since:n}}async function Cx(e,t){let n=R(e.cwd??process.cwd(),e.pmRoot),r=await x(n),i=P(r),o=e.statuses?.map(u=>u.trim().toLowerCase()).filter(Boolean);if(e.statuses!==void 0&&o?.length===0)throw new p("Duplicate cluster statuses must include at least one lifecycle status or all.",m.USAGE);let s=W(r.schema),a=o?.map(u=>{if(u==="all")return u;let _=ce(u,s);if(!_)throw new p(`Unknown duplicate-cluster status "${u}". Allowed: all, ${s.definitions.map(h=>h.id).join(", ")}.`,m.USAGE);return _}),c=a?.includes("all")===!0;if(c&&a?.some(u=>u!=="all"))throw new p('The "all" status cannot be combined with other statuses.',m.USAGE);let d=c?void 0:a,l=d?new Set(d):void 0;return{items:(await Te(n,r.item_format,i.type_to_folder,void 0,r.schema)).filter(u=>(!l||l.has(u.status))&&(!t||new Date(u.created_at).getTime()>=t.getTime())),statuses:d}}var sK={buildDuplicateClusters:Cy,collectDuplicateCandidatePairs:od,createDuplicateUnionFind:Ty};function Ty(e){let t=Array.from({length:e},(n,r)=>r);return{parent:t,findRoot:n=>{let r=n;for(;t[r]!==r;)r=t[r];for(;t[n]!==n;){let i=t[n];t[n]=r,n=i}return r}}}function Ax(e,t,n,r){let i=[];for(let o of t){let[s,a]=o.split(":").map(u=>Number.parseInt(u,10)),c=tc(e[s].prepared,e[a].prepared);if(c.score<n)continue;let d=r.findRoot(s),l=r.findRoot(a);d!==l&&(r.parent[l]=d),i.push({left_id:e[s].item.id,right_id:e[a].item.id,...c})}return i}function Cy(e,t,n,r){let i=new Map;for(let a of e.keys()){let c=n.findRoot(a),d=i.get(c)??[];d.push(a),i.set(c,d)}let o=new Map(e.map(({item:a},c)=>[a.id,n.findRoot(c)])),s=new Map;for(let a of t){let c=o.get(a.left_id),d=s.get(c)??[];d.push(a),s.set(c,d)}return[...i.values()].filter(a=>a.length>1).map(a=>{let c=(s.get(n.findRoot(a[0]))??[]).sort((d,l)=>l.score-d.score||d.left_id.localeCompare(l.left_id)||d.right_id.localeCompare(l.right_id));return{id:e[a[0]].item.id,items:a.map(d=>{let l=e[d].item;return{id:l.id,title:l.title,status:l.status,type:l.type}}),matches:c,max_score:c[0]?.score??0}}).sort((a,c)=>c.max_score-a.max_score||a.id.localeCompare(c.id)).slice(0,r)}function xx(e,t,n,r,i){return t.filter(o=>!n.has(o.id)).map(o=>({id:o.id,title:o.title,status:o.status,type:o.type,...ec(e,o.title)})).filter(o=>o.score>=r).sort((o,s)=>s.score-o.score||o.id.localeCompare(s.id)).slice(0,i)}async function Rx(e,t={}){let n=e.title.trim();if(n.length===0)throw new p("Similarity candidate title must not be empty.",m.USAGE);let{limit:r,threshold:i}=sd(t),o=R(t.cwd??process.cwd(),t.pmRoot),s=await x(o),a=P(s),c=await po(o,Object.values(a.type_to_folder)),d=Qa(n),l=c&&d.length>0?await Lp({pmRoot:o,expectedSourceCursor:c.source_cursor,query:d.map(h=>`"${h.replaceAll('"','""')}"`).join(" OR "),limit:Math.max(r*10,50)}):null,u=l===null?await Te(o,s.item_format,a.type_to_folder,void 0,s.schema):l.items,_=xx(n,u,new Set(e.excludeIds??[]),i,r);return{items:_,count:_.length,threshold:i,source:l?"persistent_index":"metadata_fallback"}}function Ix(e,t={}){let{threshold:n}=sd({...t,limit:void 0}),{limit:r}=Ey(t),i=new Set;for(let l of e){if(!l.id.trim()||i.has(l.id))throw new p("Duplicate analysis requires unique non-empty item ids.",m.USAGE);i.add(l.id)}let o=[...e].sort((l,u)=>l.id.localeCompare(u.id)).map(l=>({item:l,prepared:Za(l.title)})),s=od(o,zo,n,t.exhaustive===!0),a=Ty(o.length),c=Ax(o,s,n,a),d=Cy(o,c,a,r);return{clusters:d,count:d.length,threshold:n,cost:{item_count:o.length,algorithm:t.exhaustive===!0||n===0?"exhaustive":"prefix_exact",possible_pairs:o.length*(o.length-1)/2,pair_limit:zo,recall_guarantee:"exact",candidate_pairs:s.size,scored_pairs:s.size}}}async function Ay(e={}){sd({...e,limit:void 0});let{since:t}=Ey(e),{items:n,statuses:r}=await Cx(e,t);return{...Ix(n,e),source:"metadata_scan",filters:{statuses:r??null,since:e.since??null}}}async function ad(e,t){if(t.mode==="off")return;let n=await Rx(e,t);if(n.count===0)return;let r=await Tx(n,t),i=t.mode==="strict"&&t.allowDuplicate===!0;if(t.mode==="strict"&&!i){let o=n.items.map(a=>`${a.id} (${a.status}): ${a.title}`).join("; "),s=r.action==="reopen"?"Reopen the canonical item":"Reuse the canonical item";throw new p(`Likely duplicate item(s) found: ${o}. ${s} or pass --allow-duplicate with explicit intent.`,m.CONFLICT,{code:"likely_duplicate",required:`${s}, or explicitly acknowledge the duplicate with --allow-duplicate.`,recovery:{suggested_flags:["--allow-duplicate"],suggested_retry:r.command,suggested_retry_args:r.args}})}return{mode:t.mode,bypassed:i,result:n,recovery:r}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="499dfc08-cf70-55fe-8868-65c3107e3a91")}catch{}})();async function lK(e,t={}){let n=await Ay({pmRoot:R(process.cwd(),e.path),exhaustive:t.exhaustive,...t.status===void 0?{}:{statuses:t.status.flatMap(r=>r.split(",").map(i=>i.trim()).filter(Boolean))},...t.since===void 0?{}:{since:t.since},...t.threshold===void 0?{}:{threshold:t.threshold},...t.limit===void 0?{}:{limit:t.limit}});return{...n,clusters:n.clusters.map(r=>{let i=r.id;return{...r,canonical_id:i,close_command:`pm close <duplicate-id> --duplicate-of ${i}`}}),guidance:{strategy:"review_then_close_duplicate",command:"pm close <duplicate-id> --duplicate-of <canonical-id>"}}}import{execFile as Ox}from"node:child_process";import xy from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="15749905-177d-5ae0-b475-668733f41e8a")}catch{}})();function Ry(e,t){return new Promise((n,r)=>{Ox("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:4*1024*1024},(i,o)=>{i?r(i):n(o)})})}function Iy(e){if(e&&(!Number.isSafeInteger(e.start)||!Number.isSafeInteger(e.end)||e.start<1||e.end<e.start))throw new RangeError("Source line range must be inclusive positive integers with end >= start.")}function fK(e){let t=/^(\d+):(\d+)$/u.exec(e.trim()),n=t?{start:Number(t[1]),end:Number(t[2])}:void 0;if(Iy(n),!n)throw new RangeError("Source line range must use start:end.");return n}function Lx(e){let t=new Map;for(let n of e.split(`
|
|
7
|
-
`)){let r=/^([0-9a-f^]{40,64}) \d+ \d+(?: \d+)?$/u.exec(n)?.[1];r&&t.set(r,(t.get(r)??0)+1)}return t}function Dx(e){let t=e.split("\0"),n=new Map;for(let r=0;r+1<t.length;r+=2){let i=t[r]?.trim();if(!i)continue;let o=[...new Set(t[r+1]?.match(/\bpm-[a-z0-9][a-z0-9-]{2,63}\b/gu)??[])].sort((s,a)=>s.localeCompare(a));n.set(i,o)}return n}async function $x(e){let t=xy.relative(e.workspaceRoot,xy.resolve(e.workspaceRoot,e.sourcePath)),n=await Ry(e.workspaceRoot,["blame","--line-porcelain","-L",`${e.lineRange.start},${e.lineRange.end}`,"--",t]),r=await Ry(e.workspaceRoot,["log","-n","256","--format=%H%x00%B%x00","--",t]);return{commitLines:Lx(n),commitItems:Dx(r),available:!0}}function Nx(e){let t=e.current.nodes.at(-1),n=e.current.kinds.length+1,r;for(let i of e.graph.incidentEdges(t)){let o=i.source===t,s=o?i.target:i.source;if((e.visitedDepth.get(s)??Number.POSITIVE_INFINITY)<n)continue;e.visitedDepth.set(s,n);let a=e.graph.registry().require(i.kind),c={nodes:[...e.current.nodes,s],kinds:[...e.current.kinds,o?i.kind:a.inverse??i.kind]};e.details.get(s)?.type?.toLowerCase()==="decision"?(r=n,e.found.push(c)):e.queue.push(c)}return r}function Mx(e){let t=[{nodes:[e.itemId],kinds:[]}],n=new Map([[e.itemId,0]]),r=[],i;for(;t.length>0;){let o=t.shift(),s=o.kinds.length;i!==void 0&&s>=i||s>=e.maxDepth||(i=Nx({current:o,graph:e.graph,details:e.details,visitedDepth:n,queue:t,found:r})??i)}return r.sort((o,s)=>o.nodes.join("\0").localeCompare(s.nodes.join("\0"))),r}function Px(e,t,n){let r=lh(t);if(!r.graph.hasNode(e))return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let i=Mx({itemId:e,maxDepth:n,graph:r.graph,details:new Map(r.details.map(a=>[a.id,a]))}),o=i[0];if(!o)return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let s=[...new Set(i.map(a=>a.nodes.at(-1)))];return{status:s.length===1?"found":"ambiguous",nodes:o.nodes,kinds:o.kinds,alternative_decision_ids:s.slice(1)}}async function Fx(e){if(!e.lineRange)return{commitLines:new Map,commitItems:new Map,available:!0};try{return await $x({workspaceRoot:e.workspaceRoot,sourcePath:e.paths[0],lineRange:e.lineRange})}catch{return{commitLines:new Map,commitItems:new Map,available:!1}}}function jx(e){let t=[];return e.hasLineRange&&!e.attributionAvailable&&t.push("git_attribution_unavailable"),e.hasLineRange&&e.contributionLines===0&&t.push("line_attribution_unmapped"),e.decisionStatus==="ambiguous"&&t.push("multiple_governing_decisions"),e.decisionStatus==="not_found"&&t.push("governing_decision_not_found"),t}function Ux(e){return[...e.commitLines.keys()].filter(t=>(e.commitItems.get(t)?.length??0)>0)}async function Oy(e){Iy(e.lineRange);let t=e.decisionDepth??8;if(!Number.isSafeInteger(t)||t<1||t>32)throw new RangeError("Decision path depth must be an integer from 1 to 32.");let n=await Fx(e),r=Ux(n),i=new Map;for(let o of e.candidates){let s=[...n.commitLines.entries()].filter(([l])=>n.commitItems.get(l)?.includes(o.item.id)),a=s.reduce((l,[,u])=>l+u,0),c=Px(o.item.id,e.corpus,t),d=jx({hasLineRange:e.lineRange!==void 0,attributionAvailable:n.available,contributionLines:a,decisionStatus:c.status});i.set(o.item.id,{score:a*100+o.files.length*10+Math.max(0,9-Math.floor((Date.now()-Date.parse(o.item.updated_at))/(720*60*60*1e3))),contribution_lines:a,evidence:[...o.files.map(l=>({kind:"linked_file",reference:l.path})),...s.map(([l,u])=>({kind:"git_commit",reference:l.slice(0,12),contribution_lines:u}))],rationale:{value:o.item.value?.trim()||null,why_now:o.item.why_now?.trim()||null,outcome:o.item.outcome?.trim()||null,objective:o.item.objective?.trim()||null},decision_path:c,ambiguities:d})}return{explanations:i,receipt:{line_range:e.lineRange??null,blamed_commit_count:n.commitLines.size,mapped_commit_count:r.length,unmapped_commit_count:n.commitLines.size-r.length,decision_depth:t}}}import Ly from"node:fs/promises";import Be from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ad4d4093-7e23-5361-bec4-efb37bd610b6")}catch{}})();var Gx=32768;function cd(e){return bt(Be.normalize(e))}async function Bo(e){try{return await Ly.realpath(e)}catch{return Be.resolve(e)}}function Bn(e,t){let n=Be.isAbsolute(e.path)?Be.resolve(e.path):Be.resolve(t,e.path);return`${cd(n)}::${e.scope}`}function Ho(e,t,n){if(typeof e=="string"){let r=e.trim();r.length>0&&n.push({field:t,value:r});return}if(Array.isArray(e)){e.forEach((r,i)=>Ho(r,`${t}[${i}]`,n));return}if(typeof e=="object"&&e!==null)for(let[r,i]of Object.entries(e))Ho(i,t?`${t}.${r}`:r,n)}function qx(e){let t=[];return Ho(e.metadata,"metadata",t),Ho(e.body,"body",t),t}function Kx(e){let t=e.trim();return t=t.replace(/^[`"'<([{]+/u,""),t=t.replace(/[`"'>)\]},;!?]+$/u,""),t=t.replace(/[.]+$/u,""),t=t.replace(/:(?:\d+)(?::\d+)?$/u,""),t=t.replace(/[.]+$/u,""),t}function Wx(e){let t=[],n=/(?:[A-Za-z]:[\\/]|\/)[^\s"'`<>()[\]{},;]+/gu,r=/(?:\.{1,2}[\\/])?(?:(?:[A-Za-z0-9_.@-]+[\\/])+[A-Za-z0-9_.@-]+|[A-Za-z0-9_.@-]+\.[A-Za-z0-9][A-Za-z0-9._-]*)/gu;for(let i of e){let o=new Set,s=i.value.slice(0,Gx);for(let[a,c]of[[n,i.value],[r,s]]){a.lastIndex=0;for(let d of c.matchAll(a)){let l=Kx(d[0]);!l||o.has(l)||(o.add(l),t.push({field:i.field,value:l}))}}}return t}async function zx(e,t,n=t){let r=Be.isAbsolute(e)?Be.resolve(e):Be.resolve(n,e),i;try{i=await Ly.stat(r)}catch{return}if(!i.isFile())return;let[o,s]=await Promise.all([Bo(t),Bo(r)]);if(Pa(o,s)){let a=Be.relative(o,s);return!a||a.startsWith("..")||Be.isAbsolute(a)?void 0:{path:cd(a),scope:"project"}}return{path:cd(r),scope:"global"}}async function Bx(e,t,n=t){let r=new Set((e.metadata.files??[]).map(c=>Bn(c,t))),i=new Map,o=Wx(qx(e)),s=new Map;await Promise.all([...new Set(o.map(c=>c.value))].map(async c=>{s.set(c,await zx(c,t,n))}));let a=o.map(c=>({reference:c,resolved:s.get(c.value)}));for(let{reference:c,resolved:d}of a){if(!d)continue;let l=Bn(d,t),u=i.get(l)??{path:d.path,scope:d.scope,sourceFields:new Set,originalPaths:new Set,sourceCount:0};u.sourceFields.add(c.field),u.originalPaths.add(c.value),u.sourceCount+=1,i.set(l,u)}return[...i.entries()].map(([c,d])=>({path:d.path,scope:d.scope,status:r.has(c)?"already_linked":"addable",source_count:d.sourceCount,source_fields:[...d.sourceFields].sort((l,u)=>l.localeCompare(u)),original_paths:[...d.originalPaths].sort((l,u)=>l.localeCompare(u))})).sort((c,d)=>{let l=c.status.localeCompare(d.status);if(l!==0)return l;let u=c.path.localeCompare(d.path);return u!==0?u:c.scope.localeCompare(d.scope)})}async function Dy(e,t,n){let r=await Ko(e,t,n,{metadataKey:"files",op:"files_add",bareNoun:"file",supportsAppendStable:!0});return Wo(r,"files")}async function Hx(e,t){let n=await Bo(t),r=await Promise.all(e.map(async o=>{let s=o.trim();if(!s)throw new p("Files lookup paths must not be empty.",m.USAGE);if(!Be.isAbsolute(s))return bt(s);let a=await Bo(s);return Pa(n,a)?bt(Be.relative(n,a)):bt(a)})),i=[...new Set(r)].sort((o,s)=>o.localeCompare(s));if(i.length===0)throw new p("Files lookup requires at least one path.",m.USAGE);return i}function Vx(e){for(let[r,i]of[["limit",e.limit],["offset",e.offset]])if(i!==void 0&&(!Number.isInteger(i)||i<0))throw new p(`Files lookup ${r} must be a non-negative integer.`,m.USAGE);let{offset:t=0,limit:n=50}=e;return{offset:Math.max(0,Math.floor(t)),limit:e.noTruncate?void 0:Math.max(0,Math.floor(n))}}function $y(e){return{id:e.id,title:e.title,type:e.type,status:e.status,priority:e.priority,updated_at:e.updated_at}}function Ny(e,t){let n=e.item.priority-t.item.priority;if(n!==0)return n;let r=t.item.updated_at.localeCompare(e.item.updated_at);return r===0?e.item.id.localeCompare(t.item.id):r}function Yx(e){return e.metadata.map(t=>({item:t,files:(t.files??[]).filter(n=>e.paths.includes(bt(n.path))&&(e.scope===void 0||n.scope===e.scope)).sort((n,r)=>{let i=n.path.localeCompare(r.path);return i===0?n.scope.localeCompare(r.scope):i})})).filter(t=>t.files.length>0).sort(Ny)}async function Jx(e){if(e.explain)return Oy({workspaceRoot:e.workspaceRoot,paths:e.paths,candidates:e.matching,corpus:e.metadata,...e.lineRange?{lineRange:e.lineRange}:{},...e.decisionDepth===void 0?{}:{decisionDepth:e.decisionDepth}})}async function Xx(e){if([e.strictRead,e.noTruncate,e.explain,Um()].includes(!0))return null;let t=await po(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]);return t?Op({pmRoot:e.pmRoot,expectedSourceCursor:t.source_cursor,paths:e.paths,scope:e.scope,limit:e.limit,offset:e.offset}):null}async function Qx(e){let t=[],n=await _o(e.pmRoot,e.settings.item_format,e.typeToFolder,t,e.settings.schema),r=Yx({metadata:n,paths:e.paths,scope:e.scope}),i=t.filter(a=>/^item_list_(?:item|directory)_read_failed:/u.test(a));if(e.strictRead&&i.length>0)throw new p(`Files lookup could not read every item: ${i.join("; ")}`,m.GENERIC_FAILURE);let o=await Jx({explain:e.explain,workspaceRoot:e.workspaceRoot,paths:e.paths,matching:r,metadata:n,lineRange:e.lineRange,decisionDepth:e.decisionDepth}),s=(o?[...r].sort((a,c)=>{let d=o.explanations.get(c.item.id).score-o.explanations.get(a.item.id).score;return d!==0?d:Ny(a,c)}):r).slice(e.offset,e.limit===void 0?void 0:e.offset+e.limit);return{paths:e.paths,total:r.length,count:s.length,offset:e.offset,limit:e.limit??null,has_more:e.offset+s.length<r.length,truncated:e.offset+s.length<r.length,completeness:{status:i.length===0?"complete":"partial",source:"source_scan"},warnings:t,matches:s.map(a=>({item:$y(a.item),files:a.files,...o?{traceability:o.explanations.get(a.item.id)}:{}})),...o?{traceability_receipt:o.receipt}:{}}}async function DK(e,t){let n=R(process.cwd(),t.path),r=lt(n);await j(n);let i=await Hx(e.paths,r);if(e.lineRange&&i.length!==1)throw new p("Files lookup line attribution requires exactly one source path.",m.USAGE);let o=await x(n),s=P(o,N()),{offset:a,limit:c}=Vx(e),d=await Xx({pmRoot:n,typeToFolder:s.type_to_folder,paths:i,scope:e.scope,limit:c,offset:a,strictRead:e.strictRead===!0,noTruncate:e.noTruncate===!0,explain:e.explain===!0||e.lineRange!==void 0});return d?{paths:i,total:d.total,count:d.matches.length,offset:a,limit:c,has_more:a+d.matches.length<d.total,truncated:a+d.matches.length<d.total,completeness:{status:"unchecked",source:"index"},warnings:[],matches:d.matches.map(l=>({item:$y(l.item),files:l.files}))}:Qx({pmRoot:n,settings:o,typeToFolder:s.type_to_folder,paths:i,scope:e.scope,limit:c,offset:a,strictRead:e.strictRead===!0,workspaceRoot:r,explain:e.explain===!0||e.lineRange!==void 0,lineRange:e.lineRange,decisionDepth:e.decisionDepth})}async function $K(e,t,n){let r=R(process.cwd(),n.path),i=lt(r);await j(r);let o=await x(r),s=P(o,N()),a=await V(r,e,o.id_prefix,o.item_format,s.type_to_folder);if(!a)throw new p(`Item ${e} not found`,m.NOT_FOUND);let c=await pe(a,{schema:o.schema}),d=await Bx(c.document,i,process.cwd()),l=d.filter(C=>C.status==="addable"),u=d.filter(C=>C.status==="already_linked"),_=t.apply===!0,h=t.note?.trim()||"discovered from item text";if(!_||l.length===0){let C=c.document.metadata.files??[];return{id:a.id,files:C,changed:!1,apply:_,count:C.length,candidate_count:d.length,addable_count:l.length,added_count:0,skipped_existing_count:u.length,candidates:d,added:[],skipped_existing:u}}let f=U(t.author,o.author_default),g=l.map(C=>({path:C.path,scope:C.scope,note:h})),y=[],w=new Set,v=await he({pmRoot:r,settings:o,id:e,op:"files_discover",author:f,message:t.message??"Discover referenced file links",force:t.force,mutate(C){let O=[...C.metadata.files??[]],M=new Set(O.map(ue=>Bn(ue,i)));y=[],w.clear();for(let[ue,Ne]of g.entries()){let J=Bn(Ne,i);M.has(J)||(O.push(Ne),M.add(J),y.push(Ne),w.add(ue))}let T=id(O),F=t.appendStable?T:rd(T);return F.length>0?C.metadata.files=F:delete C.metadata.files,{changedFields:y.length>0?["files"]:[],warnings:y.length!==g.length?[`files_discover_skipped_existing:${g.length-y.length}`]:[]}}}),k=v.item.files??[],S=new Set(y.map(C=>Bn(C,i))),b=k.filter(C=>S.has(Bn(C,i))),A=l.filter((C,O)=>!w.has(O)),E=[...u,...A];return{id:v.item.id,files:k,changed:b.length>0,apply:!0,count:k.length,candidate_count:d.length,addable_count:l.length,added_count:b.length,skipped_existing_count:E.length,candidates:d,added:b,skipped_existing:E}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bee6d15d-ca4a-538c-bb70-fd3dc7e2a8ec")}catch{}})();var Zr=["software-delivery","research","agent-evaluation","operations"];function My(e,t,n,r,i){return{id:e,measurement_id:t,owner_item_id:n,scope:{kind:"active"},ceiling:r,lifetime:"hold",enforcement:i,negative_control:{cases:[{observed:r,expected:"pass"},{observed:r+1,expected:"fail"}]}}}function Vo(e,t,n,r,i){let o=`preset-${e}`,s=i.map(c=>({id:`${o}-missing-${c}`,description:`Active items missing ${c} evidence.`,source:{kind:"links",link:c,state:"missing"}})),a=s.map(c=>My(`${c.id}-zero`,c.id,r,0,"warn"));return{id:e,title:t,description:n,declarations:{measurements:s,assertions:a,gates:[{id:`${o}-readiness`,description:n,assertion_ids:a.map(c=>c.id),triggers:["ci","scheduled"]}]}}}function Yo(e,t){return e==="software-delivery"?Vo(e,"Software delivery","Warn when active delivery work lacks executable tests or documentation.",t,["tests","docs"]):e==="research"?Vo(e,"Research","Warn when active research work lacks reproducibility files or documentation.",t,["files","docs"]):e==="agent-evaluation"?Vo(e,"Agent evaluation","Warn when active evaluation work lacks executable scenarios or recorded artifacts.",t,["tests","files"]):Vo(e,"Operations","Warn when active operational work lacks runbook documentation or repair evidence.",t,["docs","files"])}function Py(e,t,n,r={}){return Wc(e,Yo(t,n).declarations,r)}async function Fy(e,t){let n=new Set(e.terminal_statuses??["closed","canceled"]),r={...e,items:e.items.filter(i=>!n.has(i.status))};return await Promise.all(["files","tests","docs"].map(async i=>{let o={id:`derived-active-missing-${i}`,description:`Observed active items missing ${i} evidence.`,source:{kind:"links",link:i,state:"missing"}},s=(await Kc(o,r)).value,a=My(`${o.id}-ceiling`,o.id,t,s,"observe"),c=`active-missing-${i}`;return{id:c,population_size:r.items.length,scope:{kind:"active"},observed:s,declarations:{measurements:[o],assertions:[a],gates:[{id:`derived-${c}`,description:`Observe the accepted ${i} evidence baseline.`,assertion_ids:[a.id],triggers:["ci","scheduled"]}]}}}))}function jy(e,t,n={}){return Wc(e,{measurements:t.flatMap(r=>r.declarations.measurements),assertions:t.flatMap(r=>r.declarations.assertions),gates:t.flatMap(r=>r.declarations.gates)},n)}async function Uy(e,t,n,r={}){let i=t.enforcement==="observe"?"warn":"block";if(t.enforcement==="block"||n!==i)throw new TypeError(`assurance assertion ${t.id} promotion must be ${t.enforcement} -> ${i}`);return Po(e,"assertion",{...t,enforcement:n},{...r,message:r.message??`Promote assurance assertion ${t.id} from ${t.enforcement} to ${n}`})}import Ky from"node:fs/promises";import{createRequire as Zx}from"node:module";import Ue from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="32adaa7c-f0aa-5aff-8d88-d7c0ccfbd971")}catch{}})();function Gy(e,t){let n=Ue.relative(t,e);if(n.length>0&&n!==".."&&!n.startsWith(`..${Ue.sep}`)&&!Ue.isAbsolute(n))return n.split(Ue.sep).join("/");let r=Ue.resolve(e),i=0xcbf29ce484222325n;for(let o=0;o<r.length;o+=1)i^=BigInt(r.charCodeAt(o)),i=BigInt.asUintN(64,i*0x100000001b3n);return`<external>/${i.toString(16).padStart(16,"0")}/${Ue.basename(Ue.dirname(e))}/package.json`}function eR(e){return e.includes(`${Ue.sep}.pnpm${Ue.sep}`)?"pnpm":e.includes(`${Ue.sep}node_modules${Ue.sep}`)?"npm":"other"}async function qy(e){try{let t=JSON.parse(await Ky.readFile(e,"utf8"));return t.name==="@unbrained/pm-cli"&&typeof t.version=="string"&&t.version.trim().length>0?t.version.trim():void 0}catch{return}}async function dd(e){try{return await Ky.realpath(e)}catch{return Ue.resolve(e)}}async function Wy(e,t,n=Tm(import.meta.url,["../../.."])){let r=await dd(t),i=await dd(Ue.join(n,"package.json")),o=await qy(i),s=new Map;o!==void 0&&s.set(i,{version:o,path:Gy(i,r),layout:"host",consumers:["pm-cli-host"]});for(let d of e)try{let l=Zx(d.entry_path).resolve("@unbrained/pm-cli/package.json"),u=await dd(l),_=await qy(u);if(_===void 0)continue;let h=u,f=s.get(h);if(f){f.consumers.includes(d.name)||(f.consumers.push(d.name),f.consumers.sort((g,y)=>g.localeCompare(y)));continue}s.set(h,{version:_,path:Gy(u,r),layout:eR(u),consumers:[d.name]})}catch{}let a=[...s.values()].sort((d,l)=>d.path.localeCompare(l.path)),c=o===void 0?[]:a.filter(d=>d.version!==o);return{host_version:o??null,copies:a,mismatches:c,warnings:c.map(d=>`extension_host_pm_cli_version_skew:${o}:${d.version}:${d.consumers.join("+")}`)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c3200eea-d2c8-5813-87e8-df765f7b6c7a")}catch{}})();var zy=25;function tR(e,t,n=[]){let r=["list","--status",e,...n],i=["--assignee-filter","unassigned"],o=["--updated-before",`-${t}h`];return{unowned:L([...r,...i]),idle:L([...r,...o]),stale:L([...r,...i,...o])}}function By(e,t){let n=e.items.length>zy;return{count:e.count,items:e.items.slice(0,zy),...n?{truncated:!0}:{},sweep:t}}function Hy(e,t,n=[]){let r=tR(t.in_progress,e.threshold_hours,n),i=(s,...a)=>`pm ${s} <id>${[...a,...n].map(c=>` ${_m(c)}`).join("")}`,o=[...e.unowned.count>0?[`in_progress_unowned:${e.unowned.count}`]:[],...e.idle.count>0?[`in_progress_idle:${e.idle.count}`]:[]];return{warnings:o,details:o.length===0?void 0:{threshold_hours:e.threshold_hours,threshold_setting:"mutation_guard.stale_in_progress_hours",unowned:By(e.unowned,r.unowned),idle:By(e.idle,r.idle),item_remedies:{claim:i("claim"),take_over_idle:i("claim","--takeover-stale"),return_to_open:i("update","--status",t.open)}},remediation:{stale_in_progress_items:r.stale,in_progress_unowned:r.unowned,in_progress_idle:r.idle}}}import{createHash as nR}from"node:crypto";import Jo from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="36749195-9194-546a-bc3e-718f09c3b8d6")}catch{}})();var rR="2026-08-09T16:15:18.000Z",Yy=Symbol("pre-durable-disposition-eligible");function kt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ld(e){if(!Array.isArray(e)||e.length>256)return!1;let t=new Set;for(let n=0;n<e.length;n+=1){let r=e[n];if(!(n in e)||typeof r!="string"||r.length===0||r.length>256||r.includes("\0")||t.has(r))return!1;t.add(r)}return!0}function Vy(e){return kt(e)?typeof e.field=="string"&&e.field.length>0&&e.field.length<=256&&!e.field.includes("\0")&&typeof e.retained_hash=="string"&&/^[a-f0-9]{64}$/u.test(e.retained_hash)&&typeof e.discarded_hash=="string"&&/^[a-f0-9]{64}$/u.test(e.discarded_hash):!1}function Jy(e,t){if(typeof e!="string")return!1;let n=Jo.posix.normalize(e);return e.length<=4096&&!e.includes("\\")&&!e.includes("\0")&&!Jo.posix.isAbsolute(e)&&n===e&&!n.startsWith("../")&&(Jo.posix.basename(n)===`${t}.toon`||Jo.posix.basename(n)===`${t}.md`)}function iR(e,t){return typeof e.receipt_id=="string"&&Fr(e.receipt_id)&&(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0&&e.conflict_resolution===void 0&&e.item_id===t&&Jy(e.item_path,t)}function Xy(e){let t=e.conflict_fields,n=e.fields_from_theirs,r=e.union_fields,i=e.decisions,o=Array.isArray(i)?new Set(i.flatMap(s=>Vy(s)?[s.field]:[])):new Set;return ld(t)&&ld(n)&&ld(r)&&Array.isArray(i)&&i.length>0&&i.length<=256&&Object.keys(i).length===i.length&&i.every(Vy)&&o.size===i.length&&t.length===o.size&&t.every(s=>o.has(s))}function oR(e,t){return iR(e,t)&&Xy(e)}function sR(e,t){return typeof e.receipt_id=="string"&&Fr(e.receipt_id)&&(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0&&(e.conflict_resolution==="preferred_side"||e.conflict_resolution==="stable_value_order")&&e.item_id===t&&Jy(e.item_path,t)&&Xy(e)}function aR(e){return e[Yy]===!0}function Qy(e,t){if(!kt(e)||!kt(e.context))return[];let n=e.context.merge;return!kt(n)||!Array.isArray(n.receipts)?[]:n.receipts.flatMap(r=>!kt(r)||typeof r.receipt_id!="string"||r.receipt_id.trim().length===0?[]:[{receiptId:r.receipt_id,legacySummaryAccepted:oR(r,t),[Yy]:sR(r,t),...typeof e.ts=="string"&&Ga(e.ts)?{eventTimestamp:e.ts}:{}}])}function Zy(e,t,n){if(!kt(e)||e.op!=="merge_reconcile")return[];if(!kt(e.context)||!kt(e.context.merge))return[];let r=e.context.merge.missing_receipt_dispositions;return!Array.isArray(r)||r.length>256?[]:r.flatMap(i=>!kt(i)||typeof i.receipt_id!="string"||!Fr(i.receipt_id)||typeof i.original_history_line!="number"||!Number.isSafeInteger(i.original_history_line)||i.original_history_line<1||typeof i.original_event_ts!="string"||!Ga(i.original_event_ts)||i.reason!=="legacy_clone_local_only"?[]:[{itemId:t,receiptId:i.receipt_id,originalHistoryLine:i.original_history_line,originalEventTimestamp:i.original_event_ts,auditHistoryLine:n,reason:i.reason}])}function ew(e,t,n=[]){let r=new Map;for(let o of n){let s=`${o.itemId}\0${o.originalHistoryLine}\0${o.receiptId}\0${o.originalEventTimestamp}`;r.set(s,Math.max(r.get(s)??0,o.auditHistoryLine))}let i=o=>aR(o)&&o.eventTimestamp!==void 0&&zi(o.eventTimestamp,rR)<0&&(r.get(`${o.itemId}\0${o.line}\0${o.receiptId}\0${o.eventTimestamp}`)??0)>o.line;return{missing:e.filter(o=>!o.legacySummaryAccepted&&!t.has(o.receiptId)&&!i(o)).map(o=>({item_id:o.itemId,history_line:o.line,...Fr(o.receiptId)?{receipt_id:o.receiptId}:{receipt_reference_hash:nR("sha256").update(o.receiptId).digest("hex")}})),acceptedLegacyCount:e.filter(o=>o.legacySummaryAccepted).length,acceptedDispositionCount:e.filter(i).length}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d8f1968e-a030-5a3c-b766-60a409163745")}catch{}})();function Xo(e,t,n=25){let r=e.definitions.filter(s=>s.roles.length===0).map(s=>s.id).sort((s,a)=>s.localeCompare(a)),i=new Set(r),o=t.filter(s=>{let a=Je(s.status,e);return a!==void 0&&i.has(a)}).map(s=>s.id).sort((s,a)=>s.localeCompare(a));return{roleless_status_count:r.length,roleless_statuses:r.slice(0,n),roleless_statuses_truncated:r.length>n,affected_item_count:o.length,affected_item_ids:o.slice(0,n),affected_item_ids_truncated:o.length>n}}function Qo(e){return e.roleless_status_count===0?[]:[`schema_status_missing_lifecycle_role:${e.roleless_status_count}`]}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1b5c9f97-33fb-5318-8bec-3aa033ef7c25")}catch{}})();var nw=8,ud=100;function rw(e,t){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function Qe(e,t){return Array.isArray(e)?{count:e.length,sample:e.slice(0,t),truncated:e.length>t}:{count:0,sample:[],truncated:!1}}function cR(e){if(typeof e!="object"||e===null||Array.isArray(e))return{};let t=e;return{layer:t.layer,directory:t.directory,name:t.name,version:t.version,enabled:t.enabled,status:t.status,has_activate:t.has_activate,capabilities:t.capabilities}}function ei(e,t){let n=Qe(e,t);return{...n,sample:n.sample.map(r=>cR(r))}}function B(e,t){if(!Array.isArray(e))return{count:0,sample:[],truncated:!1};let n=e.filter(r=>typeof r=="string");return{count:n.length,sample:n.slice(0,t),truncated:n.length>t}}function dR(e){if(typeof e!="object"||e===null)return null;let t=e;return{applied_count:t.applied_count,pending_count:t.pending_count,failed_count:t.failed_count}}var lR={settings:(e,t)=>({version:e.version,id_prefix:e.id_prefix,locks_ttl_seconds:e.locks_ttl_seconds,warnings:B(e.warnings,t)}),directories:(e,t)=>({required_count:Array.isArray(e.required)?e.required.length:0,optional_count:Array.isArray(e.optional)?e.optional.length:0,missing_required:B(e.missing_required,t),missing_optional:B(e.missing_optional,t),missing:B(e.missing,t),strict_directories:e.strict_directories}),settings_values:(e,t)=>({warnings:B(e.warnings,t)}),telemetry:e=>({enabled:e.enabled,capture_level:e.capture_level,endpoint:e.endpoint,queue_exists:e.queue_exists,queue_entries:e.queue_entries,queue_draining:e.queue_draining,queue_invalid_rows:e.queue_invalid_rows,queue_rows_total:e.queue_rows_total,last_successful_flush_at:e.last_successful_flush_at,last_failed_flush_at:e.last_failed_flush_at,endpoint_probe:e.endpoint_probe,env_overrides:e.env_overrides}),extensions:(e,t)=>{let n=typeof e.activation=="object"&&e.activation!==null?e.activation:{};return{disabled_by_flag:e.disabled_by_flag,discovered:ei(e.discovered,t),effective:ei(e.effective,t),loaded:ei(e.loaded,t),failed:Qe(e.failed,t),warnings:B(e.warnings,t),activation:{failed:Qe(n.failed,t),warnings:B(n.warnings,t),hook_counts:n.hook_counts,command_handler_count:n.command_handler_count,service_override_count:n.service_override_count,renderer_override_count:n.renderer_override_count,registration_counts:n.registration_counts,migration_status:dR(n.migration_status)},author_manifest:e.author_manifest,triage:e.triage,capability_contract:e.capability_contract,capability_guidance:Qe(e.capability_guidance,t),host_version_census:e.host_version_census}},storage:(e,t)=>{let n=typeof e.author_attribution=="object"&&e.author_attribution!==null?e.author_attribution:void 0;return{...e,...n?{author_attribution:{...n,affected_item_ids:B(n.affected_item_ids,t),samples:Qe(n.samples,t)}}:{}}},locks:e=>({active_lock_count:e.active_lock_count,stale_lock_count:e.stale_lock_count,unreadable_lock_count:e.unreadable_lock_count,unparseable_lock_count:e.unparseable_lock_count}),integrity:(e,t)=>{let n=typeof e.tracked_runtime_cache=="object"&&e.tracked_runtime_cache!==null?e.tracked_runtime_cache:void 0;return{checked_item_files:e.checked_item_files,checked_history_streams:e.checked_history_streams,counts:e.counts,item_unreadable:B(e.item_unreadable,t),item_conflict_markers:Qe(e.item_conflict_markers,t),item_parse_failures:B(e.item_parse_failures,t),tracked_runtime_cache:n===void 0?e.tracked_runtime_cache:{...n,tracked_paths:B(n.tracked_paths,t)},history_unreadable:B(e.history_unreadable,t),history_conflict_markers:Qe(e.history_conflict_markers,t),history_invalid_json:Qe(e.history_invalid_json,t),skipped:e.skipped}},history_drift:(e,t)=>{let n=typeof e.cache_confirmation=="object"&&e.cache_confirmation!==null?e.cache_confirmation:void 0;return{checked_items:e.checked_items,cache_hit_verification:e.cache_hit_verification,cache_confirmation:n===void 0?e.cache_confirmation:{...n,candidate_items:B(n.candidate_items,t),confirmed_items:B(n.confirmed_items,t),resolved_false_positive_items:B(n.resolved_false_positive_items,t)},counts:e.counts,drifted_items:B(e.drifted_items,t),merge_receipt_attributed_items:B(e.merge_receipt_attributed_items,t),missing_streams:B(e.missing_streams,t),unreadable_streams:B(e.unreadable_streams,t),hash_mismatches:B(e.hash_mismatches,t),chain_mismatches:B(e.chain_mismatches,t),version_skews:B(e.version_skews,t),workspace_state_mismatches:B(e.workspace_state_mismatches,t),workspace_state_missing:B(e.workspace_state_missing,t),workspace_state_unreadable:B(e.workspace_state_unreadable,t),skipped:e.skipped}},vectorization:(e,t)=>({semantic_runtime_available:e.semantic_runtime_available,compatibility_mode_auto_defaults:e.compatibility_mode_auto_defaults,auto_ollama_defaults_applied:e.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:e.auto_ollama_defaults_skipped_reason,auto_ollama_defaults_remediation:e.auto_ollama_defaults_remediation,refresh_policy:e.refresh_policy,provider_active:e.provider_active,vector_store_active:e.vector_store_active,items:e.items,ledger_entries_before:e.ledger_entries_before,stale_items_before_total:e.stale_items_before_total,stale_items_before:B(e.stale_items_before,t),refresh_attempted:e.refresh_attempted,refresh_skipped_reason:e.refresh_skipped_reason,refresh_result:e.refresh_result,ledger_entries_after:e.ledger_entries_after,stale_items_after_total:e.stale_items_after_total,stale_items_after:B(e.stale_items_after,t),skipped:e.skipped})};function md(e,t){let n=lR[e.name];return n?n(e.details,t):e.details}function iw(e){return{disabled_by_flag:e.details.disabled_by_flag,loaded_count:Array.isArray(e.details.loaded)?e.details.loaded.length:0,failed_count:0,warning_count:0,restore_with:"pm health --full"}}function uR(e){if(e.name==="extensions"&&e.status==="ok")return iw(e);let t=md(e,8);return Buffer.byteLength(JSON.stringify(t))<Buffer.byteLength(JSON.stringify(e.details))?t:e.details}function pd(e,t){let n=new Set([...t,...e.failed_because]);return(e.findings??[]).filter(r=>n.has(r.warning))}function mR(e){let t=B(e.warnings,8);return{ok:e.ok,...e.verdict?{verdict:e.verdict}:{},checks:e.checks.map(n=>({name:n.name,status:n.status,ok:n.ok,details:uR(n)})),warnings:t.sample,findings:pd(e,t.sample),failed_because:e.failed_because,projection:{mode:"brief",warning_count:t.count,warnings_truncated:t.truncated,detail_limit:8},generated_at:e.generated_at}}function tw(e){return e.details.skipped===!0}function pR(e){let t=B(e.warnings,8),n=e.checks.filter(tw).map(r=>r.name);return{ok:e.ok,...e.verdict?{verdict:e.verdict}:{},checks:e.checks.filter(r=>!tw(r)).map(r=>({name:r.name,status:r.status,ok:r.ok,details:{}})),warning_count:t.count,warnings:t.sample,findings:pd(e,t.sample),failed_because:e.failed_because,projection:{mode:"summary",warning_count:t.count,warnings_truncated:t.truncated,detail_limit:8,omitted_checks:n},generated_at:e.generated_at}}function _R(e,t,n){return n?pR(e):t.brief===!0?mR(e):t.full===!0?e:{...e,checks:e.checks.map(r=>r.name==="extensions"&&r.status==="ok"?{...r,details:iw(r)}:r),projection:{mode:"standard",warning_count:e.warning_count,warnings_truncated:e.warnings_truncated===!0,detail_limit:8}}}function _d(e,t,n){let r=e.warning_count??e.warnings.length,i=e.warnings.slice(0,100),o={...e,warning_count:r,warning_limit:100,warnings_truncated:r>100,warnings:i,findings:pd(e,i)},s=_R(o,t,n);return{...s,warning_count:r,warning_limit:100,warnings_truncated:r>s.warnings.length,...s.projection?{projection:{...s.projection,warning_count:r,warnings_truncated:r>s.warnings.length}}:{}}}import St from"node:fs/promises";import ge from"node:path";import Hn from"node:fs/promises";import ti from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b01042e0-77ae-5e2c-8118-6680f0002d60")}catch{}})();function ow(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t,{id:r,owner:i,created_at:o,ttl_seconds:s}=n;return typeof r!="string"||typeof i!="string"||typeof o!="string"||typeof s!="number"||!Number.isFinite(s)?null:{id:r,owner:i,created_at:o,ttl_seconds:s,pid:n.pid,host_identity:n.host_identity,process_start_identity:n.process_start_identity}}function fR(e,t,n){let r=ow(t);if(r===null)return{detail:"unparseable_json",entry:{file:e,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"}};let i=Date.parse(r.created_at);if(!Number.isFinite(i))return{detail:"invalid_timestamp",entry:{file:e,id:r.id,owner:r.owner,created_at:r.created_at,ttl_seconds:r.ttl_seconds,age_seconds:null,stale:!1,reason:"unparseable"}};let o=n-i,s=Math.floor(o/1e3),a=o>r.ttl_seconds*1e3;return{detail:a?"expired":"active",entry:{file:e,id:r.id,owner:r.owner,created_at:r.created_at,ttl_seconds:r.ttl_seconds,age_seconds:s,stale:a,reason:a?"expired":"active"}}}async function sw(e,t,n){let r=fR(e,t,n);if(r.detail!=="active")return r;let i=ow(t),o=await Rm(i);return o==="unknown"?r:{detail:o==="dead"?"owner_dead":"active",entry:{...r.entry,owner_state:o,pid:i.pid,...o==="dead"?{stale:!0,reason:"owner_dead"}:{}}}}async function hR(e,t,n){let r=await Om(e,"gc");if(r===null)return!1;try{let i;try{i=await Hn.readFile(e,"utf8")}catch(o){if(G(o))return!0;throw o}if(i!==t)return!1;n&&await Lm(e,t);try{await Hn.unlink(e)}catch(o){if(!G(o))throw o}return!0}finally{await r()}}function gR(e,t,n){t==="owner_dead"&&(e.owner_dead_lock_samples??=[],e.owner_dead_lock_samples.length<20&&e.owner_dead_lock_samples.push(n)),t==="active"?e.active_lock_count+=1:t==="expired"||t==="owner_dead"?e.stale_lock_count+=1:e.unparseable_lock_count+=1}async function aw(e,t){let n=t??Date.now(),r=ti.join(e,"locks"),i={scanned:0,active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0},o;try{o=(await Hn.readdir(r)).filter(s=>s.endsWith(".lock")).sort()}catch(s){if(G(s))return i;throw s}for(let s of o){let a;try{a=await Hn.readFile(ti.join(r,s),"utf8")}catch(l){if(G(l))continue;i.scanned+=1,i.unreadable_lock_count+=1;continue}i.scanned+=1;let{detail:c,entry:d}=await sw(s,a,n);gR(i,c,d)}return i}async function yR(e,t,n,r,i,o,s){if(!t.dryRun){try{if(!await hR(n,o,s.reason==="owner_dead")){e.warnings.push(`lock_changed_or_busy:${i}`),e.retained.push(r),e.entries.push(s);return}}catch{e.warnings.push(`lock_remove_failed:${i}`),e.retained.push(r),e.entries.push(s);return}if(t.hooks?.onWrite){let a=await t.hooks.onWrite(n);e.warnings.push(...a)}}e.removed.push(r),e.entries.push(s)}async function cw(e,t){let{hooks:n}=t,r=t.now??Date.now(),i=ti.join(e,"locks"),o={scanned:0,removed:[],retained:[],warnings:[],entries:[]};await xm(e,ti.join(i,"gc.lock"),"gc");let s;try{s=(await Hn.readdir(i)).filter(a=>a.endsWith(".lock")).sort()}catch(a){if(G(a))return o;throw a}for(let a of s){o.scanned+=1;let c=ti.join(i,a),d=`locks/${a}`;if(n?.onRead){let _=await n.onRead(c);o.warnings.push(..._)}let l;try{l=await Hn.readFile(c,"utf8")}catch(_){if(G(_)){o.scanned-=1;continue}o.warnings.push(`lock_unreadable:${a}`),o.retained.push(d),o.entries.push({file:a,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let u=await sw(a,l,r);if(u.detail==="unparseable_json"){o.warnings.push(`lock_unparseable:${a}`),o.retained.push(d),o.entries.push(u.entry);continue}if(u.detail==="invalid_timestamp"){o.warnings.push(`lock_invalid_timestamp:${a}`),o.retained.push(d),o.entries.push(u.entry);continue}if(u.detail==="active"){o.retained.push(d),o.entries.push(u.entry);continue}await yR(o,t,c,d,a,l,u.entry)}return o}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f9317f5b-f007-5882-aafe-898d1f76f2ae")}catch{}})();var wR=Object.freeze([{code:"missing_directory",command:"pm init",summary:"Recreate missing tracker directories (pm init is idempotent and restores the scaffold)."},{code:"settings_read_fs_error",command:"pm config list --json",summary:"settings.json could not be read as a regular file and pm fell back to defaults; repair the reported path or permissions, then re-run."},{code:"settings_read_invalid_json",command:"pm config list --json",summary:"settings.json is not valid JSON and pm fell back to defaults; fix the syntax error in the reported path, then re-run."},{code:"settings_read_invalid_schema",command:"pm config list --json",summary:"settings.json failed schema validation and pm fell back to defaults; correct the reported key in the file, then re-run."},{code:"settings_read_merge_failed",command:"pm config list --json",summary:"Global/project settings could not be merged; reconcile the conflicting keys in the reported settings files."},{code:"settings:id_prefix_empty",command:"pm config list --json",summary:'id_prefix is empty; set a non-empty "id_prefix" in settings.json so generated item ids are well-formed.'},{code:"settings:locks_ttl_non_positive",command:"pm config list --json",summary:'locks.ttl_seconds must be positive; set a positive "locks.ttl_seconds" in settings.json.'},{code:"telemetry_state_invalid_json",command:"pm health --check-telemetry",summary:"Local telemetry state file is corrupt; pm recreates it on the next flush. Advisory only."},{code:"telemetry_queue_invalid_rows",command:"pm health --check-telemetry",summary:"The telemetry queue has unparseable rows; they are skipped on the next flush. Advisory only."},{code:"telemetry_queue_pending",command:"pm health --check-telemetry",summary:"Telemetry events are queued; they flush automatically on the next reachable command. Advisory only."},{code:"telemetry_queue_high_retries",command:"pm telemetry flush",summary:"Some queued telemetry events are near retry exhaustion; flush now and verify endpoint reachability before entries are dropped."},{code:"telemetry_endpoint_probe_failed",command:"pm health --check-telemetry",summary:"The telemetry endpoint is unreachable; events stay queued until it recovers. Advisory only."},{code:"telemetry_endpoint_probe_http_status",command:"pm health --check-telemetry",summary:"The telemetry endpoint returned a non-success status; events stay queued until it recovers. Advisory only."},{code:"telemetry_schema_version_behind",command:"pm health --check-telemetry",summary:"Client schema is behind server; upgrade pm-cli to emit the latest event shape."},{code:"telemetry_otel_export_failing",command:"pm health --check-telemetry",summary:"OTLP trace spans are queued but the traces endpoint export is failing; spans retry automatically on the next reachable command, or set PM_TELEMETRY_OTEL_DISABLED=1 to skip OTLP export. Advisory only."},{code:"merge_driver_configuration_missing",command:"pm merge install",summary:"Install the clone-local Git drivers required by the tracker merge fence."},{code:"merge_driver_configuration_drift",command:"pm merge install",summary:"Reinstall clone-local Git drivers after runtime or package paths change."},{code:"merge_fence_missing",command:"pm merge install",summary:"Install the active tracker's committed Git merge attributes."},{code:"merge_fence_drift",command:"pm merge install",summary:"Restore the active tracker's merge mappings while retaining sibling tracker fences."},{code:"validate_merge_driver_configuration",command:"pm merge install",summary:"Restore missing or drifted clone-local Git merge driver commands."},{code:"integrity_item_unreadable",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file could not be read; restore or repair the file at the reported path."},{code:"integrity_item_parse_failed",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file failed to parse; fix the malformed item metadata at the reported path."},{code:"integrity_item_conflict_marker",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file contains Git conflict markers; resolve the <<<<<<< / >>>>>>> markers at the reported line."},{code:"integrity_history_unreadable",command:"pm history-repair <id>",summary:"A history stream could not be read; re-anchor the affected item's history chain."},{code:"integrity_history_invalid_json",command:"pm history-repair <id>",summary:"A history stream contains invalid JSON; re-anchor the affected item's history chain."},{code:"integrity_history_conflict_marker",command:"pm history-repair <id>",summary:"A history stream contains Git conflict markers; resolve the markers, then re-anchor the chain."},{code:"validate_storage_unreadable_items",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"An on-disk item file cannot be parsed (for example a botched merge resolution with stale TOON count headers); repair or restore the file at the reported path \u2014 list commands silently skip it while pm get hard-errors."},{code:"validate_storage_duplicate_item_ids",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"One item id is claimed by multiple item documents \u2014 usually two branches minting the same id for different items before merging (GH-600). Keep one document, recreate the other item under a fresh id (pm copy, then delete the colliding file), and consider raising ids.token_length for concurrent multi-agent work."},{code:"validate_storage_history_conflict_markers",command:"pm merge driver history <base> <ours> <theirs>",summary:"A history stream contains unresolved Git conflict markers; re-merge it with the pm history merge driver (or resolve the markers by hand), then run pm history-repair for the item."},{code:"validate_storage_unparseable_history",command:"pm history-repair <id>",summary:"A history stream's newest line is not valid JSONL; repair or restore the stream before further mutations."},{code:"validate_storage_resurrected_items",command:"pm delete <id>",summary:"A live item's newest history operation is a delete: a delete/modify merge silently resurrected it. Decide the winner \u2014 re-delete the item, or keep it and append a mutation documenting the revival."},{code:"validate_storage_unparseable_config",command:"pm merge driver json <base> <ours> <theirs>",summary:"settings.json or a schema file cannot be parsed, so pm silently falls back to defaults; re-merge it with the pm JSON merge driver or fix the file by hand, then rerun pm validate."},{code:"validate_merge_fence_drift",command:"pm merge install",summary:"The committed .gitattributes merge fence no longer matches the active schema's type folders or tracker JSONL stores; rerun pm merge install (and commit .gitattributes) so every tracker artifact keeps its field-aware merge driver."},{code:"validate_storage_tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command, commit the index-only removals and managed .gitignore fence, then rerun validation."},{code:"integrity_item_outdated_format_version",command:"pm validate --verbose-diagnostics",summary:"An item predates the current storage format version; a pm storage migration rewrites it. Use --verbose-diagnostics to list the affected items."},{code:"integrity_item_ahead_format_version",command:"npm install -g @unbrained/pm-cli@latest",summary:"An item was written by a newer pm format version than this runtime supports; upgrade pm to read and validate it safely."},{code:"tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command from the integrity check, commit the index-only removals, and keep the managed .gitignore fence."},{code:"merge_artifacts_ignored",command:"pm health --check-only --full",summary:"Remove or narrow the owning ignore rules listed in integrity.ignored_merge_artifacts. Merge receipts must be committed with their audit history; preserve those files, then preview pm merge reconcile --stage --dry-run before applying settlement."},{code:"merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:'Review pending receipt summaries, re-apply intended discarded values, then run pm merge reconcile. If proof is unavailable or receipt decisions are lossy, explicit review authority is required for pm merge reconcile --force --message "<reviewed receipt disposition and rationale>"; this records acceptance rather than restoring discarded values.'},{code:"merge_receipts_pending",command:"pm merge reconcile",summary:'A lossless receipt is pending; preview with pm merge reconcile --dry-run, then apply. If no receipt set proves the snapshot, review the summaries and only with explicit authority run pm merge reconcile --force --message "<reviewed receipt disposition and rationale>" to record an audited acceptance.'},{code:"merge_receipt_evidence_invalid",command:"pm merge report --include-reconciled --json",summary:"One or more receipt candidates failed bounded-file, schema, identity, or copy-consistency validation; inspect the report's privacy-safe source, receipt id, and reason before repairing only the named evidence."},{code:"merge_receipt_history_reference_missing",command:"pm merge reconcile --dry-run",summary:"Review the bounded coordinates and recover available evidence first; for exact pre-durable clone-local-only references, rerun with --force so pm appends an audited disposition and proves the health finding is cleared without rewriting history."},{code:"validate_merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:"Review the pending merge receipts before reconciliation; history-repair alone does not settle them, and lossy receipts require explicit --force acceptance."},{code:"history_drift_missing_stream",command:"pm history-repair <id>",summary:"The item has no history stream; re-anchor the chain to rebuild it (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_unreadable_stream",command:"pm history-repair <id>",summary:"The item's history stream is unreadable; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_hash_mismatch",command:"pm history-repair <id>",summary:"The item's content hash no longer matches its history; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_chain_mismatch",command:"pm history-repair <id>",summary:"The item's history chain is broken; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_version_skew",command:"npm install -g @unbrained/pm-cli@latest",summary:"A history stream declares an item hash version this runtime does not support; upgrade pm to verify the chain instead of re-anchoring it."},{code:"history_drift_merge_receipt",command:"pm merge reconcile",summary:"Canonical path, changed-field, and merged-value hash evidence attributes this drift to a pending receipt; run reconciliation (optionally preview first with --dry-run) instead of repairing history directly."},{code:"history_stream_over_compact_threshold",command:"pm history-compact <id>",summary:"The history stream exceeds the configured compaction threshold; compact it (pm history-compact --all-streams sweeps every over-threshold stream in one pass)."},{code:"stale_in_progress_items",command:"pm list --status in_progress --assignee-filter unassigned --updated-before -72h",summary:"List unowned in-progress candidates idle past mutation_guard.stale_in_progress_hours by metadata time (pm health substitutes the configured status id and threshold); claim each with pm claim <id> or return it to open with pm update <id> --status open."},{code:"in_progress_unowned",command:"pm list --status in_progress --assignee-filter unassigned",summary:"List in-progress items nobody holds (pm health substitutes the configured status id); claim each with pm claim <id> or return it to open with pm update <id> --status open."},{code:"in_progress_idle",command:"pm list --status in_progress --updated-before -72h",summary:"List in-progress candidates not updated within mutation_guard.stale_in_progress_hours (pm health substitutes the configured status id and threshold; a restored item can appear although its history is recent); resume, release or return each one, or take another holder's with pm claim <id> --takeover-stale, which re-judges under the item lock."},{code:"history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"provenance_value_domain_invalid",command:"pm history-repair --all --normalize-provenance",summary:"Remove invalid bounded provenance observations from affected streams and append privacy-safe aggregate repair receipts."},{code:"validate_history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"locks_stale_count",command:"pm gc --scope locks",summary:"Stale item-claim locks (embedded ttl elapsed) can block mutations; sweep them \u2014 gc retains active and unparseable locks."},{code:"locks_unreadable",command:"pm gc --scope locks --dry-run",summary:"Some lock files could not be read; preview the sweep and inspect the unreadable files manually \u2014 gc never deletes what it cannot read."},{code:"extension_update_health_partial_coverage",command:"pm extension --adopt-all --project",summary:"Update-health coverage is partial because unmanaged extensions were skipped; adopt the existing installs into managed metadata so the update scan covers them (use --global for global-scope extensions, or pm package --adopt-all when working with packages)."},{code:"vectorization_stale_items_remaining",command:"pm health --refresh-vectors",summary:"Some items have stale embeddings; refresh vectors so semantic search results stay current."},{code:"vectorization_embedding_identity_changed",command:"pm reindex --mode semantic",summary:"Embedding provider/model changed since the last index; run a semantic reindex to rebuild vectors."},{code:"validate_metadata_missing_closed_at",command:"pm validate --check-metadata --auto-fix --fix-scope timestamps --dry-run",summary:"Preview closure dates proven by verified lifecycle history; inspect residuals and omit --dry-run to apply only proven dates."},{code:"validate_metadata_missing_acceptance_criteria",command:'pm update <id> --acceptance-criteria "<criteria>"',summary:"Backfill the missing acceptance criteria on the reported item(s)."},{code:"validate_metadata_missing_estimate",command:'pm update <id> --estimate "<estimate>"',summary:"Backfill the missing estimate on the reported item(s)."},{code:"validate_metadata_missing_close_reason",command:'pm update <id> --close-reason "<reason>"',summary:"Backfill the missing close reason on the reported closed item(s)."},{code:"validate_metadata_missing_reviewer",command:'pm update <id> --reviewer "<name>"',summary:"Backfill the missing reviewer on the reported item(s)."},{code:"validate_metadata_missing_risk",command:'pm update <id> --risk "<level>"',summary:"Backfill the missing risk on the reported item(s)."},{code:"validate_metadata_missing_confidence",command:'pm update <id> --confidence "<level>"',summary:"Backfill the missing confidence on the reported item(s)."},{code:"validate_metadata_missing_sprint",command:'pm update <id> --sprint "<sprint>"',summary:"Backfill the missing sprint on the reported item(s)."},{code:"validate_metadata_missing_release",command:'pm update <id> --release "<release>"',summary:"Backfill the missing release on the reported item(s)."},{code:"validate_metadata_custom_profile_missing_required_fields",command:'pm config set metadata-required-fields --criterion "<field>"',summary:"Config-driven finding: the custom metadata profile has no required fields configured and falls back to core, so configure the fields rather than mutating items."},{code:"validate_metadata_duplicate_issue_codes",command:'pm update <id> --title "<distinct title>"',summary:"Two or more items share one logical issue code (GH-235); give each a distinct title so the derived code is unique, or close the redundant item with pm close <id> --duplicate-of <canonical-id> (closed-as-duplicate items are excluded from the check)."},{code:"validate_resolution_missing_fields",command:'pm update <id> --resolution "<how resolved>"',summary:"Backfill resolution / expected_result / actual_result on the reported closed item(s)."},{code:"validate_lifecycle_active_closure_like_metadata",command:"pm update <id> --unset <closure-like-field>",summary:"Clear the closure-like field the validator flags on this active item \u2014 the detail row names it (resolution / actual-result / blocked-reason) \u2014 or close the item if it is actually done."},{code:"validate_lifecycle_active_terminal_parent",command:"pm update <id> --parent <active-parent-id>",summary:"Reopen the terminal parent or move the active child under a non-terminal parent."},{code:"validate_lifecycle_stale_blockers",command:"pm update <id> --unset blocked-by --unset blocked-reason",summary:"Resolve the stale blocker the validator flags: clear blocked-by/blocked-reason when they linger on a non-blocked item or report a resolved blocker; if instead a blocked item is missing blocker context, add the context or move it out of a blocked status."},{code:"validate_lifecycle_dependency_cycles_error",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_lifecycle_dependency_cycles",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_hierarchy_parent_cycle_error",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_hierarchy_parent_cycle",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_files_missing_linked_paths",command:"pm <files|docs> <id> --remove <path>",summary:"The check spans both item.files and item.docs under one code: restore the missing linked artifact, or unlink it with pm files (linked file) or pm docs (linked doc)."},{code:"validate_files_orphaned_paths",command:"pm <files|docs> <id> --add <path>",summary:"Link the orphaned artifact with pm files (file) or pm docs (doc), or remove it from the workspace."},{code:"validate_files_tracked_all_strict_forces_pm_internals",command:"pm validate --check-files --include-pm-internals",summary:"tracked-all-strict scan flagged pm internals; re-run with --include-pm-internals or a softer --scan-mode."},{code:"validate_history_drift_missing_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items missing a history stream."},{code:"validate_history_drift_unreadable_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with an unreadable history stream."},{code:"validate_history_drift_hash_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items whose content hash drifted."},{code:"validate_history_drift_chain_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with a broken history chain."},{code:"validate_history_drift_version_skews",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more history streams declare an item hash version this runtime does not support; upgrade pm to verify the chains instead of re-anchoring them."},{code:"validate_command_references_stale_pm_ids",command:'pm update <id> --replace-tests --test "command=<corrected-command>" [--test ...]',summary:"Correct the stale pm-ID inside the item's linked test command (the check scans tests[].command, not the body). --replace-tests overwrites the entire tests list, so re-include the item's other linked tests in the same call."},{code:"validate_format_version_outdated_items",command:"pm validate --verbose-diagnostics",summary:"One or more items predate the current storage format version; a pm storage migration rewrites them. Use --verbose-diagnostics to list the affected items."},{code:"validate_format_version_ahead_items",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more items were written by a newer pm format version than this runtime supports; upgrade pm to read and validate them safely."}]);function fd(e){if(typeof e!="string")return;let t=e.trim();for(let n of wR)if(t===n.code||t.startsWith(`${n.code}:`))return n}function hd(e){let t={};for(let n of e){let r=fd(n);r!==void 0&&!Object.prototype.hasOwnProperty.call(t,r.code)&&(t[r.code]=r.command)}return t}function dw(e){return Object.values(hd(e))}import{execFile as vR}from"node:child_process";import{realpath as bR}from"node:fs/promises";import lw from"node:path";import{promisify as kR}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9af87d55-dbe2-561b-9f3f-6f12c0416147")}catch{}})();var SR=kR(vR),ER=32*1024*1024,TR=1e4,CR=["search/eval-queries.json"];function gd(e){return e.replaceAll("\\","/").replace(/\/+$/,"")}function AR(e){return`'${e.replaceAll("'","'\\''")}'`}async function xR(e,t=bR){return t(e).catch(()=>lw.resolve(e))}async function Zo(e){let t=await Dt(e);if(t===null)return{git_workspace_root:null,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let n=await xR(e),r=gd(lw.relative(t,n));if(r.length===0)return{git_workspace_root:t,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let i=mh.map(o=>`${r}/${gd(o)}`);try{let{stdout:o}=await SR("git",["ls-files","-z","--",...i.map(d=>`:(literal)${d}`)],{cwd:t,encoding:"utf8",maxBuffer:ER,windowsHide:!0,timeout:TR}),s=new Set(CR.map(d=>`${r}/${d}`)),a=[...new Set(o.split("\0").filter(d=>d.length>0&&!s.has(gd(d))))].sort((d,l)=>d.localeCompare(l)),c=i.filter(d=>a.some(l=>l===d||l.startsWith(`${d}/`)));return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:a,tracked_path_count:a.length,remediation_command:a.length===0?null:`git rm --cached -r -- ${c.map(d=>AR(`:(literal)${d}`)).join(" ")}`}}catch{return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:[],tracked_path_count:0,remediation_command:null}}}import uw from"node:path";import{realpath as RR}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7637003b-61ed-52eb-849c-eaf098df2963")}catch{}})();async function mw(e,t){let n=t===null?[]:await Th(t,[uw.relative(t,uw.join(await RR(e),"merge-receipts","00000000-0000-4000-8000-000000000000.json")).replaceAll("\\","/")]);return{rules:n,warnings:n.length>0?[`merge_artifacts_ignored:${n.length}`]:[]}}async function pw(e,t,n,r){if(t===null)return{audit:null,count:0,warnings:[]};let i=await Nn(e,$n(n));if(i.status==="ok")return{audit:i,count:0,warnings:[]};let o=Math.max(1,i.missing_patterns.length+i.stale_patterns.length);return{audit:i,count:o,warnings:r?[`merge_fence_${i.status==="not_installed"?"missing":"drift"}:${o}`]:[]}}function _w(e){let t=[];return e.invalidEvidenceCount>0&&t.push(`merge_receipt_evidence_invalid:${e.invalidEvidenceCount}`),e.missingHistoryReferenceCount>0&&t.push(`merge_receipt_history_reference_missing:${e.missingHistoryReferenceCount}`),t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b30e1b22-1dee-52b2-af2b-3f3af31334d5")}catch{}})();var IR=5;function es(e,t){let n=[],r={};for(let o of e){let s=ro(o);if(s.length!==0){for(let a of s)r[a.field]=(r[a.field]??0)+1;n.push({id:o.id,fields:s.map(a=>a.field),reasons:[...new Set(s.map(a=>a.reason))]})}}if(n.length===0)return;n.sort((o,s)=>o.id.localeCompare(s.id));let i=t?n.length:IR;return{details:{items:n.length,by_field:Object.fromEntries(Object.entries(r).sort(([o],[s])=>o.localeCompare(s))),rows:n.slice(0,i),truncated:n.length>i},warning:`validate_metadata_deferred_fields:${n.length}`}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="034a58e5-51de-5865-aa25-423e2a03c32e")}catch{}})();var gw=25,OR=ge.join("runtime","telemetry","events.jsonl"),LR=ge.join("runtime","telemetry","state.json"),DR=2500,$R=500,yw=Yp-3,NR=["x-pm-telemetry-max-schema-version","x-pm-telemetry-max-version"];function Sd(e,t=!1){return e.startsWith("agent_guidance_")||e.startsWith("telemetry_")||e.startsWith("extension_disabled_pm_")||e.startsWith("history_stream_over_compact_threshold:")||e.startsWith("integrity_legacy_hierarchy_")||e.startsWith("stale_in_progress_items:")||e.startsWith("in_progress_unowned:")||e.startsWith("in_progress_idle:")||e.startsWith("provenance_resolver_zero_success:")||e.startsWith("provenance_value_domain_invalid:")||!t&&e.startsWith("merge_driver_configuration_missing:")}function Ed(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function Vn(e){return e.trim().toLowerCase()}function vd(e,t){let n=Vn(e),r=Vn(t);return n.startsWith("builtin-")?!0:r==="beads"||r==="todos"}async function Td(e){try{return(await St.stat(e)).isDirectory()}catch{return!1}}async function MR(e){let t=(await St.readdir(e,{withFileTypes:!0})).filter(r=>r.isDirectory()),n=await Promise.all(t.map(r=>St.readdir(ge.join(e,r.name),{withFileTypes:!0})));return new Set(n.flatMap(r=>r.filter(i=>i.isFile()).filter(i=>zt.some(o=>i.name.endsWith(o))).map(i=>ge.parse(i.name).name)))}async function PR(e,t,n,r){let i=await We({path:e,scope:"project"}),o=t!=="_workspace"&&!r.has(t);if(!n.enabled&&!o)return{warnings:i,overThreshold:!1,classification:"live"};let s;try{s=await St.readFile(e,"utf8")}catch{return{warnings:i,overThreshold:!1,classification:"unreadable"}}let a="live";if(o){let d=s.split(/\r?\n/).map(l=>l.trim()).filter(Boolean).at(-1);try{a=JSON.parse(d??"{}").op==="delete"?"tombstone":"orphaned"}catch{a="orphaned"}}let c=n.enabled?s.split(/\r?\n/).filter(d=>d.trim().length>0).length:0;return{warnings:i,overThreshold:n.enabled&&c>n.max_entries,classification:a}}async function FR(e,t,n){let r=ge.join(e,"history");if(!await Td(r))return{count:0,warnings:[],over_threshold:[],max_entries:null,tombstones:[],orphaned:[]};let i=(await St.readdir(r)).filter(l=>l.endsWith(".jsonl")).sort((l,u)=>l.localeCompare(u)),o=t.enabled?t.max_entries:null,s=[],a=[],c=[],d=[];for(let l of i){let u=ge.join(r,l),_=l.slice(0,-6),h=await PR(u,_,t,n);s.push(...h.warnings),h.classification==="tombstone"&&c.push(_),h.classification==="orphaned"&&d.push(_),h.overThreshold&&a.push(_)}return{count:i.length,warnings:[...s,...a.map(l=>`history_stream_over_compact_threshold:${l}`),...d.map(l=>`history_orphaned_stream:${l}`)],over_threshold:a,max_entries:o,tombstones:c,orphaned:d}}function bd(e,t){return ge.relative(e,t).replaceAll("\\","/")}async function ww(e,t){let n=[...new Set(Object.values(t))].sort((i,o)=>i.localeCompare(o)),r=[];for(let i of n){let o=ge.join(e,i),s=[];try{s=await St.readdir(o)}catch(a){if(typeof a=="object"&&a!==null&&"code"in a&&G(a))continue;continue}for(let a of s)zt.some(c=>a.toLowerCase().endsWith(c))&&r.push(ge.join(o,a))}return r.sort((i,o)=>bd(e,i).localeCompare(bd(e,o))),r}function jR(e){return!(typeof e=="object"&&e!==null&&"code"in e&&G(e))}function UR(e){let t=es(e,!1);return t===void 0?{}:{curation:{deferred_fields:t.details}}}async function GR(e,t,n){let r=await ww(e,t),i=[],o=[],s=[],a=[],c=At(N());for(let d of r){let l=bd(e,d),u;try{u=await St.readFile(d,"utf8")}catch{i.push(l);continue}let _=Rn(u);if(_){o.push({path:l,..._});continue}try{let h=io(u,{format:om(d),schema:n,extensionFieldNames:c});a.push({ref:l,version:to(h.metadata)})}catch{s.push(l)}}return{paths:r,unreadable:i,conflictMarkers:o,parseFailures:s,formatVersions:a}}async function qR(e){let t=ge.join(e,"history"),n=[],r=[],i=[],o=[],s=[],a=[];try{a=(await St.readdir(t)).filter(c=>c.endsWith(".jsonl")).sort((c,d)=>c.localeCompare(d))}catch(c){jR(c)&&n.push("history")}for(let c of a){let d=c.slice(0,-6),l;try{l=await St.readFile(ge.join(t,c),"utf8")}catch{n.push(d);continue}let u=Rn(l);if(u){r.push({id:d,...u});continue}l.split(/\r?\n/).forEach((_,h)=>{if(_.trim())try{let f=JSON.parse(_);o.push(...Qy(f,d).map(g=>({itemId:d,line:h+1,...g}))),s.push(...Zy(f,d,h+1))}catch{i.push({id:d,line:h+1})}})}return{files:a,unreadable:n,conflictMarkers:r,invalidJson:i,mergeReceiptReferences:o,mergeReceiptDispositions:s}}function vw(e){return[...e.cycles.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_cycle:${t.item_ids.join(",")}`:`integrity_hierarchy_cycle:${t.item_ids.join(",")}`),...e.cardinality_violations.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_cardinality:${t.child_id}`:`integrity_hierarchy_cardinality:${t.child_id}`),...e.divergences.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_divergence:${t.child_id}`:`integrity_hierarchy_divergence:${t.child_id}`)]}async function KR(e,t,n,r,i,o){let s=await GR(e,t,n),a=await qR(e),c=no(s.formatVersions,Sr,eo),d=W(n),l=To(o,T=>fe(T,d),de()),u=await Zo(e),_=await Dt(e),h=await mw(e,_),f=await pw(e,_,r,i),g=_===null?null:await Mn(_),y=await Pn(_??e,{includeReconciled:!0,includeLossless:!0,pmRoot:e}),w=new Set(y.durable_receipt_ids),v=ew(a.mergeReceiptReferences,w,a.mergeReceiptDispositions),k=v.missing,S=y.receipts.filter(T=>T.state==="pending"),{pendingDecisions:b,lossless:A}=Fn(S),E=g?.status==="missing"&&g.missing_keys.length===5&&g.drifted_keys.length===0,C=[...s.unreadable.map(T=>`integrity_item_unreadable:${T}`),...s.conflictMarkers.map(T=>`integrity_item_conflict_marker:${T.path}:L${T.line}`),...s.parseFailures.map(T=>`integrity_item_parse_failed:${T}`),...a.unreadable.map(T=>`integrity_history_unreadable:${T}`),...a.conflictMarkers.map(T=>`integrity_history_conflict_marker:${T.id}:L${T.line}`),...a.invalidJson.map(T=>`integrity_history_invalid_json:${T.id}:L${T.line}`),...c.outdated.map(T=>`integrity_item_outdated_format_version:${T}`),...c.ahead.map(T=>`integrity_item_ahead_format_version:${T}`),...vw(l),...u.tracked_path_count>0?[`tracked_runtime_cache_files:${u.tracked_path_count}`]:[],...g!==null&&g.status!=="ok"?[`merge_driver_configuration_${E?"missing":"drift"}:${g.missing_keys.length+g.drifted_keys.length}`]:[],...f.warnings,...h.warnings,...b.length>0?[`merge_decisions_unreviewed:${b.length}`]:[],...A.length>0?[`merge_receipts_pending:${A.length}`]:[],..._w({invalidEvidenceCount:y.invalid_evidence_count,missingHistoryReferenceCount:k.length})],O=[...new Set(C)].sort((T,F)=>T.localeCompare(F)),M=O.filter(T=>!T.startsWith("integrity_legacy_hierarchy_"));return{check:{name:"integrity",status:M.length===0?"ok":"warn",ok:M.length===0,details:{checked_item_files:s.paths.length,checked_history_streams:a.files.length,counts:{item_unreadable:s.unreadable.length,item_conflict_markers:s.conflictMarkers.length,item_parse_failures:s.parseFailures.length,history_unreadable:a.unreadable.length,history_conflict_markers:a.conflictMarkers.length,history_invalid_json:a.invalidJson.length,item_outdated_format_version:c.outdated.length,item_ahead_format_version:c.ahead.length,hierarchy_cycles:l.cycles.length,hierarchy_cardinality_violations:l.cardinality_violations.length,hierarchy_parent_divergences:l.divergences.length,tracked_runtime_cache_files:u.tracked_path_count,merge_driver_configuration:g===null||g.status==="ok"?0:g.missing_keys.length+g.drifted_keys.length,merge_fence:f.count,ignored_merge_artifacts:h.rules.length,pending_merge_decisions:b.length,lossless_merge_receipts:A.length,invalid_merge_receipt_evidence:y.invalid_evidence_count,missing_merge_receipt_history_references:k.length,accepted_legacy_merge_receipt_references:v.acceptedLegacyCount,accepted_missing_merge_receipt_dispositions:v.acceptedDispositionCount},item_unreadable:s.unreadable,item_conflict_markers:s.conflictMarkers,item_parse_failures:s.parseFailures,item_outdated_format_version:c.outdated,item_ahead_format_version:c.ahead,...UR(o),hierarchy_integrity:{...l,relations:Qe(l.relations,nw)},history_unreadable:a.unreadable,history_conflict_markers:a.conflictMarkers,history_invalid_json:a.invalidJson,tracked_runtime_cache:{tracker_relative_root:u.tracker_relative_root,tracked_paths:u.tracked_paths,tracked_path_count:u.tracked_path_count,remediation_command:u.remediation_command},merge_driver_configuration:g===null?null:{...g,required:i},merge_fence:f.audit,ignored_merge_artifacts:h.rules,pending_merge_decision_items:[...new Set(b.map(T=>T.item_id))].sort((T,F)=>T.localeCompare(F)),lossless_merge_receipt_items:[...new Set(A.map(T=>T.item_id))].sort((T,F)=>T.localeCompare(F)),invalid_merge_receipt_evidence_details:y.invalid_evidence,invalid_merge_receipt_evidence_details_truncated:y.invalid_evidence_truncated,missing_merge_receipt_history_reference_details:k.slice(0,ud),missing_merge_receipt_history_reference_details_truncated:k.length>ud}},warnings:O,gitWorkspaceRoot:_,pendingMergeReceipts:S}}function WR(e){if(typeof e.activate=="function")return!0;let t=e.default;return typeof t!="object"||t===null?!1:typeof t.activate=="function"}function zR(e){let t={layer:e.layer,directory:e.directory,manifest_path:e.manifest_path,name:e.name,version:e.version,entry:e.entry,priority:e.priority,entry_path:e.entry_path,has_activate:WR(e.module)};return Array.isArray(e.capabilities)&&(t.capabilities=[...e.capabilities]),t}function BR(e,t){return oe(e.id)||`migration-${String(t+1).padStart(3,"0")}`}function HR(e){let t=oe(e.status)?.toLowerCase();return t==="failed"?"failed":t==="applied"?"applied":"pending"}function VR(e){return oe(e.reason)??oe(e.error)??oe(e.message)}function yd(e,t){let n=(e.layer??"").localeCompare(t.layer??"");if(n!==0)return n;let r=(e.name??"").localeCompare(t.name??"");return r!==0?r:(e.id??"").localeCompare(t.id??"")}function YR(e){let t=[],n=[],r=[];e.forEach((o,s)=>{let a=BR(o.definition,s),c=HR(o.definition);if(c==="applied"){t.push({layer:o.layer,name:o.name,id:a,status:c});return}if(c==="failed"){r.push({layer:o.layer,name:o.name,id:a,status:c,reason:VR(o.definition)});return}n.push({layer:o.layer,name:o.name,id:a,status:c})}),t.sort(yd),n.sort(yd),r.sort(yd);let i=[...r.map(o=>`extension_migration_failed:${o.layer}:${o.name}:${o.id}`),...n.map(o=>`extension_migration_pending:${o.layer}:${o.name}:${o.id}`)];return{summary:{applied:t,pending:n,failed:r,applied_count:t.length,pending_count:n.length,failed_count:r.length},warnings:i}}function bw(e,t,n,r,i,o,s,a,c){let d=[...new Set(e)].sort((y,w)=>y.localeCompare(w)),l=[...new Set(d.map(y=>Ed(y)))].sort((y,w)=>y.localeCompare(w)),u=d.filter(y=>y.startsWith("extension_capability_unknown:")).length,_=c.length>0,h=_?"partial":"full",f=d.map(vc).filter(y=>y!==void 0),g=gh(d,{deactivate:"pm extension --deactivate <name> --project/--global",doctor:"pm extension --doctor --project/--global --detail deep --trace"});return g&&f.push(g),t>0&&f.push("Run pm extension --explore --project and pm extension --explore --global to inspect load failures."),n>0&&f.push("Review checks[name=extensions].details.activation.failed in pm health --json for activation error details."),(r.failed_count>0||r.pending_count>0)&&f.push("Resolve pending/failed extension migrations before write commands; use --force only when policy allows."),i>0&&f.push("Run pm extension --manage --project and pm extension --manage --global to refresh managed-state diagnostics."),u>0&&f.push(`Unknown extension capabilities detected. Allowed capabilities: ${Ru.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`),d.some(y=>y.startsWith("extension_capability_legacy_alias:"))&&f.push("Legacy extension capability aliases were auto-remapped to canonical capabilities. Update manifests to canonical names (migration/validation -> schema)."),d.some(y=>y.startsWith("extension_command_definition_legacy_handler_alias:"))&&f.push("Extension command definitions using legacy handler were auto-remapped. Update command definitions to use run: (context) => ... for forward compatibility."),_?f.push("Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via pm extension --manage --project/--global --fix-managed-state, pm extension --adopt-all --project/--global, or pm extension --adopt <name>."):s.length>0&&f.push("Loaded unmanaged extensions are currently treated as informational. Use pm extension --manage --project/--global --fix-managed-state to adopt them for update checks."),f.length===0&&f.push("No immediate action required. Re-run pm health after extension configuration changes."),{status:d.length===0?"ok":"warn",warning_count:d.length,warning_codes:l,load_failure_count:t,activation_failure_count:n,migration_failed_count:r.failed_count,migration_pending_count:r.pending_count,managed_state_warning_count:i,managed_extension_entries_count:o,unmanaged_loaded_extension_count:s.length,unmanaged_loaded_extensions:s,unmanaged_expected_extension_count:a.length,unmanaged_expected_extensions:a,unmanaged_action_required_extension_count:c.length,unmanaged_action_required_extensions:c,update_health_coverage:h,update_health_partial:_,unknown_capability_count:u,top_warnings:d.slice(0,8),remediation:f}}async function JR(e,t,n){let r=await yh(lt(e)),i=await Vi({pmRoot:e,settings:t,cwd:process.cwd(),noExtensions:n}),o=i.loaded.map(E=>zR(E)),s=await Wy(i.loaded,lt(e)),a=await Yi({...i,loaded:i.loaded}),[c,d]=await Promise.all([wc(i.roots.project),wc(i.roots.global)]);await i_(e,a.registrations.migrations);let l=YR(a.registrations.migrations),u={failed:a.failed,warnings:a.warnings,hook_counts:a.hook_counts,command_override_count:a.command_override_count,command_handler_count:a.command_handler_count,parser_override_count:a.parser_override_count,preflight_override_count:a.preflight_override_count,service_override_count:a.service_override_count,renderer_override_count:a.renderer_override_count,registration_counts:a.registration_counts,registrations:a.registrations,migration_status:l.summary,managed_extensions:{project:{path:c.path,count:c.state.entries.length,entries:c.state.entries},global:{path:d.path,count:d.state.entries.length,entries:d.state.entries}}},_=new Set(c.state.entries.map(E=>Vn(E.name))),h=new Set(d.state.entries.map(E=>Vn(E.name))),f=[...new Map(i.loaded.filter(E=>!(E.layer==="project"?_:h).has(Vn(E.name))).map(E=>[`${E.layer}:${E.name}`,{layer:E.layer,name:E.name,directory:E.directory}])).values()].sort((E,C)=>{let O=`${E.layer}:${E.name}`,M=`${C.layer}:${C.name}`;return O.localeCompare(M)}),g=f.map(E=>`${E.layer}:${E.name}`).sort((E,C)=>E.localeCompare(C)),y=f.filter(E=>vd(E.name,E.directory)).map(E=>`${E.layer}:${E.name}`).sort((E,C)=>E.localeCompare(C)),w=f.filter(E=>!vd(E.name,E.directory)).map(E=>`${E.layer}:${E.name}`).sort((E,C)=>E.localeCompare(C)),v=w.length>0?[`extension_update_health_partial_coverage:skipped_unmanaged:${w.length}`]:[],k=[...r.warnings,...i.warnings,...u.warnings,...l.warnings,...c.warnings,...d.warnings,...v,...s.warnings],S=bc(k),b=kc(),A=bw(k,i.failed.length,a.failed.length,l.summary,c.warnings.length+d.warnings.length,c.state.entries.length+d.state.entries.length,g,y,w);return{check:{name:"extensions",status:k.length===0?"ok":"warn",ok:k.length===0,details:{...i,loaded:o,warnings:k,activation:u,author_manifest:r,triage:A,...l.summary.pending_count>0?{remediation_map:{extension_migration_pending:"pm extension migrate --project"}}:{},capability_contract:b,capability_guidance:S,host_version_census:s}},warnings:k}}function kd(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=rw(e,gw);return{values:n.values,truncated:n.truncated,total:e.length}}function ts(e){let t=(process.env[e]??"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function XR(){let e=Gp();return e.source_context_source==="env_override"?e.source_context:null}function kw(e){let t=0,n=0,r=0,i=0,o=0;for(let s of e.split(`
|
|
8
|
-
`)){let a=s.trim();if(a.length!==0){r+=1;try{let c=JSON.parse(a);if(typeof c=="object"&&c!==null&&typeof c.attempts=="number"&&Number.isFinite(c.attempts)){let d=Math.max(0,Math.trunc(c.attempts));t+=1,o=Math.max(o,d),d>=yw&&(i+=1)}else n+=1}catch{n+=1}}}return{validEntries:t,invalidRows:n,totalRows:r,highRetryEntries:i,maxAttempts:o}}function QR(){return{validEntries:0,invalidRows:0,totalRows:0,highRetryEntries:0,maxAttempts:0}}function fw(e){if(!e||e.trim().length===0)return{runtimeState:{},stateParseFailed:!1};try{let t=JSON.parse(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)?{runtimeState:t,stateParseFailed:!1}:{runtimeState:{},stateParseFailed:!0}}catch{return{runtimeState:{},stateParseFailed:!0}}}async function ZR(e,t){let n=Ar(e.telemetry.endpoint).trim();return!t||!e.telemetry.enabled||n.length===0||Zt().telemetry_disabled?void 0:{attempted:!0,...await Sw(n)}}function eI(e,t,n){let r=[];if(t.invalidRows>0&&r.push(`telemetry_queue_invalid_rows:${t.invalidRows}`),!e.telemetry.enabled||t.validEntries===0)return r;let i=n.last_successful_flush_at,o=n.last_failed_flush_at,s=o&&(!i||o>i),a=!i,c=t.validEntries>=$R;return(s||a||c)&&r.push(`telemetry_queue_pending:${t.validEntries}`),t.highRetryEntries>0&&r.push(`telemetry_queue_high_retries:${t.highRetryEntries}`),r}function tI(e){return!e||e.ok!==!1?[]:typeof e.status=="number"?[`telemetry_endpoint_probe_http_status:${e.status}`]:["telemetry_endpoint_probe_failed"]}function nI(e){let t=Number.parseInt(e?.max_schema_version??"",10);return e?.ok===!0&&Number.isInteger(t)&&t>Vp?[`telemetry_schema_version_behind:${t}`]:[]}function rI(e,t){let n=typeof t.pending_otel_spans=="number"?t.pending_otel_spans:0,r=t.last_otel_success_at,i=t.last_otel_failure_at;return e.telemetry.enabled&&n>0&&i&&(!r||i>=r)?[`telemetry_otel_export_failing:${n}`]:[]}function iI(){return{...Zt(),pm_no_telemetry:ts("PM_NO_TELEMETRY"),telemetry_otel_disabled:ts("PM_TELEMETRY_OTEL_DISABLED"),telemetry_inline_flush:ts("PM_TELEMETRY_INLINE_FLUSH"),telemetry_source_context:XR()}}function oI(e,t){return e.telemetry.enabled&&t.validEntries>0}function sI(e,t){return e&&t.every(n=>!n.startsWith("telemetry_queue_pending:")&&!n.startsWith("telemetry_queue_high_retries:"))}function hw(e){try{return decodeURIComponent(e)}catch{return e}}async function Sw(e){let t=e,n={};try{let r=new URL(e);r.pathname="/healthz",r.search="",r.hash="",(r.username.length>0||r.password.length>0)&&(n.authorization=`Basic ${Buffer.from(`${hw(r.username)}:${hw(r.password)}`).toString("base64")}`,r.username="",r.password=""),t=r.toString()}catch{}try{let r=await fetch(t,{method:"GET",headers:n,signal:AbortSignal.timeout(DR)});return{probe_url:Ot(t),ok:r.ok,status:r.status,max_schema_version:(()=>{for(let i of NR){let o=r.headers.get(i)?.trim();if(o&&o.length>0)return o}})()}}catch(r){return{probe_url:Ot(t),ok:!1,error:r instanceof Error?qp(r.message.replaceAll(t,Ot(t))):"probe_failed"}}}async function aI(e,t){let n=fw(await Q(e)),r=e===t?n:fw(await Q(t));return{runtimeState:n.runtimeState,spanState:r.runtimeState,stateParseFailed:n.stateParseFailed||r.stateParseFailed}}async function cI(e){let t=Ye(process.cwd()),n=await x(t),r=ge.join(ge.dirname(ge.join(t,OR)),It("events.jsonl")),i=ge.join(t,LR),o=ge.join(ge.dirname(i),It("state.json")),s=await Q(r),a=s!==null,c=s?Buffer.byteLength(s,"utf8"):0,d=s?kw(s):QR(),{runtimeState:l,spanState:u,stateParseFailed:_}=await aI(o,i),h=Ar(n.telemetry.endpoint).trim(),f=Ot(h),g=await ZR(n,e.checkTelemetry),y=[];_&&y.push("telemetry_state_invalid_json"),y.push(...eI(n,d,l),...tI(g),...nI(g),...rI(n,u));let w=oI(n,d),v=typeof u.pending_otel_spans=="number"?u.pending_otel_spans:0;return{check:{name:"telemetry",status:y.length===0?"ok":"warn",ok:y.length===0,details:{enabled:n.telemetry.enabled,capture_level:n.telemetry.capture_level,endpoint:f,global_pm_root:t,queue_path:r,queue_exists:a,queue_entries:d.validEntries,queue_draining:sI(w,y),queue_invalid_rows:d.invalidRows,queue_rows_total:d.totalRows,queue_size_bytes:c,queue_high_retry_entries:d.highRetryEntries,queue_high_retry_threshold:yw,queue_max_attempts:d.maxAttempts,runtime_state_path:o,last_attempted_flush_at:l.last_attempted_flush_at??null,last_successful_flush_at:l.last_successful_flush_at??null,last_failed_flush_at:l.last_failed_flush_at??null,last_failed_flush_error:l.last_failed_flush_error??null,pending_otel_spans:v,last_otel_attempt_at:u.last_otel_attempt_at??null,last_otel_success_at:u.last_otel_success_at??null,last_otel_failure_at:u.last_otel_failure_at??null,last_otel_failure_error:u.last_otel_failure_error??null,endpoint_probe:g??{attempted:!1},env_overrides:iI()}},warnings:y}}async function dI(e){let t;try{t=await aw(e)}catch(r){let i=r instanceof Error?r.message:String(r);return{check:{name:"locks",status:"warn",ok:!1,details:{active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0,scan_failed:!0,error:i,pm_root:e}},warnings:[`locks_scan_failed:${i}`]}}let n=[];return t.stale_lock_count>0&&n.push(`locks_stale_count:${t.stale_lock_count}`),t.unreadable_lock_count>0&&n.push(`locks_unreadable:${t.unreadable_lock_count}`),{check:{name:"locks",status:n.length===0?"ok":"warn",ok:n.length===0,details:{active_lock_count:t.active_lock_count,stale_lock_count:t.stale_lock_count,...t.owner_dead_lock_samples?{owner_dead_lock_samples:t.owner_dead_lock_samples,recovery_command:"pm gc --scope locks"}:{},unreadable_lock_count:t.unreadable_lock_count,unparseable_lock_count:t.unparseable_lock_count}},warnings:n}}async function lI(e){let t="metadata",n=e.items,r=await Pr(e.pmRoot,n,{cacheHitVerification:t}),i=[...new Set([...r.hashMismatches,...r.chainMismatches,...r.versionSkews])].sort((w,v)=>w.localeCompare(v)),o=[],s=[];if(i.length>0){n=await gt(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema,{forceSourceScan:!0}),r=await Pr(e.pmRoot,n),o=[...new Set([...r.hashMismatches,...r.chainMismatches,...r.versionSkews])].sort((v,k)=>v.localeCompare(k));let w=new Set(o);s=i.filter(v=>!w.has(v))}let{missingStreams:a,unreadableStreams:c,hashMismatches:d,chainMismatches:l,versionSkews:u,driftedItems:_,workspaceStateMismatches:h,workspaceStateMissing:f,workspaceStateUnreadable:g}=r,y=[...a.map(w=>`history_drift_missing_stream:${w}`),...c.map(w=>`history_drift_unreadable_stream:${w}`),...d.map(w=>`history_drift_hash_mismatch:${w}`),...l.map(w=>`history_drift_chain_mismatch:${w}`),...u.map(w=>`history_drift_version_skew:${w}`),...h.map(w=>`history_drift_workspace_state_mismatch:${w}`),...f.map(w=>`history_drift_workspace_state_missing:${w}`),...g.map(w=>`history_drift_workspace_state_unreadable:${w}`)];return{check:{name:"history_drift",status:y.length===0?"ok":"warn",ok:y.length===0,details:{checked_items:n.length,cache_hit_verification:i.length>0?"metadata_then_content_hash":t,cache_confirmation:{triggered:i.length>0,reason:i.length>0?"cached_corruption_candidate":null,candidate_items:i,confirmed_items:o,resolved_false_positive_items:s,authoritative_item_source:i.length>0},drifted_items:_,counts:{drifted:_.length,missing_streams:a.length,unreadable_streams:c.length,hash_mismatches:d.length,chain_mismatches:l.length,version_skews:u.length,workspace_state_mismatches:h.length,workspace_state_missing:f.length,workspace_state_unreadable:g.length},missing_streams:a,unreadable_streams:c,hash_mismatches:d,chain_mismatches:l,version_skews:u,workspace_state_mismatches:h,workspace_state_missing:f,workspace_state_unreadable:g}},warnings:y}}function uI(e,t){let n=Tp(e),r=Mp(n.settings),i=Pp(n.settings,t),o=r.active?Fp(r.active.name,r.active.model):null;return{runtimeDefaults:n,providerResolution:r,vectorStoreResolution:i,runtimeEmbeddingIdentity:o,semanticRuntimeAvailable:!!(r.active&&i.active)}}function mI(){return{refreshed:[],skipped:[],warnings:[]}}async function pI(e){return!e.refreshPolicy.enabled||!e.snapshot.semanticRuntimeAvailable||e.staleBefore.length===0?mI():Up(e.pmRoot,e.staleBefore,{settings:e.snapshot.runtimeDefaults.settings,apply_runtime_defaults:!1})}function _I(e){return e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&!!(e.ledgerBefore.embedding&&e.runtimeEmbeddingIdentity&&jp(e.ledgerBefore.embedding,e.runtimeEmbeddingIdentity))}function fI(e){let t=new Set([...e.ledgerBefore.warnings,...e.ledgerAfter.warnings]);if(e.strictVectorizationWarnings)for(let n of e.refreshResult.warnings)t.add(n);return e.embeddingIdentityChanged&&t.add("vectorization_embedding_identity_changed"),e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&e.staleAfter.length>0&&t.add(`vectorization_stale_items_remaining:${e.staleAfter.length}`),[...t].sort((n,r)=>n.localeCompare(r))}function hI(e,t,n){return e.enabled&&t&&n.length>0?null:e.enabled?t?"no_stale_items":"semantic_runtime_unavailable":"refresh_disabled"}function Ew(e,t){let n=t.providerResolution.active?.name??null,r=t.vectorStoreResolution.active?.name??null;return{provider_active:n,provider_configured:typeof e.search?.provider=="string"?e.search.provider:null,provider_source:Ja(n,e.search?.provider??null),vector_store_active:r,vector_store_configured:typeof e.vector_store?.adapter=="string"?e.vector_store.adapter:null,vector_store_source:Ja(r,e.vector_store?.adapter??null)}}function gI(e){return{enabled:e.enabled,check_only:e.checkOnly,no_refresh:e.noRefresh,refresh_vectors:e.refreshVectors}}function yI(e,t,n){return e.enabled&&n.length>0&&t}async function wI(e,t,n,r,i){let o=uI(t,e),s=await Xa(e),a=o.semanticRuntimeAvailable?Ec(n,s.entries):[],c=await pI({pmRoot:e,snapshot:o,refreshPolicy:r,staleBefore:a}),d=await Xa(e),l=o.semanticRuntimeAvailable?Ec(n,d.entries):[],u=!o.runtimeDefaults.auto_ollama_defaults_applied,_=_I({strictVectorizationWarnings:u,semanticRuntimeAvailable:o.semanticRuntimeAvailable,ledgerBefore:s,runtimeEmbeddingIdentity:o.runtimeEmbeddingIdentity}),h=fI({ledgerBefore:s,ledgerAfter:d,refreshResult:c,strictVectorizationWarnings:u,semanticRuntimeAvailable:o.semanticRuntimeAvailable,embeddingIdentityChanged:_,staleAfter:l}),f=kd(a,i),g=kd(l,i),y=yI(r,o.semanticRuntimeAvailable,a);return{check:{name:"vectorization",status:h.length===0?"ok":"warn",ok:h.length===0,details:{semantic_runtime_available:o.semanticRuntimeAvailable,compatibility_mode_auto_defaults:o.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_applied:o.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:o.runtimeDefaults.auto_ollama_defaults_skipped_reason??null,auto_ollama_defaults_remediation:o.runtimeDefaults.auto_ollama_defaults_remediation??null,refresh_policy:gI(r),...Ew(t,o),embedding_identity_changed:_,embedding_identity_before:s.embedding??null,embedding_identity_runtime:o.runtimeEmbeddingIdentity??null,items:n.length,ledger_entries_before:Object.keys(s.entries).length,stale_items_detail_mode:i?"full":"summary",stale_items_summary_limit:gw,stale_items_before_total:f.total,stale_items_before:f.values,stale_items_before_truncated:f.truncated,refresh_attempted:y,refresh_skipped_reason:hI(r,o.semanticRuntimeAvailable,a),refresh_result:c,ledger_entries_after:Object.keys(d.entries).length,stale_items_after_total:g.total,stale_items_after:g.values,stale_items_after_truncated:g.truncated}},warnings:h}}function vI(e){let t=[];return e.id_prefix.trim().length===0&&t.push("settings:id_prefix_empty"),e.locks.ttl_seconds<=0&&t.push("settings:locks_ttl_non_positive"),t}function Tw(e){let t=e.checkOnly===!0,n=e.refreshVectors===!0;if(n&&t)throw new p("--check-only cannot be combined with --refresh-vectors",m.USAGE);if(n&&e.noRefresh===!0)throw new p("--no-refresh cannot be combined with --refresh-vectors",m.USAGE);return{enabled:n,checkOnly:t,noRefresh:!n,refreshVectors:n}}var bI=new Set(["extensions","locks","search"]);function kI(e){let t=new Set(Lu.filter(i=>i.length>0)),n=new Set,r=new Set(Object.values(Du));for(let i of e.folders)t.has(i)&&!r.has(i)||(t.delete(i),n.add(i));for(let i of bI)t.delete(i),n.add(i);return{requiredDirs:[...t].sort((i,o)=>i.localeCompare(o)),optionalDirs:[...n].sort((i,o)=>i.localeCompare(o)),optionalDirSet:n}}async function SI(e,t,n){let{requiredDirs:r,optionalDirs:i,optionalDirSet:o}=kI(t),s=[],a=[],c=[];for(let d of[...r,...i]){let l=ge.join(e,d);c.push(...await We({path:l,scope:"project"})),!await Td(l)&&(o.has(d)?a.push(d):s.push(d))}return{requiredDirs:r,optionalDirs:i,missingRequiredDirs:s,missingOptionalDirs:a,missingDirs:n?[...s,...a]:[...s],hookWarnings:c}}function Cw(e){let t=e.checkOnly===!0&&e.brief!==!0&&e.summary!==!0&&e.full!==!0,n=e.summary===!0||t,r=e.checkOnly===!0&&(e.brief===!0||e.summary===!0)&&e.full!==!0;return{summaryMode:n,skipIntegrity:(e.skipIntegrity===!0||r)&&e.full!==!0,skipDrift:(e.skipDrift===!0||r)&&e.full!==!0,skipVectors:(e.skipVectors===!0||r)&&e.full!==!0}}async function EI(e){return e.skipPolicy.skipDrift&&e.skipPolicy.skipVectors?Te(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema):gt(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema)}function wd(e){return{check:{name:e,status:"ok",ok:!0,details:{skipped:!0}},warnings:[]}}function TI(e,t,n){return{name:"settings",status:n.length===0?"ok":"warn",ok:n.length===0,details:{path:e,version:t.version,id_prefix:t.id_prefix,locks_ttl_seconds:t.locks.ttl_seconds,warnings:n}}}function CI(e,t){return{name:"directories",status:e.missingDirs.length===0?"ok":"warn",ok:e.missingDirs.length===0,details:{required:e.requiredDirs,optional:e.optionalDirs,missing_required:e.missingRequiredDirs,missing_optional:e.missingOptionalDirs,missing:e.missingDirs,strict_directories:t}}}function AI(e,t){return{name:"settings_values",status:e.length===0?"ok":"warn",ok:e.length===0,details:{warnings:e,...t.roleless_status_count>0?{lifecycle_status_roles:t}:{}}}}var Cd=e=>e.unknown_event_count??0,Ad=e=>e.actionable_unknown_event_count??Cd(e);function xI(e,t,n,r,i,o,s){let a=Cd(r),c=Ad(r),d=a>0,l=c>0,u=i.count>0||s!==void 0;return{name:"storage",status:n.over_threshold.length===0&&n.orphaned.length===0&&!l&&!u?"ok":"warn",ok:n.over_threshold.length===0&&n.orphaned.length===0&&!l&&!u,details:{items:e.length,history_streams:n.count,tombstones:{retention_policy:"retain_append_only",gc_enabled:!1,count:n.tombstones.length,ids:n.tombstones.slice(0,25),truncated:n.tombstones.length>25},orphaned_history_streams:{count:n.orphaned.length,ids:n.orphaned.slice(0,25),truncated:n.orphaned.length>25},...d?{author_attribution:r}:{},...i.count>0?{stale_in_progress:i}:{},...s===void 0?{}:{in_progress_work:s},...o.outcomes.length>0?{provenance_resolver_outcomes:o.outcomes}:{},...o.invalid_values.length>0?{provenance_invalid_values:o.invalid_values}:{},provenance_sample:o.sample,...n.max_entries!==null?{compact_policy:{enabled:t.history.compact_policy.enabled,max_entries:n.max_entries,trigger:t.history.compact_policy.trigger,over_threshold_count:n.over_threshold.length,over_threshold:n.over_threshold}}:{}}}}function Aw(e){let t=e.count===0?[]:[`stale_in_progress_items:${e.count}`];return{scan:e,warnings:t}}function RI(e){let t=[...e.directoryState.missingDirs.map(n=>`missing_directory:${n}`),...e.normalizedSettingsReadWarnings,...e.settingWarnings,...e.normalizedItemReadWarnings,...e.telemetryCheck.warnings,...e.extensionCheck.warnings,...e.historyPolicyWarnings,...e.historySummary.warnings,...e.authorAttributionWarnings,...e.staleInProgressWarnings,...e.provenanceWarnings,...e.locksCheck.warnings,...e.integrityCheck.warnings,...e.historyDriftCheck.warnings,...e.vectorizationCheck.warnings,...e.directoryState.hookWarnings];return[...new Set(t)]}function II(e){let t=e.check.details.counts;return typeof t?.drifted=="number"?t.drifted:0}function OI(e){return{settings:e.normalizedSettingsReadWarnings,directories:e.directoryState.missingDirs.map(t=>`missing_directory:${t}`).concat(e.directoryState.hookWarnings),settings_values:e.settingWarnings,telemetry:e.telemetryCheck.warnings,extensions:e.extensionCheck.warnings,storage:[...e.historyPolicyWarnings,...e.historySummary.warnings,...e.authorAttributionWarnings,...e.staleInProgressWarnings,...e.provenanceWarnings],locks:e.locksCheck.warnings,integrity:[...e.normalizedItemReadWarnings,...e.integrityCheck.warnings],history_drift:e.historyDriftCheck.warnings,vectorization:e.vectorizationCheck.warnings}}function xw(e){let t=new Map;for(let[r,i]of Object.entries(e.remediationSources))for(let o of i)t.has(o)||t.set(o,r);let n=new Map(e.checks.map(r=>[r.name,r]));return e.warnings.map(r=>{let i=t.get(r)??"integrity",o=fd(r)?.code??Ed(r),s=n.get(i)?.details,a=typeof s?.remediation_map=="object"&&s.remediation_map!==null?s.remediation_map:{},c=vc(r)??(o==="agent_guidance_outdated"?"pm init --agent-guidance add":o==="agent_guidance_unreadable"?"Check AGENTS.md and CLAUDE.md read permissions and file types, then retry pm health.":a[o]),d=Sd(r,e.requireMergeDrivers)?"advisory":"gate_failing";return{warning:r,code:o,check:i,severity:d,...typeof c=="string"?{remediation:c}:d==="gate_failing"?{disposition:"no_safe_automatic_remediation"}:{}}})}function LI(e){if(e.check.name==="history_drift"&&e.historyDriftedCount>1)for(let t of Object.keys(e.remediationMap))t!=="history_drift_merge_receipt"&&t!=="history_drift_version_skew"&&(e.remediationMap[t]="pm history-repair --all");if(e.check.name==="storage"&&e.overThresholdCount>1)for(let t of Object.keys(e.remediationMap))e.remediationMap[t]="pm history-compact --all-streams"}function DI(e){for(let t of e.checks){let n=hd(e.remediationSources[t.name]);LI({check:t,remediationMap:n,historyDriftedCount:e.historyDriftedCount,overThresholdCount:e.overThresholdCount});for(let[r,i]of Object.entries(t.name==="storage"?e.storageRemediation:{}))Object.hasOwn(n,r)&&(n[r]=i);Object.keys(n).length>0&&(t.details={...t.details,remediation_map:n})}}async function $I(e){if(e.gitWorkspaceRoot===null||e.pendingMergeReceipts.length===0)return[];let t=e.historyDriftCheck.check.details,n=Array.isArray(t.hash_mismatches)?t.hash_mismatches.filter(s=>typeof s=="string"):[],r=new Set([t.missing_streams,t.unreadable_streams,t.chain_mismatches].flatMap(s=>Array.isArray(s)?s:[])),i=new Map;for(let s of e.pendingMergeReceipts){let a=i.get(s.item_id)??[];a.push(s),i.set(s.item_id,a)}let o=[];for(let s of n){if(r.has(s))continue;let a=i.get(s);if(!(!a||a.length===0))try{await Ch(s,{dryRun:!0,mergeReceiptProof:{gitWorkspaceRoot:e.gitWorkspaceRoot,receipts:a}},e.global),o.push(s)}catch{}}return[...new Set(o)].sort((s,a)=>s.localeCompare(a))}function NI(e,t){let n=new Set(t);e.warnings=[...e.warnings.filter(r=>r.startsWith("history_drift_hash_mismatch:")?!n.has(r.slice(r.indexOf(":")+1)):!0),...t.map(r=>`history_drift_merge_receipt:${r}`)].sort((r,i)=>r.localeCompare(i)),e.check.details={...e.check.details,merge_receipt_attributed_items:t}}async function Rw(e,t={}){let n=R(process.cwd(),e.path);await j(n);let r=Re(n),{settings:i,warnings:o}=await Sp(n),s=[...new Set(o)],a=P(i,N()),c=t.strictDirectories===!0,d=t.strictExit===!0||t.failOnWarn===!0,l=t.requireMergeDrivers===!0||d,u=Tw(t),_=await SI(n,a,c),h=vI(i),f=await cI({checkTelemetry:t.checkTelemetry===!0}),g=await JR(n,i,!!e.noExtensions),y=Cw(t),w=[],v=await EI({pmRoot:n,settings:i,typeRegistry:a,skipPolicy:y,itemReadWarnings:w}),k=v,S=Xo(W(i.schema),v),b=[...(await wh({pm_root:n,cwd:process.cwd(),mode:"status",interactive:!1,settings:i}).catch(()=>({warnings:["agent_guidance_unreadable:AGENTS.md,CLAUDE.md"]}))).warnings.filter(ae=>ae.startsWith("agent_guidance_")),...h,...Qo(S)],A=y.skipDrift?{warnings:[]}:await oo({pmRoot:n,settings:i,itemIds:v.map(ae=>ae.id),commandLabel:"health"}),E=await FR(n,i.history.compact_policy,await MR(n)),C=await Jr(n,20,t.verboseAuthorEvents===!0),O=Ad(C),M=O>0?[`history_unknown_author_events:${O}`]:[],T=W(i.schema),F=await Bp(n,v,{in_progress_status:T.in_progress_status,status_registry:T,threshold_hours:i.mutation_guard.stale_in_progress_hours}),ue=Aw(F.stale),Ne=Hy(F,{in_progress:T.in_progress_status,open:T.open_status},Ie(e)),J=[...ue.warnings,...Ne.warnings],Me=await Eh(n),Pe=Me.warnings,qe=await dI(n),re=y.skipIntegrity&&!l?{...wd("integrity"),gitWorkspaceRoot:null,pendingMergeReceipts:[]}:await KR(n,a.type_to_folder,i.schema,i,l,v),be=y.skipDrift?wd("history_drift"):await lI({pmRoot:n,items:k,settings:i,typeRegistry:a,itemReadWarnings:w}),Ee=[...new Set(w)],nt=await $I({gitWorkspaceRoot:re.gitWorkspaceRoot,pendingMergeReceipts:re.pendingMergeReceipts,historyDriftCheck:be,global:e});NI(be,nt);let rt=y.skipVectors?wd("vectorization"):await wI(n,i,k,u,t.verboseStaleItems===!0),it=[TI(r,i,s),CI(_,c),AI(b,S),f.check,g.check,xI(v,i,E,C,ue.scan,Me,Ne.details),qe.check,re.check,be.check,rt.check],ye=RI({directoryState:_,normalizedSettingsReadWarnings:s,settingWarnings:b,normalizedItemReadWarnings:Ee,telemetryCheck:f,extensionCheck:g,historyPolicyWarnings:A.warnings,historySummary:E,authorAttributionWarnings:M,staleInProgressWarnings:J,provenanceWarnings:Pe,locksCheck:qe,integrityCheck:re,historyDriftCheck:be,vectorizationCheck:rt}),se=OI({directoryState:_,normalizedSettingsReadWarnings:s,settingWarnings:b,normalizedItemReadWarnings:Ee,telemetryCheck:f,extensionCheck:g,historyPolicyWarnings:A.warnings,historySummary:E,authorAttributionWarnings:M,staleInProgressWarnings:J,provenanceWarnings:Pe,locksCheck:qe,integrityCheck:re,historyDriftCheck:be,vectorizationCheck:rt});DI({checks:it,remediationSources:se,historyDriftedCount:II(be),overThresholdCount:E.over_threshold.length,storageRemediation:Ne.remediation});let He=ye.filter(ae=>!Sd(ae,l)),$=xw({warnings:ye,checks:it,remediationSources:se,requireMergeDrivers:l}),Ve=new Set($.filter(ae=>ae.severity==="gate_failing").map(ae=>ae.check)),Ut=new Set($.map(ae=>ae.check));for(let ae of it)ae.ok=!Ve.has(ae.name),Ut.has(ae.name)&&(ae.status="warn");let Ae={ok:He.length===0,verdict:{authority:"ok",...d?{strict_exit:!0}:{},...l?{require_merge_drivers:!0}:{},exit_code:d&&He.length>0?m.GENERIC_FAILURE:0},checks:it,warnings:ye,findings:$,failed_because:He,generated_at:I()};return _d(Ae,t,y.summaryMode)}var kz={buildHierarchyIntegrityWarnings:vw,buildExtensionHealthTriageSummary:bw,buildHealthFindings:xw,buildCapabilityContractMetadata:kc,buildStaleInProgressHealthSummary:Aw,buildVectorizationProviderDetails:Ew,collectUnknownCapabilityGuidance:bc,isAdvisoryHealthWarning:Sd,isDirectory:Td,isExpectedUnmanagedExtension:vd,listItemDocumentPaths:ww,normalizeEndpointForDisplay:Ot,normalizeExtensionNameForMatch:Vn,parseTelemetryQueue:kw,probeTelemetryEndpointHealth:Sw,projectHealthResult:_d,resolveActionableUnknownAuthorEventCount:Ad,resolveHealthSkipPolicy:Cw,resolveUnknownAuthorEventCount:Cd,resolveVectorRefreshPolicy:Tw,selectStaleItemDetail:kd,summarizeHealthCheckDetails:md,summarizeExtensionList:ei,summarizeRecordList:Qe,summarizeStringList:B,telemetryEnvFlagEnabled:ts,warningCode:Ed};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a07d2f98-7c1d-5d0a-be70-5181ed0f7b4f")}catch{}})();function Iw(e,t,n){if(!n.has(t.metadata.status))return{reason:"not_terminal"};if(e.length===0)return{reason:"missing_history"};if(!r_(e,t).ok)return{reason:"unverified_history"};let r=hp(),i={reason:"no_proven_transition"};for(let[o,s]of e.entries()){let a=n.has(String(r.metadata.status));r=Cp(r,s.patch,o+1,s.op),n.has(String(r.metadata.status))?a||(i=["create","close","cancel","update","update_audit"].includes(s.op)&&vm(s.ts)?{timestamp:s.ts,source_index:o+1}:{reason:"no_proven_transition"}):i={reason:"no_proven_transition"}}return i}function Ow(e){return new Set([...e.terminal_statuses,...[...e.alias_to_id].filter(([,t])=>e.terminal_statuses.has(t)).map(([t])=>t)])}async function Lw(e,t,n,r,i){let o=Ow(n),s=t.filter(d=>o.has(d.status)&&!d.closed_at),a=[],c=[];for(let d of r?s:[]){let l;try{let u=await Jt(Bt(e,d.id),d.id),{body:_,...h}=d;l=Iw(u,{metadata:h,body:_},o)}catch{c.push({id:d.id,reason:"unreadable_history"});continue}if("reason"in l){c.push({id:d.id,reason:l.reason});continue}a.push({item_id:d.id,check:"metadata",field:"closed_at",kind:"set_closed_at",value:l.timestamp,gate:"timestamps",command:"pm validate --check-metadata --auto-fix --fix-scope timestamps"})}return{details:{missing_closed_at_count:s.length,missing_closed_at_item_ids:s.slice(0,i).map(d=>d.id),missing_closed_at_item_ids_truncated:s.length>i,closure_history_inspected:r,closure_timestamp_derivable_count:a.length,closure_timestamp_residual_count:c.length,closure_timestamp_residual:c.slice(0,i),closure_timestamp_residual_truncated:c.length>i,...s.length>0?{closure_timestamp_fix_hint:"pm validate --check-metadata --auto-fix --fix-scope timestamps --dry-run"}:{}},fixes:a,warnings:s.length>0?[`validate_metadata_missing_closed_at:${s.length}`]:[]}}async function Dw(e,t){let n=R(process.cwd(),t.path),r=await x(n),i=W(r.schema);await he({pmRoot:n,settings:r,id:e.item_id,op:"update",author:U(t.author,r.author_default),message:"Backfill closed_at from verified lifecycle history",skipNoop:!0,async mutate(o){if(o.metadata.closed_at)return{changedFields:[]};let s=await Jt(Bt(n,o.metadata.id),o.metadata.id),a=Ow(i),c=Iw(s,o,a);if(!("timestamp"in c)||c.timestamp!==e.value)throw new p("Closure timestamp evidence changed or cannot be verified; rerun the timestamp repair preview.",m.GENERIC_FAILURE);return o.metadata.closed_at=c.timestamp,{changedFields:["closed_at"]}}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="34d28b31-b098-5ffd-b39b-2e11de150ac1")}catch{}})();function MI(e,t){return e==="malformed"||t==="malformed"?"malformed":e==="moved"||t==="moved"?"moved":"deleted"}function $w(e){return`${e.item_id} ${e.link_kind}`}function Nw(e,t){let n=new Map;for(let r of e){let i=n.get(r.path);i?(i.classification=MI(i.classification,r.classification),i.owners.set($w(r),r)):n.set(r.path,{classification:r.classification,owners:new Map([[$w(r),r]])})}return[...n.entries()].sort(([r],[i])=>r.localeCompare(i)).map(([r,i])=>({path:r,classification:i.classification,items:[...i.owners.values()].map(o=>{let s=t(o.item_id);return{id:o.item_id,type:s?.type??"Unknown",title:s?.title??"",status:s?.status??"",field:o.link_kind}}).sort((o,s)=>{let a=o.id.localeCompare(s.id);return a!==0?a:o.field.localeCompare(s.field)})}))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="00f8052d-480b-5e38-86cf-4574a8ad1e92")}catch{}})();function Mw(e,t,n,r,i=40){let o=i===1/0?1/0:Number.isFinite(i)?Math.max(0,Math.floor(i)):40,s=new Map(t.map(d=>[d.path,d])),a={missing_linked_path_rows_count:0,missing_linked_path_rows:[],missing_linked_path_rows_truncated:!1,missing_linked_links_count:0,active_missing_linked_links_count:0,legacy_closed_missing_linked_links_count:0,legacy_terminal_missing_linked_links_count:0,active_missing_linked_paths_count:0},c=Nw(e,n).map(d=>{let l=[],u=[];for(let h of d.items){let f=ce(h.status,r)??h.status;r.terminal_statuses.has(f)?(u.push(h),f===r.close_status&&(a.legacy_closed_missing_linked_links_count+=1)):l.push(h)}a.missing_linked_links_count+=d.items.length,a.active_missing_linked_links_count+=l.length,a.legacy_terminal_missing_linked_links_count+=u.length,l.length>0&&(a.active_missing_linked_paths_count+=1);let _=s.get(d.path);return{...d,candidates:_?.candidates??[],candidates_truncated:_?.candidates_truncated??!1,link_count:d.items.length,active_link_count:l.length,items:[...l,...u].slice(0,o),items_truncated:d.items.length>o}});return c.sort((d,l)=>+(l.active_link_count>0)-+(d.active_link_count>0)||d.path.localeCompare(l.path)),a.missing_linked_path_rows_count=c.length,a.missing_linked_path_rows=c.slice(0,o),a.missing_linked_path_rows_truncated=c.length>o,a}import Yn from"node:fs/promises";import Jn from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7ff2e182-d84c-5e1c-8b63-daea17d55af4")}catch{}})();async function PI(e,t){let n=[...new Set(Object.values(t))],r=[];return await Promise.all(n.map(async i=>{let o;try{o=await Yn.readdir(Jn.join(e,i))}catch{return}for(let s of o)for(let a of zt)if(s.toLowerCase().endsWith(a)){r.push({relativePath:`${i}/${s}`,id:s.slice(0,-a.length)});break}})),r.sort((i,o)=>i.relativePath.localeCompare(o.relativePath))}function FI(e,t){let{id:n,relativePath:r,liveItemIds:i,out:o}=e,s=Rn(t);if(s){o.conflictMarkers.push({id:n,path:r,line:s.line,detail:`unresolved merge conflict marker ${s.marker}`});return}let a=jI(e,t);a!==null&&(a.op==="delete"&&i.has(n)&&o.resurrected.push({id:n,deleted_at:typeof a.ts=="string"?a.ts:"",deleted_by:typeof a.author=="string"?a.author:""}),a.op==="history_repair"&&Array.isArray(a.patch)&&a.patch.length>0&&(o.repairReconciliations+=1))}function jI(e,t){let{id:n,relativePath:r,out:i}=e,o=null,s=!1,a=t.split(/\r?\n/).map((c,d)=>({content:c.trim(),number:d+1})).filter(c=>c.content.length>0);for(let c of a){try{let d=JSON.parse(c.content);if(typeof d!="object"||d===null||Array.isArray(d))throw new TypeError("history entry must be an object");o=d}catch{return i.unparseable.push({id:n,path:r,line:c.number,detail:"history line is not a valid JSON object"}),null}if(o.op==="create"){if(s)return i.unparseable.push({id:n,path:r,line:c.number,detail:"duplicate item identity: more than one create event in one history stream"}),null;s=!0}}return o}function xd(e,t){let n=typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"?t.code:"UNKNOWN";return`${e} could not be read (error code: ${n})`}async function UI(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},r;try{r=await Yn.readdir(Jn.join(e,"history"))}catch{return n}for(let i of r.sort((o,s)=>o.localeCompare(s))){if(!i.endsWith(".jsonl"))continue;n.scanned+=1;let o;try{o=await Yn.readFile(Jn.join(e,"history",i),"utf8")}catch(s){n.unparseable.push({id:i.slice(0,-6),path:`history/${i}`,detail:xd("history stream",s)});continue}FI({id:i.slice(0,-6),relativePath:`history/${i}`,liveItemIds:t,out:n},o)}return n}function Pw(e){let t=Rn(e);if(t)return`unresolved merge conflict marker ${t.marker} at line ${t.line}`;try{return JSON.parse(e),null}catch(n){return`invalid JSON (${String(n)})`}}async function GI(e){let t=[],n=0,r=null;try{r=await Q(Re(e))}catch(o){n+=1,t.push({path:"settings.json",detail:xd("configuration file",o)})}if(r!==null){n+=1;let o=Pw(r);o!==null&&t.push({path:"settings.json",detail:o})}let i;try{i=await Yn.readdir(Jn.join(e,"schema"))}catch{return{scanned:n,unparseable:t}}for(let o of i.sort((s,a)=>s.localeCompare(a))){if(!o.endsWith(".json"))continue;n+=1;let s;try{s=await Yn.readFile(Jn.join(e,"schema",o),"utf8")}catch(c){t.push({path:`schema/${o}`,detail:xd("configuration file",c)});continue}let a=Pw(s);a!==null&&t.push({path:`schema/${o}`,detail:a})}return{scanned:n,unparseable:t}}async function Fw(e,t,n,r={}){let i=await PI(e,n),o=new Set(i.map(u=>u.id)),s=new Map;for(let u of i){let _=s.get(u.id);_===void 0?s.set(u.id,[u.relativePath]):_.push(u.relativePath)}let a=[...s.entries()].filter(([,u])=>u.length>1).map(([u,_])=>({id:u,paths:[..._].sort((h,f)=>h.localeCompare(f))})).sort((u,_)=>u.id.localeCompare(_.id)),c=(await Promise.all(i.map(async u=>{if(!t.has(u.id))return{path:u.relativePath,id:u.id};try{let _=Jn.join(e,u.relativePath);return io(await Yn.readFile(_,"utf8"),{format:_.toLowerCase().endsWith(".md")?"json_markdown":"toon",schema:r.schema,extensionFieldNames:r.extensionFieldNames}),null}catch{return{path:u.relativePath,id:u.id}}}))).filter(u=>u!==null),d=await UI(e,o),l=await GI(e);return{item_files_on_disk:i.length,item_ids_on_disk:o.size,parsed_items:t.size,unreadable_item_files:c,duplicate_item_ids:a,history_streams_scanned:d.scanned,history_conflict_marker_streams:d.conflictMarkers,history_unparseable_streams:d.unparseable,resurrected_items:d.resurrected,history_repair_reconciliations:d.repairReconciliations,config_files_scanned:l.scanned,unparseable_config_files:l.unparseable}}import{readFileSync as qI}from"node:fs";import ns from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d88c7294-44f1-5b65-9467-f94ed2db11ca")}catch{}})();var KI=new Set(["get","history","restore","update","close","delete","append","claim","release","comments","notes","learnings","files","docs","deps","test"]),Od=new Set(["--pm-path","--path","--author","--expect-hash"]),WI={get:new Set(["--depth","--fields","--tree-depth","--tree_depth","--at","--format"]),history:new Set(["--limit","--field","--format"]),restore:new Set(["--message"]),update:new Set(["--title","-t","--description","-d","--body","-b","--status","-s","--close-reason","--close_reason","--priority","-p","--type","--tags","--add-tags","--add_tags","--remove-tags","--remove_tags","--deadline","--estimated-minutes","--estimate","--estimated_minutes","--acceptance-criteria","--ac","--acceptance_criteria","--definition-of-ready","--definition_of_ready","--order","--rank","--goal","--objective","--value","--impact","--outcome","--why-now","--why_now","--message","--assignee","--parent","--reviewer","--risk","--confidence","--sprint","--release","--blocked-by","--blocked_by","--blocked-reason","--blocked_reason","--unblock-note","--unblock_note","--reporter","--severity","--environment","--repro-steps","--repro_steps","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual","--affected-version","--affected_version","--fixed-version","--fixed_version","--component","--regression","--customer-impact","--customer_impact","--dep","--dep-remove","--dep_remove","--comment","--note","--learning","--file","--test","--doc","--reminder","--event","--type-option","--type_option","--field","--unset","--body-file"]),close:new Set(["--reason","-r","--close-reason","--duplicate-of","-d","--message","-m","--validate-close","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual"]),delete:new Set(["--message"]),append:new Set(["--body","--text","--message"]),claim:new Set(["--assignee","--message","--type","--tag","--priority","--assignee-filter","--parent","--sprint","--release","--max-attempts"]),release:new Set(["--assignee","--message"]),comments:new Set(["--add","--body","--comment","--file","--edit","--delete","--limit","--message"]),notes:new Set(["--add","--file","--edit","--delete","--limit","--message"]),learnings:new Set(["--add","--file","--edit","--delete","--limit","--message"]),files:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),docs:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),deps:new Set(["--format","--max-depth","--collapse","--node-limit","--edge-limit","--token-budget","--cursor","--direction","--kind"]),test:new Set(["--add","--add-json","--remove","--match","--only-index","--timeout","--env-set","--env-clear","--pm-context","--message"])},zI=new Set(["-p","--package"]),BI=new Set(["-c","--call"]),Ld=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),Dd=new Set(["-C","--prefix","--userconfig","--cache"]),jw=new Set(["--cwd"]),Uw=new Set(["--cwd"]),HI=new Set(["exec","x"]),Gw=new Set(["run","run-script"]),qw=new Set(["-C","--dir","--cwd","-w","--workspace","--filter"]);function sn(e){return e.split(/&&|\|\||\||;/).map(t=>t.trim()).filter(t=>t.length>0)}function os(e,t=process.cwd()){let n=ss(e.split(" ").filter(s=>s.length>0));if(n.length===0)return null;let[r,...i]=n;if(rs(r)||is(r,t))return i;if(r==="node"&&i[0]&&is(i[0],t))return i.slice(1);let o=r==="npx"||r==="bunx"?an(i):r==="pnpm"?as(i):r==="npm"?cs(i):null;return o&&(rs(o.command)||Kw(o.command))?o.args:null}var $d=(e,t="pm")=>{let n=t.trim().toLowerCase(),r=n.length;for(;r>0&&n[r-1]==="-";)r-=1;let i=n.slice(0,r);if(i.length===0)return[];let o=e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase(),s=new Set;for(let a of sn(o)){let c=os(a),d=c?Nd(c):null,l=d&&KI.has(d.subcommand)?YI(d.remaining,WI[d.subcommand]):void 0,u=l?.trim().toLowerCase();u?.startsWith(`${i}-`)===!0&&u.length>i.length+1&&s.add(l)}return[...s].sort((a,c)=>a.localeCompare(c))};function ss(e){let t=0;for(e[t]==="env"&&(t+=1);t<e.length;){let n=e[t];if(/^(?:[a-z_][a-z0-9_]*|\$env:[a-z_][a-z0-9_]*)=.*/.test(n)){t+=1;continue}break}return e.slice(t)}function Id(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(Od.has(n)){t+=2;continue}t+=1;continue}return n}}function rs(e){return e==="pm"||e==="pm.cmd"||e==="pm.exe"||e.endsWith("/pm")||e.endsWith("/pm.cmd")||e.endsWith("/pm.exe")}function VI(e){let t=e.trim();if(!t.startsWith("@")){let i=t.indexOf("@");return i===-1?t:t.slice(0,i)}let n=t.indexOf("/");if(n===-1)return t;let r=t.indexOf("@",n+1);return r===-1?t:t.slice(0,r)}function Kw(e){let t=VI(e);return t==="pm-cli"||t.endsWith("/pm-cli")||e==="pm-cli"||e.endsWith("/pm-cli")}function is(e,t=process.cwd()){let n=e.replaceAll("\\","/");if(n!=="dist/cli.js"&&n!=="./dist/cli.js"&&!n.endsWith("/dist/cli.js"))return!1;let r=ns.resolve(t,e);try{return JSON.parse(qI(ns.join(ns.dirname(ns.dirname(r)),"package.json"),"utf8")).name==="@unbrained/pm-cli"}catch{return!1}}function an(e){let t=0;for(;t<e.length;){let r=e[t];if(r==="--"){t+=1;break}if(!r.startsWith("-"))break;let i=/^(?:-c|--call)=(.*)$/.exec(r);if(i){let o=i[1];return o?{command:o,args:e.slice(t+1)}:null}if(BI.has(r)){t+=1;break}t+=zI.has(r)&&!r.includes("=")?2:1}let n=e[t];return n?{command:n,args:e.slice(t+1)}:null}function Pt(e,t){let n=0;for(;n<e.length;){let r=e[n];if(r==="--"){n+=1;continue}if(r.startsWith("-")){if(r.includes("=")){n+=1;continue}if(t.has(r)){n+=2;continue}n+=1;continue}return{subcommand:r,args:e.slice(n+1)}}return null}function as(e){let t=Pt(e,Ld);return t?.subcommand!=="dlx"?null:an(t.args)}function cs(e){let t=Pt(e,Dd);return!t||!HI.has(t.subcommand)?null:an(t.args)}function Nd(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(Od.has(n)){t+=2;continue}t+=1;continue}return{subcommand:n,remaining:e.slice(t+1)}}return null}function YI(e,t=new Set){for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="--")return e[n+1];if(!r.startsWith("-"))return r;!r.includes("=")&&(Od.has(r)||t.has(r))&&(n+=1)}}function Rd(e){return!e||!rs(e.command)&&!Kw(e.command)?!1:Id(e.args)==="test-all"}var Md=new Map([...["sh","bash","dash","zsh"].map(e=>[e,/^(?:-c|-[a-z]*c[a-z]*)$/u]),...["cmd","cmd.exe"].map(e=>[e,/^\/[ck]$/u]),...["powershell","powershell.exe","pwsh","pwsh.exe"].map(e=>[e,/^-(?:c|command)$/u])]),JI=new Set(["npx","bunx"]);function Pd(e){let t=e.split(" ").filter(s=>s.length>0),n=ss(t);if(n.length===0)return!1;let[r,...i]=n,o=Md.get(r);if(o){let s=i.findIndex(a=>o.test(a));return s>=0?Pd(i.slice(s+1).join(" ")):!1}return rs(r)||is(r)?Id(i)==="test-all":r==="node"&&i.length>0&&is(i[0])?Id(i.slice(1))==="test-all":JI.has(r)?Rd(an(i)):r==="pnpm"?Rd(as(i)):r==="npm"?Rd(cs(i)):!1}function Fd(e){let t=Xn(e);return sn(t).some(n=>Pd(n))}function ni(e){if(Fd(e))throw new p('Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.',m.USAGE)}function Xn(e){return e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase()}import{execFile as XI}from"node:child_process";import{readFile as QI}from"node:fs/promises";import zw from"node:path";import{promisify as ZI}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8f1a3301-8938-5208-9177-72ee29f3d174")}catch{}})();var eO=ZI(XI),jd=1,tO="linked-test-trust.json";function Ud(e){return zw.join(sm(e),tO)}function Ww(){return{version:jd,acknowledged:{}}}async function Gd(e){try{let t=JSON.parse(await QI(Ud(e),"utf8"));return t.version!==jd||typeof t.acknowledged!="object"||t.acknowledged===null||Array.isArray(t.acknowledged)?Ww():{version:jd,acknowledged:t.acknowledged}}catch{return Ww()}}async function ii(e=process.cwd()){let t=process.env.GITHUB_HEAD_REF?.trim()||process.env.GITHUB_REF_NAME?.trim();if(t&&t!=="merge")return t;try{let{stdout:n}=await eO("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),r=n.trim();return r.length===0?void 0:r}catch{return}}function oi(e=process.cwd()){return process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||e}function nO(e){return e===null||typeof e!="object"?!1:typeof e.author=="string"&&e.author.trim().length>0&&typeof e.created_at=="string"&&wm(e.created_at)&&(e.source_kind==="local_mutation"||e.source_kind==="merge_union")}function ri(e,t){return{...e?{source_ref:e}:{},...t?{current_source_ref:t}:{}}}function rO(e,t,n,r){return e?.map(i=>i.command&&!i.provenance?{...i,provenance:{author:t,created_at:n,source_kind:"local_mutation",...r?{source_ref:r}:{}}}:i)}async function Qn(e,t,n){if(!e||e.length===0)return e;for(let i of e)gr(i);let r=oi();return rO(e,t,n,await ii(r))}function Bw(e){return Nu(Z({command:e.command??null,path:e.path??null,scope:e.scope,pm_context_mode:e.pm_context_mode??null,workspace_context_mode:e.workspace_context_mode??null,env_set:e.env_set??null,env_clear:e.env_clear??null,shared_host_safe:e.shared_host_safe??null,provenance:e.provenance??null,provenance_invalid:e.provenance_invalid??null}))}async function qd(e,t,n){let r=await Gd(e);return Hw(t,n,r)}function Hw(e,t,n){let r=Bw(e),i=e.provenance?.source_ref;if(e.provenance===void 0&&e.provenance_invalid!==!0)return{fingerprint:r,trusted:!0,reason:"legacy"};let o=Object.hasOwn(n.acknowledged,r);return e.provenance_invalid===!0||!nO(e.provenance)?o?{fingerprint:r,trusted:!0,reason:"acknowledged",...ri(void 0,t)}:{fingerprint:r,trusted:!1,reason:"invalid_provenance",...ri(void 0,t)}:e.provenance.source_kind==="local_mutation"&&i===void 0?{fingerprint:r,trusted:!0,reason:"local_mutation",...ri(void 0,t)}:e.provenance.source_kind==="local_mutation"&&i!==void 0&&i===t?{fingerprint:r,trusted:!0,reason:"local_source_ref",source_ref:i,current_source_ref:t}:o?{fingerprint:r,trusted:!0,reason:"acknowledged",...ri(i,t)}:{fingerprint:r,trusted:!1,reason:"foreign_source_ref",...ri(i,t)}}async function Vw(e,t,n){let r=await Gd(e);return t.map(i=>Hw(i,n,r))}async function Yw(e,t,n){let r=await Gd(e),i=t.filter(o=>typeof o.command=="string"&&o.command.length>0).map(Bw);for(let o of i)r.acknowledged[o]={acknowledged_at:n};return await Ct(zw.dirname(Ud(e))),await je(Ud(e),`${JSON.stringify(r,null,2)}
|
|
9
|
-
`),{acknowledged:i.length,fingerprints:i}}import rl from"node:fs/promises";import{realpathSync as pO}from"node:fs";import{execFile as _O}from"node:child_process";import $e from"node:path";import{promisify as fO}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8c3bbe6d-dcce-5b1a-8352-1472ab1ed6e2")}catch{}})();var iO=["metadata","resolution"],Kd=["metadata","resolution","estimates","timestamps","lifecycle"],oO="completed";function Wd(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function Jw(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function Xw(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let r=Jw(n.close_reason)??oO;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:r,command:`pm update ${n.id} --resolution ${Wd(r)}`,gate:"resolution"})}return t}function Qw(e){let t=[];for(let n of e){let r=Jw(n.resolution);r!==void 0&&t.push({item_id:n.id,check:"metadata",field:"close_reason",kind:"set_close_reason",value:r,command:`pm update ${n.id} --close-reason ${Wd(r)}`,gate:"metadata"})}return t}function Zw(e,t){return e.map(n=>{let r=kp(n.type,t);return{item_id:n.id,check:"metadata",field:"estimated_minutes",kind:"set_estimate",value:String(r),command:`pm update ${n.id} --estimate ${r}`,gate:"estimates"}})}function ev(e){return e.map(t=>t.grandparent_id!==void 0&&t.grandparent_active===!0?{item_id:t.id,check:"lifecycle",field:"parent",kind:"reparent",parent_id:t.grandparent_id,command:`pm update ${t.id} --parent ${t.grandparent_id}`,gate:"lifecycle"}:{item_id:t.id,check:"lifecycle",field:"parent",kind:"unset_parent",command:`pm update ${t.id} --unset parent`,gate:"lifecycle"})}function tv(e){let t=[];for(let n of e){if(n.classification!=="deleted")continue;let r=n.link_kind==="files"?"files":"docs";t.push({item_id:n.item_id,check:"files",field:n.link_kind,kind:n.link_kind==="files"?"prune_file_link":"prune_doc_link",path:n.path,command:`pm ${r} ${n.item_id} --remove ${Wd(n.path)}`})}return t}function nv(e){let t=(e??[]).flatMap(r=>r.split(",")).map(r=>r.trim()).filter(r=>r.length>0);if(t.length===0){if(e!==void 0&&e.length>0)throw new p(`--fix-scope values must not be empty. Supported values: ${Kd.join(", ")}.`,m.USAGE);return new Set(iO)}let n=new Set;for(let r of t){let i=r.toLowerCase().replaceAll("-","_");if(Kd.includes(i)){n.add(i);continue}throw new p(`Unknown --fix-scope value "${r}". Supported values: ${Kd.join(", ")}.`,m.USAGE)}return n}function rv(e,t){let n=[],r=[];for(let i of e)i.gate!==void 0&&!t.has(i.gate)?r.push(i):n.push(i);return{applicable:n,gated:r}}function si(e){return{item_id:e.item_id,check:e.check,field:e.field,command:e.command,...e.gate!==void 0?{gate:e.gate}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e93db1eb-e524-58bf-af2e-cb5f22f3047b")}catch{}})();var sO=/^([A-Z][A-Z0-9]*-\d+)\b/iu;function aO(e,t={}){if(typeof e!="string")return null;let n=e.trim();if(n.length===0)return null;let r=sO.exec(n);if(!r)return null;let i=r[1],o=i.toUpperCase(),s=i.slice(0,i.lastIndexOf("-")),a=new Set((t.configuredPrefixes??[]).map(u=>u.trim().replace(/-+$/u,"").toUpperCase())),c=n.slice(i.length),d=t.evidenceText?.toUpperCase()??"",l=d.includes(`ISSUE CODE: ${o}`)||d.includes(`ISSUE CODE \`${o}\``)||d.includes(`\`${o}\``)||d.includes(`[${o}]`);return s===s.toUpperCase()||/^\s*(?::|—|–|\])/u.test(c)||a.has(s.toUpperCase())||l?o:null}function iv(e){return typeof e=="string"&&e.trim().length>0}function cO(e){let t=new Set(e.map(s=>s.id.toLowerCase())),n=new Map,r=new Map;for(let s of e){let a=s.id.toLowerCase(),c=new Set([...s.parent===null?[]:[s.parent.toLowerCase()],...s.derivations].filter(d=>d!==a&&t.has(d)));n.set(a,c);for(let d of c){let l=r.get(d)??[];l.push(a),r.set(d,l)}}let i=[...[...n].filter(([,s])=>s.size===0).map(([s])=>s)],o=new Set;for(let s=0;s<i.length;s+=1)for(let a of r.get(i[s])??[]){let c=n.get(a);c.delete(i[s]),c.size===0&&(o.add(a),i.push(a))}return e.filter(s=>!o.has(s.id.toLowerCase()))}function ov(e,t={}){let n=new Map;for(let i of e){if(typeof i.title!="string"||iv(i.duplicate_of))continue;let o=aO(i.title,{...t,evidenceText:i.body});if(o===null)continue;let s=n.get(o);s||(s=[],n.set(o,s)),s.some(a=>a.id===i.id)||s.push({id:i.id,title:i.title,parent:iv(i.parent)?i.parent.trim():null,derivations:(i.dependencies??[]).filter(a=>["discovered_from","supersedes","incident_from"].includes(a.kind)).map(a=>a.id.trim().toLowerCase()).filter(a=>a!==i.id.toLowerCase())})}let r=[];for(let[i,o]of n){if(o.length<2)continue;let s=cO(o);if(s.length<2)continue;let a=[...s].sort((c,d)=>c.id.localeCompare(d.id));r.push({code:i,count:a.length,ids:a.map(c=>c.id),titles:a.map(c=>c.title)})}return r.sort((i,o)=>i.code.localeCompare(o.code))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3c32504d-254c-5156-a41f-8ffd8e49107f")}catch{}})();function sv(e){let t=new Map;for(let r of e){let i=t.get(r.item_type);i||(i=new Map,t.set(r.item_type,i)),i.set(r.field,(i.get(r.field)??0)+1)}let n={};for(let r of[...t.keys()].sort((i,o)=>i.localeCompare(o))){let i=t.get(r),o={};for(let s of[...i.keys()].sort((a,c)=>a.localeCompare(c)))o[s]=i.get(s);n[r]=o}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c577e41b-6642-554a-bc4d-0c22170c1e24")}catch{}})();function av(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function cv(e,t,n=3){let r=Number.isFinite(n)&&n>=1?Math.floor(n):3,i=new Map;for(let o of t){let s=av(o);if(s.length===0)continue;let a=i.get(s);a?a.push(o):i.set(s,[o])}return e.map(o=>{if(o.includes(",")||o.replace(/^[a-z]:[\\/]/i,"").includes(":"))return{path:o,classification:"malformed",candidates:[],candidates_truncated:!1};let s=(i.get(av(o))??[]).filter(a=>a!==o).sort((a,c)=>a.localeCompare(c));return s.length===0?{path:o,classification:"deleted",candidates:[],candidates_truncated:!1}:{path:o,classification:"moved",candidates:s.slice(0,r),candidates_truncated:s.length>r}})}function dv(e){return e.map(t=>t.classification==="moved"?`${t.path}:moved:${t.candidates[0]}`:`${t.path}:${t.classification}`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8cca9707-86a7-5ab5-8c7b-92be560254d0")}catch{}})();async function ds(e){return e.includeBody?gt(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema,{forceSourceScan:!0}):_o(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6322c4ff-92bd-59e5-aa64-ef8d3ef4b57f")}catch{}})();var dO=5;async function lO(e,t){let n=t.hashMismatches.filter(o=>o!==Xt);if(n.length===0)return;let r=await x(e),i=P(r,N());for(let o of n){let s=await xn(e,o,r.locks.ttl_seconds,"history-drift-read",!1,!0,r.locks.wait_ms);try{let a=await V(e,o,r.id_prefix,r.item_format,i.type_to_folder);if(a===null)throw new p(`Item ${o} not found`,m.NOT_FOUND,{code:"item_not_found",required:"Repeat validation after writers finish; each item-hash discrepancy requires readable canonical source."});let{document:c}=await pe(a,{schema:r.schema});if(c.metadata.id!==o)throw new p(`Item identity changed while validating ${o}`,m.CONFLICT,{code:"item_identity_conflict",required:"Restore the canonical item identity and validate storage integrity before retrying history validation."});let d=await Sh(e,{...c.metadata,body:c.body});for(let u of["missingStreams","unreadableStreams","hashMismatches","chainMismatches","versionSkews","driftedItems"])t[u]=[...t[u].filter(_=>_!==o),...d[u].filter(_=>_===o)].sort((_,h)=>_.localeCompare(h));let l=[...(t.identityDiscontinuities??[]).filter(u=>u.item_id!==o),...(d.identityDiscontinuities??[]).filter(u=>u.item_id===o)];l.length>0?t.identityDiscontinuities=l:delete t.identityDiscontinuities}finally{await s()}}}async function ls(e,t,n){let r=await Pr(e,t);await lO(e,r);let i=[["validate_history_drift_missing_streams",r.missingStreams.length],["validate_history_drift_unreadable_streams",r.unreadableStreams.length],["validate_history_drift_hash_mismatches",r.hashMismatches.length],["validate_history_drift_chain_mismatches",r.chainMismatches.length],["validate_history_drift_version_skews",r.versionSkews.length],["validate_history_drift_workspace_state_mismatches",r.workspaceStateMismatches.length],["validate_history_drift_workspace_state_missing",r.workspaceStateMissing.length],["validate_history_drift_workspace_state_unreadable",r.workspaceStateUnreadable.length]].filter(([,c])=>c>0).map(([c,d])=>`${c}:${d}`),o=n?Number.POSITIVE_INFINITY:dO,s=r.driftedItems.slice(0,o),a=r.identityDiscontinuities??[];return{check:{name:"history_drift",status:a.length>0?"error":i.length===0?"ok":"warn",ok:a.length===0&&i.length===0,details:{identity_discontinuities:a.slice(0,o),identity_discontinuities_count:a.length,identity_discontinuities_truncated:a.length>o,checked_items:t.length,drifted_items_count:r.driftedItems.length,drifted_items:s,drifted_items_truncated:s.length<r.driftedItems.length,counts:{missing_streams:r.missingStreams.length,unreadable_streams:r.unreadableStreams.length,hash_mismatches:r.hashMismatches.length,chain_mismatches:r.chainMismatches.length,version_skews:r.versionSkews.length,workspace_state_mismatches:r.workspaceStateMismatches.length,workspace_state_missing:r.workspaceStateMissing.length,workspace_state_unreadable:r.workspaceStateUnreadable.length},workspace_state_mismatches:r.workspaceStateMismatches,workspace_state_missing:r.workspaceStateMissing,workspace_state_unreadable:r.workspaceStateUnreadable,version_skews:r.versionSkews.slice(0,o)}},warnings:i}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fb73b204-3c60-5b9b-9576-e1c13ad537b3")}catch{}})();function zd(e){let t=0,n=new Map,r=new Map,i=[],o=new Set,s=[],a=d=>{n.set(d,t),r.set(d,t),t+=1,i.push(d),o.add(d);for(let u of e.get(d)??[])n.has(u)?o.has(u)&&r.set(d,Math.min(r.get(d),n.get(u))):(a(u),r.set(d,Math.min(r.get(d),r.get(u))));if(r.get(d)!==n.get(d))return;let l=[];for(;i.length>0;){let u=i.pop();if(o.delete(u),l.push(u),u===d)break}l.sort((u,_)=>u.localeCompare(_)),s.push(l)},c=[...e.keys()].sort((d,l)=>d.localeCompare(l));for(let d of c)n.has(d)||a(d);return s.filter(d=>{if(d.length>1)return!0;let l=d[0];return(e.get(l)??[]).includes(l)}).sort((d,l)=>d[0].localeCompare(l[0])||d.length-l.length||d.join(",").localeCompare(l.join(",")))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3caaa82b-d8c7-5bc4-94e5-6699da27fa3c")}catch{}})();function us(e,t){let n=e[0];if(e.length===1)return[n,n];let r=new Set(e),i=[n],o=new Set([n]),s=a=>{for(let c of(t.get(a)??[]).filter(d=>r.has(d))){if(c===n&&i.length>1)return i.push(n),!0;if(!o.has(c)){if(o.add(c),i.push(c),s(c))return!0;i.pop(),o.delete(c)}}return!1};return s(n)?[...i]:[...e,n]}function uO(e,t){if(typeof e!="string")return;let n=e.trim().toLowerCase();return n.length>0?t.get(n):void 0}function mO(e,t,n,r){for(let i of e.dependencies??[]){if(typeof i!="object"||i===null||typeof i.id!="string")continue;let o=r.resolve(i.kind);if(!o?.hierarchy)continue;let s=n.get(i.id.toLowerCase());s&&(o.hierarchyDirection==="source_parent"?t.get(s).push(e.id):t.get(e.id).push(s))}}function Bd(e,t=de()){let n=new Map(e.map(i=>[i.id.toLowerCase(),i.id])),r=new Map(e.map(i=>[i.id,[]]));for(let i of[...e].sort((o,s)=>o.id.localeCompare(s.id))){let o=r.get(i.id),s=uO(i.parent,n);s&&o.push(s),mO(i,r,n,t)}for(let[i,o]of r)r.set(i,[...new Set(o)].sort());return r}function Hd(e,t,n=de()){let r=To(e,s=>t?xt(s,t):s==="closed"||s==="canceled",n),i=Bd(e,n),o=r.cycles.map(s=>s.item_ids);return{cycle_count:o.length,active_cycle_count:r.cycles.filter(s=>!s.legacy_terminal).length,legacy_cycle_count:r.cycles.filter(s=>s.legacy_terminal).length,cycle_item_ids:[...new Set(o.flat())].sort(),cycle_sample_paths:o.map(s=>us(s,i).join("->")),cardinality_violation_count:r.cardinality_violations.length,active_cardinality_violation_count:r.cardinality_violations.filter(s=>!s.legacy_terminal).length,legacy_cardinality_violation_count:r.cardinality_violations.filter(s=>s.legacy_terminal).length,cardinality_violation_rows:r.cardinality_violations.map(s=>`${s.child_id}:${s.parent_ids.join(",")}:${s.legacy_terminal?"legacy":"active"}`),parent_divergence_count:r.divergences.length,active_parent_divergence_count:r.divergences.filter(s=>!s.legacy_terminal).length,legacy_parent_divergence_count:r.divergences.filter(s=>s.legacy_terminal).length,parent_divergence_rows:r.divergences.map(s=>`${s.child_id}:scalar=${s.scalar_parent_id}:dependencies=${s.dependency_parent_ids.join(",")}:${s.legacy_terminal?"legacy":"active"}`)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f2840c80-38f5-5563-b2c0-ef5596cf8f62")}catch{}})();function Ft(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/^\/+/,"")}function Vd(e){return Ft(e).replace(/\/+$/,"")}function Ze(e){let t=oe(e);if(!t)return;let n=t.toLowerCase();if(!(n==="none"||n==="null"||n==="n/a"||n==="na"))return t}function Yd(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length>120?`${t.slice(0,117)}...`:t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e046350f-afca-59d1-83c0-5df1e837d59d")}catch{}})();var hO=["src","tests","docs"],gO=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],yO=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),wO=["resolution","expected_result","actual_result"],vO=["default","tracked-all","tracked-all-strict"],lv=["core","strict","custom"],_s=["off","warn","error"],Qd=["author","acceptance_criteria","estimated_minutes","close_reason"],pv=[...Qd,"reviewer","risk","confidence","sprint","release"],Zd=Array.from(new Set(pv)),bO={author:"author",acceptance_criteria:"acceptance_criteria","acceptance-criteria":"acceptance_criteria",estimated_minutes:"estimated_minutes","estimated-minutes":"estimated_minutes",estimate:"estimated_minutes",close_reason:"close_reason","close-reason":"close_reason",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release"},kO={author:"validate_metadata_missing_author",acceptance_criteria:"validate_metadata_missing_acceptance_criteria",estimated_minutes:"validate_metadata_missing_estimate",close_reason:"validate_metadata_missing_close_reason",reviewer:"validate_metadata_missing_reviewer",risk:"validate_metadata_missing_risk",confidence:"validate_metadata_missing_confidence",sprint:"validate_metadata_missing_sprint",release:"validate_metadata_missing_release"},SO={author:"missing_author",acceptance_criteria:"missing_acceptance_criteria",estimated_minutes:"missing_estimated_minutes",close_reason:"closed_missing_close_reason",reviewer:"missing_reviewer",risk:"missing_risk",confidence:"missing_confidence",sprint:"missing_sprint",release:"missing_release"},EO={author:"missing_author_item_ids",acceptance_criteria:"missing_acceptance_criteria_item_ids",estimated_minutes:"missing_estimated_minutes_item_ids",close_reason:"closed_missing_close_reason_item_ids",reviewer:"missing_reviewer_item_ids",risk:"missing_risk_item_ids",confidence:"missing_confidence_item_ids",sprint:"missing_sprint_item_ids",release:"missing_release_item_ids"},TO={author:"missing_author_truncated",acceptance_criteria:"missing_acceptance_criteria_truncated",estimated_minutes:"missing_estimated_minutes_truncated",close_reason:"closed_missing_close_reason_truncated",reviewer:"missing_reviewer_truncated",risk:"missing_risk_truncated",confidence:"missing_confidence_truncated",sprint:"missing_sprint_truncated",release:"missing_release_truncated"},CO=32*1024*1024,AO=1e4,el=40,et=5,xO=4096,RO=255,IO=fO(_O);function _v(e){let t={};for(let[n,r]of Object.entries(e))Array.isArray(r)||r===!1&&n.endsWith("_truncated")||(t[n]=typeof r=="object"&&r!==null?_v(r):r);return t}function OO(e){return{...e,checks:e.checks.map(t=>({...t,details:_v(t.details)})),...e.fixes?{fixes:{mode:e.fixes.mode,auto_fix:e.fixes.auto_fix,prune_missing:e.fixes.prune_missing,planned_count:e.fixes.planned_count,applied_count:e.fixes.applied_count,gated_count:e.fixes.gated_count,failed_count:e.fixes.failed_count}}:{}}}function hs(e,t){return ce(e,t)??e}function ai(e,t){return t.terminal_statuses.has(hs(e,t))}function jt(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function ms(e,t){return e.length!==t.length?!1:e.every((n,r)=>n===t[r])}function LO(e){let t=jt($u),n={blocked_reason:jt(Ii.blocked_reason),resolution:jt(Ii.resolution),actual_result:jt(Ii.actual_result)},r=jt(e.validation.lifecycle_stale_blocker_reason_patterns),i={blocked_reason:jt(e.validation.lifecycle_closure_like_blocked_reason_patterns),resolution:jt(e.validation.lifecycle_closure_like_resolution_patterns),actual_result:jt(e.validation.lifecycle_closure_like_actual_result_patterns)};return{stale_blocker_reason_patterns:r,stale_blocker_reason_pattern_source:ms(r,t)?"default":"settings",closure_like_metadata_field_patterns:i,closure_like_metadata_field_pattern_sources:{blocked_reason:ms(i.blocked_reason,n.blocked_reason)?"default":"settings",resolution:ms(i.resolution,n.resolution)?"default":"settings",actual_result:ms(i.actual_result,n.actual_result)?"default":"settings"}}}function fv(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"core";if(lv.includes(t))return t;throw new p(`Unknown --metadata-profile value "${e}". Supported values: ${lv.join(", ")}.`,m.USAGE)}function hv(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(_s.includes(t))return t;throw new p(`Unknown --dependency-cycle-severity value "${e}". Supported values: ${_s.join(", ")}.`,m.USAGE)}function gv(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(_s.includes(t))return t;throw new p(`Unknown --parent-cycle-severity value "${e}". Supported values: ${_s.join(", ")}.`,m.USAGE)}function DO(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase().replaceAll("-","_")))].map(t=>bO[t]).filter(t=>t!==void 0).sort((t,n)=>t.localeCompare(n))}function $O(e,t,n){let r=DO(n);return e==="core"?{profile:e,profile_source:t,required_fields:[...Qd],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:e==="strict"?{profile:e,profile_source:t,required_fields:[...pv],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:r.length>0?{profile:e,profile_source:t,required_fields:r,configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:{profile:e,profile_source:t,required_fields:[...Qd],configured_custom_fields:r,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}var NO=new Set(["acceptance_criteria","estimated_minutes"]);function yv(e,t,n,r){return!r&&NO.has(t)&&ai(e.status,n)?!1:t==="author"?!oe(e.author):t==="acceptance_criteria"?!oe(e.acceptance_criteria):t==="estimated_minutes"?!Number.isFinite(e.estimated_minutes):t==="close_reason"?hs(e.status,n)===n.close_status&&!oe(e.close_reason):t==="reviewer"?!oe(e.reviewer):t==="risk"?!oe(e.risk):t==="confidence"?typeof e.confidence=="number"?!Number.isFinite(e.confidence):!oe(e.confidence):t==="sprint"?!oe(e.sprint):!oe(e.release)}function wv(e){if(e===void 0)return"default";let t=e.trim().toLowerCase();if(t.length===0||t==="default")return"default";if(t==="tracked-all"||t==="tracked_all")return"tracked-all";if(t==="tracked-all-strict"||t==="tracked_all_strict")return"tracked-all-strict";throw new p(`Unknown --scan-mode value "${e}". Supported values: ${vO.join(", ")}.`,m.USAGE)}function vv(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim();if(t)return $e.resolve(t);let n=$e.resolve(e);if(n.replaceAll("\\","/").endsWith("/.agents/pm"))return $e.dirname($e.dirname(n));let r=$e.resolve(process.cwd()),i=uv(n),o=uv(r),s=$e.relative(i,o);return s.length===0||!s.startsWith("..")&&!$e.isAbsolute(s)?n:r}function uv(e){try{return pO.native(e)}catch{return $e.resolve(e)}}function MO(e,t){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&t.includes(e.code)}async function il(e,t,n){let r=t.length>0?$e.join(e,t):e,i;try{i=await rl.readdir(r,{withFileTypes:!0})}catch(o){if(G(o))return;throw o}for(let o of i){if(o.name.startsWith("."))continue;let s=t.length>0?$e.join(t,o.name):o.name;if(o.isDirectory()){if(yO.has(o.name))continue;await il(e,s,n);continue}o.isFile()&&n.push(Ft(s))}}async function tl(e){let t=[];for(let n of hO)await il(e,n,t);for(let n of gO){let r=$e.join(e,n);try{(await rl.stat(r)).isFile()&&t.push(Ft(n))}catch{}}return[...new Set(t)].sort((n,r)=>n.localeCompare(r))}async function bv(e){try{let{stdout:t}=await IO("git",["ls-files","-z"],{cwd:e,encoding:"utf8",maxBuffer:CO,windowsHide:!0,timeout:AO}),n=t.split("\0").map(r=>Ft(r)).filter(r=>r.length>0);return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}catch{return null}}function PO(e,t){let n=new Set,r=Vd(Ou);r.length>0&&n.add(r);let i=Vd($e.relative(t,e));return i.length>0&&!i.startsWith("..")&&n.add(i),[...n].sort((o,s)=>o.localeCompare(s))}function mv(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}async function FO(e,t){if(t==="tracked-all"||t==="tracked-all-strict"){let r=await bv(e);if(r)return{requestedMode:t,appliedMode:t,source:"tracked-git",candidateFiles:r,candidateTotal:r.length,candidateScanned:r.length};let i=await tl(e);return{requestedMode:t,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:i,candidateTotal:i.length,candidateScanned:i.length}}let n=await tl(e);return{requestedMode:t,appliedMode:"default",source:"default-curated",candidateFiles:n,candidateTotal:n.length,candidateScanned:n.length}}function ne(e,t=et){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function cn(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=ne(e,el);return{values:n.values,truncated:n.truncated,total:e.length}}var jO={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},UO={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function GO(e){let t=e.missing_fields.map(n=>`${jO[n]} "${UO[n]}"`).join(" ");return`pm update ${e.id} ${t} --message "Backfill resolution metadata"`}function kv(e,t){let n=e.details?.missing_resolution_remediation_hints,r=Array.isArray(n)&&n.length>0,i=r?n.filter(s=>typeof s=="string"):dw(t);if(i.length===0)return;let o=r&&e.details?.missing_resolution_remediation_hints_truncated===!0;e.details={...e.details,fix_hints:i,...o?{fix_hints_truncated:!0}:{}}}function Sv(e){let t=new Set;return e.checkCompleteness&&t.add("completeness"),e.checkMetadata&&t.add("metadata"),e.checkResolution&&t.add("resolution"),(e.checkLifecycle||e.checkStaleBlockers)&&t.add("lifecycle"),e.checkFiles&&t.add("files"),e.checkHistoryDrift&&t.add("history_drift"),e.checkCommandReferences&&t.add("command_references"),e.checkStorageIntegrity&&t.add("storage_integrity"),t.size===0?(e.autoFix&&(t.add("metadata"),t.add("resolution"),t.add("lifecycle")),e.pruneMissing&&t.add("files"),t.size===0&&(t.add("metadata"),t.add("resolution"),t.add("lifecycle"),t.add("files"),t.add("command_references"),t.add("history_drift"),t.add("format_version"),t.add("completeness"),t.add("storage_integrity")),t):(e.pruneMissing&&t.add("files"),t)}var qO="validate_metadata_duplicate_issue_codes";function Ev(e,t){if(e.length===0)return{rows:[],truncated:!1,warnings:[]};let n=t?e.length:et,r=e.slice(0,n);return{rows:r.map(i=>({code:i.code,count:i.count,ids:i.ids,titles:i.titles,remediation_hint:`Items ${i.ids.join(", ")} share issue code "${i.code}"; rename or merge so each logical code maps to one item.`})),truncated:r.length<e.length,warnings:[`${qO}:${e.length}`]}}function KO(e,t,n){let r=Object.fromEntries(Zd.map(i=>[i,[]]));for(let i of e)for(let o of Zd)yv(i,o,t,n)&&r[o].push(i.id);return r}function WO(e,t,n){let r=[...e.warnings];for(let i of e.required_fields){let o=t[i];o.length>0&&r.push(`${kO[i]}:${o.length}`)}return r.push(...n),r}function Tv(e,t){let n={};for(let r of e.required_fields){let i=t[r],o=i?i.length:0,s=SO[r];n[s]=o}return n}function Cv(e,t,n){let r=[];for(let i of e.required_fields){let o=t[i];if(o)for(let s of o){let a=n.get(s)?.type,c=typeof a=="string"&&a.length>0?a:"Unknown";r.push({item_type:c,field:i})}}return r}function zO(e,t,n,r){for(let i of t.required_fields){let o=n[i];if(!o||o.length===0)continue;let s=EO[i],a=TO[i];if(!s||!a)continue;let c=ne(o,r?o.length:et);e[s]=c.values,e[a]=c.truncated}}function Av(e,t,n){if(!e.required_fields.includes("close_reason"))return[];let r=t.close_reason;return r?r.map(i=>({id:i,resolution:oe(n.get(i)?.resolution)})):[]}function xv(e,t,n){if(!e.required_fields.includes("estimated_minutes"))return[];let r=t.estimated_minutes;return r?r.map(i=>({id:i,type:oe(n.get(i)?.type)})):[]}function BO(e,t,n,r,i){let o=new Map(e.map(v=>[v.id,v])),s=t.profile==="strict",a=KO(e,n,s),c=ov(e,{configuredPrefixes:i}),d=Ev(c,r),l=WO(t,a,d.warnings),u=Tv(t,a),_=Cv(t,a,o),h=sv(_),f={checked_items:e.length,metadata_profile:t.profile,metadata_profile_source:t.profile_source,metadata_profile_fallback_to_core:t.fallback_to_core,required_fields:[...t.required_fields],supported_required_fields:[...Zd],counts:u,missing_by_type:h,duplicate_issue_codes_count:c.length,duplicate_issue_codes:d.rows,duplicate_issue_codes_truncated:d.truncated};t.configured_custom_fields.length>0&&(f.configured_custom_required_fields=[...t.configured_custom_fields]);let g=es(e,r);g!==void 0&&(f.deferred_fields=g.details,l.push(g.warning)),zO(f,t,a,r);let y=Av(t,a,o),w=xv(t,a,o);return{check:{name:"metadata",status:l.length===0?"ok":"warn",ok:l.length===0,details:f},warnings:l,closeReasonBackfillRows:y,estimateBackfillRows:w}}function HO(e,t,n){let r=new Set(t.terminal_done_statuses);r.add(t.close_status);let i=e.filter(_=>r.has(hs(_.status,t))),o=[],s=[];for(let _ of i){let h=wO.filter(f=>!oe(_[f]));h.length!==0&&(o.push({id:_.id,missing_fields:h}),s.push({id:_.id,missing_fields:h,close_reason:oe(_.close_reason)}))}let a=o.length>0?[`validate_resolution_missing_fields:${o.length}`]:[],c=n?Number.POSITIVE_INFINITY:et,d=ne(o.map(_=>`${_.id}:${_.missing_fields.join(",")}`),c),l=o.map(_=>GO(_)),u=ne(l,c);return{check:{name:"resolution",status:a.length===0?"ok":"warn",ok:a.length===0,details:{checked_closed_items:i.length,missing_resolution_items:o.length,missing_resolution_rows:d.values,missing_resolution_rows_truncated:d.truncated,missing_resolution_remediation_hints:u.values,missing_resolution_remediation_hints_truncated:u.truncated}},warnings:a,resolutionBackfillRows:s}}function Rv(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Iv(e,t="pm",n=Sm()){let r=new Set(e.map(o=>o.id)),i=[...e].sort((o,s)=>o.id.localeCompare(s.id));return new Map(i.map(o=>{let s=new Set,a=Ze(o.blocked_by);a&&r.has(a)&&s.add(a),(o.dependencies??[]).filter(d=>{let l=Ze(d.kind);return l!==void 0&&n.resolve(l)?.ordering===!0}).map(d=>Ze(d.id)).filter(d=>d!==void 0&&r.has(d)).forEach(d=>s.add(d));let c=Ze(o.definition_of_ready);return Lv(c??"",t).filter(d=>r.has(d)).forEach(d=>s.add(d)),[o.id,[...s].sort((d,l)=>d.localeCompare(l))]}))}function Ov(e,t,n){let r=dh(e,n?l=>ai(l,n):void 0),i=r.active.map(l=>`${l.holder_id}:${l.target_id}:${l.kind}`),o=r.legacy_terminal.map(l=>`${l.holder_id}:${l.target_id}:${l.kind}:${l.holder_status}`),s=t?Number.POSITIVE_INFINITY:et,a=ne(i,s),c=ne(o,s),d=ne(r.active.map(l=>l.source==="parent"?`pm update ${l.holder_id} --unset parent`:l.source==="blocked_by"?`pm update ${l.holder_id} --unset blocked_by`:`pm update ${l.holder_id} --replace-deps '<correct dependency edges>'`),s);return{check:{name:"dependency_references",status:i.length===0?"ok":"warn",ok:i.length===0,details:{checked_items:e.length,dangling_reference_count:i.length+o.length,active_dangling_reference_count:i.length,dangling_reference_rows:a.values,dangling_reference_rows_truncated:a.truncated,legacy_terminal_dangling_reference_count:o.length,legacy_closed_dangling_reference_count:r.legacy_terminal.filter(l=>l.holder_status==="closed").length,legacy_terminal_dangling_reference_rows:c.values,legacy_terminal_dangling_reference_rows_truncated:c.truncated,no_active_blocker_sentinel_count:r.no_active_blocker_sentinels.length,remediation_hints:d.values,remediation_hints_truncated:d.truncated}},warnings:i.length>0?[`validate_dangling_dependency_references:${i.length}`]:[]}}function Lv(e,t="pm"){let n=(t.trim().toLowerCase()||"pm").replace(/-+$/g,""),r=new RegExp(`(?:^|[^a-z0-9-])(${Rv(n)}-[a-z0-9][a-z0-9-]*)`,"gi");return[...new Set([...e.matchAll(r)].map(i=>i[1].toLowerCase()))].sort((i,o)=>i.localeCompare(o))}function Dv(e,t="pm"){let n=Iv(e,t),r=zd(n),i=[...new Set(r.flat())].sort((s,a)=>s.localeCompare(a)),o=r.map(s=>us(s,n).join("->"));return{cycle_count:r.length,cycle_item_ids:i,cycle_sample_paths:o}}function $v(e){return e.startsWith("docs/")?"docs_unowned":e.startsWith("tests/")?"tests_unowned":e.startsWith("src/")?"source_unowned":e.endsWith(".md")?"docs_unowned":"unlinked_existing"}function fs(e){let t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function Nv(e,t){let n=fs(e).split("/").filter(Boolean),r=fs(t).split("/").filter(Boolean),i=0;for(;i<n.length&&i<r.length&&n[i]===r[i];)i+=1;return i}function VO(e,t){let n=fs(t),r=fs(e),i=t.endsWith("/")?t:`${t}/`,o=e.startsWith(i),s=n.length>0&&n===r,a=Nv(e,t);return!o&&!s&&a===0?null:o?{score:t.length+1e3,confidence:"path_prefix"}:s?{score:a+500,confidence:"same_directory"}:{score:a,confidence:"shared_directory"}}function YO(e,t,n){return e===void 0||n>e.score||n===e.score&&t.id.localeCompare(e.item.id)<0}function JO(e,t,n){let r=t==="docs_unowned"?"docs":"files",i;return n.flatMap(o=>(r==="docs"?o.docs??[]:o.files??[]).map(s=>({item:o,link:s}))).forEach(({item:o,link:s})=>{if(s.scope!=="project")return;let a=Ft(s.path);if(a.length===0||a===e)return;let c=VO(e,a);c!==null&&YO(i,o,c.score)&&(i={item:o,score:c.score,confidence:c.confidence})}),i?{id:i.item.id,type:i.item.type,title:i.item.title,status:i.item.status,confidence:i.confidence}:null}function Mv(e,t){return e.map(n=>{let r=$v(n),i=r==="docs_unowned"?"docs":"files",o=JO(n,r,t),s=o?.id??"<id>";return{path:n,classification:r,owner_candidate:o,remediation_hint:`pm ${i} ${s} --add path=${n},scope=project,note="<why this artifact belongs to the item>"`}})}function Pv(e){return e.map(t=>`${t.path}:${t.classification} owner_candidate=${t.owner_candidate?.id??"unowned"} hint=${JSON.stringify(t.remediation_hint)}`)}function XO(e,t){return Object.entries(t.closure_like_metadata_field_patterns).filter(([n,r])=>{let i=Ze(e[n]);return i?r.some(o=>i.toLowerCase().includes(o)):!1}).map(([n])=>n).sort((n,r)=>n.localeCompare(r))}function QO(e,t,n,r,i){let o=Ze(t.parent),s=o?n.get(r.get(o.toLowerCase())??o):void 0;return{id:e.id,parent_id:t.id,grandparent_id:s?.id,grandparent_active:s!==void 0&&!ai(s.status,i)}}function ZO(e,t,n,r){let i=Ze(e.blocked_by),o=Ze(e.blocked_reason),s=o?.toLowerCase(),a=hs(e.status,n),c=[];return t.has(a)?(!i&&!o&&c.push("blocked_status_missing_blocker_context"),s?.includes("no active blocker")&&c.push("blocked_status_reason_reports_no_active_blocker"),s&&r.stale_blocker_reason_patterns.some(d=>s.includes(d))&&c.push("blocked_status_reason_matches_stale_pattern"),c):(i&&c.push("non_blocked_status_has_blocked_by"),o&&c.push("non_blocked_status_has_blocked_reason"),c)}function eL(e,t,n,r){let i=new Map(e.map(c=>[c.id,c])),o=new Map(e.map(c=>[c.id.toLowerCase(),c.id])),s=n.blocked_statuses.size>0?n.blocked_statuses:new Set(["blocked"]),a={activeItems:e.filter(c=>!ai(c.status,n)),closureLikeRows:[],terminalParentRows:[],terminalParentFixRows:[],staleBlockerRows:[]};for(let c of a.activeItems){let d=XO(c,r);d.length>0&&a.closureLikeRows.push({id:c.id,fields:d});let l=Ze(c.parent),u=l?i.get(o.get(l.toLowerCase())??l):void 0;if(u&&ai(u.status,n)&&(a.terminalParentRows.push({id:c.id,parent_id:u.id,parent_status:u.status}),a.terminalParentFixRows.push(QO(c,u,i,o,n))),t){let _=ZO(c,s,n,r);_.length>0&&a.staleBlockerRows.push({id:c.id,status:c.status,reasons:[...new Set(_)].sort((h,f)=>h.localeCompare(f))})}}return a}function tL(e){e.closureLikeRows.sort((t,n)=>t.id.localeCompare(n.id)),e.terminalParentRows.sort((t,n)=>t.id.localeCompare(n.id)||t.parent_id.localeCompare(n.parent_id)),e.terminalParentFixRows.sort((t,n)=>t.id.localeCompare(n.id)||t.parent_id.localeCompare(n.parent_id)),e.staleBlockerRows.sort((t,n)=>t.id.localeCompare(n.id))}function ps(e,t,n){return n<=0||t==="off"?null:`${t==="error"?`${e}_error`:e}:${n}`}function Jd(e,t,n){return n>0&&t!=="off"?`${e}:${n}`:null}function nL(e,t,n,r,i){let o=[];e.closureLikeRows.length>0&&o.push(`validate_lifecycle_active_closure_like_metadata:${e.closureLikeRows.length}`),e.terminalParentRows.length>0&&o.push(`validate_lifecycle_active_terminal_parent:${e.terminalParentRows.length}`),t&&e.staleBlockerRows.length>0&&o.push(`validate_lifecycle_stale_blockers:${e.staleBlockerRows.length}`);let s=ps("validate_lifecycle_dependency_cycles",n,i.dependencyCycles),a=ps("validate_hierarchy_parent_cycle",r,i.activeHierarchyCycles),c=ps("validate_hierarchy_cardinality_violation",r,i.activeHierarchyCardinality),d=ps("validate_hierarchy_parent_divergence",r,i.activeHierarchyDivergence),l=Jd("validate_legacy_hierarchy_parent_cycle",r,i.legacyHierarchyCycles),u=Jd("validate_legacy_hierarchy_cardinality_violation",r,i.legacyHierarchyCardinality),_=Jd("validate_legacy_hierarchy_parent_divergence",r,i.legacyHierarchyDivergence);return[...o,...s?[s]:[],...a?[a]:[],...c?[c]:[],...d?[d]:[],...l?[l]:[],...u?[u]:[],..._?[_]:[]]}function Fv(e){let t=Ft(e);return t.length>xO||t.split(/[\\/]/).some(n=>n.length>RO)}async function rL(e,t){let n=$e.isAbsolute(t)?t:$e.resolve(e,t);if(Fv(n))return!1;try{let r=await rl.stat(n);return!r.isFile()&&!r.isDirectory()}catch(r){return MO(r,["ENOENT","ENOTDIR"])}}async function iL(e,t){let n={linkedProjectPaths:new Set,remoteLinkedPaths:new Set,missingLinkedPaths:[],staleLinkRows:[]},r=e.flatMap(i=>[...(i.files??[]).map(o=>({item:i,artifact:o,link_kind:"files"})),...(i.docs??[]).map(o=>({item:i,artifact:o,link_kind:"docs"}))]);for(let{item:i,artifact:o,link_kind:s}of r){if(o.scope!=="project")continue;if(Xr(o.path)){n.remoteLinkedPaths.add(o.path.trim());continue}let a=Ft(o.path);a.length!==0&&(n.linkedProjectPaths.add(a),await rL(t,o.path)&&(n.missingLinkedPaths.push(a),n.staleLinkRows.push({item_id:i.id,path:a,link_kind:s})))}return n}function oL(e,t,n,r,i,o){let s=r==="tracked-all-strict",a=s&&!i,c=i||s,d=c?[]:PO(t,n),l=d.length===0?[]:e.candidateFiles.filter(h=>mv(h,d)),u=d.length===0?e.candidateFiles:e.candidateFiles.filter(h=>!mv(h,d)),_={};if(l.length>0){let h=cn(l,o);_.pm_internals={count:l.length,paths:h.values,paths_truncated:h.truncated,paths_total:h.total}}return{strictTrackedAllMode:s,strictModeForcesPmInternals:a,includePmInternalsEffective:c,pmInternalCandidatePrefixes:d,excludedPmInternalPaths:l,candidateFiles:u,excludedByReason:_}}function jv(e,t,n,r,i,o,s,a="pm"){let c=eL(e,t,i,o);tL(c);let d=Dv(c.activeItems,a),l=Hd(e,i),u=Xo(i,e,s?Number.POSITIVE_INFINITY:et),_=[...nL(c,t,n,r,{dependencyCycles:d.cycle_count,activeHierarchyCycles:l.active_cycle_count,activeHierarchyCardinality:l.active_cardinality_violation_count,activeHierarchyDivergence:l.active_parent_divergence_count,legacyHierarchyCycles:l.legacy_cycle_count,legacyHierarchyCardinality:l.legacy_cardinality_violation_count,legacyHierarchyDivergence:l.legacy_parent_divergence_count}),...Qo(u)],h=s?Number.POSITIVE_INFINITY:et,f=ne(c.closureLikeRows.map(C=>`${C.id}:${C.fields.join(",")}`),h),g=ne(c.terminalParentRows.map(C=>`${C.id}:${C.parent_id}:${C.parent_status}`),h),y=ne(c.staleBlockerRows.map(C=>`${C.id}:${C.status}:${C.reasons.join(",")}`),h),w=ne(d.cycle_item_ids,h),v=ne(d.cycle_sample_paths,h),k=ne(l.cycle_item_ids,h),S=ne(l.cycle_sample_paths,h),b=ne(l.cardinality_violation_rows,h),A=ne(l.parent_divergence_rows,h),E=d.cycle_count>0&&n==="error"||(l.active_cycle_count>0||l.active_cardinality_violation_count>0||l.active_parent_divergence_count>0)&&r==="error";return{check:{name:"lifecycle",status:E?"error":_.length===0?"ok":"warn",ok:!E&&_.length===0,details:{checked_active_items:c.activeItems.length,lifecycle_status_roles:u,active_closure_like_metadata_items:c.closureLikeRows.length,active_closure_like_metadata_rows:f.values,active_closure_like_metadata_rows_truncated:f.truncated,active_terminal_parent_items:c.terminalParentRows.length,active_terminal_parent_rows:g.values,active_terminal_parent_rows_truncated:g.truncated,stale_blocker_checks_enabled:t,stale_blocker_items:c.staleBlockerRows.length,stale_blocker_rows:y.values,stale_blocker_rows_truncated:y.truncated,dependency_cycle_severity_policy:n,dependency_cycle_count:d.cycle_count,dependency_cycle_item_count:d.cycle_item_ids.length,dependency_cycle_item_ids:w.values,dependency_cycle_item_ids_truncated:w.truncated,dependency_cycle_sample_paths:v.values,dependency_cycle_sample_paths_truncated:v.truncated,parent_cycle_severity_policy:r,parent_cycle_count:l.cycle_count,active_parent_cycle_count:l.active_cycle_count,legacy_parent_cycle_count:l.legacy_cycle_count,parent_cycle_item_count:l.cycle_item_ids.length,parent_cycle_item_ids:k.values,parent_cycle_item_ids_truncated:k.truncated,parent_cycle_sample_paths:S.values,parent_cycle_sample_paths_truncated:S.truncated,hierarchy_cardinality_violation_count:l.cardinality_violation_count,active_hierarchy_cardinality_violation_count:l.active_cardinality_violation_count,legacy_hierarchy_cardinality_violation_count:l.legacy_cardinality_violation_count,hierarchy_cardinality_violation_rows:b.values,hierarchy_cardinality_violation_rows_truncated:b.truncated,hierarchy_parent_divergence_count:l.parent_divergence_count,active_hierarchy_parent_divergence_count:l.active_parent_divergence_count,legacy_hierarchy_parent_divergence_count:l.legacy_parent_divergence_count,hierarchy_parent_divergence_rows:A.values,hierarchy_parent_divergence_rows_truncated:A.truncated,stale_blocker_reason_patterns:[...o.stale_blocker_reason_patterns],stale_blocker_reason_pattern_source:o.stale_blocker_reason_pattern_source,closure_like_blocked_reason_patterns:[...o.closure_like_metadata_field_patterns.blocked_reason],closure_like_blocked_reason_pattern_source:o.closure_like_metadata_field_pattern_sources.blocked_reason,closure_like_resolution_patterns:[...o.closure_like_metadata_field_patterns.resolution],closure_like_resolution_pattern_source:o.closure_like_metadata_field_pattern_sources.resolution,closure_like_actual_result_patterns:[...o.closure_like_metadata_field_patterns.actual_result],closure_like_actual_result_pattern_source:o.closure_like_metadata_field_pattern_sources.actual_result}},warnings:_,terminalParentFixRows:c.terminalParentFixRows}}async function Uv(e,t,n,r,i,o,s=W(qt.schema)){let a=await iL(e,t),c=new Map(e.map(T=>[T.id,T])),d=[...new Set(a.missingLinkedPaths)].sort((T,F)=>T.localeCompare(F)),l=await FO(t,r),u=oL(l,n,t,r,i,o),_=u.candidateFiles.filter(T=>!a.linkedProjectPaths.has(T)),h=Mv(_,e),f=cv(d,u.candidateFiles),g=new Map(f.map(T=>[T.path,T.classification])),y=f.filter(T=>T.classification==="moved").length,w=a.staleLinkRows.map(T=>({...T,classification:g.get(T.path)??"deleted"})).sort((T,F)=>T.item_id.localeCompare(F.item_id)||T.path.localeCompare(F.path)||T.link_kind.localeCompare(F.link_kind)),v=[];u.strictModeForcesPmInternals&&v.push("validate_files_tracked_all_strict_forces_pm_internals"),_.length>0&&v.push(`validate_files_orphaned_paths:${_.length}`);let k=[...a.remoteLinkedPaths].sort((T,F)=>T.localeCompare(F)),S=cn(k,o),b=cn(d,o),A=cn(_,o),E=cn(h.map(T=>`${T.path}:${T.classification}:owner_candidate=${T.owner_candidate?.id??"unowned"}`),o),C=o?h:cn(Pv(h),!1).values,O=cn(dv(f),o),M=Mw(w,f,T=>c.get(T),s,o?1/0:el);return M.active_missing_linked_paths_count>0&&v.push(`validate_files_missing_linked_paths:${M.active_missing_linked_paths_count}`),{check:{name:"files",status:v.length===0?"ok":"warn",ok:v.length===0,details:{workspace_root:t,scan_mode_requested:l.requestedMode,scan_mode_applied:l.appliedMode,strict_tracked_all_mode:u.strictTrackedAllMode,strict_mode_forces_pm_internals:u.strictModeForcesPmInternals,strict_mode_forces_pm_internals_notice:u.strictModeForcesPmInternals?"tracked-all-strict force-enables PM internals; pass --include-pm-internals to make inclusion explicit.":null,file_list_detail_mode:o?"full":"summary",file_list_summary_limit:el,candidate_scan_source:l.source,include_pm_internals:u.includePmInternalsEffective,include_pm_internals_requested:i,pm_internal_candidate_prefixes:u.pmInternalCandidatePrefixes,pm_internal_excluded_count:u.excludedPmInternalPaths.length,excluded_total:u.excludedPmInternalPaths.length,excluded_by_reason:u.excludedByReason,linked_project_paths:a.linkedProjectPaths.size,remote_linked_paths_count:k.length,remote_linked_paths_total:S.total,remote_linked_paths:S.values,remote_linked_paths_truncated:S.truncated,candidate_total_raw:l.candidateTotal,candidate_scanned_raw:l.candidateScanned,candidate_total:u.candidateFiles.length,candidate_scanned:u.candidateFiles.length,scanned_candidate_files:u.candidateFiles.length,missing_linked_paths_count:d.length,missing_linked_paths_total:b.total,missing_linked_paths:b.values,missing_linked_paths_truncated:b.truncated,missing_linked_paths_moved_count:y,missing_linked_paths_deleted_count:f.filter(T=>T.classification==="deleted").length,missing_linked_paths_malformed_count:f.filter(T=>T.classification==="malformed").length,missing_linked_path_classifications:O.values,missing_linked_path_classifications_truncated:O.truncated,...M,orphaned_paths_count:_.length,orphaned_paths_total:A.total,orphaned_paths:A.values,orphaned_paths_truncated:A.truncated,orphaned_path_classifications:E.values,orphaned_path_classifications_truncated:E.truncated,orphaned_path_rows_count:h.length,orphaned_path_rows:C}},warnings:v,staleLinkPruneRows:w}}function sL(e,t){let n=[];return e.forEach(({item:r,linkedTest:i},o)=>{let s=t[o];if(s.trusted)return;let a=Yd(i.command??"");n.push(`${r.id}:${s.source_ref??"unknown"}->${s.current_source_ref??"unknown"}:${a}`)}),n}async function Gv(e,t,n,r){let i=new Set(e.map(b=>b.id.toLowerCase())),o=0,s=0,a=new Set,c=[],d=e.flatMap(b=>(b.tests??[]).map(A=>({item:b,linkedTest:A}))),l=await ii(oi()),u=await Vw(r,d.map(({linkedTest:b})=>b),l),_=sL(d,u);for(let{item:b,linkedTest:A}of d){if(typeof A.command!="string"||A.command.trim().length===0)continue;o+=1;let E=$d(A.command,t);if(E.length!==0){s+=E.length;for(let C of E)a.add(C),i.has(C.toLowerCase())||c.push(`${b.id}:${C}:${Yd(A.command)}`)}}let h=[...new Set(c)].sort((b,A)=>b.localeCompare(A)),f=[...new Set(h.map(b=>b.split(":")[1]??""))].filter(b=>b.length>0).sort((b,A)=>b.localeCompare(A)),g=[];h.length>0&&g.push(`validate_command_references_stale_pm_ids:${h.length}`),_.length>0&&g.push(`validate_linked_test_trust_unacknowledged:${_.length}`);let y=n?Number.POSITIVE_INFINITY:et,w=ne(h,y),v=ne(f,y),k=ne([...a].sort((b,A)=>b.localeCompare(A)),y),S=ne(_,y);return{check:{name:"command_references",status:g.length===0?"ok":"warn",ok:g.length===0,details:{checked_items:e.length,linked_commands_scanned:o,referenced_pm_ids_count:s,unique_referenced_pm_ids_count:a.size,unique_referenced_pm_ids:k.values,unique_referenced_pm_ids_truncated:k.truncated,linked_test_trust_current_source_ref:l??null,untrusted_linked_tests_count:_.length,untrusted_linked_tests:S.values,untrusted_linked_tests_truncated:S.truncated,stale_pm_id_references_count:h.length,stale_pm_ids_count:f.length,stale_pm_ids:v.values,stale_pm_ids_truncated:v.truncated,stale_pm_id_reference_rows:w.values,stale_pm_id_reference_rows_truncated:w.truncated}},warnings:g}}function aL(e,t){let n=no(e.map(c=>({ref:c.id,version:to(c)})),Sr,eo),r=[];n.outdated.length>0&&r.push(`validate_format_version_outdated_items:${n.outdated.length}`),n.ahead.length>0&&r.push(`validate_format_version_ahead_items:${n.ahead.length}`);let i=t?Number.POSITIVE_INFINITY:et,o=ne(n.outdated,i),s=ne(n.ahead,i),a=n.ahead.length>0?"error":n.outdated.length>0?"warn":"ok";return{check:{name:"format_version",status:a,ok:a==="ok",details:{checked_items:e.length,current_format_version:Sr,outdated_items_count:n.outdated.length,outdated_items:o.values,outdated_items_truncated:o.truncated,ahead_items_count:n.ahead.length,ahead_items:s.values,ahead_items_truncated:s.truncated}},warnings:r}}var nl="pm validate auto-fix";async function qv(e,t,n){switch(e.kind){case"set_closed_at":await Dw(e,t);return;case"set_resolution":case"set_close_reason":case"set_estimate":case"reparent":case"unset_parent":{let r={message:nl};if(e.kind==="set_resolution"?r.resolution=e.value:e.kind==="set_close_reason"?r.closeReason=e.value:e.kind==="set_estimate"?r.estimatedMinutes=e.value:e.kind==="reparent"?r.parent=e.parent_id:r.unset=["parent"],!n.runUpdate)throw new p("Applying validate metadata/lifecycle fixes requires a runUpdate mutation service.",m.USAGE);await n.runUpdate(e.item_id,r,t);return}case"prune_file_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`);case"prune_doc_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`)}}function Xd(e){return e.kind!=="prune_file_link"&&e.kind!=="prune_doc_link"?null:`${e.kind}:${e.item_id}`}async function Kv(e,t,n){let r=[],i=[],o=new Map;for(let s of e.filter(a=>Xd(a)===null))try{await qv(s,t,n),r.push(s)}catch(a){i.push({fix:s,error:a})}for(let s of e.filter(a=>Xd(a)!==null)){let a=Xd(s),c=o.get(a);c?c.push(s):o.set(a,[s])}for(let s of o.values()){let a=s[0];if(!a)continue;let c=s.map(d=>d.path).filter(d=>typeof d=="string"&&d.length>0);try{a.kind==="prune_file_link"?await Dy(a.item_id,{remove:c,message:nl},t):await vy(a.item_id,{remove:c,message:nl},t),r.push(...s)}catch(d){i.push(...s.map(l=>({fix:l,error:d})))}}return t_(i.map(s=>s.error)),{applied:r,failed:i}}var AH={applyValidateFix:qv,applyValidateFixes:Kv,attachValidateFixHints:kv,buildCommandReferencesCheck:Gv,buildDependencyReferencesCheck:Ov,buildCloseReasonBackfillRows:Av,buildFilesCheck:Uv,buildLifecycleCheck:jv,buildLifecycleDependencyGraph:Iv,buildLifecycleParentGraph:Bd,buildEstimateBackfillRows:xv,buildMetadataCounts:Tv,buildMissingFieldOccurrences:Cv,buildOrphanedPathRows:Mv,classifyOrphanedPath:$v,collectDefaultProjectFileCandidates:tl,collectTrackedGitFileCandidates:bv,detectLifecycleDependencyCycles:Dv,detectLifecycleParentCycles:Hd,escapeRegExp:Rv,extractItemIds:Lv,findLifecycleDependencyCycleComponents:zd,isMetadataFieldMissing:yv,linkedArtifactPathExceedsFilesystemLimits:Fv,listFilesRecursive:il,resolveDependencyCycleSeverity:hv,resolveParentCycleSeverity:gv,resolveFileScanMode:wv,resolveLifecycleDependencyCycleSamplePath:us,resolveRequestedChecks:Sv,resolveValidateMetadataProfile:fv,resolveWorkspaceRoot:vv,sharedDirectoryPrefixLength:Nv,summarizeOrphanedPathRows:Pv,summarizeDuplicateIssueCodes:Ev,toMeaningfulString:Ze};function cL(e,t){t>0&&e.push(`merge_receipt_evidence_invalid:${t}`)}async function dL(e,t,n,r){let i=await Fw(e,new Set(t.map(y=>y.id)),n,{schema:r.schema,extensionFieldNames:At(N())}),o=[];i.unreadable_item_files.length>0&&o.push(`validate_storage_unreadable_items:${i.unreadable_item_files.length}`),i.duplicate_item_ids.length>0&&o.push(`validate_storage_duplicate_item_ids:${i.duplicate_item_ids.length}`),i.history_conflict_marker_streams.length>0&&o.push(`validate_storage_history_conflict_markers:${i.history_conflict_marker_streams.length}`),i.history_unparseable_streams.length>0&&o.push(`validate_storage_unparseable_history:${i.history_unparseable_streams.length}`),i.resurrected_items.length>0&&o.push(`validate_storage_resurrected_items:${i.resurrected_items.length}`),i.unparseable_config_files.length>0&&o.push(`validate_storage_unparseable_config:${i.unparseable_config_files.length}`);let s=o.length,a=await Zo(e);a.tracked_path_count>0&&o.push(`validate_storage_tracked_runtime_cache_files:${a.tracked_path_count}`);let c=await Nn(e,$n(r));c.status==="drift"&&o.push(`validate_merge_fence_drift:${c.missing_patterns.length+c.stale_patterns.length}`);let d=await Dt(e),l=d===null?null:await Mn(d);l!==null&&l.status!=="ok"&&o.push(`validate_merge_driver_configuration:${l.missing_keys.length+l.drifted_keys.length}`);let u=await Pn(d??e,{includeLossless:!0,pmRoot:e}),_=u.receipts,{pendingDecisions:h,lossless:f}=Fn(_);h.length>0&&o.push(`validate_merge_decisions_unreviewed:${h.length}`),cL(o,u.invalid_evidence_count);let g=s>0?"error":o.length>0?"warn":"ok";return{check:{name:"storage_integrity",status:g,ok:g==="ok",details:{...i,merge_fence:c,merge_driver_configuration:l,pending_merge_decision_count:h.length,pending_merge_decision_items:[...new Set(h.map(y=>y.item_id))].sort((y,w)=>y.localeCompare(w)),lossless_merge_receipt_count:f.length,invalid_merge_receipt_evidence_count:u.invalid_evidence_count,invalid_merge_receipt_evidence_details:u.invalid_evidence,invalid_merge_receipt_evidence_details_truncated:u.invalid_evidence_truncated,lossless_merge_receipt_items:[...new Set(f.map(y=>y.item_id))].sort((y,w)=>y.localeCompare(w)),tracked_runtime_cache:{tracker_relative_root:a.tracker_relative_root,tracked_paths:a.tracked_paths,tracked_path_count:a.tracked_path_count,remediation_command:a.remediation_command}}},warnings:o}}function mt(e,t,n){n&&kv(t.check,t.warnings),e.checks.push(t.check),e.warnings.push(...t.warnings)}async function lL(e){let t={closureTimestampFixes:[],checks:[],warnings:[...e.initialWarnings],closeReasonBackfillRows:[],estimateBackfillRows:[],resolutionBackfillRows:[],terminalParentFixRows:[],staleLinkPruneRows:[]},n=e.options.fixHints===!0,r=e.options.verboseDiagnostics===!0||e.options.allAffectedIds===!0||e.global.json===!0;if(e.requestedChecks.has("completeness")){let i=await hh(e.pmRoot,e.items,r?1/0:et,e.sourceIncomplete);mt(t,i,n)}if(e.requestedChecks.has("metadata")){let i=BO(e.items,e.metadataPolicy,e.statusRegistry,r,[e.settings.id_prefix]);t.closeReasonBackfillRows=i.closeReasonBackfillRows,t.estimateBackfillRows=i.estimateBackfillRows;let o=await Lw(e.pmRoot,e.items,e.statusRegistry,e.options.autoFix===!0||n,r?1/0:et);t.closureTimestampFixes=o.fixes,Object.assign(i.check.details,o.details),i.warnings.push(...o.warnings),i.check.ok=i.warnings.length===0,i.check.status=i.check.ok?"ok":"warn",mt(t,i,n)}if(e.requestedChecks.has("resolution")){let i=HO(e.items,e.statusRegistry,r);t.resolutionBackfillRows=i.resolutionBackfillRows,mt(t,i,n)}if(e.requestedChecks.has("lifecycle")){let i=jv(e.items,!!e.options.checkStaleBlockers,e.dependencyCycleSeverity,e.parentCycleSeverity,e.statusRegistry,e.lifecyclePatternPolicy,r,e.settings.id_prefix);t.terminalParentFixRows=i.terminalParentFixRows,mt(t,i,n),mt(t,Ov(e.items,r,e.statusRegistry),n)}if(e.requestedChecks.has("files")){let i=await Uv(e.items,e.workspaceRoot,e.pmRoot,e.fileScanMode,!!e.options.includePmInternals,!!e.options.verboseFileLists,e.statusRegistry);t.staleLinkPruneRows=i.staleLinkPruneRows,mt(t,i,n)}return e.requestedChecks.has("command_references")&&mt(t,await Gv(e.items,e.settings.id_prefix,r,e.pmRoot),n),e.requestedChecks.has("history_drift")&&mt(t,await ls(e.pmRoot,e.items,r),n),e.requestedChecks.has("format_version")&&mt(t,aL(e.items,r),n),e.requestedChecks.has("storage_integrity")&&mt(t,await dL(e.pmRoot,e.items,P(e.settings,N()).type_to_folder,e.settings),n),t}function uL(e,t,n){let r=[];return e.autoFix===!0&&(r.push(...t.closureTimestampFixes),r.push(...Qw(t.closeReasonBackfillRows)),r.push(...Xw(t.resolutionBackfillRows)),r.push(...Zw(t.estimateBackfillRows,n.validation.estimate_defaults_by_type)),r.push(...ev(t.terminalParentFixRows))),e.pruneMissing===!0&&r.push(...tv(t.staleLinkPruneRows)),r}async function mL(e,t,n,r,i,o){if(e.autoFix!==!0&&e.pruneMissing!==!0)return;let s=uL(e,t,n),{applicable:a,gated:c}=rv(s,r),d=e.dryRun===!0,l=[],u=[];if(!d){let _=await Kv(a,i,o);l.push(..._.applied.map(si)),u.push(..._.failed.map(({fix:h,error:f})=>({...si(h),error:f instanceof Error?f.message:String(f)})))}return{mode:d?"dry_run":"apply",auto_fix:e.autoFix===!0,prune_missing:e.pruneMissing===!0,granted_fix_scopes:[...r].sort((_,h)=>_.localeCompare(h)),planned_count:s.length,applied_count:l.length,gated_count:c.length,failed_count:u.length,planned_fixes:s.map(si),applied_fixes:l,gated_fixes:c.map(_=>({...si(_),gate_hint:`Withheld: re-run with --fix-scope ${_.gate} to apply.`})),failed_fixes:u}}async function Wv(e,t,n={}){sp(e.counts===!0,e.full===!0,"--counts");let r=e.autoFix===!0||e.pruneMissing===!0;if(e.dryRun===!0&&!r)throw new p("--dry-run requires --auto-fix or --prune-missing (there is nothing to preview otherwise).",m.USAGE);if(e.fixScope!==void 0&&e.fixScope.length>0&&e.autoFix!==!0)throw new p("--fix-scope requires --auto-fix.",m.USAGE);let i=nv(e.fixScope),o=R(process.cwd(),t.path);await j(o);let s=await x(o),a=W(s.schema),c=P(s,N()),d=Sv(e),l=[],u=await ds({includeBody:["history_drift","metadata","completeness"].some(O=>d.has(O)),pmRoot:o,settings:s,typeToFolder:c.type_to_folder,warnings:l}),_=l.length>0;if(d.has("history_drift")){let O=await Jr(o);O.actionable_unknown_event_count>0&&l.push(`validate_history_unknown_author_events:${O.actionable_unknown_event_count}`)}let h=typeof e.metadataProfile=="string"?"option":"settings",f=fv(typeof e.metadataProfile=="string"?e.metadataProfile:s.validation.metadata_profile),g=$O(f,h,s.validation.metadata_required_fields),y=LO(s),w=hv(e.dependencyCycleSeverity),v=gv(e.parentCycleSeverity),k=wv(e.scanMode),S=vv(o),b=await lL({requestedChecks:d,options:e,global:t,pmRoot:o,workspaceRoot:S,settings:s,items:u,statusRegistry:a,metadataPolicy:g,lifecyclePatternPolicy:y,dependencyCycleSeverity:w,parentCycleSeverity:v,fileScanMode:k,initialWarnings:[...new Set(l)],sourceIncomplete:_}),A=r?await mL(e,b,s,i,t,n):void 0,E=[...new Set(b.warnings)].sort((O,M)=>O.localeCompare(M)),C={ok:!b.checks.some(O=>O.status==="error"),has_warnings:E.length>0,checks:b.checks,warnings:E,...A!==void 0?{fixes:A}:{},generated_at:I(),projection:{mode:"full",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:["diagnostic_rows"]}};return e.counts!==!0?C:{...OO(C),projection:{mode:"counts",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:[]}}}import{execFile as pL}from"node:child_process";import{promisify as _L}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d50f9868-5c11-51dc-967e-61ce41225ef1")}catch{}})();var fL=_L(pL),hL=16,gL=3e4;function yL(e,t,n){if(!(e.keys[t].value_type==="number"?typeof n.value=="number"&&Number.isFinite(n.value):Array.isArray(n.value)&&n.value.every(r=>typeof r=="string")))throw new TypeError(`assurance provider ${e.id} key ${t} returned the wrong value type`);if(!Number.isInteger(n.population_size)||n.population_size<0||!Number.isFinite(n.cost)||n.cost<0)throw new TypeError(`assurance provider ${e.id} returned an invalid population or cost`);return n}function wL(e,t){let n=e.keys[t.key];if(!n)throw new TypeError(`assurance provider ${e.id} does not declare key ${t.key}`);let r=t.parameters??{},i=n.parameters??{};for(let o of Object.entries(i).filter(([,s])=>s.required===!0).map(([s])=>s))if(!Object.hasOwn(r,o))throw new TypeError(`assurance provider ${e.id} key ${t.key} requires parameter ${o}`);for(let[o,s]of Object.entries(r)){let a=i[o];if(!a)throw new TypeError(`assurance provider ${e.id} key ${t.key} does not declare parameter ${o}`);if(s===null||typeof s!==a.type)throw new TypeError(`assurance provider ${e.id} parameter ${o} must be ${a.type}`)}return{...r}}async function vL(e,t,n,r){let i=wL(e,t),o=Promise.resolve().then(()=>e.resolve({provider:e.id,key:t.key,parameters:i,trigger:r,pm_root:n,...Mm(n)}));o.catch(()=>{});let s;try{let a=await Promise.race([o,new Promise((c,d)=>{s=setTimeout(()=>d(new TypeError(`assurance provider ${e.id} timed out`)),e.timeout_ms??gL),s.unref?.()})]);return yL(e,t.key,a)}finally{clearTimeout(s)}}function Bv(e,t,n,r){let i=e;for(let o of t.split(".")){if(typeof i!="object"||i===null||Array.isArray(i))throw new ut(`assurance field ${t} is not present`,{source_kind:n,field:t,...r?{check:r}:{}});i=i[o]}if(typeof i=="number"&&Number.isFinite(i)||Array.isArray(i)&&i.every(o=>typeof o=="string"))return i;throw new ut(`assurance field ${t} must resolve to a finite number or string array`,{source_kind:n,field:t,...r?{check:r}:{}})}function zv(e,t,n,r){let i=e.checks.find(o=>o.name===t);if(!i)throw new ut(`assurance check ${t} is not present`,{source_kind:r,field:n,check:t});return{value:n==="status"||n==="ok"?i.ok?0:1:Bv(i.details,n,r,t),population_size:1,cost:e.checks.length}}async function bL(e,t){if(t?.trim())return t.trim();try{let{stdout:n}=await fL("git",["rev-parse","HEAD^{commit}"],{cwd:e,encoding:"utf8",timeout:5e3,windowsHide:!0});return n.trim()}catch{return"working-copy"}}async function kL(e,t){let n=new Array(t.length),r=0,i=Array.from({length:Math.min(hL,t.length)},async()=>{for(;r<t.length;){let o=r;r+=1;let s=t[o],a=await Jt(Bt(e,s.id),s.id);n[o]=a.map(c=>({op:c.op,author:c.author,agent_harness:c.agent_harness,agent_model:c.agent_model}))}});return await Promise.all(i),n.flat()}async function ci(e,t={}){let n=await x(e),r=P(n),i=W(n.schema),o=(t.strict_read===!0?(await uh(void 0,{status:"all",full:!0,includeBody:!0,noTruncate:!0,strictRead:!0},{path:e})).items:await gt(e,n.item_format,r.type_to_folder,void 0,n.schema)).map(_=>({..._,id:_.id,status:_.status,type:_.type})),s={path:e},a=N(),c=Object.fromEntries((a?.assurance_providers??[]).map(_=>[_.definition.id,{cost_class:_.runtime_definition.cost_class,network:_.runtime_definition.network}])),d=new Map,l,u;return{tree_id:t.resolve_tree===!1?t.tree_id??"working-copy":await bL(e,t.tree_id),items:o,history:t.include_history===!1?[]:await kL(e,o),terminal_statuses:[...i.terminal_statuses],provider_capabilities:{...c,...t.provider_capabilities},external:async _=>{if(_.kind==="graph"){let g=Z({operation:_.operation,parameters:_.parameters??{}}),y=d.get(g);y===void 0&&(y=kh(_.operation,void 0,void 0,{..._.parameters,full:!0},s),d.set(g,y));let w=await y;return{value:Bv(w,_.field,_.kind),population_size:o.length,cost:o.length}}if(_.kind==="validate"){l??=Wv({counts:!0},s);let g=await l;return zv(g,_.check,_.field,_.kind)}if(_.kind==="health"){u??=Rw(s,{checkOnly:!0,full:!0});let g=await u;return zv(g,_.check,_.field,_.kind)}let h=t.providers?.[_.provider];if(h)return h(_);let f=Km(a,_.provider);if(!f)throw new TypeError(`assurance provider ${_.provider} is not registered`);return vL(f.runtime_definition,_,e,t.trigger??"sdk")}}}import{createHash as SL}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c72d246d-a7ff-5c9d-8c36-4ebd45b8a69f")}catch{}})();function Hv(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new TypeError("recurrence coverage request must be an object");let t=e;if(Object.hasOwn(t,"change"))throw new TypeError("recurrence coverage request does not accept change");if(t.uncoveredOnly!==void 0&&typeof t.uncoveredOnly!="boolean")throw new TypeError("recurrence coverage request.uncoveredOnly must be a boolean");let{policy:n,cursor:r,limit:i}=wo({...t,change:{}});return{policy:n,...r===void 0?{}:{cursor:r},...i===void 0?{}:{limit:i},...t.uncoveredOnly===void 0?{}:{uncoveredOnly:t.uncoveredOnly}}}function EL(e,t){if(e===void 0)return 0;let n;try{n=JSON.parse(Buffer.from(e,"base64url").toString("utf8"))}catch{throw new TypeError("recurrence coverage cursor is invalid")}if(typeof n!="object"||n===null||Array.isArray(n))throw new TypeError("recurrence coverage cursor is invalid");let r=n;if(r.fingerprint!==t||typeof r.offset!="number"||!Number.isSafeInteger(r.offset)||r.offset<0)throw new TypeError("recurrence coverage cursor does not match this evidence and filter");return r.offset}function TL(e,t,n,r,i,o){let s=Object.fromEntries(pc.map(h=>[h,0])),a=0,c=0,d=0,l=0,u=[],_=SL("sha256").update(i);for(let h of r){let f=e.membership.get(h),g=n.has(h),y=f.family_ids.length>0;y&&g&&(a+=1),y||(c+=1),g||(d+=1);let w=t.get(h)?.escape_class;w!==void 0&&pc.includes(w)&&(s[w]+=1,l+=1),_.update(Z([h,g,t.get(h)??null,f.id,f.family_ids])),(!o||!y||!g)&&u.push(h)}return{classCounts:s,coveredCount:a,uncoveredCount:c,missingCount:d,classifiedCount:l,selected:u,fingerprint:_.digest("hex")}}function Vv(e,t,n={}){Jf(e);let r=n.limit??25;if(!Number.isSafeInteger(r)||r<1||r>100)throw new TypeError("recurrence coverage limit must be an integer from 1 through 100");let i=new Set,o=new Map;for(let S of t){if(i.has(S.id))throw new TypeError(`Duplicate recurrence item ${S.id}`);i.add(S.id);let b=yo(S);b!==void 0&&o.set(S.id,b)}let s=Bf(e.families,o),a=[...s.membership.keys()].sort(),c=Z({policy:e,uncoveredOnly:n.uncoveredOnly===!0}),{classCounts:d,coveredCount:l,uncoveredCount:u,missingCount:_,classifiedCount:h,selected:f,fingerprint:g}=TL(s,o,i,a,c,n.uncoveredOnly===!0),y=EL(n.cursor,g);if(y>f.length)throw new TypeError("recurrence coverage cursor offset exceeds the selected population");let w=f.slice(y,y+r).map(S=>{let b=s.membership.get(S),A=i.has(S);return{item_id:S,lineage_id:b.id,lineage_item_count:b.item_ids.length,family_ids:b.family_ids,present:A,...A?b.family_ids.length===0?{finding:"unregistered_recurrence_item"}:{}:{finding:"missing_recurrence_item"}}}),v=y+w.length,k=a.length===0?null:d.production_defect/a.length;return{ok:u===0&&_===0,fingerprint:g,items:w,total:f.length,has_more:v<f.length,...v<f.length?{next_cursor:Buffer.from(JSON.stringify({fingerprint:g,offset:v})).toString("base64url")}:{},population:{scope:"all_recorded_recurrence_items",item_count:a.length,lineage_count:s.lineages.length,edge_count:s.edge_count,covered_item_count:l,uncovered_item_count:u,missing_item_count:_,classified_item_count:h,unclassified_item_count:a.length-h,class_counts:d,escape_rate:h===a.length?k:null,escape_rate_lower_bound:k},budget_scope:"registered_families_only",cost:{items_scanned:t.length,edges_scanned:s.edge_count,row_limit:r},row_contract:{row_keys:["items"],jq_selector:".items[]"}}}import{createHash as CL}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c8cf307d-334c-5b70-93c7-991ff702e4ca")}catch{}})();var ol,Yv=["list","show","put","remove","run","verdicts","presets","apply","derive","promote","risk","lineages"],sl=["measurement","assertion","gate"];function AL(e){if(Yv.includes(e))return e;throw Hi({command_path:"assurance",token:e,allowed:Yv,display_name:"assurance action"})}function Zn(e,t,n){throw new p(t,m.USAGE,{code:"missing_required_argument",required:`Provide the missing assurance operand: ${e}.`,examples:[n],recovery:{missing:[e]}})}function xL(e){if(!e)return Zn("kind",`Assurance declaration kind is required. Expected: ${sl.join(", ")}`,"pm assurance list measurement");if(sl.includes(e))return e;throw new p(`Assurance declaration kind is required. Expected: ${sl.join(", ")}`,m.USAGE)}function Jv(e){if(!e)return Zn("preset",`Assurance preset is required. Expected: ${Zr.join(", ")}`,"pm assurance apply software-delivery --owner <pm-item-id>");if(Zr.includes(e))return e;throw new p(`Assurance preset is required. Expected: ${Zr.join(", ")}`,m.USAGE)}function al(e){return e.owner?.trim()?e.owner.trim():Zn("owner","assurance preset and derivation actions require --owner <pm-item-id>","pm assurance apply software-delivery --owner <pm-item-id>")}function RL(e,t){let n=t;if(typeof t=="string")if(!t.trim())n=void 0;else try{n=JSON.parse(t)}catch(r){throw new p("assurance definition must be valid JSON",m.USAGE,{reason:r instanceof Error?r.message:"invalid_json"})}if(typeof n!="object"||n===null||Array.isArray(n))throw new p("assurance put requires a JSON object definition",m.USAGE);return n}async function IL(e){let[t,n,r]=await Promise.all([zr(e,"measurement"),zr(e,"assertion"),zr(e,"gate")]);return{version:1,measurements:t.items,assertions:n.items,gates:r.items}}function Xv(e,t){return t===!0?{id:e.id}:e}async function OL(e,t){let n=t.authorization_decision;if(!n)return[];let r=await ci(e,{include_history:!1,resolve_tree:!1}),i=r.items.find(s=>s.id===n),o=new Set(r.terminal_statuses);if(!i||i.type.toLowerCase()!=="decision"||!o.has(i.status))throw new p(`Assurance authorization ${n} must name a terminal Decision item`,m.USAGE);return[i.id]}async function LL(e,t){let n=gc(e.limit,"assurance verdict limit");if(n!==void 0&&(n<1||n>Kn))throw new p(`assurance verdict limit must be an integer from 1 through ${Kn}`,m.USAGE);let r=await Fg(t,{gate_id:e.id??e.gate,limit:n});return{items:r,count:r.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function Qv(e,t,n){try{return await Pc(()=>Ng(e,t,n))}catch(r){if(!(r instanceof p)||r.context.reason!=="assurance_evaluation_refused")throw r;let i=["--pm-path",e,"assurance","list",t,"--output-budget","2000","--json"],o=L(i);throw Object.assign(r.context,{changed:!1,value:n,required:`Choose a configured ${t} declaration ID using the bounded discovery command.`,why:`The requested ${t} declaration does not exist. The registry and history were not changed.`,examples:[o],recovery:{next_best_command:o,suggested_retry:o,suggested_retry_args:i}}),r}}async function DL(e,t,n){if(e==="presets"){if(t.preset??t.id)return Yo(Jv(t.preset??t.id),al(t));let i=Zr.map(o=>{let s=Yo(o,"pm-owner");return{id:o,title:s.title,description:s.description}});return{items:i,count:i.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}if(e==="apply")return qn(()=>Py(n,Jv(t.preset??t.id),al(t),{author:t.author,message:t.message}));if(e==="derive"){let i=await Fy(await ci(n,{resolve_tree:!1,trigger:"derive"}),al(t)),o=t.apply?await qn(()=>jy(n,i,{author:t.author,message:t.message??"Accept observation-derived assurance proposals"})):void 0;return{items:i,count:i.length,...o?{applied:o}:{}}}if(!t.id)return Zn("assertion-id","assurance promote requires an assertion id","pm assurance promote <assertion-id> --enforcement warn");if(t.enforcement!=="warn"&&t.enforcement!=="block")throw new p("assurance promote requires --enforcement warn|block",m.USAGE);let r=await Qv(n,"assertion",t.id);return qn(()=>Uy(n,r,t.enforcement,{author:t.author,message:t.message}))}async function $L(e,t,n){if(!e.id)return Zn("gate-id","assurance run requires a gate id","pm assurance run <gate-id> --trigger ci --dry-run");let r=e.id;if(!e.trigger)throw new p("assurance run requires a trigger",m.USAGE);if(!yt.includes(e.trigger))throw new p(`Unknown assurance trigger ${e.trigger}. Expected: ${yt.join(", ")}`,m.USAGE);let i=e.trigger,[o,s]=await Promise.all([IL(t),ci(t,{...n.workspace,tree_id:e.tree,trigger:i})]),a=await Pc(()=>Dg(r,o,s,{trigger:i,dry_run:e.dry_run===!0}));return a.dry_run||await Pg(t,a,{author:e.author,message:e.message}),a}function Zv(e){throw e instanceof p?e:new p(e instanceof Error?e.message:"assurance risk request is invalid",m.USAGE)}function NL(e){if(e.limit!==void 0)throw new p(`assurance ${e.action} does not accept --limit; set limit inside the definition`,m.USAGE);let t=e.definition;if(typeof t=="string")try{t=JSON.parse(t)}catch(n){throw new p(`assurance ${e.action} definition must be valid JSON`,m.USAGE,{reason:n instanceof Error?n.message:"invalid_json"})}try{return e.action==="lineages"?Hv(t):wo(t)}catch(n){if(e.action==="risk"&&n instanceof Yf)throw new p(n.message,m.USAGE,{required:"Supply definition.policy with the project's declared recurrence policy and definition.change with the proposed change; no policy is inferred.",recovery:{suggested_retry:`pm assurance ${e.action} --help`,suggested_retry_args:["assurance",e.action,"--help"]}});return Zv(n)}}function ML(e,t){let n=new Set;for(let[r,i]of t)e.item_fingerprints.get(r)!==i&&n.add(r);for(let r of e.item_fingerprints.keys())t.has(r)||n.add(r);return n}function PL(e,t,n){let r=Z(t.policy),i=ol?.pm_root===e?ol:void 0,o=new Map(n.map(d=>[d.id,CL("sha256").update(Z([zf(d),yo(d)])).digest("hex")])),s=i?.policy_serialized===r?i:void 0,a=s?ML(s,o):new Set,c=Hf(t.policy,s?n.filter(d=>a.has(d.id)):n,s?{previous_index:s.index,changed_item_ids:[...a]}:{});return ol={pm_root:e,policy_serialized:r,item_fingerprints:o,index:c},c}async function FL(e,t){let n=NL(e),r=await ci(t,{strict_read:!0,include_history:!1,resolve_tree:!1});try{return"change"in n?Vf(PL(t,n,r.items),n.change,{cursor:n.cursor,limit:n.limit}):Vv(n.policy,r.items,n)}catch(i){return Zv(i)}}async function jL(e,t={},n={}){let r=AL(e.action),i=R(process.cwd(),t.path);if(r==="presets"||r==="apply"||r==="derive"||r==="promote")return DL(r,e,i);if(r==="verdicts")return LL(e,i);if(r==="run")return $L(e,i,n);if(["risk","lineages"].includes(r))return FL(e,i);let o=xL(e.kind);if(r==="list")return zr(i,o);if(!e.id)return Zn("id",`assurance ${r} requires an id`,`pm assurance ${r} ${o} <id>`);let s=e.id;if(r==="show")return Qv(i,o,s);if(r==="remove"){let l=await qn(()=>Mg(i,o,s,{author:e.author,message:e.message}));return Xv(l,e.idOnly)}let a=RL(o,e.definition);if(a.id!==s)throw new p(`Assurance definition id ${a.id} does not match requested id ${s}`,m.USAGE);let c={author:e.author,message:e.message,...o==="assertion"?{authorized_decision_ids:await OL(i,a)}:{}},d=await qn(()=>Po(i,o,a,c));return Xv(d,e.idOnly)}function lV(e,t,n){let r={...e,...t};return jL({action:te(r,"subcommand")??te(r,"assuranceAction")??te(r,"operation")??"",kind:te(r,"kind"),id:te(r,"id"),definition:r.definition,trigger:te(r,"trigger"),tree:te(r,"treeId")??te(r,"tree"),gate:te(r,"gate"),limit:gc(r.limit,"assurance verdict limit"),dry_run:r.dryRun===!0||r.dry_run===!0,fullChangedFields:r.fullChangedFields===!0,idOnly:r.idOnly===!0,author:te(r,"author"),message:te(r,"message"),preset:te(r,"preset"),owner:te(r,"owner"),apply:r.apply===!0,enforcement:te(r,"enforcement")},n)}import cl from"node:fs/promises";import eb from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ff5e2370-3b70-5f71-9492-72906f642c85")}catch{}})();var UL=1440*60*1e3,GL=new Set(["committed","compensated"]);function qL(e){let t;try{t=JSON.parse(e)}catch{return{status:null,updatedAt:null}}if(typeof t!="object"||t===null||Array.isArray(t))return{status:null,updatedAt:null};let n=t;return{status:n.abandonment!==void 0?"abandoned":typeof n.status=="string"?n.status:null,updatedAt:typeof n.updatedAt=="string"?n.updatedAt:null}}function KL(e,t,n,r,i){let o=n===null?Number.NaN:Date.parse(n);if(t===null||!Number.isFinite(o))return{entry:{file:e,status:t,age_seconds:null,stale:!1,reason:"unparseable"},remove:!1};let s=r-o;return GL.has(t)?s>i?{entry:{file:e,status:t,age_seconds:Math.floor(s/1e3),stale:!0},remove:!0}:{entry:{file:e,status:t,age_seconds:Math.floor(s/1e3),stale:!1,reason:"fresh"},remove:!1}:{entry:{file:e,status:t,age_seconds:Math.floor(s/1e3),stale:!1,reason:"active"},remove:!1}}async function WL(e,t,n,r){let i=r.hooks?.onRead?await r.hooks.onRead(e):[],o=qL(await cl.readFile(e,"utf8")),s=KL(t,o.status,o.updatedAt,r.nowMs,r.retentionMs);return s.entry.reason==="unparseable"&&i.push(`transaction_journal_unparseable:${n}`),s.remove&&!r.dryRun&&(await cl.rm(e,{force:!0}),r.hooks?.onWrite&&i.push(...await r.hooks.onWrite(e))),{decision:s,warnings:i}}async function tb(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),o=Math.max(0,t.retentionDays)*UL,s=eb.join(e,"transactions","sdk"),a={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c;try{c=(await cl.readdir(s)).filter(d=>d.endsWith(".json")).sort((d,l)=>d.localeCompare(l))}catch(d){if(G(d))return a;throw d}for(let d of c){let l=eb.join(s,d),u=`transactions/sdk/${d}`,_=await WL(l,u,d,{dryRun:n,hooks:r,nowMs:i,retentionMs:o});a.warnings.push(..._.warnings),a.scanned+=1;let{decision:h}=_;if(!h.remove){a.retained.push(u),a.entries.push(h.entry);continue}a.removed.push(u),a.entries.push(h.entry)}return a}import er from"node:fs/promises";import ys from"node:path";import gs from"node:fs/promises";import dl from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4fe37a62-2d0f-55f6-bb98-7162e7e8b8fe")}catch{}})();var zL=864e5;function BL(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t.created_at;return typeof n=="string"?n:null}async function HL(e,t){let n;try{n=await gs.readdir(e,{withFileTypes:!0})}catch(i){if(G(i))return[];throw i}let r=[];for(let i of n)if(i.isDirectory()){let o=dl.join(e,i.name),s;try{s=await gs.readdir(o)}catch(a){G(a)||t.push(`checkpoint_subdir_unreadable:${i.name}`);continue}for(let a of s)a.endsWith(".json")&&r.push(`${i.name}/${a}`)}else i.name.endsWith(".json")&&r.push(i.name);return r.sort()}async function nb(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),o=Math.max(0,t.retentionDays)*zL,s=dl.join(e,"checkpoints"),a={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c=await HL(s,a.warnings);for(let d of c){let l=dl.join(s,d),u=`checkpoints/${d}`;a.scanned+=1,r?.onRead&&a.warnings.push(...await r.onRead(l));let _;try{_=await gs.readFile(l,"utf8")}catch(w){if(G(w)){a.scanned-=1;continue}a.warnings.push(`checkpoint_unreadable:${d}`),a.retained.push(u),a.entries.push({file:u,created_at:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let h=BL(_),f=h===null?Number.NaN:Date.parse(h);if(!Number.isFinite(f)){a.warnings.push(`checkpoint_unparseable:${d}`),a.retained.push(u),a.entries.push({file:u,created_at:h,age_seconds:null,stale:!1,reason:"unparseable"});continue}let g=i-f,y={file:u,created_at:h,age_seconds:Math.floor(g/1e3),stale:g>o,reason:g>o?"expired":"active"};if(!y.stale){a.retained.push(u),a.entries.push(y);continue}if(!n){try{await gs.unlink(l)}catch(w){if(!G(w)){a.warnings.push(`checkpoint_remove_failed:${d}`),a.retained.push(u),a.entries.push(y);continue}}r?.onWrite&&a.warnings.push(...await r.onWrite(l))}a.removed.push(u),a.entries.push(y)}return a}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="38736716-2644-5166-bfec-4ed4bca951b9")}catch{}})();var di=["index","embeddings","runtime","locks","checkpoints","transactions"],VL=1440*60*1e3,YL=[{scope:"index",relativePath:"index/manifest.json",kind:"file"},{scope:"embeddings",relativePath:"search/embeddings.jsonl",kind:"file"},{scope:"embeddings",relativePath:"search/vectorization-status.json",kind:"file"},{scope:"embeddings",relativePath:"search/lancedb",kind:"directory"},{scope:"embeddings",relativePath:"search/pending-refresh.json",kind:"file"},{scope:"embeddings",relativePath:"search/pending-refresh.gate.lock",kind:"directory"},{scope:"runtime",relativePath:"runtime/test-runs",kind:"directory"},{scope:"runtime",relativePath:"runtime/history-drift-cache.json",kind:"file"}];async function JL(e,t,n){let r=t.relativePath,i=ys.join(e,r),o=await We({path:i,scope:"project"});try{let s=await er.stat(i);if(t.kind==="file"&&!s.isFile())return{removed:!1,warnings:[...o,`not_a_file:${r}`]};if(t.kind==="directory"&&!s.isDirectory())return{removed:!1,warnings:[...o,`not_a_directory:${r}`]};if(n)return{removed:!0,warnings:o};t.kind==="file"?await er.unlink(i):await er.rm(i,{recursive:!0,force:!0});let a=await ht({path:i,scope:"project",op:"gc:remove"});return{removed:!0,warnings:[...o,...a]}}catch(s){if(G(s))return{removed:!1,warnings:o};throw s}}async function XL(e,t){let n=[{relativePath:"runtime/workspace-snapshots/objects",prefix:".create-"},{relativePath:"runtime/workspace-snapshots/refs",prefix:".ref-"}],r=[],i=[],o=[],s=Date.now()-VL;for(let a of n){let c=ys.join(e,a.relativePath);if(!await ie(c))continue;let d=(await er.readdir(c)).filter(l=>l.startsWith(a.prefix)).sort();for(let l of d){let u=ys.posix.join(a.relativePath,l),_=ys.join(c,l);o.push(...await We({path:_,scope:"project"}));let h=await er.stat(_).catch(f=>{if(!G(f))throw f});if(h){if(h.mtimeMs>s){i.push(u);continue}r.push(u),!t&&(await er.rm(_,{recursive:!0,force:!0}),o.push(...await ht({path:_,scope:"project",op:"gc:workspace_snapshot_temp_remove"})))}}}return{removed:r,retained:i,warnings:o}}function QL(e){if(!e||e.length===0)return[...di];let t=e.flatMap(r=>r.split(",")).map(r=>r.trim().toLowerCase()).filter(r=>r.length>0);if(t.length===0)throw new p(`--scope requires at least one value (${di.join(",")})`,m.USAGE);let n=new Set;for(let r of t){if(!di.includes(r))throw new p(`Invalid --scope value "${r}". Expected one or more of: ${di.join(", ")}`,m.USAGE);n.add(r)}return di.filter(r=>n.has(r))}function ZL(e){let t=[];e.dryRun&&t.push("Dry-run preview only: no cache artifacts were deleted.");let n=e.scopes.includes("index")||e.scopes.includes("embeddings"),r=e.removed.some(i=>i==="index/manifest.json"||i==="search/embeddings.jsonl"||i==="search/vectorization-status.json"||i==="search/lancedb"||i==="search/pending-refresh.json"||i==="search/pending-refresh.gate.lock");return n&&r&&t.push('Search artifacts were removed; the semantic index (including any queued background refresh) is invalidated. Run "pm install search-advanced --project" if reindex is unavailable, then "pm reindex --mode keyword" (and "--mode semantic" when semantic search is enabled) before search-heavy workflows.'),e.removed.includes("runtime/history-drift-cache.json")&&t.push('History drift cache was removed; the next "pm health" run performs a full history-drift re-scan.'),!e.dryRun&&e.removed.some(i=>i.startsWith("checkpoints/"))&&t.push('Aged rollback checkpoints were removed; their "pm update-many"/"pm close-many --rollback" windows are no longer recoverable.'),!e.dryRun&&e.removed.some(i=>i.startsWith("transactions/"))&&t.push("Aged terminal workspace-transaction journals were removed; replaying those transactionIds re-executes their idempotent steps instead of short-circuiting."),t}async function DV(e,t={}){let n=R(process.cwd(),e.path);await j(n);let r=await x(n),i=t.dryRun===!0,o=QL(t.scope),s=YL.filter(f=>o.includes(f.scope)),a=[],c=[],d=[];for(let f of s){let g=await JL(n,f,i);g.removed?a.push(f.relativePath):c.push(f.relativePath),d.push(...g.warnings)}if(o.includes("runtime")){let f=await XL(n,i);a.push(...f.removed),c.push(...f.retained),d.push(...f.warnings)}let l;if(o.includes("locks")){let f=await cw(n,{dryRun:i,hooks:{onRead:g=>We({path:g,scope:"project"}),onWrite:g=>ht({path:g,scope:"project",op:"gc:lock_remove"})}});a.push(...f.removed),c.push(...f.retained),d.push(...f.warnings),l={scanned:f.scanned,removed:f.removed.length,retained:f.retained.length}}let u;if(o.includes("transactions")){let f=r.checkpoints.retention_days,g=await tb(n,{dryRun:i,retentionDays:f,hooks:{onRead:y=>We({path:y,scope:"project"}),onWrite:y=>ht({path:y,scope:"project",op:"gc:transaction_journal_remove"})}});a.push(...g.removed),c.push(...g.retained),d.push(...g.warnings),u={scanned:g.scanned,removed:g.removed.length,retained:g.retained.length,retention_days:f}}let _;if(o.includes("checkpoints")){let f=r.checkpoints.retention_days,g=await nb(n,{dryRun:i,retentionDays:f,hooks:{onRead:y=>We({path:y,scope:"project"}),onWrite:y=>ht({path:y,scope:"project",op:"gc:checkpoint_remove"})}});a.push(...g.removed),c.push(...g.retained),d.push(...g.warnings),_={scanned:g.scanned,removed:g.removed.length,retained:g.retained.length,retention_days:f}}d.push(...await Gm({mode:i?"gc:dry-run":"gc",total_items:s.length}));let h=ZL({dryRun:i,scopes:o,removed:a});return{ok:d.length===0,dry_run:i,scope:o,removed:a,retained:c,warnings:d,...l?{locks:l}:{},..._?{checkpoints:_}:{},...u?{transactions:u}:{},guidance:h,generated_at:I()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1430dcf8-9363-556d-aa33-184cea5421f9")}catch{}})();var PV=Object.freeze({requireCloseReason:!0,orderingEdges:"preserve"});function eD(e){let t=[{source:"explicit",value:e.explicit},{source:"duplicate",value:e.duplicateOf===void 0?void 0:`Duplicate of ${e.duplicateOf}`},{source:"resolution",value:e.resolution},{source:"message",value:e.message}];for(let n of t){let r=n.value?.trim();if(r)return{closeReason:r,source:n.source}}return{source:"none"}}function ws(e,t){return ll(e,t,{operation:"close"})}function ll(e,t,n){let r=eD(e);if(!t||r.closeReason!==void 0)return r;let i=n.operation==="create"?[`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --close-reason "<closing summary>"`,`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --resolution "<resolution summary>"`,"pm create --stdin-json < item.json"]:['pm close <id> "Done: <what changed and why>"','pm close <id> --reason "<closing summary>"','pm close <id> -m "<closing summary>"',"pm close <id> --duplicate-of <canonical-id>"];throw new p("Close reason text is required because governance.require_close_reason is enabled",m.USAGE,{code:"close_reason_required",required:"Provide an author-controlled closing summary as the reason, message, resolution, or duplicate target.",why:"governance.require_close_reason is enabled, so tools must not invent immutable closure evidence.",examples:i,nextSteps:[`Re-run the ${n.operation} operation with a closing summary.`,"To stop requiring reasons, run: pm config set governance-require-close-reason --policy disabled"]})}function rb(e,t){let n=typeof e.blocked_by=="string"?e.blocked_by.trim():"",r=e.blocked_by!==void 0,i=e.dependencies??[],o=i.filter(d=>d.kind==="blocked_by"),s=e.blocked_reason!==void 0,a=[];if(r&&(delete e.blocked_by,a.push("blocked_by")),s&&(delete e.blocked_reason,a.push("blocked_reason")),t.orderingEdges==="remove"&&o.length>0){let d=new Set(o),l=i.filter(u=>!d.has(u));l.length>0?e.dependencies=l:delete e.dependencies,a.push("dependencies")}if(t.orderingEdges==="remove")return{changedFields:a,warnings:[...n?[`closed_cleared_blocked_by:${e.id}:${n}`]:[],...o.length>0?[`closed_removed_predecessors:${e.id}:${o.map(d=>d.id).join(",")}`,`closed_removed_predecessors_count:${e.id}:${o.length}`]:[]]};let c=[...new Set([...n?[n]:[],...o.map(d=>d.id)])];return c.length===0?{changedFields:a,warnings:[]}:{changedFields:a,warnings:[`closed_preserved_predecessors:${e.id}:${c.join(",")}`]}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="94147426-41f3-5f24-b6e2-8653f5dde6d0")}catch{}})();var tD=[{key:"resolution",label:"resolution (--resolution)"},{key:"expected_result",label:"expected_result (--expected-result)"},{key:"actual_result",label:"actual_result (--actual-result)"}];function nD(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0||t==="warn")return"warn";if(t==="off"||t==="none"||t==="disabled")return"off";if(t==="strict")return"strict";throw new p(`Invalid --validate-close mode "${e}" (expected "off", "warn", or "strict")`,m.USAGE)}function ob(e){let t=[];for(let n of tD){let r=e[n.key];(typeof r!="string"||r.trim().length===0)&&t.push(n)}return t}function sb(e,t,n={}){let r=ob(e);if(r.length===0)return;let i={resolution:n.resolution,expected_result:n.expectedResult,actual_result:n.actualResult},o=r.map(a=>`--${a.key.replaceAll("_","-")}`),s=[...t,"update",e.id,...r.flatMap((a,c)=>[o[c],i[a.key]?.trim()||"<value>"])];return{missing:o,suggested_retry:L(s),suggested_retry_args:s}}async function rD(e,t,n){let r=new Set,i=t;for(;typeof i=="string"&&i.trim().length>0;){let o=i.trim();if(o===n)return!0;if(r.has(o))return!1;r.add(o),i=(await e(o))?.duplicate_of}return!1}function iD(e){return typeof e!="string"||e.trim().length===0}async function oD(e,t,n,r){let i=n?.trim();if(!i)return;if(i===r)throw new p("An item cannot be closed as a duplicate of itself.",m.USAGE,{code:"duplicate_target_self",why:"--duplicate-of must identify the canonical item that should remain open or already represent the work."});let o=P(t,N()),s=new Map,a=async d=>{if(s.has(d))return s.get(d)??null;let l=await V(e,d,t.id_prefix,t.item_format,o.type_to_folder);if(!l)return s.set(d,null),null;let{document:u}=await pe(l,{schema:t.schema});return s.set(d,u.metadata),u.metadata},c=await a(i);if(!c)throw new p(`Duplicate target "${i}" was not found. Create or locate the canonical item first.`,m.USAGE,{code:"duplicate_target_missing",why:"Duplicate closure should point at a real canonical pm item so future dedupe and changelog tooling can trace the relationship.",examples:[`pm close ${r} "Duplicate of ${i}" --duplicate-of ${i}`],nextSteps:["Run pm search/list to find the canonical item, then retry with --duplicate-of <id>."]});if(await rD(a,c.duplicate_of,r))throw new p(`Circular duplicate reference detected. Target "${i}" points back to "${r}".`,m.USAGE,{code:"duplicate_target_circular",why:"Circular duplicate relationships create loops for dedupe and status propagation tooling.",nextSteps:["Choose the existing canonical item, or clear the target duplicate_of metadata before closing this item as a duplicate."]});if(typeof c.duplicate_of=="string"&&c.duplicate_of.trim().length>0)throw new p(`Duplicate target "${i}" is already marked as a duplicate of "${c.duplicate_of.trim()}".`,m.USAGE,{code:"duplicate_target_is_duplicate",why:"Duplicate closure should point directly at the canonical item, not another duplicate.",examples:[`pm close ${r} "Duplicate of ${c.duplicate_of.trim()}" --duplicate-of ${c.duplicate_of.trim()}`],nextSteps:["Use the canonical item referenced by duplicate_of as the --duplicate-of target."]});return c.id}function sD(e,t,n){return e.filter(r=>r.parent===t&&!fe(r.status,n)).map(r=>r.id).sort((r,i)=>r.localeCompare(i))}function aD(e,t,n){let r=new Map(e.map(a=>[a.id.trim().toLowerCase(),a])),i=Qp(e),o=t.trim().toLowerCase(),s=n.blocked_statuses;return e.filter(a=>s.has(a.status)).map(a=>({item:a,blockerIds:i.get(a.id.trim().toLowerCase())})).filter(({blockerIds:a})=>a.includes(o)).filter(({blockerIds:a})=>a.every(c=>{if(c===o)return!0;let d=r.get(c);return d!==void 0&&fe(d.status,n)})).map(({item:a,blockerIds:c})=>({id:a.id,blocker_ids:c})).sort((a,c)=>a.id.localeCompare(c.id))}async function cD(e,t,n,r,i,o,s){let a=aD(n,r,o),c=[],d=[],l=[],u=[],_;for(let h of a)try{let f=await he({pmRoot:e,settings:t,id:h.id,op:"update",author:i,message:`Auto-unblocked after blocker ${r} closed`,mutate(g){let y=g.metadata.dependencies??[],w=y.filter(k=>{let S=k.id.trim().toLowerCase();return k.kind!=="blocked_by"||!h.blocker_ids.includes(S)});g.metadata.status=o.open_status,delete g.metadata.blocked_by,delete g.metadata.blocked_reason,g.metadata.unblock_note=`Auto-unblocked after blocker ${r} closed; all blockers resolved (${h.blocker_ids.join(", ")}).`,w.length>0?g.metadata.dependencies=w:delete g.metadata.dependencies;let v=["status","blocked_by","blocked_reason","unblock_note"];return w.length!==y.length&&v.push("dependencies"),{changedFields:v}}});c.push(`auto_unblocked:${f.item.id}:resolved_blockers=${h.blocker_ids.join(",")}`),d.push(f.item.id)}catch(f){let g=f instanceof Error?f.message.replace(/\s+/g," ").trim():"unknown";en(f)?(_??=f,l.push(h.id)):u.push({id:h.id,reason:g}),c.push(`auto_unblock_failed:${h.id}:${g}`)}if(_!==void 0){let h=await n_(_,e),f=[...o.blocked_statuses].sort().join(",");throw mD(h,{closedId:r,unblockedIds:d,conflictIds:l,failed:u,openStatus:o.open_status,blockedStatuses:f,commandScope:s})}return c}var Et=10,ul=20,dD=[{list:"auto_unblock_failed",omitted:"auto_unblock_failed_omitted",floor:0},{list:"changes_since",omitted:"changes_since_omitted",floor:0},{list:"pending_unblock",omitted:"pending_unblock_omitted",floor:1}];function lD(e){for(let t of dD){let n=e[t.list];if(Array.isArray(n))for(;n.length>t.floor&&!Kp(e);)n.pop(),Reflect.set(e,t.omitted,Number(e[t.omitted])+1)}return e}function ib(e){let t=e.length-Et;return`${e.slice(0,Et).join(", ")}${t>0?`, and ${t} more`:""}`}var uD="post_close_auto_unblock_refused";function mD(e,t){let{closedId:n,conflictIds:r,failed:i,commandScope:o}=t,s=String(e.context.item_id),a=f=>L([...o,"update",f,"--status",t.openStatus,"--unset","blocked_by","--unset","blocked_reason","--expect-hash",`${f}=<item_hash>`]),c=i.slice(0,Et).map(f=>({id:f.id,reason:Cm(f.reason,160)})),d=i.length===0?"":` Auto-unblocking also failed for ${ib(i.map(f=>f.id))}; details.auto_unblock_failed gives the reasons it kept (auto_unblock_failed_omitted counts the rest; their get step shows the item). Fix that cause before unblocking it.`,l=L([...o,"list","--status",t.blockedStatuses,"--fields","id,title,blocked_by,dependencies","--limit","200"]),u=[...r.slice(0,Et).flatMap(f=>[L([...o,"get",f,"--json"]),a(f)]),...c.map(f=>L([...o,"get",f.id,"--json"]))],_=r.length>Et||i.length>Et||u.length>ul,h=u.slice(0,_?ul-1:ul);return new p(`${n} was closed, but auto-unblocking ${s} was refused. ${e.message}`,e.exitCode,{...e.context,reason:uD,examples:Rp(s,!1,{scopeArgs:o}).examples,required:`The close of ${n} is complete; do not retry it. Only unblocking ${r.length===1?s:`the guarded dependents it refused (${ib(r)})`} remains: re-read each one (pm get <id> --json reports item_hash), check that every blocker it declares is resolved, then unblock it with ${a(s)}${r.length===1?"":" for each id"}.${d}${_?` This refusal does not list a step for every dependent left blocked; list them with ${l}, and while it reports has_more, continue with --after <next_cursor>.`:""}`,nextSteps:_?[...h,l]:h,details:lD({...structuredClone(e.context.details),pending_unblock:r.slice(0,Et),pending_unblock_omitted:Math.max(0,r.length-Et),auto_unblock_failed:c,auto_unblock_failed_omitted:Math.max(0,i.length-Et)}),side_effects:[{path:`history/${n}.jsonl`,op:"close"},...t.unblockedIds.map(f=>({path:`history/${f}.jsonl`,op:"update"}))]})}async function ZV(e,t,n){if(!en(e)||!e.context.side_effects?.some(i=>`${i.op}:${i.path}`==`close:history/${t}.jsonl`))return;let r=String(e.context.item_id);return{warnings:[...e.context.side_effects.filter(i=>i.op==="update").map(i=>i.path.slice(8,-6)).map(i=>`auto_unblocked:${i}`),`auto_unblock_refused:${r}:item_revision_conflict`],dependent_revision_conflict:{item_id:r,error:Wi(e),...await e_(e,n)}}}function pD(e,t){let n=[],r=[{option:t.resolution,key:"resolution"},{option:t.expectedResult,key:"expected_result"},{option:t.actualResult,key:"actual_result"}];for(let{option:i,key:o}of r){if(typeof i!="string")continue;let s=i.trim();s.length!==0&&(e[o]=s,n.push(o))}return n}function _D(e,t){if(t===void 0)return[];e.duplicate_of=t;let n=[],r=[{key:"resolution",value:`Duplicate of ${t}`},{key:"expected_result",value:`Canonical item ${t} tracks the work.`},{key:"actual_result",value:`Closed as duplicate of ${t}.`}];for(let{key:i,value:o}of r)iD(e[i])&&(e[i]=o,n.push(i));return n}function fD(e,t){let n=[["--resolution",e.resolution],["--expected-result",e.expectedResult],["--actual-result",e.actualResult],["--validate-close",e.validateClose],["--completed-at",e.completedAt],["--message",e.message],["--author",e.author]].flatMap(([r,i])=>t.has(r)||i===void 0||i.trim().length===0?[]:[`${r}=${i}`]);return e.force===!0?[...n,"--force"]:n}function hD(e,t,n){let r=t.map(y=>y.label),i=t.map(y=>`--${y.key.replaceAll("_","-")}`),o=i.flatMap(y=>[y,"<value>"]),s=[...n.commandScope,"update",e.id,...o],a=`Cannot close item ${e.id}: missing ${r.join(", ")}. Populate fields or use --validate-close warn.`,c="Use --validate-close warn only when governance permits an evidenced exception.",d=Object.entries(n.options.lifecyclePolicy??{}).filter(([,y])=>y!==void 0).map(([y])=>y),l=Cr(n.pmRoot),u=typeof n.options.author=="string"&&n.options.author.trim().length===0,_=d.length>0?`its lifecyclePolicy override (${d.join(", ")}) has no CLI spelling`:u?"its explicitly blank author has no CLI spelling (pm close refuses an empty --author)":l===void 0?"its revision guards cannot be replayed as typed (nested revision guards expect different revisions of one item, or a write in the same operation advanced a guarded revision)":void 0;if(_!==void 0)return new p(a,m.USAGE,{code:"close_validation_missing_fields",required:`Pass ${t.map(y=>y.key).join(", ")} on the same SDK close; ${_}, so no CLI retry reproduces it.`,recovery:{missing:i,next_best_command:L(s)},nextSteps:["Retry the same SDK close with the missing evidence supplied, inside the same lifecycle policy and revision guards.",c]});let h=n.closeReason===void 0?[]:[`--reason=${n.closeReason}`],f=l.map(y=>`--expect-hash=${y}`),g=[...n.commandScope,"close",e.id,...h,...fD(n.options,new Set(i)),...f,...o];return new p(a,m.USAGE,{code:"close_validation_missing_fields",required:`Supply ${i.join(", ")}: pm close accepts them and records them in the same write as the closure.`,recovery:{missing:i,suggested_retry:L(g),suggested_retry_args:g,next_best_command:L(s)},nextSteps:["Run recovery.suggested_retry when it is present: the same close with the missing flags added, so one write records the evidence and the closure.","Without it, record the evidence with recovery.next_best_command, then repeat the original close.",c]})}function gD(e,t,n,r){let i=t.map(a=>Xm(a.field).flag),o=[...r.author?.trim()?[`--author=${r.author}`]:[],...r.force===!0?["--force"]:[]],s=[...n,"update",e.id,...o,...i.flatMap(a=>[a,"<value>"])];return new p(`Cannot close item ${e.id}: deferred fields still have no value (${t.map(a=>a.field).join(", ")}). Supply them or use --validate-close warn.`,m.USAGE,{code:"close_validation_deferred_fields",required:`Supply ${i.join(", ")}: each was deferred at create (${t.map(a=>`${a.field}: ${a.reason}`).join("; ")}).`,recovery:{missing:i,next_best_command:L(s)},nextSteps:["Record the now-known values with recovery.next_best_command; the update resolves each deferral, then repeat the close.","Use --validate-close warn only when governance permits closing with deferred values still unknown."]})}function yD(e,t,n){let r=ro(e);if(r.length===0)return[];if(t==="strict")throw gD(e,r,n.commandScope,n.options);return[`close_validation_deferred_fields:${e.id}:${r.map(i=>i.field).join(",")}`]}function wD(e,t,n,r){let i=[];if(t!=="off"){i.push(...yD(e,t,r));let o=ob(e);if(o.length>0){let s=o.map(a=>a.label);if(t==="strict")throw hD(e,o,r);i.push(`close_validation_missing_fields:${e.id}:${s.join(",")}`)}if(n.length>0){if(t==="strict")throw new p(`Cannot close item ${e.id}: active child items remain open (${n.join(", ")}). Close, cancel, or re-parent them first, or use --validate-close warn.`,m.USAGE);i.push(`close_validation_active_children:${e.id}:${n.join(",")}`)}return i}return n.length>0&&i.push(`closed_with_active_children:${e.id}:${n.join(",")}`),i}function vD(e,t){return t!==void 0?(e.close_reason=t,["close_reason"]):[]}function bD(e){let t=["assignee","claim_principal"].filter(n=>e[n]!==void 0);for(let n of t)delete e[n];return[...t]}function kD(e,t){if(fe(e.status,t.statusRegistry)&&!t.force)throw new p(`Item ${e.id} is already terminal; use pm update to append acceptance evidence, or --force only for an intentional repeat closure.`,m.CONFLICT,{recovery:sb(e,t.commandScope,t.options)});let n=pD(e,t.options),r=_D(e,t.duplicateOf),i=wD(e,t.validateCloseMode,t.activeChildIds,t);e.status=t.statusRegistry.close_status,e.closed_at=t.closedAt;let o=t.options.completedAt!==void 0||e.completed_at===void 0;o&&(e.completed_at=t.completedAt);let s=["status","closed_at",...o?["completed_at"]:[],...vD(e,t.closeReason),...n];if(Hp(e)&&(e.plan_mode="completed",s.push("plan_mode")),t.duplicateOf!==void 0){s.push("duplicate_of");for(let c of r)s.includes(c)||s.push(c)}s.push(...bD(e));let a=rb(e,t.lifecyclePolicy);return s.push(...a.changedFields),i.push(...a.warnings),{changedFields:s,...i.length>0?{warnings:i}:{}}}async function SD(e,t,n,r){let i=R(process.cwd(),r.path),o=Ie(r);await j(i);let s=await x(i),a=W(s.schema),c=U(n.author,s.author_default),d=P(s,N()).type_to_folder,l=await V(i,e,s.id_prefix,s.item_format,d);if(!l)throw await Qt(i,e,s.id_prefix,d);let u=await oD(i,s,n.duplicateOf,l.id),_={requireCloseReason:n.lifecyclePolicy?.requireCloseReason??s.governance.require_close_reason,orderingEdges:n.lifecyclePolicy?.orderingEdges??"preserve"},h=ws({explicit:t,duplicateOf:u,resolution:n.resolution,message:n.message},_.requireCloseReason).closeReason,f=nD(n.validateClose)??s.governance.close_validation_default,g=await Te(i,s.item_format,d,void 0,s.schema),y=sD(g,l.id,a),w=I(),v=n.completedAt===void 0?w:me(n.completedAt,new Date(w),"completed-at"),k={timestamp:v,source:n.completedAt===void 0?"close_time":"asserted",...n.completedAt===void 0?{hint:`completed_at defaults to the close time. If work finished earlier, correct it with ${L([...o,"update",l.id,"--completed-at","<ISO>"])}.`}:{}},S=await Rt({pmRoot:i,settings:s,id:l.id,op:"close",author:c,message:n.message,force:n.force,resolveHistoryContext:()=>({completion:{timestamp:k.timestamp,source:k.source}}),mutate(A){return n.completedAt===void 0&&A.metadata.completed_at!==void 0&&(k={timestamp:A.metadata.completed_at,source:"existing"}),kD(A.metadata,{pmRoot:i,commandScope:o,statusRegistry:a,force:n.force,options:n,duplicateOf:u,validateCloseMode:f,activeChildIds:y,closeReason:h,closedAt:w,completedAt:v,lifecyclePolicy:_})}}),b=f==="warn"?sb(S.item,o):void 0;return{item:S.item,changed_fields:S.changedFields,...b?{follow_up:{kind:"complete_close_evidence",missing:b.missing,suggested_command:b.suggested_retry,suggested_command_args:b.suggested_retry_args}}:{},warnings:[...S.warnings,...await cD(i,s,g,l.id,c,a,o)],completion:k}}function vs(e,t,n,r){return SD(e,t,n,r)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="73852fdf-f072-51ab-9449-d7922712eeb4")}catch{}})();function ab(e){return[...e].sort().join("\0")}function ED(e,t,n){let r=e.successors.get(t);r?r.push(n):e.successors.set(t,[n]);let i=e.predecessors.get(n);i?i.push(t):e.predecessors.set(n,[t])}function cb(e,t,n,r,i){let o=t.resolve(i);if(o?.ordering!==!0)return;let s=ch(r),a=s===void 0?void 0:e.canonicalIds.get(s.toLowerCase());if(a===void 0)return;let c=(o.precedence??"source_before_target")==="source_before_target";ED(e,c?n:a,c?a:n)}function TD(e,t){let n={successors:new Map,predecessors:new Map,canonicalIds:new Map},r=e.filter(i=>typeof i?.id=="string"&&i.id.trim().length>0);for(let i of r){let o=i.id.trim();n.canonicalIds.set(o.toLowerCase(),o)}for(let i of r){let o=i.id.trim();cb(n,t,o,i.blocked_by,"blocked_by");for(let s of i.dependencies??[])typeof s!="object"||s===null||cb(n,t,o,s.id,typeof s.kind=="string"?s.kind:"related")}for(let i of[n.successors,n.predecessors])for(let o of i.values())o.sort();return n}function CD(e,t){let n=new Set([t]),r=[t];for(;r.length>0;){let i=r.pop();for(let o of[e.successors,e.predecessors])for(let s of o.get(i)??[])n.has(s)||(n.add(s),r.push(s))}return n}function AD(e,t){let n=new Map;for(let r of t){let i=(e.successors.get(r)??[]).filter(o=>t.has(o));i.length>0&&n.set(r,i)}return n}function db(e,t,n){let r=TD(e,t),i=r.canonicalIds.get(n.trim().toLowerCase());if(i===void 0)return{cycles:[],successors:new Map,canonical:n};let o=AD(r,CD(r,i));return{cycles:vh(o).filter(s=>s.includes(i)),successors:o,canonical:i}}function xD(e,t,n){let r=new Set(t),i=r.has(n)?n:t[0];if(e.get(i)?.includes(i))return[i,i];for(let o of e.get(i)??[]){if(!r.has(o))continue;let s=RD(e,r,i,o);if(s)return s}return[...t,t[0]]}function RD(e,t,n,r){let i=[[r]],o=new Set([n,r]);for(;i.length>0;){let s=i.shift(),a=s.at(-1);for(let c of e.get(a)??[]){if(c===n)return[n,...s,n];!t.has(c)||o.has(c)||(o.add(c),i.push([...s,c]))}}}function bs(e,t,n){let r=de(),i=db(e,r,n),o=db(t,r,n),s=new Set(i.cycles.map(ab)),a=new Set(yc(e,void 0,r).map(c=>`${c.holder_id.toLowerCase()}\0${c.target_id.toLowerCase()}\0${c.dependency_kind}`));return[...yc(t,void 0,r).filter(c=>c.holder_id.toLowerCase()===n.trim().toLowerCase()&&!a.has(`${c.holder_id.toLowerCase()}\0${c.target_id.toLowerCase()}\0${c.dependency_kind}`)).map(c=>`ordering_storage_contradiction_created:${bh(c)}:remove_contradicting_dependency_row:run_pm_graph_audit`),...o.cycles.filter(c=>!s.has(ab(c))).map(c=>`ordering_cycle_created:${xD(o.successors,c,o.canonical).join(" -> ")}:items_will_not_be_ready:run_pm_graph_audit`)]}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5f2ca18e-450d-5b6e-9e07-7bbf080764f9")}catch{}})();function ks(e,t){let n=t.resolve(e);return n?.hierarchy===!0||n?.outgoing==="one"||n?.incoming==="one"}function lb(e,t,n,r,i){let o=JSON.stringify([t,n,r]),s=e.get(o);s===void 0&&(s={kind:t,direction:n,node_id:r,endpoints:new Set},e.set(o,s)),s.endpoints.add(i)}function ub(e,t){let n=new Map;for(let r of e)for(let i of r.dependencies??[]){let o=t.resolve(i.kind);o===void 0||o.hierarchy||(o.outgoing==="one"&&lb(n,o.kind,"outgoing",r.id,i.id),o.incoming==="one"&&lb(n,o.kind,"incoming",i.id,r.id))}return n}function Ss(e,t,n=de()){let r=ub(e,n),i=ub(t,n);for(let o of[...i.keys()].sort()){let s=i.get(o);if(s.endpoints.size<=1)continue;let a=r.get(o);if(![...s.endpoints].every(c=>a?.endpoints.has(c)))throw new p(`Relationship ${s.kind} permits only one ${s.direction} endpoint for ${s.node_id}.`,m.USAGE,{code:"dependency_cardinality_created",field:"dependencies",value:s.kind,relationship_cardinality:{kind:s.kind,direction:s.direction,node_id:s.node_id,endpoint_ids:[...s.endpoints].sort()},required:"The final dependency set must satisfy the active relationship kind's one-edge cardinality.",nextSteps:["Drop extra --dep seeds, or remove conflicting rows with update --dep-remove before adding another edge.","Choose another kind only when its declared semantics match the intended relationship."]})}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="35d8018b-d17b-5d63-9d85-9db0b416326a")}catch{}})();var ID=["setup","test"];function Ce(e){return e.phase==="setup"}function tr(e,t){if(e===void 0)return;let n=typeof e=="string"?e.trim().toLowerCase():e;if(n==="setup")return"setup";if(!(n==="test"||n===""))throw new p(`${t} field "phase" must be one of: ${ID.join(", ")}`,m.USAGE,{code:"invalid_argument_value",required:"Use phase=setup for a step that runs before the linked commands, or omit phase for a regular linked test.",examples:['pm test <id> --add "command=npm run build,phase=setup"']})}function Es(e){return[...e.filter(Ce),...e.filter(t=>!Ce(t))]}function mb(e,t){if(!e.selected.some(o=>!Ce(o)))return e;let n=t.flatMap((o,s)=>Ce(o)?[s+1]:[]);if(n.length===0)return e;let r=e.selected_indexes.filter(o=>!Ce(t[o-1])),i=n.filter(o=>!e.selected_indexes.includes(o));return{...e,selected:[...n,...r].map(o=>t[o-1]),selected_indexes:[...n,...r],selected_count:n.length+r.length,skipped_count:t.length-n.length-r.length,...i.length>0?{setup_indexes:i}:{}}}function pb(e,t,n){if(!Ce(e))return;let r=[...n].filter(i=>i!==t).sort();if(r.length!==0)return{command:e.command,path:e.path,status:"refused",exit_code:null,failure_category:"config_refusal",error:`Setup entry runs in the ${t} workspace, but linked commands it prepares run in ${r.join(", ")}, so its output would not reach them. Set workspace_context_mode on the setup entry and the linked commands to one mode.`}}function li(){let e;return{blocked(t){if(e!==void 0)return{command:t.command,path:t.path,status:"skipped",...Ce(t)?{phase:"setup"}:{},error:`Skipped because setup entry "${e.label}" did not pass (${e.outcome}); no later linked command ran.`}},options(t,n){return!Ce(t)||n===void 0?n:{...n,failOnEmptyTestRun:!1,requireAssertionsForPm:!1}},record(t,n){if(!Ce(t))return n;if(n.status==="passed")return{...n,phase:"setup"};let r=n.status==="refused"||n.failure_category==="trust_refusal"||n.failure_category==="setup_failed"?{...n,phase:"setup"}:{...n,status:"failed",phase:"setup",failure_category:"setup_failed",...n.failure_category===void 0?{}:{setup_failure_cause:n.failure_category}};return e={label:t.command??t.path??"<no command>",outcome:r.failure_category??r.status},r}}}function OD(){return{infra_collision:0,trust_refusal:0,config_refusal:0,assertion_failure:0,empty_run:0,timeout:0,max_buffer:0,spawn_error:0,signal:0,setup_failed:0}}function nr(e){let t=OD();for(let n of e)n.status!=="failed"&&n.status!=="refused"||!n.failure_category||(t[n.failure_category]+=1);return t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ef8e6aec-bd75-5615-bcda-a51d055b65d7")}catch{}})();var un=new Set(["PM_PATH","PM_GLOBAL_PATH","PM_SOURCE_PM_PATH","PM_SOURCE_WORKSPACE_ROOT","PM_BUILD_CONSUMER_LEASE","PM_BUILD_CONSUMER_LEASE_ROOT",Mr,ph,"FORCE_COLOR"]),As=/^[A-Za-z_][A-Za-z0-9_]*$/,ln=["schema","tracker","auto","none"],_b=["source","isolated","snapshot"];function ui(e,t){if(!e)return;let n=e.split(/[;\n]/).map(i=>i.trim()).filter(i=>i.length>0);if(n.length===0)throw new p(`${t} env_set must include at least one KEY=VALUE assignment`,m.USAGE);let r=Object.create(null);for(let i of n){let o=i.indexOf("=");if(o<=0)throw new p(`${t} env_set entries must use KEY=VALUE and be separated by semicolons. Example: env_set=PORT=0;PLAYWRIGHT_BASE_URL=http://127.0.0.1:4173`,m.USAGE);let s=i.slice(0,o).trim(),a=i.slice(o+1);if(!As.test(s))throw new p(`${t} env_set key "${s}" is invalid`,m.USAGE);if(un.has(s.toUpperCase()))throw new p(`${t} env_set key "${s}" is reserved for sandbox safety`,m.USAGE);r[s]=a}return Object.keys(r).length>0?r:void 0}function mi(e,t){if(!e)return;let n=nc(e,{separators:/[;,\n]/});if(n.length===0)throw new p(`${t} env_clear must include at least one environment variable name`,m.USAGE);for(let r of n){if(!As.test(r))throw new p(`${t} env_clear key "${r}" is invalid`,m.USAGE);if(un.has(r.toUpperCase()))throw new p(`${t} env_clear key "${r}" is reserved for sandbox safety`,m.USAGE)}return n}function xs(e,t,n){if(!e)return;let r=e.trim().toLowerCase();if(r==="true"||r==="1"||r==="yes")return!0;if(r==="false"||r==="0"||r==="no")return!1;throw new p(`${t} ${n} must be one of true|false|1|0|yes|no`,m.USAGE)}function Rs(e,t){if(!e)return;let n=e.trim().toLowerCase();if(ln.includes(n))return n;throw new p(`${t} pm_context_mode must be one of: ${ln.join(", ")}`,m.USAGE)}function mn(e,t){if(!e)return;let n=e.trim().toLowerCase();if(_b.includes(n))return n;throw new p(`${t} workspace_context_mode must be one of: ${_b.join(", ")}`,m.USAGE)}function pn(e){if(!e)return;let t=nc(e,{separators:/[;\n]/});return t.length>0?t:void 0}function rr(e,t,n){let r=pn(e);if(!(!r||r.length===0)){for(let i of r)try{new RegExp(i,"m")}catch(o){throw new p(`${t} ${n} includes invalid regex "${i}": ${o instanceof Error?o.message:String(o)}`,m.USAGE)}return r}}function Is(e,t){if(!e)return;let n=we(e,"assert_stdout_min_lines");if(!Number.isInteger(n)||n<0)throw new p(`${t} assert_stdout_min_lines must be an integer >= 0`,m.USAGE);return n}function Os(e,t){if(!e)return;let n=e.split(/[;\n]/).map(i=>i.trim()).filter(i=>i.length>0);if(n.length===0)throw new p(`${t} assert_json_field_equals must include at least one path=value assignment`,m.USAGE);let r=Object.create(null);for(let i of n){let o=i.indexOf("=");if(o<=0)throw new p(`${t} assert_json_field_equals entries must use path=value and be separated by semicolons`,m.USAGE);let s=i.slice(0,o).trim(),a=i.slice(o+1).trim();if(s.length===0||a.length===0)throw new p(`${t} assert_json_field_equals entries must include non-empty path and value`,m.USAGE);r[s]=a}return Object.keys(r).length>0?r:void 0}function Ls(e,t){if(!e)return;let n=e.split(/[;\n]/).map(i=>i.trim()).filter(i=>i.length>0);if(n.length===0)throw new p(`${t} assert_json_field_gte must include at least one path=value assignment`,m.USAGE);let r=Object.create(null);for(let i of n){let o=i.indexOf("=");if(o<=0)throw new p(`${t} assert_json_field_gte entries must use path=value and be separated by semicolons`,m.USAGE);let s=i.slice(0,o).trim(),a=i.slice(o+1).trim();if(s.length===0||a.length===0)throw new p(`${t} assert_json_field_gte entries must include non-empty path and value`,m.USAGE);let c=Number(a);if(!Number.isFinite(c))throw new p(`${t} assert_json_field_gte value for "${s}" must be numeric`,m.USAGE);r[s]=c}return Object.keys(r).length>0?r:void 0}var LD=new Set(ft);function Ds(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function DD(e,t){let n={},r=[];for(let[i,o]of Object.entries(e)){let s=i.toLowerCase();if(!LD.has(s)){r.push(i);continue}if(Object.hasOwn(n,s))throw t(`provides key "${i}" more than once after case normalization`);n[s]=o}if(r.length>0)throw t(`does not recognize key${r.length>1?"s":""} ${r.map(i=>`"${i}"`).join(", ")}. Allowed keys: ${ft.join(", ")}.`);return n}function dn(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r!==void 0){if(typeof r!="string")throw n(`field "${t}" must be a JSON string`);return r}}function Ts(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r===void 0)return;let i=typeof r=="string"?[r]:r;if(!Array.isArray(i)||i.some(s=>typeof s!="string"))throw n(`field "${t}" must be a string or an array of strings`);let o=i.filter(s=>s.length>0);return o.length>0?o:void 0}function fb(e,t,n){let r=Ts(e,t,n);if(r){for(let i of r)try{new RegExp(i,"m")}catch(o){throw n(`field "${t}" includes invalid regex "${i}": ${o instanceof Error?o.message:String(o)}`)}return r}}function Cs(e,t,n){let r=typeof e=="number"?e:typeof e=="string"&&e.trim().length>0?Number(e.trim()):Number.NaN;if(typeof e=="boolean"||!Number.isFinite(r))throw n(`field "${t}" must be a finite number (or numeric string)`);return r}function $D(e,t){let n=e.timeout_seconds,r=e.timeout;if(n===void 0&&r===void 0)return;let i=n===void 0?void 0:Cs(n,"timeout_seconds",t),o=r===void 0?void 0:Cs(r,"timeout",t);if(i!==void 0&&o!==void 0&&i!==o)throw t("timeout and timeout_seconds must match when both are provided");let s=i??o;if(!Number.isInteger(s)||s<=0)throw t("timeout_seconds must be a positive integer");return s}function ND(e,t){let n=dn(e,"scope",t);if(n===void 0)return"project";if(!Ke.includes(n))throw t(`field "scope" must be one of: ${Ke.join(", ")}`);return n}function MD(e,t){if(!Object.hasOwn(e,"env_set"))return;let n=e.env_set;if(n===void 0)return;if(!Ds(n))throw t('field "env_set" must be a JSON object mapping environment names to string values');let r=Object.create(null);for(let[i,o]of Object.entries(n)){if(typeof o!="string")throw t(`field "env_set" value for "${i}" must be a string`);if(!As.test(i))throw t(`field "env_set" key "${i}" is invalid`);if(un.has(i.toUpperCase()))throw t(`field "env_set" key "${i}" is reserved for sandbox safety`);r[i]=o}return Object.keys(r).length>0?r:void 0}function PD(e,t){let n=Ts(e,"env_clear",t);if(n){for(let r of n){if(!As.test(r))throw t(`field "env_clear" key "${r}" is invalid`);if(un.has(r.toUpperCase()))throw t(`field "env_clear" key "${r}" is reserved for sandbox safety`)}return n}}function FD(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r!==void 0){if(typeof r!="boolean")throw n(`field "${t}" must be a JSON boolean (true or false)`);return r}}function jD(e,t){if(!Object.hasOwn(e,"assert_stdout_min_lines"))return;let n=e.assert_stdout_min_lines;if(n===void 0)return;let r=Cs(n,"assert_stdout_min_lines",t);if(!Number.isInteger(r)||r<0)throw t('field "assert_stdout_min_lines" must be an integer >= 0');return r}function UD(e,t){if(!Object.hasOwn(e,"assert_json_field_equals"))return;let n=e.assert_json_field_equals;if(n===void 0)return;if(!Ds(n))throw t('field "assert_json_field_equals" must be a JSON object mapping field paths to expected values');let r=Object.create(null);for(let[i,o]of Object.entries(n)){if(i.trim().length===0)throw t('field "assert_json_field_equals" keys must be non-empty field paths');if(typeof o!="string"&&typeof o!="number"&&typeof o!="boolean")throw t(`field "assert_json_field_equals" value for "${i}" must be a string, number, or boolean`);r[i]=String(o)}return Object.keys(r).length>0?r:void 0}function GD(e,t){if(!Object.hasOwn(e,"assert_json_field_gte"))return;let n=e.assert_json_field_gte;if(n===void 0)return;if(!Ds(n))throw t('field "assert_json_field_gte" must be a JSON object mapping field paths to numeric minimums');let r=Object.create(null);for(let[i,o]of Object.entries(n)){if(i.trim().length===0)throw t('field "assert_json_field_gte" keys must be non-empty field paths');r[i]=Cs(o,`assert_json_field_gte.${i}`,t)}return Object.keys(r).length>0?r:void 0}function qD(e,t,n){let r=_=>new p(`${n} ${t} ${_}`,m.USAGE);if(!Ds(e))throw r(`must be a JSON object with linked-test fields. Allowed keys: ${ft.join(", ")}.`);let i=DD(e,r),o=dn(i,"command",r),s=dn(i,"cmd",r);if(o!==void 0&&s!==void 0&&o!==s)throw r("command and cmd must match when both are provided");let a=o??s;if(a===void 0||a.trim().length===0)throw r('requires a non-empty "command" string');let c=dn(i,"path",r),d=dn(i,"pm_context_mode",r);if(d!==void 0&&!ln.includes(d))throw r(`field "pm_context_mode" must be one of: ${ln.join(", ")}`);let l=mn(dn(i,"workspace_context_mode",r),`${n} ${t}`),u=dn(i,"note",r);return{command:a,path:c!==void 0&&c.length>0?c:void 0,scope:ND(i,r),timeout_seconds:$D(i,r),pm_context_mode:d,workspace_context_mode:l,env_set:MD(i,r),env_clear:PD(i,r),shared_host_safe:FD(i,"shared_host_safe",r),assert_stdout_contains:Ts(i,"assert_stdout_contains",r),assert_stdout_regex:fb(i,"assert_stdout_regex",r),assert_stderr_contains:Ts(i,"assert_stderr_contains",r),assert_stderr_regex:fb(i,"assert_stderr_regex",r),assert_stdout_min_lines:jD(i,r),assert_json_field_equals:UD(i,r),assert_json_field_gte:GD(i,r),note:u!==void 0&&u.trim().length>0?u.trim():void 0,phase:tr(i.phase,`${n} ${t}`)}}function pi(e,t){let n=e.trim();if(n.length===0)throw new p(`${t} requires a JSON object or array of objects describing linked-test entries`,m.USAGE);let r;try{r=JSON.parse(n)}catch(o){throw new p(`${t} value is not valid JSON: ${o instanceof Error?o.message:String(o)}. Provide a JSON object or array of objects, e.g. '{"command":"node scripts/check.js --flag value, with commas","timeout_seconds":120}'.`,m.USAGE)}let i=Array.isArray(r)?r:[r];if(i.length===0)throw new p(`${t} array must include at least one linked-test entry object`,m.USAGE);return i.map((o,s)=>qD(o,i.length>1?`entry ${s+1}`:"entry",t))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a9b9f4df-2129-5230-af20-16bef3754d39")}catch{}})();var KD={comment:"--clear-comments",dep:"--clear-deps",doc:"--clear-docs",event:"--clear-events",file:"--clear-files",learning:"--clear-learnings",note:"--clear-notes",reminder:"--clear-reminders",test:"--clear-tests",typeOption:"--clear-type-options"};function WD(e){return KD[e]}function pl(e){return WD(e)!==void 0}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e58f7cfe-1414-5205-9f1c-b667abf67702")}catch{}})();function _l(){return Ba.map(e=>e.field).join(", ")}var zD=Object.freeze({fields:[],reason:void 0,optionKeys:new Set});function BD(e){return(e??[]).flatMap(t=>t.split(",")).map(t=>t.trim()).filter(t=>t.length>0)}function hb(e,t){let n=kn(t,"defer"),r=kn(t,"defer-reason"),i=BD(e.defer),o=e.deferReason?.trim();if(i.length===0){if(o!==void 0&&o.length>0)throw new p(`${r} needs ${n}: name the fields whose values are not known yet.`,m.USAGE,{code:"create_deferral_fields_required",required:`Pass ${n} with ${r}, or drop ${r}.`,nextSteps:[`Deferrable fields: ${_l()}.`]});return zD}let s=new Map;for(let c of i){let d=Ha(c);if(d===void 0)throw new p(`${n} cannot defer "${c}". Deferrable fields: ${_l()}.`,m.USAGE,{code:"create_deferral_field_unsupported",required:`Defer only ${_l()}; supply every other field, or clear a repeatable option with its --clear-* flag.`});s.set(d.field,d)}if(o===void 0||o.length===0)throw new p(`${n} requires ${r}: record why the deferred values are not known yet.`,m.USAGE,{code:"create_deferral_reason_required",required:`Pass ${r} "<why>", for example the system the record was imported from.`});let a=Ba.filter(c=>s.has(c.field));return{fields:a,reason:o,optionKeys:new Set(a.map(c=>c.option))}}function fl(e,t,n,r,i={}){let o=e.fields.filter(c=>{let d=t[c.option];return typeof d=="string"&&d.trim().length>0||i[c.field]!==void 0||n.has(c.field)});if(o.length===0)return;let s=kn(r,"defer"),a=o.map(c=>c.field).join(", ");throw new p(`Cannot both defer and set ${a}: ${s} records a value as not known yet.`,m.USAGE,{code:"create_deferral_conflict",required:`Drop ${s} for ${a}, or drop the value (or unset) you supplied for it.`})}function gb(e){if(e.fields.length!==0)return Qm(e.fields.map(t=>({field:t.field,reason:e.reason})))}function yb(e,t=[]){let n=(Array.isArray(e)?e:e===void 0?[]:[e]).filter(o=>typeof o=="string").flatMap(o=>o.split(",")).map(o=>Ha(o)).filter(o=>o!==void 0),r=new Set(n.map(o=>o.field)),i=t.filter(o=>o.commands.includes("create")&&r.has(o.metadata_key)).flatMap(o=>Hm(o));return[...n.map(o=>o.option),...i]}function wb(e,t,n,r,i={}){let o=new Set(t.fields.map(l=>l.field)),s=n.filter(l=>l.commands.includes("create")),a=l=>l.required!==!0&&o.has(l.metadata_key),c=new Set(s.filter(a).map(l=>`--${l.cli_flag}`)),d=new Set(s.filter(l=>!a(l)&&Vm(l,r)&&Zi(i,l)===void 0).map(l=>`--${l.cli_flag}`));return e.filter(l=>!c.has(l)||d.has(l))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b653115b-596b-5c07-b1f7-541fa1f04a33")}catch{}})();var HD="hierarchy-integrity";async function $s(e){let t=e.required?await xn(e.pmRoot,HD,e.ttlSeconds,e.author,!1,!1,e.waitMs,{waitPolicy:"progress"}):async()=>{},n=!1;return async()=>{n||(n=!0,await t())}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="01a312de-88fc-514f-b37b-2e717222a8ed")}catch{}})();function Ns(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function Ms(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function Ps(e){let t=e.trim().toLowerCase();if(t==="med")return"medium";if(Xu.includes(t))return t;let n=we(e,"confidence");if(!Number.isInteger(n)||n<0||n>100)throw new p("Confidence must be an integer 0..100 or one of low|med|medium|high",m.USAGE);return n}function Fs(e){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1;throw new p("Regression must be one of true|false|1|0",m.USAGE)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9625fa5b-47ea-52b6-bf65-ac0f32ae616b")}catch{}})();var vb=[["dependencies","dep",["id","kind","created_at","author","source_kind"]],["comments","comment",["text","created_at","author"]],["notes","note",["text","created_at","author"]],["learnings","learning",["text","created_at","author"]],["files","file",["path","scope","note"]],["tests","test",["command","scope","timeout_seconds","phase"]],["docs","doc",["path","scope","note"]],["reminders","reminder",["at","text","created_at"]],["events","event",["start_at","end_at","title","location"]],["type_options","typeOption",["key","value"]]];(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="48513c82-4195-51fc-bd68-480148a54d10")}catch{}})();var VD=["documentAnnotationSnapshot","runtimeFieldCommands","ownershipMetadataBypass","ownershipDependencyBypass"];function js(e){let t=vb.find(([r])=>r===e)?.[1]??e.replaceAll(/_([a-z])/gu,(r,i)=>i.toUpperCase()),n=[["update",mc],["create",uc]].flatMap(([r,i])=>i.flatMap(o=>{if(o.target!==t)return[];let s=o.option.match(/--[a-z][a-z0-9-]*/u)[0];return[{command:r,flag:s}]}));return{recovery:{provided_fields:[e],...n.length>0?{suggested_flags:[...new Set(n.map(r=>r.flag))]}:{}},nextSteps:n.length>0?n.map(({command:r,flag:i})=>`Use the declared core mutation: pm ${r}${r==="update"?" <id>":""} ${i} <value>; inspect its help for other required options.`):[`No dedicated create/update CLI mutation flag is declared for "${e}". Use its owning lifecycle, evidence, or importer API; --field cannot mutate core metadata.`]}}var kb={create:{name:"create",usage:"pm create",sdkScope:"create options"},update:{name:"update",usage:"pm update <id>",sdkScope:"update options"},update_many:{name:"update-many",usage:"pm update-many <selection flags>",sdkScope:"update options of the update-many request"}};function bb(e){return e.flatMap(t=>[t.flag,...t.short===void 0?[]:[t.short],...t.aliases??[]])}function Sb(e){if(e==="update_many"){let i=Sb("update"),o=bb(xr("update-many"));return{options:new Set([...i.options,...o.map(s=>za(s))]),flags:new Set([...i.flags,...o])}}let t=e==="update"?mc:uc,n=bb([...xr(e),...go]),r=[...t.flatMap(i=>[i.target,...i.keys]),...n.map(i=>za(i)),...e==="update"?VD:[]];return{options:new Set(r),flags:new Set(n)}}function YD(e,t){let n=kb[t];return e===void 0?`SDK: every option name for this field is shared with another declared field or an option of pm ${n.name}; no SDK option sets it alone.`:`SDK: pass ${e} in the ${n.sdkScope}.`}function JD(e,t,n,r){return e.definitions.some(i=>i.metadata_key===t.metadata_key&&i.commands.includes(n)&&Zi(r,i)!==void 0)}function Us(e,t,n){let r=kb[t],i=n===void 0?void 0:Object.fromEntries(Object.entries(n).filter(([o])=>o!=="field"));return o=>{let s=Wm(o),a=e.definitions.filter(h=>h.metadata_key===s||h.key===s),c=a.find(h=>h.commands.includes(t))??a[0];if(c===void 0)return;let d=`Inspect the value contract with: pm schema show-field ${c.key}`;if(!c.commands.includes(t))return{recovery:{provided_fields:[o]},nextSteps:[`The project schema declares "${c.key}" for ${c.commands.join(", ")} only; ${r.name} cannot set it.`,d]};if(i!==void 0&&JD(e,c,t,i))return{recovery:{provided_fields:[o]},nextSteps:[`This invocation already sets "${c.key}" through a declared flag or option; drop the --field ${o} assignment so the field receives one value.`,d]};let l=Sb(t),u=Bm(c,e,l,t),_=u===void 0?`Every CLI spelling of "${c.key}" is shared with another declared field or an option of pm ${r.name}; give it a distinct cli_flag in the project schema.`:`Use the declared project-schema flag: ${r.usage} ${Wa(u)} <value>`;return{recovery:{provided_fields:[o],...u===void 0?{}:{suggested_flags:[Wa(u)]}},nextSteps:[_,YD(zm(c,e,l.options,t),t),d]}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="daa816a5-05d4-5e0a-90aa-9d96afdb2117")}catch{}})();var XD=new Set(["event","meeting","reminder","milestone","decision","adr"]);function Eb(e,t,n,r){if(XD.has(t.trim().toLowerCase())||n!==r.open_status)return;let i=Je("in_progress",r);if(!(i===void 0||i===r.open_status))return{command:`pm claim ${e} --start`,to_status:i}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="48975dc8-636f-51a1-858a-f97c7a037688")}catch{}})();function Cb(e,t){let n=e.trim().toLowerCase();if(n==="true"||n==="1"||n==="yes")return!0;if(n==="false"||n==="0"||n==="no")return!1;throw new p(`${t} must be one of true|false|1|0|yes|no`,m.USAGE)}function hl(e){return e?e.split("|").map(t=>t.trim()).filter(t=>t.length>0):[]}function tt(e,t,n,r=n){if(!t.includes(e))throw new p(`Invalid ${n} value "${e}". Allowed: ${t.join(", ")}`,m.USAGE,{field:r,value:e,recovery:{allowed_values:[...t]},required:`${n} must be one of: ${t.join(", ")}.`,nextSteps:[`Choose an allowed ${n} and retry the mutation.`]});return e}var Ab=["recur_freq","recur_interval","recur_count","recur_until","recur_by_weekday","recur_by_month_day","recur_exdates"];function QD(e,t){return t==="defined"?e!==void 0:!!e}function Tb(e,t,n){if(!QD(e,n))return;let r=we(e,`event ${t}`);if(!Number.isInteger(r)||r<1)throw new p(`--event ${t} must be an integer >= 1`,m.USAGE);return r}function ZD(e,t,n){let r=e?me(e,n,"event.recur_until"):void 0;if(r&&r<t)throw new p("--event recur_until must be at or after start",m.USAGE);return r}function e$(e){return Array.from(new Set(hl(e).map(t=>tt(t.toLowerCase(),rm,"event weekday")))).sort((t,n)=>Da(t)-Da(n))}function t$(e){return Array.from(new Set(hl(e).map(t=>{let n=we(t,"event recur_by_month_day");if(!Number.isInteger(n)||n<1||n>31)throw new p("--event recur_by_month_day values must be integers 1..31",m.USAGE);return n}))).sort((t,n)=>t-n)}function n$(e,t){return Array.from(new Set(hl(e).map(n=>me(n,t,"event.recur_exdates")))).sort((n,r)=>n.localeCompare(r))}function xb(e,t,n,r){let i=e.recur_freq?.trim(),o=e.recur_interval?.trim(),s=e.recur_count?.trim(),a=e.recur_until?.trim(),c=e.recur_by_weekday?.trim(),d=e.recur_by_month_day?.trim(),l=e.recur_exdates?.trim();if(![i,o,s,a,c,d,l].some(v=>v!==void 0))return;if(!i)throw new p("--event recurrence fields require recur_freq=<daily|weekly|monthly|yearly>",m.USAGE);let u=tt(i.toLowerCase(),nm,"event recurrence frequency"),_=Tb(o,"recur_interval",r),h=Tb(s,"recur_count",r),f=ZD(a,t,n),g=e$(c),y=t$(d),w=n$(l,n);return{freq:u,interval:_,count:h,until:f,by_weekday:g.length>0?g:void 0,by_month_day:y.length>0?y:void 0,exdates:w.length>0?w:void 0}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="414326ff-8d4d-577d-b724-ab32b3f311ac")}catch{}})();function ir(e,t=de()){let n=t.resolve(e);if(n)return n.kind;let r=new Set(La),i=[...La,...t.list().filter(({kind:o})=>!r.has(o)).flatMap(({kind:o,aliases:s})=>[o,...s])];throw new p(`Invalid dependency kind value "${e}". Allowed: ${i.join(", ")}`,m.USAGE,{field:"kind",value:e,recovery:{allowed_values:i},required:`dependency kind must be one of: ${i.join(", ")}.`,nextSteps:["Choose a registered kind, or install and enable the extension that registers this kind before retrying."]})}function _i(e,t,n="--dep"){if(!t&&/[:,=]/.test(e))throw new p(`Invalid ${n} value "${e}". Use a bare item id or id=<id>,kind=<kind>.`,m.USAGE,{code:"dependency_flag_value_invalid",reason:"malformed_dependency_shorthand",flag:n,value:e,required:"Use a bare item id or an explicit id=<id>,kind=<kind> entry."})}function fi(e,t,n=de()){for(let r of t??[])try{Em(e,r.id,r.kind,n)}catch(i){throw new p(Wi(i),m.USAGE,{code:"dependency_edge_not_allowed",why:`${e} -> ${r.id} (${r.kind}) violates the active relationship-kind policy`})}}async function Rb(e,t){return(await pe(e,{schema:t})).document.metadata.created_at}async function r$(e,t){if(e.createdAt!==void 0)return e.createdAt;let n=await V(t.pmRoot,e.id,t.idPrefix,t.itemFormat,t.typeToFolder);return n===null?void 0:Rb(n,t.schema)}function i$(e){let t=e.registry.require(e.dependency.kind);return new p(`${t.kind} requires source ${e.holder.id} to be created after target ${e.dependency.id}`,m.USAGE,{code:"dependency_temporal_order_invalid",reason:"source_not_after_target",required:`${e.holder.id}.created_at must be later than ${e.dependency.id}.created_at for ${t.kind}.`,why:"Chronological recurrence direction must be validated before the relationship is persisted.",source_id:e.holder.id,source_created_at:e.sourceCreatedAt,target_id:e.dependency.id,target_created_at:e.targetCreatedAt,temporal_order:t.temporalOrder})}async function o$(e){let t=e.dependencies.filter(i=>e.registry.resolve(i.kind)?.temporalOrder==="source_after_target"&&!e.missingTargets.includes(i.id));if(t.length===0||e.holders.length===0)return;let n=new Map(e.resolutions.flatMap(({target:i,located:o})=>o===null?[]:[[i,o]])),r=new Map(await Promise.all([...new Set(t.map(({id:i})=>i))].map(async i=>[i,await Rb(n.get(i),e.context.schema)])));for(let i of e.holders){let o=await r$(i,e.context);if(o!==void 0)for(let s of t){let a=r.get(s.id),c=Date.parse(o),d=Date.parse(a);if(!(Number.isFinite(c)&&Number.isFinite(d)&&c>d))throw i$({holder:i,dependency:s,sourceCreatedAt:o,targetCreatedAt:a,registry:e.registry})}}}async function Gs(e){let t=e.registry??de(),n=(e.dependencies??[]).filter(s=>!Xp(s.source_kind)),r=[...new Set(n.map(s=>s.id))],i=await Promise.all(r.map(async s=>({target:s,located:await V(e.pmRoot,s,e.idPrefix,e.itemFormat,e.typeToFolder)}))),o=i.filter(({located:s})=>s===null).map(({target:s})=>s).sort((s,a)=>s<a?-1:1);if(o.length>0&&e.allowUnresolved!==!0)throw new p(`Dependency target${o.length===1?"":"s"} not found: ${o.join(", ")}`,m.NOT_FOUND,{code:"dependency_target_not_found",reason:"unresolved_local_dependency",required:"Every local dependency target must exist before the edge is committed.",why:"Fail-fast target resolution prevents dangling graph nodes and preserves reliable traversal semantics.",unresolved_targets:o,examples:["--dep id=<existing-item-id>,kind=related","--dep id=<external-id>,kind=related,source_kind=external","--allow-unresolved-deps --dep id=<future-item-id>,kind=related"],nextSteps:[`Create or correct ${o.length===1?"the target":"the targets"}, then retry the mutation.`,"Use source_kind=external for a cross-workspace reference.","Use --allow-unresolved-deps only when the dangling local edge is intentional."],recovery:{recovery_mode:"compact",missing:o,suggested_flags:["--allow-unresolved-deps"],suggested_retry:`pm search "${o[0]}" --limit 10`}});return await o$({dependencies:n,missingTargets:o,resolutions:i,holders:e.holders??[],registry:t,context:e}),o.map(s=>`dependency_target_unresolved:${s}`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3950ef46-cc2b-5b8e-97d6-34c739bd816e")}catch{}})();var Ib="--event end must be strictly after start. Equal start/end timestamps are treated as an instant event (end is dropped); an end earlier than start is rejected. Omit end for an instant event or set end later than start.",s$="--event end and duration are mutually exclusive; provide only one (use duration=<relative> like duration=2h, duration=30min, or duration=PT30M, or set an explicit end).",a$=/^([+-]?)(\d+)(min|mins|minute|minutes)$/i,c$=/^([+-]?)[Pp][Tt](?:(\d+)[Hh])?(?:(\d+)[Mm])?(?:(\d+)[Ss])?$/,Lb=1e3,gl=60*Lb,d$=60*gl;function Ob(e,t){let n=new Date(e);if(!Number.isFinite(n.getTime()))throw new p(`Invalid event.duration value "${t}". Duration is out of supported timestamp range.`,m.USAGE);return n.toISOString()}function l$(e,t){let n=new Date(e),r=t.trim();if(/^[+-]?\d+m$/i.test(r))throw new p(`Event duration "${r}" is ambiguous. Use min for minutes or mo for months (for example 5min or 5mo).`,m.USAGE);let i=r.replace(/^([+-]?\d+)mo$/i,"$1m"),o=a$.exec(r);if(o){let c=o[1]==="-"?-1:1,d=Number.parseInt(o[2],10)*c;return Ob(n.getTime()+d*gl,r)}let s=c$.exec(r);if(s){let[,c,d,l,u]=s;if(d||l||u){let _=c==="-"?-1:1,h=Number.parseInt(d??"0",10),f=Number.parseInt(l??"0",10),g=Number.parseInt(u??"0",10),y=h*d$+f*gl+g*Lb;return Ob(n.getTime()+_*y,r)}}let a=i.startsWith("+")||i.startsWith("-")?i:`+${i}`;return me(a,n,"event.duration")}function Db(e,t,n,r){if(t&&n)throw new p(s$,m.USAGE);if(n){let o=l$(e,n);if(o<e)throw new p(Ib,m.USAGE);return o===e?void 0:o}if(!t)return;let i=me(t,r,"event.end");if(i<e)throw new p(Ib,m.USAGE);if(i!==e)return i}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8288d6e7-a027-5bfa-9b4a-3c8b581f31ce")}catch{}})();var u$=["at","date","text","title"],m$=["start","date","end","duration","title","description","location","timezone","all_day",...Ab],p$=["key","value"];function $b(e,t){return t==="trimmed"?e?.trim():e}function _$(e,t){return t==="defined"?e!==void 0:!!e}function qs(e,t,n){return e.map(r=>{let i=ee(r,"--reminder");ke(i,"--reminder",u$);let o=$b(i.at??i.date,n.valueMode),s=$b(i.text??i.title,n.valueMode);if(!o||!s)throw new p("--reminder requires at=<iso|relative> or date=<iso|relative>, plus text=<value> or title=<value>",m.USAGE);let a=s.trim();if(!a)throw new p("--reminder text must not be empty",m.USAGE);return{at:me(o,t,"reminder.at"),text:a}})}function Ks(e,t,n){return e.map(r=>{let i=ee(r,"--event");ke(i,"--event",m$);let o=(i.start??i.date)?.trim();if(!o)throw new p("--event requires start=<iso|relative> or date=<iso|relative>",m.USAGE);let s=me(o,t,"event.start"),a=i.end?.trim(),c=i.duration?.trim(),d=Db(s,a,c,t),l=i.title,u=i.description,_=i.location,h=i.timezone,f=l?.trim(),g=u?.trim(),y=_?.trim(),w=h?.trim(),v=[["title",l,f],["description",u,g],["location",_,y],["timezone",h,w]];for(let[A,E,C]of v)if(E!==void 0&&!C)throw new p(`--event ${A} must not be empty`,m.USAGE);let k=i.all_day?.trim(),S=xb(i,s,t,n.recurrenceEmptyNumericGuard),b=_$(k,n.allDayEmptyGuard)?Cb(k,"--event all_day"):void 0;return{start_at:s,end_at:d,title:f,description:g,location:y,all_day:b,timezone:w,recurrence:S}})}function Ws(e){let t={};for(let n of e){let r=n.trim();if(r.length===0)throw new p("--type-option values must not be empty",m.USAGE);let i,o;if(r.includes(",")||r.includes(`
|
|
10
|
-
`)||r.startsWith("```")||/^(?:[-*+]\s+)?(?:key|value)\s*[:=]/i.test(r)){let s=ee(r,"--type-option");ke(s,"--type-option",p$),i=s.key?.trim(),o=s.value?.trim()}else{let s=r.indexOf("="),a=r.indexOf(":"),c=s;if(s<=0&&a>0&&(c=a),c<=0||c===r.length-1)throw new p("--type-option requires key=value or key=<name>,value=<value> entries",m.USAGE);i=r.slice(0,c).trim(),o=r.slice(c+1).trim()}if(!i||!o)throw new p("--type-option requires key and value",m.USAGE);t[i]=o}return Object.fromEntries(Object.entries(t).sort((n,r)=>n[0].localeCompare(r[0])))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3ec13188-a9eb-5f37-84b6-6786571a9b13")}catch{}})();var f$=["strict","progressive"],h$=["lightweight"],Fb=new Set(["Reminder","Meeting","Event"]),g$=new Set(["author","created_at","text"]),zs=new Map(th.map(e=>[e.optionKey,e.canonical]));function y$(e,t){let n=ce(e,t);if(!n){let r=t.definitions.map(i=>i.id);throw new p(`Invalid status value "${e}". Allowed: ${r.join(", ")}`,m.USAGE,{code:"invalid_argument_value",field:"status",value:e,allowed:r})}return n}function w$(e,t){let n=e.default_status;if(n!==void 0){let r=ce(n,t);if(r)return r}return t.open_status}function yl(e,t){if(!e||e.trim()===""||e.trim().toLowerCase()==="now")return t;let n=Date.parse(e);if(!Number.isFinite(n))throw new p(`Invalid created_at timestamp "${e}"`,m.USAGE);return new Date(n).toISOString()}var v$=vo();function jb(e){if(at(e))return e;let t={...e,unset:e.unset?[...e.unset]:void 0},n=i=>{let o=t.unset?[...t.unset]:[];o.includes(i)||o.push(i),t.unset=o};Rr(t.template)&&(t.template=void 0);let r=new Set([...zs.keys(),"rank"]);for(let i of r){if(at(e,i))continue;let o=t[i];if(typeof o!="string"||!Rr(o))continue;let s=i==="rank"?"order":zs.get(i)??i;n(s),t[i]=void 0}return dt(e,ko(t,v$))}function Ge(e){if(e!==void 0)return e}var Nb=["id","kind","type","author","created_at","source_kind"],Bs=["path","scope","note"];function b$(e,t,n,r){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Oe(e,"--dep","Use --clear-deps to clear dependencies."),{values:e.map(i=>{let o=i.trim(),s=Hs(o,Nb);_i(o,s);let a=s?ee(i,"--dep"):{id:o,kind:"related"};s&&ke(a,"--dep",Nb);let c=Ge(a.id),d=k$(Ge(a.kind??a.type));if(!c||!d)throw new p("--dep requires id and kind, or a bare item id to create a related dependency",m.USAGE);if(c.trim().toLowerCase()==="undefined")throw new p(`--dep id must not use placeholder token "${c}". Use --clear-deps to clear dependencies.`,m.USAGE);let l=$r(Ge(a.source_kind)),u=qi(a.author,"--dep author");return{id:Nr(c,n,l),kind:ir(d),created_at:yl(a.created_at,t),author:u??r,source_kind:l??"cli:create:dep",author_source:u?"asserted":"detected"}}),explicitEmpty:!1})}function k$(e){return typeof e=="string"?de().resolve(e)?.kind??e.trim():e}function Hs(e,t){return Bu(e,t)?!0:Sn(e)}function fn(e,t,n,r){return!t||t.length===0?{values:void 0,explicitEmpty:!1}:(Oe(t,e,e==="--comment"?"Use --clear-comments to clear comments.":e==="--note"?"Use --clear-notes to clear notes.":"Use --clear-learnings to clear learnings."),{values:t.map(i=>{let o=i.trim(),s=()=>{if(o.length===0)throw new p(`${e} requires text=<value>`,m.USAGE);return{created_at:n,author:r,text:o}},a;try{a=ee(i,e)}catch(d){if(e==="--comment"||e==="--note"||e==="--learning")return s();throw d}if(Object.keys(a).filter(d=>!g$.has(d)).length>0)return{created_at:yl(a.created_at,n),author:qi(a.author,`${e} author`)??r,text:o};let c=a.text??"";if(c==="")throw new p(`${e} requires text=<value>`,m.USAGE);return{created_at:yl(a.created_at,n),author:qi(a.author,`${e} author`)??r,text:c}}),explicitEmpty:!1})}function wl(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Oe(e,"--file","Use --clear-files to clear linked files."),{values:e.map(t=>{let n=t.trim(),r=Hs(n,Bs);pr(n,"--file","file path",r);let i=r?ee(t,"--file"):{path:n};if(r&&ke(i,"--file",Bs),!i.path)throw new p("--file requires path=<value> or a bare file path",m.USAGE);return{path:i.path,scope:tt(i.scope??"project",Ke,"file scope"),note:Ge(i.note)}}),explicitEmpty:!1})}function vl(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Oe(e,"--test","Use --clear-tests to clear linked tests."),{values:e.map(t=>{let n=t.trim(),r=Hs(n,ft);pr(n,"--test","test command",r);let i=r?Ki(ee(t,"--test"),"--test"):{command:n},o=Ge(i.command),s=Ge(i.path);if(!o)throw new p("--test requires command=<value> or a bare command (path=<value> is optional metadata)",m.USAGE);let a=Ge(i.timeout_seconds),c=Ge(i.timeout);if(a&&c&&a!==c)throw new p("--test timeout and timeout_seconds must match when both are provided",m.USAGE);let d=a??c;return{command:o,path:s,scope:tt(i.scope??"project",Ke,"test scope"),timeout_seconds:d?we(d,"timeout_seconds"):void 0,pm_context_mode:Rs(i.pm_context_mode,"--test"),workspace_context_mode:mn(i.workspace_context_mode,"--test"),env_set:ui(i.env_set,"--test"),env_clear:mi(i.env_clear,"--test"),shared_host_safe:xs(i.shared_host_safe,"--test","shared_host_safe"),assert_stdout_contains:pn(i.assert_stdout_contains),assert_stdout_regex:rr(i.assert_stdout_regex,"--test","assert_stdout_regex"),assert_stderr_contains:pn(i.assert_stderr_contains),assert_stderr_regex:rr(i.assert_stderr_regex,"--test","assert_stderr_regex"),assert_stdout_min_lines:Is(i.assert_stdout_min_lines,"--test"),assert_json_field_equals:Os(i.assert_json_field_equals,"--test"),assert_json_field_gte:Ls(i.assert_json_field_gte,"--test"),note:Ge(i.note),phase:tr(i.phase,"--test")}}),explicitEmpty:!1})}function bl(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Oe(e,"--doc","Use --clear-docs to clear linked docs."),{values:e.map(t=>{let n=t.trim(),r=Hs(n,Bs),i=r?ee(t,"--doc"):{path:n};if(r&&ke(i,"--doc",Bs),!i.path)throw new p("--doc requires path=<value> or a bare doc path",m.USAGE);return{path:i.path,scope:tt(i.scope??"project",Ke,"doc scope"),note:Ge(i.note)}}),explicitEmpty:!1})}function S$(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Oe(e,"--reminder","Use --clear-reminders to clear reminders."),{values:qs(e,new Date(t),{valueMode:"raw"}),explicitEmpty:!1})}function E$(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Oe(e,"--event","Use --clear-events to clear linked events."),{values:Ks(e,new Date(t),{allDayEmptyGuard:"defined",recurrenceEmptyNumericGuard:"defined"}),explicitEmpty:!1})}function T$(e,t,n,r=[]){let i=[...Iu.filter(o=>e[o]!==void 0),...r.filter(o=>e[o]!==void 0),...t.length>0?["body"]:[],...n.map(o=>`unset:${o}`)];return Array.from(new Set(i))}function C$(e,t){let n=e??"";if(t.length===0)return n;let r=`explicit_unset=${t.join(",")}`;return n?`${n} | ${r}`:r}function Mb(e,t,n){let r=_r("create",e);if(!r)throw new p(`Unsupported ${n} entry "${e}" for type "${t}"`,m.CONFLICT);return r}function A$(e){return{scalarValues:{title:e.title,description:e.description,type:e.type,status:e.status,priority:e.priority,tags:e.tags,body:e.body,deadline:e.deadline,estimatedMinutes:e.estimatedMinutes,acceptanceCriteria:e.acceptanceCriteria,definitionOfReady:e.definitionOfReady,order:e.order??e.rank,goal:e.goal,objective:e.objective,value:e.value,impact:e.impact,outcome:e.outcome,whyNow:e.whyNow,author:e.author,message:e.message,assignee:e.assignee,parent:e.parent,reviewer:e.reviewer,risk:e.risk,confidence:e.confidence,sprint:e.sprint,release:e.release,blockedBy:e.blockedBy,blockedReason:e.blockedReason,unblockNote:e.unblockNote,reporter:e.reporter,severity:e.severity,environment:e.environment,reproSteps:e.reproSteps,resolution:e.resolution,expectedResult:e.expectedResult,actualResult:e.actualResult,affectedVersion:e.affectedVersion,fixedVersion:e.fixedVersion,component:e.component,regression:e.regression,customerImpact:e.customerImpact},repeatableValues:{dep:e.dep,comment:e.comment,note:e.note,learning:e.learning,file:e.file,test:e.test,doc:e.doc,reminder:e.reminder,event:e.event,typeOption:e.typeOption,field:e.field},addTags:e.addTags}}function Ub(e,t){if(t==="tags")return e.scalarValues.tags!==void 0||Array.isArray(e.addTags)&&e.addTags.length>0;if(Object.prototype.hasOwnProperty.call(e.scalarValues,t))return e.scalarValues[t]!==void 0;if(Object.prototype.hasOwnProperty.call(e.repeatableValues,t)){let n=e.repeatableValues[t];return Array.isArray(n)&&n.length>0}return!1}function x$(e,t){let n=new Set(["title","type"]);if(t!=="strict")return n;for(let r of e.required_create_fields)n.add(Mb(r,e.name,"required_create_fields"));for(let r of e.required_create_repeatables)n.add(Mb(r,e.name,"required_create_repeatables"));return n}function R$(e,t,n,r){for(let i of e)if(!(!Ub(t,i)&&!n.has(i)))throw new p(`Option ${xe("create",i)} is disabled for type "${r}" by command_option_policies`,m.USAGE)}function I$(e,t,n){if(t!=="strict")return;let r=e.filter(o=>n.has(o)&&!pl(o));if(r.length===0)return;let i=[...new Set(r.map(o=>xe("create",o)))].sort((o,s)=>o.localeCompare(s));throw new p(`Strict create mode requires concrete values for ${i.join(", ")}; --unset cannot satisfy a required scalar option (only repeatable options accept an explicit --clear-* empty set)`,m.USAGE)}function O$(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Oe(e,"--type-option","Use --clear-type-options to clear existing type options."),{values:Ws(e),explicitEmpty:!1})}async function L$(e){return await Ni(e,[["body","--body"],["description","--description"]],[["dep","--dep"],["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"],["field","--field"]])}async function D$(e){return Wt(e)?await L$(e):e}function $$(e,t){if(e===void 0)return t;let n=e.trim().toLowerCase();if(n.length===0)return t;if(n==="strict"||n==="progressive")return n;throw new p(`Invalid --create-mode value "${e}". Allowed: ${f$.join(", ")}`,m.USAGE)}function N$(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)throw new p("--schedule-preset must not be empty",m.USAGE);if(t==="lightweight"||t==="lite"||t==="schedule-lite")return"lightweight";throw new p(`Invalid --schedule-preset value "${e}". Allowed: ${h$.join(", ")}`,m.USAGE)}function M$(e,t,n){let r=$$(e,n);if(t===void 0)return r;if(typeof e=="string"&&e.trim().length>0&&r==="strict")throw new p("--schedule-preset lightweight cannot be combined with --create-mode strict. Use --create-mode progressive or omit --create-mode.",m.USAGE);return"progressive"}function P$(e,t,n,r,i,o){let s=e.name,a=A$(t),c=x$(e,n),d=Cn(e,"create",c);if(d.errors.length>0)throw new p(d.errors.join("; "),m.CONFLICT);R$(d.disabled,a,r,s),I$(d.required,n,r);let l=_=>_==="author"&&i!=="unknown"||_==="status"&&e.default_status!==void 0||o.has(_)||r.has(_)&&pl(_)?!0:Ub(a,_),u=d.required.filter(_=>!l(_));return[...new Set(u.map(_=>xe("create",_)))].sort((_,h)=>_.localeCompare(h))}var Gb=/^Missing required type option "([^"]+)" for type "([^"]+)"$/;function F$(e,t){let n=[];for(let r of e){let i=r.match(Gb);i&&i[2]===t&&n.push(i[1])}return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}function j$(e,t){return e.filter(n=>{let r=n.match(Gb);return!r||r[2]!==t})}function U$(e,t,n,r){let i=j$(e,t);if(i.length===0)return;let o=qb(n,[],[],r.open_status);throw new p(i.join("; "),m.USAGE,{code:"invalid_argument_value",required:`Provide valid --type-option key/value pairs for type "${t}".`,examples:[o],nextSteps:[`Run "pm create --help --type ${t}" to review allowed type-option keys and values.`]})}function G$(e,t){let n=e.options.find(r=>r.key===t)?.values[0];return typeof n=="string"&&n.trim().length>0?n:"<value>"}function q$(e,t,n){let r=e.split("/")[0];switch(r){case"--title":return["--title",`"${t} example title"`];case"--description":return["--description",`"${t} example description"`];case"--type":return["--type",t];case"--status":return["--status",n];case"--priority":return["--priority","1"];case"--message":return["--message",`"Create ${t} item"`];case"--comment":return["--comment",'"author=maintainer,created_at=now,text=Implementation context"'];default:return[r,'"<value>"']}}function qb(e,t,n,r){let i=["pm","create","--title",`"${e.name} example title"`,"--description",`"${e.name} example description"`,"--type",e.name],o=["--status","--priority","--message"],s=[...new Set([...o,...t])],a=new Set(["--title","--description","--type"]);for(let c of s){if(a.has(c))continue;let d=Wb[c];i.push(...d?[d]:q$(c,e.name,r)),a.add(c)}for(let c of n){let d=G$(e,c);i.push("--type-option",`${c}=${d}`)}return i.join(" ")}function kl(e,t,n="cli"){let r=e?.trim();if(!r){let i=n==="sdk";throw t==="--title"?e!==void 0?new p(i?"Title cannot be empty or whitespace-only. Retry: pass a non-empty title.":"Title cannot be empty or whitespace-only. Retry: pass a non-empty title with --title.",m.USAGE):new p(i?'Missing required option title. Why required: every item needs a human-readable title for lookup, search, and reporting. Retry: pass title (example: client.create({ type: "Issue", title: "Fix login bug" })).':'Missing required option --title. Why required: every item needs a human-readable title for lookup, search, and reporting. Retry: pass the title as the first positional argument (example: pm create "Fix login bug" --type Issue) or with --title.',m.USAGE):new p(`Missing required option ${i?kn("sdk",t.replace(/^--/u,"")):t}`,m.USAGE)}return r}function K$(e,t,n){let r={};for(let[i,o]of Object.entries(e))r[i]=Array.isArray(o)?[...o]:o;for(let[i,o]of Object.entries(t))o!==void 0&&(r[i]=Array.isArray(o)?[...o]:o);return W$(r,t,n),dt(t,r)}function W$(e,t,n){let r=[...hc(t.unset,n).optionKeys,...yb(t.defer,n?.definitions)].flatMap(i=>i==="order"?[i,"rank"]:i==="tags"?[i,"addTags"]:[i]);for(let i of r)Reflect.get(t,i)===void 0&&Reflect.deleteProperty(e,i)}function z$(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function B$(){let e=N();return e?e.commands.some(t=>t.action==="templates-show"||z$(t.command)==="templates show"):!1}function H$(e,t){if(typeof e!="object"||e===null||!("options"in e))throw new p(`Templates package returned invalid payload for template "${t}". Expected an options object.`,m.GENERIC_FAILURE);let n=e.options;if(typeof n!="object"||n===null||Array.isArray(n))throw new p(`Templates package returned invalid options for template "${t}".`,m.GENERIC_FAILURE);let r={};for(let[i,o]of Object.entries(n)){if(typeof o=="string"||typeof o=="number"||typeof o=="boolean"){r[i]=o;continue}if(Array.isArray(o)&&o.every(s=>typeof s=="string")){r[i]=[...o];continue}throw new p(`Templates package returned unsupported option value for "${i}" in template "${t}".`,m.GENERIC_FAILURE)}return r}async function V$(e,t,n){if(!B$())throw new p("--template requires the templates package. Install it first (for example: pm install templates --project).",m.USAGE);let r=await qm({command:"templates show",args:[e],options:{},global:t,pm_root:n});if(!r.handled)throw Object.hasOwn(r,"cause")?zp("templates show",r):new p(`Unable to resolve template "${e}" via templates package. Run "pm templates show ${e}" for details.`,m.USAGE);return H$(r.result,e)}function Y(e,t,n){return e.has(t)||n===void 0?void 0:Ge(n)}function _n(e,t,n,r){return e.has(t)||n===void 0?void 0:r(n)}var Y$=new Set(["milestone","meeting","reminder","event"]);function Kb(e,t,n,r){let i=t!==void 0,o=n!==void 0&&n.length>0,s=r!==void 0&&r.length>0;return Y$.has(e.toLowerCase())&&!i&&!o&&!s}function J$(e,t,n,r,i){let o=[];return e.toLowerCase()==="event"&&(i===void 0||i.length===0)&&o.push(`event_without_schedule:${t}:no_time_set`),Kb(e,n,r,i)&&o.push(`calendar_item_without_schedule:${t}:no_deadline_or_reminder_or_event (hint: set --deadline <ISO> or --reminder "<when>", or link an Event via --event "start=<ISO>,end=<ISO>"; otherwise this item never appears on pm calendar)`),o}async function X$(e,t,n,r){if(t.inheritFocus!==!0||e!==void 0||n.has("parent")||t.parent!==void 0)return{parent:e,parentSource:void 0};let i=await $m(r);return i===void 0?{parent:e,parentSource:void 0}:{parent:i,parentSource:"focus"}}async function Q$(e,t,n,r,i,o,s){let a=Dn(so(i,s),t.id_prefix);if(ho(a))return{parent:a,warnings:[]};if(co(r,a,t.id_prefix,s),await V(e,a,t.id_prefix,t.item_format,n.type_to_folder))return{parent:a,warnings:[]};let c=Xe(a,t.id_prefix);return{parent:a,warnings:ao(c,o,s).warnings}}async function Z$(e){return e.parent===void 0?{parent:void 0,warnings:[]}:await Q$(e.pmRoot,e.settings,e.typeRegistry,e.itemId,e.parent,e.policy,e.audience)}async function eN(e){if(e.explicitId===void 0)return gp(e.pmRoot,e.settings.id_prefix,{tokenLength:e.settings.ids.token_length,typeToFolder:e.typeRegistry.type_to_folder,probeExisting:!1});Or(e.explicitId,"create","id");let t=e.explicitId.trim();if(t.length===0||yp(t))throw new p("--id must not be empty or use a placeholder token",m.USAGE);let n=Xe(t,e.settings.id_prefix);if(!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(n))throw new p("--id must contain only letters, numbers, and dashes after normalization",m.USAGE);return n}function Pb(e,t,n,r,i,o){let s=Y(e,t,n);if(s===void 0)return{value:void 0,warnings:[]};let a=uo(r,s,i,o);return{value:a.value,warnings:a.warnings}}async function tN(e){let{pmRoot:t,settings:n,typeRegistry:r,statusRegistry:i,blockedBy:o,status:s,statusExplicit:a,nowValue:c,author:d}=e,l=e.dependencyValues;if(o===void 0)return{dependencyValues:l,status:s};let u=Xe(o,n.id_prefix),_=await V(t,u,n.id_prefix,n.item_format,r.type_to_folder);if(!_)return{dependencyValues:l,status:s};if((l??[]).some(f=>f.id===_.id&&f.kind==="blocked_by")||(l=[...l??[],{id:_.id,kind:"blocked_by",created_at:c,author:d,source_kind:"cli:create:blocked_by",author_source:"detected"}]),a)return{dependencyValues:l,status:s};let h=i.blocked_statuses.has("blocked")?"blocked":[...i.blocked_statuses].sort((f,g)=>f.localeCompare(g))[0]??i.open_status;return{dependencyValues:l,status:h}}function nN(e,t,n){if(typeof e.createMode=="string"&&e.createMode.trim().toLowerCase()==="strict")return;let r=t.governance.create_default_type?.trim();if(r&&r.length>0&&_t(r,n)){e.type=r;return}_t("Task",n)&&(e.type="Task")}function rN(e,t){return e.options.filter(n=>_r("create",n.key)===void 0).flatMap(n=>{let r=t[n.key];if(r===void 0)return[];if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")return[n];throw new p(`Template custom type option "${n.key}" must be a string, number, or boolean value`,m.USAGE)})}async function iN(e,t,n,r,i){let o=e,s=[];if(o.template!==void 0){let f=o.template.trim();if(f.length===0)throw new p("--template must not be empty. Omit --template to disable template usage.",m.USAGE);let g=await V$(f,t,n);o=jb(Lr("create",K$(g,o,Vt(r.schema))))}if(o.type===void 0&&nN(o,r,i),o.type===void 0)throw new p("Missing required option --type <value>",m.USAGE);let a=_t(o.type,i);if(!a){let f=wp(o.type),g=f?_t(f,i):void 0;if(g)s.push(`type_coercion:${o.type.trim()}:${g}`),o.type=g,a=g;else throw new p(mo(o.type,i.types,Qi(n,r.schema)),m.USAGE)}let c=ji(a,i);if(!c)throw new p(`Invalid type value "${o.type}"`,m.USAGE);let d=c.name,l=rN(c,o),u=l.map(f=>`${f.key}=${String(o[f.key])}`);if(u.length>0){o.typeOption=[...u,...o.typeOption??[]];for(let f of l)delete o[f.key]}let _=N$(o.schedulePreset);if(_!==void 0&&!Fb.has(d))throw new p(`--schedule-preset ${_} is only supported for Reminder, Meeting, or Event types`,m.USAGE);let h=M$(o.createMode,_,r.governance.create_mode_default);return{resolvedOptions:o,typeDefinition:c,type:d,schedulePreset:_,createMode:h,warnings:s}}function oN(e,t){let n=new Set(t.metadataKeys),r=new Set(t.optionKeys),i=[{enabled:e.clearDeps,optionKey:"dep",clearFlag:"--clear-deps",valueFlag:"--dep",values:e.dep,metadataKey:"dependencies"},{enabled:e.clearComments,optionKey:"comment",clearFlag:"--clear-comments",valueFlag:"--comment",values:e.comment,metadataKey:"comments"},{enabled:e.clearNotes,optionKey:"note",clearFlag:"--clear-notes",valueFlag:"--note",values:e.note,metadataKey:"notes"},{enabled:e.clearLearnings,optionKey:"learning",clearFlag:"--clear-learnings",valueFlag:"--learning",values:e.learning,metadataKey:"learnings"},{enabled:e.clearFiles,optionKey:"file",clearFlag:"--clear-files",valueFlag:"--file",values:e.file,metadataKey:"files"},{enabled:e.clearTests,optionKey:"test",clearFlag:"--clear-tests",valueFlag:"--test",values:e.test,metadataKey:"tests"},{enabled:e.clearDocs,optionKey:"doc",clearFlag:"--clear-docs",valueFlag:"--doc",values:e.doc,metadataKey:"docs"},{enabled:e.clearReminders,optionKey:"reminder",clearFlag:"--clear-reminders",valueFlag:"--reminder",values:e.reminder,metadataKey:"reminders"},{enabled:e.clearEvents,optionKey:"event",clearFlag:"--clear-events",valueFlag:"--event",values:e.event,metadataKey:"events"},{enabled:e.clearTypeOptions,optionKey:"typeOption",clearFlag:"--clear-type-options",valueFlag:"--type-option",values:e.typeOption,metadataKey:"type_options"}];for(let o of i)if(o.enabled){if(o.values&&o.values.length>0)throw new p(`Cannot combine ${o.clearFlag} with ${o.valueFlag}`,m.USAGE);n.add(o.metadataKey),r.add(o.optionKey)}return{explicitUnsets:n,clearOptionKeys:r}}function sN(e,t){let n={tags:e.tags!==void 0,deadline:e.deadline!==void 0,estimatedMinutes:e.estimatedMinutes!==void 0,acceptanceCriteria:e.acceptanceCriteria!==void 0,definitionOfReady:e.definitionOfReady!==void 0,order:e.order!==void 0||e.rank!==void 0,goal:e.goal!==void 0,objective:e.objective!==void 0,value:e.value!==void 0,impact:e.impact!==void 0,outcome:e.outcome!==void 0,whyNow:e.whyNow!==void 0,author:e.author!==void 0,assignee:e.assignee!==void 0,parent:e.parent!==void 0,reviewer:e.reviewer!==void 0,risk:e.risk!==void 0,confidence:e.confidence!==void 0,sprint:e.sprint!==void 0,release:e.release!==void 0,blockedBy:e.blockedBy!==void 0,blockedReason:e.blockedReason!==void 0,unblockNote:e.unblockNote!==void 0,reporter:e.reporter!==void 0,severity:e.severity!==void 0,environment:e.environment!==void 0,reproSteps:e.reproSteps!==void 0,resolution:e.resolution!==void 0,expectedResult:e.expectedResult!==void 0,actualResult:e.actualResult!==void 0,affectedVersion:e.affectedVersion!==void 0,fixedVersion:e.fixedVersion!==void 0,component:e.component!==void 0,regression:e.regression!==void 0,customerImpact:e.customerImpact!==void 0};for(let[r,i]of Object.entries(n)){if(!i||!t.optionKeys.has(r))continue;let o=zs.get(r)??r;throw new p(`Cannot combine --unset ${o} with ${xe("create",r)}`,m.USAGE)}}function aN(e){if(at(e))return;let t=(n,r)=>{if(at(e,r))return;let i=zs.get(r),o=i?`Use --unset ${i} to clear this field.`:void 0;bo(n,xe("create",r),o)};t(e.tags,"tags"),t(e.deadline,"deadline"),t(e.estimatedMinutes,"estimatedMinutes"),t(e.acceptanceCriteria,"acceptanceCriteria"),t(e.definitionOfReady,"definitionOfReady"),t(e.order??e.rank,"order"),t(e.goal,"goal"),t(e.objective,"objective"),t(e.value,"value"),t(e.impact,"impact"),t(e.outcome,"outcome"),t(e.whyNow,"whyNow"),t(e.author,"author"),t(e.assignee,"assignee"),t(e.parent,"parent"),t(e.reviewer,"reviewer"),t(e.risk,"risk"),t(e.confidence,"confidence"),t(e.sprint,"sprint"),t(e.release,"release"),t(e.blockedBy,"blockedBy"),t(e.blockedReason,"blockedReason"),t(e.unblockNote,"unblockNote"),t(e.reporter,"reporter"),t(e.severity,"severity"),t(e.environment,"environment"),t(e.reproSteps,"reproSteps"),t(e.resolution,"resolution"),t(e.expectedResult,"expectedResult"),t(e.actualResult,"actualResult"),t(e.affectedVersion,"affectedVersion"),t(e.fixedVersion,"fixedVersion"),t(e.component,"component"),t(e.regression,"regression"),t(e.customerImpact,"customerImpact")}function cN(e,t,n){for(let r of Object.keys(e))if(n.metadataKeys.has(r))throw new p(`Cannot combine --unset ${r.replaceAll("_","-")} with --field ${r}=...`,m.USAGE);for(let r of Object.keys(t.values??{}))if(n.metadataKeys.has(r))throw new p(`Cannot combine --unset ${r.replaceAll("_","-")} with its value flag`,m.USAGE)}var Wb={"--comment":"--clear-comments","--dep":"--clear-deps","--doc":"--clear-docs","--event":"--clear-events","--file":"--clear-files","--learning":"--clear-learnings","--note":"--clear-notes","--reminder":"--clear-reminders","--test":"--clear-tests","--type-option":"--clear-type-options"};function dN(e){let{combinedMissingFlags:t,typeDefinition:n,missingRequiredCreateFlags:r,missingRequiredTypeOptionKeys:i,openStatus:o,type:s,createMode:a,missingRequiredRuntimeFields:c}=e;if(t.length===0)return;let d=c.map(f=>{let g=f.type==="boolean"?"<true|false>":f.type==="array"?"<json-array>":f.type==="object"?"<json-object>":f.type==="number"?"<number>":f.type==="string_array"||f.repeatable?"<value>":"<string>";return{example:`--${f.cli_flag} ${g}`,description:`--${f.cli_flag} maps to ${f.metadata_key} (${f.type}${f.repeatable?", repeatable":""})`}}),l=[qb(n,r,i,o),...d.map(f=>f.example)].join(" "),u=[`Run "pm create --help --type ${s}" for type-aware required option guidance.`,...t.filter(f=>f==="--title").map(()=>'Title can also be passed as the first positional argument (example: pm create "Your title" --type '+s+").")];a==="strict"&&(u.push('For staged onboarding, retry with "--create-mode progressive".'),Fb.has(s)&&u.push('For minimal scheduling inputs, try "--schedule-preset lightweight".')),d.length>0&&u.push(`Required custom field formats: ${d.map(f=>f.description).join("; ")}.`);let _=[...new Set(t.flatMap(f=>{let g=f.split(" ",1)[0],y=Wb[g];return y?[y]:[]}))];_.length>0&&u.push(`If the truthful value is an empty collection, use ${_.join(", ")} instead of inventing metadata.`);let h=t.length===1?`Missing required option ${t[0]} for type "${s}"`:`Missing required options ${t.join(", ")} for type "${s}"`;throw new p(h,m.USAGE,{code:"missing_required_option",required:`Provide all required create options and type options for type "${s}" in one invocation.`,examples:[..._.map(f=>`pm create --type ${s} ${f} ...`),l],nextSteps:u,recovery:a==="strict"?{recovery_mode:"compact",missing_required_fields:t,suggested_flags:[..._,...t,"--create-mode progressive"]}:void 0})}function lN(e,t){if(e.has("tags")&&Array.isArray(t.addTags)&&t.addTags.length>0)throw new p("Cannot combine --unset tags with --add-tags",m.USAGE);let n=e.has("tags")?[]:t.tags!==void 0?Li(t.tags):[];return $i(n,t.addTags)}function uN(e,t){if(t.order!==void 0&&t.rank!==void 0&&t.order!==t.rank)throw new p("--order and --rank must match when both are provided",m.USAGE);let n=t.order??t.rank,r=_n(e,"order",n,i=>we(i,"order"));if(r!==void 0&&!Number.isInteger(r))throw new p("Order must be an integer",m.USAGE);return r}function mN(e,t,n,r,i,o){if(r.completedAt!==void 0&&e!==t.close_status)throw new p("--completed-at requires a terminal create status.",m.USAGE);let s=e!==t.close_status?void 0:r.completedAt===void 0?o:me(r.completedAt,new Date(o),"completed-at");if(e!==t.close_status)return{closeReason:void 0,completedAt:s,warnings:[]};let a=n.governance.require_close_reason?{explicit:r.closeReason??r.message,resolution:i}:{explicit:r.closeReason};return{closeReason:ll(a,n.governance.require_close_reason,{operation:"create",status:e}).closeReason,completedAt:s,warnings:[]}}async function pN(e){let{pmRoot:t,type:n,id:r,settings:i,typeRegistry:o,author:s,extensionFieldNames:a,afterDocument:c,beforeDocument:d,historyMessage:l,changedFields:u,nowValue:_,similarityCandidate:h,allowDuplicate:f}=e,g=im(t,n,r,i.item_format,o.type_to_folder),y=Bt(t,r),w=de(),v=c.metadata.parent!==void 0||(c.metadata.dependencies??[]).some(A=>ks(A.kind,w)),k=await $s({pmRoot:t,author:s,ttlSeconds:i.locks.ttl_seconds,waitMs:i.locks.wait_ms,required:v}),S=v,b=[];try{let A=await xn(t,r,i.locks.ttl_seconds,s,!1,i.governance.force_required_for_stale_lock,i.locks.wait_ms);try{let E=c.metadata.parent!==void 0||c.metadata.dependencies!==void 0&&c.metadata.dependencies.length>0?await Te(t,i.item_format,o.type_to_folder,void 0,i.schema):void 0,C=await V(t,r,i.id_prefix,i.item_format,o.type_to_folder);if(C)throw new p(`Item "${r}" already exists`,m.CONFLICT,{code:"item_already_exists",id:C.id,path:C.itemPath,required:"Read the existing item before deciding whether to update it or create a different ID.",nextSteps:[`Inspect the existing item with pm get ${C.id}.`]});if(E){Ss(E,[...E,c.metadata],w);let F=W(i.schema);Co(E,[...E,c.metadata],r,ue=>fe(ue,F),w)}let O=await Ap({pmRoot:t,settings:i,operation:"create",author:s,before:null,after:c});await jm({pm_root:t,operation:"create",before:null,after:c,changed_fields:u,author:s,sdk:Np({pmRoot:t,settings:i,typeToFolder:o.type_to_folder})});let M=await Dp(t,s,{required:i.governance.duplicate_detection_mode==="strict"&&f!==!0}),T=[];try{i.governance.duplicate_detection_mode==="strict"&&f!==!0&&await ad(h,{pmRoot:t,mode:"strict",threshold:i.governance.duplicate_detection_threshold,limit:i.governance.duplicate_detection_limit,allowDuplicate:!1}),await je(g,rp(c,{format:i.item_format,schema:i.schema,extensionFieldNames:a}));try{let F=_p({nowIso:_,author:s,op:"create",before:d,after:c,message:l,context:O.decisions.length===0?void 0:{workflow_policies:O.decisions}});await fp(y,F)}catch(F){throw await Ju(g),F}S&&(await k(),S=!1),T=await $p({pmRoot:t,preferredFormat:i.item_format,typeToFolder:o.type_to_folder,schema:i.schema,itemPath:g,document:c})}finally{await M()}b=[...O.warnings,...E?bs(E,[...E,c.metadata],r):[],...T,...await ht({path:g,scope:"project",op:"create",item_id:c.metadata.id,item_type:c.metadata.type,before:d,after:c,changed_fields:u}),...await ht({path:y,scope:"project",op:"create:history",item_id:c.metadata.id,item_type:c.metadata.type,before:d,after:c,changed_fields:u})],Pm({id:c.metadata.id,op:"create",item_type:c.metadata.type,status:c.metadata.status,current:Fm(c.metadata,u),changed_fields:u})}finally{await A()}}finally{S&&await k()}return b}async function F4(e,t){let n=Lr("create",e),r=ct(n),i=jb(await D$(n)),o=R(process.cwd(),t.path);await j(o);let s=await x(o),a=W(s.schema),c=Vt(s.schema),d=P(s,N()),l=await iN(i,t,o,s,d);i=l.resolvedOptions;let{typeDefinition:u,type:_,createMode:h}=l,f=hc(i.unset,c),{explicitUnsets:g,clearOptionKeys:y}=oN(i,f);sN(i,f),aN(i);let w=hb(i,r);fl(w,i,f.metadataKeys,r);let v=U(Ge(i.author),s.author_default),k=P$(u,i,h,y,v,w.optionKeys),S=I(),b=b$(i.dep,S,s.id_prefix,v),A=fn("--comment",i.comment,S,v),E=fn("--note",i.note,S,v),C=fn("--learning",i.learning,S,v),O=wl(i.file),M=vl(i.test);M.values=await Qn(M.values,v,S);let T=bl(i.doc),F=S$(i.reminder,S),ue=E$(i.event,S),Ne=O$(i.typeOption),J=fr(_,Ne.values,d),Me=N(),Pe=At(Me),qe=Ji(i.field,Me,js,Us(c,"create",i)),re=Ym(i,c,_);fl(w,i,f.metadataKeys,r,re.values),re.missing_required_flags=wb(re.missing_required_flags,w,c.definitions,_,i);let be=new Set(re.missing_required_flags),Ee=c.definitions.filter(X=>be.has(`--${X.cli_flag}`));cN(qe,re,f);let nt=F$(J.errors,_),rt=nt.map(X=>`--type-option ${X}=<value>`),it=[...new Set([...k,...rt,...re.missing_required_flags])].sort((X,xa)=>X.localeCompare(xa));dN({combinedMissingFlags:it,typeDefinition:u,missingRequiredCreateFlags:k,missingRequiredTypeOptionKeys:nt,openStatus:a.open_status,type:_,createMode:h,missingRequiredRuntimeFields:Ee}),U$(J.errors,_,u,a);let ye=await eN({pmRoot:o,settings:s,typeRegistry:d,explicitId:i.id}),se=i.status!==void 0?y$(i.status,a):w$(u,a),He=i.priority!==void 0?lo(i.priority):2,$=f.metadataKeys,Ve=lN($,i),Ut=_n($,"deadline",i.deadline,X=>me(X,new Date(S),"deadline")),Ae=_n($,"estimated_minutes",i.estimatedMinutes,X=>Mi(X,"estimated-minutes")),ae=Y($,"acceptance_criteria",i.acceptanceCriteria),Ai=Y($,"definition_of_ready",i.definitionOfReady),ba=uN($,i),xi=Y($,"goal",i.goal),ES=Y($,"objective",i.objective),TS=Y($,"value",i.value),CS=Y($,"impact",i.impact),AS=Y($,"outcome",i.outcome),xS=Y($,"why_now",i.whyNow),RS=Y($,"assignee",i.assignee),IS=$.has("author")?void 0:Ge(i.author)??v,OS=Y($,"parent",i.parent),yu=await X$(OS,i,$,o),ka=yu.parent,LS=yu.parentSource,DS=Y($,"reviewer",i.reviewer),$S=_n($,"risk",i.risk,X=>tt(Ns(X),Pi,"risk")),NS=_n($,"confidence",i.confidence,X=>Ps(X)),MS=i.allowMissingParent===!0&&s.validation.parent_reference==="strict_error"?"warn":s.validation.parent_reference,wu=s.validation.sprint_release_format,Gt=[...l.warnings,...J$(_,ye,Ut,F.values,ue.values)],vu=await Z$({itemId:ye,parent:ka,pmRoot:o,settings:s,typeRegistry:d,policy:MS,audience:r});ka=vu.parent,Gt.push(...vu.warnings);let bu=Pb($,"sprint",i.sprint,"sprint",wu,r),PS=bu.value;Gt.push(...bu.warnings);let ku=Pb($,"release",i.release,"release",wu,r),FS=ku.value;Gt.push(...ku.warnings);let Su=Y($,"blocked_by",i.blockedBy),Eu=await tN({pmRoot:o,settings:s,typeRegistry:d,statusRegistry:a,blockedBy:Su,dependencyValues:b.values,status:se,statusExplicit:i.status!==void 0,nowValue:S,author:v}),Sa=Eu.dependencyValues;fi(ye,Sa),Gt.push(...await Gs({pmRoot:o,dependencies:Sa,idPrefix:s.id_prefix,itemFormat:s.item_format,typeToFolder:d.type_to_folder,allowUnresolved:i.allowUnresolvedDeps,holders:[{id:ye,createdAt:S}],schema:s.schema})),se=Eu.status;let jS=Y($,"blocked_reason",i.blockedReason),US=Y($,"unblock_note",i.unblockNote),GS=Y($,"reporter",i.reporter),qS=_n($,"severity",i.severity,X=>tt(Ms(X),Fi,"severity")),KS=Y($,"environment",i.environment),WS=Y($,"repro_steps",i.reproSteps),Tu=Y($,"resolution",i.resolution),zS=Y($,"expected_result",i.expectedResult),BS=Y($,"actual_result",i.actualResult),HS=Y($,"affected_version",i.affectedVersion),VS=Y($,"fixed_version",i.fixedVersion),YS=Y($,"component",i.component),JS=_n($,"regression",i.regression,X=>Fs(X)),XS=Y($,"customer_impact",i.customerImpact),Ea=kl(i.title,"--title",r),Ta=i.description??"",Ri=i.body??"",Cu=await ad({title:Ea,description:Ta,body:Ri},{pmRoot:o,mode:s.governance.duplicate_detection_mode,threshold:s.governance.duplicate_detection_threshold,limit:s.governance.duplicate_detection_limit,allowDuplicate:i.allowDuplicate});Gt.push(...Sy(Cu));let Ca=mN(se,a,s,i,Tu,S),QS=Ca.closeReason,ZS=se===a.close_status?S:void 0,eE=Ca.completedAt;Gt.push(...Ca.warnings);let bn=np({id:ye,title:Ea,description:Ta,type:_,type_options:J.normalized,status:se,closed_at:ZS,completed_at:eE,close_reason:QS,priority:He,tags:Ve,created_at:S,updated_at:S,deadline:Ut,assignee:RS,author:IS,estimated_minutes:Ae,acceptance_criteria:ae,deferred_fields:gb(w),definition_of_ready:Ai,order:ba,goal:xi,objective:ES,value:TS,impact:CS,outcome:AS,why_now:xS,parent:ka,reviewer:DS,risk:$S,confidence:NS,sprint:PS,release:FS,blocked_by:Su,blocked_reason:jS,unblock_note:US,reporter:GS,severity:qS,environment:KS,repro_steps:WS,resolution:Tu,expected_result:zS,actual_result:BS,affected_version:HS,fixed_version:VS,component:YS,regression:JS,customer_impact:XS,dependencies:Sa,comments:A.values,notes:E.values,learnings:C.values,files:O.values,tests:M.values,docs:T.values,reminders:F.values,events:ue.values,...qe,...re.values});hm(bn);try{Xi(bn,Me)}catch(X){throw new p(X instanceof Error?X.message:"Invalid extension item field values",m.USAGE)}Ip(bn,o);let tE=ip({metadata:bn,body:Ri},{schema:s.schema,extensionFieldNames:Pe}),nE={metadata:{},body:""},Au=[...g].sort((X,xa)=>X.localeCompare(xa)),rE=C$(i.message,Au),xu=T$(bn,Ri,Au,[...Object.keys(qe),...Object.keys(re.values??{})]),iE=await pN({pmRoot:o,type:_,id:ye,settings:s,typeRegistry:d,author:v,extensionFieldNames:Pe,afterDocument:tE,beforeDocument:nE,historyMessage:rE,changedFields:xu,nowValue:S,similarityCandidate:{title:Ea,description:Ta,body:Ri},allowDuplicate:i.allowDuplicate}),Aa=structuredClone(bn);h==="strict"&&g.has("dependencies")&&(Aa.dependencies=[]);let oE=Eb(ye,_,se,a);return Kb(_,Ut,F.values,ue.values)&&pp(`[pm] warning: ${_} '${ye}' has no deadline/reminder/event \u2014 it will not appear on the calendar. Add one via 'pm update ${ye} --deadline <ISO>' or 'pm update ${ye} --event "start=<ISO>,end=<ISO>"'.`),{item:Aa,changed_fields:xu,warnings:[...Ir("create",i,r==="sdk",Aa),...Gt,...iE],...Object.fromEntries([["parent_source",LS],["next_transition",oE],["similarity_advisory",Cu]].filter(X=>X[1]!==void 0))}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f4c54507-c8b1-5f19-b58a-61186c79c8b0")}catch{}})();function hn(e){return e.in_progress_status!==e.open_status&&e.by_id.has(e.in_progress_status)?e.in_progress_status:Je("in_progress",e)??e.open_status}import{AsyncLocalStorage as _N}from"node:async_hooks";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2d3aa974-e49d-50fc-9c29-01c0e694b4c4")}catch{}})();var fN="strict",Ys="start_blocked_by_open_dependency";function zb(e,t,n){if(t===void 0)return!1;let r=Yt(hn(n),n);return Yt(t,n)===r&&Yt(e??"",n)!==r}function Vs(e,t,n){let r=i=>Xe(i.trim(),n).toLowerCase();return r(e)===r(t)}var hN=new Set(["cli:create:blocked_by","cli:update:blocked_by"]);function Sl(e,t,n){if(e.kind!=="blocked_by"||typeof t!="string"||t.trim().length===0)return!1;let r=e.id.trim().toLowerCase();return r===t.trim().toLowerCase()?!0:r===Xe(t.trim(),n).toLowerCase()&&hN.has(e.source_kind?.trim().toLowerCase()??"")}function gN(e,t,n){let r=e.dependencies??[],i=r.filter(o=>o.kind==="blocked_by");if(r.some(o=>o.kind!=="blocked_by"&&wr(o.kind)==="blocked_by"&&Vs(o.id,t,n)))return L(["get",e.id,"--fields","blocked_by,dependencies"]);if(!(typeof e.blocked_by=="string"&&Vs(e.blocked_by,t,n))){let o=i.filter(s=>Vs(s.id,t,n));return o.length===1&&o.every(s=>s.id===Dn(s.id,n,void 0))?L(["update",e.id,"--dep-remove",`id=${o[0].id},kind=blocked_by`]):L(["get",e.id,"--fields","blocked_by,dependencies"])}return i.filter(o=>Vs(o.id,t,n)).every(o=>Sl(o,e.blocked_by,n))?L(["update",e.id,"--unset","blocked_by"]):L(["get",e.id,"--fields","blocked_by,dependencies"])}var yN=new Set(["item_document_invalid","item_document_encoding_invalid","item_format_version_unsupported","item_identity_ambiguous","item_identity_conflict"]);async function wN(e,t){try{return(await Zp(e)).filter(n=>!n.resolved)}catch(n){let r=Wp(n)?n.context.code:void 0;if(!t||typeof r!="string"||!yN.has(r))throw n;return r}}async function Bb(e){let t=e.settings.governance.start_blocker_enforcement??fN;if(t==="off")return[];let n=P(e.settings,N()).type_to_folder,r=e.metadata.id,i=await wN({pmRoot:e.pmRoot,settings:e.settings,typeToFolder:n,metadata:e.metadata},t==="warn"||e.force===!0);if(typeof i=="string")return[`start_blocker_unverifiable:${r}:${i}`];if(i.length===0)return[];let o=i.map(s=>s.id).join(",");if(t==="warn")return[`start_with_open_blockers:${r}:${o}`];if(e.force===!0)return[`start_blocker_override:${r}:${o}`];throw new p(`Cannot start ${r}: ${i.length===1?"its blocker":`${i.length} of its blockers`} ${o} ${i.length===1?"is":"are"} still open.`,m.CONFLICT,{code:"start_blocked_by_open_dependency",item_id:r,required:`Finish or close the open blocker${i.length===1?"":"s"} first, remove the blocked_by edge if it no longer applies, or start anyway with --force.`,why:"Starting work that a declared blocker still gates would leave an in-progress item that validate reports as non_blocked_status_has_blocked_by. governance.start_blocker_enforcement (strict by default) governs this check.",nextSteps:[...i.filter(s=>s.external!==!0).slice(0,3).map(s=>L(["get",s.id])),gN(e.metadata,i[0].id,e.settings.id_prefix),"pm next"],details:{enforcement:t,open_blockers:i.map(s=>({id:s.id,title:s.title,status:s.status,external:s.external===!0}))}})}async function Js(e){if(e.requested===!1||!zb(e.fromStatus,e.metadata.status,e.registry))return[];let t=await Bb(e),n=El.getStore()?.warnings??new Set;return t.filter(r=>!n.has(r))}var El=new _N;function Hb(e){return El.run({warnings:new Set},e)}async function Vb(e){let t=El.getStore();if(t===void 0)return[];let n=zb(e.metadata.status,hn(e.registry),e.registry)?await Bb(e):[];for(let r of n)t.warnings.add(r);return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d510588a-e45d-54ba-b9c0-153940bb6677")}catch{}})();var Yb="terminal_state_unchanged";function Jb(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function vN(e,t){return ce(e,t)===t.close_status}function bN(e){let t=n=>eh.includes(n.trim().toLowerCase());return nh(e.unset??[],t).some(t)}function Xb(e){!e.settings.governance.require_close_reason||!bN(e.options)||ws({explicit:e.options.closeReason},!0)}function Tl(e,t,n,r=!1){if(!vN(e.status,n))return!1;let i=Jb(t.closeReason);return r&&t.closeReason!==void 0&&i===void 0||i!==void 0&&i!==Jb(e.close_reason)?!1:t.completedAt===void 0||me(t.completedAt,new Date,"completed-at")===e.completed_at}async function Qb(e){let t=await V(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await Qt(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await pe(t,{schema:e.settings.schema});return n.metadata}async function Zb(e,t,n,r,i){if(n.length===0)return{item:t,changed_fields:[],warnings:[...e.workflowTransitionWarnings,Yb]};let o=dt(e.options,{...e.options,status:void 0,closeReason:void 0,completedAt:void 0}),s=await r(e.id,o,e.global);return Tl(s.item,e.options,e.statusRegistry,e.settings.governance.require_close_reason)?{item:s.item,changed_fields:s.changed_fields,warnings:[...e.workflowTransitionWarnings,...s.warnings,Yb]}:i(s)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4790c318-c305-53d4-895c-e9ac90665376")}catch{}})();function or(e){if(e.enforcement==="off"||e.typeWorkflows.length===0)return;let t=vp({typeName:e.typeName,fromStatus:e.fromStatus,toStatus:e.toStatus,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry});if(!t.hasRule||t.allowed)return;let n=Je(e.fromStatus,e.statusRegistry)??e.fromStatus,r=Je(e.toStatus,e.statusRegistry)??e.toStatus,i=`Disallowed transition for type "${e.typeName}": ${n} -> ${r}. Allowed transitions: ${bp(t.allowedTransitions)}.`;if(e.enforcement==="strict")throw new p(i,m.USAGE);return`workflow_transition_not_allowed: ${i}`}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f5a434fe-8703-515c-b823-c8cd3589bbb0")}catch{}})();function Xs(e){let t=e.source_kind?.trim().toLowerCase()??"",n=e.author?.trim().toLowerCase()??"",r=e.created_at?.trim()??"",i=Date.parse(r),o=Number.isFinite(i)?new Date(i).toISOString():r;return[e.id.trim().toLowerCase(),e.kind,t,n,o].join("\0")}function Cl(e,t){return!(t.id!==void 0&&e.id.trim().toLowerCase()!==t.id.trim().toLowerCase()||t.kind&&e.kind!==t.kind||t.source_kind!==void 0&&e.source_kind?.trim().toLowerCase()!==t.source_kind.trim().toLowerCase()||t.author!==void 0&&e.author?.trim().toLowerCase()!==t.author.trim().toLowerCase()||t.created_at!==void 0&&(e.created_at===void 0||!Number.isFinite(Date.parse(e.created_at))||new Date(Date.parse(e.created_at)).toISOString()!==t.created_at))}function ek(e,t,n){let r=t.filter(i=>!e.some(o=>Cl(o,i)));if(r.length!==0)throw new p(`Dependency removal did not match ${r.length===1?"a stored edge":"stored edges"}.`,m.NOT_FOUND,{code:"dependency_remove_no_match",reason:"selector_not_found",unmatched_selectors:r.map(i=>({...i,id:i.id??"*"})),available_dependencies:e.map(i=>({id:i.id,kind:i.kind,source_kind:i.source_kind,author:i.author,created_at:i.created_at})),why:"Failing on a zero-match selector prevents a mistyped dependency removal from being reported as successful.",nextSteps:[`Inspect the current item with: pm get ${n} --full`,"Retry --dep-remove with the exact id plus any kind, source_kind, author, or created_at selectors needed to identify one stored row."]})}function tk(e,t){if(!Array.isArray(e)||e.length===0)return;let n=o=>(Array.isArray(o)?o:[]).filter(s=>typeof s=="object"&&s!==null&&typeof s.id=="string"),r=new Map;for(let o of n(t)){let s=Xs(o);r.set(s,(r.get(s)??0)+1)}let i=[];for(let o of n(e)){let s=Xs(o),a=r.get(s)??0;a>0?r.set(s,a-1):i.push(`${o.id}/${o.kind}`)}return i.length>0?i.join(","):void 0}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fc1c1ca1-43e9-5019-bb3b-85b8972f090b")}catch{}})();var kN=(()=>{let e=new Map;for(let t of So)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),Qs=new Map(So.map(e=>[e.optionKey,e.canonical])),SN=So.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", "),EN=new Set(["close_reason","assignee","parent","blocked_by","blocked_reason","unblock_note","dependencies","comments","notes","learnings","files","tests","docs","reminders","events"]),TN=vo({depDisableFlagKey:"replaceDeps",fileDisableFlagKey:"replaceFiles",testDisableFlagKey:"replaceTests",docDisableFlagKey:"replaceDocs"});function lk(e){if(at(e))return e;let t={...e,unset:e.unset?[...e.unset]:void 0},n=i=>{let o=t.unset?[...t.unset]:[];o.includes(i)||o.push(i),t.unset=o},r=new Set([...Qs.keys(),"rank"]);for(let i of r){if(at(e,i))continue;let o=t[i];if(typeof o!="string"||!Rr(o))continue;let s=i==="rank"?"order":Qs.get(i)??i;n(s),t[i]=void 0}return dt(e,ko(t,TN))}function q3(e,t,n,r=["update"]){return[...Il([...e],t,n,r).metadataKeys]}function Il(e,t,n=[],r=["update"]){return rh({raw:e,supportedFields:SN,resolveDefinition:i=>{let o=n.find(s=>{let a=s.toLowerCase();return a===i||a.replaceAll("_","-")===i||a.replaceAll("-","_")===i});return kN.get(i)??r.map(s=>fc(i,s,t)).find(s=>s!==void 0)??(o?{optionKey:"field",metadataKey:o}:void 0)}})}var nk=new Map([["--comment",e=>`pm comments ${e} --add "<text>" --force`],["--file",e=>`pm files ${e} --add "path=<path>,scope=<scope>,note=<note>" --force`],["--doc",e=>`pm docs ${e} --add "path=<path>,scope=<scope>,note=<note>" --force`]]);function rk(e){let t=e.disallowedFlags.flatMap(r=>{let i=nk.get(r);return i?[i(e.id)]:[]}),n=e.disallowedFlags.flatMap(r=>{let i=nk.get(r);return i?[`Replace ${r} with: ${i(e.id)}`]:[]});return new p(e.message,m.USAGE,{code:e.code,required:e.required,why:e.why,...t.length>0?{examples:t}:{},nextSteps:[`Re-run without: ${e.disallowedFlags.join(", ")}`,...n]})}function CN(e,t,n){let r=t.ownershipMetadataBypass===!0,i=t.ownershipDependencyBypass===!0;if(!r&&!i)return;if(r&&i)throw new p("Choose only one package-provided ownership bypass mode.",m.USAGE);let o=(c,d,l)=>{c&&l.push(d)};if(i){let c=[];if(o(t.title!==void 0,"--title",c),o(t.description!==void 0,"--description",c),o(t.body!==void 0,"--body",c),o(t.status!==void 0,"--status",c),o(t.closeReason!==void 0,"--close-reason",c),o(t.priority!==void 0,"--priority",c),o(t.type!==void 0,"--type",c),o(t.tags!==void 0,"--tags",c),o(Array.isArray(t.addTags)&&t.addTags.length>0,"--add-tags",c),o(Array.isArray(t.removeTags)&&t.removeTags.length>0,"--remove-tags",c),o(t.deadline!==void 0,"--deadline",c),o(t.estimatedMinutes!==void 0,"--estimate",c),o(t.acceptanceCriteria!==void 0,"--acceptance-criteria",c),o(Array.isArray(t.addAc)&&t.addAc.length>0,"--add-ac",c),o(Array.isArray(t.removeAc)&&t.removeAc.length>0,"--remove-ac",c),o(t.definitionOfReady!==void 0,"--definition-of-ready",c),o(t.order!==void 0||t.rank!==void 0,"--order/--rank",c),o(t.goal!==void 0,"--goal",c),o(t.objective!==void 0,"--objective",c),o(t.value!==void 0,"--value",c),o(t.impact!==void 0,"--impact",c),o(t.outcome!==void 0,"--outcome",c),o(t.whyNow!==void 0,"--why-now",c),o(t.assignee!==void 0,"--assignee",c),o(t.parent!==void 0,"--parent",c),o(t.reviewer!==void 0,"--reviewer",c),o(t.risk!==void 0,"--risk",c),o(t.confidence!==void 0,"--confidence",c),o(t.sprint!==void 0,"--sprint",c),o(t.release!==void 0,"--release",c),o(t.blockedBy!==void 0,"--blocked-by",c),o(t.blockedReason!==void 0,"--blocked-reason",c),o(t.unblockNote!==void 0,"--unblock-note",c),o(t.reporter!==void 0,"--reporter",c),o(t.severity!==void 0,"--severity",c),o(t.environment!==void 0,"--environment",c),o(t.reproSteps!==void 0,"--repro-steps",c),o(t.resolution!==void 0,"--resolution",c),o(t.expectedResult!==void 0,"--expected-result",c),o(t.actualResult!==void 0,"--actual-result",c),o(t.affectedVersion!==void 0,"--affected-version",c),o(t.fixedVersion!==void 0,"--fixed-version",c),o(t.component!==void 0,"--component",c),o(t.regression!==void 0,"--regression",c),o(t.customerImpact!==void 0,"--customer-impact",c),o(t.depRemove!==void 0,"--dep-remove",c),o(t.replaceDeps===!0,"--replace-deps",c),o(t.replaceTests===!0,"--replace-tests",c),o(t.replaceFiles===!0,"--replace-files",c),o(t.replaceDocs===!0,"--replace-docs",c),o(t.comment!==void 0,"--comment",c),o(t.note!==void 0,"--note",c),o(t.learning!==void 0,"--learning",c),o(t.file!==void 0,"--file",c),o(t.test!==void 0,"--test",c),o(t.doc!==void 0,"--doc",c),o(t.reminder!==void 0,"--reminder",c),o(t.event!==void 0,"--event",c),o(t.typeOption!==void 0,"--type-option",c),o(t.clearDeps===!0,"--clear-deps",c),o(t.clearComments===!0,"--clear-comments",c),o(t.clearNotes===!0,"--clear-notes",c),o(t.clearLearnings===!0,"--clear-learnings",c),o(t.clearFiles===!0,"--clear-files",c),o(t.clearTests===!0,"--clear-tests",c),o(t.clearDocs===!0,"--clear-docs",c),o(t.clearReminders===!0,"--clear-reminders",c),o(t.clearEvents===!0,"--clear-events",c),o(t.clearTypeOptions===!0,"--clear-type-options",c),o(t.force===!0,"--force",c),o(n.size>0,"--unset",c),t.dep===void 0||t.dep.length===0)throw new p("The dependency ownership bypass requires at least one --dep value",m.USAGE);if(c.length>0)throw rk({id:e,code:"ownership_dependency_bypass_restricted_options",message:`The dependency ownership bypass supports append-only dependency additions via --dep. Remove restricted options: ${c.join(", ")}`,required:"Pass only --dep additions (plus --message/--author) with the dependency ownership bypass.",why:"the dependency ownership bypass is a narrow non-owner override scoped to append-only dependency additions; every other mutation keeps its normal ownership rules.",disallowedFlags:c});return}let s=[];o(t.status!==void 0,"--status",s),o(t.closeReason!==void 0,"--close-reason",s),o(t.assignee!==void 0,"--assignee",s),o(t.parent!==void 0,"--parent",s),o(t.blockedBy!==void 0,"--blocked-by",s),o(t.blockedReason!==void 0,"--blocked-reason",s),o(t.unblockNote!==void 0,"--unblock-note",s),o(t.dep!==void 0,"--dep",s),o(t.depRemove!==void 0,"--dep-remove",s),o(t.replaceDeps===!0,"--replace-deps",s),o(t.replaceTests===!0,"--replace-tests",s),o(t.replaceFiles===!0,"--replace-files",s),o(t.replaceDocs===!0,"--replace-docs",s),o(t.note!==void 0,"--note",s),o(t.learning!==void 0,"--learning",s),o(t.test!==void 0,"--test",s),o(t.reminder!==void 0,"--reminder",s),o(t.event!==void 0,"--event",s),o(t.clearDeps===!0,"--clear-deps",s),o(t.clearComments===!0,"--clear-comments",s),o(t.clearNotes===!0,"--clear-notes",s),o(t.clearLearnings===!0,"--clear-learnings",s),o(t.clearFiles===!0,"--clear-files",s),o(t.clearTests===!0,"--clear-tests",s),o(t.clearDocs===!0,"--clear-docs",s),o(t.clearReminders===!0,"--clear-reminders",s),o(t.clearEvents===!0,"--clear-events",s);let a=[...n].filter(c=>EN.has(c)).sort((c,d)=>c.localeCompare(d)).map(c=>`--unset ${c.replaceAll("_","-")}`);if(s.push(...a),s.length>0)throw rk({id:e,code:"ownership_metadata_bypass_restricted_options",message:`The metadata ownership bypass only supports non-lifecycle metadata fields and evidence appends. Remove restricted options: ${s.join(", ")}`,required:"Limit the metadata ownership bypass to non-lifecycle metadata fields plus append-only --comment/--file/--doc evidence; route restricted appends and lifecycle changes through their dedicated commands.",why:"the metadata ownership bypass is a non-owner override scoped to metadata maintenance and append-only evidence; lifecycle, ownership, dependency mutations, restricted append fields, and clear/replace operations keep their normal ownership rules.",disallowedFlags:s})}function AN(e,t){let n=ce(e,t);if(!n){let r=t.definitions.map(i=>i.id);throw new p(`Invalid status value "${e}". Allowed: ${r.join(", ")}`,m.USAGE,{code:"invalid_argument_value",field:"status",value:e,allowed:r})}return n}function xN(e,t){return!e||e.trim()===""||e.trim().toLowerCase()==="now"?t:uk(e)}function uk(e){let t=Date.parse(e);if(!Number.isFinite(t))throw new p(`Invalid dependency created_at timestamp "${e}"`,m.USAGE);return new Date(t).toISOString()}function gn(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}var RN=["id","kind","type","author","created_at","source_kind"],IN=["id","kind","type","author","created_at","source_kind"];function mk(e){return e.startsWith("```")||e.includes(`
|
|
11
|
-
`)||/^(?:[-*+]\s+)?(?:id|kind|type|author|created_at|source_kind)\s*[:=]/i.test(e)?!0:Sn(e)}function Ol(e){return typeof e=="string"?de().resolve(e)?.kind??e.trim():e}function ON(e,t,n,r){return e?(Oe(e,"--dep","Use --clear-deps to clear dependencies."),{additions:e.map(i=>{let o=i.trim(),s=mk(o);_i(o,s);let a=s?ee(i,"--dep"):{id:o,kind:"related"};s&&ke(a,"--dep",RN);let c=a.id?.trim(),d=Ol((a.kind??a.type)?.trim());if(!c||!d)throw new p("--dep requires id and kind, or a bare item id to add a related dependency",m.USAGE);if(c.toLowerCase()==="undefined")throw new p(`--dep id must not use placeholder token "${c}". Use --clear-deps to clear dependencies.`,m.USAGE);let l=$r(gn(a.source_kind)),u=gn(a.author);return{id:Nr(c,t,l),kind:ir(d),created_at:xN(a.created_at,n),author:u??r,source_kind:l??"cli:update:dep",author_source:u?"asserted":"detected"}})}):{additions:[]}}function LN(e,t){return e?(Oe(e,"--dep-remove"),e.map(n=>{let r=n.trim();if(!r)throw new p("--dep-remove requires id or key/value selectors",m.USAGE);let i=mk(r);if(_i(r,i,"--dep-remove"),i){let o=ee(r,"--dep-remove");ke(o,"--dep-remove",IN);let s=o.id?.trim();if(o.id===void 0)return DN(o);if(!s)throw new p("--dep-remove key/value form requires a non-empty id=<value>",m.USAGE);if(s.toLowerCase()==="undefined")throw new p(`--dep-remove id must not use placeholder token "${s}"`,m.USAGE);let a=Ol(gn(o.kind??o.type)),c=$r(gn(o.source_kind)),d=gn(o.author),l=gn(o.created_at);return{id:Nr(s,t,c),kind:a?ir(a):void 0,source_kind:c,author:d,created_at:l?uk(l):void 0}}if(r.toLowerCase()==="undefined")throw new p(`--dep-remove id must not use placeholder token "${r}"`,m.USAGE);return{id:Xe(r,t)}})):[]}function DN(e){let t=Ol(gn(e.kind??e.type)),n=Object.keys(e).filter(r=>r!=="kind"&&r!=="type");if(!t||n.length>0||e.kind!==void 0&&e.type!==void 0)throw new p("--dep-remove key/value form requires id=<value>, or kind=<kind> alone to remove every row of that kind",m.USAGE);return{kind:ir(t)}}function Zs(e){let t=e.source_kind?.trim().toLowerCase()??"";return[e.id.trim().toLowerCase(),e.kind,t].join("\0")}function $N(e,t,n,r,i){let o=[...e??[]],s=!1;if(t===void 0){let a=o.filter(c=>i===void 0||!Sl(c,i.value,i.idPrefix));return a.length!==o.length&&(o=a,s=!0),s?{dependencies:o.length>0?o:void 0,changed:!0}:{dependencies:e,changed:!1}}return o.some(a=>a.kind==="blocked_by"&&a.id===t)||(o.push({id:t,kind:"blocked_by",created_at:n,author:r,source_kind:"cli:update:blocked_by",author_source:"detected"}),s=!0),s?{dependencies:o.length>0?o:void 0,changed:!0}:{dependencies:e,changed:!1}}async function NN(e,t,n,r,i,o){if(e===void 0||t)return{};let s=e.trim();if(s.length===0)return{};let a=await V(n,Xe(s,r),r,i,o);return a?{id:a.id}:{unresolved:s}}function MN(e,t,n,r,i,o){let s=$N(e.dependencies,t,n,r,o);s.changed&&(s.dependencies===void 0?delete e.dependencies:e.dependencies=s.dependencies,i.includes("dependencies")||i.push("dependencies"))}function PN(e){return`${e.path}::${e.scope}`}function FN(e){return`${e.path}::${e.scope}`}function jN(e){return`${e.command}::${e.path??""}::${e.scope}::${e.pm_context_mode??""}::${e.workspace_context_mode??""}`}function ik(e,t){let n=_r("update",e);if(!n)throw new p(`Unsupported command_option_policies option "${e}" for update command on type "${t}"`,m.CONFLICT);return n}function UN(e,t,n){let r=new Set,i=(o,s)=>{s&&r.add(o)};if(i("title",e.title!==void 0),i("description",e.description!==void 0),i("body",e.body!==void 0),i("status",e.status!==void 0),i("closeReason",e.closeReason!==void 0),i("priority",e.priority!==void 0),i("type",e.type!==void 0),i("tags",e.tags!==void 0||Array.isArray(e.addTags)&&e.addTags.length>0||Array.isArray(e.removeTags)&&e.removeTags.length>0),i("deadline",e.deadline!==void 0),i("estimatedMinutes",e.estimatedMinutes!==void 0),i("acceptanceCriteria",e.acceptanceCriteria!==void 0||Array.isArray(e.addAc)&&e.addAc.length>0||Array.isArray(e.removeAc)&&e.removeAc.length>0),i("definitionOfReady",e.definitionOfReady!==void 0),i("order",e.order!==void 0||e.rank!==void 0),i("goal",e.goal!==void 0),i("objective",e.objective!==void 0),i("value",e.value!==void 0),i("impact",e.impact!==void 0),i("outcome",e.outcome!==void 0),i("whyNow",e.whyNow!==void 0),i("author",e.author!==void 0),i("message",e.message!==void 0),i("assignee",e.assignee!==void 0),i("parent",e.parent!==void 0),i("reviewer",e.reviewer!==void 0),i("risk",e.risk!==void 0),i("confidence",e.confidence!==void 0),i("sprint",e.sprint!==void 0),i("release",e.release!==void 0),i("blockedBy",e.blockedBy!==void 0),i("blockedReason",e.blockedReason!==void 0),i("unblockNote",e.unblockNote!==void 0),i("reporter",e.reporter!==void 0),i("severity",e.severity!==void 0),i("environment",e.environment!==void 0),i("reproSteps",e.reproSteps!==void 0),i("resolution",e.resolution!==void 0),i("expectedResult",e.expectedResult!==void 0),i("actualResult",e.actualResult!==void 0),i("affectedVersion",e.affectedVersion!==void 0),i("fixedVersion",e.fixedVersion!==void 0),i("component",e.component!==void 0),i("regression",e.regression!==void 0),i("customerImpact",e.customerImpact!==void 0),i("dep",e.dep!==void 0),i("depRemove",e.depRemove!==void 0),i("dep",e.replaceDeps===!0),i("comment",e.comment!==void 0),i("note",e.note!==void 0),i("learning",e.learning!==void 0),i("file",e.file!==void 0),i("test",e.test!==void 0),i("test",e.replaceTests===!0),i("file",e.replaceFiles===!0),i("doc",e.replaceDocs===!0),i("doc",e.doc!==void 0),i("reminder",e.reminder!==void 0),i("event",e.event!==void 0),i("typeOption",e.typeOption!==void 0),i("field",e.field!==void 0),i("force",e.force===!0),i("ownershipMetadataBypass",e.ownershipMetadataBypass===!0),i("ownershipDependencyBypass",e.ownershipDependencyBypass===!0),i("dep",e.clearDeps===!0),i("comment",e.clearComments===!0),i("note",e.clearNotes===!0),i("learning",e.clearLearnings===!0),i("file",e.clearFiles===!0),i("test",e.clearTests===!0),i("doc",e.clearDocs===!0),i("reminder",e.clearReminders===!0),i("event",e.clearEvents===!0),i("typeOption",e.clearTypeOptions===!0),e.unset&&e.unset.length>0){let o=Il(e.unset,t,n,e.runtimeFieldCommands);for(let s of o.optionKeys)i(s,!0)}return r}function GN(e,t,n,r,i){let o=ji(e,n);if(!o)throw new p(`Invalid type value "${e}"`,m.USAGE);let s=Cn(o,"update",[]);if(s.errors.length>0)throw new p(s.errors.join("; "),m.CONFLICT);let a=UN(t,r,i);for(let c of s.disabled)if(a.has(ik(c,e)))throw new p(`Option ${xe("update",c)} is disabled for type "${e}" by command_option_policies`,m.USAGE);for(let c of s.required)if(!a.has(ik(c,e)))throw new p(`Missing required option ${xe("update",c)} for type "${e}"`,m.USAGE)}var qN=new Set(["order","rank"]),KN=$a.filter(e=>!qN.has(e)),pk=["tags","closeReason",...KN],WN=["title","description","body","status","closeReason","completedAt","priority","type",...$a,"dep","depRemove","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],zN=[{optionKey:"deadline",metadataKey:"deadline",transform:(e,t)=>me(e,t.nowValue,"deadline")},{optionKey:"estimatedMinutes",metadataKey:"estimated_minutes",transform:e=>Mi(e,"estimated-minutes")},{optionKey:"acceptanceCriteria",metadataKey:"acceptance_criteria",transform:e=>e},{optionKey:"definitionOfReady",metadataKey:"definition_of_ready"},{optionKey:"goal",metadataKey:"goal"},{optionKey:"objective",metadataKey:"objective"},{optionKey:"value",metadataKey:"value"},{optionKey:"impact",metadataKey:"impact"},{optionKey:"outcome",metadataKey:"outcome"},{optionKey:"whyNow",metadataKey:"why_now"}],BN=[{optionKey:"reviewer",metadataKey:"reviewer"},{optionKey:"risk",metadataKey:"risk",transform:e=>tt(Ns(e),Pi,"risk")},{optionKey:"confidence",metadataKey:"confidence",transform:e=>Ps(e)}],HN=[{optionKey:"blockedReason",metadataKey:"blocked_reason"},{optionKey:"unblockNote",metadataKey:"unblock_note"},{optionKey:"reporter",metadataKey:"reporter"},{optionKey:"severity",metadataKey:"severity",transform:e=>tt(Ms(e),Fi,"severity")},{optionKey:"environment",metadataKey:"environment"},{optionKey:"reproSteps",metadataKey:"repro_steps"},{optionKey:"resolution",metadataKey:"resolution"},{optionKey:"expectedResult",metadataKey:"expected_result"},{optionKey:"actualResult",metadataKey:"actual_result"},{optionKey:"affectedVersion",metadataKey:"affected_version"},{optionKey:"fixedVersion",metadataKey:"fixed_version"},{optionKey:"component",metadataKey:"component"},{optionKey:"regression",metadataKey:"regression",transform:e=>Fs(e)},{optionKey:"customerImpact",metadataKey:"customer_impact"}];function Rl(e,t,n){for(let r of e){let i=t[r.optionKey],o=n.clearItemMetadataKeys.has(r.metadataKey);if(!(i===void 0&&!o)){if(o){delete n.metadataRecord[r.metadataKey],n.changedFields.push(r.metadataKey);continue}if(typeof i!="string")throw new p(`${xe("update",String(r.optionKey))} must be a string value`,m.USAGE);n.metadataRecord[r.metadataKey]=r.transform?r.transform(i,n):i.trim(),n.changedFields.push(r.metadataKey)}}}async function VN(e){return lk(await Ni(e,[["body","--body"],["description","--description"]],[["dep","--dep"],["depRemove","--dep-remove"],["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"],["field","--field"]]))}async function YN(e){let t=Lr("update",e);return Wt(t)?await VN(t):lk(t)}function JN(e){return[{enabled:e.clearDeps||e.replaceDeps,optionKey:"dep",clearFlag:"--clear-deps",valueFlag:"--dep",values:e.dep,metadataKey:"dependencies"},{enabled:e.clearComments,optionKey:"comment",clearFlag:"--clear-comments",valueFlag:"--comment",values:e.comment,metadataKey:"comments"},{enabled:e.clearNotes,optionKey:"note",clearFlag:"--clear-notes",valueFlag:"--note",values:e.note,metadataKey:"notes"},{enabled:e.clearLearnings,optionKey:"learning",clearFlag:"--clear-learnings",valueFlag:"--learning",values:e.learning,metadataKey:"learnings"},{enabled:e.clearFiles||e.replaceFiles,optionKey:"file",clearFlag:"--clear-files",valueFlag:"--file",values:e.file,metadataKey:"files"},{enabled:e.clearTests||e.replaceTests,optionKey:"test",clearFlag:"--clear-tests",valueFlag:"--test",values:e.test,metadataKey:"tests"},{enabled:e.clearDocs||e.replaceDocs,optionKey:"doc",clearFlag:"--clear-docs",valueFlag:"--doc",values:e.doc,metadataKey:"docs"},{enabled:e.clearReminders,optionKey:"reminder",clearFlag:"--clear-reminders",valueFlag:"--reminder",values:e.reminder,metadataKey:"reminders"},{enabled:e.clearEvents,optionKey:"event",clearFlag:"--clear-events",valueFlag:"--event",values:e.event,metadataKey:"events"},{enabled:e.clearTypeOptions,optionKey:"typeOption",clearFlag:"--clear-type-options",valueFlag:"--type-option",values:e.typeOption,metadataKey:"type_options"}]}function Al(e){if(e.enabled&&(!e.values||e.values.length===0))throw new p(`${e.replaceFlag} requires at least one ${e.valueFlag} entry`,m.USAGE);if(e.enabled&&e.clearEnabled)throw new p(`${e.replaceFlag} cannot be combined with ${e.clearFlag}`,m.USAGE)}function XN(e){let t=(e.addAc?.length??0)>0||(e.removeAc?.length??0)>0;if(e.acceptanceCriteria!==void 0&&t)throw new p("Cannot combine --acceptance-criteria replacement with --add-ac or --remove-ac. Use --remove-ac and --add-ac together for an atomic one-entry repair.",m.USAGE,{code:"acceptance_criteria_mutation_conflict",reason:"replacement_and_additive_mutation_combined",nextSteps:["Use --acceptance-criteria alone to replace the complete list.","Use --remove-ac <old> --add-ac <new> to repair one criterion without replacing unrelated entries."]});if(e.replaceDeps===!0&&(e.dep===void 0||e.dep.length===0))throw new p("--replace-deps requires at least one --dep entry",m.USAGE);if(e.replaceDeps===!0&&e.depRemove!==void 0&&e.depRemove.length>0)throw new p("--replace-deps cannot be combined with --dep-remove",m.USAGE);Al({enabled:e.replaceTests===!0,values:e.test,replaceFlag:"--replace-tests",clearEnabled:e.clearTests===!0,clearFlag:"--clear-tests",valueFlag:"--test"}),Al({enabled:e.replaceFiles===!0,values:e.file,replaceFlag:"--replace-files",clearEnabled:e.clearFiles===!0,clearFlag:"--clear-files",valueFlag:"--file"}),Al({enabled:e.replaceDocs===!0,values:e.doc,replaceFlag:"--replace-docs",clearEnabled:e.clearDocs===!0,clearFlag:"--clear-docs",valueFlag:"--doc"})}function QN(e){for(let t of e.definitions){if(!t.enabled)continue;let n=t.optionKey==="dep"&&e.options.replaceDeps===!0||t.optionKey==="test"&&e.options.replaceTests===!0||t.optionKey==="file"&&e.options.replaceFiles===!0||t.optionKey==="doc"&&e.options.replaceDocs===!0;if(t.values&&t.values.length>0&&!n)throw new p(`Cannot combine ${t.clearFlag} with ${t.valueFlag}`,m.USAGE);e.clearOptionKeys.add(t.optionKey),e.clearItemMetadataKeys.add(t.metadataKey)}}function ZN(e){let t={};for(let n of pk)t[String(n)]=e[n]!==void 0;return t.order=e.order!==void 0||e.rank!==void 0,t}function eM(e,t){let n=ZN(e);for(let[r,i]of Object.entries(n)){if(!i||!t.optionKeys.has(r))continue;let o=Qs.get(r)??r;throw new p(`Cannot combine --unset ${o} with ${xe("update",r)}`,m.USAGE)}if(t.metadataKeys.has("acceptance_criteria")){if(Array.isArray(e.addAc)&&e.addAc.length>0)throw new p("Cannot combine --unset acceptance-criteria with --add-ac",m.USAGE);if(Array.isArray(e.removeAc)&&e.removeAc.length>0)throw new p("Cannot combine --unset acceptance-criteria with --remove-ac",m.USAGE)}if(t.metadataKeys.has("tags")){if(Array.isArray(e.addTags)&&e.addTags.length>0)throw new p("Cannot combine --unset tags with --add-tags",m.USAGE);if(Array.isArray(e.removeTags)&&e.removeTags.length>0)throw new p("Cannot combine --unset tags with --remove-tags",m.USAGE)}}function tM(e){if(at(e))return;let t=(n,r)=>{if(at(e,r))return;let i=Qs.get(r),o=i?`Use --unset ${i} to clear this field.`:void 0;bo(n,xe("update",r),o)};for(let n of pk)t(e[n],String(n));t(e.order??e.rank,"order"),Oe(e.reminder,"--reminder","Use --clear-reminders to clear reminders."),Oe(e.event,"--event","Use --clear-events to clear linked events.")}function nM(e,t){let n={};for(let r of WN)n[String(r)]=e[r]!==void 0;return n.tags=e.tags!==void 0,n.addTags=Array.isArray(e.addTags)&&e.addTags.length>0,n.removeTags=Array.isArray(e.removeTags)&&e.removeTags.length>0,n.addAc=Array.isArray(e.addAc)&&e.addAc.length>0,n.removeAc=Array.isArray(e.removeAc)&&e.removeAc.length>0,n.order=e.order!==void 0,n.rank=e.rank!==void 0,n.replaceDeps=e.replaceDeps===!0,n.replaceTests=e.replaceTests===!0,n.replaceFiles=e.replaceFiles===!0,n.replaceDocs=e.replaceDocs===!0,n.unset=e.unset!==void 0&&e.unset.length>0,n.clearDeps=e.clearDeps===!0,n.clearComments=e.clearComments===!0,n.clearNotes=e.clearNotes===!0,n.clearLearnings=e.clearLearnings===!0,n.clearFiles=e.clearFiles===!0,n.clearTests=e.clearTests===!0,n.clearDocs=e.clearDocs===!0,n.clearReminders=e.clearReminders===!0,n.clearEvents=e.clearEvents===!0,n.clearTypeOptions=e.clearTypeOptions===!0,n.documentAnnotationSnapshot=e.documentAnnotationSnapshot!==void 0,n.runtimeFields=Object.keys(t).length>0,n}async function rM(e){let t=await V(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await Qt(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await pe(t,{schema:e.settings.schema});return{item:n.metadata,changed_fields:[],warnings:["noop_no_update_fields"]}}async function iM(e){if(!(!e.fieldFlags.dep&&!e.fieldFlags.blockedBy&&!e.fieldFlags.parent&&!e.clearedMetadataKeys.has("parent")))return Te(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}function oM(e){e.before&&(Ss(e.before,e.before.map(t=>t.id===e.document.metadata.id?e.document.metadata:t)),Co(e.before,e.before.map(t=>t.id===e.document.metadata.id?e.document.metadata:t),e.document.metadata.id,t=>fe(t,e.statusRegistry),de()))}function sM(e){if(e.order!==void 0&&e.rank!==void 0&&e.order!==e.rank)throw new p("--order and --rank must match when both are provided",m.USAGE)}async function aM(e){if(e.options.parent===void 0||e.unsetTargets.metadataKeys.has("parent"))return{resolvedParentValue:void 0,warnings:[]};let t=ct(e.options),n=Dn(so(e.options.parent,t),e.settings.id_prefix);if(ho(n))return{resolvedParentValue:n,warnings:[]};if(co(e.id,n,e.settings.id_prefix,t),await V(e.pmRoot,n,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder))return{resolvedParentValue:n,warnings:[]};let r=Xe(n,e.settings.id_prefix);return{resolvedParentValue:n,warnings:ao(r,e.parentReferencePolicy,t).warnings}}function cM(e){return e.unresolved===void 0?[]:[`blocked_by_unresolved:${e.unresolved}`]}async function dM(e){if(e.workflowEnforcement==="off"||e.typeWorkflows.length===0||!e.fieldFlags.status||e.options.status===void 0)return[];let t=await V(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await Qt(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await pe(t,{schema:e.settings.schema}),r=e.options.type!==void 0?_t(e.options.type,e.typeRegistry)??e.options.type:n.metadata?.type??"",i=or({enforcement:e.workflowEnforcement,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry,typeName:r,fromStatus:n.metadata?.status??"",toStatus:e.options.status});return i?[i]:[]}async function lM(e){if(!e.fieldFlags.status||ce(e.options.status,e.statusRegistry)!==e.statusRegistry.close_status)return;Xb(e);let t=Object.entries(e.fieldFlags).filter(([i,o])=>o&&i!=="status"&&i!=="closeReason"&&i!=="completedAt").map(([i])=>i),n=await Qb(e);if(Tl(n,e.options,e.statusRegistry,e.settings.governance.require_close_reason))return Zb(e,n,t,hi,i=>ok(e,i));let r;if(t.length>0){let i=dt(e.options,{...e.options,status:void 0,closeReason:void 0,message:void 0});r=await hi(e.id,i,e.global)}return ok(e,r)}async function ok(e,t){let n=await vs(e.id,e.options.closeReason,{author:e.options.author,message:e.options.message,force:e.options.force,completedAt:e.options.completedAt},e.global),r=[...Ir("update",e.options,ct(e.options)==="sdk",n.item),...e.workflowTransitionWarnings,...(t?.warnings??[]).filter(i=>!i.startsWith("literal_sentinel_stored:")),...n.warnings,"auto_routed_from_update_to_close"];return{item:n.item,changed_fields:[...t?.changed_fields??[],...n.changed_fields],warnings:r}}function uM(e,t,n,r){return t.title!==void 0&&(e.metadata.title=kl(t.title,"--title",ct(t)),r.push("title")),t.description!==void 0&&(e.metadata.description=t.description,r.push("description")),t.body!==void 0&&(e.body=t.body,r.push("body")),ce(e.metadata.status,n)??e.metadata.status}var mM=["closed_at","completed_at","close_reason","resolution","expected_result","actual_result","fixed_version"];function pM(e,t){for(let n of mM)e[n]!==void 0&&(delete e[n],t.push(n))}function _M(e,t,n,r,i){let o=AN(n,t.statusRegistry);if(e.metadata.status=o,i.push("status"),o===t.statusRegistry.close_status&&(e.metadata.closed_at===void 0||e.metadata.closed_at===null)){e.metadata.closed_at=t.nowIso,e.metadata.completed_at=t.nowIso,i.push("closed_at","completed_at");return}!fe(o,t.statusRegistry)&&fe(r,t.statusRegistry)&&pM(e.metadata,i)}function fM(e,t,n,r){if(t.options.status!==void 0&&_M(e,t,t.options.status,n,r),t.options.completedAt!==void 0){if(!fe(e.metadata.status,t.statusRegistry))throw new p("--completed-at can only be set on a terminal item",m.USAGE);e.metadata.completed_at=me(t.options.completedAt,new Date(t.nowIso),"completed-at"),r.push("completed_at")}}function hM(e,t,n,r){if(t.options.closeReason!==void 0||t.clearItemMetadataKeys.has("close_reason")){if(t.clearItemMetadataKeys.has("close_reason"))delete e.metadata.close_reason;else{let i=t.options.closeReason?.trim()??"";if(i.length===0)throw new p(Ia(ct(t.options),"close-reason"),m.USAGE);e.metadata.close_reason=i}r.push("close_reason");return}t.options.status!==void 0&&fe(n,t.statusRegistry)&&!fe(e.metadata.status,t.statusRegistry)&&e.metadata.close_reason!==void 0&&(delete e.metadata.close_reason,r.push("close_reason"))}function gM(e,t,n,r){fM(e,t,n,r),hM(e,t,n,r)}function yM(e,t,n){let r=_t(e.metadata.type,t.typeRegistry)??e.metadata.type;if(t.options.priority!==void 0&&(e.metadata.priority=lo(t.options.priority),n.push("priority")),t.options.type!==void 0){let i=_t(t.options.type,t.typeRegistry);if(!i)throw new p(mo(t.options.type,t.typeRegistry.types,Qi(t.pmRoot,t.settings.schema)),m.USAGE);e.metadata.type=i,r=i,n.push("type")}return GN(r,t.options,t.typeRegistry,t.runtimeFieldRegistry,t.extensionFieldNames),wM(e,t,r,n),r}function wM(e,t,n,r){if(t.options.typeOption!==void 0||t.clearItemMetadataKeys.has("type_options")){if(t.clearItemMetadataKeys.has("type_options"))delete e.metadata.type_options;else{let o=Ws(t.options.typeOption??[]),s=fr(n,o,t.typeRegistry);if(s.errors.length>0)throw new p(s.errors.join("; "),m.USAGE);e.metadata.type_options=s.normalized}r.push("type_options");return}if(t.options.type===void 0||e.metadata.type_options===void 0)return;let i=fr(n,e.metadata.type_options,t.typeRegistry);if(i.errors.length>0)throw new p(`Current type options are incompatible with type "${n}". ${i.errors.join("; ")}. Use --clear-type-options to clear them.`,m.USAGE);e.metadata.type_options=i.normalized}function vM(e,t){let n=new Set(t.map(i=>Zs(i))),r=new Set;return e.filter(i=>{if(!n.has(Zs(i)))return!0;let o=Xs(i);return r.has(o)?!1:(r.add(o),!0)})}function bM(e,t,n){if(t.options.dep===void 0&&t.options.depRemove===void 0&&!t.clearItemMetadataKeys.has("dependencies"))return;let r=t.clearItemMetadataKeys.has("dependencies")?[]:[...e.metadata.dependencies??[]];if(t.dependencyUpdates.additions.length>0){r=vM(r,t.dependencyUpdates.additions);let i=new Set(r.map(o=>Zs(o)));for(let o of t.dependencyUpdates.additions){let s=Zs(o);i.has(s)||(r.push(o),i.add(s))}}t.dependencyRemovals.length>0&&(ek(r,t.dependencyRemovals,e.metadata.id),r=r.filter(i=>!t.dependencyRemovals.some(o=>Cl(i,o)))),r.length===0?delete e.metadata.dependencies:e.metadata.dependencies=r,n.push("dependencies")}function kM(e,t,n){xl(e,"comments",t.options.comment,t.commentUpdates.values,t.clearItemMetadataKeys,n),xl(e,"notes",t.options.note,t.noteUpdates.values,t.clearItemMetadataKeys,n),xl(e,"learnings",t.options.learning,t.learningUpdates.values,t.clearItemMetadataKeys,n)}function xl(e,t,n,r,i,o){n===void 0&&!i.has(t)||(i.has(t)||!r||r.length===0?delete e.metadata[t]:e.metadata[t]=[...e.metadata[t]??[],...r],o.push(t))}function SM(e,t,n){sk(e,"files",t.options.file,t.fileUpdates.values,PN,t.options.replaceFiles===!0,t.clearItemMetadataKeys,n),EM(e,t,n),sk(e,"docs",t.options.doc,t.docUpdates.values,FN,t.options.replaceDocs===!0,t.clearItemMetadataKeys,n)}function sk(e,t,n,r,i,o,s,a){if(!(n===void 0&&!s.has(t))){if(o)e.metadata[t]=r;else if(s.has(t)||!r||r.length===0)delete e.metadata[t];else{let c=[...e.metadata[t]??[]],d=new Set(c.map(l=>i(l)));for(let l of r){let u=i(l);d.has(u)||(c.push(l),d.add(u))}e.metadata[t]=c}a.push(t)}}function EM(e,t,n){t.options.test===void 0&&!t.clearItemMetadataKeys.has("tests")||(t.clearItemMetadataKeys.has("tests")&&t.options.replaceTests===!0?e.metadata.tests=ak(t.testUpdates.values)??[]:t.clearItemMetadataKeys.has("tests")||!t.testUpdates.values||t.testUpdates.values.length===0?delete e.metadata.tests:e.metadata.tests=ak([...e.metadata.tests??[],...t.testUpdates.values]),e.metadata.tests!==void 0&&e.metadata.tests.length===0&&delete e.metadata.tests,n.push("tests"))}function ak(e){if(!e||e.length===0)return;let t=[],n=new Set;for(let r of e){let i=jN(r);n.has(i)||(t.push(r),n.add(i))}return t}function TM(e,t,n){let r=t.options.addTags,i=t.options.removeTags,o=Array.isArray(r)&&r.length>0||Array.isArray(i)&&i.length>0;if(t.options.tags!==void 0||t.clearItemMetadataKeys.has("tags")||o){let s=t.clearItemMetadataKeys.has("tags")?[]:t.options.tags!==void 0?Li(t.options.tags):Array.isArray(e.metadata.tags)?[...e.metadata.tags]:[];e.metadata.tags=Vu($i(s,r),i),n.changedFields.push("tags")}Rl(zN,t.options,n),AM(e,t,n.changedFields)}function CM(e,t,n){let r=t.options.addAc,i=t.options.removeAc;if(!(Array.isArray(r)&&r.length>0)&&!(Array.isArray(i)&&i.length>0))return;let o=Hu(Di(e.metadata.acceptance_criteria),r,i);if(o.unmatchedRemovals.length>0)throw new p(`Acceptance criteria removal did not match: ${o.unmatchedRemovals.join(", ")}`,m.NOT_FOUND,{code:"acceptance_criteria_remove_unmatched",reason:"exact_match_not_found",field:"acceptance_criteria",unmatched:o.unmatchedRemovals,why:"Lossless removal fails instead of silently applying the remaining mutations when an exact selector is wrong.",nextSteps:["Read the current acceptance_criteria value and retry with the exact criterion text.","Use --acceptance-criteria alone only when replacing the complete list is intentional."]});let s=o.criteria.join("; ");e.metadata.acceptance_criteria!==s&&(s===""&&e.metadata.acceptance_criteria===void 0||(e.metadata.acceptance_criteria=s,n.changedFields.includes("acceptance_criteria")||n.changedFields.push("acceptance_criteria")))}function AM(e,t,n){let r=t.options.order??t.options.rank;if(!(r===void 0&&!t.clearItemMetadataKeys.has("order"))){if(t.clearItemMetadataKeys.has("order"))delete e.metadata.order;else{let i=we(r??"","order");if(!Number.isInteger(i))throw new p("Order must be an integer",m.USAGE);e.metadata.order=i}n.push("order")}}function xM(e,t,n,r){RM(e,t,n.changedFields),IM(e,t,n.changedFields),Rl(BN,t.options,n),ck(e,t,"sprint",r,n.changedFields),ck(e,t,"release",r,n.changedFields),OM(e,t,n.changedFields),Rl(HN,t.options,n)}function RM(e,t,n){if(!(t.options.assignee===void 0&&!t.clearItemMetadataKeys.has("assignee"))){if(t.clearItemMetadataKeys.has("assignee"))delete e.metadata.assignee;else{let r=t.options.assignee?.trim()??"";if(r==="")throw new p(Ia(ct(t.options),"assignee",". Use --unset assignee to clear it."),m.USAGE);fm(r,"--assignee"),e.metadata.assignee=r}n.push("assignee")}}function IM(e,t,n){t.options.parent===void 0&&!t.clearItemMetadataKeys.has("parent")||(t.clearItemMetadataKeys.has("parent")?delete e.metadata.parent:e.metadata.parent=t.resolvedParentValue??"",n.push("parent"))}function ck(e,t,n,r,i){if(!(t.options[n]===void 0&&!t.clearItemMetadataKeys.has(n))){if(t.clearItemMetadataKeys.has(n))delete e.metadata[n];else{let o=uo(n,t.options[n]??"",t.settings.validation.sprint_release_format,ct(t.options));e.metadata[n]=o.value,r.push(...o.warnings)}i.push(n)}}function OM(e,t,n){if(t.options.blockedBy===void 0&&!t.clearItemMetadataKeys.has("blocked_by"))return;let r=t.clearItemMetadataKeys.has("blocked_by")?e.metadata.blocked_by:void 0;t.clearItemMetadataKeys.has("blocked_by")?delete e.metadata.blocked_by:e.metadata.blocked_by=t.options.blockedBy?.trim()??"",n.push("blocked_by"),(t.clearItemMetadataKeys.has("blocked_by")||t.resolvedBlockedByDependencyId!==void 0)&&MN(e.metadata,t.resolvedBlockedByDependencyId,t.nowIso,t.author,n,{value:r,idPrefix:t.settings.id_prefix})}function LM(e,t,n){(t.options.reminder!==void 0||t.clearItemMetadataKeys.has("reminders"))&&(t.clearItemMetadataKeys.has("reminders")?delete e.metadata.reminders:e.metadata.reminders=qs(t.options.reminder??[],t.nowValue,{valueMode:"trimmed"}),n.push("reminders")),(t.options.event!==void 0||t.clearItemMetadataKeys.has("events"))&&(t.clearItemMetadataKeys.has("events")?delete e.metadata.events:e.metadata.events=Ks(t.options.event??[],t.nowValue,{allDayEmptyGuard:"truthy",recurrenceEmptyNumericGuard:"truthy"}),n.push("events"))}function DM(e,t,n){dk(e,t.runtimeFieldRegistry.definitions.map(i=>i.metadata_key),t.clearItemMetadataKeys,n),dk(e,t.extensionFieldNames,t.clearItemMetadataKeys,n);for(let[i,o]of Object.entries(t.runtimeFieldUpdates)){if(t.clearItemMetadataKeys.has(i)){let s=i.replaceAll("_","-"),a=t.runtimeFieldRegistry.definitions.find(c=>c.metadata_key===i)?.cli_flag??s;throw new p(`Cannot combine --unset ${s} with --${a}`,m.USAGE)}Fe(e[i],o)||(e[i]=o,n.push(i))}let r=Ji(t.options.field,t.extensionRegistrations,js,Us(t.runtimeFieldRegistry,(t.options.runtimeFieldCommands??[]).includes("update_many")?"update_many":"update",t.options));for(let i of Object.keys(r))if(t.clearItemMetadataKeys.has(i))throw new p(`Cannot combine --unset ${i.replaceAll("_","-")} with --field ${i}=...`,m.USAGE);for(let[i,o]of Object.entries(r))Fe(e[i],o)||(e[i]=o,n.push(i))}function dk(e,t,n,r){for(let i of t)!n.has(i)||e[i]===void 0||(delete e[i],r.push(i))}function $M(e,t){if(t===void 0)return;let n=e.metadata,r=["comments","notes","learnings"].find(i=>{let o=t[i];return o!==void 0&&(!Array.isArray(o)||!Fe(o,n[i]??[]))});if(r!==void 0)throw new p(`Full-item --stdin-json update changed persisted ${r}; no item fields were written.`,m.USAGE,{code:"stdin_json_persisted_annotation_changed",reason:`${r}_requires_annotation_command`,required:`Use pm ${r} ${e.metadata.id} --edit <index> --add <text> to correct an existing entry.`,why:"Full-item update appends new annotations but cannot replace or remove existing audit entries.",nextSteps:[`Inspect the current ${r} with pm ${r} ${e.metadata.id}.`,`Apply the correction with pm ${r} ${e.metadata.id} --edit <index> --add <text>.`]})}function NM(e,t){$M(e,t.options.documentAnnotationSnapshot);let n=structuredClone(e.metadata),r=e.body,i=[],o=[],s=uM(e,t.options,t.statusRegistry,i),a=e.metadata,c={metadataRecord:a,clearItemMetadataKeys:t.clearItemMetadataKeys,changedFields:i,nowValue:t.nowValue};gM(e,t,s,i),yM(e,t,i),bM(e,t,i),kM(e,t,i),SM(e,t,i),TM(e,t,c),CM(e,t,c),xM(e,t,c,o),(t.options.dep!==void 0||t.options.depRemove!==void 0||t.options.blockedBy!==void 0||t.clearItemMetadataKeys.has("dependencies")||t.clearItemMetadataKeys.has("blocked_by"))&&fi(e.metadata.id,e.metadata.dependencies),ce(e.metadata.status,t.statusRegistry)===t.statusRegistry.canceled_status&&e.metadata.assignee!==void 0&&(delete e.metadata.assignee,i.includes("assignee")||i.push("assignee")),LM(e,t,i),DM(a,t,i);try{Xi(a,t.extensionRegistrations,{skipDefaultFields:t.clearItemMetadataKeys})}catch(_){throw new p(_ instanceof Error?_.message:"Invalid extension item field values",m.USAGE)}let d=e.metadata,l=[...new Set(i)].filter(_=>_==="body"?e.body!==r:!Fe(n[_],d[_])),u=tk(n.dependencies,d.dependencies);return u!==void 0&&o.push(`dependencies_removed:${e.metadata.id}:${u}`),t.options.acceptanceCriteria!==void 0&&l.includes("acceptance_criteria")&&o.push(`acceptance_criteria_replaced:${Di(n.acceptance_criteria).length}:${Di(d.acceptance_criteria).length}`),{changedFields:l,warnings:o}}async function _k(e,t,n,r={}){Or(e,"update","id");let i=await YN(t),o=R(process.cwd(),n.path);await j(o);let s=await x(o),a=W(s.schema),c=Vt(s.schema),d=N(),l=At(d),u=P(s,d),_=s.governance.workflow_enforcement??"off",h=_==="off"?[]:Ln(s.schema),f=[{strict_error:"strict_error",warn:"warn",off:"off"},{strict_error:"warn",warn:"warn",off:"off"}][+(i.allowMissingParent===!0)][s.validation.parent_reference],g=Il(i.unset,c,l,i.runtimeFieldCommands),y=new Set(g.optionKeys),w=new Set(g.metadataKeys);XN(i),QN({definitions:JN(i),options:i,clearOptionKeys:y,clearItemMetadataKeys:w}),CN(e,i,w),eM(i,g),tM(i);let v=U(i.author,s.author_default),k=new Date,S=k.toISOString(),b=ON(i.dep,s.id_prefix,S,v);fi(e,b.additions);let A=await Gs({pmRoot:o,dependencies:b.additions,idPrefix:s.id_prefix,itemFormat:s.item_format,typeToFolder:u.type_to_folder,allowUnresolved:i.allowUnresolvedDeps,holders:[{id:e}],schema:s.schema}),E=LN(i.depRemove,s.id_prefix),C=fn("--comment",i.comment,S,v),O=i.ownershipMetadataBypass===!0&&C.values?{...C,values:C.values.map(se=>({...se,author:v}))}:C,M=fn("--note",i.note,S,v),T=fn("--learning",i.learning,S,v),F=wl(i.file),ue=vl(i.test);ue.values=await Qn(ue.values,v,S);let Ne=bl(i.doc),J=[],Me=await aM({id:e,options:i,unsetTargets:g,pmRoot:o,settings:s,typeRegistry:u,parentReferencePolicy:f}),Pe=await NN(i.blockedBy,w.has("blocked_by"),o,s.id_prefix,s.item_format,u.type_to_folder),qe=Pe.id,re=[...Me.warnings,...cM(Pe)],be=Jm(i,c,i.runtimeFieldCommands),Ee=nM(i,be);if(!Object.values(Ee).some(Boolean))return rM({pmRoot:o,id:e,settings:s,typeRegistry:u});J.push(...await dM({options:i,fieldFlags:Ee,workflowEnforcement:_,typeWorkflows:h,statusRegistry:a,typeRegistry:u,pmRoot:o,id:e,settings:s}));let nt=await lM({options:i,fieldFlags:Ee,statusRegistry:a,workflowTransitionWarnings:J,global:n,id:e,pmRoot:o,settings:s,typeRegistry:u});if(nt)return nt;sM(i);let rt=de(),it=Ee.parent&&!w.has("parent")||b.additions.some(se=>ks(se.kind,rt)),ye=await $s({pmRoot:o,author:v,ttlSeconds:s.locks.ttl_seconds,waitMs:s.locks.wait_ms,required:it});try{let se=await iM({fieldFlags:Ee,clearedMetadataKeys:w,pmRoot:o,settings:s,typeToFolder:u.type_to_folder}),He,$,Ve=await Rt({pmRoot:o,settings:s,typeToFolder:u.type_to_folder,id:e,op:MM(i,r),author:v,message:i.message,resolveHistoryContext:()=>$,force:i.force,bypassAssigneeConflict:i.ownershipMetadataBypass===!0||i.ownershipDependencyBypass===!0,extensionFieldNames:l,skipNoop:!0,async mutate(Ae){let ae=Ae.metadata.status;He=PM({document:Ae,recurrenceReason:r.recurrenceReason,requestedStatus:i.status,statusRegistry:a}),$=He?{recurrence:He}:void 0,se=se?.map(xi=>xi.id===Ae.metadata.id?structuredClone(Ae.metadata):xi);let Ai=NM(Ae,{options:i,settings:s,typeRegistry:u,statusRegistry:a,runtimeFieldRegistry:c,extensionRegistrations:d,extensionFieldNames:l,clearItemMetadataKeys:w,dependencyUpdates:b,dependencyRemovals:E,commentUpdates:O,noteUpdates:M,learningUpdates:T,fileUpdates:F,testUpdates:ue,docUpdates:Ne,resolvedParentValue:Me.resolvedParentValue,resolvedBlockedByDependencyId:qe,runtimeFieldUpdates:be,nowValue:k,nowIso:S,author:v,pmRoot:o});oM({before:se,document:Ae,statusRegistry:a});let ba=await Js({pmRoot:o,settings:s,metadata:Ae.metadata,fromStatus:ae,registry:a,force:i.force===!0});return{...Ai,warnings:[...Ai.warnings,...ba]}}});await ye();let Ut=se?bs(se,se.map(Ae=>Ae.id===Ve.item.id?Ve.item:Ae),Ve.item.id):[];return{item:Ve.item,changed_fields:Ve.changedFields,warnings:[...Ir("update",i,ct(i)==="sdk",Ve.item),...J,...re,...A,...Ut,...Ve.warnings],...He===void 0?{}:{lifecycle_transition:He}}}finally{await ye()}}function MM(e,t){return e.ownershipMetadataBypass===!0||e.ownershipDependencyBypass===!0?"update_ownership_bypass":t.recurrenceReason===void 0?"update":"reopen"}function PM(e){if(e.recurrenceReason===void 0)return;let t=ce(e.document.metadata.status,e.statusRegistry)??e.document.metadata.status;if(!fe(t,e.statusRegistry))throw new p(`Item ${e.document.metadata.id} is already active with status ${t}; recurrence transitions require a terminal item.`,m.CONFLICT,{code:"item_already_active",reason:"recurrence_requires_terminal_item",required:"Use item reopen only for a terminal item whose work has recurred.",why:"Appending a recurrence event to active work would corrupt lifecycle history.",recovery:{suggested_retry:`pm get ${e.document.metadata.id} --full`,suggested_retry_args:["get",e.document.metadata.id,"--full"]},nextSteps:[`Inspect the active item with: pm get ${e.document.metadata.id} --full`,`Continue the existing work with: pm update ${e.document.metadata.id} ...`]});let n=e.requestedStatus??e.statusRegistry.open_status,r=ce(n,e.statusRegistry)??n,i=e.document.metadata,o=Object.fromEntries(["close_reason","resolution","expected_result","actual_result","fixed_version"].flatMap(s=>{let a=i[s];return typeof a=="string"?[[s,a]]:[]}));return{reason:e.recurrenceReason,from_status:t,to_status:r,previous_terminal:o}}async function hi(e,t,n){return _k(e,t,n)}async function K3(e,t,n,r){Or(r,"reopen","reason");let i=await _k(e,t,n,{recurrenceReason:r});if(i.lifecycle_transition===void 0)throw new p(`Item ${e} did not produce the required recurrence receipt.`,m.GENERIC_FAILURE,{code:"reopen_receipt_missing",reason:"recurrence_transition_not_recorded",required:"A successful reopen must return the terminal-to-active lifecycle transition recorded in immutable history."});return{...i,lifecycle_transition:i.lifecycle_transition}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e32c9f13-2e6a-5ac6-a1ce-9c839121441a")}catch{}})();function ea(e,t){if(e.handoff===void 0)return;if(e.pause===!0)throw new p("--handoff cannot be combined with --pause. Choose a handoff queue or pause the item.",m.USAGE);let n=typeof e.handoff=="string"?Je(e.handoff,t):void 0;if(n===void 0||xt(n,t)||n===t.in_progress_status)throw new p("--handoff must name a configured non-terminal status distinct from the in-progress status. Inspect pm schema statuses or add a project queue with pm schema add-status <queue> --role active.",m.USAGE);if(typeof e.message!="string"||e.message.trim().length===0)throw new p("--handoff requires --message with implementation evidence and the next verification step.",m.USAGE);return n}function fk(e,t,n,r,i){if(xt(e.status,r)||!e.assignee?.trim())throw new p("Handoff requires a claimed, non-terminal item. Claim the active work before handing it off; use pm item reopen for completed work.",m.CONFLICT);let o=n.governance.workflow_enforcement??"off",s=or({enforcement:o,typeWorkflows:o==="off"?[]:Ln(n.schema),statusRegistry:r,typeName:e.type,fromStatus:e.status,toStatus:t}),a={from_status:e.status,to_status:t,message:i},c=e.status===t?[]:["status"];return e.status=t,{receipt:a,warnings:s?[s]:[],changedFields:c}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0b2ea0f6-b501-5004-9daf-73538023fa9b")}catch{}})();var hk="no_available_next_item",u8="stale_claim_takeover_refused";function gk(e){if(!(e instanceof Error)||e.name!=="PmCliError")return;let t=e.context;if(typeof t!="object"||t===null)return;let n=t.code;return typeof n=="string"?n:void 0}function yk(e,t){return gk(e)===t}function FM(e){return yk(e,"already_claimed_by")}async function Dl(e,t,n,r={}){let i=R(process.cwd(),n.path);await j(i);let o=await x(i),s=W(o.schema),a=U(r.author,o.author_default),c=Ka(a),d=r.takeoverStale===!0;UM(d,t);let l=null,u=!1,_={},h,f=[],g=await Rt({pmRoot:i,settings:o,id:e,op:"claim",author:a,message:r.message,force:t,skipNoop:!0,resolveHistoryContext:()=>h===void 0?void 0:{stale_claim_takeover:h},async mutate(w,v){let k=w.metadata.assignee??"",S=w.metadata.claim_principal?.trim()||k;if(l=k.trim().length>0?k:null,xt(w.metadata.status,s)&&!t)throw new p(`Cannot claim terminal item ${w.metadata.id} without --force`,m.CONFLICT);if(l!==null&&S!==c){let T=await jM({pmRoot:i,storageId:v.storageId,metadata:w.metadata,holder:k,author:a,thresholdHours:o.mutation_guard.stale_in_progress_hours,force:t,ifAvailable:r.ifAvailable===!0,takeoverStale:d});if(T.kind==="skip")return u=!0,f.push(`claim_skipped_held_by:${ja(k)}`),{changedFields:[]};h=T.takeover,f.push(T.warning)}let b={assignee:a,claim_principal:c},A=["assignee","claim_principal"].filter(T=>w.metadata[T]!==b[T]);Object.assign(w.metadata,b);let E=w.metadata.status,{changedFields:C,warnings:O,...M}=VM(w.metadata,r.start===!0,o,s);return O.push(...await HM({pmRoot:i,settings:o,metadata:w.metadata,fromStatus:E,registry:s,force:t,start:r.start===!0})),_=M,f.push(...O),{changedFields:[...A,...C],warnings:f}}}),y=wk(await vk("claim",g.item.id,n,u,()=>Ah({pmRoot:i,settings:o,principal:c,itemId:g.item.id})));return f.push(...y.warnings),{item:Fa(g.item),changed_fields:g.changedFields,claimed_by:u&&l!==null?Gi(l):a,previous_assignee:l===null?null:Gi(l),forced:t,...u?{skipped:!0}:{},...f.length>0?{warnings:f}:{},...Ll("suggestions",y.suggestions),..._,...h===void 0?{}:{takeover:h}}}async function jM(e){if(e.ifAvailable&&!e.takeoverStale)return{kind:"skip"};if(e.force)return{kind:"take",warning:`claim_takeover:${ja(e.holder)}->${e.author}`};let t=await Rh(e.pmRoot,e.storageId,e.holder,{updated_at:e.metadata.updated_at,threshold_hours:e.thresholdHours}),n=e.takeoverStale?GM(t,e.author):void 0;if(n!==void 0)return{kind:"take",warning:`claim_stale_takeover:${n.previous_holder}->${e.author}:idle_hours=${n.idle_hours}`,takeover:n};if(e.takeoverStale&&e.ifAvailable)return{kind:"skip"};throw WM(e.metadata.id,t,e.takeoverStale)}function UM(e,t){if(!(!e||!t))throw new p("--takeover-stale cannot be combined with --force",m.USAGE,{code:"ambiguous_option_combination",required:"Pass --takeover-stale to take over only an idle claim, or --force for a coordinated unconditional takeover.",nextSteps:["Drop --force to let the stale-work policy decide, or drop --takeover-stale for a coordinated override."]})}function GM(e,t){let n=e.activity;if(n.stale_policy.stale)return{previous_holder:e.holder,new_holder:t,claimed_at:e.since,last_activity_at:n.last_activity_at,idle_hours:n.idle_hours,threshold_hours:n.stale_policy.threshold_hours,policy:n.stale_policy.setting}}var qM={claim_record_unavailable:"no original history record shows when the holder took it",discarded_history_tail:"a history salvage after the claim discarded a record whose time is unknown",rewritten_history:"a history repair, redaction or merge reconcile after the claim rewrote its records",workspace_restored:"a workspace snapshot restore at or after the claim may have replaced the holder's work"};function KM(e,t){return t.history_unreadable===!0?{reason:"its history stream could not be read, so idleness cannot be established",nextStep:`Repair the history stream of ${e} (pm history ${e} --verify), then retry --takeover-stale.`}:t.unproven_activity!==void 0?{reason:`${qM[t.unproven_activity]}, so idleness cannot be proven`,nextStep:`Ask the holder to release ${e} (pm release ${e}); a new claim starts a provable record.`}:t.stale_policy.eligible_at===null?{reason:t.idle_hours===null?"no valid activity time is recorded":`idle ${t.idle_hours}h of ${t.stale_policy.threshold_hours}h`,nextStep:`No eligibility time can be computed for ${e}; inspect pm history ${e}.`}:{reason:`idle ${t.idle_hours}h of ${t.stale_policy.threshold_hours}h`,nextStep:`Retry with --takeover-stale after ${t.stale_policy.eligible_at} if nothing else is recorded on ${e}.`}}function WM(e,t,n){let r=t.activity,i=r.stale_policy,o={item_id:e,claimed_by:t.holder,claimed_at:t.since,claim_source:t.source,claim_activity:r},s="Claim is an atomic test-and-set so parallel agents never proceed believing they own the same item.",a="Re-run with --force only when taking over the item is coordinated.";if(n){let c=KM(e,r);return new p(`Item ${e} is ${t.phrase}, and its claim is not stale under ${i.setting} (${c.reason}).`,m.CONFLICT,{code:"stale_claim_takeover_refused",...o,required:`The claim must be idle for at least ${i.threshold_hours}h (${i.setting}) before --takeover-stale may take it.`,why:`${s} A stale takeover needs recorded evidence that the claim has been idle for the configured threshold, so an active claim is never taken over.`,nextSteps:[c.nextStep,"Run pm next to pick a different unclaimed item.",a]})}return new p(`Item ${e} is already ${t.phrase}. Use --force to take over, or --if-available to skip without failing.`,m.CONFLICT,{code:"already_claimed_by",...o,why:s,nextSteps:["Run pm next to pick a different unclaimed item.","Re-run with --if-available to treat a held item as a no-op skip.",...i.stale?[`Re-run with --takeover-stale: the claim has been idle ${r.idle_hours}h, past ${i.setting}=${i.threshold_hours}.`]:[],a]})}var zM="claim_semantic_attribution_unrecorded";function wk(e){return e?{warnings:[e.warning],suggestions:[e.suggestion]}:{warnings:[],suggestions:[]}}function Ll(e,t){return t.length>0?{[e]:t}:{}}var BM="release_semantic_attribution_unrecorded";async function vk(e,t,n,r,i){if(!r)try{await i();return}catch(o){let s=gk(o)??"unexpected_error",a=Ie(n);return{warning:e==="claim"?zM:BM,suggestion:`The ${e} of ${t} is saved, but the session attribution that names this agent's active work was not updated (${s}); nothing needs a retry. If ${L([...a,"health"])} reports a stale lock, remove it with ${L([...a,"gc","--scope","locks"])}.`}}}function m8(e,t,n=!1){let r=n?" --start":"";if(!t&&!e)throw new p(n?"pm claim --start needs an item id, or --next to start the next available item":"Specify an item id or pass --next",m.USAGE,{code:"missing_required_argument",field:"id",required:"Pass an item id, or --next to select the next available item.",nextSteps:[`Retry as pm claim <id>${r}, or pm claim --next${r}.`]});if(t&&e)throw new p("Specify either an item id or --next, not both",m.USAGE,{code:"ambiguous_option_combination",required:"Pass either an item id or --next.",nextSteps:[`Retry as pm claim ${e}${r} to claim that item, or drop the id to select with --next.`]})}async function HM(e){return e.start?Js(e):Vb(e)}function VM(e,t,n,r){if(!t)return{changedFields:[],warnings:[]};if(xt(e.status,r))throw new p(`Cannot start terminal item ${e.id}; reopen it with pm item reopen before starting it`,m.CONFLICT,{code:"terminal_state_conflict",item_id:e.id,why:"Starting work moves an active item into progress; a terminal item must be reopened so its recurrence evidence is recorded.",nextSteps:[`Run pm item reopen ${e.id} "<reason>", then pm claim ${e.id} --start.`]});let i=hn(r),o=n.governance.workflow_enforcement??"off",s=or({enforcement:o,typeWorkflows:o==="off"?[]:Ln(n.schema),statusRegistry:r,typeName:e.type,fromStatus:e.status,toStatus:i}),a={from_status:e.status,to_status:i},c=e.status===i?[]:["status"];return e.status=i,{start:a,changedFields:c,warnings:s?[s]:[]}}async function p8(e,t,n={},r={}){if(n.takeoverStale===!0)throw new p("--takeover-stale cannot be combined with --next",m.USAGE,{code:"ambiguous_option_combination",required:"Pass an explicit item id with --takeover-stale; --next only selects work no other author holds.",nextSteps:["Retry as pm claim <id> --takeover-stale for the held item, or drop --takeover-stale to select with --next."]});let i=YM(n.maxAttempts),o=await x(R(process.cwd(),t.path)),s={...n,author:U(n.author,o.author_default)},a=await Ih({...r,callerAuthor:s.author,limit:String(i)},t),c=[a.recommended,...a.ready].filter(d=>d!==null).map(d=>({...d,reasons:"reasons"in d?d.reasons:["ranked ready candidate"]}));return JM(c.slice(0,i),e,t,s)}function YM(e){if(e===void 0)return 10;let t=Number(e);if(!Number.isSafeInteger(t)||t<1||t>100)throw new p("--max-attempts must be an integer from 1 to 100",m.USAGE);return t}async function JM(e,t,n,r={},i=Dl){let o=0,s=[],a=()=>s.length>0?{start_refused:[...s]}:{};for(let c of e){o+=1;try{let d=await i(c.id,t,n,r),l={...d,recommendation:c,attempts:o,available:!0,...a()};if(!d.skipped)return l}catch(d){if(yk(d,Ys)){s.push(c.id);continue}if(!FM(d))throw d}}if(r.ifAvailable===!0)return{available:!1,item:null,claimed_by:U(r.author,""),previous_assignee:null,forced:t,skipped:!0,recommendation:null,attempts:o,...a(),warnings:[hk]};throw XM(o,s,r.start===!0)}function XM(e,t,n){let r=e===0,i="Every ranked candidate was claimed by another agent before this atomic selection completed.";return r?i="No ready items matched the specified filters or selection criteria.":t.length>0&&(i=`${t.length} of ${e} attempted candidates refused their start because a declared blocker is open (${t.join(", ")}), and nothing was written to them; ${t.length===e?"no other candidate was attempted":"every other attempted candidate was claimed by another agent"}.`),new p(r?"No actionable items matched the selection filters":"No actionable item remained available to claim",r?m.NOT_FOUND:m.CONFLICT,{code:hk,why:i,nextSteps:[r?"Verify the filters or run pm next to inspect all ready work.":`Run pm claim --next${n?" --start":""} again, with the same filters, to refresh the ranked candidate set.`],...t.length>0?{details:{start_refused:[...t]}}:{}})}async function ta(e,t,n,r={}){let i=R(process.cwd(),n.path);await j(i);let o=await x(i),s=U(r.author,o.author_default),a=Ka(s),c=r.ownershipReleaseBypass===!0,d=null,l=W(o.schema),u=ea(r,l);if(u!==void 0&&c)throw new p("Ownership-release bypass only clears ownership; it cannot change a handoff status.",m.USAGE);let _,h;try{h=await he({pmRoot:i,settings:o,id:e,op:"release",author:s,message:r.message,force:t,bypassAssigneeConflict:c,mutate(y){d=y.metadata.assignee??null;let w=u===void 0?void 0:fk(y.metadata,u,o,l,r.message);return _=w?.receipt,!d&&!y.metadata.claim_principal?{changedFields:[]}:(delete y.metadata.assignee,delete y.metadata.claim_principal,{changedFields:["assignee","claim_principal",...w?.changedFields??[]],warnings:w?.warnings})}})}catch(y){jr(y,{required:"For approved non-owner handoffs, prefer the ownership-release bypass before considering --force.",examples:['pm release pm-a1b2 --author "reviewer" --force'],nextSteps:["Use the package-provided ownership-release bypass for handoffs that only clear assignee metadata.","Use --force only when an explicit override is approved for broader ownership conflicts."]})}let f=wk(await vk("release",h.item.id,n,!1,()=>xh({pmRoot:i,principal:a,itemId:h.item.id}))),g=QM(h.item,l);return{item:Fa(h.item),released_by:s,changed_fields:h.changedFields,previous_assignee:d===null?null:Gi(d),forced:t,..._===void 0?{}:{handoff:_},...Ll("warnings",[...h.warnings,...g.warnings,...f.warnings]),...Ll("suggestions",[...g.suggestions,...f.suggestions])}}function QM(e,t){return Yt(e.status,t)===Yt(t.in_progress_status,t)?{warnings:["released_unclaimed_in_progress"],suggestions:[`${e.id} remains ${e.status} and unclaimed. If work is paused, run pm release ${e.id} --pause to move it to ${t.open_status}.`]}:{warnings:[],suggestions:[]}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a2aa0bed-59f8-5199-a167-0283a8801595")}catch{}})();async function $l(e,t,n){try{return await n()}catch(r){let i=r instanceof p?r.context:{},o=new p(r instanceof Error?r.message:String(r),r instanceof p?r.exitCode:m.GENERIC_FAILURE,{...i,item_id:e,why:`${t} completed for ${e} before the following step failed. No rollback was performed.${i.why?` ${i.why}`:""}`,nextSteps:[`Inspect the persisted state with pm get ${e} and pm history ${e} before retrying the failed step.`,...i.nextSteps??[]]});throw o.cause=r,o}}async function x8(e,t,n){if(t.next===!0||t.ifAvailable===!0)throw new p("--start cannot be combined with --next or --if-available for an explicit item",m.USAGE,{code:"invalid_argument_value",required:"Remove --next and --if-available when starting an explicit item.",nextSteps:["Remove --next and --if-available, keep the explicit item ID and other supplied arguments, then retry."]});let r=await x(R(process.cwd(),n.path)),i=hn(W(r.schema));return Hb(async()=>{let o=await Dl(e,t.force===!0,n,Eo(t,{},["start"])),s=o.item.id,a=await $l(s,"claim",()=>hi(s,Eo(t,{status:i},["assignee","start","next","ifAvailable","maxAttempts","takeoverStale"]),n)).catch(async c=>{throw await ZM(c,o,n,t.author)});return{id:s,action:"start_task",claim:o,update:a}})}async function ZM(e,t,n,r){if(!(e instanceof p)||e.code!==Ys||t.previous_assignee!==null)return e;let i=String(t.item.id);try{await xp({pmRoot:R(process.cwd(),n.path),id:i,validate:s=>{if(s.metadata.assignee!==t.claimed_by||s.metadata.claim_principal!==t.item.claim_principal)throw new p("The claim this start took is no longer its own.",m.CONFLICT)}},()=>ta(i,!1,n,{author:r,message:"Release the claim: a blocker opened before its start could be recorded"}))}catch{return e}let o=e.cause instanceof p?e.cause:e;return new p(o.message,o.exitCode,{...o.context,why:`${o.context.why??""} A blocker opened after this start's claim, so the claim was released and no ownership remains.`.trim()})}async function R8(e,t,n){let r=await x(R(process.cwd(),n.path)),i=W(r.schema);ea({...t,pause:!0},i);let o=i.open_status,s=await hi(e,Eo(t,{status:o},["assignee","pause"]),n),a=s.item.id,c=await $l(a,"update",()=>ta(a,t.force===!0,n,t));return{id:a,action:"pause_task",update:s,release:c}}async function I8(e,t,n,r){let i=await vs(e,t,n,r),o=i.item.id,s=await $l(o,"close",()=>ta(o,n.force===!0,r,n));return{id:o,action:"close_task",close:i,release:s}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="62b04ebf-f842-5a88-8817-ed9b17350034")}catch{}})();import gi from"node:crypto";import{cp as bk,lstat as eP,mkdir as yn,readFile as ar,readdir as Ml,rename as Ek,rm as Fl,writeFile as na}from"node:fs/promises";import q from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="66cb8c82-3760-5628-a1de-69e417cf0292")}catch{}})();var Tk="https://schema.unbrained.dev/pm/workspace-snapshot/v1",B8=["create","list","inspect","restore","delete"],Ck=q.join("runtime","workspace-snapshots"),tP=new Set(["checkpoints","locks","runtime","search","transactions"]),nP=/^[a-z0-9][a-z0-9._-]*$/,sr="sdk-workspace-transaction",Nl={capacity:{code:"workspace_snapshot_storage_exhausted"},permission:{code:"workspace_snapshot_permission_denied"},resource:{code:"workspace_snapshot_resource_exhausted"}},Ak={renameEntry:Ek,removeEntry:async e=>{await Fl(e,{recursive:!0,force:!0})}},Pl=class{lockPath;owner;intervalMs;timer;refresh;failure;constructor(t,n,r){this.lockPath=t,this.owner=n,this.intervalMs=Math.max(10,Math.floor(r*1e3/3))}start(){this.scheduleRenewal(),this.timer=setInterval(()=>{this.scheduleRenewal()},this.intervalMs),this.timer.unref()}async refreshNow(){this.scheduleRenewal(),await this.refresh,this.assertHealthy()}assertHealthy(){if(this.failure!==void 0)throw new Error("Workspace snapshot restore lost its writer lock",{cause:this.failure})}async stop(){this.timer!==void 0&&clearInterval(this.timer),await this.refresh,this.assertHealthy()}scheduleRenewal(){this.refresh!==void 0||this.failure!==void 0||(this.refresh=this.renew().catch(t=>{this.failure=t}).finally(()=>{this.refresh=void 0}))}async renew(){let t=await Im(this.lockPath,sr);if(t===null)throw new Error("Workspace writer lock cleanup gate stayed held");try{let n=JSON.parse(await ar(this.lockPath,"utf8"));if(typeof n!="object"||n===null||Array.isArray(n))throw new Error("Workspace writer lock has invalid structure");let r=n;if(r.id!==sr||r.owner!==this.owner||r.pid!==process.pid)throw new Error("Workspace writer lock ownership changed");await je(this.lockPath,`${JSON.stringify({...r,created_at:new Date().toISOString()},null,2)}
|
|
12
|
-
`)}finally{await t()}}};async function xk(e,t=""){let n=await
|
|
13
|
-
`).filter(t=>t.trim().length>0).length}async function rP(e,t){let n=new Map;for(let r=0;r<t.length;r+=32){let i=t.slice(r,r+32),o=await Promise.all(i.map(async s=>[s,await
|
|
14
|
-
`,"utf8"),await yn(q.dirname(o),{recursive:!0})}),s=await iP(a,o)}if(t.name!==void 0){let a={name:t.name,fingerprint:n.fingerprint},c=q.join(i,"refs");await yn(c,{recursive:!0});let d=q.join(c,`.ref-${process.pid}-${
|
|
15
|
-
`,"utf8"),await Ek(d,q.join(c,`${t.name}.json`))}return{manifest:n,...t.name===void 0?{}:{name:t.name},deduplicated:s}}async function
|
|
16
|
-
`)}var d6={commandForWorkspacePositionState:$k,normalizeWorkspaceHistoryDrift:Nk,selectWorkspacePositionState:Dk};import{createHash as mP}from"node:crypto";import{execFile as pP}from"node:child_process";import Fk from"node:path";import{promisify as _P}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ed03b6c8-6275-55a6-8e5f-4f27a23d6696")}catch{}})();var Mk=1;function uP(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.id=="string"&&typeof t.metric=="string"&&typeof t.value=="number"&&Number.isFinite(t.value)&&["higher","lower","target"].includes(String(t.direction))&&typeof t.observed_at=="string"&&typeof t.revision=="string"&&["caller","git","unversioned"].includes(String(t.revision_source))&&typeof t.author=="string"?t.direction!=="target"||typeof t.threshold=="number"&&Number.isFinite(t.threshold):!1}function
|
|
17
|
-
`,result:i})}});return{changed:s.changed,observation:s.result,ledger_path:"improvement-ledger.json"}}async function qk(e={}){let t=R(e.cwd??process.cwd(),e.pmRoot);await j(t);let n=e.metric===void 0?void 0:jk(e.metric),r=e.since===void 0?void 0:Uk(e.since,"since"),i=wP(e.limit),o=Gl(await Q(Fk.join(t,"improvement-ledger.json"))).observations.filter(a=>(n===void 0||a.metric===n)&&(e.itemId===void 0||a.item_id===e.itemId)&&(r===void 0||a.observed_at>=r)),s=new Map;for(let a of o){let c=s.get(a.metric)??[];c.push(a),s.set(a.metric,c)}return{observations:[...o].reverse().slice(0,i),total:o.length,truncated:o.length>i,trends:[...s].map(([,a])=>SP(a)).sort((a,c)=>a.metric.localeCompare(c.metric)),source:"audited_workspace_singleton"}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="28dd16ac-2e3b-55ed-98a6-db5f6786cbd7")}catch{}})();function EP(e){return e.agent_episode!==void 0?{id:e.agent_episode.id,source:"declared"}:{id:e.agent_instance?`inferred:instance:${e.agent_instance}`:`inferred:author:${e.author}:${e.ts.slice(0,13)}`,source:"inferred"}}function TP(e,t,n){let r=t,i=new Set([e.id]);for(;r!==void 0&&!i.has(r.id);)i.add(r.id),r=r.parent_id?n.get(r.parent_id):void 0;return r===void 0}function CP(e){let t=[e];for(;t.length>0;){let n=t.pop();n.sort((r,i)=>r.entries[0].ts.localeCompare(i.entries[0].ts)||r.id.localeCompare(i.id)),t.push(...n.map(r=>r.children))}}function Kk(e=kr,t=br){return t.map(n=>{let r=e.filter(i=>((n==="model"?i.model_environment_keys:i.provenance_environment_keys?.[n])?.length??0)>0||i.provenance_resolvers?.[n]!==void 0).map(i=>i.harness).sort();return{dimension:n,harnesses:r,covered:r.length>0}})}function O6(e,t=1){let n=new Map;for(let r of e){if(!r.agent_harness)continue;let i=n.get(r.agent_harness)??{harness:r.agent_harness,entries:0,observed:0,unavailable:0,legacy_missing:0};i.entries+=1,r.agent_model||r.agent_provenance?.model&&r.agent_provenance.model.value.length>0?i.observed+=1:r.agent_provenance?.model===null?i.unavailable+=1:i.legacy_missing+=1,n.set(r.agent_harness,i)}return[...n.values()].map(r=>{let i=r.observed+r.unavailable;return{...r,coverage:i===0?null:r.observed/i,inert:i>=t&&r.observed===0}}).sort((r,i)=>r.harness.localeCompare(i.harness))}function Wk(e,t=br,n=1){let r=new Map;for(let i of e)if(i.agent_harness)for(let o of t){let s=`${i.agent_harness}\0${o}`,a=r.get(s)??{harness:i.agent_harness,dimension:o,entries:0,observed:0,unavailable:0,legacy_missing:0};a.entries+=1;let c=i.agent_provenance?.[o];c!=null&&c.value.length>0?a.observed+=1:c===null?a.unavailable+=1:a.legacy_missing+=1,r.set(s,a)}return[...r.values()].map(i=>{let o=i.observed+i.unavailable;return{...i,coverage:o===0?null:i.observed/o,inert:o>=n&&i.observed===0}}).sort((i,o)=>i.harness.localeCompare(o.harness)||i.dimension.localeCompare(o.dimension))}function L6(e,t={}){let n=t.minimumCoverage??.8,r=t.minimumEntries??5;if(![Number.isFinite(n),n>=0,n<=1].every(Boolean))throw new RangeError("Semantic attribution minimum coverage must be from 0 to 1.");if(![Number.isSafeInteger(r),r>=1].every(Boolean))throw new RangeError("Semantic attribution minimum entries must be a positive integer.");let i=new Map;for(let c of e)if(c.agent_harness)for(let d of["role","topic"]){let l=`${c.agent_harness}\0${d}`,u=i.get(l)??{harness:c.agent_harness,dimension:d,entries:0,observed:0,by_source:{},coverage:0};u.entries+=1;let _=c.agent_provenance?.[d];_?.value&&(u.observed+=1,u.by_source[_.source]=(u.by_source[_.source]??0)+1),i.set(l,u)}let o=[...i.values()].map(c=>({...c,coverage:c.observed/c.entries,by_source:Object.fromEntries(Object.entries(c.by_source).sort(([d],[l])=>d.localeCompare(l)))})).sort((c,d)=>c.harness.localeCompare(d.harness)||c.dimension.localeCompare(d.dimension)),s=o.filter(c=>c.entries>=r),a=s.filter(c=>c.coverage<n).map(c=>`${c.harness}:${c.dimension}`);return{passed:s.length>0&&a.length===0,minimum_coverage:n,minimum_entries:r,rows:o,failures:a}}function D6(e){let t=[...e].sort((o,s)=>o.ts.localeCompare(s.ts)||o.author.localeCompare(s.author)||o.op.localeCompare(s.op)||o.before_hash.localeCompare(s.before_hash)||o.after_hash.localeCompare(s.after_hash)),n=new Map,r=new Map;for(let o of t){let s=o.agent_episode,a=EP(o),c=`${a.source}:${a.id}`,d=n.get(c);if(d){d.entries.push(o);continue}let l={id:a.id,...s?.label===void 0?{}:{label:s.label},...s?.parent_id===void 0?{}:{parent_id:s.parent_id},source:a.source,entries:[o],children:[]};n.set(c,l),s!==void 0&&r.set(a.id,l)}let i=[];for(let o of n.values()){let s=o.parent_id?r.get(o.parent_id):void 0;s&&TP(o,s,r)?s.children.push(o):i.push(o)}return CP(i),i}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6b51fdd9-9923-53c5-a798-41c15fd847a0")}catch{}})();var AP=1e4,zk=1e5,xP=1e3,RP=30,IP=["append","comment","docs","file","learning","note","test_run"];function OP(e){let t=e??AP;if(!Number.isSafeInteger(t)||t<1||t>zk)throw new p(`History analytics event limit must be an integer from 1 to ${zk}.`,m.USAGE,{code:"invalid_history_analytics_limit"});return t}function Bk(e){let t=e??5;if(!Number.isSafeInteger(t)||t<1||t>1e4)throw new p("History analytics minimum sample must be an integer from 1 to 10000.",m.USAGE,{code:"invalid_history_analytics_minimum_sample"});return t}function LP(e){let t=e?.trim();if(!t)return new Date(Date.now()-RP*864e5).toISOString();let n=/^-(\d+)([dh])$/u.exec(t);if(n){let i=Number(n[1]),o=n[2]==="d"?864e5:36e5;if(!Number.isSafeInteger(i)||i<1)throw new p("History analytics --since duration must be positive.",m.USAGE,{code:"invalid_history_analytics_since"});return new Date(Date.now()-i*o).toISOString()}let r=Date.parse(t);if(!Number.isFinite(r))throw new p("History analytics --since must be an ISO timestamp or negative duration such as -30d.",m.USAGE,{code:"invalid_history_analytics_since"});return new Date(r).toISOString()}async function ra(e,t){let n=OP(t.eventLimit),r=LP(t.since),i=[],o=r,s=!1;for(;i.length<n;){let a=await Oh({pmRoot:e,since:o,limit:Math.min(xP,n-i.length),full:!0}),c=a.events.map(d=>({item_id:d.item_id,entry:d.entry}));if(i.push(...c),s=a.has_more,o=a.next_cursor,!a.has_more)break}return{events:i,receipt:{since:r,events:i.length,truncated:s,...s?{next_cursor:o}:{},source:"history_event_index"}}}function DP(e,t){return t==="harness"?e.agent_harness:t==="author_source"?e.author_source:e.agent_model??e.agent_provenance?.model?.value}function $P(e){for(let t=e.patch.length-1;t>=0;t-=1){let n=e.patch[t];if(n.path==="/metadata/status"&&"value"in n&&typeof n.value=="string")return n.value}}function NP(e){return IP.some(t=>e.startsWith(t))}function Hk(e,t){let n=e.get(t);if(n)return n;let r={events:0,stateEvents:0,annotationEvents:0,closes:0,reopens:0,defectEscapes:0};return e.set(t,r),r}function MP(e,t,n){let r=new Map,i=new Map,o=new Map;for(let s of t){let a=DP(s.entry,e),c=$P(s.entry),d=i.get(s.item_id)===!0,l=c===void 0?d:n.has(c);if(c!==void 0&&i.set(s.item_id,l),!a)continue;let u=Hk(r,a);u.events+=1,NP(s.entry.op)?u.annotationEvents+=1:u.stateEvents+=1,c!==void 0&&!d&&l?(u.closes+=1,o.set(s.item_id,a)):c!==void 0&&d&&!l&&(u.reopens+=1)}return{buckets:r,lastCloseValue:o}}function PP(e,t,n){for(let r of n){if(r.type!=="Issue")continue;let i=new Set((r.dependencies??[]).filter(o=>o.kind==="discovered_from").map(o=>o.id));for(let o of i){let s=t.get(o);s&&(Hk(e,s).defectEscapes+=1)}}}function FP(e,t,n,r){let i=t.closes>=n?"available":"insufficient";return{value:e,events:t.events,state_events:t.stateEvents,annotation_events:t.annotationEvents,closes:t.closes,reopens:t.reopens,defect_escapes:t.defectEscapes,throughput_per_day:i==="available"?t.closes/r:null,rework_rate:i==="available"?t.reopens/t.closes:null,defect_escape_rate:i==="available"?t.defectEscapes/t.closes:null,sample_status:i}}function jP(e,t,n,r,i,o){let{buckets:s,lastCloseValue:a}=MP(e,t,r);return PP(s,a,n),{dimension:e,status:s.size===0?"unavailable":"available",rows:[...s].map(([c,d])=>FP(c,d,i,o)).sort((c,d)=>d.events-c.events||c.value.localeCompare(d.value))}}function UP(e,t){let n=e[0]?.entry.ts??t,r=e[e.length-1]?.entry.ts??n,i=Date.parse(n),o=Date.parse(r);return!Number.isFinite(i)||!Number.isFinite(o)?1:Math.max(1,(o-i)/864e5)}function GP(e,t,n){let r=Kk(t),i=Wk(e,br,n),o=i.filter(a=>a.inert).map(a=>({harness:a.harness,dimension:a.dimension,explicit_samples:a.observed+a.unavailable})),s=r.filter(a=>!a.covered).map(a=>a.dimension);return{descriptors:r,observations:i,inert:o,undeclared:s,warnings:[...o.map(a=>`provenance_dimension_inert:${a.harness}:${a.dimension}:${String(a.explicit_samples)}`),...s.map(a=>`provenance_dimension_undeclared:${a}`)]}}async function U6(e,t=kr,n={}){return ql(await ra(e,n),t,n)}function ql(e,t=kr,n={}){let r=Bk(n.minimumSample);return{...GP(e.events.map(i=>i.entry),t,r),window:e.receipt}}async function G6(e,t,n,r={}){return Kl(await ra(e,r),t,n,r)}function Kl(e,t,n,r={}){let i=Bk(r.minimumSample),o=UP(e.events,e.receipt.since);return{dimensions:["harness","model","author_source"].map(s=>jP(s,e.events,t,n,i,o)),minimum_sample:i,policy:"observational_only_not_for_authorization_or_routing",window:e.receipt}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3e70310d-fc4f-5ea9-b9fb-7c519035301b")}catch{}})();var qP=32;function KP(e){let t=[];for(let n of e??[]){let r=[];for(let i of n.split(",")){let o=i.slice(0,i.indexOf("=")).trim();r.length>0&&o!=="unit"&&o!=="threshold"&&(t.push(r.join(",")),r=[]),r.push(i)}t.push(r.join(","))}return t}function wi(e,t){let n=KP(e).map(r=>{let[i,...o]=r.split(","),s=i.indexOf("="),a=i.slice(0,s).trim(),c=i.slice(s+1).trim(),d=Number(c);if(s<=0||a.length===0||c.length===0||!Number.isFinite(d))throw new p(`Invalid --measure "${r}"; expected name=value[,unit=...][,threshold=...]`,m.USAGE);let l,u;for(let _ of o){let h=_.indexOf("="),f=_.slice(0,h).trim(),g=_.slice(h+1).trim();if(f==="unit"&&g.length>0)l=g;else if(f==="threshold"&&g.length>0&&Number.isFinite(Number(g)))u=Number(g);else throw new p(`Invalid --measure attribute "${_}"`,m.USAGE)}return{name:a,value:d,unit:l,threshold:u,recorded_at:t}});return[...new Map(n.map(r=>[r.name,r])).values()].sort((r,i)=>r.name.localeCompare(i.name)).slice(0,qP)}function Vk(e,t,n){return e.flatMap(r=>(r.measurements??[]).filter(i=>i.name===t&&i.value<n).map(i=>({...i,run_id:r.run_id})))}function Yk(e,t){let n=e.flatMap(o=>o.measurements??[]).filter(o=>o.name===t).sort((o,s)=>s.recorded_at.localeCompare(o.recorded_at)),r=n[0],i=n[1];return{name:t,latest:r?.value??null,previous:i?.value??null,delta:r!==void 0&&i!==void 0?r.value-i.value:null,unit:r?.unit}}import zP from"node:fs/promises";import Xk from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9cd23db4-2411-5c95-a6a0-fa30dd3a9a18")}catch{}})();function ia(e,t,n,r,i,o="min"){let s=i==="min"?e-t:t-e,a=o==="min"?n.localeCompare(r??n):(r??n).localeCompare(n);return s<0||s===0&&r!==null&&a<0}function WP(e,t){let n=Buffer.byteLength(t,"utf8"),r=0,i=null,o=null,s=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY;for(let c of t.split(/\r?\n/)){let d=c.trim();if(d==="")continue;r+=1;let l;try{l=JSON.parse(d)}catch{continue}if(l===null||typeof l!="object"||!("ts"in l)||typeof l.ts!="string")continue;let u=l.ts,_=Date.parse(u);Number.isNaN(_)||(ia(_,s,u,i,"min")&&(s=_,i=u),ia(_,a,u,o,"max","max")&&(a=_,o=u))}return{id:e,bytes:n,lines:r,oldest_ts:i,newest_ts:o}}function Jk(e,t){let n=t?.topN??5,r=Math.max(0,Math.floor(n)),i=e.map(({id:h,raw:f})=>WP(h,f)),o=0,s=0,a=null,c=null,d=Number.POSITIVE_INFINITY,l=Number.NEGATIVE_INFINITY;for(let h of i){if(o+=h.lines,s+=h.bytes,h.oldest_ts!==null){let f=Date.parse(h.oldest_ts);ia(f,d,h.id,a?.id??null,"min")&&(d=f,a={id:h.id,ts:h.oldest_ts})}if(h.newest_ts!==null){let f=Date.parse(h.newest_ts);ia(f,l,h.id,c?.id??null,"max")&&(l=f,c={id:h.id,ts:h.newest_ts})}}let u=r===0?[]:[...i].sort((h,f)=>f.bytes-h.bytes||h.id.localeCompare(f.id)).slice(0,r),_=r===0?[]:[...i].sort((h,f)=>f.lines-h.lines||h.id.localeCompare(f.id)).slice(0,r);return{total_streams:e.length,total_lines:o,total_bytes:s,largest_by_bytes:u,deepest_by_lines:_,oldest_entry:a,newest_entry:c}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b9d089ef-bca9-547f-a860-4002ec181cd0")}catch{}})();function BP(e){return e.reduce((t,n)=>(t[n]=0,t),{})}function HP(e,t,n,r,i){let o=Dr(e,"type",r),s=new Set(o.rows.map(u=>u.key)),a=t.filter(u=>!s.has(u)),c=(i?[...o.rows,...a.map(u=>({label:u,key:u,total:0,buckets:{open:0,in_progress:0,blocked:0,draft:0,closed:0,canceled:0,other:0}}))]:o.rows).map(u=>({type:u.key??u.label,total:u.total,open:u.buckets.open,in_progress:u.buckets.in_progress,blocked:u.buckets.blocked,draft:u.buckets.draft,closed:u.buckets.closed,canceled:u.buckets.canceled,other:u.buckets.other})),d=BP([...n]);for(let u of e)d[u.status]+=1;let l=Object.fromEntries(Object.entries(d).filter(([,u])=>i||u>0));return{byType:c,byStatus:l,omitted:i?0:a.length+Object.values(d).filter(u=>u===0).length}}function VP(e){return e.trim().length===0?0:e.split(/\r?\n/u).filter(t=>t.trim().length>0).length}async function YP(e){let t=Xk.join(e,"history");if(!await ie(t))return[];await We({path:t,scope:"project"});let n=(await zP.readdir(t)).filter(i=>i.endsWith(".jsonl")).sort((i,o)=>i.localeCompare(o)),r=[];for(let i of n){let o=Xk.join(t,i),s=await Q(o);s!==null&&(await We({path:o,scope:"project"}),r.push({id:i.slice(0,-6),raw:s}))}return r}async function JP(e,t){let n=[],r=I();for(let i of wi(t.observe,r))n.push(await Gk({metric:i.name,value:i.value,direction:t.direction,unit:i.unit,threshold:i.threshold,source:t.measurementSource,itemId:t.measurementItem,revision:t.measurementRevision,observedAt:r,author:t.author,message:t.message},e));return n}function XP(e,t,n){let r={};return t.byAssignee&&(r.assignee=Dr(e,"assignee",n)),t.byTag&&(r.tag=Dr(e,"tag",n,{tagPrefix:t.tagPrefix})),t.byPriority&&(r.priority=Dr(e,"priority",n)),r}async function QP(e,t,n,r,i){let o={since:i.since,eventLimit:i.eventLimit,minimumSample:i.minimumSample},s=i.provenanceCoverage||i.fleetAttribution?await ra(e,o):void 0;return{provenanceCoverage:i.provenanceCoverage&&s?ql(s,n.agent_identity?.harness_signals,o):void 0,fleetAttribution:i.fleetAttribution&&s?Kl(s,t,r,o):void 0}}function ZP(e,t,n,r,i){let o=Object.keys(i.breakdowns).length>0;return{totals:e,by_type:t,by_status:n,omitted_zero_buckets:r,...i.metadataCoverage?{metadata_coverage:i.metadataCoverage}:{},...o?{breakdowns:i.breakdowns}:{},...i.storage?{storage:i.storage}:{},...i.fieldUtilization?{field_utilization:i.fieldUtilization}:{},...i.improvementLedger?{improvement_ledger:i.improvementLedger}:{},...i.recordedObservations.length>0?{recorded_observations:i.recordedObservations}:{},...i.provenanceCoverage?{provenance_coverage:i.provenanceCoverage}:{},...i.fleetAttribution?{fleet_attribution:i.fleetAttribution}:{},generated_at:I()}}async function l9(e,t={}){let n=R(process.cwd(),e.path);await j(n);let r=await x(n),i=await JP(e,t),o=P(r,N()),s=W(r.schema),a=t.fieldUtilization?await gt(n,r.item_format,o.type_to_folder,void 0,r.schema):await Te(n,r.item_format,o.type_to_folder,void 0,r.schema);await oo({pmRoot:n,settings:r,itemIds:a.map(k=>k.id),commandLabel:"stats"});let c=oh(s),d=HP(a,o.types,s.definitions.map(k=>k.id),c,t.includeEmpty===!0),l=await YP(n),u=0;for(let k of l)u+=VP(k.raw);let _=t.storage?Jk(l):void 0,h=t.metadataCoverage?sh(a,c):void 0,f=XP(a,t,c),g=t.fieldUtilization?ah(a):void 0,y=t.measurements===!0||i.length>0?await qk({pmRoot:n,metric:t.metric,itemId:t.measurementItem,limit:t.measurementLimit}):void 0,{provenanceCoverage:w,fleetAttribution:v}=await QP(n,a,r,s.terminal_statuses,t);return ZP({items:a.length,history_streams:l.length,history_entries:u},d.byType,d.byStatus,d.omitted,{metadataCoverage:h,breakdowns:f,storage:_,fieldUtilization:g,improvementLedger:y,recordedObservations:i,provenanceCoverage:w,fleetAttribution:v})}import e1 from"node:fs/promises";import Tt from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bc3145a3-5949-5c61-b275-a5376881b91f")}catch{}})();var n0=Tt.join("runtime","telemetry","state.json"),vi=Tt.join("runtime","telemetry"),t1=20,Bl=Kt.filter(e=>e.lifecycle==="deprecated"),Qk=["status","flush","stats","clear"],Zk=(e,t)=>{let n=Math.ceil(t*e.length),r=Math.min(e.length-1,Math.max(0,n-1));return e[r]},Wl=(e,t)=>typeof e!="string"?t:e.trim().length>0?e:t,e0=e=>{if(!(typeof e!="number"||!Number.isFinite(e)))return Math.trunc(e)},n1=e=>({command:Wl(e.event.command,"<unknown>"),eventType:Wl(e.event.event_type,"unknown"),eventSchemaVersion:e0(e.event.schema_version),clientSchemaVersion:e0(e.client_schema_version)}),r1=()=>({count:0,max_attempts:0,event_type_counts:{},event_schema_versions:new Set,client_schema_versions:new Set,finish_durations_ms:[],ok_count:0,error_count:0,resolution_counts:{}}),i1=e=>{let t=e?.duration_ms;return typeof t=="number"&&Number.isFinite(t)?t:void 0},o1=e=>{let t=e?.command_resolution;return Wl(t,"")||void 0},r0=(e,t)=>{e[t]=(e[t]??0)+1},s1=(e,t)=>{let n=i1(t);n!==void 0&&e.finish_durations_ms.push(n),t?.ok===!0?e.ok_count+=1:e.error_count+=1;let r=o1(t);r!==void 0&&r0(e.resolution_counts,r)},a1=e=>Number.isFinite(e)?Math.max(0,Math.trunc(e)):0,t0=(e,t)=>{t!==void 0&&e.add(t)},c1=(e,t)=>{let n=n1(t),r=e.get(n.command)??r1();r.count+=1,r.max_attempts=Math.max(r.max_attempts,a1(t.attempts)),r0(r.event_type_counts,n.eventType),t0(r.event_schema_versions,n.eventSchemaVersion),t0(r.client_schema_versions,n.clientSchemaVersion),n.eventType==="command_finish"&&s1(r,t.event.payload),e.set(n.command,r)},d1=(e,t)=>{let n=t.ok_count+t.error_count,r=[...t.finish_durations_ms].sort((o,s)=>o-s),i=Object.entries(t.resolution_counts).sort((o,s)=>o[0].localeCompare(s[0]));return{command:e,count:t.count,event_type_counts:Object.fromEntries(Object.entries(t.event_type_counts).sort((o,s)=>o[0].localeCompare(s[0]))),max_attempts:t.max_attempts,event_schema_versions:[...t.event_schema_versions].sort((o,s)=>o-s),client_schema_versions:[...t.client_schema_versions].sort((o,s)=>o-s),...r.length>0?{duration_p50_ms:Zk(r,.5),duration_p95_ms:Zk(r,.95),duration_max_ms:r[r.length-1]}:{},...n>0?{ok_count:t.ok_count,error_count:t.error_count,error_rate:t.error_count/n}:{},...i.length>0?{command_resolution_counts:Object.fromEntries(i)}:{}}},l1=e=>{let t=(e??"status").trim().toLowerCase();if(Qk.includes(t))return t;throw Hi({command_path:"telemetry",token:e?.trim()||"<empty>",allowed:Qk,examples:["pm telemetry status","pm telemetry flush","pm telemetry stats --limit 10","pm telemetry clear"]})},Hl=()=>{throw new p("--limit must be a positive integer",m.USAGE)},i0=e=>[!Number.isFinite(e),!Number.isInteger(e),e<=0].includes(!0)?Hl():e,u1=e=>{let t=e.trim();return[t.length===0,!/^\d+$/.test(t)].includes(!0)?Hl():i0(Number.parseInt(t,10))},m1=e=>e===void 0?t1:typeof e=="number"?i0(e):typeof e=="string"?u1(e):Hl(),p1=e=>{if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.attempts=="number"&&typeof t.event=="object"&&t.event!==null},_1=e=>{try{let t=JSON.parse(e);return p1(t)?t:void 0}catch{return}},f1=e=>e===null?[]:e.split(`
|
|
18
|
-
`).map(t=>t.trim()).filter(t=>t.length>0),o0=e=>{let t=f1(e),n=[],r=0;for(let i of t){let o=_1(i);o===void 0?r+=1:n.push(o)}return{rows_total:t.length,valid_entries:n.length,invalid_rows:r,entries:n}},h1=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),g1=e=>{try{let t=JSON.parse(e);return h1(t)?t:{}}catch{return{}}},
|
|
19
|
-
`)},e,250)}catch{}return o}async function E9(e){let t=
|
|
20
|
-
`),!0},n,250)}catch{return!1}}var oa=e=>e??null,aa=async e=>{let t=await x(e),n=Tt.join(e,vi,It("events.jsonl")),r=Tt.join(e,vi,It("state.json")),i=await Q(n),o=o0(i),s=await sa(r),a=Zt();return{enabled:t.telemetry.enabled&&!a.telemetry_disabled,configured_enabled:t.telemetry.enabled,env_overrides:a,endpoint:Ot(Ar(t.telemetry.endpoint)),queue_path:n,state_path:r,queue_rows_total:o.rows_total,queue_entries:o.valid_entries,queue_invalid_rows:o.invalid_rows,queue_size_bytes:Buffer.byteLength(i??"","utf8"),last_attempted_flush_at:oa(s.last_attempted_flush_at),last_successful_flush_at:oa(s.last_successful_flush_at),last_failed_flush_at:oa(s.last_failed_flush_at),last_failed_flush_error:oa(s.last_failed_flush_error)}},v1=e=>{let t=new Map;for(let n of e)c1(t,n);return[...t.entries()].map(([n,r])=>d1(n,r)).sort((n,r)=>r.count-n.count||n.command.localeCompare(r.command))},b1=async(e,t)=>({action:"telemetry",subcommand:"status",status:await aa(t.globalPmRoot),generated_at:I()}),k1=async(e,t)=>{let n=await aa(t.globalPmRoot);await Jp(t.globalPmRoot);let r=await aa(t.globalPmRoot),i=Math.max(0,n.queue_entries-r.queue_entries),o=r.queue_entries===0;return{action:"telemetry",subcommand:"flush",queue_entries_before:n.queue_entries,queue_entries_after:r.queue_entries,queue_entries_drained:i,queue_progressed:i>0,queue_empty:o,queue_drained:o,status:r,generated_at:I()}},S1=async(e,t)=>{let n=m1(e.limit),r=await Q(t.queuePath),i=o0(r),o=v1(i.entries),s=o.slice(0,n),a=await x(t.globalPmRoot),c=await w1(t.globalPmRoot,Tt.join(t.globalPmRoot,n0),a.telemetry.retention_days),d=Object.entries(c).map(([l,u])=>{let _=Object.values(u.days);return{alias:l,canonical:u.canonical,count:_.reduce((h,f)=>Math.min(Number.MAX_SAFE_INTEGER,h+f.count),0),last_seen:_.map(h=>h.last_seen).sort().at(-1)}}).sort((l,u)=>u.count-l.count||l.alias.localeCompare(u.alias));return{action:"telemetry",subcommand:"stats",limit:n,total_commands:o.length,queue_entries:i.valid_entries,queue_invalid_rows:i.invalid_rows,queue_rows_total:i.rows_total,truncated:o.length>s.length,stats:s,alias_usage:d,zero_use_aliases:Bl.map(l=>l.alias).filter(l=>c[l]===void 0),alias_usage_retention_days:a.telemetry.retention_days,generated_at:I()}},E1=async(e,t)=>fo(async()=>{let n=await x(t.globalPmRoot),r=[n.telemetry.enabled!==!1,n.telemetry.installation_id!=="",n.telemetry.first_run_prompt_completed!==!0].includes(!0);n.telemetry.enabled=!1,n.telemetry.first_run_prompt_completed=!0,n.telemetry.installation_id="",r&&await Ep(t.globalPmRoot,n,"telemetry:clear");let i=Tt.join(t.globalPmRoot,vi),o=await ie(i);return await e1.rm(i,{recursive:!0,force:!0}),{action:"telemetry",subcommand:"clear",settings_changed:r,runtime_dir_removed:o&&!await ie(i),queue_exists_after:await ie(t.queuePath),state_exists_after:await ie(t.statePath),status:await aa(t.globalPmRoot),generated_at:I()}},t.globalPmRoot),T1={status:b1,flush:k1,stats:S1,clear:E1};async function T9(e,t){let n=l1(e.subcommand),r=Ye(process.cwd());return T1[n](e,{globalPmRoot:r,queuePath:Tt.join(r,vi,It("events.jsonl")),statePath:Tt.join(r,vi,It("state.json"))})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7140bb24-7202-541a-bc13-6a67bac260a8")}catch{}})();var a0=100;function cr(e,t="--only-index"){let n=typeof e=="number"?e:Number(String(e).trim());if(!Number.isInteger(n)||n<1)throw new p(`${t} requires a 1-based integer index into the linked-test list (got "${e}"). Use pm test <id> --list to inspect positions.`,m.USAGE);return n}function C1(e){let t=(e.command??e.path??"<no command>").replaceAll(/\s+/g," ").trim()||"<no command>";return t.length<=a0?t:`${t.slice(0,a0-3)}...`}function c0(e){return e.map((t,n)=>`${n+1}. ${C1(t)}`).join("; ")}function A1(e){let t=[];return e.match!==void 0&&t.push("match"),e.onlyIndex!==void 0&&t.push("only-index"),e.onlyLast===!0&&t.push("only-last"),t}function x1(e,t){let n=e.command?.toLowerCase()??"",r=e.path?.toLowerCase()??"";return n.includes(t)||r.includes(t)}function d0(e,t){let n=A1(t);if(n.length===0)return{selector:null,requested:null,selected:e,selected_indexes:e.map((i,o)=>o+1),selected_count:e.length,skipped_count:0};if(n.length>1)throw new p(`Combine at most one linked-test selector per run: ${n.map(i=>`--${i}`).join(" and ")} were provided. Pick one of --match, --only-index, --only-last.`,m.USAGE);let r=n[0];if(e.length===0)throw new p(`--${r} matched no linked tests because this item has none. Add one first with --add, --command, or --add-json.`,m.USAGE);if(r==="match"){let i=t.match.trim().toLowerCase();if(i.length===0)throw new p("--match requires a non-empty substring to match against linked-test command/path values",m.USAGE);let o=[],s=[];for(let a=0;a<e.length;a+=1)x1(e[a],i)&&(s.push(e[a]),o.push(a+1));if(s.length===0)throw new p(`--match "${t.match}" matched none of the ${e.length} linked test(s). Available entries: ${c0(e)}`,m.USAGE);return{selector:"match",requested:t.match,selected:s,selected_indexes:o,selected_count:s.length,skipped_count:e.length-s.length}}if(r==="only-index"){let i=cr(t.onlyIndex);if(i>e.length)throw new p(`--only-index ${i} is out of range: this item has ${e.length} linked test(s). Available entries: ${c0(e)}`,m.USAGE);return{selector:"only-index",requested:String(i),selected:[e[i-1]],selected_indexes:[i],selected_count:1,skipped_count:e.length-1}}return{selector:"only-last",requested:"last",selected:[e[e.length-1]],selected_indexes:[e.length],selected_count:1,skipped_count:e.length-1}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f75d72fe-b7f5-576d-b6c1-1cd94e3288b3")}catch{}})();var Vl=["command","cmd"],bi=Object.freeze(ft.filter(e=>!["command","cmd","timeout"].includes(e)));function l0(e){if(e.update===void 0&&e.updateIndex===void 0&&e.setJson===void 0)return;if(e.update===void 0==(e.updateIndex===void 0)||e.setJson===void 0)throw new p("Use exactly one --update or --update-index with --set-json",m.USAGE);let t;try{t=JSON.parse(e.setJson)}catch{throw new p("--set-json must contain a JSON object with explicit linked-test metadata fields",m.USAGE)}if(e.updateIndex!==void 0)return{selector:{index:cr(e.updateIndex,"--update-index")},patch:t};let n=e.update,r=/^(command|path)=/u.exec(n);return{selector:r?.[1]==="path"?{path:n.slice(r[0].length)}:{command:r?n.slice(r[0].length):n},patch:t}}function u0(e){if([e.list,e.run,e.progress,e.timeout!==void 0,e.acknowledgeLinkedTests,e.metricBelow!==void 0,e.metricDiff!==void 0,(e.add?.length??0)>0,(e.addJson?.length??0)>0,(e.remove?.length??0)>0,(e.removeIndex?.length??0)>0].some(Boolean))throw new p("Edit linked-test metadata separately from listing, additions, removals, execution options, metric filters and trust acknowledgement",m.USAGE)}function R1(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new p("Select one linked test by index, command, or path",m.USAGE);let n=Object.keys(t);if(n.length!==1||!["index","command","path"].includes(n[0]))throw new p("Select one linked test by index, command, or path",m.USAGE);if("index"in t){let r=cr(t.index,"--update-index");if(r<=e.length)return r-1}else{let r="command"in t?"command":"path",i="command"in t?t.command:t.path;if(typeof i!="string"||i.trim().length===0)throw new p("Linked-test selector must be a non-empty command or path",m.USAGE);let o=e.flatMap((s,a)=>s[r]===i?[a]:[]);if(o.length===1)return o[0];if(o.length>1)throw new p(`Linked-test selector is ambiguous; matching indexes: ${o.map(s=>s+1).join(", ")}`,m.USAGE,{code:"linked_test_update_ambiguous",required:"List linked tests and select one current --update-index."})}throw new p("No linked test matched the update selector",m.NOT_FOUND,{code:"linked_test_update_no_match",required:"List linked tests and select a current command, path, or --update-index."})}function m0(e,t){let n=Object.keys(e),r=n.filter(i=>!bi.includes(i));if(n.length===0&&!t||r.length>0)throw new p("Patch explicit linked-test metadata fields; command, aliases and provenance cannot be edited",m.USAGE,{code:"linked_test_patch_fields_unsupported",changed:!1,...r.length>0?{field:r[0]}:{},required:`Patch at least one editable field: ${bi.join(", ")}.`,recovery:{allowed_values:[...bi]},...r.length>0?{nextSteps:[`Remove unsupported field(s) from --set-json: ${r.join(", ")}.`]}:{}});if(e.scope===null)throw new p("scope is required and cannot be cleared",m.USAGE)}function I1(e,t,n){let r={};for(let i of bi){let o=t[i]!==void 0?t[i]:e[i];o!=null&&(r[i]=o)}return{command:n,...r}}function ca(e){return{field:e,changed:!1,required:"Replace the entry instead: remove the selected linked test and add the new command in one pm test invocation, which records fresh provenance."}}function O1(e,t,n){let r=Vl.filter(o=>Object.hasOwn(e,o)).map(o=>e[o]),i=typeof e[t]=="string"?e[t].trim():"";if(r.length>1&&r.some(o=>typeof o!="string"||o.trim()!==i))throw new p("--set-json sets command and cmd to different values; send one command",m.USAGE,{code:"linked_test_command_immutable",...ca(t),nextSteps:["Send the replacement command once, as command."]});if(i.length===0||i===n.command)throw new p(i.length===0?`--set-json cannot set ${t}: a linked test's command is its immutable identity`:`--set-json ${t} repeats the selected entry's command; omit it to edit only metadata`,m.USAGE,{code:"linked_test_command_immutable",...ca(t),nextSteps:[`Patch only editable fields: ${bi.join(", ")}.`]});return ni(i),i}function L1(e){let{id:t,tests:n,index:r,identityKey:i,otherFields:o,requested:s,global:a}=e;m0(o,!0);let c=I1(n[r],o,s),d=pi(JSON.stringify(c),"--add-json")[0];gr(d);let l=n.findIndex((u,_)=>_!==r&&yr(u,d));if(l>=0)throw new p(`--set-json cannot change ${i}: linked test ${l+1} already has the requested identity, so a replacement would merge into it`,m.USAGE,{code:"linked_test_command_immutable",...ca(i),nextSteps:[`Edit linked test ${l+1} instead: ${L([...Ie(a),"test",t,"--update-index",String(l+1),"--set-json","<editable fields>"])}`,`Or drop the selected entry: ${L([...Ie(a),"test",t,"--remove-index",String(r+1)])}`]});return c}function D1(e){return[...e.author!==void 0?["--author",e.author]:[],...e.message!==void 0?["--message",e.message]:[],...e.force===!0?["--force"]:[]]}function $1(e){let{id:t,tests:n,index:r,patch:i,global:o,controls:s}=e;if(typeof i!="object"||i===null||Array.isArray(i))return;let a=i,c=Vl.find(g=>Object.hasOwn(a,g));if(c===void 0)return;let d=n[r],l=O1(a,c,d),u=Object.fromEntries(Object.entries(a).filter(([g])=>!Vl.includes(g))),_=L1({id:t,tests:n,index:r,identityKey:c,otherFields:u,requested:l,global:o}),h=d.command!==void 0&&n.filter(g=>g.command===d.command).length===1?["--remove",`command=${d.command}`]:["--remove-index",String(r+1)],f=[...Ie(o),"test",t,...h,"--add-json",JSON.stringify(_),...D1(s)];throw new p(`--set-json cannot change ${c}: a linked test's command is its immutable identity; replace the entry instead`,m.USAGE,{code:"linked_test_command_immutable",...ca(c),recovery:{suggested_retry:L(f),suggested_retry_args:f},nextSteps:["Run the suggested retry: it removes the selected entry and adds the new command in one history-recorded write. It selects the entry by its current command or list position, so list the linked tests again first if another writer may have changed them.",`SDK: runTest(${JSON.stringify(t)}, { ${h[0]==="--remove"?"remove":"removeIndex"}: [...], addJson: [...] }, { path: <the same tracker root> }) with the same values.`]})}function N1(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new p("Linked-test metadata patch must be a JSON object",m.USAGE);let n=Object.keys(t);m0(t,!1);let r=Object.fromEntries(Object.entries(e).filter(([a])=>ft.includes(a))),i=tp(pi(JSON.stringify({...r,command:e.command??"legacy-path-only",...Object.fromEntries(Object.entries(t).map(([a,c])=>[a,c===null?void 0:c]))}),"--set-json")[0]);gr(i);let o=n.filter(a=>!Fe(e[a],i[a])),s={...e};for(let a of o){let c=i[a];Object.assign(s,{[a]:c}),c===void 0&&delete s[a]}if(!s.command?.trim()&&!s.path?.trim())throw new p("Linked-test entry must retain a command or path",m.USAGE);return{test:s,fields:o}}async function p0(e,t,n={}){let r=R(process.cwd(),n.path);await j(r);let i=await x(r),o=U(t.author,i.author_default),s=P(i,N()),a=0,c=[],d=await Rt({pmRoot:r,settings:i,id:e,author:o,op:"tests_update",message:t.message,force:t.force,skipNoop:!0,typeToFolder:s.type_to_folder,resolveHistoryContext:()=>({linked_test_update:{index:a,fields:c}}),mutate(u){let _=u.metadata.tests??[],h=R1(_,t.selector);$1({id:u.metadata.id,tests:_,index:h,patch:t.patch,global:n,controls:t});let f=N1(_[h],t.patch);return a=h+1,c=f.fields,f.fields.length===0?{changedFields:[]}:(u.metadata.tests=_.map((g,y)=>y===h?{...f.test,updated_by:o,updated_at:I()}:g),{changedFields:["tests"]})}}),l=d.item.tests;return{ok:!0,id:d.item.id,tests:l,count:l.length,changed:d.changedFields.length>0,updated_index:a,updated_fields:c}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="626315a0-7ee9-500d-bb7a-9bcd33eae209")}catch{}})();var M1=[{code:"no_projects_matched_filters",regex:/\bNo projects matched the filters\b/i},{code:"no_test_files_found",regex:/\bNo test files found\b/i},{code:"no_tests_found",regex:/\bNo tests found\b/i},{code:"no_matching_tests",regex:/\bNo matching tests?\b/i},{code:"collected_zero_items",regex:/\bcollected 0 items?\b/i},{code:"reported_zero_tests",regex:/^\s*Ran 0 tests? across \d+ files?\./imu},{code:"reported_zero_passes",regex:/(?:^\s*(?:#|ℹ)?\s*tests\s+0\s*$[\s\S]*^\s*(?:#|ℹ)?\s*pass\s+0\s*$|^\s*(?:#|ℹ)?\s*pass\s+0\s*$[\s\S]*^\s*(?:#|ℹ)?\s*tests\s+0\s*$)/imu},{code:"reported_zero_tests",regex:/^\s*(?:#|ℹ)?\s*tests\s+0\s*$/imu}],P1=[{receiptCode:"reported_tests",regex:/^\s*(?:#|ℹ)?\s*tests\s+[1-9]\d*\s*$/imu},{receiptCode:"reported_passes",regex:/^\s*(?:#|ℹ)?\s*pass\s+[1-9]\d*\s*$/imu},{receiptCode:"tests_passed",regex:/\bTests?\s+[1-9]\d*\s+passed\b/iu},{receiptCode:"passed_count",regex:/\b[1-9]\d*\s+passed\b/iu},{receiptCode:"tests_summary",regex:/\bTests:\s+(?:.*\b)?[1-9]\d*\s+passed\b/iu},{receiptCode:"bun_pass_count",regex:/^\s*[1-9]\d* pass\s*$/imu},{receiptCode:"bun_executed_tests",regex:/^\s*Ran [1-9]\d* tests? across \d+ files?\./imu}];function da(e,t){let n=`${e}
|
|
21
|
-
${t}`;for(let r of M1)if(r.regex.test(n))return{code:r.code};return null}function _0(e,t){for(let[n,r]of[["stdout",e],["stderr",t]]){let i=P1.find(o=>o.regex.test(r));if(i)return{code:i.receiptCode,stream:n}}}function f0(e,t){return{trackerPath:e.path?.trim()||(process.env.PM_PATH?.trim()?t:void 0),noExtensions:e.noExtensions}}function h0(e,t={}){let n=t.trackerPath?.trim();return L(["test",e,"--list",...t.noExtensions===!0?["--no-extensions"]:[],...n?["--pm-path",n]:[]],t.platform)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="47772627-d807-55f3-95b3-69e3b00c6522")}catch{}})();function g0(e,t,n,r,i){if((t.measure?.length??0)===0||i.some(s=>s.phase!=="setup"&&typeof s.stdout=="string"&&s.failure_category!=="spawn_error"&&s.failure_category!=="empty_run"&&
|
|
22
|
-
`))return!1}finally{await r.close()}let o=i.match(/^#![ \t]*(\/[^ \t\n]+)(?:[ \t\n]|$)/u)?.[1];if(!o)return!1;try{return await tF(o),!1}catch(s){return Tn(s)}}catch{return!1}}async function T0(e,t,n,r){if(/[;&|<>()`$\r\n]/u.test(e))return!1;let i=oF(e);if(!i||!sF(i,t.exitCode,t.stderr))return!1;let o=process.platform==="win32",s=o?E0.join(n.SystemRoot??"C:\\Windows","System32","where.exe"):"/bin/sh",a=o?[i]:["-c",'command -v "$1"',"pm-linked-test-resolution",i];try{let{stdout:c}=await iF(s,a,{env:n,cwd:r,timeout:1e3,windowsHide:!0});return!o&&aF(c,r)}catch(c){let d=c;if(d.killed||d.signal)return!1;let l=d.code;return l===1||!o&&l===127}}import{spawn as q0}from"node:child_process";import{cp as A0,mkdir as iu,mkdtemp as K0,open as tu,readdir as nu,rm as Ei,symlink as dF}from"node:fs/promises";import{tmpdir as W0}from"node:os";import le from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b74444c7-c283-52b2-b65f-b0a086ff2b53")}catch{}})();var C0=20;function cF(){let e=process.env.PM_TRACKED_TEST_RUN_HISTORY_LIMIT;if(!e||e.trim().length===0)return C0;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<=0?C0:t}function eu(e){let t=[...e].filter(r=>r.run_id.trim().length>0&&r.started_at.trim().length>0&&r.finished_at.trim().length>0&&r.recorded_at.trim().length>0).sort((r,i)=>{let o=zi(r.recorded_at,i.recorded_at);if(o!==0)return o;let s=r.run_id.localeCompare(i.run_id);return s!==0?s:r.kind.localeCompare(i.kind)}),n=cF();return t.length>n?t.slice(t.length-n):t}async function pa(e){await he({pmRoot:e.pmRoot,settings:e.settings,id:e.itemId,op:"test_run_track",author:e.author,message:e.message,force:!1,mutate(t){let n=t.metadata.test_runs??[];return t.metadata.test_runs=eu([...n,e.entry]),{changedFields:["test_runs"]}}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="36de91bf-47b8-5755-ad92-6ed1a1bbcd82")}catch{}})();var ha=20*1024*1024,lF=3e3,uF=1e4,mF=5e3,x0=120,pF=new Set(["locks","extensions","runtime"]),_F=new Set(["history","index","search","extensions","locks","runtime"]),fF=[/eaddrinuse/i,/address already in use/i,/port\s+\d+\s+is already in use/i,/web server[^.\n]*already running/i,/failed to listen on/i],hF=/\b(?:could not|failed to|unable to)\s+acquire\b[^\n.]*\block\b/i,gF=/\b(?:already running|timed?\s*out|timeout|held by another|lock\s+is\s+held)\b/i,yF=new Set(["activity","calendar","context","ctx","deps","get","health","history","list","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","search","stats","test-all","validate"]);function ou(e,t){let n=process.env[e];if(typeof n!="string"||n.trim().length===0)return t;let r=Number.parseInt(n,10);return!Number.isFinite(r)||r<=0?t:r}function wF(){return ou("PM_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS",lF)}function vF(){return ou("PM_LINKED_TEST_HEARTBEAT_INTERVAL_MS",uF)}function bF(){return ou("PM_LINKED_TEST_PIPE_CLOSE_GRACE_MS",mF)}function kF(e){let t=process.env.PM_BACKGROUND_TEST_RUN_ID?.trim();return t&&t.length>0?t:`${e}-local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function SF(e){let t=0,n=0,r=0;for(let i of e){if(i.status==="passed"){t+=1;continue}if(i.status==="failed"||i.status==="refused"){n+=1;continue}r+=1}return{passed:t,failed:n,skipped:r}}function su(e){let t=0,n=0,r=0,i=0;for(let o of e){let s=o.execution_context;!s||s.is_pm_command!==!0||(t+=1,s.is_pm_tracker_read_command===!0&&(n+=1),s.mismatch_detected===!0&&(r+=1),s.auto_pm_context_applied===!0&&(i+=1))}return{checked_pm_commands:t,tracker_read_commands:n,mismatches:r,auto_remediated:i}}function EF(e){let t=e??"project";if(!Ke.includes(t))throw new p(`Invalid scope "${e}"`,m.USAGE);return t}function ya(e){if(!e)return"schema";let t=e.trim().toLowerCase();if(ln.includes(t))return t;throw new p(`Invalid --pm-context value "${e}". Expected one of: ${ln.join(", ")}`,m.USAGE)}function z0(e){return mn(e??"source","--workspace-context")}function B0(e,t,n){return n?t:mn(e.workspace_context_mode,"linked test")??t}function H0(e,t,n){return n||typeof e.pm_context_mode!="string"||e.pm_context_mode.trim().length===0?t:ya(e.pm_context_mode)}function V0(e,t){return e==="auto"?t?"tracker":"schema":e}function TF(e){return Object.entries(e).filter(([t])=>t.startsWith("assert_")).some(([,t])=>t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:typeof t=="string"?t.trim().length>0:!0)}function CF(e){let{executionContext:t,runLevelPmContextMode:n,linkedOverridePmContextMode:r}=e;return!t.is_pm_tracker_read_command||!t.mismatch_detected?"":n==="tracker"&&r==="schema"?" Linked test metadata pm_context_mode=schema overrides run-level --pm-context tracker. Set pm_context_mode=tracker (or auto) on the linked test, or remove the override, to run against seeded tracker data.":t.pm_context_mode==="schema"?" Use --auto-pm-context to route PM tracker-read linked commands through seeded tracker data automatically. Alternatively, use --pm-context tracker for the whole run.":""}function AF(e,t){let n={};if(!e)return n;for(let r of e){let i=ui(r,t);if(i)for(let[o,s]of Object.entries(i))n[o]=s}return n}function xF(e,t){if(!e)return[];let n=[];for(let r of e){let i=mi(r,t);i&&n.push(...i)}return[...new Set(n)]}function RF(e){let t=Xn(e);return sn(t).some(n=>os(n)!==null)}function Y0(e){let t=Xn(e);return sn(t).some(n=>{let r=os(n);if(!r)return!1;let i=Nd(r);return i?yF.has(i.subcommand):!1})}function _a(e){if(e)return Gw.has(e.subcommand)?Pt(e.args,qw)?.subcommand:e.subcommand}function R0(e,t){if(e==="npx"||e==="bunx")return an(t)?.command;if(e==="pnpm")return _a(Pt(t,Ld));if(e==="npm")return _a(Pt(t,Dd));if(e==="yarn")return _a(Pt(t,jw));if(e==="bun")return _a(Pt(t,Uw))}function fa(e){return e?e==="vitest"||e==="test"||e.startsWith("test:"):!1}function I0(e){return e.includes("node scripts/run-tests.mjs ")||e.endsWith("node scripts/run-tests.mjs")||e.includes("node ./scripts/run-tests.mjs ")||e.endsWith("node ./scripts/run-tests.mjs")}function au(e){let t=e.split(" ").filter(s=>s.length>0),n=ss(t);if(n.length===0)return!1;let[r,...i]=n,o=Md.get(r);if(o){let s=i.findIndex(a=>o.test(a));return s>=0&&au(i.slice(s+1).join(" "))}return r==="vitest"||r.endsWith("/vitest")||r.endsWith("/vitest.mjs")?!0:r==="node"?IF(i):OF(r,i)}function IF(e){return e.includes("--test")||e.some(t=>t==="vitest"||t==="vitest.mjs"||t.endsWith("/vitest")||t.endsWith("/vitest.mjs"))}function OF(e,t){return e==="npx"||e==="bunx"?fa(an(t)?.command):e==="pnpm"||e==="npm"?fa((e==="pnpm"?as(t):cs(t))?.command)||fa(R0(e,t)):(e==="yarn"||e==="bun")&&fa(R0(e,t))}function fY(e){let t=Xn(e),n=sn(t),r=n.some(o=>!I0(o)&&au(o)),i=n.some(I0);return{accepted:!0,command_kind:r?"direct_runner":i?"sandbox_runner":"other",tracker_isolation:"runtime_injected",trust_boundary:"provenance",advisory:r?"Accepted with runtime-injected tracker isolation. Prefer the repository sandbox runner when available for reproducible build and coverage setup.":"Accepted with runtime-injected tracker isolation and provenance checks before execution."}}function LF(e){if(Fd(e))return'Linked test command skipped: Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.'}function DF(e){return e?e.map($F):[]}function $F(e){let t=e.trim(),n=gm(t)?Ki(ee(e,"--add"),"--add"):{command:t},r=ve(n.command);if(!r)throw new p("--add requires command=<value> or a bare command (path=<value> is optional metadata)",m.USAGE);return ni(r),{command:r,path:ve(n.path),scope:EF(n.scope),timeout_seconds:NF(ve(n.timeout_seconds),ve(n.timeout)),pm_context_mode:Rs(ve(n.pm_context_mode),"--add"),workspace_context_mode:mn(ve(n.workspace_context_mode),"--add"),env_set:ui(ve(n.env_set),"--add"),env_clear:mi(ve(n.env_clear),"--add"),shared_host_safe:xs(ve(n.shared_host_safe),"--add","shared_host_safe"),assert_stdout_contains:pn(ve(n.assert_stdout_contains)),assert_stdout_regex:rr(ve(n.assert_stdout_regex),"--add","assert_stdout_regex"),assert_stderr_contains:pn(ve(n.assert_stderr_contains)),assert_stderr_regex:rr(ve(n.assert_stderr_regex),"--add","assert_stderr_regex"),assert_stdout_min_lines:Is(ve(n.assert_stdout_min_lines),"--add"),assert_json_field_equals:Os(ve(n.assert_json_field_equals),"--add"),assert_json_field_gte:Ls(ve(n.assert_json_field_gte),"--add"),note:ve(n.note),phase:tr(n.phase,"--add")}}function ve(e){let t=e?.trim();return t&&t.length>0?t:void 0}function NF(e,t){if(e&&t&&e!==t)throw new p("--add timeout and timeout_seconds must match when both are provided",m.USAGE);let n=e??t;if(n===void 0)return;let r=Math.floor(we(n,"timeout_seconds"));if(r<=0)throw new p("--add timeout_seconds must be a positive integer",m.USAGE);return r}function MF(e){return e?e.flatMap(t=>{let n=pi(t,"--add-json");for(let r of n){let i=r.command;if(!i)throw new p("--add-json requires a non-empty command string",m.USAGE);ni(i)}return n}):[]}function PF(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new p("--remove requires command or path value",m.USAGE);let r=/^(command|path)\s*=/i.exec(n);if(r){let i=n.slice(r[0].length).trim();if(!i)throw new p("--remove requires a non-empty command=<value> or path=<value>",m.USAGE);return{kind:r[1].toLowerCase(),value:i}}if(/^[A-Za-z_][\w-]*=\S+$/u.test(n))throw new p("--remove structured selectors require command=<value> or path=<value>",m.USAGE);if(/^(?:[-*+]\s+)?(?:path|command)\s*:/i.test(n)||n.startsWith("```")){let i=ee(n,"--remove"),o=i.path!==void 0?"path":"command",s=i.path??i.command;if(!s?.trim())throw new p("--remove requires command=<value> and/or path=<value>",m.USAGE);return{kind:o,value:s.trim()}}return{kind:"either",value:n}}):[]}function FF(e){return e?[...new Set(e.map(t=>{let n=typeof t=="number"?t:Number.parseInt(t,10);if(!Number.isInteger(n)||n<1||String(n)!==String(t).trim())throw new p("--remove-index must be a positive integer",m.USAGE);return n}))]:[]}function jF(e){try{e.stdin?.end()}catch{}}function J0(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length<=x0?t:`${t.slice(0,x0-3)}...`}function X0(e){return e==="off"?!1:e==="always"?!0:process.stderr.isTTY===!0}function ru(e){try{process.stderr.write(`${e}
|
|
23
|
-
`)}catch{}}function UF(e,t){if(!X0(t))return null;let n=J0(e.command),r=Date.now();
|
|
24
|
-
[pm linked-test output truncated at ${
|
|
25
|
-
`:"";!f&&await T0(e,{exitCode:v,stderr:b.text},n,o)&&(f="Linked test executable was not found. Install the tool or update the linked command before retrying.");let C={stdout:`${S.text}${E}`,stderr:b.text,exitCode:v,signal:k,timedOut:w,maxBufferExceeded:!1,outputTruncated:A,spawnError:f};return GF(r,C,s,i),C}finally{await
|
|
26
|
-
`);return fF.some(n=>n.test(t))||t.split(/\r?\n/u).some(n=>hF.test(n)&&gF.test(n))}function YF(e){return VF(e)?"infra_collision":e.timedOut?"timeout":e.maxBufferExceeded?"max_buffer":e.spawnError?"spawn_error":e.signal?"signal":"assertion_failure"}function D0(e,t){for(let[n,r]of Object.entries(t.env_set))un.has(n.toUpperCase())||(e[n]=r);for(let n of t.env_clear)un.has(n.toUpperCase())||delete e[n]}function JF(e){e.PORT===void 0&&(e.PORT="0"),e.HOST===void 0&&(e.HOST="127.0.0.1"),e.PM_SHARED_HOST_SAFE===void 0&&(e.PM_SHARED_HOST_SAFE="1"),e.PLAYWRIGHT_HTML_OPEN===void 0&&(e.PLAYWRIGHT_HTML_OPEN="never"),e.PW_TEST_HTML_REPORT_OPEN===void 0&&(e.PW_TEST_HTML_REPORT_OPEN="never")}function XF(e,t){let n={...e.env_set,...t.env_set},r=[...new Set([...e.env_clear,...t.env_clear??[]])],i=t.shared_host_safe??e.shared_host_safe;return{env_set:n,env_clear:r,shared_host_safe:i}}function Q0(e,t,n){return{env_set:AF(e,"--env-set"),env_clear:xF(t,"--env-clear"),shared_host_safe:n===!0}}async function Si(e,t,n=!1,r=iu){if(await ie(e))try{await vr("seed_linked_test",async()=>{if(await r(le.dirname(t),{recursive:!0}),n){await A0(e,t,{recursive:!0,force:!0});return}await A0(e,t,{force:!0})},{why:"Linked tests need an isolated PM context without mutating the source tracker.",nextSteps:["Reclaim capacity on the filesystem that hosts the linked-test temporary directory."]})}catch(i){if(typeof i=="object"&&i!==null&&"code"in i&&G(i))return;throw i}}async function $0(e,t,n,r=!1){for(let[i,o]of[[n.projectPmRoot,e],[n.globalPmRoot,t]])if(r){let s=await Q(Re(i));if(s!==null){let a=await x(o);await Ya({pmRoot:o,filePath:Re(o),raw:s,op:"settings:write",author:U(void 0,a.author_default),lockTtlSeconds:a.locks.ttl_seconds,lockWaitMs:a.locks.wait_ms,recordCreation:!0,message:"Seed linked-test schema settings history"})}}else await Si(Re(i),Re(o));await Si(le.join(n.projectPmRoot,"extensions"),le.join(e,"extensions"),!0),await Si(le.join(n.globalPmRoot,"extensions"),le.join(t,"extensions"),!0)}async function N0(e,t){if(!await ie(e))return;let n=await nu(e,{withFileTypes:!0});for(let r of n){if(pF.has(r.name))continue;let i=le.join(e,r.name),o=le.join(t,r.name);if(r.isDirectory()){await Si(i,o,!0);continue}r.isFile()&&await Si(i,o)}}async function M0(e,t){let n=await Q(Re(e));if(n===null||await ie(Er(e)))return;let r=await x(t);await Ei(Er(t),{force:!0}),await Ei(Re(t),{force:!0}),await Ya({pmRoot:t,filePath:Re(t),raw:n,op:"settings:write",author:U(void 0,r.author_default),lockTtlSeconds:r.locks.ttl_seconds,lockWaitMs:r.locks.wait_ms,recordCreation:!0,message:"Seed linked-test tracker settings history"})}async function dr(e){if(!await ie(e))return 0;let t=0,n=await nu(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||_F.has(r.name))continue;let i=le.join(e,r.name),o;try{o=await nu(i,{withFileTypes:!0})}catch{continue}for(let s of o)s.isFile()&&zt.some(a=>s.name.toLowerCase().endsWith(a))&&(t+=1)}return t}function QF(e){let t=typeof e.exitCode=="number"?e.exitCode:1;return(e.timedOut||e.maxBufferExceeded)&&t===0?1:t}function ZF(e){let t=e.trim();if(t==="true")return!0;if(t==="false")return!1;if(t==="null")return null;let n=Number(t);if(t.length>0&&Number.isFinite(n))return n;if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t)}catch{}return t}function ej(e,t){return typeof e=="object"&&e!==null&&typeof t=="object"&&t!==null?Fe(e,t):Object.is(e,t)}function tj(e,t,n){let r=[];r.push(...P0("stdout",t,e.assert_stdout_contains)),r.push(...F0("stdout",t,e.assert_stdout_regex)),r.push(...P0("stderr",n,e.assert_stderr_contains)),r.push(...F0("stderr",n,e.assert_stderr_regex)),r.push(...nj(t,e.assert_stdout_min_lines));let i=e.assert_json_field_equals??{},o=e.assert_json_field_gte??{};if(!(Object.keys(i).length>0||Object.keys(o).length>0))return r;let s;try{s=JSON.parse(t)}catch(a){return r.push(`stdout is not valid JSON for assert_json_field_* checks: ${a instanceof Error?a.message:String(a)}`),r}for(let[a,c]of Object.entries(i)){let d=Jl(s,a);if(!d.found){r.push(`assert_json_field_equals missing path "${a}"`);continue}let l=ZF(c);ej(d.value,l)||r.push(`assert_json_field_equals mismatch at "${a}" (expected=${JSON.stringify(l)} actual=${JSON.stringify(d.value)})`)}for(let[a,c]of Object.entries(o)){let d=Jl(s,a);if(!d.found){r.push(`assert_json_field_gte missing path "${a}"`);continue}if(typeof d.value!="number"||!Number.isFinite(d.value)){r.push(`assert_json_field_gte path "${a}" resolved to non-numeric value`);continue}d.value<c&&r.push(`assert_json_field_gte failed at "${a}" (expected >= ${c}, actual ${d.value})`)}return r}function P0(e,t,n){let r=[];for(let i of n??[])t.includes(i)||r.push(`${e} missing required text: "${i}"`);return r}function F0(e,t,n){let r=[];for(let i of n??[])try{new RegExp(i,"m").test(t)||r.push(`${e} failed regex assertion: /${i}/m`)}catch(o){r.push(`${e} regex assertion is invalid: /${i}/ (${o instanceof Error?o.message:String(o)})`)}return r}function nj(e,t){if(typeof t!="number")return[];let n=e.split(/\r?\n/).map(r=>r.trim()).filter(r=>r.length>0).length;return n<t?[`stdout line count ${n} is below required minimum ${t}`]:[]}function rj(e){let t=Xn(e);return/(?:^|\s)(?:--test-name-pattern|--testnamepattern)(?:=|\s)/u.test(t)?!0:sn(t).some(n=>/(?:^|\s)-t(?:=|\s)/u.test(n)&&au(n))}function ij(e){return{root:e,schemaProjectPmPath:le.join(e,"schema","project",".agents","pm"),schemaGlobalPmPath:le.join(e,"schema","global"),trackerProjectPmPath:le.join(e,"tracker","project",".agents","pm"),trackerGlobalPmPath:le.join(e,"tracker","global"),workspaceSnapshotRoot:le.join(e,"workspace","project"),workspaceIsolatedRoot:le.join(e,"workspace","isolated")}}function oj(e,t,n){return e.some(r=>B0(r,t,n)==="snapshot")}async function sj(e,t){let n=le.join(e,".agents"),r=le.join(n,"pm");await iu(n,{recursive:!0}),await Ei(r,{recursive:!0,force:!0}),await dF(t,r,process.platform==="win32"?"junction":"dir")}async function aj(e,t=Sc,n=!0){let r={defaults:!0,agentGuidance:"skip"};await t(void 0,{path:e.schemaProjectPmPath},r),await t(void 0,{path:e.schemaGlobalPmPath},r),n&&(await t(void 0,{path:e.trackerProjectPmPath},r),await t(void 0,{path:e.trackerGlobalPmPath},r))}async function cj(e,t,n){t&&(await $0(e.schemaProjectPmPath,e.schemaGlobalPmPath,t,!0),n&&(await $0(e.trackerProjectPmPath,e.trackerGlobalPmPath,t),await N0(t.projectPmRoot,e.trackerProjectPmPath),await N0(t.globalPmRoot,e.trackerGlobalPmPath),await M0(t.projectPmRoot,e.trackerProjectPmPath),await M0(t.globalPmRoot,e.trackerGlobalPmPath)))}function dj(e,t,n){return e.some(r=>{let i=r.command??"",o=i.length>0&&Y0(i),s=n?.autoPmContext===!0&&o?"auto":H0(r,t,n?.overrideLinkedPmContext===!0);return V0(s,o)==="tracker"})}async function lj(e,t){return{sourceProjectItemCount:t?await dr(t.projectPmRoot):0,sourceGlobalItemCount:t?await dr(t.globalPmRoot):0,schemaProjectItemCount:await dr(e.schemaProjectPmPath),schemaGlobalItemCount:await dr(e.schemaGlobalPmPath),trackerProjectItemCount:await dr(e.trackerProjectPmPath),trackerGlobalItemCount:await dr(e.trackerGlobalPmPath)}}function uj(e){let t=e.effectivePmContextMode==="tracker",n=t?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath,r=t?e.layout.trackerGlobalPmPath:e.layout.schemaGlobalPmPath,i=t?e.counts.trackerProjectItemCount:e.counts.schemaProjectItemCount,o=t?e.counts.trackerGlobalItemCount:e.counts.schemaGlobalItemCount,s=e.workspaceContextMode==="snapshot"?e.layout.workspaceSnapshotRoot:e.workspaceContextMode==="isolated"?e.layout.workspaceIsolatedRoot:e.sourceWorkspaceRoot,a=e.workspaceContextMode==="isolated"?"":s;return{requested_pm_context_mode:e.requestedPmContextMode,pm_context_mode:e.effectivePmContextMode,auto_pm_context_applied:e.autoPmContextApplied,is_pm_command:e.isPmCommand,is_pm_tracker_read_command:e.isPmTrackerReadCommand,source_project_pm_path:e.sourceRoots?.projectPmRoot??"",sandbox_project_pm_path:n,source_global_pm_path:e.sourceRoots?.globalPmRoot??"",sandbox_global_pm_path:r,source_project_item_count:e.counts.sourceProjectItemCount,sandbox_project_item_count:i,source_global_item_count:e.counts.sourceGlobalItemCount,sandbox_global_item_count:o,mismatch_detected:e.isPmCommand&&(e.counts.sourceProjectItemCount!==i||e.counts.sourceGlobalItemCount!==o),project_extensions_seeded:!!e.sourceRoots,global_extensions_seeded:!!e.sourceRoots,requested_workspace_context_mode:e.requestedWorkspaceContextMode,workspace_context_mode:e.workspaceContextMode,working_directory:s,source_workspace_root:a,trust:e.trust}}async function mj(e){let t=typeof e.linkedTest.pm_context_mode=="string"&&e.linkedTest.pm_context_mode.trim().length>0?ya(e.linkedTest.pm_context_mode):void 0,n=typeof e.linkedTest.command=="string"&&e.linkedTest.command.length>0?e.linkedTest.command:void 0,r=n?RF(n):!1,i=r&&n?Y0(n):!1,o=e.options?.autoPmContext===!0&&i,s=o?"auto":H0(e.linkedTest,e.runLevelPmContextMode,e.options?.overrideLinkedPmContext===!0),a=V0(s,i),c=a==="tracker"?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath;e.workspaceContextMode==="snapshot"&&await sj(e.layout.workspaceSnapshotRoot,c);let d=e.options?.pmRoot?await qd(e.options.pmRoot,e.linkedTest,e.currentSourceRef):await qd(e.layout.root,e.linkedTest,e.currentSourceRef);return{linkedOverridePmContextMode:t,executionContext:uj({layout:e.layout,counts:e.counts,sourceRoots:e.sourceRoots,isPmCommand:r,isPmTrackerReadCommand:i,requestedPmContextMode:s,effectivePmContextMode:a,autoPmContextApplied:o,requestedWorkspaceContextMode:e.requestedWorkspaceContextMode,workspaceContextMode:e.workspaceContextMode,sourceWorkspaceRoot:e.sourceWorkspaceRoot,trust:d})}}function j0(e,t,n){return{command:e.command,path:e.path,status:"skipped",execution_context:t,error:n}}function pj(e,t,n,r){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"assertion_failure",execution_context:t,...r?{stdout:r.stdout,stderr:r.stderr}:{},error:n}}function _j(e,t,n){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"trust_refusal",execution_context:t,error:n}}function fj(e){if(e.executionContext.trust.trusted)return null;let t=e.options?.allowUntrustedLinkedTests===!0,n=e.options?.untrustedLinkedTestsPolicyEnabled===!0;if(t&&n)return null;let r=n?"Retry with --allow-untrusted-linked-tests for this invocation, or acknowledge the current commands with --acknowledge-linked-tests.":"Set testing.allow_untrusted_linked_tests=true, then retry with --allow-untrusted-linked-tests; alternatively acknowledge the current commands with --acknowledge-linked-tests.";return _j(e.linkedTest,e.executionContext,`Linked test command is not trusted by this clone (source_ref=${e.executionContext.trust.source_ref??"unknown"}, current_ref=${e.executionContext.trust.current_source_ref??"unknown"}). ${r}`)}function hj(e){if(!e.linkedTest.command)return j0(e.linkedTest,e.executionContext,"No command configured for this linked test.");let t=LF(e.linkedTest.command);return t?j0(e.linkedTest,e.executionContext,t):null}function gj(e){return e.executionContext.pm_context_mode!=="none"?null:e.executionContext.workspace_context_mode==="source"?ga(e.linkedTest,e.executionContext,"pm_context_mode=none requires workspace_context_mode=isolated or snapshot so implicit tracker discovery cannot reach the source workspace."):e.executionContext.is_pm_command?ga(e.linkedTest,e.executionContext,"pm_context_mode=none is for self-isolating SDK tests; direct PM commands require schema, tracker, or auto context."):null}function ga(e,t,n){return{command:e.command,path:e.path,status:"refused",exit_code:null,failure_category:"config_refusal",execution_context:t,error:n}}function yj(e){let t=e.executionContext.pm_context_mode==="schema"&&e.executionContext.is_pm_tracker_read_command&&e.executionContext.mismatch_detected,n=e.options?.failOnContextMismatch===!0&&e.executionContext.is_pm_command&&e.executionContext.mismatch_detected;if(!t&&!n)return null;let r=CF({executionContext:e.executionContext,runLevelPmContextMode:e.runLevelPmContextMode,linkedOverridePmContextMode:e.linkedOverridePmContextMode}),i=e.options?.checkContext===!0?"Linked test preflight PM context mismatch detected":"Linked test PM context mismatch detected";return ga(e.linkedTest,e.executionContext,`${i} (source_project_items=${e.executionContext.source_project_item_count}, sandbox_project_items=${e.executionContext.sandbox_project_item_count}).${r}`)}function wj(e){return hj(e)||fj(e)||gj(e)||yj(e)||(e.options?.requireAssertionsForPm===!0&&e.executionContext.is_pm_command&&!TF(e.linkedTest)?ga(e.linkedTest,e.executionContext,"Linked PM command requires assertions when --require-assertions-for-pm is enabled."):null)}function vj(e){let t=XF(e.runtimeDirectives,e.linkedTest),n={...process.env,SENTRY_ENVIRONMENT:"test"};return D0(n,e.runtimeDirectives),D0(n,{env_set:e.linkedTest.env_set??{},env_clear:e.linkedTest.env_clear??[]}),t.shared_host_safe&&JF(n),n.FORCE_COLOR="0",e.executionContext.pm_context_mode==="none"?delete n.PM_PATH:n.PM_PATH=e.executionContext.sandbox_project_pm_path,n.PM_GLOBAL_PATH=e.executionContext.sandbox_global_pm_path,e.executionContext.workspace_context_mode!=="source"&&(delete n.PM_BUILD_CONSUMER_LEASE,delete n.PM_BUILD_CONSUMER_LEASE_ROOT),e.executionContext.workspace_context_mode==="isolated"?(delete n.PM_SOURCE_WORKSPACE_ROOT,delete n.PM_SOURCE_PM_PATH,delete n[Mr]):(n.PM_SOURCE_WORKSPACE_ROOT=e.executionContext.source_workspace_root,n.PM_SOURCE_PM_PATH=e.executionContext.workspace_context_mode==="snapshot"?e.executionContext.sandbox_project_pm_path:e.executionContext.source_project_pm_path,n[Mr]="read_only"),n}function bj(e,t,n,r){return{command:e.command,path:e.path,status:"passed",exit_code:0,execution_context:t,stdout:n.stdout,stderr:n.stderr,...r?{execution_receipt:r}:{}}}function U0(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:1,failure_category:"empty_run",execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:`Linked test reported an empty test run (${e.emptyRunSignal.code}). Update the test selection so at least one test executes; unfiltered commands may opt out by omitting --fail-on-empty-test-run.`}}function kj(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:QF(e.execution),failure_category:YF(e.execution),execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:HF(e.execution,e.timeoutMs)}}function Sj(e){let t=_0(e.execution.stdout,e.execution.stderr),n=e.linkedTest.phase!=="setup"&&rj(e.linkedTest.command??"");if(e.options?.failOnEmptyTestRun===!0||n){let i=da(e.execution.stdout,e.execution.stderr);if(i)return U0({...e,emptyRunSignal:i});if(n&&!t)return U0({...e,emptyRunSignal:{code:"missing_positive_execution_receipt"}})}let r=tj(e.linkedTest,e.execution.stdout,e.execution.stderr);return r.length>0?pj(e.linkedTest,e.executionContext,`Linked test assertion(s) failed: ${r.join("; ")}`,e.execution):bj(e.linkedTest,e.executionContext,e.execution,t)}async function Ej(e){let t=e.linkedTest.command??"",n=(e.linkedTest.timeout_seconds??e.defaultTimeoutSeconds??120)*1e3,r=await BF(t,n,vj(e),{index:e.index+1,total:e.total,timeoutMs:n,command:t},e.progressMode,e.executionContext.working_directory);return r.exitCode===0&&!r.timedOut&&!r.maxBufferExceeded?Sj({...e,execution:r}):kj({...e,execution:r,timeoutMs:n})}async function cu(e,t,n){let r=Es(e);for(let y of r)hr(y.command);let i=[],o=await K0(le.join(W0(),"pm-linked-test-")),s=ij(o),a=ya(n?.pmContext),c=z0(n?.workspaceContext),d=n?.progress===!0?"always":"auto",l=Q0(n?.envSet,n?.envClear,n?.sharedHostSafe),u=n?.sourceRoots,_=oi(),h=dj(r,a,n),f=oj(r,c,n?.overrideLinkedWorkspaceContext===!0),g=await ii(_);try{await aj(s,Sc,h),await iu(s.workspaceIsolatedRoot,{recursive:!0}),await cj(s,u,h),f&&await k0(_,s.workspaceSnapshotRoot,u?.projectPmRoot,h);let y=await lj(s,u),w=li(),v=b=>B0(b,c,n?.overrideLinkedWorkspaceContext===!0),k=new Set(r.filter(b=>!Ce(b)).map(v)),S=async(b,A)=>{let E=w.options(b,n),C=v(b),O=pb(b,C,k);if(O)return O;let M=await mj({linkedTest:b,layout:s,counts:y,sourceRoots:u,runLevelPmContextMode:a,options:n,requestedWorkspaceContextMode:c,workspaceContextMode:C,currentSourceRef:g,sourceWorkspaceRoot:_});return wj({linkedTest:b,executionContext:M.executionContext,runLevelPmContextMode:a,linkedOverridePmContextMode:M.linkedOverridePmContextMode,options:E})??await Ej({linkedTest:b,index:A,total:r.length,defaultTimeoutSeconds:t,runtimeDirectives:l,progressMode:d,executionContext:M.executionContext,options:E})};for(let b=0;b<r.length;b+=1){let A=r[b];i.push(w.blocked(A)??w.record(A,await S(A,b)))}}finally{await Ei(s.root,{recursive:!0,force:!0,maxRetries:3,retryDelay:100})}return i}function Tj(e,t){let n=[...t];return e.filter(r=>{let i=n.findIndex(o=>yr(o,r));return i>=0&&n.splice(i,1),i<0}).length}async function Cj(e){let{id:t,pmRoot:n,settings:r,typeToFolder:i}=e,o=await V(n,t,r.id_prefix,r.item_format,i);if(!o)throw new p(`Item ${t} not found`,m.NOT_FOUND);let s=await pe(o,{schema:r.schema});return{itemId:o.id,tests:s.document.metadata.tests??[],testRuns:s.document.metadata.test_runs??[],changed:!1,removed:0}}function Aj(e,t){let n=[...e];for(let r of t)n.some(i=>yr(i,r))||n.push(r);return n}function xj(e,t,n){if(t.length===0&&n.length===0)return{tests:e,removed:0};let r=new Set(n),i=e.filter((o,s)=>r.has(s+1)?!1:!t.some(a=>a.kind==="command"?o.command===a.value:a.kind==="path"?o.path===a.value:o.command===a.value||o.path===a.value));return{tests:i,removed:e.length-i.length}}function Rj(e,t,n,r){return xj(Aj(e,t),n,r)}function Ij(e){return[e.timeout!==void 0,e.progress===!0,(e.envSet?.length??0)>0,(e.envClear?.length??0)>0,e.sharedHostSafe===!0,e.pmContext!==void 0,e.overrideLinkedPmContext===!0,e.failOnContextMismatch===!0,e.failOnSkipped===!0,e.failOnEmptyTestRun===!0,e.requireAssertionsForPm===!0,e.checkContext===!0,e.fullOutput===!0,e.autoPmContext===!0,e.workspaceContext!==void 0,e.overrideLinkedWorkspaceContext===!0,e.allowUntrustedLinkedTests===!0].some(Boolean)}function Z0(e){if(Ij(e)&&e.run!==!0)throw new p("--timeout, --progress, --env-set, --env-clear, --shared-host-safe, --pm-context, --override-linked-pm-context, --workspace-context, --override-linked-workspace-context, --allow-untrusted-linked-tests, --fail-on-context-mismatch, --fail-on-skipped, --fail-on-empty-test-run, --require-assertions-for-pm, --check-context, --full-output, and --auto-pm-context require --run",m.USAGE);if(e.acknowledgeLinkedTests===!0&&e.run===!0)throw new p("--acknowledge-linked-tests records trust without executing commands; run it separately before --run",m.USAGE);if((e.match!==void 0||e.onlyIndex!==void 0||e.onlyLast===!0)&&e.run!==!0)throw new p("--match, --only-index, and --only-last require --run",m.USAGE)}async function Oj(e){let{id:t,options:n,pmRoot:r,settings:i,typeToFolder:o,adds:s,removes:a,removeIndexes:c}=e;if(s.length===0&&a.length===0&&c.length===0)return Cj({id:t,pmRoot:r,settings:i,typeToFolder:o});let d=0,l=[],u=await he({pmRoot:r,settings:i,id:t,op:s.length>0?"tests_add":"tests_remove",author:U(n.author,i.author_default),message:n.message,force:n.force,skipNoop:!0,mutate(h){let f=h.metadata.tests??[],g=Rj(f,s,a,c);if(Ua(()=>eS(n,g.tests)),d=g.removed,(a.length>0||c.length>0)&&d===0)throw new p("No linked tests matched the requested removal selector",m.NOT_FOUND,{code:"linked_test_remove_no_match",unmatched:[...a.map(y=>`${y.kind}=${y.value}`),...c.map(y=>`index=${y}`)],required:"List linked tests and retry with an exact command/path or a current 1-based --remove-index.",examples:[`pm test ${t} --list`,`pm test ${t} --remove-index 1`]});return h.metadata.tests=g.tests,l=f,{changedFields:Fe(f,g.tests)?[]:["tests"]}}}),_=u.item.tests??[];return{itemId:u.item.id,tests:_,testRuns:u.item.test_runs??[],changed:u.changedFields.length>0,removed:d,written:u.changedFields.length>0?td(l,_):[],storedRemoved:Tj(l,_)}}function eS(e,t){let n=ya(e.pmContext);z0(e.workspaceContext),Q0(e.envSet,e.envClear,e.sharedHostSafe);let r={match:e.match,onlyIndex:e.onlyIndex===void 0?void 0:cr(e.onlyIndex),onlyLast:e.onlyLast},i=e.timeout===void 0?void 0:we(e.timeout,"--timeout");if(i!==void 0&&i<=0)throw new p(`--timeout must be a positive number (got "${e.timeout}")`,m.USAGE);Z0(e);let o=e.run===!0?mb(d0(t,r),t):void 0;if(o)for(let s of o.selected)hr(s.command);return{defaultTimeoutSeconds:i,pmContextMode:n,runSelection:o,testsToRun:o?.selected??t}}async function Lj(e){let{options:t,runOptions:n,pmRoot:r}=e;return t.run!==!0?[]:await cu(n.testsToRun,n.defaultTimeoutSeconds,{progress:t.progress,envSet:t.envSet,envClear:t.envClear,sharedHostSafe:t.sharedHostSafe,pmContext:n.pmContextMode,overrideLinkedPmContext:t.overrideLinkedPmContext,failOnContextMismatch:t.failOnContextMismatch,failOnEmptyTestRun:t.failOnEmptyTestRun===!0||(t.measure?.length??0)>0,requireAssertionsForPm:t.requireAssertionsForPm,checkContext:t.checkContext,autoPmContext:t.autoPmContext,workspaceContext:t.workspaceContext,overrideLinkedWorkspaceContext:t.overrideLinkedWorkspaceContext,pmRoot:r,allowUntrustedLinkedTests:t.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:e.untrustedLinkedTestsPolicyEnabled,sourceRoots:{projectPmRoot:r,globalPmRoot:Ye(process.cwd())}})}function Dj(e,t){let n=[];if(e.run===!0&&e.checkContext===!0){let r=su(t);n.push(`context_preflight:checked_pm_commands=${r.checked_pm_commands};tracker_read_commands=${r.tracker_read_commands};mismatches=${r.mismatches};auto_remediated=${r.auto_remediated}`)}return n}function $j(e){let t=SF(e.runResults),n=Number.parseInt(process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim()??"",10),r=process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM?.trim(),i=I(),o=wi(e.options.measure,i);return{run_id:kF("test"),kind:"test",status:t.failed>0||e.failOnSkippedTriggered?"failed":"passed",started_at:e.runStartedAt,finished_at:i,recorded_at:i,attempt:Number.isFinite(n)&&n>=1?n:void 0,resumed_from:r&&r.length>0?r:void 0,passed:t.passed,failed:t.failed,skipped:t.skipped,fail_on_skipped_triggered:e.failOnSkippedTriggered?!0:void 0,measurements:o.length>0?o:void 0,executions:e.runResults.filter(s=>s.command?.trim()).slice(0,32).map(s=>({command:s.command.trim(),requested_pm_context_mode:s.execution_context?.requested_pm_context_mode,pm_context_mode:s.execution_context?.pm_context_mode,workspace_context_mode:s.execution_context?.workspace_context_mode,trust_reason:s.execution_context?.trust.reason}))}}async function Nj(e){let{options:t,pmRoot:n,settings:r,itemId:i,runStartedAt:o,runResults:s,failOnSkippedTriggered:a,warnings:c}=e;if(t.run!==!0||!o)return;let d=$j({options:t,runStartedAt:o,runResults:s,failOnSkippedTriggered:a});if(r.testing.record_results_to_items!==!0)return{entry:d,receipt:{recorded:!1,reason:"tracking_disabled",run_id:d.run_id,recovery_command:"pm config project set test-result-tracking --policy enabled"}};try{return await pa({pmRoot:n,settings:r,itemId:i,author:U(t.author,r.author_default),message:`Track test run summary (${d.run_id})`,entry:d}),{entry:d,receipt:{recorded:!0,reason:"recorded",run_id:d.run_id}}}catch(l){if(en(l))throw l;return c.push(`test_result_tracking_failed:${i}:${l instanceof Error?l.message:String(l)}`),{entry:d,receipt:{recorded:!1,reason:"write_failed",run_id:d.run_id}}}}function G0(e,t,n){let r;if(e.metricBelow!==void 0){let i=e.metricBelow.indexOf("="),o=e.metricBelow.slice(0,i).trim(),s=e.metricBelow.slice(i+1).trim(),a=Number(s);if(i<=0||o.length===0||s.length===0||!Number.isFinite(a))throw new p("--metric-below must use name=value",m.USAGE);r=Vk(t,o,a)}return{measurements:n?.measurements,metric_below:r,metric_diff:e.metricDiff===void 0?void 0:Yk(t,e.metricDiff)}}async function Mj(e,t,n){if(e.acknowledgeLinkedTests===!0)return Yw(t,n,I())}function Pj(e){let{item:t,runResults:n,failureCategories:r,runSelection:i,failOnSkippedTriggered:o,warnings:s,recording:a,measurementProjection:c,restoreScope:d}=e,l=jj(t,e.fullHistory),u=Fj(t,i,l,d),{counts:_,receipts:h}=qo(l);return{ok:n.every(f=>f.status!=="failed"&&f.status!=="refused")&&o!==!0,id:t.itemId,tests:u.tests,...u.omitted,run_results:n,...e.ran?{failure_categories:r}:{},selection:i?{selector:i.selector,requested:i.requested,selected_indexes:i.selected_indexes,selected_count:i.selected_count,skipped_count:i.skipped_count,...i.setup_indexes?{setup_indexes:i.setup_indexes}:{}}:void 0,fail_on_skipped_triggered:o?!0:void 0,warnings:s.length>0?s:void 0,changed:t.changed||a?.receipt.recorded===!0,...a?{evidence_recording:a.receipt}:{},count:u.count,...t.removed>0?{removed:t.removed}:{},..._,...c,...h}}function Fj(e,t,n,r){return n!==void 0?{tests:n.entries,count:n.returned_count,omitted:{}}:t!==void 0&&t.selector!==null&&t.skipped_count>0?{tests:t.selected,count:e.tests.length,omitted:{tests_omitted:{count:e.tests.length-t.selected.length,restore_with:h0(e.itemId,r)}}}:{tests:e.tests,count:e.tests.length,omitted:{}}}function jj(e,t){if(e.written!==void 0)return Qr({collectionKey:"tests",stored:e.tests,written:e.written,removedCount:e.storedRemoved,fullHistory:t})}function Uj(e,t){let n=e.tests[e.updated_index-1],r=Qr({collectionKey:"tests",stored:e.tests,written:e.changed&&n!==void 0?[n]:[],removedCount:0,fullHistory:t}),{counts:i,receipts:o}=qo(r);return{...e,tests:r.entries,run_results:[],count:r.returned_count,...i,...o}}async function tS(e,t,n){let r=l0(t);if(r){u0(t),Z0(t),Yl(e,t,n,R(process.cwd(),n.path));let M=await p0(e,{...r,author:t.author,message:t.message,force:t.force},n);return Uj(M,t.fullHistory===!0)}let i=En(),o=R(process.cwd(),n.path);await j(o);let s=await x(o);Yl(e,t,n,o),wi(t.measure,"validation"),G0(t,[],void 0);let a=P(s,N()),c=await i.resolveList(t.add,"--add"),d=await i.resolveList(t.addJson,"--add-json"),l=await i.resolveList(t.remove,"--remove"),u=[...DF(c),...MF(d)],_=await Qn(u,U(t.author,s.author_default),I())??[],h=PF(l),f=FF(t.removeIndex),g=await Oj({id:e,options:t,pmRoot:o,settings:s,typeToFolder:a.type_to_folder,adds:_,removes:h,removeIndexes:f}),y=Ua(()=>eS(t,g.tests)),w=await Mj(t,o,g.tests),v=t.run===!0?I():void 0,k=await Lj({options:t,runOptions:y,pmRoot:o,untrustedLinkedTestsPolicyEnabled:s.testing.allow_untrusted_linked_tests});g0(e,t,n,o,k);let S=nr(k),b=t.run===!0&&t.failOnSkipped===!0&&k.some(M=>M.status==="skipped"),A=Dj(t,k);w&&A.push(`linked_test_trust_acknowledged:${w.acknowledged}`);let E=await Nj({options:t,pmRoot:o,settings:s,itemId:g.itemId,runStartedAt:v,runResults:k,failOnSkippedTriggered:b,warnings:A}),C=E?.receipt.recorded?eu([...g.testRuns,E.entry]):g.testRuns,O=G0(t,C,E?.entry);return Pj({item:g,runResults:k,failureCategories:S,runSelection:y.runSelection,failOnSkippedTriggered:b,warnings:A,recording:E,measurementProjection:O,restoreScope:f0(n,o),ran:t.run===!0,fullHistory:t.fullHistory===!0})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bc840a99-3b4c-5386-81e2-5480897f2d19")}catch{}})();var Gj=(e,t)=>{if(e===void 0)return;let n=ce(e,t);if(!n){let r=t.definitions.map(i=>i.id);throw new p(`Invalid --status value "${e}". Allowed: ${r.join(", ")}`,m.USAGE)}return n},qj=e=>{if(e===void 0)return;let t=we(e,"timeout");if(t<=0)throw new p("timeout must be a positive number",m.USAGE);return t},nS=(e,t)=>{if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<0)throw new p(`${t} must be a non-negative integer`,m.USAGE);return n},Kj=e=>e instanceof Error?e.message:String(e),Wj=()=>{let e=process.env.PM_BACKGROUND_TEST_RUN_ID?.trim();return e&&e.length>0?e:`test-all-local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`},zj=e=>e.trim().replaceAll(/\s+/g," "),Bj=e=>!e||Object.keys(e).length===0?"{}":JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))),Hj=e=>!e||e.length===0?"[]":JSON.stringify([...e].sort((t,n)=>t.localeCompare(n))),Vj=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"none"},Yj=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"source"},wa=e=>[...new Set(e??[])].sort((t,n)=>t.localeCompare(n)),rS=e=>Object.fromEntries(Object.entries(e??{}).sort(([t],[n])=>t.localeCompare(n))),Jj=e=>typeof e=="number"?e:void 0,Xj=e=>{let t={assert_stdout_contains:wa(e.assert_stdout_contains),assert_stdout_regex:wa(e.assert_stdout_regex),assert_stderr_contains:wa(e.assert_stderr_contains),assert_stderr_regex:wa(e.assert_stderr_regex),assert_stdout_min_lines:Jj(e.assert_stdout_min_lines),assert_json_field_equals:rS(e.assert_json_field_equals),assert_json_field_gte:rS(e.assert_json_field_gte)};return JSON.stringify(t)},Qj=e=>{let t=lu(e.command);return t!==void 0?`command:${e.scope}:${zj(t)}`:`path:${e.scope}:${lu(e.path)??""}`},du=e=>{let t=Bj(e.env_set),n=Hj(e.env_clear),r=Vj(e.pm_context_mode),i=Yj(e.workspace_context_mode),o=e.shared_host_safe===!0?"true":"false",s=Xj(e);return`${Qj(e)}:${t}:${n}:${r}:${i}:${o}:${s}`},Zj=(e,t)=>t===void 0?e:e===void 0||t>e?t:e,eU=e=>{let t=0,n=0,r=0;for(let i of e){if(i.status==="passed"){t+=1;continue}if(i.status==="failed"||i.status==="refused"){n+=1;continue}r+=1}return{passed:t,failed:n,skipped:r}},tU=(e,t)=>{for(let[n,r]of Object.entries(t))e[n]+=r},va=(e,t)=>{if(e.progress===!0)try{process.stderr.write(`[pm test-all] ${t}
|
|
27
|
-
`)}catch{}},nU=async(e,t,n)=>{let r=[],i=0;for(let o of e){let s=await tS(o.id,{run:!1},{...t,path:n});i+=s.tests.length,r.push({item:o,tests:s.tests})}return{itemTests:r,linkedTests:i}},rU=async e=>{let t=W(e.settings.schema),n=P(e.settings,N()),r=Gj(e.options.status,t),i=nS(e.options.limit,"--limit"),o=nS(e.options.offset,"--offset")??0,s=(await Te(e.pmRoot,e.settings.item_format,n.type_to_folder,void 0,e.settings.schema)).filter(a=>r?a.status===r:!0).sort((a,c)=>a.id.localeCompare(c.id));return{filteredItems:i===void 0?s.slice(o):s.slice(o,o+i),statusFilter:r,limitFilter:i,offsetFilter:o}},iS=e=>{let t=e.filter(Ce).map(({provenance:n,provenance_invalid:r,updated_by:i,updated_at:o,note:s,timeout_seconds:a,...c})=>c);return t.length===0?"":Z(t)},oS=(e,t)=>t.length===0?du(e):`${du(e)}:setup[${t}]`,iU=e=>{let t=new Map;for(let{tests:n}of e){let r=iS(n);for(let i of n){if(Ce(i))continue;let o=oS(i,r);if(!t.has(o)){t.set(o,i.timeout_seconds);continue}t.set(o,Zj(t.get(o),i.timeout_seconds))}}return t};function oU(e,t){try{hr(e.command);return}catch(n){if(!(n instanceof p)||n.code!=="linked_test_command_not_executable")throw n;return{command:e.command,path:e.path,status:"refused",exit_code:null,failure_category:"config_refusal",error:`Linked test refused for ${t}: ${n.message}`}}}var sU=(e,t)=>{let n=[],r=[],i=Es(e.tests),o=iS(i),s=li();return{plans:i.map(a=>{let c=Ce(a),d=c?du(a):oS(a,o),l=s.blocked(a);if(l)return{test:a,key:d,duplicate:!1,refusal:l};let u=oU(a,e.item.id);if(u)return{test:a,key:d,duplicate:!1,refusal:s.record(a,u)};if(c)return n.push(a),{test:a,key:d,duplicate:!1,refusal:void 0};if(t.seenTestKeys.has(d))return{test:a,key:d,duplicate:!0,refusal:void 0};t.seenTestKeys.add(d),r.push(d);let _=t.effectiveTimeoutByKey.get(d);return n.push(_===void 0?a:{...a,timeout_seconds:_}),{test:a,key:d,duplicate:!1,refusal:void 0}}),testsToRun:n,reservedKeys:r}},aU=(e,t,n)=>{if(e.some(r=>r.phase==="setup"&&r.status!=="passed"))for(let r of t)n.seenTestKeys.delete(r)},cU=async(e,t)=>{let{plans:n,testsToRun:r,reservedKeys:i}=sU(e,t),o=r.length>0?await cu(r,t.defaultTimeoutSeconds,{progress:t.options.progress,sourceRoots:t.sourceRoots,envSet:t.options.envSet,envClear:t.options.envClear,sharedHostSafe:t.options.sharedHostSafe,pmContext:t.options.pmContext,overrideLinkedPmContext:t.options.overrideLinkedPmContext,failOnContextMismatch:t.options.failOnContextMismatch,failOnEmptyTestRun:t.options.failOnEmptyTestRun,requireAssertionsForPm:t.options.requireAssertionsForPm,checkContext:t.options.checkContext,autoPmContext:t.options.autoPmContext,workspaceContext:t.options.workspaceContext,overrideLinkedWorkspaceContext:t.options.overrideLinkedWorkspaceContext,pmRoot:t.pmRoot,allowUntrustedLinkedTests:t.options.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:t.settings.testing.allow_untrusted_linked_tests}):[];aU(o,i,t);let s=0,a=li(),c=n.map(({test:_,key:h,duplicate:f,refusal:g})=>{if(g)return a.blocked(_)??g;if(!f){let y=o[s];return s+=1,a.blocked(_)??a.record(_,y)}return a.blocked(_)??{command:_.command,path:_.path,status:"skipped",error:`Duplicate linked test skipped (key=${h}).`}}),d=eU(c),l=nr(c),u=await uU(e,d,c,t);return{passed:d.passed,failed:d.failed,skipped:d.skipped,trackingWarnings:u,failureCategories:l,result:{ok:d.failed===0&&!(t.options.failOnSkipped===!0&&d.skipped>0),id:e.item.id,status:e.item.status,test_count:e.tests.length,passed:d.passed,failed:d.failed,skipped:d.skipped,run_results:c,failure_categories:l}}},dU=(e,t)=>[e.failed>0,t.failOnSkipped===!0&&e.skipped>0].includes(!0),lU=e=>e?!0:void 0,uU=async(e,t,n,r)=>{if(!r.trackingEnabled)return[];try{let i=dU(t,r.options);await pa({pmRoot:r.pmRoot,settings:r.settings,itemId:e.item.id,author:r.trackingAuthor,message:`Track test-all run summary (${r.trackingRunId})`,entry:{run_id:r.trackingRunId,kind:"test-all",status:i?"failed":"passed",started_at:r.runStartedAt,finished_at:I(),recorded_at:I(),attempt:r.trackingAttempt,resumed_from:r.trackingResumedFrom,passed:t.passed,failed:t.failed,skipped:t.skipped,items:1,linked_tests:e.tests.length,fail_on_skipped_triggered:lU(r.options.failOnSkipped===!0&&t.skipped>0),executions:n.filter(o=>o.command?.trim()).slice(0,32).map(o=>({command:o.command.trim(),requested_pm_context_mode:o.execution_context?.requested_pm_context_mode,pm_context_mode:o.execution_context?.pm_context_mode,workspace_context_mode:o.execution_context?.workspace_context_mode,trust_reason:o.execution_context?.trust.reason}))}})}catch(i){return en(i)?(r.revisionConflicts.push(i),[]):[`test_result_tracking_failed:${e.item.id}:${Kj(i)}`]}return[]},mU=()=>{let e=process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim(),t=e?Number.parseInt(e,10):Number.NaN;return Number.isFinite(t)&&t>=1?t:void 0},lu=e=>{let t=e?.trim();return t&&t.length>0?t:void 0},pU=e=>({pmRoot:e.pmRoot,settings:e.settings,options:e.options,defaultTimeoutSeconds:e.defaultTimeoutSeconds,sourceRoots:{projectPmRoot:e.pmRoot,globalPmRoot:Ye(process.cwd())},seenTestKeys:new Set,effectiveTimeoutByKey:iU(e.itemTests),trackingEnabled:e.settings.testing.record_results_to_items===!0,trackingAuthor:U(e.options.author,e.settings.author_default),trackingRunId:Wj(),trackingAttempt:mU(),trackingResumedFrom:lu(process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM),runStartedAt:e.runStartedAt,revisionConflicts:[]}),_U=(e,t,n)=>{let r={results:[],passed:0,failed:0,skipped:0,failureCategories:nr([]),trackingWarnings:[]},i=e.failOnEmptyTestRun===!0&&t===0;return i&&(r.failed+=1,r.failureCategories.empty_run+=1,r.trackingWarnings.push(`empty_linked_test_selection:items=${n.length};linked_tests=0;fail_on_empty_test_run=true`)),{accumulation:r,failOnEmptyTestRunTriggered:i}},fU=async(e,t,n)=>{for(let[i,o]of e.entries()){va(t.options,`item ${i+1}/${e.length} start id=${o.item.id} linked_tests=${o.tests.length}`);let s=await cU(o,t);tU(n.failureCategories,s.failureCategories),n.passed+=s.passed,n.failed+=s.failed,n.skipped+=s.skipped,n.trackingWarnings.push(...s.trackingWarnings),n.results.push(s.result),va(t.options,`item ${i+1}/${e.length} end id=${o.item.id} status=${s.failed===0?"passed":"failed"} passed=${s.passed} failed=${s.failed} skipped=${s.skipped}`)}let[r]=t.revisionConflicts;if(r!==void 0)throw r},hU=(e,t)=>{if(e.checkContext!==!0)return;let n=t.results.flatMap(i=>i.run_results),r=su(n);t.trackingWarnings.push(`context_preflight:checked_pm_commands=${r.checked_pm_commands};tracker_read_commands=${r.tracker_read_commands};mismatches=${r.mismatches};auto_remediated=${r.auto_remediated}`)},gU=e=>({ok:e.ok,totals:{items:e.filteredItems.length,linked_tests:e.linkedTests,passed:e.accumulation.passed,failed:e.accumulation.failed,skipped:e.accumulation.skipped,failure_categories:e.accumulation.failureCategories},failed:e.accumulation.failed,passed:e.accumulation.passed,skipped:e.accumulation.skipped,fail_on_skipped_triggered:e.failOnSkippedTriggered?!0:void 0,fail_on_empty_test_run_triggered:e.failOnEmptyTestRunTriggered?!0:void 0,warnings:e.accumulation.trackingWarnings.length>0?e.accumulation.trackingWarnings:void 0,results:e.accumulation.results}),yU=e=>[`selection items=${e.filteredItems.length}`,`linked_tests=${e.linkedTests}`,e.statusFilter===void 0?"":`status=${e.statusFilter}`,e.limitFilter===void 0?"":`limit=${e.limitFilter}`,e.offsetFilter>0?`offset=${e.offsetFilter}`:""].filter(t=>t.length>0).join(" "),wU=async(e,t)=>{let n=R(process.cwd(),t.path);await j(n);let r=await x(n),i=await rU({pmRoot:n,settings:r,options:e}),o=qj(e.timeout),s=I(),a=await nU(i.filteredItems,t,n);return va(e,yU({...i,linkedTests:a.linkedTests})),{pmRoot:n,settings:r,filteredItems:i.filteredItems,itemTests:a.itemTests,linkedTests:a.linkedTests,defaultTimeoutSeconds:o,runStartedAt:s}},vU=e=>{let t=e.options.failOnSkipped===!0&&e.accumulation.skipped>0,n=![e.accumulation.failed>0,t,e.failOnEmptyTestRunTriggered].includes(!0);return{failOnSkippedTriggered:t,ok:n}},MY=async(e,t)=>{let n=await wU(e,t),{accumulation:r,failOnEmptyTestRunTriggered:i}=_U(e,n.linkedTests,n.filteredItems),o=pU({pmRoot:n.pmRoot,settings:n.settings,options:e,itemTests:n.itemTests,defaultTimeoutSeconds:n.defaultTimeoutSeconds,runStartedAt:n.runStartedAt});await fU(n.itemTests,o,r),hU(e,r);let s=vU({options:e,accumulation:r,failOnEmptyTestRunTriggered:i});return va(e,`end status=${s.ok?"passed":"failed"} items=${n.filteredItems.length} linked_tests=${n.linkedTests} passed=${r.passed} failed=${r.failed} skipped=${r.skipped}`),gU({ok:s.ok,filteredItems:n.filteredItems,linkedTests:n.linkedTests,accumulation:r,failOnSkippedTriggered:s.failOnSkippedTriggered,failOnEmptyTestRunTriggered:i})};import JU from"node:os";import lr from"node:fs/promises";import{spawn as lS}from"node:child_process";import{createHash as bU,randomBytes as kU}from"node:crypto";import Ti from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7a7096c6-a9c3-5d8e-96e4-ed1b0218234e")}catch{}})();var uS=new Set(["queued","running"]),_u=new Set(["passed","failed","stopped","canceled"]),SU=3e3,EU=3e3,TU=3e4,mS=100,sS=100;function pS(){return Date.now()}function _S(e){return e.map(t=>t.trim()).filter(t=>t.length>0)}function CU(e){let t=e.join(" ").replaceAll(/\s+/g," ").trim();return t.length<=180?t:`${t.slice(0,177)}...`}function AU(){let e=Date.now().toString(36),t=kU(3).toString("hex");return`tr-${e}-${t}`}function xU(e,t,n){let r={kind:e,command:_S(t),pm_root:Ti.resolve(n)};return bU("sha256").update(JSON.stringify(r)).digest("hex")}function ur(e){if(!Number.isInteger(e)||!e||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)==="EPERM"}}async function RU(e){await Ct(am(e)),await Ct(Na(e)),await Ct(cm(e)),await Ct(dm(e)),await Ct(mm(e))}async function fS(e,t){try{let n=JSON.parse(e);if(!n||typeof n!="object"||typeof n.id!="string")throw new Error("invalid run record payload");return n}catch(n){throw new p(`Failed to parse background test run record at ${t}: ${n instanceof Error?n.message:String(n)}`,m.GENERIC_FAILURE)}}async function pt(e,t){let n={...t,updated_at:I()};await je(Ma(e,t.id),`${JSON.stringify(n,null,2)}
|
|
28
|
-
`)}async function
|
|
29
|
-
`);return}await je(e.result_path,`${JSON.stringify({parse_error:"Background run output was not valid JSON.",stdout_excerpt:
|
|
30
|
-
`)}async function yS(e,t,n=!1){let r=await
|
|
31
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{a as Th}from"./chunk-HQYIKAC6.js";import{J as ih,a as bo,b as xr,c as ko,d as Oe,e as So,f as eh,g as th,h as Eo,i as Rr,j as nh,k as rh,l as hc,m as gc,n as Ir,r as Or,t as To,u as te,y as yc}from"./chunk-36R3JTAD.js";import{Ba as yh,Ga as wh,Ka as Ec,j as i_,la as vc,va as bc,wa as gh,xa as kc,y as hh,ya as Sc}from"./chunk-3IU2S5UQ.js";import{a as Nr,b as ph,i as Dt,k as Dn,l as $n,m as Nn}from"./chunk-H64BNM4A.js";import{c as mh}from"./chunk-Y4LXVPA5.js";import{A as Ln,B as de,D as Co,G as Ao,H as ch,Ha as kh,Ia as Sh,J as wc,Ja as Mr,K as dh,Ka as Tc,M as lh,Mc as Ih,Na as Eh,Pc as Oh,U as uh,_a as Pr,bb as Mn,eb as Pn,l as oh,lb as Ch,o as sh,oa as vh,p as Lr,pa as bh,pb as Ah,qb as xh,s as ah,wb as Rh,y as Dr,z as $r}from"./chunk-X5TFNFTS.js";import{a as r_}from"./chunk-RXNBNF6O.js";import{$ as cc,$a as Af,$b as wo,Aa as of,Ab as Kf,B as sc,Bb as Wf,C as ac,D as u_,E as yo,Ea as sf,F as m_,Fa as af,G as p_,Ga as cf,H as __,Ha as df,I as f_,Ia as lf,J as h_,Ja as uf,K as g_,Ka as mf,L as y_,La as pf,M as w_,Ma as _f,N as v_,Na as ff,O as b_,Oa as hf,P as k_,Pa as gf,Q as S_,Qa as yf,R as E_,Ra as wf,S as T_,Sa as vf,T as C_,Ta as bf,U as A_,Ua as kf,V as x_,Va as Sf,W as R_,Wa as lc,X as I_,Xa as Ef,Y as O_,Ya as Tf,Za as uc,_ as L_,_a as Cf,_b as zf,aa as D_,ab as xf,ac as Bf,b as o_,ba as $_,bb as Rf,bc as _c,c as s_,ca as N_,cb as If,d as a_,da as M_,db as Lt,dc as Hf,ea as P_,eb as Of,ec as Vf,fa as F_,fb as Lf,ga as j_,gb as Df,gc as Yf,ha as U_,hb as $f,hc as Jf,ia as G_,ic as vo,ja as q_,jb as Nf,jc as Xf,ka as K_,la as W_,lb as Ar,ma as z_,na as B_,nb as Mf,o as ic,oa as H_,ob as Pf,p as c_,pa as dc,pb as Ff,pc as fc,qa as V_,qb as jf,ra as Y_,s as d_,sa as J_,sb as Uf,t as oc,ta as X_,tc as Qf,u as tn,ua as Q_,va as Z_,w as l_,wa as ef,wb as mc,wc as Zf,xa as tf,xb as Gf,ya as nf,yb as qf,za as rf,zb as pc}from"./chunk-7K2RUKMK.js";import{d as Qp,j as Zp,r as e_,s as en,t as t_,w as n_}from"./chunk-VLKCFZY6.js";import{$b as Gp,A as En,Ab as he,Ad as go,B as we,Ba as Tr,Bd as Xp,C as Ni,Cb as Xa,D as Ga,Db as Mp,E as fr,F as hr,G as gr,H as ft,I as ym,J as qi,La as po,Nb as Pp,Oa as On,Oc as Za,Pa as kp,Pc as ec,Qa as Sp,Qc as tc,R as Bi,Ra as Ap,Rc as nc,Sb as Fp,T as xt,U as io,Ub as jp,V as oo,Xb as Qa,Y as yp,Ya as xp,Zb as Up,ac as It,bc as qp,c as at,cc as Ot,dc as Cr,e as ct,eb as Rp,ec as Zt,f as kn,g as Oa,ga as so,gc as Kp,gd as Bp,h as Hu,i as Oi,ib as Op,j as Li,jb as Lp,k as Vu,ka as Xe,l as Di,la as wp,ld as rc,m as Yu,mb as Dp,n as Ju,na as ao,nb as _o,o as ee,oa as vp,ob as $p,od as Hp,p as Sn,pa as co,pc as Wp,q as mr,qa as lo,qb as V,r as ke,ra as uo,rb as pe,tb as fo,tc as zp,td as Vp,ub as Te,ud as Yp,v as dt,va as mo,vb as gt,vd as ho,wb as Np,wd as Jp,x as Wt,xb as Qt,ya as bp,z as $i,zb as Rt}from"./chunk-AM26RAG7.js";import{C as Ip,I as j,a as Xt,b as Er,e as Rn,f as In,g as Ja,l as Ep,u as Tp,v as x,w as Cp}from"./chunk-CR5GC3VO.js";import{$a as cm,$b as Wi,$c as Ba,$d as Va,Ad as to,B as Fu,Bb as wm,C as ju,Cc as W,D as Uu,Db as Ht,Dc as Je,E as Gu,Ec as Vt,Ee as Hm,Eg as tp,Eh as sp,F as qu,Fa as Na,Fe as Vm,G as Ku,Ga as pr,Gc as At,H as st,Ha as xe,Hc as Tm,Hd as Wm,I as Wu,Ib as oe,Ic as Wa,Jc as Cm,Ka as P,Kc as za,Kd as wr,La as _t,Lb as Ki,Lc as Am,Ld as vr,Li as no,Ma as Fi,Mc as Vi,Na as Cn,Ni as ro,O as zu,Oa as _r,Oc as xm,Oh as ap,P as Bu,Pa as zt,Pc as Rm,Q as Ia,Qc as Im,Qe as Ym,Qh as cp,Rc as Yi,Sa as R,Sc as yr,Sf as Qm,Sh as kr,Ta as lt,Tf as Zm,Ua as Ye,Uc as Ji,Uh as dp,Va as Re,Vd as zm,Wa as om,Wi as up,Xa as sm,Xb as I,Xc as Xi,Xf as ep,Xh as lp,Ya as Bt,Yb as vm,Yc as ce,Za as ji,Zb as qa,Zc as Yt,_a as am,_b as bm,_c as fe,a as Z,ab as Ma,ad as Ha,ae as U,ah as np,b as Fe,bb as Pa,bc as me,bd as Om,c as Mu,cb as dm,cc as km,ce as Jt,cj as N,db as lm,dc as An,dd as Qi,e as Pu,eb as um,ec as Ka,fa as La,fb as mm,fc as zi,fd as Lm,fe as Bm,gb as pm,gd as xn,hb as _m,hd as Dm,ib as Fa,id as $m,ja as Da,jd as Nm,jj as mp,ka as Ke,kb as fm,kd as Mm,kf as Jm,kj as pp,la as Mi,lb as L,lc as Sm,ma as Pi,md as Zi,na as Qu,nd as Pm,nj as ht,ob as Ui,od as Fm,of as Xm,pa as Zu,pb as ja,qa as em,qb as hm,qj as _p,ra as tm,rb as Gi,ri as Sr,rj as We,sa as nm,sb as gm,sh as rp,sj as fp,t as ot,tb as Ua,tf as Ya,th as ip,tj as hp,ua as rm,uc as Em,ud as jm,uh as op,uj as gp,v as K,va as im,vd as Um,w as Ii,wa as $a,wd as Gm,x as Kt,xd as qm,yb as Ie,yd as Km,zc as Hi,zd as eo,zh as br}from"./chunk-7UUPLMCU.js";import{b as _h}from"./chunk-VS565KBX.js";import{a as fh}from"./chunk-SPPHDVZE.js";import{A as m,C as p,D as Ct,E as ie,F as Tn,G,H as Q,K as je,M as Xu,a as Iu,m as Ou,p as Lu,s as Du,u as $u,w as Nu,x as Ri,y as qt}from"./chunk-5OFMWP3Q.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="11e0a702-31a9-577b-a9c3-464830765883")}catch{}})();var sE=Object.freeze({"--body":"Set the item body.","--body-file":"Read the item body from a file, or from stdin when set to -.","--description":"Set the item description.","--stdin":"Read the value from stdin.","--stdin-json":"Read a complete JSON document from stdin."}),aE=new Set(["--add","--body","--comment","--dep","--dep-remove","--description","--doc","--event","--field","--file","--learning","--note","--remove","--reminder","--test","--type-option"]),cE=new Set(["append","comments","create","docs","files","learnings","notes","test","update","update-many"]),dE=new Set(["close-many:--ids","comments:--file","create:--body-file","history-compact:--ids","learnings:--file","notes:--file","update:--body-file","update-many:--ids"]),lE=new Set(["close-many:--ids","history-compact:--ids","update-many:--ids"]),uE=["--allow-","--check-","--dry-run","--explain","--fail-","--fix-","--full","--has-","--include-","--json","--no-","--prune-","--quiet","--refresh-","--require-","--runtime-only","--schema-only","--skip-","--stream","--strict-","--summary","--today","--verbose"],mE=new Set(["--activate","--active-only","--adopt","--adopt-all","--all","--all-actionable","--all-affected-ids","--all-day","--all-streams","--acknowledge-linked-tests","--append-stable","--auto-fix","--auto-pm-context","--availability-only","--background","--brief","--by-assignee","--by-priority","--by-tag","--catalog","--claim","--clear","--clear-comments","--clear-criteria","--clear-deps","--clear-docs","--clear-events","--clear-files","--clear-learnings","--clear-notes","--clear-reminders","--clear-tests","--clear-type-options","--cli-only","--closed","--compact","--completion","--count","--counts","--deactivate","--declarative","--defaults","--describe","--diff","--doctor","--empty-body","--explore","--field-utilization","--filter-empty-body","--flags-only","--follow","--force","--global","--highlight","--hybrid","--id-only","--if-available","--ignore-global","--include_unparented","--infer","--init","--install","--isolated","--lean","--list","--local","--manage","--markdown","--metadata-coverage","--next","--normalize-provenance","--only","--only-last","--output-row-contract","--override-linked-pm-context","--override-linked-workspace-context","--packages-only","--past","--phrase-exact","--profile","--progress","--project","--promote-to-item-dep","--provenance","--provenance-summary","--raw","--ready-only","--ready_only","--rebuild","--recent","--reload","--repair","--replace-deps","--replace-docs","--replace-files","--replace-tests","--required","--required-on-create","--run","--runtime-probe","--save-baseline","--scaffold","--semantic","--shared-host-safe","--storage","--takeover-stale","--title-exact","--token-accounting","--trace","--tree","--unbounded","--uninstall","--validate-paths","--verify","--watch","--with-packages"]),pE=new Set(["--only-index"]),_E=new Set(["activity:--stream","eval:--fail-under","validate:--fix-scope"]),fE=new Set(["activity:--stream","close:--validate-close","close-many:--validate-close","comments:--author","learnings:--author","notes:--author"]),hE=new Set(["--regression"]);function gE(e,t){return t==="--stdin"||t==="--stdin-json"?["stdin"]:dE.has(`${e}:${t}`)?["argv","file","stdin"]:t.endsWith("-file")?["argv","file"]:aE.has(t)&&cE.has(e)?["argv","stdin"]:["argv"]}function yE(e,t){let n=_E.has(`${e}:${t.flag}`)||t.value_name!==void 0||t.value_type==="string"||t.value_type==="number"||t.list===!0||t.repeatable===!0,r=t.value_type==="boolean"||t.flag==="--stdin"||t.flag==="--stdin-json"||t.flag.startsWith("--filter-")&&(t.flag.endsWith("-missing")||t.flag.startsWith("--filter-has-")||t.flag.startsWith("--filter-no-"))||uE.some(i=>t.flag.startsWith(i));return n||pE.has(t.flag)||!mE.has(t.flag)&&!r}function wE(e,t){return t.value_arity!==void 0?t.value_arity:yE(e,t)?hE.has(t.flag)||fE.has(`${e}:${t.flag}`)?"optional":"required":"none"}function vE(e,t){let n=Ii(e),r=wE(n,t),i=r!=="none",o=gE(n,t.flag),s=t.description??sE[t.flag]??`${i?"Set":"Enable"} ${t.flag.slice(2).replaceAll("-"," ")}.`;return{...t,description:s,takes_value:i,value_required:r==="required",...i?{value_name:t.value_name??"value"}:{},value_type:i?t.value_type??"string":"boolean",required:t.required===!0,repeatable:t.repeatable===!0||t.list===!0,input_sources:o,...o.includes("stdin")&&t.flag!=="--stdin"&&t.flag!=="--stdin-json"?{stdin_token:"-"}:{},...lE.has(`${n}:${t.flag}`)?{file_token_prefix:"@"}:{}}}function Lh(e,t){return t.map(n=>vE(e,n))}function rG(e,t,n){let r=e.trim().toLowerCase(),i=[],o=new Map,s=0;for(let c of n)if(c.command.trim().toLowerCase()===r){if(s+=1,o.has(c.flag)){i.push({code:"duplicate_observation",command:r,flag:c.flag,detail:`${r} ${c.flag} was observed more than once.`});continue}o.set(c.flag,c)}let a=new Set(t.map(({flag:c})=>c));for(let c of t){let d=o.get(c.flag);if(!d){i.push({code:"missing_observation",command:r,flag:c.flag,detail:`${r} ${c.flag} has no executable option observation.`});continue}for(let[l,u]of[["takes_value","takes_value_mismatch"],["value_required","value_required_mismatch"],["repeatable","repeatable_mismatch"]])c[l]!==d[l]&&i.push({code:u,command:r,flag:c.flag,detail:`${r} ${c.flag} declares ${l}=${String(c[l])} but the executable option reports ${String(d[l])}.`})}for(let c of o.values())a.has(c.flag)||i.push({code:"undeclared_observation",command:r,flag:c.flag,detail:`${r} ${c.flag} is executable but absent from invocation contracts.`});return i.sort((c,d)=>c.flag.localeCompare(d.flag)||c.code.localeCompare(d.code)),{ok:i.length===0,declared_count:t.length,observed_count:s,findings:i}}import{readFile as bE}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="59163d45-c136-5ead-adf1-b08ebb9c27ae")}catch{}})();function SG(e){let t={...e,...e.full===!0?{fullHistory:!0}:{}};return delete t.full,dt(e,t)}function Fh(e){return Object.prototype.toString.call(e)==="[object Object]"}function kE(e,t,n,r){let i=I();if(!Fh(e))return{...r({created_at:i,author:n,text:t}),text:t,edited_at:i};let o=s=>typeof s=="string"&&s!=="";return{...e,...o(e.created_at)?{}:{created_at:i},...o(e.author)?{}:{author:n},text:t,edited_at:i}}function Dh(e,t){if(typeof e=="object"&&e!==null&&"format"in e&&e.format==="json")throw new p(`Structured context events are append-only and cannot be ${t}.`,m.USAGE,{code:"structured_event_immutable"})}function SE(e,t){return t===void 0?e:t===0?[]:e.slice(Math.max(0,e.length-t))}function nn(e,t){let n=e[t];return Array.isArray(n)?n:[]}function EG(e,t={}){let n=e.trim();if(!n)return"";let r=/^(?:[-*+]\s*)?text\s*[:=]/i.exec(n);if(t.stripPlainTextPrefix===!0&&r&&!n.startsWith("```"))return n.slice(r[0].length).trim()||n;if(!(/^(?:[-*+]\s*)?text\s*[:=]/im.test(n)||n.startsWith("```")))return n;try{let i=ee(n,"--add");return Object.keys(i).map(o=>o.trim().toLowerCase()).some(o=>o!=="text")?n:i.text?.trim()||n}catch{return n}}function EE(e){return typeof e=="object"&&e!==null&&"code"in e}function $h(e,t){if(!Wt(e))throw new p(`${t} cannot read process stdin through the MCP JSON-RPC transport. Pass annotation text in options.add instead.`,m.USAGE,{code:"mcp_stdin_unavailable",required:"Pass annotation text as JSON data; the MCP protocol already owns process stdin."})}async function TE(e,t){if(+(e.add!==void 0)+ +(e.stdin===!0)+ +(typeof e.file=="string")>1)throw new p(`Specify ${t} text using only one input source: --add, --stdin, or --file`,m.USAGE);let n=En(),r=Wt(e);if(e.add!==void 0)return{value:await n.resolveValue(e.add,"--add",r)??"",rawValue:e.add,emptyFlag:"--add"};if(e.stdin===!0)return $h(e,"--stdin"),{value:await n.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};if(typeof e.file!="string")return;let i=e.file.trim();if(!i)throw new p("--file path cannot be empty",m.USAGE);if(i==="-")return $h(e,"--file -"),{value:await n.resolveValue("-","--file")??"",emptyFlag:"--file"};try{return{value:await bE(i,"utf8"),emptyFlag:"--file"}}catch(o){if(EE(o)&&Tn(o))throw new p(`--file path not found: ${i}. Use --file - to read stdin.`,m.USAGE);let s=o instanceof Error?o.message:String(o);throw new p(`Failed to read --file path "${i}": ${s}. Use --file - to read stdin.`,m.USAGE)}}async function TG(e,t){if(e.edit!==void 0&&e.delete!==void 0)throw new p("Specify only one of --edit or --delete",m.USAGE);if(e.delete!==void 0){if(e.add!==void 0||e.stdin===!0||typeof e.file=="string")throw new p("--delete cannot be combined with replacement text",m.USAGE);if(!Number.isInteger(e.delete)||e.delete<1)throw new p("--delete must be a positive integer",m.USAGE);return{mode:"delete",index:e.delete}}if(e.edit!==void 0&&(!Number.isInteger(e.edit)||e.edit<1))throw new p("--edit must be a positive integer",m.USAGE);let n=await TE(e,t);if(e.edit!==void 0){if(!n)throw new p("--edit requires replacement text from --add, --stdin, or --file",m.USAGE);return{mode:"edit",index:e.edit,...n}}return n?{mode:"add",...n}:{mode:"list"}}function Fr(e,t){throw e instanceof p&&e.exitCode===m.CONFLICT&&e.message.includes("is assigned to")&&e.message.includes("Use --force to override")?new p(e.message,e.exitCode,{code:"ownership_conflict",required:t.required,examples:t.examples,nextSteps:t.nextSteps}):e}function jh(e){return e==="comments"?"--stdin":"--add -"}var CG="annotation_flag_like_value";function CE(e){return/^-{1,2}[A-Za-z][\w-]*(?:=.*)?$/.test(e.trim())}function AE(e){return e==="--file"?"--file <path>":e.startsWith("--file=")?e:e==="--stdin"?"--stdin":void 0}function xE(e){let t=e.value.trim(),n=e.collectionKey.replace(/s$/,""),r=AE(t),i=jh(e.collectionKey),o=e.retryArgs===void 0?{}:{field:e.textFlag,recovery:{suggested_flags:[t],suggested_retry:L(e.retryArgs),suggested_retry_args:[...e.retryArgs]}};if(r!==void 0){let s=r.split(/[ =]/,1)[0],a=s==="--file"?"that file":"stdin",c=e.conflictingOperand===void 0?"":` "${e.conflictingOperand}" was read as positional text, which ${s} cannot be combined with: drop it, or pass it as the text without ${s}.`;return new p(`${e.textFlag} value "${t}" looks like an option, not annotation text: ${e.textFlag} took ${s} as its value. Drop ${e.textFlag} and pass ${r} on its own.${c}`,m.USAGE,{code:"annotation_flag_like_value",required:`Drop ${e.textFlag}: ${r} reads the ${n} text from ${a} by itself. Use ${e.textFlag} text=${t} only when the text really is "${t}".`,examples:[`${e.commandPrefix} ${r}`,`${e.commandPrefix} ${e.textFlag} text=${t}`],...o})}return new p(`${e.textFlag} value "${t}" looks like an option, not annotation text. Use ${i} to read stdin, or use text=${t} for literal dash-leading text.`,m.USAGE,{code:"annotation_flag_like_value",required:`Use ${i} for stdin input, pass plain text, or use text=${t} when the text really starts with "-".`,examples:[`${e.commandPrefix} ${i}`,`${e.commandPrefix} ${e.textFlag} text=${t}`],...o})}function RE(e,t){if(!((t.input.emptyFlag??"--add")!=="--add"||!CE(e)))throw xE({collectionKey:t.collectionKey,textFlag:"--add",value:e,commandPrefix:t.input.mode==="edit"?`pm ${t.collectionKey} <id> --edit <index>`:`pm ${t.collectionKey} <id>`})}function IE(e,t,n,r,i){if(n.input.mode!=="edit")return;let o=Vm(t);if(o===void 0)return;let s=n.collectionKey.replace(/s$/,""),a=n.input.index,c=Ie(r)[0]==="--pm-path"?["--pm-path",i]:[];throw new p(`Replacement text for ${s} ${a} on ${e} ends with the read-output compaction marker, so it was copied from a compacted read that left out ${o} characters. Nothing was written.`,m.USAGE,{code:"annotation_text_compacted",item_id:e,details:{collection:n.collectionKey,entry_index:a,omitted_characters:o},required:`Read the whole ${s} with --output-budget unbounded, apply the change to the full text, and retry the edit without the trailing marker.`,why:"A budgeted read shortens long entries to a prefix plus a marker naming how many characters it left out; editing from that text would replace the stored entry with the shortened prefix.",examples:[L([...c,n.collectionKey,e,"--output-budget","unbounded","--json"]),`${L([...c,n.collectionKey,e,"--edit",String(a),"--file"])} <full-text-file>`]})}function OE(e,t){if(t.ifAbsent===!0&&!["add","stdin","file"].includes(e.input.mode))throw new p(`--if-absent requires a ${e.collectionKey.replace(/s$/,"")} append`,m.USAGE,{code:"annotation_if_absent_without_append",required:"Combine --if-absent with one append text source; omit it for list, edit, and delete operations."});if(LE(e,t),e.input.mode!=="list"||t.message===void 0)return;let n=e.collectionKey.replace(/s$/,"");throw new p(`--message labels a ${n} mutation but does not provide ${n} text. Pass text positionally or with --add, --stdin, or --file.`,m.USAGE,{code:"annotation_message_without_text",required:`Provide ${n} text through a content source; --message only annotates the history entry of a mutation.`,examples:[`pm ${e.collectionKey} <id> --add "text" --message "why"`,`pm ${e.collectionKey} <id> ${jh(e.collectionKey)}`]})}function LE(e,t){if(t.expectAt!==void 0){if(e.input.mode!=="edit"&&e.input.mode!=="delete")throw new p(`--expect-at guards an --edit or --delete of one ${e.collectionKey.replace(/s$/,"")}`,m.USAGE,{code:"annotation_expectation_without_target",required:"Combine --expect-at with --edit <index> or --delete <index>; omit it for list and append operations.",examples:[`pm ${e.collectionKey} <id> --edit <index> --expect-at <created_at> --add "<text>"`,`pm ${e.collectionKey} <id> --delete <index> --expect-at <created_at>`]});if(typeof t.expectAt!="string"||t.expectAt.trim().length===0)throw new p("--expect-at must be the non-empty created_at timestamp of the entry you read",m.USAGE,{code:"annotation_expectation_invalid",required:"Pass the created_at value of the row you read at that index, as a string."})}}function Nh(e,t,n,r,i){if(i===void 0)return;let o=t[n]?.created_at,s=typeof o=="string"?o:null;if(s===i)return;let a=t.flatMap((_,h)=>_?.created_at===i?[h+1]:[]),c=r.collectionKey.replace(/s$/,""),d=r.input.mode==="delete"?"--delete":"--edit",l=n+1,u=a.length===1?` The ${c} created at ${i} is at index ${a[0]}.`:a.length>1?` ${a.length} ${r.collectionKey} were created at ${i}: indexes ${a.join(", ")}.`:` No ${c} on ${e} was created at ${i}.`;throw new p(`${c.charAt(0).toUpperCase()}${c.slice(1)} ${l} on ${e} was created at ${s||"an unrecorded time (malformed entry)"}, not ${i}; refusing ${d} of an entry the caller did not read. Nothing was written.${u}`,m.CONFLICT,{code:"annotation_entry_mismatch",item_id:e,details:{collection:r.collectionKey,entry_index:l,expected_created_at:i,actual_created_at:s,matching_indexes:a},required:`Address the ${c} by the index its listing row reports and keep --expect-at set to that row's created_at. When several indexes share the timestamp, inspect those rows before retrying, because the guard compares timestamps, not entry identities.`,why:"A listing page's position or count is not an entry address; only the row's index is, and the expectation checks that the entry at that index still carries the created_at that was read.",examples:[`pm ${r.collectionKey} ${e} --limit 5`,`pm ${r.collectionKey} ${e} ${d} ${a.length===1?a[0]:"<index>"} --expect-at ${i}${d==="--edit"?' --add "<text>"':""}`]})}function DE(e,t,n,r,i,o){let s=nn(e.metadata,t),a=i?s.findIndex(c=>Fh(c)&&c.author===n&&c.text===r):-1;return a>=0?{changedFields:[],written:s,position:a}:(s.push(o({created_at:I(),author:n,text:r})),e.metadata[t]=s,{changedFields:[t],written:s,position:s.length-1})}function Mh(e,t,n){return Dm.has(e)?t.map((r,i)=>i).sort((r,i)=>$m(t[r],t[i])||r-i).indexOf(n)+1:n+1}async function AG(e,t,n,r){OE(r,t);let i=R(process.cwd(),n.path);await j(i);let o=await x(i),s=P(o,N()),a=Tr(t.limit);if(r.input.mode==="list"){let f=await V(i,e,o.id_prefix,o.item_format,s.type_to_folder);if(!f)throw new p(`Item ${e} not found`,m.NOT_FOUND);let g=await pe(f,{schema:o.schema}),y=nn(g.document.metadata,r.collectionKey);return xo(f.id,r.collectionKey,y,a,t.includeMeta===!0)}let c=U(t.author,o.author_default);if(r.input.mode==="delete"){let f=r.deleteOp??r.op,g;try{g=await he({pmRoot:i,settings:o,id:e,op:f,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(w){let v=nn(w.metadata,r.collectionKey),k=Ph(r.input.index,v.length,r.collectionKey);return Nh(e,v,k,r,t.expectAt),Dh(v[k],"deleted"),v.splice(k,1),w.metadata[r.collectionKey]=v,{changedFields:[r.collectionKey]}}})}catch(w){Fr(w,r.conflictGuidance)}let y=nn(g.item,r.collectionKey);return xo(g.item.id,r.collectionKey,y,a,t.includeMeta===!0,{action:"delete",entryIndex:r.input.index},t.fullHistory===!0)}let d=r.input.rawValue??r.input.value??"";RE(d,r);let l=r.parseText(r.input.value??"");if(!l.trim())throw new p(`${r.input.emptyFlag??"--add"} text cannot be empty`,m.USAGE);if(IE(e,l,r,n,i),r.input.mode==="edit"){let f=r.editOp??r.op,g,y=0;try{g=await he({pmRoot:i,settings:o,id:e,op:f,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(k){let S=nn(k.metadata,r.collectionKey),b=Ph(r.input.index,S.length,r.collectionKey);Nh(e,S,b,r,t.expectAt);let A=S[b];return Dh(A,"edited"),S[b]=kE(A,l,c,r.createEntry),y=Mh(r.collectionKey,S,b),k.metadata[r.collectionKey]=S,{changedFields:[r.collectionKey]}}})}catch(k){Fr(k,r.conflictGuidance)}let w=nn(g.item,r.collectionKey),v=y;return xo(g.item.id,r.collectionKey,w,a,t.includeMeta===!0,{action:"edit",entryIndex:v,entry:w[v-1]},t.fullHistory===!0)}let u,_=0;try{u=await he({pmRoot:i,settings:o,id:e,op:r.op,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,skipNoop:t.ifAbsent===!0,mutate(f){let g=DE(f,r.collectionKey,c,l,t.ifAbsent===!0,r.createEntry);return _=Mh(r.collectionKey,g.written,g.position),{changedFields:g.changedFields}}})}catch(f){Fr(f,r.conflictGuidance)}let h=nn(u.item,r.collectionKey);return xo(u.item.id,r.collectionKey,h,a,t.includeMeta===!0,{action:"add",entryIndex:_,entry:h[_-1],changedCount:t.ifAbsent===!0?Math.min(u.changedFields.length,1):void 0},t.fullHistory===!0)}function Ph(e,t,n){if(e===void 0||!Number.isInteger(e)||e<1||e>t){let r=n.replace(/s$/,""),i=`${r.charAt(0).toUpperCase()}${r.slice(1)}`,o=t===1?`1 ${r}`:`${t} ${n}`;throw new p(`${i} index ${e??"(missing)"} out of range (item has ${o})`,m.USAGE)}return e-1}function $E(e,t,n){return t===void 0?{}:{mutation_receipt:{action:t.action,entry_index:t.entryIndex,changed_count:t.changedCount??1,full_history_included:!n},omission_receipt:{has_omissions:n,omitted_field_group_count:n?1:0,omitted_field_groups:n?[{name:`${e}_history`,restore_with:{selector:"full_history",cli_flag:"--full-history",sdk_option:"fullHistory",mcp_option:"full"}}]:[]}}}function Uh(e,t){if(Object.prototype.toString.call(e)!=="[object Object]")return e;let n={index:t,...e};return n.index=t,n}function NE(e,t){let n=e.length-t.length;return t.map((r,i)=>Uh(r,n+i+1))}function xo(e,t,n,r,i,o,s=!1){let a=o===void 0||s?NE(n,SE(n,o!==void 0&&s?void 0:r)):o.entry===void 0?[]:[Uh(o.entry,o.entryIndex)],c=o!==void 0&&a.length<n.length;return{id:e,[t]:a,count:a.length,...o?.changedCount===void 0?{}:{changed:o.changedCount===1},...[i,o!==void 0].includes(!0)?{total_count:n.length,returned_count:a.length,has_more:c||a.length<n.length,...r!==void 0?{limit:r}:{}}:{},...$E(t,o,c)}}import{isDeepStrictEqual as zh}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ab4e2ed3-e7e8-5a7a-a13e-7b8dce750dc4")}catch{}})();var ME=new Set(["__proto__","prototype","constructor"]),Ac=Symbol("looseOptionOccurrences");function $t(e){return e.trim().toLowerCase().replaceAll(/-([a-z0-9])/g,(t,n)=>n.toUpperCase())}function PE(e,t,n){let r=e[t];if(r===void 0){e[t]=n;return}if(Array.isArray(r)){r.push(n),e[t]=r;return}e[t]=[r,n]}function xc(e,t){let n=e[t];if(!n.startsWith("-")||n==="-"||n==="--")return null;if(!n.startsWith("--")){let s=n.indexOf("=");if(s>=0)return{consumed:1,key:n.slice(1,s).trim(),value:n.slice(s+1),attached:!0};let a=n.slice(1).trim(),c=e[t+1];return typeof c=="string"&&!c.startsWith("-")?{consumed:2,key:a,value:c}:{consumed:1,key:a,value:!0}}let r=n.indexOf("=");if(r>=0)return{consumed:1,key:n.slice(2,r).trim(),value:n.slice(r+1),attached:!0};if(n.startsWith("--no-"))return{consumed:1,key:n.slice(5).trim(),value:!1};let i=n.slice(2).trim(),o=e[t+1];return typeof o=="string"&&!o.startsWith("-")?{consumed:2,key:i,value:o}:{consumed:1,key:i,value:!0}}function Io(e){return ME.has(e)}function Oo(e){let t=(typeof e.value_type=="string"?e.value_type:void 0)??(typeof e.type=="string"?e.type:void 0);return km(t)}function jr(e){let t=[],n=Ht(e.long)??"",r=typeof e.short=="string"?e.short.trim():"";if(n.startsWith("--")){let i=$t(n.slice(2));i.length>0&&!Io(i)&&t.push(i)}if(r.startsWith("-")&&!r.startsWith("--")){let i=$t(r.slice(1));i.length>0&&!Io(i)&&t.push(i)}return[...new Set(t)]}function DG(e){let t=new Set;for(let n of e)for(let r of jr(n))t.add(r);return t}function Fn(e){let t=Ht(e.long)??"";if(t.startsWith("--")){let n=$t(t.slice(2));if(n.length>0&&!Io(n))return n}return jr(e)[0]??null}function jn(e){let t=Ht(e.long)??"";if(t.startsWith("--")&&t.length>2)return t;let n=typeof e.short=="string"?e.short.trim():"";return n.startsWith("-")&&!n.startsWith("--")&&n.length>1?n:null}function Bh(e,t){return[...(t.definitions??e).map(n=>jn(n)).filter(n=>n!==null),...t.inheritedFlags??[]]}function $G(e,t,n,r={}){if(t.length===0)return;let i=new Set,o=new Map,s=[],a=Bh(t,r);for(let c of t){let d=jr(c),l=jn(c);for(let u of d)i.add(u),c.enabled===!1&&o.set(u,l);c.required===!0&&c.enabled!==!1&&d.length>0&&s.push({keys:d,label:l,definition:c})}for(let c of Object.keys(e)){i.has(c)||Hh(`--${c}`,`--${c}`,n,a);let d=o.get(c);d&&Vh(d,n)}for(let c of s){let d=l=>Object.hasOwn(e,l)&&(c.definition.list!==!0||Xh(c.definition,e[l]));c.keys.some(d)||Yh(c.definition,c.keys[0],c.label,n)}}function Hh(e,t,n,r){let i=r.length>0?` Expected one of: ${[...new Set(r)].join(", ")}.`:"";throw new p(`Unknown option '${e}' for extension command '${n}'.${i}`,m.USAGE,{code:"unknown_option",flag:t,required:`Use a flag the command accepts; run pm contracts --command ${n} --flags-only --json to list them.`})}function Vh(e,t){throw new p(`Option '${e}' is disabled for extension command '${t}'.`,m.USAGE,{code:"extension_option_disabled",flag:e,required:`Remove ${e}; the command declares it with enabled: false.`,why:"A disabled declaration keeps the flag in the contract while refusing every value for it.",examples:[`pm ${t} --help`],nextSteps:[`Run pm contracts --command ${t} --flags-only --json to list the flags this command accepts.`]})}function Yh(e,t,n,r){let i=An(e),o=i.value_arity==="none"?n:i.value_arity==="optional"?`${n} [${i.value_name}]`:`${n} <${i.value_name}>`;throw new p(`Missing required option '${n}' for extension command '${r}'.`,m.USAGE,{code:"missing_required_option",flag:n,field:t,required:`Pass ${o}.`,why:"The command declares this flag as required, so pm refuses the invocation before the extension handler runs.",examples:[`pm ${r} ${o}`],nextSteps:[`Run pm contracts --command ${r} --flags-only --json to read each flag's sdk_option key.`],recovery:{missing:[n]}})}function FE(e){return typeof e=="string"||e==null?e:String(e)}function jE(e){if(typeof e=="number")return e;if(typeof e=="string"&&e.trim().length>0){let t=Number(e);return Number.isFinite(t)?t:e}return e}function Jh(e){if(typeof e=="boolean")return e;if(typeof e=="string"){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1}return e}var UE={string:FE,number:jE,boolean:Jh};function rn(e,t){return Array.isArray(e)?e.map(n=>rn(n,t)):UE[t](e)}function Rc(e,t,n){let r=n?(Array.isArray(e)?e.flat(1/0):[e]).filter(i=>i!=null&&i!==""):Ka(e);return t?r.map(i=>rn(i,t)):r}function Xh(e,t){return Rc(t,null,e.repeatable===!0).length>0}function GE(e,t,n,r){return n?Rc(e,t,r):t?rn(e,t):e}function qE(e,t,n){let r=Zh(e,t);return r.length===0?n:r.map(i=>i.value)}function Qh(e){return An(e).value_arity==="none"}function Ic(e,t,n,r,i){let o=jn(e),s=i?` for extension command '${i}'`:"",a=n===!0?"no value":JSON.stringify(n);throw new p(`Option '${o}'${s} expects ${r}; received ${a}.`,m.USAGE,{code:"extension_flag_value_invalid",flag:o,required:`Pass ${o} ${t==="number"?"<number>":"<true|false|1|0>"}.`,why:`The flag declares value_type ${t} with value_validation strict, so a malformed token is refused before the extension handler runs.`,nextSteps:[`Re-run with a valid ${t} value for ${o}.`,`Run pm ${i??"<command>"} --help to review the declared flag contract.`]})}function Oc(e,t){return e.value_validation==="strict"&&t!=="string"}function Zh(e,t){let n=e[Ac];if(!n)return[];let r=new Set(t);return n.filter(i=>r.has(i.key))}function KE(e,t,n,r){if(Qh(e))for(let i of Zh(n,t)){if(i.attached!==!0)continue;let o=e.list===!0&&e.repeatable!==!0?Ka(i.value):[i.value];for(let s of o){let a=zi(rn(s,"boolean"),"boolean");a!==null&&Ic(e,"boolean",s,a.expected,r)}}}function WE(e,t,n,r,i){let o=Array.isArray(n)?n.flat(1/0):[n],s=r?o:o.flatMap(a=>typeof a=="string"?a.split(","):[a]);for(let a of s)if(typeof a=="string"&&a.trim().length===0){let c=zi(a,t);Ic(e,t,a,c.expected,i)}}function Lc(e,t,n,r){if(!Oc(e,n))return t;let i=n==="boolean"&&Qh(e),o=s=>{let a=zi(s,n);return a===null?s:i&&typeof s=="string"?!0:Ic(e,n,s,a.expected,r)};return Array.isArray(t)?t.map(o):o(t)}function zE(e,t,n,r){for(let i of n)if(!(i===t||!Object.hasOwn(e,i))){if(Object.hasOwn(e,t)){if(r){let o=e[t],s=e[i];e[t]=[...Array.isArray(o)?o:[o],...Array.isArray(s)?s:[s]].filter(a=>a!=null)}delete e[i];continue}e[t]=e[i],delete e[i]}}function eg(e,t,n=e,r){if(t.length===0)return e;let i=Object.create(null);for(let[s,a]of Object.entries(e))i[s]=a;let o=new Set(t.map(s=>Fn(s)).filter(s=>s!==null));for(let s of t){let a=Fn(s);if(a){let c=jr(s).filter(d=>d===a||!o.has(d));BE(i,s,a,c,n,r)}}return i}function BE(e,t,n,r,i,o){let s=t.list===!0,a=Oo(t);a&&!s&&HE(e,t,n,r,a,o),zE(e,n,r,s);let c=t.repeatable===!0;if(!Object.hasOwn(e,n)){t.default!==void 0&&(e[n]=GE(t.default,a,s,c));return}if(a==="boolean"&&Oc(t,a)&&KE(t,r,i,o),s){e[n]=VE(t,r,i,e[n],a,c,o);return}a&&(e[n]=Lc(t,rn(e[n],a),a,o))}function HE(e,t,n,r,i,o){for(let s of r)s!==n&&Object.hasOwn(e,s)&&Lc(t,rn(e[s],i),i,o)}function VE(e,t,n,r,i,o,s){let a=qE(n,t,r);i&&Oc(e,i)&&WE(e,i,a,o,s);let c=Rc(a,i,o);return i?Lc(e,c,i,s):c}function NG(e){let t=Object.create(null),n=[];Object.defineProperty(t,Ac,{value:n});let r=0;for(;r<e.length;){let i=xc(e,r);if(!i){r+=1;continue}let o=$t(i.key);if(o.length===0||Io(o)){r+=i.consumed;continue}PE(t,o,i.value),n.push({...i,key:o}),r+=i.consumed}return t}function MG(e){let t=[],n=0;for(;n<e.length;){if(e[n]==="--"){t.push(...e.slice(n+1));break}let r=xc(e,n);if(r){n+=Math.max(1,r.consumed);continue}t.push(e[n]),n+=1}return t}function PG(e,t){if(t.length===0)return[...e];let n=new Set,r=new Set;for(let s of t){let a=Oo(s);for(let c of jr(s))n.add(c),a==="boolean"&&r.add(c)}if(n.size===0)return[...e];let i=[],o=0;for(;o<e.length;){if(e[o]==="--"){i.push(...e.slice(o+1));break}let s=xc(e,o);if(s){let a=$t(s.key);if(n.has(a)){let c=e[o],d=r.has(a)&&!c.includes("=")?1:s.consumed;o+=d;continue}}i.push(e[o]),o+=1}return i}function Dc(e){return Fn(e)}function Gh(e){return e.trim().toLowerCase().split(/\s+/u).filter(t=>t.length>0).join(" ")}function FG(e,t){let n=Gh(t);if(n.length===0)return[];let r=K(n);return e.flags.filter(i=>K(Gh(i.target_command))===r).flatMap(i=>[...i.flags])}function tg(e,t,n,r){let i=jn(e),[o,s]=n;throw new p(`Options '${o}' and '${s}' both set ${i} for extension command '${r}' with different values.`,m.USAGE,{code:"extension_option_spelling_conflict",required:`Pass ${i} once, under the handler key '${t}'.`,why:`'${o}' and '${s}' are spellings of the same declared flag, and pm refuses to choose between two different values.`,nextSteps:[`Remove '${o}' or '${s}' and pass one value as '${t}'.`,`Run pm contracts --command ${r} --flags-only --json to read each flag's sdk_option key.`]})}function jG(e,t,n,r={}){if(t.length===0)return e;let i=t.map(l=>l.repeatable===!0&&l.list!==!0?{...l,list:!0}:l),o=QE(i),s=tT(e,o,n),a=new Set([...o.long.values()].map(({handlerKey:l})=>l)),c=Object.create(null),d=Object.create(null);for(let[l,u]of Object.entries(s))a.has(l)?c[l]=u:u===void 0||r.undeclaredKeys==="pass"||JE(l)?d[l]=u:Hh(l,XE(l),n,Bh(i,{}));return rg(c,i,n),Object.assign(d,eg(c,i,ng(c,o),n))}function ng(e,t){let n=new Set([...t.long.values()].map(({handlerKey:o})=>o)),r=Object.entries(e).filter(([o])=>n.has(o)).flatMap(([o,s])=>(Array.isArray(s)?s.flat(1/0):[s]).map(a=>({consumed:1,key:o,value:a,attached:!0}))),i=Object.create(null);return Object.defineProperty(i,Ac,{value:r}),i}function rg(e,t,n){for(let r of t){let i=Fn(r);if(i===null)continue;let o=jn(r),s=e[i],a=Object.hasOwn(e,i);r.enabled===!1&&a&&Vh(o,n);let c=a&&(r.list!==!0||Xh(r,s));r.required===!0&&r.enabled!==!1&&!c&&Yh(r,i,o,n),r.list!==!0&&Array.isArray(s)&&YE(o,n)}}function YE(e,t){throw new p(`Option '${e}' for extension command '${t}' takes one value; received an array.`,m.USAGE,{code:"extension_flag_value_invalid",flag:e,required:`Pass one value for ${e}, or ask the package to declare it with list: true or repeatable: true.`,why:"The flag is not declared list or repeatable, so pm refuses an array before the extension handler runs instead of handing it a value of the wrong shape.",nextSteps:[`Run pm contracts --command ${t} --flags-only --json to read each flag's value contract.`]})}var qh=new Set([...[...wm].flatMap(e=>{let t=e.replace(/^--/u,"");return[t,...t.startsWith("no-")?[t.slice(3)]:[]].flatMap(n=>[$t(n),n.replaceAll("-","_")])}),"force","subcommand","inputResponses","requestState"]);function JE(e){return qh.has(e)||qh.has($t(e.replace(/^-{1,2}/u,"")))}function XE(e){return`--${e.replace(/^-+/u,"").replace(/([a-z0-9])([A-Z])/gu,"$1-$2").replaceAll("_","-").toLowerCase()}`}function QE(e){let t={long:new Map,short:new Map},n=(r,i,o)=>{i.length>0&&!r.has(i)&&r.set(i,o)};for(let r of e){let i=Fn(r);if(i===null)continue;let o={handlerKey:i,definition:r};n(t.long,i,o);let s=typeof r.short=="string"?r.short.trim():"";s.startsWith("-")&&!s.startsWith("--")&&n(t.short,s.slice(1),o)}return t}function Cc(e,t){return e.long.get(t)??e.short.get(t.replace(/^-(?!-)/u,""))??e.long.get($t(t.replace(/^-{1,2}/u,"")))}function ZE(e,t,n,r){let i=/^(?:--)?no-(.+)$/u.exec(t)?.[1];if(i===void 0||Cc(e,t)!==void 0)return{spelling:t,value:n};let o=Cc(e,i);return o===void 0||Oo(o.definition)!=="boolean"?{spelling:t,value:n}:(o.definition.list===!0||o.definition.repeatable===!0)&&Array.isArray(n)?{spelling:i,value:n.flat(1/0).map(s=>Kh(t,o.definition,s,r))}:o.definition.list===!0&&n!==void 0?{spelling:i,value:Kh(t,o.definition,n,r)}:{spelling:i,value:n===void 0?n:Ro(t,o.definition,n,r)}}function Kh(e,t,n,r){let i=o=>o.trim().length===0?o:String(Ro(e,t,o.trim(),r));return n==null?n:typeof n!="string"?Ro(e,t,n,r):n.trim().length===0?n:t.repeatable===!0||!n.includes(",")?Ro(e,t,n,r):n.split(",").map(i).join(",")}function Ro(e,t,n,r){let i=Jh(n);return typeof i=="boolean"?!i:eT(e,t,n,r)}function eT(e,t,n,r){let i=jn(t);throw new p(`Option '${e}' for extension command '${r}' negates ${i} and expects true, false, 1, or 0; received ${JSON.stringify(n)}.`,m.USAGE,{code:"extension_flag_value_invalid",flag:i,required:`Pass ${i} as true or false, or '${e}' as true.`,why:`'${e}' is the negated spelling of the boolean ${i}, so only a boolean value can be inverted before the extension handler runs.`,nextSteps:[`Run pm contracts --command ${r} --flags-only --json to read each flag's value contract.`]})}function tT(e,t,n){let r=Object.create(null),i=new Map;for(let[o,s]of Object.entries(e)){let{spelling:a,value:c}=ZE(t,o,s,n),d=Cc(t,a);if(d===void 0)r[a]=c;else if(c!==void 0){let l=i.get(d.handlerKey);l===void 0?(i.set(d.handlerKey,a),r[d.handlerKey]=c):zh(Wh(d.definition,d.handlerKey,r[d.handlerKey],t,n),Wh(d.definition,d.handlerKey,c,t,n))||tg(d.definition,d.handlerKey,[l,a],n)}}return r}function Wh(e,t,n,r,i){let o={[t]:n};return rg(o,[e],i),eg(o,[e],ng(o,r),i)[t]}function nT(e){let t=new Map;for(let n of e){let r=Fn(n);if(r===null)continue;let i={definition:n,handlerKey:r,kind:Oo(n),arity:An(n).value_arity,scalar:n.list!==!0},o=[Ht(n.long),typeof n.short=="string"?n.short.trim():""];for(let s of o.filter(a=>a?.startsWith("-")===!0))t.has(s)||t.set(s,i)}return t}function rT(e,t,n){let r=e.optionOf(n),i=t.get(n),o=i?.scalar===!0?i:void 0;if(r!==void 0){let s={arity:r.arity,...r.variadic===!0?{variadic:!0}:{}};if(o?.handlerKey===r.key)return{...s,declared:o};let a=i===void 0&&n.startsWith("--no-")?t.get(`--${n.slice(5)}`):void 0;return a?.scalar===!0&&a.kind==="boolean"&&a.handlerKey===r.key?{...s,declared:a,negates:!0}:s}if(!(!e.includesLooseFlags||i===void 0))return o===void 0?{arity:i.arity,loose:!0}:{arity:i.arity,declared:o,loose:!0}}function $c(e){return e.length>1&&e.startsWith("-")}var ig=/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/u;function iT(e,t,n){let{tokens:r}=e,i=0,o,s=!1,a=!1;for(;i<r.length||o!==void 0;){let c=o??r[i++];if(c==="--")return;if(a&&o===void 0&&oT(e,c))continue;let d=$c(c)?aT(e,c,r[i],t,n):{consumedByCommander:!1,consumed:0};if(i+=d.consumed,o=d.group,a=d.variadic===!0,!d.consumedByCommander){if(sT(e.stop,c,s))return;s=!0}}}function oT(e,t){return!$c(t)||e.negativeNumbersAreValues&&ig.test(t)}function sT(e,t,n){return e!==void 0&&(e.atFirstUnrecognized||!n&&e.atSubcommand(t))}function aT(e,t,n,r,i){let o=cT(t,n,r);if(o!==void 0)return i(o.spelling,o.entry,o.value),{consumedByCommander:!1,consumed:o.consumed};let s=r(t);if(s!==void 0){let a=s.arity==="required"||s.arity==="optional"&&n!==void 0&&(!$c(n)||e.negativeNumbersAreValues&&ig.test(n));return i(t,s,s.negates===!0?!1:a?n:!0),{consumedByCommander:!0,consumed:a?1:0,variadic:s.variadic===!0}}return t[1]!=="-"?{consumed:0,...dT(t,r,i)}:{consumedByCommander:lT(t,r,i,e.includesLooseFlags?i:()=>{}),consumed:0}}function cT(e,t,n){let r=e.indexOf("="),i=r>1?e.slice(0,r):e,o=n(i);if(o?.loose===!0)return r>1?{spelling:i,entry:o,value:e.slice(r+1),consumed:0}:t!==void 0&&!t.startsWith("-")?{spelling:i,entry:o,value:t,consumed:1}:{spelling:i,entry:o,value:!0,consumed:0};let s=r<0&&e.startsWith("--no-")?n(`--${e.slice(5)}`):void 0;return s?.loose===!0&&s.declared?.kind==="boolean"?{spelling:e,entry:s,value:!1,consumed:0}:void 0}function dT(e,t,n){let r=e.slice(0,2),i=e.length>2?t(r):void 0;return i===void 0||i.loose===!0?{consumedByCommander:!1}:i.arity!=="none"?(n(r,i,e.slice(2)),{consumedByCommander:!0}):(n(r,i,!0),{consumedByCommander:!0,group:`-${e.slice(2)}`})}function lT(e,t,n,r){let i=e.indexOf("=");if(i>2){let s=e.slice(0,i),a=t(s);return a!==void 0&&a.arity!=="none"?(n(s,a,e.slice(i+1)),!0):(a?.declared?.kind==="boolean"&&r(s,a,e.slice(i+1)),!1)}let o=e.startsWith("--no-")?t(`--${e.slice(5)}`):void 0;return o?.declared?.kind==="boolean"&&r(e,o,!1),!1}function UG(e,t,n){let r=nT(t),i=new Map;for(let o of e)iT(o,s=>rT(o,r,s),(s,a,c)=>{a.declared!==void 0&&uT(i,a.declared,s,c,n)})}function uT(e,t,n,r,i){let{definition:o,handlerKey:s,kind:a}=t,c=a?rn(r,a):r,d=e.get(s)??new Map,l=[...d].find(([u,_])=>u!==n&&!zh(_,c));l!==void 0&&tg(o,s,[l[0],n],i),d.set(n,c),e.set(s,d)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0c0bb7ab-6157-5861-ad7e-a63ae62220f4")}catch{}})();var mT=new Set(["claim","close","context","create","get","help","init","list","next","plan","release","search","update","validate","workspace"]),pT=new Set(["append","comments","config","contracts","deps","docs","events","files","focus","graph","health","history","learnings","list-all","list-blocked","list-closed","list-in-progress","list-open","notes","profile","schema","test"]),_T=Object.freeze({workspace:new Set(["config","gc","health","init","merge","profile","schema","telemetry","workspace"]),intake:new Set(["copy","create","focus","item","restore"]),context:new Set(["activity","aggregate","context","ctx","duplicates","eval","get","help","list","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","next","search","stats"]),lifecycle:new Set(["claim","close","close-many","close-task","delete","pause-task","item-reopen","release","start-task","update","update-many"]),evidence:new Set(["append","comments","docs","events","files","history","history-attest","history-author-acknowledge","history-compact","history-redact","history-repair","learnings","notes"]),graph:new Set(["deps","graph","plan"]),quality:new Set(["assurance","contracts","test","test-all","validate"]),automation:new Set(["event","meet","remind"])}),fT=new Set(["extension","install","package","packages","upgrade"]);function hT(e){let t=K(e.trim().toLowerCase());if(t==="ops")return"quality";for(let[n,r]of Object.entries(_T))if(r.has(t))return n;return fT.has(t)?"extensions":"internal"}var Un=Object.freeze([...st.flatMap(e=>e==="item"?["item","item-reopen"]:[e,...ot.filter(t=>t.alias===e).map(t=>t.canonical)]).map(e=>({command:e,tier:mT.has(K(e))?"core":pT.has(K(e))?"standard":"full",family:hT(e)})),{command:"ops",tier:"core",family:"quality"},{command:"completion-statuses",tier:"internal",family:"internal"},{command:"completion-tags",tier:"internal",family:"internal"},{command:"completion-types",tier:"internal",family:"internal"},{command:"test-runs-worker",tier:"internal",family:"internal"},{command:"item test worker",tier:"internal",family:"internal"}]),gT=Un,og=Object.freeze({max_lines:50,max_utf8_bytes:6e3}),WG=Object.freeze(["-V, --version","--all","--json","--output-include <fields>","--output-limit <count>","--output-budget <tokens|unbounded>","--output-cursor <cursor>","--pm-path <dir>","--no-extensions","--no-pager","--explain","-h, --help"]);function zG(e){let t=e===""?0:e.split(/\r?\n/).length,n=Buffer.byteLength(e,"utf8");return{lines:t,utf8_bytes:n,within_budget:t<=og.max_lines&&n<=og.max_utf8_bytes}}var sg={core:0,standard:1,full:2,internal:3},ag=new Map(gT.map(({command:e,tier:t})=>[e,t]));function Nc(e,t="standard"){return ag.get(e.trim().toLowerCase())??ag.get(K(e.trim().toLowerCase()))??t}function BG(e){return cg(e,Un)}function cg(e,t){let n=sg[e];return t.filter(r=>r.tier!=="internal"&&sg[r.tier]<=n).map(r=>r.command)}function HG(e){return dg(e,Un)}function dg(e,t){return t.filter(n=>n.family===e).map(n=>n.command)}var yT=["workspace","intake","context","lifecycle","evidence","graph","quality","automation","extensions","internal"],wT=new Set([...Kt.filter(e=>e.hidden).map(e=>e.alias),"ctx","extension","install","item-reopen","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","packages","upgrade"]);function VG(e=Un){return yT.map(t=>({family:t,commands:dg(t,e).filter(n=>e.find(r=>r.command===n)?.tier!=="internal"&&!wT.has(n))})).filter(({commands:t})=>t.length>0)}var vT=Object.freeze({pm_append:"append",pm_claim:"claim",pm_close:"close",pm_comments:"comments",pm_config:"config",pm_context:"context",pm_contracts:"contracts",pm_copy:"copy",pm_create:"create",pm_deps:"deps",pm_discover:"help",pm_docs:"docs",pm_events:"history",pm_files:"files",pm_focus:"focus",pm_get:"get",pm_graph:"graph",pm_health:"health",pm_learnings:"learnings",pm_list:"list",pm_mutate:"update",pm_next:"next",pm_notes:"notes",pm_plan:"plan",pm_profile:"profile",pm_release:"release",pm_run:"package",pm_schema:"schema",pm_search:"search",pm_test:"test",pm_update:"update",pm_validate:"validate"});function YG(e,t){return bT(e,t,Un)}function bT(e,t,n){if(t==="full")return[...e];let r=new Set(cg(t,n));return e.filter(i=>{let o=vT[i];return o!==void 0&&r.has(o)})}var JG=Object.freeze([{uri:"pm://workspace/context",name:"Workspace context",description:"Bounded project context for orientation, including active hierarchy and progress.",mimeType:"application/json"},{uri:"pm://workspace/focus",name:"Active focus",description:"The session focus that supplies the default create parent.",mimeType:"application/json"},{uri:"pm://workspace/claims",name:"Active claims",description:"Bounded in-progress work and active ownership context.",mimeType:"application/json"},{uri:"pm://workspace/agent-guide",name:"Agent guidance",description:"Repository-local AGENTS.md instructions, bounded for safe host attachment.",mimeType:"text/markdown"}]),XG=Object.freeze([{name:"orient",description:"Build bounded live context, search all statuses, and select canonical work without creating duplicates.",arguments:[{name:"request",description:"The user's requested outcome or topic.",required:!0},{name:"scope",description:"Optional bounded workspace or subsystem scope.",required:!1}],template:"Orient to the live pm workspace for: {{request}}. Scope hint: {{scope}}. Read context, search all statuses, inspect full metadata for relevant items, and select canonical lineage before any mutation."},{name:"claim-and-start",description:"Claim one canonical item and begin implementation with linked context.",arguments:[{name:"id",description:"Canonical pm item id.",required:!0}],template:"Read {{id}} in full, claim it, set it in_progress, then implement only its acceptance scope while linking files, docs, tests, and evidence."},{name:"record-evidence-and-close",description:"Record exact verification evidence, close the item, and release ownership.",arguments:[{name:"id",description:"Canonical pm item id.",required:!0},{name:"evidence",description:"Exact verification and outcome evidence.",required:!0}],template:"For {{id}}, record this evidence: {{evidence}}. Verify linked tests, close only if acceptance is met, then release the claim."}]);function QG(){return kT(Un)}function kT(e){return["# Generated agent command surface","","This file is generated from `PM_COMMAND_CAPABILITY_CONTRACTS`. Do not edit it manually.","","| Command | Minimum visibility tier | Capability family |","| --- | --- | --- |",...e.map(({command:t,tier:n,family:r})=>`| \`${t}\` | ${n} | ${r} |`),""].join(`
|
|
2
|
+
`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7df4fe91-e8a4-540f-8737-c67f2efa460e")}catch{}})();var Mc=[{exit_code:1,class:"generic_failure"},{exit_code:2,class:"usage"},{exit_code:3,class:"not_found"},{exit_code:4,class:"conflict"},{exit_code:5,class:"dependency_failed"}],ST=new Map(Mc.map(e=>[e.exit_code,e.class]));function Lo(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))].sort()}function ET(e){if(!e)return[];let t=new Set,n=new Set;return e.map(r=>{let i=r.state.trim(),o=r.probe_id.trim(),s=Lo(r.entrypoints);if(!/^[a-z][a-z0-9_]*$/.test(i)||!/^[a-z][a-z0-9-]*$/.test(o)||s.length===0||t.has(i)||n.has(o))throw new TypeError("Invalid pm refusal state contract");return t.add(i),n.add(o),{state:i,probe_id:o,entrypoints:s,expected_exit_class:r.expected_exit_class}}).sort((r,i)=>r.state.localeCompare(i.state))}function TT(e,t,n,r,i){return![[1,2,3,4,5].includes(e.exit_code),e.meaning.trim().length>0,e.recovery.trim().length>0,t.length>0,n.length>0,/^[a-z][a-z0-9_]*$/.test(r),i.every(o=>/^[a-z][a-z0-9_]*$/.test(o)),ST.get(e.exit_code)===e.class].includes(!1)}function CT(e,t){let n=e,r=new Set;for(;n.canonical_code!==n.code;){if(r.has(n.code))throw new TypeError(`Alias cycle in pm error code catalog: ${e.code}`);r.add(n.code);let i=t.get(n.canonical_code);if(!i)throw new TypeError(`Invalid pm error code contract: ${e.code}`);n=i}return n}function AT(e){let t=new Map(e.map(n=>[n.code,n]));for(let n of e){let r=CT(n,t);if(r.exit_code!==n.exit_code||r.class!==n.class)throw new TypeError(`Alias transport mismatch for pm error code: ${n.code}`);let i=e.filter(o=>o.code!==r.code&&o.canonical_code===r.code).map(o=>o.code).sort();if(n.code===r.code?JSON.stringify(n.aliases)!==JSON.stringify(i):n.aliases.length>0)throw new TypeError(`Invalid pm error code contract: ${n.code}`)}}function ug(e){let t=new Set,n=e.map(r=>{let i=r.code.trim();if(!/^[a-z][a-z0-9_]*$/.test(i))throw new TypeError(`Invalid pm error code: ${JSON.stringify(r.code)}`);if(t.has(i))throw new TypeError(`Duplicate pm error code: ${i}`);t.add(i);let o=Lo(r.sources),s=Lo(r.emitting_commands),a=(r.canonical_code??i).trim(),c=Lo(r.aliases??[]),d=ET(r.owned_states);if(!TT(r,o,s,a,c))throw new TypeError(`Invalid pm error code contract: ${i}`);if(d.some(l=>l.expected_exit_class!==r.class))throw new TypeError(`Invalid pm refusal state exit class: ${i}`);return Object.freeze({...r,code:i,meaning:r.meaning.trim(),recovery:r.recovery.trim(),sources:o,emitting_commands:s,canonical_code:a,aliases:c,owned_states:d})});return AT(n),Object.freeze(n.sort((r,i)=>r.code.localeCompare(i.code)))}function eq(e,t){let n=lg(e,t);return lg(n.canonical_code??n.code,t)}function lg(e,t){let n=e.trim(),r=t.find(i=>i.code===n);if(!r)throw new TypeError(`Unknown pm error code "${n}"`);return r}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0b0d726a-0fd5-5196-bee1-d34c433c0016")}catch{}})();var xT="Inspect the structured error guidance, then retry the suggested command when one is present.",RT=new Map(Mc.map(e=>[e.exit_code,e.class]));function mg(e){return e.map(t=>{let n=`${t.code.replaceAll("_"," ")} condition.`,r={code:t.code,meaning:`${n.charAt(0).toUpperCase()}${n.slice(1)}`,stability:t.stable?"stable":"provisional",exit_code:t.exit_code,class:RT.get(t.exit_code),recovery:xT,sources:t.sources,emitting_commands:t.emitting_commands??["*"],canonical_code:t.canonical_code??t.code,aliases:t.aliases??[]};return t.owned_states&&(r.owned_states=t.owned_states),r})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1cc13594-afb5-5125-bc33-490d0d1c15a4")}catch{}})();var pg=[{code:"acceptance_criteria_mutation_conflict",exit_code:2,sources:["sdk/lifecycle/update.ts"],emitting_commands:["update","update-many"]},{code:"acceptance_criteria_remove_unmatched",exit_code:3,sources:["sdk/lifecycle/update-many.ts","sdk/lifecycle/update.ts"],emitting_commands:["update","update-many"]},{code:"acceptance_criteria_semicolon_forbidden",exit_code:2,stable:!0,sources:["core/item/parse.ts"]},{code:"accepted_rejected_value",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"alias_collision",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"alias_target_missing",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"already_claimed_by",exit_code:4,stable:!0,sources:["sdk/lifecycle/claim.ts"],emitting_commands:["claim"]},{code:"ambiguous_option_combination",exit_code:2,stable:!0,sources:["sdk/lifecycle/claim.ts","sdk/lifecycle/plan.ts"],emitting_commands:["claim","plan"]},{code:"annotation_alias_conflict",exit_code:2,sources:["cli/register-annotations.ts"]},{code:"annotation_entry_mismatch",exit_code:4,sources:["sdk/annotations.ts"]},{code:"annotation_expectation_invalid",exit_code:2,sources:["sdk/annotations.ts"]},{code:"annotation_expectation_without_target",exit_code:2,sources:["sdk/annotations.ts"]},{code:"annotation_flag_like_value",exit_code:2,stable:!0,sources:["sdk/annotations.ts"]},{code:"annotation_if_absent_without_append",exit_code:2,sources:["sdk/annotations.ts"]},{code:"annotation_message_without_text",exit_code:2,stable:!0,sources:["sdk/annotations.ts"]},{code:"annotation_text_compacted",exit_code:2,sources:["sdk/annotations.ts"]},{code:"annotation_text_source_conflict",exit_code:2,sources:["sdk/runtime-input.ts"]},{code:"annotation_transposed_subcommand",exit_code:2,sources:["cli/register-annotations.ts"]},{code:"append_empty_body",exit_code:2,stable:!0,sources:["sdk/lifecycle/append.ts"],emitting_commands:["append"]},{code:"assurance_registry_invalid",exit_code:1,sources:["sdk/governance/assurance.ts"]},{code:"bare_comma_entry_ambiguous",exit_code:2,sources:["core/item/parse.ts"]},{code:"blocker_identity_read_failed",exit_code:1,sources:["sdk/query/declared-blockers.ts"]},{code:"body_file_conflicts_with_body",exit_code:2,stable:!0,sources:["core/io/body-file.ts"]},{code:"body_file_missing_path",exit_code:2,stable:!0,sources:["core/io/body-file.ts"]},{code:"body_file_unreadable",exit_code:3,stable:!0,sources:["core/io/body-file.ts"]},{code:"budget_exceeded",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"bulk_create_route",exit_code:2,sources:["cli/register-mutation.ts"]},{code:"bulk_ids_input_empty",exit_code:2,sources:["core/io/bulk-ids-input.ts","sdk/history-compact.ts","sdk/history-mcp.ts"],owned_states:[{state:"bulk_ids_stdin_contains_no_nonempty_ids",probe_id:"bulk-ids-stdin-empty",entrypoints:["update-many"],expected_exit_class:"usage"}]},{code:"bulk_ids_input_missing_path",exit_code:2,sources:["core/io/bulk-ids-input.ts"],owned_states:[{state:"bulk_ids_file_token_omits_its_path",probe_id:"bulk-ids-file-path-missing",entrypoints:["update-many"],expected_exit_class:"usage"}]},{code:"bulk_ids_input_unreadable",exit_code:3,sources:["core/io/bulk-ids-input.ts"],owned_states:[{state:"bulk_ids_file_path_cannot_be_read",probe_id:"bulk-ids-file-unreadable",entrypoints:["update-many"],expected_exit_class:"not_found"}]},{code:"bundle_integrity_torn_install",exit_code:1,stable:!0,sources:["cli/bundle-integrity.ts"]},{code:"capability_undeclared",exit_code:1,stable:!0,sources:["sdk/compose.ts"]},{code:"capability_unused",exit_code:1,stable:!0,sources:["sdk/compose.ts"]},{code:"child_projection_item_bound_exceeded",exit_code:1,stable:!0,sources:["sdk/item-children.ts"]},{code:"close_reason_required",exit_code:2,stable:!0,sources:["sdk/lifecycle-policy.ts","sdk/lifecycle/close-many.ts"],emitting_commands:["*","close-many"]},{code:"close_through_update",exit_code:1,stable:!0,sources:["core/telemetry/observability.ts"]},{code:"close_validation_deferred_fields",exit_code:2,sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"]},{code:"close_validation_missing_fields",exit_code:2,stable:!0,sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"]},{code:"collected_zero_items",exit_code:1,stable:!0,sources:["sdk/test/execution-receipts.ts"]},{code:"collection_transposed_subcommand",exit_code:2,sources:["cli/error-guidance.ts"]},{code:"command_failed",exit_code:1,stable:!0,sources:["cli/error-guidance.ts"]},{code:"command_namespace",exit_code:2,stable:!0,sources:["sdk/cli-contracts/runtime-contracts.ts"]},{code:"command_override_conflict",exit_code:4,stable:!0,sources:["sdk/compose.ts"]},{code:"config_duplicate",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"config_key_unknown",exit_code:2,stable:!0,sources:["core/profile/profile-lint.ts","sdk/config.ts"]},{code:"config_value_invalid",exit_code:2,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"conflicting_lifecycle_owner",exit_code:2,stable:!0,sources:["cli/register-operations.ts"]},{code:"context_evaluation_read_incomplete",exit_code:2,sources:["sdk/context-relevance.ts"]},{code:"context_signal_store_invalid",exit_code:2,sources:["sdk/context-signal-store.ts"]},{code:"context_signal_store_stale",exit_code:1,sources:["sdk/context-signal-store.ts"]},{code:"context_signal_store_write_failed",exit_code:1,sources:["sdk/context-signal-store.ts"]},{code:"context_takes_no_item_argument",exit_code:1,stable:!0,sources:["cli/error-guidance.ts"]},{code:"core_item_field_requires_dedicated_flag",exit_code:2,stable:!0,sources:["core/extensions/item-fields.ts"]},{code:"create_deferral_conflict",exit_code:2,sources:["sdk/lifecycle/create-deferrals.ts"],emitting_commands:["create"]},{code:"create_deferral_field_unsupported",exit_code:2,sources:["sdk/lifecycle/create-deferrals.ts"],emitting_commands:["create"]},{code:"create_deferral_fields_required",exit_code:2,sources:["sdk/lifecycle/create-deferrals.ts"],emitting_commands:["create"]},{code:"create_deferral_reason_required",exit_code:2,sources:["sdk/lifecycle/create-deferrals.ts"],emitting_commands:["create"]},{code:"create_positional_type_without_title",exit_code:2,stable:!0,sources:["cli/register-mutation.ts"]},{code:"dependency_cardinality_created",exit_code:2,sources:["sdk/graph/cardinality-integrity.ts"]},{code:"dependency_edge_not_allowed",exit_code:2,stable:!0,sources:["sdk/dependency-flag-validation.ts"]},{code:"dependency_flag_value_invalid",exit_code:2,sources:["sdk/dependency-flag-validation.ts"]},{code:"dependency_remove_no_match",exit_code:3,sources:["sdk/lifecycle/dependency-removal.ts"],emitting_commands:["update"]},{code:"dependency_target_not_found",exit_code:3,sources:["sdk/dependency-flag-validation.ts"]},{code:"dependency_temporal_order_invalid",exit_code:2,sources:["sdk/dependency-flag-validation.ts"]},{code:"duplicate_canonical_flag",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"duplicate_command",exit_code:1,stable:!0,sources:["sdk/compose.ts"]},{code:"duplicate_destination",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"duplicate_edge",exit_code:1,stable:!0,sources:["sdk/graph/remediation.ts"]},{code:"duplicate_observation",exit_code:1,sources:["sdk/flag-invocation-contracts.ts"]},{code:"duplicate_probe",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"duplicate_sweep_cost_limit",exit_code:4,stable:!0,sources:["sdk/query/duplicate-candidates.ts"],emitting_commands:["duplicate-candidates"]},{code:"duplicate_target_circular",exit_code:2,stable:!0,sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"]},{code:"duplicate_target_is_duplicate",exit_code:2,stable:!0,sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"]},{code:"duplicate_target_missing",exit_code:2,stable:!0,sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"]},{code:"duplicate_target_self",exit_code:2,stable:!0,sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"]},{code:"empty_corpus",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"empty_surface",exit_code:1,stable:!0,sources:["sdk/compose.ts"]},{code:"error_code_mismatch",exit_code:1,sources:["sdk/agent/refusal-closure.ts","sdk/agent/tracker-preflight-contracts.ts"]},{code:"event_cursor_query_mismatch",exit_code:2,stable:!0,sources:["sdk/mutation-events.ts"]},{code:"event_history_integrity_failed",exit_code:1,sources:["core/history/event-index.ts"]},{code:"event_index_unavailable",exit_code:1,stable:!0,sources:["sdk/mutation-events.ts"]},{code:"exit_code_mismatch",exit_code:1,sources:["sdk/agent/tracker-preflight-contracts.ts"]},{code:"expect_hash_background_unsupported",exit_code:2,sources:["sdk/lifecycle/item-revision.ts"]},{code:"expect_hash_invalid",exit_code:2,sources:["sdk/lifecycle/item-revision.ts"]},{code:"expect_hash_invocation_rewritten",exit_code:2,sources:["sdk/lifecycle/item-revision.ts"]},{code:"expect_hash_requires_mutation",exit_code:2,sources:["sdk/lifecycle/item-revision.ts"]},{code:"expect_hash_target_required",exit_code:2,sources:["sdk/lifecycle/item-revision.ts"]},{code:"expected_revision_duplicate",exit_code:2,sources:["core/store/item-mutation-precondition.ts"]},{code:"expected_revision_scope_conflict",exit_code:2,sources:["core/store/item-mutation-precondition.ts"]},{code:"extension_command_activation_failed",exit_code:1,stable:!0,sources:["cli/commander-usage.ts"]},{code:"extension_dependency_name_unsafe",exit_code:2,stable:!0,sources:["sdk/extension/install-sources.ts"]},{code:"extension_dependency_spec_invalid",exit_code:2,stable:!0,sources:["sdk/extension/install-sources.ts"]},{code:"extension_dependency_version_unsafe",exit_code:2,stable:!0,sources:["sdk/extension/install-sources.ts"]},{code:"extension_flag_value_invalid",exit_code:2,sources:["sdk/extension/command-options.ts"]},{code:"extension_install_incomplete_source_scan",exit_code:2,sources:["sdk/extension/install-plan.ts"]},{code:"extension_install_rollback_failed",exit_code:1,sources:["sdk/extension/install-snapshot.ts"]},{code:"extension_install_soft_failed",exit_code:1,stable:!0,sources:["cli/register-setup.ts"]},{code:"extension_install_source_contains_destination",exit_code:2,stable:!0,sources:["sdk/extension/install-runtime.ts"]},{code:"extension_item_field_reserved",exit_code:2,stable:!0,sources:["core/extensions/item-fields.ts"]},{code:"extension_item_field_type_conflict",exit_code:2,stable:!0,sources:["core/extensions/item-fields.ts"]},{code:"extension_item_field_unknown",exit_code:2,stable:!0,sources:["core/extensions/item-fields.ts"]},{code:"extension_mutation_guard_failed",exit_code:4,stable:!0,sources:["core/extensions/extension-hook-runtime.ts"]},{code:"extension_mutation_guard_invalid_decision",exit_code:4,stable:!0,sources:["core/extensions/extension-hook-runtime.ts"]},{code:"extension_mutation_guard_invalid_denial",exit_code:4,stable:!0,sources:["core/extensions/extension-hook-runtime.ts"]},{code:"extension_mutation_guard_timed_out",exit_code:4,stable:!0,sources:["core/extensions/extension-hook-runtime.ts"]},{code:"extension_option_disabled",exit_code:2,sources:["sdk/extension/command-options.ts"]},{code:"extension_option_spelling_conflict",exit_code:2,sources:["sdk/extension/command-options.ts"]},{code:"extension_read_output_invalid",exit_code:2,sources:["sdk/read-output/extension.ts"]},{code:"extension_update_health_partial_coverage",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"extensions_unreadable",exit_code:1,sources:["sdk/extension/static-inventory.ts"]},{code:"field_duplicate",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"field_invalid",exit_code:2,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"field_mcp_input_collision",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"github_source_entry_unbuilt",exit_code:2,stable:!0,sources:["sdk/extension/shared.ts"]},{code:"hierarchy_cardinality_created",exit_code:4,sources:["sdk/graph/hierarchy-integrity.ts"]},{code:"hierarchy_cycle_created",exit_code:4,sources:["sdk/graph/hierarchy-integrity.ts"]},{code:"hierarchy_parent_divergence_created",exit_code:4,sources:["sdk/graph/hierarchy-integrity.ts"]},{code:"history_author_acknowledge_plan_conflict",exit_code:4,sources:["sdk/author-attribution.ts"]},{code:"history_author_acknowledge_plan_fingerprint_required",exit_code:2,sources:["sdk/author-attribution.ts"]},{code:"history_author_acknowledge_preview_limit_invalid",exit_code:2,sources:["sdk/author-attribution.ts"]},{code:"history_author_acknowledge_required_values_missing",exit_code:2,sources:["sdk/author-attribution.ts"]},{code:"history_author_acknowledge_selector_conflict",exit_code:2,sources:["sdk/author-attribution.ts"]},{code:"history_author_acknowledge_selector_required",exit_code:2,stable:!0,sources:["sdk/author-attribution.ts"]},{code:"history_author_acknowledge_target_not_actionable",exit_code:2,sources:["sdk/author-attribution.ts"]},{code:"history_author_acknowledge_target_unreadable",exit_code:2,sources:["sdk/author-attribution.ts"]},{code:"history_baseline_unavailable",exit_code:1,sources:["core/history/projection.ts"]},{code:"history_drift_chain_mismatch",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_history_drift_chain_mismatches"]},{code:"history_drift_hash_mismatch",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_history_drift_hash_mismatches"]},{code:"history_drift_merge_receipt",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"history_drift_missing_stream",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_history_drift_missing_streams"]},{code:"history_drift_unreadable_stream",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_history_drift_unreadable_streams"]},{code:"history_drift_version_skew",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_history_drift_version_skews"]},{code:"history_json_invalid",exit_code:1,sources:["core/history/read.ts"]},{code:"history_merge_conflict_markers_detected",exit_code:1,stable:!0,sources:["core/history/read.ts"],canonical_code:"merge_conflict_markers_detected"},{code:"history_replay_invalid",exit_code:1,sources:["core/history/projection.ts","core/history/tombstone.ts"]},{code:"history_salvage_refused",exit_code:4,sources:["sdk/history/salvage.ts"]},{code:"history_stream_over_compact_threshold",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"history_target_out_of_range",exit_code:1,stable:!0,sources:["core/history/projection.ts"]},{code:"history_timestamp_invalid",exit_code:1,sources:["core/history/event-index.ts","core/history/history.ts"]},{code:"history_union_rebase_conflict",exit_code:4,sources:["sdk/merge/history-scalar-rebase.ts"]},{code:"history_unknown_author_events",exit_code:2,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_history_unknown_author_events"]},{code:"history_version_mapping_unavailable",exit_code:2,sources:["core/history/version-address.ts"]},{code:"history_version_pruned",exit_code:2,sources:["core/history/projection.ts"]},{code:"host_environment_capacity_fault",exit_code:1,sources:["core/fs/host-environment-errors.ts"]},{code:"host_environment_operation_invalid",exit_code:2,sources:["core/fs/host-environment-errors.ts"]},{code:"host_environment_permission_fault",exit_code:1,sources:["core/fs/host-environment-errors.ts"]},{code:"host_environment_resource_fault",exit_code:1,sources:["core/fs/host-environment-errors.ts"]},{code:"improvement_metric_contract_conflict",exit_code:4,sources:["sdk/improvement-ledger.ts"]},{code:"improvement_observation_conflict",exit_code:4,sources:["sdk/improvement-ledger.ts"]},{code:"in_progress_idle",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"in_progress_unowned",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"incomplete_allowed_values",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"inconsistent_concept_kind",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"init_existing_settings_requires_force",exit_code:2,stable:!0,sources:["sdk/init.ts"]},{code:"init_gitignore_unwritable",exit_code:1,stable:!0,sources:["sdk/workspace.ts"]},{code:"init_id_prefix_conflict",exit_code:2,stable:!0,sources:["sdk/init.ts"]},{code:"init_id_prefix_path_like",exit_code:2,stable:!0,sources:["sdk/init.ts"]},{code:"integrity_history_conflict_marker",exit_code:4,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_storage_history_conflict_markers"]},{code:"integrity_history_invalid_json",exit_code:2,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"integrity_history_unreadable",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"integrity_item_ahead_format_version",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_format_version_ahead_items"]},{code:"integrity_item_conflict_marker",exit_code:4,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"integrity_item_outdated_format_version",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_format_version_outdated_items"]},{code:"integrity_item_parse_failed",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"integrity_item_unreadable",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"invalid_argument_value",exit_code:2,stable:!0,sources:["cli/error-guidance.ts","core/item/priority.ts","core/shared/url-credentials.ts","core/telemetry/observability.ts","sdk/config.ts","sdk/context-intent-contracts.ts","sdk/dependencies.ts","sdk/governance/assurance-mutation-error.ts","sdk/history-redact.ts","sdk/lifecycle/create.ts","sdk/lifecycle/task-composition.ts","sdk/lifecycle/update-many.ts","sdk/lifecycle/update.ts","sdk/linked-artifacts.ts","sdk/query/next.ts","sdk/runtime-input.ts","sdk/runtime/mutation-admission.ts","sdk/runtime/mutation-value-validation.ts","sdk/runtime/schema-preview.ts","sdk/test/run-phases.ts","sdk/workspace.ts"],emitting_commands:["*","create","next","task-composition","update","update-many"]},{code:"invalid_command_usage",exit_code:2,stable:!0,sources:["cli/error-guidance.ts","core/telemetry/observability.ts"]},{code:"invalid_event_cursor",exit_code:2,stable:!0,sources:["sdk/mutation-events.ts"]},{code:"invalid_event_cursor_mode",exit_code:2,sources:["cli/register-list-query.ts","sdk/mutation-events.ts","sdk/runtime-extended-actions.ts"]},{code:"invalid_event_follow_interval",exit_code:2,stable:!0,sources:["sdk/mutation-events.ts"]},{code:"invalid_event_limit",exit_code:2,stable:!0,sources:["sdk/mutation-events.ts"]},{code:"invalid_event_since",exit_code:2,stable:!0,sources:["sdk/mutation-events.ts"]},{code:"invalid_history_analytics_limit",exit_code:2,sources:["sdk/history-analytics.ts"]},{code:"invalid_history_analytics_minimum_sample",exit_code:2,sources:["sdk/history-analytics.ts"]},{code:"invalid_history_analytics_since",exit_code:2,sources:["sdk/history-analytics.ts"]},{code:"invalid_improvement_ledger",exit_code:1,sources:["sdk/improvement-ledger-validation.ts"]},{code:"invalid_improvement_metric",exit_code:2,sources:["sdk/improvement-ledger.ts"]},{code:"invalid_improvement_observation",exit_code:2,sources:["sdk/improvement-ledger.ts"]},{code:"invalid_improvement_observation_limit",exit_code:2,sources:["sdk/improvement-ledger.ts"]},{code:"invalid_improvement_observation_timestamp",exit_code:2,sources:["sdk/improvement-ledger.ts"]},{code:"invalid_provenance_predicate",exit_code:2,stable:!0,sources:["sdk/history-provenance.ts"]},{code:"invalid_query_cursor",exit_code:2,stable:!0,sources:["sdk/pagination.ts","sdk/query/window-pagination.ts"]},{code:"invalid_read_output_session",exit_code:2,sources:["sdk/read-output-session.ts"]},{code:"invalid_reproducible_process_environment",exit_code:2,sources:["sdk/reproducibility/process.ts"]},{code:"invalid_workspace_snapshot_target",exit_code:2,sources:["sdk/workspace-snapshot.ts"]},{code:"item_already_active",exit_code:4,sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"]},{code:"item_already_exists",exit_code:4,stable:!0,sources:["sdk/lifecycle/create.ts"],emitting_commands:["create"]},{code:"item_deleted",exit_code:3,sources:["core/history/tombstone.ts"]},{code:"item_document_encoding_invalid",exit_code:4,sources:["core/store/item-store.ts"]},{code:"item_document_invalid",exit_code:1,stable:!0,sources:["core/item/item-format.ts"]},{code:"item_document_roundtrip_failed",exit_code:1,stable:!0,sources:["core/item/item-format.ts"]},{code:"item_format_version_unsupported",exit_code:4,sources:["core/item/item-format.ts"]},{code:"item_id_collision",exit_code:4,stable:!0,sources:["sdk/lifecycle/copy.ts"],emitting_commands:["copy"]},{code:"item_identity_ambiguous",exit_code:4,sources:["core/store/item-store.ts"]},{code:"item_identity_conflict",exit_code:4,sources:["sdk/governance/validate-history-drift.ts","sdk/lifecycle/item-revision.ts","sdk/merge/three-way.ts","sdk/query/declared-blockers.ts"]},{code:"item_identity_reserved",exit_code:4,sources:["core/history/history.ts"]},{code:"item_not_found",exit_code:3,stable:!0,sources:["cli/error-guidance.ts","core/store/item-store.ts","core/telemetry/observability.ts","sdk/governance/validate-history-drift.ts"]},{code:"item_revision_conflict",exit_code:4,sources:["core/store/item-mutation-precondition.ts"]},{code:"likely_duplicate",exit_code:4,stable:!0,sources:["sdk/similarity.ts"]},{code:"linked_artifact_mutation_conflict",exit_code:2,sources:["sdk/linked-artifacts.ts"]},{code:"linked_artifact_note_conflict",exit_code:4,sources:["sdk/linked-artifacts.ts"]},{code:"linked_artifact_note_key_misread",exit_code:2,sources:["sdk/linked-artifacts.ts"]},{code:"linked_resource_positional_value",exit_code:2,sources:["cli/error-guidance.ts"]},{code:"linked_test_command_immutable",exit_code:2,sources:["sdk/test/update.ts"]},{code:"linked_test_command_not_executable",exit_code:2,sources:["sdk/test/entry.ts"]},{code:"linked_test_context_invalid",exit_code:2,sources:["sdk/test/entry.ts"]},{code:"linked_test_patch_fields_unsupported",exit_code:2,sources:["sdk/test/update.ts"]},{code:"linked_test_remove_no_match",exit_code:3,sources:["sdk/test/execution.ts"]},{code:"linked_test_update_ambiguous",exit_code:2,sources:["sdk/test/update.ts"]},{code:"linked_test_update_no_match",exit_code:3,sources:["sdk/test/update.ts"]},{code:"linked_test_value_not_quoted",exit_code:1,stable:!0,sources:["cli/error-guidance.ts"]},{code:"list_source_incomplete",exit_code:1,stable:!0,sources:["sdk/query/list.ts"],emitting_commands:["list"]},{code:"local_package_archive_unsafe",exit_code:2,stable:!0,sources:["sdk/extension/install-sources.ts"]},{code:"local_source_not_found_bare_name",exit_code:3,stable:!0,sources:["sdk/extension/install-sources.ts"]},{code:"lock_conflict",exit_code:4,stable:!0,sources:["cli/error-guidance.ts","core/lock/lock.ts","core/telemetry/observability.ts"]},{code:"lock_lost",exit_code:4,sources:["core/lock/lock.ts"]},{code:"lock_path_unsafe",exit_code:4,sources:["core/lock/lock-confinement.ts"]},{code:"locks_stale_count",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"locks_unreadable",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"malformed_plan_step_evidence",exit_code:2,stable:!0,sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"]},{code:"managed_state_invalid",exit_code:2,sources:["sdk/extension/static-inventory.ts"]},{code:"managed_state_unreadable",exit_code:1,sources:["sdk/extension/static-inventory.ts"]},{code:"manifest_capabilities_absent",exit_code:1,stable:!0,sources:["sdk/compose.ts"]},{code:"manifest_invalid",exit_code:2,sources:["sdk/extension/static-inventory.ts"]},{code:"manifest_unknown_key",exit_code:1,sources:["core/extensions/manifest-schema.ts"],owned_states:[{state:"author_workspace_manifest_declares_an_unknown_top_level_key",probe_id:"author-manifest-unknown-key",entrypoints:["health"],expected_exit_class:"generic_failure"}]},{code:"manifest_unreadable",exit_code:1,sources:["sdk/extension/static-inventory.ts"]},{code:"mcp_annotation_file_unavailable",exit_code:2,sources:["sdk/runtime-input.ts"]},{code:"mcp_stdin_unavailable",exit_code:2,sources:["sdk/annotations.ts"]},{code:"mcp_task_not_found_or_not_authorized",exit_code:3,sources:["sdk/mcp/tasks.ts"]},{code:"merge_artifacts_ignored",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"merge_bun_launcher_unavailable",exit_code:5,sources:["sdk/merge/install.ts"]},{code:"merge_conflict_markers_detected",exit_code:1,stable:!0,sources:["core/item/item-format.ts"],aliases:["history_merge_conflict_markers_detected"]},{code:"merge_decisions_unreviewed",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"merge_driver_configuration_drift",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"merge_driver_configuration_missing",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"merge_fence_drift",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"merge_fence_missing",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"merge_git_config_unwritable",exit_code:5,stable:!0,sources:["sdk/merge/install.ts"]},{code:"merge_receipt_evidence_invalid",exit_code:4,sources:["core/diagnostics/remediation.ts","sdk/merge/reconcile.ts"]}];(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1295716e-cbc9-5497-9a14-30274f1f7086")}catch{}})();var _g=[{code:"merge_receipt_history_reference_missing",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"merge_receipt_not_portable",exit_code:4,sources:["sdk/merge/receipts.ts"]},{code:"merge_receipts_pending",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"merge_reconcile_receipt_evidence_untrusted",exit_code:4,sources:["sdk/history-repair.ts"]},{code:"merge_root_not_found",exit_code:3,stable:!0,sources:["sdk/merge/install.ts"]},{code:"merge_settlement_hook_conflict",exit_code:4,sources:["sdk/merge/settlement-hook.ts"]},{code:"merge_settlement_review_required",exit_code:4,sources:["sdk/merge/ignored-artifacts.ts","sdk/merge/reconcile.ts","sdk/merge/stage.ts"]},{code:"missing_allowed_values",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"missing_budget",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"missing_cli_flag",exit_code:1,sources:["sdk/cli-contracts/tool-option-contracts.ts"]},{code:"missing_destination",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"missing_directory",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"missing_init_recovery",exit_code:1,sources:["sdk/agent/tracker-preflight-contracts.ts"]},{code:"missing_lifecycle_target",exit_code:2,stable:!0,sources:["sdk/extension.ts"]},{code:"missing_observation",exit_code:1,sources:["sdk/flag-invocation-contracts.ts"]},{code:"missing_observed_signature",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"missing_parameter_alias",exit_code:1,sources:["sdk/cli-contracts/tool-option-contracts.ts"]},{code:"missing_positive_execution_receipt",exit_code:1,sources:["sdk/test/execution.ts"]},{code:"missing_probe",exit_code:1,sources:["sdk/agent/tracker-preflight-contracts.ts"]},{code:"missing_required_argument",exit_code:2,stable:!0,sources:["cli/error-guidance.ts","cli/main.ts","cli/register-mutation.ts","cli/schema/registration.ts","core/telemetry/observability.ts","sdk/governance/assurance-action.ts","sdk/history-redact.ts","sdk/invocation-author.ts","sdk/lifecycle/claim.ts","sdk/linked-artifacts.ts"],emitting_commands:["*","claim"]},{code:"missing_required_option",exit_code:2,stable:!0,sources:["cli/error-guidance.ts","core/telemetry/observability.ts","sdk/context-intent-contracts.ts","sdk/extension/command-options.ts","sdk/lifecycle/create.ts","sdk/lifecycle/plan.ts"],emitting_commands:["*","create","plan"]},{code:"missing_suggested_retry",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"missing_suggested_retry_args",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"module_import_failed",exit_code:1,stable:!0,sources:["cli/error-guidance.ts"]},{code:"multi_target_github_install_ambiguous",exit_code:2,stable:!0,sources:["cli/register-setup.ts"]},{code:"mutation_author_required",exit_code:2,stable:!0,sources:["sdk/mutation-guard.ts"]},{code:"mutation_document_unreadable",exit_code:2,sources:["cli/register-structured-mutation.ts"]},{code:"mutation_option_value_invalid",exit_code:2,sources:["sdk/lifecycle/mutation-option-validation.ts"],emitting_commands:["item mutate"]},{code:"mutation_secret_guard_blocked",exit_code:4,stable:!0,sources:["sdk/mutation-guard.ts"]},{code:"no_matching_tests",exit_code:1,stable:!0,sources:["sdk/test/execution-receipts.ts"]},{code:"no_projects_matched_filters",exit_code:1,stable:!0,sources:["sdk/test/execution-receipts.ts"]},{code:"no_test_files_found",exit_code:1,stable:!0,sources:["sdk/test/execution-receipts.ts"]},{code:"no_tests_found",exit_code:1,stable:!0,sources:["sdk/test/execution-receipts.ts"]},{code:"no_update_fields",exit_code:1,stable:!0,sources:["cli/error-guidance.ts","core/telemetry/observability.ts"]},{code:"no_version_bounds_declared",exit_code:1,sources:["core/extensions/manifest-schema.ts"],owned_states:[{state:"author_workspace_manifest_omits_canonical_pm_version_bounds",probe_id:"author-manifest-version-bounds-missing",entrypoints:["health"],expected_exit_class:"generic_failure"}]},{code:"non_refusal_exit",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"npm_pack_json_shape_unsupported",exit_code:1,sources:["sdk/extension/install-sources.ts"]},{code:"npm_package_archive_missing",exit_code:1,sources:["sdk/extension/install-sources.ts"]},{code:"npm_package_archive_unsafe",exit_code:1,sources:["sdk/extension/install-sources.ts"]},{code:"npm_package_not_found",exit_code:3,stable:!0,sources:["sdk/extension/install-sources.ts"]},{code:"output_budget_exceeded",exit_code:2,sources:["sdk/testing.ts"]},{code:"ownership_conflict",exit_code:4,stable:!0,sources:["cli/error-guidance.ts","core/telemetry/observability.ts","sdk/annotations.ts"]},{code:"ownership_dependency_bypass_restricted_options",exit_code:1,stable:!0,sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"]},{code:"ownership_metadata_bypass_restricted_options",exit_code:1,stable:!0,sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"]},{code:"package_spec_empty",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"package_upgrade_modes_mutually_exclusive",exit_code:2,sources:["sdk/governance/upgrade.ts"]},{code:"positional_shape_budget_exceeded",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"positional_signature_mismatch",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"profile_name_empty",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"profile_name_not_normalized",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"profile_summary_empty",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"profile_title_empty",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"project_runtime_history_epoch_incompatible",exit_code:4,sources:["sdk/environment/project-runtime-compatibility.ts"]},{code:"project_runtime_item_format_incompatible",exit_code:4,sources:["sdk/environment/project-runtime-compatibility.ts"]},{code:"project_runtime_stale_mutation",exit_code:4,sources:["sdk/environment/project-runtime-compatibility.ts"]},{code:"project_runtime_stale_read",exit_code:1,sources:["sdk/environment/project-runtime-compatibility.ts"]},{code:"project_schema_field_requires_declared_flag",exit_code:2,sources:["core/extensions/item-fields.ts"]},{code:"projection_options_mutually_exclusive",exit_code:2,sources:["sdk/query/get.ts","sdk/query/list.ts","sdk/query/search-contracts.ts"],emitting_commands:["get","list","search"]},{code:"provenance_value_domain_invalid",exit_code:2,sources:["core/diagnostics/remediation.ts"]},{code:"read_output_cursor_command_mismatch",exit_code:2,sources:["sdk/read-output/continuation.ts"]},{code:"read_output_cursor_invalid",exit_code:2,sources:["sdk/read-output/continuation.ts"]},{code:"read_output_cursor_stale",exit_code:2,sources:["sdk/read-output/continuation.ts"]},{code:"read_output_mutation_conflict",exit_code:2,sources:["sdk/read-output-contracts.ts"]},{code:"recovery_kind_mismatch",exit_code:1,sources:["sdk/agent/tracker-preflight-contracts.ts"]},{code:"redundant_edge",exit_code:1,stable:!0,sources:["sdk/graph/remediation.ts"]},{code:"refusal_allowed_values_mismatch",exit_code:1,sources:["sdk/agent/refusal-corpus-contracts.ts"]},{code:"refusal_error_code_mismatch",exit_code:1,sources:["sdk/agent/refusal-corpus-contracts.ts"]},{code:"refusal_exit_code_mismatch",exit_code:1,sources:["sdk/agent/refusal-corpus-contracts.ts"]},{code:"refusal_mutated_state",exit_code:1,sources:["sdk/agent/refusal-corpus-contracts.ts"]},{code:"refusal_probe_missing",exit_code:1,sources:["sdk/agent/refusal-corpus-contracts.ts"]},{code:"refusal_recovery_failed",exit_code:1,sources:["sdk/agent/refusal-corpus-contracts.ts"]},{code:"reindex_already_running",exit_code:4,stable:!0,sources:["sdk/governance/reindex.ts"]},{code:"removed_canonical_spelling",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"removed_compatibility_spelling",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"reopen_reason_required",exit_code:2,sources:["sdk/lifecycle/reopen.ts"],emitting_commands:["item reopen"]},{code:"reopen_receipt_missing",exit_code:1,sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"]},{code:"reopen_target_status_invalid",exit_code:2,sources:["sdk/lifecycle/reopen.ts"],emitting_commands:["item reopen"]},{code:"reported_zero_passes",exit_code:1,sources:["sdk/test/execution-receipts.ts"]},{code:"reported_zero_tests",exit_code:1,sources:["sdk/test/execution-receipts.ts"]},{code:"reserved_item_field",exit_code:1,stable:!0,sources:["sdk/compose.ts"]},{code:"retry_failed",exit_code:1,sources:["sdk/agent/refusal-closure.ts","sdk/agent/tracker-preflight-contracts.ts"]},{code:"schema_migration_input_required",exit_code:2,stable:!0,sources:["cli/migration-gates.ts"]},{code:"semantic_spelling_collision",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"settings_invalid",exit_code:2,sources:["sdk/extension/static-inventory.ts"]},{code:"settings_read_fs_error",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"settings_read_invalid_json",exit_code:2,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"settings_read_invalid_schema",exit_code:2,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"settings_read_merge_failed",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"settings_section_document_malformed",exit_code:2,sources:["core/store/settings-sections.ts"]},{code:"settings_section_document_missing",exit_code:3,sources:["core/store/settings-sections.ts"]},{code:"settings_section_invalid",exit_code:2,sources:["core/store/settings-sections.ts"]},{code:"settings_section_name_invalid",exit_code:2,sources:["core/store/settings-sections.ts"]},{code:"settings_section_reserved",exit_code:2,sources:["core/store/settings-sections.ts"]},{code:"settings_section_revision_conflict",exit_code:4,sources:["core/store/settings-sections.ts"]},{code:"settings_unreadable",exit_code:1,sources:["sdk/extension/static-inventory.ts"]},{code:"settings_write_assigned_path_invalid",exit_code:2,sources:["core/store/settings.ts"]},{code:"settings_write_invalid_existing_json",exit_code:2,sources:["core/store/settings.ts"]},{code:"settings_write_invalid_existing_schema",exit_code:2,sources:["core/store/settings.ts"]},{code:"stale_budget",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"stale_claim_takeover_refused",exit_code:4,sources:["sdk/lifecycle/claim.ts"],emitting_commands:["claim"]},{code:"stale_destination",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"stale_in_progress_items",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"stale_lock_requires_override",exit_code:4,sources:["core/lock/lock.ts"]},{code:"stale_observed_signature",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"stale_revision",exit_code:4,sources:["core/store/item-store.ts"]},{code:"start_blocked_by_open_dependency",exit_code:4,sources:["sdk/lifecycle/start-blockers.ts"],emitting_commands:["claim","start-task","update"]},{code:"status_duplicate",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"status_invalid",exit_code:2,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"status_lifecycle_role_required",exit_code:2,sources:["sdk/schema.ts"]},{code:"stdin_json_invalid",exit_code:2,stable:!0,sources:["sdk/structured-mutations.ts"]},{code:"stdin_json_persisted_annotation_changed",exit_code:2,sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"]},{code:"stdin_json_unknown_key",exit_code:2,stable:!0,sources:["sdk/structured-mutations.ts"]},{code:"structured_entry_key_repeated",exit_code:2,sources:["core/item/parse.ts"]},{code:"structured_event_immutable",exit_code:2,stable:!0,sources:["sdk/annotations.ts"]},{code:"structured_event_input_conflict",exit_code:2,stable:!0,sources:["sdk/notes.ts"]},{code:"structured_event_json_empty",exit_code:2,stable:!0,sources:["sdk/notes.ts"]},{code:"structured_event_json_invalid",exit_code:2,stable:!0,sources:["sdk/notes.ts"]},{code:"structured_event_since_invalid",exit_code:2,stable:!0,sources:["sdk/notes.ts"]},{code:"suggested_retry_args_mismatch",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"telemetry_endpoint_probe_failed",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"telemetry_endpoint_probe_http_status",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"telemetry_otel_export_failing",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"telemetry_queue_high_retries",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"telemetry_queue_invalid_rows",exit_code:2,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"telemetry_queue_pending",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"telemetry_schema_version_behind",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"telemetry_state_invalid_json",exit_code:2,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"template_type_unknown",exit_code:2,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"terminal_plan_mutation",exit_code:4,stable:!0,sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"]},{code:"terminal_state_conflict",exit_code:4,stable:!0,sources:["core/telemetry/observability.ts","sdk/lifecycle/claim.ts"],emitting_commands:["*","claim"]},{code:"test_measure_requires_execution",exit_code:2,sources:["sdk/test/prerequisites.ts"]},{code:"test_measure_requires_run",exit_code:2,sources:["sdk/test/prerequisites.ts"]},{code:"text_unpaired_surrogate",exit_code:2,sources:["core/item/item-format.ts","core/shared/output-unicode.ts"]},{code:"tracked_runtime_cache_files",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_storage_tracked_runtime_cache_files"]},{code:"tracker_not_initialized",exit_code:3,stable:!0,sources:["cli/error-guidance.ts","core/store/tracker-preflight.ts","core/telemetry/observability.ts"],owned_states:[{state:"selected_tracker_root_exists_without_settings",probe_id:"tracker-root-settings-missing",entrypoints:["list"],expected_exit_class:"not_found"}]},{code:"tracker_root_missing",exit_code:3,stable:!0,sources:["core/store/tracker-preflight.ts"],owned_states:[{state:"selected_tracker_root_does_not_exist",probe_id:"tracker-root-missing",entrypoints:["list"],expected_exit_class:"not_found"}]},{code:"tracker_root_not_directory",exit_code:2,stable:!0,sources:["core/store/tracker-preflight.ts"],owned_states:[{state:"selected_tracker_root_is_a_regular_file",probe_id:"tracker-root-not-directory",entrypoints:["list"],expected_exit_class:"usage"}]},{code:"tracker_root_unreadable",exit_code:1,sources:["core/store/tracker-preflight.ts"],owned_states:[{state:"selected_tracker_root_is_not_readable",probe_id:"tracker-root-unreadable",entrypoints:["list"],expected_exit_class:"generic_failure"}]},{code:"transaction_abandoned",exit_code:4,sources:["sdk/workspace-transaction.ts"]},{code:"transaction_committed",exit_code:4,sources:["sdk/workspace-transaction.ts"]},{code:"transaction_create_compensated",exit_code:4,sources:["sdk/item-transaction.ts"]},{code:"transaction_journal_invalid",exit_code:4,sources:["sdk/workspace-transaction.ts"]},{code:"transaction_partial_mutation",exit_code:4,sources:["sdk/item-transaction.ts"]},{code:"transaction_plan_mismatch",exit_code:4,sources:["sdk/workspace-transaction.ts"]},{code:"transaction_preview_external_schema",exit_code:2,sources:["sdk/item-transaction.ts"]},{code:"transaction_preview_non_regular_file",exit_code:2,sources:["core/fs/fs-utils.ts"]},{code:"transaction_preview_snapshot_changed",exit_code:4,sources:["sdk/item-transaction.ts"]},{code:"transaction_recovery_plan_missing",exit_code:4,sources:["sdk/item-transaction.ts"]},{code:"type_duplicate",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"type_invalid",exit_code:2,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"undeclared_observation",exit_code:1,sources:["sdk/flag-invocation-contracts.ts"]},{code:"unexpected_refusal_probe",exit_code:1,sources:["sdk/agent/refusal-corpus-contracts.ts"]},{code:"unknown_command",exit_code:2,stable:!0,sources:["cli/error-guidance.ts","core/telemetry/observability.ts","sdk/cli-contracts/runtime-contracts.ts"]},{code:"unknown_context_intent",exit_code:2,stable:!0,sources:["sdk/context-intent-contracts.ts"]},{code:"unknown_error",exit_code:1,stable:!0,sources:["cli/error-guidance.ts"]},{code:"unknown_field",exit_code:3,stable:!0,sources:["sdk/schema.ts"]},{code:"unknown_field_projection",exit_code:2,stable:!0,sources:["sdk/query/get.ts","sdk/query/list.ts","sdk/query/search-contracts.ts"],emitting_commands:["get","list","search"]},{code:"unknown_item_type",exit_code:3,stable:!0,sources:["sdk/schema.ts"]},{code:"unknown_lifecycle_action",exit_code:2,stable:!0,sources:["sdk/agent/subcommand-recovery.ts"],canonical_code:"unknown_subcommand"},{code:"unknown_noun",exit_code:2,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"unknown_option",exit_code:2,stable:!0,sources:["cli/error-guidance.ts","cli/runtime/invocation-options.ts","core/telemetry/observability.ts","sdk/extension/command-options.ts"],owned_states:[{state:"declared_option_is_rejected_on_the_selected_command_path",probe_id:"cross-command-unknown-option",entrypoints:["deps"],expected_exit_class:"usage"}]},{code:"unknown_plan_template",exit_code:2,stable:!0,sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"]},{code:"unknown_provenance_dimension",exit_code:2,stable:!0,sources:["sdk/history-provenance.ts"]},{code:"unknown_status",exit_code:3,stable:!0,sources:["sdk/schema.ts"]},{code:"unknown_subcommand",exit_code:2,stable:!0,sources:["cli/error-guidance.ts","sdk/agent/subcommand-recovery.ts"],aliases:["unknown_lifecycle_action"],owned_states:[{state:"config_action_token_is_not_declared",probe_id:"config-unknown-action",entrypoints:["config"],expected_exit_class:"usage"},{state:"graph_command_token_is_not_declared",probe_id:"graph-unknown-subcommand",entrypoints:["graph"],expected_exit_class:"usage"},{state:"nested_command_token_is_not_declared_by_its_family",probe_id:"schema-unknown-subcommand",entrypoints:["schema"],expected_exit_class:"usage"},{state:"package_lifecycle_token_is_not_declared",probe_id:"package-unknown-action",entrypoints:["package"],expected_exit_class:"usage"}]},{code:"unsafe_init_recovery",exit_code:1,sources:["sdk/agent/tracker-preflight-contracts.ts"]},{code:"unsupported_update_option",exit_code:1,stable:!0,sources:["cli/error-guidance.ts"]},{code:"upsert_key_ambiguous",exit_code:4,sources:["sdk/structured-mutations.ts"]},{code:"upsert_key_conflict",exit_code:4,sources:["sdk/item-transaction.ts"]},{code:"upsert_key_duplicate",exit_code:2,sources:["sdk/item-transaction.ts","sdk/structured-mutations.ts"]},{code:"upsert_key_missing",exit_code:2,sources:["sdk/structured-mutations.ts"]},{code:"upsert_match_changed",exit_code:4,sources:["sdk/item-transaction.ts"]},{code:"validate_command_references_stale_pm_ids",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_files_missing_linked_paths",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_files_orphaned_paths",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_files_tracked_all_strict_forces_pm_internals",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_format_version_ahead_items",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"integrity_item_ahead_format_version"},{code:"validate_format_version_outdated_items",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"integrity_item_outdated_format_version"},{code:"validate_hierarchy_parent_cycle",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_hierarchy_parent_cycle_error",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_history_drift_chain_mismatches",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"history_drift_chain_mismatch"},{code:"validate_history_drift_hash_mismatches",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"history_drift_hash_mismatch"},{code:"validate_history_drift_missing_streams",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"history_drift_missing_stream"},{code:"validate_history_drift_unreadable_streams",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"history_drift_unreadable_stream"},{code:"validate_history_drift_version_skews",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"history_drift_version_skew"},{code:"validate_history_unknown_author_events",exit_code:2,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"history_unknown_author_events"},{code:"validate_lifecycle_active_closure_like_metadata",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_lifecycle_active_terminal_parent",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_lifecycle_dependency_cycles",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_lifecycle_dependency_cycles_error",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_lifecycle_stale_blockers",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_merge_decisions_unreviewed",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"validate_merge_driver_configuration",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"validate_merge_fence_drift",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_custom_profile_missing_required_fields",exit_code:2,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_duplicate_issue_codes",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_acceptance_criteria",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_close_reason",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_closed_at",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_confidence",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_estimate",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_release",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_reviewer",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_risk",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_sprint",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_resolution_missing_fields",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_storage_duplicate_item_ids",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_storage_history_conflict_markers",exit_code:4,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"integrity_history_conflict_marker"},{code:"validate_storage_resurrected_items",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_storage_tracked_runtime_cache_files",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"tracked_runtime_cache_files"},{code:"validate_storage_unparseable_config",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_storage_unparseable_history",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_storage_unreadable_items",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"vectorization_embedding_identity_changed",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"vectorization_stale_items_remaining",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"visible_surface_ceiling_exceeded",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"workflow_duplicate_type",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"workflow_policy_approval_history_invalid",exit_code:4,sources:["core/policy/workflow-policy-store.ts"]},{code:"workflow_policy_audit_failed",exit_code:4,sources:["core/policy/workflow-policy-store.ts"]},{code:"workflow_policy_input_unreadable",exit_code:4,sources:["core/policy/workflow-policy-store.ts"]},{code:"workflow_policy_invalid",exit_code:2,sources:["core/policy/workflow-policy.ts"]},{code:"workflow_policy_refused",exit_code:4,sources:["core/policy/workflow-policy-store.ts"]},{code:"workflow_policy_registry_invalid",exit_code:4,sources:["core/policy/workflow-policy-store.ts"]},{code:"workflow_status_unknown",exit_code:2,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"workflow_transition_malformed",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"workflow_type_empty",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"workflow_type_unknown",exit_code:2,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"workspace_history_chain_invalid",exit_code:4,sources:["core/history/workspace-history.ts"]},{code:"workspace_history_state_conflict",exit_code:4,stable:!0,sources:["core/history/workspace-history.ts"]},{code:"workspace_root_pm_path",exit_code:2,stable:!0,sources:["sdk/init.ts"]},{code:"workspace_snapshot_force_required",exit_code:2,sources:["sdk/workspace-snapshot.ts"]},{code:"workspace_snapshot_manifest_mismatch",exit_code:4,sources:["sdk/workspace-snapshot.ts"]},{code:"workspace_snapshot_name_reserved_fingerprint",exit_code:2,sources:["sdk/workspace-snapshot.ts"]},{code:"workspace_snapshot_not_found",exit_code:3,sources:["sdk/workspace-snapshot.ts"]},{code:"workspace_snapshot_permission_denied",exit_code:1,sources:["sdk/workspace-snapshot.ts"]},{code:"workspace_snapshot_resource_exhausted",exit_code:1,sources:["sdk/workspace-snapshot.ts"]},{code:"workspace_snapshot_storage_exhausted",exit_code:1,sources:["sdk/workspace-snapshot.ts"]},{code:"wrong_item_type",exit_code:2,stable:!0,sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"]}];(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b525d8c8-3a70-52bd-83db-c956aba0c6fb")}catch{}})();var fg=ug(mg([...pg,..._g]));(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="76c420db-b520-5fde-bd43-16a7324feb0a")}catch{}})();var IT=["mutation_receipt","entity","collection","diagnostic","stream"],OT=new Set(["append","claim","close","close-task","copy","create","delete","focus","pause-task","release","restore","start-task","update"]),LT=new Set(["close-many","update-many"]),DT=new Set(["activity","comments","contracts","events","history","learnings","list","notes","search"]),$T=new Set(["aggregate","deps","graph","health","history-redact","history-repair","history-compact","stats","validate"]);function Ur(e){if(e.command.trim().length===0)throw new TypeError("command must be a non-empty command path");if(!IT.includes(e.kind))throw new TypeError(`Unsupported output envelope kind: ${e.kind}`);return e}function hg(e){let t=e.trim().replace(/\s+/gu," "),[n=t]=t.split(" ");return LT.has(n)?Ur({command:t,kind:"collection",wrapper_key:"rows",cardinality:"many",format_flag:"--json"}):OT.has(n)?Ur({command:t,kind:"mutation_receipt",wrapper_key:null,cardinality:"one",format_flag:"--json"}):DT.has(n)?Ur({command:t,kind:"collection",wrapper_key:n==="contracts"?null:"items",cardinality:"many",format_flag:"--json"}):$T.has(n)?Ur({command:t,kind:"diagnostic",wrapper_key:null,cardinality:"none",format_flag:"--json"}):Ur({command:t,kind:n==="get"?"entity":"diagnostic",wrapper_key:n==="get"?"item":null,cardinality:n==="get"?"one":"none",format_flag:"--json"})}var NT=st.map(e=>hg(e)),MT=new Map(NT.map(e=>[e.command,e]));function gg(e){let t=e.trim().replace(/\s+/gu," ");if(t.length===0)throw new TypeError("command must be a non-empty command path");let[n=t]=Ii(t).split(" "),r=MT.get(n);return r?{...r,command:t}:hg(t)}function PT(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function FT(e){return PT(e)&&typeof e.id=="string"&&e.id.length>0&&typeof e.status=="string"&&e.status.length>0&&Number.isSafeInteger(e.changed_field_count)&&Number(e.changed_field_count)>=0&&(e.close_reason===void 0||typeof e.close_reason=="string")&&(e.deleted===void 0||typeof e.deleted=="boolean")&&(e.previous_status===void 0||typeof e.previous_status=="string")&&(e.warnings===void 0||Array.isArray(e.warnings))}function pq(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch(n){throw new TypeError(`Mutation receipt must be valid JSON: ${String(n)}`,{cause:n})}if(!FT(t))throw new TypeError("Mutation receipt must be a flat object with top-level id, status, and changed_field_count fields");return{id:t.id,status:t.status,changedFieldCount:t.changed_field_count,...typeof t.close_reason=="string"?{closeReason:t.close_reason}:{},...typeof t.deleted=="boolean"?{deleted:t.deleted}:{},...typeof t.previous_status=="string"?{previousStatus:t.previous_status}:{},...Array.isArray(t.warnings)?{warnings:t.warnings}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7c95b311-b408-50f7-87e8-2c2fa2323092")}catch{}})();var Pc=[{exit_code:m.SUCCESS,outcome:"effect",success:!0,meaning:"The requested operation completed with its intended effect."},{exit_code:m.GENERIC_FAILURE,outcome:"internal_failure",success:!1,meaning:"An unexpected runtime or internal failure prevented completion."},{exit_code:m.USAGE,outcome:"refused_input",success:!1,meaning:"The invocation was refused because its input or composition was invalid."},{exit_code:m.NOT_FOUND,outcome:"refused_tracker_state",success:!1,meaning:"The requested tracker, item, or resource was not present."},{exit_code:m.CONFLICT,outcome:"conflict",success:!1,meaning:"Current state or concurrency prevented the requested effect."},{exit_code:m.DEPENDENCY_FAILED,outcome:"dependency_failed",success:!1,meaning:"A required dependency operation failed."},{exit_code:m.NO_EFFECT,outcome:"no_effect",success:!0,meaning:"The request was valid and completed, but matched nothing to change."},{exit_code:m.PARTIAL_EFFECT,outcome:"partial_effect",success:!0,meaning:"The request completed and changed some, but not all, selected targets."}],yg=[m.SUCCESS,m.GENERIC_FAILURE,m.USAGE,m.NOT_FOUND,m.CONFLICT,m.DEPENDENCY_FAILED],jT=new Set(["close-many","update-many"]),vg=st.map(e=>({command:e,exit_codes:jT.has(e)?[...yg,m.NO_EFFECT,m.PARTIAL_EFFECT]:[...yg]})),wg=new Map(vg.map(e=>[e.command,e])),UT=[m.SUCCESS,m.NO_EFFECT,m.PARTIAL_EFFECT];function gq(e){return UT.includes(e)}function yq(e){return Pc.some(t=>t.exit_code===e)}function bg(e){let t=e.trim().toLowerCase().split(/\s+/u).filter(Boolean).join(" ");return wg.get(t)??wg.get(t.split(" ")[0])}function wq(e,t=st,n=vg){let r=new Map(n.map(c=>[c.command,c])),i=t.filter(c=>!r.has(c)),o=e.filter(c=>{let d=r.get(c.command)??r.get(c.command.split(" ")[0]);return d===void 0||!d.exit_codes.includes(c.exit_code)}),s=new Set(e.map(c=>c.exit_code)),a=[...new Set(n.flatMap(c=>c.exit_codes))].filter(c=>!s.has(c)).sort((c,d)=>c-d);return{ok:i.length===0&&o.length===0&&a.length===0,missing_commands:i,undeclared_observations:o,unreachable_exit_codes:a}}function vq(e){return e.applied===0&&e.failed>0?{outcome:"dependency_failed",exit_code:m.DEPENDENCY_FAILED}:e.applied===0?{outcome:"no_effect",exit_code:m.NO_EFFECT}:e.skipped>0||e.failed>0||e.unmatched>0?{outcome:"partial_effect",exit_code:m.PARTIAL_EFFECT}:{outcome:"effect",exit_code:m.SUCCESS}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="081bf1eb-4b9a-5fa9-a272-34ae781d250c")}catch{}})();var D=class extends TypeError{constructor(t){super(t),this.name="AssuranceMutationRefusalError"}},Le=class extends TypeError{context;constructor(t,n={}){super(t),this.name="AssuranceEvaluationRefusalError",this.context=n}},ut=class extends TypeError{measurement_id;source_kind;field;check;constructor(t,n){super(t),this.name="AssuranceSourceResolutionError",this.measurement_id=n.measurement_id,this.source_kind=n.source_kind,this.field=n.field,this.check=n.check}};async function Gn(e){try{return await e()}catch(t){throw t instanceof D?new p(t.message,m.USAGE,{code:"invalid_argument_value",reason:"assurance_mutation_refused"}):t}}async function Fc(e){try{return await e()}catch(t){throw t instanceof Le?new p(t.message,m.USAGE,{code:"invalid_argument_value",reason:"assurance_evaluation_refused",...t.context}):t}}import{createHash as GT}from"node:crypto";import qT from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b00dcab2-22c6-55b7-b93d-f6f5413d4b04")}catch{}})();var qn=1e3;(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="eaede7d4-43ae-5551-915e-19befefc29d0")}catch{}})();var Sg=1,yt=["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"],Gr=["items","dependency_kind","prose_edge_gap","graph","validate","health","history","links","provider","derived"],KT=["ceiling","floor","equals","zero","monotone_nondecreasing","monotone_nonincreasing","subset_of"],WT=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,Do=30,$o=5e3,Eg=4,zT=50;function wt(e,t){if(!WT.test(e))throw new D(`${t} must be a stable lowercase id`)}function BT(e,t){if(!Number.isFinite(e)||e<0)throw new D(`${t} must be a finite non-negative number`)}function qr(e){let t=KT.filter(i=>e[i]!==void 0);if(t.length!==1)throw new D(`assertion ${e.id} must declare exactly one polarity`);let n=t[0],r=e[n];return{polarity:n,value:n==="zero"?0:r}}function Uc(e,t){return Z(e)===Z(t)}function Tg(e,t){if(t.polarity==="equals")return Uc(e,t.value);if(t.polarity==="subset_of"){if(!Array.isArray(e)||!Array.isArray(t.value))return!1;let r=t.value;return e.every(i=>r.includes(i))}if(typeof e!="number")return!1;let n=t.value;return t.polarity==="ceiling"||t.polarity==="monotone_nonincreasing"?e<=n:t.polarity==="floor"||t.polarity==="monotone_nondecreasing"?e>=n:e===0}function Cg(e){let t=qr(e),n=e.negative_control.cases;return n.some(r=>r.expected==="pass")&&n.some(r=>r.expected==="fail")&&n.every(r=>Tg(r.observed,t)===(r.expected==="pass"))}function HT(e,t){if(e.polarity!==t.polarity)return!0;if(typeof e.value=="number"&&typeof t.value=="number")return e.polarity==="ceiling"||e.polarity==="monotone_nonincreasing"?t.value>e.value:e.polarity==="floor"||e.polarity==="monotone_nondecreasing"?t.value<e.value:t.value!==e.value;if(e.polarity==="subset_of"){let n=e.value,r=t.value;return!Array.isArray(n)||!Array.isArray(r)||r.some(i=>!n.includes(i))}return!Uc(e.value,t.value)}function VT(e,t){if(e.measurement_id!==t.measurement_id||e.owner_item_id!==t.owner_item_id||Z(e.scope)!==Z(t.scope))return!0;let n={observe:0,warn:1,block:2},r=(e.lifetime??"hold")==="hold"&&(t.lifetime??"hold")==="retire";return HT(qr(e),qr(t))||n[t.enforcement]<n[e.enforcement]||r}function YT(e){if(e.state!==void 0&&!(e.state==="present"||e.state==="missing"))throw new D("items source state must be present or missing");let t=Object.hasOwn(e,"equals"),n=e.state!==void 0,r=Number(t)+Number(n);if(e.field!==void 0&&r!==1)throw new D("items source with field requires exactly one of equals or state");if(e.field===void 0&&r!==0)throw new D("items source equals/state requires field")}function JT(e){if(typeof e.dependency_kind!="string"||e.dependency_kind.trim().length===0)throw new D("dependency_kind source requires dependency_kind");if([e.source_kind,e.source_kind_prefix,e.source_kind_state].filter(t=>t!==void 0).length>1)throw new D("dependency_kind source accepts at most one source_kind predicate");if(e.source_kind!==void 0&&e.source_kind.trim().length===0||e.source_kind_prefix!==void 0&&e.source_kind_prefix.trim().length===0)throw new D("dependency_kind source provenance values must not be empty");if(e.source_kind_state!==void 0&&e.source_kind_state!=="present"&&e.source_kind_state!=="missing")throw new D("dependency_kind source source_kind_state must be present or missing")}function XT(e){if(e.sample_limit!==void 0&&(!Number.isInteger(e.sample_limit)||e.sample_limit<1))throw new D("prose_edge_gap sample_limit must be a positive integer");for(let t of e.exemptions??[]){if(typeof t.holder_id!="string"||t.holder_id.trim().length===0||typeof t.reason!="string"||t.reason.trim().length===0)throw new D("prose_edge_gap exemptions require holder_id and reason");if(t.target_id!==void 0&&t.target_id.trim().length===0||t.text_contains!==void 0&&t.text_contains.trim().length===0)throw new D("prose_edge_gap exemption selectors must not be empty")}}function Gc(e){wt(e.id,"measurement.id"),e.max_cost!==void 0&&BT(e.max_cost,"measurement.max_cost");let t=e.source;if(Object.prototype.toString.call(t)!=="[object Object]")throw new D(`measurement.source.kind must be one of ${Gr.join(", ")}`);let n=Reflect.get(t,"kind");if(!Gr.includes(n))throw new D(`measurement.source.kind must be one of ${Gr.join(", ")}`);let r=t;if(r.kind==="items"&&YT(r),r.kind==="dependency_kind"&&JT(r),r.kind==="prose_edge_gap"&&XT(r),(r.kind==="graph"||r.kind==="validate"||r.kind==="health")&&(typeof r.field!="string"||r.field.trim().length===0))throw new D(`${r.kind} source requires field`);return r.kind==="provider"&&(wt(r.provider,"provider source provider"),wt(r.key,"provider source key")),e}function qc(e){if(wt(e.id,"assertion.id"),wt(e.measurement_id,"assertion.measurement_id"),typeof e.owner_item_id!="string"||e.owner_item_id.trim().length===0)throw new D("assertion.owner_item_id is required");let t=qr(e);if(typeof t.value=="number"&&!Number.isFinite(t.value))throw new D(`assertion.${t.polarity} must be a finite number`);if(e.lifetime==="retire"&&(typeof e.retire_reason!="string"||e.retire_reason.trim().length===0))throw new D("retired assertion requires retire_reason");e.scope.kind==="filter"&&wt(e.scope.measurement_id,"assertion.scope.measurement_id");let n=e.negative_control?.cases;if(!Array.isArray(n)||!n.some(r=>r.expected==="pass")||!n.some(r=>r.expected==="fail"))throw new D("assertion negative control requires pass and fail cases");if(!Cg(e))throw new D(`assertion ${e.id} negative control does not prove its bound`);return e}function QT(e){if(!Array.isArray(e.allowed_providers))throw new D("gate provider_policy.allowed_providers must be an array");for(let t of e.allowed_providers)wt(t,"gate.provider_policy.allowed_provider");if(typeof e.triggers!="object"||e.triggers===null||Array.isArray(e.triggers))throw new D("gate provider_policy.triggers must be an object");for(let[t,n]of Object.entries(e.triggers)){if(!yt.includes(t))throw new D(`gate provider policy has unknown trigger ${t}`);if(typeof n!="object"||n===null||!["low","medium","high"].includes(n.max_cost_class)||typeof n.allow_network!="boolean")throw new D(`gate provider policy trigger ${t} is invalid`)}}function Ag(e){if(wt(e.id,"gate.id"),!Array.isArray(e.assertion_ids))throw new D("gate.assertion_ids is required and must be an array");if(e.assertion_ids.length===0)throw new D("gate requires at least one assertion");for(let t of e.assertion_ids)wt(t,"gate.assertion_id");if(!Array.isArray(e.triggers))throw new D(`gate.triggers is required and must be an array of ${yt.join(", ")}`);if(e.triggers.length===0)throw new D("gate requires at least one trigger");for(let t of e.triggers)if(!yt.includes(t))throw new D(`gate trigger must be one of ${yt.join(", ")}`);return e.provider_policy&&QT(e.provider_policy),e}function Kn(e){if(e.version!==Sg)throw new D(`unsupported assurance document version ${String(e.version)}`);let t=new Set;for(let r of e.measurements){if(Gc(r),t.has(`measurement:${r.id}`))throw new D(`duplicate measurement ${r.id}`);t.add(`measurement:${r.id}`)}for(let r of e.assertions){if(qc(r),t.has(`assertion:${r.id}`))throw new D(`duplicate assertion ${r.id}`);t.add(`assertion:${r.id}`)}for(let r of e.gates){Ag(r);let i=r.assertion_ids.filter(o=>!e.assertions.some(s=>s.id===o));if(i.length>0)throw new D(`gate ${r.id} references missing assertions: ${i.join(", ")}`);if(t.has(`gate:${r.id}`))throw new D(`duplicate gate ${r.id}`);t.add(`gate:${r.id}`)}let n=new Set(e.measurements.map(r=>r.id));for(let[r,i]of xg(e))if(!n.has(r))throw new D(`${i.join(", ")} references missing measurement ${r}`);return e}function Kc(e,t){if("measurement"in e){t.push(e.measurement);return}if("operator"in e)for(let n of e.operands)Kc(n,t)}function xg(e){let t=new Map,n=(r,i)=>{let o=t.get(r)??[];o.push(i),t.set(r,o)};for(let r of e.assertions)n(r.measurement_id,`assertion ${r.id}`),r.scope.kind==="filter"&&n(r.scope.measurement_id,`assertion ${r.id} scope`);for(let r of e.measurements){if(r.source.kind!=="derived")continue;let i=[];Kc(r.source.expression,i);for(let o of i)n(o,`derived measurement ${r.id}`)}return t}function ZT(e,t){let n=e.assertion_ids.flatMap(o=>{let s=t.assertions.find(a=>a.id===o);return[s.measurement_id,...s.scope.kind==="filter"?[s.scope.measurement_id]:[]]}),r=new Set,i=new Set;for(;n.length>0;){let o=n.pop();if(r.has(o))continue;r.add(o);let s=t.measurements.find(a=>a.id===o);s.source.kind==="provider"?i.add(s.source.provider):s.source.kind==="derived"&&Kc(s.source.expression,n)}return i}function Kr(){return{version:Sg,measurements:[],assertions:[],gates:[]}}function eC(e,t){let n=t.items.filter(r=>(e.statuses===void 0||e.statuses.includes(r.status))&&(e.types===void 0||e.types.includes(r.type))&&(e.tags===void 0||e.tags.every(i=>r.tags?.includes(i)))&&(e.field===void 0||(()=>{let i=r[e.field];if(e.state!==void 0){let o=i==null||i===""||Array.isArray(i)&&i.length===0;return e.state==="missing"?o:!o}return Uc(i,e.equals)})()));return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(r=>r.id)}}function tC(e,t){return e.source_kind!==void 0?t?.toLowerCase()===e.source_kind.trim().toLowerCase():e.source_kind_prefix!==void 0?t?.toLowerCase().startsWith(e.source_kind_prefix.trim().toLowerCase())===!0:e.source_kind_state==="present"?t!==void 0&&t.length>0:e.source_kind_state==="missing"?t===void 0||t.length===0:!0}function nC(e,t){let n=[],r=kr(e.dependency_kind)??e.dependency_kind.trim().toLowerCase();for(let i of t.items)for(let o of i.dependencies??[]){let s=kr(o.kind)??o.kind.trim().toLowerCase(),a=o.source_kind?.trim();s===r&&tC(e,a)&&n.push(`${i.id}->${o.id}${a?`@${a}`:""}`)}return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n}}function rC(e){let t=[e.description,e.body].filter(n=>typeof n=="string").map(n=>n.trim()).filter(Boolean);for(let n of["comments","notes","learnings"]){let r=e[n];if(Array.isArray(r)){for(let i of r)if(typeof i=="string")t.push(i);else if(typeof i=="object"&&i!==null){let o=Reflect.get(i,"text");typeof o=="string"&&t.push(o)}}}return t}function iC(e,t,n,r){return e.some(i=>i.holder_id.trim().toLowerCase()===t.toLowerCase()&&(i.target_id===void 0||i.target_id.trim().toLowerCase()===n.toLowerCase())&&(i.text_contains===void 0||r.toLowerCase().includes(i.text_contains.trim().toLowerCase())))}function jc(e,t){return[e.toLowerCase(),t.toLowerCase()].sort().join("\0")}function oC(e){let t=new Map,n=new Set,r=[],i=/(?<![\w-])[a-z0-9]+(?:-+[a-z0-9]+)+(?![\w-])/giu,o=0;for(let s of e){t.set(s.id.toLowerCase(),s.id);for(let a of s.dependencies??[])n.add(jc(s.id,a.id));for(let a of[s.parent,s.blocked_by])typeof a=="string"&&n.add(jc(s.id,a));for(let a of rC(s)){let c=[...a.matchAll(i)].map(d=>d[0]);o+=c.length,r.push({holder_id:s.id,segment:a,mentioned_ids:c})}}return{canonical_ids:t,linked_pairs:n,prose_mentions:r,mention_count:o}}function sC(e,t){let n=oC(t.items),r=new Map;for(let s of n.prose_mentions){let a=s.mentioned_ids.map(d=>n.canonical_ids.get(d.toLowerCase())).filter(d=>d!==void 0&&d!==s.holder_id),c=[...new Set(a)];for(let d of c){let l=jc(s.holder_id,d);if(n.linked_pairs.has(l)||iC(e.exemptions??[],s.holder_id,d,s.segment))continue;let u=c.some(_=>_!==d);r.get(l)?.explicit===!0&&!u||r.set(l,{contributor:`${s.holder_id}->${d}|subject=${u?"explicit":"implicit"}`,explicit:u})}}let i=[...r.values()],o=i.map(s=>s.contributor).sort();return{value:o.length,population_size:n.canonical_ids.size,cost:t.items.length+n.linked_pairs.size+n.mention_count,contributors:o.slice(0,e.sample_limit??25),partitions:{explicit_subject:i.filter(s=>s.explicit).length,implicit_subject:i.filter(s=>!s.explicit).length}}}function aC(e,t){return{value:t.history.filter(n=>(e.op===void 0||n.op===e.op)&&(e.author===void 0||n.author===e.author)&&(e.harness===void 0||n.agent_harness===e.harness)&&(e.model===void 0||n.agent_model===e.model)).length,population_size:t.history.length,cost:t.history.length}}function cC(e,t){let n=t.items.filter(r=>{let i=r[e.link],o=Array.isArray(i)&&i.length>0;return e.state==="present"?o:!o});return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(r=>r.id)}}function dC(e,t){let n=e.source;return n.kind==="items"?eC(n,t):n.kind==="dependency_kind"?nC(n,t):n.kind==="prose_edge_gap"?sC(n,t):n.kind==="history"?aC(n,t):n.kind==="links"?cC(n,t):null}function Rg(e,t){return e.reduce((n,r)=>({units:n.units+r.units,items_scanned:n.items_scanned+r.items_scanned,history_entries:n.history_entries+r.history_entries,provider_calls:n.provider_calls+r.provider_calls,duration_ms:t}),{units:0,items_scanned:0,history_entries:0,provider_calls:0,duration_ms:t})}function lC(e,t){if(t.length===0)throw new TypeError(`derived ${e} requires operands`);if(e==="add")return t.reduce((n,r)=>n+r,0);if(e==="subtract")return t.slice(1).reduce((n,r)=>n-r,t[0]);if(e==="multiply")return t.reduce((n,r)=>n*r,1);if(e==="divide"){if(t.slice(1).includes(0))throw new TypeError("derived divide cannot divide by zero");return t.slice(1).reduce((n,r)=>n/r,t[0])}return e==="min"?Math.min(...t):Math.max(...t)}async function Ig(e,t,n){let r=new Array(e.length),i=0,o=Array.from({length:Math.min(t,e.length)},async()=>{for(;i<e.length;){let s=i;i+=1,r[s]=await n(e[s],s)}});return await Promise.all(o),r}async function Og(e,t,n,r,i){if("literal"in e)return{value:e.literal,costs:[],population_size:0,contributors:[]};if("measurement"in e){let s=n.find(d=>d.id===e.measurement);if(!s)throw new TypeError(`derived measurement references missing ${e.measurement}`);let a=await Lg(s,t,n,r,i);if(typeof a.value!="number")throw new TypeError(`derived measurement ${s.id} is not numeric`);let c=i.charged.has(s.id)?[]:[a.cost];return i.charged.add(s.id),{value:a.value,costs:c,population_size:a.population_size,contributors:a.contributors}}let o=await Ig(e.operands,Eg,s=>Og(s,t,n,r,i));return{value:lC(e.operator,o.map(s=>s.value)),costs:o.flatMap(s=>s.costs),population_size:Math.max(0,...o.map(s=>s.population_size)),contributors:[...new Set(o.flatMap(s=>s.contributors))]}}async function uC(e,t,n,r,i){Gc(e);let o=Date.now(),s,a=[],c=0;if(e.source.kind==="derived"){let u=await Og(e.source.expression,t,n,[...r,e.id],i);s={value:u.value,population_size:u.population_size,cost:0,contributors:u.contributors},a=u.costs}else{let u=dC(e,t);u!==null?s=u:(s=await t.external(e.source),c=1)}let d={units:s.cost,items_scanned:e.source.kind==="items"||e.source.kind==="dependency_kind"||e.source.kind==="prose_edge_gap"||e.source.kind==="links"?t.items.length:0,history_entries:e.source.kind==="history"?t.history.length:0,provider_calls:c,duration_ms:Date.now()-o},l=Rg([...a,d],Date.now()-o);if(e.max_cost!==void 0&&l.units>e.max_cost)throw new Le(`measurement ${e.id} exceeded cost ceiling ${e.max_cost} with ${l.units}`);return{id:e.id,definition_fingerprint:`sha256:${GT("sha256").update(Z(e)).digest("hex")}`,value:s.value,population_size:s.population_size,cost:l,contributors:s.contributors??[],...s.partitions?{partitions:s.partitions}:{}}}function Lg(e,t,n,r,i){if(r.includes(e.id))throw new TypeError(`derived measurement cycle: ${[...r,e.id].join(" -> ")}`);let o=i.cache.get(e.id);if(o)return o;let s=uC(e,t,n,r,i).catch(a=>{if(a instanceof ut&&a.measurement_id===void 0){let c={measurement_id:e.id,source_kind:a.source_kind,field:a.field,...a.check?{check:a.check}:{}},d=new ut(a.message,c);throw d.cause=a,d}throw a});return i.cache.set(e.id,s),s}async function Wc(e,t,n=[e]){return Lg(e,t,n,[],{cache:new Map,charged:new Set})}function mC(e,t){return typeof e!="number"||typeof t.value!="number"?null:t.polarity==="ceiling"||t.polarity==="monotone_nonincreasing"?t.value-e:(t.polarity==="floor"||t.polarity,e-t.value)}function pC(e,t,n={}){qc(e);let r=qr(e),i=e.lifetime==="retire"&&n.owner_terminal===!0;return{assertion_id:e.id,measurement_id:e.measurement_id,measurement_definition_fingerprint:t.definition_fingerprint,scope:e.scope,population_size:t.population_size,observed:t.value,bound:r,distance:mC(t.value,r),verdict:i?"retired":Tg(t.value,r)?"pass":"fail",enforcement:e.enforcement,negative_control_proven:Cg(e),cost:t.cost,contributors:t.contributors,...t.partitions?{partitions:t.partitions}:{}}}function _C(e,t,n,r){let i=ZT(e,t);if(i.size===0)return;let o=e.provider_policy,s=o?.triggers[r];if(!o||!s)throw new Le(`assurance gate ${e.id} refuses provider execution at trigger ${r} without an explicit provider policy`);let a=new Set(o.allowed_providers),c={low:0,medium:1,high:2};for(let d of i){if(!a.has(d))throw new Le(`assurance gate ${e.id} refuses provider ${d}`);let l=n.provider_capabilities?.[d];if(!l)throw new Le(`assurance provider ${d} has no declared capabilities`);if(c[l.cost_class]>c[s.max_cost_class])throw new Le(`assurance gate ${e.id} refuses ${l.cost_class}-cost provider ${d} at trigger ${r}`);if(l.network&&!s.allow_network)throw new Le(`assurance gate ${e.id} refuses network provider ${d} at trigger ${r}`)}}async function kg(e,t,n,r,i){try{return await Wc(n,r,i)}catch(o){if(o instanceof ut){let s=o.check?` check ${o.check}`:"",a=o.measurement_id??n.id,c=new Le(`assurance gate ${e} assertion ${t} measurement ${a} source ${o.source_kind}${s} field ${o.field} could not resolve: ${o.message}`,{gate_id:e,assertion_id:t,measurement_id:a,source_kind:o.source_kind,field:o.field,...o.check?{check:o.check}:{}});throw c.cause=o,c}throw o}}async function Dg(e,t,n,r){Kn(t);let i=t.gates.find(c=>c.id===e);if(!i)throw new Le(`assurance gate ${e} not found`);if(!i.triggers.includes(r.trigger))throw new Le(`assurance gate ${e} does not declare trigger ${r.trigger}`);_C(i,t,n,r.trigger);let o=await Ig(i.assertion_ids,Eg,async c=>{let d=t.assertions.find(f=>f.id===c),l=t.measurements.find(f=>f.id===d.measurement_id),u=n;if(d.scope.kind==="active"){let f=new Set(n.terminal_statuses??["closed","canceled"]);u={...n,items:n.items.filter(g=>!f.has(g.status))}}else if(d.scope.kind==="filter"){let f=d.scope.measurement_id,g=t.measurements.find(v=>v.id===f),y=await kg(i.id,d.id,g,n,t.measurements),w=new Set(y.contributors);u={...n,items:n.items.filter(v=>w.has(v.id))}}let _=n.items.find(f=>f.id===d.owner_item_id),h=_!==void 0&&new Set(n.terminal_statuses??["closed","canceled"]).has(_.status);return pC(d,await kg(i.id,d.id,l,u,t.measurements),{owner_terminal:h})}),s=o.some(c=>c.verdict==="fail"&&c.enforcement==="block"),a=o.some(c=>c.verdict==="fail"&&c.enforcement==="warn");return{gate_id:i.id,tree_id:n.tree_id,trigger:r.trigger,dry_run:r.dry_run===!0,evaluated_at:new Date().toISOString(),verdict:s?"block":a?"warn":"pass",exit_code:s?1:0,assertions:o,assertions_total:o.length,row_contract:{row_keys:["assertions"],jq_selector:".assertions[]"},cost:Rg(o.map(c=>c.cost),Math.max(0,...o.map(c=>c.cost.duration_ms)))}}function No(e){return qT.join(e,"assurance.json")}async function $g(e){let t=await Q(No(e));return t===null?Kr():Mo(t)}function Mo(e){try{return Kn(JSON.parse(e))}catch(t){throw new p("The assurance registry is invalid. Repair or restore .agents/pm/assurance.json and retry.",m.GENERIC_FAILURE,{code:"assurance_registry_invalid",reason:String(t),nextSteps:["Restore a valid assurance.json from version control or repair its declaration references.","Run pm assurance list measurement after the repair."]})}}function Po(e,t){return t==="measurement"?e.measurements:t==="assertion"?e.assertions:e.gates}function fC(e,t){e==="measurement"?Gc(t):e==="assertion"?qc(t):Ag(t)}async function Wr(e,t){let n=structuredClone(Po(await $g(e),t));return{items:n,count:n.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function Ng(e,t,n){let r=Po(await $g(e),t).find(i=>i.id===n);if(!r)throw new Le(`assurance ${t} ${n} not found`);return structuredClone(r)}async function Fo(e,t,n,r={}){fC(t,n);let i=await x(e),o=U(r.author,i.author_default),s=await In({pmRoot:e,filePath:No(e),op:`assurance:${t}:put`,author:o,message:r.message,lockTtlSeconds:Do,lockWaitMs:$o,mutate:a=>{let c=a===null?Kr():Mo(a),d=Po(c,t),l=d.findIndex(_=>_.id===n.id),u=l<0?"created":"updated";if(t==="assertion"&&l>=0&&VT(d[l],n)){let _=n.authorization_decision;if(!_||!r.authorized_decision_ids?.includes(_))throw new D(`loosening assertion ${n.id} requires a verified authorization_decision`)}return l<0?d.push(structuredClone(n)):d[l]=structuredClone(n),Kn(c),{raw:`${JSON.stringify(c,null,2)}
|
|
3
|
+
`,result:{changed:!0,action:u,kind:t,id:n.id}}}});return{...s.result,changed:s.changed}}async function zc(e,t,n={}){let r=Kr();r.measurements=structuredClone(t.measurements),r.assertions=structuredClone(t.assertions),r.gates=structuredClone(t.gates),Kn(r);let i=await x(e),o=U(n.author,i.author_default),s=await In({pmRoot:e,filePath:No(e),op:"assurance:bundle:apply",author:o,message:n.message,lockTtlSeconds:Do,lockWaitMs:$o,mutate:a=>{let c=a===null?Kr():Mo(a),d=[],l=[],u=(_,h,f)=>{for(let g of h){let y=_.find(w=>w.id===g.id);if(!y){_.push(structuredClone(g)),d.push(`${f}:${g.id}`);continue}if(Z(y)!==Z(g))throw new D(`assurance bundle refuses to replace divergent ${f} ${g.id}`);l.push(`${f}:${g.id}`)}};return u(c.measurements,r.measurements,"measurement"),u(c.assertions,r.assertions,"assertion"),u(c.gates,r.gates,"gate"),Kn(c),{raw:`${JSON.stringify(c,null,2)}
|
|
4
|
+
`,result:{changed:d.length>0,created_ids:d,unchanged_ids:l}}}});return{...s.result,changed:s.changed}}async function Mg(e,t,n,r={}){let i=await x(e),o=U(r.author,i.author_default),s=await In({pmRoot:e,filePath:No(e),op:`assurance:${t}:remove`,author:o,message:r.message,lockTtlSeconds:Do,lockWaitMs:$o,mutate:a=>{let c=a===null?Kr():Mo(a);if(t==="measurement"){let u=xg(c).get(n);if(u&&u.length>0)throw new D(`assurance measurement ${n} is referenced by ${u.join(", ")}`)}if(t==="assertion"&&c.gates.some(u=>u.assertion_ids.includes(n)))throw new D(`assurance assertion ${n} is referenced by gate`);let d=Po(c,t),l=d.findIndex(u=>u.id===n);if(l<0)throw new D(`assurance ${t} ${n} not found`);return d.splice(l,1),Kn(c),{raw:`${JSON.stringify(c,null,2)}
|
|
5
|
+
`,result:{changed:!0,action:"removed",kind:t,id:n}}}});return{...s.result,changed:s.changed}}async function Pg(e,t,n={}){if(t.dry_run)throw new TypeError("dry-run assurance verdicts are not persisted");let r=await x(e);await Rn({pmRoot:e,op:"assurance:gate:verdict",author:U(n.author,r.author_default),context:{assurance_verdict:t},message:n.message??`Assurance gate ${t.gate_id} returned ${t.verdict}`,lockTtlSeconds:Do,lockWaitMs:$o})}async function Fg(e,t={}){let n=t.limit??zT;if(!Number.isInteger(n)||n<1||n>qn)throw new TypeError(`assurance verdict limit must be an integer from 1 through ${qn}`);return(await Jt(Er(e),Xt)).reverse().filter(r=>r.op==="assurance:gate:verdict").map(r=>r.context?.assurance_verdict).filter(r=>typeof r=="object"&&r!==null&&"gate_id"in r).filter(r=>t.gate_id===void 0||r.gate_id===t.gate_id).slice(0,n)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="78b20f7a-4ae7-5811-9ab7-049a07d844e5")}catch{}})();var hC=fc("list").properties.outputSession,gC={outputInclude:{type:"string",minLength:1,description:"Comma-separated fields or sections retained by any built-in read action."},outputLimit:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}],description:"Universal read row ceiling, or unbounded to disable the shared ceiling."},outputBudget:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}],description:"Universal estimated-token ceiling, or unbounded to return the complete read result."},outputFormat:{type:"string",enum:["json","toon"],description:"Universal read-result encoding selector."},outputSession:{...hC},outputCursor:{type:"string",minLength:1,description:"Opaque continuation cursor returned after budget compaction of a declared row collection."}},jg={definition:{anyOf:[{type:"object"},{type:"string"}],description:"Policy declaration for policy-put, or proposed metadata for policy-check; structured JSON or JSON text."},policy:{type:"string",description:"Approval policy id for policy-approve."},message:{type:"string",description:"History explanation for policy mutations and approvals."},dryRun:{type:"boolean",description:"Preview registry changes without writing; policy-approve rejects previews."}},Ug={type:"object",properties:{cwd:{type:"string",description:"Workspace directory to run the native pm operation in. Defaults to the MCP server process cwd."},path:{type:"string",description:"Optional pm data root, equivalent to PM_PATH/global --path. Leave unset for real repository tracking."},author:{type:"string",description:"Optional mutation author override. Otherwise pm uses PM_AUTHOR, project settings, or detected harness identity."},tokenAccounting:{type:"boolean",description:"Attach the same bounded per-section token-cost receipt emitted by CLI --token-accounting."}},additionalProperties:!0},_e={type:"string",description:"pm item id, for example pm-abc1."},yC=`Operation name (one of): ${Ia.join(", ")}. Package-owned actions are available dynamically when their provider package is installed.`,wC={status:{type:"string",description:"Alias for options.status."},type:{type:"string",description:"Alias for options.type."},tag:{type:"string",description:"Alias for options.tag."},priority:{type:"string",description:"Alias for options.priority."},limit:{type:["string","number"],description:"Alias for options.limit."},offset:{type:["string","number"],description:"Alias for options.offset."}},vC={mode:{type:"string",description:"Alias for options.mode."},status:{type:"string",description:"Alias for options.status."},type:{type:"string",description:"Alias for options.type."},tag:{type:"string",description:"Alias for options.tag."},priority:{type:"string",description:"Alias for options.priority."},limit:{type:["string","number"],description:"Alias for options.limit."}};function z(e,t=[]){return{...Ug,properties:{...Ug.properties,...e},required:t}}var bC=[{name:"pm_run",description:"Run any supported pm operation natively through the pm library. Use this for commands not covered by narrower pm_* tools.",inputSchema:z({action:{type:"string",enum:[...Ia],description:yC},id:_e,query:{type:"string",description:"Search query for action=search."},reason:{type:"string",description:"Close reason for action=close."},force:{type:"boolean",description:"Force ownership/terminal-state override when supported."},subcommand:{type:"string",description:"Subcommand selector for actions that take one (for example telemetry, or schema \u2014 prefer the dedicated pm_schema tool for schema operations)."},options:{type:"object",description:"Underlying pm command options using camelCase keys."},fullChangedFields:{type:"boolean",description:"For mutation actions, return the full changed_fields array instead of the default changed_field_count."},idOnly:{type:"boolean",description:"For single-item mutation actions, return only id and status."},...gC},["action"])},{name:"pm_discover",description:"Discover the smallest relevant authorized pm tool catalog under an explicit token budget. Ranking is deterministic and returns public lexical, semantic, graph, permission, freshness, and usage signal explanations. Continue with next_cursor; set includeSchema=true only when complete input schemas are needed.",inputSchema:z({query:{type:"string",maxLength:4096,description:"Free-text capability intent. Empty text lists by stable policy order."},family:{type:"string",enum:["workspace","intake","context","lifecycle","evidence","graph","quality","automation","extensions","internal"],description:"Optional stable capability-family filter."},tier:{type:"string",enum:["core","standard","full"],description:"Maximum command visibility tier included in results."},limit:{type:"integer",minimum:1,maximum:100,description:"Maximum result rows; defaults to 10."},cursor:{type:"string",minLength:1,maxLength:4096,description:"Opaque next_cursor from an equivalent discovery request."},includeSchema:{type:"boolean",description:"Include complete tool input schemas; false by default."},outputBudget:{anyOf:[{type:"integer",minimum:128},{const:"unbounded"}],description:"Estimated-token ceiling; defaults to 1200."}})},{name:"pm_context",description:"Return the agent-oriented project context snapshot. Pass options.depth=brief|standard|deep|full (full = every section with no per-section row cap), options.parent='<id>' to scope the snapshot to one item's subtree (the item plus all descendants), options.fields='id,title,priority' to project focus rows to a field subset for low-token reads, or options.section=['hierarchy','progress',...] to pick sections.",inputSchema:z({options:{type:"object"}})},{name:"pm_next",description:"Recommend the next actionable work item: the single highest-priority READY item (active status, no open blockers, no open children; completed containers surface only when no concrete leaf work is ready) plus the ranked ready and blocked queues. The recommended item carries a rationale and each blocked item lists the open blockers gating it. Pass options.parent='<id>' to scope to one subtree, options.limit=N to cap ready rows, options.readyOnly=true to omit the blocked list, or filters (options.type/tag/priority/assignee/sprint/release). The most token-efficient 'what should I do now?' read for agents.",inputSchema:z({options:{type:"object"}})},{name:"pm_search",description:"Search pm items with keyword, semantic, or hybrid search. Defaults to a compact projection for token efficiency. Pass options.mode=keyword|semantic|hybrid (default follows search.default_mode: auto runs hybrid when semantic search is configured and runnable, else keyword; the result reports mode_source), options.limit=N to cap hits, options.status='all' for no lifecycle restriction, options.fields='id,title,score' for a custom projection, or options.full=true for full item bodies (can be large). The result echoes the applied filters and projection mode in query_summary.",inputSchema:z({query:{type:"string"},options:{type:"object"},...vC},["query"])},{name:"pm_list",description:"List pm items with status/type/tag/priority filters. Defaults to compact projection for token efficiency. options.status accepts CSV (all,open,in_progress). Pass options.compact=false or options.includeBody=true for full bodies/comments. Pass options.brief=true for ultra-terse (id/status/type/title only). Pass options.fields='id,title,priority' for custom projection. Pass options.limit=N to cap row count. The result echoes the applied filters and projection mode in query_summary.",inputSchema:z({options:{type:"object"},...wC})},{name:"pm_get",description:"Read one pm item with shared SDK projections. Pass options.depth='brief' or options.fields='id,title,status' for low-token inspection, options.fields='id,schedule.start_at' for schedule context, or options.at='7' / an ISO timestamp for a verified mutation-free historical read. Parent results include bounded child counts, samples, and continuation metadata.",inputSchema:z({id:_e,options:{type:"object",description:"Get options such as depth=brief|standard|deep|full, fields=id,title,status, or at=<version|ISO timestamp>."}},["id"])},{name:"pm_events",description:"Read a bounded, cursor-resumable page of committed mutation events across item history streams. Batch cursors are the token-efficient default; pass cursorMode=row for per-event checkpoints.",inputSchema:z({verify:{type:"boolean",description:"Verify complete selected authoritative history chains."},since:{type:"string",description:"Durable event cursor or ISO timestamp lower bound."},type:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},author:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},item:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},limit:{type:"integer",minimum:0,maximum:1e3},full:{type:"boolean"},cursorMode:{type:"string",enum:["batch","row"],description:"Cursor framing: batch returns one terminal next_cursor (default); row also adds a cursor to every event."}})},{name:"pm_create",description:"Create a pm item natively and write pm history. Output is compact by default (changed_fields replaced with changed_field_count for token efficiency); pass fullChangedFields=true for the full changed_fields array.",inputSchema:z({fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},allowMissingParent:{type:"boolean",description:"Allow unresolved parent references and emit a validation warning."},allowDuplicate:{type:"boolean",description:"Explicitly create when strict similarity governance finds likely duplicates."},options:{type:"object",description:"Create options. title and description are required."}},["options"])},{name:"pm_mutate",description:"Apply an ordered create/update/close/release batch atomically through the public pm SDK. Create rows may declare ref and omit id; @ref forward references resolve deterministically from the stable transactionId, which is derived from the batch when omitted. Bulk creation: rows shaped as {item:{title,type,...}} are create documents using pm create field names; upsertKey updates the existing item whose field matches instead of creating a duplicate. Set dryRun=true to validate and preview without writes.",inputSchema:z({transactionId:{type:"string",description:"Stable idempotency key for this atomic mutation batch; derived from the batch content when omitted."},mutations:{type:"array",minItems:1,description:"Ordered rows shaped as {op:create|update|close|release,id?,ref?,options?,reason?} or create documents {ref?,item:{...}}.",items:{type:"object",properties:{op:{type:"string",enum:["create","update","close","release"],description:"Operation; omitted rows carrying item are creates."},id:_e,ref:{type:"string",description:"Batch-local create alias; its deterministic id can be referenced as @alias by any row."},reason:{type:"string"},options:{type:"object"},item:{type:"object",description:"Create document using pm create field names (title, type, description, body, tags, parent, custom fields)."},unique:{type:"object",description:"Create-only guard {key,value} re-checked under the writer lock; keyed upsert sets it on rows that matched nothing at planning time."},match:{type:"object",description:"Update-only guard {key,value} re-read under the writer lock; keyed upsert sets it on rows it converted into updates of a matched item."}},additionalProperties:!1}},upsertKey:{type:"string",description:"Item field whose value identifies an existing item to update instead of creating a duplicate."},dryRun:{type:"boolean",description:"Validate and preview without writing."},createCompensation:{type:"string",enum:["close","delete"],description:"How a failed batch compensates created items; defaults to close."},lockTtlSeconds:{type:"number"},lockWaitMs:{type:"number"}},["mutations"])},{name:"pm_copy",description:"Copy an existing pm item into a new id while resetting lifecycle fields. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:z({id:_e,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object",description:"Copy options such as title override, author, and message."}},["id"])},{name:"pm_focus",description:"Set, clear, or show the session focused item. When focused, pm_create defaults its parent to the focused item (an explicit parent still overrides). Pass id to focus an item, options.clear=true to clear, or neither to show current focus.",inputSchema:z({id:_e,clear:{type:"boolean",description:"Clear the focused item (cannot be combined with id)."},options:{type:"object",description:"Focus options such as clear (boolean)."}},[])},{name:"pm_update",description:"Update pm item metadata/body/dependencies/log seeds natively. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields delta.",inputSchema:z({id:_e,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object"}},["id","options"])},{name:"pm_append",description:"Append markdown text to a pm item body and write pm history. Useful for seeding evidence/log entries before close. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:z({id:_e,body:{type:"string",description:"Markdown text to append to the item body. Required here or as options.body."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object",description:"Append options such as body, author, and message."}},["id"])},{name:"pm_claim",description:"Claim a pm item.",inputSchema:z({id:_e,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_release",description:"Release a pm item claim.",inputSchema:z({id:_e,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_close",description:"Close a pm item with optional close reason and optional close validation (reason requirement follows governance settings). Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:z({id:_e,reason:{type:"string",description:"Close reason text when provided or required by governance settings."},duplicateOf:{type:"string",description:"Canonical item id when closing this item as a duplicate."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object"}},["id"])},{name:"pm_comments",description:'List, add, edit, or delete comments on a pm item. Use options.add to append, options.edit=<1-based index> with replacement text to fix a comment, or options.delete=<1-based index> to remove one. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. List calls return the newest comments that fit the output budget, with total_count/has_more metadata and a next_cursor that pages back to older comments through outputCursor; without options.limit or outputLimit, outputBudget "unbounded" returns the complete listing at once. Pass options.limit=N for only the newest N comments (next_cursor pages within that window when the budget trims it; has_more reports older comments beyond it without a cursor) or options.limit=0 for summary-only metadata; options.full=true returns the complete history after a write. Rows carry their absolute index; pair edit/delete with options.expectAt to refuse a different entry.',inputSchema:z({id:_e,options:{type:"object"}},["id"])},{name:"pm_files",description:"List, add, remove, or validate linked files for a pm item.",inputSchema:z({id:_e,options:{type:"object"}},["id"])},{name:"pm_docs",description:"List, add, or remove linked docs for a pm item.",inputSchema:z({id:_e,options:{type:"object"}},["id"])},{name:"pm_notes",description:"List, add, edit, or delete structured notes on a pm item. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. Omit mutation options to list existing notes; rows carry their absolute index, and options.expectAt guards edit/delete.",inputSchema:z({id:_e,options:{type:"object"}},["id"])},{name:"pm_learnings",description:"List, add, edit, or delete learnings on a pm item. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. Omit mutation options to list existing learnings; rows carry their absolute index, and options.expectAt guards edit/delete.",inputSchema:z({id:_e,options:{type:"object"}},["id"])},{name:"pm_deps",description:"Read dependency trees/graphs or one bounded explainable relationship context packet. Use options.format=context with direction, kind, depth, node, edge, token, and cursor bounds; context returns a counts-first summary, per-node roles/reasons, root evidence pointers, and enumerated missing references.",inputSchema:z({id:_e,options:{type:"object"}},["id"])},{name:"pm_graph",description:"Run bounded workspace relationship-graph queries: ancestors/descendants (hierarchy), predecessors/successors (ordering), paths, impact (blast radius), analyze (execution + knowledge analytics), audit (governance findings with change-since-baseline deltas), communities (label-propagation clusters), redundancy (transitively implied edges), dominators (structural bottlenecks), slack (critical-path method float per task), centrality (betweenness/closeness/degree with directed fan-in/out), articulation (cut points and bridges \u2014 single points of failure), plan (dry-run remediation proposals derived from the audit), and index (durable cross-process graph index status/rebuild/clear). Traversals, paths, impact, and dominators require id; paths also requires target. Options support kind, maxDepth, limit, after, direction, maxPaths, sample, exemptIsolate, exemptIsolateType, saveBaseline (audit), rebuild/clear (index), and counts-first summary.",inputSchema:z({subcommand:{type:"string",enum:[...Wu]},id:_e,target:_e,options:{type:"object"}},["subcommand"])},{name:"pm_test",description:"List, add, remove, or run linked tests for a pm item.",inputSchema:z({id:_e,options:{type:"object"}},["id"])},{name:"pm_validate",description:"Run pm validation checks.",inputSchema:z({options:{type:"object"}})},{name:"pm_health",description:"Run pm health diagnostics. Pass options.brief=true for compact low-token details, options.skipIntegrity=true, options.skipDrift=true, options.skipVectors=true for a fast status-only check, or options.full=true for the complete deep check.",inputSchema:z({options:{type:"object"}})},{name:"pm_contracts",description:"Inspect pm command, flag, schema, and availability contracts.",inputSchema:z({options:{type:"object"}})},{name:"pm_schema",description:"Inspect or modify the workspace item-type/status/field schema (pm schema). subcommand selects the operation; name carries the item type name (show/add-type/remove-type), status id (show-status/add-status/remove-status), or field key (show-field/add-field/remove-field). apply-preset adopts a domain type preset; add-type with infer=true derives types from title-prefix conventions. Policy verbs author declarations, preview changes, set enforcement, and record content-bound approvals. Registry mutations write workspace history; approvals write item history.",inputSchema:z({...jg,subcommand:{type:"string",enum:["list","show","show-status","add-type","remove-type","add-status","remove-status","add-field","remove-field","list-fields","show-field","apply-preset",...Pu],description:"Schema subcommand to run."},name:{type:"string",description:"Item type name, status id, field key, policy id, or item id for the selected schema verb; policy-mode requires advise|refuse."},description:{type:"string",description:"Custom item type, status, or field description for add-type/add-status/add-field."},defaultStatus:{type:"string",description:"Default status for add-type."},folder:{type:"string",description:"Storage folder for add-type."},alias:{type:"array",items:{type:"string"},description:"Aliases for add-type/add-status, or extra CLI flag aliases for add-field."},role:{type:"array",items:{type:"string",enum:[...La]},description:`Lifecycle roles for add-status: ${La.join(", ")}.`},order:{type:"number",description:"Display/sort order for add-status."},fieldType:{type:"string",enum:["string","number","boolean","string_array"],description:"Value type for a custom field (add-field)."},commands:{type:"array",items:{type:"string"},description:"Commands a custom field is wired onto (add-field): create, update, update_many, list, search, calendar, context."},cliFlag:{type:"string",description:"Override the auto-derived CLI flag for a custom field (add-field)."},required:{type:"boolean",description:"Mark a custom field as always required (add-field)."},requiredOnCreate:{type:"boolean",description:"Mark a custom field as required at create time (add-field)."},allowUnset:{type:"boolean",description:"Whether a custom field may be cleared via --unset (add-field); defaults to true."},requiredTypes:{type:"array",items:{type:"string"},description:"Restrict a custom field's requirement to specific item types (add-field)."},typePreset:{type:"string",enum:["agile","ops","research"],description:"Domain type preset to adopt (apply-preset)."},infer:{type:"boolean",description:"Infer item types from title-prefix conventions (add-type); previews unless apply is true."},minCount:{type:"number",description:"Minimum items sharing a prefix for add-type inference (default 10)."},apply:{type:"boolean",description:"Register inferred types (add-type infer); without it the call previews only."},force:{type:"boolean",description:"Override removal guardrails for destructive schema changes when supported."},options:{type:"object",description:"Additional schema options using camelCase keys.",properties:jg}},["subcommand"])},{name:"pm_profile",description:"List, show, apply, or lint project profiles (pm profile) \u2014 archetype bundles that stage item types, statuses, fields, per-type workflows, config knobs, create templates, and recommended packages. subcommand selects the operation; name carries the profile name (agile, ops, research) for show/apply/lint. apply stages every dimension idempotently; dryRun previews the diff without writing; lint reports author-time consistency findings (graded error/warning) without touching the tracker. Profile staging writes workspace config/schema files, not item history.",inputSchema:z({subcommand:{type:"string",enum:["list","show","apply","lint"],description:"Profile subcommand to run."},name:{type:"string",description:"Profile name for show/apply/lint. Required for those subcommands. Built-ins are agile, ops, and research; an active extension can contribute additional archetype names that resolve here too."},dryRun:{type:"boolean",description:"Preview the apply diff without writing any files (apply)."},author:{type:"string",description:"Mutation author for apply."},force:{type:"boolean",description:"Force ownership/lock override for apply."},options:{type:"object",description:"Additional profile options using camelCase keys."}},["subcommand"])},{name:"pm_config",description:"Read or write pm workspace configuration (pm config). configAction selects get/set/list/export; key/value address a single setting for get/set. scope chooses the project (default) or global settings file.",inputSchema:z({configAction:{type:"string",enum:["get","set","list","export"],description:"Config operation to perform. get/set require key; list/export dump the resolved settings surface."},key:{type:"string",description:"Settings key for get/set, for example governance-require-close-reason, telemetry-tracking, or a nested leaf such as search_provider (dash and underscore variants accepted; configAction=get without a key lists supported keys in the error)."},value:{type:"string",description:"New value for configAction=set."},scope:{type:"string",enum:["project","global"],description:"Settings scope to read or write. Defaults to project."},options:{type:"object",description:"Additional config options such as criterion, clearCriteria, format, or policy."}},["configAction"])},{name:"pm_plan",description:"Run agent-optimized Plan workflows. options.subcommand selects: create|show|add-step|update-step|complete-step|block-step|reorder-step|remove-step|link|unlink|decision|discovery|validation|resume|approve|materialize. Provide id for all non-create subcommands; provide stepRef for step lifecycle subcommands. Plans store agent-readable steps with dependencies, decisions, discoveries, validation, and resume context.",inputSchema:z({id:{type:"string",description:"Plan id (required for all subcommands except create)."},stepRef:{type:"string",description:"Step id or order for step lifecycle subcommands."},options:{type:"object",description:"Plan options including subcommand, stepRef, stepStatus, link, depth, etc."}})}],kC={pm_append:"append",pm_claim:"claim",pm_close:"close",pm_comments:"comments",pm_config:"config",pm_context:"context",pm_contracts:"contracts",pm_copy:"copy",pm_create:"create",pm_deps:"deps",pm_docs:"docs",pm_events:"events",pm_files:"files",pm_focus:"focus",pm_get:"get",pm_graph:"graph",pm_health:"health",pm_learnings:"learnings",pm_list:"list",pm_next:"next",pm_notes:"notes",pm_plan:"plan",pm_profile:"profile",pm_release:"release",pm_schema:"schema",pm_search:"search",pm_test:"test",pm_update:"update",pm_validate:"validate"},SC=bC.map(e=>{let t=kC[e.name];if(!t)return e;let n=e.inputSchema.properties,r=e.inputSchema.required.map(String);return{...e,inputSchema:fc(t,{properties:n,required:r})}});function Gg(){return SC.map(e=>{let t=e.inputSchema.required,n=Array.isArray(t)?t.map(r=>String(r)).sort((r,i)=>r.localeCompare(i)):[];return{name:e.name,description:e.description,required:n,input_schema:e.inputSchema}}).sort((e,t)=>e.name.localeCompare(t.name))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="208db30b-9299-52bf-902b-14c6a63b08f5")}catch{}})();var qg=new Map([["activity",["--limit","--after","--full"]],["claim",["--if-available","--next","--type","--priority","--token-budget","--explain-ranking"]],["close",["--reason","--validate-close","--resolution","--expected-result","--actual-result","--message"]],["context",["--limit","--after","--depth","--section","--token-budget","--explain-ranking"]],["contracts",["--command","--flags-only","--summary","--runtime-only","--availability-only","--full"]],["create",["--title","--type","--status","--priority","--dep","--comment"]],["get",["--full","--depth","--fields","--tree","--tree-depth","--format"]],["health",["--check-only","--summary","--brief","--check-telemetry","--strict-exit","--full"]],["list",["--status","--type","--limit","--after","--brief","--fields"]],["next",["--limit","--blocked-limit","--ready-only","--token-budget","--explain-ranking","--format"]],["search",["--mode","--status","--type","--limit","--after","--fields"]],["update",["--status","--message","--dep","--comment","--file","--test"]],["validate",["--check-resolution","--check-history-drift","--check-storage-integrity","--counts","--strict-exit","--fix-hints"]]]),EC=["--limit","--after","--offset","--token-budget","--brief","--summary","--compact","--fields","--full","--format","--since","--until"],Qg=new Set(["list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"]),Uo=new Set(["calendar","guide","reindex","completion","test-runs-list","test-runs-status","test-runs-logs","test-runs-stop","test-runs-resume","templates-list","templates-save","templates-show"]),on=new Set(["meet","event","remind","search-advanced","dedupe-audit","dedupe-merge","comments-audit","cal","calendar","completion","completion-statuses","completion-tags","completion-types","guide","reindex","normalize","templates","templates list","templates save","templates show","test-runs","test-runs list","test-runs status","test-runs logs","test-runs stop","test-runs resume"]),Zg=new Map([["meet","calendar"],["event","calendar"],["remind","calendar"],["search-advanced","search-advanced"],["dedupe-audit","governance-audit"],["dedupe-merge","governance-audit"],["comments-audit","governance-audit"],["cal","calendar"],["calendar","calendar"],["completion","guide-shell"],["completion-statuses","guide-shell"],["completion-tags","guide-shell"],["completion-types","guide-shell"],["guide","guide-shell"],["reindex","search-advanced"],["normalize","governance-audit"],["templates","templates"],["templates list","templates"],["templates save","templates"],["templates show","templates"],["test-runs","linked-test-adapters"],["test-runs list","linked-test-adapters"],["test-runs status","linked-test-adapters"],["test-runs logs","linked-test-adapters"],["test-runs stop","linked-test-adapters"],["test-runs resume","linked-test-adapters"]]),ey=new Map([["calendar","calendar|cal"],["guide","guide"],["reindex","reindex"],["completion","completion"],["test-runs-list","test-runs|test-runs list"],["test-runs-status","test-runs status"],["test-runs-logs","test-runs logs"],["test-runs-stop","test-runs stop"],["test-runs-resume","test-runs resume"],["templates-list","templates|templates list"],["templates-save","templates save"],["templates-show","templates show"]]),ty=new Map([...ey.entries()].flatMap(([e,t])=>vt(t).map(n=>[n,e]))),ny=[{canonical:"context",aliases:["ctx"]},{canonical:"package",aliases:["extension","packages"]}],Vc=new Map(ny.flatMap(e=>e.aliases.map(t=>[t,e.canonical]))),TC=10,CC=20,Kg=new Map([["activity","Read activity."],["aggregate","Group counts."],["append","Append body."],["assurance","Evaluate assurance."],["assurance derive","Derive checks."],["assurance risk","Select checks for changes."],["assurance lineages","Measure recurrence coverage."],["beads","Manage Beads interoperability."],["cal","Manage calendar integration."],["calendar","Manage calendar integration."],["changelog","Generate changelog output."],["claim","Claim work."],["close","Close work."],["close-many","Close matching work."],["close-task","Close task work."],["command-kit","Inspect command authoring primitives."],["comments","Manage comments."],["comments-audit","Audit comment governance."],["completion","Generate shell completions."],["config","Manage settings."],["context","Build context."],["contracts","Inspect contracts."],["copy","Copy work."],["create","Create work."],["dedupe-audit","Audit duplicate work."],["dedupe-merge","Merge duplicate work."],["delete","Delete work."],["deps","Manage deps."],["duplicates","Find duplicate clusters."],["docs","Link docs."],["eval","Run evaluations."],["event","Manage events."],["events","Read events."],["files","Link files."],["focus","Manage focus."],["gc","Clean caches."],["get","Read item."],["graph","Query graph."],["guide","Show user guides."],["health","Check health."],["help","Show help."],["history","Inspect history."],["init","Initialize workspace."],["install","Install packages."],["item","Mutate items."],["learnings","Manage learnings."],["list","List work."],["list-all","List work across every status."],["list-blocked","List blocked work."],["list-canceled","List canceled work."],["list-closed","List closed work."],["list-draft","List draft work."],["list-in-progress","List in-progress work."],["list-open","List open work."],["meet","Record meeting context."],["merge","Manage tracker merges."],["next","Pick next work."],["notes","Manage notes."],["normalize","Normalize tracker data."],["ops","Run operations."],["package","Manage packages."],["packages","Manage packages."],["pause-task","Pause task work."],["plan","Manage plans."],["profile","Manage profiles."],["reindex","Refresh search index."],["release","Release claim."],["remind","Manage reminders."],["restore","Restore history."],["schema","Customize schema."],["search","Search work."],["search-advanced","Run advanced search."],["start-task","Start task work."],["stats","Show stats."],["telemetry","Manage telemetry."],["templates","Manage work templates."],["test","Run linked tests."],["test-all","Run all linked tests."],["test-runs","Inspect background test runs."],["todos","Manage source-code todos."],["twin","Manage repository twins."],["update","Update work."],["update-many","Update matching work."],["upgrade","Upgrade packages."],["validate","Validate data."],["vcs","Inspect version-control context."],["workspace","Manage workspaces."],["history-author-acknowledge","Acknowledge reviewed history authors."],["history-compact","Compact history."],["history-attest","Export or verify detached history proof."],["history-redact","Redact sensitive history values."],["history-repair","Repair history integrity."]]),ry=[["init",L_],["install",$_],["uninstall",N_],["explore",M_],["manage",q_],["describe",P_],["reload",K_],["doctor",W_],["catalog",z_],["adopt",B_],["adopt-all",F_],["activate",j_],["deactivate",U_],["migrate",G_]],AC=[...ry.map(([e,t])=>e==="init"?[e,D_]:[e,t]),["upgrade",dc]],xC=[...ry.map(([e,t])=>[`extension ${e}`,t]),...AC.flatMap(([e,t])=>[[`package ${e}`,t],[`packages ${e}`,t]]),["init",R_],["config",I_],["extension",O_],["package",cc],["packages",cc],["install",H_],["create",hf],["item mutate",gf],["item complete",yf],["item reopen",wf],["copy",vf],["focus",bf],["update",kf],["update-many",Sf],["upgrade",dc],["calendar",lc],["cal",lc],["context",uc],["ctx",uc],["get",Cf],["search",Lf],["eval",If],["events",Tf],["workspace",Lt],["workspace position",[]],["workspace snapshot",Lt],["workspace snapshot create",Lt],["workspace snapshot list",Lt],["workspace snapshot inspect",Lt],["workspace snapshot restore",Lt],["workspace snapshot delete",Lt],["next",Of],["aggregate",p_],["deps",xf],["graph",Rf],["guide",Af],["reindex",V_],["history",w_],["history-compact",E_],["history-attest",T_],["history-redact",b_],["history-repair",k_],["history-author-acknowledge",S_],["merge",v_],["schema",C_],["profile",A_],["plan",x_],["restore",Z_],["delete",ef],["close",Y_],["close-many",J_],["append",X_],["claim",Q_],["release",tf],["start-task",nf],["pause-task",rf],["close-task",of],["comments",__],["notes",f_],["learnings",h_],["files",g_],["docs",y_],["test",sf],["test-runs-worker",[]],["test-all",af],["telemetry",cf],["test-runs",df],["gc",lf],["stats",uf],["ops",[]],["duplicates",mf],["validate",_f],["health",pf],["assurance",ff],...Nf,["contracts",Df],["completion",$f],["activity",Ef],...[...Qg].map(e=>[e,m_])],zr=new Map(xC);for(let{alias:e,canonical:t}of ot){let n=zr.get(e);n!==void 0&&zr.set(t,n)}function RC(e){return ty.get(e)||(e.startsWith("test-runs ")?`test-runs-${e.slice(10)}`:e.startsWith("templates ")?`templates-${e.slice(10)}`:e)}function Wg(e){let t=ot.find(n=>n.alias===e);return t?`${t.canonical}|${t.alias}`:st.includes(e)?Se(e):e.startsWith("extension-")?Se(`extension ${e.slice(10)}`):e.startsWith("package-")?Se(`package ${e.slice(8)}`):e.startsWith("item-")?Se(`item ${e.slice(5)}`):e.startsWith("test-runs-")?Se(`test-runs ${e.slice(10)}`):e.startsWith("templates-")?Se(`templates ${e.slice(10)}`):Uo.has(e)?ey.get(e)??Se(e):null}function IC(e,t){let n=K(t);return n!==t||ot.some(r=>r.alias===t)?e.action===n:e.command_path===null?!1:vt(e.command_path).some(r=>r===t?!0:r.startsWith(`${t} `)||t.startsWith(`${r} `))}function vt(e){return e.split("|").map(t=>Se(t)).filter(t=>t.length>0)}function OC(e,t){let n=new Set(t),r=new Set;for(let i of e)if(i.command_path)for(let o of vt(i.command_path)){let s=o.split(" ").filter(a=>a.length>0);if(s.length!==0)for(let a=s.length;a>0;a-=1){let c=s.slice(0,a).join(" ");if(n.has(c)){r.add(c);break}}}return[...r].sort((i,o)=>i.localeCompare(o))}function jo(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function Br(e){let t=e.oneOf;return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null):[]}function LC(e,t){if(!t)return{...e};let n=Br(e).filter(r=>{let i=r.properties;if(typeof i!="object"||i===null)return!1;let o=i.action;return typeof o!="object"||o===null?!1:o.const===t});return{...e,oneOf:n}}function Bc(e,t){let n=Br(e).filter(r=>{let i=r.properties;if(typeof i!="object"||i===null)return!1;let o=i.action;if(typeof o!="object"||o===null)return!1;let s=o.const;return typeof s=="string"&&t.has(s)});return{...e,oneOf:n}}function Se(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function iy(e){return e.replace(/\s+/g,"-")}function Nt(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function zg(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let i=Nt(r);!i||n.has(i)||(n.add(i),t.push(i))}return t}function Hc(e,t,n){n&&(e[t]=!0)}function Bg(e,t){if(e==null)return null;if(typeof e!="string")throw new TypeError("Expected string for extension flag name.");let n=e.trim();return n.length===0?null:t==="long"?n.startsWith("--")&&n.length>2?Ht(n):null:n.startsWith("-")&&!n.startsWith("--")&&n.length>1?n:null}function DC(e){let t=Bg(e.long,"long"),n=Bg(e.short,"short"),r=t??n;if(!r)return null;let i={flag:r};n&&t&&(i.short=n),Hc(i,"required",e.required===!0),Hc(i,"repeatable",e.repeatable===!0),Hc(i,"list",e.list===!0),e.default!==void 0&&(i.default=e.default);let o=Nt(e.description);o&&(i.description=o);let s=An(e);i.value_arity=s.value_arity;let a=Nt(e.value_name)??s.value_name;a&&(i.value_name=a);let c=s.value_type??(s.value_name?"string":null);return c&&(i.value_type=c),i}function oy(e){let t=new Map;for(let r of e){let i=Se(r.target_command);if(i.length===0)continue;let o=t.get(i)??{flags:[],sources:[],dedupe:new Set,sourceDedupe:new Set},s=`${r.layer}:${r.name}`;o.sourceDedupe.has(s)||(o.sourceDedupe.add(s),o.sources.push({layer:r.layer,name:r.name}));for(let a of r.flags){let c=DC(a);if(!c)continue;let d=`${c.flag}|${c.short??""}`;o.dedupe.has(d)||(o.dedupe.add(d),o.flags.push(c))}t.set(i,o)}let n=new Map;for(let[r,i]of t.entries())n.set(r,{flags:i.flags,sources:i.sources.sort((o,s)=>{let a=o.layer.localeCompare(s.layer);return a!==0?a:(o.name??"").localeCompare(s.name??"")})});return n}function $C(e,t){return e.read_output===void 0?{flags:t}:{read_output:e.read_output,flags:[...t,...ac.filter(({flag:n})=>n.startsWith("--output-"))]}}function NC(e){let t=oy(e.flagRegistrations),n=new Map;for(let o of e.commandDefinitions){let s=Se(o.command);if(s.length===0)continue;let a=Nt(o.action)??iy(s),c=Array.isArray(o.arguments)?o.arguments.map(d=>{let l=Nt(d.name);return l?{name:l,required:d.required===!0,variadic:d.variadic===!0,description:Nt(d.description)}:null}).filter(d=>d!==null):[];n.set(s,{...o.tier===void 0?{}:{tier:o.tier},...$C(o,t.get(s)?.flags??[]),command:s,action:a,source:{layer:o.layer,name:o.name},description:Nt(o.description),intent:Nt(o.intent),arguments:c,examples:zg(o.examples),failure_hints:zg(o.failure_hints)})}let r=new Set;for(let o of e.handlers)r.add(Se(o));for(let o of n.keys())r.add(o);for(let o of t.keys())r.add(o);let i=[];for(let o of[...r].sort((s,a)=>s.localeCompare(a))){let s=n.get(o);i.push(MC(o,s,t.get(o)?.flags??[]))}return i}function MC(e,t,n){return t?{...t,flags:t.flags.length>0?t.flags:n}:{command:e,action:iy(e),source:null,description:null,intent:null,arguments:[],flags:n,examples:[],failure_hints:[]}}function PC(e){let t=e.flag.startsWith("--")?e.flag:void 0,n=Dc({long:t,short:t===void 0?e.flag:void 0});return n!==null&&/[a-z0-9]/iu.test(n)?n:null}function FC(e,t){return e.variadic?{type:"array",items:{type:"string"},description:e.description??`Variadic argument '${e.name}' for extension action '${t}'.`}:{type:"string",description:e.description??`Argument '${e.name}' for extension action '${t}'.`}}function jC(e,t){let n=e.value_type??"boolean",r=n==="boolean"?"boolean":n==="number"?["number","string"]:"string",i=e.repeatable===!0||e.list===!0;return{type:i?"array":r,...i?{items:{type:r}}:{},...e.default!==void 0?{default:e.default}:{},description:e.description??`Extension option '${e.flag}' for action '${t}'.`}}function UC(e){let t=e.command.split("|").map(i=>i.trim()).filter(i=>i.length>0),n={action:{type:"string",const:e.action,description:e.intent??e.description??`Invoke extension command '${e.command}'.`}},r=["action"];for(let i of e.arguments)n[i.name]=FC(i,e.action),i.required&&r.push(i.name);for(let i of e.flags){let o=PC(i);!o||n[o]!==void 0||(n[o]=ac.some(s=>s.flag===i.flag&&s.flag.startsWith("--output-"))?Xf[o]:jC(i,e.action),i.required===!0&&r.push(o))}return{type:"object",properties:n,required:r,additionalProperties:!0,"x-extension-source":e.source,"x-extension-command":t[0]??e.command,"x-extension-commands":t}}function GC(e,t){e.description??=t.description,e.value_name??=t.value_name,e.value_type??=t.value_type,t.required===!0&&(e.required=!0),t.repeatable===!0&&(e.repeatable=!0)}function qC(e){let t=new Map;for(let n of e){let r=t.get(n.action);if(!r){t.set(n.action,{...n,flags:[...n.flags],examples:[...n.examples],failure_hints:[...n.failure_hints]});continue}r.command=[...new Set([r.command,n.command])].sort((o,s)=>o.localeCompare(s)).join("|"),r.arguments=r.arguments.length>=n.arguments.length?r.arguments:n.arguments;let i=new Set(r.flags.map(o=>`${o.flag}|${o.short??""}`));for(let o of n.flags){let s=`${o.flag}|${o.short??""}`;if(!i.has(s))i.add(s),r.flags.push(o);else{let a=r.flags.find(c=>`${c.flag}|${c.short??""}`===s);a&&GC(a,o)}}r.examples=[...new Set([...r.examples,...n.examples])],r.failure_hints=[...new Set([...r.failure_hints,...n.failure_hints])]}return[...t.values()].sort((n,r)=>n.action.localeCompare(r.action))}async function KC(e,t=x){let n={mode:qt.extensions.policy.mode,trust_mode:qt.extensions.policy.trust_mode,default_sandbox_profile:qt.extensions.policy.default_sandbox_profile};if(e.noExtensions)return{handlers:new Set,disabledReason:"extensions_disabled",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};let r=R(process.cwd(),e.path);if(!await ie(Re(r)))return{handlers:new Set,disabledReason:null,commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};try{let i=await t(r),o=await no({pmRoot:r,settings:i,cwd:process.cwd(),noExtensions:!1}),s=await ro({...o,loaded:o.loaded});return{handlers:new Set(s.commands.handlers.map(a=>Se(a.command))),disabledReason:null,commandDefinitions:s.registrations.commands,flagRegistrations:s.registrations.flags,registrations:s.registrations,policyState:{mode:o.policy.mode,trust_mode:o.policy.trust_mode,default_sandbox_profile:o.policy.default_sandbox_profile}}}catch{return{handlers:new Set,disabledReason:"extension_runtime_probe_failed",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n}}}function WC(e,t={}){let n=new Map;for(let r of zu){let i=Uo.has(r);if(i&&!t.includePackageOwnedActions)continue;let o=Wg(r);n.set(r,{action:r,provider:i?"extension":"core",requires_extension:i,command_path:o})}if(t.includePackageOwnedActions)for(let r of Uo)n.has(r)||n.set(r,{action:r,provider:"extension",requires_extension:!0,command_path:Wg(r)});for(let r of e)n.has(r.action)||n.set(r.action,{action:r.action,provider:"extension",requires_extension:!0,command_path:ot.find(i=>i.alias===r.command)?.canonical??Se(r.command)});return[...n.values()].sort((r,i)=>(r.action??"").localeCompare(i.action??""))}function zC(e,t){if(e.provider==="core"&&!e.requires_extension)return{action:e.action,invocable:!0,available:!0,requires_extension:!1,provider:"core",disabled_reason:null,command_path:e.command_path,cli_exposed:e.command_path!==null&&(!on.has(e.action)||t.handlers.has(e.action))};let n=e.command_path?vt(e.command_path):[],r=n.some(s=>t.handlers.has(s)||t.handlers.has(K(s))),i=n.map(s=>Zg.get(K(s))).find(s=>typeof s=="string"),o=t.disabledReason===null&&r;return{action:e.action,invocable:o,available:o,requires_extension:!0,provider:"extension",disabled_reason:o?null:t.disabledReason??(i?`optional_package_not_installed:${i}`:"extension_command_not_registered"),command_path:e.command_path,cli_exposed:r,policy_state:{mode:t.policyState.mode,trust_mode:t.policyState.trust_mode,default_sandbox_profile:t.policyState.default_sandbox_profile}}}function sy(e){let t=zr.get(e)??yo,n=Ar(e).find(r=>r.flag==="--output-format"&&r.aliases?.includes("--format"));return n?[...t,n]:t}function BC(e){return on.has(K(e))?!1:zr.has(e)}function HC(e){return Qg.has(e)?"list":e==="cal"?"calendar":e==="ctx"?"context":e==="update-many"?"update_many":e}function Hg(e){let t=e.trim();return t?t.startsWith("--")?t:t.startsWith("-")?null:`--${t}`:null}function VC(e){let t=e.trim();return!t||t.startsWith("--")?null:t.startsWith("-")?t:null}function YC(e){let t=new Map;for(let r of e.definitions){let i=Hg(r.cli_flag);if(!i)continue;let o=r.cli_aliases.map(a=>VC(a)).find(a=>a!==null),s=r.cli_aliases.map(a=>Hg(a)).filter(a=>a!==null&&a!==i);for(let a of r.commands){let c=t.get(a)??{flags:[],seen:new Set},d=o?{flag:i,short:o}:{flag:i},l=`${d.flag}|${d.short??""}`;c.seen.has(l)||(c.seen.add(l),c.flags.push(d));for(let u of s){let _=`${u}|`;c.seen.has(_)||(c.seen.add(_),c.flags.push({flag:u}))}t.set(a,c)}}let n=new Map;for(let[r,i]of t.entries())n.set(r,sc(i.flags));return n}function Vg(e,t){let n=[],r=new Set;for(let i of[...e,...t]){let o=`${i.flag}|${i.short??""}`;r.has(o)||(r.add(o),n.push(i))}return sc(n)}function JC(e){let t=Dc(e.flag.startsWith("--")?{long:e.flag}:{short:e.flag});return{...e,owner:"extension",...t===null?{}:{sdk_option:t}}}function XC(e,t,n,r){let i=(n??[]).map(JC),o=t==="extension"&&(n!==void 0||QC(e,r));return{flags:i,inherited:o?{inherited_flags:u_({readOutput:ZC(e,r)})}:{}}}function ay(e,t){let n=K(e);return t.find(r=>K(r.command)===n)}function QC(e,t){return ay(e,t)!==void 0}function ZC(e,t){return ay(e,t)?.read_output!==void 0}function eA(e,t,n,r,i){let o=new Map(t);for(let{alias:s,canonical:a}of ot){let c=t.get(a)??t.get(s);c&&(o.set(s,c),o.set(a,c))}return e.map(s=>{let a=BC(s),c=a?sy(s):[],d=n.get(HC(s))??[],l=o.get(s),u=Vg(c,d),_=c.length>0&&(l?.flags.length??0)>0?"mixed":a?"core":"extension",h=XC(s,_,l?.flags,i),f=Vg(u,h.flags);return{command:s,flags:f,...h.inherited,...r?{canonical_command:dy(s),visibility:cy(s,i),positionals:c_(s)?.slots??[],flag_invocations:Lh(s,f)}:{},provider:_,extension_sources:l?.sources}}).sort((s,a)=>s.command.localeCompare(a.command))}function tA(e,t=Kt){let n=new Set(e),r=new Map;for(let i of ny){let o=i.aliases.filter(s=>n.has(s));r.set(i.canonical,{canonical:i.canonical,aliases:o,contracts:[]})}for(let i of t){if(!n.has(i.canonical)||i.registration==="commander"&&!n.has(i.alias))continue;let o=r.get(i.canonical)??{canonical:i.canonical,aliases:[],contracts:[]};o.aliases.includes(i.alias)||o.aliases.push(i.alias),o.contracts.push(i),r.set(i.canonical,o)}return[...r.values()].map(({contracts:i,...o})=>i.length===0?o:{...o,contracts:i}).sort((i,o)=>i.canonical.localeCompare(o.canonical))}function nA(){return{create_string_options:Gf,create_repeatable_options:qf,update_string_options:Kf,update_repeatable_options:Wf,list_string_options:Mf,search_string_options:Pf,calendar_string_options:Ff,context_string_options:jf,activity_string_options:Uf}}function Yg(e,t){let n=new Set(["title","type"]);if(t==="strict"){for(let a of e.required_create_fields)n.add(a);for(let a of e.required_create_repeatables)n.add(a)}let r=Cn(e,"create",n),i=[...new Set(r.required)].sort((a,c)=>a.localeCompare(c)),o=[...new Set(i.map(a=>xe("create",a)))].sort((a,c)=>a.localeCompare(c)),s=[...new Set(e.options.filter(a=>a.required===!0).map(a=>a.key))].sort((a,c)=>a.localeCompare(c));return{required_option_keys:i,required_flags:o,required_type_options:s,policy_errors:[...new Set(r.errors)].sort((a,c)=>a.localeCompare(c))}}function rA(e){let t={},n={};for(let r of[...e.types].sort((i,o)=>i.localeCompare(o))){let i=e.by_type[r];t[r]=Yg(i,"strict"),n[r]=Yg(i,"progressive")}return{default_create_mode:"strict",by_create_mode:{strict:{by_type:t},progressive:{by_type:n}}}}function iA(e,t){let n=Br(e);if(n.length===0)return e;let r=!1,i=n.map(o=>{let s=o.properties;if(typeof s!="object"||s===null)return o;let a=s.action;return typeof a!="object"||a===null||a.const!=="create"?o:(r=!0,{...o,"x-create-required-options":t})});return r?{...e,oneOf:i}:e}function oA(e){let t=jo(e.action)!==void 0||jo(e.command)!==void 0,n=e.schemaOnly===!0||e.flagsOnly===!0||e.availabilityOnly===!0,r=e.summary===!0||e.full!==!0&&e.runtimeOnly!==!0&&!t&&!n,i=e.schemaOnly===!0,o=e.flagsOnly===!0,s=e.availabilityOnly===!0,a=e.runtimeOnly===!0,c=e.full===!0,d=jo(e.action),l=jo(e.command),u=!r&&!c&&!i&&!o&&!s&&!d&&!l;return{selectedAction:d,selectedCommand:l,summary:r,schemaOnly:i,flagsOnly:o,availabilityOnly:s,runtimeOnly:a,fullOutput:c,omitUnfilteredSchema:u,omitUnfilteredCommandFlags:u,omitUnfilteredCommanderAliases:u||l!==void 0&&!c}}function sA(e){if([e.summary,e.schemaOnly,e.flagsOnly,e.availabilityOnly].filter(t=>t).length>1)throw new p("Choose only one projection flag: --summary, --schema-only, --flags-only, or --availability-only.",m.USAGE)}async function aA(e,t=x){try{return await t(e)}catch{return structuredClone(qt)}}async function cA(e,t,n){let r=await aA(t),i=await KC(e),o=P(r,i.registrations??N()),s=Vt(r.schema),a=NC(i);return{settings:r,runtimeProbe:i,typeRegistry:o,statusRegistry:W(r.schema),runtimeFieldRegistry:s,runtimeFieldFlagMap:YC(s),createRequiredOptionContracts:rA(o),extensionContracts:a,mergedExtensionContracts:qC(a.filter(c=>Go(n,c.command,a))),extensionFlagMap:oy(i.flagRegistrations)}}function Jg(e){return e.availabilityOnly&&(e.selectedAction!==void 0&&Uo.has(e.selectedAction)||e.selectedCommand!==void 0&&on.has(K(e.selectedCommand)))}function dA(e,t){let n=WC(t,{includePackageOwnedActions:Jg(e)});if(e.selectedAction===void 0&&e.selectedCommand===void 0){let r=new Set(Bu);return n.filter(i=>!r.has(i.action)&&(e.fullOutput||(t.find(o=>o.action===i.action)?.tier??Nc(i.action))!=="internal"))}return Jg(e)&&e.selectedCommand!==void 0&&on.has(K(e.selectedCommand))&&!n.some(r=>r.command_path===e.selectedCommand)&&n.push({action:RC(K(e.selectedCommand)),provider:"extension",requires_extension:!0,command_path:e.selectedCommand}),n}function lA(e,t){let n=new Set(t.map(r=>r.action));if(e.selectedAction&&!n.has(e.selectedAction))throw new p(`Unknown action: "${e.selectedAction}".`,m.USAGE)}function uA(e,t){return[...new Set([...st.filter(n=>!on.has(K(n))),...[...zr.keys()].filter(n=>!on.has(K(n))),...e.flatMap(n=>n.command_path?vt(n.command_path).filter(r=>n.provider==="extension"||!on.has(K(r))||t.some(i=>i.action===n.action)):[]),...t.flatMap(n=>n.command.split("|").flatMap(r=>{let i=ot.find(o=>o.alias===r||o.canonical===r);return i===void 0?[r]:[i.alias,i.canonical]}))])].map(n=>Se(n)).filter(n=>n.length>0).sort((n,r)=>n.localeCompare(r))}function mA(e,t){let n=t.slice(0,TC),r=t.length-n.length,i=r>0?`${n.join(", ")}, and ${r} more`:n.join(", "),o=t.slice(0,CC),s=t.slice(0,5).map(c=>`pm contracts --command "${c}" --flags-only --json`),a=t[0];return new p(`Command "${e}" is a command namespace. Choose a concrete child command: ${i}.`,m.USAGE,{code:"command_namespace",required:"Use a concrete child command path listed under this namespace.",why:"Command groups expose help at the namespace root, but command flag contracts belong to executable child commands.",examples:s,nextSteps:[`Retry with a child command, for example: ${s[0]}`],recovery:{suggested_retry:`pm contracts --command "${a}" --flags-only --json`,fallback_candidates:o.map(c=>({source:"command_namespace",command:`pm contracts --command "${c}" --flags-only --json`,reason:`Child command under ${e}`}))}})}function pA(e,t){return new p(`Unknown command: "${e}". Command "${e}" is provided by the optional "${t}" package. Run "pm package install ${t} --project" and retry.`,m.USAGE,{code:"unknown_command",required:`Install the optional "${t}" package, or choose a command from pm contracts --flags-only --json.`,why:"Command contracts include core commands plus commands registered by active packages and extensions.",examples:[`pm package install ${t} --project`,`pm contracts --command ${e} --flags-only --json`],nextSteps:[`Install the optional package first: pm package install ${t} --project`],recovery:{suggested_retry:`pm package install ${t} --project`}})}function _A(e){return new p(`Unknown command: "${e}".`,m.USAGE,{code:"unknown_command",required:"Use a command path listed by pm contracts --flags-only --json.",why:"Command contracts are generated from the active core, package, and extension command registry.",examples:["pm contracts --flags-only --json","pm --help"],nextSteps:["Verify spelling and active packages/extensions, then rerun with a known command path."],recovery:{suggested_retry:"pm contracts --flags-only --json"}})}function fA(e,t){if(!e.selectedCommand||new Set(t).has(e.selectedCommand))return;let n=t.filter(i=>i.startsWith(`${e.selectedCommand} `));if(n.length>0)throw mA(e.selectedCommand,n);let r=Zg.get(K(e.selectedCommand));throw r?pA(e.selectedCommand,r):_A(e.selectedCommand)}function hA(e,t){let n=dA(e,t.mergedExtensionContracts);lA(e,n);let r=uA(n,t.mergedExtensionContracts);fA(e,r);let i=e.selectedCommand?ty.get(K(e.selectedCommand)):void 0,o=e.selectedCommand?n.filter(d=>i?d.action===i:IC(d,e.selectedCommand)):n;if(e.selectedCommand&&e.selectedAction&&!o.some(d=>d.action===e.selectedAction))throw new p(`Action "${e.selectedAction}" is not mapped to command "${e.selectedCommand}" in contracts output.`,m.USAGE);let s=e.selectedAction?o.filter(d=>d.action===e.selectedAction):o,a=[...new Map(s.map(d=>zC(d,t.runtimeProbe)).map(d=>[i?d.action:`${d.action}|${d.command_path??""}`,d])).values()],c=e.runtimeOnly&&!e.selectedAction&&!e.availabilityOnly?a.filter(d=>d.invocable):a;return{actionDescriptors:n,commandCatalog:r,commandScopedDescriptors:o,scopedActionDescriptors:s,selectedPackageOwnedAction:i,actionAvailability:c,actions:[...new Set(c.map(d=>d.action))]}}function gA(e){return new Set(Br(e).map(t=>{let n=t.properties;if(typeof n!="object"||n===null)return null;let r=n.action;if(typeof r!="object"||r===null)return null;let i=r.const;return typeof i=="string"?i:null}).filter(t=>t!==null))}function yA(e){let t=Qf,n=Br(t),r=gA(t),i=e.filter(o=>!r.has(o.action)).map(o=>UC(o));return i.length>0?{...t,oneOf:[...n,...i]}:t}function Xg(e,t,n){let r=new Set(t.actionDescriptors.map(o=>o.action)),i=e.selectedAction?LC(n,e.selectedAction):e.selectedCommand?Bc(n,new Set(t.scopedActionDescriptors.map(o=>o.action))):Bc(n,r);return e.runtimeOnly&&!e.selectedAction?Bc(i,new Set(t.actions)):i}function wA(e,t,n){let r=yA(t.mergedExtensionContracts),i=!e.flagsOnly&&!e.availabilityOnly?iA(Xg(e,n,r),t.createRequiredOptionContracts):Xg(e,n,r);return{mergedSchema:r,filteredSchema:i}}function vA(e,t){return e.selectedCommand!==void 0?[e.selectedCommand]:e.selectedAction?OC(t.scopedActionDescriptors,t.commandCatalog):t.commandCatalog}function cy(e,t){return t.find(n=>K(n.command)===K(e))?.tier??Nc(e)}function Go(e,t,n){return e.fullOutput||e.selectedCommand!==void 0||e.selectedAction!==void 0||cy(t,n)!=="internal"}function bA(e,t,n){if(e.selectedCommand!==void 0||e.selectedAction!==void 0)return t;let r=new Set(Kt.filter(i=>i.hidden&&(i.lifecycle==="deprecated"||!e.fullOutput&&!e.availabilityOnly)).map(i=>i.alias));if(e.summary&&!e.fullOutput)for(let i of Vc.keys())r.add(i);return t.filter(i=>!r.has(i)&&Go(e,i,n))}function dy(e){let t=ot.find(r=>r.alias===e||r.canonical===e);if(t)return t.canonical;let n=e.split(" ")[0];return n.startsWith("list-")?"list":Vc.get(n)??n}var kA=new Map([["activate","Activate"],["adopt","Adopt"],["adopt-all","Adopt all"],["catalog","Catalog"],["complete","Complete"],["create","Create"],["deactivate","Deactivate"],["delete","Delete"],["describe","Describe"],["doctor","Diagnose"],["explore","Explore"],["init","Initialize"],["inspect","Inspect"],["install","Install"],["list","List"],["manage","Manage"],["migrate","Migrate"],["mutate","Mutate"],["reload","Reload"],["restore","Restore"],["run","Run"],["snapshot","Manage snapshots for"],["uninstall","Uninstall"],["upgrade","Upgrade"]]),SA=new Map([["extension adopt-all","extensions"],["package adopt-all","packages"],["workspace snapshot list","workspace snapshots"]]);function EA(e,t){let n=Kg.get(K(e))??(e.includes(" ")?void 0:Kg.get(dy(e)));if(n!==void 0)return{intent:n,intent_source:"command"};let r=t.find(d=>vt(d.command).some(l=>K(l)===K(e)));if(r?.intent!==null&&r?.intent!==void 0)return{intent:r.intent,intent_source:"command"};if(r?.description!==null&&r?.description!==void 0)return{intent:r.description,intent_source:"description"};let i=e.split(" "),o=i.at(-1),s=i.slice(0,-1).join(" "),a=kA.get(o),c=SA.get(e)??s;return{intent:a===void 0||s.length===0?`Run ${e}.`:`${a} ${c}.`,intent_source:"generated"}}function TA(e,t=[],n={}){let r=n.includeFormatBudgets??!0,i=n.includeIntentProvenance??!0;return[...new Set(e.map(Se))].filter(o=>o.length>0).sort((o,s)=>o.localeCompare(s)).map(o=>{let s=Ya(o,{generateFallback:!0}),a=o.split(" ")[0],c=Vc.get(a)??(a.startsWith("list-")?"list":a.startsWith("history-")?"history":a),d=new Set([...sy(o).map(_=>_.flag),...t.filter(_=>vt(_.command).some(h=>K(h)===K(o))).flatMap(_=>_.flags.map(h=>h.flag))]),l=(qg.get(K(o))??qg.get(c)??EC).filter(_=>d.has(_)),u=EA(o,t);return{command:o,intent:u.intent,...i||u.intent_source!=="command"?{intent_source:u.intent_source}:{},...l.length>0?{flags:l}:{},default_max_estimated_tokens:s.default_max_estimated_tokens,...r?{default_max_estimated_tokens_by_format:{...s.default_max_estimated_tokens_by_format}}:{}}})}function CA(e){return e.map(t=>({budget:Ya(t,{generateFallback:!0}),envelope:gg(t)}))}function AA(e){let t=new Map;for(let n of e){let r=bg(n),i=r===void 0?[m.SUCCESS,m.GENERIC_FAILURE,m.USAGE,m.NOT_FOUND,m.CONFLICT,m.DEPENDENCY_FAILED]:r.exit_codes,o=i.join(","),s=t.get(o)??{commands:[],exit_codes:i};s.commands.push(n),t.set(o,s)}return[...t.values()]}function xA(e,t,n){if(e.selectedCommand)return t.extensionContracts.filter(r=>vt(r.command).some(i=>K(i)===K(e.selectedCommand)));if(e.selectedAction){let r=new Set(n);return t.extensionContracts.filter(i=>vt(i.command).some(o=>r.has(o)))}return t.extensionContracts.filter(r=>Go(e,r.command,t.extensionContracts))}function RA(e,t,n,r){return{schema_version:typeof t.mergedSchema["x-schema-version"]=="string"?t.mergedSchema["x-schema-version"]:null,schema_id:typeof t.mergedSchema.$id=="string"?t.mergedSchema.$id:null,selected:{action:e.selectedAction??null,command:e.selectedCommand??null,summary:e.summary,schema_only:e.schemaOnly,flags_only:e.flagsOnly,availability_only:e.availabilityOnly,runtime_only:e.runtimeOnly,command_scoped:e.selectedCommand!==void 0},commands:e.summary?[]:r,...!e.summary&&!e.flagsOnly?{actions:n.actions,action_availability:n.actionAvailability}:{}}}function IA(e,t,n){(n.selectedCommand==="history"||n.fullOutput)&&!n.flagsOnly&&!n.schemaOnly&&!n.availabilityOnly&&(e.history_operations=Sm);let r=n.selectedCommand;e.runtime_schema={statuses:t.statusRegistry.definitions.map(i=>i.id),open_status:t.statusRegistry.open_status,close_status:t.statusRegistry.close_status,canceled_status:t.statusRegistry.canceled_status,types:[...t.typeRegistry.types],fields_by_command:Object.fromEntries([...t.runtimeFieldRegistry.command_to_fields.entries()].filter(([i])=>r===void 0||i===r).map(([i,o])=>[i,[...new Set(o.map(s=>`--${s.cli_flag}`))].sort((s,a)=>s.localeCompare(a))]))},!(r!==void 0&&!n.fullOutput)&&(e.extension_contracts={capabilities:[...Fu],services:[...ju],policy_modes:[...Uu],policy_mode_scope:"extensions.policy.mode",policy_surfaces:[...Ku],trust_modes:[...Gu],trust_mode_scope:"extensions.policy.trust_mode",sandbox_profiles:[...qu],manifest_versions:[1,2],compatibility:{current:"v2",previous:["v1"],breaking_strategy:"versioned_breaking"}},e.governance_contracts={ownership_enforcement_modes:[...Zu],create_modes:[...em],close_validation_modes:[...tm],workflow_enforcement_modes:[...nm]},e.relationship_kind_contracts=[...ap,...(t.runtimeProbe.registrations?.relationship_kinds??[]).flatMap(i=>i.definitions)].sort((i,o)=>i.kind.localeCompare(o.kind)).map(i=>({canonical:i.kind,aliases:[...i.aliases??[]],...i.inverse===void 0?{}:{inverse:i.inverse},ordering:i.ordering,hierarchy:i.hierarchy})))}function OA(e,t,n,r){if(!(t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredSchema){e.schema=n.filteredSchema,e.extension_commands=r;return}e.schema_omitted_reason="unfiltered_default_brief",e.extension_commands=r}}function LA(e,t,n,r,i){if(!(t.schemaOnly||t.availabilityOnly)){if(t.omitUnfilteredCommandFlags)e.command_flags_omitted_reason="unfiltered_default_brief";else{e.command_flags=eA(r,n.extensionFlagMap,n.runtimeFieldFlagMap,t.selectedCommand!==void 0,n.extensionContracts);let o=new Set(r);e.list_projections=Object.entries(a_).filter(([s])=>o.has(s)).map(([s,a])=>({command:s,default:a,brief_fields:[...s_,"priority"],compact_fields:[...o_]}))}e.command_aliases=t.fullOutput?i:i.map(({canonical:o,aliases:s})=>({canonical:o,aliases:s})),t.fullOutput||(e.command_alias_contracts_omitted_reason="compact_projection; restore with --full")}}function DA(e,t){if(!(t.schemaOnly||t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredCommanderAliases){e.commander_aliases=nA();return}e.commander_aliases_omitted_reason=t.selectedCommand?"command_scoped":"unfiltered_default_brief"}}function $A(e,t,n,r){e.command_summaries=TA(t,n,{includeFormatBudgets:r.includeFormatBudgets,includeIntentProvenance:r.includeIntentProvenance}),e.output_policy={token_estimate:"ceil(utf8_bytes / 4)",degradation_ladder:[...Jm],allows_unbounded_opt_out:!0},e.output_projection_contracts={global_ladder_field:"output_policy.degradation_ladder",global_ladder_scope:"union_not_per_command",discovery:"pm contracts --command <command> --summary",...r.includeProjectionModeMatrix?{commands:[...new Set(t.map(Se))].filter(i=>Zm(i)!==void 0).sort((i,o)=>i.localeCompare(o)).map(i=>({command:i,modes:[...ep(i).keys()]}))}:{}},e.grammar_contracts={nouns:tn.nouns,shared_verbs:tn.shared_verbs,scope_before_verb:tn.scope_before_verb,visible_top_level_ceiling:tn.visible_top_level_ceiling,ceiling_raise_requires_pm_item:tn.ceiling_raise_requires_pm_item,positional_shape_budget:tn.positional_shape_budget,positional_shape_count:new Set(oc.map(({slots:i})=>l_(i))).size,positional_action_count:ic.length,positional_action_parents:[...new Set(ic.map(({parent:i})=>i))].sort((i,o)=>i.localeCompare(o)),...r.includePositionalSignatures?{positional_signatures:oc}:{}}}async function o2(e,t){let n=oA(e);sA(n);let r=R(process.cwd(),t.path),i=await cA(t,r,n),o=hA(n,i),s=wA(n,i,o),a=vA(n,o),c=bA(n,a,i.extensionContracts),d=RA(n,s,o,c),l=xA(n,i,c),u=n.fullOutput||n.selectedCommand!==void 0;if((n.summary||n.fullOutput)&&$A(d,c,l,{includeFormatBudgets:u,includeIntentProvenance:u,includePositionalSignatures:u,includeProjectionModeMatrix:u}),n.summary)return d;let _=tA(o.commandCatalog.filter(h=>Go(n,h,i.extensionContracts)));return n.flagsOnly&&!n.fullOutput||IA(d,i,n),OA(d,n,s,l),LA(d,n,i,c,_),DA(d,n),(n.selectedCommand==="assurance"||n.fullOutput)&&(d.assurance_contracts={measurement_source_kinds:[...Gr],gate_triggers:[...yt]}),n.fullOutput&&d.grammar_contracts&&(d.grammar_contracts.destinations=d_.map(h=>({...h,reason:h.reason??""}))),n.fullOutput&&!n.schemaOnly&&!n.flagsOnly&&!n.availabilityOnly&&(d.mcp_tools=Gg(),d.context_intents=tp(),d.read_output_dimensions=Qm,d.error_codes=fg,d.command_output_contracts=CA(c),d.diagnostic_output_contracts=Xm,d.command_exit_contracts={vocabulary:Pc,command_sets:AA(c)}),d}import{createHash as uy}from"node:crypto";import Hr from"node:fs/promises";import Vr from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="69bf315a-01aa-56d9-bd56-196d6792dea2")}catch{}})();function ze(e,t){throw new p(e,m.USAGE,t)}var NA="2026-07-15T06:22:12.276Z",MA=Date.parse(NA),PA=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],ly=e=>typeof e=="string"?e:"",my=e=>{let t=e??{},n=ly(t.author).trim().toLowerCase(),r=Number(["","unknown"].includes(n)),i=+(Date.parse(ly(t.ts))>=MA);return PA[r][i]};function py(e,t,n=20,r=new Set,i=!1){let o=[],s=[],a={legacy_unknown:0,actionable_unknown:0},c=Math.max(0,n),d=0,l=0,u=0;for(let[_,h]of t.split(/\r?\n/).entries()){let f;try{f=JSON.parse(h)}catch{continue}d+=1;let g=my(f);if(g!=="attributed"){if(l+=1,g==="actionable_unknown"&&r.has(`${e}:${_+1}`)){u+=1;continue}a[g]+=1,i&&g==="actionable_unknown"&&s.push({item_id:e,line:_+1}),o.length<c&&o.push({item_id:e,line:_+1})}}return{checked_events:d,unknown_event_count:l,legacy_unknown_event_count:a.legacy_unknown,actionable_unknown_event_count:a.actionable_unknown,acknowledged_actionable_event_count:u,samples:o,samples_truncated:a.legacy_unknown+a.actionable_unknown>o.length,actionable_events:s}}var f2=(e,t,n=20,r=new Set)=>py(e,t,n,r);function _y(e){let t=new Set;for(let n of e.split(/\r?\n/)){let r;try{r=JSON.parse(n)}catch{continue}let i=(typeof r=="object"&&r!==null&&typeof r.context=="object"&&r.context!==null?r.context:{}).author_acknowledgment;if(!(typeof i!="object"||i===null||!Array.isArray(i.events)))for(let o of i.events)typeof o=="object"&&o!==null&&typeof o.item_id=="string"&&Number.isSafeInteger(o.line)&&t.add(`${o.item_id}:${String(o.line)}`)}return t}var Yr=async(e,t=20,n=!1)=>{let r=Vr.join(e,"history"),i;try{i=(await Hr.readdir(r)).filter(w=>w.endsWith(".jsonl")).sort((w,v)=>w.localeCompare(v))}catch{i=[]}let o=new Set,s=[],a=[],c=0,d=0,l=0,u=0,_=0,h=0,f="_workspace.jsonl",g=new Set;if(i.includes(f))try{g=_y(await Hr.readFile(Vr.join(r,f),"utf8"))}catch{g=new Set}for(let w of i){let v;try{v=await Hr.readFile(Vr.join(r,w),"utf8")}catch{continue}let k=w.slice(0,-6),S=py(k,v,t-s.length,g,n);c+=1,d+=S.checked_events,l+=S.unknown_event_count,u+=S.legacy_unknown_event_count,_+=S.actionable_unknown_event_count,h+=S.acknowledged_actionable_event_count,S.unknown_event_count>0&&o.add(k),s.push(...S.samples),n&&a.push(...S.actionable_events)}let y=u+_;return{checked_streams:c,checked_events:d,unknown_event_count:l,legacy_unknown_event_count:u,actionable_unknown_event_count:_,acknowledged_actionable_event_count:h,affected_item_ids:[...o].sort((w,v)=>w.localeCompare(v)),samples:s,samples_truncated:y>s.length,...n?{actionable_events:a}:{}}};function FA(e){return[...new Map(e.map(t=>[`${t.item_id}:${t.line}`,{item_id:t.item_id,line:t.line}])).values()].sort((t,n)=>t.item_id.localeCompare(n.item_id)||t.line-n.line)}async function jA(e){try{return _y(await Hr.readFile(Vr.join(e,"history","_workspace.jsonl"),"utf8"))}catch{return new Set}}function UA(e){return(e.item_id===Xt||/^[a-z0-9][a-z0-9-]*$/iu.test(e.item_id))&&Number.isSafeInteger(e.line)&&e.line>=1}function GA(e,t,n){let r=n[e.line-1]??"",i;try{i=JSON.parse(r)}catch{ze(`Unknown-author acknowledgment target ${e.item_id}:${e.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}return my(i)!=="actionable_unknown"&&ze(`Author acknowledgment target ${e.item_id}:${e.line} is not an actionable unknown-author event.`,{code:"history_author_acknowledge_target_not_actionable"}),{...e,source_event_hash:uy("sha256").update(r).digest("hex"),disposition:t.has(`${e.item_id}:${e.line}`)?"already_acknowledged":"actionable"}}async function fy(e,t,n){let r=t.events??[],i=+(t.all_actionable===!0)+ +(r.length>0);i===0&&ze("Specify exactly one selector: events or all_actionable.",{code:"history_author_acknowledge_selector_required"}),i>1&&ze("Author acknowledgment accepts either explicit events or all_actionable, not both.",{code:"history_author_acknowledge_selector_conflict"}),(!Number.isSafeInteger(n)||n<0)&&ze("Author acknowledgment coordinate_limit must be a non-negative integer.",{code:"history_author_acknowledge_preview_limit_invalid"});let o=FA(t.all_actionable===!0?(await Yr(e,0,!0)).actionable_events:r),s=await jA(e),a=new Map;for(let _ of o)if(UA(_)||ze(`Unknown-author acknowledgment target ${_.item_id}:${_.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"}),!a.has(_.item_id))try{a.set(_.item_id,(await Hr.readFile(Vr.join(e,"history",`${_.item_id}.jsonl`),"utf8")).split(/\r?\n/u))}catch{ze(`Unknown-author acknowledgment target ${_.item_id}:${_.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}let c=o.map(_=>GA(_,s,a.get(_.item_id))),d=t.all_actionable===!0?"all_actionable":"events",l=uy("sha256").update(JSON.stringify({version:1,selection:d,coordinates:c})).digest("hex"),u=c.filter(({disposition:_})=>_==="actionable").length;return{plan:{selection:{kind:d},selected_count:c.length,actionable_count:u,already_acknowledged_count:c.length-u,omitted_count:Math.max(0,c.length-n),coordinates:c.slice(0,n),plan_fingerprint:l},completeCoordinates:c}}async function h2(e,t,n=50){return(await fy(e,t,n)).plan}function qA(e,t){let n=e.length>0;return n&&t&&ze("Specify exactly one selector: repeat --event or pass --all-actionable.",{code:"history_author_acknowledge_selector_conflict",required:"Exactly one of --event or --all-actionable",examples:['pm history-author-acknowledge --event pm-a1b2:4 --attributed-author agent --reviewer maintainer --reason "Verified provenance"','pm history-author-acknowledge --all-actionable --attributed-author import-agent --reviewer maintainer --reason "Reviewed the complete actionable set"']}),!n&&!t&&ze("Specify exactly one selector: repeat --event or pass --all-actionable.",{code:"history_author_acknowledge_selector_required",required:"Exactly one of --event or --all-actionable",examples:['pm history-author-acknowledge --event pm-a1b2:4 --attributed-author agent --reviewer maintainer --reason "Verified provenance"','pm history-author-acknowledge --all-actionable --attributed-author import-agent --reviewer maintainer --reason "Reviewed the complete actionable set"']}),{events:KA(e),all_actionable:t}}function KA(e){return e.map(t=>{let n=t.lastIndexOf(":"),r=t.slice(0,n).trim(),i=Number(t.slice(n+1)),o=r===Xt||/^[a-z0-9][a-z0-9-]*$/iu.test(r);return(n<1||!o||!Number.isSafeInteger(i)||i<1)&&ze(`history-author-acknowledge --event expects <item-id>:<one-based-line>, received "${t}".`,{code:"history_author_acknowledge_target_unreadable"}),{item_id:r,line:i}})}function g2(e,t){let n=qA(ih(t.historyEvent),t.allActionable===!0||t.all_actionable===!0);return WA(e,{events:n.events,all_actionable:n.all_actionable,dry_run:t.dryRun===!0||t.dry_run===!0,plan_fingerprint:te(t,"planFingerprint")??te(t,"plan_fingerprint"),coordinate_limit:typeof t.limit=="number"?t.limit:typeof t.limit=="string"?Number(t.limit):void 0,attributed_author:te(t,"attributedAuthor")??te(t,"attributed_author")??void 0,reviewer:te(t,"reviewer"),reason:te(t,"reason")})}async function WA(e,t){let n=t.reviewer?.trim()??"",r=t.attributed_author?.trim()??"",i=t.reason?.trim()??"",o=await fy(e,t,t.coordinate_limit??50);if(t.dry_run===!0)return{dry_run:!0,mutated:!1,acknowledged:0,outcome:"preview",exit_code:m.SUCCESS,plan:o.plan};if([n.length>0,n.toLowerCase()!=="unknown",r.length>0,r.toLowerCase()!=="unknown",i.length>0].includes(!1)&&ze("Author acknowledgment requires events, reviewer, attributed_author, and reason.",{code:"history_author_acknowledge_required_values_missing"}),t.plan_fingerprint?.trim()||ze("Author acknowledgment apply requires plan_fingerprint from a fresh dry-run preview.",{code:"history_author_acknowledge_plan_fingerprint_required",recovery:{suggested_retry:"Rerun history-author-acknowledge with --dry-run, then pass --plan-fingerprint <value>."}}),t.plan_fingerprint.trim()!==o.plan.plan_fingerprint)throw new p("Author acknowledgment selection changed after preview; no history was mutated.",m.CONFLICT,{code:"history_author_acknowledge_plan_conflict",recovery:{suggested_retry:"Rerun history-author-acknowledge with --dry-run and apply the fresh plan_fingerprint."}});let s=o.completeCoordinates.filter(({disposition:l})=>o.plan.selection.kind==="events"||l==="actionable").map(({item_id:l,line:u})=>({item_id:l,line:u}));if(s.length===0)return{dry_run:!1,mutated:!1,acknowledged:0,outcome:"no_effect",exit_code:m.NO_EFFECT,plan:o.plan};let a=await x(e),c=await Rn({pmRoot:e,op:"history:author-acknowledge",author:n,context:{author_acknowledgment:{events:s,attributed_author:r}},message:i,lockTtlSeconds:a.locks.ttl_seconds,lockWaitMs:a.locks.wait_ms}),d=o.plan.actionable_count>0&&o.plan.already_acknowledged_count>0?{outcome:"partial_effect",exit_code:m.PARTIAL_EFFECT}:{outcome:"effect",exit_code:m.SUCCESS};return{dry_run:!1,mutated:!0,acknowledged:s.length,...d,plan:o.plan,history_path:c.historyPath}}import BA from"node:fs/promises";import De from"node:path";import{glob as HA}from"tinyglobby";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6f94fb3c-3d6c-5543-a2f0-e12680459e71")}catch{}})();var zA=/^[a-z][a-z0-9+.-]+:\/\//i;function Jr(e){return zA.test(e.trim())}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6c72ddef-c0fa-5d0b-9e35-20e3ba3c8d73")}catch{}})();var Yc=["refuse","replace","append"],Xc="; ";function VA(e,t){if(e===void 0)return"refuse";let n=e.trim().toLowerCase();if(!Yc.some(r=>r===n))throw new p(`--note-conflict must be one of ${Yc.join(", ")}; got "${e}"`,m.USAGE,{code:"invalid_argument_value",flag:"--note-conflict",value:e,required:`Pass --note-conflict ${Yc.join("|")}.`});if(!t)throw new p("--note-conflict requires --add or --add-glob in the same invocation (it decides how those links treat an existing note)",m.USAGE,{code:"missing_required_argument",flag:"--note-conflict",required:"Pass --add or --add-glob with --note-conflict."});return n}function YA(e,t,n){if(t===void 0||t===e)return{note:e,outcome:"unchanged",conflict:!1};if(e===void 0)return{note:t,outcome:"note_added",conflict:!1};if(n==="replace")return{note:t,outcome:"note_replaced",conflict:!1};if(n==="append"){let r=Xc;return`${r}${e}${r}`.includes(`${r}${t}${r}`)?{note:e,outcome:"unchanged",conflict:!1}:{note:`${e}${Xc}${t}`,outcome:"note_appended",conflict:!1}}return{note:e,outcome:"unchanged",conflict:!0}}function JA(e){let t=e.conflicts[0],n=e.conflicts.length>1?` and ${e.conflicts.length-1} more`:"",r=e.retryArgs("append"),i=e.retryArgs("replace"),o=t.source==="stored"?`${e.itemId} already links ${e.noun} ${t.path} with the note "${t.existing_note}"${n}; the add was refused so that note is kept`:`The add names ${e.noun} ${t.path} on ${e.itemId} with two notes, "${t.existing_note}" and then "${t.requested_note}"${n}; the add was refused because they disagree`;return new p(o,m.CONFLICT,{code:"linked_artifact_note_conflict",item_id:e.itemId,why:"A different stored note is usually another agent's rationale, so --add never overwrites it silently.",required:"Re-run with --note-conflict append to keep both notes, or --note-conflict replace to overwrite the stored note.",...r===void 0||i===void 0?{}:{nextSteps:[e.render(r),e.render(i)],recovery:{suggested_retry:e.render(r),suggested_retry_args:r}},details:{conflicts:e.conflicts.map(s=>({...s}))}})}var Qc=["path","scope","note"],XA=["pattern","glob","path","scope","note"],QA=["path"],ZA=["from","to"],ex=new Set(["note","scope"]);function hy(e){return JSON.parse(JSON.stringify(e))}function nd(e,t){let n=e.map(hy);return t.filter(r=>{let i=hy(r),o=n.findIndex(s=>Fe(s,i));return o>=0&&n.splice(o,1),o<0})}function Xr(e){let t=e.fullHistory?[...e.stored]:[...e.written],n=t.length<e.stored.length;return{entries:t,total_count:e.stored.length,returned_count:t.length,has_more:n,mutation_receipt:{changed_count:e.written.length,removed_count:e.removedCount,full_history_included:!n,...e.linkOutcomes&&e.linkOutcomes.length>0?{link_outcomes:[...e.linkOutcomes]}:{}},omission_receipt:{has_omissions:n,omitted_field_group_count:n?1:0,omitted_field_groups:n?[{name:`${e.collectionKey}_history`,restore_with:{selector:"full_history",cli_flag:"--full-history",sdk_option:"fullHistory",mcp_option:"full"}}]:[]}}}function gy(e){let t=e??"project";if(!Ke.includes(t))throw new p(`Invalid scope "${e}". Valid scopes: ${Ke.join(", ")} (default: project).`,m.USAGE);return t}function Zc(e){if(e.startsWith("```")||e.includes(`
|
|
6
|
+
`)||/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(e))return!0;let t=e.indexOf(","),n=e.slice(0,t>=0?t:e.length),r=n.indexOf("=");return r>=0&&!/\s/u.test(e)&&(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)||/^(?:[A-Za-z]:[\\/]|[\\/]{1,2}|\.\.?(?:[\\/]))/u.test(e)||[e.indexOf("/"),e.indexOf("\\")].some(i=>i>=0&&i<r))?!1:n.includes("=")||Sn(e)}function tx(e){let t=0;for(let n of e)if(n==="("&&(t+=1),n===")"&&(t-=1),t<0)return!1;return t===0}function nx(e){if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)&&!Zc(e))return{path:e,scope:"project",note:void 0};let t=e.indexOf("](");if(e.startsWith("[")&&t>0&&e.endsWith(")")){let o=e.slice(t+2,-1).trim();if(o.length>0&&tx(o))return{path:o,scope:"project",note:e.slice(1,t).trim()||void 0}}let n=e.indexOf(",");if(n<0)return;let r=e.slice(0,n).trim(),i=e.slice(n+1).trim();if(!(r.length===0||!/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(i)))return{path:i,scope:"project",note:r}}function rd(e,t){return e?e.flatMap(n=>{let r=n.trim();if(t==="doc"){let o=nx(r);if(o!==void 0)return[o]}mr(r,"--add",`${t} path`,Zc(r));let i=Zc(r)?ee(n,"--add"):{path:r};if(ke(i,"--add",Qc),!i.path)throw new p(`--add requires path=<value> or a bare ${t} path`,m.USAGE);return[{path:i.path,scope:gy(i.scope),note:i.note?.trim()||void 0}]}):[]}function rx(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new p("--add-glob requires a glob pattern value",m.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?(?:pattern|glob|path)\s*[:=]/i.test(n)||n.startsWith("```")){let r=ee(n,"--add-glob");ke(r,"--add-glob",XA);let i=r.pattern?.trim()||r.glob?.trim()||r.path?.trim();if(!i)throw new p("--add-glob key/value form requires pattern=<glob>",m.USAGE);return{pattern:i,scope:gy(r.scope),note:r.note?.trim()||void 0}}return{pattern:n,scope:"project"}}):[]}function ix(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new p("--remove requires a path value",m.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?path\s*[:=]/i.test(n)||n.startsWith("```")){let r=ee(n,"--remove"),i=Object.keys(r).filter(o=>ex.has(o.toLowerCase()));if(i.length>0)throw new p(`--remove identifies a linked artifact by path only and does not accept ${i.map(o=>`"${o}"`).join(", ")}. Pass just the path (path=<value>, path:<value>, or a bare path); record removal context with --message "<why removed>".`,m.USAGE);if(ke(r,"--remove",QA),!r.path)throw new p("--remove key/value form requires path=<value>",m.USAGE);return r.path}return n}):[]}function ox(e){return e?e.map(t=>{let n=ee(t,"--migrate");ke(n,"--migrate",ZA);let r=n.from?.trim(),i=n.to?.trim();if(!r||!i)throw new p("--migrate requires from=<value> and to=<value>",m.USAGE);return{from:r,to:i}}):[]}function Wn(e,t){let n=e;for(let r of t)n.startsWith(r.from)&&(n=`${r.to}${n.slice(r.from.length)}`);return n}function sx(e,t,n=[]){if(e.length===0||t.length===0)return;let r=new Set(e.map(o=>Mt(Wn(o.path,n)))),i=[...new Set(t.map(o=>Mt(Wn(o,n))).filter(o=>r.has(o)))].sort((o,s)=>o.localeCompare(s));if(i.length!==0)throw new p(`Linked artifact mutation cannot add and remove the same normalized path in one transaction: ${i.join(", ")}. Split the replacement into separate commands so each history event has one unambiguous intent.`,m.USAGE,{code:"linked_artifact_mutation_conflict",reason:"same_path_added_and_removed",required:"Use distinct normalized paths for --add and --remove in one invocation.",why:"Conflicting batch intent cannot be applied deterministically without silently discarding metadata or a removal.",nextSteps:["Run the removal and addition as separate commands with a --message describing each intent."]})}function bt(e){return e.split(De.sep).join("/")}function ed(e,t,n=process.cwd()){let r=e.trim();if(Jr(r))return r;if(De.isAbsolute(r)||/^[A-Za-z]:[\\/]/.test(r))return bt(r.replaceAll("\\",De.sep));let i=De.relative(t,n);return i.startsWith(`..${De.sep}`)||i===".."||De.isAbsolute(i)?bt(De.normalize(r)):bt(De.relative(t,De.resolve(n,r)))}async function ax(e,t=process.cwd(),n=process.cwd()){let r=[];for(let i of e){if(De.resolve(n,i.pattern)===De.resolve(n))continue;let o=De.isAbsolute(i.pattern),s=await HA(i.pattern,{cwd:n,absolute:o,onlyFiles:!0,dot:!0,expandDirectories:!1,followSymbolicLinks:!0}),a=[...new Set(s.map(c=>ed(c,t,n)))].sort((c,d)=>c.localeCompare(d));for(let c of a)r.push({path:c,scope:i.scope,note:i.note})}return r}function cx(e,t,n){if(t===void 0)return e;if(!n)throw new p("--note requires --add or --add-glob in the same invocation (the note annotates the links being added)",m.USAGE);let r=t.trim();return r.length===0?e:e.map(i=>i.note===void 0?{...i,note:r}:i)}function td(e){return`${e.path}::${e.scope}`}function id(e){return[...e].sort((t,n)=>{let r=t.path.localeCompare(n.path);return r!==0?r:t.scope.localeCompare(n.scope)})}function od(e){return[...new Map(e.map(t=>[td(t),t])).values()].map(t=>({...t,note:t.note?.trim()||void 0}))}async function dx(e,t=process.cwd()){let n=[...new Set(e)].sort((a,c)=>a.localeCompare(c)),r=[],i=[],o=[],s=[];for(let a of n){if(Jr(a)){s.push(a.trim());continue}let c=De.isAbsolute(a)?a:De.resolve(t,a);try{(await BA.stat(c)).isFile()?r.push(a):o.push(a)}catch(d){if(typeof d=="object"&&d!==null&&"code"in d&&Tn(d)){i.push(a);continue}o.push(a)}}return{checked:n.length,existing_files:r,missing_paths:i,non_file_paths:o,remote_references:s}}function lx(e,t,n,r){let i=0;for(let o=0;o<e.length;o+=1){let s=Wn(e[o].path,r);s!==e[o].path&&(i+=1);let a=Mt(s);a!==e[o].path&&(e[o]={...e[o],path:a})}return{adds:t.map(o=>{let s=Wn(o.path,r);return s!==o.path&&(i+=1),{...o,path:Mt(s)}}),removes:n.map(o=>Mt(Wn(o,r))),count:i}}function Mt(e){return e.replaceAll("\\","/")}function Jc(e){return`${e.scope}\0${Mt(e.path)}`}function ux(e,t,n){let r=new Map(e.map(s=>[Jc(s),s.note])),i=new Map(t.map(s=>[Jc(s),s.note])),o=new Map;for(let s of n){let a=Jc(s);o.has(a)||o.set(a,{path:Mt(s.path),scope:s.scope,outcome:mx(r.has(a),r.get(a),i.get(a))})}return[...o.values()]}function mx(e,t,n){return e?n===t?"unchanged":t===void 0?"note_added":n?.startsWith(`${t}${Xc}`)?"note_appended":"note_replaced":"added"}function px(e,t,n){let r=e.merged.findIndex(s=>s.path===t.path&&s.scope===t.scope),i=e.merged[r];if(i===void 0){e.merged.push(t),t.note!==void 0&&e.notedHere.add(t);return}let o=YA(i.note,t.note,n);if(o.conflict)e.conflicts.push({path:t.path,scope:t.scope,existing_note:i.note,requested_note:t.note,source:e.notedHere.has(i)?"this_write":"stored"});else if(o.note!==i.note){let s={...i,note:o.note};e.merged[r]=s,e.notedHere.add(s)}}function _x(e,t,n,r,i){let o=od(e),s={merged:[...o],notedHere:new Set,conflicts:[]};for(let d of t)px(s,d,i);let{merged:a}=s,c=ux(o,a,t);if(n.length>0)for(let d=a.length-1;d>=0;d-=1)n.includes(a[d].path)&&a.splice(d,1);return{entries:r?a:id(a),outcomes:c,conflicts:s.conflicts}}async function yy(e){let t=e.mutation?.entries??e.artifacts,n=e.options.validatePaths?e.artifacts:t,{counts:r,receipts:i}=Ko(e.mutation);return{id:e.id,artifacts:t,changed:e.changed,count:t.length,...r,migrations_applied:e.migrationsApplied&&e.migrationsApplied>0?e.migrationsApplied:void 0,validation:e.options.validatePaths||e.changed&&n.length>0?await dx(n.map(o=>o.path),e.workspaceRoot):void 0,...i}}function fx(e,t,n){let r=new Map;for(let o of t){let s=td(o);r.set(s,(r.get(s)??0)+1)}let i=0;for(let o of e){let s=td({...o,path:Mt(Wn(o.path,n))}),a=r.get(s)??0;a>0?r.set(s,a-1):i+=1}return i}function hx(e,t){let n=/[\n\r]|^\s*[-*+`]/u.test(e)?[]:Ju(e),r=n.findIndex(l=>l.key?.toLowerCase()==="note");if(r<0)return;let i=n.slice(0,r).map(l=>l.raw.trim()),o=new Set(n.slice(0,r).map(l=>l.key?.toLowerCase())),s=[n[r].value],a;for(let l of n.slice(r+1)){let u=l.key?.toLowerCase();if((u==="path"||u==="scope")&&!o.has(u)){i.push(l.raw.trim()),o.add(u);continue}a??=l.key===void 0?void 0:{segment:l.text.trim(),key:l.key},s.push(l.text)}if(a===void 0)return;let c=s.join(",").trim(),d=[...i,`note=${JSON.stringify(c)}`].join(",");try{rd([d],t)}catch{return}return{entry:d,note:c,...a}}function gx(e,t){return e.findIndex(n=>{try{return rd([n],t),!1}catch{return!0}})+1}function qo(e,t,n){return(t??[]).flatMap(r=>[e,n!==void 0&&r.trim()==="-"?`${n}=-`:r])}function wy(e){let{options:t}=e,n=e.noteConflict??t.noteConflict;return[...Ie(e.global),...e.guards.map(r=>`--expect-hash=${r}`),e.config.metadataKey,e.id,...qo("--add",e.entries.map((r,i)=>i===e.position-1?e.rewritten:r),"path"),...qo("--add-glob",e.resolved.addGlob,"pattern"),...qo("--remove",e.resolved.remove,"path"),...qo("--migrate",e.resolved.migrate),...t.note===void 0?[]:["--note",t.note],...n===void 0?[]:["--note-conflict",n],...e.config.supportsAppendStable&&t.appendStable===!0?["--append-stable"]:[],...t.validatePaths===!0?["--validate-paths"]:[],...t.fullHistory===!0?["--full-history"]:[],...t.author?["--author",t.author]:[],...t.message?["--message",t.message]:[],...t.force===!0?["--force"]:[]]}function yx(e){return Qc.some(t=>t===e.toLowerCase())?`If "${e}" was meant as a key, give it once per entry.`:`If "${e}" was meant as a key, it is not one of: ${Qc.join(", ")}.`}function wx(e){try{return rd(e.entries,e.config.bareNoun)}catch(t){let n=e.entries,r=t,i=gx(n,e.config.bareNoun),o=hx(n[i-1],e.config.bareNoun);if(o===void 0)throw t;let s=br(e.pmRoot),a=s===void 0?void 0:wy({...e,entries:n,position:i,rewritten:o.entry,guards:s});throw new p(`--add read the note segment "${o.segment}" as a new key "${o.key}", so the ${e.config.bareNoun} link was refused (${r.message})`,m.USAGE,{code:"linked_artifact_note_key_misread",flag:"--add",value:n[i-1],required:`Retry with the note quoted so its commas stay prose (${a===void 0?`as ${o.entry}; its revision guards cannot be replayed as typed, so no executable retry is offered`:"recovery.suggested_retry_args replays the whole invocation that way"}), or pass the prose through --note in a single-entry call. ${yx(o.key)}`,why:"After a comma, an identifier followed by = or : opens a new key, so that a typo such as lable=main is refused instead of being stored as note text (GH-258).",...a===void 0?{}:{nextSteps:[L(a)]},details:{entry_index:i,misread_segment:o.segment,misread_key:o.key,note:o.note,rewritten_entry:o.entry,cause:r.context.code??"invalid_argument_value"},...a===void 0?{}:{recovery:{suggested_retry:L(a),suggested_retry_args:a}}})}}function Ko(e){return e===void 0?{counts:{},receipts:{}}:{counts:{total_count:e.total_count,returned_count:e.returned_count,has_more:e.has_more},receipts:{mutation_receipt:e.mutation_receipt,omission_receipt:e.omission_receipt}}}async function vx(e){let{settings:t,config:n}=e,r=await V(e.pmRoot,e.id,t.id_prefix,t.item_format,e.typeToFolder);if(!r)throw new p(`Item ${e.id} not found`,m.NOT_FOUND);let i=(await pe(r,{schema:t.schema})).document.metadata[n.metadataKey]??[],o=e.writeRequested?Xr({collectionKey:n.metadataKey,stored:i,written:[],removedCount:0,fullHistory:e.options.fullHistory===!0}):void 0;return yy({id:r.id,artifacts:i,changed:!1,options:e.options,workspaceRoot:e.workspaceRoot,mutation:o})}async function Wo(e,t,n,r){let{metadataKey:i}=r,o=En(),s=R(process.cwd(),n.path),a=lt(s),c=process.cwd();await j(s);let d=await x(s),l=P(d,N()),u=await o.resolveList(t.add,"--add"),_=await o.resolveList(t.addGlob,"--add-glob"),h=await o.resolveList(t.remove,"--remove"),f=await o.resolveList(t.migrate,"--migrate"),g=wx({id:e,pmRoot:s,entries:u,resolved:{addGlob:_,remove:h,migrate:f},options:t,global:n,config:r}).map(J=>({...J,path:ed(J.path,a,c)})),y=rx(_),w=await ax(y,a,c),v=g.length>0||y.length>0,k=cx([...g,...w],t.note,v),S=VA(t.noteConflict,v),b=ix(h).map(J=>ed(J,a,c)),A=ox(f);if(sx(k,b,A),!(k.length>0||b.length>0||A.length>0))return vx({id:e,pmRoot:s,settings:d,typeToFolder:l.type_to_folder,options:t,workspaceRoot:a,config:r,writeRequested:y.length>0});let E=U(t.author,d.author_default),C=[],O=0,M=[],T=await he({pmRoot:s,settings:d,id:e,op:r.op,author:E,message:t.message,force:t.force,skipNoop:!0,mutate(J){let Me=J.metadata,Pe=Me[i]??[],qe=[...Pe],re=lx(qe,k,b,A),be=_x(qe,re.adds,re.removes,r.supportsAppendStable&&t.appendStable===!0,S);if(be.conflicts.length>0){let rt=br(s);throw JA({itemId:J.metadata.id,noun:r.bareNoun,conflicts:be.conflicts,retryArgs:it=>rt===void 0?void 0:wy({id:J.metadata.id,entries:u??[],position:0,rewritten:"",resolved:{addGlob:_,remove:h,migrate:f},options:t,global:n,config:r,guards:rt,noteConflict:it}),render:L})}let Ee=be.entries;M=be.outcomes,Ee.length>0?Me[i]=Ee:delete Me[i];let nt=!Fe(Pe,Ee);return C=Pe,O=fx(Pe,Ee,A),{changedFields:nt?[i]:[],warnings:nt&&re.count>0?[`path_migrations_applied:${re.count}`]:[]}}}),F=T.item[i]??[],ue=T.warnings.find(J=>J.startsWith("path_migrations_applied:")),Ne=ue?Number(ue.slice(24)):0;return yy({id:T.item.id,artifacts:F,changed:T.changedFields.includes(i),migrationsApplied:Ne,options:t,workspaceRoot:a,mutation:Xr({collectionKey:i,stored:F,written:nd(C,F),removedCount:O,fullHistory:t.fullHistory===!0,linkOutcomes:M})})}function zo(e,t){let n={};for(let[r,i]of Object.entries(e))n[r==="artifacts"?t:r]=i;return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b1de9573-b582-502d-8fb1-9e6ba3a521b0")}catch{}})();async function vy(e,t,n){let r=await Wo(e,t,n,{metadataKey:"docs",op:"docs_add",bareNoun:"doc",supportsAppendStable:!1});return zo(r,"docs")}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="67d97df8-6551-52ed-9307-8b573a087831")}catch{}})();var Bo=1e6;function sd(e,t=Bo,n=.8,r=!1){let i=new Set,o=(l,u)=>{if(i.add(`${l}:${u}`),i.size>t)throw new p(`Duplicate sweep exceeded ${t} candidate pairs; narrow it with statuses or since.`,m.CONFLICT,{code:"duplicate_sweep_cost_limit",required:"Narrow the duplicate query or increase its similarity threshold. No partial result was returned."})};if(r||n===0){for(let l=0;l<e.length;l+=1)for(let u=0;u<l;u+=1)o(u,l);return i}let s=new Map;for(let{prepared:l}of e)for(let u of l.tokens)s.set(u,(s.get(u)??0)+1);let a=new Map,c=new Map,d=new Map;for(let[l,{prepared:u}]of e.entries()){let _=[...u.tokens].sort((g,y)=>s.get(g)-s.get(y)||g.localeCompare(y)),h=_.length-Math.ceil(n*_.length-1e-12)+1,f=[{index:a,keys:[u.normalized],lengthFilter:!1},{index:c,keys:n<=.99?u.issueCodes:[],lengthFilter:!1},{index:d,keys:_.length===0?[""]:_.slice(0,h),lengthFilter:!0}];for(let g of f)bx(e,l,g,n,o)}return i}function bx(e,t,n,r,i){let o=e[t].prepared.tokens.length;for(let s of n.keys){let a=n.index.get(s)??[];for(let c of a){let d=e[c].prepared.tokens.length;n.lengthFilter&&Math.min(d,o)/Math.max(d,o)+1e-12<r||i(c,t)}a.push(t),n.index.set(s,a)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a5f450bd-8970-5b1b-8250-b76b7818e6e1")}catch{}})();var kx=3,by=20,Sx=.8,Ex=100,ky=1e3;function Sy(e){return e===void 0?[]:[`likely_duplicates:${e.result.items.map(t=>t.id).join(",")}`,`likely_duplicate_recovery:${e.recovery.action}:${e.recovery.item_id}`]}async function Tx(e,t){let n=e.items[0],r=R(t.cwd??process.cwd(),t.pmRoot),i=W((await x(r)).schema);return fe(n.status,i)?{action:"reopen",item_id:n.id,command:`pm item reopen ${n.id} "<recurrence reason>"`,args:["item","reopen",n.id,"<recurrence reason>"]}:{action:"reuse",item_id:n.id,command:`pm get ${n.id} --full`,args:["get",n.id,"--full"]}}function ad(e){let t=e.limit??kx,n=e.threshold??Sx;if(!Number.isSafeInteger(t)||t<0||t>by)throw new p(`Similarity limit must be an integer from 0 to ${by}.`,m.USAGE);if(!Number.isFinite(n)||n<0||n>1)throw new p("Similarity threshold must be a number from 0 to 1.",m.USAGE);return{limit:t,threshold:n}}function Ey(e){let t=e.limit??Ex;if(!Number.isSafeInteger(t)||t<0||t>ky)throw new p(`Duplicate cluster limit must be an integer from 0 to ${ky}.`,m.USAGE);let n=e.since===void 0?void 0:new Date(e.since);if(n&&Number.isNaN(n.getTime()))throw new p("Duplicate cluster --since must be a valid ISO timestamp.",m.USAGE);return{limit:t,since:n}}async function Cx(e,t){let n=R(e.cwd??process.cwd(),e.pmRoot),r=await x(n),i=P(r),o=e.statuses?.map(u=>u.trim().toLowerCase()).filter(Boolean);if(e.statuses!==void 0&&o?.length===0)throw new p("Duplicate cluster statuses must include at least one lifecycle status or all.",m.USAGE);let s=W(r.schema),a=o?.map(u=>{if(u==="all")return u;let _=ce(u,s);if(!_)throw new p(`Unknown duplicate-cluster status "${u}". Allowed: all, ${s.definitions.map(h=>h.id).join(", ")}.`,m.USAGE);return _}),c=a?.includes("all")===!0;if(c&&a?.some(u=>u!=="all"))throw new p('The "all" status cannot be combined with other statuses.',m.USAGE);let d=c?void 0:a,l=d?new Set(d):void 0;return{items:(await Te(n,r.item_format,i.type_to_folder,void 0,r.schema)).filter(u=>(!l||l.has(u.status))&&(!t||new Date(u.created_at).getTime()>=t.getTime())),statuses:d}}var sK={buildDuplicateClusters:Cy,collectDuplicateCandidatePairs:sd,createDuplicateUnionFind:Ty};function Ty(e){let t=Array.from({length:e},(n,r)=>r);return{parent:t,findRoot:n=>{let r=n;for(;t[r]!==r;)r=t[r];for(;t[n]!==n;){let i=t[n];t[n]=r,n=i}return r}}}function Ax(e,t,n,r){let i=[];for(let o of t){let[s,a]=o.split(":").map(u=>Number.parseInt(u,10)),c=nc(e[s].prepared,e[a].prepared);if(c.score<n)continue;let d=r.findRoot(s),l=r.findRoot(a);d!==l&&(r.parent[l]=d),i.push({left_id:e[s].item.id,right_id:e[a].item.id,...c})}return i}function Cy(e,t,n,r){let i=new Map;for(let a of e.keys()){let c=n.findRoot(a),d=i.get(c)??[];d.push(a),i.set(c,d)}let o=new Map(e.map(({item:a},c)=>[a.id,n.findRoot(c)])),s=new Map;for(let a of t){let c=o.get(a.left_id),d=s.get(c)??[];d.push(a),s.set(c,d)}return[...i.values()].filter(a=>a.length>1).map(a=>{let c=(s.get(n.findRoot(a[0]))??[]).sort((d,l)=>l.score-d.score||d.left_id.localeCompare(l.left_id)||d.right_id.localeCompare(l.right_id));return{id:e[a[0]].item.id,items:a.map(d=>{let l=e[d].item;return{id:l.id,title:l.title,status:l.status,type:l.type}}),matches:c,max_score:c[0]?.score??0}}).sort((a,c)=>c.max_score-a.max_score||a.id.localeCompare(c.id)).slice(0,r)}function xx(e,t,n,r,i){return t.filter(o=>!n.has(o.id)).map(o=>({id:o.id,title:o.title,status:o.status,type:o.type,...tc(e,o.title)})).filter(o=>o.score>=r).sort((o,s)=>s.score-o.score||o.id.localeCompare(s.id)).slice(0,i)}async function Rx(e,t={}){let n=e.title.trim();if(n.length===0)throw new p("Similarity candidate title must not be empty.",m.USAGE);let{limit:r,threshold:i}=ad(t),o=R(t.cwd??process.cwd(),t.pmRoot),s=await x(o),a=P(s),c=await _o(o,Object.values(a.type_to_folder)),d=Za(n),l=c&&d.length>0?await Lp({pmRoot:o,expectedSourceCursor:c.source_cursor,query:d.map(h=>`"${h.replaceAll('"','""')}"`).join(" OR "),limit:Math.max(r*10,50)}):null,u=l===null?await Te(o,s.item_format,a.type_to_folder,void 0,s.schema):l.items,_=xx(n,u,new Set(e.excludeIds??[]),i,r);return{items:_,count:_.length,threshold:i,source:l?"persistent_index":"metadata_fallback"}}function Ix(e,t={}){let{threshold:n}=ad({...t,limit:void 0}),{limit:r}=Ey(t),i=new Set;for(let l of e){if(!l.id.trim()||i.has(l.id))throw new p("Duplicate analysis requires unique non-empty item ids.",m.USAGE);i.add(l.id)}let o=[...e].sort((l,u)=>l.id.localeCompare(u.id)).map(l=>({item:l,prepared:ec(l.title)})),s=sd(o,Bo,n,t.exhaustive===!0),a=Ty(o.length),c=Ax(o,s,n,a),d=Cy(o,c,a,r);return{clusters:d,count:d.length,threshold:n,cost:{item_count:o.length,algorithm:t.exhaustive===!0||n===0?"exhaustive":"prefix_exact",possible_pairs:o.length*(o.length-1)/2,pair_limit:Bo,recall_guarantee:"exact",candidate_pairs:s.size,scored_pairs:s.size}}}async function Ay(e={}){ad({...e,limit:void 0});let{since:t}=Ey(e),{items:n,statuses:r}=await Cx(e,t);return{...Ix(n,e),source:"metadata_scan",filters:{statuses:r??null,since:e.since??null}}}async function cd(e,t){if(t.mode==="off")return;let n=await Rx(e,t);if(n.count===0)return;let r=await Tx(n,t),i=t.mode==="strict"&&t.allowDuplicate===!0;if(t.mode==="strict"&&!i){let o=n.items.map(a=>`${a.id} (${a.status}): ${a.title}`).join("; "),s=r.action==="reopen"?"Reopen the canonical item":"Reuse the canonical item";throw new p(`Likely duplicate item(s) found: ${o}. ${s} or pass --allow-duplicate with explicit intent.`,m.CONFLICT,{code:"likely_duplicate",required:`${s}, or explicitly acknowledge the duplicate with --allow-duplicate.`,recovery:{suggested_flags:["--allow-duplicate"],suggested_retry:r.command,suggested_retry_args:r.args}})}return{mode:t.mode,bypassed:i,result:n,recovery:r}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="499dfc08-cf70-55fe-8868-65c3107e3a91")}catch{}})();async function lK(e,t={}){let n=await Ay({pmRoot:R(process.cwd(),e.path),exhaustive:t.exhaustive,...t.status===void 0?{}:{statuses:t.status.flatMap(r=>r.split(",").map(i=>i.trim()).filter(Boolean))},...t.since===void 0?{}:{since:t.since},...t.threshold===void 0?{}:{threshold:t.threshold},...t.limit===void 0?{}:{limit:t.limit}});return{...n,clusters:n.clusters.map(r=>{let i=r.id;return{...r,canonical_id:i,close_command:`pm close <duplicate-id> --duplicate-of ${i}`}}),guidance:{strategy:"review_then_close_duplicate",command:"pm close <duplicate-id> --duplicate-of <canonical-id>"}}}import{execFile as Ox}from"node:child_process";import xy from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="15749905-177d-5ae0-b475-668733f41e8a")}catch{}})();function Ry(e,t){return new Promise((n,r)=>{Ox("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:4*1024*1024},(i,o)=>{i?r(i):n(o)})})}function Iy(e){if(e&&(!Number.isSafeInteger(e.start)||!Number.isSafeInteger(e.end)||e.start<1||e.end<e.start))throw new RangeError("Source line range must be inclusive positive integers with end >= start.")}function fK(e){let t=/^(\d+):(\d+)$/u.exec(e.trim()),n=t?{start:Number(t[1]),end:Number(t[2])}:void 0;if(Iy(n),!n)throw new RangeError("Source line range must use start:end.");return n}function Lx(e){let t=new Map;for(let n of e.split(`
|
|
7
|
+
`)){let r=/^([0-9a-f^]{40,64}) \d+ \d+(?: \d+)?$/u.exec(n)?.[1];r&&t.set(r,(t.get(r)??0)+1)}return t}function Dx(e){let t=e.split("\0"),n=new Map;for(let r=0;r+1<t.length;r+=2){let i=t[r]?.trim();if(!i)continue;let o=[...new Set(t[r+1]?.match(/\bpm-[a-z0-9][a-z0-9-]{2,63}\b/gu)??[])].sort((s,a)=>s.localeCompare(a));n.set(i,o)}return n}async function $x(e){let t=xy.relative(e.workspaceRoot,xy.resolve(e.workspaceRoot,e.sourcePath)),n=await Ry(e.workspaceRoot,["blame","--line-porcelain","-L",`${e.lineRange.start},${e.lineRange.end}`,"--",t]),r=await Ry(e.workspaceRoot,["log","-n","256","--format=%H%x00%B%x00","--",t]);return{commitLines:Lx(n),commitItems:Dx(r),available:!0}}function Nx(e){let t=e.current.nodes.at(-1),n=e.current.kinds.length+1,r;for(let i of e.graph.incidentEdges(t)){let o=i.source===t,s=o?i.target:i.source;if((e.visitedDepth.get(s)??Number.POSITIVE_INFINITY)<n)continue;e.visitedDepth.set(s,n);let a=e.graph.registry().require(i.kind),c={nodes:[...e.current.nodes,s],kinds:[...e.current.kinds,o?i.kind:a.inverse??i.kind]};e.details.get(s)?.type?.toLowerCase()==="decision"?(r=n,e.found.push(c)):e.queue.push(c)}return r}function Mx(e){let t=[{nodes:[e.itemId],kinds:[]}],n=new Map([[e.itemId,0]]),r=[],i;for(;t.length>0;){let o=t.shift(),s=o.kinds.length;i!==void 0&&s>=i||s>=e.maxDepth||(i=Nx({current:o,graph:e.graph,details:e.details,visitedDepth:n,queue:t,found:r})??i)}return r.sort((o,s)=>o.nodes.join("\0").localeCompare(s.nodes.join("\0"))),r}function Px(e,t,n){let r=lh(t);if(!r.graph.hasNode(e))return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let i=Mx({itemId:e,maxDepth:n,graph:r.graph,details:new Map(r.details.map(a=>[a.id,a]))}),o=i[0];if(!o)return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let s=[...new Set(i.map(a=>a.nodes.at(-1)))];return{status:s.length===1?"found":"ambiguous",nodes:o.nodes,kinds:o.kinds,alternative_decision_ids:s.slice(1)}}async function Fx(e){if(!e.lineRange)return{commitLines:new Map,commitItems:new Map,available:!0};try{return await $x({workspaceRoot:e.workspaceRoot,sourcePath:e.paths[0],lineRange:e.lineRange})}catch{return{commitLines:new Map,commitItems:new Map,available:!1}}}function jx(e){let t=[];return e.hasLineRange&&!e.attributionAvailable&&t.push("git_attribution_unavailable"),e.hasLineRange&&e.contributionLines===0&&t.push("line_attribution_unmapped"),e.decisionStatus==="ambiguous"&&t.push("multiple_governing_decisions"),e.decisionStatus==="not_found"&&t.push("governing_decision_not_found"),t}function Ux(e){return[...e.commitLines.keys()].filter(t=>(e.commitItems.get(t)?.length??0)>0)}async function Oy(e){Iy(e.lineRange);let t=e.decisionDepth??8;if(!Number.isSafeInteger(t)||t<1||t>32)throw new RangeError("Decision path depth must be an integer from 1 to 32.");let n=await Fx(e),r=Ux(n),i=new Map;for(let o of e.candidates){let s=[...n.commitLines.entries()].filter(([l])=>n.commitItems.get(l)?.includes(o.item.id)),a=s.reduce((l,[,u])=>l+u,0),c=Px(o.item.id,e.corpus,t),d=jx({hasLineRange:e.lineRange!==void 0,attributionAvailable:n.available,contributionLines:a,decisionStatus:c.status});i.set(o.item.id,{score:a*100+o.files.length*10+Math.max(0,9-Math.floor((Date.now()-Date.parse(o.item.updated_at))/(720*60*60*1e3))),contribution_lines:a,evidence:[...o.files.map(l=>({kind:"linked_file",reference:l.path})),...s.map(([l,u])=>({kind:"git_commit",reference:l.slice(0,12),contribution_lines:u}))],rationale:{value:o.item.value?.trim()||null,why_now:o.item.why_now?.trim()||null,outcome:o.item.outcome?.trim()||null,objective:o.item.objective?.trim()||null},decision_path:c,ambiguities:d})}return{explanations:i,receipt:{line_range:e.lineRange??null,blamed_commit_count:n.commitLines.size,mapped_commit_count:r.length,unmapped_commit_count:n.commitLines.size-r.length,decision_depth:t}}}import Ly from"node:fs/promises";import Be from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ad4d4093-7e23-5361-bec4-efb37bd610b6")}catch{}})();var Gx=32768;function dd(e){return bt(Be.normalize(e))}async function Ho(e){try{return await Ly.realpath(e)}catch{return Be.resolve(e)}}function zn(e,t){let n=Be.isAbsolute(e.path)?Be.resolve(e.path):Be.resolve(t,e.path);return`${dd(n)}::${e.scope}`}function Vo(e,t,n){if(typeof e=="string"){let r=e.trim();r.length>0&&n.push({field:t,value:r});return}if(Array.isArray(e)){e.forEach((r,i)=>Vo(r,`${t}[${i}]`,n));return}if(typeof e=="object"&&e!==null)for(let[r,i]of Object.entries(e))Vo(i,t?`${t}.${r}`:r,n)}function qx(e){let t=[];return Vo(e.metadata,"metadata",t),Vo(e.body,"body",t),t}function Kx(e){let t=e.trim();return t=t.replace(/^[`"'<([{]+/u,""),t=t.replace(/[`"'>)\]},;!?]+$/u,""),t=t.replace(/[.]+$/u,""),t=t.replace(/:(?:\d+)(?::\d+)?$/u,""),t=t.replace(/[.]+$/u,""),t}function Wx(e){let t=[],n=/(?:[A-Za-z]:[\\/]|\/)[^\s"'`<>()[\]{},;]+/gu,r=/(?:\.{1,2}[\\/])?(?:(?:[A-Za-z0-9_.@-]+[\\/])+[A-Za-z0-9_.@-]+|[A-Za-z0-9_.@-]+\.[A-Za-z0-9][A-Za-z0-9._-]*)/gu;for(let i of e){let o=new Set,s=i.value.slice(0,Gx);for(let[a,c]of[[n,i.value],[r,s]]){a.lastIndex=0;for(let d of c.matchAll(a)){let l=Kx(d[0]);!l||o.has(l)||(o.add(l),t.push({field:i.field,value:l}))}}}return t}async function zx(e,t,n=t){let r=Be.isAbsolute(e)?Be.resolve(e):Be.resolve(n,e),i;try{i=await Ly.stat(r)}catch{return}if(!i.isFile())return;let[o,s]=await Promise.all([Ho(t),Ho(r)]);if(Fa(o,s)){let a=Be.relative(o,s);return!a||a.startsWith("..")||Be.isAbsolute(a)?void 0:{path:dd(a),scope:"project"}}return{path:dd(r),scope:"global"}}async function Bx(e,t,n=t){let r=new Set((e.metadata.files??[]).map(c=>zn(c,t))),i=new Map,o=Wx(qx(e)),s=new Map;await Promise.all([...new Set(o.map(c=>c.value))].map(async c=>{s.set(c,await zx(c,t,n))}));let a=o.map(c=>({reference:c,resolved:s.get(c.value)}));for(let{reference:c,resolved:d}of a){if(!d)continue;let l=zn(d,t),u=i.get(l)??{path:d.path,scope:d.scope,sourceFields:new Set,originalPaths:new Set,sourceCount:0};u.sourceFields.add(c.field),u.originalPaths.add(c.value),u.sourceCount+=1,i.set(l,u)}return[...i.entries()].map(([c,d])=>({path:d.path,scope:d.scope,status:r.has(c)?"already_linked":"addable",source_count:d.sourceCount,source_fields:[...d.sourceFields].sort((l,u)=>l.localeCompare(u)),original_paths:[...d.originalPaths].sort((l,u)=>l.localeCompare(u))})).sort((c,d)=>{let l=c.status.localeCompare(d.status);if(l!==0)return l;let u=c.path.localeCompare(d.path);return u!==0?u:c.scope.localeCompare(d.scope)})}async function Dy(e,t,n){let r=await Wo(e,t,n,{metadataKey:"files",op:"files_add",bareNoun:"file",supportsAppendStable:!0});return zo(r,"files")}async function Hx(e,t){let n=await Ho(t),r=await Promise.all(e.map(async o=>{let s=o.trim();if(!s)throw new p("Files lookup paths must not be empty.",m.USAGE);if(!Be.isAbsolute(s))return bt(s);let a=await Ho(s);return Fa(n,a)?bt(Be.relative(n,a)):bt(a)})),i=[...new Set(r)].sort((o,s)=>o.localeCompare(s));if(i.length===0)throw new p("Files lookup requires at least one path.",m.USAGE);return i}function Vx(e){for(let[r,i]of[["limit",e.limit],["offset",e.offset]])if(i!==void 0&&(!Number.isInteger(i)||i<0))throw new p(`Files lookup ${r} must be a non-negative integer.`,m.USAGE);let{offset:t=0,limit:n=50}=e;return{offset:Math.max(0,Math.floor(t)),limit:e.noTruncate?void 0:Math.max(0,Math.floor(n))}}function $y(e){return{id:e.id,title:e.title,type:e.type,status:e.status,priority:e.priority,updated_at:e.updated_at}}function Ny(e,t){let n=e.item.priority-t.item.priority;if(n!==0)return n;let r=t.item.updated_at.localeCompare(e.item.updated_at);return r===0?e.item.id.localeCompare(t.item.id):r}function Yx(e){return e.metadata.map(t=>({item:t,files:(t.files??[]).filter(n=>e.paths.includes(bt(n.path))&&(e.scope===void 0||n.scope===e.scope)).sort((n,r)=>{let i=n.path.localeCompare(r.path);return i===0?n.scope.localeCompare(r.scope):i})})).filter(t=>t.files.length>0).sort(Ny)}async function Jx(e){if(e.explain)return Oy({workspaceRoot:e.workspaceRoot,paths:e.paths,candidates:e.matching,corpus:e.metadata,...e.lineRange?{lineRange:e.lineRange}:{},...e.decisionDepth===void 0?{}:{decisionDepth:e.decisionDepth}})}async function Xx(e){if([e.strictRead,e.noTruncate,e.explain,fp()].includes(!0))return null;let t=await _o(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]);return t?Op({pmRoot:e.pmRoot,expectedSourceCursor:t.source_cursor,paths:e.paths,scope:e.scope,limit:e.limit,offset:e.offset}):null}async function Qx(e){let t=[],n=await fo(e.pmRoot,e.settings.item_format,e.typeToFolder,t,e.settings.schema),r=Yx({metadata:n,paths:e.paths,scope:e.scope}),i=t.filter(a=>/^item_list_(?:item|directory)_read_failed:/u.test(a));if(e.strictRead&&i.length>0)throw new p(`Files lookup could not read every item: ${i.join("; ")}`,m.GENERIC_FAILURE);let o=await Jx({explain:e.explain,workspaceRoot:e.workspaceRoot,paths:e.paths,matching:r,metadata:n,lineRange:e.lineRange,decisionDepth:e.decisionDepth}),s=(o?[...r].sort((a,c)=>{let d=o.explanations.get(c.item.id).score-o.explanations.get(a.item.id).score;return d!==0?d:Ny(a,c)}):r).slice(e.offset,e.limit===void 0?void 0:e.offset+e.limit);return{paths:e.paths,total:r.length,count:s.length,offset:e.offset,limit:e.limit??null,has_more:e.offset+s.length<r.length,truncated:e.offset+s.length<r.length,completeness:{status:i.length===0?"complete":"partial",source:"source_scan"},warnings:t,matches:s.map(a=>({item:$y(a.item),files:a.files,...o?{traceability:o.explanations.get(a.item.id)}:{}})),...o?{traceability_receipt:o.receipt}:{}}}async function DK(e,t){let n=R(process.cwd(),t.path),r=lt(n);await j(n);let i=await Hx(e.paths,r);if(e.lineRange&&i.length!==1)throw new p("Files lookup line attribution requires exactly one source path.",m.USAGE);let o=await x(n),s=P(o,N()),{offset:a,limit:c}=Vx(e),d=await Xx({pmRoot:n,typeToFolder:s.type_to_folder,paths:i,scope:e.scope,limit:c,offset:a,strictRead:e.strictRead===!0,noTruncate:e.noTruncate===!0,explain:e.explain===!0||e.lineRange!==void 0});return d?{paths:i,total:d.total,count:d.matches.length,offset:a,limit:c,has_more:a+d.matches.length<d.total,truncated:a+d.matches.length<d.total,completeness:{status:"unchecked",source:"index"},warnings:[],matches:d.matches.map(l=>({item:$y(l.item),files:l.files}))}:Qx({pmRoot:n,settings:o,typeToFolder:s.type_to_folder,paths:i,scope:e.scope,limit:c,offset:a,strictRead:e.strictRead===!0,workspaceRoot:r,explain:e.explain===!0||e.lineRange!==void 0,lineRange:e.lineRange,decisionDepth:e.decisionDepth})}async function $K(e,t,n){let r=R(process.cwd(),n.path),i=lt(r);await j(r);let o=await x(r),s=P(o,N()),a=await V(r,e,o.id_prefix,o.item_format,s.type_to_folder);if(!a)throw new p(`Item ${e} not found`,m.NOT_FOUND);let c=await pe(a,{schema:o.schema}),d=await Bx(c.document,i,process.cwd()),l=d.filter(C=>C.status==="addable"),u=d.filter(C=>C.status==="already_linked"),_=t.apply===!0,h=t.note?.trim()||"discovered from item text";if(!_||l.length===0){let C=c.document.metadata.files??[];return{id:a.id,files:C,changed:!1,apply:_,count:C.length,candidate_count:d.length,addable_count:l.length,added_count:0,skipped_existing_count:u.length,candidates:d,added:[],skipped_existing:u}}let f=U(t.author,o.author_default),g=l.map(C=>({path:C.path,scope:C.scope,note:h})),y=[],w=new Set,v=await he({pmRoot:r,settings:o,id:e,op:"files_discover",author:f,message:t.message??"Discover referenced file links",force:t.force,mutate(C){let O=[...C.metadata.files??[]],M=new Set(O.map(ue=>zn(ue,i)));y=[],w.clear();for(let[ue,Ne]of g.entries()){let J=zn(Ne,i);M.has(J)||(O.push(Ne),M.add(J),y.push(Ne),w.add(ue))}let T=od(O),F=t.appendStable?T:id(T);return F.length>0?C.metadata.files=F:delete C.metadata.files,{changedFields:y.length>0?["files"]:[],warnings:y.length!==g.length?[`files_discover_skipped_existing:${g.length-y.length}`]:[]}}}),k=v.item.files??[],S=new Set(y.map(C=>zn(C,i))),b=k.filter(C=>S.has(zn(C,i))),A=l.filter((C,O)=>!w.has(O)),E=[...u,...A];return{id:v.item.id,files:k,changed:b.length>0,apply:!0,count:k.length,candidate_count:d.length,addable_count:l.length,added_count:b.length,skipped_existing_count:E.length,candidates:d,added:b,skipped_existing:E}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bee6d15d-ca4a-538c-bb70-fd3dc7e2a8ec")}catch{}})();var Qr=["software-delivery","research","agent-evaluation","operations"];function My(e,t,n,r,i){return{id:e,measurement_id:t,owner_item_id:n,scope:{kind:"active"},ceiling:r,lifetime:"hold",enforcement:i,negative_control:{cases:[{observed:r,expected:"pass"},{observed:r+1,expected:"fail"}]}}}function Yo(e,t,n,r,i){let o=`preset-${e}`,s=i.map(c=>({id:`${o}-missing-${c}`,description:`Active items missing ${c} evidence.`,source:{kind:"links",link:c,state:"missing"}})),a=s.map(c=>My(`${c.id}-zero`,c.id,r,0,"warn"));return{id:e,title:t,description:n,declarations:{measurements:s,assertions:a,gates:[{id:`${o}-readiness`,description:n,assertion_ids:a.map(c=>c.id),triggers:["ci","scheduled"]}]}}}function Jo(e,t){return e==="software-delivery"?Yo(e,"Software delivery","Warn when active delivery work lacks executable tests or documentation.",t,["tests","docs"]):e==="research"?Yo(e,"Research","Warn when active research work lacks reproducibility files or documentation.",t,["files","docs"]):e==="agent-evaluation"?Yo(e,"Agent evaluation","Warn when active evaluation work lacks executable scenarios or recorded artifacts.",t,["tests","files"]):Yo(e,"Operations","Warn when active operational work lacks runbook documentation or repair evidence.",t,["docs","files"])}function Py(e,t,n,r={}){return zc(e,Jo(t,n).declarations,r)}async function Fy(e,t){let n=new Set(e.terminal_statuses??["closed","canceled"]),r={...e,items:e.items.filter(i=>!n.has(i.status))};return await Promise.all(["files","tests","docs"].map(async i=>{let o={id:`derived-active-missing-${i}`,description:`Observed active items missing ${i} evidence.`,source:{kind:"links",link:i,state:"missing"}},s=(await Wc(o,r)).value,a=My(`${o.id}-ceiling`,o.id,t,s,"observe"),c=`active-missing-${i}`;return{id:c,population_size:r.items.length,scope:{kind:"active"},observed:s,declarations:{measurements:[o],assertions:[a],gates:[{id:`derived-${c}`,description:`Observe the accepted ${i} evidence baseline.`,assertion_ids:[a.id],triggers:["ci","scheduled"]}]}}}))}function jy(e,t,n={}){return zc(e,{measurements:t.flatMap(r=>r.declarations.measurements),assertions:t.flatMap(r=>r.declarations.assertions),gates:t.flatMap(r=>r.declarations.gates)},n)}async function Uy(e,t,n,r={}){let i=t.enforcement==="observe"?"warn":"block";if(t.enforcement==="block"||n!==i)throw new TypeError(`assurance assertion ${t.id} promotion must be ${t.enforcement} -> ${i}`);return Fo(e,"assertion",{...t,enforcement:n},{...r,message:r.message??`Promote assurance assertion ${t.id} from ${t.enforcement} to ${n}`})}import Ky from"node:fs/promises";import{createRequire as Zx}from"node:module";import Ue from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="32adaa7c-f0aa-5aff-8d88-d7c0ccfbd971")}catch{}})();function Gy(e,t){let n=Ue.relative(t,e);if(n.length>0&&n!==".."&&!n.startsWith(`..${Ue.sep}`)&&!Ue.isAbsolute(n))return n.split(Ue.sep).join("/");let r=Ue.resolve(e),i=0xcbf29ce484222325n;for(let o=0;o<r.length;o+=1)i^=BigInt(r.charCodeAt(o)),i=BigInt.asUintN(64,i*0x100000001b3n);return`<external>/${i.toString(16).padStart(16,"0")}/${Ue.basename(Ue.dirname(e))}/package.json`}function eR(e){return e.includes(`${Ue.sep}.pnpm${Ue.sep}`)?"pnpm":e.includes(`${Ue.sep}node_modules${Ue.sep}`)?"npm":"other"}async function qy(e){try{let t=JSON.parse(await Ky.readFile(e,"utf8"));return t.name==="@unbrained/pm-cli"&&typeof t.version=="string"&&t.version.trim().length>0?t.version.trim():void 0}catch{return}}async function ld(e){try{return await Ky.realpath(e)}catch{return Ue.resolve(e)}}async function Wy(e,t,n=lp(import.meta.url,["../../.."])){let r=await ld(t),i=await ld(Ue.join(n,"package.json")),o=await qy(i),s=new Map;o!==void 0&&s.set(i,{version:o,path:Gy(i,r),layout:"host",consumers:["pm-cli-host"]});for(let d of e)try{let l=Zx(d.entry_path).resolve("@unbrained/pm-cli/package.json"),u=await ld(l),_=await qy(u);if(_===void 0)continue;let h=u,f=s.get(h);if(f){f.consumers.includes(d.name)||(f.consumers.push(d.name),f.consumers.sort((g,y)=>g.localeCompare(y)));continue}s.set(h,{version:_,path:Gy(u,r),layout:eR(u),consumers:[d.name]})}catch{}let a=[...s.values()].sort((d,l)=>d.path.localeCompare(l.path)),c=o===void 0?[]:a.filter(d=>d.version!==o);return{host_version:o??null,copies:a,mismatches:c,warnings:c.map(d=>`extension_host_pm_cli_version_skew:${o}:${d.version}:${d.consumers.join("+")}`)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c3200eea-d2c8-5813-87e8-df765f7b6c7a")}catch{}})();var zy=25;function tR(e,t,n=[]){let r=["list","--status",e,...n],i=["--assignee-filter","unassigned"],o=["--updated-before",`-${t}h`];return{unowned:L([...r,...i]),idle:L([...r,...o]),stale:L([...r,...i,...o])}}function By(e,t){let n=e.items.length>zy;return{count:e.count,items:e.items.slice(0,zy),...n?{truncated:!0}:{},sweep:t}}function Hy(e,t,n=[]){let r=tR(t.in_progress,e.threshold_hours,n),i=(s,...a)=>`pm ${s} <id>${[...a,...n].map(c=>` ${fm(c)}`).join("")}`,o=[...e.unowned.count>0?[`in_progress_unowned:${e.unowned.count}`]:[],...e.idle.count>0?[`in_progress_idle:${e.idle.count}`]:[]];return{warnings:o,details:o.length===0?void 0:{threshold_hours:e.threshold_hours,threshold_setting:"mutation_guard.stale_in_progress_hours",unowned:By(e.unowned,r.unowned),idle:By(e.idle,r.idle),item_remedies:{claim:i("claim"),take_over_idle:i("claim","--takeover-stale"),return_to_open:i("update","--status",t.open)}},remediation:{stale_in_progress_items:r.stale,in_progress_unowned:r.unowned,in_progress_idle:r.idle}}}import{createHash as nR}from"node:crypto";import Xo from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="36749195-9194-546a-bc3e-718f09c3b8d6")}catch{}})();var rR="2026-08-09T16:15:18.000Z",Yy=Symbol("pre-durable-disposition-eligible");function kt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ud(e){if(!Array.isArray(e)||e.length>256)return!1;let t=new Set;for(let n=0;n<e.length;n+=1){let r=e[n];if(!(n in e)||typeof r!="string"||r.length===0||r.length>256||r.includes("\0")||t.has(r))return!1;t.add(r)}return!0}function Vy(e){return kt(e)?typeof e.field=="string"&&e.field.length>0&&e.field.length<=256&&!e.field.includes("\0")&&typeof e.retained_hash=="string"&&/^[a-f0-9]{64}$/u.test(e.retained_hash)&&typeof e.discarded_hash=="string"&&/^[a-f0-9]{64}$/u.test(e.discarded_hash):!1}function Jy(e,t){if(typeof e!="string")return!1;let n=Xo.posix.normalize(e);return e.length<=4096&&!e.includes("\\")&&!e.includes("\0")&&!Xo.posix.isAbsolute(e)&&n===e&&!n.startsWith("../")&&(Xo.posix.basename(n)===`${t}.toon`||Xo.posix.basename(n)===`${t}.md`)}function iR(e,t){return typeof e.receipt_id=="string"&&Pr(e.receipt_id)&&(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0&&e.conflict_resolution===void 0&&e.item_id===t&&Jy(e.item_path,t)}function Xy(e){let t=e.conflict_fields,n=e.fields_from_theirs,r=e.union_fields,i=e.decisions,o=Array.isArray(i)?new Set(i.flatMap(s=>Vy(s)?[s.field]:[])):new Set;return ud(t)&&ud(n)&&ud(r)&&Array.isArray(i)&&i.length>0&&i.length<=256&&Object.keys(i).length===i.length&&i.every(Vy)&&o.size===i.length&&t.length===o.size&&t.every(s=>o.has(s))}function oR(e,t){return iR(e,t)&&Xy(e)}function sR(e,t){return typeof e.receipt_id=="string"&&Pr(e.receipt_id)&&(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0&&(e.conflict_resolution==="preferred_side"||e.conflict_resolution==="stable_value_order")&&e.item_id===t&&Jy(e.item_path,t)&&Xy(e)}function aR(e){return e[Yy]===!0}function Qy(e,t){if(!kt(e)||!kt(e.context))return[];let n=e.context.merge;return!kt(n)||!Array.isArray(n.receipts)?[]:n.receipts.flatMap(r=>!kt(r)||typeof r.receipt_id!="string"||r.receipt_id.trim().length===0?[]:[{receiptId:r.receipt_id,legacySummaryAccepted:oR(r,t),[Yy]:sR(r,t),...typeof e.ts=="string"&&qa(e.ts)?{eventTimestamp:e.ts}:{}}])}function Zy(e,t,n){if(!kt(e)||e.op!=="merge_reconcile")return[];if(!kt(e.context)||!kt(e.context.merge))return[];let r=e.context.merge.missing_receipt_dispositions;return!Array.isArray(r)||r.length>256?[]:r.flatMap(i=>!kt(i)||typeof i.receipt_id!="string"||!Pr(i.receipt_id)||typeof i.original_history_line!="number"||!Number.isSafeInteger(i.original_history_line)||i.original_history_line<1||typeof i.original_event_ts!="string"||!qa(i.original_event_ts)||i.reason!=="legacy_clone_local_only"?[]:[{itemId:t,receiptId:i.receipt_id,originalHistoryLine:i.original_history_line,originalEventTimestamp:i.original_event_ts,auditHistoryLine:n,reason:i.reason}])}function ew(e,t,n=[]){let r=new Map;for(let o of n){let s=`${o.itemId}\0${o.originalHistoryLine}\0${o.receiptId}\0${o.originalEventTimestamp}`;r.set(s,Math.max(r.get(s)??0,o.auditHistoryLine))}let i=o=>aR(o)&&o.eventTimestamp!==void 0&&Wi(o.eventTimestamp,rR)<0&&(r.get(`${o.itemId}\0${o.line}\0${o.receiptId}\0${o.eventTimestamp}`)??0)>o.line;return{missing:e.filter(o=>!o.legacySummaryAccepted&&!t.has(o.receiptId)&&!i(o)).map(o=>({item_id:o.itemId,history_line:o.line,...Pr(o.receiptId)?{receipt_id:o.receiptId}:{receipt_reference_hash:nR("sha256").update(o.receiptId).digest("hex")}})),acceptedLegacyCount:e.filter(o=>o.legacySummaryAccepted).length,acceptedDispositionCount:e.filter(i).length}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d8f1968e-a030-5a3c-b766-60a409163745")}catch{}})();function Qo(e,t,n=25){let r=e.definitions.filter(s=>s.roles.length===0).map(s=>s.id).sort((s,a)=>s.localeCompare(a)),i=new Set(r),o=t.filter(s=>{let a=Je(s.status,e);return a!==void 0&&i.has(a)}).map(s=>s.id).sort((s,a)=>s.localeCompare(a));return{roleless_status_count:r.length,roleless_statuses:r.slice(0,n),roleless_statuses_truncated:r.length>n,affected_item_count:o.length,affected_item_ids:o.slice(0,n),affected_item_ids_truncated:o.length>n}}function Zo(e){return e.roleless_status_count===0?[]:[`schema_status_missing_lifecycle_role:${e.roleless_status_count}`]}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1b5c9f97-33fb-5318-8bec-3aa033ef7c25")}catch{}})();var nw=8,md=100;function rw(e,t){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function Qe(e,t){return Array.isArray(e)?{count:e.length,sample:e.slice(0,t),truncated:e.length>t}:{count:0,sample:[],truncated:!1}}function cR(e){if(typeof e!="object"||e===null||Array.isArray(e))return{};let t=e;return{layer:t.layer,directory:t.directory,name:t.name,version:t.version,enabled:t.enabled,status:t.status,has_activate:t.has_activate,capabilities:t.capabilities}}function Zr(e,t){let n=Qe(e,t);return{...n,sample:n.sample.map(r=>cR(r))}}function B(e,t){if(!Array.isArray(e))return{count:0,sample:[],truncated:!1};let n=e.filter(r=>typeof r=="string");return{count:n.length,sample:n.slice(0,t),truncated:n.length>t}}function dR(e){if(typeof e!="object"||e===null)return null;let t=e;return{applied_count:t.applied_count,pending_count:t.pending_count,failed_count:t.failed_count}}var lR={settings:(e,t)=>({version:e.version,id_prefix:e.id_prefix,locks_ttl_seconds:e.locks_ttl_seconds,warnings:B(e.warnings,t)}),directories:(e,t)=>({required_count:Array.isArray(e.required)?e.required.length:0,optional_count:Array.isArray(e.optional)?e.optional.length:0,missing_required:B(e.missing_required,t),missing_optional:B(e.missing_optional,t),missing:B(e.missing,t),strict_directories:e.strict_directories}),settings_values:(e,t)=>({warnings:B(e.warnings,t)}),telemetry:e=>({enabled:e.enabled,capture_level:e.capture_level,endpoint:e.endpoint,queue_exists:e.queue_exists,queue_entries:e.queue_entries,queue_draining:e.queue_draining,queue_invalid_rows:e.queue_invalid_rows,queue_rows_total:e.queue_rows_total,last_successful_flush_at:e.last_successful_flush_at,last_failed_flush_at:e.last_failed_flush_at,endpoint_probe:e.endpoint_probe,env_overrides:e.env_overrides}),extensions:(e,t)=>{let n=typeof e.activation=="object"&&e.activation!==null?e.activation:{};return{disabled_by_flag:e.disabled_by_flag,discovered:Zr(e.discovered,t),effective:Zr(e.effective,t),loaded:Zr(e.loaded,t),failed:Qe(e.failed,t),warnings:B(e.warnings,t),activation:{failed:Qe(n.failed,t),warnings:B(n.warnings,t),hook_counts:n.hook_counts,command_handler_count:n.command_handler_count,service_override_count:n.service_override_count,renderer_override_count:n.renderer_override_count,registration_counts:n.registration_counts,migration_status:dR(n.migration_status)},author_manifest:e.author_manifest,triage:e.triage,capability_contract:e.capability_contract,capability_guidance:Qe(e.capability_guidance,t),host_version_census:e.host_version_census}},storage:(e,t)=>{let n=typeof e.author_attribution=="object"&&e.author_attribution!==null?e.author_attribution:void 0;return{...e,...n?{author_attribution:{...n,affected_item_ids:B(n.affected_item_ids,t),samples:Qe(n.samples,t)}}:{}}},locks:e=>({active_lock_count:e.active_lock_count,stale_lock_count:e.stale_lock_count,unreadable_lock_count:e.unreadable_lock_count,unparseable_lock_count:e.unparseable_lock_count}),integrity:(e,t)=>{let n=typeof e.tracked_runtime_cache=="object"&&e.tracked_runtime_cache!==null?e.tracked_runtime_cache:void 0;return{checked_item_files:e.checked_item_files,checked_history_streams:e.checked_history_streams,counts:e.counts,item_unreadable:B(e.item_unreadable,t),item_conflict_markers:Qe(e.item_conflict_markers,t),item_parse_failures:B(e.item_parse_failures,t),tracked_runtime_cache:n===void 0?e.tracked_runtime_cache:{...n,tracked_paths:B(n.tracked_paths,t)},history_unreadable:B(e.history_unreadable,t),history_conflict_markers:Qe(e.history_conflict_markers,t),history_invalid_json:Qe(e.history_invalid_json,t),skipped:e.skipped}},history_drift:(e,t)=>{let n=typeof e.cache_confirmation=="object"&&e.cache_confirmation!==null?e.cache_confirmation:void 0;return{checked_items:e.checked_items,cache_hit_verification:e.cache_hit_verification,cache_confirmation:n===void 0?e.cache_confirmation:{...n,candidate_items:B(n.candidate_items,t),confirmed_items:B(n.confirmed_items,t),resolved_false_positive_items:B(n.resolved_false_positive_items,t)},counts:e.counts,drifted_items:B(e.drifted_items,t),merge_receipt_attributed_items:B(e.merge_receipt_attributed_items,t),missing_streams:B(e.missing_streams,t),unreadable_streams:B(e.unreadable_streams,t),hash_mismatches:B(e.hash_mismatches,t),chain_mismatches:B(e.chain_mismatches,t),version_skews:B(e.version_skews,t),workspace_state_mismatches:B(e.workspace_state_mismatches,t),workspace_state_missing:B(e.workspace_state_missing,t),workspace_state_unreadable:B(e.workspace_state_unreadable,t),skipped:e.skipped}},vectorization:(e,t)=>({semantic_runtime_available:e.semantic_runtime_available,compatibility_mode_auto_defaults:e.compatibility_mode_auto_defaults,auto_ollama_defaults_applied:e.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:e.auto_ollama_defaults_skipped_reason,auto_ollama_defaults_remediation:e.auto_ollama_defaults_remediation,refresh_policy:e.refresh_policy,provider_active:e.provider_active,vector_store_active:e.vector_store_active,items:e.items,ledger_entries_before:e.ledger_entries_before,stale_items_before_total:e.stale_items_before_total,stale_items_before:B(e.stale_items_before,t),refresh_attempted:e.refresh_attempted,refresh_skipped_reason:e.refresh_skipped_reason,refresh_result:e.refresh_result,ledger_entries_after:e.ledger_entries_after,stale_items_after_total:e.stale_items_after_total,stale_items_after:B(e.stale_items_after,t),skipped:e.skipped})};function pd(e,t){let n=lR[e.name];return n?n(e.details,t):e.details}function iw(e){return{disabled_by_flag:e.details.disabled_by_flag,loaded_count:Array.isArray(e.details.loaded)?e.details.loaded.length:0,failed_count:0,warning_count:0,restore_with:"pm health --full"}}function uR(e){if(e.name==="extensions"&&e.status==="ok")return iw(e);let t=pd(e,8);return Buffer.byteLength(JSON.stringify(t))<Buffer.byteLength(JSON.stringify(e.details))?t:e.details}function _d(e,t){let n=new Set([...t,...e.failed_because]);return(e.findings??[]).filter(r=>n.has(r.warning))}function mR(e){let t=B(e.warnings,8);return{ok:e.ok,...e.verdict?{verdict:e.verdict}:{},checks:e.checks.map(n=>({name:n.name,status:n.status,ok:n.ok,details:uR(n)})),warnings:t.sample,findings:_d(e,t.sample),failed_because:e.failed_because,projection:{mode:"brief",warning_count:t.count,warnings_truncated:t.truncated,detail_limit:8},generated_at:e.generated_at}}function tw(e){return e.details.skipped===!0}function pR(e){let t=B(e.warnings,8),n=e.checks.filter(tw).map(r=>r.name);return{ok:e.ok,...e.verdict?{verdict:e.verdict}:{},checks:e.checks.filter(r=>!tw(r)).map(r=>({name:r.name,status:r.status,ok:r.ok,details:{}})),warning_count:t.count,warnings:t.sample,findings:_d(e,t.sample),failed_because:e.failed_because,projection:{mode:"summary",warning_count:t.count,warnings_truncated:t.truncated,detail_limit:8,omitted_checks:n},generated_at:e.generated_at}}function _R(e,t,n){return n?pR(e):t.brief===!0?mR(e):t.full===!0?e:{...e,checks:e.checks.map(r=>r.name==="extensions"&&r.status==="ok"?{...r,details:iw(r)}:r),projection:{mode:"standard",warning_count:e.warning_count,warnings_truncated:e.warnings_truncated===!0,detail_limit:8}}}function fd(e,t,n){let r=e.warning_count??e.warnings.length,i=e.warnings.slice(0,100),o={...e,warning_count:r,warning_limit:100,warnings_truncated:r>100,warnings:i,findings:_d(e,i)},s=_R(o,t,n);return{...s,warning_count:r,warning_limit:100,warnings_truncated:r>s.warnings.length,...s.projection?{projection:{...s.projection,warning_count:r,warnings_truncated:r>s.warnings.length}}:{}}}import St from"node:fs/promises";import ge from"node:path";import Bn from"node:fs/promises";import ei from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b01042e0-77ae-5e2c-8118-6680f0002d60")}catch{}})();function ow(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t,{id:r,owner:i,created_at:o,ttl_seconds:s}=n;return typeof r!="string"||typeof i!="string"||typeof o!="string"||typeof s!="number"||!Number.isFinite(s)?null:{id:r,owner:i,created_at:o,ttl_seconds:s,pid:n.pid,host_identity:n.host_identity,process_start_identity:n.process_start_identity}}function fR(e,t,n){let r=ow(t);if(r===null)return{detail:"unparseable_json",entry:{file:e,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"}};let i=Date.parse(r.created_at);if(!Number.isFinite(i))return{detail:"invalid_timestamp",entry:{file:e,id:r.id,owner:r.owner,created_at:r.created_at,ttl_seconds:r.ttl_seconds,age_seconds:null,stale:!1,reason:"unparseable"}};let o=n-i,s=Math.floor(o/1e3),a=o>r.ttl_seconds*1e3;return{detail:a?"expired":"active",entry:{file:e,id:r.id,owner:r.owner,created_at:r.created_at,ttl_seconds:r.ttl_seconds,age_seconds:s,stale:a,reason:a?"expired":"active"}}}async function sw(e,t,n){let r=fR(e,t,n);if(r.detail!=="active")return r;let i=ow(t),o=await Um(i);return o==="unknown"?r:{detail:o==="dead"?"owner_dead":"active",entry:{...r.entry,owner_state:o,pid:i.pid,...o==="dead"?{stale:!0,reason:"owner_dead"}:{}}}}async function hR(e,t,n){let r=await qm(e,"gc");if(r===null)return!1;try{let i;try{i=await Bn.readFile(e,"utf8")}catch(o){if(G(o))return!0;throw o}if(i!==t)return!1;n&&await Km(e,t);try{await Bn.unlink(e)}catch(o){if(!G(o))throw o}return!0}finally{await r()}}function gR(e,t,n){t==="owner_dead"&&(e.owner_dead_lock_samples??=[],e.owner_dead_lock_samples.length<20&&e.owner_dead_lock_samples.push(n)),t==="active"?e.active_lock_count+=1:t==="expired"||t==="owner_dead"?e.stale_lock_count+=1:e.unparseable_lock_count+=1}async function aw(e,t){let n=t??Date.now(),r=ei.join(e,"locks"),i={scanned:0,active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0},o;try{o=(await Bn.readdir(r)).filter(s=>s.endsWith(".lock")).sort()}catch(s){if(G(s))return i;throw s}for(let s of o){let a;try{a=await Bn.readFile(ei.join(r,s),"utf8")}catch(l){if(G(l))continue;i.scanned+=1,i.unreadable_lock_count+=1;continue}i.scanned+=1;let{detail:c,entry:d}=await sw(s,a,n);gR(i,c,d)}return i}async function yR(e,t,n,r,i,o,s){if(!t.dryRun){try{if(!await hR(n,o,s.reason==="owner_dead")){e.warnings.push(`lock_changed_or_busy:${i}`),e.retained.push(r),e.entries.push(s);return}}catch{e.warnings.push(`lock_remove_failed:${i}`),e.retained.push(r),e.entries.push(s);return}if(t.hooks?.onWrite){let a=await t.hooks.onWrite(n);e.warnings.push(...a)}}e.removed.push(r),e.entries.push(s)}async function cw(e,t){let{hooks:n}=t,r=t.now??Date.now(),i=ei.join(e,"locks"),o={scanned:0,removed:[],retained:[],warnings:[],entries:[]};await jm(e,ei.join(i,"gc.lock"),"gc");let s;try{s=(await Bn.readdir(i)).filter(a=>a.endsWith(".lock")).sort()}catch(a){if(G(a))return o;throw a}for(let a of s){o.scanned+=1;let c=ei.join(i,a),d=`locks/${a}`;if(n?.onRead){let _=await n.onRead(c);o.warnings.push(..._)}let l;try{l=await Bn.readFile(c,"utf8")}catch(_){if(G(_)){o.scanned-=1;continue}o.warnings.push(`lock_unreadable:${a}`),o.retained.push(d),o.entries.push({file:a,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let u=await sw(a,l,r);if(u.detail==="unparseable_json"){o.warnings.push(`lock_unparseable:${a}`),o.retained.push(d),o.entries.push(u.entry);continue}if(u.detail==="invalid_timestamp"){o.warnings.push(`lock_invalid_timestamp:${a}`),o.retained.push(d),o.entries.push(u.entry);continue}if(u.detail==="active"){o.retained.push(d),o.entries.push(u.entry);continue}await yR(o,t,c,d,a,l,u.entry)}return o}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f9317f5b-f007-5882-aafe-898d1f76f2ae")}catch{}})();var wR=Object.freeze([{code:"missing_directory",command:"pm init",summary:"Recreate missing tracker directories (pm init is idempotent and restores the scaffold)."},{code:"settings_read_fs_error",command:"pm config list --json",summary:"settings.json could not be read as a regular file and pm fell back to defaults; repair the reported path or permissions, then re-run."},{code:"settings_read_invalid_json",command:"pm config list --json",summary:"settings.json is not valid JSON and pm fell back to defaults; fix the syntax error in the reported path, then re-run."},{code:"settings_read_invalid_schema",command:"pm config list --json",summary:"settings.json failed schema validation and pm fell back to defaults; correct the reported key in the file, then re-run."},{code:"settings_read_merge_failed",command:"pm config list --json",summary:"Global/project settings could not be merged; reconcile the conflicting keys in the reported settings files."},{code:"settings:id_prefix_empty",command:"pm config list --json",summary:'id_prefix is empty; set a non-empty "id_prefix" in settings.json so generated item ids are well-formed.'},{code:"settings:locks_ttl_non_positive",command:"pm config list --json",summary:'locks.ttl_seconds must be positive; set a positive "locks.ttl_seconds" in settings.json.'},{code:"telemetry_state_invalid_json",command:"pm health --check-telemetry",summary:"Local telemetry state file is corrupt; pm recreates it on the next flush. Advisory only."},{code:"telemetry_queue_invalid_rows",command:"pm health --check-telemetry",summary:"The telemetry queue has unparseable rows; they are skipped on the next flush. Advisory only."},{code:"telemetry_queue_pending",command:"pm health --check-telemetry",summary:"Telemetry events are queued; they flush automatically on the next reachable command. Advisory only."},{code:"telemetry_queue_high_retries",command:"pm telemetry flush",summary:"Some queued telemetry events are near retry exhaustion; flush now and verify endpoint reachability before entries are dropped."},{code:"telemetry_endpoint_probe_failed",command:"pm health --check-telemetry",summary:"The telemetry endpoint is unreachable; events stay queued until it recovers. Advisory only."},{code:"telemetry_endpoint_probe_http_status",command:"pm health --check-telemetry",summary:"The telemetry endpoint returned a non-success status; events stay queued until it recovers. Advisory only."},{code:"telemetry_schema_version_behind",command:"pm health --check-telemetry",summary:"Client schema is behind server; upgrade pm-cli to emit the latest event shape."},{code:"telemetry_otel_export_failing",command:"pm health --check-telemetry",summary:"OTLP trace spans are queued but the traces endpoint export is failing; spans retry automatically on the next reachable command, or set PM_TELEMETRY_OTEL_DISABLED=1 to skip OTLP export. Advisory only."},{code:"merge_driver_configuration_missing",command:"pm merge install",summary:"Install the clone-local Git drivers required by the tracker merge fence."},{code:"merge_driver_configuration_drift",command:"pm merge install",summary:"Reinstall clone-local Git drivers after runtime or package paths change."},{code:"merge_fence_missing",command:"pm merge install",summary:"Install the active tracker's committed Git merge attributes."},{code:"merge_fence_drift",command:"pm merge install",summary:"Restore the active tracker's merge mappings while retaining sibling tracker fences."},{code:"validate_merge_driver_configuration",command:"pm merge install",summary:"Restore missing or drifted clone-local Git merge driver commands."},{code:"integrity_item_unreadable",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file could not be read; restore or repair the file at the reported path."},{code:"integrity_item_parse_failed",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file failed to parse; fix the malformed item metadata at the reported path."},{code:"integrity_item_conflict_marker",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file contains Git conflict markers; resolve the <<<<<<< / >>>>>>> markers at the reported line."},{code:"integrity_history_unreadable",command:"pm history-repair <id>",summary:"A history stream could not be read; re-anchor the affected item's history chain."},{code:"integrity_history_invalid_json",command:"pm history-repair <id>",summary:"A history stream contains invalid JSON; re-anchor the affected item's history chain."},{code:"integrity_history_conflict_marker",command:"pm history-repair <id>",summary:"A history stream contains Git conflict markers; resolve the markers, then re-anchor the chain."},{code:"validate_storage_unreadable_items",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"An on-disk item file cannot be parsed (for example a botched merge resolution with stale TOON count headers); repair or restore the file at the reported path \u2014 list commands silently skip it while pm get hard-errors."},{code:"validate_storage_duplicate_item_ids",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"One item id is claimed by multiple item documents \u2014 usually two branches minting the same id for different items before merging (GH-600). Keep one document, recreate the other item under a fresh id (pm copy, then delete the colliding file), and consider raising ids.token_length for concurrent multi-agent work."},{code:"validate_storage_history_conflict_markers",command:"pm merge driver history <base> <ours> <theirs>",summary:"A history stream contains unresolved Git conflict markers; re-merge it with the pm history merge driver (or resolve the markers by hand), then run pm history-repair for the item."},{code:"validate_storage_unparseable_history",command:"pm history-repair <id>",summary:"A history stream's newest line is not valid JSONL; repair or restore the stream before further mutations."},{code:"validate_storage_resurrected_items",command:"pm delete <id>",summary:"A live item's newest history operation is a delete: a delete/modify merge silently resurrected it. Decide the winner \u2014 re-delete the item, or keep it and append a mutation documenting the revival."},{code:"validate_storage_unparseable_config",command:"pm merge driver json <base> <ours> <theirs>",summary:"settings.json or a schema file cannot be parsed, so pm silently falls back to defaults; re-merge it with the pm JSON merge driver or fix the file by hand, then rerun pm validate."},{code:"validate_merge_fence_drift",command:"pm merge install",summary:"The committed .gitattributes merge fence no longer matches the active schema's type folders or tracker JSONL stores; rerun pm merge install (and commit .gitattributes) so every tracker artifact keeps its field-aware merge driver."},{code:"validate_storage_tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command, commit the index-only removals and managed .gitignore fence, then rerun validation."},{code:"integrity_item_outdated_format_version",command:"pm validate --verbose-diagnostics",summary:"An item predates the current storage format version; a pm storage migration rewrites it. Use --verbose-diagnostics to list the affected items."},{code:"integrity_item_ahead_format_version",command:"npm install -g @unbrained/pm-cli@latest",summary:"An item was written by a newer pm format version than this runtime supports; upgrade pm to read and validate it safely."},{code:"tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command from the integrity check, commit the index-only removals, and keep the managed .gitignore fence."},{code:"merge_artifacts_ignored",command:"pm health --check-only --full",summary:"Remove or narrow the owning ignore rules listed in integrity.ignored_merge_artifacts. Merge receipts must be committed with their audit history; preserve those files, then preview pm merge reconcile --stage --dry-run before applying settlement."},{code:"merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:'Review pending receipt summaries, re-apply intended discarded values, then run pm merge reconcile. If proof is unavailable or receipt decisions are lossy, explicit review authority is required for pm merge reconcile --force --message "<reviewed receipt disposition and rationale>"; this records acceptance rather than restoring discarded values.'},{code:"merge_receipts_pending",command:"pm merge reconcile",summary:'A lossless receipt is pending; preview with pm merge reconcile --dry-run, then apply. If no receipt set proves the snapshot, review the summaries and only with explicit authority run pm merge reconcile --force --message "<reviewed receipt disposition and rationale>" to record an audited acceptance.'},{code:"merge_receipt_evidence_invalid",command:"pm merge report --include-reconciled --json",summary:"One or more receipt candidates failed bounded-file, schema, identity, or copy-consistency validation; inspect the report's privacy-safe source, receipt id, and reason before repairing only the named evidence."},{code:"merge_receipt_history_reference_missing",command:"pm merge reconcile --dry-run",summary:"Review the bounded coordinates and recover available evidence first; for exact pre-durable clone-local-only references, rerun with --force so pm appends an audited disposition and proves the health finding is cleared without rewriting history."},{code:"validate_merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:"Review the pending merge receipts before reconciliation; history-repair alone does not settle them, and lossy receipts require explicit --force acceptance."},{code:"history_drift_missing_stream",command:"pm history-repair <id>",summary:"The item has no history stream; re-anchor the chain to rebuild it (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_unreadable_stream",command:"pm history-repair <id>",summary:"The item's history stream is unreadable; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_hash_mismatch",command:"pm history-repair <id>",summary:"The item's content hash no longer matches its history; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_chain_mismatch",command:"pm history-repair <id>",summary:"The item's history chain is broken; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_version_skew",command:"npm install -g @unbrained/pm-cli@latest",summary:"A history stream declares an item hash version this runtime does not support; upgrade pm to verify the chain instead of re-anchoring it."},{code:"history_drift_merge_receipt",command:"pm merge reconcile",summary:"Canonical path, changed-field, and merged-value hash evidence attributes this drift to a pending receipt; run reconciliation (optionally preview first with --dry-run) instead of repairing history directly."},{code:"history_stream_over_compact_threshold",command:"pm history-compact <id>",summary:"The history stream exceeds the configured compaction threshold; compact it (pm history-compact --all-streams sweeps every over-threshold stream in one pass)."},{code:"stale_in_progress_items",command:"pm list --status in_progress --assignee-filter unassigned --updated-before -72h",summary:"List unowned in-progress candidates idle past mutation_guard.stale_in_progress_hours by metadata time (pm health substitutes the configured status id and threshold); claim each with pm claim <id> or return it to open with pm update <id> --status open."},{code:"in_progress_unowned",command:"pm list --status in_progress --assignee-filter unassigned",summary:"List in-progress items nobody holds (pm health substitutes the configured status id); claim each with pm claim <id> or return it to open with pm update <id> --status open."},{code:"in_progress_idle",command:"pm list --status in_progress --updated-before -72h",summary:"List in-progress candidates not updated within mutation_guard.stale_in_progress_hours (pm health substitutes the configured status id and threshold; a restored item can appear although its history is recent); resume, release or return each one, or take another holder's with pm claim <id> --takeover-stale, which re-judges under the item lock."},{code:"history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"provenance_value_domain_invalid",command:"pm history-repair --all --normalize-provenance",summary:"Remove invalid bounded provenance observations from affected streams and append privacy-safe aggregate repair receipts."},{code:"validate_history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"locks_stale_count",command:"pm gc --scope locks",summary:"Stale item-claim locks (embedded ttl elapsed) can block mutations; sweep them \u2014 gc retains active and unparseable locks."},{code:"locks_unreadable",command:"pm gc --scope locks --dry-run",summary:"Some lock files could not be read; preview the sweep and inspect the unreadable files manually \u2014 gc never deletes what it cannot read."},{code:"extension_update_health_partial_coverage",command:"pm extension --adopt-all --project",summary:"Update-health coverage is partial because unmanaged extensions were skipped; adopt the existing installs into managed metadata so the update scan covers them (use --global for global-scope extensions, or pm package --adopt-all when working with packages)."},{code:"vectorization_stale_items_remaining",command:"pm health --refresh-vectors",summary:"Some items have stale embeddings; refresh vectors so semantic search results stay current."},{code:"vectorization_embedding_identity_changed",command:"pm reindex --mode semantic",summary:"Embedding provider/model changed since the last index; run a semantic reindex to rebuild vectors."},{code:"validate_metadata_missing_closed_at",command:"pm validate --check-metadata --auto-fix --fix-scope timestamps --dry-run",summary:"Preview closure dates proven by verified lifecycle history; inspect residuals and omit --dry-run to apply only proven dates."},{code:"validate_metadata_missing_acceptance_criteria",command:'pm update <id> --acceptance-criteria "<criteria>"',summary:"Backfill the missing acceptance criteria on the reported item(s)."},{code:"validate_metadata_missing_estimate",command:'pm update <id> --estimate "<estimate>"',summary:"Backfill the missing estimate on the reported item(s)."},{code:"validate_metadata_missing_close_reason",command:'pm update <id> --close-reason "<reason>"',summary:"Backfill the missing close reason on the reported closed item(s)."},{code:"validate_metadata_missing_reviewer",command:'pm update <id> --reviewer "<name>"',summary:"Backfill the missing reviewer on the reported item(s)."},{code:"validate_metadata_missing_risk",command:'pm update <id> --risk "<level>"',summary:"Backfill the missing risk on the reported item(s)."},{code:"validate_metadata_missing_confidence",command:'pm update <id> --confidence "<level>"',summary:"Backfill the missing confidence on the reported item(s)."},{code:"validate_metadata_missing_sprint",command:'pm update <id> --sprint "<sprint>"',summary:"Backfill the missing sprint on the reported item(s)."},{code:"validate_metadata_missing_release",command:'pm update <id> --release "<release>"',summary:"Backfill the missing release on the reported item(s)."},{code:"validate_metadata_custom_profile_missing_required_fields",command:'pm config set metadata-required-fields --criterion "<field>"',summary:"Config-driven finding: the custom metadata profile has no required fields configured and falls back to core, so configure the fields rather than mutating items."},{code:"validate_metadata_duplicate_issue_codes",command:'pm update <id> --title "<distinct title>"',summary:"Two or more items share one logical issue code (GH-235); give each a distinct title so the derived code is unique, or close the redundant item with pm close <id> --duplicate-of <canonical-id> (closed-as-duplicate items are excluded from the check)."},{code:"validate_resolution_missing_fields",command:'pm update <id> --resolution "<how resolved>"',summary:"Backfill resolution / expected_result / actual_result on the reported closed item(s)."},{code:"validate_lifecycle_active_closure_like_metadata",command:"pm update <id> --unset <closure-like-field>",summary:"Clear the closure-like field the validator flags on this active item \u2014 the detail row names it (resolution / actual-result / blocked-reason) \u2014 or close the item if it is actually done."},{code:"validate_lifecycle_active_terminal_parent",command:"pm update <id> --parent <active-parent-id>",summary:"Reopen the terminal parent or move the active child under a non-terminal parent."},{code:"validate_lifecycle_stale_blockers",command:"pm update <id> --unset blocked-by --unset blocked-reason",summary:"Resolve the stale blocker the validator flags: clear blocked-by/blocked-reason when they linger on a non-blocked item or report a resolved blocker; if instead a blocked item is missing blocker context, add the context or move it out of a blocked status."},{code:"validate_lifecycle_dependency_cycles_error",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_lifecycle_dependency_cycles",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_hierarchy_parent_cycle_error",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_hierarchy_parent_cycle",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_files_missing_linked_paths",command:"pm <files|docs> <id> --remove <path>",summary:"The check spans both item.files and item.docs under one code: restore the missing linked artifact, or unlink it with pm files (linked file) or pm docs (linked doc)."},{code:"validate_files_orphaned_paths",command:"pm <files|docs> <id> --add <path>",summary:"Link the orphaned artifact with pm files (file) or pm docs (doc), or remove it from the workspace."},{code:"validate_files_tracked_all_strict_forces_pm_internals",command:"pm validate --check-files --include-pm-internals",summary:"tracked-all-strict scan flagged pm internals; re-run with --include-pm-internals or a softer --scan-mode."},{code:"validate_history_drift_missing_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items missing a history stream."},{code:"validate_history_drift_unreadable_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with an unreadable history stream."},{code:"validate_history_drift_hash_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items whose content hash drifted."},{code:"validate_history_drift_chain_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with a broken history chain."},{code:"validate_history_drift_version_skews",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more history streams declare an item hash version this runtime does not support; upgrade pm to verify the chains instead of re-anchoring them."},{code:"validate_command_references_stale_pm_ids",command:'pm update <id> --replace-tests --test "command=<corrected-command>" [--test ...]',summary:"Correct the stale pm-ID inside the item's linked test command (the check scans tests[].command, not the body). --replace-tests overwrites the entire tests list, so re-include the item's other linked tests in the same call."},{code:"validate_format_version_outdated_items",command:"pm validate --verbose-diagnostics",summary:"One or more items predate the current storage format version; a pm storage migration rewrites them. Use --verbose-diagnostics to list the affected items."},{code:"validate_format_version_ahead_items",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more items were written by a newer pm format version than this runtime supports; upgrade pm to read and validate them safely."}]);function hd(e){if(typeof e!="string")return;let t=e.trim();for(let n of wR)if(t===n.code||t.startsWith(`${n.code}:`))return n}function gd(e){let t={};for(let n of e){let r=hd(n);r!==void 0&&!Object.prototype.hasOwnProperty.call(t,r.code)&&(t[r.code]=r.command)}return t}function dw(e){return Object.values(gd(e))}import{execFile as vR}from"node:child_process";import{realpath as bR}from"node:fs/promises";import lw from"node:path";import{promisify as kR}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9af87d55-dbe2-561b-9f3f-6f12c0416147")}catch{}})();var SR=kR(vR),ER=32*1024*1024,TR=1e4,CR=["search/eval-queries.json"];function yd(e){return e.replaceAll("\\","/").replace(/\/+$/,"")}function AR(e){return`'${e.replaceAll("'","'\\''")}'`}async function xR(e,t=bR){return t(e).catch(()=>lw.resolve(e))}async function es(e){let t=await Dt(e);if(t===null)return{git_workspace_root:null,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let n=await xR(e),r=yd(lw.relative(t,n));if(r.length===0)return{git_workspace_root:t,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let i=mh.map(o=>`${r}/${yd(o)}`);try{let{stdout:o}=await SR("git",["ls-files","-z","--",...i.map(d=>`:(literal)${d}`)],{cwd:t,encoding:"utf8",maxBuffer:ER,windowsHide:!0,timeout:TR}),s=new Set(CR.map(d=>`${r}/${d}`)),a=[...new Set(o.split("\0").filter(d=>d.length>0&&!s.has(yd(d))))].sort((d,l)=>d.localeCompare(l)),c=i.filter(d=>a.some(l=>l===d||l.startsWith(`${d}/`)));return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:a,tracked_path_count:a.length,remediation_command:a.length===0?null:`git rm --cached -r -- ${c.map(d=>AR(`:(literal)${d}`)).join(" ")}`}}catch{return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:[],tracked_path_count:0,remediation_command:null}}}import uw from"node:path";import{realpath as RR}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7637003b-61ed-52eb-849c-eaf098df2963")}catch{}})();async function mw(e,t){let n=t===null?[]:await Th(t,[uw.relative(t,uw.join(await RR(e),"merge-receipts","00000000-0000-4000-8000-000000000000.json")).replaceAll("\\","/")]);return{rules:n,warnings:n.length>0?[`merge_artifacts_ignored:${n.length}`]:[]}}async function pw(e,t,n,r){if(t===null)return{audit:null,count:0,warnings:[]};let i=await $n(e,Dn(n));if(i.status==="ok")return{audit:i,count:0,warnings:[]};let o=Math.max(1,i.missing_patterns.length+i.stale_patterns.length);return{audit:i,count:o,warnings:r?[`merge_fence_${i.status==="not_installed"?"missing":"drift"}:${o}`]:[]}}function _w(e){let t=[];return e.invalidEvidenceCount>0&&t.push(`merge_receipt_evidence_invalid:${e.invalidEvidenceCount}`),e.missingHistoryReferenceCount>0&&t.push(`merge_receipt_history_reference_missing:${e.missingHistoryReferenceCount}`),t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b30e1b22-1dee-52b2-af2b-3f3af31334d5")}catch{}})();var IR=5;function ts(e,t){let n=[],r={};for(let o of e){let s=Qi(o);if(s.length!==0){for(let a of s)r[a.field]=(r[a.field]??0)+1;n.push({id:o.id,fields:s.map(a=>a.field),reasons:[...new Set(s.map(a=>a.reason))]})}}if(n.length===0)return;n.sort((o,s)=>o.id.localeCompare(s.id));let i=t?n.length:IR;return{details:{items:n.length,by_field:Object.fromEntries(Object.entries(r).sort(([o],[s])=>o.localeCompare(s))),rows:n.slice(0,i),truncated:n.length>i},warning:`validate_metadata_deferred_fields:${n.length}`}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="034a58e5-51de-5865-aa25-423e2a03c32e")}catch{}})();var gw=25,OR=ge.join("runtime","telemetry","events.jsonl"),LR=ge.join("runtime","telemetry","state.json"),DR=2500,$R=500,yw=Yp-3,NR=["x-pm-telemetry-max-schema-version","x-pm-telemetry-max-version"];function Ed(e,t=!1){return e.startsWith("agent_guidance_")||e.startsWith("telemetry_")||e.startsWith("extension_disabled_pm_")||e.startsWith("history_stream_over_compact_threshold:")||e.startsWith("integrity_legacy_hierarchy_")||e.startsWith("stale_in_progress_items:")||e.startsWith("in_progress_unowned:")||e.startsWith("in_progress_idle:")||e.startsWith("provenance_resolver_zero_success:")||e.startsWith("provenance_value_domain_invalid:")||!t&&e.startsWith("merge_driver_configuration_missing:")}function Td(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function Hn(e){return e.trim().toLowerCase()}function bd(e,t){let n=Hn(e),r=Hn(t);return n.startsWith("builtin-")?!0:r==="beads"||r==="todos"}async function Cd(e){try{return(await St.stat(e)).isDirectory()}catch{return!1}}async function MR(e){let t=(await St.readdir(e,{withFileTypes:!0})).filter(r=>r.isDirectory()),n=await Promise.all(t.map(r=>St.readdir(ge.join(e,r.name),{withFileTypes:!0})));return new Set(n.flatMap(r=>r.filter(i=>i.isFile()).filter(i=>zt.some(o=>i.name.endsWith(o))).map(i=>ge.parse(i.name).name)))}async function PR(e,t,n,r){let i=await We({path:e,scope:"project"}),o=t!=="_workspace"&&!r.has(t);if(!n.enabled&&!o)return{warnings:i,overThreshold:!1,classification:"live"};let s;try{s=await St.readFile(e,"utf8")}catch{return{warnings:i,overThreshold:!1,classification:"unreadable"}}let a="live";if(o){let d=s.split(/\r?\n/).map(l=>l.trim()).filter(Boolean).at(-1);try{a=JSON.parse(d??"{}").op==="delete"?"tombstone":"orphaned"}catch{a="orphaned"}}let c=n.enabled?s.split(/\r?\n/).filter(d=>d.trim().length>0).length:0;return{warnings:i,overThreshold:n.enabled&&c>n.max_entries,classification:a}}async function FR(e,t,n){let r=ge.join(e,"history");if(!await Cd(r))return{count:0,warnings:[],over_threshold:[],max_entries:null,tombstones:[],orphaned:[]};let i=(await St.readdir(r)).filter(l=>l.endsWith(".jsonl")).sort((l,u)=>l.localeCompare(u)),o=t.enabled?t.max_entries:null,s=[],a=[],c=[],d=[];for(let l of i){let u=ge.join(r,l),_=l.slice(0,-6),h=await PR(u,_,t,n);s.push(...h.warnings),h.classification==="tombstone"&&c.push(_),h.classification==="orphaned"&&d.push(_),h.overThreshold&&a.push(_)}return{count:i.length,warnings:[...s,...a.map(l=>`history_stream_over_compact_threshold:${l}`),...d.map(l=>`history_orphaned_stream:${l}`)],over_threshold:a,max_entries:o,tombstones:c,orphaned:d}}function kd(e,t){return ge.relative(e,t).replaceAll("\\","/")}async function ww(e,t){let n=[...new Set(Object.values(t))].sort((i,o)=>i.localeCompare(o)),r=[];for(let i of n){let o=ge.join(e,i),s=[];try{s=await St.readdir(o)}catch(a){if(typeof a=="object"&&a!==null&&"code"in a&&G(a))continue;continue}for(let a of s)zt.some(c=>a.toLowerCase().endsWith(c))&&r.push(ge.join(o,a))}return r.sort((i,o)=>kd(e,i).localeCompare(kd(e,o))),r}function jR(e){return!(typeof e=="object"&&e!==null&&"code"in e&&G(e))}function UR(e){let t=ts(e,!1);return t===void 0?{}:{curation:{deferred_fields:t.details}}}async function GR(e,t,n){let r=await ww(e,t),i=[],o=[],s=[],a=[],c=xt(N());for(let d of r){let l=kd(e,d),u;try{u=await St.readFile(d,"utf8")}catch{i.push(l);continue}let _=xn(u);if(_){o.push({path:l,..._});continue}try{let h=Zi(u,{format:sm(d),schema:n,extensionFieldNames:c});a.push({ref:l,version:Ji(h.metadata)})}catch{s.push(l)}}return{paths:r,unreadable:i,conflictMarkers:o,parseFailures:s,formatVersions:a}}async function qR(e){let t=ge.join(e,"history"),n=[],r=[],i=[],o=[],s=[],a=[];try{a=(await St.readdir(t)).filter(c=>c.endsWith(".jsonl")).sort((c,d)=>c.localeCompare(d))}catch(c){jR(c)&&n.push("history")}for(let c of a){let d=c.slice(0,-6),l;try{l=await St.readFile(ge.join(t,c),"utf8")}catch{n.push(d);continue}let u=xn(l);if(u){r.push({id:d,...u});continue}l.split(/\r?\n/).forEach((_,h)=>{if(_.trim())try{let f=JSON.parse(_);o.push(...Qy(f,d).map(g=>({itemId:d,line:h+1,...g}))),s.push(...Zy(f,d,h+1))}catch{i.push({id:d,line:h+1})}})}return{files:a,unreadable:n,conflictMarkers:r,invalidJson:i,mergeReceiptReferences:o,mergeReceiptDispositions:s}}function vw(e){return[...e.cycles.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_cycle:${t.item_ids.join(",")}`:`integrity_hierarchy_cycle:${t.item_ids.join(",")}`),...e.cardinality_violations.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_cardinality:${t.child_id}`:`integrity_hierarchy_cardinality:${t.child_id}`),...e.divergences.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_divergence:${t.child_id}`:`integrity_hierarchy_divergence:${t.child_id}`)]}async function KR(e,t,n,r,i,o){let s=await GR(e,t,n),a=await qR(e),c=Xi(s.formatVersions,yr,Yi),d=W(n),l=Co(o,T=>fe(T,d),de()),u=await es(e),_=await Dt(e),h=await mw(e,_),f=await pw(e,_,r,i),g=_===null?null:await Nn(_),y=await Mn(_??e,{includeReconciled:!0,includeLossless:!0,pmRoot:e}),w=new Set(y.durable_receipt_ids),v=ew(a.mergeReceiptReferences,w,a.mergeReceiptDispositions),k=v.missing,S=y.receipts.filter(T=>T.state==="pending"),{pendingDecisions:b,lossless:A}=Pn(S),E=g?.status==="missing"&&g.missing_keys.length===5&&g.drifted_keys.length===0,C=[...s.unreadable.map(T=>`integrity_item_unreadable:${T}`),...s.conflictMarkers.map(T=>`integrity_item_conflict_marker:${T.path}:L${T.line}`),...s.parseFailures.map(T=>`integrity_item_parse_failed:${T}`),...a.unreadable.map(T=>`integrity_history_unreadable:${T}`),...a.conflictMarkers.map(T=>`integrity_history_conflict_marker:${T.id}:L${T.line}`),...a.invalidJson.map(T=>`integrity_history_invalid_json:${T.id}:L${T.line}`),...c.outdated.map(T=>`integrity_item_outdated_format_version:${T}`),...c.ahead.map(T=>`integrity_item_ahead_format_version:${T}`),...vw(l),...u.tracked_path_count>0?[`tracked_runtime_cache_files:${u.tracked_path_count}`]:[],...g!==null&&g.status!=="ok"?[`merge_driver_configuration_${E?"missing":"drift"}:${g.missing_keys.length+g.drifted_keys.length}`]:[],...f.warnings,...h.warnings,...b.length>0?[`merge_decisions_unreviewed:${b.length}`]:[],...A.length>0?[`merge_receipts_pending:${A.length}`]:[],..._w({invalidEvidenceCount:y.invalid_evidence_count,missingHistoryReferenceCount:k.length})],O=[...new Set(C)].sort((T,F)=>T.localeCompare(F)),M=O.filter(T=>!T.startsWith("integrity_legacy_hierarchy_"));return{check:{name:"integrity",status:M.length===0?"ok":"warn",ok:M.length===0,details:{checked_item_files:s.paths.length,checked_history_streams:a.files.length,counts:{item_unreadable:s.unreadable.length,item_conflict_markers:s.conflictMarkers.length,item_parse_failures:s.parseFailures.length,history_unreadable:a.unreadable.length,history_conflict_markers:a.conflictMarkers.length,history_invalid_json:a.invalidJson.length,item_outdated_format_version:c.outdated.length,item_ahead_format_version:c.ahead.length,hierarchy_cycles:l.cycles.length,hierarchy_cardinality_violations:l.cardinality_violations.length,hierarchy_parent_divergences:l.divergences.length,tracked_runtime_cache_files:u.tracked_path_count,merge_driver_configuration:g===null||g.status==="ok"?0:g.missing_keys.length+g.drifted_keys.length,merge_fence:f.count,ignored_merge_artifacts:h.rules.length,pending_merge_decisions:b.length,lossless_merge_receipts:A.length,invalid_merge_receipt_evidence:y.invalid_evidence_count,missing_merge_receipt_history_references:k.length,accepted_legacy_merge_receipt_references:v.acceptedLegacyCount,accepted_missing_merge_receipt_dispositions:v.acceptedDispositionCount},item_unreadable:s.unreadable,item_conflict_markers:s.conflictMarkers,item_parse_failures:s.parseFailures,item_outdated_format_version:c.outdated,item_ahead_format_version:c.ahead,...UR(o),hierarchy_integrity:{...l,relations:Qe(l.relations,nw)},history_unreadable:a.unreadable,history_conflict_markers:a.conflictMarkers,history_invalid_json:a.invalidJson,tracked_runtime_cache:{tracker_relative_root:u.tracker_relative_root,tracked_paths:u.tracked_paths,tracked_path_count:u.tracked_path_count,remediation_command:u.remediation_command},merge_driver_configuration:g===null?null:{...g,required:i},merge_fence:f.audit,ignored_merge_artifacts:h.rules,pending_merge_decision_items:[...new Set(b.map(T=>T.item_id))].sort((T,F)=>T.localeCompare(F)),lossless_merge_receipt_items:[...new Set(A.map(T=>T.item_id))].sort((T,F)=>T.localeCompare(F)),invalid_merge_receipt_evidence_details:y.invalid_evidence,invalid_merge_receipt_evidence_details_truncated:y.invalid_evidence_truncated,missing_merge_receipt_history_reference_details:k.slice(0,md),missing_merge_receipt_history_reference_details_truncated:k.length>md}},warnings:O,gitWorkspaceRoot:_,pendingMergeReceipts:S}}function WR(e){if(typeof e.activate=="function")return!0;let t=e.default;return typeof t!="object"||t===null?!1:typeof t.activate=="function"}function zR(e){let t={layer:e.layer,directory:e.directory,manifest_path:e.manifest_path,name:e.name,version:e.version,entry:e.entry,priority:e.priority,entry_path:e.entry_path,has_activate:WR(e.module)};return Array.isArray(e.capabilities)&&(t.capabilities=[...e.capabilities]),t}function BR(e,t){return oe(e.id)||`migration-${String(t+1).padStart(3,"0")}`}function HR(e){let t=oe(e.status)?.toLowerCase();return t==="failed"?"failed":t==="applied"?"applied":"pending"}function VR(e){return oe(e.reason)??oe(e.error)??oe(e.message)}function wd(e,t){let n=(e.layer??"").localeCompare(t.layer??"");if(n!==0)return n;let r=(e.name??"").localeCompare(t.name??"");return r!==0?r:(e.id??"").localeCompare(t.id??"")}function YR(e){let t=[],n=[],r=[];e.forEach((o,s)=>{let a=BR(o.definition,s),c=HR(o.definition);if(c==="applied"){t.push({layer:o.layer,name:o.name,id:a,status:c});return}if(c==="failed"){r.push({layer:o.layer,name:o.name,id:a,status:c,reason:VR(o.definition)});return}n.push({layer:o.layer,name:o.name,id:a,status:c})}),t.sort(wd),n.sort(wd),r.sort(wd);let i=[...r.map(o=>`extension_migration_failed:${o.layer}:${o.name}:${o.id}`),...n.map(o=>`extension_migration_pending:${o.layer}:${o.name}:${o.id}`)];return{summary:{applied:t,pending:n,failed:r,applied_count:t.length,pending_count:n.length,failed_count:r.length},warnings:i}}function bw(e,t,n,r,i,o,s,a,c){let d=[...new Set(e)].sort((y,w)=>y.localeCompare(w)),l=[...new Set(d.map(y=>Td(y)))].sort((y,w)=>y.localeCompare(w)),u=d.filter(y=>y.startsWith("extension_capability_unknown:")).length,_=c.length>0,h=_?"partial":"full",f=d.map(bc).filter(y=>y!==void 0),g=gh(d,{deactivate:"pm extension --deactivate <name> --project/--global",doctor:"pm extension --doctor --project/--global --detail deep --trace"});return g&&f.push(g),t>0&&f.push("Run pm extension --explore --project and pm extension --explore --global to inspect load failures."),n>0&&f.push("Review checks[name=extensions].details.activation.failed in pm health --json for activation error details."),(r.failed_count>0||r.pending_count>0)&&f.push("Resolve pending/failed extension migrations before write commands; use --force only when policy allows."),i>0&&f.push("Run pm extension --manage --project and pm extension --manage --global to refresh managed-state diagnostics."),u>0&&f.push(`Unknown extension capabilities detected. Allowed capabilities: ${Iu.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`),d.some(y=>y.startsWith("extension_capability_legacy_alias:"))&&f.push("Legacy extension capability aliases were auto-remapped to canonical capabilities. Update manifests to canonical names (migration/validation -> schema)."),d.some(y=>y.startsWith("extension_command_definition_legacy_handler_alias:"))&&f.push("Extension command definitions using legacy handler were auto-remapped. Update command definitions to use run: (context) => ... for forward compatibility."),_?f.push("Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via pm extension --manage --project/--global --fix-managed-state, pm extension --adopt-all --project/--global, or pm extension --adopt <name>."):s.length>0&&f.push("Loaded unmanaged extensions are currently treated as informational. Use pm extension --manage --project/--global --fix-managed-state to adopt them for update checks."),f.length===0&&f.push("No immediate action required. Re-run pm health after extension configuration changes."),{status:d.length===0?"ok":"warn",warning_count:d.length,warning_codes:l,load_failure_count:t,activation_failure_count:n,migration_failed_count:r.failed_count,migration_pending_count:r.pending_count,managed_state_warning_count:i,managed_extension_entries_count:o,unmanaged_loaded_extension_count:s.length,unmanaged_loaded_extensions:s,unmanaged_expected_extension_count:a.length,unmanaged_expected_extensions:a,unmanaged_action_required_extension_count:c.length,unmanaged_action_required_extensions:c,update_health_coverage:h,update_health_partial:_,unknown_capability_count:u,top_warnings:d.slice(0,8),remediation:f}}async function JR(e,t,n){let r=await yh(lt(e)),i=await no({pmRoot:e,settings:t,cwd:process.cwd(),noExtensions:n}),o=i.loaded.map(E=>zR(E)),s=await Wy(i.loaded,lt(e)),a=await ro({...i,loaded:i.loaded}),[c,d]=await Promise.all([vc(i.roots.project),vc(i.roots.global)]);await i_(e,a.registrations.migrations);let l=YR(a.registrations.migrations),u={failed:a.failed,warnings:a.warnings,hook_counts:a.hook_counts,command_override_count:a.command_override_count,command_handler_count:a.command_handler_count,parser_override_count:a.parser_override_count,preflight_override_count:a.preflight_override_count,service_override_count:a.service_override_count,renderer_override_count:a.renderer_override_count,registration_counts:a.registration_counts,registrations:a.registrations,migration_status:l.summary,managed_extensions:{project:{path:c.path,count:c.state.entries.length,entries:c.state.entries},global:{path:d.path,count:d.state.entries.length,entries:d.state.entries}}},_=new Set(c.state.entries.map(E=>Hn(E.name))),h=new Set(d.state.entries.map(E=>Hn(E.name))),f=[...new Map(i.loaded.filter(E=>!(E.layer==="project"?_:h).has(Hn(E.name))).map(E=>[`${E.layer}:${E.name}`,{layer:E.layer,name:E.name,directory:E.directory}])).values()].sort((E,C)=>{let O=`${E.layer}:${E.name}`,M=`${C.layer}:${C.name}`;return O.localeCompare(M)}),g=f.map(E=>`${E.layer}:${E.name}`).sort((E,C)=>E.localeCompare(C)),y=f.filter(E=>bd(E.name,E.directory)).map(E=>`${E.layer}:${E.name}`).sort((E,C)=>E.localeCompare(C)),w=f.filter(E=>!bd(E.name,E.directory)).map(E=>`${E.layer}:${E.name}`).sort((E,C)=>E.localeCompare(C)),v=w.length>0?[`extension_update_health_partial_coverage:skipped_unmanaged:${w.length}`]:[],k=[...r.warnings,...i.warnings,...u.warnings,...l.warnings,...c.warnings,...d.warnings,...v,...s.warnings],S=kc(k),b=Sc(),A=bw(k,i.failed.length,a.failed.length,l.summary,c.warnings.length+d.warnings.length,c.state.entries.length+d.state.entries.length,g,y,w);return{check:{name:"extensions",status:k.length===0?"ok":"warn",ok:k.length===0,details:{...i,loaded:o,warnings:k,activation:u,author_manifest:r,triage:A,...l.summary.pending_count>0?{remediation_map:{extension_migration_pending:"pm extension migrate --project"}}:{},capability_contract:b,capability_guidance:S,host_version_census:s}},warnings:k}}function Sd(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=rw(e,gw);return{values:n.values,truncated:n.truncated,total:e.length}}function ns(e){let t=(process.env[e]??"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function XR(){let e=Gp();return e.source_context_source==="env_override"?e.source_context:null}function kw(e){let t=0,n=0,r=0,i=0,o=0;for(let s of e.split(`
|
|
8
|
+
`)){let a=s.trim();if(a.length!==0){r+=1;try{let c=JSON.parse(a);if(typeof c=="object"&&c!==null&&typeof c.attempts=="number"&&Number.isFinite(c.attempts)){let d=Math.max(0,Math.trunc(c.attempts));t+=1,o=Math.max(o,d),d>=yw&&(i+=1)}else n+=1}catch{n+=1}}}return{validEntries:t,invalidRows:n,totalRows:r,highRetryEntries:i,maxAttempts:o}}function QR(){return{validEntries:0,invalidRows:0,totalRows:0,highRetryEntries:0,maxAttempts:0}}function fw(e){if(!e||e.trim().length===0)return{runtimeState:{},stateParseFailed:!1};try{let t=JSON.parse(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)?{runtimeState:t,stateParseFailed:!1}:{runtimeState:{},stateParseFailed:!0}}catch{return{runtimeState:{},stateParseFailed:!0}}}async function ZR(e,t){let n=Cr(e.telemetry.endpoint).trim();return!t||!e.telemetry.enabled||n.length===0||Zt().telemetry_disabled?void 0:{attempted:!0,...await Sw(n)}}function eI(e,t,n){let r=[];if(t.invalidRows>0&&r.push(`telemetry_queue_invalid_rows:${t.invalidRows}`),!e.telemetry.enabled||t.validEntries===0)return r;let i=n.last_successful_flush_at,o=n.last_failed_flush_at,s=o&&(!i||o>i),a=!i,c=t.validEntries>=$R;return(s||a||c)&&r.push(`telemetry_queue_pending:${t.validEntries}`),t.highRetryEntries>0&&r.push(`telemetry_queue_high_retries:${t.highRetryEntries}`),r}function tI(e){return!e||e.ok!==!1?[]:typeof e.status=="number"?[`telemetry_endpoint_probe_http_status:${e.status}`]:["telemetry_endpoint_probe_failed"]}function nI(e){let t=Number.parseInt(e?.max_schema_version??"",10);return e?.ok===!0&&Number.isInteger(t)&&t>Vp?[`telemetry_schema_version_behind:${t}`]:[]}function rI(e,t){let n=typeof t.pending_otel_spans=="number"?t.pending_otel_spans:0,r=t.last_otel_success_at,i=t.last_otel_failure_at;return e.telemetry.enabled&&n>0&&i&&(!r||i>=r)?[`telemetry_otel_export_failing:${n}`]:[]}function iI(){return{...Zt(),pm_no_telemetry:ns("PM_NO_TELEMETRY"),telemetry_otel_disabled:ns("PM_TELEMETRY_OTEL_DISABLED"),telemetry_inline_flush:ns("PM_TELEMETRY_INLINE_FLUSH"),telemetry_source_context:XR()}}function oI(e,t){return e.telemetry.enabled&&t.validEntries>0}function sI(e,t){return e&&t.every(n=>!n.startsWith("telemetry_queue_pending:")&&!n.startsWith("telemetry_queue_high_retries:"))}function hw(e){try{return decodeURIComponent(e)}catch{return e}}async function Sw(e){let t=e,n={};try{let r=new URL(e);r.pathname="/healthz",r.search="",r.hash="",(r.username.length>0||r.password.length>0)&&(n.authorization=`Basic ${Buffer.from(`${hw(r.username)}:${hw(r.password)}`).toString("base64")}`,r.username="",r.password=""),t=r.toString()}catch{}try{let r=await fetch(t,{method:"GET",headers:n,signal:AbortSignal.timeout(DR)});return{probe_url:Ot(t),ok:r.ok,status:r.status,max_schema_version:(()=>{for(let i of NR){let o=r.headers.get(i)?.trim();if(o&&o.length>0)return o}})()}}catch(r){return{probe_url:Ot(t),ok:!1,error:r instanceof Error?qp(r.message.replaceAll(t,Ot(t))):"probe_failed"}}}async function aI(e,t){let n=fw(await Q(e)),r=e===t?n:fw(await Q(t));return{runtimeState:n.runtimeState,spanState:r.runtimeState,stateParseFailed:n.stateParseFailed||r.stateParseFailed}}async function cI(e){let t=Ye(process.cwd()),n=await x(t),r=ge.join(ge.dirname(ge.join(t,OR)),It("events.jsonl")),i=ge.join(t,LR),o=ge.join(ge.dirname(i),It("state.json")),s=await Q(r),a=s!==null,c=s?Buffer.byteLength(s,"utf8"):0,d=s?kw(s):QR(),{runtimeState:l,spanState:u,stateParseFailed:_}=await aI(o,i),h=Cr(n.telemetry.endpoint).trim(),f=Ot(h),g=await ZR(n,e.checkTelemetry),y=[];_&&y.push("telemetry_state_invalid_json"),y.push(...eI(n,d,l),...tI(g),...nI(g),...rI(n,u));let w=oI(n,d),v=typeof u.pending_otel_spans=="number"?u.pending_otel_spans:0;return{check:{name:"telemetry",status:y.length===0?"ok":"warn",ok:y.length===0,details:{enabled:n.telemetry.enabled,capture_level:n.telemetry.capture_level,endpoint:f,global_pm_root:t,queue_path:r,queue_exists:a,queue_entries:d.validEntries,queue_draining:sI(w,y),queue_invalid_rows:d.invalidRows,queue_rows_total:d.totalRows,queue_size_bytes:c,queue_high_retry_entries:d.highRetryEntries,queue_high_retry_threshold:yw,queue_max_attempts:d.maxAttempts,runtime_state_path:o,last_attempted_flush_at:l.last_attempted_flush_at??null,last_successful_flush_at:l.last_successful_flush_at??null,last_failed_flush_at:l.last_failed_flush_at??null,last_failed_flush_error:l.last_failed_flush_error??null,pending_otel_spans:v,last_otel_attempt_at:u.last_otel_attempt_at??null,last_otel_success_at:u.last_otel_success_at??null,last_otel_failure_at:u.last_otel_failure_at??null,last_otel_failure_error:u.last_otel_failure_error??null,endpoint_probe:g??{attempted:!1},env_overrides:iI()}},warnings:y}}async function dI(e){let t;try{t=await aw(e)}catch(r){let i=r instanceof Error?r.message:String(r);return{check:{name:"locks",status:"warn",ok:!1,details:{active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0,scan_failed:!0,error:i,pm_root:e}},warnings:[`locks_scan_failed:${i}`]}}let n=[];return t.stale_lock_count>0&&n.push(`locks_stale_count:${t.stale_lock_count}`),t.unreadable_lock_count>0&&n.push(`locks_unreadable:${t.unreadable_lock_count}`),{check:{name:"locks",status:n.length===0?"ok":"warn",ok:n.length===0,details:{active_lock_count:t.active_lock_count,stale_lock_count:t.stale_lock_count,...t.owner_dead_lock_samples?{owner_dead_lock_samples:t.owner_dead_lock_samples,recovery_command:"pm gc --scope locks"}:{},unreadable_lock_count:t.unreadable_lock_count,unparseable_lock_count:t.unparseable_lock_count}},warnings:n}}async function lI(e){let t="metadata",n=e.items,r=await Mr(e.pmRoot,n,{cacheHitVerification:t}),i=[...new Set([...r.hashMismatches,...r.chainMismatches,...r.versionSkews])].sort((w,v)=>w.localeCompare(v)),o=[],s=[];if(i.length>0){n=await gt(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema,{forceSourceScan:!0}),r=await Mr(e.pmRoot,n),o=[...new Set([...r.hashMismatches,...r.chainMismatches,...r.versionSkews])].sort((v,k)=>v.localeCompare(k));let w=new Set(o);s=i.filter(v=>!w.has(v))}let{missingStreams:a,unreadableStreams:c,hashMismatches:d,chainMismatches:l,versionSkews:u,driftedItems:_,workspaceStateMismatches:h,workspaceStateMissing:f,workspaceStateUnreadable:g}=r,y=[...a.map(w=>`history_drift_missing_stream:${w}`),...c.map(w=>`history_drift_unreadable_stream:${w}`),...d.map(w=>`history_drift_hash_mismatch:${w}`),...l.map(w=>`history_drift_chain_mismatch:${w}`),...u.map(w=>`history_drift_version_skew:${w}`),...h.map(w=>`history_drift_workspace_state_mismatch:${w}`),...f.map(w=>`history_drift_workspace_state_missing:${w}`),...g.map(w=>`history_drift_workspace_state_unreadable:${w}`)];return{check:{name:"history_drift",status:y.length===0?"ok":"warn",ok:y.length===0,details:{checked_items:n.length,cache_hit_verification:i.length>0?"metadata_then_content_hash":t,cache_confirmation:{triggered:i.length>0,reason:i.length>0?"cached_corruption_candidate":null,candidate_items:i,confirmed_items:o,resolved_false_positive_items:s,authoritative_item_source:i.length>0},drifted_items:_,counts:{drifted:_.length,missing_streams:a.length,unreadable_streams:c.length,hash_mismatches:d.length,chain_mismatches:l.length,version_skews:u.length,workspace_state_mismatches:h.length,workspace_state_missing:f.length,workspace_state_unreadable:g.length},missing_streams:a,unreadable_streams:c,hash_mismatches:d,chain_mismatches:l,version_skews:u,workspace_state_mismatches:h,workspace_state_missing:f,workspace_state_unreadable:g}},warnings:y}}function uI(e,t){let n=Ap(e),r=Mp(n.settings),i=Pp(n.settings,t),o=r.active?Fp(r.active.name,r.active.model):null;return{runtimeDefaults:n,providerResolution:r,vectorStoreResolution:i,runtimeEmbeddingIdentity:o,semanticRuntimeAvailable:!!(r.active&&i.active)}}function mI(){return{refreshed:[],skipped:[],warnings:[]}}async function pI(e){return!e.refreshPolicy.enabled||!e.snapshot.semanticRuntimeAvailable||e.staleBefore.length===0?mI():Up(e.pmRoot,e.staleBefore,{settings:e.snapshot.runtimeDefaults.settings,apply_runtime_defaults:!1})}function _I(e){return e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&!!(e.ledgerBefore.embedding&&e.runtimeEmbeddingIdentity&&jp(e.ledgerBefore.embedding,e.runtimeEmbeddingIdentity))}function fI(e){let t=new Set([...e.ledgerBefore.warnings,...e.ledgerAfter.warnings]);if(e.strictVectorizationWarnings)for(let n of e.refreshResult.warnings)t.add(n);return e.embeddingIdentityChanged&&t.add("vectorization_embedding_identity_changed"),e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&e.staleAfter.length>0&&t.add(`vectorization_stale_items_remaining:${e.staleAfter.length}`),[...t].sort((n,r)=>n.localeCompare(r))}function hI(e,t,n){return e.enabled&&t&&n.length>0?null:e.enabled?t?"no_stale_items":"semantic_runtime_unavailable":"refresh_disabled"}function Ew(e,t){let n=t.providerResolution.active?.name??null,r=t.vectorStoreResolution.active?.name??null;return{provider_active:n,provider_configured:typeof e.search?.provider=="string"?e.search.provider:null,provider_source:Xa(n,e.search?.provider??null),vector_store_active:r,vector_store_configured:typeof e.vector_store?.adapter=="string"?e.vector_store.adapter:null,vector_store_source:Xa(r,e.vector_store?.adapter??null)}}function gI(e){return{enabled:e.enabled,check_only:e.checkOnly,no_refresh:e.noRefresh,refresh_vectors:e.refreshVectors}}function yI(e,t,n){return e.enabled&&n.length>0&&t}async function wI(e,t,n,r,i){let o=uI(t,e),s=await Qa(e),a=o.semanticRuntimeAvailable?Tc(n,s.entries):[],c=await pI({pmRoot:e,snapshot:o,refreshPolicy:r,staleBefore:a}),d=await Qa(e),l=o.semanticRuntimeAvailable?Tc(n,d.entries):[],u=!o.runtimeDefaults.auto_ollama_defaults_applied,_=_I({strictVectorizationWarnings:u,semanticRuntimeAvailable:o.semanticRuntimeAvailable,ledgerBefore:s,runtimeEmbeddingIdentity:o.runtimeEmbeddingIdentity}),h=fI({ledgerBefore:s,ledgerAfter:d,refreshResult:c,strictVectorizationWarnings:u,semanticRuntimeAvailable:o.semanticRuntimeAvailable,embeddingIdentityChanged:_,staleAfter:l}),f=Sd(a,i),g=Sd(l,i),y=yI(r,o.semanticRuntimeAvailable,a);return{check:{name:"vectorization",status:h.length===0?"ok":"warn",ok:h.length===0,details:{semantic_runtime_available:o.semanticRuntimeAvailable,compatibility_mode_auto_defaults:o.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_applied:o.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:o.runtimeDefaults.auto_ollama_defaults_skipped_reason??null,auto_ollama_defaults_remediation:o.runtimeDefaults.auto_ollama_defaults_remediation??null,refresh_policy:gI(r),...Ew(t,o),embedding_identity_changed:_,embedding_identity_before:s.embedding??null,embedding_identity_runtime:o.runtimeEmbeddingIdentity??null,items:n.length,ledger_entries_before:Object.keys(s.entries).length,stale_items_detail_mode:i?"full":"summary",stale_items_summary_limit:gw,stale_items_before_total:f.total,stale_items_before:f.values,stale_items_before_truncated:f.truncated,refresh_attempted:y,refresh_skipped_reason:hI(r,o.semanticRuntimeAvailable,a),refresh_result:c,ledger_entries_after:Object.keys(d.entries).length,stale_items_after_total:g.total,stale_items_after:g.values,stale_items_after_truncated:g.truncated}},warnings:h}}function vI(e){let t=[];return e.id_prefix.trim().length===0&&t.push("settings:id_prefix_empty"),e.locks.ttl_seconds<=0&&t.push("settings:locks_ttl_non_positive"),t}function Tw(e){let t=e.checkOnly===!0,n=e.refreshVectors===!0;if(n&&t)throw new p("--check-only cannot be combined with --refresh-vectors",m.USAGE);if(n&&e.noRefresh===!0)throw new p("--no-refresh cannot be combined with --refresh-vectors",m.USAGE);return{enabled:n,checkOnly:t,noRefresh:!n,refreshVectors:n}}var bI=new Set(["extensions","locks","search"]);function kI(e){let t=new Set(Du.filter(i=>i.length>0)),n=new Set,r=new Set(Object.values($u));for(let i of e.folders)t.has(i)&&!r.has(i)||(t.delete(i),n.add(i));for(let i of bI)t.delete(i),n.add(i);return{requiredDirs:[...t].sort((i,o)=>i.localeCompare(o)),optionalDirs:[...n].sort((i,o)=>i.localeCompare(o)),optionalDirSet:n}}async function SI(e,t,n){let{requiredDirs:r,optionalDirs:i,optionalDirSet:o}=kI(t),s=[],a=[],c=[];for(let d of[...r,...i]){let l=ge.join(e,d);c.push(...await We({path:l,scope:"project"})),!await Cd(l)&&(o.has(d)?a.push(d):s.push(d))}return{requiredDirs:r,optionalDirs:i,missingRequiredDirs:s,missingOptionalDirs:a,missingDirs:n?[...s,...a]:[...s],hookWarnings:c}}function Cw(e){let t=e.checkOnly===!0&&e.brief!==!0&&e.summary!==!0&&e.full!==!0,n=e.summary===!0||t,r=e.checkOnly===!0&&(e.brief===!0||e.summary===!0)&&e.full!==!0;return{summaryMode:n,skipIntegrity:(e.skipIntegrity===!0||r)&&e.full!==!0,skipDrift:(e.skipDrift===!0||r)&&e.full!==!0,skipVectors:(e.skipVectors===!0||r)&&e.full!==!0}}async function EI(e){return e.skipPolicy.skipDrift&&e.skipPolicy.skipVectors?Te(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema):gt(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema)}function vd(e){return{check:{name:e,status:"ok",ok:!0,details:{skipped:!0}},warnings:[]}}function TI(e,t,n){return{name:"settings",status:n.length===0?"ok":"warn",ok:n.length===0,details:{path:e,version:t.version,id_prefix:t.id_prefix,locks_ttl_seconds:t.locks.ttl_seconds,warnings:n}}}function CI(e,t){return{name:"directories",status:e.missingDirs.length===0?"ok":"warn",ok:e.missingDirs.length===0,details:{required:e.requiredDirs,optional:e.optionalDirs,missing_required:e.missingRequiredDirs,missing_optional:e.missingOptionalDirs,missing:e.missingDirs,strict_directories:t}}}function AI(e,t){return{name:"settings_values",status:e.length===0?"ok":"warn",ok:e.length===0,details:{warnings:e,...t.roleless_status_count>0?{lifecycle_status_roles:t}:{}}}}var Ad=e=>e.unknown_event_count??0,xd=e=>e.actionable_unknown_event_count??Ad(e);function xI(e,t,n,r,i,o,s){let a=Ad(r),c=xd(r),d=a>0,l=c>0,u=i.count>0||s!==void 0;return{name:"storage",status:n.over_threshold.length===0&&n.orphaned.length===0&&!l&&!u?"ok":"warn",ok:n.over_threshold.length===0&&n.orphaned.length===0&&!l&&!u,details:{items:e.length,history_streams:n.count,tombstones:{retention_policy:"retain_append_only",gc_enabled:!1,count:n.tombstones.length,ids:n.tombstones.slice(0,25),truncated:n.tombstones.length>25},orphaned_history_streams:{count:n.orphaned.length,ids:n.orphaned.slice(0,25),truncated:n.orphaned.length>25},...d?{author_attribution:r}:{},...i.count>0?{stale_in_progress:i}:{},...s===void 0?{}:{in_progress_work:s},...o.outcomes.length>0?{provenance_resolver_outcomes:o.outcomes}:{},...o.invalid_values.length>0?{provenance_invalid_values:o.invalid_values}:{},provenance_sample:o.sample,...n.max_entries!==null?{compact_policy:{enabled:t.history.compact_policy.enabled,max_entries:n.max_entries,trigger:t.history.compact_policy.trigger,over_threshold_count:n.over_threshold.length,over_threshold:n.over_threshold}}:{}}}}function Aw(e){let t=e.count===0?[]:[`stale_in_progress_items:${e.count}`];return{scan:e,warnings:t}}function RI(e){let t=[...e.directoryState.missingDirs.map(n=>`missing_directory:${n}`),...e.normalizedSettingsReadWarnings,...e.settingWarnings,...e.normalizedItemReadWarnings,...e.telemetryCheck.warnings,...e.extensionCheck.warnings,...e.historyPolicyWarnings,...e.historySummary.warnings,...e.authorAttributionWarnings,...e.staleInProgressWarnings,...e.provenanceWarnings,...e.locksCheck.warnings,...e.integrityCheck.warnings,...e.historyDriftCheck.warnings,...e.vectorizationCheck.warnings,...e.directoryState.hookWarnings];return[...new Set(t)]}function II(e){let t=e.check.details.counts;return typeof t?.drifted=="number"?t.drifted:0}function OI(e){return{settings:e.normalizedSettingsReadWarnings,directories:e.directoryState.missingDirs.map(t=>`missing_directory:${t}`).concat(e.directoryState.hookWarnings),settings_values:e.settingWarnings,telemetry:e.telemetryCheck.warnings,extensions:e.extensionCheck.warnings,storage:[...e.historyPolicyWarnings,...e.historySummary.warnings,...e.authorAttributionWarnings,...e.staleInProgressWarnings,...e.provenanceWarnings],locks:e.locksCheck.warnings,integrity:[...e.normalizedItemReadWarnings,...e.integrityCheck.warnings],history_drift:e.historyDriftCheck.warnings,vectorization:e.vectorizationCheck.warnings}}function xw(e){let t=new Map;for(let[r,i]of Object.entries(e.remediationSources))for(let o of i)t.has(o)||t.set(o,r);let n=new Map(e.checks.map(r=>[r.name,r]));return e.warnings.map(r=>{let i=t.get(r)??"integrity",o=hd(r)?.code??Td(r),s=n.get(i)?.details,a=typeof s?.remediation_map=="object"&&s.remediation_map!==null?s.remediation_map:{},c=bc(r)??(o==="agent_guidance_outdated"?"pm init --agent-guidance add":o==="agent_guidance_unreadable"?"Check AGENTS.md and CLAUDE.md read permissions and file types, then retry pm health.":a[o]),d=Ed(r,e.requireMergeDrivers)?"advisory":"gate_failing";return{warning:r,code:o,check:i,severity:d,...typeof c=="string"?{remediation:c}:d==="gate_failing"?{disposition:"no_safe_automatic_remediation"}:{}}})}function LI(e){if(e.check.name==="history_drift"&&e.historyDriftedCount>1)for(let t of Object.keys(e.remediationMap))t!=="history_drift_merge_receipt"&&t!=="history_drift_version_skew"&&(e.remediationMap[t]="pm history-repair --all");if(e.check.name==="storage"&&e.overThresholdCount>1)for(let t of Object.keys(e.remediationMap))e.remediationMap[t]="pm history-compact --all-streams"}function DI(e){for(let t of e.checks){let n=gd(e.remediationSources[t.name]);LI({check:t,remediationMap:n,historyDriftedCount:e.historyDriftedCount,overThresholdCount:e.overThresholdCount});for(let[r,i]of Object.entries(t.name==="storage"?e.storageRemediation:{}))Object.hasOwn(n,r)&&(n[r]=i);Object.keys(n).length>0&&(t.details={...t.details,remediation_map:n})}}async function $I(e){if(e.gitWorkspaceRoot===null||e.pendingMergeReceipts.length===0)return[];let t=e.historyDriftCheck.check.details,n=Array.isArray(t.hash_mismatches)?t.hash_mismatches.filter(s=>typeof s=="string"):[],r=new Set([t.missing_streams,t.unreadable_streams,t.chain_mismatches].flatMap(s=>Array.isArray(s)?s:[])),i=new Map;for(let s of e.pendingMergeReceipts){let a=i.get(s.item_id)??[];a.push(s),i.set(s.item_id,a)}let o=[];for(let s of n){if(r.has(s))continue;let a=i.get(s);if(!(!a||a.length===0))try{await Ch(s,{dryRun:!0,mergeReceiptProof:{gitWorkspaceRoot:e.gitWorkspaceRoot,receipts:a}},e.global),o.push(s)}catch{}}return[...new Set(o)].sort((s,a)=>s.localeCompare(a))}function NI(e,t){let n=new Set(t);e.warnings=[...e.warnings.filter(r=>r.startsWith("history_drift_hash_mismatch:")?!n.has(r.slice(r.indexOf(":")+1)):!0),...t.map(r=>`history_drift_merge_receipt:${r}`)].sort((r,i)=>r.localeCompare(i)),e.check.details={...e.check.details,merge_receipt_attributed_items:t}}async function Rw(e,t={}){let n=R(process.cwd(),e.path);await j(n);let r=Re(n),{settings:i,warnings:o}=await Tp(n),s=[...new Set(o)],a=P(i,N()),c=t.strictDirectories===!0,d=t.strictExit===!0||t.failOnWarn===!0,l=t.requireMergeDrivers===!0||d,u=Tw(t),_=await SI(n,a,c),h=vI(i),f=await cI({checkTelemetry:t.checkTelemetry===!0}),g=await JR(n,i,!!e.noExtensions),y=Cw(t),w=[],v=await EI({pmRoot:n,settings:i,typeRegistry:a,skipPolicy:y,itemReadWarnings:w}),k=v,S=Qo(W(i.schema),v),b=[...(await wh({pm_root:n,cwd:process.cwd(),mode:"status",interactive:!1,settings:i}).catch(()=>({warnings:["agent_guidance_unreadable:AGENTS.md,CLAUDE.md"]}))).warnings.filter(ae=>ae.startsWith("agent_guidance_")),...h,...Zo(S)],A=y.skipDrift?{warnings:[]}:await so({pmRoot:n,settings:i,itemIds:v.map(ae=>ae.id),commandLabel:"health"}),E=await FR(n,i.history.compact_policy,await MR(n)),C=await Yr(n,20,t.verboseAuthorEvents===!0),O=xd(C),M=O>0?[`history_unknown_author_events:${O}`]:[],T=W(i.schema),F=await Bp(n,v,{in_progress_status:T.in_progress_status,status_registry:T,threshold_hours:i.mutation_guard.stale_in_progress_hours}),ue=Aw(F.stale),Ne=Hy(F,{in_progress:T.in_progress_status,open:T.open_status},Ie(e)),J=[...ue.warnings,...Ne.warnings],Me=await Eh(n),Pe=Me.warnings,qe=await dI(n),re=y.skipIntegrity&&!l?{...vd("integrity"),gitWorkspaceRoot:null,pendingMergeReceipts:[]}:await KR(n,a.type_to_folder,i.schema,i,l,v),be=y.skipDrift?vd("history_drift"):await lI({pmRoot:n,items:k,settings:i,typeRegistry:a,itemReadWarnings:w}),Ee=[...new Set(w)],nt=await $I({gitWorkspaceRoot:re.gitWorkspaceRoot,pendingMergeReceipts:re.pendingMergeReceipts,historyDriftCheck:be,global:e});NI(be,nt);let rt=y.skipVectors?vd("vectorization"):await wI(n,i,k,u,t.verboseStaleItems===!0),it=[TI(r,i,s),CI(_,c),AI(b,S),f.check,g.check,xI(v,i,E,C,ue.scan,Me,Ne.details),qe.check,re.check,be.check,rt.check],ye=RI({directoryState:_,normalizedSettingsReadWarnings:s,settingWarnings:b,normalizedItemReadWarnings:Ee,telemetryCheck:f,extensionCheck:g,historyPolicyWarnings:A.warnings,historySummary:E,authorAttributionWarnings:M,staleInProgressWarnings:J,provenanceWarnings:Pe,locksCheck:qe,integrityCheck:re,historyDriftCheck:be,vectorizationCheck:rt}),se=OI({directoryState:_,normalizedSettingsReadWarnings:s,settingWarnings:b,normalizedItemReadWarnings:Ee,telemetryCheck:f,extensionCheck:g,historyPolicyWarnings:A.warnings,historySummary:E,authorAttributionWarnings:M,staleInProgressWarnings:J,provenanceWarnings:Pe,locksCheck:qe,integrityCheck:re,historyDriftCheck:be,vectorizationCheck:rt});DI({checks:it,remediationSources:se,historyDriftedCount:II(be),overThresholdCount:E.over_threshold.length,storageRemediation:Ne.remediation});let He=ye.filter(ae=>!Ed(ae,l)),$=xw({warnings:ye,checks:it,remediationSources:se,requireMergeDrivers:l}),Ve=new Set($.filter(ae=>ae.severity==="gate_failing").map(ae=>ae.check)),Ut=new Set($.map(ae=>ae.check));for(let ae of it)ae.ok=!Ve.has(ae.name),Ut.has(ae.name)&&(ae.status="warn");let Ae={ok:He.length===0,verdict:{authority:"ok",...d?{strict_exit:!0}:{},...l?{require_merge_drivers:!0}:{},exit_code:d&&He.length>0?m.GENERIC_FAILURE:0},checks:it,warnings:ye,findings:$,failed_because:He,generated_at:I()};return fd(Ae,t,y.summaryMode)}var kz={buildHierarchyIntegrityWarnings:vw,buildExtensionHealthTriageSummary:bw,buildHealthFindings:xw,buildCapabilityContractMetadata:Sc,buildStaleInProgressHealthSummary:Aw,buildVectorizationProviderDetails:Ew,collectUnknownCapabilityGuidance:kc,isAdvisoryHealthWarning:Ed,isDirectory:Cd,isExpectedUnmanagedExtension:bd,listItemDocumentPaths:ww,normalizeEndpointForDisplay:Ot,normalizeExtensionNameForMatch:Hn,parseTelemetryQueue:kw,probeTelemetryEndpointHealth:Sw,projectHealthResult:fd,resolveActionableUnknownAuthorEventCount:xd,resolveHealthSkipPolicy:Cw,resolveUnknownAuthorEventCount:Ad,resolveVectorRefreshPolicy:Tw,selectStaleItemDetail:Sd,summarizeHealthCheckDetails:pd,summarizeExtensionList:Zr,summarizeRecordList:Qe,summarizeStringList:B,telemetryEnvFlagEnabled:ns,warningCode:Td};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a07d2f98-7c1d-5d0a-be70-5181ed0f7b4f")}catch{}})();function Iw(e,t,n){if(!n.has(t.metadata.status))return{reason:"not_terminal"};if(e.length===0)return{reason:"missing_history"};if(!r_(e,t).ok)return{reason:"unverified_history"};let r=Bm(),i={reason:"no_proven_transition"};for(let[o,s]of e.entries()){let a=n.has(String(r.metadata.status));r=xp(r,s.patch,o+1,s.op),n.has(String(r.metadata.status))?a||(i=["create","close","cancel","update","update_audit"].includes(s.op)&&bm(s.ts)?{timestamp:s.ts,source_index:o+1}:{reason:"no_proven_transition"}):i={reason:"no_proven_transition"}}return i}function Ow(e){return new Set([...e.terminal_statuses,...[...e.alias_to_id].filter(([,t])=>e.terminal_statuses.has(t)).map(([t])=>t)])}async function Lw(e,t,n,r,i){let o=Ow(n),s=t.filter(d=>o.has(d.status)&&!d.closed_at),a=[],c=[];for(let d of r?s:[]){let l;try{let u=await Jt(Bt(e,d.id),d.id),{body:_,...h}=d;l=Iw(u,{metadata:h,body:_},o)}catch{c.push({id:d.id,reason:"unreadable_history"});continue}if("reason"in l){c.push({id:d.id,reason:l.reason});continue}a.push({item_id:d.id,check:"metadata",field:"closed_at",kind:"set_closed_at",value:l.timestamp,gate:"timestamps",command:"pm validate --check-metadata --auto-fix --fix-scope timestamps"})}return{details:{missing_closed_at_count:s.length,missing_closed_at_item_ids:s.slice(0,i).map(d=>d.id),missing_closed_at_item_ids_truncated:s.length>i,closure_history_inspected:r,closure_timestamp_derivable_count:a.length,closure_timestamp_residual_count:c.length,closure_timestamp_residual:c.slice(0,i),closure_timestamp_residual_truncated:c.length>i,...s.length>0?{closure_timestamp_fix_hint:"pm validate --check-metadata --auto-fix --fix-scope timestamps --dry-run"}:{}},fixes:a,warnings:s.length>0?[`validate_metadata_missing_closed_at:${s.length}`]:[]}}async function Dw(e,t){let n=R(process.cwd(),t.path),r=await x(n),i=W(r.schema);await he({pmRoot:n,settings:r,id:e.item_id,op:"update",author:U(t.author,r.author_default),message:"Backfill closed_at from verified lifecycle history",skipNoop:!0,async mutate(o){if(o.metadata.closed_at)return{changedFields:[]};let s=await Jt(Bt(n,o.metadata.id),o.metadata.id),a=Ow(i),c=Iw(s,o,a);if(!("timestamp"in c)||c.timestamp!==e.value)throw new p("Closure timestamp evidence changed or cannot be verified; rerun the timestamp repair preview.",m.GENERIC_FAILURE);return o.metadata.closed_at=c.timestamp,{changedFields:["closed_at"]}}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="34d28b31-b098-5ffd-b39b-2e11de150ac1")}catch{}})();function MI(e,t){return e==="malformed"||t==="malformed"?"malformed":e==="moved"||t==="moved"?"moved":"deleted"}function $w(e){return`${e.item_id} ${e.link_kind}`}function Nw(e,t){let n=new Map;for(let r of e){let i=n.get(r.path);i?(i.classification=MI(i.classification,r.classification),i.owners.set($w(r),r)):n.set(r.path,{classification:r.classification,owners:new Map([[$w(r),r]])})}return[...n.entries()].sort(([r],[i])=>r.localeCompare(i)).map(([r,i])=>({path:r,classification:i.classification,items:[...i.owners.values()].map(o=>{let s=t(o.item_id);return{id:o.item_id,type:s?.type??"Unknown",title:s?.title??"",status:s?.status??"",field:o.link_kind}}).sort((o,s)=>{let a=o.id.localeCompare(s.id);return a!==0?a:o.field.localeCompare(s.field)})}))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="00f8052d-480b-5e38-86cf-4574a8ad1e92")}catch{}})();function Mw(e,t,n,r,i=40){let o=i===1/0?1/0:Number.isFinite(i)?Math.max(0,Math.floor(i)):40,s=new Map(t.map(d=>[d.path,d])),a={missing_linked_path_rows_count:0,missing_linked_path_rows:[],missing_linked_path_rows_truncated:!1,missing_linked_links_count:0,active_missing_linked_links_count:0,legacy_closed_missing_linked_links_count:0,legacy_terminal_missing_linked_links_count:0,active_missing_linked_paths_count:0},c=Nw(e,n).map(d=>{let l=[],u=[];for(let h of d.items){let f=ce(h.status,r)??h.status;r.terminal_statuses.has(f)?(u.push(h),f===r.close_status&&(a.legacy_closed_missing_linked_links_count+=1)):l.push(h)}a.missing_linked_links_count+=d.items.length,a.active_missing_linked_links_count+=l.length,a.legacy_terminal_missing_linked_links_count+=u.length,l.length>0&&(a.active_missing_linked_paths_count+=1);let _=s.get(d.path);return{...d,candidates:_?.candidates??[],candidates_truncated:_?.candidates_truncated??!1,link_count:d.items.length,active_link_count:l.length,items:[...l,...u].slice(0,o),items_truncated:d.items.length>o}});return c.sort((d,l)=>+(l.active_link_count>0)-+(d.active_link_count>0)||d.path.localeCompare(l.path)),a.missing_linked_path_rows_count=c.length,a.missing_linked_path_rows=c.slice(0,o),a.missing_linked_path_rows_truncated=c.length>o,a}import Vn from"node:fs/promises";import Yn from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7ff2e182-d84c-5e1c-8b63-daea17d55af4")}catch{}})();async function PI(e,t){let n=[...new Set(Object.values(t))],r=[];return await Promise.all(n.map(async i=>{let o;try{o=await Vn.readdir(Yn.join(e,i))}catch{return}for(let s of o)for(let a of zt)if(s.toLowerCase().endsWith(a)){r.push({relativePath:`${i}/${s}`,id:s.slice(0,-a.length)});break}})),r.sort((i,o)=>i.relativePath.localeCompare(o.relativePath))}function FI(e,t){let{id:n,relativePath:r,liveItemIds:i,out:o}=e,s=xn(t);if(s){o.conflictMarkers.push({id:n,path:r,line:s.line,detail:`unresolved merge conflict marker ${s.marker}`});return}let a=jI(e,t);a!==null&&(a.op==="delete"&&i.has(n)&&o.resurrected.push({id:n,deleted_at:typeof a.ts=="string"?a.ts:"",deleted_by:typeof a.author=="string"?a.author:""}),a.op==="history_repair"&&Array.isArray(a.patch)&&a.patch.length>0&&(o.repairReconciliations+=1))}function jI(e,t){let{id:n,relativePath:r,out:i}=e,o=null,s=!1,a=t.split(/\r?\n/).map((c,d)=>({content:c.trim(),number:d+1})).filter(c=>c.content.length>0);for(let c of a){try{let d=JSON.parse(c.content);if(typeof d!="object"||d===null||Array.isArray(d))throw new TypeError("history entry must be an object");o=d}catch{return i.unparseable.push({id:n,path:r,line:c.number,detail:"history line is not a valid JSON object"}),null}if(o.op==="create"){if(s)return i.unparseable.push({id:n,path:r,line:c.number,detail:"duplicate item identity: more than one create event in one history stream"}),null;s=!0}}return o}function Rd(e,t){let n=typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"?t.code:"UNKNOWN";return`${e} could not be read (error code: ${n})`}async function UI(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},r;try{r=await Vn.readdir(Yn.join(e,"history"))}catch{return n}for(let i of r.sort((o,s)=>o.localeCompare(s))){if(!i.endsWith(".jsonl"))continue;n.scanned+=1;let o;try{o=await Vn.readFile(Yn.join(e,"history",i),"utf8")}catch(s){n.unparseable.push({id:i.slice(0,-6),path:`history/${i}`,detail:Rd("history stream",s)});continue}FI({id:i.slice(0,-6),relativePath:`history/${i}`,liveItemIds:t,out:n},o)}return n}function Pw(e){let t=xn(e);if(t)return`unresolved merge conflict marker ${t.marker} at line ${t.line}`;try{return JSON.parse(e),null}catch(n){return`invalid JSON (${String(n)})`}}async function GI(e){let t=[],n=0,r=null;try{r=await Q(Re(e))}catch(o){n+=1,t.push({path:"settings.json",detail:Rd("configuration file",o)})}if(r!==null){n+=1;let o=Pw(r);o!==null&&t.push({path:"settings.json",detail:o})}let i;try{i=await Vn.readdir(Yn.join(e,"schema"))}catch{return{scanned:n,unparseable:t}}for(let o of i.sort((s,a)=>s.localeCompare(a))){if(!o.endsWith(".json"))continue;n+=1;let s;try{s=await Vn.readFile(Yn.join(e,"schema",o),"utf8")}catch(c){t.push({path:`schema/${o}`,detail:Rd("configuration file",c)});continue}let a=Pw(s);a!==null&&t.push({path:`schema/${o}`,detail:a})}return{scanned:n,unparseable:t}}async function Fw(e,t,n,r={}){let i=await PI(e,n),o=new Set(i.map(u=>u.id)),s=new Map;for(let u of i){let _=s.get(u.id);_===void 0?s.set(u.id,[u.relativePath]):_.push(u.relativePath)}let a=[...s.entries()].filter(([,u])=>u.length>1).map(([u,_])=>({id:u,paths:[..._].sort((h,f)=>h.localeCompare(f))})).sort((u,_)=>u.id.localeCompare(_.id)),c=(await Promise.all(i.map(async u=>{if(!t.has(u.id))return{path:u.relativePath,id:u.id};try{let _=Yn.join(e,u.relativePath);return Zi(await Vn.readFile(_,"utf8"),{format:_.toLowerCase().endsWith(".md")?"json_markdown":"toon",schema:r.schema,extensionFieldNames:r.extensionFieldNames}),null}catch{return{path:u.relativePath,id:u.id}}}))).filter(u=>u!==null),d=await UI(e,o),l=await GI(e);return{item_files_on_disk:i.length,item_ids_on_disk:o.size,parsed_items:t.size,unreadable_item_files:c,duplicate_item_ids:a,history_streams_scanned:d.scanned,history_conflict_marker_streams:d.conflictMarkers,history_unparseable_streams:d.unparseable,resurrected_items:d.resurrected,history_repair_reconciliations:d.repairReconciliations,config_files_scanned:l.scanned,unparseable_config_files:l.unparseable}}import{readFileSync as qI}from"node:fs";import rs from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d88c7294-44f1-5b65-9467-f94ed2db11ca")}catch{}})();var KI=new Set(["get","history","restore","update","close","delete","append","claim","release","comments","notes","learnings","files","docs","deps","test"]),Ld=new Set(["--pm-path","--path","--author","--expect-hash"]),WI={get:new Set(["--depth","--fields","--tree-depth","--tree_depth","--at","--format"]),history:new Set(["--limit","--field","--format"]),restore:new Set(["--message"]),update:new Set(["--title","-t","--description","-d","--body","-b","--status","-s","--close-reason","--close_reason","--priority","-p","--type","--tags","--add-tags","--add_tags","--remove-tags","--remove_tags","--deadline","--estimated-minutes","--estimate","--estimated_minutes","--acceptance-criteria","--ac","--acceptance_criteria","--definition-of-ready","--definition_of_ready","--order","--rank","--goal","--objective","--value","--impact","--outcome","--why-now","--why_now","--message","--assignee","--parent","--reviewer","--risk","--confidence","--sprint","--release","--blocked-by","--blocked_by","--blocked-reason","--blocked_reason","--unblock-note","--unblock_note","--reporter","--severity","--environment","--repro-steps","--repro_steps","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual","--affected-version","--affected_version","--fixed-version","--fixed_version","--component","--regression","--customer-impact","--customer_impact","--dep","--dep-remove","--dep_remove","--comment","--note","--learning","--file","--test","--doc","--reminder","--event","--type-option","--type_option","--field","--unset","--body-file"]),close:new Set(["--reason","-r","--close-reason","--duplicate-of","-d","--message","-m","--validate-close","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual"]),delete:new Set(["--message"]),append:new Set(["--body","--text","--message"]),claim:new Set(["--assignee","--message","--type","--tag","--priority","--assignee-filter","--parent","--sprint","--release","--max-attempts"]),release:new Set(["--assignee","--message"]),comments:new Set(["--add","--body","--comment","--file","--edit","--delete","--limit","--message"]),notes:new Set(["--add","--file","--edit","--delete","--limit","--message"]),learnings:new Set(["--add","--file","--edit","--delete","--limit","--message"]),files:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),docs:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),deps:new Set(["--format","--max-depth","--collapse","--node-limit","--edge-limit","--token-budget","--cursor","--direction","--kind"]),test:new Set(["--add","--add-json","--remove","--match","--only-index","--timeout","--env-set","--env-clear","--pm-context","--message"])},zI=new Set(["-p","--package"]),BI=new Set(["-c","--call"]),Dd=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),$d=new Set(["-C","--prefix","--userconfig","--cache"]),jw=new Set(["--cwd"]),Uw=new Set(["--cwd"]),HI=new Set(["exec","x"]),Gw=new Set(["run","run-script"]),qw=new Set(["-C","--dir","--cwd","-w","--workspace","--filter"]);function sn(e){return e.split(/&&|\|\||\||;/).map(t=>t.trim()).filter(t=>t.length>0)}function ss(e,t=process.cwd()){let n=as(e.split(" ").filter(s=>s.length>0));if(n.length===0)return null;let[r,...i]=n;if(is(r)||os(r,t))return i;if(r==="node"&&i[0]&&os(i[0],t))return i.slice(1);let o=r==="npx"||r==="bunx"?an(i):r==="pnpm"?cs(i):r==="npm"?ds(i):null;return o&&(is(o.command)||Kw(o.command))?o.args:null}var Nd=(e,t="pm")=>{let n=t.trim().toLowerCase(),r=n.length;for(;r>0&&n[r-1]==="-";)r-=1;let i=n.slice(0,r);if(i.length===0)return[];let o=e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase(),s=new Set;for(let a of sn(o)){let c=ss(a),d=c?Md(c):null,l=d&&KI.has(d.subcommand)?YI(d.remaining,WI[d.subcommand]):void 0,u=l?.trim().toLowerCase();u?.startsWith(`${i}-`)===!0&&u.length>i.length+1&&s.add(l)}return[...s].sort((a,c)=>a.localeCompare(c))};function as(e){let t=0;for(e[t]==="env"&&(t+=1);t<e.length;){let n=e[t];if(/^(?:[a-z_][a-z0-9_]*|\$env:[a-z_][a-z0-9_]*)=.*/.test(n)){t+=1;continue}break}return e.slice(t)}function Od(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(Ld.has(n)){t+=2;continue}t+=1;continue}return n}}function is(e){return e==="pm"||e==="pm.cmd"||e==="pm.exe"||e.endsWith("/pm")||e.endsWith("/pm.cmd")||e.endsWith("/pm.exe")}function VI(e){let t=e.trim();if(!t.startsWith("@")){let i=t.indexOf("@");return i===-1?t:t.slice(0,i)}let n=t.indexOf("/");if(n===-1)return t;let r=t.indexOf("@",n+1);return r===-1?t:t.slice(0,r)}function Kw(e){let t=VI(e);return t==="pm-cli"||t.endsWith("/pm-cli")||e==="pm-cli"||e.endsWith("/pm-cli")}function os(e,t=process.cwd()){let n=e.replaceAll("\\","/");if(n!=="dist/cli.js"&&n!=="./dist/cli.js"&&!n.endsWith("/dist/cli.js"))return!1;let r=rs.resolve(t,e);try{return JSON.parse(qI(rs.join(rs.dirname(rs.dirname(r)),"package.json"),"utf8")).name==="@unbrained/pm-cli"}catch{return!1}}function an(e){let t=0;for(;t<e.length;){let r=e[t];if(r==="--"){t+=1;break}if(!r.startsWith("-"))break;let i=/^(?:-c|--call)=(.*)$/.exec(r);if(i){let o=i[1];return o?{command:o,args:e.slice(t+1)}:null}if(BI.has(r)){t+=1;break}t+=zI.has(r)&&!r.includes("=")?2:1}let n=e[t];return n?{command:n,args:e.slice(t+1)}:null}function Pt(e,t){let n=0;for(;n<e.length;){let r=e[n];if(r==="--"){n+=1;continue}if(r.startsWith("-")){if(r.includes("=")){n+=1;continue}if(t.has(r)){n+=2;continue}n+=1;continue}return{subcommand:r,args:e.slice(n+1)}}return null}function cs(e){let t=Pt(e,Dd);return t?.subcommand!=="dlx"?null:an(t.args)}function ds(e){let t=Pt(e,$d);return!t||!HI.has(t.subcommand)?null:an(t.args)}function Md(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(Ld.has(n)){t+=2;continue}t+=1;continue}return{subcommand:n,remaining:e.slice(t+1)}}return null}function YI(e,t=new Set){for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="--")return e[n+1];if(!r.startsWith("-"))return r;!r.includes("=")&&(Ld.has(r)||t.has(r))&&(n+=1)}}function Id(e){return!e||!is(e.command)&&!Kw(e.command)?!1:Od(e.args)==="test-all"}var Pd=new Map([...["sh","bash","dash","zsh"].map(e=>[e,/^(?:-c|-[a-z]*c[a-z]*)$/u]),...["cmd","cmd.exe"].map(e=>[e,/^\/[ck]$/u]),...["powershell","powershell.exe","pwsh","pwsh.exe"].map(e=>[e,/^-(?:c|command)$/u])]),JI=new Set(["npx","bunx"]);function Fd(e){let t=e.split(" ").filter(s=>s.length>0),n=as(t);if(n.length===0)return!1;let[r,...i]=n,o=Pd.get(r);if(o){let s=i.findIndex(a=>o.test(a));return s>=0?Fd(i.slice(s+1).join(" ")):!1}return is(r)||os(r)?Od(i)==="test-all":r==="node"&&i.length>0&&os(i[0])?Od(i.slice(1))==="test-all":JI.has(r)?Id(an(i)):r==="pnpm"?Id(cs(i)):r==="npm"?Id(ds(i)):!1}function jd(e){let t=Jn(e);return sn(t).some(n=>Fd(n))}function ti(e){if(jd(e))throw new p('Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.',m.USAGE)}function Jn(e){return e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase()}import{execFile as XI}from"node:child_process";import{readFile as QI}from"node:fs/promises";import zw from"node:path";import{promisify as ZI}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8f1a3301-8938-5208-9177-72ee29f3d174")}catch{}})();var eO=ZI(XI),Ud=1,tO="linked-test-trust.json";function Gd(e){return zw.join(am(e),tO)}function Ww(){return{version:Ud,acknowledged:{}}}async function qd(e){try{let t=JSON.parse(await QI(Gd(e),"utf8"));return t.version!==Ud||typeof t.acknowledged!="object"||t.acknowledged===null||Array.isArray(t.acknowledged)?Ww():{version:Ud,acknowledged:t.acknowledged}}catch{return Ww()}}async function ri(e=process.cwd()){let t=process.env.GITHUB_HEAD_REF?.trim()||process.env.GITHUB_REF_NAME?.trim();if(t&&t!=="merge")return t;try{let{stdout:n}=await eO("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),r=n.trim();return r.length===0?void 0:r}catch{return}}function ii(e=process.cwd()){return process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||e}function nO(e){return e===null||typeof e!="object"?!1:typeof e.author=="string"&&e.author.trim().length>0&&typeof e.created_at=="string"&&vm(e.created_at)&&(e.source_kind==="local_mutation"||e.source_kind==="merge_union")}function ni(e,t){return{...e?{source_ref:e}:{},...t?{current_source_ref:t}:{}}}function rO(e,t,n,r){return e?.map(i=>i.command&&!i.provenance?{...i,provenance:{author:t,created_at:n,source_kind:"local_mutation",...r?{source_ref:r}:{}}}:i)}async function Xn(e,t,n){if(!e||e.length===0)return e;for(let i of e)hr(i);let r=ii();return rO(e,t,n,await ri(r))}function Bw(e){return Mu(Z({command:e.command??null,path:e.path??null,scope:e.scope,pm_context_mode:e.pm_context_mode??null,workspace_context_mode:e.workspace_context_mode??null,env_set:e.env_set??null,env_clear:e.env_clear??null,shared_host_safe:e.shared_host_safe??null,provenance:e.provenance??null,provenance_invalid:e.provenance_invalid??null}))}async function Kd(e,t,n){let r=await qd(e);return Hw(t,n,r)}function Hw(e,t,n){let r=Bw(e),i=e.provenance?.source_ref;if(e.provenance===void 0&&e.provenance_invalid!==!0)return{fingerprint:r,trusted:!0,reason:"legacy"};let o=Object.hasOwn(n.acknowledged,r);return e.provenance_invalid===!0||!nO(e.provenance)?o?{fingerprint:r,trusted:!0,reason:"acknowledged",...ni(void 0,t)}:{fingerprint:r,trusted:!1,reason:"invalid_provenance",...ni(void 0,t)}:e.provenance.source_kind==="local_mutation"&&i===void 0?{fingerprint:r,trusted:!0,reason:"local_mutation",...ni(void 0,t)}:e.provenance.source_kind==="local_mutation"&&i!==void 0&&i===t?{fingerprint:r,trusted:!0,reason:"local_source_ref",source_ref:i,current_source_ref:t}:o?{fingerprint:r,trusted:!0,reason:"acknowledged",...ni(i,t)}:{fingerprint:r,trusted:!1,reason:"foreign_source_ref",...ni(i,t)}}async function Vw(e,t,n){let r=await qd(e);return t.map(i=>Hw(i,n,r))}async function Yw(e,t,n){let r=await qd(e),i=t.filter(o=>typeof o.command=="string"&&o.command.length>0).map(Bw);for(let o of i)r.acknowledged[o]={acknowledged_at:n};return await Ct(zw.dirname(Gd(e))),await je(Gd(e),`${JSON.stringify(r,null,2)}
|
|
9
|
+
`),{acknowledged:i.length,fingerprints:i}}import il from"node:fs/promises";import{realpathSync as pO}from"node:fs";import{execFile as _O}from"node:child_process";import $e from"node:path";import{promisify as fO}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8c3bbe6d-dcce-5b1a-8352-1472ab1ed6e2")}catch{}})();var iO=["metadata","resolution"],Wd=["metadata","resolution","estimates","timestamps","lifecycle"],oO="completed";function zd(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function Jw(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function Xw(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let r=Jw(n.close_reason)??oO;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:r,command:`pm update ${n.id} --resolution ${zd(r)}`,gate:"resolution"})}return t}function Qw(e){let t=[];for(let n of e){let r=Jw(n.resolution);r!==void 0&&t.push({item_id:n.id,check:"metadata",field:"close_reason",kind:"set_close_reason",value:r,command:`pm update ${n.id} --close-reason ${zd(r)}`,gate:"metadata"})}return t}function Zw(e,t){return e.map(n=>{let r=Ep(n.type,t);return{item_id:n.id,check:"metadata",field:"estimated_minutes",kind:"set_estimate",value:String(r),command:`pm update ${n.id} --estimate ${r}`,gate:"estimates"}})}function ev(e){return e.map(t=>t.grandparent_id!==void 0&&t.grandparent_active===!0?{item_id:t.id,check:"lifecycle",field:"parent",kind:"reparent",parent_id:t.grandparent_id,command:`pm update ${t.id} --parent ${t.grandparent_id}`,gate:"lifecycle"}:{item_id:t.id,check:"lifecycle",field:"parent",kind:"unset_parent",command:`pm update ${t.id} --unset parent`,gate:"lifecycle"})}function tv(e){let t=[];for(let n of e){if(n.classification!=="deleted")continue;let r=n.link_kind==="files"?"files":"docs";t.push({item_id:n.item_id,check:"files",field:n.link_kind,kind:n.link_kind==="files"?"prune_file_link":"prune_doc_link",path:n.path,command:`pm ${r} ${n.item_id} --remove ${zd(n.path)}`})}return t}function nv(e){let t=(e??[]).flatMap(r=>r.split(",")).map(r=>r.trim()).filter(r=>r.length>0);if(t.length===0){if(e!==void 0&&e.length>0)throw new p(`--fix-scope values must not be empty. Supported values: ${Wd.join(", ")}.`,m.USAGE);return new Set(iO)}let n=new Set;for(let r of t){let i=r.toLowerCase().replaceAll("-","_");if(Wd.includes(i)){n.add(i);continue}throw new p(`Unknown --fix-scope value "${r}". Supported values: ${Wd.join(", ")}.`,m.USAGE)}return n}function rv(e,t){let n=[],r=[];for(let i of e)i.gate!==void 0&&!t.has(i.gate)?r.push(i):n.push(i);return{applicable:n,gated:r}}function oi(e){return{item_id:e.item_id,check:e.check,field:e.field,command:e.command,...e.gate!==void 0?{gate:e.gate}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e93db1eb-e524-58bf-af2e-cb5f22f3047b")}catch{}})();var sO=/^([A-Z][A-Z0-9]*-\d+)\b/iu;function aO(e,t={}){if(typeof e!="string")return null;let n=e.trim();if(n.length===0)return null;let r=sO.exec(n);if(!r)return null;let i=r[1],o=i.toUpperCase(),s=i.slice(0,i.lastIndexOf("-")),a=new Set((t.configuredPrefixes??[]).map(u=>u.trim().replace(/-+$/u,"").toUpperCase())),c=n.slice(i.length),d=t.evidenceText?.toUpperCase()??"",l=d.includes(`ISSUE CODE: ${o}`)||d.includes(`ISSUE CODE \`${o}\``)||d.includes(`\`${o}\``)||d.includes(`[${o}]`);return s===s.toUpperCase()||/^\s*(?::|—|–|\])/u.test(c)||a.has(s.toUpperCase())||l?o:null}function iv(e){return typeof e=="string"&&e.trim().length>0}function cO(e){let t=new Set(e.map(s=>s.id.toLowerCase())),n=new Map,r=new Map;for(let s of e){let a=s.id.toLowerCase(),c=new Set([...s.parent===null?[]:[s.parent.toLowerCase()],...s.derivations].filter(d=>d!==a&&t.has(d)));n.set(a,c);for(let d of c){let l=r.get(d)??[];l.push(a),r.set(d,l)}}let i=[...[...n].filter(([,s])=>s.size===0).map(([s])=>s)],o=new Set;for(let s=0;s<i.length;s+=1)for(let a of r.get(i[s])??[]){let c=n.get(a);c.delete(i[s]),c.size===0&&(o.add(a),i.push(a))}return e.filter(s=>!o.has(s.id.toLowerCase()))}function ov(e,t={}){let n=new Map;for(let i of e){if(typeof i.title!="string"||iv(i.duplicate_of))continue;let o=aO(i.title,{...t,evidenceText:i.body});if(o===null)continue;let s=n.get(o);s||(s=[],n.set(o,s)),s.some(a=>a.id===i.id)||s.push({id:i.id,title:i.title,parent:iv(i.parent)?i.parent.trim():null,derivations:(i.dependencies??[]).filter(a=>["discovered_from","supersedes","incident_from"].includes(a.kind)).map(a=>a.id.trim().toLowerCase()).filter(a=>a!==i.id.toLowerCase())})}let r=[];for(let[i,o]of n){if(o.length<2)continue;let s=cO(o);if(s.length<2)continue;let a=[...s].sort((c,d)=>c.id.localeCompare(d.id));r.push({code:i,count:a.length,ids:a.map(c=>c.id),titles:a.map(c=>c.title)})}return r.sort((i,o)=>i.code.localeCompare(o.code))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3c32504d-254c-5156-a41f-8ffd8e49107f")}catch{}})();function sv(e){let t=new Map;for(let r of e){let i=t.get(r.item_type);i||(i=new Map,t.set(r.item_type,i)),i.set(r.field,(i.get(r.field)??0)+1)}let n={};for(let r of[...t.keys()].sort((i,o)=>i.localeCompare(o))){let i=t.get(r),o={};for(let s of[...i.keys()].sort((a,c)=>a.localeCompare(c)))o[s]=i.get(s);n[r]=o}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c577e41b-6642-554a-bc4d-0c22170c1e24")}catch{}})();function av(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function cv(e,t,n=3){let r=Number.isFinite(n)&&n>=1?Math.floor(n):3,i=new Map;for(let o of t){let s=av(o);if(s.length===0)continue;let a=i.get(s);a?a.push(o):i.set(s,[o])}return e.map(o=>{if(o.includes(",")||o.replace(/^[a-z]:[\\/]/i,"").includes(":"))return{path:o,classification:"malformed",candidates:[],candidates_truncated:!1};let s=(i.get(av(o))??[]).filter(a=>a!==o).sort((a,c)=>a.localeCompare(c));return s.length===0?{path:o,classification:"deleted",candidates:[],candidates_truncated:!1}:{path:o,classification:"moved",candidates:s.slice(0,r),candidates_truncated:s.length>r}})}function dv(e){return e.map(t=>t.classification==="moved"?`${t.path}:moved:${t.candidates[0]}`:`${t.path}:${t.classification}`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8cca9707-86a7-5ab5-8c7b-92be560254d0")}catch{}})();async function ls(e){return e.includeBody?gt(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema,{forceSourceScan:!0}):fo(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6322c4ff-92bd-59e5-aa64-ef8d3ef4b57f")}catch{}})();var dO=5;async function lO(e,t){let n=t.hashMismatches.filter(o=>o!==Xt);if(n.length===0)return;let r=await x(e),i=P(r,N());for(let o of n){let s=await eo(e,o,r.locks.ttl_seconds,"history-drift-read",!1,!0,r.locks.wait_ms);try{let a=await V(e,o,r.id_prefix,r.item_format,i.type_to_folder);if(a===null)throw new p(`Item ${o} not found`,m.NOT_FOUND,{code:"item_not_found",required:"Repeat validation after writers finish; each item-hash discrepancy requires readable canonical source."});let{document:c}=await pe(a,{schema:r.schema});if(c.metadata.id!==o)throw new p(`Item identity changed while validating ${o}`,m.CONFLICT,{code:"item_identity_conflict",required:"Restore the canonical item identity and validate storage integrity before retrying history validation."});let d=await Sh(e,{...c.metadata,body:c.body});for(let u of["missingStreams","unreadableStreams","hashMismatches","chainMismatches","versionSkews","driftedItems"])t[u]=[...t[u].filter(_=>_!==o),...d[u].filter(_=>_===o)].sort((_,h)=>_.localeCompare(h));let l=[...(t.identityDiscontinuities??[]).filter(u=>u.item_id!==o),...(d.identityDiscontinuities??[]).filter(u=>u.item_id===o)];l.length>0?t.identityDiscontinuities=l:delete t.identityDiscontinuities}finally{await s()}}}async function us(e,t,n){let r=await Mr(e,t);await lO(e,r);let i=[["validate_history_drift_missing_streams",r.missingStreams.length],["validate_history_drift_unreadable_streams",r.unreadableStreams.length],["validate_history_drift_hash_mismatches",r.hashMismatches.length],["validate_history_drift_chain_mismatches",r.chainMismatches.length],["validate_history_drift_version_skews",r.versionSkews.length],["validate_history_drift_workspace_state_mismatches",r.workspaceStateMismatches.length],["validate_history_drift_workspace_state_missing",r.workspaceStateMissing.length],["validate_history_drift_workspace_state_unreadable",r.workspaceStateUnreadable.length]].filter(([,c])=>c>0).map(([c,d])=>`${c}:${d}`),o=n?Number.POSITIVE_INFINITY:dO,s=r.driftedItems.slice(0,o),a=r.identityDiscontinuities??[];return{check:{name:"history_drift",status:a.length>0?"error":i.length===0?"ok":"warn",ok:a.length===0&&i.length===0,details:{identity_discontinuities:a.slice(0,o),identity_discontinuities_count:a.length,identity_discontinuities_truncated:a.length>o,checked_items:t.length,drifted_items_count:r.driftedItems.length,drifted_items:s,drifted_items_truncated:s.length<r.driftedItems.length,counts:{missing_streams:r.missingStreams.length,unreadable_streams:r.unreadableStreams.length,hash_mismatches:r.hashMismatches.length,chain_mismatches:r.chainMismatches.length,version_skews:r.versionSkews.length,workspace_state_mismatches:r.workspaceStateMismatches.length,workspace_state_missing:r.workspaceStateMissing.length,workspace_state_unreadable:r.workspaceStateUnreadable.length},workspace_state_mismatches:r.workspaceStateMismatches,workspace_state_missing:r.workspaceStateMissing,workspace_state_unreadable:r.workspaceStateUnreadable,version_skews:r.versionSkews.slice(0,o)}},warnings:i}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fb73b204-3c60-5b9b-9576-e1c13ad537b3")}catch{}})();function Bd(e){let t=0,n=new Map,r=new Map,i=[],o=new Set,s=[],a=d=>{n.set(d,t),r.set(d,t),t+=1,i.push(d),o.add(d);for(let u of e.get(d)??[])n.has(u)?o.has(u)&&r.set(d,Math.min(r.get(d),n.get(u))):(a(u),r.set(d,Math.min(r.get(d),r.get(u))));if(r.get(d)!==n.get(d))return;let l=[];for(;i.length>0;){let u=i.pop();if(o.delete(u),l.push(u),u===d)break}l.sort((u,_)=>u.localeCompare(_)),s.push(l)},c=[...e.keys()].sort((d,l)=>d.localeCompare(l));for(let d of c)n.has(d)||a(d);return s.filter(d=>{if(d.length>1)return!0;let l=d[0];return(e.get(l)??[]).includes(l)}).sort((d,l)=>d[0].localeCompare(l[0])||d.length-l.length||d.join(",").localeCompare(l.join(",")))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3caaa82b-d8c7-5bc4-94e5-6699da27fa3c")}catch{}})();function ms(e,t){let n=e[0];if(e.length===1)return[n,n];let r=new Set(e),i=[n],o=new Set([n]),s=a=>{for(let c of(t.get(a)??[]).filter(d=>r.has(d))){if(c===n&&i.length>1)return i.push(n),!0;if(!o.has(c)){if(o.add(c),i.push(c),s(c))return!0;i.pop(),o.delete(c)}}return!1};return s(n)?[...i]:[...e,n]}function uO(e,t){if(typeof e!="string")return;let n=e.trim().toLowerCase();return n.length>0?t.get(n):void 0}function mO(e,t,n,r){for(let i of e.dependencies??[]){if(typeof i!="object"||i===null||typeof i.id!="string")continue;let o=r.resolve(i.kind);if(!o?.hierarchy)continue;let s=n.get(i.id.toLowerCase());s&&(o.hierarchyDirection==="source_parent"?t.get(s).push(e.id):t.get(e.id).push(s))}}function Hd(e,t=de()){let n=new Map(e.map(i=>[i.id.toLowerCase(),i.id])),r=new Map(e.map(i=>[i.id,[]]));for(let i of[...e].sort((o,s)=>o.id.localeCompare(s.id))){let o=r.get(i.id),s=uO(i.parent,n);s&&o.push(s),mO(i,r,n,t)}for(let[i,o]of r)r.set(i,[...new Set(o)].sort());return r}function Vd(e,t,n=de()){let r=Co(e,s=>t?At(s,t):s==="closed"||s==="canceled",n),i=Hd(e,n),o=r.cycles.map(s=>s.item_ids);return{cycle_count:o.length,active_cycle_count:r.cycles.filter(s=>!s.legacy_terminal).length,legacy_cycle_count:r.cycles.filter(s=>s.legacy_terminal).length,cycle_item_ids:[...new Set(o.flat())].sort(),cycle_sample_paths:o.map(s=>ms(s,i).join("->")),cardinality_violation_count:r.cardinality_violations.length,active_cardinality_violation_count:r.cardinality_violations.filter(s=>!s.legacy_terminal).length,legacy_cardinality_violation_count:r.cardinality_violations.filter(s=>s.legacy_terminal).length,cardinality_violation_rows:r.cardinality_violations.map(s=>`${s.child_id}:${s.parent_ids.join(",")}:${s.legacy_terminal?"legacy":"active"}`),parent_divergence_count:r.divergences.length,active_parent_divergence_count:r.divergences.filter(s=>!s.legacy_terminal).length,legacy_parent_divergence_count:r.divergences.filter(s=>s.legacy_terminal).length,parent_divergence_rows:r.divergences.map(s=>`${s.child_id}:scalar=${s.scalar_parent_id}:dependencies=${s.dependency_parent_ids.join(",")}:${s.legacy_terminal?"legacy":"active"}`)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f2840c80-38f5-5563-b2c0-ef5596cf8f62")}catch{}})();function Ft(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/^\/+/,"")}function Yd(e){return Ft(e).replace(/\/+$/,"")}function Ze(e){let t=oe(e);if(!t)return;let n=t.toLowerCase();if(!(n==="none"||n==="null"||n==="n/a"||n==="na"))return t}function Jd(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length>120?`${t.slice(0,117)}...`:t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e046350f-afca-59d1-83c0-5df1e837d59d")}catch{}})();var hO=["src","tests","docs"],gO=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],yO=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),wO=["resolution","expected_result","actual_result"],vO=["default","tracked-all","tracked-all-strict"],lv=["core","strict","custom"],fs=["off","warn","error"],Zd=["author","acceptance_criteria","estimated_minutes","close_reason"],pv=[...Zd,"reviewer","risk","confidence","sprint","release"],el=Array.from(new Set(pv)),bO={author:"author",acceptance_criteria:"acceptance_criteria","acceptance-criteria":"acceptance_criteria",estimated_minutes:"estimated_minutes","estimated-minutes":"estimated_minutes",estimate:"estimated_minutes",close_reason:"close_reason","close-reason":"close_reason",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release"},kO={author:"validate_metadata_missing_author",acceptance_criteria:"validate_metadata_missing_acceptance_criteria",estimated_minutes:"validate_metadata_missing_estimate",close_reason:"validate_metadata_missing_close_reason",reviewer:"validate_metadata_missing_reviewer",risk:"validate_metadata_missing_risk",confidence:"validate_metadata_missing_confidence",sprint:"validate_metadata_missing_sprint",release:"validate_metadata_missing_release"},SO={author:"missing_author",acceptance_criteria:"missing_acceptance_criteria",estimated_minutes:"missing_estimated_minutes",close_reason:"closed_missing_close_reason",reviewer:"missing_reviewer",risk:"missing_risk",confidence:"missing_confidence",sprint:"missing_sprint",release:"missing_release"},EO={author:"missing_author_item_ids",acceptance_criteria:"missing_acceptance_criteria_item_ids",estimated_minutes:"missing_estimated_minutes_item_ids",close_reason:"closed_missing_close_reason_item_ids",reviewer:"missing_reviewer_item_ids",risk:"missing_risk_item_ids",confidence:"missing_confidence_item_ids",sprint:"missing_sprint_item_ids",release:"missing_release_item_ids"},TO={author:"missing_author_truncated",acceptance_criteria:"missing_acceptance_criteria_truncated",estimated_minutes:"missing_estimated_minutes_truncated",close_reason:"closed_missing_close_reason_truncated",reviewer:"missing_reviewer_truncated",risk:"missing_risk_truncated",confidence:"missing_confidence_truncated",sprint:"missing_sprint_truncated",release:"missing_release_truncated"},CO=32*1024*1024,AO=1e4,tl=40,et=5,xO=4096,RO=255,IO=fO(_O);function _v(e){let t={};for(let[n,r]of Object.entries(e))Array.isArray(r)||r===!1&&n.endsWith("_truncated")||(t[n]=typeof r=="object"&&r!==null?_v(r):r);return t}function OO(e){return{...e,checks:e.checks.map(t=>({...t,details:_v(t.details)})),...e.fixes?{fixes:{mode:e.fixes.mode,auto_fix:e.fixes.auto_fix,prune_missing:e.fixes.prune_missing,planned_count:e.fixes.planned_count,applied_count:e.fixes.applied_count,gated_count:e.fixes.gated_count,failed_count:e.fixes.failed_count}}:{}}}function gs(e,t){return ce(e,t)??e}function si(e,t){return t.terminal_statuses.has(gs(e,t))}function jt(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function ps(e,t){return e.length!==t.length?!1:e.every((n,r)=>n===t[r])}function LO(e){let t=jt(Nu),n={blocked_reason:jt(Ri.blocked_reason),resolution:jt(Ri.resolution),actual_result:jt(Ri.actual_result)},r=jt(e.validation.lifecycle_stale_blocker_reason_patterns),i={blocked_reason:jt(e.validation.lifecycle_closure_like_blocked_reason_patterns),resolution:jt(e.validation.lifecycle_closure_like_resolution_patterns),actual_result:jt(e.validation.lifecycle_closure_like_actual_result_patterns)};return{stale_blocker_reason_patterns:r,stale_blocker_reason_pattern_source:ps(r,t)?"default":"settings",closure_like_metadata_field_patterns:i,closure_like_metadata_field_pattern_sources:{blocked_reason:ps(i.blocked_reason,n.blocked_reason)?"default":"settings",resolution:ps(i.resolution,n.resolution)?"default":"settings",actual_result:ps(i.actual_result,n.actual_result)?"default":"settings"}}}function fv(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"core";if(lv.includes(t))return t;throw new p(`Unknown --metadata-profile value "${e}". Supported values: ${lv.join(", ")}.`,m.USAGE)}function hv(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(fs.includes(t))return t;throw new p(`Unknown --dependency-cycle-severity value "${e}". Supported values: ${fs.join(", ")}.`,m.USAGE)}function gv(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(fs.includes(t))return t;throw new p(`Unknown --parent-cycle-severity value "${e}". Supported values: ${fs.join(", ")}.`,m.USAGE)}function DO(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase().replaceAll("-","_")))].map(t=>bO[t]).filter(t=>t!==void 0).sort((t,n)=>t.localeCompare(n))}function $O(e,t,n){let r=DO(n);return e==="core"?{profile:e,profile_source:t,required_fields:[...Zd],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:e==="strict"?{profile:e,profile_source:t,required_fields:[...pv],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:r.length>0?{profile:e,profile_source:t,required_fields:r,configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:{profile:e,profile_source:t,required_fields:[...Zd],configured_custom_fields:r,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}var NO=new Set(["acceptance_criteria","estimated_minutes"]);function yv(e,t,n,r){return!r&&NO.has(t)&&si(e.status,n)?!1:t==="author"?!oe(e.author):t==="acceptance_criteria"?!oe(e.acceptance_criteria):t==="estimated_minutes"?!Number.isFinite(e.estimated_minutes):t==="close_reason"?gs(e.status,n)===n.close_status&&!oe(e.close_reason):t==="reviewer"?!oe(e.reviewer):t==="risk"?!oe(e.risk):t==="confidence"?typeof e.confidence=="number"?!Number.isFinite(e.confidence):!oe(e.confidence):t==="sprint"?!oe(e.sprint):!oe(e.release)}function wv(e){if(e===void 0)return"default";let t=e.trim().toLowerCase();if(t.length===0||t==="default")return"default";if(t==="tracked-all"||t==="tracked_all")return"tracked-all";if(t==="tracked-all-strict"||t==="tracked_all_strict")return"tracked-all-strict";throw new p(`Unknown --scan-mode value "${e}". Supported values: ${vO.join(", ")}.`,m.USAGE)}function vv(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim();if(t)return $e.resolve(t);let n=$e.resolve(e);if(n.replaceAll("\\","/").endsWith("/.agents/pm"))return $e.dirname($e.dirname(n));let r=$e.resolve(process.cwd()),i=uv(n),o=uv(r),s=$e.relative(i,o);return s.length===0||!s.startsWith("..")&&!$e.isAbsolute(s)?n:r}function uv(e){try{return pO.native(e)}catch{return $e.resolve(e)}}function MO(e,t){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&t.includes(e.code)}async function ol(e,t,n){let r=t.length>0?$e.join(e,t):e,i;try{i=await il.readdir(r,{withFileTypes:!0})}catch(o){if(G(o))return;throw o}for(let o of i){if(o.name.startsWith("."))continue;let s=t.length>0?$e.join(t,o.name):o.name;if(o.isDirectory()){if(yO.has(o.name))continue;await ol(e,s,n);continue}o.isFile()&&n.push(Ft(s))}}async function nl(e){let t=[];for(let n of hO)await ol(e,n,t);for(let n of gO){let r=$e.join(e,n);try{(await il.stat(r)).isFile()&&t.push(Ft(n))}catch{}}return[...new Set(t)].sort((n,r)=>n.localeCompare(r))}async function bv(e){try{let{stdout:t}=await IO("git",["ls-files","-z"],{cwd:e,encoding:"utf8",maxBuffer:CO,windowsHide:!0,timeout:AO}),n=t.split("\0").map(r=>Ft(r)).filter(r=>r.length>0);return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}catch{return null}}function PO(e,t){let n=new Set,r=Yd(Lu);r.length>0&&n.add(r);let i=Yd($e.relative(t,e));return i.length>0&&!i.startsWith("..")&&n.add(i),[...n].sort((o,s)=>o.localeCompare(s))}function mv(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}async function FO(e,t){if(t==="tracked-all"||t==="tracked-all-strict"){let r=await bv(e);if(r)return{requestedMode:t,appliedMode:t,source:"tracked-git",candidateFiles:r,candidateTotal:r.length,candidateScanned:r.length};let i=await nl(e);return{requestedMode:t,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:i,candidateTotal:i.length,candidateScanned:i.length}}let n=await nl(e);return{requestedMode:t,appliedMode:"default",source:"default-curated",candidateFiles:n,candidateTotal:n.length,candidateScanned:n.length}}function ne(e,t=et){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function cn(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=ne(e,tl);return{values:n.values,truncated:n.truncated,total:e.length}}var jO={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},UO={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function GO(e){let t=e.missing_fields.map(n=>`${jO[n]} "${UO[n]}"`).join(" ");return`pm update ${e.id} ${t} --message "Backfill resolution metadata"`}function kv(e,t){let n=e.details?.missing_resolution_remediation_hints,r=Array.isArray(n)&&n.length>0,i=r?n.filter(s=>typeof s=="string"):dw(t);if(i.length===0)return;let o=r&&e.details?.missing_resolution_remediation_hints_truncated===!0;e.details={...e.details,fix_hints:i,...o?{fix_hints_truncated:!0}:{}}}function Sv(e){let t=new Set;return e.checkCompleteness&&t.add("completeness"),e.checkMetadata&&t.add("metadata"),e.checkResolution&&t.add("resolution"),(e.checkLifecycle||e.checkStaleBlockers)&&t.add("lifecycle"),e.checkFiles&&t.add("files"),e.checkHistoryDrift&&t.add("history_drift"),e.checkCommandReferences&&t.add("command_references"),e.checkStorageIntegrity&&t.add("storage_integrity"),t.size===0?(e.autoFix&&(t.add("metadata"),t.add("resolution"),t.add("lifecycle")),e.pruneMissing&&t.add("files"),t.size===0&&(t.add("metadata"),t.add("resolution"),t.add("lifecycle"),t.add("files"),t.add("command_references"),t.add("history_drift"),t.add("format_version"),t.add("completeness"),t.add("storage_integrity")),t):(e.pruneMissing&&t.add("files"),t)}var qO="validate_metadata_duplicate_issue_codes";function Ev(e,t){if(e.length===0)return{rows:[],truncated:!1,warnings:[]};let n=t?e.length:et,r=e.slice(0,n);return{rows:r.map(i=>({code:i.code,count:i.count,ids:i.ids,titles:i.titles,remediation_hint:`Items ${i.ids.join(", ")} share issue code "${i.code}"; rename or merge so each logical code maps to one item.`})),truncated:r.length<e.length,warnings:[`${qO}:${e.length}`]}}function KO(e,t,n){let r=Object.fromEntries(el.map(i=>[i,[]]));for(let i of e)for(let o of el)yv(i,o,t,n)&&r[o].push(i.id);return r}function WO(e,t,n){let r=[...e.warnings];for(let i of e.required_fields){let o=t[i];o.length>0&&r.push(`${kO[i]}:${o.length}`)}return r.push(...n),r}function Tv(e,t){let n={};for(let r of e.required_fields){let i=t[r],o=i?i.length:0,s=SO[r];n[s]=o}return n}function Cv(e,t,n){let r=[];for(let i of e.required_fields){let o=t[i];if(o)for(let s of o){let a=n.get(s)?.type,c=typeof a=="string"&&a.length>0?a:"Unknown";r.push({item_type:c,field:i})}}return r}function zO(e,t,n,r){for(let i of t.required_fields){let o=n[i];if(!o||o.length===0)continue;let s=EO[i],a=TO[i];if(!s||!a)continue;let c=ne(o,r?o.length:et);e[s]=c.values,e[a]=c.truncated}}function Av(e,t,n){if(!e.required_fields.includes("close_reason"))return[];let r=t.close_reason;return r?r.map(i=>({id:i,resolution:oe(n.get(i)?.resolution)})):[]}function xv(e,t,n){if(!e.required_fields.includes("estimated_minutes"))return[];let r=t.estimated_minutes;return r?r.map(i=>({id:i,type:oe(n.get(i)?.type)})):[]}function BO(e,t,n,r,i){let o=new Map(e.map(v=>[v.id,v])),s=t.profile==="strict",a=KO(e,n,s),c=ov(e,{configuredPrefixes:i}),d=Ev(c,r),l=WO(t,a,d.warnings),u=Tv(t,a),_=Cv(t,a,o),h=sv(_),f={checked_items:e.length,metadata_profile:t.profile,metadata_profile_source:t.profile_source,metadata_profile_fallback_to_core:t.fallback_to_core,required_fields:[...t.required_fields],supported_required_fields:[...el],counts:u,missing_by_type:h,duplicate_issue_codes_count:c.length,duplicate_issue_codes:d.rows,duplicate_issue_codes_truncated:d.truncated};t.configured_custom_fields.length>0&&(f.configured_custom_required_fields=[...t.configured_custom_fields]);let g=ts(e,r);g!==void 0&&(f.deferred_fields=g.details,l.push(g.warning)),zO(f,t,a,r);let y=Av(t,a,o),w=xv(t,a,o);return{check:{name:"metadata",status:l.length===0?"ok":"warn",ok:l.length===0,details:f},warnings:l,closeReasonBackfillRows:y,estimateBackfillRows:w}}function HO(e,t,n){let r=new Set(t.terminal_done_statuses);r.add(t.close_status);let i=e.filter(_=>r.has(gs(_.status,t))),o=[],s=[];for(let _ of i){let h=wO.filter(f=>!oe(_[f]));h.length!==0&&(o.push({id:_.id,missing_fields:h}),s.push({id:_.id,missing_fields:h,close_reason:oe(_.close_reason)}))}let a=o.length>0?[`validate_resolution_missing_fields:${o.length}`]:[],c=n?Number.POSITIVE_INFINITY:et,d=ne(o.map(_=>`${_.id}:${_.missing_fields.join(",")}`),c),l=o.map(_=>GO(_)),u=ne(l,c);return{check:{name:"resolution",status:a.length===0?"ok":"warn",ok:a.length===0,details:{checked_closed_items:i.length,missing_resolution_items:o.length,missing_resolution_rows:d.values,missing_resolution_rows_truncated:d.truncated,missing_resolution_remediation_hints:u.values,missing_resolution_remediation_hints_truncated:u.truncated}},warnings:a,resolutionBackfillRows:s}}function Rv(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Iv(e,t="pm",n=cp()){let r=new Set(e.map(o=>o.id)),i=[...e].sort((o,s)=>o.id.localeCompare(s.id));return new Map(i.map(o=>{let s=new Set,a=Ze(o.blocked_by);a&&r.has(a)&&s.add(a),(o.dependencies??[]).filter(d=>{let l=Ze(d.kind);return l!==void 0&&n.resolve(l)?.ordering===!0}).map(d=>Ze(d.id)).filter(d=>d!==void 0&&r.has(d)).forEach(d=>s.add(d));let c=Ze(o.definition_of_ready);return Lv(c??"",t).filter(d=>r.has(d)).forEach(d=>s.add(d)),[o.id,[...s].sort((d,l)=>d.localeCompare(l))]}))}function Ov(e,t,n){let r=dh(e,n?l=>si(l,n):void 0),i=r.active.map(l=>`${l.holder_id}:${l.target_id}:${l.kind}`),o=r.legacy_terminal.map(l=>`${l.holder_id}:${l.target_id}:${l.kind}:${l.holder_status}`),s=t?Number.POSITIVE_INFINITY:et,a=ne(i,s),c=ne(o,s),d=ne(r.active.map(l=>l.source==="parent"?`pm update ${l.holder_id} --unset parent`:l.source==="blocked_by"?`pm update ${l.holder_id} --unset blocked_by`:`pm update ${l.holder_id} --replace-deps '<correct dependency edges>'`),s);return{check:{name:"dependency_references",status:i.length===0?"ok":"warn",ok:i.length===0,details:{checked_items:e.length,dangling_reference_count:i.length+o.length,active_dangling_reference_count:i.length,dangling_reference_rows:a.values,dangling_reference_rows_truncated:a.truncated,legacy_terminal_dangling_reference_count:o.length,legacy_closed_dangling_reference_count:r.legacy_terminal.filter(l=>l.holder_status==="closed").length,legacy_terminal_dangling_reference_rows:c.values,legacy_terminal_dangling_reference_rows_truncated:c.truncated,no_active_blocker_sentinel_count:r.no_active_blocker_sentinels.length,remediation_hints:d.values,remediation_hints_truncated:d.truncated}},warnings:i.length>0?[`validate_dangling_dependency_references:${i.length}`]:[]}}function Lv(e,t="pm"){let n=(t.trim().toLowerCase()||"pm").replace(/-+$/g,""),r=new RegExp(`(?:^|[^a-z0-9-])(${Rv(n)}-[a-z0-9][a-z0-9-]*)`,"gi");return[...new Set([...e.matchAll(r)].map(i=>i[1].toLowerCase()))].sort((i,o)=>i.localeCompare(o))}function Dv(e,t="pm"){let n=Iv(e,t),r=Bd(n),i=[...new Set(r.flat())].sort((s,a)=>s.localeCompare(a)),o=r.map(s=>ms(s,n).join("->"));return{cycle_count:r.length,cycle_item_ids:i,cycle_sample_paths:o}}function $v(e){return e.startsWith("docs/")?"docs_unowned":e.startsWith("tests/")?"tests_unowned":e.startsWith("src/")?"source_unowned":e.endsWith(".md")?"docs_unowned":"unlinked_existing"}function hs(e){let t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function Nv(e,t){let n=hs(e).split("/").filter(Boolean),r=hs(t).split("/").filter(Boolean),i=0;for(;i<n.length&&i<r.length&&n[i]===r[i];)i+=1;return i}function VO(e,t){let n=hs(t),r=hs(e),i=t.endsWith("/")?t:`${t}/`,o=e.startsWith(i),s=n.length>0&&n===r,a=Nv(e,t);return!o&&!s&&a===0?null:o?{score:t.length+1e3,confidence:"path_prefix"}:s?{score:a+500,confidence:"same_directory"}:{score:a,confidence:"shared_directory"}}function YO(e,t,n){return e===void 0||n>e.score||n===e.score&&t.id.localeCompare(e.item.id)<0}function JO(e,t,n){let r=t==="docs_unowned"?"docs":"files",i;return n.flatMap(o=>(r==="docs"?o.docs??[]:o.files??[]).map(s=>({item:o,link:s}))).forEach(({item:o,link:s})=>{if(s.scope!=="project")return;let a=Ft(s.path);if(a.length===0||a===e)return;let c=VO(e,a);c!==null&&YO(i,o,c.score)&&(i={item:o,score:c.score,confidence:c.confidence})}),i?{id:i.item.id,type:i.item.type,title:i.item.title,status:i.item.status,confidence:i.confidence}:null}function Mv(e,t){return e.map(n=>{let r=$v(n),i=r==="docs_unowned"?"docs":"files",o=JO(n,r,t),s=o?.id??"<id>";return{path:n,classification:r,owner_candidate:o,remediation_hint:`pm ${i} ${s} --add path=${n},scope=project,note="<why this artifact belongs to the item>"`}})}function Pv(e){return e.map(t=>`${t.path}:${t.classification} owner_candidate=${t.owner_candidate?.id??"unowned"} hint=${JSON.stringify(t.remediation_hint)}`)}function XO(e,t){return Object.entries(t.closure_like_metadata_field_patterns).filter(([n,r])=>{let i=Ze(e[n]);return i?r.some(o=>i.toLowerCase().includes(o)):!1}).map(([n])=>n).sort((n,r)=>n.localeCompare(r))}function QO(e,t,n,r,i){let o=Ze(t.parent),s=o?n.get(r.get(o.toLowerCase())??o):void 0;return{id:e.id,parent_id:t.id,grandparent_id:s?.id,grandparent_active:s!==void 0&&!si(s.status,i)}}function ZO(e,t,n,r){let i=Ze(e.blocked_by),o=Ze(e.blocked_reason),s=o?.toLowerCase(),a=gs(e.status,n),c=[];return t.has(a)?(!i&&!o&&c.push("blocked_status_missing_blocker_context"),s?.includes("no active blocker")&&c.push("blocked_status_reason_reports_no_active_blocker"),s&&r.stale_blocker_reason_patterns.some(d=>s.includes(d))&&c.push("blocked_status_reason_matches_stale_pattern"),c):(i&&c.push("non_blocked_status_has_blocked_by"),o&&c.push("non_blocked_status_has_blocked_reason"),c)}function eL(e,t,n,r){let i=new Map(e.map(c=>[c.id,c])),o=new Map(e.map(c=>[c.id.toLowerCase(),c.id])),s=n.blocked_statuses.size>0?n.blocked_statuses:new Set(["blocked"]),a={activeItems:e.filter(c=>!si(c.status,n)),closureLikeRows:[],terminalParentRows:[],terminalParentFixRows:[],staleBlockerRows:[]};for(let c of a.activeItems){let d=XO(c,r);d.length>0&&a.closureLikeRows.push({id:c.id,fields:d});let l=Ze(c.parent),u=l?i.get(o.get(l.toLowerCase())??l):void 0;if(u&&si(u.status,n)&&(a.terminalParentRows.push({id:c.id,parent_id:u.id,parent_status:u.status}),a.terminalParentFixRows.push(QO(c,u,i,o,n))),t){let _=ZO(c,s,n,r);_.length>0&&a.staleBlockerRows.push({id:c.id,status:c.status,reasons:[...new Set(_)].sort((h,f)=>h.localeCompare(f))})}}return a}function tL(e){e.closureLikeRows.sort((t,n)=>t.id.localeCompare(n.id)),e.terminalParentRows.sort((t,n)=>t.id.localeCompare(n.id)||t.parent_id.localeCompare(n.parent_id)),e.terminalParentFixRows.sort((t,n)=>t.id.localeCompare(n.id)||t.parent_id.localeCompare(n.parent_id)),e.staleBlockerRows.sort((t,n)=>t.id.localeCompare(n.id))}function _s(e,t,n){return n<=0||t==="off"?null:`${t==="error"?`${e}_error`:e}:${n}`}function Xd(e,t,n){return n>0&&t!=="off"?`${e}:${n}`:null}function nL(e,t,n,r,i){let o=[];e.closureLikeRows.length>0&&o.push(`validate_lifecycle_active_closure_like_metadata:${e.closureLikeRows.length}`),e.terminalParentRows.length>0&&o.push(`validate_lifecycle_active_terminal_parent:${e.terminalParentRows.length}`),t&&e.staleBlockerRows.length>0&&o.push(`validate_lifecycle_stale_blockers:${e.staleBlockerRows.length}`);let s=_s("validate_lifecycle_dependency_cycles",n,i.dependencyCycles),a=_s("validate_hierarchy_parent_cycle",r,i.activeHierarchyCycles),c=_s("validate_hierarchy_cardinality_violation",r,i.activeHierarchyCardinality),d=_s("validate_hierarchy_parent_divergence",r,i.activeHierarchyDivergence),l=Xd("validate_legacy_hierarchy_parent_cycle",r,i.legacyHierarchyCycles),u=Xd("validate_legacy_hierarchy_cardinality_violation",r,i.legacyHierarchyCardinality),_=Xd("validate_legacy_hierarchy_parent_divergence",r,i.legacyHierarchyDivergence);return[...o,...s?[s]:[],...a?[a]:[],...c?[c]:[],...d?[d]:[],...l?[l]:[],...u?[u]:[],..._?[_]:[]]}function Fv(e){let t=Ft(e);return t.length>xO||t.split(/[\\/]/).some(n=>n.length>RO)}async function rL(e,t){let n=$e.isAbsolute(t)?t:$e.resolve(e,t);if(Fv(n))return!1;try{let r=await il.stat(n);return!r.isFile()&&!r.isDirectory()}catch(r){return MO(r,["ENOENT","ENOTDIR"])}}async function iL(e,t){let n={linkedProjectPaths:new Set,remoteLinkedPaths:new Set,missingLinkedPaths:[],staleLinkRows:[]},r=e.flatMap(i=>[...(i.files??[]).map(o=>({item:i,artifact:o,link_kind:"files"})),...(i.docs??[]).map(o=>({item:i,artifact:o,link_kind:"docs"}))]);for(let{item:i,artifact:o,link_kind:s}of r){if(o.scope!=="project")continue;if(Jr(o.path)){n.remoteLinkedPaths.add(o.path.trim());continue}let a=Ft(o.path);a.length!==0&&(n.linkedProjectPaths.add(a),await rL(t,o.path)&&(n.missingLinkedPaths.push(a),n.staleLinkRows.push({item_id:i.id,path:a,link_kind:s})))}return n}function oL(e,t,n,r,i,o){let s=r==="tracked-all-strict",a=s&&!i,c=i||s,d=c?[]:PO(t,n),l=d.length===0?[]:e.candidateFiles.filter(h=>mv(h,d)),u=d.length===0?e.candidateFiles:e.candidateFiles.filter(h=>!mv(h,d)),_={};if(l.length>0){let h=cn(l,o);_.pm_internals={count:l.length,paths:h.values,paths_truncated:h.truncated,paths_total:h.total}}return{strictTrackedAllMode:s,strictModeForcesPmInternals:a,includePmInternalsEffective:c,pmInternalCandidatePrefixes:d,excludedPmInternalPaths:l,candidateFiles:u,excludedByReason:_}}function jv(e,t,n,r,i,o,s,a="pm"){let c=eL(e,t,i,o);tL(c);let d=Dv(c.activeItems,a),l=Vd(e,i),u=Qo(i,e,s?Number.POSITIVE_INFINITY:et),_=[...nL(c,t,n,r,{dependencyCycles:d.cycle_count,activeHierarchyCycles:l.active_cycle_count,activeHierarchyCardinality:l.active_cardinality_violation_count,activeHierarchyDivergence:l.active_parent_divergence_count,legacyHierarchyCycles:l.legacy_cycle_count,legacyHierarchyCardinality:l.legacy_cardinality_violation_count,legacyHierarchyDivergence:l.legacy_parent_divergence_count}),...Zo(u)],h=s?Number.POSITIVE_INFINITY:et,f=ne(c.closureLikeRows.map(C=>`${C.id}:${C.fields.join(",")}`),h),g=ne(c.terminalParentRows.map(C=>`${C.id}:${C.parent_id}:${C.parent_status}`),h),y=ne(c.staleBlockerRows.map(C=>`${C.id}:${C.status}:${C.reasons.join(",")}`),h),w=ne(d.cycle_item_ids,h),v=ne(d.cycle_sample_paths,h),k=ne(l.cycle_item_ids,h),S=ne(l.cycle_sample_paths,h),b=ne(l.cardinality_violation_rows,h),A=ne(l.parent_divergence_rows,h),E=d.cycle_count>0&&n==="error"||(l.active_cycle_count>0||l.active_cardinality_violation_count>0||l.active_parent_divergence_count>0)&&r==="error";return{check:{name:"lifecycle",status:E?"error":_.length===0?"ok":"warn",ok:!E&&_.length===0,details:{checked_active_items:c.activeItems.length,lifecycle_status_roles:u,active_closure_like_metadata_items:c.closureLikeRows.length,active_closure_like_metadata_rows:f.values,active_closure_like_metadata_rows_truncated:f.truncated,active_terminal_parent_items:c.terminalParentRows.length,active_terminal_parent_rows:g.values,active_terminal_parent_rows_truncated:g.truncated,stale_blocker_checks_enabled:t,stale_blocker_items:c.staleBlockerRows.length,stale_blocker_rows:y.values,stale_blocker_rows_truncated:y.truncated,dependency_cycle_severity_policy:n,dependency_cycle_count:d.cycle_count,dependency_cycle_item_count:d.cycle_item_ids.length,dependency_cycle_item_ids:w.values,dependency_cycle_item_ids_truncated:w.truncated,dependency_cycle_sample_paths:v.values,dependency_cycle_sample_paths_truncated:v.truncated,parent_cycle_severity_policy:r,parent_cycle_count:l.cycle_count,active_parent_cycle_count:l.active_cycle_count,legacy_parent_cycle_count:l.legacy_cycle_count,parent_cycle_item_count:l.cycle_item_ids.length,parent_cycle_item_ids:k.values,parent_cycle_item_ids_truncated:k.truncated,parent_cycle_sample_paths:S.values,parent_cycle_sample_paths_truncated:S.truncated,hierarchy_cardinality_violation_count:l.cardinality_violation_count,active_hierarchy_cardinality_violation_count:l.active_cardinality_violation_count,legacy_hierarchy_cardinality_violation_count:l.legacy_cardinality_violation_count,hierarchy_cardinality_violation_rows:b.values,hierarchy_cardinality_violation_rows_truncated:b.truncated,hierarchy_parent_divergence_count:l.parent_divergence_count,active_hierarchy_parent_divergence_count:l.active_parent_divergence_count,legacy_hierarchy_parent_divergence_count:l.legacy_parent_divergence_count,hierarchy_parent_divergence_rows:A.values,hierarchy_parent_divergence_rows_truncated:A.truncated,stale_blocker_reason_patterns:[...o.stale_blocker_reason_patterns],stale_blocker_reason_pattern_source:o.stale_blocker_reason_pattern_source,closure_like_blocked_reason_patterns:[...o.closure_like_metadata_field_patterns.blocked_reason],closure_like_blocked_reason_pattern_source:o.closure_like_metadata_field_pattern_sources.blocked_reason,closure_like_resolution_patterns:[...o.closure_like_metadata_field_patterns.resolution],closure_like_resolution_pattern_source:o.closure_like_metadata_field_pattern_sources.resolution,closure_like_actual_result_patterns:[...o.closure_like_metadata_field_patterns.actual_result],closure_like_actual_result_pattern_source:o.closure_like_metadata_field_pattern_sources.actual_result}},warnings:_,terminalParentFixRows:c.terminalParentFixRows}}async function Uv(e,t,n,r,i,o,s=W(qt.schema)){let a=await iL(e,t),c=new Map(e.map(T=>[T.id,T])),d=[...new Set(a.missingLinkedPaths)].sort((T,F)=>T.localeCompare(F)),l=await FO(t,r),u=oL(l,n,t,r,i,o),_=u.candidateFiles.filter(T=>!a.linkedProjectPaths.has(T)),h=Mv(_,e),f=cv(d,u.candidateFiles),g=new Map(f.map(T=>[T.path,T.classification])),y=f.filter(T=>T.classification==="moved").length,w=a.staleLinkRows.map(T=>({...T,classification:g.get(T.path)??"deleted"})).sort((T,F)=>T.item_id.localeCompare(F.item_id)||T.path.localeCompare(F.path)||T.link_kind.localeCompare(F.link_kind)),v=[];u.strictModeForcesPmInternals&&v.push("validate_files_tracked_all_strict_forces_pm_internals"),_.length>0&&v.push(`validate_files_orphaned_paths:${_.length}`);let k=[...a.remoteLinkedPaths].sort((T,F)=>T.localeCompare(F)),S=cn(k,o),b=cn(d,o),A=cn(_,o),E=cn(h.map(T=>`${T.path}:${T.classification}:owner_candidate=${T.owner_candidate?.id??"unowned"}`),o),C=o?h:cn(Pv(h),!1).values,O=cn(dv(f),o),M=Mw(w,f,T=>c.get(T),s,o?1/0:tl);return M.active_missing_linked_paths_count>0&&v.push(`validate_files_missing_linked_paths:${M.active_missing_linked_paths_count}`),{check:{name:"files",status:v.length===0?"ok":"warn",ok:v.length===0,details:{workspace_root:t,scan_mode_requested:l.requestedMode,scan_mode_applied:l.appliedMode,strict_tracked_all_mode:u.strictTrackedAllMode,strict_mode_forces_pm_internals:u.strictModeForcesPmInternals,strict_mode_forces_pm_internals_notice:u.strictModeForcesPmInternals?"tracked-all-strict force-enables PM internals; pass --include-pm-internals to make inclusion explicit.":null,file_list_detail_mode:o?"full":"summary",file_list_summary_limit:tl,candidate_scan_source:l.source,include_pm_internals:u.includePmInternalsEffective,include_pm_internals_requested:i,pm_internal_candidate_prefixes:u.pmInternalCandidatePrefixes,pm_internal_excluded_count:u.excludedPmInternalPaths.length,excluded_total:u.excludedPmInternalPaths.length,excluded_by_reason:u.excludedByReason,linked_project_paths:a.linkedProjectPaths.size,remote_linked_paths_count:k.length,remote_linked_paths_total:S.total,remote_linked_paths:S.values,remote_linked_paths_truncated:S.truncated,candidate_total_raw:l.candidateTotal,candidate_scanned_raw:l.candidateScanned,candidate_total:u.candidateFiles.length,candidate_scanned:u.candidateFiles.length,scanned_candidate_files:u.candidateFiles.length,missing_linked_paths_count:d.length,missing_linked_paths_total:b.total,missing_linked_paths:b.values,missing_linked_paths_truncated:b.truncated,missing_linked_paths_moved_count:y,missing_linked_paths_deleted_count:f.filter(T=>T.classification==="deleted").length,missing_linked_paths_malformed_count:f.filter(T=>T.classification==="malformed").length,missing_linked_path_classifications:O.values,missing_linked_path_classifications_truncated:O.truncated,...M,orphaned_paths_count:_.length,orphaned_paths_total:A.total,orphaned_paths:A.values,orphaned_paths_truncated:A.truncated,orphaned_path_classifications:E.values,orphaned_path_classifications_truncated:E.truncated,orphaned_path_rows_count:h.length,orphaned_path_rows:C}},warnings:v,staleLinkPruneRows:w}}function sL(e,t){let n=[];return e.forEach(({item:r,linkedTest:i},o)=>{let s=t[o];if(s.trusted)return;let a=Jd(i.command??"");n.push(`${r.id}:${s.source_ref??"unknown"}->${s.current_source_ref??"unknown"}:${a}`)}),n}async function Gv(e,t,n,r){let i=new Set(e.map(b=>b.id.toLowerCase())),o=0,s=0,a=new Set,c=[],d=e.flatMap(b=>(b.tests??[]).map(A=>({item:b,linkedTest:A}))),l=await ri(ii()),u=await Vw(r,d.map(({linkedTest:b})=>b),l),_=sL(d,u);for(let{item:b,linkedTest:A}of d){if(typeof A.command!="string"||A.command.trim().length===0)continue;o+=1;let E=Nd(A.command,t);if(E.length!==0){s+=E.length;for(let C of E)a.add(C),i.has(C.toLowerCase())||c.push(`${b.id}:${C}:${Jd(A.command)}`)}}let h=[...new Set(c)].sort((b,A)=>b.localeCompare(A)),f=[...new Set(h.map(b=>b.split(":")[1]??""))].filter(b=>b.length>0).sort((b,A)=>b.localeCompare(A)),g=[];h.length>0&&g.push(`validate_command_references_stale_pm_ids:${h.length}`),_.length>0&&g.push(`validate_linked_test_trust_unacknowledged:${_.length}`);let y=n?Number.POSITIVE_INFINITY:et,w=ne(h,y),v=ne(f,y),k=ne([...a].sort((b,A)=>b.localeCompare(A)),y),S=ne(_,y);return{check:{name:"command_references",status:g.length===0?"ok":"warn",ok:g.length===0,details:{checked_items:e.length,linked_commands_scanned:o,referenced_pm_ids_count:s,unique_referenced_pm_ids_count:a.size,unique_referenced_pm_ids:k.values,unique_referenced_pm_ids_truncated:k.truncated,linked_test_trust_current_source_ref:l??null,untrusted_linked_tests_count:_.length,untrusted_linked_tests:S.values,untrusted_linked_tests_truncated:S.truncated,stale_pm_id_references_count:h.length,stale_pm_ids_count:f.length,stale_pm_ids:v.values,stale_pm_ids_truncated:v.truncated,stale_pm_id_reference_rows:w.values,stale_pm_id_reference_rows_truncated:w.truncated}},warnings:g}}function aL(e,t){let n=Xi(e.map(c=>({ref:c.id,version:Ji(c)})),yr,Yi),r=[];n.outdated.length>0&&r.push(`validate_format_version_outdated_items:${n.outdated.length}`),n.ahead.length>0&&r.push(`validate_format_version_ahead_items:${n.ahead.length}`);let i=t?Number.POSITIVE_INFINITY:et,o=ne(n.outdated,i),s=ne(n.ahead,i),a=n.ahead.length>0?"error":n.outdated.length>0?"warn":"ok";return{check:{name:"format_version",status:a,ok:a==="ok",details:{checked_items:e.length,current_format_version:yr,outdated_items_count:n.outdated.length,outdated_items:o.values,outdated_items_truncated:o.truncated,ahead_items_count:n.ahead.length,ahead_items:s.values,ahead_items_truncated:s.truncated}},warnings:r}}var rl="pm validate auto-fix";async function qv(e,t,n){switch(e.kind){case"set_closed_at":await Dw(e,t);return;case"set_resolution":case"set_close_reason":case"set_estimate":case"reparent":case"unset_parent":{let r={message:rl};if(e.kind==="set_resolution"?r.resolution=e.value:e.kind==="set_close_reason"?r.closeReason=e.value:e.kind==="set_estimate"?r.estimatedMinutes=e.value:e.kind==="reparent"?r.parent=e.parent_id:r.unset=["parent"],!n.runUpdate)throw new p("Applying validate metadata/lifecycle fixes requires a runUpdate mutation service.",m.USAGE);await n.runUpdate(e.item_id,r,t);return}case"prune_file_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`);case"prune_doc_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`)}}function Qd(e){return e.kind!=="prune_file_link"&&e.kind!=="prune_doc_link"?null:`${e.kind}:${e.item_id}`}async function Kv(e,t,n){let r=[],i=[],o=new Map;for(let s of e.filter(a=>Qd(a)===null))try{await qv(s,t,n),r.push(s)}catch(a){i.push({fix:s,error:a})}for(let s of e.filter(a=>Qd(a)!==null)){let a=Qd(s),c=o.get(a);c?c.push(s):o.set(a,[s])}for(let s of o.values()){let a=s[0];if(!a)continue;let c=s.map(d=>d.path).filter(d=>typeof d=="string"&&d.length>0);try{a.kind==="prune_file_link"?await Dy(a.item_id,{remove:c,message:rl},t):await vy(a.item_id,{remove:c,message:rl},t),r.push(...s)}catch(d){i.push(...s.map(l=>({fix:l,error:d})))}}return t_(i.map(s=>s.error)),{applied:r,failed:i}}var AH={applyValidateFix:qv,applyValidateFixes:Kv,attachValidateFixHints:kv,buildCommandReferencesCheck:Gv,buildDependencyReferencesCheck:Ov,buildCloseReasonBackfillRows:Av,buildFilesCheck:Uv,buildLifecycleCheck:jv,buildLifecycleDependencyGraph:Iv,buildLifecycleParentGraph:Hd,buildEstimateBackfillRows:xv,buildMetadataCounts:Tv,buildMissingFieldOccurrences:Cv,buildOrphanedPathRows:Mv,classifyOrphanedPath:$v,collectDefaultProjectFileCandidates:nl,collectTrackedGitFileCandidates:bv,detectLifecycleDependencyCycles:Dv,detectLifecycleParentCycles:Vd,escapeRegExp:Rv,extractItemIds:Lv,findLifecycleDependencyCycleComponents:Bd,isMetadataFieldMissing:yv,linkedArtifactPathExceedsFilesystemLimits:Fv,listFilesRecursive:ol,resolveDependencyCycleSeverity:hv,resolveParentCycleSeverity:gv,resolveFileScanMode:wv,resolveLifecycleDependencyCycleSamplePath:ms,resolveRequestedChecks:Sv,resolveValidateMetadataProfile:fv,resolveWorkspaceRoot:vv,sharedDirectoryPrefixLength:Nv,summarizeOrphanedPathRows:Pv,summarizeDuplicateIssueCodes:Ev,toMeaningfulString:Ze};function cL(e,t){t>0&&e.push(`merge_receipt_evidence_invalid:${t}`)}async function dL(e,t,n,r){let i=await Fw(e,new Set(t.map(y=>y.id)),n,{schema:r.schema,extensionFieldNames:xt(N())}),o=[];i.unreadable_item_files.length>0&&o.push(`validate_storage_unreadable_items:${i.unreadable_item_files.length}`),i.duplicate_item_ids.length>0&&o.push(`validate_storage_duplicate_item_ids:${i.duplicate_item_ids.length}`),i.history_conflict_marker_streams.length>0&&o.push(`validate_storage_history_conflict_markers:${i.history_conflict_marker_streams.length}`),i.history_unparseable_streams.length>0&&o.push(`validate_storage_unparseable_history:${i.history_unparseable_streams.length}`),i.resurrected_items.length>0&&o.push(`validate_storage_resurrected_items:${i.resurrected_items.length}`),i.unparseable_config_files.length>0&&o.push(`validate_storage_unparseable_config:${i.unparseable_config_files.length}`);let s=o.length,a=await es(e);a.tracked_path_count>0&&o.push(`validate_storage_tracked_runtime_cache_files:${a.tracked_path_count}`);let c=await $n(e,Dn(r));c.status==="drift"&&o.push(`validate_merge_fence_drift:${c.missing_patterns.length+c.stale_patterns.length}`);let d=await Dt(e),l=d===null?null:await Nn(d);l!==null&&l.status!=="ok"&&o.push(`validate_merge_driver_configuration:${l.missing_keys.length+l.drifted_keys.length}`);let u=await Mn(d??e,{includeLossless:!0,pmRoot:e}),_=u.receipts,{pendingDecisions:h,lossless:f}=Pn(_);h.length>0&&o.push(`validate_merge_decisions_unreviewed:${h.length}`),cL(o,u.invalid_evidence_count);let g=s>0?"error":o.length>0?"warn":"ok";return{check:{name:"storage_integrity",status:g,ok:g==="ok",details:{...i,merge_fence:c,merge_driver_configuration:l,pending_merge_decision_count:h.length,pending_merge_decision_items:[...new Set(h.map(y=>y.item_id))].sort((y,w)=>y.localeCompare(w)),lossless_merge_receipt_count:f.length,invalid_merge_receipt_evidence_count:u.invalid_evidence_count,invalid_merge_receipt_evidence_details:u.invalid_evidence,invalid_merge_receipt_evidence_details_truncated:u.invalid_evidence_truncated,lossless_merge_receipt_items:[...new Set(f.map(y=>y.item_id))].sort((y,w)=>y.localeCompare(w)),tracked_runtime_cache:{tracker_relative_root:a.tracker_relative_root,tracked_paths:a.tracked_paths,tracked_path_count:a.tracked_path_count,remediation_command:a.remediation_command}}},warnings:o}}function mt(e,t,n){n&&kv(t.check,t.warnings),e.checks.push(t.check),e.warnings.push(...t.warnings)}async function lL(e){let t={closureTimestampFixes:[],checks:[],warnings:[...e.initialWarnings],closeReasonBackfillRows:[],estimateBackfillRows:[],resolutionBackfillRows:[],terminalParentFixRows:[],staleLinkPruneRows:[]},n=e.options.fixHints===!0,r=e.options.verboseDiagnostics===!0||e.options.allAffectedIds===!0||e.global.json===!0;if(e.requestedChecks.has("completeness")){let i=await hh(e.pmRoot,e.items,r?1/0:et,e.sourceIncomplete);mt(t,i,n)}if(e.requestedChecks.has("metadata")){let i=BO(e.items,e.metadataPolicy,e.statusRegistry,r,[e.settings.id_prefix]);t.closeReasonBackfillRows=i.closeReasonBackfillRows,t.estimateBackfillRows=i.estimateBackfillRows;let o=await Lw(e.pmRoot,e.items,e.statusRegistry,e.options.autoFix===!0||n,r?1/0:et);t.closureTimestampFixes=o.fixes,Object.assign(i.check.details,o.details),i.warnings.push(...o.warnings),i.check.ok=i.warnings.length===0,i.check.status=i.check.ok?"ok":"warn",mt(t,i,n)}if(e.requestedChecks.has("resolution")){let i=HO(e.items,e.statusRegistry,r);t.resolutionBackfillRows=i.resolutionBackfillRows,mt(t,i,n)}if(e.requestedChecks.has("lifecycle")){let i=jv(e.items,!!e.options.checkStaleBlockers,e.dependencyCycleSeverity,e.parentCycleSeverity,e.statusRegistry,e.lifecyclePatternPolicy,r,e.settings.id_prefix);t.terminalParentFixRows=i.terminalParentFixRows,mt(t,i,n),mt(t,Ov(e.items,r,e.statusRegistry),n)}if(e.requestedChecks.has("files")){let i=await Uv(e.items,e.workspaceRoot,e.pmRoot,e.fileScanMode,!!e.options.includePmInternals,!!e.options.verboseFileLists,e.statusRegistry);t.staleLinkPruneRows=i.staleLinkPruneRows,mt(t,i,n)}return e.requestedChecks.has("command_references")&&mt(t,await Gv(e.items,e.settings.id_prefix,r,e.pmRoot),n),e.requestedChecks.has("history_drift")&&mt(t,await us(e.pmRoot,e.items,r),n),e.requestedChecks.has("format_version")&&mt(t,aL(e.items,r),n),e.requestedChecks.has("storage_integrity")&&mt(t,await dL(e.pmRoot,e.items,P(e.settings,N()).type_to_folder,e.settings),n),t}function uL(e,t,n){let r=[];return e.autoFix===!0&&(r.push(...t.closureTimestampFixes),r.push(...Qw(t.closeReasonBackfillRows)),r.push(...Xw(t.resolutionBackfillRows)),r.push(...Zw(t.estimateBackfillRows,n.validation.estimate_defaults_by_type)),r.push(...ev(t.terminalParentFixRows))),e.pruneMissing===!0&&r.push(...tv(t.staleLinkPruneRows)),r}async function mL(e,t,n,r,i,o){if(e.autoFix!==!0&&e.pruneMissing!==!0)return;let s=uL(e,t,n),{applicable:a,gated:c}=rv(s,r),d=e.dryRun===!0,l=[],u=[];if(!d){let _=await Kv(a,i,o);l.push(..._.applied.map(oi)),u.push(..._.failed.map(({fix:h,error:f})=>({...oi(h),error:f instanceof Error?f.message:String(f)})))}return{mode:d?"dry_run":"apply",auto_fix:e.autoFix===!0,prune_missing:e.pruneMissing===!0,granted_fix_scopes:[...r].sort((_,h)=>_.localeCompare(h)),planned_count:s.length,applied_count:l.length,gated_count:c.length,failed_count:u.length,planned_fixes:s.map(oi),applied_fixes:l,gated_fixes:c.map(_=>({...oi(_),gate_hint:`Withheld: re-run with --fix-scope ${_.gate} to apply.`})),failed_fixes:u}}async function Wv(e,t,n={}){Ym(e.counts===!0,e.full===!0,"--counts");let r=e.autoFix===!0||e.pruneMissing===!0;if(e.dryRun===!0&&!r)throw new p("--dry-run requires --auto-fix or --prune-missing (there is nothing to preview otherwise).",m.USAGE);if(e.fixScope!==void 0&&e.fixScope.length>0&&e.autoFix!==!0)throw new p("--fix-scope requires --auto-fix.",m.USAGE);let i=nv(e.fixScope),o=R(process.cwd(),t.path);await j(o);let s=await x(o),a=W(s.schema),c=P(s,N()),d=Sv(e),l=[],u=await ls({includeBody:["history_drift","metadata","completeness"].some(O=>d.has(O)),pmRoot:o,settings:s,typeToFolder:c.type_to_folder,warnings:l}),_=l.length>0;if(d.has("history_drift")){let O=await Yr(o);O.actionable_unknown_event_count>0&&l.push(`validate_history_unknown_author_events:${O.actionable_unknown_event_count}`)}let h=typeof e.metadataProfile=="string"?"option":"settings",f=fv(typeof e.metadataProfile=="string"?e.metadataProfile:s.validation.metadata_profile),g=$O(f,h,s.validation.metadata_required_fields),y=LO(s),w=hv(e.dependencyCycleSeverity),v=gv(e.parentCycleSeverity),k=wv(e.scanMode),S=vv(o),b=await lL({requestedChecks:d,options:e,global:t,pmRoot:o,workspaceRoot:S,settings:s,items:u,statusRegistry:a,metadataPolicy:g,lifecyclePatternPolicy:y,dependencyCycleSeverity:w,parentCycleSeverity:v,fileScanMode:k,initialWarnings:[...new Set(l)],sourceIncomplete:_}),A=r?await mL(e,b,s,i,t,n):void 0,E=[...new Set(b.warnings)].sort((O,M)=>O.localeCompare(M)),C={ok:!b.checks.some(O=>O.status==="error"),has_warnings:E.length>0,checks:b.checks,warnings:E,...A!==void 0?{fixes:A}:{},generated_at:I(),projection:{mode:"full",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:["diagnostic_rows"]}};return e.counts!==!0?C:{...OO(C),projection:{mode:"counts",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:[]}}}import{execFile as pL}from"node:child_process";import{promisify as _L}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d50f9868-5c11-51dc-967e-61ce41225ef1")}catch{}})();var fL=_L(pL),hL=16,gL=3e4;function yL(e,t,n){if(!(e.keys[t].value_type==="number"?typeof n.value=="number"&&Number.isFinite(n.value):Array.isArray(n.value)&&n.value.every(r=>typeof r=="string")))throw new TypeError(`assurance provider ${e.id} key ${t} returned the wrong value type`);if(!Number.isInteger(n.population_size)||n.population_size<0||!Number.isFinite(n.cost)||n.cost<0)throw new TypeError(`assurance provider ${e.id} returned an invalid population or cost`);return n}function wL(e,t){let n=e.keys[t.key];if(!n)throw new TypeError(`assurance provider ${e.id} does not declare key ${t.key}`);let r=t.parameters??{},i=n.parameters??{};for(let o of Object.entries(i).filter(([,s])=>s.required===!0).map(([s])=>s))if(!Object.hasOwn(r,o))throw new TypeError(`assurance provider ${e.id} key ${t.key} requires parameter ${o}`);for(let[o,s]of Object.entries(r)){let a=i[o];if(!a)throw new TypeError(`assurance provider ${e.id} key ${t.key} does not declare parameter ${o}`);if(s===null||typeof s!==a.type)throw new TypeError(`assurance provider ${e.id} parameter ${o} must be ${a.type}`)}return{...r}}async function vL(e,t,n,r){let i=wL(e,t),o=Promise.resolve().then(()=>e.resolve({provider:e.id,key:t.key,parameters:i,trigger:r,pm_root:n,...up(n)}));o.catch(()=>{});let s;try{let a=await Promise.race([o,new Promise((c,d)=>{s=setTimeout(()=>d(new TypeError(`assurance provider ${e.id} timed out`)),e.timeout_ms??gL),s.unref?.()})]);return yL(e,t.key,a)}finally{clearTimeout(s)}}function Bv(e,t,n,r){let i=e;for(let o of t.split(".")){if(typeof i!="object"||i===null||Array.isArray(i))throw new ut(`assurance field ${t} is not present`,{source_kind:n,field:t,...r?{check:r}:{}});i=i[o]}if(typeof i=="number"&&Number.isFinite(i)||Array.isArray(i)&&i.every(o=>typeof o=="string"))return i;throw new ut(`assurance field ${t} must resolve to a finite number or string array`,{source_kind:n,field:t,...r?{check:r}:{}})}function zv(e,t,n,r){let i=e.checks.find(o=>o.name===t);if(!i)throw new ut(`assurance check ${t} is not present`,{source_kind:r,field:n,check:t});return{value:n==="status"||n==="ok"?i.ok?0:1:Bv(i.details,n,r,t),population_size:1,cost:e.checks.length}}async function bL(e,t){if(t?.trim())return t.trim();try{let{stdout:n}=await fL("git",["rev-parse","HEAD^{commit}"],{cwd:e,encoding:"utf8",timeout:5e3,windowsHide:!0});return n.trim()}catch{return"working-copy"}}async function kL(e,t){let n=new Array(t.length),r=0,i=Array.from({length:Math.min(hL,t.length)},async()=>{for(;r<t.length;){let o=r;r+=1;let s=t[o],a=await Jt(Bt(e,s.id),s.id);n[o]=a.map(c=>({op:c.op,author:c.author,agent_harness:c.agent_harness,agent_model:c.agent_model}))}});return await Promise.all(i),n.flat()}async function ai(e,t={}){let n=await x(e),r=P(n),i=W(n.schema),o=(t.strict_read===!0?(await uh(void 0,{status:"all",full:!0,includeBody:!0,noTruncate:!0,strictRead:!0},{path:e})).items:await gt(e,n.item_format,r.type_to_folder,void 0,n.schema)).map(_=>({..._,id:_.id,status:_.status,type:_.type})),s={path:e},a=N(),c=Object.fromEntries((a?.assurance_providers??[]).map(_=>[_.definition.id,{cost_class:_.runtime_definition.cost_class,network:_.runtime_definition.network}])),d=new Map,l,u;return{tree_id:t.resolve_tree===!1?t.tree_id??"working-copy":await bL(e,t.tree_id),items:o,history:t.include_history===!1?[]:await kL(e,o),terminal_statuses:[...i.terminal_statuses],provider_capabilities:{...c,...t.provider_capabilities},external:async _=>{if(_.kind==="graph"){let g=Z({operation:_.operation,parameters:_.parameters??{}}),y=d.get(g);y===void 0&&(y=kh(_.operation,void 0,void 0,{..._.parameters,full:!0},s),d.set(g,y));let w=await y;return{value:Bv(w,_.field,_.kind),population_size:o.length,cost:o.length}}if(_.kind==="validate"){l??=Wv({counts:!0},s);let g=await l;return zv(g,_.check,_.field,_.kind)}if(_.kind==="health"){u??=Rw(s,{checkOnly:!0,full:!0});let g=await u;return zv(g,_.check,_.field,_.kind)}let h=t.providers?.[_.provider];if(h)return h(_);let f=yp(a,_.provider);if(!f)throw new TypeError(`assurance provider ${_.provider} is not registered`);return vL(f.runtime_definition,_,e,t.trigger??"sdk")}}}import{createHash as SL}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c72d246d-a7ff-5c9d-8c36-4ebd45b8a69f")}catch{}})();function Hv(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new TypeError("recurrence coverage request must be an object");let t=e;if(Object.hasOwn(t,"change"))throw new TypeError("recurrence coverage request does not accept change");if(t.uncoveredOnly!==void 0&&typeof t.uncoveredOnly!="boolean")throw new TypeError("recurrence coverage request.uncoveredOnly must be a boolean");let{policy:n,cursor:r,limit:i}=vo({...t,change:{}});return{policy:n,...r===void 0?{}:{cursor:r},...i===void 0?{}:{limit:i},...t.uncoveredOnly===void 0?{}:{uncoveredOnly:t.uncoveredOnly}}}function EL(e,t){if(e===void 0)return 0;let n;try{n=JSON.parse(Buffer.from(e,"base64url").toString("utf8"))}catch{throw new TypeError("recurrence coverage cursor is invalid")}if(typeof n!="object"||n===null||Array.isArray(n))throw new TypeError("recurrence coverage cursor is invalid");let r=n;if(r.fingerprint!==t||typeof r.offset!="number"||!Number.isSafeInteger(r.offset)||r.offset<0)throw new TypeError("recurrence coverage cursor does not match this evidence and filter");return r.offset}function TL(e,t,n,r,i,o){let s=Object.fromEntries(_c.map(h=>[h,0])),a=0,c=0,d=0,l=0,u=[],_=SL("sha256").update(i);for(let h of r){let f=e.membership.get(h),g=n.has(h),y=f.family_ids.length>0;y&&g&&(a+=1),y||(c+=1),g||(d+=1);let w=t.get(h)?.escape_class;w!==void 0&&_c.includes(w)&&(s[w]+=1,l+=1),_.update(Z([h,g,t.get(h)??null,f.id,f.family_ids])),(!o||!y||!g)&&u.push(h)}return{classCounts:s,coveredCount:a,uncoveredCount:c,missingCount:d,classifiedCount:l,selected:u,fingerprint:_.digest("hex")}}function Vv(e,t,n={}){Jf(e);let r=n.limit??25;if(!Number.isSafeInteger(r)||r<1||r>100)throw new TypeError("recurrence coverage limit must be an integer from 1 through 100");let i=new Set,o=new Map;for(let S of t){if(i.has(S.id))throw new TypeError(`Duplicate recurrence item ${S.id}`);i.add(S.id);let b=wo(S);b!==void 0&&o.set(S.id,b)}let s=Bf(e.families,o),a=[...s.membership.keys()].sort(),c=Z({policy:e,uncoveredOnly:n.uncoveredOnly===!0}),{classCounts:d,coveredCount:l,uncoveredCount:u,missingCount:_,classifiedCount:h,selected:f,fingerprint:g}=TL(s,o,i,a,c,n.uncoveredOnly===!0),y=EL(n.cursor,g);if(y>f.length)throw new TypeError("recurrence coverage cursor offset exceeds the selected population");let w=f.slice(y,y+r).map(S=>{let b=s.membership.get(S),A=i.has(S);return{item_id:S,lineage_id:b.id,lineage_item_count:b.item_ids.length,family_ids:b.family_ids,present:A,...A?b.family_ids.length===0?{finding:"unregistered_recurrence_item"}:{}:{finding:"missing_recurrence_item"}}}),v=y+w.length,k=a.length===0?null:d.production_defect/a.length;return{ok:u===0&&_===0,fingerprint:g,items:w,total:f.length,has_more:v<f.length,...v<f.length?{next_cursor:Buffer.from(JSON.stringify({fingerprint:g,offset:v})).toString("base64url")}:{},population:{scope:"all_recorded_recurrence_items",item_count:a.length,lineage_count:s.lineages.length,edge_count:s.edge_count,covered_item_count:l,uncovered_item_count:u,missing_item_count:_,classified_item_count:h,unclassified_item_count:a.length-h,class_counts:d,escape_rate:h===a.length?k:null,escape_rate_lower_bound:k},budget_scope:"registered_families_only",cost:{items_scanned:t.length,edges_scanned:s.edge_count,row_limit:r},row_contract:{row_keys:["items"],jq_selector:".items[]"}}}import{createHash as CL}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c8cf307d-334c-5b70-93c7-991ff702e4ca")}catch{}})();var sl,Yv=["list","show","put","remove","run","verdicts","presets","apply","derive","promote","risk","lineages"],al=["measurement","assertion","gate"];function AL(e){if(Yv.includes(e))return e;throw Bi({command_path:"assurance",token:e,allowed:Yv,display_name:"assurance action"})}function Qn(e,t,n){throw new p(t,m.USAGE,{code:"missing_required_argument",required:`Provide the missing assurance operand: ${e}.`,examples:[n],recovery:{missing:[e]}})}function xL(e){if(!e)return Qn("kind",`Assurance declaration kind is required. Expected: ${al.join(", ")}`,"pm assurance list measurement");if(al.includes(e))return e;throw new p(`Assurance declaration kind is required. Expected: ${al.join(", ")}`,m.USAGE)}function Jv(e){if(!e)return Qn("preset",`Assurance preset is required. Expected: ${Qr.join(", ")}`,"pm assurance apply software-delivery --owner <pm-item-id>");if(Qr.includes(e))return e;throw new p(`Assurance preset is required. Expected: ${Qr.join(", ")}`,m.USAGE)}function cl(e){return e.owner?.trim()?e.owner.trim():Qn("owner","assurance preset and derivation actions require --owner <pm-item-id>","pm assurance apply software-delivery --owner <pm-item-id>")}function RL(e,t){let n=t;if(typeof t=="string")if(!t.trim())n=void 0;else try{n=JSON.parse(t)}catch(r){throw new p("assurance definition must be valid JSON",m.USAGE,{reason:r instanceof Error?r.message:"invalid_json"})}if(typeof n!="object"||n===null||Array.isArray(n))throw new p("assurance put requires a JSON object definition",m.USAGE);return n}async function IL(e){let[t,n,r]=await Promise.all([Wr(e,"measurement"),Wr(e,"assertion"),Wr(e,"gate")]);return{version:1,measurements:t.items,assertions:n.items,gates:r.items}}function Xv(e,t){return t===!0?{id:e.id}:e}async function OL(e,t){let n=t.authorization_decision;if(!n)return[];let r=await ai(e,{include_history:!1,resolve_tree:!1}),i=r.items.find(s=>s.id===n),o=new Set(r.terminal_statuses);if(!i||i.type.toLowerCase()!=="decision"||!o.has(i.status))throw new p(`Assurance authorization ${n} must name a terminal Decision item`,m.USAGE);return[i.id]}async function LL(e,t){let n=yc(e.limit,"assurance verdict limit");if(n!==void 0&&(n<1||n>qn))throw new p(`assurance verdict limit must be an integer from 1 through ${qn}`,m.USAGE);let r=await Fg(t,{gate_id:e.id??e.gate,limit:n});return{items:r,count:r.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function Qv(e,t,n){try{return await Fc(()=>Ng(e,t,n))}catch(r){if(!(r instanceof p)||r.context.reason!=="assurance_evaluation_refused")throw r;let i=["--pm-path",e,"assurance","list",t,"--output-budget","2000","--json"],o=L(i);throw Object.assign(r.context,{changed:!1,value:n,required:`Choose a configured ${t} declaration ID using the bounded discovery command.`,why:`The requested ${t} declaration does not exist. The registry and history were not changed.`,examples:[o],recovery:{next_best_command:o,suggested_retry:o,suggested_retry_args:i}}),r}}async function DL(e,t,n){if(e==="presets"){if(t.preset??t.id)return Jo(Jv(t.preset??t.id),cl(t));let i=Qr.map(o=>{let s=Jo(o,"pm-owner");return{id:o,title:s.title,description:s.description}});return{items:i,count:i.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}if(e==="apply")return Gn(()=>Py(n,Jv(t.preset??t.id),cl(t),{author:t.author,message:t.message}));if(e==="derive"){let i=await Fy(await ai(n,{resolve_tree:!1,trigger:"derive"}),cl(t)),o=t.apply?await Gn(()=>jy(n,i,{author:t.author,message:t.message??"Accept observation-derived assurance proposals"})):void 0;return{items:i,count:i.length,...o?{applied:o}:{}}}if(!t.id)return Qn("assertion-id","assurance promote requires an assertion id","pm assurance promote <assertion-id> --enforcement warn");if(t.enforcement!=="warn"&&t.enforcement!=="block")throw new p("assurance promote requires --enforcement warn|block",m.USAGE);let r=await Qv(n,"assertion",t.id);return Gn(()=>Uy(n,r,t.enforcement,{author:t.author,message:t.message}))}async function $L(e,t,n){if(!e.id)return Qn("gate-id","assurance run requires a gate id","pm assurance run <gate-id> --trigger ci --dry-run");let r=e.id;if(!e.trigger)throw new p("assurance run requires a trigger",m.USAGE);if(!yt.includes(e.trigger))throw new p(`Unknown assurance trigger ${e.trigger}. Expected: ${yt.join(", ")}`,m.USAGE);let i=e.trigger,[o,s]=await Promise.all([IL(t),ai(t,{...n.workspace,tree_id:e.tree,trigger:i})]),a=await Fc(()=>Dg(r,o,s,{trigger:i,dry_run:e.dry_run===!0}));return a.dry_run||await Pg(t,a,{author:e.author,message:e.message}),a}function Zv(e){throw e instanceof p?e:new p(e instanceof Error?e.message:"assurance risk request is invalid",m.USAGE)}function NL(e){if(e.limit!==void 0)throw new p(`assurance ${e.action} does not accept --limit; set limit inside the definition`,m.USAGE);let t=e.definition;if(typeof t=="string")try{t=JSON.parse(t)}catch(n){throw new p(`assurance ${e.action} definition must be valid JSON`,m.USAGE,{reason:n instanceof Error?n.message:"invalid_json"})}try{return e.action==="lineages"?Hv(t):vo(t)}catch(n){if(e.action==="risk"&&n instanceof Yf)throw new p(n.message,m.USAGE,{required:"Supply definition.policy with the project's declared recurrence policy and definition.change with the proposed change; no policy is inferred.",recovery:{suggested_retry:`pm assurance ${e.action} --help`,suggested_retry_args:["assurance",e.action,"--help"]}});return Zv(n)}}function ML(e,t){let n=new Set;for(let[r,i]of t)e.item_fingerprints.get(r)!==i&&n.add(r);for(let r of e.item_fingerprints.keys())t.has(r)||n.add(r);return n}function PL(e,t,n){let r=Z(t.policy),i=sl?.pm_root===e?sl:void 0,o=new Map(n.map(d=>[d.id,CL("sha256").update(Z([zf(d),wo(d)])).digest("hex")])),s=i?.policy_serialized===r?i:void 0,a=s?ML(s,o):new Set,c=Hf(t.policy,s?n.filter(d=>a.has(d.id)):n,s?{previous_index:s.index,changed_item_ids:[...a]}:{});return sl={pm_root:e,policy_serialized:r,item_fingerprints:o,index:c},c}async function FL(e,t){let n=NL(e),r=await ai(t,{strict_read:!0,include_history:!1,resolve_tree:!1});try{return"change"in n?Vf(PL(t,n,r.items),n.change,{cursor:n.cursor,limit:n.limit}):Vv(n.policy,r.items,n)}catch(i){return Zv(i)}}async function jL(e,t={},n={}){let r=AL(e.action),i=R(process.cwd(),t.path);if(r==="presets"||r==="apply"||r==="derive"||r==="promote")return DL(r,e,i);if(r==="verdicts")return LL(e,i);if(r==="run")return $L(e,i,n);if(["risk","lineages"].includes(r))return FL(e,i);let o=xL(e.kind);if(r==="list")return Wr(i,o);if(!e.id)return Qn("id",`assurance ${r} requires an id`,`pm assurance ${r} ${o} <id>`);let s=e.id;if(r==="show")return Qv(i,o,s);if(r==="remove"){let l=await Gn(()=>Mg(i,o,s,{author:e.author,message:e.message}));return Xv(l,e.idOnly)}let a=RL(o,e.definition);if(a.id!==s)throw new p(`Assurance definition id ${a.id} does not match requested id ${s}`,m.USAGE);let c={author:e.author,message:e.message,...o==="assertion"?{authorized_decision_ids:await OL(i,a)}:{}},d=await Gn(()=>Fo(i,o,a,c));return Xv(d,e.idOnly)}function lV(e,t,n){let r={...e,...t};return jL({action:te(r,"subcommand")??te(r,"assuranceAction")??te(r,"operation")??"",kind:te(r,"kind"),id:te(r,"id"),definition:r.definition,trigger:te(r,"trigger"),tree:te(r,"treeId")??te(r,"tree"),gate:te(r,"gate"),limit:yc(r.limit,"assurance verdict limit"),dry_run:r.dryRun===!0||r.dry_run===!0,fullChangedFields:r.fullChangedFields===!0,idOnly:r.idOnly===!0,author:te(r,"author"),message:te(r,"message"),preset:te(r,"preset"),owner:te(r,"owner"),apply:r.apply===!0,enforcement:te(r,"enforcement")},n)}import dl from"node:fs/promises";import eb from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ff5e2370-3b70-5f71-9492-72906f642c85")}catch{}})();var UL=1440*60*1e3,GL=new Set(["committed","compensated"]);function qL(e){let t;try{t=JSON.parse(e)}catch{return{status:null,updatedAt:null}}if(typeof t!="object"||t===null||Array.isArray(t))return{status:null,updatedAt:null};let n=t;return{status:n.abandonment!==void 0?"abandoned":typeof n.status=="string"?n.status:null,updatedAt:typeof n.updatedAt=="string"?n.updatedAt:null}}function KL(e,t,n,r,i){let o=n===null?Number.NaN:Date.parse(n);if(t===null||!Number.isFinite(o))return{entry:{file:e,status:t,age_seconds:null,stale:!1,reason:"unparseable"},remove:!1};let s=r-o;return GL.has(t)?s>i?{entry:{file:e,status:t,age_seconds:Math.floor(s/1e3),stale:!0},remove:!0}:{entry:{file:e,status:t,age_seconds:Math.floor(s/1e3),stale:!1,reason:"fresh"},remove:!1}:{entry:{file:e,status:t,age_seconds:Math.floor(s/1e3),stale:!1,reason:"active"},remove:!1}}async function WL(e,t,n,r){let i=r.hooks?.onRead?await r.hooks.onRead(e):[],o=qL(await dl.readFile(e,"utf8")),s=KL(t,o.status,o.updatedAt,r.nowMs,r.retentionMs);return s.entry.reason==="unparseable"&&i.push(`transaction_journal_unparseable:${n}`),s.remove&&!r.dryRun&&(await dl.rm(e,{force:!0}),r.hooks?.onWrite&&i.push(...await r.hooks.onWrite(e))),{decision:s,warnings:i}}async function tb(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),o=Math.max(0,t.retentionDays)*UL,s=eb.join(e,"transactions","sdk"),a={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c;try{c=(await dl.readdir(s)).filter(d=>d.endsWith(".json")).sort((d,l)=>d.localeCompare(l))}catch(d){if(G(d))return a;throw d}for(let d of c){let l=eb.join(s,d),u=`transactions/sdk/${d}`,_=await WL(l,u,d,{dryRun:n,hooks:r,nowMs:i,retentionMs:o});a.warnings.push(..._.warnings),a.scanned+=1;let{decision:h}=_;if(!h.remove){a.retained.push(u),a.entries.push(h.entry);continue}a.removed.push(u),a.entries.push(h.entry)}return a}import Zn from"node:fs/promises";import ws from"node:path";import ys from"node:fs/promises";import ll from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4fe37a62-2d0f-55f6-bb98-7162e7e8b8fe")}catch{}})();var zL=864e5;function BL(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t.created_at;return typeof n=="string"?n:null}async function HL(e,t){let n;try{n=await ys.readdir(e,{withFileTypes:!0})}catch(i){if(G(i))return[];throw i}let r=[];for(let i of n)if(i.isDirectory()){let o=ll.join(e,i.name),s;try{s=await ys.readdir(o)}catch(a){G(a)||t.push(`checkpoint_subdir_unreadable:${i.name}`);continue}for(let a of s)a.endsWith(".json")&&r.push(`${i.name}/${a}`)}else i.name.endsWith(".json")&&r.push(i.name);return r.sort()}async function nb(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),o=Math.max(0,t.retentionDays)*zL,s=ll.join(e,"checkpoints"),a={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c=await HL(s,a.warnings);for(let d of c){let l=ll.join(s,d),u=`checkpoints/${d}`;a.scanned+=1,r?.onRead&&a.warnings.push(...await r.onRead(l));let _;try{_=await ys.readFile(l,"utf8")}catch(w){if(G(w)){a.scanned-=1;continue}a.warnings.push(`checkpoint_unreadable:${d}`),a.retained.push(u),a.entries.push({file:u,created_at:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let h=BL(_),f=h===null?Number.NaN:Date.parse(h);if(!Number.isFinite(f)){a.warnings.push(`checkpoint_unparseable:${d}`),a.retained.push(u),a.entries.push({file:u,created_at:h,age_seconds:null,stale:!1,reason:"unparseable"});continue}let g=i-f,y={file:u,created_at:h,age_seconds:Math.floor(g/1e3),stale:g>o,reason:g>o?"expired":"active"};if(!y.stale){a.retained.push(u),a.entries.push(y);continue}if(!n){try{await ys.unlink(l)}catch(w){if(!G(w)){a.warnings.push(`checkpoint_remove_failed:${d}`),a.retained.push(u),a.entries.push(y);continue}}r?.onWrite&&a.warnings.push(...await r.onWrite(l))}a.removed.push(u),a.entries.push(y)}return a}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="38736716-2644-5166-bfec-4ed4bca951b9")}catch{}})();var ci=["index","embeddings","runtime","locks","checkpoints","transactions"],VL=1440*60*1e3,YL=[{scope:"index",relativePath:"index/manifest.json",kind:"file"},{scope:"embeddings",relativePath:"search/embeddings.jsonl",kind:"file"},{scope:"embeddings",relativePath:"search/vectorization-status.json",kind:"file"},{scope:"embeddings",relativePath:"search/lancedb",kind:"directory"},{scope:"embeddings",relativePath:"search/pending-refresh.json",kind:"file"},{scope:"embeddings",relativePath:"search/pending-refresh.gate.lock",kind:"directory"},{scope:"runtime",relativePath:"runtime/test-runs",kind:"directory"},{scope:"runtime",relativePath:"runtime/history-drift-cache.json",kind:"file"}];async function JL(e,t,n){let r=t.relativePath,i=ws.join(e,r),o=await We({path:i,scope:"project"});try{let s=await Zn.stat(i);if(t.kind==="file"&&!s.isFile())return{removed:!1,warnings:[...o,`not_a_file:${r}`]};if(t.kind==="directory"&&!s.isDirectory())return{removed:!1,warnings:[...o,`not_a_directory:${r}`]};if(n)return{removed:!0,warnings:o};t.kind==="file"?await Zn.unlink(i):await Zn.rm(i,{recursive:!0,force:!0});let a=await ht({path:i,scope:"project",op:"gc:remove"});return{removed:!0,warnings:[...o,...a]}}catch(s){if(G(s))return{removed:!1,warnings:o};throw s}}async function XL(e,t){let n=[{relativePath:"runtime/workspace-snapshots/objects",prefix:".create-"},{relativePath:"runtime/workspace-snapshots/refs",prefix:".ref-"}],r=[],i=[],o=[],s=Date.now()-VL;for(let a of n){let c=ws.join(e,a.relativePath);if(!await ie(c))continue;let d=(await Zn.readdir(c)).filter(l=>l.startsWith(a.prefix)).sort();for(let l of d){let u=ws.posix.join(a.relativePath,l),_=ws.join(c,l);o.push(...await We({path:_,scope:"project"}));let h=await Zn.stat(_).catch(f=>{if(!G(f))throw f});if(h){if(h.mtimeMs>s){i.push(u);continue}r.push(u),!t&&(await Zn.rm(_,{recursive:!0,force:!0}),o.push(...await ht({path:_,scope:"project",op:"gc:workspace_snapshot_temp_remove"})))}}}return{removed:r,retained:i,warnings:o}}function QL(e){if(!e||e.length===0)return[...ci];let t=e.flatMap(r=>r.split(",")).map(r=>r.trim().toLowerCase()).filter(r=>r.length>0);if(t.length===0)throw new p(`--scope requires at least one value (${ci.join(",")})`,m.USAGE);let n=new Set;for(let r of t){if(!ci.includes(r))throw new p(`Invalid --scope value "${r}". Expected one or more of: ${ci.join(", ")}`,m.USAGE);n.add(r)}return ci.filter(r=>n.has(r))}function ZL(e){let t=[];e.dryRun&&t.push("Dry-run preview only: no cache artifacts were deleted.");let n=e.scopes.includes("index")||e.scopes.includes("embeddings"),r=e.removed.some(i=>i==="index/manifest.json"||i==="search/embeddings.jsonl"||i==="search/vectorization-status.json"||i==="search/lancedb"||i==="search/pending-refresh.json"||i==="search/pending-refresh.gate.lock");return n&&r&&t.push('Search artifacts were removed; the semantic index (including any queued background refresh) is invalidated. Run "pm install search-advanced --project" if reindex is unavailable, then "pm reindex --mode keyword" (and "--mode semantic" when semantic search is enabled) before search-heavy workflows.'),e.removed.includes("runtime/history-drift-cache.json")&&t.push('History drift cache was removed; the next "pm health" run performs a full history-drift re-scan.'),!e.dryRun&&e.removed.some(i=>i.startsWith("checkpoints/"))&&t.push('Aged rollback checkpoints were removed; their "pm update-many"/"pm close-many --rollback" windows are no longer recoverable.'),!e.dryRun&&e.removed.some(i=>i.startsWith("transactions/"))&&t.push("Aged terminal workspace-transaction journals were removed; replaying those transactionIds re-executes their idempotent steps instead of short-circuiting."),t}async function DV(e,t={}){let n=R(process.cwd(),e.path);await j(n);let r=await x(n),i=t.dryRun===!0,o=QL(t.scope),s=YL.filter(f=>o.includes(f.scope)),a=[],c=[],d=[];for(let f of s){let g=await JL(n,f,i);g.removed?a.push(f.relativePath):c.push(f.relativePath),d.push(...g.warnings)}if(o.includes("runtime")){let f=await XL(n,i);a.push(...f.removed),c.push(...f.retained),d.push(...f.warnings)}let l;if(o.includes("locks")){let f=await cw(n,{dryRun:i,hooks:{onRead:g=>We({path:g,scope:"project"}),onWrite:g=>ht({path:g,scope:"project",op:"gc:lock_remove"})}});a.push(...f.removed),c.push(...f.retained),d.push(...f.warnings),l={scanned:f.scanned,removed:f.removed.length,retained:f.retained.length}}let u;if(o.includes("transactions")){let f=r.checkpoints.retention_days,g=await tb(n,{dryRun:i,retentionDays:f,hooks:{onRead:y=>We({path:y,scope:"project"}),onWrite:y=>ht({path:y,scope:"project",op:"gc:transaction_journal_remove"})}});a.push(...g.removed),c.push(...g.retained),d.push(...g.warnings),u={scanned:g.scanned,removed:g.removed.length,retained:g.retained.length,retention_days:f}}let _;if(o.includes("checkpoints")){let f=r.checkpoints.retention_days,g=await nb(n,{dryRun:i,retentionDays:f,hooks:{onRead:y=>We({path:y,scope:"project"}),onWrite:y=>ht({path:y,scope:"project",op:"gc:checkpoint_remove"})}});a.push(...g.removed),c.push(...g.retained),d.push(...g.warnings),_={scanned:g.scanned,removed:g.removed.length,retained:g.retained.length,retention_days:f}}d.push(...await hp({mode:i?"gc:dry-run":"gc",total_items:s.length}));let h=ZL({dryRun:i,scopes:o,removed:a});return{ok:d.length===0,dry_run:i,scope:o,removed:a,retained:c,warnings:d,...l?{locks:l}:{},..._?{checkpoints:_}:{},...u?{transactions:u}:{},guidance:h,generated_at:I()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1430dcf8-9363-556d-aa33-184cea5421f9")}catch{}})();var PV=Object.freeze({requireCloseReason:!0,orderingEdges:"preserve"});function eD(e){let t=[{source:"explicit",value:e.explicit},{source:"duplicate",value:e.duplicateOf===void 0?void 0:`Duplicate of ${e.duplicateOf}`},{source:"resolution",value:e.resolution},{source:"message",value:e.message}];for(let n of t){let r=n.value?.trim();if(r)return{closeReason:r,source:n.source}}return{source:"none"}}function vs(e,t){return ul(e,t,{operation:"close"})}function ul(e,t,n){let r=eD(e);if(!t||r.closeReason!==void 0)return r;let i=n.operation==="create"?[`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --close-reason "<closing summary>"`,`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --resolution "<resolution summary>"`,"pm create --stdin-json < item.json"]:['pm close <id> "Done: <what changed and why>"','pm close <id> --reason "<closing summary>"','pm close <id> -m "<closing summary>"',"pm close <id> --duplicate-of <canonical-id>"];throw new p("Close reason text is required because governance.require_close_reason is enabled",m.USAGE,{code:"close_reason_required",required:"Provide an author-controlled closing summary as the reason, message, resolution, or duplicate target.",why:"governance.require_close_reason is enabled, so tools must not invent immutable closure evidence.",examples:i,nextSteps:[`Re-run the ${n.operation} operation with a closing summary.`,"To stop requiring reasons, run: pm config set governance-require-close-reason --policy disabled"]})}function rb(e,t){let n=typeof e.blocked_by=="string"?e.blocked_by.trim():"",r=e.blocked_by!==void 0,i=e.dependencies??[],o=i.filter(d=>d.kind==="blocked_by"),s=e.blocked_reason!==void 0,a=[];if(r&&(delete e.blocked_by,a.push("blocked_by")),s&&(delete e.blocked_reason,a.push("blocked_reason")),t.orderingEdges==="remove"&&o.length>0){let d=new Set(o),l=i.filter(u=>!d.has(u));l.length>0?e.dependencies=l:delete e.dependencies,a.push("dependencies")}if(t.orderingEdges==="remove")return{changedFields:a,warnings:[...n?[`closed_cleared_blocked_by:${e.id}:${n}`]:[],...o.length>0?[`closed_removed_predecessors:${e.id}:${o.map(d=>d.id).join(",")}`,`closed_removed_predecessors_count:${e.id}:${o.length}`]:[]]};let c=[...new Set([...n?[n]:[],...o.map(d=>d.id)])];return c.length===0?{changedFields:a,warnings:[]}:{changedFields:a,warnings:[`closed_preserved_predecessors:${e.id}:${c.join(",")}`]}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="94147426-41f3-5f24-b6e2-8653f5dde6d0")}catch{}})();var tD=[{key:"resolution",label:"resolution (--resolution)"},{key:"expected_result",label:"expected_result (--expected-result)"},{key:"actual_result",label:"actual_result (--actual-result)"}];function nD(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0||t==="warn")return"warn";if(t==="off"||t==="none"||t==="disabled")return"off";if(t==="strict")return"strict";throw new p(`Invalid --validate-close mode "${e}" (expected "off", "warn", or "strict")`,m.USAGE)}function ob(e){let t=[];for(let n of tD){let r=e[n.key];(typeof r!="string"||r.trim().length===0)&&t.push(n)}return t}function sb(e,t,n={}){let r=ob(e);if(r.length===0)return;let i={resolution:n.resolution,expected_result:n.expectedResult,actual_result:n.actualResult},o=r.map(a=>`--${a.key.replaceAll("_","-")}`),s=[...t,"update",e.id,...r.flatMap((a,c)=>[o[c],i[a.key]?.trim()||"<value>"])];return{missing:o,suggested_retry:L(s),suggested_retry_args:s}}async function rD(e,t,n){let r=new Set,i=t;for(;typeof i=="string"&&i.trim().length>0;){let o=i.trim();if(o===n)return!0;if(r.has(o))return!1;r.add(o),i=(await e(o))?.duplicate_of}return!1}function iD(e){return typeof e!="string"||e.trim().length===0}async function oD(e,t,n,r){let i=n?.trim();if(!i)return;if(i===r)throw new p("An item cannot be closed as a duplicate of itself.",m.USAGE,{code:"duplicate_target_self",why:"--duplicate-of must identify the canonical item that should remain open or already represent the work."});let o=P(t,N()),s=new Map,a=async d=>{if(s.has(d))return s.get(d)??null;let l=await V(e,d,t.id_prefix,t.item_format,o.type_to_folder);if(!l)return s.set(d,null),null;let{document:u}=await pe(l,{schema:t.schema});return s.set(d,u.metadata),u.metadata},c=await a(i);if(!c)throw new p(`Duplicate target "${i}" was not found. Create or locate the canonical item first.`,m.USAGE,{code:"duplicate_target_missing",why:"Duplicate closure should point at a real canonical pm item so future dedupe and changelog tooling can trace the relationship.",examples:[`pm close ${r} "Duplicate of ${i}" --duplicate-of ${i}`],nextSteps:["Run pm search/list to find the canonical item, then retry with --duplicate-of <id>."]});if(await rD(a,c.duplicate_of,r))throw new p(`Circular duplicate reference detected. Target "${i}" points back to "${r}".`,m.USAGE,{code:"duplicate_target_circular",why:"Circular duplicate relationships create loops for dedupe and status propagation tooling.",nextSteps:["Choose the existing canonical item, or clear the target duplicate_of metadata before closing this item as a duplicate."]});if(typeof c.duplicate_of=="string"&&c.duplicate_of.trim().length>0)throw new p(`Duplicate target "${i}" is already marked as a duplicate of "${c.duplicate_of.trim()}".`,m.USAGE,{code:"duplicate_target_is_duplicate",why:"Duplicate closure should point directly at the canonical item, not another duplicate.",examples:[`pm close ${r} "Duplicate of ${c.duplicate_of.trim()}" --duplicate-of ${c.duplicate_of.trim()}`],nextSteps:["Use the canonical item referenced by duplicate_of as the --duplicate-of target."]});return c.id}function sD(e,t,n){return e.filter(r=>r.parent===t&&!fe(r.status,n)).map(r=>r.id).sort((r,i)=>r.localeCompare(i))}function aD(e,t,n){let r=new Map(e.map(a=>[a.id.trim().toLowerCase(),a])),i=Qp(e),o=t.trim().toLowerCase(),s=n.blocked_statuses;return e.filter(a=>s.has(a.status)).map(a=>({item:a,blockerIds:i.get(a.id.trim().toLowerCase())})).filter(({blockerIds:a})=>a.includes(o)).filter(({blockerIds:a})=>a.every(c=>{if(c===o)return!0;let d=r.get(c);return d!==void 0&&fe(d.status,n)})).map(({item:a,blockerIds:c})=>({id:a.id,blocker_ids:c})).sort((a,c)=>a.id.localeCompare(c.id))}async function cD(e,t,n,r,i,o,s){let a=aD(n,r,o),c=[],d=[],l=[],u=[],_;for(let h of a)try{let f=await he({pmRoot:e,settings:t,id:h.id,op:"update",author:i,message:`Auto-unblocked after blocker ${r} closed`,mutate(g){let y=g.metadata.dependencies??[],w=y.filter(k=>{let S=k.id.trim().toLowerCase();return k.kind!=="blocked_by"||!h.blocker_ids.includes(S)});g.metadata.status=o.open_status,delete g.metadata.blocked_by,delete g.metadata.blocked_reason,g.metadata.unblock_note=`Auto-unblocked after blocker ${r} closed; all blockers resolved (${h.blocker_ids.join(", ")}).`,w.length>0?g.metadata.dependencies=w:delete g.metadata.dependencies;let v=["status","blocked_by","blocked_reason","unblock_note"];return w.length!==y.length&&v.push("dependencies"),{changedFields:v}}});c.push(`auto_unblocked:${f.item.id}:resolved_blockers=${h.blocker_ids.join(",")}`),d.push(f.item.id)}catch(f){let g=f instanceof Error?f.message.replace(/\s+/g," ").trim():"unknown";en(f)?(_??=f,l.push(h.id)):u.push({id:h.id,reason:g}),c.push(`auto_unblock_failed:${h.id}:${g}`)}if(_!==void 0){let h=await n_(_,e),f=[...o.blocked_statuses].sort().join(",");throw mD(h,{closedId:r,unblockedIds:d,conflictIds:l,failed:u,openStatus:o.open_status,blockedStatuses:f,commandScope:s})}return c}var Et=10,ml=20,dD=[{list:"auto_unblock_failed",omitted:"auto_unblock_failed_omitted",floor:0},{list:"changes_since",omitted:"changes_since_omitted",floor:0},{list:"pending_unblock",omitted:"pending_unblock_omitted",floor:1}];function lD(e){for(let t of dD){let n=e[t.list];if(Array.isArray(n))for(;n.length>t.floor&&!Kp(e);)n.pop(),Reflect.set(e,t.omitted,Number(e[t.omitted])+1)}return e}function ib(e){let t=e.length-Et;return`${e.slice(0,Et).join(", ")}${t>0?`, and ${t} more`:""}`}var uD="post_close_auto_unblock_refused";function mD(e,t){let{closedId:n,conflictIds:r,failed:i,commandScope:o}=t,s=String(e.context.item_id),a=f=>L([...o,"update",f,"--status",t.openStatus,"--unset","blocked_by","--unset","blocked_reason","--expect-hash",`${f}=<item_hash>`]),c=i.slice(0,Et).map(f=>({id:f.id,reason:Hm(f.reason,160)})),d=i.length===0?"":` Auto-unblocking also failed for ${ib(i.map(f=>f.id))}; details.auto_unblock_failed gives the reasons it kept (auto_unblock_failed_omitted counts the rest; their get step shows the item). Fix that cause before unblocking it.`,l=L([...o,"list","--status",t.blockedStatuses,"--fields","id,title,blocked_by,dependencies","--limit","200"]),u=[...r.slice(0,Et).flatMap(f=>[L([...o,"get",f,"--json"]),a(f)]),...c.map(f=>L([...o,"get",f.id,"--json"]))],_=r.length>Et||i.length>Et||u.length>ml,h=u.slice(0,_?ml-1:ml);return new p(`${n} was closed, but auto-unblocking ${s} was refused. ${e.message}`,e.exitCode,{...e.context,reason:uD,examples:sp(s,!1,{scopeArgs:o}).examples,required:`The close of ${n} is complete; do not retry it. Only unblocking ${r.length===1?s:`the guarded dependents it refused (${ib(r)})`} remains: re-read each one (pm get <id> --json reports item_hash), check that every blocker it declares is resolved, then unblock it with ${a(s)}${r.length===1?"":" for each id"}.${d}${_?` This refusal does not list a step for every dependent left blocked; list them with ${l}, and while it reports has_more, continue with --after <next_cursor>.`:""}`,nextSteps:_?[...h,l]:h,details:lD({...structuredClone(e.context.details),pending_unblock:r.slice(0,Et),pending_unblock_omitted:Math.max(0,r.length-Et),auto_unblock_failed:c,auto_unblock_failed_omitted:Math.max(0,i.length-Et)}),side_effects:[{path:`history/${n}.jsonl`,op:"close"},...t.unblockedIds.map(f=>({path:`history/${f}.jsonl`,op:"update"}))]})}async function ZV(e,t,n){if(!en(e)||!e.context.side_effects?.some(i=>`${i.op}:${i.path}`==`close:history/${t}.jsonl`))return;let r=String(e.context.item_id);return{warnings:[...e.context.side_effects.filter(i=>i.op==="update").map(i=>i.path.slice(8,-6)).map(i=>`auto_unblocked:${i}`),`auto_unblock_refused:${r}:item_revision_conflict`],dependent_revision_conflict:{item_id:r,error:Ki(e),...await e_(e,n)}}}function pD(e,t){let n=[],r=[{option:t.resolution,key:"resolution"},{option:t.expectedResult,key:"expected_result"},{option:t.actualResult,key:"actual_result"}];for(let{option:i,key:o}of r){if(typeof i!="string")continue;let s=i.trim();s.length!==0&&(e[o]=s,n.push(o))}return n}function _D(e,t){if(t===void 0)return[];e.duplicate_of=t;let n=[],r=[{key:"resolution",value:`Duplicate of ${t}`},{key:"expected_result",value:`Canonical item ${t} tracks the work.`},{key:"actual_result",value:`Closed as duplicate of ${t}.`}];for(let{key:i,value:o}of r)iD(e[i])&&(e[i]=o,n.push(i));return n}function fD(e,t){let n=[["--resolution",e.resolution],["--expected-result",e.expectedResult],["--actual-result",e.actualResult],["--validate-close",e.validateClose],["--completed-at",e.completedAt],["--message",e.message],["--author",e.author]].flatMap(([r,i])=>t.has(r)||i===void 0||i.trim().length===0?[]:[`${r}=${i}`]);return e.force===!0?[...n,"--force"]:n}function hD(e,t,n){let r=t.map(y=>y.label),i=t.map(y=>`--${y.key.replaceAll("_","-")}`),o=i.flatMap(y=>[y,"<value>"]),s=[...n.commandScope,"update",e.id,...o],a=`Cannot close item ${e.id}: missing ${r.join(", ")}. Populate fields or use --validate-close warn.`,c="Use --validate-close warn only when governance permits an evidenced exception.",d=Object.entries(n.options.lifecyclePolicy??{}).filter(([,y])=>y!==void 0).map(([y])=>y),l=br(n.pmRoot),u=typeof n.options.author=="string"&&n.options.author.trim().length===0,_=d.length>0?`its lifecyclePolicy override (${d.join(", ")}) has no CLI spelling`:u?"its explicitly blank author has no CLI spelling (pm close refuses an empty --author)":l===void 0?"its revision guards cannot be replayed as typed (nested revision guards expect different revisions of one item, or a write in the same operation advanced a guarded revision)":void 0;if(_!==void 0)return new p(a,m.USAGE,{code:"close_validation_missing_fields",required:`Pass ${t.map(y=>y.key).join(", ")} on the same SDK close; ${_}, so no CLI retry reproduces it.`,recovery:{missing:i,next_best_command:L(s)},nextSteps:["Retry the same SDK close with the missing evidence supplied, inside the same lifecycle policy and revision guards.",c]});let h=n.closeReason===void 0?[]:[`--reason=${n.closeReason}`],f=l.map(y=>`--expect-hash=${y}`),g=[...n.commandScope,"close",e.id,...h,...fD(n.options,new Set(i)),...f,...o];return new p(a,m.USAGE,{code:"close_validation_missing_fields",required:`Supply ${i.join(", ")}: pm close accepts them and records them in the same write as the closure.`,recovery:{missing:i,suggested_retry:L(g),suggested_retry_args:g,next_best_command:L(s)},nextSteps:["Run recovery.suggested_retry when it is present: the same close with the missing flags added, so one write records the evidence and the closure.","Without it, record the evidence with recovery.next_best_command, then repeat the original close.",c]})}function gD(e,t,n,r){let i=t.map(a=>Om(a.field).flag),o=[...r.author?.trim()?[`--author=${r.author}`]:[],...r.force===!0?["--force"]:[]],s=[...n,"update",e.id,...o,...i.flatMap(a=>[a,"<value>"])];return new p(`Cannot close item ${e.id}: deferred fields still have no value (${t.map(a=>a.field).join(", ")}). Supply them or use --validate-close warn.`,m.USAGE,{code:"close_validation_deferred_fields",required:`Supply ${i.join(", ")}: each was deferred at create (${t.map(a=>`${a.field}: ${a.reason}`).join("; ")}).`,recovery:{missing:i,next_best_command:L(s)},nextSteps:["Record the now-known values with recovery.next_best_command; the update resolves each deferral, then repeat the close.","Use --validate-close warn only when governance permits closing with deferred values still unknown."]})}function yD(e,t,n){let r=Qi(e);if(r.length===0)return[];if(t==="strict")throw gD(e,r,n.commandScope,n.options);return[`close_validation_deferred_fields:${e.id}:${r.map(i=>i.field).join(",")}`]}function wD(e,t,n,r){let i=[];if(t!=="off"){i.push(...yD(e,t,r));let o=ob(e);if(o.length>0){let s=o.map(a=>a.label);if(t==="strict")throw hD(e,o,r);i.push(`close_validation_missing_fields:${e.id}:${s.join(",")}`)}if(n.length>0){if(t==="strict")throw new p(`Cannot close item ${e.id}: active child items remain open (${n.join(", ")}). Close, cancel, or re-parent them first, or use --validate-close warn.`,m.USAGE);i.push(`close_validation_active_children:${e.id}:${n.join(",")}`)}return i}return n.length>0&&i.push(`closed_with_active_children:${e.id}:${n.join(",")}`),i}function vD(e,t){return t!==void 0?(e.close_reason=t,["close_reason"]):[]}function bD(e){let t=["assignee","claim_principal"].filter(n=>e[n]!==void 0);for(let n of t)delete e[n];return[...t]}function kD(e,t){if(fe(e.status,t.statusRegistry)&&!t.force)throw new p(`Item ${e.id} is already terminal; use pm update to append acceptance evidence, or --force only for an intentional repeat closure.`,m.CONFLICT,{recovery:sb(e,t.commandScope,t.options)});let n=pD(e,t.options),r=_D(e,t.duplicateOf),i=wD(e,t.validateCloseMode,t.activeChildIds,t);e.status=t.statusRegistry.close_status,e.closed_at=t.closedAt;let o=t.options.completedAt!==void 0||e.completed_at===void 0;o&&(e.completed_at=t.completedAt);let s=["status","closed_at",...o?["completed_at"]:[],...vD(e,t.closeReason),...n];if(Hp(e)&&(e.plan_mode="completed",s.push("plan_mode")),t.duplicateOf!==void 0){s.push("duplicate_of");for(let c of r)s.includes(c)||s.push(c)}s.push(...bD(e));let a=rb(e,t.lifecyclePolicy);return s.push(...a.changedFields),i.push(...a.warnings),{changedFields:s,...i.length>0?{warnings:i}:{}}}async function SD(e,t,n,r){let i=R(process.cwd(),r.path),o=Ie(r);await j(i);let s=await x(i),a=W(s.schema),c=U(n.author,s.author_default),d=P(s,N()).type_to_folder,l=await V(i,e,s.id_prefix,s.item_format,d);if(!l)throw await Qt(i,e,s.id_prefix,d);let u=await oD(i,s,n.duplicateOf,l.id),_={requireCloseReason:n.lifecyclePolicy?.requireCloseReason??s.governance.require_close_reason,orderingEdges:n.lifecyclePolicy?.orderingEdges??"preserve"},h=vs({explicit:t,duplicateOf:u,resolution:n.resolution,message:n.message},_.requireCloseReason).closeReason,f=nD(n.validateClose)??s.governance.close_validation_default,g=await Te(i,s.item_format,d,void 0,s.schema),y=sD(g,l.id,a),w=I(),v=n.completedAt===void 0?w:me(n.completedAt,new Date(w),"completed-at"),k={timestamp:v,source:n.completedAt===void 0?"close_time":"asserted",...n.completedAt===void 0?{hint:`completed_at defaults to the close time. If work finished earlier, correct it with ${L([...o,"update",l.id,"--completed-at","<ISO>"])}.`}:{}},S=await Rt({pmRoot:i,settings:s,id:l.id,op:"close",author:c,message:n.message,force:n.force,resolveHistoryContext:()=>({completion:{timestamp:k.timestamp,source:k.source}}),mutate(A){return n.completedAt===void 0&&A.metadata.completed_at!==void 0&&(k={timestamp:A.metadata.completed_at,source:"existing"}),kD(A.metadata,{pmRoot:i,commandScope:o,statusRegistry:a,force:n.force,options:n,duplicateOf:u,validateCloseMode:f,activeChildIds:y,closeReason:h,closedAt:w,completedAt:v,lifecyclePolicy:_})}}),b=f==="warn"?sb(S.item,o):void 0;return{item:S.item,changed_fields:S.changedFields,...b?{follow_up:{kind:"complete_close_evidence",missing:b.missing,suggested_command:b.suggested_retry,suggested_command_args:b.suggested_retry_args}}:{},warnings:[...S.warnings,...await cD(i,s,g,l.id,c,a,o)],completion:k}}function bs(e,t,n,r){return SD(e,t,n,r)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="73852fdf-f072-51ab-9449-d7922712eeb4")}catch{}})();function ab(e){return[...e].sort().join("\0")}function ED(e,t,n){let r=e.successors.get(t);r?r.push(n):e.successors.set(t,[n]);let i=e.predecessors.get(n);i?i.push(t):e.predecessors.set(n,[t])}function cb(e,t,n,r,i){let o=t.resolve(i);if(o?.ordering!==!0)return;let s=ch(r),a=s===void 0?void 0:e.canonicalIds.get(s.toLowerCase());if(a===void 0)return;let c=(o.precedence??"source_before_target")==="source_before_target";ED(e,c?n:a,c?a:n)}function TD(e,t){let n={successors:new Map,predecessors:new Map,canonicalIds:new Map},r=e.filter(i=>typeof i?.id=="string"&&i.id.trim().length>0);for(let i of r){let o=i.id.trim();n.canonicalIds.set(o.toLowerCase(),o)}for(let i of r){let o=i.id.trim();cb(n,t,o,i.blocked_by,"blocked_by");for(let s of i.dependencies??[])typeof s!="object"||s===null||cb(n,t,o,s.id,typeof s.kind=="string"?s.kind:"related")}for(let i of[n.successors,n.predecessors])for(let o of i.values())o.sort();return n}function CD(e,t){let n=new Set([t]),r=[t];for(;r.length>0;){let i=r.pop();for(let o of[e.successors,e.predecessors])for(let s of o.get(i)??[])n.has(s)||(n.add(s),r.push(s))}return n}function AD(e,t){let n=new Map;for(let r of t){let i=(e.successors.get(r)??[]).filter(o=>t.has(o));i.length>0&&n.set(r,i)}return n}function db(e,t,n){let r=TD(e,t),i=r.canonicalIds.get(n.trim().toLowerCase());if(i===void 0)return{cycles:[],successors:new Map,canonical:n};let o=AD(r,CD(r,i));return{cycles:vh(o).filter(s=>s.includes(i)),successors:o,canonical:i}}function xD(e,t,n){let r=new Set(t),i=r.has(n)?n:t[0];if(e.get(i)?.includes(i))return[i,i];for(let o of e.get(i)??[]){if(!r.has(o))continue;let s=RD(e,r,i,o);if(s)return s}return[...t,t[0]]}function RD(e,t,n,r){let i=[[r]],o=new Set([n,r]);for(;i.length>0;){let s=i.shift(),a=s.at(-1);for(let c of e.get(a)??[]){if(c===n)return[n,...s,n];!t.has(c)||o.has(c)||(o.add(c),i.push([...s,c]))}}}function ks(e,t,n){let r=de(),i=db(e,r,n),o=db(t,r,n),s=new Set(i.cycles.map(ab)),a=new Set(wc(e,void 0,r).map(c=>`${c.holder_id.toLowerCase()}\0${c.target_id.toLowerCase()}\0${c.dependency_kind}`));return[...wc(t,void 0,r).filter(c=>c.holder_id.toLowerCase()===n.trim().toLowerCase()&&!a.has(`${c.holder_id.toLowerCase()}\0${c.target_id.toLowerCase()}\0${c.dependency_kind}`)).map(c=>`ordering_storage_contradiction_created:${bh(c)}:remove_contradicting_dependency_row:run_pm_graph_audit`),...o.cycles.filter(c=>!s.has(ab(c))).map(c=>`ordering_cycle_created:${xD(o.successors,c,o.canonical).join(" -> ")}:items_will_not_be_ready:run_pm_graph_audit`)]}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5f2ca18e-450d-5b6e-9e07-7bbf080764f9")}catch{}})();function Ss(e,t){let n=t.resolve(e);return n?.hierarchy===!0||n?.outgoing==="one"||n?.incoming==="one"}function lb(e,t,n,r,i){let o=JSON.stringify([t,n,r]),s=e.get(o);s===void 0&&(s={kind:t,direction:n,node_id:r,endpoints:new Set},e.set(o,s)),s.endpoints.add(i)}function ub(e,t){let n=new Map;for(let r of e)for(let i of r.dependencies??[]){let o=t.resolve(i.kind);o===void 0||o.hierarchy||(o.outgoing==="one"&&lb(n,o.kind,"outgoing",r.id,i.id),o.incoming==="one"&&lb(n,o.kind,"incoming",i.id,r.id))}return n}function Es(e,t,n=de()){let r=ub(e,n),i=ub(t,n);for(let o of[...i.keys()].sort()){let s=i.get(o);if(s.endpoints.size<=1)continue;let a=r.get(o);if(![...s.endpoints].every(c=>a?.endpoints.has(c)))throw new p(`Relationship ${s.kind} permits only one ${s.direction} endpoint for ${s.node_id}.`,m.USAGE,{code:"dependency_cardinality_created",field:"dependencies",value:s.kind,relationship_cardinality:{kind:s.kind,direction:s.direction,node_id:s.node_id,endpoint_ids:[...s.endpoints].sort()},required:"The final dependency set must satisfy the active relationship kind's one-edge cardinality.",nextSteps:["Drop extra --dep seeds, or remove conflicting rows with update --dep-remove before adding another edge.","Choose another kind only when its declared semantics match the intended relationship."]})}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="35d8018b-d17b-5d63-9d85-9db0b416326a")}catch{}})();var ID=["setup","test"];function Ce(e){return e.phase==="setup"}function er(e,t){if(e===void 0)return;let n=typeof e=="string"?e.trim().toLowerCase():e;if(n==="setup")return"setup";if(!(n==="test"||n===""))throw new p(`${t} field "phase" must be one of: ${ID.join(", ")}`,m.USAGE,{code:"invalid_argument_value",required:"Use phase=setup for a step that runs before the linked commands, or omit phase for a regular linked test.",examples:['pm test <id> --add "command=npm run build,phase=setup"']})}function Ts(e){return[...e.filter(Ce),...e.filter(t=>!Ce(t))]}function mb(e,t){if(!e.selected.some(o=>!Ce(o)))return e;let n=t.flatMap((o,s)=>Ce(o)?[s+1]:[]);if(n.length===0)return e;let r=e.selected_indexes.filter(o=>!Ce(t[o-1])),i=n.filter(o=>!e.selected_indexes.includes(o));return{...e,selected:[...n,...r].map(o=>t[o-1]),selected_indexes:[...n,...r],selected_count:n.length+r.length,skipped_count:t.length-n.length-r.length,...i.length>0?{setup_indexes:i}:{}}}function pb(e,t,n){if(!Ce(e))return;let r=[...n].filter(i=>i!==t).sort();if(r.length!==0)return{command:e.command,path:e.path,status:"refused",exit_code:null,failure_category:"config_refusal",error:`Setup entry runs in the ${t} workspace, but linked commands it prepares run in ${r.join(", ")}, so its output would not reach them. Set workspace_context_mode on the setup entry and the linked commands to one mode.`}}function di(){let e;return{blocked(t){if(e!==void 0)return{command:t.command,path:t.path,status:"skipped",...Ce(t)?{phase:"setup"}:{},error:`Skipped because setup entry "${e.label}" did not pass (${e.outcome}); no later linked command ran.`}},options(t,n){return!Ce(t)||n===void 0?n:{...n,failOnEmptyTestRun:!1,requireAssertionsForPm:!1}},record(t,n){if(!Ce(t))return n;if(n.status==="passed")return{...n,phase:"setup"};let r=n.status==="refused"||n.failure_category==="trust_refusal"||n.failure_category==="setup_failed"?{...n,phase:"setup"}:{...n,status:"failed",phase:"setup",failure_category:"setup_failed",...n.failure_category===void 0?{}:{setup_failure_cause:n.failure_category}};return e={label:t.command??t.path??"<no command>",outcome:r.failure_category??r.status},r}}}function OD(){return{infra_collision:0,trust_refusal:0,config_refusal:0,assertion_failure:0,empty_run:0,timeout:0,max_buffer:0,spawn_error:0,signal:0,setup_failed:0}}function tr(e){let t=OD();for(let n of e)n.status!=="failed"&&n.status!=="refused"||!n.failure_category||(t[n.failure_category]+=1);return t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ef8e6aec-bd75-5615-bcda-a51d055b65d7")}catch{}})();var un=new Set(["PM_PATH","PM_GLOBAL_PATH","PM_SOURCE_PM_PATH","PM_SOURCE_WORKSPACE_ROOT","PM_BUILD_CONSUMER_LEASE","PM_BUILD_CONSUMER_LEASE_ROOT",Nr,ph,"FORCE_COLOR"]),xs=/^[A-Za-z_][A-Za-z0-9_]*$/,ln=["schema","tracker","auto","none"],_b=["source","isolated","snapshot"];function li(e,t){if(!e)return;let n=e.split(/[;\n]/).map(i=>i.trim()).filter(i=>i.length>0);if(n.length===0)throw new p(`${t} env_set must include at least one KEY=VALUE assignment`,m.USAGE);let r=Object.create(null);for(let i of n){let o=i.indexOf("=");if(o<=0)throw new p(`${t} env_set entries must use KEY=VALUE and be separated by semicolons. Example: env_set=PORT=0;PLAYWRIGHT_BASE_URL=http://127.0.0.1:4173`,m.USAGE);let s=i.slice(0,o).trim(),a=i.slice(o+1);if(!xs.test(s))throw new p(`${t} env_set key "${s}" is invalid`,m.USAGE);if(un.has(s.toUpperCase()))throw new p(`${t} env_set key "${s}" is reserved for sandbox safety`,m.USAGE);r[s]=a}return Object.keys(r).length>0?r:void 0}function ui(e,t){if(!e)return;let n=rc(e,{separators:/[;,\n]/});if(n.length===0)throw new p(`${t} env_clear must include at least one environment variable name`,m.USAGE);for(let r of n){if(!xs.test(r))throw new p(`${t} env_clear key "${r}" is invalid`,m.USAGE);if(un.has(r.toUpperCase()))throw new p(`${t} env_clear key "${r}" is reserved for sandbox safety`,m.USAGE)}return n}function Rs(e,t,n){if(!e)return;let r=e.trim().toLowerCase();if(r==="true"||r==="1"||r==="yes")return!0;if(r==="false"||r==="0"||r==="no")return!1;throw new p(`${t} ${n} must be one of true|false|1|0|yes|no`,m.USAGE)}function Is(e,t){if(!e)return;let n=e.trim().toLowerCase();if(ln.includes(n))return n;throw new p(`${t} pm_context_mode must be one of: ${ln.join(", ")}`,m.USAGE)}function mn(e,t){if(!e)return;let n=e.trim().toLowerCase();if(_b.includes(n))return n;throw new p(`${t} workspace_context_mode must be one of: ${_b.join(", ")}`,m.USAGE)}function pn(e){if(!e)return;let t=rc(e,{separators:/[;\n]/});return t.length>0?t:void 0}function nr(e,t,n){let r=pn(e);if(!(!r||r.length===0)){for(let i of r)try{new RegExp(i,"m")}catch(o){throw new p(`${t} ${n} includes invalid regex "${i}": ${o instanceof Error?o.message:String(o)}`,m.USAGE)}return r}}function Os(e,t){if(!e)return;let n=we(e,"assert_stdout_min_lines");if(!Number.isInteger(n)||n<0)throw new p(`${t} assert_stdout_min_lines must be an integer >= 0`,m.USAGE);return n}function Ls(e,t){if(!e)return;let n=e.split(/[;\n]/).map(i=>i.trim()).filter(i=>i.length>0);if(n.length===0)throw new p(`${t} assert_json_field_equals must include at least one path=value assignment`,m.USAGE);let r=Object.create(null);for(let i of n){let o=i.indexOf("=");if(o<=0)throw new p(`${t} assert_json_field_equals entries must use path=value and be separated by semicolons`,m.USAGE);let s=i.slice(0,o).trim(),a=i.slice(o+1).trim();if(s.length===0||a.length===0)throw new p(`${t} assert_json_field_equals entries must include non-empty path and value`,m.USAGE);r[s]=a}return Object.keys(r).length>0?r:void 0}function Ds(e,t){if(!e)return;let n=e.split(/[;\n]/).map(i=>i.trim()).filter(i=>i.length>0);if(n.length===0)throw new p(`${t} assert_json_field_gte must include at least one path=value assignment`,m.USAGE);let r=Object.create(null);for(let i of n){let o=i.indexOf("=");if(o<=0)throw new p(`${t} assert_json_field_gte entries must use path=value and be separated by semicolons`,m.USAGE);let s=i.slice(0,o).trim(),a=i.slice(o+1).trim();if(s.length===0||a.length===0)throw new p(`${t} assert_json_field_gte entries must include non-empty path and value`,m.USAGE);let c=Number(a);if(!Number.isFinite(c))throw new p(`${t} assert_json_field_gte value for "${s}" must be numeric`,m.USAGE);r[s]=c}return Object.keys(r).length>0?r:void 0}var LD=new Set(ft);function $s(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function DD(e,t){let n={},r=[];for(let[i,o]of Object.entries(e)){let s=i.toLowerCase();if(!LD.has(s)){r.push(i);continue}if(Object.hasOwn(n,s))throw t(`provides key "${i}" more than once after case normalization`);n[s]=o}if(r.length>0)throw t(`does not recognize key${r.length>1?"s":""} ${r.map(i=>`"${i}"`).join(", ")}. Allowed keys: ${ft.join(", ")}.`);return n}function dn(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r!==void 0){if(typeof r!="string")throw n(`field "${t}" must be a JSON string`);return r}}function Cs(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r===void 0)return;let i=typeof r=="string"?[r]:r;if(!Array.isArray(i)||i.some(s=>typeof s!="string"))throw n(`field "${t}" must be a string or an array of strings`);let o=i.filter(s=>s.length>0);return o.length>0?o:void 0}function fb(e,t,n){let r=Cs(e,t,n);if(r){for(let i of r)try{new RegExp(i,"m")}catch(o){throw n(`field "${t}" includes invalid regex "${i}": ${o instanceof Error?o.message:String(o)}`)}return r}}function As(e,t,n){let r=typeof e=="number"?e:typeof e=="string"&&e.trim().length>0?Number(e.trim()):Number.NaN;if(typeof e=="boolean"||!Number.isFinite(r))throw n(`field "${t}" must be a finite number (or numeric string)`);return r}function $D(e,t){let n=e.timeout_seconds,r=e.timeout;if(n===void 0&&r===void 0)return;let i=n===void 0?void 0:As(n,"timeout_seconds",t),o=r===void 0?void 0:As(r,"timeout",t);if(i!==void 0&&o!==void 0&&i!==o)throw t("timeout and timeout_seconds must match when both are provided");let s=i??o;if(!Number.isInteger(s)||s<=0)throw t("timeout_seconds must be a positive integer");return s}function ND(e,t){let n=dn(e,"scope",t);if(n===void 0)return"project";if(!Ke.includes(n))throw t(`field "scope" must be one of: ${Ke.join(", ")}`);return n}function MD(e,t){if(!Object.hasOwn(e,"env_set"))return;let n=e.env_set;if(n===void 0)return;if(!$s(n))throw t('field "env_set" must be a JSON object mapping environment names to string values');let r=Object.create(null);for(let[i,o]of Object.entries(n)){if(typeof o!="string")throw t(`field "env_set" value for "${i}" must be a string`);if(!xs.test(i))throw t(`field "env_set" key "${i}" is invalid`);if(un.has(i.toUpperCase()))throw t(`field "env_set" key "${i}" is reserved for sandbox safety`);r[i]=o}return Object.keys(r).length>0?r:void 0}function PD(e,t){let n=Cs(e,"env_clear",t);if(n){for(let r of n){if(!xs.test(r))throw t(`field "env_clear" key "${r}" is invalid`);if(un.has(r.toUpperCase()))throw t(`field "env_clear" key "${r}" is reserved for sandbox safety`)}return n}}function FD(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r!==void 0){if(typeof r!="boolean")throw n(`field "${t}" must be a JSON boolean (true or false)`);return r}}function jD(e,t){if(!Object.hasOwn(e,"assert_stdout_min_lines"))return;let n=e.assert_stdout_min_lines;if(n===void 0)return;let r=As(n,"assert_stdout_min_lines",t);if(!Number.isInteger(r)||r<0)throw t('field "assert_stdout_min_lines" must be an integer >= 0');return r}function UD(e,t){if(!Object.hasOwn(e,"assert_json_field_equals"))return;let n=e.assert_json_field_equals;if(n===void 0)return;if(!$s(n))throw t('field "assert_json_field_equals" must be a JSON object mapping field paths to expected values');let r=Object.create(null);for(let[i,o]of Object.entries(n)){if(i.trim().length===0)throw t('field "assert_json_field_equals" keys must be non-empty field paths');if(typeof o!="string"&&typeof o!="number"&&typeof o!="boolean")throw t(`field "assert_json_field_equals" value for "${i}" must be a string, number, or boolean`);r[i]=String(o)}return Object.keys(r).length>0?r:void 0}function GD(e,t){if(!Object.hasOwn(e,"assert_json_field_gte"))return;let n=e.assert_json_field_gte;if(n===void 0)return;if(!$s(n))throw t('field "assert_json_field_gte" must be a JSON object mapping field paths to numeric minimums');let r=Object.create(null);for(let[i,o]of Object.entries(n)){if(i.trim().length===0)throw t('field "assert_json_field_gte" keys must be non-empty field paths');r[i]=As(o,`assert_json_field_gte.${i}`,t)}return Object.keys(r).length>0?r:void 0}function qD(e,t,n){let r=_=>new p(`${n} ${t} ${_}`,m.USAGE);if(!$s(e))throw r(`must be a JSON object with linked-test fields. Allowed keys: ${ft.join(", ")}.`);let i=DD(e,r),o=dn(i,"command",r),s=dn(i,"cmd",r);if(o!==void 0&&s!==void 0&&o!==s)throw r("command and cmd must match when both are provided");let a=o??s;if(a===void 0||a.trim().length===0)throw r('requires a non-empty "command" string');let c=dn(i,"path",r),d=dn(i,"pm_context_mode",r);if(d!==void 0&&!ln.includes(d))throw r(`field "pm_context_mode" must be one of: ${ln.join(", ")}`);let l=mn(dn(i,"workspace_context_mode",r),`${n} ${t}`),u=dn(i,"note",r);return{command:a,path:c!==void 0&&c.length>0?c:void 0,scope:ND(i,r),timeout_seconds:$D(i,r),pm_context_mode:d,workspace_context_mode:l,env_set:MD(i,r),env_clear:PD(i,r),shared_host_safe:FD(i,"shared_host_safe",r),assert_stdout_contains:Cs(i,"assert_stdout_contains",r),assert_stdout_regex:fb(i,"assert_stdout_regex",r),assert_stderr_contains:Cs(i,"assert_stderr_contains",r),assert_stderr_regex:fb(i,"assert_stderr_regex",r),assert_stdout_min_lines:jD(i,r),assert_json_field_equals:UD(i,r),assert_json_field_gte:GD(i,r),note:u!==void 0&&u.trim().length>0?u.trim():void 0,phase:er(i.phase,`${n} ${t}`)}}function mi(e,t){let n=e.trim();if(n.length===0)throw new p(`${t} requires a JSON object or array of objects describing linked-test entries`,m.USAGE);let r;try{r=JSON.parse(n)}catch(o){throw new p(`${t} value is not valid JSON: ${o instanceof Error?o.message:String(o)}. Provide a JSON object or array of objects, e.g. '{"command":"node scripts/check.js --flag value, with commas","timeout_seconds":120}'.`,m.USAGE)}let i=Array.isArray(r)?r:[r];if(i.length===0)throw new p(`${t} array must include at least one linked-test entry object`,m.USAGE);return i.map((o,s)=>qD(o,i.length>1?`entry ${s+1}`:"entry",t))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a9b9f4df-2129-5230-af20-16bef3754d39")}catch{}})();var KD={comment:"--clear-comments",dep:"--clear-deps",doc:"--clear-docs",event:"--clear-events",file:"--clear-files",learning:"--clear-learnings",note:"--clear-notes",reminder:"--clear-reminders",test:"--clear-tests",typeOption:"--clear-type-options"};function WD(e){return KD[e]}function _l(e){return WD(e)!==void 0}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e58f7cfe-1414-5205-9f1c-b667abf67702")}catch{}})();function fl(){return Ba.map(e=>e.field).join(", ")}var zD=Object.freeze({fields:[],reason:void 0,optionKeys:new Set});function BD(e){return(e??[]).flatMap(t=>t.split(",")).map(t=>t.trim()).filter(t=>t.length>0)}function hb(e,t){let n=kn(t,"defer"),r=kn(t,"defer-reason"),i=BD(e.defer),o=e.deferReason?.trim();if(i.length===0){if(o!==void 0&&o.length>0)throw new p(`${r} needs ${n}: name the fields whose values are not known yet.`,m.USAGE,{code:"create_deferral_fields_required",required:`Pass ${n} with ${r}, or drop ${r}.`,nextSteps:[`Deferrable fields: ${fl()}.`]});return zD}let s=new Map;for(let c of i){let d=Ha(c);if(d===void 0)throw new p(`${n} cannot defer "${c}". Deferrable fields: ${fl()}.`,m.USAGE,{code:"create_deferral_field_unsupported",required:`Defer only ${fl()}; supply every other field, or clear a repeatable option with its --clear-* flag.`});s.set(d.field,d)}if(o===void 0||o.length===0)throw new p(`${n} requires ${r}: record why the deferred values are not known yet.`,m.USAGE,{code:"create_deferral_reason_required",required:`Pass ${r} "<why>", for example the system the record was imported from.`});let a=Ba.filter(c=>s.has(c.field));return{fields:a,reason:o,optionKeys:new Set(a.map(c=>c.option))}}function hl(e,t,n,r,i={}){let o=e.fields.filter(c=>{let d=t[c.option];return typeof d=="string"&&d.trim().length>0||i[c.field]!==void 0||n.has(c.field)});if(o.length===0)return;let s=kn(r,"defer"),a=o.map(c=>c.field).join(", ");throw new p(`Cannot both defer and set ${a}: ${s} records a value as not known yet.`,m.USAGE,{code:"create_deferral_conflict",required:`Drop ${s} for ${a}, or drop the value (or unset) you supplied for it.`})}function gb(e){if(e.fields.length!==0)return Lm(e.fields.map(t=>({field:t.field,reason:e.reason})))}function yb(e,t=[]){let n=(Array.isArray(e)?e:e===void 0?[]:[e]).filter(o=>typeof o=="string").flatMap(o=>o.split(",")).map(o=>Ha(o)).filter(o=>o!==void 0),r=new Set(n.map(o=>o.field)),i=t.filter(o=>o.commands.includes("create")&&r.has(o.metadata_key)).flatMap(o=>Am(o));return[...n.map(o=>o.option),...i]}function wb(e,t,n,r,i={}){let o=new Set(t.fields.map(l=>l.field)),s=n.filter(l=>l.commands.includes("create")),a=l=>l.required!==!0&&o.has(l.metadata_key),c=new Set(s.filter(a).map(l=>`--${l.cli_flag}`)),d=new Set(s.filter(l=>!a(l)&&xm(l,r)&&Vi(i,l)===void 0).map(l=>`--${l.cli_flag}`));return e.filter(l=>!c.has(l)||d.has(l))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b653115b-596b-5c07-b1f7-541fa1f04a33")}catch{}})();var HD="hierarchy-integrity";async function Ns(e){let t=e.required?await eo(e.pmRoot,HD,e.ttlSeconds,e.author,!1,!1,e.waitMs,{waitPolicy:"progress"}):async()=>{},n=!1;return async()=>{n||(n=!0,await t())}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="01a312de-88fc-514f-b37b-2e717222a8ed")}catch{}})();function Ms(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function Ps(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function Fs(e){let t=e.trim().toLowerCase();if(t==="med")return"medium";if(Qu.includes(t))return t;let n=we(e,"confidence");if(!Number.isInteger(n)||n<0||n>100)throw new p("Confidence must be an integer 0..100 or one of low|med|medium|high",m.USAGE);return n}function js(e){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1;throw new p("Regression must be one of true|false|1|0",m.USAGE)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9625fa5b-47ea-52b6-bf65-ac0f32ae616b")}catch{}})();var vb=[["dependencies","dep",["id","kind","created_at","author","source_kind"]],["comments","comment",["text","created_at","author"]],["notes","note",["text","created_at","author"]],["learnings","learning",["text","created_at","author"]],["files","file",["path","scope","note"]],["tests","test",["command","scope","timeout_seconds","phase"]],["docs","doc",["path","scope","note"]],["reminders","reminder",["at","text","created_at"]],["events","event",["start_at","end_at","title","location"]],["type_options","typeOption",["key","value"]]];(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="48513c82-4195-51fc-bd68-480148a54d10")}catch{}})();var VD=["documentAnnotationSnapshot","runtimeFieldCommands","ownershipMetadataBypass","ownershipDependencyBypass"];function Us(e){let t=vb.find(([r])=>r===e)?.[1]??e.replaceAll(/_([a-z])/gu,(r,i)=>i.toUpperCase()),n=[["update",pc],["create",mc]].flatMap(([r,i])=>i.flatMap(o=>{if(o.target!==t)return[];let s=o.option.match(/--[a-z][a-z0-9-]*/u)[0];return[{command:r,flag:s}]}));return{recovery:{provided_fields:[e],...n.length>0?{suggested_flags:[...new Set(n.map(r=>r.flag))]}:{}},nextSteps:n.length>0?n.map(({command:r,flag:i})=>`Use the declared core mutation: pm ${r}${r==="update"?" <id>":""} ${i} <value>; inspect its help for other required options.`):[`No dedicated create/update CLI mutation flag is declared for "${e}". Use its owning lifecycle, evidence, or importer API; --field cannot mutate core metadata.`]}}var kb={create:{name:"create",usage:"pm create",sdkScope:"create options"},update:{name:"update",usage:"pm update <id>",sdkScope:"update options"},update_many:{name:"update-many",usage:"pm update-many <selection flags>",sdkScope:"update options of the update-many request"}};function bb(e){return e.flatMap(t=>[t.flag,...t.short===void 0?[]:[t.short],...t.aliases??[]])}function Sb(e){if(e==="update_many"){let i=Sb("update"),o=bb(Ar("update-many"));return{options:new Set([...i.options,...o.map(s=>za(s))]),flags:new Set([...i.flags,...o])}}let t=e==="update"?pc:mc,n=bb([...Ar(e),...yo]),r=[...t.flatMap(i=>[i.target,...i.keys]),...n.map(i=>za(i)),...e==="update"?VD:[]];return{options:new Set(r),flags:new Set(n)}}function YD(e,t){let n=kb[t];return e===void 0?`SDK: every option name for this field is shared with another declared field or an option of pm ${n.name}; no SDK option sets it alone.`:`SDK: pass ${e} in the ${n.sdkScope}.`}function JD(e,t,n,r){return e.definitions.some(i=>i.metadata_key===t.metadata_key&&i.commands.includes(n)&&Vi(r,i)!==void 0)}function Gs(e,t,n){let r=kb[t],i=n===void 0?void 0:Object.fromEntries(Object.entries(n).filter(([o])=>o!=="field"));return o=>{let s=Em(o),a=e.definitions.filter(h=>h.metadata_key===s||h.key===s),c=a.find(h=>h.commands.includes(t))??a[0];if(c===void 0)return;let d=`Inspect the value contract with: pm schema show-field ${c.key}`;if(!c.commands.includes(t))return{recovery:{provided_fields:[o]},nextSteps:[`The project schema declares "${c.key}" for ${c.commands.join(", ")} only; ${r.name} cannot set it.`,d]};if(i!==void 0&&JD(e,c,t,i))return{recovery:{provided_fields:[o]},nextSteps:[`This invocation already sets "${c.key}" through a declared flag or option; drop the --field ${o} assignment so the field receives one value.`,d]};let l=Sb(t),u=Cm(c,e,l,t),_=u===void 0?`Every CLI spelling of "${c.key}" is shared with another declared field or an option of pm ${r.name}; give it a distinct cli_flag in the project schema.`:`Use the declared project-schema flag: ${r.usage} ${Wa(u)} <value>`;return{recovery:{provided_fields:[o],...u===void 0?{}:{suggested_flags:[Wa(u)]}},nextSteps:[_,YD(Tm(c,e,l.options,t),t),d]}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="daa816a5-05d4-5e0a-90aa-9d96afdb2117")}catch{}})();var XD=new Set(["event","meeting","reminder","milestone","decision","adr"]);function Eb(e,t,n,r){if(XD.has(t.trim().toLowerCase())||n!==r.open_status)return;let i=Je("in_progress",r);if(!(i===void 0||i===r.open_status))return{command:`pm claim ${e} --start`,to_status:i}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="48975dc8-636f-51a1-858a-f97c7a037688")}catch{}})();function Cb(e,t){let n=e.trim().toLowerCase();if(n==="true"||n==="1"||n==="yes")return!0;if(n==="false"||n==="0"||n==="no")return!1;throw new p(`${t} must be one of true|false|1|0|yes|no`,m.USAGE)}function gl(e){return e?e.split("|").map(t=>t.trim()).filter(t=>t.length>0):[]}function tt(e,t,n,r=n){if(!t.includes(e))throw new p(`Invalid ${n} value "${e}". Allowed: ${t.join(", ")}`,m.USAGE,{field:r,value:e,recovery:{allowed_values:[...t]},required:`${n} must be one of: ${t.join(", ")}.`,nextSteps:[`Choose an allowed ${n} and retry the mutation.`]});return e}var Ab=["recur_freq","recur_interval","recur_count","recur_until","recur_by_weekday","recur_by_month_day","recur_exdates"];function QD(e,t){return t==="defined"?e!==void 0:!!e}function Tb(e,t,n){if(!QD(e,n))return;let r=we(e,`event ${t}`);if(!Number.isInteger(r)||r<1)throw new p(`--event ${t} must be an integer >= 1`,m.USAGE);return r}function ZD(e,t,n){let r=e?me(e,n,"event.recur_until"):void 0;if(r&&r<t)throw new p("--event recur_until must be at or after start",m.USAGE);return r}function e$(e){return Array.from(new Set(gl(e).map(t=>tt(t.toLowerCase(),im,"event weekday")))).sort((t,n)=>$a(t)-$a(n))}function t$(e){return Array.from(new Set(gl(e).map(t=>{let n=we(t,"event recur_by_month_day");if(!Number.isInteger(n)||n<1||n>31)throw new p("--event recur_by_month_day values must be integers 1..31",m.USAGE);return n}))).sort((t,n)=>t-n)}function n$(e,t){return Array.from(new Set(gl(e).map(n=>me(n,t,"event.recur_exdates")))).sort((n,r)=>n.localeCompare(r))}function xb(e,t,n,r){let i=e.recur_freq?.trim(),o=e.recur_interval?.trim(),s=e.recur_count?.trim(),a=e.recur_until?.trim(),c=e.recur_by_weekday?.trim(),d=e.recur_by_month_day?.trim(),l=e.recur_exdates?.trim();if(![i,o,s,a,c,d,l].some(v=>v!==void 0))return;if(!i)throw new p("--event recurrence fields require recur_freq=<daily|weekly|monthly|yearly>",m.USAGE);let u=tt(i.toLowerCase(),rm,"event recurrence frequency"),_=Tb(o,"recur_interval",r),h=Tb(s,"recur_count",r),f=ZD(a,t,n),g=e$(c),y=t$(d),w=n$(l,n);return{freq:u,interval:_,count:h,until:f,by_weekday:g.length>0?g:void 0,by_month_day:y.length>0?y:void 0,exdates:w.length>0?w:void 0}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="414326ff-8d4d-577d-b724-ab32b3f311ac")}catch{}})();function rr(e,t=de()){let n=t.resolve(e);if(n)return n.kind;let r=new Set(Da),i=[...Da,...t.list().filter(({kind:o})=>!r.has(o)).flatMap(({kind:o,aliases:s})=>[o,...s])];throw new p(`Invalid dependency kind value "${e}". Allowed: ${i.join(", ")}`,m.USAGE,{field:"kind",value:e,recovery:{allowed_values:i},required:`dependency kind must be one of: ${i.join(", ")}.`,nextSteps:["Choose a registered kind, or install and enable the extension that registers this kind before retrying."]})}function pi(e,t,n="--dep"){if(!t&&/[:,=]/.test(e))throw new p(`Invalid ${n} value "${e}". Use a bare item id or id=<id>,kind=<kind>.`,m.USAGE,{code:"dependency_flag_value_invalid",reason:"malformed_dependency_shorthand",flag:n,value:e,required:"Use a bare item id or an explicit id=<id>,kind=<kind> entry."})}function _i(e,t,n=de()){for(let r of t??[])try{dp(e,r.id,r.kind,n)}catch(i){throw new p(Ki(i),m.USAGE,{code:"dependency_edge_not_allowed",why:`${e} -> ${r.id} (${r.kind}) violates the active relationship-kind policy`})}}async function Rb(e,t){return(await pe(e,{schema:t})).document.metadata.created_at}async function r$(e,t){if(e.createdAt!==void 0)return e.createdAt;let n=await V(t.pmRoot,e.id,t.idPrefix,t.itemFormat,t.typeToFolder);return n===null?void 0:Rb(n,t.schema)}function i$(e){let t=e.registry.require(e.dependency.kind);return new p(`${t.kind} requires source ${e.holder.id} to be created after target ${e.dependency.id}`,m.USAGE,{code:"dependency_temporal_order_invalid",reason:"source_not_after_target",required:`${e.holder.id}.created_at must be later than ${e.dependency.id}.created_at for ${t.kind}.`,why:"Chronological recurrence direction must be validated before the relationship is persisted.",source_id:e.holder.id,source_created_at:e.sourceCreatedAt,target_id:e.dependency.id,target_created_at:e.targetCreatedAt,temporal_order:t.temporalOrder})}async function o$(e){let t=e.dependencies.filter(i=>e.registry.resolve(i.kind)?.temporalOrder==="source_after_target"&&!e.missingTargets.includes(i.id));if(t.length===0||e.holders.length===0)return;let n=new Map(e.resolutions.flatMap(({target:i,located:o})=>o===null?[]:[[i,o]])),r=new Map(await Promise.all([...new Set(t.map(({id:i})=>i))].map(async i=>[i,await Rb(n.get(i),e.context.schema)])));for(let i of e.holders){let o=await r$(i,e.context);if(o!==void 0)for(let s of t){let a=r.get(s.id),c=Date.parse(o),d=Date.parse(a);if(!(Number.isFinite(c)&&Number.isFinite(d)&&c>d))throw i$({holder:i,dependency:s,sourceCreatedAt:o,targetCreatedAt:a,registry:e.registry})}}}async function qs(e){let t=e.registry??de(),n=(e.dependencies??[]).filter(s=>!Xp(s.source_kind)),r=[...new Set(n.map(s=>s.id))],i=await Promise.all(r.map(async s=>({target:s,located:await V(e.pmRoot,s,e.idPrefix,e.itemFormat,e.typeToFolder)}))),o=i.filter(({located:s})=>s===null).map(({target:s})=>s).sort((s,a)=>s<a?-1:1);if(o.length>0&&e.allowUnresolved!==!0)throw new p(`Dependency target${o.length===1?"":"s"} not found: ${o.join(", ")}`,m.NOT_FOUND,{code:"dependency_target_not_found",reason:"unresolved_local_dependency",required:"Every local dependency target must exist before the edge is committed.",why:"Fail-fast target resolution prevents dangling graph nodes and preserves reliable traversal semantics.",unresolved_targets:o,examples:["--dep id=<existing-item-id>,kind=related","--dep id=<external-id>,kind=related,source_kind=external","--allow-unresolved-deps --dep id=<future-item-id>,kind=related"],nextSteps:[`Create or correct ${o.length===1?"the target":"the targets"}, then retry the mutation.`,"Use source_kind=external for a cross-workspace reference.","Use --allow-unresolved-deps only when the dangling local edge is intentional."],recovery:{recovery_mode:"compact",missing:o,suggested_flags:["--allow-unresolved-deps"],suggested_retry:`pm search "${o[0]}" --limit 10`}});return await o$({dependencies:n,missingTargets:o,resolutions:i,holders:e.holders??[],registry:t,context:e}),o.map(s=>`dependency_target_unresolved:${s}`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3950ef46-cc2b-5b8e-97d6-34c739bd816e")}catch{}})();var Ib="--event end must be strictly after start. Equal start/end timestamps are treated as an instant event (end is dropped); an end earlier than start is rejected. Omit end for an instant event or set end later than start.",s$="--event end and duration are mutually exclusive; provide only one (use duration=<relative> like duration=2h, duration=30min, or duration=PT30M, or set an explicit end).",a$=/^([+-]?)(\d+)(min|mins|minute|minutes)$/i,c$=/^([+-]?)[Pp][Tt](?:(\d+)[Hh])?(?:(\d+)[Mm])?(?:(\d+)[Ss])?$/,Lb=1e3,yl=60*Lb,d$=60*yl;function Ob(e,t){let n=new Date(e);if(!Number.isFinite(n.getTime()))throw new p(`Invalid event.duration value "${t}". Duration is out of supported timestamp range.`,m.USAGE);return n.toISOString()}function l$(e,t){let n=new Date(e),r=t.trim();if(/^[+-]?\d+m$/i.test(r))throw new p(`Event duration "${r}" is ambiguous. Use min for minutes or mo for months (for example 5min or 5mo).`,m.USAGE);let i=r.replace(/^([+-]?\d+)mo$/i,"$1m"),o=a$.exec(r);if(o){let c=o[1]==="-"?-1:1,d=Number.parseInt(o[2],10)*c;return Ob(n.getTime()+d*yl,r)}let s=c$.exec(r);if(s){let[,c,d,l,u]=s;if(d||l||u){let _=c==="-"?-1:1,h=Number.parseInt(d??"0",10),f=Number.parseInt(l??"0",10),g=Number.parseInt(u??"0",10),y=h*d$+f*yl+g*Lb;return Ob(n.getTime()+_*y,r)}}let a=i.startsWith("+")||i.startsWith("-")?i:`+${i}`;return me(a,n,"event.duration")}function Db(e,t,n,r){if(t&&n)throw new p(s$,m.USAGE);if(n){let o=l$(e,n);if(o<e)throw new p(Ib,m.USAGE);return o===e?void 0:o}if(!t)return;let i=me(t,r,"event.end");if(i<e)throw new p(Ib,m.USAGE);if(i!==e)return i}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8288d6e7-a027-5bfa-9b4a-3c8b581f31ce")}catch{}})();var u$=["at","date","text","title"],m$=["start","date","end","duration","title","description","location","timezone","all_day",...Ab],p$=["key","value"];function $b(e,t){return t==="trimmed"?e?.trim():e}function _$(e,t){return t==="defined"?e!==void 0:!!e}function Ks(e,t,n){return e.map(r=>{let i=ee(r,"--reminder");ke(i,"--reminder",u$);let o=$b(i.at??i.date,n.valueMode),s=$b(i.text??i.title,n.valueMode);if(!o||!s)throw new p("--reminder requires at=<iso|relative> or date=<iso|relative>, plus text=<value> or title=<value>",m.USAGE);let a=s.trim();if(!a)throw new p("--reminder text must not be empty",m.USAGE);return{at:me(o,t,"reminder.at"),text:a}})}function Ws(e,t,n){return e.map(r=>{let i=ee(r,"--event");ke(i,"--event",m$);let o=(i.start??i.date)?.trim();if(!o)throw new p("--event requires start=<iso|relative> or date=<iso|relative>",m.USAGE);let s=me(o,t,"event.start"),a=i.end?.trim(),c=i.duration?.trim(),d=Db(s,a,c,t),l=i.title,u=i.description,_=i.location,h=i.timezone,f=l?.trim(),g=u?.trim(),y=_?.trim(),w=h?.trim(),v=[["title",l,f],["description",u,g],["location",_,y],["timezone",h,w]];for(let[A,E,C]of v)if(E!==void 0&&!C)throw new p(`--event ${A} must not be empty`,m.USAGE);let k=i.all_day?.trim(),S=xb(i,s,t,n.recurrenceEmptyNumericGuard),b=_$(k,n.allDayEmptyGuard)?Cb(k,"--event all_day"):void 0;return{start_at:s,end_at:d,title:f,description:g,location:y,all_day:b,timezone:w,recurrence:S}})}function zs(e){let t={};for(let n of e){let r=n.trim();if(r.length===0)throw new p("--type-option values must not be empty",m.USAGE);let i,o;if(r.includes(",")||r.includes(`
|
|
10
|
+
`)||r.startsWith("```")||/^(?:[-*+]\s+)?(?:key|value)\s*[:=]/i.test(r)){let s=ee(r,"--type-option");ke(s,"--type-option",p$),i=s.key?.trim(),o=s.value?.trim()}else{let s=r.indexOf("="),a=r.indexOf(":"),c=s;if(s<=0&&a>0&&(c=a),c<=0||c===r.length-1)throw new p("--type-option requires key=value or key=<name>,value=<value> entries",m.USAGE);i=r.slice(0,c).trim(),o=r.slice(c+1).trim()}if(!i||!o)throw new p("--type-option requires key and value",m.USAGE);t[i]=o}return Object.fromEntries(Object.entries(t).sort((n,r)=>n[0].localeCompare(r[0])))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b41e79c5-b53f-5793-8445-ac0e336244c3")}catch{}})();var f$=["strict","progressive"],h$=["lightweight"],Fb=new Set(["Reminder","Meeting","Event"]),g$=new Set(["author","created_at","text"]),Bs=new Map(th.map(e=>[e.optionKey,e.canonical]));function y$(e,t){let n=ce(e,t);if(!n){let r=t.definitions.map(i=>i.id);throw new p(`Invalid status value "${e}". Allowed: ${r.join(", ")}`,m.USAGE,{code:"invalid_argument_value",field:"status",value:e,allowed:r})}return n}function w$(e,t){let n=e.default_status;if(n!==void 0){let r=ce(n,t);if(r)return r}return t.open_status}function wl(e,t){if(!e||e.trim()===""||e.trim().toLowerCase()==="now")return t;let n=Date.parse(e);if(!Number.isFinite(n))throw new p(`Invalid created_at timestamp "${e}"`,m.USAGE);return new Date(n).toISOString()}var v$=bo();function jb(e){if(at(e))return e;let t={...e,unset:e.unset?[...e.unset]:void 0},n=i=>{let o=t.unset?[...t.unset]:[];o.includes(i)||o.push(i),t.unset=o};xr(t.template)&&(t.template=void 0);let r=new Set([...Bs.keys(),"rank"]);for(let i of r){if(at(e,i))continue;let o=t[i];if(typeof o!="string"||!xr(o))continue;let s=i==="rank"?"order":Bs.get(i)??i;n(s),t[i]=void 0}return dt(e,So(t,v$))}function Ge(e){if(e!==void 0)return e}var Nb=["id","kind","type","author","created_at","source_kind"],Hs=["path","scope","note"];function b$(e,t,n,r){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Oe(e,"--dep","Use --clear-deps to clear dependencies."),{values:e.map(i=>{let o=i.trim(),s=Vs(o,Nb);pi(o,s);let a=s?ee(i,"--dep"):{id:o,kind:"related"};s&&ke(a,"--dep",Nb);let c=Ge(a.id),d=k$(Ge(a.kind??a.type));if(!c||!d)throw new p("--dep requires id and kind, or a bare item id to create a related dependency",m.USAGE);if(c.trim().toLowerCase()==="undefined")throw new p(`--dep id must not use placeholder token "${c}". Use --clear-deps to clear dependencies.`,m.USAGE);let l=Dr(Ge(a.source_kind)),u=Gi(a.author,"--dep author");return{id:$r(c,n,l),kind:rr(d),created_at:wl(a.created_at,t),author:u??r,source_kind:l??"cli:create:dep",author_source:u?"asserted":"detected"}}),explicitEmpty:!1})}function k$(e){return typeof e=="string"?de().resolve(e)?.kind??e.trim():e}function Vs(e,t){return Hu(e,t)?!0:Sn(e)}function fn(e,t,n,r){return!t||t.length===0?{values:void 0,explicitEmpty:!1}:(Oe(t,e,e==="--comment"?"Use --clear-comments to clear comments.":e==="--note"?"Use --clear-notes to clear notes.":"Use --clear-learnings to clear learnings."),{values:t.map(i=>{let o=i.trim(),s=()=>{if(o.length===0)throw new p(`${e} requires text=<value>`,m.USAGE);return{created_at:n,author:r,text:o}},a;try{a=ee(i,e)}catch(d){if(e==="--comment"||e==="--note"||e==="--learning")return s();throw d}if(Object.keys(a).filter(d=>!g$.has(d)).length>0)return{created_at:wl(a.created_at,n),author:Gi(a.author,`${e} author`)??r,text:o};let c=a.text??"";if(c==="")throw new p(`${e} requires text=<value>`,m.USAGE);return{created_at:wl(a.created_at,n),author:Gi(a.author,`${e} author`)??r,text:c}}),explicitEmpty:!1})}function vl(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Oe(e,"--file","Use --clear-files to clear linked files."),{values:e.map(t=>{let n=t.trim(),r=Vs(n,Hs);mr(n,"--file","file path",r);let i=r?ee(t,"--file"):{path:n};if(r&&ke(i,"--file",Hs),!i.path)throw new p("--file requires path=<value> or a bare file path",m.USAGE);return{path:i.path,scope:tt(i.scope??"project",Ke,"file scope"),note:Ge(i.note)}}),explicitEmpty:!1})}function bl(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Oe(e,"--test","Use --clear-tests to clear linked tests."),{values:e.map(t=>{let n=t.trim(),r=Vs(n,ft);mr(n,"--test","test command",r);let i=r?qi(ee(t,"--test"),"--test"):{command:n},o=Ge(i.command),s=Ge(i.path);if(!o)throw new p("--test requires command=<value> or a bare command (path=<value> is optional metadata)",m.USAGE);let a=Ge(i.timeout_seconds),c=Ge(i.timeout);if(a&&c&&a!==c)throw new p("--test timeout and timeout_seconds must match when both are provided",m.USAGE);let d=a??c;return{command:o,path:s,scope:tt(i.scope??"project",Ke,"test scope"),timeout_seconds:d?we(d,"timeout_seconds"):void 0,pm_context_mode:Is(i.pm_context_mode,"--test"),workspace_context_mode:mn(i.workspace_context_mode,"--test"),env_set:li(i.env_set,"--test"),env_clear:ui(i.env_clear,"--test"),shared_host_safe:Rs(i.shared_host_safe,"--test","shared_host_safe"),assert_stdout_contains:pn(i.assert_stdout_contains),assert_stdout_regex:nr(i.assert_stdout_regex,"--test","assert_stdout_regex"),assert_stderr_contains:pn(i.assert_stderr_contains),assert_stderr_regex:nr(i.assert_stderr_regex,"--test","assert_stderr_regex"),assert_stdout_min_lines:Os(i.assert_stdout_min_lines,"--test"),assert_json_field_equals:Ls(i.assert_json_field_equals,"--test"),assert_json_field_gte:Ds(i.assert_json_field_gte,"--test"),note:Ge(i.note),phase:er(i.phase,"--test")}}),explicitEmpty:!1})}function kl(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Oe(e,"--doc","Use --clear-docs to clear linked docs."),{values:e.map(t=>{let n=t.trim(),r=Vs(n,Hs),i=r?ee(t,"--doc"):{path:n};if(r&&ke(i,"--doc",Hs),!i.path)throw new p("--doc requires path=<value> or a bare doc path",m.USAGE);return{path:i.path,scope:tt(i.scope??"project",Ke,"doc scope"),note:Ge(i.note)}}),explicitEmpty:!1})}function S$(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Oe(e,"--reminder","Use --clear-reminders to clear reminders."),{values:Ks(e,new Date(t),{valueMode:"raw"}),explicitEmpty:!1})}function E$(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Oe(e,"--event","Use --clear-events to clear linked events."),{values:Ws(e,new Date(t),{allDayEmptyGuard:"defined",recurrenceEmptyNumericGuard:"defined"}),explicitEmpty:!1})}function T$(e,t,n,r=[]){let i=[...Ou.filter(o=>e[o]!==void 0),...r.filter(o=>e[o]!==void 0),...t.length>0?["body"]:[],...n.map(o=>`unset:${o}`)];return Array.from(new Set(i))}function C$(e,t){let n=e??"";if(t.length===0)return n;let r=`explicit_unset=${t.join(",")}`;return n?`${n} | ${r}`:r}function Mb(e,t,n){let r=pr("create",e);if(!r)throw new p(`Unsupported ${n} entry "${e}" for type "${t}"`,m.CONFLICT);return r}function A$(e){return{scalarValues:{title:e.title,description:e.description,type:e.type,status:e.status,priority:e.priority,tags:e.tags,body:e.body,deadline:e.deadline,estimatedMinutes:e.estimatedMinutes,acceptanceCriteria:e.acceptanceCriteria,definitionOfReady:e.definitionOfReady,order:e.order??e.rank,goal:e.goal,objective:e.objective,value:e.value,impact:e.impact,outcome:e.outcome,whyNow:e.whyNow,author:e.author,message:e.message,assignee:e.assignee,parent:e.parent,reviewer:e.reviewer,risk:e.risk,confidence:e.confidence,sprint:e.sprint,release:e.release,blockedBy:e.blockedBy,blockedReason:e.blockedReason,unblockNote:e.unblockNote,reporter:e.reporter,severity:e.severity,environment:e.environment,reproSteps:e.reproSteps,resolution:e.resolution,expectedResult:e.expectedResult,actualResult:e.actualResult,affectedVersion:e.affectedVersion,fixedVersion:e.fixedVersion,component:e.component,regression:e.regression,customerImpact:e.customerImpact},repeatableValues:{dep:e.dep,comment:e.comment,note:e.note,learning:e.learning,file:e.file,test:e.test,doc:e.doc,reminder:e.reminder,event:e.event,typeOption:e.typeOption,field:e.field},addTags:e.addTags}}function Ub(e,t){if(t==="tags")return e.scalarValues.tags!==void 0||Array.isArray(e.addTags)&&e.addTags.length>0;if(Object.prototype.hasOwnProperty.call(e.scalarValues,t))return e.scalarValues[t]!==void 0;if(Object.prototype.hasOwnProperty.call(e.repeatableValues,t)){let n=e.repeatableValues[t];return Array.isArray(n)&&n.length>0}return!1}function x$(e,t){let n=new Set(["title","type"]);if(t!=="strict")return n;for(let r of e.required_create_fields)n.add(Mb(r,e.name,"required_create_fields"));for(let r of e.required_create_repeatables)n.add(Mb(r,e.name,"required_create_repeatables"));return n}function R$(e,t,n,r){for(let i of e)if(!(!Ub(t,i)&&!n.has(i)))throw new p(`Option ${xe("create",i)} is disabled for type "${r}" by command_option_policies`,m.USAGE)}function I$(e,t,n){if(t!=="strict")return;let r=e.filter(o=>n.has(o)&&!_l(o));if(r.length===0)return;let i=[...new Set(r.map(o=>xe("create",o)))].sort((o,s)=>o.localeCompare(s));throw new p(`Strict create mode requires concrete values for ${i.join(", ")}; --unset cannot satisfy a required scalar option (only repeatable options accept an explicit --clear-* empty set)`,m.USAGE)}function O$(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Oe(e,"--type-option","Use --clear-type-options to clear existing type options."),{values:zs(e),explicitEmpty:!1})}async function L$(e){return await $i(e,[["body","--body"],["description","--description"]],[["dep","--dep"],["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"],["field","--field"]])}async function D$(e){return Wt(e)?await L$(e):e}function $$(e,t){if(e===void 0)return t;let n=e.trim().toLowerCase();if(n.length===0)return t;if(n==="strict"||n==="progressive")return n;throw new p(`Invalid --create-mode value "${e}". Allowed: ${f$.join(", ")}`,m.USAGE)}function N$(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)throw new p("--schedule-preset must not be empty",m.USAGE);if(t==="lightweight"||t==="lite"||t==="schedule-lite")return"lightweight";throw new p(`Invalid --schedule-preset value "${e}". Allowed: ${h$.join(", ")}`,m.USAGE)}function M$(e,t,n){let r=$$(e,n);if(t===void 0)return r;if(typeof e=="string"&&e.trim().length>0&&r==="strict")throw new p("--schedule-preset lightweight cannot be combined with --create-mode strict. Use --create-mode progressive or omit --create-mode.",m.USAGE);return"progressive"}function P$(e,t,n,r,i,o){let s=e.name,a=A$(t),c=x$(e,n),d=Cn(e,"create",c);if(d.errors.length>0)throw new p(d.errors.join("; "),m.CONFLICT);R$(d.disabled,a,r,s),I$(d.required,n,r);let l=_=>_==="author"&&i!=="unknown"||_==="status"&&e.default_status!==void 0||o.has(_)||r.has(_)&&_l(_)?!0:Ub(a,_),u=d.required.filter(_=>!l(_));return[...new Set(u.map(_=>xe("create",_)))].sort((_,h)=>_.localeCompare(h))}var Gb=/^Missing required type option "([^"]+)" for type "([^"]+)"$/;function F$(e,t){let n=[];for(let r of e){let i=r.match(Gb);i&&i[2]===t&&n.push(i[1])}return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}function j$(e,t){return e.filter(n=>{let r=n.match(Gb);return!r||r[2]!==t})}function U$(e,t,n,r){let i=j$(e,t);if(i.length===0)return;let o=qb(n,[],[],r.open_status);throw new p(i.join("; "),m.USAGE,{code:"invalid_argument_value",required:`Provide valid --type-option key/value pairs for type "${t}".`,examples:[o],nextSteps:[`Run "pm create --help --type ${t}" to review allowed type-option keys and values.`]})}function G$(e,t){let n=e.options.find(r=>r.key===t)?.values[0];return typeof n=="string"&&n.trim().length>0?n:"<value>"}function q$(e,t,n){let r=e.split("/")[0];switch(r){case"--title":return["--title",`"${t} example title"`];case"--description":return["--description",`"${t} example description"`];case"--type":return["--type",t];case"--status":return["--status",n];case"--priority":return["--priority","1"];case"--message":return["--message",`"Create ${t} item"`];case"--comment":return["--comment",'"author=maintainer,created_at=now,text=Implementation context"'];default:return[r,'"<value>"']}}function qb(e,t,n,r){let i=["pm","create","--title",`"${e.name} example title"`,"--description",`"${e.name} example description"`,"--type",e.name],o=["--status","--priority","--message"],s=[...new Set([...o,...t])],a=new Set(["--title","--description","--type"]);for(let c of s){if(a.has(c))continue;let d=Wb[c];i.push(...d?[d]:q$(c,e.name,r)),a.add(c)}for(let c of n){let d=G$(e,c);i.push("--type-option",`${c}=${d}`)}return i.join(" ")}function Sl(e,t,n="cli"){let r=e?.trim();if(!r){let i=n==="sdk";throw t==="--title"?e!==void 0?new p(i?"Title cannot be empty or whitespace-only. Retry: pass a non-empty title.":"Title cannot be empty or whitespace-only. Retry: pass a non-empty title with --title.",m.USAGE):new p(i?'Missing required option title. Why required: every item needs a human-readable title for lookup, search, and reporting. Retry: pass title (example: client.create({ type: "Issue", title: "Fix login bug" })).':'Missing required option --title. Why required: every item needs a human-readable title for lookup, search, and reporting. Retry: pass the title as the first positional argument (example: pm create "Fix login bug" --type Issue) or with --title.',m.USAGE):new p(`Missing required option ${i?kn("sdk",t.replace(/^--/u,"")):t}`,m.USAGE)}return r}function K$(e,t,n){let r={};for(let[i,o]of Object.entries(e))r[i]=Array.isArray(o)?[...o]:o;for(let[i,o]of Object.entries(t))o!==void 0&&(r[i]=Array.isArray(o)?[...o]:o);return W$(r,t,n),dt(t,r)}function W$(e,t,n){let r=[...gc(t.unset,n).optionKeys,...yb(t.defer,n?.definitions)].flatMap(i=>i==="order"?[i,"rank"]:i==="tags"?[i,"addTags"]:[i]);for(let i of r)Reflect.get(t,i)===void 0&&Reflect.deleteProperty(e,i)}function z$(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function B$(){let e=N();return e?e.commands.some(t=>t.action==="templates-show"||z$(t.command)==="templates show"):!1}function H$(e,t){if(typeof e!="object"||e===null||!("options"in e))throw new p(`Templates package returned invalid payload for template "${t}". Expected an options object.`,m.GENERIC_FAILURE);let n=e.options;if(typeof n!="object"||n===null||Array.isArray(n))throw new p(`Templates package returned invalid options for template "${t}".`,m.GENERIC_FAILURE);let r={};for(let[i,o]of Object.entries(n)){if(typeof o=="string"||typeof o=="number"||typeof o=="boolean"){r[i]=o;continue}if(Array.isArray(o)&&o.every(s=>typeof s=="string")){r[i]=[...o];continue}throw new p(`Templates package returned unsupported option value for "${i}" in template "${t}".`,m.GENERIC_FAILURE)}return r}async function V$(e,t,n){if(!B$())throw new p("--template requires the templates package. Install it first (for example: pm install templates --project).",m.USAGE);let r=await gp({command:"templates show",args:[e],options:{},global:t,pm_root:n});if(!r.handled)throw Object.hasOwn(r,"cause")?zp("templates show",r):new p(`Unable to resolve template "${e}" via templates package. Run "pm templates show ${e}" for details.`,m.USAGE);return H$(r.result,e)}function Y(e,t,n){return e.has(t)||n===void 0?void 0:Ge(n)}function _n(e,t,n,r){return e.has(t)||n===void 0?void 0:r(n)}var Y$=new Set(["milestone","meeting","reminder","event"]);function Kb(e,t,n,r){let i=t!==void 0,o=n!==void 0&&n.length>0,s=r!==void 0&&r.length>0;return Y$.has(e.toLowerCase())&&!i&&!o&&!s}function J$(e,t,n,r,i){let o=[];return e.toLowerCase()==="event"&&(i===void 0||i.length===0)&&o.push(`event_without_schedule:${t}:no_time_set`),Kb(e,n,r,i)&&o.push(`calendar_item_without_schedule:${t}:no_deadline_or_reminder_or_event (hint: set --deadline <ISO> or --reminder "<when>", or link an Event via --event "start=<ISO>,end=<ISO>"; otherwise this item never appears on pm calendar)`),o}async function X$(e,t,n,r){if(t.inheritFocus!==!0||e!==void 0||n.has("parent")||t.parent!==void 0)return{parent:e,parentSource:void 0};let i=await Wm(r);return i===void 0?{parent:e,parentSource:void 0}:{parent:i,parentSource:"focus"}}async function Q$(e,t,n,r,i,o,s){let a=Ln(ao(i,s),t.id_prefix);if(go(a))return{parent:a,warnings:[]};if(lo(r,a,t.id_prefix,s),await V(e,a,t.id_prefix,t.item_format,n.type_to_folder))return{parent:a,warnings:[]};let c=Xe(a,t.id_prefix);return{parent:a,warnings:co(c,o,s).warnings}}async function Z$(e){return e.parent===void 0?{parent:void 0,warnings:[]}:await Q$(e.pmRoot,e.settings,e.typeRegistry,e.itemId,e.parent,e.policy,e.audience)}async function eN(e){if(e.explicitId===void 0)return wp(e.pmRoot,e.settings.id_prefix,{tokenLength:e.settings.ids.token_length,typeToFolder:e.typeRegistry.type_to_folder,probeExisting:!1});Ir(e.explicitId,"create","id");let t=e.explicitId.trim();if(t.length===0||vp(t))throw new p("--id must not be empty or use a placeholder token",m.USAGE);let n=Xe(t,e.settings.id_prefix);if(!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(n))throw new p("--id must contain only letters, numbers, and dashes after normalization",m.USAGE);return n}function Pb(e,t,n,r,i,o){let s=Y(e,t,n);if(s===void 0)return{value:void 0,warnings:[]};let a=mo(r,s,i,o);return{value:a.value,warnings:a.warnings}}async function tN(e){let{pmRoot:t,settings:n,typeRegistry:r,statusRegistry:i,blockedBy:o,status:s,statusExplicit:a,nowValue:c,author:d}=e,l=e.dependencyValues;if(o===void 0)return{dependencyValues:l,status:s};let u=Xe(o,n.id_prefix),_=await V(t,u,n.id_prefix,n.item_format,r.type_to_folder);if(!_)return{dependencyValues:l,status:s};if((l??[]).some(f=>f.id===_.id&&f.kind==="blocked_by")||(l=[...l??[],{id:_.id,kind:"blocked_by",created_at:c,author:d,source_kind:"cli:create:blocked_by",author_source:"detected"}]),a)return{dependencyValues:l,status:s};let h=i.blocked_statuses.has("blocked")?"blocked":[...i.blocked_statuses].sort((f,g)=>f.localeCompare(g))[0]??i.open_status;return{dependencyValues:l,status:h}}function nN(e,t,n){if(typeof e.createMode=="string"&&e.createMode.trim().toLowerCase()==="strict")return;let r=t.governance.create_default_type?.trim();if(r&&r.length>0&&_t(r,n)){e.type=r;return}_t("Task",n)&&(e.type="Task")}function rN(e,t){return e.options.filter(n=>pr("create",n.key)===void 0).flatMap(n=>{let r=t[n.key];if(r===void 0)return[];if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")return[n];throw new p(`Template custom type option "${n.key}" must be a string, number, or boolean value`,m.USAGE)})}async function iN(e,t,n,r,i){let o=e,s=[];if(o.template!==void 0){let f=o.template.trim();if(f.length===0)throw new p("--template must not be empty. Omit --template to disable template usage.",m.USAGE);let g=await V$(f,t,n);o=jb(Or("create",K$(g,o,Vt(r.schema))))}if(o.type===void 0&&nN(o,r,i),o.type===void 0)throw new p("Missing required option --type <value>",m.USAGE);let a=_t(o.type,i);if(!a){let f=bp(o.type),g=f?_t(f,i):void 0;if(g)s.push(`type_coercion:${o.type.trim()}:${g}`),o.type=g,a=g;else throw new p(po(o.type,i.types,Hi(n,r.schema)),m.USAGE)}let c=Fi(a,i);if(!c)throw new p(`Invalid type value "${o.type}"`,m.USAGE);let d=c.name,l=rN(c,o),u=l.map(f=>`${f.key}=${String(o[f.key])}`);if(u.length>0){o.typeOption=[...u,...o.typeOption??[]];for(let f of l)delete o[f.key]}let _=N$(o.schedulePreset);if(_!==void 0&&!Fb.has(d))throw new p(`--schedule-preset ${_} is only supported for Reminder, Meeting, or Event types`,m.USAGE);let h=M$(o.createMode,_,r.governance.create_mode_default);return{resolvedOptions:o,typeDefinition:c,type:d,schedulePreset:_,createMode:h,warnings:s}}function oN(e,t){let n=new Set(t.metadataKeys),r=new Set(t.optionKeys),i=[{enabled:e.clearDeps,optionKey:"dep",clearFlag:"--clear-deps",valueFlag:"--dep",values:e.dep,metadataKey:"dependencies"},{enabled:e.clearComments,optionKey:"comment",clearFlag:"--clear-comments",valueFlag:"--comment",values:e.comment,metadataKey:"comments"},{enabled:e.clearNotes,optionKey:"note",clearFlag:"--clear-notes",valueFlag:"--note",values:e.note,metadataKey:"notes"},{enabled:e.clearLearnings,optionKey:"learning",clearFlag:"--clear-learnings",valueFlag:"--learning",values:e.learning,metadataKey:"learnings"},{enabled:e.clearFiles,optionKey:"file",clearFlag:"--clear-files",valueFlag:"--file",values:e.file,metadataKey:"files"},{enabled:e.clearTests,optionKey:"test",clearFlag:"--clear-tests",valueFlag:"--test",values:e.test,metadataKey:"tests"},{enabled:e.clearDocs,optionKey:"doc",clearFlag:"--clear-docs",valueFlag:"--doc",values:e.doc,metadataKey:"docs"},{enabled:e.clearReminders,optionKey:"reminder",clearFlag:"--clear-reminders",valueFlag:"--reminder",values:e.reminder,metadataKey:"reminders"},{enabled:e.clearEvents,optionKey:"event",clearFlag:"--clear-events",valueFlag:"--event",values:e.event,metadataKey:"events"},{enabled:e.clearTypeOptions,optionKey:"typeOption",clearFlag:"--clear-type-options",valueFlag:"--type-option",values:e.typeOption,metadataKey:"type_options"}];for(let o of i)if(o.enabled){if(o.values&&o.values.length>0)throw new p(`Cannot combine ${o.clearFlag} with ${o.valueFlag}`,m.USAGE);n.add(o.metadataKey),r.add(o.optionKey)}return{explicitUnsets:n,clearOptionKeys:r}}function sN(e,t){let n={tags:e.tags!==void 0,deadline:e.deadline!==void 0,estimatedMinutes:e.estimatedMinutes!==void 0,acceptanceCriteria:e.acceptanceCriteria!==void 0,definitionOfReady:e.definitionOfReady!==void 0,order:e.order!==void 0||e.rank!==void 0,goal:e.goal!==void 0,objective:e.objective!==void 0,value:e.value!==void 0,impact:e.impact!==void 0,outcome:e.outcome!==void 0,whyNow:e.whyNow!==void 0,author:e.author!==void 0,assignee:e.assignee!==void 0,parent:e.parent!==void 0,reviewer:e.reviewer!==void 0,risk:e.risk!==void 0,confidence:e.confidence!==void 0,sprint:e.sprint!==void 0,release:e.release!==void 0,blockedBy:e.blockedBy!==void 0,blockedReason:e.blockedReason!==void 0,unblockNote:e.unblockNote!==void 0,reporter:e.reporter!==void 0,severity:e.severity!==void 0,environment:e.environment!==void 0,reproSteps:e.reproSteps!==void 0,resolution:e.resolution!==void 0,expectedResult:e.expectedResult!==void 0,actualResult:e.actualResult!==void 0,affectedVersion:e.affectedVersion!==void 0,fixedVersion:e.fixedVersion!==void 0,component:e.component!==void 0,regression:e.regression!==void 0,customerImpact:e.customerImpact!==void 0};for(let[r,i]of Object.entries(n)){if(!i||!t.optionKeys.has(r))continue;let o=Bs.get(r)??r;throw new p(`Cannot combine --unset ${o} with ${xe("create",r)}`,m.USAGE)}}function aN(e){if(at(e))return;let t=(n,r)=>{if(at(e,r))return;let i=Bs.get(r),o=i?`Use --unset ${i} to clear this field.`:void 0;ko(n,xe("create",r),o)};t(e.tags,"tags"),t(e.deadline,"deadline"),t(e.estimatedMinutes,"estimatedMinutes"),t(e.acceptanceCriteria,"acceptanceCriteria"),t(e.definitionOfReady,"definitionOfReady"),t(e.order??e.rank,"order"),t(e.goal,"goal"),t(e.objective,"objective"),t(e.value,"value"),t(e.impact,"impact"),t(e.outcome,"outcome"),t(e.whyNow,"whyNow"),t(e.author,"author"),t(e.assignee,"assignee"),t(e.parent,"parent"),t(e.reviewer,"reviewer"),t(e.risk,"risk"),t(e.confidence,"confidence"),t(e.sprint,"sprint"),t(e.release,"release"),t(e.blockedBy,"blockedBy"),t(e.blockedReason,"blockedReason"),t(e.unblockNote,"unblockNote"),t(e.reporter,"reporter"),t(e.severity,"severity"),t(e.environment,"environment"),t(e.reproSteps,"reproSteps"),t(e.resolution,"resolution"),t(e.expectedResult,"expectedResult"),t(e.actualResult,"actualResult"),t(e.affectedVersion,"affectedVersion"),t(e.fixedVersion,"fixedVersion"),t(e.component,"component"),t(e.regression,"regression"),t(e.customerImpact,"customerImpact")}function cN(e,t,n){for(let r of Object.keys(e))if(n.metadataKeys.has(r))throw new p(`Cannot combine --unset ${r.replaceAll("_","-")} with --field ${r}=...`,m.USAGE);for(let r of Object.keys(t.values??{}))if(n.metadataKeys.has(r))throw new p(`Cannot combine --unset ${r.replaceAll("_","-")} with its value flag`,m.USAGE)}var Wb={"--comment":"--clear-comments","--dep":"--clear-deps","--doc":"--clear-docs","--event":"--clear-events","--file":"--clear-files","--learning":"--clear-learnings","--note":"--clear-notes","--reminder":"--clear-reminders","--test":"--clear-tests","--type-option":"--clear-type-options"};function dN(e){let{combinedMissingFlags:t,typeDefinition:n,missingRequiredCreateFlags:r,missingRequiredTypeOptionKeys:i,openStatus:o,type:s,createMode:a,missingRequiredRuntimeFields:c}=e;if(t.length===0)return;let d=c.map(f=>{let g=f.type==="boolean"?"<true|false>":f.type==="array"?"<json-array>":f.type==="object"?"<json-object>":f.type==="number"?"<number>":f.type==="string_array"||f.repeatable?"<value>":"<string>";return{example:`--${f.cli_flag} ${g}`,description:`--${f.cli_flag} maps to ${f.metadata_key} (${f.type}${f.repeatable?", repeatable":""})`}}),l=[qb(n,r,i,o),...d.map(f=>f.example)].join(" "),u=[`Run "pm create --help --type ${s}" for type-aware required option guidance.`,...t.filter(f=>f==="--title").map(()=>'Title can also be passed as the first positional argument (example: pm create "Your title" --type '+s+").")];a==="strict"&&(u.push('For staged onboarding, retry with "--create-mode progressive".'),Fb.has(s)&&u.push('For minimal scheduling inputs, try "--schedule-preset lightweight".')),d.length>0&&u.push(`Required custom field formats: ${d.map(f=>f.description).join("; ")}.`);let _=[...new Set(t.flatMap(f=>{let g=f.split(" ",1)[0],y=Wb[g];return y?[y]:[]}))];_.length>0&&u.push(`If the truthful value is an empty collection, use ${_.join(", ")} instead of inventing metadata.`);let h=t.length===1?`Missing required option ${t[0]} for type "${s}"`:`Missing required options ${t.join(", ")} for type "${s}"`;throw new p(h,m.USAGE,{code:"missing_required_option",required:`Provide all required create options and type options for type "${s}" in one invocation.`,examples:[..._.map(f=>`pm create --type ${s} ${f} ...`),l],nextSteps:u,recovery:a==="strict"?{recovery_mode:"compact",missing_required_fields:t,suggested_flags:[..._,...t,"--create-mode progressive"]}:void 0})}function lN(e,t){if(e.has("tags")&&Array.isArray(t.addTags)&&t.addTags.length>0)throw new p("Cannot combine --unset tags with --add-tags",m.USAGE);let n=e.has("tags")?[]:t.tags!==void 0?Oi(t.tags):[];return Di(n,t.addTags)}function uN(e,t){if(t.order!==void 0&&t.rank!==void 0&&t.order!==t.rank)throw new p("--order and --rank must match when both are provided",m.USAGE);let n=t.order??t.rank,r=_n(e,"order",n,i=>we(i,"order"));if(r!==void 0&&!Number.isInteger(r))throw new p("Order must be an integer",m.USAGE);return r}function mN(e,t,n,r,i,o){if(r.completedAt!==void 0&&e!==t.close_status)throw new p("--completed-at requires a terminal create status.",m.USAGE);let s=e!==t.close_status?void 0:r.completedAt===void 0?o:me(r.completedAt,new Date(o),"completed-at");if(e!==t.close_status)return{closeReason:void 0,completedAt:s,warnings:[]};let a=n.governance.require_close_reason?{explicit:r.closeReason??r.message,resolution:i}:{explicit:r.closeReason};return{closeReason:ul(a,n.governance.require_close_reason,{operation:"create",status:e}).closeReason,completedAt:s,warnings:[]}}async function pN(e){let{pmRoot:t,type:n,id:r,settings:i,typeRegistry:o,author:s,extensionFieldNames:a,afterDocument:c,beforeDocument:d,historyMessage:l,changedFields:u,nowValue:_,similarityCandidate:h,allowDuplicate:f}=e,g=om(t,n,r,i.item_format,o.type_to_folder),y=Bt(t,r),w=de(),v=c.metadata.parent!==void 0||(c.metadata.dependencies??[]).some(A=>Ss(A.kind,w)),k=await Ns({pmRoot:t,author:s,ttlSeconds:i.locks.ttl_seconds,waitMs:i.locks.wait_ms,required:v}),S=v,b=[];try{let A=await to(t,r,i.locks.ttl_seconds,s,!1,i.governance.force_required_for_stale_lock,i.locks.wait_ms);try{let E=c.metadata.parent!==void 0||c.metadata.dependencies!==void 0&&c.metadata.dependencies.length>0?await Te(t,i.item_format,o.type_to_folder,void 0,i.schema):void 0,C=await V(t,r,i.id_prefix,i.item_format,o.type_to_folder);if(C)throw new p(`Item "${r}" already exists`,m.CONFLICT,{code:"item_already_exists",id:C.id,path:C.itemPath,required:"Read the existing item before deciding whether to update it or create a different ID.",nextSteps:[`Inspect the existing item with pm get ${C.id}.`]});if(E){Es(E,[...E,c.metadata],w);let F=W(i.schema);Ao(E,[...E,c.metadata],r,ue=>fe(ue,F),w)}let O=await Rp({pmRoot:t,settings:i,operation:"create",author:s,before:null,after:c});await _p({pm_root:t,operation:"create",before:null,after:c,changed_fields:u,author:s,sdk:Np({pmRoot:t,settings:i,typeToFolder:o.type_to_folder})});let M=await Dp(t,s,{required:i.governance.duplicate_detection_mode==="strict"&&f!==!0}),T=[];try{i.governance.duplicate_detection_mode==="strict"&&f!==!0&&await cd(h,{pmRoot:t,mode:"strict",threshold:i.governance.duplicate_detection_threshold,limit:i.governance.duplicate_detection_limit,allowDuplicate:!1}),await A.fence(async()=>{await je(g,Pm(c,{format:i.item_format,schema:i.schema,extensionFieldNames:a}));try{let F=rp({nowIso:_,author:s,op:"create",before:d,after:c,message:l,context:O.decisions.length===0?void 0:{workflow_policies:O.decisions}});await ip(y,F)}catch(F){throw await Xu(g),F}}),S&&(await k(),S=!1),T=await $p({pmRoot:t,preferredFormat:i.item_format,typeToFolder:o.type_to_folder,schema:i.schema,itemPath:g,document:c})}finally{await M()}b=[...O.warnings,...E?ks(E,[...E,c.metadata],r):[],...T,...await ht({path:g,scope:"project",op:"create",item_id:c.metadata.id,item_type:c.metadata.type,before:d,after:c,changed_fields:u}),...await ht({path:y,scope:"project",op:"create:history",item_id:c.metadata.id,item_type:c.metadata.type,before:d,after:c,changed_fields:u})],mp({id:c.metadata.id,op:"create",item_type:c.metadata.type,status:c.metadata.status,current:pp(c.metadata,u),changed_fields:u})}finally{await A.release()}}finally{S&&await k()}return b}async function F4(e,t){let n=Or("create",e),r=ct(n),i=jb(await D$(n)),o=R(process.cwd(),t.path);await j(o);let s=await x(o),a=W(s.schema),c=Vt(s.schema),d=P(s,N()),l=await iN(i,t,o,s,d);i=l.resolvedOptions;let{typeDefinition:u,type:_,createMode:h}=l,f=gc(i.unset,c),{explicitUnsets:g,clearOptionKeys:y}=oN(i,f);sN(i,f),aN(i);let w=hb(i,r);hl(w,i,f.metadataKeys,r);let v=U(Ge(i.author),s.author_default),k=P$(u,i,h,y,v,w.optionKeys),S=I(),b=b$(i.dep,S,s.id_prefix,v),A=fn("--comment",i.comment,S,v),E=fn("--note",i.note,S,v),C=fn("--learning",i.learning,S,v),O=vl(i.file),M=bl(i.test);M.values=await Xn(M.values,v,S);let T=kl(i.doc),F=S$(i.reminder,S),ue=E$(i.event,S),Ne=O$(i.typeOption),J=_r(_,Ne.values,d),Me=N(),Pe=xt(Me),qe=io(i.field,Me,Us,Gs(c,"create",i)),re=Rm(i,c,_);hl(w,i,f.metadataKeys,r,re.values),re.missing_required_flags=wb(re.missing_required_flags,w,c.definitions,_,i);let be=new Set(re.missing_required_flags),Ee=c.definitions.filter(X=>be.has(`--${X.cli_flag}`));cN(qe,re,f);let nt=F$(J.errors,_),rt=nt.map(X=>`--type-option ${X}=<value>`),it=[...new Set([...k,...rt,...re.missing_required_flags])].sort((X,Ra)=>X.localeCompare(Ra));dN({combinedMissingFlags:it,typeDefinition:u,missingRequiredCreateFlags:k,missingRequiredTypeOptionKeys:nt,openStatus:a.open_status,type:_,createMode:h,missingRequiredRuntimeFields:Ee}),U$(J.errors,_,u,a);let ye=await eN({pmRoot:o,settings:s,typeRegistry:d,explicitId:i.id}),se=i.status!==void 0?y$(i.status,a):w$(u,a),He=i.priority!==void 0?uo(i.priority):2,$=f.metadataKeys,Ve=lN($,i),Ut=_n($,"deadline",i.deadline,X=>me(X,new Date(S),"deadline")),Ae=_n($,"estimated_minutes",i.estimatedMinutes,X=>Ni(X,"estimated-minutes")),ae=Y($,"acceptance_criteria",i.acceptanceCriteria),Ci=Y($,"definition_of_ready",i.definitionOfReady),ka=uN($,i),Ai=Y($,"goal",i.goal),ES=Y($,"objective",i.objective),TS=Y($,"value",i.value),CS=Y($,"impact",i.impact),AS=Y($,"outcome",i.outcome),xS=Y($,"why_now",i.whyNow),RS=Y($,"assignee",i.assignee),IS=$.has("author")?void 0:Ge(i.author)??v,OS=Y($,"parent",i.parent),wu=await X$(OS,i,$,o),Sa=wu.parent,LS=wu.parentSource,DS=Y($,"reviewer",i.reviewer),$S=_n($,"risk",i.risk,X=>tt(Ms(X),Mi,"risk")),NS=_n($,"confidence",i.confidence,X=>Fs(X)),MS=i.allowMissingParent===!0&&s.validation.parent_reference==="strict_error"?"warn":s.validation.parent_reference,vu=s.validation.sprint_release_format,Gt=[...l.warnings,...J$(_,ye,Ut,F.values,ue.values)],bu=await Z$({itemId:ye,parent:Sa,pmRoot:o,settings:s,typeRegistry:d,policy:MS,audience:r});Sa=bu.parent,Gt.push(...bu.warnings);let ku=Pb($,"sprint",i.sprint,"sprint",vu,r),PS=ku.value;Gt.push(...ku.warnings);let Su=Pb($,"release",i.release,"release",vu,r),FS=Su.value;Gt.push(...Su.warnings);let Eu=Y($,"blocked_by",i.blockedBy),Tu=await tN({pmRoot:o,settings:s,typeRegistry:d,statusRegistry:a,blockedBy:Eu,dependencyValues:b.values,status:se,statusExplicit:i.status!==void 0,nowValue:S,author:v}),Ea=Tu.dependencyValues;_i(ye,Ea),Gt.push(...await qs({pmRoot:o,dependencies:Ea,idPrefix:s.id_prefix,itemFormat:s.item_format,typeToFolder:d.type_to_folder,allowUnresolved:i.allowUnresolvedDeps,holders:[{id:ye,createdAt:S}],schema:s.schema})),se=Tu.status;let jS=Y($,"blocked_reason",i.blockedReason),US=Y($,"unblock_note",i.unblockNote),GS=Y($,"reporter",i.reporter),qS=_n($,"severity",i.severity,X=>tt(Ps(X),Pi,"severity")),KS=Y($,"environment",i.environment),WS=Y($,"repro_steps",i.reproSteps),Cu=Y($,"resolution",i.resolution),zS=Y($,"expected_result",i.expectedResult),BS=Y($,"actual_result",i.actualResult),HS=Y($,"affected_version",i.affectedVersion),VS=Y($,"fixed_version",i.fixedVersion),YS=Y($,"component",i.component),JS=_n($,"regression",i.regression,X=>js(X)),XS=Y($,"customer_impact",i.customerImpact),Ta=Sl(i.title,"--title",r),Ca=i.description??"",xi=i.body??"",Au=await cd({title:Ta,description:Ca,body:xi},{pmRoot:o,mode:s.governance.duplicate_detection_mode,threshold:s.governance.duplicate_detection_threshold,limit:s.governance.duplicate_detection_limit,allowDuplicate:i.allowDuplicate});Gt.push(...Sy(Au));let Aa=mN(se,a,s,i,Cu,S),QS=Aa.closeReason,ZS=se===a.close_status?S:void 0,eE=Aa.completedAt;Gt.push(...Aa.warnings);let bn=Mm({id:ye,title:Ta,description:Ca,type:_,type_options:J.normalized,status:se,closed_at:ZS,completed_at:eE,close_reason:QS,priority:He,tags:Ve,created_at:S,updated_at:S,deadline:Ut,assignee:RS,author:IS,estimated_minutes:Ae,acceptance_criteria:ae,deferred_fields:gb(w),definition_of_ready:Ci,order:ka,goal:Ai,objective:ES,value:TS,impact:CS,outcome:AS,why_now:xS,parent:Sa,reviewer:DS,risk:$S,confidence:NS,sprint:PS,release:FS,blocked_by:Eu,blocked_reason:jS,unblock_note:US,reporter:GS,severity:qS,environment:KS,repro_steps:WS,resolution:Cu,expected_result:zS,actual_result:BS,affected_version:HS,fixed_version:VS,component:YS,regression:JS,customer_impact:XS,dependencies:Ea,comments:A.values,notes:E.values,learnings:C.values,files:O.values,tests:M.values,docs:T.values,reminders:F.values,events:ue.values,...qe,...re.values});gm(bn);try{oo(bn,Me)}catch(X){throw new p(X instanceof Error?X.message:"Invalid extension item field values",m.USAGE)}Ip(bn,o);let tE=Fm({metadata:bn,body:xi},{schema:s.schema,extensionFieldNames:Pe}),nE={metadata:{},body:""},xu=[...g].sort((X,Ra)=>X.localeCompare(Ra)),rE=C$(i.message,xu),Ru=T$(bn,xi,xu,[...Object.keys(qe),...Object.keys(re.values??{})]),iE=await pN({pmRoot:o,type:_,id:ye,settings:s,typeRegistry:d,author:v,extensionFieldNames:Pe,afterDocument:tE,beforeDocument:nE,historyMessage:rE,changedFields:Ru,nowValue:S,similarityCandidate:{title:Ta,description:Ca,body:xi},allowDuplicate:i.allowDuplicate}),xa=structuredClone(bn);h==="strict"&&g.has("dependencies")&&(xa.dependencies=[]);let oE=Eb(ye,_,se,a);return Kb(_,Ut,F.values,ue.values)&&np(`[pm] warning: ${_} '${ye}' has no deadline/reminder/event \u2014 it will not appear on the calendar. Add one via 'pm update ${ye} --deadline <ISO>' or 'pm update ${ye} --event "start=<ISO>,end=<ISO>"'.`),{item:xa,changed_fields:Ru,warnings:[...Rr("create",i,r==="sdk",xa),...Gt,...iE],...Object.fromEntries([["parent_source",LS],["next_transition",oE],["similarity_advisory",Au]].filter(X=>X[1]!==void 0))}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f4c54507-c8b1-5f19-b58a-61186c79c8b0")}catch{}})();function hn(e){return e.in_progress_status!==e.open_status&&e.by_id.has(e.in_progress_status)?e.in_progress_status:Je("in_progress",e)??e.open_status}import{AsyncLocalStorage as _N}from"node:async_hooks";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2d3aa974-e49d-50fc-9c29-01c0e694b4c4")}catch{}})();var fN="strict",Js="start_blocked_by_open_dependency";function zb(e,t,n){if(t===void 0)return!1;let r=Yt(hn(n),n);return Yt(t,n)===r&&Yt(e??"",n)!==r}function Ys(e,t,n){let r=i=>Xe(i.trim(),n).toLowerCase();return r(e)===r(t)}var hN=new Set(["cli:create:blocked_by","cli:update:blocked_by"]);function El(e,t,n){if(e.kind!=="blocked_by"||typeof t!="string"||t.trim().length===0)return!1;let r=e.id.trim().toLowerCase();return r===t.trim().toLowerCase()?!0:r===Xe(t.trim(),n).toLowerCase()&&hN.has(e.source_kind?.trim().toLowerCase()??"")}function gN(e,t,n){let r=e.dependencies??[],i=r.filter(o=>o.kind==="blocked_by");if(r.some(o=>o.kind!=="blocked_by"&&kr(o.kind)==="blocked_by"&&Ys(o.id,t,n)))return L(["get",e.id,"--fields","blocked_by,dependencies"]);if(!(typeof e.blocked_by=="string"&&Ys(e.blocked_by,t,n))){let o=i.filter(s=>Ys(s.id,t,n));return o.length===1&&o.every(s=>s.id===Ln(s.id,n,void 0))?L(["update",e.id,"--dep-remove",`id=${o[0].id},kind=blocked_by`]):L(["get",e.id,"--fields","blocked_by,dependencies"])}return i.filter(o=>Ys(o.id,t,n)).every(o=>El(o,e.blocked_by,n))?L(["update",e.id,"--unset","blocked_by"]):L(["get",e.id,"--fields","blocked_by,dependencies"])}var yN=new Set(["item_document_invalid","item_document_encoding_invalid","item_format_version_unsupported","item_identity_ambiguous","item_identity_conflict"]);async function wN(e,t){try{return(await Zp(e)).filter(n=>!n.resolved)}catch(n){let r=Wp(n)?n.context.code:void 0;if(!t||typeof r!="string"||!yN.has(r))throw n;return r}}async function Bb(e){let t=e.settings.governance.start_blocker_enforcement??fN;if(t==="off")return[];let n=P(e.settings,N()).type_to_folder,r=e.metadata.id,i=await wN({pmRoot:e.pmRoot,settings:e.settings,typeToFolder:n,metadata:e.metadata},t==="warn"||e.force===!0);if(typeof i=="string")return[`start_blocker_unverifiable:${r}:${i}`];if(i.length===0)return[];let o=i.map(s=>s.id).join(",");if(t==="warn")return[`start_with_open_blockers:${r}:${o}`];if(e.force===!0)return[`start_blocker_override:${r}:${o}`];throw new p(`Cannot start ${r}: ${i.length===1?"its blocker":`${i.length} of its blockers`} ${o} ${i.length===1?"is":"are"} still open.`,m.CONFLICT,{code:"start_blocked_by_open_dependency",item_id:r,required:`Finish or close the open blocker${i.length===1?"":"s"} first, remove the blocked_by edge if it no longer applies, or start anyway with --force.`,why:"Starting work that a declared blocker still gates would leave an in-progress item that validate reports as non_blocked_status_has_blocked_by. governance.start_blocker_enforcement (strict by default) governs this check.",nextSteps:[...i.filter(s=>s.external!==!0).slice(0,3).map(s=>L(["get",s.id])),gN(e.metadata,i[0].id,e.settings.id_prefix),"pm next"],details:{enforcement:t,open_blockers:i.map(s=>({id:s.id,title:s.title,status:s.status,external:s.external===!0}))}})}async function Xs(e){if(e.requested===!1||!zb(e.fromStatus,e.metadata.status,e.registry))return[];let t=await Bb(e),n=Tl.getStore()?.warnings??new Set;return t.filter(r=>!n.has(r))}var Tl=new _N;function Hb(e){return Tl.run({warnings:new Set},e)}async function Vb(e){let t=Tl.getStore();if(t===void 0)return[];let n=zb(e.metadata.status,hn(e.registry),e.registry)?await Bb(e):[];for(let r of n)t.warnings.add(r);return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d510588a-e45d-54ba-b9c0-153940bb6677")}catch{}})();var Yb="terminal_state_unchanged";function Jb(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function vN(e,t){return ce(e,t)===t.close_status}function bN(e){let t=n=>eh.includes(n.trim().toLowerCase());return nh(e.unset??[],t).some(t)}function Xb(e){!e.settings.governance.require_close_reason||!bN(e.options)||vs({explicit:e.options.closeReason},!0)}function Cl(e,t,n,r=!1){if(!vN(e.status,n))return!1;let i=Jb(t.closeReason);return r&&t.closeReason!==void 0&&i===void 0||i!==void 0&&i!==Jb(e.close_reason)?!1:t.completedAt===void 0||me(t.completedAt,new Date,"completed-at")===e.completed_at}async function Qb(e){let t=await V(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await Qt(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await pe(t,{schema:e.settings.schema});return n.metadata}async function Zb(e,t,n,r,i){if(n.length===0)return{item:t,changed_fields:[],warnings:[...e.workflowTransitionWarnings,Yb]};let o=dt(e.options,{...e.options,status:void 0,closeReason:void 0,completedAt:void 0}),s=await r(e.id,o,e.global);return Cl(s.item,e.options,e.statusRegistry,e.settings.governance.require_close_reason)?{item:s.item,changed_fields:s.changed_fields,warnings:[...e.workflowTransitionWarnings,...s.warnings,Yb]}:i(s)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4790c318-c305-53d4-895c-e9ac90665376")}catch{}})();function ir(e){if(e.enforcement==="off"||e.typeWorkflows.length===0)return;let t=kp({typeName:e.typeName,fromStatus:e.fromStatus,toStatus:e.toStatus,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry});if(!t.hasRule||t.allowed)return;let n=Je(e.fromStatus,e.statusRegistry)??e.fromStatus,r=Je(e.toStatus,e.statusRegistry)??e.toStatus,i=`Disallowed transition for type "${e.typeName}": ${n} -> ${r}. Allowed transitions: ${Sp(t.allowedTransitions)}.`;if(e.enforcement==="strict")throw new p(i,m.USAGE);return`workflow_transition_not_allowed: ${i}`}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f5a434fe-8703-515c-b823-c8cd3589bbb0")}catch{}})();function Qs(e){let t=e.source_kind?.trim().toLowerCase()??"",n=e.author?.trim().toLowerCase()??"",r=e.created_at?.trim()??"",i=Date.parse(r),o=Number.isFinite(i)?new Date(i).toISOString():r;return[e.id.trim().toLowerCase(),e.kind,t,n,o].join("\0")}function Al(e,t){return!(t.id!==void 0&&e.id.trim().toLowerCase()!==t.id.trim().toLowerCase()||t.kind&&e.kind!==t.kind||t.source_kind!==void 0&&e.source_kind?.trim().toLowerCase()!==t.source_kind.trim().toLowerCase()||t.author!==void 0&&e.author?.trim().toLowerCase()!==t.author.trim().toLowerCase()||t.created_at!==void 0&&(e.created_at===void 0||!Number.isFinite(Date.parse(e.created_at))||new Date(Date.parse(e.created_at)).toISOString()!==t.created_at))}function ek(e,t,n){let r=t.filter(i=>!e.some(o=>Al(o,i)));if(r.length!==0)throw new p(`Dependency removal did not match ${r.length===1?"a stored edge":"stored edges"}.`,m.NOT_FOUND,{code:"dependency_remove_no_match",reason:"selector_not_found",unmatched_selectors:r.map(i=>({...i,id:i.id??"*"})),available_dependencies:e.map(i=>({id:i.id,kind:i.kind,source_kind:i.source_kind,author:i.author,created_at:i.created_at})),why:"Failing on a zero-match selector prevents a mistyped dependency removal from being reported as successful.",nextSteps:[`Inspect the current item with: pm get ${n} --full`,"Retry --dep-remove with the exact id plus any kind, source_kind, author, or created_at selectors needed to identify one stored row."]})}function tk(e,t){if(!Array.isArray(e)||e.length===0)return;let n=o=>(Array.isArray(o)?o:[]).filter(s=>typeof s=="object"&&s!==null&&typeof s.id=="string"),r=new Map;for(let o of n(t)){let s=Qs(o);r.set(s,(r.get(s)??0)+1)}let i=[];for(let o of n(e)){let s=Qs(o),a=r.get(s)??0;a>0?r.set(s,a-1):i.push(`${o.id}/${o.kind}`)}return i.length>0?i.join(","):void 0}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fc1c1ca1-43e9-5019-bb3b-85b8972f090b")}catch{}})();var kN=(()=>{let e=new Map;for(let t of Eo)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),Zs=new Map(Eo.map(e=>[e.optionKey,e.canonical])),SN=Eo.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", "),EN=new Set(["close_reason","assignee","parent","blocked_by","blocked_reason","unblock_note","dependencies","comments","notes","learnings","files","tests","docs","reminders","events"]),TN=bo({depDisableFlagKey:"replaceDeps",fileDisableFlagKey:"replaceFiles",testDisableFlagKey:"replaceTests",docDisableFlagKey:"replaceDocs"});function lk(e){if(at(e))return e;let t={...e,unset:e.unset?[...e.unset]:void 0},n=i=>{let o=t.unset?[...t.unset]:[];o.includes(i)||o.push(i),t.unset=o},r=new Set([...Zs.keys(),"rank"]);for(let i of r){if(at(e,i))continue;let o=t[i];if(typeof o!="string"||!xr(o))continue;let s=i==="rank"?"order":Zs.get(i)??i;n(s),t[i]=void 0}return dt(e,So(t,TN))}function q3(e,t,n,r=["update"]){return[...Ol([...e],t,n,r).metadataKeys]}function Ol(e,t,n=[],r=["update"]){return rh({raw:e,supportedFields:SN,resolveDefinition:i=>{let o=n.find(s=>{let a=s.toLowerCase();return a===i||a.replaceAll("_","-")===i||a.replaceAll("-","_")===i});return kN.get(i)??r.map(s=>hc(i,s,t)).find(s=>s!==void 0)??(o?{optionKey:"field",metadataKey:o}:void 0)}})}var nk=new Map([["--comment",e=>`pm comments ${e} --add "<text>" --force`],["--file",e=>`pm files ${e} --add "path=<path>,scope=<scope>,note=<note>" --force`],["--doc",e=>`pm docs ${e} --add "path=<path>,scope=<scope>,note=<note>" --force`]]);function rk(e){let t=e.disallowedFlags.flatMap(r=>{let i=nk.get(r);return i?[i(e.id)]:[]}),n=e.disallowedFlags.flatMap(r=>{let i=nk.get(r);return i?[`Replace ${r} with: ${i(e.id)}`]:[]});return new p(e.message,m.USAGE,{code:e.code,required:e.required,why:e.why,...t.length>0?{examples:t}:{},nextSteps:[`Re-run without: ${e.disallowedFlags.join(", ")}`,...n]})}function CN(e,t,n){let r=t.ownershipMetadataBypass===!0,i=t.ownershipDependencyBypass===!0;if(!r&&!i)return;if(r&&i)throw new p("Choose only one package-provided ownership bypass mode.",m.USAGE);let o=(c,d,l)=>{c&&l.push(d)};if(i){let c=[];if(o(t.title!==void 0,"--title",c),o(t.description!==void 0,"--description",c),o(t.body!==void 0,"--body",c),o(t.status!==void 0,"--status",c),o(t.closeReason!==void 0,"--close-reason",c),o(t.priority!==void 0,"--priority",c),o(t.type!==void 0,"--type",c),o(t.tags!==void 0,"--tags",c),o(Array.isArray(t.addTags)&&t.addTags.length>0,"--add-tags",c),o(Array.isArray(t.removeTags)&&t.removeTags.length>0,"--remove-tags",c),o(t.deadline!==void 0,"--deadline",c),o(t.estimatedMinutes!==void 0,"--estimate",c),o(t.acceptanceCriteria!==void 0,"--acceptance-criteria",c),o(Array.isArray(t.addAc)&&t.addAc.length>0,"--add-ac",c),o(Array.isArray(t.removeAc)&&t.removeAc.length>0,"--remove-ac",c),o(t.definitionOfReady!==void 0,"--definition-of-ready",c),o(t.order!==void 0||t.rank!==void 0,"--order/--rank",c),o(t.goal!==void 0,"--goal",c),o(t.objective!==void 0,"--objective",c),o(t.value!==void 0,"--value",c),o(t.impact!==void 0,"--impact",c),o(t.outcome!==void 0,"--outcome",c),o(t.whyNow!==void 0,"--why-now",c),o(t.assignee!==void 0,"--assignee",c),o(t.parent!==void 0,"--parent",c),o(t.reviewer!==void 0,"--reviewer",c),o(t.risk!==void 0,"--risk",c),o(t.confidence!==void 0,"--confidence",c),o(t.sprint!==void 0,"--sprint",c),o(t.release!==void 0,"--release",c),o(t.blockedBy!==void 0,"--blocked-by",c),o(t.blockedReason!==void 0,"--blocked-reason",c),o(t.unblockNote!==void 0,"--unblock-note",c),o(t.reporter!==void 0,"--reporter",c),o(t.severity!==void 0,"--severity",c),o(t.environment!==void 0,"--environment",c),o(t.reproSteps!==void 0,"--repro-steps",c),o(t.resolution!==void 0,"--resolution",c),o(t.expectedResult!==void 0,"--expected-result",c),o(t.actualResult!==void 0,"--actual-result",c),o(t.affectedVersion!==void 0,"--affected-version",c),o(t.fixedVersion!==void 0,"--fixed-version",c),o(t.component!==void 0,"--component",c),o(t.regression!==void 0,"--regression",c),o(t.customerImpact!==void 0,"--customer-impact",c),o(t.depRemove!==void 0,"--dep-remove",c),o(t.replaceDeps===!0,"--replace-deps",c),o(t.replaceTests===!0,"--replace-tests",c),o(t.replaceFiles===!0,"--replace-files",c),o(t.replaceDocs===!0,"--replace-docs",c),o(t.comment!==void 0,"--comment",c),o(t.note!==void 0,"--note",c),o(t.learning!==void 0,"--learning",c),o(t.file!==void 0,"--file",c),o(t.test!==void 0,"--test",c),o(t.doc!==void 0,"--doc",c),o(t.reminder!==void 0,"--reminder",c),o(t.event!==void 0,"--event",c),o(t.typeOption!==void 0,"--type-option",c),o(t.clearDeps===!0,"--clear-deps",c),o(t.clearComments===!0,"--clear-comments",c),o(t.clearNotes===!0,"--clear-notes",c),o(t.clearLearnings===!0,"--clear-learnings",c),o(t.clearFiles===!0,"--clear-files",c),o(t.clearTests===!0,"--clear-tests",c),o(t.clearDocs===!0,"--clear-docs",c),o(t.clearReminders===!0,"--clear-reminders",c),o(t.clearEvents===!0,"--clear-events",c),o(t.clearTypeOptions===!0,"--clear-type-options",c),o(t.force===!0,"--force",c),o(n.size>0,"--unset",c),t.dep===void 0||t.dep.length===0)throw new p("The dependency ownership bypass requires at least one --dep value",m.USAGE);if(c.length>0)throw rk({id:e,code:"ownership_dependency_bypass_restricted_options",message:`The dependency ownership bypass supports append-only dependency additions via --dep. Remove restricted options: ${c.join(", ")}`,required:"Pass only --dep additions (plus --message/--author) with the dependency ownership bypass.",why:"the dependency ownership bypass is a narrow non-owner override scoped to append-only dependency additions; every other mutation keeps its normal ownership rules.",disallowedFlags:c});return}let s=[];o(t.status!==void 0,"--status",s),o(t.closeReason!==void 0,"--close-reason",s),o(t.assignee!==void 0,"--assignee",s),o(t.parent!==void 0,"--parent",s),o(t.blockedBy!==void 0,"--blocked-by",s),o(t.blockedReason!==void 0,"--blocked-reason",s),o(t.unblockNote!==void 0,"--unblock-note",s),o(t.dep!==void 0,"--dep",s),o(t.depRemove!==void 0,"--dep-remove",s),o(t.replaceDeps===!0,"--replace-deps",s),o(t.replaceTests===!0,"--replace-tests",s),o(t.replaceFiles===!0,"--replace-files",s),o(t.replaceDocs===!0,"--replace-docs",s),o(t.note!==void 0,"--note",s),o(t.learning!==void 0,"--learning",s),o(t.test!==void 0,"--test",s),o(t.reminder!==void 0,"--reminder",s),o(t.event!==void 0,"--event",s),o(t.clearDeps===!0,"--clear-deps",s),o(t.clearComments===!0,"--clear-comments",s),o(t.clearNotes===!0,"--clear-notes",s),o(t.clearLearnings===!0,"--clear-learnings",s),o(t.clearFiles===!0,"--clear-files",s),o(t.clearTests===!0,"--clear-tests",s),o(t.clearDocs===!0,"--clear-docs",s),o(t.clearReminders===!0,"--clear-reminders",s),o(t.clearEvents===!0,"--clear-events",s);let a=[...n].filter(c=>EN.has(c)).sort((c,d)=>c.localeCompare(d)).map(c=>`--unset ${c.replaceAll("_","-")}`);if(s.push(...a),s.length>0)throw rk({id:e,code:"ownership_metadata_bypass_restricted_options",message:`The metadata ownership bypass only supports non-lifecycle metadata fields and evidence appends. Remove restricted options: ${s.join(", ")}`,required:"Limit the metadata ownership bypass to non-lifecycle metadata fields plus append-only --comment/--file/--doc evidence; route restricted appends and lifecycle changes through their dedicated commands.",why:"the metadata ownership bypass is a non-owner override scoped to metadata maintenance and append-only evidence; lifecycle, ownership, dependency mutations, restricted append fields, and clear/replace operations keep their normal ownership rules.",disallowedFlags:s})}function AN(e,t){let n=ce(e,t);if(!n){let r=t.definitions.map(i=>i.id);throw new p(`Invalid status value "${e}". Allowed: ${r.join(", ")}`,m.USAGE,{code:"invalid_argument_value",field:"status",value:e,allowed:r})}return n}function xN(e,t){return!e||e.trim()===""||e.trim().toLowerCase()==="now"?t:uk(e)}function uk(e){let t=Date.parse(e);if(!Number.isFinite(t))throw new p(`Invalid dependency created_at timestamp "${e}"`,m.USAGE);return new Date(t).toISOString()}function gn(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}var RN=["id","kind","type","author","created_at","source_kind"],IN=["id","kind","type","author","created_at","source_kind"];function mk(e){return e.startsWith("```")||e.includes(`
|
|
11
|
+
`)||/^(?:[-*+]\s+)?(?:id|kind|type|author|created_at|source_kind)\s*[:=]/i.test(e)?!0:Sn(e)}function Ll(e){return typeof e=="string"?de().resolve(e)?.kind??e.trim():e}function ON(e,t,n,r){return e?(Oe(e,"--dep","Use --clear-deps to clear dependencies."),{additions:e.map(i=>{let o=i.trim(),s=mk(o);pi(o,s);let a=s?ee(i,"--dep"):{id:o,kind:"related"};s&&ke(a,"--dep",RN);let c=a.id?.trim(),d=Ll((a.kind??a.type)?.trim());if(!c||!d)throw new p("--dep requires id and kind, or a bare item id to add a related dependency",m.USAGE);if(c.toLowerCase()==="undefined")throw new p(`--dep id must not use placeholder token "${c}". Use --clear-deps to clear dependencies.`,m.USAGE);let l=Dr(gn(a.source_kind)),u=gn(a.author);return{id:$r(c,t,l),kind:rr(d),created_at:xN(a.created_at,n),author:u??r,source_kind:l??"cli:update:dep",author_source:u?"asserted":"detected"}})}):{additions:[]}}function LN(e,t){return e?(Oe(e,"--dep-remove"),e.map(n=>{let r=n.trim();if(!r)throw new p("--dep-remove requires id or key/value selectors",m.USAGE);let i=mk(r);if(pi(r,i,"--dep-remove"),i){let o=ee(r,"--dep-remove");ke(o,"--dep-remove",IN);let s=o.id?.trim();if(o.id===void 0)return DN(o);if(!s)throw new p("--dep-remove key/value form requires a non-empty id=<value>",m.USAGE);if(s.toLowerCase()==="undefined")throw new p(`--dep-remove id must not use placeholder token "${s}"`,m.USAGE);let a=Ll(gn(o.kind??o.type)),c=Dr(gn(o.source_kind)),d=gn(o.author),l=gn(o.created_at);return{id:$r(s,t,c),kind:a?rr(a):void 0,source_kind:c,author:d,created_at:l?uk(l):void 0}}if(r.toLowerCase()==="undefined")throw new p(`--dep-remove id must not use placeholder token "${r}"`,m.USAGE);return{id:Xe(r,t)}})):[]}function DN(e){let t=Ll(gn(e.kind??e.type)),n=Object.keys(e).filter(r=>r!=="kind"&&r!=="type");if(!t||n.length>0||e.kind!==void 0&&e.type!==void 0)throw new p("--dep-remove key/value form requires id=<value>, or kind=<kind> alone to remove every row of that kind",m.USAGE);return{kind:rr(t)}}function ea(e){let t=e.source_kind?.trim().toLowerCase()??"";return[e.id.trim().toLowerCase(),e.kind,t].join("\0")}function $N(e,t,n,r,i){let o=[...e??[]],s=!1;if(t===void 0){let a=o.filter(c=>i===void 0||!El(c,i.value,i.idPrefix));return a.length!==o.length&&(o=a,s=!0),s?{dependencies:o.length>0?o:void 0,changed:!0}:{dependencies:e,changed:!1}}return o.some(a=>a.kind==="blocked_by"&&a.id===t)||(o.push({id:t,kind:"blocked_by",created_at:n,author:r,source_kind:"cli:update:blocked_by",author_source:"detected"}),s=!0),s?{dependencies:o.length>0?o:void 0,changed:!0}:{dependencies:e,changed:!1}}async function NN(e,t,n,r,i,o){if(e===void 0||t)return{};let s=e.trim();if(s.length===0)return{};let a=await V(n,Xe(s,r),r,i,o);return a?{id:a.id}:{unresolved:s}}function MN(e,t,n,r,i,o){let s=$N(e.dependencies,t,n,r,o);s.changed&&(s.dependencies===void 0?delete e.dependencies:e.dependencies=s.dependencies,i.includes("dependencies")||i.push("dependencies"))}function PN(e){return`${e.path}::${e.scope}`}function FN(e){return`${e.path}::${e.scope}`}function jN(e){return`${e.command}::${e.path??""}::${e.scope}::${e.pm_context_mode??""}::${e.workspace_context_mode??""}`}function ik(e,t){let n=pr("update",e);if(!n)throw new p(`Unsupported command_option_policies option "${e}" for update command on type "${t}"`,m.CONFLICT);return n}function UN(e,t,n){let r=new Set,i=(o,s)=>{s&&r.add(o)};if(i("title",e.title!==void 0),i("description",e.description!==void 0),i("body",e.body!==void 0),i("status",e.status!==void 0),i("closeReason",e.closeReason!==void 0),i("priority",e.priority!==void 0),i("type",e.type!==void 0),i("tags",e.tags!==void 0||Array.isArray(e.addTags)&&e.addTags.length>0||Array.isArray(e.removeTags)&&e.removeTags.length>0),i("deadline",e.deadline!==void 0),i("estimatedMinutes",e.estimatedMinutes!==void 0),i("acceptanceCriteria",e.acceptanceCriteria!==void 0||Array.isArray(e.addAc)&&e.addAc.length>0||Array.isArray(e.removeAc)&&e.removeAc.length>0),i("definitionOfReady",e.definitionOfReady!==void 0),i("order",e.order!==void 0||e.rank!==void 0),i("goal",e.goal!==void 0),i("objective",e.objective!==void 0),i("value",e.value!==void 0),i("impact",e.impact!==void 0),i("outcome",e.outcome!==void 0),i("whyNow",e.whyNow!==void 0),i("author",e.author!==void 0),i("message",e.message!==void 0),i("assignee",e.assignee!==void 0),i("parent",e.parent!==void 0),i("reviewer",e.reviewer!==void 0),i("risk",e.risk!==void 0),i("confidence",e.confidence!==void 0),i("sprint",e.sprint!==void 0),i("release",e.release!==void 0),i("blockedBy",e.blockedBy!==void 0),i("blockedReason",e.blockedReason!==void 0),i("unblockNote",e.unblockNote!==void 0),i("reporter",e.reporter!==void 0),i("severity",e.severity!==void 0),i("environment",e.environment!==void 0),i("reproSteps",e.reproSteps!==void 0),i("resolution",e.resolution!==void 0),i("expectedResult",e.expectedResult!==void 0),i("actualResult",e.actualResult!==void 0),i("affectedVersion",e.affectedVersion!==void 0),i("fixedVersion",e.fixedVersion!==void 0),i("component",e.component!==void 0),i("regression",e.regression!==void 0),i("customerImpact",e.customerImpact!==void 0),i("dep",e.dep!==void 0),i("depRemove",e.depRemove!==void 0),i("dep",e.replaceDeps===!0),i("comment",e.comment!==void 0),i("note",e.note!==void 0),i("learning",e.learning!==void 0),i("file",e.file!==void 0),i("test",e.test!==void 0),i("test",e.replaceTests===!0),i("file",e.replaceFiles===!0),i("doc",e.replaceDocs===!0),i("doc",e.doc!==void 0),i("reminder",e.reminder!==void 0),i("event",e.event!==void 0),i("typeOption",e.typeOption!==void 0),i("field",e.field!==void 0),i("force",e.force===!0),i("ownershipMetadataBypass",e.ownershipMetadataBypass===!0),i("ownershipDependencyBypass",e.ownershipDependencyBypass===!0),i("dep",e.clearDeps===!0),i("comment",e.clearComments===!0),i("note",e.clearNotes===!0),i("learning",e.clearLearnings===!0),i("file",e.clearFiles===!0),i("test",e.clearTests===!0),i("doc",e.clearDocs===!0),i("reminder",e.clearReminders===!0),i("event",e.clearEvents===!0),i("typeOption",e.clearTypeOptions===!0),e.unset&&e.unset.length>0){let o=Ol(e.unset,t,n,e.runtimeFieldCommands);for(let s of o.optionKeys)i(s,!0)}return r}function GN(e,t,n,r,i){let o=Fi(e,n);if(!o)throw new p(`Invalid type value "${e}"`,m.USAGE);let s=Cn(o,"update",[]);if(s.errors.length>0)throw new p(s.errors.join("; "),m.CONFLICT);let a=UN(t,r,i);for(let c of s.disabled)if(a.has(ik(c,e)))throw new p(`Option ${xe("update",c)} is disabled for type "${e}" by command_option_policies`,m.USAGE);for(let c of s.required)if(!a.has(ik(c,e)))throw new p(`Missing required option ${xe("update",c)} for type "${e}"`,m.USAGE)}var qN=new Set(["order","rank"]),KN=Na.filter(e=>!qN.has(e)),pk=["tags","closeReason",...KN],WN=["title","description","body","status","closeReason","completedAt","priority","type",...Na,"dep","depRemove","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],zN=[{optionKey:"deadline",metadataKey:"deadline",transform:(e,t)=>me(e,t.nowValue,"deadline")},{optionKey:"estimatedMinutes",metadataKey:"estimated_minutes",transform:e=>Ni(e,"estimated-minutes")},{optionKey:"acceptanceCriteria",metadataKey:"acceptance_criteria",transform:e=>e},{optionKey:"definitionOfReady",metadataKey:"definition_of_ready"},{optionKey:"goal",metadataKey:"goal"},{optionKey:"objective",metadataKey:"objective"},{optionKey:"value",metadataKey:"value"},{optionKey:"impact",metadataKey:"impact"},{optionKey:"outcome",metadataKey:"outcome"},{optionKey:"whyNow",metadataKey:"why_now"}],BN=[{optionKey:"reviewer",metadataKey:"reviewer"},{optionKey:"risk",metadataKey:"risk",transform:e=>tt(Ms(e),Mi,"risk")},{optionKey:"confidence",metadataKey:"confidence",transform:e=>Fs(e)}],HN=[{optionKey:"blockedReason",metadataKey:"blocked_reason"},{optionKey:"unblockNote",metadataKey:"unblock_note"},{optionKey:"reporter",metadataKey:"reporter"},{optionKey:"severity",metadataKey:"severity",transform:e=>tt(Ps(e),Pi,"severity")},{optionKey:"environment",metadataKey:"environment"},{optionKey:"reproSteps",metadataKey:"repro_steps"},{optionKey:"resolution",metadataKey:"resolution"},{optionKey:"expectedResult",metadataKey:"expected_result"},{optionKey:"actualResult",metadataKey:"actual_result"},{optionKey:"affectedVersion",metadataKey:"affected_version"},{optionKey:"fixedVersion",metadataKey:"fixed_version"},{optionKey:"component",metadataKey:"component"},{optionKey:"regression",metadataKey:"regression",transform:e=>js(e)},{optionKey:"customerImpact",metadataKey:"customer_impact"}];function Il(e,t,n){for(let r of e){let i=t[r.optionKey],o=n.clearItemMetadataKeys.has(r.metadataKey);if(!(i===void 0&&!o)){if(o){delete n.metadataRecord[r.metadataKey],n.changedFields.push(r.metadataKey);continue}if(typeof i!="string")throw new p(`${xe("update",String(r.optionKey))} must be a string value`,m.USAGE);n.metadataRecord[r.metadataKey]=r.transform?r.transform(i,n):i.trim(),n.changedFields.push(r.metadataKey)}}}async function VN(e){return lk(await $i(e,[["body","--body"],["description","--description"]],[["dep","--dep"],["depRemove","--dep-remove"],["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"],["field","--field"]]))}async function YN(e){let t=Or("update",e);return Wt(t)?await VN(t):lk(t)}function JN(e){return[{enabled:e.clearDeps||e.replaceDeps,optionKey:"dep",clearFlag:"--clear-deps",valueFlag:"--dep",values:e.dep,metadataKey:"dependencies"},{enabled:e.clearComments,optionKey:"comment",clearFlag:"--clear-comments",valueFlag:"--comment",values:e.comment,metadataKey:"comments"},{enabled:e.clearNotes,optionKey:"note",clearFlag:"--clear-notes",valueFlag:"--note",values:e.note,metadataKey:"notes"},{enabled:e.clearLearnings,optionKey:"learning",clearFlag:"--clear-learnings",valueFlag:"--learning",values:e.learning,metadataKey:"learnings"},{enabled:e.clearFiles||e.replaceFiles,optionKey:"file",clearFlag:"--clear-files",valueFlag:"--file",values:e.file,metadataKey:"files"},{enabled:e.clearTests||e.replaceTests,optionKey:"test",clearFlag:"--clear-tests",valueFlag:"--test",values:e.test,metadataKey:"tests"},{enabled:e.clearDocs||e.replaceDocs,optionKey:"doc",clearFlag:"--clear-docs",valueFlag:"--doc",values:e.doc,metadataKey:"docs"},{enabled:e.clearReminders,optionKey:"reminder",clearFlag:"--clear-reminders",valueFlag:"--reminder",values:e.reminder,metadataKey:"reminders"},{enabled:e.clearEvents,optionKey:"event",clearFlag:"--clear-events",valueFlag:"--event",values:e.event,metadataKey:"events"},{enabled:e.clearTypeOptions,optionKey:"typeOption",clearFlag:"--clear-type-options",valueFlag:"--type-option",values:e.typeOption,metadataKey:"type_options"}]}function xl(e){if(e.enabled&&(!e.values||e.values.length===0))throw new p(`${e.replaceFlag} requires at least one ${e.valueFlag} entry`,m.USAGE);if(e.enabled&&e.clearEnabled)throw new p(`${e.replaceFlag} cannot be combined with ${e.clearFlag}`,m.USAGE)}function XN(e){let t=(e.addAc?.length??0)>0||(e.removeAc?.length??0)>0;if(e.acceptanceCriteria!==void 0&&t)throw new p("Cannot combine --acceptance-criteria replacement with --add-ac or --remove-ac. Use --remove-ac and --add-ac together for an atomic one-entry repair.",m.USAGE,{code:"acceptance_criteria_mutation_conflict",reason:"replacement_and_additive_mutation_combined",nextSteps:["Use --acceptance-criteria alone to replace the complete list.","Use --remove-ac <old> --add-ac <new> to repair one criterion without replacing unrelated entries."]});if(e.replaceDeps===!0&&(e.dep===void 0||e.dep.length===0))throw new p("--replace-deps requires at least one --dep entry",m.USAGE);if(e.replaceDeps===!0&&e.depRemove!==void 0&&e.depRemove.length>0)throw new p("--replace-deps cannot be combined with --dep-remove",m.USAGE);xl({enabled:e.replaceTests===!0,values:e.test,replaceFlag:"--replace-tests",clearEnabled:e.clearTests===!0,clearFlag:"--clear-tests",valueFlag:"--test"}),xl({enabled:e.replaceFiles===!0,values:e.file,replaceFlag:"--replace-files",clearEnabled:e.clearFiles===!0,clearFlag:"--clear-files",valueFlag:"--file"}),xl({enabled:e.replaceDocs===!0,values:e.doc,replaceFlag:"--replace-docs",clearEnabled:e.clearDocs===!0,clearFlag:"--clear-docs",valueFlag:"--doc"})}function QN(e){for(let t of e.definitions){if(!t.enabled)continue;let n=t.optionKey==="dep"&&e.options.replaceDeps===!0||t.optionKey==="test"&&e.options.replaceTests===!0||t.optionKey==="file"&&e.options.replaceFiles===!0||t.optionKey==="doc"&&e.options.replaceDocs===!0;if(t.values&&t.values.length>0&&!n)throw new p(`Cannot combine ${t.clearFlag} with ${t.valueFlag}`,m.USAGE);e.clearOptionKeys.add(t.optionKey),e.clearItemMetadataKeys.add(t.metadataKey)}}function ZN(e){let t={};for(let n of pk)t[String(n)]=e[n]!==void 0;return t.order=e.order!==void 0||e.rank!==void 0,t}function eM(e,t){let n=ZN(e);for(let[r,i]of Object.entries(n)){if(!i||!t.optionKeys.has(r))continue;let o=Zs.get(r)??r;throw new p(`Cannot combine --unset ${o} with ${xe("update",r)}`,m.USAGE)}if(t.metadataKeys.has("acceptance_criteria")){if(Array.isArray(e.addAc)&&e.addAc.length>0)throw new p("Cannot combine --unset acceptance-criteria with --add-ac",m.USAGE);if(Array.isArray(e.removeAc)&&e.removeAc.length>0)throw new p("Cannot combine --unset acceptance-criteria with --remove-ac",m.USAGE)}if(t.metadataKeys.has("tags")){if(Array.isArray(e.addTags)&&e.addTags.length>0)throw new p("Cannot combine --unset tags with --add-tags",m.USAGE);if(Array.isArray(e.removeTags)&&e.removeTags.length>0)throw new p("Cannot combine --unset tags with --remove-tags",m.USAGE)}}function tM(e){if(at(e))return;let t=(n,r)=>{if(at(e,r))return;let i=Zs.get(r),o=i?`Use --unset ${i} to clear this field.`:void 0;ko(n,xe("update",r),o)};for(let n of pk)t(e[n],String(n));t(e.order??e.rank,"order"),Oe(e.reminder,"--reminder","Use --clear-reminders to clear reminders."),Oe(e.event,"--event","Use --clear-events to clear linked events.")}function nM(e,t){let n={};for(let r of WN)n[String(r)]=e[r]!==void 0;return n.tags=e.tags!==void 0,n.addTags=Array.isArray(e.addTags)&&e.addTags.length>0,n.removeTags=Array.isArray(e.removeTags)&&e.removeTags.length>0,n.addAc=Array.isArray(e.addAc)&&e.addAc.length>0,n.removeAc=Array.isArray(e.removeAc)&&e.removeAc.length>0,n.order=e.order!==void 0,n.rank=e.rank!==void 0,n.replaceDeps=e.replaceDeps===!0,n.replaceTests=e.replaceTests===!0,n.replaceFiles=e.replaceFiles===!0,n.replaceDocs=e.replaceDocs===!0,n.unset=e.unset!==void 0&&e.unset.length>0,n.clearDeps=e.clearDeps===!0,n.clearComments=e.clearComments===!0,n.clearNotes=e.clearNotes===!0,n.clearLearnings=e.clearLearnings===!0,n.clearFiles=e.clearFiles===!0,n.clearTests=e.clearTests===!0,n.clearDocs=e.clearDocs===!0,n.clearReminders=e.clearReminders===!0,n.clearEvents=e.clearEvents===!0,n.clearTypeOptions=e.clearTypeOptions===!0,n.documentAnnotationSnapshot=e.documentAnnotationSnapshot!==void 0,n.runtimeFields=Object.keys(t).length>0,n}async function rM(e){let t=await V(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await Qt(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await pe(t,{schema:e.settings.schema});return{item:n.metadata,changed_fields:[],warnings:["noop_no_update_fields"]}}async function iM(e){if(!(!e.fieldFlags.dep&&!e.fieldFlags.blockedBy&&!e.fieldFlags.parent&&!e.clearedMetadataKeys.has("parent")))return Te(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}function oM(e){e.before&&(Es(e.before,e.before.map(t=>t.id===e.document.metadata.id?e.document.metadata:t)),Ao(e.before,e.before.map(t=>t.id===e.document.metadata.id?e.document.metadata:t),e.document.metadata.id,t=>fe(t,e.statusRegistry),de()))}function sM(e){if(e.order!==void 0&&e.rank!==void 0&&e.order!==e.rank)throw new p("--order and --rank must match when both are provided",m.USAGE)}async function aM(e){if(e.options.parent===void 0||e.unsetTargets.metadataKeys.has("parent"))return{resolvedParentValue:void 0,warnings:[]};let t=ct(e.options),n=Ln(ao(e.options.parent,t),e.settings.id_prefix);if(go(n))return{resolvedParentValue:n,warnings:[]};if(lo(e.id,n,e.settings.id_prefix,t),await V(e.pmRoot,n,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder))return{resolvedParentValue:n,warnings:[]};let r=Xe(n,e.settings.id_prefix);return{resolvedParentValue:n,warnings:co(r,e.parentReferencePolicy,t).warnings}}function cM(e){return e.unresolved===void 0?[]:[`blocked_by_unresolved:${e.unresolved}`]}async function dM(e){if(e.workflowEnforcement==="off"||e.typeWorkflows.length===0||!e.fieldFlags.status||e.options.status===void 0)return[];let t=await V(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await Qt(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await pe(t,{schema:e.settings.schema}),r=e.options.type!==void 0?_t(e.options.type,e.typeRegistry)??e.options.type:n.metadata?.type??"",i=ir({enforcement:e.workflowEnforcement,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry,typeName:r,fromStatus:n.metadata?.status??"",toStatus:e.options.status});return i?[i]:[]}async function lM(e){if(!e.fieldFlags.status||ce(e.options.status,e.statusRegistry)!==e.statusRegistry.close_status)return;Xb(e);let t=Object.entries(e.fieldFlags).filter(([i,o])=>o&&i!=="status"&&i!=="closeReason"&&i!=="completedAt").map(([i])=>i),n=await Qb(e);if(Cl(n,e.options,e.statusRegistry,e.settings.governance.require_close_reason))return Zb(e,n,t,fi,i=>ok(e,i));let r;if(t.length>0){let i=dt(e.options,{...e.options,status:void 0,closeReason:void 0,message:void 0});r=await fi(e.id,i,e.global)}return ok(e,r)}async function ok(e,t){let n=await bs(e.id,e.options.closeReason,{author:e.options.author,message:e.options.message,force:e.options.force,completedAt:e.options.completedAt},e.global),r=[...Rr("update",e.options,ct(e.options)==="sdk",n.item),...e.workflowTransitionWarnings,...(t?.warnings??[]).filter(i=>!i.startsWith("literal_sentinel_stored:")),...n.warnings,"auto_routed_from_update_to_close"];return{item:n.item,changed_fields:[...t?.changed_fields??[],...n.changed_fields],warnings:r}}function uM(e,t,n,r){return t.title!==void 0&&(e.metadata.title=Sl(t.title,"--title",ct(t)),r.push("title")),t.description!==void 0&&(e.metadata.description=t.description,r.push("description")),t.body!==void 0&&(e.body=t.body,r.push("body")),ce(e.metadata.status,n)??e.metadata.status}var mM=["closed_at","completed_at","close_reason","resolution","expected_result","actual_result","fixed_version"];function pM(e,t){for(let n of mM)e[n]!==void 0&&(delete e[n],t.push(n))}function _M(e,t,n,r,i){let o=AN(n,t.statusRegistry);if(e.metadata.status=o,i.push("status"),o===t.statusRegistry.close_status&&(e.metadata.closed_at===void 0||e.metadata.closed_at===null)){e.metadata.closed_at=t.nowIso,e.metadata.completed_at=t.nowIso,i.push("closed_at","completed_at");return}!fe(o,t.statusRegistry)&&fe(r,t.statusRegistry)&&pM(e.metadata,i)}function fM(e,t,n,r){if(t.options.status!==void 0&&_M(e,t,t.options.status,n,r),t.options.completedAt!==void 0){if(!fe(e.metadata.status,t.statusRegistry))throw new p("--completed-at can only be set on a terminal item",m.USAGE);e.metadata.completed_at=me(t.options.completedAt,new Date(t.nowIso),"completed-at"),r.push("completed_at")}}function hM(e,t,n,r){if(t.options.closeReason!==void 0||t.clearItemMetadataKeys.has("close_reason")){if(t.clearItemMetadataKeys.has("close_reason"))delete e.metadata.close_reason;else{let i=t.options.closeReason?.trim()??"";if(i.length===0)throw new p(Oa(ct(t.options),"close-reason"),m.USAGE);e.metadata.close_reason=i}r.push("close_reason");return}t.options.status!==void 0&&fe(n,t.statusRegistry)&&!fe(e.metadata.status,t.statusRegistry)&&e.metadata.close_reason!==void 0&&(delete e.metadata.close_reason,r.push("close_reason"))}function gM(e,t,n,r){fM(e,t,n,r),hM(e,t,n,r)}function yM(e,t,n){let r=_t(e.metadata.type,t.typeRegistry)??e.metadata.type;if(t.options.priority!==void 0&&(e.metadata.priority=uo(t.options.priority),n.push("priority")),t.options.type!==void 0){let i=_t(t.options.type,t.typeRegistry);if(!i)throw new p(po(t.options.type,t.typeRegistry.types,Hi(t.pmRoot,t.settings.schema)),m.USAGE);e.metadata.type=i,r=i,n.push("type")}return GN(r,t.options,t.typeRegistry,t.runtimeFieldRegistry,t.extensionFieldNames),wM(e,t,r,n),r}function wM(e,t,n,r){if(t.options.typeOption!==void 0||t.clearItemMetadataKeys.has("type_options")){if(t.clearItemMetadataKeys.has("type_options"))delete e.metadata.type_options;else{let o=zs(t.options.typeOption??[]),s=_r(n,o,t.typeRegistry);if(s.errors.length>0)throw new p(s.errors.join("; "),m.USAGE);e.metadata.type_options=s.normalized}r.push("type_options");return}if(t.options.type===void 0||e.metadata.type_options===void 0)return;let i=_r(n,e.metadata.type_options,t.typeRegistry);if(i.errors.length>0)throw new p(`Current type options are incompatible with type "${n}". ${i.errors.join("; ")}. Use --clear-type-options to clear them.`,m.USAGE);e.metadata.type_options=i.normalized}function vM(e,t){let n=new Set(t.map(i=>ea(i))),r=new Set;return e.filter(i=>{if(!n.has(ea(i)))return!0;let o=Qs(i);return r.has(o)?!1:(r.add(o),!0)})}function bM(e,t,n){if(t.options.dep===void 0&&t.options.depRemove===void 0&&!t.clearItemMetadataKeys.has("dependencies"))return;let r=t.clearItemMetadataKeys.has("dependencies")?[]:[...e.metadata.dependencies??[]];if(t.dependencyUpdates.additions.length>0){r=vM(r,t.dependencyUpdates.additions);let i=new Set(r.map(o=>ea(o)));for(let o of t.dependencyUpdates.additions){let s=ea(o);i.has(s)||(r.push(o),i.add(s))}}t.dependencyRemovals.length>0&&(ek(r,t.dependencyRemovals,e.metadata.id),r=r.filter(i=>!t.dependencyRemovals.some(o=>Al(i,o)))),r.length===0?delete e.metadata.dependencies:e.metadata.dependencies=r,n.push("dependencies")}function kM(e,t,n){Rl(e,"comments",t.options.comment,t.commentUpdates.values,t.clearItemMetadataKeys,n),Rl(e,"notes",t.options.note,t.noteUpdates.values,t.clearItemMetadataKeys,n),Rl(e,"learnings",t.options.learning,t.learningUpdates.values,t.clearItemMetadataKeys,n)}function Rl(e,t,n,r,i,o){n===void 0&&!i.has(t)||(i.has(t)||!r||r.length===0?delete e.metadata[t]:e.metadata[t]=[...e.metadata[t]??[],...r],o.push(t))}function SM(e,t,n){sk(e,"files",t.options.file,t.fileUpdates.values,PN,t.options.replaceFiles===!0,t.clearItemMetadataKeys,n),EM(e,t,n),sk(e,"docs",t.options.doc,t.docUpdates.values,FN,t.options.replaceDocs===!0,t.clearItemMetadataKeys,n)}function sk(e,t,n,r,i,o,s,a){if(!(n===void 0&&!s.has(t))){if(o)e.metadata[t]=r;else if(s.has(t)||!r||r.length===0)delete e.metadata[t];else{let c=[...e.metadata[t]??[]],d=new Set(c.map(l=>i(l)));for(let l of r){let u=i(l);d.has(u)||(c.push(l),d.add(u))}e.metadata[t]=c}a.push(t)}}function EM(e,t,n){t.options.test===void 0&&!t.clearItemMetadataKeys.has("tests")||(t.clearItemMetadataKeys.has("tests")&&t.options.replaceTests===!0?e.metadata.tests=ak(t.testUpdates.values)??[]:t.clearItemMetadataKeys.has("tests")||!t.testUpdates.values||t.testUpdates.values.length===0?delete e.metadata.tests:e.metadata.tests=ak([...e.metadata.tests??[],...t.testUpdates.values]),e.metadata.tests!==void 0&&e.metadata.tests.length===0&&delete e.metadata.tests,n.push("tests"))}function ak(e){if(!e||e.length===0)return;let t=[],n=new Set;for(let r of e){let i=jN(r);n.has(i)||(t.push(r),n.add(i))}return t}function TM(e,t,n){let r=t.options.addTags,i=t.options.removeTags,o=Array.isArray(r)&&r.length>0||Array.isArray(i)&&i.length>0;if(t.options.tags!==void 0||t.clearItemMetadataKeys.has("tags")||o){let s=t.clearItemMetadataKeys.has("tags")?[]:t.options.tags!==void 0?Oi(t.options.tags):Array.isArray(e.metadata.tags)?[...e.metadata.tags]:[];e.metadata.tags=Yu(Di(s,r),i),n.changedFields.push("tags")}Il(zN,t.options,n),AM(e,t,n.changedFields)}function CM(e,t,n){let r=t.options.addAc,i=t.options.removeAc;if(!(Array.isArray(r)&&r.length>0)&&!(Array.isArray(i)&&i.length>0))return;let o=Vu(Li(e.metadata.acceptance_criteria),r,i);if(o.unmatchedRemovals.length>0)throw new p(`Acceptance criteria removal did not match: ${o.unmatchedRemovals.join(", ")}`,m.NOT_FOUND,{code:"acceptance_criteria_remove_unmatched",reason:"exact_match_not_found",field:"acceptance_criteria",unmatched:o.unmatchedRemovals,why:"Lossless removal fails instead of silently applying the remaining mutations when an exact selector is wrong.",nextSteps:["Read the current acceptance_criteria value and retry with the exact criterion text.","Use --acceptance-criteria alone only when replacing the complete list is intentional."]});let s=o.criteria.join("; ");e.metadata.acceptance_criteria!==s&&(s===""&&e.metadata.acceptance_criteria===void 0||(e.metadata.acceptance_criteria=s,n.changedFields.includes("acceptance_criteria")||n.changedFields.push("acceptance_criteria")))}function AM(e,t,n){let r=t.options.order??t.options.rank;if(!(r===void 0&&!t.clearItemMetadataKeys.has("order"))){if(t.clearItemMetadataKeys.has("order"))delete e.metadata.order;else{let i=we(r??"","order");if(!Number.isInteger(i))throw new p("Order must be an integer",m.USAGE);e.metadata.order=i}n.push("order")}}function xM(e,t,n,r){RM(e,t,n.changedFields),IM(e,t,n.changedFields),Il(BN,t.options,n),ck(e,t,"sprint",r,n.changedFields),ck(e,t,"release",r,n.changedFields),OM(e,t,n.changedFields),Il(HN,t.options,n)}function RM(e,t,n){if(!(t.options.assignee===void 0&&!t.clearItemMetadataKeys.has("assignee"))){if(t.clearItemMetadataKeys.has("assignee"))delete e.metadata.assignee;else{let r=t.options.assignee?.trim()??"";if(r==="")throw new p(Oa(ct(t.options),"assignee",". Use --unset assignee to clear it."),m.USAGE);hm(r,"--assignee"),e.metadata.assignee=r}n.push("assignee")}}function IM(e,t,n){t.options.parent===void 0&&!t.clearItemMetadataKeys.has("parent")||(t.clearItemMetadataKeys.has("parent")?delete e.metadata.parent:e.metadata.parent=t.resolvedParentValue??"",n.push("parent"))}function ck(e,t,n,r,i){if(!(t.options[n]===void 0&&!t.clearItemMetadataKeys.has(n))){if(t.clearItemMetadataKeys.has(n))delete e.metadata[n];else{let o=mo(n,t.options[n]??"",t.settings.validation.sprint_release_format,ct(t.options));e.metadata[n]=o.value,r.push(...o.warnings)}i.push(n)}}function OM(e,t,n){if(t.options.blockedBy===void 0&&!t.clearItemMetadataKeys.has("blocked_by"))return;let r=t.clearItemMetadataKeys.has("blocked_by")?e.metadata.blocked_by:void 0;t.clearItemMetadataKeys.has("blocked_by")?delete e.metadata.blocked_by:e.metadata.blocked_by=t.options.blockedBy?.trim()??"",n.push("blocked_by"),(t.clearItemMetadataKeys.has("blocked_by")||t.resolvedBlockedByDependencyId!==void 0)&&MN(e.metadata,t.resolvedBlockedByDependencyId,t.nowIso,t.author,n,{value:r,idPrefix:t.settings.id_prefix})}function LM(e,t,n){(t.options.reminder!==void 0||t.clearItemMetadataKeys.has("reminders"))&&(t.clearItemMetadataKeys.has("reminders")?delete e.metadata.reminders:e.metadata.reminders=Ks(t.options.reminder??[],t.nowValue,{valueMode:"trimmed"}),n.push("reminders")),(t.options.event!==void 0||t.clearItemMetadataKeys.has("events"))&&(t.clearItemMetadataKeys.has("events")?delete e.metadata.events:e.metadata.events=Ws(t.options.event??[],t.nowValue,{allDayEmptyGuard:"truthy",recurrenceEmptyNumericGuard:"truthy"}),n.push("events"))}function DM(e,t,n){dk(e,t.runtimeFieldRegistry.definitions.map(i=>i.metadata_key),t.clearItemMetadataKeys,n),dk(e,t.extensionFieldNames,t.clearItemMetadataKeys,n);for(let[i,o]of Object.entries(t.runtimeFieldUpdates)){if(t.clearItemMetadataKeys.has(i)){let s=i.replaceAll("_","-"),a=t.runtimeFieldRegistry.definitions.find(c=>c.metadata_key===i)?.cli_flag??s;throw new p(`Cannot combine --unset ${s} with --${a}`,m.USAGE)}Fe(e[i],o)||(e[i]=o,n.push(i))}let r=io(t.options.field,t.extensionRegistrations,Us,Gs(t.runtimeFieldRegistry,(t.options.runtimeFieldCommands??[]).includes("update_many")?"update_many":"update",t.options));for(let i of Object.keys(r))if(t.clearItemMetadataKeys.has(i))throw new p(`Cannot combine --unset ${i.replaceAll("_","-")} with --field ${i}=...`,m.USAGE);for(let[i,o]of Object.entries(r))Fe(e[i],o)||(e[i]=o,n.push(i))}function dk(e,t,n,r){for(let i of t)!n.has(i)||e[i]===void 0||(delete e[i],r.push(i))}function $M(e,t){if(t===void 0)return;let n=e.metadata,r=["comments","notes","learnings"].find(i=>{let o=t[i];return o!==void 0&&(!Array.isArray(o)||!Fe(o,n[i]??[]))});if(r!==void 0)throw new p(`Full-item --stdin-json update changed persisted ${r}; no item fields were written.`,m.USAGE,{code:"stdin_json_persisted_annotation_changed",reason:`${r}_requires_annotation_command`,required:`Use pm ${r} ${e.metadata.id} --edit <index> --add <text> to correct an existing entry.`,why:"Full-item update appends new annotations but cannot replace or remove existing audit entries.",nextSteps:[`Inspect the current ${r} with pm ${r} ${e.metadata.id}.`,`Apply the correction with pm ${r} ${e.metadata.id} --edit <index> --add <text>.`]})}function NM(e,t){$M(e,t.options.documentAnnotationSnapshot);let n=structuredClone(e.metadata),r=e.body,i=[],o=[],s=uM(e,t.options,t.statusRegistry,i),a=e.metadata,c={metadataRecord:a,clearItemMetadataKeys:t.clearItemMetadataKeys,changedFields:i,nowValue:t.nowValue};gM(e,t,s,i),yM(e,t,i),bM(e,t,i),kM(e,t,i),SM(e,t,i),TM(e,t,c),CM(e,t,c),xM(e,t,c,o),(t.options.dep!==void 0||t.options.depRemove!==void 0||t.options.blockedBy!==void 0||t.clearItemMetadataKeys.has("dependencies")||t.clearItemMetadataKeys.has("blocked_by"))&&_i(e.metadata.id,e.metadata.dependencies),ce(e.metadata.status,t.statusRegistry)===t.statusRegistry.canceled_status&&e.metadata.assignee!==void 0&&(delete e.metadata.assignee,i.includes("assignee")||i.push("assignee")),LM(e,t,i),DM(a,t,i);try{oo(a,t.extensionRegistrations,{skipDefaultFields:t.clearItemMetadataKeys})}catch(_){throw new p(_ instanceof Error?_.message:"Invalid extension item field values",m.USAGE)}let d=e.metadata,l=[...new Set(i)].filter(_=>_==="body"?e.body!==r:!Fe(n[_],d[_])),u=tk(n.dependencies,d.dependencies);return u!==void 0&&o.push(`dependencies_removed:${e.metadata.id}:${u}`),t.options.acceptanceCriteria!==void 0&&l.includes("acceptance_criteria")&&o.push(`acceptance_criteria_replaced:${Li(n.acceptance_criteria).length}:${Li(d.acceptance_criteria).length}`),{changedFields:l,warnings:o}}async function _k(e,t,n,r={}){Ir(e,"update","id");let i=await YN(t),o=R(process.cwd(),n.path);await j(o);let s=await x(o),a=W(s.schema),c=Vt(s.schema),d=N(),l=xt(d),u=P(s,d),_=s.governance.workflow_enforcement??"off",h=_==="off"?[]:On(s.schema),f=[{strict_error:"strict_error",warn:"warn",off:"off"},{strict_error:"warn",warn:"warn",off:"off"}][+(i.allowMissingParent===!0)][s.validation.parent_reference],g=Ol(i.unset,c,l,i.runtimeFieldCommands),y=new Set(g.optionKeys),w=new Set(g.metadataKeys);XN(i),QN({definitions:JN(i),options:i,clearOptionKeys:y,clearItemMetadataKeys:w}),CN(e,i,w),eM(i,g),tM(i);let v=U(i.author,s.author_default),k=new Date,S=k.toISOString(),b=ON(i.dep,s.id_prefix,S,v);_i(e,b.additions);let A=await qs({pmRoot:o,dependencies:b.additions,idPrefix:s.id_prefix,itemFormat:s.item_format,typeToFolder:u.type_to_folder,allowUnresolved:i.allowUnresolvedDeps,holders:[{id:e}],schema:s.schema}),E=LN(i.depRemove,s.id_prefix),C=fn("--comment",i.comment,S,v),O=i.ownershipMetadataBypass===!0&&C.values?{...C,values:C.values.map(se=>({...se,author:v}))}:C,M=fn("--note",i.note,S,v),T=fn("--learning",i.learning,S,v),F=vl(i.file),ue=bl(i.test);ue.values=await Xn(ue.values,v,S);let Ne=kl(i.doc),J=[],Me=await aM({id:e,options:i,unsetTargets:g,pmRoot:o,settings:s,typeRegistry:u,parentReferencePolicy:f}),Pe=await NN(i.blockedBy,w.has("blocked_by"),o,s.id_prefix,s.item_format,u.type_to_folder),qe=Pe.id,re=[...Me.warnings,...cM(Pe)],be=Im(i,c,i.runtimeFieldCommands),Ee=nM(i,be);if(!Object.values(Ee).some(Boolean))return rM({pmRoot:o,id:e,settings:s,typeRegistry:u});J.push(...await dM({options:i,fieldFlags:Ee,workflowEnforcement:_,typeWorkflows:h,statusRegistry:a,typeRegistry:u,pmRoot:o,id:e,settings:s}));let nt=await lM({options:i,fieldFlags:Ee,statusRegistry:a,workflowTransitionWarnings:J,global:n,id:e,pmRoot:o,settings:s,typeRegistry:u});if(nt)return nt;sM(i);let rt=de(),it=Ee.parent&&!w.has("parent")||b.additions.some(se=>Ss(se.kind,rt)),ye=await Ns({pmRoot:o,author:v,ttlSeconds:s.locks.ttl_seconds,waitMs:s.locks.wait_ms,required:it});try{let se=await iM({fieldFlags:Ee,clearedMetadataKeys:w,pmRoot:o,settings:s,typeToFolder:u.type_to_folder}),He,$,Ve=await Rt({pmRoot:o,settings:s,typeToFolder:u.type_to_folder,id:e,op:MM(i,r),author:v,message:i.message,resolveHistoryContext:()=>$,force:i.force,bypassAssigneeConflict:i.ownershipMetadataBypass===!0||i.ownershipDependencyBypass===!0,extensionFieldNames:l,skipNoop:!0,async mutate(Ae){let ae=Ae.metadata.status;He=PM({document:Ae,recurrenceReason:r.recurrenceReason,requestedStatus:i.status,statusRegistry:a}),$=He?{recurrence:He}:void 0,se=se?.map(Ai=>Ai.id===Ae.metadata.id?structuredClone(Ae.metadata):Ai);let Ci=NM(Ae,{options:i,settings:s,typeRegistry:u,statusRegistry:a,runtimeFieldRegistry:c,extensionRegistrations:d,extensionFieldNames:l,clearItemMetadataKeys:w,dependencyUpdates:b,dependencyRemovals:E,commentUpdates:O,noteUpdates:M,learningUpdates:T,fileUpdates:F,testUpdates:ue,docUpdates:Ne,resolvedParentValue:Me.resolvedParentValue,resolvedBlockedByDependencyId:qe,runtimeFieldUpdates:be,nowValue:k,nowIso:S,author:v,pmRoot:o});oM({before:se,document:Ae,statusRegistry:a});let ka=await Xs({pmRoot:o,settings:s,metadata:Ae.metadata,fromStatus:ae,registry:a,force:i.force===!0});return{...Ci,warnings:[...Ci.warnings,...ka]}}});await ye();let Ut=se?ks(se,se.map(Ae=>Ae.id===Ve.item.id?Ve.item:Ae),Ve.item.id):[];return{item:Ve.item,changed_fields:Ve.changedFields,warnings:[...Rr("update",i,ct(i)==="sdk",Ve.item),...J,...re,...A,...Ut,...Ve.warnings],...He===void 0?{}:{lifecycle_transition:He}}}finally{await ye()}}function MM(e,t){return e.ownershipMetadataBypass===!0||e.ownershipDependencyBypass===!0?"update_ownership_bypass":t.recurrenceReason===void 0?"update":"reopen"}function PM(e){if(e.recurrenceReason===void 0)return;let t=ce(e.document.metadata.status,e.statusRegistry)??e.document.metadata.status;if(!fe(t,e.statusRegistry))throw new p(`Item ${e.document.metadata.id} is already active with status ${t}; recurrence transitions require a terminal item.`,m.CONFLICT,{code:"item_already_active",reason:"recurrence_requires_terminal_item",required:"Use item reopen only for a terminal item whose work has recurred.",why:"Appending a recurrence event to active work would corrupt lifecycle history.",recovery:{suggested_retry:`pm get ${e.document.metadata.id} --full`,suggested_retry_args:["get",e.document.metadata.id,"--full"]},nextSteps:[`Inspect the active item with: pm get ${e.document.metadata.id} --full`,`Continue the existing work with: pm update ${e.document.metadata.id} ...`]});let n=e.requestedStatus??e.statusRegistry.open_status,r=ce(n,e.statusRegistry)??n,i=e.document.metadata,o=Object.fromEntries(["close_reason","resolution","expected_result","actual_result","fixed_version"].flatMap(s=>{let a=i[s];return typeof a=="string"?[[s,a]]:[]}));return{reason:e.recurrenceReason,from_status:t,to_status:r,previous_terminal:o}}async function fi(e,t,n){return _k(e,t,n)}async function K3(e,t,n,r){Ir(r,"reopen","reason");let i=await _k(e,t,n,{recurrenceReason:r});if(i.lifecycle_transition===void 0)throw new p(`Item ${e} did not produce the required recurrence receipt.`,m.GENERIC_FAILURE,{code:"reopen_receipt_missing",reason:"recurrence_transition_not_recorded",required:"A successful reopen must return the terminal-to-active lifecycle transition recorded in immutable history."});return{...i,lifecycle_transition:i.lifecycle_transition}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e32c9f13-2e6a-5ac6-a1ce-9c839121441a")}catch{}})();function ta(e,t){if(e.handoff===void 0)return;if(e.pause===!0)throw new p("--handoff cannot be combined with --pause. Choose a handoff queue or pause the item.",m.USAGE);let n=typeof e.handoff=="string"?Je(e.handoff,t):void 0;if(n===void 0||At(n,t)||n===t.in_progress_status)throw new p("--handoff must name a configured non-terminal status distinct from the in-progress status. Inspect pm schema statuses or add a project queue with pm schema add-status <queue> --role active.",m.USAGE);if(typeof e.message!="string"||e.message.trim().length===0)throw new p("--handoff requires --message with implementation evidence and the next verification step.",m.USAGE);return n}function fk(e,t,n,r,i){if(At(e.status,r)||!e.assignee?.trim())throw new p("Handoff requires a claimed, non-terminal item. Claim the active work before handing it off; use pm item reopen for completed work.",m.CONFLICT);let o=n.governance.workflow_enforcement??"off",s=ir({enforcement:o,typeWorkflows:o==="off"?[]:On(n.schema),statusRegistry:r,typeName:e.type,fromStatus:e.status,toStatus:t}),a={from_status:e.status,to_status:t,message:i},c=e.status===t?[]:["status"];return e.status=t,{receipt:a,warnings:s?[s]:[],changedFields:c}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0b2ea0f6-b501-5004-9daf-73538023fa9b")}catch{}})();var hk="no_available_next_item",u8="stale_claim_takeover_refused";function gk(e){if(!(e instanceof Error)||e.name!=="PmCliError")return;let t=e.context;if(typeof t!="object"||t===null)return;let n=t.code;return typeof n=="string"?n:void 0}function yk(e,t){return gk(e)===t}function FM(e){return yk(e,"already_claimed_by")}async function $l(e,t,n,r={}){let i=R(process.cwd(),n.path);await j(i);let o=await x(i),s=W(o.schema),a=U(r.author,o.author_default),c=Va(a),d=r.takeoverStale===!0;UM(d,t);let l=null,u=!1,_={},h,f=[],g=await Rt({pmRoot:i,settings:o,id:e,op:"claim",author:a,message:r.message,force:t,skipNoop:!0,resolveHistoryContext:()=>h===void 0?void 0:{stale_claim_takeover:h},async mutate(w,v){let k=w.metadata.assignee??"",S=w.metadata.claim_principal?.trim()||k;if(l=k.trim().length>0?k:null,At(w.metadata.status,s)&&!t)throw new p(`Cannot claim terminal item ${w.metadata.id} without --force`,m.CONFLICT);if(l!==null&&S!==c){let T=await jM({pmRoot:i,storageId:v.storageId,metadata:w.metadata,holder:k,author:a,thresholdHours:o.mutation_guard.stale_in_progress_hours,force:t,ifAvailable:r.ifAvailable===!0,takeoverStale:d});if(T.kind==="skip")return u=!0,f.push(`claim_skipped_held_by:${Ua(k)}`),{changedFields:[]};h=T.takeover,f.push(T.warning)}let b={assignee:a,claim_principal:c},A=["assignee","claim_principal"].filter(T=>w.metadata[T]!==b[T]);Object.assign(w.metadata,b);let E=w.metadata.status,{changedFields:C,warnings:O,...M}=VM(w.metadata,r.start===!0,o,s);return O.push(...await HM({pmRoot:i,settings:o,metadata:w.metadata,fromStatus:E,registry:s,force:t,start:r.start===!0})),_=M,f.push(...O),{changedFields:[...A,...C],warnings:f}}}),y=wk(await vk("claim",g.item.id,n,u,()=>Ah({pmRoot:i,settings:o,principal:c,itemId:g.item.id})));return f.push(...y.warnings),{item:ja(g.item),changed_fields:g.changedFields,claimed_by:u&&l!==null?Ui(l):a,previous_assignee:l===null?null:Ui(l),forced:t,...u?{skipped:!0}:{},...f.length>0?{warnings:f}:{},...Dl("suggestions",y.suggestions),..._,...h===void 0?{}:{takeover:h}}}async function jM(e){if(e.ifAvailable&&!e.takeoverStale)return{kind:"skip"};if(e.force)return{kind:"take",warning:`claim_takeover:${Ua(e.holder)}->${e.author}`};let t=await Rh(e.pmRoot,e.storageId,e.holder,{updated_at:e.metadata.updated_at,threshold_hours:e.thresholdHours}),n=e.takeoverStale?GM(t,e.author):void 0;if(n!==void 0)return{kind:"take",warning:`claim_stale_takeover:${n.previous_holder}->${e.author}:idle_hours=${n.idle_hours}`,takeover:n};if(e.takeoverStale&&e.ifAvailable)return{kind:"skip"};throw WM(e.metadata.id,t,e.takeoverStale)}function UM(e,t){if(!(!e||!t))throw new p("--takeover-stale cannot be combined with --force",m.USAGE,{code:"ambiguous_option_combination",required:"Pass --takeover-stale to take over only an idle claim, or --force for a coordinated unconditional takeover.",nextSteps:["Drop --force to let the stale-work policy decide, or drop --takeover-stale for a coordinated override."]})}function GM(e,t){let n=e.activity;if(n.stale_policy.stale)return{previous_holder:e.holder,new_holder:t,claimed_at:e.since,last_activity_at:n.last_activity_at,idle_hours:n.idle_hours,threshold_hours:n.stale_policy.threshold_hours,policy:n.stale_policy.setting}}var qM={claim_record_unavailable:"no original history record shows when the holder took it",discarded_history_tail:"a history salvage after the claim discarded a record whose time is unknown",rewritten_history:"a history repair, redaction or merge reconcile after the claim rewrote its records",workspace_restored:"a workspace snapshot restore at or after the claim may have replaced the holder's work"};function KM(e,t){return t.history_unreadable===!0?{reason:"its history stream could not be read, so idleness cannot be established",nextStep:`Repair the history stream of ${e} (pm history ${e} --verify), then retry --takeover-stale.`}:t.unproven_activity!==void 0?{reason:`${qM[t.unproven_activity]}, so idleness cannot be proven`,nextStep:`Ask the holder to release ${e} (pm release ${e}); a new claim starts a provable record.`}:t.stale_policy.eligible_at===null?{reason:t.idle_hours===null?"no valid activity time is recorded":`idle ${t.idle_hours}h of ${t.stale_policy.threshold_hours}h`,nextStep:`No eligibility time can be computed for ${e}; inspect pm history ${e}.`}:{reason:`idle ${t.idle_hours}h of ${t.stale_policy.threshold_hours}h`,nextStep:`Retry with --takeover-stale after ${t.stale_policy.eligible_at} if nothing else is recorded on ${e}.`}}function WM(e,t,n){let r=t.activity,i=r.stale_policy,o={item_id:e,claimed_by:t.holder,claimed_at:t.since,claim_source:t.source,claim_activity:r},s="Claim is an atomic test-and-set so parallel agents never proceed believing they own the same item.",a="Re-run with --force only when taking over the item is coordinated.";if(n){let c=KM(e,r);return new p(`Item ${e} is ${t.phrase}, and its claim is not stale under ${i.setting} (${c.reason}).`,m.CONFLICT,{code:"stale_claim_takeover_refused",...o,required:`The claim must be idle for at least ${i.threshold_hours}h (${i.setting}) before --takeover-stale may take it.`,why:`${s} A stale takeover needs recorded evidence that the claim has been idle for the configured threshold, so an active claim is never taken over.`,nextSteps:[c.nextStep,"Run pm next to pick a different unclaimed item.",a]})}return new p(`Item ${e} is already ${t.phrase}. Use --force to take over, or --if-available to skip without failing.`,m.CONFLICT,{code:"already_claimed_by",...o,why:s,nextSteps:["Run pm next to pick a different unclaimed item.","Re-run with --if-available to treat a held item as a no-op skip.",...i.stale?[`Re-run with --takeover-stale: the claim has been idle ${r.idle_hours}h, past ${i.setting}=${i.threshold_hours}.`]:[],a]})}var zM="claim_semantic_attribution_unrecorded";function wk(e){return e?{warnings:[e.warning],suggestions:[e.suggestion]}:{warnings:[],suggestions:[]}}function Dl(e,t){return t.length>0?{[e]:t}:{}}var BM="release_semantic_attribution_unrecorded";async function vk(e,t,n,r,i){if(!r)try{await i();return}catch(o){let s=gk(o)??"unexpected_error",a=Ie(n);return{warning:e==="claim"?zM:BM,suggestion:`The ${e} of ${t} is saved, but the session attribution that names this agent's active work was not updated (${s}); nothing needs a retry. If ${L([...a,"health"])} reports a stale lock, remove it with ${L([...a,"gc","--scope","locks"])}.`}}}function m8(e,t,n=!1){let r=n?" --start":"";if(!t&&!e)throw new p(n?"pm claim --start needs an item id, or --next to start the next available item":"Specify an item id or pass --next",m.USAGE,{code:"missing_required_argument",field:"id",required:"Pass an item id, or --next to select the next available item.",nextSteps:[`Retry as pm claim <id>${r}, or pm claim --next${r}.`]});if(t&&e)throw new p("Specify either an item id or --next, not both",m.USAGE,{code:"ambiguous_option_combination",required:"Pass either an item id or --next.",nextSteps:[`Retry as pm claim ${e}${r} to claim that item, or drop the id to select with --next.`]})}async function HM(e){return e.start?Xs(e):Vb(e)}function VM(e,t,n,r){if(!t)return{changedFields:[],warnings:[]};if(At(e.status,r))throw new p(`Cannot start terminal item ${e.id}; reopen it with pm item reopen before starting it`,m.CONFLICT,{code:"terminal_state_conflict",item_id:e.id,why:"Starting work moves an active item into progress; a terminal item must be reopened so its recurrence evidence is recorded.",nextSteps:[`Run pm item reopen ${e.id} "<reason>", then pm claim ${e.id} --start.`]});let i=hn(r),o=n.governance.workflow_enforcement??"off",s=ir({enforcement:o,typeWorkflows:o==="off"?[]:On(n.schema),statusRegistry:r,typeName:e.type,fromStatus:e.status,toStatus:i}),a={from_status:e.status,to_status:i},c=e.status===i?[]:["status"];return e.status=i,{start:a,changedFields:c,warnings:s?[s]:[]}}async function p8(e,t,n={},r={}){if(n.takeoverStale===!0)throw new p("--takeover-stale cannot be combined with --next",m.USAGE,{code:"ambiguous_option_combination",required:"Pass an explicit item id with --takeover-stale; --next only selects work no other author holds.",nextSteps:["Retry as pm claim <id> --takeover-stale for the held item, or drop --takeover-stale to select with --next."]});let i=YM(n.maxAttempts),o=await x(R(process.cwd(),t.path)),s={...n,author:U(n.author,o.author_default)},a=await Ih({...r,callerAuthor:s.author,limit:String(i)},t),c=[a.recommended,...a.ready].filter(d=>d!==null).map(d=>({...d,reasons:"reasons"in d?d.reasons:["ranked ready candidate"]}));return JM(c.slice(0,i),e,t,s)}function YM(e){if(e===void 0)return 10;let t=Number(e);if(!Number.isSafeInteger(t)||t<1||t>100)throw new p("--max-attempts must be an integer from 1 to 100",m.USAGE);return t}async function JM(e,t,n,r={},i=$l){let o=0,s=[],a=()=>s.length>0?{start_refused:[...s]}:{};for(let c of e){o+=1;try{let d=await i(c.id,t,n,r),l={...d,recommendation:c,attempts:o,available:!0,...a()};if(!d.skipped)return l}catch(d){if(yk(d,Js)){s.push(c.id);continue}if(!FM(d))throw d}}if(r.ifAvailable===!0)return{available:!1,item:null,claimed_by:U(r.author,""),previous_assignee:null,forced:t,skipped:!0,recommendation:null,attempts:o,...a(),warnings:[hk]};throw XM(o,s,r.start===!0)}function XM(e,t,n){let r=e===0,i="Every ranked candidate was claimed by another agent before this atomic selection completed.";return r?i="No ready items matched the specified filters or selection criteria.":t.length>0&&(i=`${t.length} of ${e} attempted candidates refused their start because a declared blocker is open (${t.join(", ")}), and nothing was written to them; ${t.length===e?"no other candidate was attempted":"every other attempted candidate was claimed by another agent"}.`),new p(r?"No actionable items matched the selection filters":"No actionable item remained available to claim",r?m.NOT_FOUND:m.CONFLICT,{code:hk,why:i,nextSteps:[r?"Verify the filters or run pm next to inspect all ready work.":`Run pm claim --next${n?" --start":""} again, with the same filters, to refresh the ranked candidate set.`],...t.length>0?{details:{start_refused:[...t]}}:{}})}async function na(e,t,n,r={}){let i=R(process.cwd(),n.path);await j(i);let o=await x(i),s=U(r.author,o.author_default),a=Va(s),c=r.ownershipReleaseBypass===!0,d=null,l=W(o.schema),u=ta(r,l);if(u!==void 0&&c)throw new p("Ownership-release bypass only clears ownership; it cannot change a handoff status.",m.USAGE);let _,h;try{h=await he({pmRoot:i,settings:o,id:e,op:"release",author:s,message:r.message,force:t,bypassAssigneeConflict:c,mutate(y){d=y.metadata.assignee??null;let w=u===void 0?void 0:fk(y.metadata,u,o,l,r.message);return _=w?.receipt,!d&&!y.metadata.claim_principal?{changedFields:[]}:(delete y.metadata.assignee,delete y.metadata.claim_principal,{changedFields:["assignee","claim_principal",...w?.changedFields??[]],warnings:w?.warnings})}})}catch(y){Fr(y,{required:"For approved non-owner handoffs, prefer the ownership-release bypass before considering --force.",examples:['pm release pm-a1b2 --author "reviewer" --force'],nextSteps:["Use the package-provided ownership-release bypass for handoffs that only clear assignee metadata.","Use --force only when an explicit override is approved for broader ownership conflicts."]})}let f=wk(await vk("release",h.item.id,n,!1,()=>xh({pmRoot:i,principal:a,itemId:h.item.id}))),g=QM(h.item,l);return{item:ja(h.item),released_by:s,changed_fields:h.changedFields,previous_assignee:d===null?null:Ui(d),forced:t,..._===void 0?{}:{handoff:_},...Dl("warnings",[...h.warnings,...g.warnings,...f.warnings]),...Dl("suggestions",[...g.suggestions,...f.suggestions])}}function QM(e,t){return Yt(e.status,t)===Yt(t.in_progress_status,t)?{warnings:["released_unclaimed_in_progress"],suggestions:[`${e.id} remains ${e.status} and unclaimed. If work is paused, run pm release ${e.id} --pause to move it to ${t.open_status}.`]}:{warnings:[],suggestions:[]}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a2aa0bed-59f8-5199-a167-0283a8801595")}catch{}})();async function Nl(e,t,n){try{return await n()}catch(r){let i=r instanceof p?r.context:{},o=new p(r instanceof Error?r.message:String(r),r instanceof p?r.exitCode:m.GENERIC_FAILURE,{...i,item_id:e,why:`${t} completed for ${e} before the following step failed. No rollback was performed.${i.why?` ${i.why}`:""}`,nextSteps:[`Inspect the persisted state with pm get ${e} and pm history ${e} before retrying the failed step.`,...i.nextSteps??[]]});throw o.cause=r,o}}async function x8(e,t,n){if(t.next===!0||t.ifAvailable===!0)throw new p("--start cannot be combined with --next or --if-available for an explicit item",m.USAGE,{code:"invalid_argument_value",required:"Remove --next and --if-available when starting an explicit item.",nextSteps:["Remove --next and --if-available, keep the explicit item ID and other supplied arguments, then retry."]});let r=await x(R(process.cwd(),n.path)),i=hn(W(r.schema));return Hb(async()=>{let o=await $l(e,t.force===!0,n,To(t,{},["start"])),s=o.item.id,a=await Nl(s,"claim",()=>fi(s,To(t,{status:i},["assignee","start","next","ifAvailable","maxAttempts","takeoverStale"]),n)).catch(async c=>{throw await ZM(c,o,n,t.author)});return{id:s,action:"start_task",claim:o,update:a}})}async function ZM(e,t,n,r){if(!(e instanceof p)||e.code!==Js||t.previous_assignee!==null)return e;let i=String(t.item.id);try{await op({pmRoot:R(process.cwd(),n.path),id:i,validate:s=>{if(s.metadata.assignee!==t.claimed_by||s.metadata.claim_principal!==t.item.claim_principal)throw new p("The claim this start took is no longer its own.",m.CONFLICT)}},()=>na(i,!1,n,{author:r,message:"Release the claim: a blocker opened before its start could be recorded"}))}catch{return e}let o=e.cause instanceof p?e.cause:e;return new p(o.message,o.exitCode,{...o.context,why:`${o.context.why??""} A blocker opened after this start's claim, so the claim was released and no ownership remains.`.trim()})}async function R8(e,t,n){let r=await x(R(process.cwd(),n.path)),i=W(r.schema);ta({...t,pause:!0},i);let o=i.open_status,s=await fi(e,To(t,{status:o},["assignee","pause"]),n),a=s.item.id,c=await Nl(a,"update",()=>na(a,t.force===!0,n,t));return{id:a,action:"pause_task",update:s,release:c}}async function I8(e,t,n,r){let i=await bs(e,t,n,r),o=i.item.id,s=await Nl(o,"close",()=>na(o,n.force===!0,r,n));return{id:o,action:"close_task",close:i,release:s}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="62b04ebf-f842-5a88-8817-ed9b17350034")}catch{}})();import hi from"node:crypto";import{cp as bk,lstat as eP,mkdir as yn,readFile as sr,readdir as Pl,rename as Ek,rm as jl,writeFile as ra}from"node:fs/promises";import q from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="66cb8c82-3760-5628-a1de-69e417cf0292")}catch{}})();var Tk="https://schema.unbrained.dev/pm/workspace-snapshot/v1",B8=["create","list","inspect","restore","delete"],Ck=q.join("runtime","workspace-snapshots"),tP=new Set(["checkpoints","locks","runtime","search","transactions"]),nP=/^[a-z0-9][a-z0-9._-]*$/,or="sdk-workspace-transaction",Ml={capacity:{code:"workspace_snapshot_storage_exhausted"},permission:{code:"workspace_snapshot_permission_denied"},resource:{code:"workspace_snapshot_resource_exhausted"}},Ak={renameEntry:Ek,removeEntry:async e=>{await jl(e,{recursive:!0,force:!0})}},Fl=class{lockPath;owner;intervalMs;timer;refresh;failure;constructor(t,n,r){this.lockPath=t,this.owner=n,this.intervalMs=Math.max(10,Math.floor(r*1e3/3))}start(){this.scheduleRenewal(),this.timer=setInterval(()=>{this.scheduleRenewal()},this.intervalMs),this.timer.unref()}async refreshNow(){this.scheduleRenewal(),await this.refresh,this.assertHealthy()}assertHealthy(){if(this.failure!==void 0)throw new Error("Workspace snapshot restore lost its writer lock",{cause:this.failure})}async stop(){this.timer!==void 0&&clearInterval(this.timer),await this.refresh,this.assertHealthy()}scheduleRenewal(){this.refresh!==void 0||this.failure!==void 0||(this.refresh=this.renew().catch(t=>{this.failure=t}).finally(()=>{this.refresh=void 0}))}async renew(){let t=await Gm(this.lockPath,or);if(t===null)throw new Error("Workspace writer lock cleanup gate stayed held");try{let n=JSON.parse(await sr(this.lockPath,"utf8"));if(typeof n!="object"||n===null||Array.isArray(n))throw new Error("Workspace writer lock has invalid structure");let r=n;if(r.id!==or||r.owner!==this.owner||r.pid!==process.pid)throw new Error("Workspace writer lock ownership changed");await je(this.lockPath,`${JSON.stringify({...r,created_at:new Date().toISOString()},null,2)}
|
|
12
|
+
`)}finally{await t()}}};async function xk(e,t=""){let n=await Pl(q.join(e,t),{withFileTypes:!0}),r=[];for(let i of n.sort((o,s)=>o.name.localeCompare(s.name))){if(t.length===0&&tP.has(i.name))continue;let o=q.posix.join(t.replaceAll(q.sep,"/"),i.name);if(i.isSymbolicLink())throw new Error(`Workspace snapshots reject symbolic links: ${o}`);if(i.isDirectory())r.push(...await xk(e,o));else if(i.isFile())r.push(o);else throw new Error(`Workspace snapshots reject unsupported filesystem entries: ${o}`)}return r}async function Rk(e){let t=await xk(e),n=hi.createHash("sha256"),r=[],i=0;for(let s of t){let a=await sr(q.join(e,s));r.push(a),i+=a.byteLength,n.update(s),n.update("\0"),n.update(String(a.byteLength)),n.update("\0"),n.update(a)}let o=n.digest("hex");return{manifest:{schema:Tk,fingerprint:o,files:t,bytes:i},contents:r}}function kk(e){return e===void 0||e.byteLength===0?0:e.toString("utf8").split(`
|
|
13
|
+
`).filter(t=>t.trim().length>0).length}async function rP(e,t){let n=new Map;for(let r=0;r<t.length;r+=32){let i=t.slice(r,r+32),o=await Promise.all(i.map(async s=>[s,await sr(q.join(e,s))]));for(let[s,a]of o)n.set(s,a)}return n}function Ul(e){if(!nP.test(e))throw new p("Snapshot names and fingerprints must use lowercase letters, digits, dots, underscores, or hyphens",m.USAGE,{code:"invalid_workspace_snapshot_target",required:"Provide a non-empty lowercase snapshot name or 64-character hexadecimal fingerprint.",why:"Snapshot targets are used as portable reference filenames and content identities.",examples:["pm workspace snapshot list --json","pm workspace snapshot inspect baseline --json"],nextSteps:["List available snapshots, then retry with a returned name or fingerprint."],recovery:{suggested_retry:"pm workspace snapshot list --json"}})}async function Ik(e,t){return Sr(`workspace_snapshot_${e}`,t,{codes:{capacity:Ml.capacity.code,permission:Ml.permission.code,resource:Ml.resource.code},why:"Snapshot create and restore copy authoritative tracker state before activation, so the stage needs capacity and write access up front.",nextSteps:["Reclaim rebuildable tracker cache space with pm gc, then retry."],suggestedRetry:"pm gc --json"})}function wn(e){return q.join(e,Ck)}function Ok(e){return new p(`Unknown workspace snapshot: ${e}`,m.NOT_FOUND,{code:"workspace_snapshot_not_found",required:"Use a snapshot name or fingerprint returned by snapshot list.",why:"The requested reference or immutable snapshot object does not exist.",examples:["pm workspace snapshot list --json"],nextSteps:["List available snapshots and retry with an exact target."],recovery:{suggested_retry:"pm workspace snapshot list --json"}})}async function Lk(e,t){try{return JSON.parse(await sr(e,"utf8"))}catch(n){throw G(n)?Ok(t):n}}async function Sk(e,t,n){try{await jl(e,{recursive:n})}catch(r){throw G(r)?Ok(t):r}}async function iP(e,t,n=Ak){try{return await n.renameEntry(e,t),!1}catch(r){if(!(r instanceof Error&&"code"in r&&(r.code==="EEXIST"||r.code==="ENOTEMPTY")))throw r;return await n.removeEntry(e),!0}}async function oP(e,t,n,r,i){await r.renameEntry(t,n);try{await r.renameEntry(e,t),await i?.()}catch(o){throw await r.renameEntry(n,t),await r.removeEntry(e),o}await r.removeEntry(n)}async function sP(e,t){return Ul(t),/^[a-f0-9]{64}$/.test(t)?t:(await Lk(q.join(wn(e),"refs",`${t}.json`),t)).fingerprint}async function aP(e,t={}){if(t.name!==void 0&&(Ul(t.name),/^[a-f0-9]{64}$/.test(t.name)))throw new p("Snapshot names must not be 64-character lowercase hexadecimal fingerprints",m.USAGE,{code:"workspace_snapshot_name_reserved_fingerprint",required:"Choose a human-readable reference name that cannot be mistaken for a content fingerprint.",why:"Exact 64-character hexadecimal values address immutable objects.",examples:["pm workspace snapshot create baseline --json"],nextSteps:["Retry with a shorter descriptive snapshot name."]});let{manifest:n,contents:r}=await Rk(e),i=wn(e),o=q.join(i,"objects",n.fingerprint),s=!1;try{s=(await eP(o)).isDirectory()}catch(a){if(!(a instanceof Error&&"code"in a&&G(a)))throw a}if(!s){let a=q.join(i,"objects",`.create-${process.pid}-${hi.randomUUID()}`);await Ik("create_object",async()=>{await yn(q.join(a,"files"),{recursive:!0});for(let[c,d]of n.files.entries()){let l=q.join(a,"files",d);await yn(q.dirname(l),{recursive:!0}),await ra(l,r[c])}await ra(q.join(a,"manifest.json"),`${JSON.stringify(n,null,2)}
|
|
14
|
+
`,"utf8"),await yn(q.dirname(o),{recursive:!0})}),s=await iP(a,o)}if(t.name!==void 0){let a={name:t.name,fingerprint:n.fingerprint},c=q.join(i,"refs");await yn(c,{recursive:!0});let d=q.join(c,`.ref-${process.pid}-${hi.randomUUID()}`);await ra(d,`${JSON.stringify(a,null,2)}
|
|
15
|
+
`,"utf8"),await Ek(d,q.join(c,`${t.name}.json`))}return{manifest:n,...t.name===void 0?{}:{name:t.name},deduplicated:s}}async function Gl(e,t){let n=await sP(e,t),r=await Lk(q.join(wn(e),"objects",n,"manifest.json"),t);if(r.schema!==Tk||r.fingerprint!==n)throw new p(`Snapshot manifest identity mismatch: ${t}`,m.CONFLICT,{code:"workspace_snapshot_manifest_mismatch",required:"Use an intact snapshot whose manifest fingerprint matches its object path.",why:"Content identity must be verified before snapshot data is trusted.",examples:["pm workspace snapshot list --json"],nextSteps:["Inspect or recreate the snapshot before restoring it."]});return r}async function cP(e){let t=wn(e),n=await Pl(q.join(t,"objects")).catch(i=>{if(i instanceof Error&&"code"in i&&G(i))return[];throw i}),r=await Pl(q.join(t,"refs")).catch(i=>{if(i instanceof Error&&"code"in i&&G(i))return[];throw i});return{objects:await Promise.all(n.filter(i=>/^[a-f0-9]{64}$/.test(i)).sort().map(i=>Gl(e,i))),references:await Promise.all(r.filter(i=>i.endsWith(".json")).sort().map(async i=>JSON.parse(await sr(q.join(t,"refs",i),"utf8"))))}}async function dP(e,t){let n=await Gl(e,t),{manifest:r,contents:i}=await Rk(e),o=new Map(r.files.map((u,_)=>[u,i[_]])),s=await rP(q.join(wn(e),"objects",n.fingerprint,"files"),n.files),a=new Set(r.files),c=new Set(n.files),d=new Set([...a,...c]);for(let u of d){let _=o.get(u),h=s.get(u);_!==void 0&&h!==void 0&&_.equals(h)&&d.delete(u)}let l=r.files.filter(u=>u.startsWith("history/")&&u.endsWith(".jsonl")).map(u=>{let _=kk(o.get(u)),h=kk(s.get(u));return{path:u,current_entries:_,target_entries:h,removed_entries:Math.max(0,_-h)}}).filter(u=>u.removed_entries>0).sort((u,_)=>u.path.localeCompare(_.path));return{target_fingerprint:n.fingerprint,current_fingerprint:r.fingerprint,changed_file_count:d.size,removed_file_count:[...a].filter(u=>!c.has(u)).length,added_file_count:[...c].filter(u=>!a.has(u)).length,removed_item_count:[...a].filter(u=>u.endsWith(".toon")&&!c.has(u)).length,affected_history_stream_count:l.length,removed_history_entry_count:l.reduce((u,_)=>u+_.removed_entries,0),affected_history_streams:l,changes_authoritative_state:r.fingerprint!==n.fingerprint}}async function lP(e,t,n={}){if(n.force!==!0)throw new p("Workspace snapshot restore requires explicit force confirmation; inspect the impact with planWorkspaceSnapshotRestore or pm workspace snapshot restore <target> --dry-run, then retry with force",m.USAGE,{code:"workspace_snapshot_force_required",required:"Preview the destructive impact, then explicitly confirm the restore.",why:"A restore replaces the complete authoritative tracker state.",examples:[`pm workspace snapshot restore ${t} --dry-run --json`,`pm workspace snapshot restore ${t} --force --json`],nextSteps:["Review the dry-run counts before retrying with --force."],recovery:{suggested_retry:`pm workspace snapshot restore ${t} --dry-run --json`}});let r=n.author?.trim()||"pm-sdk",i=n.lockTtlSeconds??60,o=n.lockWaitMs??5e3,s=await to(e,or,i,r,!1,!1,o),a=s.release,c=new Fl(ji(e,or),r,i);c.start(),await c.refreshNow();let d,l=!1,u=!1;try{let _=await dP(e,t),h=await Gl(e,t),f=await aP(e),g=h.fingerprint,y=wn(e),w=q.join(y,"objects",g,"files"),v=q.dirname(e),k=q.basename(e);d=q.join(v,`.${k}.restore-${hi.randomUUID()}`);let S=q.join(v,`.${k}.backup-${hi.randomUUID()}`);await Ik("restore_stage",async()=>{await yn(d,{recursive:!0}),await bk(w,d,{recursive:!0,force:!1}),await yn(q.join(d,"runtime"),{recursive:!0}),await bk(y,q.join(d,Ck),{recursive:!0,force:!1})});let b=await Rn({pmRoot:d,op:"workspace_snapshot_restore",author:r,message:n.message??`Restore workspace snapshot ${g}; recovery snapshot ${f.manifest.fingerprint}`,context:{target_fingerprint:g,pre_restore_fingerprint:f.manifest.fingerprint,changed_file_count:_.changed_file_count,removed_file_count:_.removed_file_count,removed_item_count:_.removed_item_count,affected_history_stream_count:_.affected_history_stream_count,removed_history_entry_count:_.removed_history_entry_count},lockTtlSeconds:i,lockWaitMs:o}),A=q.relative(d,b.historyPath).replaceAll("\\","/");await c.stop(),u=!0;let E=ji(d,or),C=d;return await s.fence(async()=>{await yn(q.dirname(E),{recursive:!0}),await ra(E,await sr(ji(e,or)),{flag:"wx"}),l=!0,await oP(C,e,S,Ak,async()=>{c.start(),u=!1,await c.refreshNow()})}),await c.stop(),u=!0,{manifest:h,plan:_,recovery_fingerprint:f.manifest.fingerprint,audit_history_path:A,audit_operation:"workspace_snapshot_restore"}}catch(_){throw d!==void 0&&!l&&await Promise.allSettled([jl(d,{recursive:!0,force:!0})]),_}finally{try{u||await c.stop()}catch{}finally{await a()}}}async function H8(e,t){return(await lP(e,t,{force:!0,message:"Restore requested through the compatibility SDK signature"})).manifest}async function V8(e,t){Ul(t);let n=wn(e);if(!/^[a-f0-9]{64}$/.test(t))return await Sk(q.join(n,"refs",`${t}.json`),t,!1),{deleted:"reference",target:t};let{references:r}=await cP(e);if(r.some(i=>i.fingerprint===t))throw new Error(`Snapshot object ${t} is still referenced`);return await Sk(q.join(n,"objects",t),t,!0),{deleted:"object",target:t}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="42dc4379-016c-5b5d-a15b-37fe3a80dab5")}catch{}})();function Dk(e){return e.invalidEvidenceCount>0?"merge_evidence_invalid":e.historyEvidenceValid?e.pendingDecisionCount>0||e.losslessCount>0?"merge_reconciliation_required":e.driftedItemCount>0?"history_repair_required":e.fence.status!=="ok"||e.drivers===null||e.drivers.status!=="ok"?"merge_fence_unprepared":"ready":"history_evidence_invalid"}function $k(e,t,n=process.platform){let r=["--pm-path",t];return e==="merge_evidence_invalid"?L([...r,"merge","report"],n):e==="history_evidence_invalid"?L([...r,"validate","--check-history-drift","--full"],n):e==="merge_reconciliation_required"?L([...r,"merge","reconcile"],n):e==="history_repair_required"?L([...r,"history-repair","--all"],n):e==="merge_fence_unprepared"?L([...r,"merge","install"],n):null}function Nk(e){let t=Array.isArray(e.drifted_items)?e.drifted_items.filter(n=>typeof n=="string"):[];return{evidence_valid:Array.isArray(e.drifted_items)&&e.drifted_items.every(n=>typeof n=="string")&&typeof e.drifted_items_count=="number"&&Number.isInteger(e.drifted_items_count)&&e.drifted_items_count>=0&&typeof e.drifted_items_truncated=="boolean"&&typeof e.counts=="object"&&e.counts!==null&&!Array.isArray(e.counts),drifted_item_count:typeof e.drifted_items_count=="number"?e.drifted_items_count:t.length,drifted_item_ids:t,drifted_item_ids_truncated:e.drifted_items_truncated===!0,counts:typeof e.counts=="object"&&e.counts!==null?e.counts:{}}}async function a6(e){let t=R(process.cwd(),e.path);await j(t);let n=await x(t),r=P(n,N()),i=[],o=await ls({includeBody:!0,pmRoot:t,settings:n,typeToFolder:r.type_to_folder,warnings:i}),s=await Dt(t),[a,c,d,l]=await Promise.all([$n(t,Dn(n)),s===null?Promise.resolve(null):Nn(s),Mn(s??t,{includeLossless:!0,pmRoot:t}),us(t,o,!1)]),{pendingDecisions:u,lossless:_}=Pn(d.receipts),h=[...new Set(u.map(w=>w.item_id))].sort((w,v)=>w.localeCompare(v)),f=l.check.details,g=Nk(f),y=Dk({invalidEvidenceCount:d.invalid_evidence_count,pendingDecisionCount:u.length,losslessCount:_.length,historyEvidenceValid:g.evidence_valid,driftedItemCount:g.drifted_item_count,fence:a,drivers:c});return{ok:y==="ready",state:y,merge_fence:{committed:a,clone_local_drivers:c},merge_receipts:{pending_decision_count:u.length,pending_item_ids:h.slice(0,25),pending_item_ids_truncated:h.length>25,lossless_count:_.length,invalid_evidence_count:d.invalid_evidence_count},history_drift:g,next_action:{command:$k(y,t),reason:y},warnings:[...new Set(i)].sort((w,v)=>w.localeCompare(v)),generated_at:I()}}function c6(e){let t=e.next_action.command??"none";return[`workspace_position: ${e.state}`,`merge_fence: ${e.merge_fence.committed.status}`,`clone_local_drivers: ${e.merge_fence.clone_local_drivers?.status??"unavailable"}`,`pending_merge_decisions: ${e.merge_receipts.pending_decision_count}`,`history_drifted_items: ${e.history_drift.drifted_item_count}`,`next_action: ${t}`].join(`
|
|
16
|
+
`)}var d6={commandForWorkspacePositionState:$k,normalizeWorkspaceHistoryDrift:Nk,selectWorkspacePositionState:Dk};import{createHash as mP}from"node:crypto";import{execFile as pP}from"node:child_process";import Fk from"node:path";import{promisify as _P}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ed03b6c8-6275-55a6-8e5f-4f27a23d6696")}catch{}})();var Mk=1;function uP(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.id=="string"&&typeof t.metric=="string"&&typeof t.value=="number"&&Number.isFinite(t.value)&&["higher","lower","target"].includes(String(t.direction))&&typeof t.observed_at=="string"&&typeof t.revision=="string"&&["caller","git","unversioned"].includes(String(t.revision_source))&&typeof t.author=="string"?t.direction!=="target"||typeof t.threshold=="number"&&Number.isFinite(t.threshold):!1}function ql(e){if(e===null)return{format_version:Mk,observations:[]};let t;try{t=JSON.parse(e)}catch{throw new p("Improvement ledger contains invalid JSON.",m.GENERIC_FAILURE,{code:"invalid_improvement_ledger"})}if(typeof t!="object"||t===null||Array.isArray(t)||t.format_version!==Mk||!Array.isArray(t.observations))throw new p("Improvement ledger has an unsupported shape or format version.",m.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});let n=t.observations;for(let r of n)if(!uP(r))throw new p("Improvement ledger contains an invalid observation.",m.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});return t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e7ad59ce-5111-5649-9025-340183539b4a")}catch{}})();var fP=_P(pP),hP=50,Pk=1e3,gP=/^[a-z0-9](?:[a-z0-9._/-]{0,126}[a-z0-9])?$/u;function jk(e){let t=e.trim().toLowerCase();if(!gP.test(t))throw new p(`Invalid metric name "${e}"; use 1-128 lowercase letters, digits, dots, slashes, underscores, or hyphens.`,m.USAGE,{code:"invalid_improvement_metric"});return t}function yP(e){let t=e??"lower";if(!["higher","lower","target"].includes(t))throw new p("Improvement direction must be higher, lower, or target.",m.USAGE,{code:"invalid_improvement_observation"});return t}function gi(e,t){let n=e?.trim();if(n){if(n.length>256)throw new p(`${t} must not exceed 256 characters.`,m.USAGE,{code:"invalid_improvement_observation"});return n}}function wP(e){let t=e??hP;if(!Number.isSafeInteger(t)||t<0||t>Pk)throw new p(`Improvement observation limit must be an integer from 0 to ${Pk}.`,m.USAGE,{code:"invalid_improvement_observation_limit"});return t}function Uk(e,t){let n=Date.parse(e);if(!Number.isFinite(n))throw new p(`${t} must be an ISO timestamp.`,m.USAGE,{code:"invalid_improvement_observation_timestamp"});return new Date(n).toISOString()}async function vP(e,t,n){if(!Number.isFinite(n.value))throw new p("Improvement observation value must be finite.",m.USAGE,{code:"invalid_improvement_observation"});let r=jk(n.metric),i=yP(n.direction);if(n.threshold!==void 0&&!Number.isFinite(n.threshold)||i==="target"&&n.threshold===void 0)throw new p("Target-directed observations require a finite threshold.",m.USAGE,{code:"invalid_improvement_observation"});let o=await kP(e,n.revision),s=gi(n.source,"source"),a=gi(n.itemId,"itemId"),c=gi(n.unit,"unit"),d=gi(n.idempotencyKey,"idempotencyKey")??(o.revision_source==="unversioned"?void 0:[o.revision,r,s??"manual",a??"workspace"].join(":")),l={metric:r,value:n.value,direction:i,...c===void 0?{}:{unit:c},...n.threshold===void 0?{}:{threshold:n.threshold},observed_at:Uk(n.observedAt??I(),"observedAt"),...o,author:U(n.author,t.author_default),...a===void 0?{}:{item_id:a},...s===void 0?{}:{source:s},...d===void 0?{}:{idempotency_key:d}};return{id:mP("sha256").update(Z(l)).digest("hex").slice(0,24),...l}}function bP(e,t){let n=t.idempotency_key?e.observations.find(i=>i.idempotency_key===t.idempotency_key):e.observations.find(i=>i.id===t.id);if(n){if(n.metric!==t.metric||n.value!==t.value||n.direction!==t.direction||n.threshold!==t.threshold||n.unit!==t.unit)throw new p(`Improvement observation retry key already records a different value for ${t.metric}.`,m.CONFLICT,{code:"improvement_observation_conflict"});return n}let r=e.observations.find(i=>i.metric===t.metric);if(r&&(r.direction!==t.direction||r.unit!==t.unit||t.direction==="target"&&r.threshold!==t.threshold))throw new p(`Metric ${t.metric} is already declared with direction ${r.direction} and unit ${r.unit??"<none>"}.`,m.CONFLICT,{code:"improvement_metric_contract_conflict"})}async function kP(e,t){let n=gi(t,"revision");if(n)return{revision:n,revision_source:"caller"};try{return{revision:(await fP("git",["rev-parse","--verify","HEAD^{commit}"],{cwd:lt(e),encoding:"utf8",timeout:5e3})).stdout.trim(),revision_source:"git"}}catch{}return{revision:"unversioned",revision_source:"unversioned"}}function SP(e){let t=e[0],n=e[e.length-1],r=n.value-t.value,i=n.direction==="higher"?r>0:n.direction==="lower"?r<0:Math.abs(n.value-n.threshold)<Math.abs(t.value-t.threshold);return{metric:n.metric,direction:n.direction,baseline:t,latest:n,delta:r,improved:i,sample_count:e.length}}async function Gk(e,t={}){let n=R(process.cwd(),t.path);await j(n);let r=await x(n),i=await vP(n,r,e),o=Fk.join(n,"improvement-ledger.json"),s=await In({pmRoot:n,filePath:o,op:"improvement_observe",author:i.author,lockTtlSeconds:r.locks.ttl_seconds,lockWaitMs:r.locks.wait_ms,message:e.message??`Record ${i.metric}=${String(e.value)} improvement observation`,mutate:a=>{let c=ql(a),d=bP(c,i);return d?{raw:a,result:d}:(c.observations.push(i),c.observations.sort((l,u)=>l.observed_at.localeCompare(u.observed_at)||l.metric.localeCompare(u.metric)||l.id.localeCompare(u.id)),{raw:`${Z(c)}
|
|
17
|
+
`,result:i})}});return{changed:s.changed,observation:s.result,ledger_path:"improvement-ledger.json"}}async function qk(e={}){let t=R(e.cwd??process.cwd(),e.pmRoot);await j(t);let n=e.metric===void 0?void 0:jk(e.metric),r=e.since===void 0?void 0:Uk(e.since,"since"),i=wP(e.limit),o=ql(await Q(Fk.join(t,"improvement-ledger.json"))).observations.filter(a=>(n===void 0||a.metric===n)&&(e.itemId===void 0||a.item_id===e.itemId)&&(r===void 0||a.observed_at>=r)),s=new Map;for(let a of o){let c=s.get(a.metric)??[];c.push(a),s.set(a.metric,c)}return{observations:[...o].reverse().slice(0,i),total:o.length,truncated:o.length>i,trends:[...s].map(([,a])=>SP(a)).sort((a,c)=>a.metric.localeCompare(c.metric)),source:"audited_workspace_singleton"}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="28dd16ac-2e3b-55ed-98a6-db5f6786cbd7")}catch{}})();function EP(e){return e.agent_episode!==void 0?{id:e.agent_episode.id,source:"declared"}:{id:e.agent_instance?`inferred:instance:${e.agent_instance}`:`inferred:author:${e.author}:${e.ts.slice(0,13)}`,source:"inferred"}}function TP(e,t,n){let r=t,i=new Set([e.id]);for(;r!==void 0&&!i.has(r.id);)i.add(r.id),r=r.parent_id?n.get(r.parent_id):void 0;return r===void 0}function CP(e){let t=[e];for(;t.length>0;){let n=t.pop();n.sort((r,i)=>r.entries[0].ts.localeCompare(i.entries[0].ts)||r.id.localeCompare(i.id)),t.push(...n.map(r=>r.children))}}function Kk(e=vr,t=wr){return t.map(n=>{let r=e.filter(i=>((n==="model"?i.model_environment_keys:i.provenance_environment_keys?.[n])?.length??0)>0||i.provenance_resolvers?.[n]!==void 0).map(i=>i.harness).sort();return{dimension:n,harnesses:r,covered:r.length>0}})}function O6(e,t=1){let n=new Map;for(let r of e){if(!r.agent_harness)continue;let i=n.get(r.agent_harness)??{harness:r.agent_harness,entries:0,observed:0,unavailable:0,legacy_missing:0};i.entries+=1,r.agent_model||r.agent_provenance?.model&&r.agent_provenance.model.value.length>0?i.observed+=1:r.agent_provenance?.model===null?i.unavailable+=1:i.legacy_missing+=1,n.set(r.agent_harness,i)}return[...n.values()].map(r=>{let i=r.observed+r.unavailable;return{...r,coverage:i===0?null:r.observed/i,inert:i>=t&&r.observed===0}}).sort((r,i)=>r.harness.localeCompare(i.harness))}function Wk(e,t=wr,n=1){let r=new Map;for(let i of e)if(i.agent_harness)for(let o of t){let s=`${i.agent_harness}\0${o}`,a=r.get(s)??{harness:i.agent_harness,dimension:o,entries:0,observed:0,unavailable:0,legacy_missing:0};a.entries+=1;let c=i.agent_provenance?.[o];c!=null&&c.value.length>0?a.observed+=1:c===null?a.unavailable+=1:a.legacy_missing+=1,r.set(s,a)}return[...r.values()].map(i=>{let o=i.observed+i.unavailable;return{...i,coverage:o===0?null:i.observed/o,inert:o>=n&&i.observed===0}}).sort((i,o)=>i.harness.localeCompare(o.harness)||i.dimension.localeCompare(o.dimension))}function L6(e,t={}){let n=t.minimumCoverage??.8,r=t.minimumEntries??5;if(![Number.isFinite(n),n>=0,n<=1].every(Boolean))throw new RangeError("Semantic attribution minimum coverage must be from 0 to 1.");if(![Number.isSafeInteger(r),r>=1].every(Boolean))throw new RangeError("Semantic attribution minimum entries must be a positive integer.");let i=new Map;for(let c of e)if(c.agent_harness)for(let d of["role","topic"]){let l=`${c.agent_harness}\0${d}`,u=i.get(l)??{harness:c.agent_harness,dimension:d,entries:0,observed:0,by_source:{},coverage:0};u.entries+=1;let _=c.agent_provenance?.[d];_?.value&&(u.observed+=1,u.by_source[_.source]=(u.by_source[_.source]??0)+1),i.set(l,u)}let o=[...i.values()].map(c=>({...c,coverage:c.observed/c.entries,by_source:Object.fromEntries(Object.entries(c.by_source).sort(([d],[l])=>d.localeCompare(l)))})).sort((c,d)=>c.harness.localeCompare(d.harness)||c.dimension.localeCompare(d.dimension)),s=o.filter(c=>c.entries>=r),a=s.filter(c=>c.coverage<n).map(c=>`${c.harness}:${c.dimension}`);return{passed:s.length>0&&a.length===0,minimum_coverage:n,minimum_entries:r,rows:o,failures:a}}function D6(e){let t=[...e].sort((o,s)=>o.ts.localeCompare(s.ts)||o.author.localeCompare(s.author)||o.op.localeCompare(s.op)||o.before_hash.localeCompare(s.before_hash)||o.after_hash.localeCompare(s.after_hash)),n=new Map,r=new Map;for(let o of t){let s=o.agent_episode,a=EP(o),c=`${a.source}:${a.id}`,d=n.get(c);if(d){d.entries.push(o);continue}let l={id:a.id,...s?.label===void 0?{}:{label:s.label},...s?.parent_id===void 0?{}:{parent_id:s.parent_id},source:a.source,entries:[o],children:[]};n.set(c,l),s!==void 0&&r.set(a.id,l)}let i=[];for(let o of n.values()){let s=o.parent_id?r.get(o.parent_id):void 0;s&&TP(o,s,r)?s.children.push(o):i.push(o)}return CP(i),i}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6b51fdd9-9923-53c5-a798-41c15fd847a0")}catch{}})();var AP=1e4,zk=1e5,xP=1e3,RP=30,IP=["append","comment","docs","file","learning","note","test_run"];function OP(e){let t=e??AP;if(!Number.isSafeInteger(t)||t<1||t>zk)throw new p(`History analytics event limit must be an integer from 1 to ${zk}.`,m.USAGE,{code:"invalid_history_analytics_limit"});return t}function Bk(e){let t=e??5;if(!Number.isSafeInteger(t)||t<1||t>1e4)throw new p("History analytics minimum sample must be an integer from 1 to 10000.",m.USAGE,{code:"invalid_history_analytics_minimum_sample"});return t}function LP(e){let t=e?.trim();if(!t)return new Date(Date.now()-RP*864e5).toISOString();let n=/^-(\d+)([dh])$/u.exec(t);if(n){let i=Number(n[1]),o=n[2]==="d"?864e5:36e5;if(!Number.isSafeInteger(i)||i<1)throw new p("History analytics --since duration must be positive.",m.USAGE,{code:"invalid_history_analytics_since"});return new Date(Date.now()-i*o).toISOString()}let r=Date.parse(t);if(!Number.isFinite(r))throw new p("History analytics --since must be an ISO timestamp or negative duration such as -30d.",m.USAGE,{code:"invalid_history_analytics_since"});return new Date(r).toISOString()}async function ia(e,t){let n=OP(t.eventLimit),r=LP(t.since),i=[],o=r,s=!1;for(;i.length<n;){let a=await Oh({pmRoot:e,since:o,limit:Math.min(xP,n-i.length),full:!0}),c=a.events.map(d=>({item_id:d.item_id,entry:d.entry}));if(i.push(...c),s=a.has_more,o=a.next_cursor,!a.has_more)break}return{events:i,receipt:{since:r,events:i.length,truncated:s,...s?{next_cursor:o}:{},source:"history_event_index"}}}function DP(e,t){return t==="harness"?e.agent_harness:t==="author_source"?e.author_source:e.agent_model??e.agent_provenance?.model?.value}function $P(e){for(let t=e.patch.length-1;t>=0;t-=1){let n=e.patch[t];if(n.path==="/metadata/status"&&"value"in n&&typeof n.value=="string")return n.value}}function NP(e){return IP.some(t=>e.startsWith(t))}function Hk(e,t){let n=e.get(t);if(n)return n;let r={events:0,stateEvents:0,annotationEvents:0,closes:0,reopens:0,defectEscapes:0};return e.set(t,r),r}function MP(e,t,n){let r=new Map,i=new Map,o=new Map;for(let s of t){let a=DP(s.entry,e),c=$P(s.entry),d=i.get(s.item_id)===!0,l=c===void 0?d:n.has(c);if(c!==void 0&&i.set(s.item_id,l),!a)continue;let u=Hk(r,a);u.events+=1,NP(s.entry.op)?u.annotationEvents+=1:u.stateEvents+=1,c!==void 0&&!d&&l?(u.closes+=1,o.set(s.item_id,a)):c!==void 0&&d&&!l&&(u.reopens+=1)}return{buckets:r,lastCloseValue:o}}function PP(e,t,n){for(let r of n){if(r.type!=="Issue")continue;let i=new Set((r.dependencies??[]).filter(o=>o.kind==="discovered_from").map(o=>o.id));for(let o of i){let s=t.get(o);s&&(Hk(e,s).defectEscapes+=1)}}}function FP(e,t,n,r){let i=t.closes>=n?"available":"insufficient";return{value:e,events:t.events,state_events:t.stateEvents,annotation_events:t.annotationEvents,closes:t.closes,reopens:t.reopens,defect_escapes:t.defectEscapes,throughput_per_day:i==="available"?t.closes/r:null,rework_rate:i==="available"?t.reopens/t.closes:null,defect_escape_rate:i==="available"?t.defectEscapes/t.closes:null,sample_status:i}}function jP(e,t,n,r,i,o){let{buckets:s,lastCloseValue:a}=MP(e,t,r);return PP(s,a,n),{dimension:e,status:s.size===0?"unavailable":"available",rows:[...s].map(([c,d])=>FP(c,d,i,o)).sort((c,d)=>d.events-c.events||c.value.localeCompare(d.value))}}function UP(e,t){let n=e[0]?.entry.ts??t,r=e[e.length-1]?.entry.ts??n,i=Date.parse(n),o=Date.parse(r);return!Number.isFinite(i)||!Number.isFinite(o)?1:Math.max(1,(o-i)/864e5)}function GP(e,t,n){let r=Kk(t),i=Wk(e,wr,n),o=i.filter(a=>a.inert).map(a=>({harness:a.harness,dimension:a.dimension,explicit_samples:a.observed+a.unavailable})),s=r.filter(a=>!a.covered).map(a=>a.dimension);return{descriptors:r,observations:i,inert:o,undeclared:s,warnings:[...o.map(a=>`provenance_dimension_inert:${a.harness}:${a.dimension}:${String(a.explicit_samples)}`),...s.map(a=>`provenance_dimension_undeclared:${a}`)]}}async function U6(e,t=vr,n={}){return Kl(await ia(e,n),t,n)}function Kl(e,t=vr,n={}){let r=Bk(n.minimumSample);return{...GP(e.events.map(i=>i.entry),t,r),window:e.receipt}}async function G6(e,t,n,r={}){return Wl(await ia(e,r),t,n,r)}function Wl(e,t,n,r={}){let i=Bk(r.minimumSample),o=UP(e.events,e.receipt.since);return{dimensions:["harness","model","author_source"].map(s=>jP(s,e.events,t,n,i,o)),minimum_sample:i,policy:"observational_only_not_for_authorization_or_routing",window:e.receipt}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3e70310d-fc4f-5ea9-b9fb-7c519035301b")}catch{}})();var qP=32;function KP(e){let t=[];for(let n of e??[]){let r=[];for(let i of n.split(",")){let o=i.slice(0,i.indexOf("=")).trim();r.length>0&&o!=="unit"&&o!=="threshold"&&(t.push(r.join(",")),r=[]),r.push(i)}t.push(r.join(","))}return t}function yi(e,t){let n=KP(e).map(r=>{let[i,...o]=r.split(","),s=i.indexOf("="),a=i.slice(0,s).trim(),c=i.slice(s+1).trim(),d=Number(c);if(s<=0||a.length===0||c.length===0||!Number.isFinite(d))throw new p(`Invalid --measure "${r}"; expected name=value[,unit=...][,threshold=...]`,m.USAGE);let l,u;for(let _ of o){let h=_.indexOf("="),f=_.slice(0,h).trim(),g=_.slice(h+1).trim();if(f==="unit"&&g.length>0)l=g;else if(f==="threshold"&&g.length>0&&Number.isFinite(Number(g)))u=Number(g);else throw new p(`Invalid --measure attribute "${_}"`,m.USAGE)}return{name:a,value:d,unit:l,threshold:u,recorded_at:t}});return[...new Map(n.map(r=>[r.name,r])).values()].sort((r,i)=>r.name.localeCompare(i.name)).slice(0,qP)}function Vk(e,t,n){return e.flatMap(r=>(r.measurements??[]).filter(i=>i.name===t&&i.value<n).map(i=>({...i,run_id:r.run_id})))}function Yk(e,t){let n=e.flatMap(o=>o.measurements??[]).filter(o=>o.name===t).sort((o,s)=>s.recorded_at.localeCompare(o.recorded_at)),r=n[0],i=n[1];return{name:t,latest:r?.value??null,previous:i?.value??null,delta:r!==void 0&&i!==void 0?r.value-i.value:null,unit:r?.unit}}import zP from"node:fs/promises";import Xk from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9cd23db4-2411-5c95-a6a0-fa30dd3a9a18")}catch{}})();function oa(e,t,n,r,i,o="min"){let s=i==="min"?e-t:t-e,a=o==="min"?n.localeCompare(r??n):(r??n).localeCompare(n);return s<0||s===0&&r!==null&&a<0}function WP(e,t){let n=Buffer.byteLength(t,"utf8"),r=0,i=null,o=null,s=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY;for(let c of t.split(/\r?\n/)){let d=c.trim();if(d==="")continue;r+=1;let l;try{l=JSON.parse(d)}catch{continue}if(l===null||typeof l!="object"||!("ts"in l)||typeof l.ts!="string")continue;let u=l.ts,_=Date.parse(u);Number.isNaN(_)||(oa(_,s,u,i,"min")&&(s=_,i=u),oa(_,a,u,o,"max","max")&&(a=_,o=u))}return{id:e,bytes:n,lines:r,oldest_ts:i,newest_ts:o}}function Jk(e,t){let n=t?.topN??5,r=Math.max(0,Math.floor(n)),i=e.map(({id:h,raw:f})=>WP(h,f)),o=0,s=0,a=null,c=null,d=Number.POSITIVE_INFINITY,l=Number.NEGATIVE_INFINITY;for(let h of i){if(o+=h.lines,s+=h.bytes,h.oldest_ts!==null){let f=Date.parse(h.oldest_ts);oa(f,d,h.id,a?.id??null,"min")&&(d=f,a={id:h.id,ts:h.oldest_ts})}if(h.newest_ts!==null){let f=Date.parse(h.newest_ts);oa(f,l,h.id,c?.id??null,"max")&&(l=f,c={id:h.id,ts:h.newest_ts})}}let u=r===0?[]:[...i].sort((h,f)=>f.bytes-h.bytes||h.id.localeCompare(f.id)).slice(0,r),_=r===0?[]:[...i].sort((h,f)=>f.lines-h.lines||h.id.localeCompare(f.id)).slice(0,r);return{total_streams:e.length,total_lines:o,total_bytes:s,largest_by_bytes:u,deepest_by_lines:_,oldest_entry:a,newest_entry:c}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b9d089ef-bca9-547f-a860-4002ec181cd0")}catch{}})();function BP(e){return e.reduce((t,n)=>(t[n]=0,t),{})}function HP(e,t,n,r,i){let o=Lr(e,"type",r),s=new Set(o.rows.map(u=>u.key)),a=t.filter(u=>!s.has(u)),c=(i?[...o.rows,...a.map(u=>({label:u,key:u,total:0,buckets:{open:0,in_progress:0,blocked:0,draft:0,closed:0,canceled:0,other:0}}))]:o.rows).map(u=>({type:u.key??u.label,total:u.total,open:u.buckets.open,in_progress:u.buckets.in_progress,blocked:u.buckets.blocked,draft:u.buckets.draft,closed:u.buckets.closed,canceled:u.buckets.canceled,other:u.buckets.other})),d=BP([...n]);for(let u of e)d[u.status]+=1;let l=Object.fromEntries(Object.entries(d).filter(([,u])=>i||u>0));return{byType:c,byStatus:l,omitted:i?0:a.length+Object.values(d).filter(u=>u===0).length}}function VP(e){return e.trim().length===0?0:e.split(/\r?\n/u).filter(t=>t.trim().length>0).length}async function YP(e){let t=Xk.join(e,"history");if(!await ie(t))return[];await We({path:t,scope:"project"});let n=(await zP.readdir(t)).filter(i=>i.endsWith(".jsonl")).sort((i,o)=>i.localeCompare(o)),r=[];for(let i of n){let o=Xk.join(t,i),s=await Q(o);s!==null&&(await We({path:o,scope:"project"}),r.push({id:i.slice(0,-6),raw:s}))}return r}async function JP(e,t){let n=[],r=I();for(let i of yi(t.observe,r))n.push(await Gk({metric:i.name,value:i.value,direction:t.direction,unit:i.unit,threshold:i.threshold,source:t.measurementSource,itemId:t.measurementItem,revision:t.measurementRevision,observedAt:r,author:t.author,message:t.message},e));return n}function XP(e,t,n){let r={};return t.byAssignee&&(r.assignee=Lr(e,"assignee",n)),t.byTag&&(r.tag=Lr(e,"tag",n,{tagPrefix:t.tagPrefix})),t.byPriority&&(r.priority=Lr(e,"priority",n)),r}async function QP(e,t,n,r,i){let o={since:i.since,eventLimit:i.eventLimit,minimumSample:i.minimumSample},s=i.provenanceCoverage||i.fleetAttribution?await ia(e,o):void 0;return{provenanceCoverage:i.provenanceCoverage&&s?Kl(s,n.agent_identity?.harness_signals,o):void 0,fleetAttribution:i.fleetAttribution&&s?Wl(s,t,r,o):void 0}}function ZP(e,t,n,r,i){let o=Object.keys(i.breakdowns).length>0;return{totals:e,by_type:t,by_status:n,omitted_zero_buckets:r,...i.metadataCoverage?{metadata_coverage:i.metadataCoverage}:{},...o?{breakdowns:i.breakdowns}:{},...i.storage?{storage:i.storage}:{},...i.fieldUtilization?{field_utilization:i.fieldUtilization}:{},...i.improvementLedger?{improvement_ledger:i.improvementLedger}:{},...i.recordedObservations.length>0?{recorded_observations:i.recordedObservations}:{},...i.provenanceCoverage?{provenance_coverage:i.provenanceCoverage}:{},...i.fleetAttribution?{fleet_attribution:i.fleetAttribution}:{},generated_at:I()}}async function l9(e,t={}){let n=R(process.cwd(),e.path);await j(n);let r=await x(n),i=await JP(e,t),o=P(r,N()),s=W(r.schema),a=t.fieldUtilization?await gt(n,r.item_format,o.type_to_folder,void 0,r.schema):await Te(n,r.item_format,o.type_to_folder,void 0,r.schema);await so({pmRoot:n,settings:r,itemIds:a.map(k=>k.id),commandLabel:"stats"});let c=oh(s),d=HP(a,o.types,s.definitions.map(k=>k.id),c,t.includeEmpty===!0),l=await YP(n),u=0;for(let k of l)u+=VP(k.raw);let _=t.storage?Jk(l):void 0,h=t.metadataCoverage?sh(a,c):void 0,f=XP(a,t,c),g=t.fieldUtilization?ah(a):void 0,y=t.measurements===!0||i.length>0?await qk({pmRoot:n,metric:t.metric,itemId:t.measurementItem,limit:t.measurementLimit}):void 0,{provenanceCoverage:w,fleetAttribution:v}=await QP(n,a,r,s.terminal_statuses,t);return ZP({items:a.length,history_streams:l.length,history_entries:u},d.byType,d.byStatus,d.omitted,{metadataCoverage:h,breakdowns:f,storage:_,fieldUtilization:g,improvementLedger:y,recordedObservations:i,provenanceCoverage:w,fleetAttribution:v})}import e1 from"node:fs/promises";import Tt from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bc3145a3-5949-5c61-b275-a5376881b91f")}catch{}})();var n0=Tt.join("runtime","telemetry","state.json"),wi=Tt.join("runtime","telemetry"),t1=20,Hl=Kt.filter(e=>e.lifecycle==="deprecated"),Qk=["status","flush","stats","clear"],Zk=(e,t)=>{let n=Math.ceil(t*e.length),r=Math.min(e.length-1,Math.max(0,n-1));return e[r]},zl=(e,t)=>typeof e!="string"?t:e.trim().length>0?e:t,e0=e=>{if(!(typeof e!="number"||!Number.isFinite(e)))return Math.trunc(e)},n1=e=>({command:zl(e.event.command,"<unknown>"),eventType:zl(e.event.event_type,"unknown"),eventSchemaVersion:e0(e.event.schema_version),clientSchemaVersion:e0(e.client_schema_version)}),r1=()=>({count:0,max_attempts:0,event_type_counts:{},event_schema_versions:new Set,client_schema_versions:new Set,finish_durations_ms:[],ok_count:0,error_count:0,resolution_counts:{}}),i1=e=>{let t=e?.duration_ms;return typeof t=="number"&&Number.isFinite(t)?t:void 0},o1=e=>{let t=e?.command_resolution;return zl(t,"")||void 0},r0=(e,t)=>{e[t]=(e[t]??0)+1},s1=(e,t)=>{let n=i1(t);n!==void 0&&e.finish_durations_ms.push(n),t?.ok===!0?e.ok_count+=1:e.error_count+=1;let r=o1(t);r!==void 0&&r0(e.resolution_counts,r)},a1=e=>Number.isFinite(e)?Math.max(0,Math.trunc(e)):0,t0=(e,t)=>{t!==void 0&&e.add(t)},c1=(e,t)=>{let n=n1(t),r=e.get(n.command)??r1();r.count+=1,r.max_attempts=Math.max(r.max_attempts,a1(t.attempts)),r0(r.event_type_counts,n.eventType),t0(r.event_schema_versions,n.eventSchemaVersion),t0(r.client_schema_versions,n.clientSchemaVersion),n.eventType==="command_finish"&&s1(r,t.event.payload),e.set(n.command,r)},d1=(e,t)=>{let n=t.ok_count+t.error_count,r=[...t.finish_durations_ms].sort((o,s)=>o-s),i=Object.entries(t.resolution_counts).sort((o,s)=>o[0].localeCompare(s[0]));return{command:e,count:t.count,event_type_counts:Object.fromEntries(Object.entries(t.event_type_counts).sort((o,s)=>o[0].localeCompare(s[0]))),max_attempts:t.max_attempts,event_schema_versions:[...t.event_schema_versions].sort((o,s)=>o-s),client_schema_versions:[...t.client_schema_versions].sort((o,s)=>o-s),...r.length>0?{duration_p50_ms:Zk(r,.5),duration_p95_ms:Zk(r,.95),duration_max_ms:r[r.length-1]}:{},...n>0?{ok_count:t.ok_count,error_count:t.error_count,error_rate:t.error_count/n}:{},...i.length>0?{command_resolution_counts:Object.fromEntries(i)}:{}}},l1=e=>{let t=(e??"status").trim().toLowerCase();if(Qk.includes(t))return t;throw Bi({command_path:"telemetry",token:e?.trim()||"<empty>",allowed:Qk,examples:["pm telemetry status","pm telemetry flush","pm telemetry stats --limit 10","pm telemetry clear"]})},Vl=()=>{throw new p("--limit must be a positive integer",m.USAGE)},i0=e=>[!Number.isFinite(e),!Number.isInteger(e),e<=0].includes(!0)?Vl():e,u1=e=>{let t=e.trim();return[t.length===0,!/^\d+$/.test(t)].includes(!0)?Vl():i0(Number.parseInt(t,10))},m1=e=>e===void 0?t1:typeof e=="number"?i0(e):typeof e=="string"?u1(e):Vl(),p1=e=>{if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.attempts=="number"&&typeof t.event=="object"&&t.event!==null},_1=e=>{try{let t=JSON.parse(e);return p1(t)?t:void 0}catch{return}},f1=e=>e===null?[]:e.split(`
|
|
18
|
+
`).map(t=>t.trim()).filter(t=>t.length>0),o0=e=>{let t=f1(e),n=[],r=0;for(let i of t){let o=_1(i);o===void 0?r+=1:n.push(o)}return{rows_total:t.length,valid_entries:n.length,invalid_rows:r,entries:n}},h1=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),g1=e=>{try{let t=JSON.parse(e);return h1(t)?t:{}}catch{return{}}},aa=async e=>{let t=await Q(e);return t===null||t.trim().length===0?{}:g1(t)};function s0(e){let t=new Date;return new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()-Math.max(1,Math.trunc(e))+1)).toISOString().slice(0,10)}function y1(e,t,n){let r=Object.create(null);for(let[i,o]of Object.entries(e)){if(!/^\d{4}-\d{2}-\d{2}$/u.test(i)||i<t||i>n||typeof o!="object"||o===null||Array.isArray(o))continue;let s=o;!Number.isSafeInteger(s.count)||s.count<1||typeof s.last_seen!="string"||!s.last_seen.startsWith(i)||(r[i]={count:s.count,last_seen:s.last_seen})}return r}function Bl(e,t){let n=Object.create(null);if(typeof e!="object"||e===null||Array.isArray(e))return n;let r=e,i=new Date().toISOString().slice(0,10);for(let o of Hl){let s=r[o.alias];if(typeof s!="object"||s===null||Array.isArray(s))continue;let a=s;if(a.canonical!==o.canonical||typeof a.days!="object"||a.days===null||Array.isArray(a.days))continue;let c=y1(a.days,t,i);Object.keys(c).length>0&&(n[o.alias]={canonical:o.canonical,days:c})}return n}async function w1(e,t,n){let r=s0(n),i=await aa(t),o=Bl(i.alias_usage,r);if(JSON.stringify(i.alias_usage??{})===JSON.stringify(o))return o;try{await ho(async()=>{let s=await aa(t);if(s.alias_usage===void 0)return;let a=Bl(s.alias_usage,r);JSON.stringify(s.alias_usage)!==JSON.stringify(a)&&await je(t,`${JSON.stringify({...s,alias_usage:a},null,2)}
|
|
19
|
+
`)},e,250)}catch{}return o}async function E9(e){let t=Hl.find(r=>r.alias===e);if(!t||Zt().telemetry_disabled)return!1;let n=Ye(process.cwd());try{return await ho(async()=>{let r=await x(n);if(!r.telemetry.enabled||Zt().telemetry_disabled)return!1;let i=Tt.join(n,n0),o=await aa(i),s=Bl(o.alias_usage,s0(r.telemetry.retention_days)),a=new Date().toISOString().slice(0,10),c=s[e]?.days[a];return s[e]={canonical:t.canonical,days:{...s[e]?.days,[a]:{count:Math.min(Number.MAX_SAFE_INTEGER,(c?.count??0)+1),last_seen:I()}}},await je(i,`${JSON.stringify({...o,alias_usage:s},null,2)}
|
|
20
|
+
`),!0},n,250)}catch{return!1}}var sa=e=>e??null,ca=async e=>{let t=await x(e),n=Tt.join(e,wi,It("events.jsonl")),r=Tt.join(e,wi,It("state.json")),i=await Q(n),o=o0(i),s=await aa(r),a=Zt();return{enabled:t.telemetry.enabled&&!a.telemetry_disabled,configured_enabled:t.telemetry.enabled,env_overrides:a,endpoint:Ot(Cr(t.telemetry.endpoint)),queue_path:n,state_path:r,queue_rows_total:o.rows_total,queue_entries:o.valid_entries,queue_invalid_rows:o.invalid_rows,queue_size_bytes:Buffer.byteLength(i??"","utf8"),last_attempted_flush_at:sa(s.last_attempted_flush_at),last_successful_flush_at:sa(s.last_successful_flush_at),last_failed_flush_at:sa(s.last_failed_flush_at),last_failed_flush_error:sa(s.last_failed_flush_error)}},v1=e=>{let t=new Map;for(let n of e)c1(t,n);return[...t.entries()].map(([n,r])=>d1(n,r)).sort((n,r)=>r.count-n.count||n.command.localeCompare(r.command))},b1=async(e,t)=>({action:"telemetry",subcommand:"status",status:await ca(t.globalPmRoot),generated_at:I()}),k1=async(e,t)=>{let n=await ca(t.globalPmRoot);await Jp(t.globalPmRoot);let r=await ca(t.globalPmRoot),i=Math.max(0,n.queue_entries-r.queue_entries),o=r.queue_entries===0;return{action:"telemetry",subcommand:"flush",queue_entries_before:n.queue_entries,queue_entries_after:r.queue_entries,queue_entries_drained:i,queue_progressed:i>0,queue_empty:o,queue_drained:o,status:r,generated_at:I()}},S1=async(e,t)=>{let n=m1(e.limit),r=await Q(t.queuePath),i=o0(r),o=v1(i.entries),s=o.slice(0,n),a=await x(t.globalPmRoot),c=await w1(t.globalPmRoot,Tt.join(t.globalPmRoot,n0),a.telemetry.retention_days),d=Object.entries(c).map(([l,u])=>{let _=Object.values(u.days);return{alias:l,canonical:u.canonical,count:_.reduce((h,f)=>Math.min(Number.MAX_SAFE_INTEGER,h+f.count),0),last_seen:_.map(h=>h.last_seen).sort().at(-1)}}).sort((l,u)=>u.count-l.count||l.alias.localeCompare(u.alias));return{action:"telemetry",subcommand:"stats",limit:n,total_commands:o.length,queue_entries:i.valid_entries,queue_invalid_rows:i.invalid_rows,queue_rows_total:i.rows_total,truncated:o.length>s.length,stats:s,alias_usage:d,zero_use_aliases:Hl.map(l=>l.alias).filter(l=>c[l]===void 0),alias_usage_retention_days:a.telemetry.retention_days,generated_at:I()}},E1=async(e,t)=>ho(async()=>{let n=await x(t.globalPmRoot),r=[n.telemetry.enabled!==!1,n.telemetry.installation_id!=="",n.telemetry.first_run_prompt_completed!==!0].includes(!0);n.telemetry.enabled=!1,n.telemetry.first_run_prompt_completed=!0,n.telemetry.installation_id="",r&&await Cp(t.globalPmRoot,n,"telemetry:clear");let i=Tt.join(t.globalPmRoot,wi),o=await ie(i);return await e1.rm(i,{recursive:!0,force:!0}),{action:"telemetry",subcommand:"clear",settings_changed:r,runtime_dir_removed:o&&!await ie(i),queue_exists_after:await ie(t.queuePath),state_exists_after:await ie(t.statePath),status:await ca(t.globalPmRoot),generated_at:I()}},t.globalPmRoot),T1={status:b1,flush:k1,stats:S1,clear:E1};async function T9(e,t){let n=l1(e.subcommand),r=Ye(process.cwd());return T1[n](e,{globalPmRoot:r,queuePath:Tt.join(r,wi,It("events.jsonl")),statePath:Tt.join(r,wi,It("state.json"))})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7140bb24-7202-541a-bc13-6a67bac260a8")}catch{}})();var a0=100;function ar(e,t="--only-index"){let n=typeof e=="number"?e:Number(String(e).trim());if(!Number.isInteger(n)||n<1)throw new p(`${t} requires a 1-based integer index into the linked-test list (got "${e}"). Use pm test <id> --list to inspect positions.`,m.USAGE);return n}function C1(e){let t=(e.command??e.path??"<no command>").replaceAll(/\s+/g," ").trim()||"<no command>";return t.length<=a0?t:`${t.slice(0,a0-3)}...`}function c0(e){return e.map((t,n)=>`${n+1}. ${C1(t)}`).join("; ")}function A1(e){let t=[];return e.match!==void 0&&t.push("match"),e.onlyIndex!==void 0&&t.push("only-index"),e.onlyLast===!0&&t.push("only-last"),t}function x1(e,t){let n=e.command?.toLowerCase()??"",r=e.path?.toLowerCase()??"";return n.includes(t)||r.includes(t)}function d0(e,t){let n=A1(t);if(n.length===0)return{selector:null,requested:null,selected:e,selected_indexes:e.map((i,o)=>o+1),selected_count:e.length,skipped_count:0};if(n.length>1)throw new p(`Combine at most one linked-test selector per run: ${n.map(i=>`--${i}`).join(" and ")} were provided. Pick one of --match, --only-index, --only-last.`,m.USAGE);let r=n[0];if(e.length===0)throw new p(`--${r} matched no linked tests because this item has none. Add one first with --add, --command, or --add-json.`,m.USAGE);if(r==="match"){let i=t.match.trim().toLowerCase();if(i.length===0)throw new p("--match requires a non-empty substring to match against linked-test command/path values",m.USAGE);let o=[],s=[];for(let a=0;a<e.length;a+=1)x1(e[a],i)&&(s.push(e[a]),o.push(a+1));if(s.length===0)throw new p(`--match "${t.match}" matched none of the ${e.length} linked test(s). Available entries: ${c0(e)}`,m.USAGE);return{selector:"match",requested:t.match,selected:s,selected_indexes:o,selected_count:s.length,skipped_count:e.length-s.length}}if(r==="only-index"){let i=ar(t.onlyIndex);if(i>e.length)throw new p(`--only-index ${i} is out of range: this item has ${e.length} linked test(s). Available entries: ${c0(e)}`,m.USAGE);return{selector:"only-index",requested:String(i),selected:[e[i-1]],selected_indexes:[i],selected_count:1,skipped_count:e.length-1}}return{selector:"only-last",requested:"last",selected:[e[e.length-1]],selected_indexes:[e.length],selected_count:1,skipped_count:e.length-1}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f75d72fe-b7f5-576d-b6c1-1cd94e3288b3")}catch{}})();var Yl=["command","cmd"],vi=Object.freeze(ft.filter(e=>!["command","cmd","timeout"].includes(e)));function l0(e){if(e.update===void 0&&e.updateIndex===void 0&&e.setJson===void 0)return;if(e.update===void 0==(e.updateIndex===void 0)||e.setJson===void 0)throw new p("Use exactly one --update or --update-index with --set-json",m.USAGE);let t;try{t=JSON.parse(e.setJson)}catch{throw new p("--set-json must contain a JSON object with explicit linked-test metadata fields",m.USAGE)}if(e.updateIndex!==void 0)return{selector:{index:ar(e.updateIndex,"--update-index")},patch:t};let n=e.update,r=/^(command|path)=/u.exec(n);return{selector:r?.[1]==="path"?{path:n.slice(r[0].length)}:{command:r?n.slice(r[0].length):n},patch:t}}function u0(e){if([e.list,e.run,e.progress,e.timeout!==void 0,e.acknowledgeLinkedTests,e.metricBelow!==void 0,e.metricDiff!==void 0,(e.add?.length??0)>0,(e.addJson?.length??0)>0,(e.remove?.length??0)>0,(e.removeIndex?.length??0)>0].some(Boolean))throw new p("Edit linked-test metadata separately from listing, additions, removals, execution options, metric filters and trust acknowledgement",m.USAGE)}function R1(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new p("Select one linked test by index, command, or path",m.USAGE);let n=Object.keys(t);if(n.length!==1||!["index","command","path"].includes(n[0]))throw new p("Select one linked test by index, command, or path",m.USAGE);if("index"in t){let r=ar(t.index,"--update-index");if(r<=e.length)return r-1}else{let r="command"in t?"command":"path",i="command"in t?t.command:t.path;if(typeof i!="string"||i.trim().length===0)throw new p("Linked-test selector must be a non-empty command or path",m.USAGE);let o=e.flatMap((s,a)=>s[r]===i?[a]:[]);if(o.length===1)return o[0];if(o.length>1)throw new p(`Linked-test selector is ambiguous; matching indexes: ${o.map(s=>s+1).join(", ")}`,m.USAGE,{code:"linked_test_update_ambiguous",required:"List linked tests and select one current --update-index."})}throw new p("No linked test matched the update selector",m.NOT_FOUND,{code:"linked_test_update_no_match",required:"List linked tests and select a current command, path, or --update-index."})}function m0(e,t){let n=Object.keys(e),r=n.filter(i=>!vi.includes(i));if(n.length===0&&!t||r.length>0)throw new p("Patch explicit linked-test metadata fields; command, aliases and provenance cannot be edited",m.USAGE,{code:"linked_test_patch_fields_unsupported",changed:!1,...r.length>0?{field:r[0]}:{},required:`Patch at least one editable field: ${vi.join(", ")}.`,recovery:{allowed_values:[...vi]},...r.length>0?{nextSteps:[`Remove unsupported field(s) from --set-json: ${r.join(", ")}.`]}:{}});if(e.scope===null)throw new p("scope is required and cannot be cleared",m.USAGE)}function I1(e,t,n){let r={};for(let i of vi){let o=t[i]!==void 0?t[i]:e[i];o!=null&&(r[i]=o)}return{command:n,...r}}function da(e){return{field:e,changed:!1,required:"Replace the entry instead: remove the selected linked test and add the new command in one pm test invocation, which records fresh provenance."}}function O1(e,t,n){let r=Yl.filter(o=>Object.hasOwn(e,o)).map(o=>e[o]),i=typeof e[t]=="string"?e[t].trim():"";if(r.length>1&&r.some(o=>typeof o!="string"||o.trim()!==i))throw new p("--set-json sets command and cmd to different values; send one command",m.USAGE,{code:"linked_test_command_immutable",...da(t),nextSteps:["Send the replacement command once, as command."]});if(i.length===0||i===n.command)throw new p(i.length===0?`--set-json cannot set ${t}: a linked test's command is its immutable identity`:`--set-json ${t} repeats the selected entry's command; omit it to edit only metadata`,m.USAGE,{code:"linked_test_command_immutable",...da(t),nextSteps:[`Patch only editable fields: ${vi.join(", ")}.`]});return ti(i),i}function L1(e){let{id:t,tests:n,index:r,identityKey:i,otherFields:o,requested:s,global:a}=e;m0(o,!0);let c=I1(n[r],o,s),d=mi(JSON.stringify(c),"--add-json")[0];hr(d);let l=n.findIndex((u,_)=>_!==r&&gr(u,d));if(l>=0)throw new p(`--set-json cannot change ${i}: linked test ${l+1} already has the requested identity, so a replacement would merge into it`,m.USAGE,{code:"linked_test_command_immutable",...da(i),nextSteps:[`Edit linked test ${l+1} instead: ${L([...Ie(a),"test",t,"--update-index",String(l+1),"--set-json","<editable fields>"])}`,`Or drop the selected entry: ${L([...Ie(a),"test",t,"--remove-index",String(r+1)])}`]});return c}function D1(e){return[...e.author!==void 0?["--author",e.author]:[],...e.message!==void 0?["--message",e.message]:[],...e.force===!0?["--force"]:[]]}function $1(e){let{id:t,tests:n,index:r,patch:i,global:o,controls:s}=e;if(typeof i!="object"||i===null||Array.isArray(i))return;let a=i,c=Yl.find(g=>Object.hasOwn(a,g));if(c===void 0)return;let d=n[r],l=O1(a,c,d),u=Object.fromEntries(Object.entries(a).filter(([g])=>!Yl.includes(g))),_=L1({id:t,tests:n,index:r,identityKey:c,otherFields:u,requested:l,global:o}),h=d.command!==void 0&&n.filter(g=>g.command===d.command).length===1?["--remove",`command=${d.command}`]:["--remove-index",String(r+1)],f=[...Ie(o),"test",t,...h,"--add-json",JSON.stringify(_),...D1(s)];throw new p(`--set-json cannot change ${c}: a linked test's command is its immutable identity; replace the entry instead`,m.USAGE,{code:"linked_test_command_immutable",...da(c),recovery:{suggested_retry:L(f),suggested_retry_args:f},nextSteps:["Run the suggested retry: it removes the selected entry and adds the new command in one history-recorded write. It selects the entry by its current command or list position, so list the linked tests again first if another writer may have changed them.",`SDK: runTest(${JSON.stringify(t)}, { ${h[0]==="--remove"?"remove":"removeIndex"}: [...], addJson: [...] }, { path: <the same tracker root> }) with the same values.`]})}function N1(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new p("Linked-test metadata patch must be a JSON object",m.USAGE);let n=Object.keys(t);m0(t,!1);let r=Object.fromEntries(Object.entries(e).filter(([a])=>ft.includes(a))),i=Nm(mi(JSON.stringify({...r,command:e.command??"legacy-path-only",...Object.fromEntries(Object.entries(t).map(([a,c])=>[a,c===null?void 0:c]))}),"--set-json")[0]);hr(i);let o=n.filter(a=>!Fe(e[a],i[a])),s={...e};for(let a of o){let c=i[a];Object.assign(s,{[a]:c}),c===void 0&&delete s[a]}if(!s.command?.trim()&&!s.path?.trim())throw new p("Linked-test entry must retain a command or path",m.USAGE);return{test:s,fields:o}}async function p0(e,t,n={}){let r=R(process.cwd(),n.path);await j(r);let i=await x(r),o=U(t.author,i.author_default),s=P(i,N()),a=0,c=[],d=await Rt({pmRoot:r,settings:i,id:e,author:o,op:"tests_update",message:t.message,force:t.force,skipNoop:!0,typeToFolder:s.type_to_folder,resolveHistoryContext:()=>({linked_test_update:{index:a,fields:c}}),mutate(u){let _=u.metadata.tests??[],h=R1(_,t.selector);$1({id:u.metadata.id,tests:_,index:h,patch:t.patch,global:n,controls:t});let f=N1(_[h],t.patch);return a=h+1,c=f.fields,f.fields.length===0?{changedFields:[]}:(u.metadata.tests=_.map((g,y)=>y===h?{...f.test,updated_by:o,updated_at:I()}:g),{changedFields:["tests"]})}}),l=d.item.tests;return{ok:!0,id:d.item.id,tests:l,count:l.length,changed:d.changedFields.length>0,updated_index:a,updated_fields:c}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="626315a0-7ee9-500d-bb7a-9bcd33eae209")}catch{}})();var M1=[{code:"no_projects_matched_filters",regex:/\bNo projects matched the filters\b/i},{code:"no_test_files_found",regex:/\bNo test files found\b/i},{code:"no_tests_found",regex:/\bNo tests found\b/i},{code:"no_matching_tests",regex:/\bNo matching tests?\b/i},{code:"collected_zero_items",regex:/\bcollected 0 items?\b/i},{code:"reported_zero_tests",regex:/^\s*Ran 0 tests? across \d+ files?\./imu},{code:"reported_zero_passes",regex:/(?:^\s*(?:#|ℹ)?\s*tests\s+0\s*$[\s\S]*^\s*(?:#|ℹ)?\s*pass\s+0\s*$|^\s*(?:#|ℹ)?\s*pass\s+0\s*$[\s\S]*^\s*(?:#|ℹ)?\s*tests\s+0\s*$)/imu},{code:"reported_zero_tests",regex:/^\s*(?:#|ℹ)?\s*tests\s+0\s*$/imu}],P1=[{receiptCode:"reported_tests",regex:/^\s*(?:#|ℹ)?\s*tests\s+[1-9]\d*\s*$/imu},{receiptCode:"reported_passes",regex:/^\s*(?:#|ℹ)?\s*pass\s+[1-9]\d*\s*$/imu},{receiptCode:"tests_passed",regex:/\bTests?\s+[1-9]\d*\s+passed\b/iu},{receiptCode:"passed_count",regex:/\b[1-9]\d*\s+passed\b/iu},{receiptCode:"tests_summary",regex:/\bTests:\s+(?:.*\b)?[1-9]\d*\s+passed\b/iu},{receiptCode:"bun_pass_count",regex:/^\s*[1-9]\d* pass\s*$/imu},{receiptCode:"bun_executed_tests",regex:/^\s*Ran [1-9]\d* tests? across \d+ files?\./imu}];function la(e,t){let n=`${e}
|
|
21
|
+
${t}`;for(let r of M1)if(r.regex.test(n))return{code:r.code};return null}function _0(e,t){for(let[n,r]of[["stdout",e],["stderr",t]]){let i=P1.find(o=>o.regex.test(r));if(i)return{code:i.receiptCode,stream:n}}}function f0(e,t){return{trackerPath:e.path?.trim()||(process.env.PM_PATH?.trim()?t:void 0),noExtensions:e.noExtensions}}function h0(e,t={}){let n=t.trackerPath?.trim();return L(["test",e,"--list",...t.noExtensions===!0?["--no-extensions"]:[],...n?["--pm-path",n]:[]],t.platform)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="47772627-d807-55f3-95b3-69e3b00c6522")}catch{}})();function g0(e,t,n,r,i){if((t.measure?.length??0)===0||i.some(s=>s.phase!=="setup"&&typeof s.stdout=="string"&&s.failure_category!=="spawn_error"&&s.failure_category!=="empty_run"&&la(s.stdout,s.stderr??"")===null))return;let o=["--pm-path",r,...n.noExtensions?["--no-extensions"]:[],...n.author?["--author",n.author]:[],"test",e,"--list","--json"];throw new p("--measure requires an executed linked test",m.USAGE,{code:"test_measure_requires_execution",required:"Execute at least one linked command before recording measurement evidence.",why:"Empty, skipped and pre-execution refused runs cannot support measured evidence.",nextSteps:["Inspect the linked commands, adjust empty selections or missing commands, and resolve any trust refusal before retrying the measurement."],recovery:{suggested_retry:L(o),suggested_retry_args:o}})}function Jl(e,t,n,r,i=!1){if((t.measure?.length??0)===0||t.run===!0)return;let o=["--pm-path",r,...n.noExtensions?["--no-extensions"]:[],...n.author?["--author",n.author]:[]],s=[...o,...Zf(e,t),...t.list?["--list"]:[],...i?["--background"]:[]],a=t.acknowledgeLinkedTests?[...o,"test",e,"--help"]:s,c=[...o,"test",e,"--acknowledge-linked-tests",...t.author?["--author",t.author]:[]];throw new p("--measure requires --run",m.USAGE,{code:"test_measure_requires_run",flag:"--measure",required:"Run the linked tests with --run to record measurement evidence.",why:"Measurements describe an executed linked-test run; recording them without execution would fabricate evidence.",...t.acknowledgeLinkedTests?{nextSteps:[`Review the linked commands and apply any requested link updates separately before acknowledging trust: ${L([...o,"test",e,"--list"])}`,`After review, acknowledge trust as a separate non-executing operation: ${L(c)}`,`Then run the measurement without --acknowledge-linked-tests: ${L(s)}`]}:{},recovery:{missing:["--run"],suggested_retry:L(a),suggested_retry_args:a}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="92f73d30-eac7-5c84-a7be-133323d1f549")}catch{}})();function y0(e){if(!/^(?:[^.[\]]+|\[\d+\])(?:\.[^.[\]]+|\[\d+\])*$/u.test(e))return[];let t=[],n=e.matchAll(/[^.[\]]+|\[\d+\]/g);for(let[r]of n){if(r.startsWith("[")&&r.endsWith("]")){let i=Number.parseInt(r.slice(1,-1),10);if(!Number.isSafeInteger(i))return[];t.push(i);continue}t.push(r)}return t}function Xl(e,t){let n=t.trim();if(n.length===0)return{found:!1,value:void 0};let r=y0(n);if(r.length===0)return{found:!1,value:void 0};let i=e;for(let o of r){if(typeof i!="object"||i===null)return{found:!1,value:void 0};if(typeof o=="number"&&(!Array.isArray(i)||o>=i.length))return{found:!1,value:void 0};let s=Object.getOwnPropertyDescriptor(i,o);if(!s||!Object.hasOwn(s,"value"))return{found:!1,value:void 0};i=s.value}return{found:!0,value:i}}import{cp as K1,lstat as W1,mkdir as z1,readlink as B1,realpath as eu,stat as H1,symlink as b0}from"node:fs/promises";import{execFile as V1}from"node:child_process";import H from"node:path";import{promisify as Y1}from"node:util";import{execFile as F1}from"node:child_process";import{readdir as j1,realpath as U1}from"node:fs/promises";import G1 from"node:path";import{promisify as q1}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e67d1a06-77f7-5e86-8f15-bde8b6db0d5a")}catch{}})();var Ql=q1(F1),w0=".agents/pm/merge-receipts";async function v0(e,t,n){let r=G1.join(n,"merge-receipts"),i=(await j1(r).catch(c=>{if(G(c))return[];throw c})).filter(c=>c.endsWith(".json")),{readIndexedReceiptBlobs:o}=await import("./indexed-receipt-blobs-ELEMA7IW.js"),s=i.length===0?new Map:await o(e,r,i,fh,await U1(r),{failOnReadError:!0}),a={cwd:t,env:_h(),timeout:1e4,maxBuffer:1024*1024,windowsHide:!0};await Ql("git",["rm","-q","-r","--cached","--ignore-unmatch","--",w0],a);for(let[c,d]of s){let l=Ql("git",["hash-object","-w","--stdin"],a),u=l.child.stdin;u!==null&&(u.on("error",()=>{l.child.kill()}),u.end(d));let _=(await l).stdout.trim();if(!/^(?:[a-f\d]{40}|[a-f\d]{64})$/u.test(_))throw new Error("Invalid snapshot receipt object identity.");await Ql("git",["update-index","--add","--cacheinfo","100644",_,`${w0}/${c}`],a)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6638f21c-6cf5-5dec-a0d9-91ae323afce3")}catch{}})();var J1=new Set([".agents",".git",".nyc_output",".turbo","coverage"]),ua=Y1(V1);async function X1(e,t){let n=await ma(H.join(e,".git"));if(!n||n.isDirectory()&&!await ma(H.join(e,".git/HEAD")))return!1;let r=Object.fromEntries(Object.entries(process.env).filter(([i])=>!i.toUpperCase().startsWith("GIT_")));await ua("git",["clone","--no-local","--no-checkout","--template=","--origin=origin","--",e,t],{env:r,timeout:12e4,maxBuffer:1024*1024,windowsHide:!0}),await ua("git",["-C",t,"remote","remove","origin"],{env:r,timeout:1e4,windowsHide:!0});try{await ua("git",["-C",t,"rev-parse","--verify","--quiet","HEAD"],{env:r,timeout:1e4,windowsHide:!0})}catch(i){if(i.code===1)return!0;throw i}return await ua("git",["-C",t,"read-tree","HEAD"],{env:r,timeout:1e4,windowsHide:!0}),!0}async function Q1(e,t,n,r){await X1(e,t)&&n&&r!==!1&&await v0(e,t,n)}function Zl(e){return e.split(H.sep).some(t=>J1.has(t.toLowerCase()))}function bi(e){return e===".."||e.startsWith(`..${H.sep}`)||H.isAbsolute(e)}async function ma(e){try{return await H1(e)}catch(t){if(!G(t))throw t;return}}async function pa(e){let t=[],n=e;for(;H.dirname(n)!==n;)try{return H.join(await eu(n),...t)}catch(r){if(!G(r))throw r;t.unshift(H.basename(n)),n=H.dirname(n)}return H.join(await eu(n),...t)}async function Z1(e,t,n){let r=H.relative(t,await pa(e));if(!bi(r))return r;let i=[],o=e;for(;H.dirname(o)!==o;){let s=await pa(o),a=n.find(([,c])=>c===s);if(a)return H.join(a[0],...i);i.unshift(H.basename(o)),o=H.dirname(o)}return r}async function k0(e,t,n,r){let i=[],o=[],s=await eu(e),a=await pa(H.resolve(t));if(![H.relative(s,a),H.relative(a,s)].every(bi))throw new Error("Snapshot destination must be disjoint from the source workspace; choose a temporary root outside the checkout.");await z1(H.dirname(t),{recursive:!0}),await Q1(s,t,n,r),await K1(s,t,{recursive:!0,force:!0,async filter(c){let d=H.relative(s,c);if(!d)return!0;if(Zl(d))return!1;if(H.basename(c).toLowerCase()==="node_modules"){if((await ma(c))?.isDirectory()){let l=await pa(c),u=H.relative(s,l);if(!bi(H.relative(l,s))||!bi(u)&&(Zl(u)||!u.split(H.sep).some(_=>_.toLowerCase()==="node_modules")))throw new Error(`Dependency symlink must target an included dependency directory or external installation: ${d}`);i.push([d,l])}return!1}return(await W1(c)).isSymbolicLink()?(o.push([d,H.resolve(H.dirname(c),await B1(c)),(await ma(c))?.isDirectory()?"junction":"file"]),!1):!0}});for(let[c]of i)await b0(H.resolve(s,c),H.join(t,c),"junction");for(let[c,d,l]of o){let u=await Z1(d,s,i);if(bi(u)||Zl(u))throw new Error(`Source symlink must target included workspace source: ${c}`);await b0(H.resolve(t,u),H.join(t,c),l)}}import{execFile as eF}from"node:child_process";import{constants as S0}from"node:fs";import{access as tF,open as nF}from"node:fs/promises";import E0 from"node:path";import{promisify as rF}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b42f8889-4b5a-5391-b8e4-b68084e20a49")}catch{}})();var iF=rF(eF);function oF(e){let t=e.match(/^\s*(?:"([^"\r\n]+)"|'([^'\r\n]+)'|([\w./\\:-]+))(?=\s|$)/u),n=t?.[1]??t?.[2]??t?.[3];return n&&!/[$`%&|<>^;]/u.test(n)?n:void 0}function sF(e,t,n){return process.platform==="win32"?(t===1||t===9009)&&n.split(/\r?\n/u).some(r=>r.trim()===`'${e}' is not recognized as an internal or external command,`):t!==126&&t!==127?!1:n.split(/\r?\n/u).some(r=>t===127&&(r.endsWith(`: ${e}: not found`)||r.endsWith(`: ${e}: command not found`))||t===126&&r.includes(`: ${e}: `)&&r.endsWith(": bad interpreter: No such file or directory"))}async function aF(e,t){let n=e.trim();if(!n||/[\r\n]/u.test(n))return!1;try{let r=await nF(E0.resolve(t,n),S0.O_RDONLY|S0.O_NONBLOCK),i;try{let s=Buffer.alloc(256),{bytesRead:a}=await r.read(s,0,s.length,0);if(i=s.toString("utf8",0,a),a===s.length&&!i.includes(`
|
|
22
|
+
`))return!1}finally{await r.close()}let o=i.match(/^#![ \t]*(\/[^ \t\n]+)(?:[ \t\n]|$)/u)?.[1];if(!o)return!1;try{return await tF(o),!1}catch(s){return Tn(s)}}catch{return!1}}async function T0(e,t,n,r){if(/[;&|<>()`$\r\n]/u.test(e))return!1;let i=oF(e);if(!i||!sF(i,t.exitCode,t.stderr))return!1;let o=process.platform==="win32",s=o?E0.join(n.SystemRoot??"C:\\Windows","System32","where.exe"):"/bin/sh",a=o?[i]:["-c",'command -v "$1"',"pm-linked-test-resolution",i];try{let{stdout:c}=await iF(s,a,{env:n,cwd:r,timeout:1e3,windowsHide:!0});return!o&&aF(c,r)}catch(c){let d=c;if(d.killed||d.signal)return!1;let l=d.code;return l===1||!o&&l===127}}import{spawn as q0}from"node:child_process";import{cp as A0,mkdir as ou,mkdtemp as K0,open as nu,readdir as ru,rm as Si,symlink as dF}from"node:fs/promises";import{tmpdir as W0}from"node:os";import le from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b74444c7-c283-52b2-b65f-b0a086ff2b53")}catch{}})();var C0=20;function cF(){let e=process.env.PM_TRACKED_TEST_RUN_HISTORY_LIMIT;if(!e||e.trim().length===0)return C0;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<=0?C0:t}function tu(e){let t=[...e].filter(r=>r.run_id.trim().length>0&&r.started_at.trim().length>0&&r.finished_at.trim().length>0&&r.recorded_at.trim().length>0).sort((r,i)=>{let o=Wi(r.recorded_at,i.recorded_at);if(o!==0)return o;let s=r.run_id.localeCompare(i.run_id);return s!==0?s:r.kind.localeCompare(i.kind)}),n=cF();return t.length>n?t.slice(t.length-n):t}async function _a(e){await he({pmRoot:e.pmRoot,settings:e.settings,id:e.itemId,op:"test_run_track",author:e.author,message:e.message,force:!1,mutate(t){let n=t.metadata.test_runs??[];return t.metadata.test_runs=tu([...n,e.entry]),{changedFields:["test_runs"]}}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="36de91bf-47b8-5755-ad92-6ed1a1bbcd82")}catch{}})();var ga=20*1024*1024,lF=3e3,uF=1e4,mF=5e3,x0=120,pF=new Set(["locks","extensions","runtime"]),_F=new Set(["history","index","search","extensions","locks","runtime"]),fF=[/eaddrinuse/i,/address already in use/i,/port\s+\d+\s+is already in use/i,/web server[^.\n]*already running/i,/failed to listen on/i],hF=/\b(?:could not|failed to|unable to)\s+acquire\b[^\n.]*\block\b/i,gF=/\b(?:already running|timed?\s*out|timeout|held by another|lock\s+is\s+held)\b/i,yF=new Set(["activity","calendar","context","ctx","deps","get","health","history","list","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","search","stats","test-all","validate"]);function su(e,t){let n=process.env[e];if(typeof n!="string"||n.trim().length===0)return t;let r=Number.parseInt(n,10);return!Number.isFinite(r)||r<=0?t:r}function wF(){return su("PM_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS",lF)}function vF(){return su("PM_LINKED_TEST_HEARTBEAT_INTERVAL_MS",uF)}function bF(){return su("PM_LINKED_TEST_PIPE_CLOSE_GRACE_MS",mF)}function kF(e){let t=process.env.PM_BACKGROUND_TEST_RUN_ID?.trim();return t&&t.length>0?t:`${e}-local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function SF(e){let t=0,n=0,r=0;for(let i of e){if(i.status==="passed"){t+=1;continue}if(i.status==="failed"||i.status==="refused"){n+=1;continue}r+=1}return{passed:t,failed:n,skipped:r}}function au(e){let t=0,n=0,r=0,i=0;for(let o of e){let s=o.execution_context;!s||s.is_pm_command!==!0||(t+=1,s.is_pm_tracker_read_command===!0&&(n+=1),s.mismatch_detected===!0&&(r+=1),s.auto_pm_context_applied===!0&&(i+=1))}return{checked_pm_commands:t,tracker_read_commands:n,mismatches:r,auto_remediated:i}}function EF(e){let t=e??"project";if(!Ke.includes(t))throw new p(`Invalid scope "${e}"`,m.USAGE);return t}function wa(e){if(!e)return"schema";let t=e.trim().toLowerCase();if(ln.includes(t))return t;throw new p(`Invalid --pm-context value "${e}". Expected one of: ${ln.join(", ")}`,m.USAGE)}function z0(e){return mn(e??"source","--workspace-context")}function B0(e,t,n){return n?t:mn(e.workspace_context_mode,"linked test")??t}function H0(e,t,n){return n||typeof e.pm_context_mode!="string"||e.pm_context_mode.trim().length===0?t:wa(e.pm_context_mode)}function V0(e,t){return e==="auto"?t?"tracker":"schema":e}function TF(e){return Object.entries(e).filter(([t])=>t.startsWith("assert_")).some(([,t])=>t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:typeof t=="string"?t.trim().length>0:!0)}function CF(e){let{executionContext:t,runLevelPmContextMode:n,linkedOverridePmContextMode:r}=e;return!t.is_pm_tracker_read_command||!t.mismatch_detected?"":n==="tracker"&&r==="schema"?" Linked test metadata pm_context_mode=schema overrides run-level --pm-context tracker. Set pm_context_mode=tracker (or auto) on the linked test, or remove the override, to run against seeded tracker data.":t.pm_context_mode==="schema"?" Use --auto-pm-context to route PM tracker-read linked commands through seeded tracker data automatically. Alternatively, use --pm-context tracker for the whole run.":""}function AF(e,t){let n={};if(!e)return n;for(let r of e){let i=li(r,t);if(i)for(let[o,s]of Object.entries(i))n[o]=s}return n}function xF(e,t){if(!e)return[];let n=[];for(let r of e){let i=ui(r,t);i&&n.push(...i)}return[...new Set(n)]}function RF(e){let t=Jn(e);return sn(t).some(n=>ss(n)!==null)}function Y0(e){let t=Jn(e);return sn(t).some(n=>{let r=ss(n);if(!r)return!1;let i=Md(r);return i?yF.has(i.subcommand):!1})}function fa(e){if(e)return Gw.has(e.subcommand)?Pt(e.args,qw)?.subcommand:e.subcommand}function R0(e,t){if(e==="npx"||e==="bunx")return an(t)?.command;if(e==="pnpm")return fa(Pt(t,Dd));if(e==="npm")return fa(Pt(t,$d));if(e==="yarn")return fa(Pt(t,jw));if(e==="bun")return fa(Pt(t,Uw))}function ha(e){return e?e==="vitest"||e==="test"||e.startsWith("test:"):!1}function I0(e){return e.includes("node scripts/run-tests.mjs ")||e.endsWith("node scripts/run-tests.mjs")||e.includes("node ./scripts/run-tests.mjs ")||e.endsWith("node ./scripts/run-tests.mjs")}function cu(e){let t=e.split(" ").filter(s=>s.length>0),n=as(t);if(n.length===0)return!1;let[r,...i]=n,o=Pd.get(r);if(o){let s=i.findIndex(a=>o.test(a));return s>=0&&cu(i.slice(s+1).join(" "))}return r==="vitest"||r.endsWith("/vitest")||r.endsWith("/vitest.mjs")?!0:r==="node"?IF(i):OF(r,i)}function IF(e){return e.includes("--test")||e.some(t=>t==="vitest"||t==="vitest.mjs"||t.endsWith("/vitest")||t.endsWith("/vitest.mjs"))}function OF(e,t){return e==="npx"||e==="bunx"?ha(an(t)?.command):e==="pnpm"||e==="npm"?ha((e==="pnpm"?cs(t):ds(t))?.command)||ha(R0(e,t)):(e==="yarn"||e==="bun")&&ha(R0(e,t))}function fY(e){let t=Jn(e),n=sn(t),r=n.some(o=>!I0(o)&&cu(o)),i=n.some(I0);return{accepted:!0,command_kind:r?"direct_runner":i?"sandbox_runner":"other",tracker_isolation:"runtime_injected",trust_boundary:"provenance",advisory:r?"Accepted with runtime-injected tracker isolation. Prefer the repository sandbox runner when available for reproducible build and coverage setup.":"Accepted with runtime-injected tracker isolation and provenance checks before execution."}}function LF(e){if(jd(e))return'Linked test command skipped: Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.'}function DF(e){return e?e.map($F):[]}function $F(e){let t=e.trim(),n=ym(t)?qi(ee(e,"--add"),"--add"):{command:t},r=ve(n.command);if(!r)throw new p("--add requires command=<value> or a bare command (path=<value> is optional metadata)",m.USAGE);return ti(r),{command:r,path:ve(n.path),scope:EF(n.scope),timeout_seconds:NF(ve(n.timeout_seconds),ve(n.timeout)),pm_context_mode:Is(ve(n.pm_context_mode),"--add"),workspace_context_mode:mn(ve(n.workspace_context_mode),"--add"),env_set:li(ve(n.env_set),"--add"),env_clear:ui(ve(n.env_clear),"--add"),shared_host_safe:Rs(ve(n.shared_host_safe),"--add","shared_host_safe"),assert_stdout_contains:pn(ve(n.assert_stdout_contains)),assert_stdout_regex:nr(ve(n.assert_stdout_regex),"--add","assert_stdout_regex"),assert_stderr_contains:pn(ve(n.assert_stderr_contains)),assert_stderr_regex:nr(ve(n.assert_stderr_regex),"--add","assert_stderr_regex"),assert_stdout_min_lines:Os(ve(n.assert_stdout_min_lines),"--add"),assert_json_field_equals:Ls(ve(n.assert_json_field_equals),"--add"),assert_json_field_gte:Ds(ve(n.assert_json_field_gte),"--add"),note:ve(n.note),phase:er(n.phase,"--add")}}function ve(e){let t=e?.trim();return t&&t.length>0?t:void 0}function NF(e,t){if(e&&t&&e!==t)throw new p("--add timeout and timeout_seconds must match when both are provided",m.USAGE);let n=e??t;if(n===void 0)return;let r=Math.floor(we(n,"timeout_seconds"));if(r<=0)throw new p("--add timeout_seconds must be a positive integer",m.USAGE);return r}function MF(e){return e?e.flatMap(t=>{let n=mi(t,"--add-json");for(let r of n){let i=r.command;if(!i)throw new p("--add-json requires a non-empty command string",m.USAGE);ti(i)}return n}):[]}function PF(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new p("--remove requires command or path value",m.USAGE);let r=/^(command|path)\s*=/i.exec(n);if(r){let i=n.slice(r[0].length).trim();if(!i)throw new p("--remove requires a non-empty command=<value> or path=<value>",m.USAGE);return{kind:r[1].toLowerCase(),value:i}}if(/^[A-Za-z_][\w-]*=\S+$/u.test(n))throw new p("--remove structured selectors require command=<value> or path=<value>",m.USAGE);if(/^(?:[-*+]\s+)?(?:path|command)\s*:/i.test(n)||n.startsWith("```")){let i=ee(n,"--remove"),o=i.path!==void 0?"path":"command",s=i.path??i.command;if(!s?.trim())throw new p("--remove requires command=<value> and/or path=<value>",m.USAGE);return{kind:o,value:s.trim()}}return{kind:"either",value:n}}):[]}function FF(e){return e?[...new Set(e.map(t=>{let n=typeof t=="number"?t:Number.parseInt(t,10);if(!Number.isInteger(n)||n<1||String(n)!==String(t).trim())throw new p("--remove-index must be a positive integer",m.USAGE);return n}))]:[]}function jF(e){try{e.stdin?.end()}catch{}}function J0(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length<=x0?t:`${t.slice(0,x0-3)}...`}function X0(e){return e==="off"?!1:e==="always"?!0:process.stderr.isTTY===!0}function iu(e){try{process.stderr.write(`${e}
|
|
23
|
+
`)}catch{}}function UF(e,t){if(!X0(t))return null;let n=J0(e.command),r=Date.now();iu(`[pm test] linked-test ${e.index}/${e.total} start timeout_ms=${e.timeoutMs} command="${n}"`);let i=setInterval(()=>{let o=Date.now()-r;iu(`[pm test] linked-test ${e.index}/${e.total} running elapsed_ms=${o} command="${n}"`)},vF());return i.unref?.(),i}function GF(e,t,n,r){if(!X0(r))return;let i=J0(e.command),o=Date.now()-n,s=t.timedOut||t.maxBufferExceeded||t.exitCode!==0?"failed":"passed",a=[];t.timedOut&&a.push("reason=timeout"),t.maxBufferExceeded&&a.push("reason=max_buffer"),t.outputTruncated&&a.push("output=truncated"),t.signal&&a.push(`signal=${t.signal}`);let c=t.exitCode===null?"null":String(t.exitCode),d=a.length>0?` ${a.join(" ")}`:"";iu(`[pm test] linked-test ${e.index}/${e.total} end status=${s} exit_code=${c} elapsed_ms=${o}${d} command="${i}"`)}async function O0(e){if(!(!Number.isInteger(e)||e<=0)){if(process.platform==="win32"){await new Promise(t=>{let n=q0("taskkill",["/pid",String(e),"/T","/F"],{stdio:"ignore",windowsHide:!0});n.on("error",()=>t()),n.on("close",()=>t())});return}try{process.kill(-e,"SIGKILL");return}catch{}try{process.kill(e,"SIGKILL")}catch{}}}function qF(e){e.heartbeat&&clearInterval(e.heartbeat),e.timedOutTimer&&(clearTimeout(e.timedOutTimer),e.timedOutTimer=null),e.forceKillTimer&&(clearTimeout(e.forceKillTimer),e.forceKillTimer=null)}function KF(e,t){let n=!1;return async()=>{if(n)return;n=!0;let r=e.pid;if(!r||r<=0){try{e.kill("SIGTERM")}catch{}return}if(process.platform==="win32"){await O0(r);return}try{process.kill(-r,"SIGTERM")}catch{try{e.kill("SIGTERM")}catch{}}t.forceKillTimer=setTimeout(()=>{O0(r)},wF()),t.forceKillTimer.unref?.()}}function WF(e){return new Promise(t=>{let n=!1,r=null,i=(o,s=!1)=>{n||(n=!0,r&&(clearTimeout(r),r=null),s&&(e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy()),t(o))};e.on("exit",(o,s)=>{n||(r=setTimeout(()=>{i({code:o,signal:s},!0)},bF()),r.unref?.())}),e.on("close",(o,s)=>{i({code:o,signal:s})})})}function zF(e,t,n,r,i){return q0(e,{cwd:i,env:t,shell:!0,windowsHide:!0,detached:process.platform!=="win32",stdio:["pipe",n,r]})}async function L0(e){let t=await nu(e,"r");try{let n=(await t.stat()).size,r=Math.min(n,ga),i=Buffer.alloc(r);return r>0&&await t.read(i,0,r,0),{text:i.toString("utf8"),truncated:n>ga}}finally{await t.close()}}async function BF(e,t,n,r,i,o=process.cwd()){let s=Date.now(),a=await K0(le.join(W0(),"pm-linked-test-output-"));try{let c=le.join(a,"stdout.log"),d=le.join(a,"stderr.log"),[l,u]=await Promise.all([nu(c,"w"),nu(d,"w")]),_;try{_=zF(e,n,l.fd,u.fd,o)}catch(O){throw await Promise.all([l.close(),u.close()]),O}let h=WF(_),f;_.on("error",O=>{f=O.message}),await Promise.all([l.close(),u.close()]),jF(_);let g={heartbeat:UF(r,i),forceKillTimer:null,timedOutTimer:null},y=KF(_,g),w=!1;g.timedOutTimer=setTimeout(()=>{w=!0,y()},t),g.timedOutTimer.unref?.();let{code:v,signal:k}=await h;qF(g);let[S,b]=await Promise.all([L0(c),L0(d)]),A=S.truncated||b.truncated,E=A?`
|
|
24
|
+
[pm linked-test output truncated at ${ga} bytes per stream; the child process continued to completion]
|
|
25
|
+
`:"";!f&&await T0(e,{exitCode:v,stderr:b.text},n,o)&&(f="Linked test executable was not found. Install the tool or update the linked command before retrying.");let C={stdout:`${S.text}${E}`,stderr:b.text,exitCode:v,signal:k,timedOut:w,maxBufferExceeded:!1,outputTruncated:A,spawnError:f};return GF(r,C,s,i),C}finally{await Si(a,{recursive:!0,force:!0})}}function HF(e,t){let n=[];e.maxBufferExceeded&&n.push(`Linked test output exceeded maxBuffer=${ga} bytes. Reduce output volume or split the command.`),e.timedOut&&t>0&&n.push(`Linked test timed out after ${t}ms.`);let r=e.signal?`Linked test command terminated by signal ${e.signal}.`:void 0,i=e.spawnError?.trim()||r||"Linked test command failed.";return n.length===0?i:`${i} ${n.join(" ")}`}function VF(e){let t=[e.spawnError??"",e.stderr,e.stdout].join(`
|
|
26
|
+
`);return fF.some(n=>n.test(t))||t.split(/\r?\n/u).some(n=>hF.test(n)&&gF.test(n))}function YF(e){return VF(e)?"infra_collision":e.timedOut?"timeout":e.maxBufferExceeded?"max_buffer":e.spawnError?"spawn_error":e.signal?"signal":"assertion_failure"}function D0(e,t){for(let[n,r]of Object.entries(t.env_set))un.has(n.toUpperCase())||(e[n]=r);for(let n of t.env_clear)un.has(n.toUpperCase())||delete e[n]}function JF(e){e.PORT===void 0&&(e.PORT="0"),e.HOST===void 0&&(e.HOST="127.0.0.1"),e.PM_SHARED_HOST_SAFE===void 0&&(e.PM_SHARED_HOST_SAFE="1"),e.PLAYWRIGHT_HTML_OPEN===void 0&&(e.PLAYWRIGHT_HTML_OPEN="never"),e.PW_TEST_HTML_REPORT_OPEN===void 0&&(e.PW_TEST_HTML_REPORT_OPEN="never")}function XF(e,t){let n={...e.env_set,...t.env_set},r=[...new Set([...e.env_clear,...t.env_clear??[]])],i=t.shared_host_safe??e.shared_host_safe;return{env_set:n,env_clear:r,shared_host_safe:i}}function Q0(e,t,n){return{env_set:AF(e,"--env-set"),env_clear:xF(t,"--env-clear"),shared_host_safe:n===!0}}async function ki(e,t,n=!1,r=ou){if(await ie(e))try{await Sr("seed_linked_test",async()=>{if(await r(le.dirname(t),{recursive:!0}),n){await A0(e,t,{recursive:!0,force:!0});return}await A0(e,t,{force:!0})},{why:"Linked tests need an isolated PM context without mutating the source tracker.",nextSteps:["Reclaim capacity on the filesystem that hosts the linked-test temporary directory."]})}catch(i){if(typeof i=="object"&&i!==null&&"code"in i&&G(i))return;throw i}}async function $0(e,t,n,r=!1){for(let[i,o]of[[n.projectPmRoot,e],[n.globalPmRoot,t]])if(r){let s=await Q(Re(i));if(s!==null){let a=await x(o);await Ja({pmRoot:o,filePath:Re(o),raw:s,op:"settings:write",author:U(void 0,a.author_default),lockTtlSeconds:a.locks.ttl_seconds,lockWaitMs:a.locks.wait_ms,recordCreation:!0,message:"Seed linked-test schema settings history"})}}else await ki(Re(i),Re(o));await ki(le.join(n.projectPmRoot,"extensions"),le.join(e,"extensions"),!0),await ki(le.join(n.globalPmRoot,"extensions"),le.join(t,"extensions"),!0)}async function N0(e,t){if(!await ie(e))return;let n=await ru(e,{withFileTypes:!0});for(let r of n){if(pF.has(r.name))continue;let i=le.join(e,r.name),o=le.join(t,r.name);if(r.isDirectory()){await ki(i,o,!0);continue}r.isFile()&&await ki(i,o)}}async function M0(e,t){let n=await Q(Re(e));if(n===null||await ie(Er(e)))return;let r=await x(t);await Si(Er(t),{force:!0}),await Si(Re(t),{force:!0}),await Ja({pmRoot:t,filePath:Re(t),raw:n,op:"settings:write",author:U(void 0,r.author_default),lockTtlSeconds:r.locks.ttl_seconds,lockWaitMs:r.locks.wait_ms,recordCreation:!0,message:"Seed linked-test tracker settings history"})}async function cr(e){if(!await ie(e))return 0;let t=0,n=await ru(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||_F.has(r.name))continue;let i=le.join(e,r.name),o;try{o=await ru(i,{withFileTypes:!0})}catch{continue}for(let s of o)s.isFile()&&zt.some(a=>s.name.toLowerCase().endsWith(a))&&(t+=1)}return t}function QF(e){let t=typeof e.exitCode=="number"?e.exitCode:1;return(e.timedOut||e.maxBufferExceeded)&&t===0?1:t}function ZF(e){let t=e.trim();if(t==="true")return!0;if(t==="false")return!1;if(t==="null")return null;let n=Number(t);if(t.length>0&&Number.isFinite(n))return n;if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t)}catch{}return t}function ej(e,t){return typeof e=="object"&&e!==null&&typeof t=="object"&&t!==null?Fe(e,t):Object.is(e,t)}function tj(e,t,n){let r=[];r.push(...P0("stdout",t,e.assert_stdout_contains)),r.push(...F0("stdout",t,e.assert_stdout_regex)),r.push(...P0("stderr",n,e.assert_stderr_contains)),r.push(...F0("stderr",n,e.assert_stderr_regex)),r.push(...nj(t,e.assert_stdout_min_lines));let i=e.assert_json_field_equals??{},o=e.assert_json_field_gte??{};if(!(Object.keys(i).length>0||Object.keys(o).length>0))return r;let s;try{s=JSON.parse(t)}catch(a){return r.push(`stdout is not valid JSON for assert_json_field_* checks: ${a instanceof Error?a.message:String(a)}`),r}for(let[a,c]of Object.entries(i)){let d=Xl(s,a);if(!d.found){r.push(`assert_json_field_equals missing path "${a}"`);continue}let l=ZF(c);ej(d.value,l)||r.push(`assert_json_field_equals mismatch at "${a}" (expected=${JSON.stringify(l)} actual=${JSON.stringify(d.value)})`)}for(let[a,c]of Object.entries(o)){let d=Xl(s,a);if(!d.found){r.push(`assert_json_field_gte missing path "${a}"`);continue}if(typeof d.value!="number"||!Number.isFinite(d.value)){r.push(`assert_json_field_gte path "${a}" resolved to non-numeric value`);continue}d.value<c&&r.push(`assert_json_field_gte failed at "${a}" (expected >= ${c}, actual ${d.value})`)}return r}function P0(e,t,n){let r=[];for(let i of n??[])t.includes(i)||r.push(`${e} missing required text: "${i}"`);return r}function F0(e,t,n){let r=[];for(let i of n??[])try{new RegExp(i,"m").test(t)||r.push(`${e} failed regex assertion: /${i}/m`)}catch(o){r.push(`${e} regex assertion is invalid: /${i}/ (${o instanceof Error?o.message:String(o)})`)}return r}function nj(e,t){if(typeof t!="number")return[];let n=e.split(/\r?\n/).map(r=>r.trim()).filter(r=>r.length>0).length;return n<t?[`stdout line count ${n} is below required minimum ${t}`]:[]}function rj(e){let t=Jn(e);return/(?:^|\s)(?:--test-name-pattern|--testnamepattern)(?:=|\s)/u.test(t)?!0:sn(t).some(n=>/(?:^|\s)-t(?:=|\s)/u.test(n)&&cu(n))}function ij(e){return{root:e,schemaProjectPmPath:le.join(e,"schema","project",".agents","pm"),schemaGlobalPmPath:le.join(e,"schema","global"),trackerProjectPmPath:le.join(e,"tracker","project",".agents","pm"),trackerGlobalPmPath:le.join(e,"tracker","global"),workspaceSnapshotRoot:le.join(e,"workspace","project"),workspaceIsolatedRoot:le.join(e,"workspace","isolated")}}function oj(e,t,n){return e.some(r=>B0(r,t,n)==="snapshot")}async function sj(e,t){let n=le.join(e,".agents"),r=le.join(n,"pm");await ou(n,{recursive:!0}),await Si(r,{recursive:!0,force:!0}),await dF(t,r,process.platform==="win32"?"junction":"dir")}async function aj(e,t=Ec,n=!0){let r={defaults:!0,agentGuidance:"skip"};await t(void 0,{path:e.schemaProjectPmPath},r),await t(void 0,{path:e.schemaGlobalPmPath},r),n&&(await t(void 0,{path:e.trackerProjectPmPath},r),await t(void 0,{path:e.trackerGlobalPmPath},r))}async function cj(e,t,n){t&&(await $0(e.schemaProjectPmPath,e.schemaGlobalPmPath,t,!0),n&&(await $0(e.trackerProjectPmPath,e.trackerGlobalPmPath,t),await N0(t.projectPmRoot,e.trackerProjectPmPath),await N0(t.globalPmRoot,e.trackerGlobalPmPath),await M0(t.projectPmRoot,e.trackerProjectPmPath),await M0(t.globalPmRoot,e.trackerGlobalPmPath)))}function dj(e,t,n){return e.some(r=>{let i=r.command??"",o=i.length>0&&Y0(i),s=n?.autoPmContext===!0&&o?"auto":H0(r,t,n?.overrideLinkedPmContext===!0);return V0(s,o)==="tracker"})}async function lj(e,t){return{sourceProjectItemCount:t?await cr(t.projectPmRoot):0,sourceGlobalItemCount:t?await cr(t.globalPmRoot):0,schemaProjectItemCount:await cr(e.schemaProjectPmPath),schemaGlobalItemCount:await cr(e.schemaGlobalPmPath),trackerProjectItemCount:await cr(e.trackerProjectPmPath),trackerGlobalItemCount:await cr(e.trackerGlobalPmPath)}}function uj(e){let t=e.effectivePmContextMode==="tracker",n=t?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath,r=t?e.layout.trackerGlobalPmPath:e.layout.schemaGlobalPmPath,i=t?e.counts.trackerProjectItemCount:e.counts.schemaProjectItemCount,o=t?e.counts.trackerGlobalItemCount:e.counts.schemaGlobalItemCount,s=e.workspaceContextMode==="snapshot"?e.layout.workspaceSnapshotRoot:e.workspaceContextMode==="isolated"?e.layout.workspaceIsolatedRoot:e.sourceWorkspaceRoot,a=e.workspaceContextMode==="isolated"?"":s;return{requested_pm_context_mode:e.requestedPmContextMode,pm_context_mode:e.effectivePmContextMode,auto_pm_context_applied:e.autoPmContextApplied,is_pm_command:e.isPmCommand,is_pm_tracker_read_command:e.isPmTrackerReadCommand,source_project_pm_path:e.sourceRoots?.projectPmRoot??"",sandbox_project_pm_path:n,source_global_pm_path:e.sourceRoots?.globalPmRoot??"",sandbox_global_pm_path:r,source_project_item_count:e.counts.sourceProjectItemCount,sandbox_project_item_count:i,source_global_item_count:e.counts.sourceGlobalItemCount,sandbox_global_item_count:o,mismatch_detected:e.isPmCommand&&(e.counts.sourceProjectItemCount!==i||e.counts.sourceGlobalItemCount!==o),project_extensions_seeded:!!e.sourceRoots,global_extensions_seeded:!!e.sourceRoots,requested_workspace_context_mode:e.requestedWorkspaceContextMode,workspace_context_mode:e.workspaceContextMode,working_directory:s,source_workspace_root:a,trust:e.trust}}async function mj(e){let t=typeof e.linkedTest.pm_context_mode=="string"&&e.linkedTest.pm_context_mode.trim().length>0?wa(e.linkedTest.pm_context_mode):void 0,n=typeof e.linkedTest.command=="string"&&e.linkedTest.command.length>0?e.linkedTest.command:void 0,r=n?RF(n):!1,i=r&&n?Y0(n):!1,o=e.options?.autoPmContext===!0&&i,s=o?"auto":H0(e.linkedTest,e.runLevelPmContextMode,e.options?.overrideLinkedPmContext===!0),a=V0(s,i),c=a==="tracker"?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath;e.workspaceContextMode==="snapshot"&&await sj(e.layout.workspaceSnapshotRoot,c);let d=e.options?.pmRoot?await Kd(e.options.pmRoot,e.linkedTest,e.currentSourceRef):await Kd(e.layout.root,e.linkedTest,e.currentSourceRef);return{linkedOverridePmContextMode:t,executionContext:uj({layout:e.layout,counts:e.counts,sourceRoots:e.sourceRoots,isPmCommand:r,isPmTrackerReadCommand:i,requestedPmContextMode:s,effectivePmContextMode:a,autoPmContextApplied:o,requestedWorkspaceContextMode:e.requestedWorkspaceContextMode,workspaceContextMode:e.workspaceContextMode,sourceWorkspaceRoot:e.sourceWorkspaceRoot,trust:d})}}function j0(e,t,n){return{command:e.command,path:e.path,status:"skipped",execution_context:t,error:n}}function pj(e,t,n,r){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"assertion_failure",execution_context:t,...r?{stdout:r.stdout,stderr:r.stderr}:{},error:n}}function _j(e,t,n){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"trust_refusal",execution_context:t,error:n}}function fj(e){if(e.executionContext.trust.trusted)return null;let t=e.options?.allowUntrustedLinkedTests===!0,n=e.options?.untrustedLinkedTestsPolicyEnabled===!0;if(t&&n)return null;let r=n?"Retry with --allow-untrusted-linked-tests for this invocation, or acknowledge the current commands with --acknowledge-linked-tests.":"Set testing.allow_untrusted_linked_tests=true, then retry with --allow-untrusted-linked-tests; alternatively acknowledge the current commands with --acknowledge-linked-tests.";return _j(e.linkedTest,e.executionContext,`Linked test command is not trusted by this clone (source_ref=${e.executionContext.trust.source_ref??"unknown"}, current_ref=${e.executionContext.trust.current_source_ref??"unknown"}). ${r}`)}function hj(e){if(!e.linkedTest.command)return j0(e.linkedTest,e.executionContext,"No command configured for this linked test.");let t=LF(e.linkedTest.command);return t?j0(e.linkedTest,e.executionContext,t):null}function gj(e){return e.executionContext.pm_context_mode!=="none"?null:e.executionContext.workspace_context_mode==="source"?ya(e.linkedTest,e.executionContext,"pm_context_mode=none requires workspace_context_mode=isolated or snapshot so implicit tracker discovery cannot reach the source workspace."):e.executionContext.is_pm_command?ya(e.linkedTest,e.executionContext,"pm_context_mode=none is for self-isolating SDK tests; direct PM commands require schema, tracker, or auto context."):null}function ya(e,t,n){return{command:e.command,path:e.path,status:"refused",exit_code:null,failure_category:"config_refusal",execution_context:t,error:n}}function yj(e){let t=e.executionContext.pm_context_mode==="schema"&&e.executionContext.is_pm_tracker_read_command&&e.executionContext.mismatch_detected,n=e.options?.failOnContextMismatch===!0&&e.executionContext.is_pm_command&&e.executionContext.mismatch_detected;if(!t&&!n)return null;let r=CF({executionContext:e.executionContext,runLevelPmContextMode:e.runLevelPmContextMode,linkedOverridePmContextMode:e.linkedOverridePmContextMode}),i=e.options?.checkContext===!0?"Linked test preflight PM context mismatch detected":"Linked test PM context mismatch detected";return ya(e.linkedTest,e.executionContext,`${i} (source_project_items=${e.executionContext.source_project_item_count}, sandbox_project_items=${e.executionContext.sandbox_project_item_count}).${r}`)}function wj(e){return hj(e)||fj(e)||gj(e)||yj(e)||(e.options?.requireAssertionsForPm===!0&&e.executionContext.is_pm_command&&!TF(e.linkedTest)?ya(e.linkedTest,e.executionContext,"Linked PM command requires assertions when --require-assertions-for-pm is enabled."):null)}function vj(e){let t=XF(e.runtimeDirectives,e.linkedTest),n={...process.env,SENTRY_ENVIRONMENT:"test"};return D0(n,e.runtimeDirectives),D0(n,{env_set:e.linkedTest.env_set??{},env_clear:e.linkedTest.env_clear??[]}),t.shared_host_safe&&JF(n),n.FORCE_COLOR="0",e.executionContext.pm_context_mode==="none"?delete n.PM_PATH:n.PM_PATH=e.executionContext.sandbox_project_pm_path,n.PM_GLOBAL_PATH=e.executionContext.sandbox_global_pm_path,e.executionContext.workspace_context_mode!=="source"&&(delete n.PM_BUILD_CONSUMER_LEASE,delete n.PM_BUILD_CONSUMER_LEASE_ROOT),e.executionContext.workspace_context_mode==="isolated"?(delete n.PM_SOURCE_WORKSPACE_ROOT,delete n.PM_SOURCE_PM_PATH,delete n[Nr]):(n.PM_SOURCE_WORKSPACE_ROOT=e.executionContext.source_workspace_root,n.PM_SOURCE_PM_PATH=e.executionContext.workspace_context_mode==="snapshot"?e.executionContext.sandbox_project_pm_path:e.executionContext.source_project_pm_path,n[Nr]="read_only"),n}function bj(e,t,n,r){return{command:e.command,path:e.path,status:"passed",exit_code:0,execution_context:t,stdout:n.stdout,stderr:n.stderr,...r?{execution_receipt:r}:{}}}function U0(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:1,failure_category:"empty_run",execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:`Linked test reported an empty test run (${e.emptyRunSignal.code}). Update the test selection so at least one test executes; unfiltered commands may opt out by omitting --fail-on-empty-test-run.`}}function kj(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:QF(e.execution),failure_category:YF(e.execution),execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:HF(e.execution,e.timeoutMs)}}function Sj(e){let t=_0(e.execution.stdout,e.execution.stderr),n=e.linkedTest.phase!=="setup"&&rj(e.linkedTest.command??"");if(e.options?.failOnEmptyTestRun===!0||n){let i=la(e.execution.stdout,e.execution.stderr);if(i)return U0({...e,emptyRunSignal:i});if(n&&!t)return U0({...e,emptyRunSignal:{code:"missing_positive_execution_receipt"}})}let r=tj(e.linkedTest,e.execution.stdout,e.execution.stderr);return r.length>0?pj(e.linkedTest,e.executionContext,`Linked test assertion(s) failed: ${r.join("; ")}`,e.execution):bj(e.linkedTest,e.executionContext,e.execution,t)}async function Ej(e){let t=e.linkedTest.command??"",n=(e.linkedTest.timeout_seconds??e.defaultTimeoutSeconds??120)*1e3,r=await BF(t,n,vj(e),{index:e.index+1,total:e.total,timeoutMs:n,command:t},e.progressMode,e.executionContext.working_directory);return r.exitCode===0&&!r.timedOut&&!r.maxBufferExceeded?Sj({...e,execution:r}):kj({...e,execution:r,timeoutMs:n})}async function du(e,t,n){let r=Ts(e);for(let y of r)fr(y.command);let i=[],o=await K0(le.join(W0(),"pm-linked-test-")),s=ij(o),a=wa(n?.pmContext),c=z0(n?.workspaceContext),d=n?.progress===!0?"always":"auto",l=Q0(n?.envSet,n?.envClear,n?.sharedHostSafe),u=n?.sourceRoots,_=ii(),h=dj(r,a,n),f=oj(r,c,n?.overrideLinkedWorkspaceContext===!0),g=await ri(_);try{await aj(s,Ec,h),await ou(s.workspaceIsolatedRoot,{recursive:!0}),await cj(s,u,h),f&&await k0(_,s.workspaceSnapshotRoot,u?.projectPmRoot,h);let y=await lj(s,u),w=di(),v=b=>B0(b,c,n?.overrideLinkedWorkspaceContext===!0),k=new Set(r.filter(b=>!Ce(b)).map(v)),S=async(b,A)=>{let E=w.options(b,n),C=v(b),O=pb(b,C,k);if(O)return O;let M=await mj({linkedTest:b,layout:s,counts:y,sourceRoots:u,runLevelPmContextMode:a,options:n,requestedWorkspaceContextMode:c,workspaceContextMode:C,currentSourceRef:g,sourceWorkspaceRoot:_});return wj({linkedTest:b,executionContext:M.executionContext,runLevelPmContextMode:a,linkedOverridePmContextMode:M.linkedOverridePmContextMode,options:E})??await Ej({linkedTest:b,index:A,total:r.length,defaultTimeoutSeconds:t,runtimeDirectives:l,progressMode:d,executionContext:M.executionContext,options:E})};for(let b=0;b<r.length;b+=1){let A=r[b];i.push(w.blocked(A)??w.record(A,await S(A,b)))}}finally{await Si(s.root,{recursive:!0,force:!0,maxRetries:3,retryDelay:100})}return i}function Tj(e,t){let n=[...t];return e.filter(r=>{let i=n.findIndex(o=>gr(o,r));return i>=0&&n.splice(i,1),i<0}).length}async function Cj(e){let{id:t,pmRoot:n,settings:r,typeToFolder:i}=e,o=await V(n,t,r.id_prefix,r.item_format,i);if(!o)throw new p(`Item ${t} not found`,m.NOT_FOUND);let s=await pe(o,{schema:r.schema});return{itemId:o.id,tests:s.document.metadata.tests??[],testRuns:s.document.metadata.test_runs??[],changed:!1,removed:0}}function Aj(e,t){let n=[...e];for(let r of t)n.some(i=>gr(i,r))||n.push(r);return n}function xj(e,t,n){if(t.length===0&&n.length===0)return{tests:e,removed:0};let r=new Set(n),i=e.filter((o,s)=>r.has(s+1)?!1:!t.some(a=>a.kind==="command"?o.command===a.value:a.kind==="path"?o.path===a.value:o.command===a.value||o.path===a.value));return{tests:i,removed:e.length-i.length}}function Rj(e,t,n,r){return xj(Aj(e,t),n,r)}function Ij(e){return[e.timeout!==void 0,e.progress===!0,(e.envSet?.length??0)>0,(e.envClear?.length??0)>0,e.sharedHostSafe===!0,e.pmContext!==void 0,e.overrideLinkedPmContext===!0,e.failOnContextMismatch===!0,e.failOnSkipped===!0,e.failOnEmptyTestRun===!0,e.requireAssertionsForPm===!0,e.checkContext===!0,e.fullOutput===!0,e.autoPmContext===!0,e.workspaceContext!==void 0,e.overrideLinkedWorkspaceContext===!0,e.allowUntrustedLinkedTests===!0].some(Boolean)}function Z0(e){if(Ij(e)&&e.run!==!0)throw new p("--timeout, --progress, --env-set, --env-clear, --shared-host-safe, --pm-context, --override-linked-pm-context, --workspace-context, --override-linked-workspace-context, --allow-untrusted-linked-tests, --fail-on-context-mismatch, --fail-on-skipped, --fail-on-empty-test-run, --require-assertions-for-pm, --check-context, --full-output, and --auto-pm-context require --run",m.USAGE);if(e.acknowledgeLinkedTests===!0&&e.run===!0)throw new p("--acknowledge-linked-tests records trust without executing commands; run it separately before --run",m.USAGE);if((e.match!==void 0||e.onlyIndex!==void 0||e.onlyLast===!0)&&e.run!==!0)throw new p("--match, --only-index, and --only-last require --run",m.USAGE)}async function Oj(e){let{id:t,options:n,pmRoot:r,settings:i,typeToFolder:o,adds:s,removes:a,removeIndexes:c}=e;if(s.length===0&&a.length===0&&c.length===0)return Cj({id:t,pmRoot:r,settings:i,typeToFolder:o});let d=0,l=[],u=await he({pmRoot:r,settings:i,id:t,op:s.length>0?"tests_add":"tests_remove",author:U(n.author,i.author_default),message:n.message,force:n.force,skipNoop:!0,mutate(h){let f=h.metadata.tests??[],g=Rj(f,s,a,c);if(Ga(()=>eS(n,g.tests)),d=g.removed,(a.length>0||c.length>0)&&d===0)throw new p("No linked tests matched the requested removal selector",m.NOT_FOUND,{code:"linked_test_remove_no_match",unmatched:[...a.map(y=>`${y.kind}=${y.value}`),...c.map(y=>`index=${y}`)],required:"List linked tests and retry with an exact command/path or a current 1-based --remove-index.",examples:[`pm test ${t} --list`,`pm test ${t} --remove-index 1`]});return h.metadata.tests=g.tests,l=f,{changedFields:Fe(f,g.tests)?[]:["tests"]}}}),_=u.item.tests??[];return{itemId:u.item.id,tests:_,testRuns:u.item.test_runs??[],changed:u.changedFields.length>0,removed:d,written:u.changedFields.length>0?nd(l,_):[],storedRemoved:Tj(l,_)}}function eS(e,t){let n=wa(e.pmContext);z0(e.workspaceContext),Q0(e.envSet,e.envClear,e.sharedHostSafe);let r={match:e.match,onlyIndex:e.onlyIndex===void 0?void 0:ar(e.onlyIndex),onlyLast:e.onlyLast},i=e.timeout===void 0?void 0:we(e.timeout,"--timeout");if(i!==void 0&&i<=0)throw new p(`--timeout must be a positive number (got "${e.timeout}")`,m.USAGE);Z0(e);let o=e.run===!0?mb(d0(t,r),t):void 0;if(o)for(let s of o.selected)fr(s.command);return{defaultTimeoutSeconds:i,pmContextMode:n,runSelection:o,testsToRun:o?.selected??t}}async function Lj(e){let{options:t,runOptions:n,pmRoot:r}=e;return t.run!==!0?[]:await du(n.testsToRun,n.defaultTimeoutSeconds,{progress:t.progress,envSet:t.envSet,envClear:t.envClear,sharedHostSafe:t.sharedHostSafe,pmContext:n.pmContextMode,overrideLinkedPmContext:t.overrideLinkedPmContext,failOnContextMismatch:t.failOnContextMismatch,failOnEmptyTestRun:t.failOnEmptyTestRun===!0||(t.measure?.length??0)>0,requireAssertionsForPm:t.requireAssertionsForPm,checkContext:t.checkContext,autoPmContext:t.autoPmContext,workspaceContext:t.workspaceContext,overrideLinkedWorkspaceContext:t.overrideLinkedWorkspaceContext,pmRoot:r,allowUntrustedLinkedTests:t.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:e.untrustedLinkedTestsPolicyEnabled,sourceRoots:{projectPmRoot:r,globalPmRoot:Ye(process.cwd())}})}function Dj(e,t){let n=[];if(e.run===!0&&e.checkContext===!0){let r=au(t);n.push(`context_preflight:checked_pm_commands=${r.checked_pm_commands};tracker_read_commands=${r.tracker_read_commands};mismatches=${r.mismatches};auto_remediated=${r.auto_remediated}`)}return n}function $j(e){let t=SF(e.runResults),n=Number.parseInt(process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim()??"",10),r=process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM?.trim(),i=I(),o=yi(e.options.measure,i);return{run_id:kF("test"),kind:"test",status:t.failed>0||e.failOnSkippedTriggered?"failed":"passed",started_at:e.runStartedAt,finished_at:i,recorded_at:i,attempt:Number.isFinite(n)&&n>=1?n:void 0,resumed_from:r&&r.length>0?r:void 0,passed:t.passed,failed:t.failed,skipped:t.skipped,fail_on_skipped_triggered:e.failOnSkippedTriggered?!0:void 0,measurements:o.length>0?o:void 0,executions:e.runResults.filter(s=>s.command?.trim()).slice(0,32).map(s=>({command:s.command.trim(),requested_pm_context_mode:s.execution_context?.requested_pm_context_mode,pm_context_mode:s.execution_context?.pm_context_mode,workspace_context_mode:s.execution_context?.workspace_context_mode,trust_reason:s.execution_context?.trust.reason}))}}async function Nj(e){let{options:t,pmRoot:n,settings:r,itemId:i,runStartedAt:o,runResults:s,failOnSkippedTriggered:a,warnings:c}=e;if(t.run!==!0||!o)return;let d=$j({options:t,runStartedAt:o,runResults:s,failOnSkippedTriggered:a});if(r.testing.record_results_to_items!==!0)return{entry:d,receipt:{recorded:!1,reason:"tracking_disabled",run_id:d.run_id,recovery_command:"pm config project set test-result-tracking --policy enabled"}};try{return await _a({pmRoot:n,settings:r,itemId:i,author:U(t.author,r.author_default),message:`Track test run summary (${d.run_id})`,entry:d}),{entry:d,receipt:{recorded:!0,reason:"recorded",run_id:d.run_id}}}catch(l){if(en(l))throw l;return c.push(`test_result_tracking_failed:${i}:${l instanceof Error?l.message:String(l)}`),{entry:d,receipt:{recorded:!1,reason:"write_failed",run_id:d.run_id}}}}function G0(e,t,n){let r;if(e.metricBelow!==void 0){let i=e.metricBelow.indexOf("="),o=e.metricBelow.slice(0,i).trim(),s=e.metricBelow.slice(i+1).trim(),a=Number(s);if(i<=0||o.length===0||s.length===0||!Number.isFinite(a))throw new p("--metric-below must use name=value",m.USAGE);r=Vk(t,o,a)}return{measurements:n?.measurements,metric_below:r,metric_diff:e.metricDiff===void 0?void 0:Yk(t,e.metricDiff)}}async function Mj(e,t,n){if(e.acknowledgeLinkedTests===!0)return Yw(t,n,I())}function Pj(e){let{item:t,runResults:n,failureCategories:r,runSelection:i,failOnSkippedTriggered:o,warnings:s,recording:a,measurementProjection:c,restoreScope:d}=e,l=jj(t,e.fullHistory),u=Fj(t,i,l,d),{counts:_,receipts:h}=Ko(l);return{ok:n.every(f=>f.status!=="failed"&&f.status!=="refused")&&o!==!0,id:t.itemId,tests:u.tests,...u.omitted,run_results:n,...e.ran?{failure_categories:r}:{},selection:i?{selector:i.selector,requested:i.requested,selected_indexes:i.selected_indexes,selected_count:i.selected_count,skipped_count:i.skipped_count,...i.setup_indexes?{setup_indexes:i.setup_indexes}:{}}:void 0,fail_on_skipped_triggered:o?!0:void 0,warnings:s.length>0?s:void 0,changed:t.changed||a?.receipt.recorded===!0,...a?{evidence_recording:a.receipt}:{},count:u.count,...t.removed>0?{removed:t.removed}:{},..._,...c,...h}}function Fj(e,t,n,r){return n!==void 0?{tests:n.entries,count:n.returned_count,omitted:{}}:t!==void 0&&t.selector!==null&&t.skipped_count>0?{tests:t.selected,count:e.tests.length,omitted:{tests_omitted:{count:e.tests.length-t.selected.length,restore_with:h0(e.itemId,r)}}}:{tests:e.tests,count:e.tests.length,omitted:{}}}function jj(e,t){if(e.written!==void 0)return Xr({collectionKey:"tests",stored:e.tests,written:e.written,removedCount:e.storedRemoved,fullHistory:t})}function Uj(e,t){let n=e.tests[e.updated_index-1],r=Xr({collectionKey:"tests",stored:e.tests,written:e.changed&&n!==void 0?[n]:[],removedCount:0,fullHistory:t}),{counts:i,receipts:o}=Ko(r);return{...e,tests:r.entries,run_results:[],count:r.returned_count,...i,...o}}async function tS(e,t,n){let r=l0(t);if(r){u0(t),Z0(t),Jl(e,t,n,R(process.cwd(),n.path));let M=await p0(e,{...r,author:t.author,message:t.message,force:t.force},n);return Uj(M,t.fullHistory===!0)}let i=En(),o=R(process.cwd(),n.path);await j(o);let s=await x(o);Jl(e,t,n,o),yi(t.measure,"validation"),G0(t,[],void 0);let a=P(s,N()),c=await i.resolveList(t.add,"--add"),d=await i.resolveList(t.addJson,"--add-json"),l=await i.resolveList(t.remove,"--remove"),u=[...DF(c),...MF(d)],_=await Xn(u,U(t.author,s.author_default),I())??[],h=PF(l),f=FF(t.removeIndex),g=await Oj({id:e,options:t,pmRoot:o,settings:s,typeToFolder:a.type_to_folder,adds:_,removes:h,removeIndexes:f}),y=Ga(()=>eS(t,g.tests)),w=await Mj(t,o,g.tests),v=t.run===!0?I():void 0,k=await Lj({options:t,runOptions:y,pmRoot:o,untrustedLinkedTestsPolicyEnabled:s.testing.allow_untrusted_linked_tests});g0(e,t,n,o,k);let S=tr(k),b=t.run===!0&&t.failOnSkipped===!0&&k.some(M=>M.status==="skipped"),A=Dj(t,k);w&&A.push(`linked_test_trust_acknowledged:${w.acknowledged}`);let E=await Nj({options:t,pmRoot:o,settings:s,itemId:g.itemId,runStartedAt:v,runResults:k,failOnSkippedTriggered:b,warnings:A}),C=E?.receipt.recorded?tu([...g.testRuns,E.entry]):g.testRuns,O=G0(t,C,E?.entry);return Pj({item:g,runResults:k,failureCategories:S,runSelection:y.runSelection,failOnSkippedTriggered:b,warnings:A,recording:E,measurementProjection:O,restoreScope:f0(n,o),ran:t.run===!0,fullHistory:t.fullHistory===!0})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bc840a99-3b4c-5386-81e2-5480897f2d19")}catch{}})();var Gj=(e,t)=>{if(e===void 0)return;let n=ce(e,t);if(!n){let r=t.definitions.map(i=>i.id);throw new p(`Invalid --status value "${e}". Allowed: ${r.join(", ")}`,m.USAGE)}return n},qj=e=>{if(e===void 0)return;let t=we(e,"timeout");if(t<=0)throw new p("timeout must be a positive number",m.USAGE);return t},nS=(e,t)=>{if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<0)throw new p(`${t} must be a non-negative integer`,m.USAGE);return n},Kj=e=>e instanceof Error?e.message:String(e),Wj=()=>{let e=process.env.PM_BACKGROUND_TEST_RUN_ID?.trim();return e&&e.length>0?e:`test-all-local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`},zj=e=>e.trim().replaceAll(/\s+/g," "),Bj=e=>!e||Object.keys(e).length===0?"{}":JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))),Hj=e=>!e||e.length===0?"[]":JSON.stringify([...e].sort((t,n)=>t.localeCompare(n))),Vj=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"none"},Yj=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"source"},va=e=>[...new Set(e??[])].sort((t,n)=>t.localeCompare(n)),rS=e=>Object.fromEntries(Object.entries(e??{}).sort(([t],[n])=>t.localeCompare(n))),Jj=e=>typeof e=="number"?e:void 0,Xj=e=>{let t={assert_stdout_contains:va(e.assert_stdout_contains),assert_stdout_regex:va(e.assert_stdout_regex),assert_stderr_contains:va(e.assert_stderr_contains),assert_stderr_regex:va(e.assert_stderr_regex),assert_stdout_min_lines:Jj(e.assert_stdout_min_lines),assert_json_field_equals:rS(e.assert_json_field_equals),assert_json_field_gte:rS(e.assert_json_field_gte)};return JSON.stringify(t)},Qj=e=>{let t=uu(e.command);return t!==void 0?`command:${e.scope}:${zj(t)}`:`path:${e.scope}:${uu(e.path)??""}`},lu=e=>{let t=Bj(e.env_set),n=Hj(e.env_clear),r=Vj(e.pm_context_mode),i=Yj(e.workspace_context_mode),o=e.shared_host_safe===!0?"true":"false",s=Xj(e);return`${Qj(e)}:${t}:${n}:${r}:${i}:${o}:${s}`},Zj=(e,t)=>t===void 0?e:e===void 0||t>e?t:e,eU=e=>{let t=0,n=0,r=0;for(let i of e){if(i.status==="passed"){t+=1;continue}if(i.status==="failed"||i.status==="refused"){n+=1;continue}r+=1}return{passed:t,failed:n,skipped:r}},tU=(e,t)=>{for(let[n,r]of Object.entries(t))e[n]+=r},ba=(e,t)=>{if(e.progress===!0)try{process.stderr.write(`[pm test-all] ${t}
|
|
27
|
+
`)}catch{}},nU=async(e,t,n)=>{let r=[],i=0;for(let o of e){let s=await tS(o.id,{run:!1},{...t,path:n});i+=s.tests.length,r.push({item:o,tests:s.tests})}return{itemTests:r,linkedTests:i}},rU=async e=>{let t=W(e.settings.schema),n=P(e.settings,N()),r=Gj(e.options.status,t),i=nS(e.options.limit,"--limit"),o=nS(e.options.offset,"--offset")??0,s=(await Te(e.pmRoot,e.settings.item_format,n.type_to_folder,void 0,e.settings.schema)).filter(a=>r?a.status===r:!0).sort((a,c)=>a.id.localeCompare(c.id));return{filteredItems:i===void 0?s.slice(o):s.slice(o,o+i),statusFilter:r,limitFilter:i,offsetFilter:o}},iS=e=>{let t=e.filter(Ce).map(({provenance:n,provenance_invalid:r,updated_by:i,updated_at:o,note:s,timeout_seconds:a,...c})=>c);return t.length===0?"":Z(t)},oS=(e,t)=>t.length===0?lu(e):`${lu(e)}:setup[${t}]`,iU=e=>{let t=new Map;for(let{tests:n}of e){let r=iS(n);for(let i of n){if(Ce(i))continue;let o=oS(i,r);if(!t.has(o)){t.set(o,i.timeout_seconds);continue}t.set(o,Zj(t.get(o),i.timeout_seconds))}}return t};function oU(e,t){try{fr(e.command);return}catch(n){if(!(n instanceof p)||n.code!=="linked_test_command_not_executable")throw n;return{command:e.command,path:e.path,status:"refused",exit_code:null,failure_category:"config_refusal",error:`Linked test refused for ${t}: ${n.message}`}}}var sU=(e,t)=>{let n=[],r=[],i=Ts(e.tests),o=iS(i),s=di();return{plans:i.map(a=>{let c=Ce(a),d=c?lu(a):oS(a,o),l=s.blocked(a);if(l)return{test:a,key:d,duplicate:!1,refusal:l};let u=oU(a,e.item.id);if(u)return{test:a,key:d,duplicate:!1,refusal:s.record(a,u)};if(c)return n.push(a),{test:a,key:d,duplicate:!1,refusal:void 0};if(t.seenTestKeys.has(d))return{test:a,key:d,duplicate:!0,refusal:void 0};t.seenTestKeys.add(d),r.push(d);let _=t.effectiveTimeoutByKey.get(d);return n.push(_===void 0?a:{...a,timeout_seconds:_}),{test:a,key:d,duplicate:!1,refusal:void 0}}),testsToRun:n,reservedKeys:r}},aU=(e,t,n)=>{if(e.some(r=>r.phase==="setup"&&r.status!=="passed"))for(let r of t)n.seenTestKeys.delete(r)},cU=async(e,t)=>{let{plans:n,testsToRun:r,reservedKeys:i}=sU(e,t),o=r.length>0?await du(r,t.defaultTimeoutSeconds,{progress:t.options.progress,sourceRoots:t.sourceRoots,envSet:t.options.envSet,envClear:t.options.envClear,sharedHostSafe:t.options.sharedHostSafe,pmContext:t.options.pmContext,overrideLinkedPmContext:t.options.overrideLinkedPmContext,failOnContextMismatch:t.options.failOnContextMismatch,failOnEmptyTestRun:t.options.failOnEmptyTestRun,requireAssertionsForPm:t.options.requireAssertionsForPm,checkContext:t.options.checkContext,autoPmContext:t.options.autoPmContext,workspaceContext:t.options.workspaceContext,overrideLinkedWorkspaceContext:t.options.overrideLinkedWorkspaceContext,pmRoot:t.pmRoot,allowUntrustedLinkedTests:t.options.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:t.settings.testing.allow_untrusted_linked_tests}):[];aU(o,i,t);let s=0,a=di(),c=n.map(({test:_,key:h,duplicate:f,refusal:g})=>{if(g)return a.blocked(_)??g;if(!f){let y=o[s];return s+=1,a.blocked(_)??a.record(_,y)}return a.blocked(_)??{command:_.command,path:_.path,status:"skipped",error:`Duplicate linked test skipped (key=${h}).`}}),d=eU(c),l=tr(c),u=await uU(e,d,c,t);return{passed:d.passed,failed:d.failed,skipped:d.skipped,trackingWarnings:u,failureCategories:l,result:{ok:d.failed===0&&!(t.options.failOnSkipped===!0&&d.skipped>0),id:e.item.id,status:e.item.status,test_count:e.tests.length,passed:d.passed,failed:d.failed,skipped:d.skipped,run_results:c,failure_categories:l}}},dU=(e,t)=>[e.failed>0,t.failOnSkipped===!0&&e.skipped>0].includes(!0),lU=e=>e?!0:void 0,uU=async(e,t,n,r)=>{if(!r.trackingEnabled)return[];try{let i=dU(t,r.options);await _a({pmRoot:r.pmRoot,settings:r.settings,itemId:e.item.id,author:r.trackingAuthor,message:`Track test-all run summary (${r.trackingRunId})`,entry:{run_id:r.trackingRunId,kind:"test-all",status:i?"failed":"passed",started_at:r.runStartedAt,finished_at:I(),recorded_at:I(),attempt:r.trackingAttempt,resumed_from:r.trackingResumedFrom,passed:t.passed,failed:t.failed,skipped:t.skipped,items:1,linked_tests:e.tests.length,fail_on_skipped_triggered:lU(r.options.failOnSkipped===!0&&t.skipped>0),executions:n.filter(o=>o.command?.trim()).slice(0,32).map(o=>({command:o.command.trim(),requested_pm_context_mode:o.execution_context?.requested_pm_context_mode,pm_context_mode:o.execution_context?.pm_context_mode,workspace_context_mode:o.execution_context?.workspace_context_mode,trust_reason:o.execution_context?.trust.reason}))}})}catch(i){return en(i)?(r.revisionConflicts.push(i),[]):[`test_result_tracking_failed:${e.item.id}:${Kj(i)}`]}return[]},mU=()=>{let e=process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim(),t=e?Number.parseInt(e,10):Number.NaN;return Number.isFinite(t)&&t>=1?t:void 0},uu=e=>{let t=e?.trim();return t&&t.length>0?t:void 0},pU=e=>({pmRoot:e.pmRoot,settings:e.settings,options:e.options,defaultTimeoutSeconds:e.defaultTimeoutSeconds,sourceRoots:{projectPmRoot:e.pmRoot,globalPmRoot:Ye(process.cwd())},seenTestKeys:new Set,effectiveTimeoutByKey:iU(e.itemTests),trackingEnabled:e.settings.testing.record_results_to_items===!0,trackingAuthor:U(e.options.author,e.settings.author_default),trackingRunId:Wj(),trackingAttempt:mU(),trackingResumedFrom:uu(process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM),runStartedAt:e.runStartedAt,revisionConflicts:[]}),_U=(e,t,n)=>{let r={results:[],passed:0,failed:0,skipped:0,failureCategories:tr([]),trackingWarnings:[]},i=e.failOnEmptyTestRun===!0&&t===0;return i&&(r.failed+=1,r.failureCategories.empty_run+=1,r.trackingWarnings.push(`empty_linked_test_selection:items=${n.length};linked_tests=0;fail_on_empty_test_run=true`)),{accumulation:r,failOnEmptyTestRunTriggered:i}},fU=async(e,t,n)=>{for(let[i,o]of e.entries()){ba(t.options,`item ${i+1}/${e.length} start id=${o.item.id} linked_tests=${o.tests.length}`);let s=await cU(o,t);tU(n.failureCategories,s.failureCategories),n.passed+=s.passed,n.failed+=s.failed,n.skipped+=s.skipped,n.trackingWarnings.push(...s.trackingWarnings),n.results.push(s.result),ba(t.options,`item ${i+1}/${e.length} end id=${o.item.id} status=${s.failed===0?"passed":"failed"} passed=${s.passed} failed=${s.failed} skipped=${s.skipped}`)}let[r]=t.revisionConflicts;if(r!==void 0)throw r},hU=(e,t)=>{if(e.checkContext!==!0)return;let n=t.results.flatMap(i=>i.run_results),r=au(n);t.trackingWarnings.push(`context_preflight:checked_pm_commands=${r.checked_pm_commands};tracker_read_commands=${r.tracker_read_commands};mismatches=${r.mismatches};auto_remediated=${r.auto_remediated}`)},gU=e=>({ok:e.ok,totals:{items:e.filteredItems.length,linked_tests:e.linkedTests,passed:e.accumulation.passed,failed:e.accumulation.failed,skipped:e.accumulation.skipped,failure_categories:e.accumulation.failureCategories},failed:e.accumulation.failed,passed:e.accumulation.passed,skipped:e.accumulation.skipped,fail_on_skipped_triggered:e.failOnSkippedTriggered?!0:void 0,fail_on_empty_test_run_triggered:e.failOnEmptyTestRunTriggered?!0:void 0,warnings:e.accumulation.trackingWarnings.length>0?e.accumulation.trackingWarnings:void 0,results:e.accumulation.results}),yU=e=>[`selection items=${e.filteredItems.length}`,`linked_tests=${e.linkedTests}`,e.statusFilter===void 0?"":`status=${e.statusFilter}`,e.limitFilter===void 0?"":`limit=${e.limitFilter}`,e.offsetFilter>0?`offset=${e.offsetFilter}`:""].filter(t=>t.length>0).join(" "),wU=async(e,t)=>{let n=R(process.cwd(),t.path);await j(n);let r=await x(n),i=await rU({pmRoot:n,settings:r,options:e}),o=qj(e.timeout),s=I(),a=await nU(i.filteredItems,t,n);return ba(e,yU({...i,linkedTests:a.linkedTests})),{pmRoot:n,settings:r,filteredItems:i.filteredItems,itemTests:a.itemTests,linkedTests:a.linkedTests,defaultTimeoutSeconds:o,runStartedAt:s}},vU=e=>{let t=e.options.failOnSkipped===!0&&e.accumulation.skipped>0,n=![e.accumulation.failed>0,t,e.failOnEmptyTestRunTriggered].includes(!0);return{failOnSkippedTriggered:t,ok:n}},MY=async(e,t)=>{let n=await wU(e,t),{accumulation:r,failOnEmptyTestRunTriggered:i}=_U(e,n.linkedTests,n.filteredItems),o=pU({pmRoot:n.pmRoot,settings:n.settings,options:e,itemTests:n.itemTests,defaultTimeoutSeconds:n.defaultTimeoutSeconds,runStartedAt:n.runStartedAt});await fU(n.itemTests,o,r),hU(e,r);let s=vU({options:e,accumulation:r,failOnEmptyTestRunTriggered:i});return ba(e,`end status=${s.ok?"passed":"failed"} items=${n.filteredItems.length} linked_tests=${n.linkedTests} passed=${r.passed} failed=${r.failed} skipped=${r.skipped}`),gU({ok:s.ok,filteredItems:n.filteredItems,linkedTests:n.linkedTests,accumulation:r,failOnSkippedTriggered:s.failOnSkippedTriggered,failOnEmptyTestRunTriggered:i})};import JU from"node:os";import dr from"node:fs/promises";import{spawn as lS}from"node:child_process";import{createHash as bU,randomBytes as kU}from"node:crypto";import Ei from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7a7096c6-a9c3-5d8e-96e4-ed1b0218234e")}catch{}})();var uS=new Set(["queued","running"]),fu=new Set(["passed","failed","stopped","canceled"]),SU=3e3,EU=3e3,TU=3e4,mS=100,sS=100;function pS(){return Date.now()}function _S(e){return e.map(t=>t.trim()).filter(t=>t.length>0)}function CU(e){let t=e.join(" ").replaceAll(/\s+/g," ").trim();return t.length<=180?t:`${t.slice(0,177)}...`}function AU(){let e=Date.now().toString(36),t=kU(3).toString("hex");return`tr-${e}-${t}`}function xU(e,t,n){let r={kind:e,command:_S(t),pm_root:Ei.resolve(n)};return bU("sha256").update(JSON.stringify(r)).digest("hex")}function lr(e){if(!Number.isInteger(e)||!e||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)==="EPERM"}}async function RU(e){await Ct(cm(e)),await Ct(Ma(e)),await Ct(dm(e)),await Ct(lm(e)),await Ct(pm(e))}async function fS(e,t){try{let n=JSON.parse(e);if(!n||typeof n!="object"||typeof n.id!="string")throw new Error("invalid run record payload");return n}catch(n){throw new p(`Failed to parse background test run record at ${t}: ${n instanceof Error?n.message:String(n)}`,m.GENERIC_FAILURE)}}async function pt(e,t){let n={...t,updated_at:I()};await je(Pa(e,t.id),`${JSON.stringify(n,null,2)}
|
|
28
|
+
`)}async function ur(e,t){let n=Pa(e,t),r=await Q(n);return r?fS(r,n):null}async function IU(e){let t=Ma(e);return await ie(t)?(await dr.readdir(t,{withFileTypes:!0})).filter(n=>n.isFile()&&n.name.endsWith(".json")).map(n=>Ei.join(t,n.name)).sort((n,r)=>r.localeCompare(n)):[]}function OU(e){let t=e.match(/^VmRSS:\s+(\d+)\s+kB$/m);if(t)return Number.parseInt(t[1],10)*1024}async function LU(e){if(process.platform==="linux")try{let t=await dr.readFile(`/proc/${e}/status`,"utf8");return OU(t)}catch{return}}function DU(e){let t=e.lastIndexOf(")");if(t<0)return{};let n=e.slice(t+2).trim().split(/\s+/),r=Number.parseInt(n[11],10),i=Number.parseInt(n[12],10);return!Number.isFinite(r)||!Number.isFinite(i)?{}:{cpu_user_seconds:r/sS,cpu_system_seconds:i/sS}}async function $U(e){if(process.platform!=="linux")return{};try{let t=await dr.readFile(`/proc/${e}/stat`,"utf8");return DU(t)}catch{return{}}}async function pu(e){let t=e.child_pid??e.worker_pid;if(!lr(t))return;let n=await LU(t),r=await $U(t),i=e.started_at?Date.parse(e.started_at):Number.NaN,o=Number.isFinite(i)?Math.max(0,(pS()-i)/1e3):void 0;return{recorded_at:I(),rss_bytes:n,cpu_user_seconds:r.cpu_user_seconds,cpu_system_seconds:r.cpu_system_seconds,uptime_seconds:o}}function mu(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function NU(e,t){if(!t||typeof t!="object")return{summary:{passed:0,failed:1,skipped:0},parsedResult:null};let n=t;if(e==="test-all"){let a=n.totals??{};return{summary:{items:typeof a.items=="number"?a.items:void 0,linked_tests:typeof a.linked_tests=="number"?a.linked_tests:void 0,passed:mu(a.passed),failed:mu(a.failed),skipped:mu(a.skipped),fail_on_skipped_triggered:n.fail_on_skipped_triggered===!0?!0:void 0},parsedResult:t}}let r=Array.isArray(n.run_results)?n.run_results:[],i=0,o=0,s=0;for(let a of r){if(!a||typeof a!="object")continue;let c=a.status;if(c==="passed"){i+=1;continue}if(c==="failed"||c==="refused"){o+=1;continue}s+=1}return{summary:{passed:i,failed:o,skipped:s,fail_on_skipped_triggered:n.fail_on_skipped_triggered===!0?!0:void 0},parsedResult:t}}function MU(e){let t=e.trim();if(t.length===0)return null;let n=t.match(/\[pm test-all\]\s+item\s+(\d+)\/(\d+)\s+(start|end)\s+id=([^\s]+)/i);if(n){let d=Number.parseInt(n[1],10),l=Number.parseInt(n[2],10);return{item_index:d,item_total:l,item_id:n[4],linked_test_index:void 0,linked_test_total:void 0,current_command:void 0,elapsed_ms:void 0,heartbeat_at:I(),phase:n[3]?.toLowerCase()==="end"?"finished":"running"}}let r=t.match(/\[pm test\]\s+linked-test\s+(\d+)\/(\d+)\s+(start|running|end)(?:.*elapsed_ms=(\d+))?/i);if(!r)return null;let i=Number.parseInt(r[1],10),o=Number.parseInt(r[2],10),s=r[4]?Number.parseInt(r[4],10):void 0,a=t.match(/\scommand="((?:\\.|[^"\\])*)"/),c=a?a[1].replaceAll('\\"','"').replaceAll("\\\\","\\"):void 0;return{linked_test_index:i,linked_test_total:o,current_command:c,elapsed_ms:Number.isFinite(s)?s:void 0,heartbeat_at:I(),phase:r[3]?.toLowerCase()==="end"?"finished":"running"}}function PU(e){return e.split(/\r?\n/).map(t=>t.trimEnd()).filter(t=>t.length>0)}function _u(e,t){if(t<=0)return[];let n=PU(e);return n.length<=t?n:n.slice(n.length-t)}async function hS(e){let t=process.env.PM_BACKGROUND_CLI_ENTRY?.trim();if(t&&t.length>0){let i=Ei.resolve(e,t);if(await ie(i))return i}let n=Ei.resolve(e,"dist","cli.js");if(await ie(n))return n;let r=process.argv[1]?.trim();if(r&&r.length>0){let i=Ei.resolve(e,r);if(await ie(i))return i}throw new p("Unable to resolve a CLI entrypoint for background test runs. Build the project or set PM_BACKGROUND_CLI_ENTRY.",m.GENERIC_FAILURE)}async function Ti(e,t){if(!uS.has(t.status)||lr(t.worker_pid)||t.finished_at)return t;let n={...t,status:"failed",finished_at:I(),error:t.error??"Background test run worker exited before writing terminal status."};return await pt(e,n),n}async function hu(e){await RU(e.pmRoot);let t=_S(e.commandArgs);if(t.length===0)throw new p("Background test run requires command arguments.",m.USAGE);let n=xU(e.kind,t,e.pmRoot),r=await yu(e.pmRoot,{});for(let l of r){let u=await Ti(e.pmRoot,l);if(u.fingerprint===n&&!(!uS.has(u.status)||!lr(u.worker_pid)))return{started:!1,run:{...u,duplicate_of:u.id},duplicate_of:u.id}}let i=AU(),o=I(),s=um(e.pmRoot,i),a=mm(e.pmRoot,i),c=_m(e.pmRoot,i);await dr.writeFile(s,"","utf8"),await dr.writeFile(a,"","utf8");let d={id:i,kind:e.kind,status:"queued",created_at:o,updated_at:o,requested_by:e.requestedBy,fingerprint:n,command_args:t,command_label:CU(t),pm_root:e.pmRoot,global_pm_root:e.globalPmRoot,target_id:e.targetId,status_filter:e.statusFilter,attempt:typeof e.attempt=="number"&&Number.isFinite(e.attempt)&&e.attempt>=1?Math.floor(e.attempt):1,resumed_from:e.resumedFrom,resumed_by:e.resumedBy,stdout_path:s,stderr_path:a,result_path:c,progress:{phase:"queued",message:"Queued for background execution.",heartbeat_at:o}};return await pt(e.pmRoot,d),{started:!0,run:d}}async function gu(e){let t=await ur(e.pmRoot,e.runId);if(!t)throw new p(`Background test run ${e.runId} not found`,m.NOT_FOUND);if(fu.has(t.status))throw new p(`Background test run ${t.id} is already terminal (${t.status}).`,m.CONFLICT);let n=await hS(process.cwd()),r=[];e.noExtensions===!0&&r.push("--no-extensions"),r.push("--path",t.pm_root,"test-runs-worker",t.id);let i={...process.env,PM_PATH:t.pm_root,PM_GLOBAL_PATH:t.global_pm_root,PM_BACKGROUND_TEST_RUN_ID:t.id,PM_BACKGROUND_TEST_RUN_ATTEMPT:String(t.attempt),PM_BACKGROUND_TEST_RUN_RESUMED_FROM:t.resumed_from??"",FORCE_COLOR:"0"},o=lS(process.execPath,[n,...r],{cwd:process.cwd(),env:i,detached:!0,stdio:"ignore",windowsHide:!0});o.unref();let s={...t,status:"queued",worker_pid:o.pid,progress:{phase:"queued",message:"Worker process started.",heartbeat_at:I()}};return await pt(e.pmRoot,s),s}async function aS(e,t,n){await e,await dr.appendFile(t,n,"utf8")}function gS(e,t){let n=Number.parseInt(process.env[e]??"",10);return Number.isFinite(n)&&n>0?n:t}function FU(e){return{...process.env,PM_PATH:e.pm_root,PM_GLOBAL_PATH:e.global_pm_root,FORCE_COLOR:"0"}}function jU(e,t){return t?["--no-extensions",...e.command_args]:[...e.command_args]}function UU(e,t){let n=Promise.resolve();return{schedule(){n=n.then(async()=>{try{await pt(e,t)}catch{}})},async flush(){await n}}}function cS(e,t){try{e.kill(t)}catch{}}async function GU(e,t,n,r){n.stopRequested||(n.stopRequested=!0,e.stop_requested_at=I(),e.progress={...e.progress,phase:"stopping",message:"Stop requested for background run.",heartbeat_at:I()},r(),cS(t,"SIGTERM"),setTimeout(()=>cS(t,"SIGKILL"),gS("PM_BACKGROUND_RUN_FORCE_KILL_DELAY_MS",EU)).unref?.())}function qU(e,t,n){return{phase:n,message:e,heartbeat_at:I(),item_index:t.item_index,item_total:t.item_total,item_id:t.item_id,linked_test_index:void 0,linked_test_total:void 0,current_command:void 0,elapsed_ms:void 0}}function KU(e,t,n,r){return{phase:r,message:e,heartbeat_at:I(),item_index:n.item_index??t.progress?.item_index,item_total:n.item_total??t.progress?.item_total,item_id:n.item_id??t.progress?.item_id,linked_test_index:n.linked_test_index,linked_test_total:n.linked_test_total,current_command:n.current_command,elapsed_ms:n.elapsed_ms}}function dS(e,t,n){let r=MU(t);if(!r)return!1;let i=e.progress?.phase==="stopping"?"stopping":"running";return e.progress=r.item_id?qU(t,r,i):KU(t,e,r,i),r.phase==="finished"&&!n&&(e.progress.phase="running"),!0}function WU(e){if(e.trim().length===0)return null;try{return JSON.parse(e)}catch{return null}}function zU(e,t,n){return n?"stopped":e===0&&t.failed===0&&t.fail_on_skipped_triggered!==!0?"passed":"failed"}function BU(e,t){return{phase:"finished",message:t?"Background run stopped.":`Background run finished with status=${e.status}.`,heartbeat_at:I(),item_index:e.progress?.item_index,item_total:e.progress?.item_total,item_id:e.progress?.item_id,linked_test_index:e.progress?.linked_test_index,linked_test_total:e.progress?.linked_test_total,current_command:e.progress?.current_command,elapsed_ms:e.progress?.elapsed_ms}}async function HU(e,t,n){if(t!==null){await je(e.result_path,`${JSON.stringify(t,null,2)}
|
|
29
|
+
`);return}await je(e.result_path,`${JSON.stringify({parse_error:"Background run output was not valid JSON.",stdout_excerpt:_u(n,mS)},null,2)}
|
|
30
|
+
`)}async function yS(e,t,n=!1){let r=await ur(e,t);if(!r)throw new p(`Background test run ${t} not found`,m.NOT_FOUND);let i={...r,status:"running",started_at:r.started_at??I(),worker_pid:process.pid,progress:{phase:"running",message:"Worker started.",heartbeat_at:I()}},o=await hS(process.cwd()),s=FU(i);await pt(e,i);let a=jU(i,n),c=lS(process.execPath,[o,...a],{cwd:process.cwd(),env:s,detached:!1,stdio:["ignore","pipe","pipe"],windowsHide:!0});i.child_pid=c.pid;let d=UU(e,i),l=d.schedule,u=Promise.resolve(),_=Promise.resolve(),h="",f="",g={stopRequested:!1},y=()=>{GU(i,c,g,l)};process.on("SIGTERM",y),process.on("SIGINT",y);let w=setInterval(()=>{(async()=>(i.resource=await pu(i),i.progress.heartbeat_at=I(),l()))()},gS("PM_BACKGROUND_RUN_RESOURCE_INTERVAL_MS",SU));w.unref?.(),c.stdout?.on("data",E=>{let C=E.toString("utf8");h+=C,u=aS(u,i.stdout_path,C)}),c.stderr?.on("data",E=>{let C=E.toString("utf8");_=aS(_,i.stderr_path,C),f+=C;let O=f.split(/\r?\n/);f=O.pop();let M=!1;for(let T of O){let F=T.trimEnd();F.length>0&&dS(i,F,g.stopRequested)&&(M=!0)}M&&l()});let v=null,k=null;try{({code:v,signal:k}=await new Promise(E=>{c.on("close",(C,O)=>{E({code:C,signal:O})})}))}finally{clearInterval(w),process.off("SIGTERM",y),process.off("SIGINT",y)}await u,await _;let S=f.trimEnd();S.length>0&&dS(i,S,g.stopRequested)&&l(),f="";let b=WU(h),A=NU(i.kind,b);return i.summary=A.summary,i.exit_code=typeof v=="number"?v:void 0,i.signal=k??void 0,i.finished_at=I(),i.status=zU(i.exit_code,A.summary,g.stopRequested),i.progress=BU(i,g.stopRequested),i.resource=await pu(i),await HU(i,b,h),await pt(e,i),await d.flush(),i}async function yu(e,t){let n=await IU(e),r=[];for(let a of n){let c=await Q(a);if(!c)continue;let d=await fS(c,a);r.push(d)}let i=[];for(let a of r)i.push(await Ti(e,a));let o=(t.status?i.filter(a=>a.status===t.status):i).sort((a,c)=>{let d=Date.parse(c.updated_at)-Date.parse(a.updated_at);return Number.isFinite(d)&&d!==0?d:c.id.localeCompare(a.id)}),s=typeof t.limit=="number"&&t.limit>=0?t.limit:void 0;return s===void 0?o:o.slice(0,s)}async function wS(e,t){let n=await ur(e,t);if(!n)throw new p(`Background test run ${t} not found`,m.NOT_FOUND);let r=await Ti(e,n),i=lr(r.worker_pid),o=lr(r.child_pid);r.status==="running"&&!o&&!r.finished_at&&!i&&(r.status="failed",r.finished_at=I(),r.error=r.error??"Background run process exited unexpectedly.",await pt(e,r)),r.status==="running"&&(r.resource=await pu(r),await pt(e,r));let s=r.progress?.heartbeat_at,a=s?Date.parse(s):Number.NaN,c=Number.isFinite(a)?Math.max(0,pS()-a):void 0,d=Number.parseInt(process.env.PM_BACKGROUND_RUN_HEARTBEAT_STALE_MS??"",10),l=Number.isFinite(d)&&d>0?d:TU,u=r.status==="running"?c!==void 0&&c>l?"stale":"healthy":"inactive";return{run:r,health:{state:u,last_heartbeat_at:s,heartbeat_lag_ms:c,worker_alive:i,child_alive:o}}}function VU(e,t){let n=t?"SIGKILL":"SIGTERM";if(!lr(e.worker_pid)||!e.worker_pid)return"none";try{return process.kill(e.worker_pid,n),n}catch{return"none"}}function YU(e,t){return{phase:"stopping",message:t==="none"?"Run marked stopped.":`Stop requested via ${t}.`,heartbeat_at:I(),item_index:e.progress?.item_index,item_total:e.progress?.item_total,item_id:e.progress?.item_id,linked_test_index:e.progress?.linked_test_index,linked_test_total:e.progress?.linked_test_total,current_command:e.progress?.current_command,elapsed_ms:e.progress?.elapsed_ms}}async function vS(e,t,n=!1){let r=await ur(e,t);if(!r)throw new p(`Background test run ${t} not found`,m.NOT_FOUND);let i=await Ti(e,r);if(fu.has(i.status))return{run:i,signal_sent:"none"};let o=VU(i,n);return o==="none"&&(i.status="stopped",i.finished_at=i.finished_at??I()),i.stop_requested_at=I(),i.progress=YU(i,o),await pt(e,i),{run:i,signal_sent:o}}async function bS(e,t,n,r=!1){let i=await ur(e,t);if(!i)throw new p(`Background test run ${t} not found`,m.NOT_FOUND);let o=await Ti(e,i);if(!fu.has(o.status))throw new p(`Background test run ${t} is not terminal and cannot be resumed.`,m.CONFLICT);let s=await hu({pmRoot:o.pm_root,globalPmRoot:o.global_pm_root,kind:o.kind,commandArgs:o.command_args,requestedBy:n,targetId:o.target_id,statusFilter:o.status_filter,resumedFrom:o.id,resumedBy:n,attempt:o.attempt+1});if(!s.started)return s.run;let a=await gu({pmRoot:e,runId:s.run.id,noExtensions:r}),c={...o,resumed_by:a.id};return await pt(e,c),a}async function kS(e,t,n,r){let i=await ur(e,t);if(!i)throw new p(`Background test run ${t} not found`,m.NOT_FOUND);let o=typeof r=="number"&&Number.isFinite(r)&&r>=0?Math.floor(r):mS,s=n==="stdout"||n==="both"?await Q(i.stdout_path)??"":"",a=n==="stderr"||n==="both"?await Q(i.stderr_path)??"":"";return{run:i,stream:n,tail:o,stdout:n==="stdout"||n==="both"?_u(s,o):[],stderr:n==="stderr"||n==="both"?_u(a,o):[]}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8e9a2374-d190-52e1-8afd-14e1954863f0")}catch{}})();var XU=["queued","running","passed","failed","stopped","canceled"],QU=["stdout","stderr","both"];function ZU(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(XU.includes(t))return t;throw new p(`Invalid --status value "${e}"`,m.USAGE)}function eG(e){if(e===void 0||e.trim().length===0)return"stderr";let t=e.trim().toLowerCase();if(QU.includes(t))return t;throw new p(`Invalid --stream value "${e}"`,m.USAGE)}function tG(){try{let e=JU.userInfo().username.trim();if(e.length>0)return e}catch{}}function SS(e,t){let n=[e,zm(),t,process.env.USER,process.env.LOGNAME,process.env.USERNAME,tG()];for(let r of n){if(typeof r!="string")continue;let i=r.trim();if(i.length>0)return i}return"unknown"}async function vn(e){await j(e)}async function rJ(e,t){let n=R(process.cwd(),t.path),r=Ye(process.cwd());await vn(n);let i=await x(n),o=SS(e.author,i.author_default),s=await hu({pmRoot:n,globalPmRoot:r,kind:e.kind,commandArgs:e.commandArgs,requestedBy:o,targetId:e.targetId,statusFilter:e.statusFilter});return s.started?{started:!0,run:await gu({pmRoot:n,runId:s.run.id,noExtensions:e.noExtensions===!0})}:{started:!1,duplicate_of:s.duplicate_of,run:s.run}}async function iJ(e,t){let n=R(process.cwd(),t.path);await vn(n);let r=ZU(e.status),i=Tr(e.limit,"limit"),o=await yu(n,{status:r,limit:i});return{runs:o,count:o.length,filters:{status:r,limit:i}}}async function oJ(e,t){let n=R(process.cwd(),t.path);await vn(n);let r=await wS(n,e);return{run:r.run,health:r.health}}async function sJ(e,t,n){let r=R(process.cwd(),n.path);await vn(r);let i=eG(t.stream),o=Tr(t.tail,"tail"),s=await kS(r,e,i,o);return{run:s.run,stream:s.stream,tail:s.tail,stdout:s.stdout,stderr:s.stderr}}async function aJ(e,t,n){let r=R(process.cwd(),n.path);await vn(r);let i=await vS(r,e,t.force===!0);return{run:i.run,signal_sent:i.signal_sent}}async function cJ(e,t,n){let r=R(process.cwd(),n.path);await vn(r);let i=await x(r),o=SS(t.author,i.author_default),s=await bS(r,e,o,t.noExtensions===!0);return{resumed_from:e,run:s}}async function dJ(e,t){let n=R(process.cwd(),t.path);await vn(n);let r=await yS(n,e,t.noExtensions===!0);return{id:r.id,status:r.status,exit_code:r.exit_code}}export{vE as a,Lh as b,rG as c,SG as d,SE as e,nn as f,EG as g,EE as h,$h as i,TG as j,Fr as k,CG as l,CE as m,xE as n,AG as o,Ph as p,DG as q,$G as r,eg as s,NG as t,MG as u,PG as v,Dc as w,FG as x,jG as y,UG as z,hT as A,Un as B,gT as C,WG as D,zG as E,Nc as F,BG as G,HG as H,VG as I,vT as J,YG as K,JG as L,XG as M,QG as N,Mc as O,ug as P,eq as Q,lg as R,fg as S,IT as T,Ur as U,NT as V,gg as W,FT as X,pq as Y,Pc as Z,vg as _,UT as $,gq as aa,yq as ba,bg as ca,wq as da,vq as ea,D as fa,Le as ga,ut as ha,Gn as ia,Fc as ja,Sg as ka,yt as la,Gr as ma,VT as na,Gc as oa,qc as pa,Ag as qa,Kn as ra,Kr as sa,Wc as ta,pC as ua,Dg as va,Wr as wa,Ng as xa,Fo as ya,zc as za,Mg as Aa,Pg as Ba,Fg as Ca,BC as Da,o2 as Ea,NA as Fa,my as Ga,f2 as Ha,Yr as Ia,h2 as Ja,qA as Ka,KA as La,g2 as Ma,WA as Na,Yc as Oa,YA as Pa,nd as Qa,Xr as Ra,gy as Sa,rd as Ta,rx as Ua,ix as Va,ox as Wa,Wn as Xa,sx as Ya,bt as Za,ax as _a,cx as $a,td as ab,id as bb,od as cb,dx as db,Wo as eb,zo as fb,vy as gb,Sy as hb,sK as ib,Rx as jb,Ix as kb,Ay as lb,cd as mb,lK as nb,fK as ob,Oy as pb,Dy as qb,DK as rb,$K as sb,Qr as tb,Jo as ub,Py as vb,Fy as wb,jy as xb,Uy as yb,Wy as zb,zy as Ab,tR as Bb,Hy as Cb,rR as Db,oR as Eb,sR as Fb,aR as Gb,Qy as Hb,Zy as Ib,ew as Jb,Qo as Kb,Zo as Lb,Rw as Mb,kz as Nb,Iw as Ob,Lw as Pb,Dw as Qb,Mw as Rb,Fw as Sb,Nd as Tb,ri as Ub,ii as Vb,rO as Wb,Xn as Xb,Bw as Yb,Kd as Zb,Vw as _b,Yw as $b,OO as ac,AH as bc,Wv as cc,ai as dc,Hv as ec,Vv as fc,Yv as gc,al as hc,jL as ic,lV as jc,tb as kc,DV as lc,PV as mc,eD as nc,vs as oc,ul as pc,rb as qc,ZV as rc,SD as sc,bs as tc,ks as uc,Es as vc,vb as wc,tr as xc,un as yc,xs as zc,ln as Ac,_b as Bc,li as Cc,ui as Dc,Rs as Ec,Is as Fc,mn as Gc,pn as Hc,nr as Ic,Os as Jc,Ls as Kc,Ds as Lc,mi as Mc,qs as Nc,WD as Oc,_l as Pc,F4 as Qc,hn as Rc,fN as Sc,Js as Tc,zb as Uc,Bb as Vc,q3 as Wc,ON as Xc,YN as Yc,XN as Zc,fi as _c,K3 as $c,u8 as ad,FM as bd,$l as cd,m8 as dd,p8 as ed,na as fd,x8 as gd,R8 as hd,I8 as id,Tk as jd,B8 as kd,aP as ld,Gl as md,cP as nd,dP as od,lP as pd,H8 as qd,V8 as rd,a6 as sd,c6 as td,d6 as ud,Gk as vd,qk as wd,EP as xd,Kk as yd,O6 as zd,Wk as Ad,L6 as Bd,D6 as Cd,ia as Dd,GP as Ed,U6 as Fd,Kl as Gd,G6 as Hd,Wl as Id,qP as Jd,yi as Kd,Vk as Ld,Yk as Md,l9 as Nd,Qk as Od,E9 as Pd,T9 as Qd,p0 as Rd,Jl as Sd,au as Td,fY as Ud,YF as Vd,QF as Wd,du as Xd,tS as Yd,MY as Zd,rJ as _d,iJ as $d,oJ as ae,sJ as be,aJ as ce,cJ as de,dJ as ee};
|
|
31
|
+
//# sourceMappingURL=chunk-2WHXFKMY.js.map
|