@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,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="7b271a35-800c-52bf-9368-0410e76b8d4e")}catch{}})();import{EXECUTABLE_COMMAND_ALIASES,PM_COMMAND_ALIAS_CONTRACTS,renderPmCommandAliasMigrationHint,resolvePmCommandAlias}from"./cli-contracts/command-aliases.js";import{resolveSubcommandFlagContractsForCommand}from"./cli-contracts/flag-contracts.js";import{levenshteinDistanceWithinLimit}from"../core/shared/levenshtein.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{findPmNamespacedCommand,resolvePmCommandOperation}from"./cli-contracts/command-aliases.js";import{normalizeItemAddressInvocation}from"./agent/item-addressing.js";import{BOOTSTRAP_BOOLEAN_FLAGS,GLOBAL_VALUE_CONSUMING_FLAGS,consumesBootstrapValue,findBootstrapCommandTokenIndex as findContractBootstrapCommandTokenIndex,isInlineGlobalValueToken,parseBootstrapCommandName as parseContractBootstrapCommandName}from"./cli-contracts/bootstrap-command-scanner.js";const OUTPUT_VALUE_FLAGS=new Set(["--output-include","--output-limit","--output-budget","--output-format","--output-session","--output-cursor"]),BOOTSTRAP_OUTPUT_ENCODINGS=new Set(["toon","json"]);function consumeBootstrapGlobalToken(argv,index,state){const token=argv[index];if(BOOTSTRAP_BOOLEAN_FLAGS.has(token))return state.booleanFlags.add(token),1;const equalsIndex=token.indexOf("="),canonicalFlag=equalsIndex>0?token.slice(0,equalsIndex):token;if(!GLOBAL_VALUE_CONSUMING_FLAGS.has(canonicalFlag))return 1;const inlineValue=equalsIndex>0?token.slice(equalsIndex+1):void 0,consumesValue=inlineValue===void 0&&consumesBootstrapValue(canonicalFlag,argv[index+1]),value=inlineValue??(consumesValue?argv[index+1]:void 0);return canonicalFlag==="--author"?state.author=value??"":typeof value=="string"&&value.length>0&&(OUTPUT_VALUE_FLAGS.has(canonicalFlag)?state.outputValues:state.pathValues).set(canonicalFlag,value),consumesValue?2:1}function isBootstrapJsonOutput(state){return state.outputValues.get("--output-format")!=="toon"&&(state.booleanFlags.has("--json")||state.outputValues.get("--output-format")==="json"||state.pathValues.get("--format")?.trim().toLowerCase()==="json")}function parseBootstrapGlobalOptions(argv){const state={booleanFlags:new Set,outputValues:new Map,pathValues:new Map};let index=0;for(;index<argv.length&&argv[index]!=="--";)index+=consumeBootstrapGlobalToken(argv,index,state);return{path:state.pathValues.get("--pm-path")??state.pathValues.get("--path"),noExtensions:state.booleanFlags.has("--no-extensions")||["history attest","history-attest"].includes(parseBootstrapCommandPathName(argv)??""),noPager:state.booleanFlags.has("--no-pager"),json:isBootstrapJsonOutput(state),quiet:state.booleanFlags.has("--quiet"),lean:state.booleanFlags.has("--lean"),tokenAccounting:state.booleanFlags.has("--token-accounting"),...state.booleanFlags.has("--output-row-contract")?{outputRowContract:!0}:{},...state.outputValues.get("--output-include")===void 0?{}:{outputInclude:state.outputValues.get("--output-include")},...state.outputValues.get("--output-limit")===void 0?{}:{outputLimit:state.outputValues.get("--output-limit")},...state.outputValues.get("--output-budget")===void 0?{}:{outputBudget:state.outputValues.get("--output-budget")},...BOOTSTRAP_OUTPUT_ENCODINGS.has(state.outputValues.get("--output-format"))?{outputFormat:state.outputValues.get("--output-format")}:{},...state.outputValues.get("--output-session")===void 0?{}:{outputSession:state.outputValues.get("--output-session")},...state.outputValues.get("--output-cursor")===void 0?{}:{outputCursor:state.outputValues.get("--output-cursor")},...state.author===""?{authorMissingValue:!0}:state.author!==void 0?{author:state.author}:{}}}function stripGlobalBootstrapTokens(argv){const remaining=[];let index=0;for(;index<argv.length;){const token=argv[index];if(token==="--")break;if(BOOTSTRAP_BOOLEAN_FLAGS.has(token)||token==="--profile"||token==="--id-only"||token==="--full-changed-fields"||token==="--explain"){index+=1;continue}if(GLOBAL_VALUE_CONSUMING_FLAGS.has(token)){index+=consumesBootstrapValue(token,argv[index+1])?2:1;continue}if(isInlineGlobalValueToken(token)){index+=1;continue}remaining.push(token),index+=1}return remaining}function parseBootstrapHelpRequest(argv){const stripped=stripGlobalBootstrapTokens(argv);if(stripped[0]?.trim().toLowerCase()==="help"){const commandPathTokens2=[];for(let index=1;index<stripped.length;index+=1){const token=stripped[index];if(token.startsWith("-"))break;commandPathTokens2.push(token.trim().toLowerCase())}return{requested:!0,commandPathTokens:commandPathTokens2}}if(stripped.findIndex(token=>token==="--help"||token==="-h")<0)return{requested:!1,commandPathTokens:[]};const commandPathTokens=[];for(const token of stripped){if(token.startsWith("-"))break;commandPathTokens.push(token.trim().toLowerCase())}return{requested:!0,commandPathTokens}}function findBootstrapCommandTokenIndex(argv){return findContractBootstrapCommandTokenIndex(argv)}function parseBootstrapCommandName(argv){return parseContractBootstrapCommandName(argv)}function shouldDisablePagerForInvocation(argv,bootstrapGlobal){return bootstrapGlobal.noPager?!0:process.stdout.isTTY===!0?!1:parseBootstrapHelpRequest(argv).requested}function applyBootstrapPagerPolicy(argv){const pagerEnvironmentKeys=["PAGER","MANPAGER","GIT_PAGER","LESS"],previousValues=pagerEnvironmentKeys.map(key=>process.env[key]),restore=()=>{for(const[index,key]of pagerEnvironmentKeys.entries()){const value=previousValues[index];value===void 0?delete process.env[key]:process.env[key]=value}},bootstrapGlobal=parseBootstrapGlobalOptions(argv);return shouldDisablePagerForInvocation(argv,bootstrapGlobal)&&(process.env.PAGER="cat",process.env.MANPAGER="cat",process.env.GIT_PAGER="cat",(typeof process.env.LESS!="string"||process.env.LESS.trim().length===0)&&(process.env.LESS="FRX")),restore}const EXTENSION_ACTION_SYNTAX_TOKENS=new Set(["install","uninstall","explore","manage","doctor","adopt","adopt-all","activate","deactivate"]);function normalizeLegacyExtensionActionSyntax(argv){const extensionIndex=findBootstrapCommandTokenIndex(argv);if(extensionIndex===void 0||argv[extensionIndex]!=="extension")return[...argv];const actionToken=argv[extensionIndex+1];if(!actionToken||actionToken.startsWith("-"))return[...argv];if(!EXTENSION_ACTION_SYNTAX_TOKENS.has(actionToken))return[...argv];if(argv.includes("--help")||argv.includes("-h"))return[...argv];const forcedActionFlag=`--${actionToken}`;return argv.includes(forcedActionFlag)?[...argv]:[...argv.slice(0,extensionIndex+1),forcedActionFlag,...argv.slice(extensionIndex+2)]}const CLI_EXECUTABLE_ALIASES=new Set(["pm","pm-cli"]);function stripLeadingExecutableAlias(argv,trace){const index=findBootstrapCommandTokenIndex(argv);if(index===void 0)return argv;const token=argv[index];return CLI_EXECUTABLE_ALIASES.has(token.trim().toLowerCase())?(trace.push({from:token,to:[],reason:"executable_alias",confidence:"high"}),[...argv.slice(0,index),...argv.slice(index+1)]):argv}function rewriteCommandAlias(argv,trace){let index=findBootstrapCommandTokenIndex(argv);if(index!==void 0&&argv[index]==="help"){const offset=findBootstrapCommandTokenIndex(argv.slice(index+1));index=offset===void 0?void 0:index+1+offset}if(index===void 0)return argv;const token=argv[index],canonical=EXECUTABLE_COMMAND_ALIASES[token.trim().toLowerCase()];if(!canonical)return argv;const canonicalTokens=canonical.split(" "),rewritten=[...argv.slice(0,index),...canonicalTokens,...argv.slice(index+1)];return trace.push({from:token,to:canonicalTokens,reason:"command_alias",confidence:"high"}),rewritten}function normalizeFlagKeyToken(raw){return raw.replace(/^--?/,"").replace(/_/g,"-").replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}function toComparableFlagKey(raw){return normalizeFlagKeyToken(raw).replace(/-/g,"")}function markUnambiguousFlag(map,key,canonicalFlag){const existing=map.get(key);if(existing===void 0){map.set(key,canonicalFlag);return}existing!==canonicalFlag&&map.set(key,null)}function collectLongFlagCandidates(contract){const candidates=[],pushLongFlag=value=>{typeof value=="string"&&value.startsWith("--")&&candidates.push(value)};pushLongFlag(contract.flag);for(const alias of contract.aliases??[])pushLongFlag(alias);return candidates}function buildFlagLookup(commandName,contractsOverride){const contracts=contractsOverride??resolveSubcommandFlagContractsForCommand(commandName),canonicalByNormalized=new Map,canonicalByCompact=new Map,canonicalComparablesMap=new Map,listCanonicalFlags=new Set;for(const contract of contracts){const longCandidates=collectLongFlagCandidates(contract);if(longCandidates.length===0)continue;const canonicalFlag=`--${normalizeFlagKeyToken(longCandidates[0])}`;for(const candidate of longCandidates)markUnambiguousFlag(canonicalByNormalized,normalizeFlagKeyToken(candidate),canonicalFlag),markUnambiguousFlag(canonicalByCompact,toComparableFlagKey(candidate),canonicalFlag);const comparable=toComparableFlagKey(canonicalFlag);canonicalComparablesMap.has(canonicalFlag)||canonicalComparablesMap.set(canonicalFlag,comparable),contract.list===!0&&listCanonicalFlags.add(canonicalFlag)}return{canonicalByNormalized,canonicalByCompact,canonicalComparables:[...canonicalComparablesMap.entries()].map(([canonicalFlag,comparable])=>({canonicalFlag,comparable})),listCanonicalFlags}}function resolveCanonicalFlag(rawKey,lookup){const normalizedKey=normalizeFlagKeyToken(rawKey),direct=lookup.canonicalByNormalized.get(normalizedKey);if(typeof direct=="string")return{flag:direct,reason:"flag_alias",confidence:"high"};const comparableKey=normalizedKey.replace(/-/g,""),compactMatch=lookup.canonicalByCompact.get(comparableKey);if(typeof compactMatch=="string")return{flag:compactMatch,reason:"flag_alias",confidence:"high"};const maxDistance=comparableKey.length>=8?2:1;let bestDistance=Number.POSITIVE_INFINITY,bestFlag,tied=!1;for(const candidate of lookup.canonicalComparables){const distance=levenshteinDistanceWithinLimit(comparableKey,candidate.comparable,maxDistance);if(distance!==null){if(distance<bestDistance){bestDistance=distance,bestFlag=candidate.canonicalFlag,tied=!1;continue}distance===bestDistance&&bestFlag!==candidate.canonicalFlag&&(tied=!0)}}return!bestFlag||tied||!Number.isFinite(bestDistance)||bestDistance<=0?null:{flag:bestFlag,reason:"flag_typo",confidence:bestDistance>=2?"medium":"high"}}function listAliasPluralKeys(normalizedKey){const candidates=[`${normalizedKey}s`];return normalizedKey.endsWith("y")&&normalizedKey.length>1&&candidates.push(`${normalizedKey.slice(0,-1)}ies`),candidates}function parseBareKeyValueToken(token,preserve=!1){if(preserve||token.includes("://"))return null;const match=token.match(/^([A-Za-z][A-Za-z0-9_-]{1,63})([:=])(.*)$/);if(!match)return null;const key=match[1],value=match[3];return value.length===0?null:{key,value}}function normalizeLongOptionToken(token,lookup,preserve=!1){if(preserve||!token.startsWith("--"))return{tokens:[token]};const equalsIndex=token.indexOf("="),key=equalsIndex>=0?token.slice(0,equalsIndex):token,inlineValue=equalsIndex>=0?token.slice(equalsIndex+1):void 0,resolution=resolveCanonicalFlag(key,lookup);if(!resolution)return{tokens:[token]};const normalizedToken=inlineValue===void 0?resolution.flag:`${resolution.flag}=${inlineValue}`;return normalizedToken===token?{tokens:[token]}:{tokens:[normalizedToken],event:{from:token,to:[normalizedToken],reason:resolution.reason,confidence:resolution.confidence}}}function collectBootstrapPathValueIndices(argv){const indices=new Set;let expectsValue=!1;for(let index=0;index<argv.length;index+=1){if(expectsValue){indices.add(index),expectsValue=!1;continue}const token=argv[index];expectsValue=token==="--path"||token==="--pm-path"}return indices}function splitCanonicalListToken(token){if(!token.startsWith("--"))return null;const equalsIndex=token.indexOf("=");return equalsIndex<0?{flag:token}:{flag:token.slice(0,equalsIndex),inlineValue:token.slice(equalsIndex+1)}}function copyValueConsumingFlag(argv,index,result){result.push(argv[index]);const next=argv[index+1];return typeof next=="string"&&next!=="--"?(result.push(next),index+2):index+1}function readListFlagOccurrence(argv,index,parsed,multiValueListFlags){if(parsed.inlineValue!==void 0)return{originalTokens:[argv[index]],value:parsed.inlineValue,consumed:1};const values=[];let valueIndex=index+1;for(;valueIndex<argv.length&&argv[valueIndex]!=="--"&&!argv[valueIndex].startsWith("-")&&(values.length===0||multiValueListFlags.has(parsed.flag));)values.push(argv[valueIndex]),valueIndex+=1;const consumed=values.length===0?1:1+values.length;return{originalTokens:argv.slice(index,index+consumed),value:values.length===0?void 0:values.join(","),consumed}}function recordListFlagOccurrence(slots,result,flag,occurrence){const existing=slots.get(flag);if(existing){existing.values.push(occurrence.value),existing.occurrences+=1;return}slots.set(flag,{outputIndex:result.length,originalTokens:occurrence.originalTokens,values:[occurrence.value],occurrences:1}),result.push(null)}function buildListFlagCoalescingSplices(slots,multiValueListFlags){const events=[],splices=[];for(const[flag,slot]of slots){if(!(slot.occurrences>=2||multiValueListFlags.has(flag)&&slot.originalTokens.length>2)){splices.push({outputIndex:slot.outputIndex,tokens:slot.originalTokens});continue}const mergedToken=`${flag}=${slot.values.join(",")}`;splices.push({outputIndex:slot.outputIndex,tokens:[mergedToken]}),events.push({from:`${flag} (x${slot.occurrences})`,to:[mergedToken],reason:"list_merge",confidence:"high"})}return{events,splices}}function applyListFlagSplices(result,splices){splices.sort((a,b)=>b.outputIndex-a.outputIndex);for(const splice of splices)result.splice(splice.outputIndex,1,...splice.tokens)}function coalesceRepeatedListFlags(argv,listFlags,valueConsumingFlags=new Set,multiValueListFlags=new Set){if(listFlags.size===0)return{argv:[...argv],events:[]};const result=[],slots=new Map;let index=0;for(;index<argv.length;){const token=argv[index];if(token==="--"){result.push(...argv.slice(index));break}if(valueConsumingFlags.has(token)){index=copyValueConsumingFlag(argv,index,result);continue}const parsed=splitCanonicalListToken(token);if(!parsed||!listFlags.has(parsed.flag)){result.push(token),index+=1;continue}const occurrence=readListFlagOccurrence(argv,index,parsed,multiValueListFlags);if(occurrence.value===void 0){result.push(token),index+=occurrence.consumed;continue}recordListFlagOccurrence(slots,result,parsed.flag,{originalTokens:occurrence.originalTokens,value:occurrence.value}),index+=occurrence.consumed}const{events,splices}=buildListFlagCoalescingSplices(slots,multiValueListFlags);return applyListFlagSplices(result,splices),{argv:result,events}}const LINKED_TEST_TWO_TOKEN_KEYS_BY_FLAG=new Map([["--add",new Set(["command","cmd","path"])],["--remove",new Set(["command","path"])]]);function isLinkedTestTwoTokenValuePosition(commandName,emittedTokens){if(commandName!=="test"||emittedTokens.length<2)return!1;const key=emittedTokens[emittedTokens.length-1],flag=emittedTokens[emittedTokens.length-2],keys=LINKED_TEST_TWO_TOKEN_KEYS_BY_FLAG.get(flag);return keys!==void 0&&keys.has(key)}function mergeLinkedTestTwoTokenEntries(argv,commandName,trace){if(commandName!=="test")return argv;const result=[];let index=0;for(;index<argv.length;){const token=argv[index];if(token==="--")return result.push(...argv.slice(index)),result;const keys=LINKED_TEST_TWO_TOKEN_KEYS_BY_FLAG.get(token),key=keys?argv[index+1]:void 0;if(!keys||typeof key!="string"||!keys.has(key)){result.push(token),index+=1;continue}let runEnd=index+2;for(;runEnd<argv.length&&!argv[runEnd].startsWith("-");)runEnd+=1;if(runEnd-(index+2)!==1){result.push(token),index+=1;continue}const value=argv[index+2],mergedValue=`${key}=${value}`;result.push(token,mergedValue),trace.push({from:`${token} ${key} ${value}`,to:[token,mergedValue],reason:"bare_key_value",confidence:"high"}),index+=3}return result}function normalizeBootstrapTokens(argv,lookup,commandName,trace){const normalizedArgv=[],pathValueIndices=collectBootstrapPathValueIndices(argv);for(let index=0;index<argv.length;index+=1){const token=argv[index];if(token==="--"){normalizedArgv.push(...argv.slice(index));break}const preserveCurrentToken=pathValueIndices.has(index),previous=normalizedArgv[normalizedArgv.length-1];if(token.startsWith("--")){const normalizedToken=normalizeLongOptionToken(token,lookup,preserveCurrentToken);normalizedArgv.push(...normalizedToken.tokens),normalizedToken.event&&trace.push(normalizedToken.event);continue}const bareKeyValue=parseBareKeyValueToken(token,preserveCurrentToken);if(!bareKeyValue||typeof previous=="string"&&previous.startsWith("-")&&!previous.includes("=")||["search","comments","notes","learnings"].includes(commandName)||isLinkedTestTwoTokenValuePosition(commandName,normalizedArgv)){normalizedArgv.push(token);continue}const resolution=resolveCanonicalFlag(bareKeyValue.key,lookup);if(!resolution){normalizedArgv.push(token);continue}const replacement=bareKeyValue.value.startsWith("-")?[`${resolution.flag}=${bareKeyValue.value}`]:[resolution.flag,bareKeyValue.value];normalizedArgv.push(...replacement),trace.push({from:token,to:replacement,reason:"bare_key_value",confidence:resolution.confidence})}return normalizedArgv}function bindAttestationVerification(argv){for(let index=0;index<argv.length;index+=1){const token=argv[index];if(token==="--")break;if(token==="--verify"){const value=argv[index+1];if(value===void 0||value==="--")throw new PmCliError("history attest --verify requires a bundle file.",EXIT_CODE.USAGE);argv.splice(index,2,`--verify=${value}`)}else(GLOBAL_VALUE_CONSUMING_FLAGS.has(token)||token==="--output"||token==="--hash-algorithm")&&(index+=1)}}function protectBootstrapHelpDiscovery(argv,command){if(!argv.some(token=>token==="--help"||token==="-h"))return;const declaredFlags=new Set(resolveSubcommandFlagContractsForCommand(command).flatMap(contract=>[contract.flag,...contract.aliases??[],...contract.short===void 0?[]:[contract.short]]));for(let index=0;index<argv.length;index+=1){const token=argv[index];if(token==="--")break;token!=="--help"&&token!=="-h"||declaredFlags.has(argv[index-1])&&!BOOTSTRAP_BOOLEAN_FLAGS.has(argv[index-1])&&(argv[index-1]=token)}}function normalizeBootstrapInvocation(argv){const trace=[],executableNormalized=stripLeadingExecutableAlias(argv,trace),legacyNormalized=normalizeLegacyExtensionActionSyntax(executableNormalized);(legacyNormalized.length!==executableNormalized.length||legacyNormalized.some((token,index)=>token!==executableNormalized[index]))&&trace.push({from:executableNormalized.join(" "),to:[...legacyNormalized],reason:"legacy_extension_action",confidence:"high"});const aliasNormalized=rewriteCommandAlias(legacyNormalized,trace),itemAddress=normalizeItemAddressInvocation(aliasNormalized);if(itemAddress.conflict)throw new PmCliError("Provide the item id either positionally or with --id, not both.",EXIT_CODE.USAGE);itemAddress.changed&&trace.push({from:`--id ${itemAddress.itemId}`,to:[itemAddress.itemId],reason:"item_id_alias",confidence:"high"});const commandName=parseBootstrapCommandName(itemAddress.argv),commandPathName=parseBootstrapCommandPathName(itemAddress.argv),operationName=resolvePmCommandOperation(commandPathName??commandName??""),lookup=buildFlagLookup(commandPathName??commandName),normalizedArgv=normalizeBootstrapTokens(itemAddress.argv,lookup,operationName,trace),linkedTestNormalized=mergeLinkedTestTwoTokenEntries(normalizedArgv,operationName,trace),coalesced=coalesceRepeatedListFlags(linkedTestNormalized,lookup.listCanonicalFlags,GLOBAL_VALUE_CONSUMING_FLAGS,commandName==="create"?new Set(["--tags"]):new Set);for(const event of coalesced.events)trace.push(event);return protectBootstrapHelpDiscovery(coalesced.argv,commandPathName??commandName),commandPathName==="history attest"&&bindAttestationVerification(coalesced.argv),{argv:coalesced.argv,commandName,trace}}function parseBootstrapCommandPathName(argv){const stripped=stripGlobalBootstrapTokens(argv),first=stripped[0]?.trim().toLowerCase(),second=stripped[1]?.trim().toLowerCase(),namespaced=findPmNamespacedCommand(stripped);return namespaced?namespaced.canonical:(first==="extension"||first==="package"||first==="packages")&&typeof second=="string"&&second.length>0&&!second.startsWith("-")?`${first} ${second}`:first}function parseBootstrapTypeValue(argv){for(let index=0;index<argv.length;index+=1){const token=argv[index];if(token==="--")break;if(token==="--type"){const candidate=argv[index+1];if(typeof candidate=="string"&&candidate.trim().length>0)return candidate.trim();continue}if(token.startsWith("--type=")){const candidate=token.slice(7).trim();if(candidate.length>0)return candidate}}}const _testOnly={buildFlagLookup,collectBootstrapPathValueIndices,collectLongFlagCandidates,markUnambiguousFlag,normalizeLongOptionToken,resolveCanonicalFlag};export{EXECUTABLE_COMMAND_ALIASES,PM_COMMAND_ALIAS_CONTRACTS,_testOnly,applyBootstrapPagerPolicy,coalesceRepeatedListFlags,findBootstrapCommandTokenIndex,listAliasPluralKeys,mergeLinkedTestTwoTokenEntries,normalizeBootstrapInvocation,normalizeLegacyExtensionActionSyntax,parseBootstrapCommandName,parseBootstrapGlobalOptions,parseBootstrapHelpRequest,parseBootstrapTypeValue,renderPmCommandAliasMigrationHint,resolvePmCommandAlias,stripGlobalBootstrapTokens};
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="10f173af-3f3d-5678-85a1-267469d22069")}catch{}})();import{EXECUTABLE_COMMAND_ALIASES,PM_COMMAND_ALIAS_CONTRACTS,renderPmCommandAliasMigrationHint,resolvePmCommandAlias}from"./cli-contracts/command-aliases.js";import{resolveSubcommandFlagContractsForCommand}from"./cli-contracts/flag-contracts.js";import{levenshteinDistanceWithinLimit}from"../core/shared/levenshtein.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{findPmNamespacedCommand,resolvePmCommandOperation}from"./cli-contracts/command-aliases.js";import{normalizeItemAddressInvocation}from"./agent/item-addressing.js";import{BOOTSTRAP_BOOLEAN_FLAGS,GLOBAL_VALUE_CONSUMING_FLAGS,consumesBootstrapValue,findBootstrapCommandTokenIndex as findContractBootstrapCommandTokenIndex,isInlineGlobalValueToken,parseBootstrapCommandName as parseContractBootstrapCommandName}from"./cli-contracts/bootstrap-command-scanner.js";const OUTPUT_VALUE_FLAGS=new Set(["--output-include","--output-limit","--output-budget","--output-format","--output-session","--output-cursor"]),BOOTSTRAP_OUTPUT_ENCODINGS=new Set(["toon","json"]);function consumeBootstrapGlobalToken(argv,index,state){const token=argv[index];if(BOOTSTRAP_BOOLEAN_FLAGS.has(token))return state.booleanFlags.add(token),1;const equalsIndex=token.indexOf("="),canonicalFlag=equalsIndex>0?token.slice(0,equalsIndex):token;if(!GLOBAL_VALUE_CONSUMING_FLAGS.has(canonicalFlag))return 1;const inlineValue=equalsIndex>0?token.slice(equalsIndex+1):void 0,consumesValue=inlineValue===void 0&&consumesBootstrapValue(canonicalFlag,argv[index+1]),value=inlineValue??(consumesValue?argv[index+1]:void 0);return canonicalFlag==="--author"?state.author=value??"":typeof value=="string"&&value.length>0&&(OUTPUT_VALUE_FLAGS.has(canonicalFlag)?state.outputValues:state.pathValues).set(canonicalFlag,value),consumesValue?2:1}function isBootstrapJsonOutput(state){return state.outputValues.get("--output-format")!=="toon"&&(state.booleanFlags.has("--json")||state.outputValues.get("--output-format")==="json"||state.pathValues.get("--format")?.trim().toLowerCase()==="json")}function parseBootstrapGlobalOptions(argv){const state={booleanFlags:new Set,outputValues:new Map,pathValues:new Map};let index=0;for(;index<argv.length&&argv[index]!=="--";)index+=consumeBootstrapGlobalToken(argv,index,state);return{path:state.pathValues.get("--pm-path")??state.pathValues.get("--path"),noExtensions:state.booleanFlags.has("--no-extensions")||["history attest","history-attest"].includes(parseBootstrapCommandPathName(argv)??""),noPager:state.booleanFlags.has("--no-pager"),json:isBootstrapJsonOutput(state),quiet:state.booleanFlags.has("--quiet"),lean:state.booleanFlags.has("--lean"),tokenAccounting:state.booleanFlags.has("--token-accounting"),...state.booleanFlags.has("--output-row-contract")?{outputRowContract:!0}:{},...state.outputValues.get("--output-include")===void 0?{}:{outputInclude:state.outputValues.get("--output-include")},...state.outputValues.get("--output-limit")===void 0?{}:{outputLimit:state.outputValues.get("--output-limit")},...state.outputValues.get("--output-budget")===void 0?{}:{outputBudget:state.outputValues.get("--output-budget")},...BOOTSTRAP_OUTPUT_ENCODINGS.has(state.outputValues.get("--output-format"))?{outputFormat:state.outputValues.get("--output-format")}:{},...state.outputValues.get("--output-session")===void 0?{}:{outputSession:state.outputValues.get("--output-session")},...state.outputValues.get("--output-cursor")===void 0?{}:{outputCursor:state.outputValues.get("--output-cursor")},...state.author===""?{authorMissingValue:!0}:state.author!==void 0?{author:state.author}:{}}}function stripGlobalBootstrapTokens(argv){const remaining=[];let index=0;for(;index<argv.length;){const token=argv[index];if(token==="--")break;if(BOOTSTRAP_BOOLEAN_FLAGS.has(token)||token==="--profile"||token==="--id-only"||token==="--full-changed-fields"||token==="--explain"){index+=1;continue}if(GLOBAL_VALUE_CONSUMING_FLAGS.has(token)){index+=consumesBootstrapValue(token,argv[index+1])?2:1;continue}if(isInlineGlobalValueToken(token)){index+=1;continue}remaining.push(token),index+=1}return remaining}function parseBootstrapHelpRequest(argv){const stripped=stripGlobalBootstrapTokens(argv);if(stripped[0]?.trim().toLowerCase()==="help"){const commandPathTokens2=[];for(let index=1;index<stripped.length;index+=1){const token=stripped[index];if(token.startsWith("-"))break;commandPathTokens2.push(token.trim().toLowerCase())}return{requested:!0,commandPathTokens:commandPathTokens2}}if(stripped.findIndex(token=>token==="--help"||token==="-h")<0)return{requested:!1,commandPathTokens:[]};const commandPathTokens=[];for(const token of stripped){if(token.startsWith("-"))break;commandPathTokens.push(token.trim().toLowerCase())}return{requested:!0,commandPathTokens}}function findBootstrapCommandTokenIndex(argv){return findContractBootstrapCommandTokenIndex(argv)}function parseBootstrapCommandName(argv){return parseContractBootstrapCommandName(argv)}function shouldDisablePagerForInvocation(argv,bootstrapGlobal){return bootstrapGlobal.noPager?!0:process.stdout.isTTY===!0?!1:parseBootstrapHelpRequest(argv).requested}function applyBootstrapPagerPolicy(argv){const pagerEnvironmentKeys=["PAGER","MANPAGER","GIT_PAGER","LESS"],previousValues=pagerEnvironmentKeys.map(key=>process.env[key]),restore=()=>{for(const[index,key]of pagerEnvironmentKeys.entries()){const value=previousValues[index];value===void 0?delete process.env[key]:process.env[key]=value}},bootstrapGlobal=parseBootstrapGlobalOptions(argv);return shouldDisablePagerForInvocation(argv,bootstrapGlobal)&&(process.env.PAGER="cat",process.env.MANPAGER="cat",process.env.GIT_PAGER="cat",(typeof process.env.LESS!="string"||process.env.LESS.trim().length===0)&&(process.env.LESS="FRX")),restore}const EXTENSION_ACTION_SYNTAX_TOKENS=new Set(["install","uninstall","explore","manage","doctor","adopt","adopt-all","activate","deactivate"]);function normalizeLegacyExtensionActionSyntax(argv){const extensionIndex=findBootstrapCommandTokenIndex(argv);if(extensionIndex===void 0||argv[extensionIndex]!=="extension")return[...argv];const actionToken=argv[extensionIndex+1];if(!actionToken||actionToken.startsWith("-"))return[...argv];if(!EXTENSION_ACTION_SYNTAX_TOKENS.has(actionToken))return[...argv];if(argv.includes("--help")||argv.includes("-h"))return[...argv];const forcedActionFlag=`--${actionToken}`;return argv.includes(forcedActionFlag)?[...argv]:[...argv.slice(0,extensionIndex+1),forcedActionFlag,...argv.slice(extensionIndex+2)]}const CLI_EXECUTABLE_ALIASES=new Set(["pm","pm-cli"]);function stripLeadingExecutableAlias(argv,trace){const index=findBootstrapCommandTokenIndex(argv);if(index===void 0)return argv;const token=argv[index];return CLI_EXECUTABLE_ALIASES.has(token.trim().toLowerCase())?(trace.push({from:token,to:[],reason:"executable_alias",confidence:"high"}),[...argv.slice(0,index),...argv.slice(index+1)]):argv}function rewriteCommandAlias(argv,trace){let index=findBootstrapCommandTokenIndex(argv);if(index!==void 0&&argv[index]==="help"){const offset=findBootstrapCommandTokenIndex(argv.slice(index+1));index=offset===void 0?void 0:index+1+offset}if(index===void 0)return argv;const token=argv[index],canonical=EXECUTABLE_COMMAND_ALIASES[token.trim().toLowerCase()];if(!canonical)return argv;const canonicalTokens=canonical.split(" "),rewritten=[...argv.slice(0,index),...canonicalTokens,...argv.slice(index+1)];return trace.push({from:token,to:canonicalTokens,reason:"command_alias",confidence:"high"}),rewritten}function normalizeFlagKeyToken(raw){return raw.replace(/^--?/,"").replace(/_/g,"-").replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}function toComparableFlagKey(raw){return normalizeFlagKeyToken(raw).replace(/-/g,"")}function markUnambiguousFlag(map,key,canonicalFlag){const existing=map.get(key);if(existing===void 0){map.set(key,canonicalFlag);return}existing!==canonicalFlag&&map.set(key,null)}function collectLongFlagCandidates(contract){const candidates=[],pushLongFlag=value=>{typeof value=="string"&&value.startsWith("--")&&candidates.push(value)};pushLongFlag(contract.flag);for(const alias of contract.aliases??[])pushLongFlag(alias);return candidates}function buildFlagLookup(commandName,contractsOverride){const contracts=contractsOverride??resolveSubcommandFlagContractsForCommand(commandName),canonicalByNormalized=new Map,canonicalByCompact=new Map,canonicalComparablesMap=new Map,listCanonicalFlags=new Set;for(const contract of contracts){const longCandidates=collectLongFlagCandidates(contract);if(longCandidates.length===0)continue;const canonicalFlag=`--${normalizeFlagKeyToken(longCandidates[0])}`;for(const candidate of longCandidates)markUnambiguousFlag(canonicalByNormalized,normalizeFlagKeyToken(candidate),canonicalFlag),markUnambiguousFlag(canonicalByCompact,toComparableFlagKey(candidate),canonicalFlag);const comparable=toComparableFlagKey(canonicalFlag);canonicalComparablesMap.has(canonicalFlag)||canonicalComparablesMap.set(canonicalFlag,comparable),contract.list===!0&&listCanonicalFlags.add(canonicalFlag)}return{canonicalByNormalized,canonicalByCompact,canonicalComparables:[...canonicalComparablesMap.entries()].map(([canonicalFlag,comparable])=>({canonicalFlag,comparable})),listCanonicalFlags}}function resolveCanonicalFlag(rawKey,lookup){const normalizedKey=normalizeFlagKeyToken(rawKey),direct=lookup.canonicalByNormalized.get(normalizedKey);if(typeof direct=="string")return{flag:direct,reason:"flag_alias",confidence:"high"};const comparableKey=normalizedKey.replace(/-/g,""),compactMatch=lookup.canonicalByCompact.get(comparableKey);if(typeof compactMatch=="string")return{flag:compactMatch,reason:"flag_alias",confidence:"high"};const maxDistance=comparableKey.length>=8?2:1;let bestDistance=Number.POSITIVE_INFINITY,bestFlag,tied=!1;for(const candidate of lookup.canonicalComparables){const distance=levenshteinDistanceWithinLimit(comparableKey,candidate.comparable,maxDistance);if(distance!==null){if(distance<bestDistance){bestDistance=distance,bestFlag=candidate.canonicalFlag,tied=!1;continue}distance===bestDistance&&bestFlag!==candidate.canonicalFlag&&(tied=!0)}}return!bestFlag||tied||!Number.isFinite(bestDistance)||bestDistance<=0?null:{flag:bestFlag,reason:"flag_typo",confidence:bestDistance>=2?"medium":"high"}}function listAliasPluralKeys(normalizedKey){const candidates=[`${normalizedKey}s`];return normalizedKey.endsWith("y")&&normalizedKey.length>1&&candidates.push(`${normalizedKey.slice(0,-1)}ies`),candidates}function parseBareKeyValueToken(token,preserve=!1){if(preserve||token.includes("://"))return null;const match=token.match(/^([A-Za-z][A-Za-z0-9_-]{1,63})([:=])(.*)$/);if(!match)return null;const key=match[1],value=match[3];return value.length===0||match[2]===":"&&/\s/u.test(token)?null:{key,value}}function normalizeLongOptionToken(token,lookup,preserve=!1){if(preserve||!token.startsWith("--"))return{tokens:[token]};const equalsIndex=token.indexOf("="),key=equalsIndex>=0?token.slice(0,equalsIndex):token,inlineValue=equalsIndex>=0?token.slice(equalsIndex+1):void 0,resolution=resolveCanonicalFlag(key,lookup);if(!resolution)return{tokens:[token]};const normalizedToken=inlineValue===void 0?resolution.flag:`${resolution.flag}=${inlineValue}`;return normalizedToken===token?{tokens:[token]}:{tokens:[normalizedToken],event:{from:token,to:[normalizedToken],reason:resolution.reason,confidence:resolution.confidence}}}function collectBootstrapPathValueIndices(argv){const indices=new Set;let expectsValue=!1;for(let index=0;index<argv.length;index+=1){if(expectsValue){indices.add(index),expectsValue=!1;continue}const token=argv[index];expectsValue=token==="--path"||token==="--pm-path"}return indices}function splitCanonicalListToken(token){if(!token.startsWith("--"))return null;const equalsIndex=token.indexOf("=");return equalsIndex<0?{flag:token}:{flag:token.slice(0,equalsIndex),inlineValue:token.slice(equalsIndex+1)}}function copyValueConsumingFlag(argv,index,result){result.push(argv[index]);const next=argv[index+1];return typeof next=="string"&&next!=="--"?(result.push(next),index+2):index+1}function readListFlagOccurrence(argv,index,parsed,multiValueListFlags){if(parsed.inlineValue!==void 0)return{originalTokens:[argv[index]],value:parsed.inlineValue,consumed:1};const values=[];let valueIndex=index+1;for(;valueIndex<argv.length&&argv[valueIndex]!=="--"&&!argv[valueIndex].startsWith("-")&&(values.length===0||multiValueListFlags.has(parsed.flag));)values.push(argv[valueIndex]),valueIndex+=1;const consumed=values.length===0?1:1+values.length;return{originalTokens:argv.slice(index,index+consumed),value:values.length===0?void 0:values.join(","),consumed}}function recordListFlagOccurrence(slots,result,flag,occurrence){const existing=slots.get(flag);if(existing){existing.values.push(occurrence.value),existing.occurrences+=1;return}slots.set(flag,{outputIndex:result.length,originalTokens:occurrence.originalTokens,values:[occurrence.value],occurrences:1}),result.push(null)}function buildListFlagCoalescingSplices(slots,multiValueListFlags){const events=[],splices=[];for(const[flag,slot]of slots){if(!(slot.occurrences>=2||multiValueListFlags.has(flag)&&slot.originalTokens.length>2)){splices.push({outputIndex:slot.outputIndex,tokens:slot.originalTokens});continue}const mergedToken=`${flag}=${slot.values.join(",")}`;splices.push({outputIndex:slot.outputIndex,tokens:[mergedToken]}),events.push({from:`${flag} (x${slot.occurrences})`,to:[mergedToken],reason:"list_merge",confidence:"high"})}return{events,splices}}function applyListFlagSplices(result,splices){splices.sort((a,b)=>b.outputIndex-a.outputIndex);for(const splice of splices)result.splice(splice.outputIndex,1,...splice.tokens)}function coalesceRepeatedListFlags(argv,listFlags,valueConsumingFlags=new Set,multiValueListFlags=new Set){if(listFlags.size===0)return{argv:[...argv],events:[]};const result=[],slots=new Map;let index=0;for(;index<argv.length;){const token=argv[index];if(token==="--"){result.push(...argv.slice(index));break}if(valueConsumingFlags.has(token)){index=copyValueConsumingFlag(argv,index,result);continue}const parsed=splitCanonicalListToken(token);if(!parsed||!listFlags.has(parsed.flag)){result.push(token),index+=1;continue}const occurrence=readListFlagOccurrence(argv,index,parsed,multiValueListFlags);if(occurrence.value===void 0){result.push(token),index+=occurrence.consumed;continue}recordListFlagOccurrence(slots,result,parsed.flag,{originalTokens:occurrence.originalTokens,value:occurrence.value}),index+=occurrence.consumed}const{events,splices}=buildListFlagCoalescingSplices(slots,multiValueListFlags);return applyListFlagSplices(result,splices),{argv:result,events}}const LINKED_TEST_TWO_TOKEN_KEYS_BY_FLAG=new Map([["--add",new Set(["command","cmd","path"])],["--remove",new Set(["command","path"])]]);function isLinkedTestTwoTokenValuePosition(commandName,emittedTokens){if(commandName!=="test"||emittedTokens.length<2)return!1;const key=emittedTokens[emittedTokens.length-1],flag=emittedTokens[emittedTokens.length-2],keys=LINKED_TEST_TWO_TOKEN_KEYS_BY_FLAG.get(flag);return keys!==void 0&&keys.has(key)}function mergeLinkedTestTwoTokenEntries(argv,commandName,trace){if(commandName!=="test")return argv;const result=[];let index=0;for(;index<argv.length;){const token=argv[index];if(token==="--")return result.push(...argv.slice(index)),result;const keys=LINKED_TEST_TWO_TOKEN_KEYS_BY_FLAG.get(token),key=keys?argv[index+1]:void 0;if(!keys||typeof key!="string"||!keys.has(key)){result.push(token),index+=1;continue}let runEnd=index+2;for(;runEnd<argv.length&&!argv[runEnd].startsWith("-");)runEnd+=1;if(runEnd-(index+2)!==1){result.push(token),index+=1;continue}const value=argv[index+2],mergedValue=`${key}=${value}`;result.push(token,mergedValue),trace.push({from:`${token} ${key} ${value}`,to:[token,mergedValue],reason:"bare_key_value",confidence:"high"}),index+=3}return result}function normalizeBootstrapTokens(argv,lookup,commandName,trace){const normalizedArgv=[],pathValueIndices=collectBootstrapPathValueIndices(argv);for(let index=0;index<argv.length;index+=1){const token=argv[index];if(token==="--"){normalizedArgv.push(...argv.slice(index));break}const preserveCurrentToken=pathValueIndices.has(index),previous=normalizedArgv[normalizedArgv.length-1];if(token.startsWith("--")){const normalizedToken=normalizeLongOptionToken(token,lookup,preserveCurrentToken);normalizedArgv.push(...normalizedToken.tokens),normalizedToken.event&&trace.push(normalizedToken.event);continue}const bareKeyValue=parseBareKeyValueToken(token,preserveCurrentToken);if(!bareKeyValue||typeof previous=="string"&&previous.startsWith("-")&&!previous.includes("=")||["search","comments","notes","learnings"].includes(commandName)||isLinkedTestTwoTokenValuePosition(commandName,normalizedArgv)){normalizedArgv.push(token);continue}const resolution=resolveCanonicalFlag(bareKeyValue.key,lookup);if(!resolution){normalizedArgv.push(token);continue}const replacement=bareKeyValue.value.startsWith("-")?[`${resolution.flag}=${bareKeyValue.value}`]:[resolution.flag,bareKeyValue.value];normalizedArgv.push(...replacement),trace.push({from:token,to:replacement,reason:"bare_key_value",confidence:resolution.confidence})}return normalizedArgv}function bindAttestationVerification(argv){for(let index=0;index<argv.length;index+=1){const token=argv[index];if(token==="--")break;if(token==="--verify"){const value=argv[index+1];if(value===void 0||value==="--")throw new PmCliError("history attest --verify requires a bundle file.",EXIT_CODE.USAGE);argv.splice(index,2,`--verify=${value}`)}else(GLOBAL_VALUE_CONSUMING_FLAGS.has(token)||token==="--output"||token==="--hash-algorithm")&&(index+=1)}}function protectBootstrapHelpDiscovery(argv,command){if(!argv.some(token=>token==="--help"||token==="-h"))return;const declaredFlags=new Set(resolveSubcommandFlagContractsForCommand(command).flatMap(contract=>[contract.flag,...contract.aliases??[],...contract.short===void 0?[]:[contract.short]]));for(let index=0;index<argv.length;index+=1){const token=argv[index];if(token==="--")break;token!=="--help"&&token!=="-h"||declaredFlags.has(argv[index-1])&&!BOOTSTRAP_BOOLEAN_FLAGS.has(argv[index-1])&&(argv[index-1]=token)}}function normalizeBootstrapInvocation(argv){const trace=[],executableNormalized=stripLeadingExecutableAlias(argv,trace),legacyNormalized=normalizeLegacyExtensionActionSyntax(executableNormalized);(legacyNormalized.length!==executableNormalized.length||legacyNormalized.some((token,index)=>token!==executableNormalized[index]))&&trace.push({from:executableNormalized.join(" "),to:[...legacyNormalized],reason:"legacy_extension_action",confidence:"high"});const aliasNormalized=rewriteCommandAlias(legacyNormalized,trace),itemAddress=normalizeItemAddressInvocation(aliasNormalized);if(itemAddress.conflict)throw new PmCliError("Provide the item id either positionally or with --id, not both.",EXIT_CODE.USAGE);itemAddress.changed&&trace.push({from:`--id ${itemAddress.itemId}`,to:[itemAddress.itemId],reason:"item_id_alias",confidence:"high"});const commandName=parseBootstrapCommandName(itemAddress.argv),commandPathName=parseBootstrapCommandPathName(itemAddress.argv),operationName=resolvePmCommandOperation(commandPathName??commandName??""),lookup=buildFlagLookup(commandPathName??commandName),normalizedArgv=normalizeBootstrapTokens(itemAddress.argv,lookup,operationName,trace),linkedTestNormalized=mergeLinkedTestTwoTokenEntries(normalizedArgv,operationName,trace),coalesced=coalesceRepeatedListFlags(linkedTestNormalized,lookup.listCanonicalFlags,GLOBAL_VALUE_CONSUMING_FLAGS,commandName==="create"?new Set(["--tags"]):new Set);for(const event of coalesced.events)trace.push(event);return protectBootstrapHelpDiscovery(coalesced.argv,commandPathName??commandName),commandPathName==="history attest"&&bindAttestationVerification(coalesced.argv),{argv:coalesced.argv,commandName,trace}}function parseBootstrapCommandPathName(argv){const stripped=stripGlobalBootstrapTokens(argv),first=stripped[0]?.trim().toLowerCase(),second=stripped[1]?.trim().toLowerCase(),namespaced=findPmNamespacedCommand(stripped);return namespaced?namespaced.canonical:(first==="extension"||first==="package"||first==="packages")&&typeof second=="string"&&second.length>0&&!second.startsWith("-")?`${first} ${second}`:first}function parseBootstrapTypeValue(argv){for(let index=0;index<argv.length;index+=1){const token=argv[index];if(token==="--")break;if(token==="--type"){const candidate=argv[index+1];if(typeof candidate=="string"&&candidate.trim().length>0)return candidate.trim();continue}if(token.startsWith("--type=")){const candidate=token.slice(7).trim();if(candidate.length>0)return candidate}}}const _testOnly={buildFlagLookup,collectBootstrapPathValueIndices,collectLongFlagCandidates,markUnambiguousFlag,normalizeLongOptionToken,resolveCanonicalFlag};export{EXECUTABLE_COMMAND_ALIASES,PM_COMMAND_ALIAS_CONTRACTS,_testOnly,applyBootstrapPagerPolicy,coalesceRepeatedListFlags,findBootstrapCommandTokenIndex,listAliasPluralKeys,mergeLinkedTestTwoTokenEntries,normalizeBootstrapInvocation,normalizeLegacyExtensionActionSyntax,parseBootstrapCommandName,parseBootstrapGlobalOptions,parseBootstrapHelpRequest,parseBootstrapTypeValue,renderPmCommandAliasMigrationHint,resolvePmCommandAlias,stripGlobalBootstrapTokens};
|
|
2
2
|
//# sourceMappingURL=cli-bootstrap.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="5bde03cb-def4-549f-89d5-6822bd2235e6")}catch{}})();import crypto from"node:crypto";import{runGet}from"./query/get.js";import{constants}from"node:fs";import{isFileMissingError,readRegularFile,transactionPreviewNonRegularFileError}from"../core/fs/fs-utils.js";import{cp,lstat,mkdir,mkdtemp,open,readdir,realpath,rm,stat,writeFile}from"node:fs/promises";import{tmpdir}from"node:os";import{getActiveExtensionHooks,getActiveExtensionRegistrations,runWithPreviewMutationGuards,setActiveExtensionRegistrations}from"../core/extensions/index.js";import path from"node:path";import{transferMutationStdinTokenPolicy}from"../core/item/parse.js";import{EXIT_CODE,PM_REQUIRED_SUBDIRS,SETTINGS_DEFAULTS,SETTINGS_FILENAME}from"../core/shared/constants.js";import{resolveItemTypeRegistry}from"../core/item/type-registry.js";import{listAllItemMetadataLight}from"../core/store/item-store.js";import{runWithItemMutationPrecondition}from"../core/store/item-mutation-precondition.js";import{hashDocument,hashHistoryStream}from"../core/history/history.js";import{historyVersionOffset}from"../core/history/version-address.js";import{isConfigurationOnlySettingsRead,readSettings}from"../core/store/settings.js";import{DEFAULT_RUNTIME_SCHEMA_FILE_PATHS,filePathForSchemaSection,loadRuntimeSchemaFromOptionalFiles,normalizeRuntimeSchemaSettings}from"../core/schema/runtime-schema.js";import{validateSettings}from"../core/store/settings-validator.js";import{resolveWorkspaceRoot}from"../core/store/paths.js";import{getSessionStatePath}from"../core/session/session-state.js";import{PmCliError}from"../core/shared/errors.js";import{stableUpsertValue}from"./structured-mutations.js";import{stableStringify}from"../core/shared/serialization.js";import{assertMutationOptionValueTypes}from"./lifecycle/mutation-option-validation.js";import{readHistoryEntries}from"./history-read.js";import{PM_CONTEXT_INTENTS_FILE}from"./context-intent-runtime.js";import{close,create,deleteItem,get,release,restore,update,runWithActiveExtensions}from"./runtime.js";import{commitWorkspaceTransaction,abandonWorkspaceTransaction,readWorkspaceTransaction,workspaceTransactionPlanDigest,validateWorkspaceTransactionIdentity}from"./workspace-transaction.js";async function resolveTransactionSchema(pmRoot,settings){if(!isConfigurationOnlySettingsRead(pmRoot))return{schema:normalizeRuntimeSchemaSettings(settings.schema),typeDefinitionsFromFile:[]};const loaded=await loadGuardedRuntimeSchema(pmRoot,settings.schema);return{schema:loaded.schema,typeDefinitionsFromFile:loaded.type_definitions_from_file??[]}}async function listUpsertKeyCandidates(pmRoot,settings,schemaContext,key){const typeRegistry=resolveItemTypeRegistry({...settings,item_types:{...settings.item_types,definitions:[...settings.item_types?.definitions??[],...schemaContext.typeDefinitionsFromFile]}},getActiveExtensionRegistrations());return(await listAllItemMetadataLight(pmRoot,settings.item_format,typeRegistry.type_to_folder,void 0,schemaContext.schema)).flatMap(item=>{const value=item[key];return value==null?[]:[{id:item.id,value}]})}function createUniqueKeyIndex(pmRoot){const scans=new Map,scan=async key=>{const settings=await readSettings(pmRoot),schemaContext=await resolveTransactionSchema(pmRoot,settings),byValue=new Map;for(const candidate of await listUpsertKeyCandidates(pmRoot,settings,schemaContext,key)){const stable=stableUpsertValue(candidate.value);byValue.set(stable,[...byValue.get(stable)??[],candidate.id])}return byValue};return{lookup(key){const pending=scans.get(key)??scan(key);return scans.set(key,pending),pending},async recordCreate(item){for(const[key,pending]of scans){const value=item[key];if(value==null)continue;const byValue=await pending,stable=stableUpsertValue(value);byValue.set(stable,[...byValue.get(stable)??[],String(item.id)])}},invalidate(){scans.clear()}}}async function assertUniqueKeyFree(index,unique){const stable=stableUpsertValue(unique.value),existing=(await index.lookup(unique.key)).get(stable)??[];if(existing.length!==0)throw new PmCliError(`Upsert key "${unique.key}" value ${JSON.stringify(stable)} now matches existing item ${existing.join(", ")}; the plan was resolved before it existed.`,EXIT_CODE.CONFLICT,{code:"upsert_key_conflict",required:"Re-plan the document so the row updates the existing item instead of creating a duplicate.",why:"Keyed upsert is resolved before the writer lock, so every remaining create is re-checked under the lock; concurrent imports therefore cannot create two items for one key value.",nextSteps:["Re-run pm item mutate with the same document and --upsert-key; the re-plan turns the row into an update of the existing item.","Inspect the existing item first when its content should win over the document row."]})}function assertUpsertMatchCurrent(document,id,match){const current=document.metadata[match.key],expected=stableUpsertValue(match.value);if(stableUpsertValue(current)!==expected)throw new PmCliError(`Item ${id} no longer carries upsert key "${match.key}" value ${JSON.stringify(expected)}; the plan selected it before the key changed.`,EXIT_CODE.CONFLICT,{code:"upsert_match_changed",required:"Re-plan the document so the row is resolved against the current key values.",why:"Keyed upsert selects its target before the writer lock, so the update re-reads the key under the lock instead of updating a mismatched item blindly.",nextSteps:["Re-run pm item mutate with the same document and --upsert-key; the re-plan creates or re-targets the row from the current key values."]})}function isValidUniqueKey(value){if(value===null||typeof value!="object"||Array.isArray(value))return!1;const candidate=value;return typeof candidate.key=="string"&&candidate.key.trim().length>0&&candidate.value!==void 0&&candidate.value!==null}function mergeTransactionMutationOptions(source,additions){const merged={...source,...additions};return source===void 0?merged:transferMutationStdinTokenPolicy(source,merged)}async function readItemSnapshot(pmRoot,id){try{const item=(await get(id,{},{pmRoot})).item;return{id:item.id,closedAt:item.closed_at,updatedAt:item.updated_at,assignee:item.assignee,claimPrincipal:item.claim_principal}}catch(error){if(error instanceof PmCliError&&error.exitCode===EXIT_CODE.NOT_FOUND)return;throw error}}function deriveStepId(mutation,index){const sanitizedTarget=mutation.id.replaceAll(/[^a-zA-Z0-9._-]/gu,"_"),fingerprint=crypto.createHash("sha256").update(stableStringify(mutation)).digest("hex").slice(0,12);return`${index+1}-${mutation.op}-${sanitizedTarget}-${fingerprint}`}function deriveOutcomeKey(mutation,index){const sanitizedTarget=mutation.id.replaceAll(/[^a-zA-Z0-9._-]/gu,"_");return`${index+1}-${mutation.op}-${sanitizedTarget}`}function bulkHistoryMarker(transactionId,stepId,phase){return`bulk-item-transaction ${transactionId} ${stepId} ${phase}`}function isStepMarkerMessage(message,marker){return message===marker||(message?.startsWith(`${marker} | `)??!1)}async function isUpdateMarkerApplied(pmRoot,canonicalId,transactionId,stepId){const entries=await readHistoryEntries(path.join(pmRoot,"history",`${canonicalId}.jsonl`),canonicalId),applyMarker=bulkHistoryMarker(transactionId,stepId,"apply"),compensateMarker=bulkHistoryMarker(transactionId,stepId,"compensate");for(let index=entries.length-1;index>=0;index-=1){const message=entries[index].message;if(isStepMarkerMessage(message,applyMarker))return!0;if(message===compensateMarker)return!1}return!1}async function prepareRestoreCompensation(pmRoot,mutation){const snapshot=await readItemSnapshot(pmRoot,mutation.id);if(snapshot?.updatedAt===void 0)throw new PmCliError(`Bulk ${mutation.op} target ${mutation.id} does not exist or has no restorable version`,EXIT_CODE.NOT_FOUND);const history=await readHistoryEntries(path.join(pmRoot,"history",`${snapshot.id}.jsonl`),snapshot.id);if(history.length===0)throw new PmCliError(`Bulk ${mutation.op} target ${mutation.id} has no restorable history`,EXIT_CODE.NOT_FOUND);return{target_updated_at:snapshot.updatedAt,target_version:String(historyVersionOffset(history)+history.length),target_history_hash:hashHistoryStream(history),target_history_length:history.length}}function partialMutationError(config,itemId,stepId){return new PmCliError(`Transaction ${config.transactionId} cannot safely compensate incomplete step ${stepId}; review item ${itemId} history before recovery.`,EXIT_CODE.CONFLICT,{code:"transaction_partial_mutation",item_id:itemId,required:"Reconcile the item's partial or intervening changes before resuming this transaction.",why:"The retained history does not prove exclusive ownership of the changes to undo. The journal remains compensating instead of claiming a rollback or overwriting another writer.",nextSteps:[`Run pm history ${itemId} and inspect this transaction's retained compensation data before explicitly restoring or reconciling the item.`]})}function isTransactionHistoryEntry(entry,transactionId){const prefix=`bulk-item-transaction ${transactionId} `;return[entry.message,entry.context?.item_transaction_step].some(value=>typeof value=="string"&&value.startsWith(prefix))}function hasOwnedCompensationEffects(history,proof,identity){const{expectedHistory,length,version}=proof;if(hashHistoryStream(history)===expectedHistory)return!1;if(typeof length!="number"||!Number.isSafeInteger(length)||length<1||hashHistoryStream(history.slice(0,length))!==expectedHistory||version!==String(historyVersionOffset(history)+length))throw partialMutationError(identity,identity.itemId,identity.stepId);const marker=bulkHistoryMarker(identity.transactionId,identity.stepId,"apply"),changes=history.slice(length),isOwned=entry=>isStepMarkerMessage(entry.message,marker)||entry.context?.item_transaction_step===marker,compensationMarker=bulkHistoryMarker(identity.transactionId,identity.stepId,"compensate");if(changes.filter(entry=>isOwned(entry)||entry.message===compensationMarker).at(-1)?.message===compensationMarker)return!1;const owned=changes.filter(isOwned);if(owned.length===0)return!1;const siblingsRestored=history.at(-1).after_hash===owned.at(-1).after_hash&&changes.every(entry=>isTransactionHistoryEntry(entry,identity.transactionId));if(owned.length!==changes.length&&!siblingsRestored)throw partialMutationError(identity,identity.itemId,identity.stepId);return!0}async function compensateByRestore(config,itemId,stepId,data){const receipt=data!==null&&typeof data=="object"&&!Array.isArray(data)?data:void 0;if(receipt===void 0||typeof receipt.target_updated_at!="string")return;const target=receipt.target_updated_at,current=await readItemSnapshot(config.pmRoot,itemId);if(current===void 0)return;const history=await readHistoryEntries(path.join(config.pmRoot,"history",`${current.id}.jsonl`),current.id),expectedHistory=receipt.target_history_hash;if(typeof expectedHistory=="string"){if(!hasOwnedCompensationEffects(history,{expectedHistory,length:receipt.target_history_length,version:receipt.target_version},{...config,itemId:current.id,stepId}))return}else{if(current.updatedAt===target)return;if(!await isUpdateMarkerApplied(config.pmRoot,current.id,config.transactionId,stepId))throw partialMutationError(config,current.id,stepId)}const applyRestore=()=>restore(itemId,typeof receipt.target_version=="string"?receipt.target_version:target,{force:!0,author:config.author,message:bulkHistoryMarker(config.transactionId,stepId,"compensate")},{pmRoot:config.pmRoot});await runWithItemMutationPrecondition({pmRoot:config.pmRoot,id:current.id,validate:document=>{if(hashDocument(document)!==history.at(-1).after_hash)throw partialMutationError(config,current.id,stepId)}},applyRestore)}function buildCreateStep(config,mutation,stepId){return{id:stepId,async inspect(){const snapshot=await readItemSnapshot(config.pmRoot,mutation.id);if(snapshot===void 0)return{state:"pending"};if(snapshot.closedAt!==void 0){const history=await readHistoryEntries(path.join(config.pmRoot,"history",`${snapshot.id}.jsonl`),snapshot.id),reason=`Compensated: interrupted bulk transaction ${config.transactionId}`;if(history.filter(entry=>entry.op==="close").at(-1)?.patch.some(change=>change.op==="add"||change.op==="replace"?change.path==="/metadata/close_reason"&&change.value===reason:!1)??!1)throw new PmCliError(`Created item ${snapshot.id} remains closed by transaction compensation; explicitly reopen or reconcile it before retrying.`,EXIT_CODE.CONFLICT,{code:"transaction_create_compensated",item_id:snapshot.id,required:"Review the compensated item and explicitly reopen it before retrying the same document.",why:"This item's latest closure belongs to transaction compensation. Automatically reopening it could overwrite later lifecycle decisions.",nextSteps:[`Run pm item reopen ${snapshot.id} "Retry compensated creation" after reviewing its history, then retry the transaction.`]})}return{state:"applied",result:{id:snapshot.id,op:"create"}}},async apply(){mutation.unique!==void 0&&await assertUniqueKeyFree(config.uniqueIndex,mutation.unique);const created=await create(mergeTransactionMutationOptions(mutation.options,{author:config.author,id:mutation.id,message:bulkHistoryMarker(config.transactionId,stepId,"apply")}),{pmRoot:config.pmRoot}),createdItem=created.item;return config.onCreateWarnings?.(String(createdItem.id),created.warnings),await config.uniqueIndex.recordCreate(createdItem),{id:String(createdItem.id),op:"create"}},async compensate(){await compensateCreatedItem(config,mutation.id,stepId)}}}async function compensateCreatedItem(config,id,stepId){const snapshot=await readItemSnapshot(config.pmRoot,id);if(snapshot===void 0||config.createCompensation==="close"&&snapshot.closedAt!==void 0)return;const history=await readHistoryEntries(path.join(config.pmRoot,"history",`${snapshot.id}.jsonl`),snapshot.id),applyMarker=bulkHistoryMarker(config.transactionId,stepId,"apply"),compensationMarker=bulkHistoryMarker(config.transactionId,stepId,"compensate"),latestMarker=history.filter(entry=>isStepMarkerMessage(entry.message,applyMarker)||entry.message===compensationMarker).at(-1);if(latestMarker?.message!==compensationMarker){if(latestMarker===void 0||!history.every(entry=>isTransactionHistoryEntry(entry,config.transactionId)))throw partialMutationError(config,snapshot.id,stepId);await runWithItemMutationPrecondition({pmRoot:config.pmRoot,id:snapshot.id,validate:document=>{if(hashDocument(document)!==history.at(-1).after_hash)throw partialMutationError(config,snapshot.id,stepId)}},async()=>{const options={force:!0,author:config.author,message:compensationMarker};config.createCompensation==="delete"?await deleteItem(id,options,{pmRoot:config.pmRoot}):await close(id,`Compensated: interrupted bulk transaction ${config.transactionId}`,{...options,validateClose:"off"},{pmRoot:config.pmRoot})})}}function buildUpdateStep(config,mutation,stepId){return{id:stepId,compensatePending:!0,async inspect(){const snapshot=await readItemSnapshot(config.pmRoot,mutation.id);return snapshot===void 0?{state:"pending"}:await isUpdateMarkerApplied(config.pmRoot,snapshot.id,config.transactionId,stepId)?{state:"applied",result:{id:snapshot.id,op:"update"}}:{state:"pending"}},async prepareCompensation(){return prepareRestoreCompensation(config.pmRoot,mutation)},async apply(){const applyUpdate=()=>update(mutation.id,mergeTransactionMutationOptions(mutation.options,{author:config.author,message:bulkHistoryMarker(config.transactionId,stepId,"apply")}),{pmRoot:config.pmRoot}),match=mutation.match;let currentMatch=match;const updatedItem=(await runWithItemMutationPrecondition({pmRoot:config.pmRoot,id:String((await get(mutation.id,{},{pmRoot:config.pmRoot})).item.id),validate:document=>{currentMatch!==void 0&&assertUpsertMatchCurrent(document,mutation.id,currentMatch)},committed:document=>{match!==void 0&&(currentMatch={key:match.key,value:structuredClone(document.metadata[match.key])})},historyContext:{item_transaction_step:bulkHistoryMarker(config.transactionId,stepId,"apply")}},applyUpdate)).item;return config.uniqueIndex.invalidate(),{id:String(updatedItem.id),op:"update"}},async compensate(data){await compensateByRestore(config,mutation.id,stepId,data)}}}function buildCloseStep(config,mutation,stepId){return{id:stepId,async inspect(){const snapshot=await readItemSnapshot(config.pmRoot,mutation.id);return snapshot===void 0?{state:"pending"}:await isUpdateMarkerApplied(config.pmRoot,snapshot.id,config.transactionId,stepId)?{state:"applied",result:{id:snapshot.id,op:"close"}}:snapshot.closedAt===void 0?{state:"pending"}:{state:"applied",result:{id:snapshot.id,op:"close"}}},async prepareCompensation(){return prepareRestoreCompensation(config.pmRoot,mutation)},async apply(){const closedItem=(await close(mutation.id,mutation.reason,mergeTransactionMutationOptions(mutation.options,{author:config.author,message:bulkHistoryMarker(config.transactionId,stepId,"apply")}),{pmRoot:config.pmRoot})).item;return config.uniqueIndex.invalidate(),{id:String(closedItem.id),op:"close"}},async compensate(data){await compensateByRestore(config,mutation.id,stepId,data)}}}function buildReleaseStep(config,mutation,stepId){return{id:stepId,async inspect(){const snapshot=await readItemSnapshot(config.pmRoot,mutation.id);return snapshot===void 0?{state:"pending"}:await isUpdateMarkerApplied(config.pmRoot,snapshot.id,config.transactionId,stepId)?{state:"applied",result:{id:snapshot.id,op:"release"}}:snapshot.assignee!==void 0||snapshot.claimPrincipal!==void 0?{state:"pending"}:{state:"applied",result:{id:snapshot.id,op:"release"}}},async prepareCompensation(){return prepareRestoreCompensation(config.pmRoot,mutation)},async apply(){const releasedItem=(await release(mutation.id,mergeTransactionMutationOptions(mutation.options,{author:config.author,message:bulkHistoryMarker(config.transactionId,stepId,"apply")}),{pmRoot:config.pmRoot})).item;return config.uniqueIndex.invalidate(),{id:String(releasedItem.id),op:"release"}},async compensate(data){await compensateByRestore(config,mutation.id,stepId,data)}}}function buildStepForMutation(config,mutation,index){const stepId=deriveStepId(mutation,index);switch(mutation.op){case"create":return buildCreateStep(config,mutation,stepId);case"update":return buildUpdateStep(config,mutation,stepId);case"close":return buildCloseStep(config,mutation,stepId);case"release":return buildReleaseStep(config,mutation,stepId)}}function assertValidBulkMutation(mutation,index){if(mutation===null||typeof mutation!="object"||Array.isArray(mutation))throw new TypeError(`Bulk mutation ${index+1} must be an object`);if(!["create","update","close","release"].includes(mutation.op))throw new TypeError(`Bulk mutation ${index+1} op must be create, update, close, or release`);if(typeof mutation.id!="string"||mutation.id.trim().length===0)throw new TypeError(`Bulk mutation ${index+1} requires a non-empty id`);if(mutation.op==="close"&&(typeof mutation.reason!="string"||mutation.reason.trim().length===0))throw new TypeError(`Bulk close mutation ${index+1} requires a non-empty reason`);if(mutation.op==="create"&&mutation.unique!==void 0&&!isValidUniqueKey(mutation.unique))throw new TypeError(`Bulk create mutation ${index+1} unique must be an object with a non-empty key and a value`);if(mutation.op==="update"&&mutation.match!==void 0&&!isValidUniqueKey(mutation.match))throw new TypeError(`Bulk update mutation ${index+1} match must be an object with a non-empty key and a value`);assertMutationOptionValueTypes(mutation.options,mutation.op,index)}function assertValidBulkMutations(mutations){if(mutations.length===0)throw new TypeError("Bulk item transaction requires at least one mutation");const keys=new Map;for(const[index,mutation]of mutations.entries()){if(assertValidBulkMutation(mutation,index),mutation.op!=="create"||mutation.unique===void 0)continue;const{key,value}=mutation.unique,values=keys.get(key)??new Map,stable=stableUpsertValue(value),previous=values.get(stable);if(previous!==void 0)throw new PmCliError(`Bulk create mutations ${previous+1} and ${index+1} share the upsert key value ${JSON.stringify(stable)} for "${key}".`,EXIT_CODE.USAGE,{code:"upsert_key_duplicate",required:"Each create must carry a distinct unique key value within one batch.",why:"Direct SDK batches must preserve the same uniqueness invariant as planned document rows."});values.set(stable,index),keys.set(key,values)}}function snapshotBulkMutations(input){const mutations=[...input];return assertValidBulkMutations(mutations),mutations.map(mutation=>{const snapshot=structuredClone(mutation);return mutation.options!==void 0&&snapshot.options!==void 0&&transferMutationStdinTokenPolicy(mutation.options,snapshot.options),snapshot})}function previewClockFields(value,pointer=""){return value===null||typeof value!="object"?[]:Object.entries(value).flatMap(([key,nested])=>{const current=`${pointer}/${key.replaceAll("~","~0").replaceAll("/","~1")}`;return/^(created_at|updated_at|closed_at|completed_at|timestamp)$/u.test(key)?[current]:previewClockFields(nested,current)})}async function validateMutationOperation(mutation,index,run){try{return await run()}catch(error){throw error instanceof PmCliError?new PmCliError(error.message,error.exitCode,{...error.context,transaction_operation:{index,op:mutation.op,id:mutation.id}}):error}}function includePreviewPath(root,file,ownedPaths,retainedPaths){const relative=path.relative(root,file),segments=relative.split(path.sep);return segments[0]==="extensions"&&segments[2]==="node_modules"&&!retainedPaths.some(retained=>relative===retained||relative.startsWith(`${retained}${path.sep}`)||retained.startsWith(`${relative}${path.sep}`))?!1:["locks","runtime","search"].includes(relative.split(path.sep)[0])?retainedPaths.some(retained=>relative===retained||relative.startsWith(`${retained}${path.sep}`)||retained.startsWith(`${relative}${path.sep}`)):relative===""||ownedPaths===void 0||ownedPaths.some(owned=>relative===owned||relative.startsWith(`${owned}${path.sep}`)||owned.startsWith(`${relative}${path.sep}`))}async function previewEntryStat(root,file){const entry=await lstat(file);if(entry.isSymbolicLink())await stat(file);else if(entry.isDirectory()||entry.isFile())return entry;throw transactionPreviewNonRegularFileError(path.relative(root,file))}async function previewFileDigest(root,file){const handle=await open(file,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{const entry=await handle.stat();if(!entry.isFile())throw transactionPreviewNonRegularFileError(path.relative(root,file));const contents=crypto.createHash("sha256");if(entry.size>0)for await(const chunk of handle.createReadStream({highWaterMark:64*1024,end:entry.size-1,autoClose:!1}))contents.update(chunk);return contents.digest()}finally{await handle.close()}}async function previewTrackerFingerprint(root,ownedPaths,retainedPaths){const fingerprint=crypto.createHash("sha256");async function visit(directory){for(const name of(await readdir(directory)).sort()){const file=path.join(directory,name);includePreviewPath(root,file,ownedPaths,retainedPaths)&&((await previewEntryStat(root,file)).isDirectory()?await visit(file):(fingerprint.update(JSON.stringify(path.relative(root,file))),fingerprint.update(await previewFileDigest(root,file))))}}return await visit(root),fingerprint.digest("hex")}function previewSnapshotChangedError(){return new PmCliError("Tracker changed while preparing the transaction preview; retry against stable state.",EXIT_CODE.CONFLICT,{code:"transaction_preview_snapshot_changed"})}async function isDisappearingPreviewPath(error){if(!isFileMissingError(error))return!1;const file=error.path;if(typeof file!="string")return!1;const original=path.resolve(file);let candidate=original;for(;;)try{const entry=await lstat(candidate);return candidate!==original&&entry.isDirectory()}catch(lookupError){if(!isFileMissingError(lookupError))return!1;const parent=path.dirname(candidate);if(parent===candidate)return!1;candidate=parent}}async function readPreviewConfiguration(root,relative){const file=path.join(root,relative);try{let current=root;for(const component of relative.split(path.sep).slice(0,-1))current=path.join(current,component),await previewEntryStat(root,current);if(!(await previewEntryStat(root,file)).isFile())throw transactionPreviewNonRegularFileError(relative);return await readRegularFile(file,transactionPreviewNonRegularFileError(relative))}catch(error){if(await isDisappearingPreviewPath(error))return;throw error}}async function stageGuardedSchemaSections(root,configurationRoot,schemaSettings,configuration){const schema=normalizeRuntimeSchemaSettings(schemaSettings);for(const[section,configuredPath]of Object.entries(schema.files)){const relative=path.relative(root,filePathForSchemaSection(root,configuredPath,DEFAULT_RUNTIME_SCHEMA_FILE_PATHS[section]));if(relative===""||!path.resolve(root,relative).startsWith(path.join(root,path.sep)))throw new PmCliError("Transaction preview requires schema files inside the selected tracker root; relocate the configured schema file before retrying.",EXIT_CODE.USAGE,{code:"transaction_preview_external_schema",field:`schema.files.${section}`});schema.files[section]=relative;const contents=await readPreviewConfiguration(root,relative);if(configuration?.set(relative,contents),contents!==void 0){const target=path.join(configurationRoot,relative);await mkdir(path.dirname(target),{recursive:!0}),await writeFile(target,contents)}}return loadRuntimeSchemaFromOptionalFiles(configurationRoot,schema)}async function loadGuardedRuntimeSchema(pmRoot,schemaSettings){await stat(pmRoot);const root=await mkdtemp(path.join(tmpdir(),"pm-schema-plan-"));try{const resolvedRoot=await realpath(pmRoot);return await stageGuardedSchemaSections(resolvedRoot,path.join(root,"configuration"),schemaSettings)}catch(error){throw await isDisappearingPreviewPath(error)?previewSnapshotChangedError():error}finally{await rm(root,{recursive:!0,force:!0})}}async function resolvePreviewStorage(root,configurationRoot,registrations){const configuration=new Map,rawSettings=await readPreviewConfiguration(root,SETTINGS_FILENAME);configuration.set(SETTINGS_FILENAME,rawSettings);let parsed;try{parsed=JSON.parse(rawSettings??"null")}catch{parsed=null}const validated=validateSettings(parsed),settings=validated.success?validated.data:void 0,loaded=await stageGuardedSchemaSections(root,configurationRoot,settings?.schema,configuration),schema=loaded.schema,sessionPath=path.relative(root,getSessionStatePath(root));configuration.set(sessionPath,await readPreviewConfiguration(root,sessionPath));const registry=resolveItemTypeRegistry({...SETTINGS_DEFAULTS,item_types:{definitions:[...settings?.item_types?.definitions??[],...loaded.type_definitions_from_file??[]]}},registrations),ownedPaths=resolveWorkspaceRoot(root)===root?[...PM_REQUIRED_SUBDIRS.filter(Boolean),SETTINGS_FILENAME,PM_CONTEXT_INTENTS_FILE,"transactions",...registry.folders,...configuration.keys()].map(entry=>path.normalize(entry)):void 0,stagedSettings=settings===void 0?void 0:JSON.stringify({...parsed,schema:{...settings.schema,files:schema.files}});return{configuration,ownedPaths,stagedSettings,registryFolders:registry.folders}}async function stagePreviewTracker(sourceRoot,stagedRoot,registrations){await stat(sourceRoot);try{const resolvedRoot=await realpath(sourceRoot),storage=await resolvePreviewStorage(resolvedRoot,path.join(path.dirname(stagedRoot),"configuration"),registrations),retainedPaths=[...storage.configuration.keys(),...storage.registryFolders].map(entry=>path.normalize(entry)),sourceFingerprint=await previewTrackerFingerprint(resolvedRoot,storage.ownedPaths,retainedPaths);await cp(resolvedRoot,stagedRoot,{recursive:!0,dereference:!1,filter:async source=>includePreviewPath(resolvedRoot,source,storage.ownedPaths,retainedPaths)?(await previewEntryStat(resolvedRoot,source),!0):!1});const[currentFingerprint,stagedFingerprint]=await Promise.all([previewTrackerFingerprint(resolvedRoot,storage.ownedPaths,retainedPaths),previewTrackerFingerprint(stagedRoot,storage.ownedPaths,retainedPaths)]);if(sourceFingerprint!==currentFingerprint||sourceFingerprint!==stagedFingerprint)throw previewSnapshotChangedError();for(const[relative,contents]of storage.configuration)if(await readPreviewConfiguration(stagedRoot,relative)!==contents)throw previewSnapshotChangedError();storage.stagedSettings!==void 0&&await writeFile(path.join(stagedRoot,SETTINGS_FILENAME),storage.stagedSettings)}catch(error){throw await isDisappearingPreviewPath(error)?previewSnapshotChangedError():error}}async function previewItemMutations(options){const identity=validateWorkspaceTransactionIdentity(options),mutations=snapshotBulkMutations(options.mutations),registrations=getActiveExtensionRegistrations(),guards=getActiveExtensionHooks(),root=await mkdtemp(path.join(tmpdir(),"pm-transaction-preview-")),stagedRoot=path.join(root,"tracker");try{await stagePreviewTracker(identity.pmRoot,stagedRoot,registrations);let validated=!1;const warnings=[],records=[],applied=new Set;return await runWithPreviewMutationGuards(guards,()=>runWithActiveExtensions({path:stagedRoot,noExtensions:!0},async()=>{setActiveExtensionRegistrations(registrations);const config={...identity,pmRoot:stagedRoot,createCompensation:"close",uniqueIndex:createUniqueKeyIndex(stagedRoot)},steps=mutations.map((mutation,index)=>{const step=buildStepForMutation({...config,onCreateWarnings:(id,messages)=>{messages.length>0&&warnings.push({index,id,op:"create",warnings:messages})}},mutation,index);return{...step,inspect:()=>validateMutationOperation(mutation,index,()=>step.inspect()),prepareCompensation:()=>validateMutationOperation(mutation,index,async()=>step.prepareCompensation?.()),apply:()=>validateMutationOperation(mutation,index,async()=>{const outcome=await step.apply();return applied.add(index),outcome})}});if(await commitWorkspaceTransaction({...identity,pmRoot:stagedRoot,steps,onTransition:({transition})=>{transition==="committed"&&(validated=!0)}}),validated)for(const[index,mutation]of mutations.entries()){const item=(await runGet(mutation.id,{path:stagedRoot},{full:!0})).item;records.push({index,id:String(item.id),op:mutation.op,execution:applied.has(index)?"applied":"adopted",item,commit_time_fields:previewClockFields(item)})}})),{records,validated,state:validated?"staged_snapshot":"replayed_committed_plan",warnings,unresolved_commit_constraints:["concurrent_tracker_changes","extension_write_hooks","derived_extension_dependencies_excluded","generated_timestamps_and_provenance"]}}finally{await rm(root,{recursive:!0,force:!0})}}async function commitItemMutations(options){const identity=validateWorkspaceTransactionIdentity(options),mutations=snapshotBulkMutations(options.mutations),createCompensation=options.createCompensation??"close";if(!["close","delete"].includes(createCompensation))throw new TypeError("Bulk item transaction createCompensation must be close or delete");const stepConfig={...identity,createCompensation,uniqueIndex:createUniqueKeyIndex(identity.pmRoot)},committed=await commitWorkspaceTransaction({...identity,steps:mutations.map((mutation,index)=>buildStepForMutation(stepConfig,mutation,index)),recoveryData:JSON.parse(JSON.stringify({kind:"item-mutations-v1",mutations,createCompensation})),...options.lockTtlSeconds===void 0?{}:{lockTtlSeconds:options.lockTtlSeconds},...options.lockWaitMs===void 0?{}:{lockWaitMs:options.lockWaitMs},...options.onTransition===void 0?{}:{onTransition:options.onTransition}}),results={};for(const[index,mutation]of mutations.entries()){const stepId=deriveStepId(mutation,index),value=committed.results[stepId];results[deriveOutcomeKey(mutation,index)]=value}return{transactionId:committed.transactionId,status:"committed",recovered:committed.recovered,results}}function buildItemCompletionMutations(options){const mutations=[];return options.evidence!==void 0&&Object.keys(options.evidence).length>0&&mutations.push({op:"update",id:options.id,options:options.evidence}),mutations.push({op:"close",id:options.id,reason:options.reason,...options.closeOptions===void 0?{}:{options:options.closeOptions}},{op:"release",id:options.id,...options.releaseOptions===void 0?{}:{options:options.releaseOptions}}),mutations}function commitItemCompletion(options){return commitItemMutations({pmRoot:options.pmRoot,transactionId:options.transactionId,author:options.author,mutations:buildItemCompletionMutations(options),...options.lockTtlSeconds===void 0?{}:{lockTtlSeconds:options.lockTtlSeconds},...options.lockWaitMs===void 0?{}:{lockWaitMs:options.lockWaitMs},...options.onTransition===void 0?{}:{onTransition:options.onTransition}})}const _testOnlyItemTransaction={buildCreateStep,bulkHistoryMarker,compensateByRestore,deriveStepId,isUpdateMarkerApplied,readItemSnapshot};async function readItemTransaction(pmRoot,transactionId){const journal=await readWorkspaceTransaction(pmRoot,transactionId);return journal===void 0?void 0:{journal,planDigest:workspaceTransactionPlanDigest(journal)}}function recoveryItemSteps(options,journal){const data=journal.recoveryData;if(data===null||typeof data!="object"||Array.isArray(data)||data.kind!=="item-mutations-v1"||!Array.isArray(data.mutations)||!["close","delete"].includes(String(data.createCompensation)))throw new PmCliError("Transaction has no supported item recovery plan",EXIT_CODE.CONFLICT,{code:"transaction_recovery_plan_missing",required:"Resume with the original plan and its original adapter.",why:"Legacy or foreign journals cannot safely reconstruct item compensation."});const mutations=data.mutations;assertValidBulkMutations(mutations);const config={...options,createCompensation:data.createCompensation,uniqueIndex:createUniqueKeyIndex(options.pmRoot)};return mutations.map((mutation,index)=>buildStepForMutation(config,mutation,index))}async function abandonItemTransaction(options){const identity=validateWorkspaceTransactionIdentity(options),journal=await abandonWorkspaceTransaction({...options,...identity,resolveSteps:receipt=>recoveryItemSteps({...options,...identity},receipt)});return{journal,planDigest:workspaceTransactionPlanDigest(journal)}}export{_testOnlyItemTransaction,abandonItemTransaction,buildItemCompletionMutations,commitItemCompletion,commitItemMutations,listUpsertKeyCandidates,loadGuardedRuntimeSchema,previewItemMutations,readItemTransaction,resolveTransactionSchema};
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="359a47e6-c7e8-5713-bd07-1e19fb81674a")}catch{}})();import crypto from"node:crypto";import{runGet}from"./query/get.js";import{constants,readFileSync}from"node:fs";import{isFileMissingError,readRegularFile,transactionPreviewNonRegularFileError}from"../core/fs/fs-utils.js";import{cp,lstat,mkdir,mkdtemp,open,readdir,realpath,rm,stat,writeFile}from"node:fs/promises";import{tmpdir}from"node:os";import{getActiveExtensionHooks,getActiveExtensionRegistrations,runWithPreviewMutationGuards,setActiveExtensionRegistrations}from"../core/extensions/index.js";import path from"node:path";import{transferMutationStdinTokenPolicy}from"../core/item/parse.js";import{EXIT_CODE,PM_REQUIRED_SUBDIRS,SETTINGS_DEFAULTS,SETTINGS_FILENAME}from"../core/shared/constants.js";import{resolveItemTypeRegistry}from"../core/item/type-registry.js";import{listAllItemMetadataLight}from"../core/store/item-store.js";import{runWithItemMutationPrecondition}from"../core/store/item-mutation-precondition.js";import{activeCoordinatorStep}from"../core/store/transaction-coordinator-scope.js";import{hashDocument,hashHistoryStream}from"../core/history/history.js";import{historyVersionOffset}from"../core/history/version-address.js";import{isConfigurationOnlySettingsRead,readSettings}from"../core/store/settings.js";import{DEFAULT_RUNTIME_SCHEMA_FILE_PATHS,filePathForSchemaSection,loadRuntimeSchemaFromOptionalFiles,normalizeRuntimeSchemaSettings}from"../core/schema/runtime-schema.js";import{validateSettings}from"../core/store/settings-validator.js";import{resolveWorkspaceRoot}from"../core/store/paths.js";import{getSessionStatePath}from"../core/session/session-state.js";import{PmCliError}from"../core/shared/errors.js";import{stableUpsertValue}from"./structured-mutations.js";import{stableStringify}from"../core/shared/serialization.js";import{assertMutationOptionValueTypes}from"./lifecycle/mutation-option-validation.js";import{readHistoryEntries}from"./history-read.js";import{readHistorySnapshot}from"../core/history/read.js";import{PM_CONTEXT_INTENTS_FILE}from"./context-intent-runtime.js";import{close,create,deleteItem,get,release,restore,update,runWithActiveExtensions}from"./runtime.js";import{commitWorkspaceTransaction,abandonWorkspaceTransaction,readWorkspaceTransaction,workspaceTransactionPlanDigest,validateWorkspaceTransactionIdentity}from"./workspace-transaction.js";async function resolveTransactionSchema(pmRoot,settings){if(!isConfigurationOnlySettingsRead(pmRoot))return{schema:normalizeRuntimeSchemaSettings(settings.schema),typeDefinitionsFromFile:[]};const loaded=await loadGuardedRuntimeSchema(pmRoot,settings.schema);return{schema:loaded.schema,typeDefinitionsFromFile:loaded.type_definitions_from_file??[]}}async function listUpsertKeyCandidates(pmRoot,settings,schemaContext,key){const typeRegistry=resolveItemTypeRegistry({...settings,item_types:{...settings.item_types,definitions:[...settings.item_types?.definitions??[],...schemaContext.typeDefinitionsFromFile]}},getActiveExtensionRegistrations());return(await listAllItemMetadataLight(pmRoot,settings.item_format,typeRegistry.type_to_folder,void 0,schemaContext.schema)).flatMap(item=>{const value=item[key];return value==null?[]:[{id:item.id,value}]})}function createUniqueKeyIndex(pmRoot){const scans=new Map,scan=async key=>{const settings=await readSettings(pmRoot),schemaContext=await resolveTransactionSchema(pmRoot,settings),byValue=new Map;for(const candidate of await listUpsertKeyCandidates(pmRoot,settings,schemaContext,key)){const stable=stableUpsertValue(candidate.value);byValue.set(stable,[...byValue.get(stable)??[],candidate.id])}return byValue};return{lookup(key){const pending=scans.get(key)??scan(key);return scans.set(key,pending),pending},async recordCreate(item){for(const[key,pending]of scans){const value=item[key];if(value==null)continue;const byValue=await pending,stable=stableUpsertValue(value);byValue.set(stable,[...byValue.get(stable)??[],String(item.id)])}},invalidate(){scans.clear()}}}async function assertUniqueKeyFree(index,unique){const stable=stableUpsertValue(unique.value),existing=(await index.lookup(unique.key)).get(stable)??[];if(existing.length!==0)throw new PmCliError(`Upsert key "${unique.key}" value ${JSON.stringify(stable)} now matches existing item ${existing.join(", ")}; the plan was resolved before it existed.`,EXIT_CODE.CONFLICT,{code:"upsert_key_conflict",required:"Re-plan the document so the row updates the existing item instead of creating a duplicate.",why:"Keyed upsert is resolved before the writer lock, so every remaining create is re-checked under the lock; concurrent imports therefore cannot create two items for one key value.",nextSteps:["Re-run pm item mutate with the same document and --upsert-key; the re-plan turns the row into an update of the existing item.","Inspect the existing item first when its content should win over the document row."]})}function assertUpsertMatchCurrent(document,id,match){const current=document.metadata[match.key],expected=stableUpsertValue(match.value);if(stableUpsertValue(current)!==expected)throw new PmCliError(`Item ${id} no longer carries upsert key "${match.key}" value ${JSON.stringify(expected)}; the plan selected it before the key changed.`,EXIT_CODE.CONFLICT,{code:"upsert_match_changed",required:"Re-plan the document so the row is resolved against the current key values.",why:"Keyed upsert selects its target before the writer lock, so the update re-reads the key under the lock instead of updating a mismatched item blindly.",nextSteps:["Re-run pm item mutate with the same document and --upsert-key; the re-plan creates or re-targets the row from the current key values."]})}function isValidUniqueKey(value){if(value===null||typeof value!="object"||Array.isArray(value))return!1;const candidate=value;return typeof candidate.key=="string"&&candidate.key.trim().length>0&&candidate.value!==void 0&&candidate.value!==null}function mergeTransactionMutationOptions(source,additions){const merged={...source,...additions};return source===void 0?merged:transferMutationStdinTokenPolicy(source,merged)}async function readItemSnapshot(pmRoot,id){try{const item=(await get(id,{},{pmRoot})).item;return{id:item.id,closedAt:item.closed_at,updatedAt:item.updated_at,assignee:item.assignee,claimPrincipal:item.claim_principal}}catch(error){if(error instanceof PmCliError&&error.exitCode===EXIT_CODE.NOT_FOUND)return;throw error}}function deriveStepId(mutation,index){const sanitizedTarget=mutation.id.replaceAll(/[^a-zA-Z0-9._-]/gu,"_"),fingerprint=crypto.createHash("sha256").update(stableStringify(mutation)).digest("hex").slice(0,12);return`${index+1}-${mutation.op}-${sanitizedTarget}-${fingerprint}`}function deriveOutcomeKey(mutation,index){const sanitizedTarget=mutation.id.replaceAll(/[^a-zA-Z0-9._-]/gu,"_");return`${index+1}-${mutation.op}-${sanitizedTarget}`}function bulkHistoryMarker(transactionId,stepId,phase){return`bulk-item-transaction ${transactionId} ${stepId} ${phase}`}function isStepMarkerMessage(message,marker){return message===marker||(message?.startsWith(`${marker} | `)??!1)}async function isUpdateMarkerApplied(pmRoot,canonicalId,transactionId,stepId){const entries=await readHistoryEntries(path.join(pmRoot,"history",`${canonicalId}.jsonl`),canonicalId),applyMarker=bulkHistoryMarker(transactionId,stepId,"apply"),compensateMarker=bulkHistoryMarker(transactionId,stepId,"compensate");for(let index=entries.length-1;index>=0;index-=1){const message=entries[index].message;if(isStepMarkerMessage(message,applyMarker))return!0;if(message===compensateMarker)return!1}return!1}async function prepareRestoreCompensation(pmRoot,mutation){const snapshot=await readItemSnapshot(pmRoot,mutation.id);if(snapshot?.updatedAt===void 0)throw new PmCliError(`Bulk ${mutation.op} target ${mutation.id} does not exist or has no restorable version`,EXIT_CODE.NOT_FOUND);const history=await readHistoryEntries(path.join(pmRoot,"history",`${snapshot.id}.jsonl`),snapshot.id);if(history.length===0)throw new PmCliError(`Bulk ${mutation.op} target ${mutation.id} has no restorable history`,EXIT_CODE.NOT_FOUND);return{target_updated_at:snapshot.updatedAt,target_version:String(historyVersionOffset(history)+history.length),target_history_hash:hashHistoryStream(history),target_history_length:history.length}}function partialMutationError(config,itemId,stepId){return new PmCliError(`Transaction ${config.transactionId} cannot safely compensate incomplete step ${stepId}; review item ${itemId} history before recovery.`,EXIT_CODE.CONFLICT,{code:"transaction_partial_mutation",item_id:itemId,required:"Reconcile the item's partial or intervening changes before resuming this transaction.",why:"The retained history does not prove exclusive ownership of the changes to undo. The journal remains compensating instead of claiming a rollback or overwriting another writer.",nextSteps:[`Run pm history ${itemId} and inspect this transaction's retained compensation data before explicitly restoring or reconciling the item.`]})}function isTransactionHistoryEntry(entry,transactionId){const prefix=`bulk-item-transaction ${transactionId} `;return[entry.message,entry.context?.item_transaction_step].some(value=>typeof value=="string"&&value.startsWith(prefix))}function hasOwnedCompensationEffects(history,proof,identity){const{expectedHistory,length,version}=proof;if(hashHistoryStream(history)===expectedHistory)return!1;if(typeof length!="number"||!Number.isSafeInteger(length)||length<1||hashHistoryStream(history.slice(0,length))!==expectedHistory||version!==String(historyVersionOffset(history)+length))throw partialMutationError(identity,identity.itemId,identity.stepId);const marker=bulkHistoryMarker(identity.transactionId,identity.stepId,"apply"),changes=history.slice(length),isOwned=entry=>isStepMarkerMessage(entry.message,marker)||entry.context?.item_transaction_step===marker,compensationMarker=bulkHistoryMarker(identity.transactionId,identity.stepId,"compensate");if(changes.filter(entry=>isOwned(entry)||entry.message===compensationMarker).at(-1)?.message===compensationMarker)return!1;const owned=changes.filter(isOwned);if(owned.length===0)return!1;const siblingsRestored=history.at(-1).after_hash===owned.at(-1).after_hash&&changes.every(entry=>isTransactionHistoryEntry(entry,identity.transactionId));if(owned.length!==changes.length&&!siblingsRestored)throw partialMutationError(identity,identity.itemId,identity.stepId);return!0}async function readOwnershipHistory(pmRoot,id){const historyPath=path.join(pmRoot,"history",`${id}.jsonl`),snapshot=await readHistorySnapshot(historyPath,id);return{history:snapshot.entries,assertOwnedUnderLock:(document,refusal)=>{let owned;try{owned=readFileSync(historyPath).equals(snapshot.raw_bytes)&&hashDocument(document)===snapshot.entries.at(-1).after_hash}catch(cause){throw Object.assign(refusal(),{cause})}if(!owned)throw refusal()}}}async function compensateByRestore(config,itemId,stepId,data){const receipt=data!==null&&typeof data=="object"&&!Array.isArray(data)?data:void 0;if(receipt===void 0||typeof receipt.target_updated_at!="string")return;const target=receipt.target_updated_at,current=await readItemSnapshot(config.pmRoot,itemId);if(current===void 0)return;const{history,assertOwnedUnderLock}=await readOwnershipHistory(config.pmRoot,current.id),expectedHistory=receipt.target_history_hash,journalBound=typeof expectedHistory=="string";if(typeof expectedHistory=="string"){if(!hasOwnedCompensationEffects(history,{expectedHistory,length:receipt.target_history_length,version:receipt.target_version},{...config,itemId:current.id,stepId}))return}else{if(current.updatedAt===target)return;if(!await isUpdateMarkerApplied(config.pmRoot,current.id,config.transactionId,stepId))throw partialMutationError(config,current.id,stepId)}const applyRestore=()=>restore(itemId,typeof receipt.target_version=="string"?receipt.target_version:target,{force:!0,author:config.author,message:bulkHistoryMarker(config.transactionId,stepId,"compensate")},{pmRoot:config.pmRoot});await runWithItemMutationPrecondition({pmRoot:config.pmRoot,id:current.id,validate:document=>{assertOwnedUnderLock(document,()=>partialMutationError(config,current.id,stepId))},compensation:ownedCompensation(config,itemId,stepId,"restore",journalBound)},applyRestore)}const coordinatorOwnedSteps=new WeakMap;function ownedCompensation(config,itemId,stepId,operation,historyBound){const step=historyBound?activeCoordinatorStep(config.pmRoot,config.transactionId):void 0,owner=step===void 0?void 0:coordinatorOwnedSteps.get(step);if(!(owner?.stepId!==stepId||owner.itemId!==itemId||owner.operation!==operation))return{transaction_id:config.transactionId,step_id:stepId,operations:[operation],overrides:[]}}function buildCreateStep(config,mutation,stepId){return{id:stepId,async inspect(){const snapshot=await readItemSnapshot(config.pmRoot,mutation.id);if(snapshot===void 0)return{state:"pending"};if(snapshot.closedAt!==void 0){const history=await readHistoryEntries(path.join(config.pmRoot,"history",`${snapshot.id}.jsonl`),snapshot.id),reason=`Compensated: interrupted bulk transaction ${config.transactionId}`;if(history.filter(entry=>entry.op==="close").at(-1)?.patch.some(change=>change.op==="add"||change.op==="replace"?change.path==="/metadata/close_reason"&&change.value===reason:!1)??!1)throw new PmCliError(`Created item ${snapshot.id} remains closed by transaction compensation; explicitly reopen or reconcile it before retrying.`,EXIT_CODE.CONFLICT,{code:"transaction_create_compensated",item_id:snapshot.id,required:"Review the compensated item and explicitly reopen it before retrying the same document.",why:"This item's latest closure belongs to transaction compensation. Automatically reopening it could overwrite later lifecycle decisions.",nextSteps:[`Run pm item reopen ${snapshot.id} "Retry compensated creation" after reviewing its history, then retry the transaction.`]})}return{state:"applied",result:{id:snapshot.id,op:"create"}}},async apply(){mutation.unique!==void 0&&await assertUniqueKeyFree(config.uniqueIndex,mutation.unique);const created=await create(mergeTransactionMutationOptions(mutation.options,{author:config.author,id:mutation.id,message:bulkHistoryMarker(config.transactionId,stepId,"apply")}),{pmRoot:config.pmRoot}),createdItem=created.item;return config.onCreateWarnings?.(String(createdItem.id),created.warnings),await config.uniqueIndex.recordCreate(createdItem),{id:String(createdItem.id),op:"create"}},async compensate(){await compensateCreatedItem(config,mutation.id,stepId)}}}async function compensateCreatedItem(config,id,stepId){const snapshot=await readItemSnapshot(config.pmRoot,id);if(snapshot===void 0||config.createCompensation==="close"&&snapshot.closedAt!==void 0)return;const{history,assertOwnedUnderLock}=await readOwnershipHistory(config.pmRoot,snapshot.id),applyMarker=bulkHistoryMarker(config.transactionId,stepId,"apply"),compensationMarker=bulkHistoryMarker(config.transactionId,stepId,"compensate"),latestMarker=history.filter(entry=>isStepMarkerMessage(entry.message,applyMarker)||entry.message===compensationMarker).at(-1);if(latestMarker?.message!==compensationMarker){if(latestMarker===void 0||!history.every(entry=>isTransactionHistoryEntry(entry,config.transactionId)))throw partialMutationError(config,snapshot.id,stepId);await runWithItemMutationPrecondition({pmRoot:config.pmRoot,id:snapshot.id,validate:document=>{assertOwnedUnderLock(document,()=>partialMutationError(config,snapshot.id,stepId))},compensation:ownedCompensation(config,id,stepId,config.createCompensation==="delete"?"delete":"close",!0)},async()=>{const options={force:!0,author:config.author,message:compensationMarker};config.createCompensation==="delete"?await deleteItem(id,options,{pmRoot:config.pmRoot}):await close(id,`Compensated: interrupted bulk transaction ${config.transactionId}`,{...options,validateClose:"off"},{pmRoot:config.pmRoot})})}}function buildUpdateStep(config,mutation,stepId){return{id:stepId,compensatePending:!0,async inspect(){const snapshot=await readItemSnapshot(config.pmRoot,mutation.id);return snapshot===void 0?{state:"pending"}:await isUpdateMarkerApplied(config.pmRoot,snapshot.id,config.transactionId,stepId)?{state:"applied",result:{id:snapshot.id,op:"update"}}:{state:"pending"}},async prepareCompensation(){return prepareRestoreCompensation(config.pmRoot,mutation)},async apply(){const applyUpdate=()=>update(mutation.id,mergeTransactionMutationOptions(mutation.options,{author:config.author,message:bulkHistoryMarker(config.transactionId,stepId,"apply")}),{pmRoot:config.pmRoot}),match=mutation.match;let currentMatch=match;const updatedItem=(await runWithItemMutationPrecondition({pmRoot:config.pmRoot,id:String((await get(mutation.id,{},{pmRoot:config.pmRoot})).item.id),validate:document=>{currentMatch!==void 0&&assertUpsertMatchCurrent(document,mutation.id,currentMatch)},committed:document=>{match!==void 0&&(currentMatch={key:match.key,value:structuredClone(document.metadata[match.key])})},historyContext:{item_transaction_step:bulkHistoryMarker(config.transactionId,stepId,"apply")}},applyUpdate)).item;return config.uniqueIndex.invalidate(),{id:String(updatedItem.id),op:"update"}},async compensate(data){await compensateByRestore(config,mutation.id,stepId,data)}}}function buildCloseStep(config,mutation,stepId){return{id:stepId,async inspect(){const snapshot=await readItemSnapshot(config.pmRoot,mutation.id);return snapshot===void 0?{state:"pending"}:await isUpdateMarkerApplied(config.pmRoot,snapshot.id,config.transactionId,stepId)?{state:"applied",result:{id:snapshot.id,op:"close"}}:snapshot.closedAt===void 0?{state:"pending"}:{state:"applied",result:{id:snapshot.id,op:"close"}}},async prepareCompensation(){return prepareRestoreCompensation(config.pmRoot,mutation)},async apply(){const closedItem=(await close(mutation.id,mutation.reason,mergeTransactionMutationOptions(mutation.options,{author:config.author,message:bulkHistoryMarker(config.transactionId,stepId,"apply")}),{pmRoot:config.pmRoot})).item;return config.uniqueIndex.invalidate(),{id:String(closedItem.id),op:"close"}},async compensate(data){await compensateByRestore(config,mutation.id,stepId,data)}}}function buildReleaseStep(config,mutation,stepId){return{id:stepId,async inspect(){const snapshot=await readItemSnapshot(config.pmRoot,mutation.id);return snapshot===void 0?{state:"pending"}:await isUpdateMarkerApplied(config.pmRoot,snapshot.id,config.transactionId,stepId)?{state:"applied",result:{id:snapshot.id,op:"release"}}:snapshot.assignee!==void 0||snapshot.claimPrincipal!==void 0?{state:"pending"}:{state:"applied",result:{id:snapshot.id,op:"release"}}},async prepareCompensation(){return prepareRestoreCompensation(config.pmRoot,mutation)},async apply(){const releasedItem=(await release(mutation.id,mergeTransactionMutationOptions(mutation.options,{author:config.author,message:bulkHistoryMarker(config.transactionId,stepId,"apply")}),{pmRoot:config.pmRoot})).item;return config.uniqueIndex.invalidate(),{id:String(releasedItem.id),op:"release"}},async compensate(data){await compensateByRestore(config,mutation.id,stepId,data)}}}function buildStepForMutation(config,mutation,index){const stepId=deriveStepId(mutation,index),step=buildPlannedStep(config,mutation,stepId);return coordinatorOwnedSteps.set(step,{transactionId:config.transactionId,stepId,itemId:mutation.id,operation:mutation.op!=="create"?"restore":config.createCompensation==="delete"?"delete":"close"}),step}function buildPlannedStep(config,mutation,stepId){switch(mutation.op){case"create":return buildCreateStep(config,mutation,stepId);case"update":return buildUpdateStep(config,mutation,stepId);case"close":return buildCloseStep(config,mutation,stepId);case"release":return buildReleaseStep(config,mutation,stepId)}}function assertValidBulkMutation(mutation,index){if(mutation===null||typeof mutation!="object"||Array.isArray(mutation))throw new TypeError(`Bulk mutation ${index+1} must be an object`);if(!["create","update","close","release"].includes(mutation.op))throw new TypeError(`Bulk mutation ${index+1} op must be create, update, close, or release`);if(typeof mutation.id!="string"||mutation.id.trim().length===0)throw new TypeError(`Bulk mutation ${index+1} requires a non-empty id`);if(mutation.op==="close"&&(typeof mutation.reason!="string"||mutation.reason.trim().length===0))throw new TypeError(`Bulk close mutation ${index+1} requires a non-empty reason`);if(mutation.op==="create"&&mutation.unique!==void 0&&!isValidUniqueKey(mutation.unique))throw new TypeError(`Bulk create mutation ${index+1} unique must be an object with a non-empty key and a value`);if(mutation.op==="update"&&mutation.match!==void 0&&!isValidUniqueKey(mutation.match))throw new TypeError(`Bulk update mutation ${index+1} match must be an object with a non-empty key and a value`);assertMutationOptionValueTypes(mutation.options,mutation.op,index)}function assertValidBulkMutations(mutations){if(mutations.length===0)throw new TypeError("Bulk item transaction requires at least one mutation");const keys=new Map;for(const[index,mutation]of mutations.entries()){if(assertValidBulkMutation(mutation,index),mutation.op!=="create"||mutation.unique===void 0)continue;const{key,value}=mutation.unique,values=keys.get(key)??new Map,stable=stableUpsertValue(value),previous=values.get(stable);if(previous!==void 0)throw new PmCliError(`Bulk create mutations ${previous+1} and ${index+1} share the upsert key value ${JSON.stringify(stable)} for "${key}".`,EXIT_CODE.USAGE,{code:"upsert_key_duplicate",required:"Each create must carry a distinct unique key value within one batch.",why:"Direct SDK batches must preserve the same uniqueness invariant as planned document rows."});values.set(stable,index),keys.set(key,values)}}function snapshotBulkMutations(input){const mutations=[...input];return assertValidBulkMutations(mutations),mutations.map(mutation=>{const snapshot=structuredClone(mutation);return mutation.options!==void 0&&snapshot.options!==void 0&&transferMutationStdinTokenPolicy(mutation.options,snapshot.options),snapshot})}function previewClockFields(value,pointer=""){return value===null||typeof value!="object"?[]:Object.entries(value).flatMap(([key,nested])=>{const current=`${pointer}/${key.replaceAll("~","~0").replaceAll("/","~1")}`;return/^(created_at|updated_at|closed_at|completed_at|timestamp)$/u.test(key)?[current]:previewClockFields(nested,current)})}async function validateMutationOperation(mutation,index,run){try{return await run()}catch(error){throw error instanceof PmCliError?new PmCliError(error.message,error.exitCode,{...error.context,transaction_operation:{index,op:mutation.op,id:mutation.id}}):error}}function includePreviewPath(root,file,ownedPaths,retainedPaths){const relative=path.relative(root,file),segments=relative.split(path.sep);return segments[0]==="extensions"&&segments[2]==="node_modules"&&!retainedPaths.some(retained=>relative===retained||relative.startsWith(`${retained}${path.sep}`)||retained.startsWith(`${relative}${path.sep}`))?!1:["locks","runtime","search"].includes(relative.split(path.sep)[0])?retainedPaths.some(retained=>relative===retained||relative.startsWith(`${retained}${path.sep}`)||retained.startsWith(`${relative}${path.sep}`)):relative===""||ownedPaths===void 0||ownedPaths.some(owned=>relative===owned||relative.startsWith(`${owned}${path.sep}`)||owned.startsWith(`${relative}${path.sep}`))}async function previewEntryStat(root,file){const entry=await lstat(file);if(entry.isSymbolicLink())await stat(file);else if(entry.isDirectory()||entry.isFile())return entry;throw transactionPreviewNonRegularFileError(path.relative(root,file))}async function previewFileDigest(root,file){const handle=await open(file,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{const entry=await handle.stat();if(!entry.isFile())throw transactionPreviewNonRegularFileError(path.relative(root,file));const contents=crypto.createHash("sha256");if(entry.size>0)for await(const chunk of handle.createReadStream({highWaterMark:64*1024,end:entry.size-1,autoClose:!1}))contents.update(chunk);return contents.digest()}finally{await handle.close()}}async function previewTrackerFingerprint(root,ownedPaths,retainedPaths){const fingerprint=crypto.createHash("sha256");async function visit(directory){for(const name of(await readdir(directory)).sort()){const file=path.join(directory,name);includePreviewPath(root,file,ownedPaths,retainedPaths)&&((await previewEntryStat(root,file)).isDirectory()?await visit(file):(fingerprint.update(JSON.stringify(path.relative(root,file))),fingerprint.update(await previewFileDigest(root,file))))}}return await visit(root),fingerprint.digest("hex")}function previewSnapshotChangedError(){return new PmCliError("Tracker changed while preparing the transaction preview; retry against stable state.",EXIT_CODE.CONFLICT,{code:"transaction_preview_snapshot_changed"})}async function isDisappearingPreviewPath(error){if(!isFileMissingError(error))return!1;const file=error.path;if(typeof file!="string")return!1;const original=path.resolve(file);let candidate=original;for(;;)try{const entry=await lstat(candidate);return candidate!==original&&entry.isDirectory()}catch(lookupError){if(!isFileMissingError(lookupError))return!1;const parent=path.dirname(candidate);if(parent===candidate)return!1;candidate=parent}}async function readPreviewConfiguration(root,relative){const file=path.join(root,relative);try{let current=root;for(const component of relative.split(path.sep).slice(0,-1))current=path.join(current,component),await previewEntryStat(root,current);if(!(await previewEntryStat(root,file)).isFile())throw transactionPreviewNonRegularFileError(relative);return await readRegularFile(file,transactionPreviewNonRegularFileError(relative))}catch(error){if(await isDisappearingPreviewPath(error))return;throw error}}async function stageGuardedSchemaSections(root,configurationRoot,schemaSettings,configuration){const schema=normalizeRuntimeSchemaSettings(schemaSettings);for(const[section,configuredPath]of Object.entries(schema.files)){const relative=path.relative(root,filePathForSchemaSection(root,configuredPath,DEFAULT_RUNTIME_SCHEMA_FILE_PATHS[section]));if(relative===""||!path.resolve(root,relative).startsWith(path.join(root,path.sep)))throw new PmCliError("Transaction preview requires schema files inside the selected tracker root; relocate the configured schema file before retrying.",EXIT_CODE.USAGE,{code:"transaction_preview_external_schema",field:`schema.files.${section}`});schema.files[section]=relative;const contents=await readPreviewConfiguration(root,relative);if(configuration?.set(relative,contents),contents!==void 0){const target=path.join(configurationRoot,relative);await mkdir(path.dirname(target),{recursive:!0}),await writeFile(target,contents)}}return loadRuntimeSchemaFromOptionalFiles(configurationRoot,schema)}async function loadGuardedRuntimeSchema(pmRoot,schemaSettings){await stat(pmRoot);const root=await mkdtemp(path.join(tmpdir(),"pm-schema-plan-"));try{const resolvedRoot=await realpath(pmRoot);return await stageGuardedSchemaSections(resolvedRoot,path.join(root,"configuration"),schemaSettings)}catch(error){throw await isDisappearingPreviewPath(error)?previewSnapshotChangedError():error}finally{await rm(root,{recursive:!0,force:!0})}}async function resolvePreviewStorage(root,configurationRoot,registrations){const configuration=new Map,rawSettings=await readPreviewConfiguration(root,SETTINGS_FILENAME);configuration.set(SETTINGS_FILENAME,rawSettings);let parsed;try{parsed=JSON.parse(rawSettings??"null")}catch{parsed=null}const validated=validateSettings(parsed),settings=validated.success?validated.data:void 0,loaded=await stageGuardedSchemaSections(root,configurationRoot,settings?.schema,configuration),schema=loaded.schema,sessionPath=path.relative(root,getSessionStatePath(root));configuration.set(sessionPath,await readPreviewConfiguration(root,sessionPath));const registry=resolveItemTypeRegistry({...SETTINGS_DEFAULTS,item_types:{definitions:[...settings?.item_types?.definitions??[],...loaded.type_definitions_from_file??[]]}},registrations),ownedPaths=resolveWorkspaceRoot(root)===root?[...PM_REQUIRED_SUBDIRS.filter(Boolean),SETTINGS_FILENAME,PM_CONTEXT_INTENTS_FILE,"transactions",...registry.folders,...configuration.keys()].map(entry=>path.normalize(entry)):void 0,stagedSettings=settings===void 0?void 0:JSON.stringify({...parsed,schema:{...settings.schema,files:schema.files}});return{configuration,ownedPaths,stagedSettings,registryFolders:registry.folders}}async function stagePreviewTracker(sourceRoot,stagedRoot,registrations){await stat(sourceRoot);try{const resolvedRoot=await realpath(sourceRoot),storage=await resolvePreviewStorage(resolvedRoot,path.join(path.dirname(stagedRoot),"configuration"),registrations),retainedPaths=[...storage.configuration.keys(),...storage.registryFolders].map(entry=>path.normalize(entry)),sourceFingerprint=await previewTrackerFingerprint(resolvedRoot,storage.ownedPaths,retainedPaths);await cp(resolvedRoot,stagedRoot,{recursive:!0,dereference:!1,filter:async source=>includePreviewPath(resolvedRoot,source,storage.ownedPaths,retainedPaths)?(await previewEntryStat(resolvedRoot,source),!0):!1});const[currentFingerprint,stagedFingerprint]=await Promise.all([previewTrackerFingerprint(resolvedRoot,storage.ownedPaths,retainedPaths),previewTrackerFingerprint(stagedRoot,storage.ownedPaths,retainedPaths)]);if(sourceFingerprint!==currentFingerprint||sourceFingerprint!==stagedFingerprint)throw previewSnapshotChangedError();for(const[relative,contents]of storage.configuration)if(await readPreviewConfiguration(stagedRoot,relative)!==contents)throw previewSnapshotChangedError();storage.stagedSettings!==void 0&&await writeFile(path.join(stagedRoot,SETTINGS_FILENAME),storage.stagedSettings)}catch(error){throw await isDisappearingPreviewPath(error)?previewSnapshotChangedError():error}}async function previewItemMutations(options){const identity=validateWorkspaceTransactionIdentity(options),mutations=snapshotBulkMutations(options.mutations),registrations=getActiveExtensionRegistrations(),guards=getActiveExtensionHooks(),root=await mkdtemp(path.join(tmpdir(),"pm-transaction-preview-")),stagedRoot=path.join(root,"tracker");try{await stagePreviewTracker(identity.pmRoot,stagedRoot,registrations);let validated=!1;const warnings=[],records=[],applied=new Set;return await runWithPreviewMutationGuards(guards,()=>runWithActiveExtensions({path:stagedRoot,noExtensions:!0},async()=>{setActiveExtensionRegistrations(registrations);const config={...identity,pmRoot:stagedRoot,createCompensation:"close",uniqueIndex:createUniqueKeyIndex(stagedRoot)},steps=mutations.map((mutation,index)=>{const step=buildStepForMutation({...config,onCreateWarnings:(id,messages)=>{messages.length>0&&warnings.push({index,id,op:"create",warnings:messages})}},mutation,index);return{...step,inspect:()=>validateMutationOperation(mutation,index,()=>step.inspect()),prepareCompensation:()=>validateMutationOperation(mutation,index,async()=>step.prepareCompensation?.()),apply:()=>validateMutationOperation(mutation,index,async()=>{const outcome=await step.apply();return applied.add(index),outcome})}});if(await commitWorkspaceTransaction({...identity,pmRoot:stagedRoot,steps,onTransition:({transition})=>{transition==="committed"&&(validated=!0)}}),validated)for(const[index,mutation]of mutations.entries()){const item=(await runGet(mutation.id,{path:stagedRoot},{full:!0})).item;records.push({index,id:String(item.id),op:mutation.op,execution:applied.has(index)?"applied":"adopted",item,commit_time_fields:previewClockFields(item)})}})),{records,validated,state:validated?"staged_snapshot":"replayed_committed_plan",warnings,unresolved_commit_constraints:["concurrent_tracker_changes","extension_write_hooks","derived_extension_dependencies_excluded","generated_timestamps_and_provenance"]}}finally{await rm(root,{recursive:!0,force:!0})}}async function commitItemMutations(options){const identity=validateWorkspaceTransactionIdentity(options),mutations=snapshotBulkMutations(options.mutations),createCompensation=options.createCompensation??"close";if(!["close","delete"].includes(createCompensation))throw new TypeError("Bulk item transaction createCompensation must be close or delete");const stepConfig={...identity,createCompensation,uniqueIndex:createUniqueKeyIndex(identity.pmRoot)},committed=await commitWorkspaceTransaction({...identity,steps:mutations.map((mutation,index)=>buildStepForMutation(stepConfig,mutation,index)),recoveryData:JSON.parse(JSON.stringify({kind:"item-mutations-v1",mutations,createCompensation})),...options.lockTtlSeconds===void 0?{}:{lockTtlSeconds:options.lockTtlSeconds},...options.lockWaitMs===void 0?{}:{lockWaitMs:options.lockWaitMs},...options.onTransition===void 0?{}:{onTransition:options.onTransition}}),results={};for(const[index,mutation]of mutations.entries()){const stepId=deriveStepId(mutation,index),value=committed.results[stepId];results[deriveOutcomeKey(mutation,index)]=value}return{transactionId:committed.transactionId,status:"committed",recovered:committed.recovered,results}}function buildItemCompletionMutations(options){const mutations=[];return options.evidence!==void 0&&Object.keys(options.evidence).length>0&&mutations.push({op:"update",id:options.id,options:options.evidence}),mutations.push({op:"close",id:options.id,reason:options.reason,...options.closeOptions===void 0?{}:{options:options.closeOptions}},{op:"release",id:options.id,...options.releaseOptions===void 0?{}:{options:options.releaseOptions}}),mutations}function commitItemCompletion(options){return commitItemMutations({pmRoot:options.pmRoot,transactionId:options.transactionId,author:options.author,mutations:buildItemCompletionMutations(options),...options.lockTtlSeconds===void 0?{}:{lockTtlSeconds:options.lockTtlSeconds},...options.lockWaitMs===void 0?{}:{lockWaitMs:options.lockWaitMs},...options.onTransition===void 0?{}:{onTransition:options.onTransition}})}const _testOnlyItemTransaction={buildCreateStep,bulkHistoryMarker,compensateByRestore,deriveStepId,isUpdateMarkerApplied,readItemSnapshot};async function readItemTransaction(pmRoot,transactionId){const journal=await readWorkspaceTransaction(pmRoot,transactionId);return journal===void 0?void 0:{journal,planDigest:workspaceTransactionPlanDigest(journal)}}function recoveryItemSteps(options,journal){const data=journal.recoveryData;if(data===null||typeof data!="object"||Array.isArray(data)||data.kind!=="item-mutations-v1"||!Array.isArray(data.mutations)||!["close","delete"].includes(String(data.createCompensation)))throw new PmCliError("Transaction has no supported item recovery plan",EXIT_CODE.CONFLICT,{code:"transaction_recovery_plan_missing",required:"Resume with the original plan and its original adapter.",why:"Legacy or foreign journals cannot safely reconstruct item compensation."});const mutations=data.mutations;assertValidBulkMutations(mutations);const config={...options,createCompensation:data.createCompensation,uniqueIndex:createUniqueKeyIndex(options.pmRoot)};return mutations.map((mutation,index)=>buildStepForMutation(config,mutation,index))}async function abandonItemTransaction(options){const identity=validateWorkspaceTransactionIdentity(options),journal=await abandonWorkspaceTransaction({...options,...identity,resolveSteps:receipt=>recoveryItemSteps({...options,...identity},receipt)});return{journal,planDigest:workspaceTransactionPlanDigest(journal)}}export{_testOnlyItemTransaction,abandonItemTransaction,buildItemCompletionMutations,commitItemCompletion,commitItemMutations,listUpsertKeyCandidates,loadGuardedRuntimeSchema,previewItemMutations,readItemTransaction,resolveTransactionSchema};
|
|
2
2
|
//# sourceMappingURL=item-transaction.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="051d143c-fcb1-585e-ac86-55642a88b4dc")}catch{}})();import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{removeFileIfExists,writeFileAtomic,appendHistoryEntry,createHistoryEntry,generateItemId,canonicalDocument,serializeItemDocument,acquireLockLease,getActiveExtensionRegistrations,projectAfterCommandItemSnapshot,recordAfterCommandAffectedItem,runActiveOnWriteHooks,runActiveBeforeMutationHooks,createMutationGuardSdk,collectRegisteredItemFieldNames,resolveRuntimeStatusRegistry,EXIT_CODE,ITEM_METADATA_KEY_ORDER,nowIso,PmCliError,resolveItemTypeRegistry,buildItemNotFoundError,locateItem,readLocatedItem,getHistoryPath,getItemPath,resolvePmRoot,readSettings,resolveAuthor}from"../runtime-primitives.js";import{evaluateSimilarityGovernance,similarityAdvisoryWarnings}from"../similarity.js";import{acquireItemMetadataDerivedIndexLock,refreshItemMetadataDerivedIndex}from"../item-metadata-index.js";import{enforceWorkflowMutation}from"../../core/policy/workflow-policy-store.js";function buildChangedFields(itemMetadata,body){return[...new Set([...ITEM_METADATA_KEY_ORDER.filter(key=>itemMetadata[key]!==void 0),...Object.keys(itemMetadata).filter(key=>itemMetadata[key]!==void 0),...body.length>0?["body"]:[]])].sort((left,right)=>left.localeCompare(right))}function buildCopyMessage(sourceId,message){const suffix=`copied_from=${sourceId}`;if(!message)return suffix;const trimmed=message.trim();return trimmed.length>0?`${trimmed} | ${suffix}`:suffix}async function runCopy(sourceId,options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot),typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()),located=await locateItem(pmRoot,sourceId,settings.id_prefix,settings.item_format,typeRegistry.type_to_folder);if(!located)throw await buildItemNotFoundError(pmRoot,sourceId,settings.id_prefix,typeRegistry.type_to_folder);const sourceLoaded=await readLocatedItem(located,{schema:settings.schema}),sourceMetadata=sourceLoaded.document.metadata,copiedAt=nowIso(),author=resolveAuthor(options.author,settings.author_default),newId=await generateItemId(pmRoot,settings.id_prefix,{tokenLength:settings.ids.token_length,typeToFolder:typeRegistry.type_to_folder,probeExisting:!1}),statusRegistry=resolveRuntimeStatusRegistry(settings.schema),titleOverride=options.title?.trim();if(titleOverride!==void 0&&titleOverride.length===0)throw new PmCliError("Copy --title must not be empty",EXIT_CODE.USAGE);const copiedMetadata={...sourceMetadata,id:newId,title:titleOverride??sourceMetadata.title,status:statusRegistry.open_status,created_at:copiedAt,updated_at:copiedAt};delete copiedMetadata.closed_at,delete copiedMetadata.completed_at,delete copiedMetadata.close_reason,delete copiedMetadata.test_runs;const extensionFieldNames=collectRegisteredItemFieldNames(getActiveExtensionRegistrations()),copiedDocument=canonicalDocument({metadata:copiedMetadata,body:sourceLoaded.document.body},{schema:settings.schema,extensionFieldNames}),similarityAdvisory=await evaluateSimilarityGovernance({title:copiedDocument.metadata.title,description:copiedDocument.metadata.description,body:copiedDocument.body,excludeIds:[located.id]},{pmRoot,mode:settings.governance.duplicate_detection_mode==="strict"&&options.allowDuplicate!==!0?"off":settings.governance.duplicate_detection_mode,threshold:settings.governance.duplicate_detection_threshold,limit:settings.governance.duplicate_detection_limit,allowDuplicate:options.allowDuplicate}),changedFields=buildChangedFields(copiedDocument.metadata,copiedDocument.body),itemPath=getItemPath(pmRoot,copiedDocument.metadata.type,newId,settings.item_format,typeRegistry.type_to_folder),historyPath=getHistoryPath(pmRoot,newId),lease=await acquireLockLease(pmRoot,newId,settings.locks.ttl_seconds,author,!1,settings.governance.force_required_for_stale_lock,settings.locks.wait_ms),beforeDocument={metadata:{},body:""};let hookWarnings,derivedIndexWarnings,workflowWarnings;try{const releaseDerivedIndexLock=await acquireItemMetadataDerivedIndexLock(pmRoot,author,{required:settings.governance.duplicate_detection_mode==="strict"&&options.allowDuplicate!==!0});try{settings.governance.duplicate_detection_mode==="strict"&&options.allowDuplicate!==!0&&await evaluateSimilarityGovernance({title:copiedDocument.metadata.title,description:copiedDocument.metadata.description,body:copiedDocument.body,excludeIds:[located.id]},{pmRoot,mode:"strict",threshold:settings.governance.duplicate_detection_threshold,limit:settings.governance.duplicate_detection_limit,allowDuplicate:!1});const collision=await locateItem(pmRoot,newId,settings.id_prefix,settings.item_format,typeRegistry.type_to_folder);if(collision)throw new PmCliError(`Cannot copy to ${newId}: an item with that id already exists at ${collision.itemPath}. Retry the copy to allocate a new id.`,EXIT_CODE.CONFLICT,{code:"item_id_collision",why:`Allocated id ${newId} already exists at ${collision.itemPath}.`,recovery:{suggested_retry:`pm copy ${located.id}`}});const workflowPolicy=await enforceWorkflowMutation({pmRoot,settings,operation:"create",author,before:null,after:copiedDocument});workflowWarnings=workflowPolicy.warnings,await runActiveBeforeMutationHooks({pm_root:pmRoot,operation:"create",before:null,after:copiedDocument,changed_fields:changedFields,author,sdk:createMutationGuardSdk({pmRoot,settings,typeToFolder:typeRegistry.type_to_folder})}),await lease.fence(async()=>{await writeFileAtomic(itemPath,serializeItemDocument(copiedDocument,{format:settings.item_format,schema:settings.schema,extensionFieldNames}));try{const historyEntry=createHistoryEntry({nowIso:copiedAt,author,op:"create",before:beforeDocument,after:copiedDocument,message:buildCopyMessage(located.id,options.message),context:workflowPolicy.decisions.length===0?void 0:{workflow_policies:workflowPolicy.decisions}});await appendHistoryEntry(historyPath,historyEntry)}catch(error){throw await removeFileIfExists(itemPath),error}}),derivedIndexWarnings=await refreshItemMetadataDerivedIndex({pmRoot,preferredFormat:settings.item_format,typeToFolder:typeRegistry.type_to_folder,schema:settings.schema,itemPath,document:copiedDocument})}finally{await releaseDerivedIndexLock()}hookWarnings=[...await runActiveOnWriteHooks({path:itemPath,scope:"project",op:"create",item_id:copiedDocument.metadata.id,item_type:copiedDocument.metadata.type,before:beforeDocument,after:copiedDocument,changed_fields:changedFields}),...await runActiveOnWriteHooks({path:historyPath,scope:"project",op:"create:history",item_id:copiedDocument.metadata.id,item_type:copiedDocument.metadata.type,before:beforeDocument,after:copiedDocument,changed_fields:changedFields})],recordAfterCommandAffectedItem({id:copiedDocument.metadata.id,op:"create",item_type:copiedDocument.metadata.type,status:copiedDocument.metadata.status,current:projectAfterCommandItemSnapshot(copiedDocument.metadata,changedFields),changed_fields:changedFields})}finally{await lease.release()}return{source_id:located.id,item:structuredClone(copiedDocument.metadata),changed_fields:changedFields,warnings:[...similarityAdvisoryWarnings(similarityAdvisory),...workflowWarnings,...derivedIndexWarnings,...hookWarnings],...similarityAdvisory===void 0?{}:{similarity_advisory:similarityAdvisory}}}export{runCopy};
|
|
2
2
|
//# sourceMappingURL=copy.js.map
|