@unbrained/pm-cli 2026.11.11 → 2026.11.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.agents/skills/pm-test-audit/SKILL.md +2 -1
- package/.agents/skills/pm-user/references/ECOSYSTEM_PLANNING.md +2 -1
- package/.claude-plugin/marketplace.json +1 -1
- package/AGENTS.md +2 -2
- package/CHANGELOG.md +30 -0
- package/CONTRIBUTING.md +1 -1
- package/README.md +1 -1
- package/dist/cli/register-mutation.js +2 -2
- package/dist/cli/register-operations.js +1 -1
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/{chunk-DIWTFDU7.js → chunk-36E4L2R4.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-ZJDYBXMC.js → chunk-4WD4CHVH.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-QCTA2UFR.js → chunk-5LG5YZYF.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-DV7WBAKQ.js → chunk-6UXBWMEM.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-ZSL6U53K.js → chunk-CO7RWLCM.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-COTC2QOR.js +6 -0
- package/dist/cli-bundle/chunks/{chunk-XJUYJXHZ.js → chunk-FAYX6C7H.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-GIAJX2QJ.js +9 -0
- package/dist/cli-bundle/chunks/{chunk-EBAHNZJT.js → chunk-GWVP23RZ.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-GOLQYO6M.js → chunk-GXGMMIZN.js} +47 -43
- package/dist/cli-bundle/chunks/{chunk-PZI6CR24.js → chunk-HQINCDF6.js} +47 -47
- package/dist/cli-bundle/chunks/{chunk-JESMEJTD.js → chunk-IYDIPXBO.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-SPERPX27.js → chunk-L4F4ZHGR.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-4RHXGQMK.js → chunk-LKVFPQNY.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-Z4YEH7VQ.js → chunk-O6PBQMD7.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-NIOOJ3AG.js → chunk-O6T24Z3M.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-L3SA3354.js → chunk-OQCVU2SG.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-FM375BHH.js → chunk-PUU5DXSV.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-QSSENTXG.js +20 -0
- package/dist/cli-bundle/chunks/chunk-TCYIGAQG.js +31 -0
- package/dist/cli-bundle/chunks/chunk-UFZQPKQS.js +124 -0
- package/dist/cli-bundle/chunks/{chunk-WEAF3OY4.js → chunk-URWNUZQZ.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-5N3JMGXU.js → chunk-UYARS5XF.js} +2 -2
- package/dist/cli-bundle/chunks/{item-revision-LNIHK36Q.js → item-revision-G5OVYGZ5.js} +2 -2
- package/dist/cli-bundle/chunks/item-transaction-I2X2P4TW.js +2 -0
- package/dist/cli-bundle/chunks/{mutation-admission-WZY22LVH.js → mutation-admission-SET4KY73.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-DYGPLVRL.js → register-list-query-JNJY2D3N.js} +2 -2
- package/dist/cli-bundle/chunks/register-mutation-WTHZHPOP.js +20 -0
- package/dist/cli-bundle/chunks/register-operations-EZP3EG6A.js +2 -0
- package/dist/cli-bundle/chunks/{register-setup-G66U2WFV.js → register-setup-THFZP23A.js} +2 -2
- package/dist/cli-bundle/chunks/{stage-VIDXGF3T.js → stage-JXJILTYE.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-2ZPGEGTB.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-NSOXVVQX.js → chunk-3MB47JLT.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-M5FZTPFA.js → chunk-4LFE3FQL.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-5KTOMFLR.js +44 -0
- package/dist/cli-bundle/focused-chunks/{chunk-MK7UQEE5.js → chunk-5NTLNE54.js} +18 -18
- package/dist/cli-bundle/focused-chunks/{chunk-P6KYUJD4.js → chunk-ADBFVDTG.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-AXPRCCYM.js → chunk-CSKDIMQP.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-FNIX62V6.js +3 -0
- package/dist/cli-bundle/focused-chunks/{chunk-3A6XMQZJ.js → chunk-IYV3IPRF.js} +53 -53
- package/dist/cli-bundle/focused-chunks/chunk-J3LQQP3N.js +26 -0
- package/dist/cli-bundle/focused-chunks/{chunk-JYWVRXLD.js → chunk-JR75B6HU.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-NP5C2TQM.js → chunk-Q3OA5OAK.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-QGQJBQCH.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-VVGXPF4W.js → chunk-RIMNSVFA.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-GBW2EAAG.js → chunk-TVJ2PHAK.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-3SH3L3DB.js → chunk-VGFKTSGY.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-VGJDKDKA.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-VGUQ4V47.js +82 -0
- package/dist/cli-bundle/focused-chunks/chunk-VTOTZ5UC.js +91 -0
- package/dist/cli-bundle/focused-chunks/{chunk-NMU3QFAU.js → chunk-WFVZ7GGR.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-3FN4ON2Z.js → chunk-ZJF6ZA7B.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-ZOGEQFGH.js +2 -0
- package/dist/cli-bundle/focused-chunks/{item-revision-B3BIG66B.js → item-revision-IF7E7BVY.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{item-transaction-4JDWOXNB.js → item-transaction-5TFWIOXI.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{mutation-admission-577MXOGD.js → mutation-admission-KELM46JF.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{stage-EKYWEU2Y.js → stage-UAKMQTCI.js} +2 -2
- package/dist/cli-bundle/main.js +2 -2
- 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 +12 -12
- package/dist/core/history/history-rewrite.js +1 -1
- package/dist/core/item/parse.d.ts +13 -1
- package/dist/core/item/parse.js +4 -4
- package/dist/core/schema/runtime-field-values.js +1 -1
- package/dist/core/shared/author.js +2 -2
- package/dist/core/shared/secret-rules.d.ts +8 -2
- package/dist/core/shared/secret-rules.js +3 -3
- package/dist/core/shared/url-credentials.d.ts +33 -5
- package/dist/core/shared/url-credentials.js +1 -1
- package/dist/core/store/item-store.js +1 -1
- package/dist/sdk/agent/command-recovery.js +1 -1
- package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1
- package/dist/sdk/cli-contracts/completeness.js +1 -1
- package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
- package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
- package/dist/sdk/cli-contracts/tool-schema.d.ts +1 -1
- package/dist/sdk/cli-contracts/tool-schema.js +1 -1
- package/dist/sdk/completion/bash.js +1 -1
- package/dist/sdk/completion/fish.js +3 -1
- package/dist/sdk/completion/zsh.js +3 -1
- package/dist/sdk/docs.d.ts +14 -2
- package/dist/sdk/docs.js +1 -1
- package/dist/sdk/files.d.ts +14 -2
- package/dist/sdk/files.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
- package/dist/sdk/governance/boundary-fixtures.d.ts +25 -0
- package/dist/sdk/governance/boundary-fixtures.js +1 -1
- package/dist/sdk/governance/defect-recurrence.d.ts +8 -1
- package/dist/sdk/governance/defect-recurrence.js +2 -2
- package/dist/sdk/guide-topics.js +1 -1
- package/dist/sdk/index.d.ts +1 -1
- package/dist/sdk/index.js +1 -1
- package/dist/sdk/lifecycle/claim.js +1 -1
- package/dist/sdk/lifecycle/create.js +1 -1
- package/dist/sdk/lifecycle/dependency-removal.js +2 -0
- package/dist/sdk/lifecycle/restore.js +1 -1
- package/dist/sdk/lifecycle/start-blockers.d.ts +9 -0
- package/dist/sdk/lifecycle/start-blockers.js +1 -1
- package/dist/sdk/lifecycle/update.d.ts +10 -4
- package/dist/sdk/lifecycle/update.js +2 -2
- package/dist/sdk/linked-artifacts.d.ts +73 -3
- package/dist/sdk/linked-artifacts.js +2 -2
- package/dist/sdk/ownership-source.js +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/runtime/actions.js +1 -1
- package/dist/sdk/test/command-args.js +1 -1
- package/dist/sdk/test/execution.d.ts +15 -3
- package/dist/sdk/test/execution.js +2 -2
- package/docs/AGENT_GUIDE.md +2 -2
- package/docs/AGENT_UX_CONTRACTS.md +7 -1
- package/docs/BUILD_AND_RELEASE_ACCEPTANCE.md +1 -1
- package/docs/COMMANDS.md +16 -9
- package/docs/CORPUS_SHAPES.md +1 -1
- package/docs/DEFECT_RECURRENCE.md +20 -1
- package/docs/MUTATION_INTEGRITY.md +56 -6
- package/docs/ONBOARDING.md +1 -1
- package/docs/README.md +6 -6
- package/docs/SDK.md +30 -0
- package/docs/SDK_CONTEXT_INTEGRITY.md +2 -0
- package/docs/TESTING.md +1 -1
- package/docs/generated/FLAG_LEXICON_BUDGETS.md +6 -6
- package/marketplace.json +1 -1
- package/package.json +8 -1
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-claude/package.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/plugins/pm-codex/package.json +1 -1
- package/plugins/pm-codex/plugin.json +1 -1
- package/runtime-dependencies.json +1 -1
- package/dist/cli-bundle/chunks/chunk-GZ52WAY2.js +0 -124
- package/dist/cli-bundle/chunks/chunk-JLQ7O6UV.js +0 -20
- package/dist/cli-bundle/chunks/chunk-SVVFJPNW.js +0 -9
- package/dist/cli-bundle/chunks/chunk-WWW5WHHJ.js +0 -31
- package/dist/cli-bundle/chunks/chunk-XN2BRWDD.js +0 -6
- package/dist/cli-bundle/chunks/item-transaction-TMUYPSMR.js +0 -2
- package/dist/cli-bundle/chunks/register-mutation-MP5JCBAJ.js +0 -20
- package/dist/cli-bundle/chunks/register-operations-QEASK3EF.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-2ZS3I5ZP.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-33EK522E.js +0 -26
- package/dist/cli-bundle/focused-chunks/chunk-6ICHSVEY.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-6TJXTKZD.js +0 -44
- package/dist/cli-bundle/focused-chunks/chunk-DW5S67LO.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-HIKZYZ26.js +0 -82
- package/dist/cli-bundle/focused-chunks/chunk-NY65XTX7.js +0 -91
- package/dist/cli-bundle/focused-chunks/chunk-UCUESVFW.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-V27M5UQH.js +0 -3
- package/docs/CONTEXT_ALGORITHM_PORTFOLIO.md +0 -167
- package/docs/DEVELOPMENT_DEPENDENCY_SECURITY.md +0 -246
- package/docs/PR_REVIEW_LOOP.md +0 -96
- package/docs/RELEASE_LEDGER_RECONCILIATION.md +0 -148
- package/docs/RELEASE_RELIABILITY.md +0 -147
- package/docs/RELEASING.md +0 -805
- package/docs/performance/corpus-shape-comparison.json +0 -1
- package/docs/performance/latest-scale-report.json +0 -1
- package/docs/performance/scale-100k-report.json +0 -1
|
@@ -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]="99e0fe28-8c78-52d7-8cec-11ed8079bc7c")}catch{}})();import{projectMutationResult}from"../../core/output/mutation-projection.js";import{withQuerySummary}from"../../core/output/query-summary.js";import{PmCliError}from"../../core/shared/errors.js";import{resolvePmRoot}from"../../core/store/paths.js";import{createUnknownSubcommandError}from"../agent/subcommand-recovery.js";import{normalizeAnnotationTransportOptions}from"../annotations.js";import{acknowledgeUnknownAuthorHistoryEventsFromTransport}from"../author-attribution.js";import{runContracts}from"../cli-contracts/runtime-contracts.js";import{runComments}from"../comments.js";import{runConfig}from"../config.js";import{applyContextIntentProjection}from"../context-intent-contracts.js";import{runDeps}from"../dependencies.js";import{runDocs}from"../docs.js";import{runDuplicates}from"../duplicates.js";import{runExtension}from"../extension.js";import{runFiles,runFilesDiscover,runFilesLookup}from"../files.js";import{runAssuranceDispatch}from"../governance/assurance-action.js";import{runGc}from"../governance/gc.js";import{runHealth}from"../governance/health.js";import{runUpgrade}from"../governance/upgrade.js";import{runValidate}from"../governance/validate.js";import{runGraph}from"../graph/run.js";import{runMcpHistoryCompactAction,runMcpHistoryRepairAction}from"../history-mcp.js";import{runHistoryRedact}from"../history-redact.js";import{runHistoryAttest}from"../history/attestation-command.js";import{runInit}from"../init.js";import{runLearnings}from"../learnings.js";import{runAppend}from"../lifecycle/append.js";import{runCloseMany}from"../lifecycle/close-many.js";import{runCopy}from"../lifecycle/copy.js";import{runCreate}from"../lifecycle/create.js";import{runDelete}from"../lifecycle/delete.js";import{runFocus}from"../lifecycle/focus.js";import{runMcpClaimAction,runMcpCloseAction,runMcpReleaseAction,runMcpReopenAction,runMcpTaskCompositionAction}from"../lifecycle/mcp-actions.js";import{runPlan}from"../lifecycle/plan.js";import{runRestore}from"../lifecycle/restore.js";import{buildPlanMutationReceipt}from"../lifecycle/plan-mutation-receipt.js";import{runUpdateMany}from"../lifecycle/update-many.js";import{runUpdate}from"../lifecycle/update.js";import{runNotes}from"../notes.js";import{PROFILE_SUBCOMMANDS,runProfileApply,runProfileLint,runProfileList,runProfileShow}from"../profile.js";import{normalizeActivityProjectionOptions,runActivity}from"../query/activity.js";import{runAggregate}from"../query/aggregate.js";import{runContext}from"../query/context.js";import{runGet}from"../query/get.js";import{runHistory}from"../query/history.js";import{runList}from"../query/list.js";import{runNext}from"../query/next.js";import{runSearch}from"../query/search.js";import{runRuntimeEvalAction,runRuntimeEventsAction,runRuntimeMergeAction,runRuntimeSchedulingAction,runRuntimeWorkspaceAction}from"../runtime-extended-actions.js";import{closeManyOptionsFromFlat,graphOptionsFromFlat,isMcpMutationTransportInput,parseRuntimeInteger as parseMcpInteger,readRuntimeString as readString,readRuntimeStringArray as readStringArray,resolveRuntimeLimit,updateManyOptionsFromFlat,withAddNoteOption,withFilesDiscoveryOptions,withMutationCompaction}from"../runtime-input.js";import{statsCommandOptionsFromRuntime}from"../runtime-stats-options.js";import{runStats}from"../stats.js";import{runTelemetry}from"../telemetry.js";import{runTestAll}from"../test/batch.js";import{runTest}from"../test/execution.js";import{runtimeFilesLookupOptions}from"../traceability/runtime-files-lookup.js";import{getOwnHandler,readRequiredString}from"./context.js";import{runMcpSchemaAction}from"./schema.js";import{defaultConfigScope}from"../../core/config/positional-value.js";function readMcpTarget(ctx){return readString(ctx.args,"target")??readString(ctx.options,"target")}function requireMcpItemId(ctx,source=ctx.options){return ctx.id??readRequiredString(source,"id")}async function runMcpListAction(ctx){const listOptions=applyContextIntentProjection("list",ctx.options);return listOptions.compact===void 0&&listOptions.brief===void 0&&listOptions.full===void 0&&listOptions.fields===void 0&&listOptions.includeBody===void 0&&(listOptions.compact=!0),withQuerySummary(await runList(readString(ctx.args,"status")??readString(listOptions,"status"),listOptions,ctx.global),listOptions)}async function runMcpSearchAction(ctx){const query=readString(ctx.args,"query")??readString(ctx.args,"keywords")??readRequiredString(ctx.args,"query"),searchOptions=applyContextIntentProjection("search",ctx.options,[query]);return searchOptions.compact===void 0&&searchOptions.full===void 0&&searchOptions.fields===void 0&&(searchOptions.compact=!0),withQuerySummary(await runSearch(query,searchOptions,ctx.global),searchOptions)}async function runMcpCreateAction(ctx){const{changedFields,idOnly,runnerOptions}=withMutationCompaction(ctx.args,ctx.options);return projectMutationResult(await runCreate(runnerOptions,ctx.global),{changedFields,compactEnvelope:changedFields==="compact"&&!idOnly,idOnly})}async function runMcpCopyAction(ctx){const{changedFields,idOnly,runnerOptions}=withMutationCompaction(ctx.args,ctx.options),copyOptions={...runnerOptions,...runnerOptions.title===void 0&&typeof ctx.args.title=="string"?{title:ctx.args.title}:{},...runnerOptions.message===void 0&&typeof ctx.args.message=="string"?{message:ctx.args.message}:{}};return projectMutationResult(await runCopy(requireMcpItemId(ctx,copyOptions),copyOptions,ctx.global),{changedFields,compactEnvelope:changedFields==="compact"&&!idOnly,idOnly})}async function runMcpUpdateAction(ctx){const{changedFields,idOnly,runnerOptions}=withMutationCompaction(ctx.args,ctx.options);return projectMutationResult(await runUpdate(requireMcpItemId(ctx,runnerOptions),runnerOptions,ctx.global),{changedFields,compactEnvelope:changedFields==="compact"&&!idOnly,idOnly})}function runMcpCommentsAction(ctx){const commentOptions=normalizeAnnotationTransportOptions(ctx.options);return commentOptions.add===void 0&&commentOptions.stdin===void 0&&commentOptions.file===void 0&&commentOptions.edit===void 0&&commentOptions.delete===void 0&&(commentOptions.includeMeta=!0),runComments(requireMcpItemId(ctx),commentOptions,ctx.global)}function runMcpFilesLookupAction(ctx,paths){return runFilesLookup(runtimeFilesLookupOptions(ctx.options,paths,parseMcpInteger),ctx.global)}function runMcpFilesAction(ctx){const lookupPaths=readStringArray(ctx.options.lookupPath);if(lookupPaths&&lookupPaths.length>0)return runMcpFilesLookupAction(ctx,lookupPaths);const fileId=requireMcpItemId(ctx);return ctx.options.discover===!0?runFilesDiscover(fileId,withFilesDiscoveryOptions(ctx.options),ctx.global):runFiles(fileId,withAddNoteOption(ctx.options),ctx.global)}function runMcpTelemetryAction(ctx){return runTelemetry({subcommand:readString(ctx.args,"subcommand")??readString(ctx.options,"subcommand"),limit:resolveRuntimeLimit(ctx.args,ctx.options)},ctx.global)}function runMcpHealthAction(ctx){const healthOptions={...ctx.options};return healthOptions.brief===void 0&&healthOptions.summary===void 0&&healthOptions.full===void 0&&(healthOptions.summary=!0),runHealth(ctx.global,healthOptions)}function runMcpConfigAction(ctx){const configAction=readString(ctx.args,"configAction")??readString(ctx.options,"configAction")??readString(ctx.options,"action");if(configAction===void 0)throw new PmCliError("Missing required argument: configAction",64);const value=readString(ctx.args,"value")??readString(ctx.options,"value"),options=readString(ctx.options,"policy")!==void 0&&value!==void 0?{...ctx.options,value}:ctx.options,key=readString(ctx.args,"key")??readString(ctx.options,"key");return runConfig(readString(ctx.args,"scope")??readString(ctx.options,"scope")??defaultConfigScope(key),configAction,key,options,ctx.global,readString(ctx.options,"policy")===void 0?value:void 0)}function runMcpActivityAction(ctx){const options=ctx.options;return runActivity(normalizeActivityProjectionOptions(options),ctx.global)}function parseMcpIntegerPrefix(value,label){if(typeof value=="number"){if(!Number.isFinite(value)||!Number.isInteger(value))throw new PmCliError(`${label} must be a finite integer.`,64);return value}if(typeof value=="string"&&value.trim().length>0){const trimmed=value.trim();if(!/^[+-]?\d+(?:st|nd|rd|th)?$/i.test(trimmed))throw new PmCliError(`${label} must be a finite integer.`,64);const parsed=Number.parseInt(trimmed,10);if(!Number.isInteger(parsed))throw new PmCliError(`${label} must be a finite integer.`,64);return parsed}}async function runMcpPlanAction(ctx){const subcommand=readString(ctx.args,"subcommand")??readRequiredString(ctx.options,"subcommand"),planRecord=ctx.options,{changedFields,idOnly}=withMutationCompaction(ctx.args,ctx.options),result=await runPlan({subcommand,id:typeof ctx.id=="string"?ctx.id:typeof planRecord.id=="string"?planRecord.id:void 0,stepRef:readMcpPlanStepRef(ctx),reorderTo:parseMcpIntegerPrefix(planRecord.reorderTo??ctx.args.reorderTo,"plan reorderTo"),options:ctx.options,global:ctx.global});return subcommand!=="show"&&isMcpMutationTransportInput(ctx.args)&&(result.mutation_receipt=buildPlanMutationReceipt(result,void 0)),subcommand==="show"?result:projectMutationResult(result,{changedFields,idOnly,compactEnvelope:changedFields==="compact"&&!idOnly})}function readMcpPlanStepRef(ctx){return typeof ctx.options.stepRef=="string"?ctx.options.stepRef:typeof ctx.args.stepRef=="string"?ctx.args.stepRef:void 0}function runMcpProfileAction(ctx){const subcommand=readString(ctx.args,"subcommand")??readRequiredString(ctx.options,"subcommand"),normalizedSubcommand=subcommand.trim().toLowerCase(),profileName=readString(ctx.args,"name")??readString(ctx.options,"name"),handler=getOwnHandler({list:()=>runProfileList(),show:()=>runProfileShow(profileName),lint:()=>runProfileLint(profileName),apply:()=>runProfileApply(profileName,{dryRun:ctx.args.dryRun===!0||ctx.options.dryRun===!0,author:readString(ctx.args,"author")??readString(ctx.options,"author"),force:ctx.args.force===!0||ctx.options.force===!0},ctx.global)},normalizedSubcommand);if(!handler)throw createUnknownSubcommandError({command_path:"profile",token:subcommand,allowed:PROFILE_SUBCOMMANDS,exit_code:64});return handler()}async function runMcpAppendAction(ctx){const{changedFields,idOnly,runnerOptions}=withMutationCompaction(ctx.args,ctx.options);return projectMutationResult(await runAppend(requireMcpItemId(ctx,runnerOptions),runnerOptions,ctx.global),{changedFields,compactEnvelope:changedFields==="compact"&&!idOnly,idOnly})}async function runMcpUpdateManyAction(ctx){const{changedFields,runnerOptions}=withMutationCompaction(ctx.args,ctx.options);return projectMutationResult(await runUpdateMany(updateManyOptionsFromFlat(runnerOptions),ctx.global),{changedFields})}async function runMcpCloseManyAction(ctx){const{changedFields,runnerOptions}=withMutationCompaction(ctx.args,ctx.options),topLevelReason=readString(ctx.args,"reason"),closeManyRunnerOptions=topLevelReason!==void 0&&runnerOptions.reason===void 0?{...runnerOptions,reason:topLevelReason}:{...runnerOptions};return ctx.force&&closeManyRunnerOptions.force===void 0&&(closeManyRunnerOptions.force=!0),projectMutationResult(await runCloseMany(closeManyOptionsFromFlat(closeManyRunnerOptions),ctx.global),{changedFields})}async function runMcpRestoreAction(ctx){const{changedFields,idOnly,runnerOptions}=withMutationCompaction(ctx.args,ctx.options),target=readString(runnerOptions,"target")??readRequiredString(ctx.args,"target");return projectMutationResult(await runRestore(requireMcpItemId(ctx,runnerOptions),target,runnerOptions,ctx.global),{changedFields,compactEnvelope:changedFields==="compact"&&!idOnly,idOnly})}function runMcpGraphAction(ctx){const merged={...ctx.args,...ctx.options};return runGraph(readRequiredString(merged,"subcommand"),readString(merged,"id")??ctx.id,readString(merged,"target"),graphOptionsFromFlat(merged),ctx.global)}function runMcpHistoryAuthorAcknowledgeAction(ctx){return acknowledgeUnknownAuthorHistoryEventsFromTransport(resolvePmRoot(process.cwd(),ctx.global.path),{...ctx.args,...ctx.options})}const SDK_ACTION_HANDLERS={init:ctx=>runInit(readString(ctx.args,"prefix"),ctx.global,ctx.options),context:ctx=>runContext(applyContextIntentProjection("context",ctx.options),ctx.global),next:ctx=>runNext(applyContextIntentProjection("next",ctx.options),ctx.global),eval:runRuntimeEvalAction,events:runRuntimeEventsAction,merge:runRuntimeMergeAction,workspace:runRuntimeWorkspaceAction,meet:runRuntimeSchedulingAction,event:runRuntimeSchedulingAction,remind:runRuntimeSchedulingAction,list:runMcpListAction,get:ctx=>{const id=requireMcpItemId(ctx);return runGet(id,ctx.global,applyContextIntentProjection("get",ctx.options,[id]))},search:runMcpSearchAction,duplicates:ctx=>{const status=typeof ctx.options.status=="string"?[ctx.options.status]:readStringArray(ctx.options.status);return runDuplicates(ctx.global,{exhaustive:ctx.options.exhaustive===!0,...status.length===0?{}:{status},since:readString(ctx.options,"since"),threshold:typeof ctx.options.threshold=="number"?ctx.options.threshold:void 0,limit:ctx.options.limit==="default"?void 0:parseMcpInteger(ctx.options.limit,"limit")})},create:runMcpCreateAction,copy:runMcpCopyAction,focus:ctx=>runFocus(ctx.id,{clear:ctx.options.clear===!0||ctx.args.clear===!0},ctx.global),update:runMcpUpdateAction,"item-reopen":runMcpReopenAction,restore:runMcpRestoreAction,claim:runMcpClaimAction,release:runMcpReleaseAction,"start-task":ctx=>runMcpTaskCompositionAction(ctx,"start_task"),"pause-task":ctx=>runMcpTaskCompositionAction(ctx,"pause_task"),"close-task":ctx=>runMcpTaskCompositionAction(ctx,"close_task"),close:runMcpCloseAction,comments:runMcpCommentsAction,notes:ctx=>runNotes(requireMcpItemId(ctx),normalizeAnnotationTransportOptions(ctx.options),ctx.global),learnings:ctx=>runLearnings(requireMcpItemId(ctx),normalizeAnnotationTransportOptions(ctx.options),ctx.global),files:runMcpFilesAction,docs:ctx=>runDocs(requireMcpItemId(ctx),withAddNoteOption(ctx.options),ctx.global),test:ctx=>runTest(requireMcpItemId(ctx),ctx.options,ctx.global),"test-all":ctx=>runTestAll(ctx.options,ctx.global),telemetry:runMcpTelemetryAction,validate:ctx=>runValidate(ctx.options,ctx.global,{runUpdate:(id,options,global2)=>runUpdate(id,options,global2)}),health:runMcpHealthAction,assurance:ctx=>runAssuranceDispatch(ctx.args,ctx.options,ctx.global),contracts:ctx=>runContracts(ctx.options,ctx.global),config:runMcpConfigAction,activity:runMcpActivityAction,aggregate:ctx=>runAggregate(ctx.options,ctx.global),extension:ctx=>runExtension(readMcpTarget(ctx),ctx.options,ctx.global),package:ctx=>runExtension(readMcpTarget(ctx),ctx.options,ctx.global),install:ctx=>runExtension(readMcpTarget(ctx),{...ctx.options,install:!0},ctx.global),upgrade:ctx=>runUpgrade(readMcpTarget(ctx),ctx.options,ctx.global),delete:ctx=>runDelete(requireMcpItemId(ctx),ctx.options,ctx.global),deps:ctx=>runDeps(requireMcpItemId(ctx),ctx.options,ctx.global),graph:runMcpGraphAction,"files-discover":ctx=>runFilesDiscover(requireMcpItemId(ctx),ctx.options,ctx.global),"files-lookup":ctx=>runMcpFilesLookupAction(ctx,readStringArray(ctx.options.paths)),history:ctx=>runHistory(requireMcpItemId(ctx),{...ctx.options,compact:ctx.options.full===!0||ctx.options.provenance===!0?!1:ctx.options.compact!==!1},ctx.global),"history-redact":ctx=>runHistoryRedact(requireMcpItemId(ctx),ctx.options,ctx.global),"history-repair":runMcpHistoryRepairAction,"history-compact":runMcpHistoryCompactAction,"history-attest":ctx=>runHistoryAttest(ctx.options,ctx.global),"history-author-acknowledge":runMcpHistoryAuthorAcknowledgeAction,plan:runMcpPlanAction,schema:runMcpSchemaAction,profile:runMcpProfileAction,stats:ctx=>runStats(ctx.global,statsCommandOptionsFromRuntime(ctx.options)),append:runMcpAppendAction,"update-many":runMcpUpdateManyAction,"close-many":runMcpCloseManyAction,gc:ctx=>runGc(ctx.global,ctx.options)};export{SDK_ACTION_HANDLERS};
|
|
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]="6d51b67b-2f13-580b-aa6a-eb3b840a1784")}catch{}})();import{projectMutationResult}from"../../core/output/mutation-projection.js";import{withQuerySummary}from"../../core/output/query-summary.js";import{PmCliError}from"../../core/shared/errors.js";import{resolvePmRoot}from"../../core/store/paths.js";import{createUnknownSubcommandError}from"../agent/subcommand-recovery.js";import{normalizeAnnotationTransportOptions}from"../annotations.js";import{acknowledgeUnknownAuthorHistoryEventsFromTransport}from"../author-attribution.js";import{runContracts}from"../cli-contracts/runtime-contracts.js";import{runComments}from"../comments.js";import{runConfig}from"../config.js";import{applyContextIntentProjection}from"../context-intent-contracts.js";import{runDeps}from"../dependencies.js";import{runDocs}from"../docs.js";import{runDuplicates}from"../duplicates.js";import{runExtension}from"../extension.js";import{runFiles,runFilesDiscover,runFilesLookup}from"../files.js";import{runAssuranceDispatch}from"../governance/assurance-action.js";import{runGc}from"../governance/gc.js";import{runHealth}from"../governance/health.js";import{runUpgrade}from"../governance/upgrade.js";import{runValidate}from"../governance/validate.js";import{runGraph}from"../graph/run.js";import{runMcpHistoryCompactAction,runMcpHistoryRepairAction}from"../history-mcp.js";import{runHistoryRedact}from"../history-redact.js";import{runHistoryAttest}from"../history/attestation-command.js";import{runInit}from"../init.js";import{runLearnings}from"../learnings.js";import{runAppend}from"../lifecycle/append.js";import{runCloseMany}from"../lifecycle/close-many.js";import{runCopy}from"../lifecycle/copy.js";import{runCreate}from"../lifecycle/create.js";import{runDelete}from"../lifecycle/delete.js";import{runFocus}from"../lifecycle/focus.js";import{runMcpClaimAction,runMcpCloseAction,runMcpReleaseAction,runMcpReopenAction,runMcpTaskCompositionAction}from"../lifecycle/mcp-actions.js";import{runPlan}from"../lifecycle/plan.js";import{runRestore}from"../lifecycle/restore.js";import{buildPlanMutationReceipt}from"../lifecycle/plan-mutation-receipt.js";import{runUpdateMany}from"../lifecycle/update-many.js";import{runUpdate}from"../lifecycle/update.js";import{runNotes}from"../notes.js";import{PROFILE_SUBCOMMANDS,runProfileApply,runProfileLint,runProfileList,runProfileShow}from"../profile.js";import{normalizeActivityProjectionOptions,runActivity}from"../query/activity.js";import{runAggregate}from"../query/aggregate.js";import{runContext}from"../query/context.js";import{runGet}from"../query/get.js";import{runHistory}from"../query/history.js";import{runList}from"../query/list.js";import{runNext}from"../query/next.js";import{runSearch}from"../query/search.js";import{runRuntimeEvalAction,runRuntimeEventsAction,runRuntimeMergeAction,runRuntimeSchedulingAction,runRuntimeWorkspaceAction}from"../runtime-extended-actions.js";import{closeManyOptionsFromFlat,graphOptionsFromFlat,isMcpMutationTransportInput,parseRuntimeInteger as parseMcpInteger,readRuntimeString as readString,readRuntimeStringArray as readStringArray,resolveRuntimeLimit,updateManyOptionsFromFlat,withAddNoteOption,withFilesDiscoveryOptions,withMutationCompaction}from"../runtime-input.js";import{statsCommandOptionsFromRuntime}from"../runtime-stats-options.js";import{runStats}from"../stats.js";import{runTelemetry}from"../telemetry.js";import{runTestAll}from"../test/batch.js";import{runTest}from"../test/execution.js";import{runtimeFilesLookupOptions}from"../traceability/runtime-files-lookup.js";import{getOwnHandler,readRequiredString}from"./context.js";import{runMcpSchemaAction}from"./schema.js";import{defaultConfigScope}from"../../core/config/positional-value.js";function readMcpTarget(ctx){return readString(ctx.args,"target")??readString(ctx.options,"target")}function requireMcpItemId(ctx,source=ctx.options){return ctx.id??readRequiredString(source,"id")}async function runMcpListAction(ctx){const listOptions=applyContextIntentProjection("list",ctx.options);return listOptions.compact===void 0&&listOptions.brief===void 0&&listOptions.full===void 0&&listOptions.fields===void 0&&listOptions.includeBody===void 0&&(listOptions.compact=!0),withQuerySummary(await runList(readString(ctx.args,"status")??readString(listOptions,"status"),listOptions,ctx.global),listOptions)}async function runMcpSearchAction(ctx){const query=readString(ctx.args,"query")??readString(ctx.args,"keywords")??readRequiredString(ctx.args,"query"),searchOptions=applyContextIntentProjection("search",ctx.options,[query]);return searchOptions.compact===void 0&&searchOptions.full===void 0&&searchOptions.fields===void 0&&(searchOptions.compact=!0),withQuerySummary(await runSearch(query,searchOptions,ctx.global),searchOptions)}async function runMcpCreateAction(ctx){const{changedFields,idOnly,runnerOptions}=withMutationCompaction(ctx.args,ctx.options);return projectMutationResult(await runCreate(runnerOptions,ctx.global),{changedFields,compactEnvelope:changedFields==="compact"&&!idOnly,idOnly})}async function runMcpCopyAction(ctx){const{changedFields,idOnly,runnerOptions}=withMutationCompaction(ctx.args,ctx.options),copyOptions={...runnerOptions,...runnerOptions.title===void 0&&typeof ctx.args.title=="string"?{title:ctx.args.title}:{},...runnerOptions.message===void 0&&typeof ctx.args.message=="string"?{message:ctx.args.message}:{}};return projectMutationResult(await runCopy(requireMcpItemId(ctx,copyOptions),copyOptions,ctx.global),{changedFields,compactEnvelope:changedFields==="compact"&&!idOnly,idOnly})}async function runMcpUpdateAction(ctx){const{changedFields,idOnly,runnerOptions}=withMutationCompaction(ctx.args,ctx.options);return projectMutationResult(await runUpdate(requireMcpItemId(ctx,runnerOptions),runnerOptions,ctx.global),{changedFields,compactEnvelope:changedFields==="compact"&&!idOnly,idOnly})}function runMcpCommentsAction(ctx){const commentOptions=normalizeAnnotationTransportOptions(ctx.options);return commentOptions.add===void 0&&commentOptions.stdin===void 0&&commentOptions.file===void 0&&commentOptions.edit===void 0&&commentOptions.delete===void 0&&(commentOptions.includeMeta=!0),runComments(requireMcpItemId(ctx),commentOptions,ctx.global)}function runMcpFilesLookupAction(ctx,paths){return runFilesLookup(runtimeFilesLookupOptions(ctx.options,paths,parseMcpInteger),ctx.global)}function runMcpFilesAction(ctx){const lookupPaths=readStringArray(ctx.options.lookupPath);if(lookupPaths&&lookupPaths.length>0)return runMcpFilesLookupAction(ctx,lookupPaths);const fileId=requireMcpItemId(ctx);return ctx.options.discover===!0?runFilesDiscover(fileId,withFilesDiscoveryOptions(ctx.options),ctx.global):runFiles(fileId,withAddNoteOption(normalizeAnnotationTransportOptions(ctx.options)),ctx.global)}function runMcpTelemetryAction(ctx){return runTelemetry({subcommand:readString(ctx.args,"subcommand")??readString(ctx.options,"subcommand"),limit:resolveRuntimeLimit(ctx.args,ctx.options)},ctx.global)}function runMcpHealthAction(ctx){const healthOptions={...ctx.options};return healthOptions.brief===void 0&&healthOptions.summary===void 0&&healthOptions.full===void 0&&(healthOptions.summary=!0),runHealth(ctx.global,healthOptions)}function runMcpConfigAction(ctx){const configAction=readString(ctx.args,"configAction")??readString(ctx.options,"configAction")??readString(ctx.options,"action");if(configAction===void 0)throw new PmCliError("Missing required argument: configAction",64);const value=readString(ctx.args,"value")??readString(ctx.options,"value"),options=readString(ctx.options,"policy")!==void 0&&value!==void 0?{...ctx.options,value}:ctx.options,key=readString(ctx.args,"key")??readString(ctx.options,"key");return runConfig(readString(ctx.args,"scope")??readString(ctx.options,"scope")??defaultConfigScope(key),configAction,key,options,ctx.global,readString(ctx.options,"policy")===void 0?value:void 0)}function runMcpActivityAction(ctx){const options=ctx.options;return runActivity(normalizeActivityProjectionOptions(options),ctx.global)}function parseMcpIntegerPrefix(value,label){if(typeof value=="number"){if(!Number.isFinite(value)||!Number.isInteger(value))throw new PmCliError(`${label} must be a finite integer.`,64);return value}if(typeof value=="string"&&value.trim().length>0){const trimmed=value.trim();if(!/^[+-]?\d+(?:st|nd|rd|th)?$/i.test(trimmed))throw new PmCliError(`${label} must be a finite integer.`,64);const parsed=Number.parseInt(trimmed,10);if(!Number.isInteger(parsed))throw new PmCliError(`${label} must be a finite integer.`,64);return parsed}}async function runMcpPlanAction(ctx){const subcommand=readString(ctx.args,"subcommand")??readRequiredString(ctx.options,"subcommand"),planRecord=ctx.options,{changedFields,idOnly}=withMutationCompaction(ctx.args,ctx.options),result=await runPlan({subcommand,id:typeof ctx.id=="string"?ctx.id:typeof planRecord.id=="string"?planRecord.id:void 0,stepRef:readMcpPlanStepRef(ctx),reorderTo:parseMcpIntegerPrefix(planRecord.reorderTo??ctx.args.reorderTo,"plan reorderTo"),options:ctx.options,global:ctx.global});return subcommand!=="show"&&isMcpMutationTransportInput(ctx.args)&&(result.mutation_receipt=buildPlanMutationReceipt(result,void 0)),subcommand==="show"?result:projectMutationResult(result,{changedFields,idOnly,compactEnvelope:changedFields==="compact"&&!idOnly})}function readMcpPlanStepRef(ctx){return typeof ctx.options.stepRef=="string"?ctx.options.stepRef:typeof ctx.args.stepRef=="string"?ctx.args.stepRef:void 0}function runMcpProfileAction(ctx){const subcommand=readString(ctx.args,"subcommand")??readRequiredString(ctx.options,"subcommand"),normalizedSubcommand=subcommand.trim().toLowerCase(),profileName=readString(ctx.args,"name")??readString(ctx.options,"name"),handler=getOwnHandler({list:()=>runProfileList(),show:()=>runProfileShow(profileName),lint:()=>runProfileLint(profileName),apply:()=>runProfileApply(profileName,{dryRun:ctx.args.dryRun===!0||ctx.options.dryRun===!0,author:readString(ctx.args,"author")??readString(ctx.options,"author"),force:ctx.args.force===!0||ctx.options.force===!0},ctx.global)},normalizedSubcommand);if(!handler)throw createUnknownSubcommandError({command_path:"profile",token:subcommand,allowed:PROFILE_SUBCOMMANDS,exit_code:64});return handler()}async function runMcpAppendAction(ctx){const{changedFields,idOnly,runnerOptions}=withMutationCompaction(ctx.args,ctx.options);return projectMutationResult(await runAppend(requireMcpItemId(ctx,runnerOptions),runnerOptions,ctx.global),{changedFields,compactEnvelope:changedFields==="compact"&&!idOnly,idOnly})}async function runMcpUpdateManyAction(ctx){const{changedFields,runnerOptions}=withMutationCompaction(ctx.args,ctx.options);return projectMutationResult(await runUpdateMany(updateManyOptionsFromFlat(runnerOptions),ctx.global),{changedFields})}async function runMcpCloseManyAction(ctx){const{changedFields,runnerOptions}=withMutationCompaction(ctx.args,ctx.options),topLevelReason=readString(ctx.args,"reason"),closeManyRunnerOptions=topLevelReason!==void 0&&runnerOptions.reason===void 0?{...runnerOptions,reason:topLevelReason}:{...runnerOptions};return ctx.force&&closeManyRunnerOptions.force===void 0&&(closeManyRunnerOptions.force=!0),projectMutationResult(await runCloseMany(closeManyOptionsFromFlat(closeManyRunnerOptions),ctx.global),{changedFields})}async function runMcpRestoreAction(ctx){const{changedFields,idOnly,runnerOptions}=withMutationCompaction(ctx.args,ctx.options),target=readString(runnerOptions,"target")??readRequiredString(ctx.args,"target");return projectMutationResult(await runRestore(requireMcpItemId(ctx,runnerOptions),target,runnerOptions,ctx.global),{changedFields,compactEnvelope:changedFields==="compact"&&!idOnly,idOnly})}function runMcpGraphAction(ctx){const merged={...ctx.args,...ctx.options};return runGraph(readRequiredString(merged,"subcommand"),readString(merged,"id")??ctx.id,readString(merged,"target"),graphOptionsFromFlat(merged),ctx.global)}function runMcpHistoryAuthorAcknowledgeAction(ctx){return acknowledgeUnknownAuthorHistoryEventsFromTransport(resolvePmRoot(process.cwd(),ctx.global.path),{...ctx.args,...ctx.options})}const SDK_ACTION_HANDLERS={init:ctx=>runInit(readString(ctx.args,"prefix"),ctx.global,ctx.options),context:ctx=>runContext(applyContextIntentProjection("context",ctx.options),ctx.global),next:ctx=>runNext(applyContextIntentProjection("next",ctx.options),ctx.global),eval:runRuntimeEvalAction,events:runRuntimeEventsAction,merge:runRuntimeMergeAction,workspace:runRuntimeWorkspaceAction,meet:runRuntimeSchedulingAction,event:runRuntimeSchedulingAction,remind:runRuntimeSchedulingAction,list:runMcpListAction,get:ctx=>{const id=requireMcpItemId(ctx);return runGet(id,ctx.global,applyContextIntentProjection("get",ctx.options,[id]))},search:runMcpSearchAction,duplicates:ctx=>{const status=typeof ctx.options.status=="string"?[ctx.options.status]:readStringArray(ctx.options.status);return runDuplicates(ctx.global,{exhaustive:ctx.options.exhaustive===!0,...status.length===0?{}:{status},since:readString(ctx.options,"since"),threshold:typeof ctx.options.threshold=="number"?ctx.options.threshold:void 0,limit:ctx.options.limit==="default"?void 0:parseMcpInteger(ctx.options.limit,"limit")})},create:runMcpCreateAction,copy:runMcpCopyAction,focus:ctx=>runFocus(ctx.id,{clear:ctx.options.clear===!0||ctx.args.clear===!0},ctx.global),update:runMcpUpdateAction,"item-reopen":runMcpReopenAction,restore:runMcpRestoreAction,claim:runMcpClaimAction,release:runMcpReleaseAction,"start-task":ctx=>runMcpTaskCompositionAction(ctx,"start_task"),"pause-task":ctx=>runMcpTaskCompositionAction(ctx,"pause_task"),"close-task":ctx=>runMcpTaskCompositionAction(ctx,"close_task"),close:runMcpCloseAction,comments:runMcpCommentsAction,notes:ctx=>runNotes(requireMcpItemId(ctx),normalizeAnnotationTransportOptions(ctx.options),ctx.global),learnings:ctx=>runLearnings(requireMcpItemId(ctx),normalizeAnnotationTransportOptions(ctx.options),ctx.global),files:runMcpFilesAction,docs:ctx=>runDocs(requireMcpItemId(ctx),withAddNoteOption(normalizeAnnotationTransportOptions(ctx.options)),ctx.global),test:ctx=>runTest(requireMcpItemId(ctx),normalizeAnnotationTransportOptions(ctx.options),ctx.global),"test-all":ctx=>runTestAll(ctx.options,ctx.global),telemetry:runMcpTelemetryAction,validate:ctx=>runValidate(ctx.options,ctx.global,{runUpdate:(id,options,global2)=>runUpdate(id,options,global2)}),health:runMcpHealthAction,assurance:ctx=>runAssuranceDispatch(ctx.args,ctx.options,ctx.global),contracts:ctx=>runContracts(ctx.options,ctx.global),config:runMcpConfigAction,activity:runMcpActivityAction,aggregate:ctx=>runAggregate(ctx.options,ctx.global),extension:ctx=>runExtension(readMcpTarget(ctx),ctx.options,ctx.global),package:ctx=>runExtension(readMcpTarget(ctx),ctx.options,ctx.global),install:ctx=>runExtension(readMcpTarget(ctx),{...ctx.options,install:!0},ctx.global),upgrade:ctx=>runUpgrade(readMcpTarget(ctx),ctx.options,ctx.global),delete:ctx=>runDelete(requireMcpItemId(ctx),ctx.options,ctx.global),deps:ctx=>runDeps(requireMcpItemId(ctx),ctx.options,ctx.global),graph:runMcpGraphAction,"files-discover":ctx=>runFilesDiscover(requireMcpItemId(ctx),ctx.options,ctx.global),"files-lookup":ctx=>runMcpFilesLookupAction(ctx,readStringArray(ctx.options.paths)),history:ctx=>runHistory(requireMcpItemId(ctx),{...ctx.options,compact:ctx.options.full===!0||ctx.options.provenance===!0?!1:ctx.options.compact!==!1},ctx.global),"history-redact":ctx=>runHistoryRedact(requireMcpItemId(ctx),ctx.options,ctx.global),"history-repair":runMcpHistoryRepairAction,"history-compact":runMcpHistoryCompactAction,"history-attest":ctx=>runHistoryAttest(ctx.options,ctx.global),"history-author-acknowledge":runMcpHistoryAuthorAcknowledgeAction,plan:runMcpPlanAction,schema:runMcpSchemaAction,profile:runMcpProfileAction,stats:ctx=>runStats(ctx.global,statsCommandOptionsFromRuntime(ctx.options)),append:runMcpAppendAction,"update-many":runMcpUpdateManyAction,"close-many":runMcpCloseManyAction,gc:ctx=>runGc(ctx.global,ctx.options)};export{SDK_ACTION_HANDLERS};
|
|
2
2
|
//# sourceMappingURL=actions.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]="015691ad-9dc3-59e0-8049-bf2a79b7646f")}catch{}})();function pushOptionalValueFlag(args,flag,value){if(typeof value!="string")return;const trimmed=value.trim();trimmed.length!==0&&args.push(flag,trimmed)}function pushOptionalBooleanFlag(args,flag,value){value===!0&&args.push(flag)}function pushRepeatableValueFlag(args,flag,values){if(Array.isArray(values))for(const value of values){if(typeof value!="string")continue;const trimmed=value.trim();trimmed.length!==0&&args.push(flag,trimmed)}}function buildBackgroundTestCommandArgs(id,options){const args=["test",id,"--run","--json","--progress"];return pushRepeatableValueFlag(args,"--add",options.add),pushRepeatableValueFlag(args,"--add-json",options.addJson),pushRepeatableValueFlag(args,"--remove",options.remove),pushRepeatableValueFlag(args,"--remove-index",Array.isArray(options.removeIndex)?options.removeIndex.map(index=>typeof index=="number"?String(index):index):options.removeIndex),pushOptionalValueFlag(args,"--match",options.match),pushOptionalValueFlag(args,"--only-index",typeof options.onlyIndex=="number"?String(options.onlyIndex):options.onlyIndex),pushOptionalBooleanFlag(args,"--only-last",options.onlyLast),pushOptionalBooleanFlag(args,"--full-history",options.fullHistory),pushRepeatableValueFlag(args,"--measure",options.measure),pushOptionalValueFlag(args,"--metric-below",options.metricBelow),pushOptionalValueFlag(args,"--metric-diff",options.metricDiff),pushSharedBackgroundTestCommandArgs(args,options),pushOptionalValueFlag(args,"--author",options.author),pushOptionalValueFlag(args,"--message",options.message),pushOptionalBooleanFlag(args,"--force",options.force),args}function pushSharedBackgroundTestCommandArgs(args,options){pushOptionalValueFlag(args,"--timeout",options.timeout),pushRepeatableValueFlag(args,"--env-set",options.envSet),pushRepeatableValueFlag(args,"--env-clear",options.envClear),pushOptionalBooleanFlag(args,"--shared-host-safe",options.sharedHostSafe),pushOptionalValueFlag(args,"--pm-context",options.pmContext),pushOptionalBooleanFlag(args,"--override-linked-pm-context",options.overrideLinkedPmContext),pushOptionalValueFlag(args,"--workspace-context",options.workspaceContext),pushOptionalBooleanFlag(args,"--override-linked-workspace-context",options.overrideLinkedWorkspaceContext),pushOptionalBooleanFlag(args,"--allow-untrusted-linked-tests",options.allowUntrustedLinkedTests),pushOptionalBooleanFlag(args,"--fail-on-context-mismatch",options.failOnContextMismatch),pushOptionalBooleanFlag(args,"--fail-on-skipped",options.failOnSkipped),pushOptionalBooleanFlag(args,"--fail-on-empty-test-run",options.failOnEmptyTestRun),pushOptionalBooleanFlag(args,"--require-assertions-for-pm",options.requireAssertionsForPm),pushOptionalBooleanFlag(args,"--check-context",options.checkContext),pushOptionalBooleanFlag(args,"--auto-pm-context",options.autoPmContext)}function buildBackgroundTestAllCommandArgs(options){const args=["test-all","--json","--progress"];return pushOptionalValueFlag(args,"--status",options.status),pushOptionalValueFlag(args,"--limit",options.limit),pushOptionalValueFlag(args,"--offset",options.offset),pushSharedBackgroundTestCommandArgs(args,options),args}export{buildBackgroundTestAllCommandArgs,buildBackgroundTestCommandArgs};
|
|
2
2
|
//# sourceMappingURL=command-args.js.map
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
*
|
|
4
4
|
* Implements the pm test command surface and its agent-facing runtime behavior.
|
|
5
5
|
*/
|
|
6
|
-
import{readJsonPathValue,splitJsonPathSegments}from "./json-path.js";import type{GlobalOptions}from "../../core/shared/command-types.js";import{resolveAuthor}from "../../core/shared/author.js";import{runInit}from "../init.js";import{type LinkedTestPmContextMode,type LinkedTestWorkspaceContextMode}from "./parsers.js";import{type LinkedTestRunSelection}from "../../core/test/run-selectors.js";import type{LinkedTest,LinkScope,TestRunMeasurement}from "../../types/index.js";import{type TestRunMeasurementDiff}from "./measurements.js";import{type LinkedTestTrustDecision}from "./trust.js";type ResolvedLinkedTestPmContextMode=Exclude<LinkedTestPmContextMode,"auto">;
|
|
6
|
+
import{readJsonPathValue,splitJsonPathSegments}from "./json-path.js";import type{GlobalOptions}from "../../core/shared/command-types.js";import{resolveAuthor}from "../../core/shared/author.js";import{runInit}from "../init.js";import{type LinkedTestPmContextMode,type LinkedTestWorkspaceContextMode}from "./parsers.js";import{type LinkedTestRunSelection}from "../../core/test/run-selectors.js";import type{LinkedTest,LinkScope,TestRunMeasurement}from "../../types/index.js";import{type TestRunMeasurementDiff}from "./measurements.js";import{type LinkedCollectionMutationReceipt}from "../linked-artifacts.js";import type{AnnotationOmissionReceipt}from "../annotations.js";import{type LinkedTestTrustDecision}from "./trust.js";type ResolvedLinkedTestPmContextMode=Exclude<LinkedTestPmContextMode,"auto">;
|
|
7
7
|
/** Captured outcome of one linked test command run. */
|
|
8
8
|
export interface LinkedTestExecutionResult{
|
|
9
9
|
/** Standard output captured from the command. */
|
|
@@ -42,6 +42,8 @@ updateIndex?:string|number;
|
|
|
42
42
|
setJson?:string;
|
|
43
43
|
/** Value that configures or reports list for this contract. */
|
|
44
44
|
list?:boolean;
|
|
45
|
+
/** Return every linked test after a write instead of the bounded mutation receipt (pm-gh1700). */
|
|
46
|
+
fullHistory?:boolean;
|
|
45
47
|
/** Value that configures or reports run for this contract. */
|
|
46
48
|
run?:boolean;
|
|
47
49
|
/** Value that configures or reports match for this contract. */
|
|
@@ -130,8 +132,8 @@ id:string;
|
|
|
130
132
|
tests:LinkedTest[];
|
|
131
133
|
/** Executes the results operation through the package runtime. */
|
|
132
134
|
run_results:TestRunResult[];
|
|
133
|
-
/**
|
|
134
|
-
failure_categories
|
|
135
|
+
/** Failure counts by category; present only when the invocation ran linked tests (pm-gh1700). */
|
|
136
|
+
failure_categories?:Record<LinkedTestFailureCategory,number>;
|
|
135
137
|
/** Value that configures or reports selection for this contract. */
|
|
136
138
|
selection?:Omit<LinkedTestRunSelection,"selected">;
|
|
137
139
|
/** Present when a run selector narrowed `tests` to the selected entries; counts the stored tests left out and names the read that restores them. */
|
|
@@ -156,6 +158,16 @@ recovery_command?:string;};
|
|
|
156
158
|
count:number;
|
|
157
159
|
/** Number of linked-test entries removed by this mutation. */
|
|
158
160
|
removed?:number;
|
|
161
|
+
/** Mutations only: linked tests stored after the write (pm-gh1700). */
|
|
162
|
+
total_count?:number;
|
|
163
|
+
/** Mutations only: linked tests this response carries. */
|
|
164
|
+
returned_count?:number;
|
|
165
|
+
/** Mutations only: whether stored linked tests exist beyond the ones returned. */
|
|
166
|
+
has_more?:boolean;
|
|
167
|
+
/** Mutations only: what the write changed. */
|
|
168
|
+
mutation_receipt?:LinkedCollectionMutationReceipt;
|
|
169
|
+
/** Mutations only: withheld linked tests and the selector that restores them. */
|
|
170
|
+
omission_receipt?:AnnotationOmissionReceipt;
|
|
159
171
|
/** One-based position selected by an explicit linked-test metadata edit. */
|
|
160
172
|
updated_index?:number;
|
|
161
173
|
/** Normalized metadata fields changed by an explicit edit. */
|
|
@@ -1,6 +1,6 @@
|
|
|
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]="5e10ed2d-e4e6-5884-8022-233b90ff5585")}catch{}})();import{readJsonPathValue,splitJsonPathSegments}from"./json-path.js";import{isItemRevisionConflict}from"../lifecycle/item-revision.js";import{detectEmptyLinkedTestRun,findLinkedTestExecutionReceipt,renderLinkedTestRestoreCommand,resolveLinkedTestRestoreScope}from"./execution-receipts.js";import{seedLinkedTestWorkspaceSnapshot}from"./workspace-snapshot.js";import{detectLinkedTestCommandNotFound}from"./command-resolution.js";import{updateLinkedTest,parseLinkedTestUpdateOptions,assertLinkedTestEditUsage}from"./update.js";import{admitLinkedTestRequest,assertLinkedTestCommand,linkedTestsHaveSameIdentity}from"./entry.js";import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{spawn}from"node:child_process";import{cp,mkdir,mkdtemp,open,readdir,rm,symlink}from"node:fs/promises";import{tmpdir}from"node:os";import path from"node:path";import{getActiveExtensionRegistrations}from"../../core/extensions/index.js";import{isFileMissingError,pathExists,readFileIfExists}from"../../core/fs/fs-utils.js";import{getWorkspaceHistoryPath,writeWorkspaceJsonWithHistory}from"../../core/history/workspace-history.js";import{resolveItemTypeRegistry}from"../../core/item/type-registry.js";import{createStdinTokenResolver,parseCsvKv,parseOptionalNumber}from"../../core/item/parse.js";import{EXIT_CODE}from"../../core/shared/constants.js";import{resolveAuthor}from"../../core/shared/author.js";import{PmCliError}from"../../core/shared/errors.js";import{stableValueEquals}from"../../core/shared/serialization.js";import{nowIso}from"../../core/shared/time.js";import{locateItem,mutateItem,readLocatedItem}from"../../core/store/item-store.js";import{getSettingsPath,ITEM_FILE_EXTENSIONS,resolveGlobalPmRoot,resolvePmRoot}from"../../core/store/paths.js";import{readSettings}from"../../core/store/settings.js";import{appendTrackedTestRunSummary,buildTrackedTestRunHistory}from"../../core/test/item-test-run-tracking.js";import{runInit}from"../init.js";import{looksLikeStructuredLinkedTestEntry,normalizeStructuredLinkedTestEntry}from"./entry.js";import{LINKED_TEST_PM_CONTEXT_MODE_VALUES as PM_CONTEXT_MODE_VALUES,LINKED_TEST_PROTECTED_ENV_KEYS,parseLinkedTestAssertionEqualsMap,parseLinkedTestAssertionGteMap,parseLinkedTestBoolean as parseLinkedTestBooleanValue,parseLinkedTestContextMode as parseLinkedTestContextModeValue,parseLinkedTestEnvClear as parseLinkedTestEnvClearValue,parseLinkedTestEnvSet as parseLinkedTestEnvSetValue,parseLinkedTestJsonEntries,parseLinkedTestMinLines,parseLinkedTestRegexList,parseLinkedTestStringList,parseLinkedTestWorkspaceContextMode}from"./parsers.js";import{parseOnlyIndexValue,resolveLinkedTestRunSelection}from"../../core/test/run-selectors.js";import{SCOPE_VALUES}from"../../types/index.js";import{diffTestRunMeasurements,parseTestRunMeasurements,queryTestRunMeasurementsBelow}from"./measurements.js";import{withHostEnvironmentBoundary}from"../environment/host-environment-errors.js";import{SOURCE_CONTEXT_ACCESS_ENV}from"../environment/source-context.js";import{assertTestMeasurementExecution,assertTestMeasurementRun}from"./prerequisites.js";import{acknowledgeLinkedTests,attachLinkedTestMutationProvenance,resolveLinkedTestSourceRef,resolveLinkedTestSourceWorkspaceRoot,resolveLinkedTestTrust}from"./trust.js";const TEST_OUTPUT_MAX_BUFFER_BYTES=20*1024*1024,DEFAULT_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS=3e3,DEFAULT_LINKED_TEST_HEARTBEAT_INTERVAL_MS=1e4,DEFAULT_LINKED_TEST_PIPE_CLOSE_GRACE_MS=5e3,MAX_LINKED_TEST_COMMAND_LABEL_LENGTH=120,LINKED_TEST_TRACKER_DIRS_TO_SKIP=new Set(["locks","extensions","runtime"]),LINKED_TEST_ITEM_COUNT_DIRS_TO_SKIP=new Set(["history","index","search","extensions","locks","runtime"]),LINKED_TEST_INFRA_COLLISION_PATTERNS=[/eaddrinuse/i,/address already in use/i,/port\s+\d+\s+is already in use/i,/web server[^.\n]*already running/i,/failed to listen on/i],LINKED_TEST_LOCK_ACQUISITION_PATTERN=/\b(?:could not|failed to|unable to)\s+acquire\b[^\n.]*\block\b/i,LINKED_TEST_LOCK_CONTENTION_CONTEXT_PATTERN=/\b(?:already running|timed?\s*out|timeout|held by another|lock\s+is\s+held)\b/i,PM_TRACKER_READ_SUBCOMMANDS=new Set(["activity","calendar","context","ctx","deps","get","health","history","list","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","search","stats","test-all","validate"]);function readPositiveIntegerEnv(name,fallback){const raw=process.env[name];if(typeof raw!="string"||raw.trim().length===0)return fallback;const parsed=Number.parseInt(raw,10);return!Number.isFinite(parsed)||parsed<=0?fallback:parsed}function linkedTestTimeoutForceKillDelayMs(){return readPositiveIntegerEnv("PM_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS",DEFAULT_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS)}function linkedTestHeartbeatIntervalMs(){return readPositiveIntegerEnv("PM_LINKED_TEST_HEARTBEAT_INTERVAL_MS",DEFAULT_LINKED_TEST_HEARTBEAT_INTERVAL_MS)}function linkedTestPipeCloseGraceMs(){return readPositiveIntegerEnv("PM_LINKED_TEST_PIPE_CLOSE_GRACE_MS",DEFAULT_LINKED_TEST_PIPE_CLOSE_GRACE_MS)}function resolveTrackedRunId(kind){const fromEnv=process.env.PM_BACKGROUND_TEST_RUN_ID?.trim();return fromEnv&&fromEnv.length>0?fromEnv:`${kind}-local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function summarizeRunResultStatuses(results){let passed=0,failed=0,skipped=0;for(const entry of results){if(entry.status==="passed"){passed+=1;continue}if(entry.status==="failed"||entry.status==="refused"){failed+=1;continue}skipped+=1}return{passed,failed,skipped}}function summarizeContextPreflight(runResults){let checkedPmCommands=0,trackerReadCommands=0,mismatches=0,autoRemediated=0;for(const result of runResults){const context=result.execution_context;!context||context.is_pm_command!==!0||(checkedPmCommands+=1,context.is_pm_tracker_read_command===!0&&(trackerReadCommands+=1),context.mismatch_detected===!0&&(mismatches+=1),context.auto_pm_context_applied===!0&&(autoRemediated+=1))}return{checked_pm_commands:checkedPmCommands,tracker_read_commands:trackerReadCommands,mismatches,auto_remediated:autoRemediated}}function ensureScope(raw){const value=raw??"project";if(!SCOPE_VALUES.includes(value))throw new PmCliError(`Invalid scope "${raw}"`,EXIT_CODE.USAGE);return value}function parsePmContextMode(raw){if(!raw)return"schema";const normalized=raw.trim().toLowerCase();if(PM_CONTEXT_MODE_VALUES.includes(normalized))return normalized;throw new PmCliError(`Invalid --pm-context value "${raw}". Expected one of: ${PM_CONTEXT_MODE_VALUES.join(", ")}`,EXIT_CODE.USAGE)}function parseWorkspaceContextMode(raw){return parseLinkedTestWorkspaceContextMode(raw??"source","--workspace-context")}function resolveLinkedTestWorkspaceContextMode(linkedTest,runLevelMode,overrideLinkedMode){return overrideLinkedMode?runLevelMode:parseLinkedTestWorkspaceContextMode(linkedTest.workspace_context_mode,"linked test")??runLevelMode}function resolveLinkedTestRequestedContextMode(linkedTest,runLevelMode,overrideLinkedPmContext){return overrideLinkedPmContext||typeof linkedTest.pm_context_mode!="string"||linkedTest.pm_context_mode.trim().length===0?runLevelMode:parsePmContextMode(linkedTest.pm_context_mode)}function resolveLinkedTestEffectiveContextMode(requestedMode,isPmTrackerReadCommand){return requestedMode==="auto"?isPmTrackerReadCommand?"tracker":"schema":requestedMode}function hasLinkedTestAssertions(linkedTest){return Object.entries(linkedTest).filter(([key])=>key.startsWith("assert_")).some(([,value])=>value==null?!1:Array.isArray(value)?value.length>0:typeof value=="object"?Object.keys(value).length>0:typeof value=="string"?value.trim().length>0:!0)}function buildPmContextMismatchHint(params){const{executionContext,runLevelPmContextMode,linkedOverridePmContextMode}=params;return!executionContext.is_pm_tracker_read_command||!executionContext.mismatch_detected?"":runLevelPmContextMode==="tracker"&&linkedOverridePmContextMode==="schema"?" Linked test metadata pm_context_mode=schema overrides run-level --pm-context tracker. Set pm_context_mode=tracker (or auto) on the linked test, or remove the override, to run against seeded tracker data.":executionContext.pm_context_mode==="schema"?" Use --auto-pm-context to route PM tracker-read linked commands through seeded tracker data automatically. Alternatively, use --pm-context tracker for the whole run.":""}function mergeEnvSetDirectives(entries,optionName){const merged={};if(!entries)return merged;for(const entry of entries){const parsed=parseLinkedTestEnvSetValue(entry,optionName);if(parsed)for(const[key,value]of Object.entries(parsed))merged[key]=value}return merged}function mergeEnvClearDirectives(entries,optionName){if(!entries)return[];const values=[];for(const entry of entries){const parsed=parseLinkedTestEnvClearValue(entry,optionName);parsed&&values.push(...parsed)}return[...new Set(values)]}import{BUN_GLOBAL_FLAGS_WITH_VALUE,NPM_GLOBAL_FLAGS_WITH_VALUE,PNPM_GLOBAL_FLAGS_WITH_VALUE,SCRIPT_RUN_FLAGS_WITH_VALUE,SCRIPT_RUN_SUBCOMMANDS,YARN_GLOBAL_FLAGS_WITH_VALUE,extractPmInvocationArgsFromSegment,parseLauncherSubcommand,parseNpmExecCommand,parseNpxCommand,parsePnpmDlxCommand,resolvePmSubcommandContext,splitNormalizedCommandSegments,stripLeadingEnvAssignments,SHELL_COMMAND_FLAG_PATTERNS,assertNoRecursiveTestAllCommand,invokesRecursiveTestAllCommand,normalizeCommandForValidation,segmentInvokesRecursiveTestAll}from"./linked-command-detection.js";import{extractReferencedPmItemIdsFromCommand}from"./linked-command-detection.js";function commandInvokesPmCli(command){const normalizedCommand=normalizeCommandForValidation(command);return splitNormalizedCommandSegments(normalizedCommand).some(segment=>extractPmInvocationArgsFromSegment(segment)!==null)}function commandInvokesPmTrackerReadCommand(command){const normalizedCommand=normalizeCommandForValidation(command);return splitNormalizedCommandSegments(normalizedCommand).some(segment=>{const invocationArgs=extractPmInvocationArgsFromSegment(segment);if(!invocationArgs)return!1;const context=resolvePmSubcommandContext(invocationArgs);return context?PM_TRACKER_READ_SUBCOMMANDS.has(context.subcommand):!1})}function resolveDirectRunnerSubcommand(parsed){if(parsed)return SCRIPT_RUN_SUBCOMMANDS.has(parsed.subcommand)?parseLauncherSubcommand(parsed.args,SCRIPT_RUN_FLAGS_WITH_VALUE)?.subcommand:parsed.subcommand}function firstDirectTestRunnerSubcommand(executable,args){if(executable==="npx"||executable==="bunx")return parseNpxCommand(args)?.command;if(executable==="pnpm")return resolveDirectRunnerSubcommand(parseLauncherSubcommand(args,PNPM_GLOBAL_FLAGS_WITH_VALUE));if(executable==="npm")return resolveDirectRunnerSubcommand(parseLauncherSubcommand(args,NPM_GLOBAL_FLAGS_WITH_VALUE));if(executable==="yarn")return resolveDirectRunnerSubcommand(parseLauncherSubcommand(args,YARN_GLOBAL_FLAGS_WITH_VALUE));if(executable==="bun")return resolveDirectRunnerSubcommand(parseLauncherSubcommand(args,BUN_GLOBAL_FLAGS_WITH_VALUE))}function isDirectTestRunnerSubcommand(token){return token?token==="vitest"||token==="test"||token.startsWith("test:"):!1}function commandUsesSandboxRunner(normalizedCommand){return normalizedCommand.includes("node scripts/run-tests.mjs ")||normalizedCommand.endsWith("node scripts/run-tests.mjs")||normalizedCommand.includes("node ./scripts/run-tests.mjs ")||normalizedCommand.endsWith("node ./scripts/run-tests.mjs")}function segmentInvokesDirectTestRunner(normalizedSegment){const rawTokens=normalizedSegment.split(" ").filter(token=>token.length>0),tokens=stripLeadingEnvAssignments(rawTokens);if(tokens.length===0)return!1;const[executable,...args]=tokens,shellCommandFlagPattern=SHELL_COMMAND_FLAG_PATTERNS.get(executable);if(shellCommandFlagPattern){const commandFlagIndex=args.findIndex(argument=>shellCommandFlagPattern.test(argument));return commandFlagIndex>=0&&segmentInvokesDirectTestRunner(args.slice(commandFlagIndex+1).join(" "))}return executable==="vitest"||executable.endsWith("/vitest")||executable.endsWith("/vitest.mjs")?!0:executable==="node"?nodeArgsInvokeDirectTestRunner(args):packageManagerInvokesDirectTestRunner(executable,args)}function nodeArgsInvokeDirectTestRunner(args){return args.includes("--test")||args.some(arg=>arg==="vitest"||arg==="vitest.mjs"||arg.endsWith("/vitest")||arg.endsWith("/vitest.mjs"))}function packageManagerInvokesDirectTestRunner(executable,args){return executable==="npx"||executable==="bunx"?isDirectTestRunnerSubcommand(parseNpxCommand(args)?.command):executable==="pnpm"||executable==="npm"?isDirectTestRunnerSubcommand((executable==="pnpm"?parsePnpmDlxCommand(args):parseNpmExecCommand(args))?.command)||isDirectTestRunnerSubcommand(firstDirectTestRunnerSubcommand(executable,args)):(executable==="yarn"||executable==="bun")&&isDirectTestRunnerSubcommand(firstDirectTestRunnerSubcommand(executable,args))}function classifyLinkedTestCommandSafety(command){const normalized=normalizeCommandForValidation(command),segments=splitNormalizedCommandSegments(normalized),directRunner=segments.some(segment=>!commandUsesSandboxRunner(segment)&&segmentInvokesDirectTestRunner(segment)),sandboxRunner=segments.some(commandUsesSandboxRunner);return{accepted:!0,command_kind:directRunner?"direct_runner":sandboxRunner?"sandbox_runner":"other",tracker_isolation:"runtime_injected",trust_boundary:"provenance",advisory:directRunner?"Accepted with runtime-injected tracker isolation. Prefer the repository sandbox runner when available for reproducible build and coverage setup.":"Accepted with runtime-injected tracker isolation and provenance checks before execution."}}function getRuntimeSafetySkipReason(command){if(invokesRecursiveTestAllCommand(command))return'Linked test command skipped: Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.'}function parseAddEntries(raw){return raw?raw.map(parseAddEntry):[]}function parseAddEntry(entry){const trimmed=entry.trim(),kv=looksLikeStructuredLinkedTestEntry(trimmed)?normalizeStructuredLinkedTestEntry(parseCsvKv(entry,"--add"),"--add"):{command:trimmed},command=trimLinkedTestEntryField(kv.command);if(!command)throw new PmCliError("--add requires command=<value> or a bare command (path=<value> is optional metadata)",EXIT_CODE.USAGE);return assertNoRecursiveTestAllCommand(command),{command,path:trimLinkedTestEntryField(kv.path),scope:ensureScope(kv.scope),timeout_seconds:parseLinkedTestTimeoutSeconds(trimLinkedTestEntryField(kv.timeout_seconds),trimLinkedTestEntryField(kv.timeout)),pm_context_mode:parseLinkedTestContextModeValue(trimLinkedTestEntryField(kv.pm_context_mode),"--add"),workspace_context_mode:parseLinkedTestWorkspaceContextMode(trimLinkedTestEntryField(kv.workspace_context_mode),"--add"),env_set:parseLinkedTestEnvSetValue(trimLinkedTestEntryField(kv.env_set),"--add"),env_clear:parseLinkedTestEnvClearValue(trimLinkedTestEntryField(kv.env_clear),"--add"),shared_host_safe:parseLinkedTestBooleanValue(trimLinkedTestEntryField(kv.shared_host_safe),"--add","shared_host_safe"),assert_stdout_contains:parseLinkedTestStringList(trimLinkedTestEntryField(kv.assert_stdout_contains)),assert_stdout_regex:parseLinkedTestRegexList(trimLinkedTestEntryField(kv.assert_stdout_regex),"--add","assert_stdout_regex"),assert_stderr_contains:parseLinkedTestStringList(trimLinkedTestEntryField(kv.assert_stderr_contains)),assert_stderr_regex:parseLinkedTestRegexList(trimLinkedTestEntryField(kv.assert_stderr_regex),"--add","assert_stderr_regex"),assert_stdout_min_lines:parseLinkedTestMinLines(trimLinkedTestEntryField(kv.assert_stdout_min_lines),"--add"),assert_json_field_equals:parseLinkedTestAssertionEqualsMap(trimLinkedTestEntryField(kv.assert_json_field_equals),"--add"),assert_json_field_gte:parseLinkedTestAssertionGteMap(trimLinkedTestEntryField(kv.assert_json_field_gte),"--add"),note:trimLinkedTestEntryField(kv.note)}}function trimLinkedTestEntryField(value){const trimmed=value?.trim();return trimmed&&trimmed.length>0?trimmed:void 0}function parseLinkedTestTimeoutSeconds(timeoutSecondsRaw,timeoutAliasRaw){if(timeoutSecondsRaw&&timeoutAliasRaw&&timeoutSecondsRaw!==timeoutAliasRaw)throw new PmCliError("--add timeout and timeout_seconds must match when both are provided",EXIT_CODE.USAGE);const timeoutRaw=timeoutSecondsRaw??timeoutAliasRaw;if(timeoutRaw===void 0)return;const timeout=Math.floor(parseOptionalNumber(timeoutRaw,"timeout_seconds"));if(timeout<=0)throw new PmCliError("--add timeout_seconds must be a positive integer",EXIT_CODE.USAGE);return timeout}function parseAddJsonEntries(raw){return raw?raw.flatMap(entry=>{const parsed=parseLinkedTestJsonEntries(entry,"--add-json");for(const linkedTest of parsed){const command=linkedTest.command;if(!command)throw new PmCliError("--add-json requires a non-empty command string",EXIT_CODE.USAGE);assertNoRecursiveTestAllCommand(command)}return parsed}):[]}function parseRemoveEntries(raw){return raw?raw.map(entry=>{const trimmed=entry.trim();if(!trimmed)throw new PmCliError("--remove requires command or path value",EXIT_CODE.USAGE);const identityPrefix=/^(command|path)\s*=/i.exec(trimmed);if(identityPrefix){const value=trimmed.slice(identityPrefix[0].length).trim();if(!value)throw new PmCliError("--remove requires a non-empty command=<value> or path=<value>",EXIT_CODE.USAGE);return{kind:identityPrefix[1].toLowerCase(),value}}if(/^[A-Za-z_][\w-]*=\S+$/u.test(trimmed))throw new PmCliError("--remove structured selectors require command=<value> or path=<value>",EXIT_CODE.USAGE);if(/^(?:[-*+]\s+)?(?:path|command)\s*:/i.test(trimmed)||trimmed.startsWith("```")){const kv=parseCsvKv(trimmed,"--remove"),kind=kv.path!==void 0?"path":"command",value=kv.path??kv.command;if(!value?.trim())throw new PmCliError("--remove requires command=<value> and/or path=<value>",EXIT_CODE.USAGE);return{kind,value:value.trim()}}return{kind:"either",value:trimmed}}):[]}function parseRemoveIndexes(raw){return raw?[...new Set(raw.map(value=>{const parsed=typeof value=="number"?value:Number.parseInt(value,10);if(!Number.isInteger(parsed)||parsed<1||String(parsed)!==String(value).trim())throw new PmCliError("--remove-index must be a positive integer",EXIT_CODE.USAGE);return parsed}))]:[]}function closeLinkedTestStdin(child){try{child.stdin?.end()}catch{}}function summarizeLinkedTestCommand(command){const normalized=command.trim().replaceAll(/\s+/g," ");return normalized.length<=MAX_LINKED_TEST_COMMAND_LABEL_LENGTH?normalized:`${normalized.slice(0,MAX_LINKED_TEST_COMMAND_LABEL_LENGTH-3)}...`}function shouldEmitLinkedTestProgress(mode){return mode==="off"?!1:mode==="always"?!0:process.stderr.isTTY===!0}function emitLinkedTestProgress(message){try{process.stderr.write(`${message}
|
|
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]="7130661b-2c3e-5c42-a09d-45a205b191e1")}catch{}})();import{readJsonPathValue,splitJsonPathSegments}from"./json-path.js";import{isItemRevisionConflict}from"../lifecycle/item-revision.js";import{detectEmptyLinkedTestRun,findLinkedTestExecutionReceipt,renderLinkedTestRestoreCommand,resolveLinkedTestRestoreScope}from"./execution-receipts.js";import{seedLinkedTestWorkspaceSnapshot}from"./workspace-snapshot.js";import{detectLinkedTestCommandNotFound}from"./command-resolution.js";import{updateLinkedTest,parseLinkedTestUpdateOptions,assertLinkedTestEditUsage}from"./update.js";import{admitLinkedTestRequest,assertLinkedTestCommand,linkedTestsHaveSameIdentity}from"./entry.js";import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{spawn}from"node:child_process";import{cp,mkdir,mkdtemp,open,readdir,rm,symlink}from"node:fs/promises";import{tmpdir}from"node:os";import path from"node:path";import{getActiveExtensionRegistrations}from"../../core/extensions/index.js";import{isFileMissingError,pathExists,readFileIfExists}from"../../core/fs/fs-utils.js";import{getWorkspaceHistoryPath,writeWorkspaceJsonWithHistory}from"../../core/history/workspace-history.js";import{resolveItemTypeRegistry}from"../../core/item/type-registry.js";import{createStdinTokenResolver,parseCsvKv,parseOptionalNumber}from"../../core/item/parse.js";import{EXIT_CODE}from"../../core/shared/constants.js";import{resolveAuthor}from"../../core/shared/author.js";import{PmCliError}from"../../core/shared/errors.js";import{stableValueEquals}from"../../core/shared/serialization.js";import{nowIso}from"../../core/shared/time.js";import{locateItem,mutateItem,readLocatedItem}from"../../core/store/item-store.js";import{getSettingsPath,ITEM_FILE_EXTENSIONS,resolveGlobalPmRoot,resolvePmRoot}from"../../core/store/paths.js";import{readSettings}from"../../core/store/settings.js";import{appendTrackedTestRunSummary,buildTrackedTestRunHistory}from"../../core/test/item-test-run-tracking.js";import{runInit}from"../init.js";import{looksLikeStructuredLinkedTestEntry,normalizeStructuredLinkedTestEntry}from"./entry.js";import{LINKED_TEST_PM_CONTEXT_MODE_VALUES as PM_CONTEXT_MODE_VALUES,LINKED_TEST_PROTECTED_ENV_KEYS,parseLinkedTestAssertionEqualsMap,parseLinkedTestAssertionGteMap,parseLinkedTestBoolean as parseLinkedTestBooleanValue,parseLinkedTestContextMode as parseLinkedTestContextModeValue,parseLinkedTestEnvClear as parseLinkedTestEnvClearValue,parseLinkedTestEnvSet as parseLinkedTestEnvSetValue,parseLinkedTestJsonEntries,parseLinkedTestMinLines,parseLinkedTestRegexList,parseLinkedTestStringList,parseLinkedTestWorkspaceContextMode}from"./parsers.js";import{parseOnlyIndexValue,resolveLinkedTestRunSelection}from"../../core/test/run-selectors.js";import{SCOPE_VALUES}from"../../types/index.js";import{diffTestRunMeasurements,parseTestRunMeasurements,queryTestRunMeasurementsBelow}from"./measurements.js";import{withHostEnvironmentBoundary}from"../environment/host-environment-errors.js";import{linkedCollectionMutationFields,projectLinkedCollectionMutation,writtenLinkedEntries}from"../linked-artifacts.js";import{SOURCE_CONTEXT_ACCESS_ENV}from"../environment/source-context.js";import{assertTestMeasurementExecution,assertTestMeasurementRun}from"./prerequisites.js";import{acknowledgeLinkedTests,attachLinkedTestMutationProvenance,resolveLinkedTestSourceRef,resolveLinkedTestSourceWorkspaceRoot,resolveLinkedTestTrust}from"./trust.js";const TEST_OUTPUT_MAX_BUFFER_BYTES=20*1024*1024,DEFAULT_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS=3e3,DEFAULT_LINKED_TEST_HEARTBEAT_INTERVAL_MS=1e4,DEFAULT_LINKED_TEST_PIPE_CLOSE_GRACE_MS=5e3,MAX_LINKED_TEST_COMMAND_LABEL_LENGTH=120,LINKED_TEST_TRACKER_DIRS_TO_SKIP=new Set(["locks","extensions","runtime"]),LINKED_TEST_ITEM_COUNT_DIRS_TO_SKIP=new Set(["history","index","search","extensions","locks","runtime"]),LINKED_TEST_INFRA_COLLISION_PATTERNS=[/eaddrinuse/i,/address already in use/i,/port\s+\d+\s+is already in use/i,/web server[^.\n]*already running/i,/failed to listen on/i],LINKED_TEST_LOCK_ACQUISITION_PATTERN=/\b(?:could not|failed to|unable to)\s+acquire\b[^\n.]*\block\b/i,LINKED_TEST_LOCK_CONTENTION_CONTEXT_PATTERN=/\b(?:already running|timed?\s*out|timeout|held by another|lock\s+is\s+held)\b/i,PM_TRACKER_READ_SUBCOMMANDS=new Set(["activity","calendar","context","ctx","deps","get","health","history","list","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","search","stats","test-all","validate"]);function readPositiveIntegerEnv(name,fallback){const raw=process.env[name];if(typeof raw!="string"||raw.trim().length===0)return fallback;const parsed=Number.parseInt(raw,10);return!Number.isFinite(parsed)||parsed<=0?fallback:parsed}function linkedTestTimeoutForceKillDelayMs(){return readPositiveIntegerEnv("PM_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS",DEFAULT_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS)}function linkedTestHeartbeatIntervalMs(){return readPositiveIntegerEnv("PM_LINKED_TEST_HEARTBEAT_INTERVAL_MS",DEFAULT_LINKED_TEST_HEARTBEAT_INTERVAL_MS)}function linkedTestPipeCloseGraceMs(){return readPositiveIntegerEnv("PM_LINKED_TEST_PIPE_CLOSE_GRACE_MS",DEFAULT_LINKED_TEST_PIPE_CLOSE_GRACE_MS)}function resolveTrackedRunId(kind){const fromEnv=process.env.PM_BACKGROUND_TEST_RUN_ID?.trim();return fromEnv&&fromEnv.length>0?fromEnv:`${kind}-local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function summarizeRunResultStatuses(results){let passed=0,failed=0,skipped=0;for(const entry of results){if(entry.status==="passed"){passed+=1;continue}if(entry.status==="failed"||entry.status==="refused"){failed+=1;continue}skipped+=1}return{passed,failed,skipped}}function summarizeContextPreflight(runResults){let checkedPmCommands=0,trackerReadCommands=0,mismatches=0,autoRemediated=0;for(const result of runResults){const context=result.execution_context;!context||context.is_pm_command!==!0||(checkedPmCommands+=1,context.is_pm_tracker_read_command===!0&&(trackerReadCommands+=1),context.mismatch_detected===!0&&(mismatches+=1),context.auto_pm_context_applied===!0&&(autoRemediated+=1))}return{checked_pm_commands:checkedPmCommands,tracker_read_commands:trackerReadCommands,mismatches,auto_remediated:autoRemediated}}function ensureScope(raw){const value=raw??"project";if(!SCOPE_VALUES.includes(value))throw new PmCliError(`Invalid scope "${raw}"`,EXIT_CODE.USAGE);return value}function parsePmContextMode(raw){if(!raw)return"schema";const normalized=raw.trim().toLowerCase();if(PM_CONTEXT_MODE_VALUES.includes(normalized))return normalized;throw new PmCliError(`Invalid --pm-context value "${raw}". Expected one of: ${PM_CONTEXT_MODE_VALUES.join(", ")}`,EXIT_CODE.USAGE)}function parseWorkspaceContextMode(raw){return parseLinkedTestWorkspaceContextMode(raw??"source","--workspace-context")}function resolveLinkedTestWorkspaceContextMode(linkedTest,runLevelMode,overrideLinkedMode){return overrideLinkedMode?runLevelMode:parseLinkedTestWorkspaceContextMode(linkedTest.workspace_context_mode,"linked test")??runLevelMode}function resolveLinkedTestRequestedContextMode(linkedTest,runLevelMode,overrideLinkedPmContext){return overrideLinkedPmContext||typeof linkedTest.pm_context_mode!="string"||linkedTest.pm_context_mode.trim().length===0?runLevelMode:parsePmContextMode(linkedTest.pm_context_mode)}function resolveLinkedTestEffectiveContextMode(requestedMode,isPmTrackerReadCommand){return requestedMode==="auto"?isPmTrackerReadCommand?"tracker":"schema":requestedMode}function hasLinkedTestAssertions(linkedTest){return Object.entries(linkedTest).filter(([key])=>key.startsWith("assert_")).some(([,value])=>value==null?!1:Array.isArray(value)?value.length>0:typeof value=="object"?Object.keys(value).length>0:typeof value=="string"?value.trim().length>0:!0)}function buildPmContextMismatchHint(params){const{executionContext,runLevelPmContextMode,linkedOverridePmContextMode}=params;return!executionContext.is_pm_tracker_read_command||!executionContext.mismatch_detected?"":runLevelPmContextMode==="tracker"&&linkedOverridePmContextMode==="schema"?" Linked test metadata pm_context_mode=schema overrides run-level --pm-context tracker. Set pm_context_mode=tracker (or auto) on the linked test, or remove the override, to run against seeded tracker data.":executionContext.pm_context_mode==="schema"?" Use --auto-pm-context to route PM tracker-read linked commands through seeded tracker data automatically. Alternatively, use --pm-context tracker for the whole run.":""}function mergeEnvSetDirectives(entries,optionName){const merged={};if(!entries)return merged;for(const entry of entries){const parsed=parseLinkedTestEnvSetValue(entry,optionName);if(parsed)for(const[key,value]of Object.entries(parsed))merged[key]=value}return merged}function mergeEnvClearDirectives(entries,optionName){if(!entries)return[];const values=[];for(const entry of entries){const parsed=parseLinkedTestEnvClearValue(entry,optionName);parsed&&values.push(...parsed)}return[...new Set(values)]}import{BUN_GLOBAL_FLAGS_WITH_VALUE,NPM_GLOBAL_FLAGS_WITH_VALUE,PNPM_GLOBAL_FLAGS_WITH_VALUE,SCRIPT_RUN_FLAGS_WITH_VALUE,SCRIPT_RUN_SUBCOMMANDS,YARN_GLOBAL_FLAGS_WITH_VALUE,extractPmInvocationArgsFromSegment,parseLauncherSubcommand,parseNpmExecCommand,parseNpxCommand,parsePnpmDlxCommand,resolvePmSubcommandContext,splitNormalizedCommandSegments,stripLeadingEnvAssignments,SHELL_COMMAND_FLAG_PATTERNS,assertNoRecursiveTestAllCommand,invokesRecursiveTestAllCommand,normalizeCommandForValidation,segmentInvokesRecursiveTestAll}from"./linked-command-detection.js";import{extractReferencedPmItemIdsFromCommand}from"./linked-command-detection.js";function commandInvokesPmCli(command){const normalizedCommand=normalizeCommandForValidation(command);return splitNormalizedCommandSegments(normalizedCommand).some(segment=>extractPmInvocationArgsFromSegment(segment)!==null)}function commandInvokesPmTrackerReadCommand(command){const normalizedCommand=normalizeCommandForValidation(command);return splitNormalizedCommandSegments(normalizedCommand).some(segment=>{const invocationArgs=extractPmInvocationArgsFromSegment(segment);if(!invocationArgs)return!1;const context=resolvePmSubcommandContext(invocationArgs);return context?PM_TRACKER_READ_SUBCOMMANDS.has(context.subcommand):!1})}function resolveDirectRunnerSubcommand(parsed){if(parsed)return SCRIPT_RUN_SUBCOMMANDS.has(parsed.subcommand)?parseLauncherSubcommand(parsed.args,SCRIPT_RUN_FLAGS_WITH_VALUE)?.subcommand:parsed.subcommand}function firstDirectTestRunnerSubcommand(executable,args){if(executable==="npx"||executable==="bunx")return parseNpxCommand(args)?.command;if(executable==="pnpm")return resolveDirectRunnerSubcommand(parseLauncherSubcommand(args,PNPM_GLOBAL_FLAGS_WITH_VALUE));if(executable==="npm")return resolveDirectRunnerSubcommand(parseLauncherSubcommand(args,NPM_GLOBAL_FLAGS_WITH_VALUE));if(executable==="yarn")return resolveDirectRunnerSubcommand(parseLauncherSubcommand(args,YARN_GLOBAL_FLAGS_WITH_VALUE));if(executable==="bun")return resolveDirectRunnerSubcommand(parseLauncherSubcommand(args,BUN_GLOBAL_FLAGS_WITH_VALUE))}function isDirectTestRunnerSubcommand(token){return token?token==="vitest"||token==="test"||token.startsWith("test:"):!1}function commandUsesSandboxRunner(normalizedCommand){return normalizedCommand.includes("node scripts/run-tests.mjs ")||normalizedCommand.endsWith("node scripts/run-tests.mjs")||normalizedCommand.includes("node ./scripts/run-tests.mjs ")||normalizedCommand.endsWith("node ./scripts/run-tests.mjs")}function segmentInvokesDirectTestRunner(normalizedSegment){const rawTokens=normalizedSegment.split(" ").filter(token=>token.length>0),tokens=stripLeadingEnvAssignments(rawTokens);if(tokens.length===0)return!1;const[executable,...args]=tokens,shellCommandFlagPattern=SHELL_COMMAND_FLAG_PATTERNS.get(executable);if(shellCommandFlagPattern){const commandFlagIndex=args.findIndex(argument=>shellCommandFlagPattern.test(argument));return commandFlagIndex>=0&&segmentInvokesDirectTestRunner(args.slice(commandFlagIndex+1).join(" "))}return executable==="vitest"||executable.endsWith("/vitest")||executable.endsWith("/vitest.mjs")?!0:executable==="node"?nodeArgsInvokeDirectTestRunner(args):packageManagerInvokesDirectTestRunner(executable,args)}function nodeArgsInvokeDirectTestRunner(args){return args.includes("--test")||args.some(arg=>arg==="vitest"||arg==="vitest.mjs"||arg.endsWith("/vitest")||arg.endsWith("/vitest.mjs"))}function packageManagerInvokesDirectTestRunner(executable,args){return executable==="npx"||executable==="bunx"?isDirectTestRunnerSubcommand(parseNpxCommand(args)?.command):executable==="pnpm"||executable==="npm"?isDirectTestRunnerSubcommand((executable==="pnpm"?parsePnpmDlxCommand(args):parseNpmExecCommand(args))?.command)||isDirectTestRunnerSubcommand(firstDirectTestRunnerSubcommand(executable,args)):(executable==="yarn"||executable==="bun")&&isDirectTestRunnerSubcommand(firstDirectTestRunnerSubcommand(executable,args))}function classifyLinkedTestCommandSafety(command){const normalized=normalizeCommandForValidation(command),segments=splitNormalizedCommandSegments(normalized),directRunner=segments.some(segment=>!commandUsesSandboxRunner(segment)&&segmentInvokesDirectTestRunner(segment)),sandboxRunner=segments.some(commandUsesSandboxRunner);return{accepted:!0,command_kind:directRunner?"direct_runner":sandboxRunner?"sandbox_runner":"other",tracker_isolation:"runtime_injected",trust_boundary:"provenance",advisory:directRunner?"Accepted with runtime-injected tracker isolation. Prefer the repository sandbox runner when available for reproducible build and coverage setup.":"Accepted with runtime-injected tracker isolation and provenance checks before execution."}}function getRuntimeSafetySkipReason(command){if(invokesRecursiveTestAllCommand(command))return'Linked test command skipped: Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.'}function parseAddEntries(raw){return raw?raw.map(parseAddEntry):[]}function parseAddEntry(entry){const trimmed=entry.trim(),kv=looksLikeStructuredLinkedTestEntry(trimmed)?normalizeStructuredLinkedTestEntry(parseCsvKv(entry,"--add"),"--add"):{command:trimmed},command=trimLinkedTestEntryField(kv.command);if(!command)throw new PmCliError("--add requires command=<value> or a bare command (path=<value> is optional metadata)",EXIT_CODE.USAGE);return assertNoRecursiveTestAllCommand(command),{command,path:trimLinkedTestEntryField(kv.path),scope:ensureScope(kv.scope),timeout_seconds:parseLinkedTestTimeoutSeconds(trimLinkedTestEntryField(kv.timeout_seconds),trimLinkedTestEntryField(kv.timeout)),pm_context_mode:parseLinkedTestContextModeValue(trimLinkedTestEntryField(kv.pm_context_mode),"--add"),workspace_context_mode:parseLinkedTestWorkspaceContextMode(trimLinkedTestEntryField(kv.workspace_context_mode),"--add"),env_set:parseLinkedTestEnvSetValue(trimLinkedTestEntryField(kv.env_set),"--add"),env_clear:parseLinkedTestEnvClearValue(trimLinkedTestEntryField(kv.env_clear),"--add"),shared_host_safe:parseLinkedTestBooleanValue(trimLinkedTestEntryField(kv.shared_host_safe),"--add","shared_host_safe"),assert_stdout_contains:parseLinkedTestStringList(trimLinkedTestEntryField(kv.assert_stdout_contains)),assert_stdout_regex:parseLinkedTestRegexList(trimLinkedTestEntryField(kv.assert_stdout_regex),"--add","assert_stdout_regex"),assert_stderr_contains:parseLinkedTestStringList(trimLinkedTestEntryField(kv.assert_stderr_contains)),assert_stderr_regex:parseLinkedTestRegexList(trimLinkedTestEntryField(kv.assert_stderr_regex),"--add","assert_stderr_regex"),assert_stdout_min_lines:parseLinkedTestMinLines(trimLinkedTestEntryField(kv.assert_stdout_min_lines),"--add"),assert_json_field_equals:parseLinkedTestAssertionEqualsMap(trimLinkedTestEntryField(kv.assert_json_field_equals),"--add"),assert_json_field_gte:parseLinkedTestAssertionGteMap(trimLinkedTestEntryField(kv.assert_json_field_gte),"--add"),note:trimLinkedTestEntryField(kv.note)}}function trimLinkedTestEntryField(value){const trimmed=value?.trim();return trimmed&&trimmed.length>0?trimmed:void 0}function parseLinkedTestTimeoutSeconds(timeoutSecondsRaw,timeoutAliasRaw){if(timeoutSecondsRaw&&timeoutAliasRaw&&timeoutSecondsRaw!==timeoutAliasRaw)throw new PmCliError("--add timeout and timeout_seconds must match when both are provided",EXIT_CODE.USAGE);const timeoutRaw=timeoutSecondsRaw??timeoutAliasRaw;if(timeoutRaw===void 0)return;const timeout=Math.floor(parseOptionalNumber(timeoutRaw,"timeout_seconds"));if(timeout<=0)throw new PmCliError("--add timeout_seconds must be a positive integer",EXIT_CODE.USAGE);return timeout}function parseAddJsonEntries(raw){return raw?raw.flatMap(entry=>{const parsed=parseLinkedTestJsonEntries(entry,"--add-json");for(const linkedTest of parsed){const command=linkedTest.command;if(!command)throw new PmCliError("--add-json requires a non-empty command string",EXIT_CODE.USAGE);assertNoRecursiveTestAllCommand(command)}return parsed}):[]}function parseRemoveEntries(raw){return raw?raw.map(entry=>{const trimmed=entry.trim();if(!trimmed)throw new PmCliError("--remove requires command or path value",EXIT_CODE.USAGE);const identityPrefix=/^(command|path)\s*=/i.exec(trimmed);if(identityPrefix){const value=trimmed.slice(identityPrefix[0].length).trim();if(!value)throw new PmCliError("--remove requires a non-empty command=<value> or path=<value>",EXIT_CODE.USAGE);return{kind:identityPrefix[1].toLowerCase(),value}}if(/^[A-Za-z_][\w-]*=\S+$/u.test(trimmed))throw new PmCliError("--remove structured selectors require command=<value> or path=<value>",EXIT_CODE.USAGE);if(/^(?:[-*+]\s+)?(?:path|command)\s*:/i.test(trimmed)||trimmed.startsWith("```")){const kv=parseCsvKv(trimmed,"--remove"),kind=kv.path!==void 0?"path":"command",value=kv.path??kv.command;if(!value?.trim())throw new PmCliError("--remove requires command=<value> and/or path=<value>",EXIT_CODE.USAGE);return{kind,value:value.trim()}}return{kind:"either",value:trimmed}}):[]}function parseRemoveIndexes(raw){return raw?[...new Set(raw.map(value=>{const parsed=typeof value=="number"?value:Number.parseInt(value,10);if(!Number.isInteger(parsed)||parsed<1||String(parsed)!==String(value).trim())throw new PmCliError("--remove-index must be a positive integer",EXIT_CODE.USAGE);return parsed}))]:[]}function closeLinkedTestStdin(child){try{child.stdin?.end()}catch{}}function summarizeLinkedTestCommand(command){const normalized=command.trim().replaceAll(/\s+/g," ");return normalized.length<=MAX_LINKED_TEST_COMMAND_LABEL_LENGTH?normalized:`${normalized.slice(0,MAX_LINKED_TEST_COMMAND_LABEL_LENGTH-3)}...`}function shouldEmitLinkedTestProgress(mode){return mode==="off"?!1:mode==="always"?!0:process.stderr.isTTY===!0}function emitLinkedTestProgress(message){try{process.stderr.write(`${message}
|
|
2
2
|
`)}catch{}}function beginLinkedTestProgress(context,mode){if(!shouldEmitLinkedTestProgress(mode))return null;const commandLabel=summarizeLinkedTestCommand(context.command),startAt=Date.now();emitLinkedTestProgress(`[pm test] linked-test ${context.index}/${context.total} start timeout_ms=${context.timeoutMs} command="${commandLabel}"`);const heartbeat=setInterval(()=>{const elapsedMs=Date.now()-startAt;emitLinkedTestProgress(`[pm test] linked-test ${context.index}/${context.total} running elapsed_ms=${elapsedMs} command="${commandLabel}"`)},linkedTestHeartbeatIntervalMs());return heartbeat.unref?.(),heartbeat}function endLinkedTestProgress(context,executionResult,startedAt,mode){if(!shouldEmitLinkedTestProgress(mode))return;const commandLabel=summarizeLinkedTestCommand(context.command),elapsedMs=Date.now()-startedAt,statusLabel=executionResult.timedOut||executionResult.maxBufferExceeded||executionResult.exitCode!==0?"failed":"passed",reasonTokens=[];executionResult.timedOut&&reasonTokens.push("reason=timeout"),executionResult.maxBufferExceeded&&reasonTokens.push("reason=max_buffer"),executionResult.outputTruncated&&reasonTokens.push("output=truncated"),executionResult.signal&&reasonTokens.push(`signal=${executionResult.signal}`);const exitLabel=executionResult.exitCode===null?"null":String(executionResult.exitCode),reasonSuffix=reasonTokens.length>0?` ${reasonTokens.join(" ")}`:"";emitLinkedTestProgress(`[pm test] linked-test ${context.index}/${context.total} end status=${statusLabel} exit_code=${exitLabel} elapsed_ms=${elapsedMs}${reasonSuffix} command="${commandLabel}"`)}async function killProcessTree(pid){if(!(!Number.isInteger(pid)||pid<=0)){if(process.platform==="win32"){await new Promise(resolve=>{const killer=spawn("taskkill",["/pid",String(pid),"/T","/F"],{stdio:"ignore",windowsHide:!0});killer.on("error",()=>resolve()),killer.on("close",()=>resolve())});return}try{process.kill(-pid,"SIGKILL");return}catch{}try{process.kill(pid,"SIGKILL")}catch{}}}function clearLinkedTestTimers(timers){timers.heartbeat&&clearInterval(timers.heartbeat),timers.timedOutTimer&&(clearTimeout(timers.timedOutTimer),timers.timedOutTimer=null),timers.forceKillTimer&&(clearTimeout(timers.forceKillTimer),timers.forceKillTimer=null)}function createLinkedTestTerminationRequester(child,timers){let terminationRequested=!1;return async()=>{if(terminationRequested)return;terminationRequested=!0;const pid=child.pid;if(!pid||pid<=0){try{child.kill("SIGTERM")}catch{}return}if(process.platform==="win32"){await killProcessTree(pid);return}try{process.kill(-pid,"SIGTERM")}catch{try{child.kill("SIGTERM")}catch{}}timers.forceKillTimer=setTimeout(()=>{killProcessTree(pid)},linkedTestTimeoutForceKillDelayMs()),timers.forceKillTimer.unref?.()}}function waitForLinkedTestChildClose(child){return new Promise(resolve=>{let settled=!1,pipeCloseGraceTimer=null;const settle=(value,destroyPipes=!1)=>{settled||(settled=!0,pipeCloseGraceTimer&&(clearTimeout(pipeCloseGraceTimer),pipeCloseGraceTimer=null),destroyPipes&&(child.stdin?.destroy(),child.stdout?.destroy(),child.stderr?.destroy()),resolve(value))};child.on("exit",(exitCode,exitSignal)=>{settled||(pipeCloseGraceTimer=setTimeout(()=>{settle({code:exitCode,signal:exitSignal},!0)},linkedTestPipeCloseGraceMs()),pipeCloseGraceTimer.unref?.())}),child.on("close",(closeCode,closeSignal)=>{settle({code:closeCode,signal:closeSignal})})})}function createLinkedTestChild(command,env,stdoutFd,stderrFd,cwd){return spawn(command,{cwd,env,shell:!0,windowsHide:!0,detached:process.platform!=="win32",stdio:["pipe",stdoutFd,stderrFd]})}async function readLinkedTestCapture(capturePath){const handle=await open(capturePath,"r");try{const size=(await handle.stat()).size,retainedBytes=Math.min(size,TEST_OUTPUT_MAX_BUFFER_BYTES),buffer=Buffer.alloc(retainedBytes);return retainedBytes>0&&await handle.read(buffer,0,retainedBytes,0),{text:buffer.toString("utf8"),truncated:size>TEST_OUTPUT_MAX_BUFFER_BYTES}}finally{await handle.close()}}async function runLinkedTestCommand(command,timeoutMs,env,progressContext,progressMode,cwd=process.cwd()){const startedAt=Date.now(),captureRoot=await mkdtemp(path.join(tmpdir(),"pm-linked-test-output-"));try{const stdoutPath=path.join(captureRoot,"stdout.log"),stderrPath=path.join(captureRoot,"stderr.log"),[stdoutHandle,stderrHandle]=await Promise.all([open(stdoutPath,"w"),open(stderrPath,"w")]);let child;try{child=createLinkedTestChild(command,env,stdoutHandle.fd,stderrHandle.fd,cwd)}catch(error){throw await Promise.all([stdoutHandle.close(),stderrHandle.close()]),error}const childClose=waitForLinkedTestChildClose(child);let spawnError;child.on("error",error=>{spawnError=error.message}),await Promise.all([stdoutHandle.close(),stderrHandle.close()]),closeLinkedTestStdin(child);const timers={heartbeat:beginLinkedTestProgress(progressContext,progressMode),forceKillTimer:null,timedOutTimer:null},requestTermination=createLinkedTestTerminationRequester(child,timers);let timedOut=!1;timers.timedOutTimer=setTimeout(()=>{timedOut=!0,requestTermination()},timeoutMs),timers.timedOutTimer.unref?.();const{code,signal}=await childClose;clearLinkedTestTimers(timers);const[stdout,stderr]=await Promise.all([readLinkedTestCapture(stdoutPath),readLinkedTestCapture(stderrPath)]),outputTruncated=stdout.truncated||stderr.truncated,truncationNotice=outputTruncated?`
|
|
3
3
|
[pm linked-test output truncated at ${TEST_OUTPUT_MAX_BUFFER_BYTES} bytes per stream; the child process continued to completion]
|
|
4
4
|
`:"";!spawnError&&await detectLinkedTestCommandNotFound(command,{exitCode:code,stderr:stderr.text},env,cwd)&&(spawnError="Linked test executable was not found. Install the tool or update the linked command before retrying.");const executionResult={stdout:`${stdout.text}${truncationNotice}`,stderr:stderr.text,exitCode:code,signal,timedOut,maxBufferExceeded:!1,outputTruncated,spawnError};return endLinkedTestProgress(progressContext,executionResult,startedAt,progressMode),executionResult}finally{await rm(captureRoot,{recursive:!0,force:!0})}}function formatLinkedTestExecutionError(result,timeoutMs){const details=[];result.maxBufferExceeded&&details.push(`Linked test output exceeded maxBuffer=${TEST_OUTPUT_MAX_BUFFER_BYTES} bytes. Reduce output volume or split the command.`),result.timedOut&&timeoutMs>0&&details.push(`Linked test timed out after ${timeoutMs}ms.`);const signalMessage=result.signal?`Linked test command terminated by signal ${result.signal}.`:void 0,baseMessage=result.spawnError?.trim()||signalMessage||"Linked test command failed.";return details.length===0?baseMessage:`${baseMessage} ${details.join(" ")}`}function hasInfraCollisionSignal(result){const combined=[result.spawnError??"",result.stderr,result.stdout].join(`
|
|
5
|
-
`);return LINKED_TEST_INFRA_COLLISION_PATTERNS.some(pattern=>pattern.test(combined))||combined.split(/\r?\n/u).some(line=>LINKED_TEST_LOCK_ACQUISITION_PATTERN.test(line)&&LINKED_TEST_LOCK_CONTENTION_CONTEXT_PATTERN.test(line))}function classifyLinkedTestFailure(result){return hasInfraCollisionSignal(result)?"infra_collision":result.timedOut?"timeout":result.maxBufferExceeded?"max_buffer":result.spawnError?"spawn_error":result.signal?"signal":"assertion_failure"}function createEmptyFailureCategoryCounts(){return{infra_collision:0,trust_refusal:0,config_refusal:0,assertion_failure:0,empty_run:0,timeout:0,max_buffer:0,spawn_error:0,signal:0}}function countFailureCategories(runResults){const counts=createEmptyFailureCategoryCounts();for(const result of runResults)result.status!=="failed"&&result.status!=="refused"||!result.failure_category||(counts[result.failure_category]+=1);return counts}function applyEnvDirectiveStage(env,directives){for(const[key,value]of Object.entries(directives.env_set))LINKED_TEST_PROTECTED_ENV_KEYS.has(key.toUpperCase())||(env[key]=value);for(const key of directives.env_clear)LINKED_TEST_PROTECTED_ENV_KEYS.has(key.toUpperCase())||delete env[key]}function applySharedHostSafeDefaults(env){env.PORT===void 0&&(env.PORT="0"),env.HOST===void 0&&(env.HOST="127.0.0.1"),env.PM_SHARED_HOST_SAFE===void 0&&(env.PM_SHARED_HOST_SAFE="1"),env.PLAYWRIGHT_HTML_OPEN===void 0&&(env.PLAYWRIGHT_HTML_OPEN="never"),env.PW_TEST_HTML_REPORT_OPEN===void 0&&(env.PW_TEST_HTML_REPORT_OPEN="never")}function resolveEffectiveLinkedTestDirectives(runtimeDirectives,linkedTest){const envSet={...runtimeDirectives.env_set,...linkedTest.env_set},envClear=[...new Set([...runtimeDirectives.env_clear,...linkedTest.env_clear??[]])],sharedHostSafe=linkedTest.shared_host_safe??runtimeDirectives.shared_host_safe;return{env_set:envSet,env_clear:envClear,shared_host_safe:sharedHostSafe}}function resolveRuntimeDirectives(envSetEntries,envClearEntries,sharedHostSafe){return{env_set:mergeEnvSetDirectives(envSetEntries,"--env-set"),env_clear:mergeEnvClearDirectives(envClearEntries,"--env-clear"),shared_host_safe:sharedHostSafe===!0}}async function copyIntoSandboxIfPresent(sourcePath,targetPath,recursive=!1,makeDirectory=mkdir){if(await pathExists(sourcePath))try{await withHostEnvironmentBoundary("seed_linked_test",async()=>{if(await makeDirectory(path.dirname(targetPath),{recursive:!0}),recursive){await cp(sourcePath,targetPath,{recursive:!0,force:!0});return}await cp(sourcePath,targetPath,{force:!0})},{why:"Linked tests need an isolated PM context without mutating the source tracker.",nextSteps:["Reclaim capacity on the filesystem that hosts the linked-test temporary directory."]})}catch(error){if(typeof error=="object"&&error!==null&&"code"in error&&isFileMissingError(error))return;throw error}}async function seedLinkedTestSandbox(sandboxPmPath,sandboxGlobalPath,sourceRoots,auditSettings=!1){for(const[sourceRoot,sandboxRoot]of[[sourceRoots.projectPmRoot,sandboxPmPath],[sourceRoots.globalPmRoot,sandboxGlobalPath]])if(auditSettings){const raw=await readFileIfExists(getSettingsPath(sourceRoot));if(raw!==null){const settings=await readSettings(sandboxRoot);await writeWorkspaceJsonWithHistory({pmRoot:sandboxRoot,filePath:getSettingsPath(sandboxRoot),raw,op:"settings:write",author:resolveAuthor(void 0,settings.author_default),lockTtlSeconds:settings.locks.ttl_seconds,lockWaitMs:settings.locks.wait_ms,recordCreation:!0,message:"Seed linked-test schema settings history"})}}else await copyIntoSandboxIfPresent(getSettingsPath(sourceRoot),getSettingsPath(sandboxRoot));await copyIntoSandboxIfPresent(path.join(sourceRoots.projectPmRoot,"extensions"),path.join(sandboxPmPath,"extensions"),!0),await copyIntoSandboxIfPresent(path.join(sourceRoots.globalPmRoot,"extensions"),path.join(sandboxGlobalPath,"extensions"),!0)}async function seedLinkedTestTrackerData(sourceRoot,sandboxRoot){if(!await pathExists(sourceRoot))return;const entries=await readdir(sourceRoot,{withFileTypes:!0});for(const entry of entries){if(LINKED_TEST_TRACKER_DIRS_TO_SKIP.has(entry.name))continue;const sourcePath=path.join(sourceRoot,entry.name),targetPath=path.join(sandboxRoot,entry.name);if(entry.isDirectory()){await copyIntoSandboxIfPresent(sourcePath,targetPath,!0);continue}entry.isFile()&&await copyIntoSandboxIfPresent(sourcePath,targetPath)}}async function seedMissingLinkedTestSettingsHistory(sourceRoot,sandboxRoot){const sourceSettingsRaw=await readFileIfExists(getSettingsPath(sourceRoot));if(sourceSettingsRaw===null||await pathExists(getWorkspaceHistoryPath(sourceRoot)))return;const sandboxSettings=await readSettings(sandboxRoot);await rm(getWorkspaceHistoryPath(sandboxRoot),{force:!0}),await rm(getSettingsPath(sandboxRoot),{force:!0}),await writeWorkspaceJsonWithHistory({pmRoot:sandboxRoot,filePath:getSettingsPath(sandboxRoot),raw:sourceSettingsRaw,op:"settings:write",author:resolveAuthor(void 0,sandboxSettings.author_default),lockTtlSeconds:sandboxSettings.locks.ttl_seconds,lockWaitMs:sandboxSettings.locks.wait_ms,recordCreation:!0,message:"Seed linked-test tracker settings history"})}async function countLinkedTestItemFiles(pmRoot){if(!await pathExists(pmRoot))return 0;let total=0;const entries=await readdir(pmRoot,{withFileTypes:!0});for(const entry of entries){if(!entry.isDirectory()||LINKED_TEST_ITEM_COUNT_DIRS_TO_SKIP.has(entry.name))continue;const folderPath=path.join(pmRoot,entry.name);let files;try{files=await readdir(folderPath,{withFileTypes:!0})}catch{continue}for(const file of files)file.isFile()&&ITEM_FILE_EXTENSIONS.some(extension=>file.name.toLowerCase().endsWith(extension))&&(total+=1)}return total}function resolveLinkedTestFailureExitCode(execution){const rawExitCode=typeof execution.exitCode=="number"?execution.exitCode:1;return(execution.timedOut||execution.maxBufferExceeded)&&rawExitCode===0?1:rawExitCode}function parseAssertionLiteral(raw){const trimmed=raw.trim();if(trimmed==="true")return!0;if(trimmed==="false")return!1;if(trimmed==="null")return null;const numeric=Number(trimmed);if(trimmed.length>0&&Number.isFinite(numeric))return numeric;if(trimmed.startsWith("{")&&trimmed.endsWith("}")||trimmed.startsWith("[")&&trimmed.endsWith("]"))try{return JSON.parse(trimmed)}catch{}return trimmed}function compareAssertionValues(actual,expected){return typeof actual=="object"&&actual!==null&&typeof expected=="object"&&expected!==null?stableValueEquals(actual,expected):Object.is(actual,expected)}function evaluateLinkedTestAssertions(linkedTest,stdout,stderr){const failures=[];failures.push(...evaluateContainsAssertions("stdout",stdout,linkedTest.assert_stdout_contains)),failures.push(...evaluateRegexAssertions("stdout",stdout,linkedTest.assert_stdout_regex)),failures.push(...evaluateContainsAssertions("stderr",stderr,linkedTest.assert_stderr_contains)),failures.push(...evaluateRegexAssertions("stderr",stderr,linkedTest.assert_stderr_regex)),failures.push(...evaluateStdoutLineCountAssertion(stdout,linkedTest.assert_stdout_min_lines));const jsonEqualsAssertions=linkedTest.assert_json_field_equals??{},jsonGteAssertions=linkedTest.assert_json_field_gte??{};if(!(Object.keys(jsonEqualsAssertions).length>0||Object.keys(jsonGteAssertions).length>0))return failures;let parsedJson;try{parsedJson=JSON.parse(stdout)}catch(error){return failures.push(`stdout is not valid JSON for assert_json_field_* checks: ${error instanceof Error?error.message:String(error)}`),failures}for(const[fieldPath,expectedRaw]of Object.entries(jsonEqualsAssertions)){const resolved=readJsonPathValue(parsedJson,fieldPath);if(!resolved.found){failures.push(`assert_json_field_equals missing path "${fieldPath}"`);continue}const expected=parseAssertionLiteral(expectedRaw);compareAssertionValues(resolved.value,expected)||failures.push(`assert_json_field_equals mismatch at "${fieldPath}" (expected=${JSON.stringify(expected)} actual=${JSON.stringify(resolved.value)})`)}for(const[fieldPath,expectedMinimum]of Object.entries(jsonGteAssertions)){const resolved=readJsonPathValue(parsedJson,fieldPath);if(!resolved.found){failures.push(`assert_json_field_gte missing path "${fieldPath}"`);continue}if(typeof resolved.value!="number"||!Number.isFinite(resolved.value)){failures.push(`assert_json_field_gte path "${fieldPath}" resolved to non-numeric value`);continue}resolved.value<expectedMinimum&&failures.push(`assert_json_field_gte failed at "${fieldPath}" (expected >= ${expectedMinimum}, actual ${resolved.value})`)}return failures}function evaluateContainsAssertions(streamName,output,expectedValues){const failures=[];for(const expected of expectedValues??[])output.includes(expected)||failures.push(`${streamName} missing required text: "${expected}"`);return failures}function evaluateRegexAssertions(streamName,output,patterns){const failures=[];for(const pattern of patterns??[])try{new RegExp(pattern,"m").test(output)||failures.push(`${streamName} failed regex assertion: /${pattern}/m`)}catch(error){failures.push(`${streamName} regex assertion is invalid: /${pattern}/ (${error instanceof Error?error.message:String(error)})`)}return failures}function evaluateStdoutLineCountAssertion(stdout,minimum){if(typeof minimum!="number")return[];const lineCount=stdout.split(/\r?\n/).map(line=>line.trim()).filter(line=>line.length>0).length;return lineCount<minimum?[`stdout line count ${lineCount} is below required minimum ${minimum}`]:[]}function commandUsesTestNameFilter(command){const normalized=normalizeCommandForValidation(command);return/(?:^|\s)(?:--test-name-pattern|--testnamepattern)(?:=|\s)/u.test(normalized)?!0:splitNormalizedCommandSegments(normalized).some(segment=>/(?:^|\s)-t(?:=|\s)/u.test(segment)&&segmentInvokesDirectTestRunner(segment))}function createLinkedTestSandboxLayout(sandboxRoot){return{root:sandboxRoot,schemaProjectPmPath:path.join(sandboxRoot,"schema","project",".agents","pm"),schemaGlobalPmPath:path.join(sandboxRoot,"schema","global"),trackerProjectPmPath:path.join(sandboxRoot,"tracker","project",".agents","pm"),trackerGlobalPmPath:path.join(sandboxRoot,"tracker","global"),workspaceSnapshotRoot:path.join(sandboxRoot,"workspace","project"),workspaceIsolatedRoot:path.join(sandboxRoot,"workspace","isolated")}}function linkedTestsRequireWorkspaceSnapshot(tests,runLevelMode,overrideLinkedMode){return tests.some(linkedTest=>resolveLinkedTestWorkspaceContextMode(linkedTest,runLevelMode,overrideLinkedMode)==="snapshot")}async function bindSnapshotTracker(snapshotRoot,sandboxPmPath){const agentsRoot=path.join(snapshotRoot,".agents"),target=path.join(agentsRoot,"pm");await mkdir(agentsRoot,{recursive:!0}),await rm(target,{recursive:!0,force:!0}),await symlink(sandboxPmPath,target,process.platform==="win32"?"junction":"dir")}async function initializeLinkedTestSandboxes(layout,initialize=runInit,includeTrackerData=!0){const initOptions={defaults:!0,agentGuidance:"skip"};await initialize(void 0,{path:layout.schemaProjectPmPath},initOptions),await initialize(void 0,{path:layout.schemaGlobalPmPath},initOptions),includeTrackerData&&(await initialize(void 0,{path:layout.trackerProjectPmPath},initOptions),await initialize(void 0,{path:layout.trackerGlobalPmPath},initOptions))}async function seedLinkedTestSandboxesFromSource(layout,sourceRoots,includeTrackerData){sourceRoots&&(await seedLinkedTestSandbox(layout.schemaProjectPmPath,layout.schemaGlobalPmPath,sourceRoots,!0),includeTrackerData&&(await seedLinkedTestSandbox(layout.trackerProjectPmPath,layout.trackerGlobalPmPath,sourceRoots),await seedLinkedTestTrackerData(sourceRoots.projectPmRoot,layout.trackerProjectPmPath),await seedLinkedTestTrackerData(sourceRoots.globalPmRoot,layout.trackerGlobalPmPath),await seedMissingLinkedTestSettingsHistory(sourceRoots.projectPmRoot,layout.trackerProjectPmPath),await seedMissingLinkedTestSettingsHistory(sourceRoots.globalPmRoot,layout.trackerGlobalPmPath)))}function linkedTestsRequireTrackerData(tests,runLevelPmContextMode,options){return tests.some(linkedTest=>{const command=linkedTest.command??"",isPmTrackerReadCommand=command.length>0&&commandInvokesPmTrackerReadCommand(command),requestedPmContextMode=options?.autoPmContext===!0&&isPmTrackerReadCommand?"auto":resolveLinkedTestRequestedContextMode(linkedTest,runLevelPmContextMode,options?.overrideLinkedPmContext===!0);return resolveLinkedTestEffectiveContextMode(requestedPmContextMode,isPmTrackerReadCommand)==="tracker"})}async function countLinkedTestSandboxItems(layout,sourceRoots){return{sourceProjectItemCount:sourceRoots?await countLinkedTestItemFiles(sourceRoots.projectPmRoot):0,sourceGlobalItemCount:sourceRoots?await countLinkedTestItemFiles(sourceRoots.globalPmRoot):0,schemaProjectItemCount:await countLinkedTestItemFiles(layout.schemaProjectPmPath),schemaGlobalItemCount:await countLinkedTestItemFiles(layout.schemaGlobalPmPath),trackerProjectItemCount:await countLinkedTestItemFiles(layout.trackerProjectPmPath),trackerGlobalItemCount:await countLinkedTestItemFiles(layout.trackerGlobalPmPath)}}function buildLinkedTestExecutionContext(params){const trackerMode=params.effectivePmContextMode==="tracker",selectedSandboxProjectPmPath=trackerMode?params.layout.trackerProjectPmPath:params.layout.schemaProjectPmPath,selectedSandboxGlobalPmPath=trackerMode?params.layout.trackerGlobalPmPath:params.layout.schemaGlobalPmPath,selectedSandboxProjectItemCount=trackerMode?params.counts.trackerProjectItemCount:params.counts.schemaProjectItemCount,selectedSandboxGlobalItemCount=trackerMode?params.counts.trackerGlobalItemCount:params.counts.schemaGlobalItemCount,workingDirectory=params.workspaceContextMode==="snapshot"?params.layout.workspaceSnapshotRoot:params.workspaceContextMode==="isolated"?params.layout.workspaceIsolatedRoot:params.sourceWorkspaceRoot,exposedSourceWorkspaceRoot=params.workspaceContextMode==="isolated"?"":workingDirectory;return{requested_pm_context_mode:params.requestedPmContextMode,pm_context_mode:params.effectivePmContextMode,auto_pm_context_applied:params.autoPmContextApplied,is_pm_command:params.isPmCommand,is_pm_tracker_read_command:params.isPmTrackerReadCommand,source_project_pm_path:params.sourceRoots?.projectPmRoot??"",sandbox_project_pm_path:selectedSandboxProjectPmPath,source_global_pm_path:params.sourceRoots?.globalPmRoot??"",sandbox_global_pm_path:selectedSandboxGlobalPmPath,source_project_item_count:params.counts.sourceProjectItemCount,sandbox_project_item_count:selectedSandboxProjectItemCount,source_global_item_count:params.counts.sourceGlobalItemCount,sandbox_global_item_count:selectedSandboxGlobalItemCount,mismatch_detected:params.isPmCommand&&(params.counts.sourceProjectItemCount!==selectedSandboxProjectItemCount||params.counts.sourceGlobalItemCount!==selectedSandboxGlobalItemCount),project_extensions_seeded:!!params.sourceRoots,global_extensions_seeded:!!params.sourceRoots,requested_workspace_context_mode:params.requestedWorkspaceContextMode,workspace_context_mode:params.workspaceContextMode,working_directory:workingDirectory,source_workspace_root:exposedSourceWorkspaceRoot,trust:params.trust}}async function resolveLinkedTestCommandContext(params){const linkedOverridePmContextMode=typeof params.linkedTest.pm_context_mode=="string"&¶ms.linkedTest.pm_context_mode.trim().length>0?parsePmContextMode(params.linkedTest.pm_context_mode):void 0,command=typeof params.linkedTest.command=="string"&¶ms.linkedTest.command.length>0?params.linkedTest.command:void 0,isPmCommand=command?commandInvokesPmCli(command):!1,isPmTrackerReadCommand=isPmCommand&&command?commandInvokesPmTrackerReadCommand(command):!1,autoPmContextApplied=params.options?.autoPmContext===!0&&isPmTrackerReadCommand,requestedPmContextMode=autoPmContextApplied?"auto":resolveLinkedTestRequestedContextMode(params.linkedTest,params.runLevelPmContextMode,params.options?.overrideLinkedPmContext===!0),effectivePmContextMode=resolveLinkedTestEffectiveContextMode(requestedPmContextMode,isPmTrackerReadCommand),selectedSandboxProjectPmPath=effectivePmContextMode==="tracker"?params.layout.trackerProjectPmPath:params.layout.schemaProjectPmPath;params.workspaceContextMode==="snapshot"&&await bindSnapshotTracker(params.layout.workspaceSnapshotRoot,selectedSandboxProjectPmPath);const trust=params.options?.pmRoot?await resolveLinkedTestTrust(params.options.pmRoot,params.linkedTest,params.currentSourceRef):await resolveLinkedTestTrust(params.layout.root,params.linkedTest,params.currentSourceRef);return{linkedOverridePmContextMode,executionContext:buildLinkedTestExecutionContext({layout:params.layout,counts:params.counts,sourceRoots:params.sourceRoots,isPmCommand,isPmTrackerReadCommand,requestedPmContextMode,effectivePmContextMode,autoPmContextApplied,requestedWorkspaceContextMode:params.requestedWorkspaceContextMode,workspaceContextMode:params.workspaceContextMode,sourceWorkspaceRoot:params.sourceWorkspaceRoot,trust})}}function buildLinkedTestSkippedResult(linkedTest,executionContext,error){return{command:linkedTest.command,path:linkedTest.path,status:"skipped",execution_context:executionContext,error}}function buildLinkedTestAssertionFailureResult(linkedTest,executionContext,error,output){return{command:linkedTest.command,path:linkedTest.path,status:"failed",exit_code:1,failure_category:"assertion_failure",execution_context:executionContext,...output?{stdout:output.stdout,stderr:output.stderr}:{},error}}function buildLinkedTestTrustRefusalResult(linkedTest,executionContext,error){return{command:linkedTest.command,path:linkedTest.path,status:"failed",exit_code:1,failure_category:"trust_refusal",execution_context:executionContext,error}}function resolveLinkedTestTrustPreflightResult(params){if(params.executionContext.trust.trusted)return null;const overrideRequested=params.options?.allowUntrustedLinkedTests===!0,policyEnabled=params.options?.untrustedLinkedTestsPolicyEnabled===!0;if(overrideRequested&&policyEnabled)return null;const recovery=policyEnabled?"Retry with --allow-untrusted-linked-tests for this invocation, or acknowledge the current commands with --acknowledge-linked-tests.":"Set testing.allow_untrusted_linked_tests=true, then retry with --allow-untrusted-linked-tests; alternatively acknowledge the current commands with --acknowledge-linked-tests.";return buildLinkedTestTrustRefusalResult(params.linkedTest,params.executionContext,`Linked test command is not trusted by this clone (source_ref=${params.executionContext.trust.source_ref??"unknown"}, current_ref=${params.executionContext.trust.current_source_ref??"unknown"}). ${recovery}`)}function resolveLinkedTestSafetyPreflightResult(params){if(!params.linkedTest.command)return buildLinkedTestSkippedResult(params.linkedTest,params.executionContext,"No command configured for this linked test.");const runtimeSafetySkipReason=getRuntimeSafetySkipReason(params.linkedTest.command);return runtimeSafetySkipReason?buildLinkedTestSkippedResult(params.linkedTest,params.executionContext,runtimeSafetySkipReason):null}function resolveUnboundPmContextFailure(params){return params.executionContext.pm_context_mode!=="none"?null:params.executionContext.workspace_context_mode==="source"?buildLinkedTestConfigurationRefusalResult(params.linkedTest,params.executionContext,"pm_context_mode=none requires workspace_context_mode=isolated or snapshot so implicit tracker discovery cannot reach the source workspace."):params.executionContext.is_pm_command?buildLinkedTestConfigurationRefusalResult(params.linkedTest,params.executionContext,"pm_context_mode=none is for self-isolating SDK tests; direct PM commands require schema, tracker, or auto context."):null}function buildLinkedTestConfigurationRefusalResult(linkedTest,executionContext,error){return{command:linkedTest.command,path:linkedTest.path,status:"refused",exit_code:null,failure_category:"config_refusal",execution_context:executionContext,error}}function resolvePmContextMismatchFailure(params){const failOnMismatchByDefault=params.executionContext.pm_context_mode==="schema"&¶ms.executionContext.is_pm_tracker_read_command&¶ms.executionContext.mismatch_detected,failOnMismatchByFlag=params.options?.failOnContextMismatch===!0&¶ms.executionContext.is_pm_command&¶ms.executionContext.mismatch_detected;if(!failOnMismatchByDefault&&!failOnMismatchByFlag)return null;const mismatchHint=buildPmContextMismatchHint({executionContext:params.executionContext,runLevelPmContextMode:params.runLevelPmContextMode,linkedOverridePmContextMode:params.linkedOverridePmContextMode}),mismatchPrefix=params.options?.checkContext===!0?"Linked test preflight PM context mismatch detected":"Linked test PM context mismatch detected";return buildLinkedTestConfigurationRefusalResult(params.linkedTest,params.executionContext,`${mismatchPrefix} (source_project_items=${params.executionContext.source_project_item_count}, sandbox_project_items=${params.executionContext.sandbox_project_item_count}).${mismatchHint}`)}function resolveLinkedTestPreflightResult(params){return resolveLinkedTestSafetyPreflightResult(params)||resolveLinkedTestTrustPreflightResult(params)||resolveUnboundPmContextFailure(params)||resolvePmContextMismatchFailure(params)||(params.options?.requireAssertionsForPm===!0&¶ms.executionContext.is_pm_command&&!hasLinkedTestAssertions(params.linkedTest)?buildLinkedTestConfigurationRefusalResult(params.linkedTest,params.executionContext,"Linked PM command requires assertions when --require-assertions-for-pm is enabled."):null)}function buildLinkedTestExecutionEnv(params){const effectiveDirectives=resolveEffectiveLinkedTestDirectives(params.runtimeDirectives,params.linkedTest),executionEnv={...process.env,SENTRY_ENVIRONMENT:"test"};return applyEnvDirectiveStage(executionEnv,params.runtimeDirectives),applyEnvDirectiveStage(executionEnv,{env_set:params.linkedTest.env_set??{},env_clear:params.linkedTest.env_clear??[]}),effectiveDirectives.shared_host_safe&&applySharedHostSafeDefaults(executionEnv),executionEnv.FORCE_COLOR="0",params.executionContext.pm_context_mode==="none"?delete executionEnv.PM_PATH:executionEnv.PM_PATH=params.executionContext.sandbox_project_pm_path,executionEnv.PM_GLOBAL_PATH=params.executionContext.sandbox_global_pm_path,params.executionContext.workspace_context_mode!=="source"&&(delete executionEnv.PM_BUILD_CONSUMER_LEASE,delete executionEnv.PM_BUILD_CONSUMER_LEASE_ROOT),params.executionContext.workspace_context_mode==="isolated"?(delete executionEnv.PM_SOURCE_WORKSPACE_ROOT,delete executionEnv.PM_SOURCE_PM_PATH,delete executionEnv[SOURCE_CONTEXT_ACCESS_ENV]):(executionEnv.PM_SOURCE_WORKSPACE_ROOT=params.executionContext.source_workspace_root,executionEnv.PM_SOURCE_PM_PATH=params.executionContext.workspace_context_mode==="snapshot"?params.executionContext.sandbox_project_pm_path:params.executionContext.source_project_pm_path,executionEnv[SOURCE_CONTEXT_ACCESS_ENV]="read_only"),executionEnv}function buildLinkedTestPassedResult(linkedTest,executionContext,execution,receipt){return{command:linkedTest.command,path:linkedTest.path,status:"passed",exit_code:0,execution_context:executionContext,stdout:execution.stdout,stderr:execution.stderr,...receipt?{execution_receipt:receipt}:{}}}function buildLinkedTestEmptyRunResult(params){return{command:params.linkedTest.command,path:params.linkedTest.path,status:"failed",exit_code:1,failure_category:"empty_run",execution_context:params.executionContext,stdout:params.execution.stdout,stderr:params.execution.stderr,error:`Linked test reported an empty test run (${params.emptyRunSignal.code}). Update the test selection so at least one test executes; unfiltered commands may opt out by omitting --fail-on-empty-test-run.`}}function buildLinkedTestCommandFailureResult(params){return{command:params.linkedTest.command,path:params.linkedTest.path,status:"failed",exit_code:resolveLinkedTestFailureExitCode(params.execution),failure_category:classifyLinkedTestFailure(params.execution),execution_context:params.executionContext,stdout:params.execution.stdout,stderr:params.execution.stderr,error:formatLinkedTestExecutionError(params.execution,params.timeoutMs)}}function buildLinkedTestPassedExecutionResult(params){const receipt=findLinkedTestExecutionReceipt(params.execution.stdout,params.execution.stderr);if(params.options?.failOnEmptyTestRun===!0||commandUsesTestNameFilter(params.linkedTest.command??"")){const emptyRunSignal=detectEmptyLinkedTestRun(params.execution.stdout,params.execution.stderr);if(emptyRunSignal)return buildLinkedTestEmptyRunResult({...params,emptyRunSignal});if(commandUsesTestNameFilter(params.linkedTest.command??"")&&!receipt)return buildLinkedTestEmptyRunResult({...params,emptyRunSignal:{code:"missing_positive_execution_receipt"}})}const assertionFailures=evaluateLinkedTestAssertions(params.linkedTest,params.execution.stdout,params.execution.stderr);return assertionFailures.length>0?buildLinkedTestAssertionFailureResult(params.linkedTest,params.executionContext,`Linked test assertion(s) failed: ${assertionFailures.join("; ")}`,params.execution):buildLinkedTestPassedResult(params.linkedTest,params.executionContext,params.execution,receipt)}async function runSingleLinkedTest(params){const command=params.linkedTest.command??"",timeoutMs=(params.linkedTest.timeout_seconds??params.defaultTimeoutSeconds??120)*1e3,execution=await runLinkedTestCommand(command,timeoutMs,buildLinkedTestExecutionEnv(params),{index:params.index+1,total:params.total,timeoutMs,command},params.progressMode,params.executionContext.working_directory);return execution.exitCode===0&&!execution.timedOut&&!execution.maxBufferExceeded?buildLinkedTestPassedExecutionResult({...params,execution}):buildLinkedTestCommandFailureResult({...params,execution,timeoutMs})}async function runLinkedTests(tests,defaultTimeoutSeconds,options){for(const test of tests)assertLinkedTestCommand(test.command);const results=[],sandboxRoot=await mkdtemp(path.join(tmpdir(),"pm-linked-test-")),layout=createLinkedTestSandboxLayout(sandboxRoot),runLevelPmContextMode=parsePmContextMode(options?.pmContext),runLevelWorkspaceContextMode=parseWorkspaceContextMode(options?.workspaceContext),progressMode=options?.progress===!0?"always":"auto",runtimeDirectives=resolveRuntimeDirectives(options?.envSet,options?.envClear,options?.sharedHostSafe),sourceRoots=options?.sourceRoots,sourceWorkspaceRoot=resolveLinkedTestSourceWorkspaceRoot(),includeTrackerData=linkedTestsRequireTrackerData(tests,runLevelPmContextMode,options),includeWorkspaceSnapshot=linkedTestsRequireWorkspaceSnapshot(tests,runLevelWorkspaceContextMode,options?.overrideLinkedWorkspaceContext===!0),currentSourceRef=await resolveLinkedTestSourceRef(sourceWorkspaceRoot);try{await initializeLinkedTestSandboxes(layout,runInit,includeTrackerData),await mkdir(layout.workspaceIsolatedRoot,{recursive:!0}),await seedLinkedTestSandboxesFromSource(layout,sourceRoots,includeTrackerData),includeWorkspaceSnapshot&&await seedLinkedTestWorkspaceSnapshot(sourceWorkspaceRoot,layout.workspaceSnapshotRoot,sourceRoots?.projectPmRoot,includeTrackerData);const counts=await countLinkedTestSandboxItems(layout,sourceRoots);for(let index=0;index<tests.length;index+=1){const linkedTest=tests[index],workspaceContextMode=resolveLinkedTestWorkspaceContextMode(linkedTest,runLevelWorkspaceContextMode,options?.overrideLinkedWorkspaceContext===!0),commandContext=await resolveLinkedTestCommandContext({linkedTest,layout,counts,sourceRoots,runLevelPmContextMode,options,requestedWorkspaceContextMode:runLevelWorkspaceContextMode,workspaceContextMode,currentSourceRef,sourceWorkspaceRoot}),preflightResult=resolveLinkedTestPreflightResult({linkedTest,executionContext:commandContext.executionContext,runLevelPmContextMode,linkedOverridePmContextMode:commandContext.linkedOverridePmContextMode,options});if(preflightResult){results.push(preflightResult);continue}results.push(await runSingleLinkedTest({linkedTest,index,total:tests.length,defaultTimeoutSeconds,runtimeDirectives,progressMode,executionContext:commandContext.executionContext,options}))}}finally{await rm(layout.root,{recursive:!0,force:!0,maxRetries:3,retryDelay:100})}return results}async function readLinkedTestItem(params){const{id,pmRoot,settings,typeToFolder}=params,located=await locateItem(pmRoot,id,settings.id_prefix,settings.item_format,typeToFolder);if(!located)throw new PmCliError(`Item ${id} not found`,EXIT_CODE.NOT_FOUND);const loaded=await readLocatedItem(located,{schema:settings.schema});return{itemId:located.id,tests:loaded.document.metadata.tests??[],testRuns:loaded.document.metadata.test_runs??[],changed:!1,removed:0}}function appendMissingLinkedTests(current,additions){const next=[...current];for(const addition of additions)next.some(entry=>linkedTestsHaveSameIdentity(entry,addition))||next.push(addition);return next}function removeLinkedTestsBySelector(current,removals,removeIndexes){if(removals.length===0&&removeIndexes.length===0)return{tests:current,removed:0};const indexSet=new Set(removeIndexes),tests=current.filter((entry,index)=>indexSet.has(index+1)?!1:!removals.some(selector=>selector.kind==="command"?entry.command===selector.value:selector.kind==="path"?entry.path===selector.value:entry.command===selector.value||entry.path===selector.value));return{tests,removed:current.length-tests.length}}function applyLinkedTestMutations(previous,adds,removes,removeIndexes){return removeLinkedTestsBySelector(appendMissingLinkedTests(previous,adds),removes,removeIndexes)}function hasTestRuntimeDirectiveFlags(options){return[options.timeout!==void 0,options.progress===!0,(options.envSet?.length??0)>0,(options.envClear?.length??0)>0,options.sharedHostSafe===!0,options.pmContext!==void 0,options.overrideLinkedPmContext===!0,options.failOnContextMismatch===!0,options.failOnSkipped===!0,options.failOnEmptyTestRun===!0,options.requireAssertionsForPm===!0,options.checkContext===!0,options.autoPmContext===!0,options.workspaceContext!==void 0,options.overrideLinkedWorkspaceContext===!0,options.allowUntrustedLinkedTests===!0].some(Boolean)}function assertTestRunFlagUsage(options){if(hasTestRuntimeDirectiveFlags(options)&&options.run!==!0)throw new PmCliError("--timeout, --progress, --env-set, --env-clear, --shared-host-safe, --pm-context, --override-linked-pm-context, --workspace-context, --override-linked-workspace-context, --allow-untrusted-linked-tests, --fail-on-context-mismatch, --fail-on-skipped, --fail-on-empty-test-run, --require-assertions-for-pm, --check-context, and --auto-pm-context require --run",EXIT_CODE.USAGE);if(options.acknowledgeLinkedTests===!0&&options.run===!0)throw new PmCliError("--acknowledge-linked-tests records trust without executing commands; run it separately before --run",EXIT_CODE.USAGE);if((options.match!==void 0||options.onlyIndex!==void 0||options.onlyLast===!0)&&options.run!==!0)throw new PmCliError("--match, --only-index, and --only-last require --run",EXIT_CODE.USAGE)}async function resolveLinkedTestItem(params){const{id,options,pmRoot,settings,typeToFolder,adds,removes,removeIndexes}=params;if(adds.length===0&&removes.length===0&&removeIndexes.length===0)return readLinkedTestItem({id,pmRoot,settings,typeToFolder});let removed=0;const result=await mutateItem({pmRoot,settings,id,op:adds.length>0?"tests_add":"tests_remove",author:resolveAuthor(options.author,settings.author_default),message:options.message,force:options.force,skipNoop:!0,mutate(document){const previous=document.metadata.tests??[],mutation=applyLinkedTestMutations(previous,adds,removes,removeIndexes);if(admitLinkedTestRequest(()=>resolveTestRunOptions(options,mutation.tests)),removed=mutation.removed,(removes.length>0||removeIndexes.length>0)&&removed===0)throw new PmCliError("No linked tests matched the requested removal selector",EXIT_CODE.NOT_FOUND,{code:"linked_test_remove_no_match",unmatched:[...removes.map(entry=>`${entry.kind}=${entry.value}`),...removeIndexes.map(index=>`index=${index}`)],required:"List linked tests and retry with an exact command/path or a current 1-based --remove-index.",examples:[`pm test ${id} --list`,`pm test ${id} --remove-index 1`]});return document.metadata.tests=mutation.tests,{changedFields:stableValueEquals(previous,mutation.tests)?[]:["tests"]}}});return{itemId:result.item.id,tests:result.item.tests??[],testRuns:result.item.test_runs??[],changed:result.changedFields.length>0,removed}}function resolveTestRunOptions(options,tests){const pmContextMode=parsePmContextMode(options.pmContext);parseWorkspaceContextMode(options.workspaceContext),resolveRuntimeDirectives(options.envSet,options.envClear,options.sharedHostSafe);const selectorInput={match:options.match,onlyIndex:options.onlyIndex===void 0?void 0:parseOnlyIndexValue(options.onlyIndex),onlyLast:options.onlyLast},defaultTimeoutSeconds=options.timeout===void 0?void 0:parseOptionalNumber(options.timeout,"--timeout");if(defaultTimeoutSeconds!==void 0&&defaultTimeoutSeconds<=0)throw new PmCliError(`--timeout must be a positive number (got "${options.timeout}")`,EXIT_CODE.USAGE);assertTestRunFlagUsage(options);const runSelection=options.run===!0?resolveLinkedTestRunSelection(tests,selectorInput):void 0;if(runSelection)for(const test of runSelection.selected)assertLinkedTestCommand(test.command);return{defaultTimeoutSeconds,pmContextMode,runSelection,testsToRun:runSelection?.selected??tests}}async function executeSelectedLinkedTests(params){const{options,runOptions,pmRoot}=params;return options.run!==!0?[]:await runLinkedTests(runOptions.testsToRun,runOptions.defaultTimeoutSeconds,{progress:options.progress,envSet:options.envSet,envClear:options.envClear,sharedHostSafe:options.sharedHostSafe,pmContext:runOptions.pmContextMode,overrideLinkedPmContext:options.overrideLinkedPmContext,failOnContextMismatch:options.failOnContextMismatch,failOnEmptyTestRun:options.failOnEmptyTestRun===!0||(options.measure?.length??0)>0,requireAssertionsForPm:options.requireAssertionsForPm,checkContext:options.checkContext,autoPmContext:options.autoPmContext,workspaceContext:options.workspaceContext,overrideLinkedWorkspaceContext:options.overrideLinkedWorkspaceContext,pmRoot,allowUntrustedLinkedTests:options.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:params.untrustedLinkedTestsPolicyEnabled,sourceRoots:{projectPmRoot:pmRoot,globalPmRoot:resolveGlobalPmRoot(process.cwd())}})}function buildTestWarnings(options,runResults){const warnings=[];if(options.run===!0&&options.checkContext===!0){const preflight=summarizeContextPreflight(runResults);warnings.push(`context_preflight:checked_pm_commands=${preflight.checked_pm_commands};tracker_read_commands=${preflight.tracker_read_commands};mismatches=${preflight.mismatches};auto_remediated=${preflight.auto_remediated}`)}return warnings}function buildTrackedTestRunSummary(params){const summary=summarizeRunResultStatuses(params.runResults),parsedAttempt=Number.parseInt(process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim()??"",10),resumedFrom=process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM?.trim(),recordedAt=nowIso(),measurements=parseTestRunMeasurements(params.options.measure,recordedAt);return{run_id:resolveTrackedRunId("test"),kind:"test",status:summary.failed>0||params.failOnSkippedTriggered?"failed":"passed",started_at:params.runStartedAt,finished_at:recordedAt,recorded_at:recordedAt,attempt:Number.isFinite(parsedAttempt)&&parsedAttempt>=1?parsedAttempt:void 0,resumed_from:resumedFrom&&resumedFrom.length>0?resumedFrom:void 0,passed:summary.passed,failed:summary.failed,skipped:summary.skipped,fail_on_skipped_triggered:params.failOnSkippedTriggered?!0:void 0,measurements:measurements.length>0?measurements:void 0,executions:params.runResults.filter(result=>result.command?.trim()).slice(0,32).map(result=>({command:result.command.trim(),requested_pm_context_mode:result.execution_context?.requested_pm_context_mode,pm_context_mode:result.execution_context?.pm_context_mode,workspace_context_mode:result.execution_context?.workspace_context_mode,trust_reason:result.execution_context?.trust.reason}))}}async function recordTestRunSummary(params){const{options,pmRoot,settings,itemId,runStartedAt,runResults,failOnSkippedTriggered,warnings}=params;if(options.run!==!0||!runStartedAt)return;const entry=buildTrackedTestRunSummary({options,runStartedAt,runResults,failOnSkippedTriggered});if(settings.testing.record_results_to_items!==!0)return{entry,receipt:{recorded:!1,reason:"tracking_disabled",run_id:entry.run_id,recovery_command:"pm config project set test-result-tracking --policy enabled"}};try{return await appendTrackedTestRunSummary({pmRoot,settings,itemId,author:resolveAuthor(options.author,settings.author_default),message:`Track test run summary (${entry.run_id})`,entry}),{entry,receipt:{recorded:!0,reason:"recorded",run_id:entry.run_id}}}catch(error){if(isItemRevisionConflict(error))throw error;return warnings.push(`test_result_tracking_failed:${itemId}:${error instanceof Error?error.message:String(error)}`),{entry,receipt:{recorded:!1,reason:"write_failed",run_id:entry.run_id}}}}function buildTestMeasurementProjection(options,runs,recordedRun){let metricBelow;if(options.metricBelow!==void 0){const separator=options.metricBelow.indexOf("="),name=options.metricBelow.slice(0,separator).trim(),thresholdText=options.metricBelow.slice(separator+1).trim(),threshold=Number(thresholdText);if(separator<=0||name.length===0||thresholdText.length===0||!Number.isFinite(threshold))throw new PmCliError("--metric-below must use name=value",EXIT_CODE.USAGE);metricBelow=queryTestRunMeasurementsBelow(runs,name,threshold)}return{measurements:recordedRun?.measurements,metric_below:metricBelow,metric_diff:options.metricDiff===void 0?void 0:diffTestRunMeasurements(runs,options.metricDiff)}}async function maybeAcknowledgeLinkedTests(options,pmRoot,tests){if(options.acknowledgeLinkedTests===!0)return acknowledgeLinkedTests(pmRoot,tests,nowIso())}function projectTestResult(input){const{item,runResults,failureCategories,runSelection,failOnSkippedTriggered,warnings,recording,measurementProjection,restoreScope}=input,narrowed=runSelection!==void 0&&runSelection.selector!==null&&runSelection.skipped_count>0,restoreWith=renderLinkedTestRestoreCommand(item.itemId,restoreScope);return{ok:runResults.every(entry=>entry.status!=="failed"&&entry.status!=="refused")&&failOnSkippedTriggered!==!0,id:item.itemId,tests:narrowed?runSelection.selected:item.tests,...narrowed?{tests_omitted:{count:item.tests.length-runSelection.selected.length,restore_with:restoreWith}}:{},run_results:runResults,failure_categories:failureCategories,selection:runSelection?{selector:runSelection.selector,requested:runSelection.requested,selected_indexes:runSelection.selected_indexes,selected_count:runSelection.selected_count,skipped_count:runSelection.skipped_count}:void 0,fail_on_skipped_triggered:failOnSkippedTriggered?!0:void 0,warnings:warnings.length>0?warnings:void 0,changed:item.changed||recording?.receipt.recorded===!0,...recording?{evidence_recording:recording.receipt}:{},count:item.tests.length,...item.removed>0?{removed:item.removed}:{},...measurementProjection}}async function runTest(id,options,global2){const edit=parseLinkedTestUpdateOptions(options);if(edit)return assertLinkedTestEditUsage(options),assertTestRunFlagUsage(options),assertTestMeasurementRun(id,options,global2,resolvePmRoot(process.cwd(),global2.path)),{...await updateLinkedTest(id,{...edit,author:options.author,message:options.message,force:options.force},global2),run_results:[],failure_categories:countFailureCategories([])};const stdinResolver=createStdinTokenResolver(),pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot);assertTestMeasurementRun(id,options,global2,pmRoot),parseTestRunMeasurements(options.measure,"validation"),buildTestMeasurementProjection(options,[],void 0);const typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()),resolvedAdds=await stdinResolver.resolveList(options.add,"--add"),resolvedAddJsons=await stdinResolver.resolveList(options.addJson,"--add-json"),resolvedRemoves=await stdinResolver.resolveList(options.remove,"--remove"),parsedAdds=[...parseAddEntries(resolvedAdds),...parseAddJsonEntries(resolvedAddJsons)],adds=await attachLinkedTestMutationProvenance(parsedAdds,resolveAuthor(options.author,settings.author_default),nowIso())??[],removes=parseRemoveEntries(resolvedRemoves),removeIndexes=parseRemoveIndexes(options.removeIndex),item=await resolveLinkedTestItem({id,options,pmRoot,settings,typeToFolder:typeRegistry.type_to_folder,adds,removes,removeIndexes}),runOptions=admitLinkedTestRequest(()=>resolveTestRunOptions(options,item.tests)),trustAcknowledgement=await maybeAcknowledgeLinkedTests(options,pmRoot,item.tests),runStartedAt=options.run===!0?nowIso():void 0,runResults=await executeSelectedLinkedTests({options,runOptions,pmRoot,untrustedLinkedTestsPolicyEnabled:settings.testing.allow_untrusted_linked_tests});assertTestMeasurementExecution(id,options,global2,pmRoot,runResults);const failureCategories=countFailureCategories(runResults),failOnSkippedTriggered=options.run===!0&&options.failOnSkipped===!0&&runResults.some(entry=>entry.status==="skipped"),warnings=buildTestWarnings(options,runResults);trustAcknowledgement&&warnings.push(`linked_test_trust_acknowledged:${trustAcknowledgement.acknowledged}`);const recording=await recordTestRunSummary({options,pmRoot,settings,itemId:item.itemId,runStartedAt,runResults,failOnSkippedTriggered,warnings}),runs=recording?.receipt.recorded?buildTrackedTestRunHistory([...item.testRuns,recording.entry]):item.testRuns,measurementProjection=buildTestMeasurementProjection(options,runs,recording?.entry);return projectTestResult({item,runResults,failureCategories,runSelection:runOptions.runSelection,failOnSkippedTriggered,warnings,recording,measurementProjection,restoreScope:resolveLinkedTestRestoreScope(global2,pmRoot)})}const _testOnlyTestCommand={buildLinkedTestExecutionContext,buildPmContextMismatchHint,commandInvokesPmCli,commandInvokesPmTrackerReadCommand,commandUsesTestNameFilter,copyIntoSandboxIfPresent,countLinkedTestItemFiles,ensureScope,evaluateLinkedTestAssertions,endLinkedTestProgress,extractPmInvocationArgsFromSegment,firstDirectTestRunnerSubcommand,formatLinkedTestExecutionError,hasLinkedTestAssertions,initializeLinkedTestSandboxes,linkedTestsRequireTrackerData,parseAddJsonEntries,parseLinkedTestTimeoutSeconds,parsePmContextMode,readJsonPathValue,resolveAuthor,resolveDirectRunnerSubcommand,resolveLinkedTestEffectiveContextMode,resolveLinkedTestFailureExitCode,resolveLinkedTestRequestedContextMode,resolveTestRunOptions,resolveTrackedRunId,runLinkedTestCommand,seedMissingLinkedTestSettingsHistory,seedLinkedTestSandbox,seedLinkedTestTrackerData,segmentInvokesRecursiveTestAll,splitJsonPathSegments,summarizeRunResultStatuses};export{_testOnlyTestCommand,classifyLinkedTestCommandSafety,classifyLinkedTestFailure,countFailureCategories,extractReferencedPmItemIdsFromCommand,resolveLinkedTestFailureExitCode,runLinkedTests,runTest,summarizeContextPreflight};
|
|
5
|
+
`);return LINKED_TEST_INFRA_COLLISION_PATTERNS.some(pattern=>pattern.test(combined))||combined.split(/\r?\n/u).some(line=>LINKED_TEST_LOCK_ACQUISITION_PATTERN.test(line)&&LINKED_TEST_LOCK_CONTENTION_CONTEXT_PATTERN.test(line))}function classifyLinkedTestFailure(result){return hasInfraCollisionSignal(result)?"infra_collision":result.timedOut?"timeout":result.maxBufferExceeded?"max_buffer":result.spawnError?"spawn_error":result.signal?"signal":"assertion_failure"}function createEmptyFailureCategoryCounts(){return{infra_collision:0,trust_refusal:0,config_refusal:0,assertion_failure:0,empty_run:0,timeout:0,max_buffer:0,spawn_error:0,signal:0}}function countFailureCategories(runResults){const counts=createEmptyFailureCategoryCounts();for(const result of runResults)result.status!=="failed"&&result.status!=="refused"||!result.failure_category||(counts[result.failure_category]+=1);return counts}function applyEnvDirectiveStage(env,directives){for(const[key,value]of Object.entries(directives.env_set))LINKED_TEST_PROTECTED_ENV_KEYS.has(key.toUpperCase())||(env[key]=value);for(const key of directives.env_clear)LINKED_TEST_PROTECTED_ENV_KEYS.has(key.toUpperCase())||delete env[key]}function applySharedHostSafeDefaults(env){env.PORT===void 0&&(env.PORT="0"),env.HOST===void 0&&(env.HOST="127.0.0.1"),env.PM_SHARED_HOST_SAFE===void 0&&(env.PM_SHARED_HOST_SAFE="1"),env.PLAYWRIGHT_HTML_OPEN===void 0&&(env.PLAYWRIGHT_HTML_OPEN="never"),env.PW_TEST_HTML_REPORT_OPEN===void 0&&(env.PW_TEST_HTML_REPORT_OPEN="never")}function resolveEffectiveLinkedTestDirectives(runtimeDirectives,linkedTest){const envSet={...runtimeDirectives.env_set,...linkedTest.env_set},envClear=[...new Set([...runtimeDirectives.env_clear,...linkedTest.env_clear??[]])],sharedHostSafe=linkedTest.shared_host_safe??runtimeDirectives.shared_host_safe;return{env_set:envSet,env_clear:envClear,shared_host_safe:sharedHostSafe}}function resolveRuntimeDirectives(envSetEntries,envClearEntries,sharedHostSafe){return{env_set:mergeEnvSetDirectives(envSetEntries,"--env-set"),env_clear:mergeEnvClearDirectives(envClearEntries,"--env-clear"),shared_host_safe:sharedHostSafe===!0}}async function copyIntoSandboxIfPresent(sourcePath,targetPath,recursive=!1,makeDirectory=mkdir){if(await pathExists(sourcePath))try{await withHostEnvironmentBoundary("seed_linked_test",async()=>{if(await makeDirectory(path.dirname(targetPath),{recursive:!0}),recursive){await cp(sourcePath,targetPath,{recursive:!0,force:!0});return}await cp(sourcePath,targetPath,{force:!0})},{why:"Linked tests need an isolated PM context without mutating the source tracker.",nextSteps:["Reclaim capacity on the filesystem that hosts the linked-test temporary directory."]})}catch(error){if(typeof error=="object"&&error!==null&&"code"in error&&isFileMissingError(error))return;throw error}}async function seedLinkedTestSandbox(sandboxPmPath,sandboxGlobalPath,sourceRoots,auditSettings=!1){for(const[sourceRoot,sandboxRoot]of[[sourceRoots.projectPmRoot,sandboxPmPath],[sourceRoots.globalPmRoot,sandboxGlobalPath]])if(auditSettings){const raw=await readFileIfExists(getSettingsPath(sourceRoot));if(raw!==null){const settings=await readSettings(sandboxRoot);await writeWorkspaceJsonWithHistory({pmRoot:sandboxRoot,filePath:getSettingsPath(sandboxRoot),raw,op:"settings:write",author:resolveAuthor(void 0,settings.author_default),lockTtlSeconds:settings.locks.ttl_seconds,lockWaitMs:settings.locks.wait_ms,recordCreation:!0,message:"Seed linked-test schema settings history"})}}else await copyIntoSandboxIfPresent(getSettingsPath(sourceRoot),getSettingsPath(sandboxRoot));await copyIntoSandboxIfPresent(path.join(sourceRoots.projectPmRoot,"extensions"),path.join(sandboxPmPath,"extensions"),!0),await copyIntoSandboxIfPresent(path.join(sourceRoots.globalPmRoot,"extensions"),path.join(sandboxGlobalPath,"extensions"),!0)}async function seedLinkedTestTrackerData(sourceRoot,sandboxRoot){if(!await pathExists(sourceRoot))return;const entries=await readdir(sourceRoot,{withFileTypes:!0});for(const entry of entries){if(LINKED_TEST_TRACKER_DIRS_TO_SKIP.has(entry.name))continue;const sourcePath=path.join(sourceRoot,entry.name),targetPath=path.join(sandboxRoot,entry.name);if(entry.isDirectory()){await copyIntoSandboxIfPresent(sourcePath,targetPath,!0);continue}entry.isFile()&&await copyIntoSandboxIfPresent(sourcePath,targetPath)}}async function seedMissingLinkedTestSettingsHistory(sourceRoot,sandboxRoot){const sourceSettingsRaw=await readFileIfExists(getSettingsPath(sourceRoot));if(sourceSettingsRaw===null||await pathExists(getWorkspaceHistoryPath(sourceRoot)))return;const sandboxSettings=await readSettings(sandboxRoot);await rm(getWorkspaceHistoryPath(sandboxRoot),{force:!0}),await rm(getSettingsPath(sandboxRoot),{force:!0}),await writeWorkspaceJsonWithHistory({pmRoot:sandboxRoot,filePath:getSettingsPath(sandboxRoot),raw:sourceSettingsRaw,op:"settings:write",author:resolveAuthor(void 0,sandboxSettings.author_default),lockTtlSeconds:sandboxSettings.locks.ttl_seconds,lockWaitMs:sandboxSettings.locks.wait_ms,recordCreation:!0,message:"Seed linked-test tracker settings history"})}async function countLinkedTestItemFiles(pmRoot){if(!await pathExists(pmRoot))return 0;let total=0;const entries=await readdir(pmRoot,{withFileTypes:!0});for(const entry of entries){if(!entry.isDirectory()||LINKED_TEST_ITEM_COUNT_DIRS_TO_SKIP.has(entry.name))continue;const folderPath=path.join(pmRoot,entry.name);let files;try{files=await readdir(folderPath,{withFileTypes:!0})}catch{continue}for(const file of files)file.isFile()&&ITEM_FILE_EXTENSIONS.some(extension=>file.name.toLowerCase().endsWith(extension))&&(total+=1)}return total}function resolveLinkedTestFailureExitCode(execution){const rawExitCode=typeof execution.exitCode=="number"?execution.exitCode:1;return(execution.timedOut||execution.maxBufferExceeded)&&rawExitCode===0?1:rawExitCode}function parseAssertionLiteral(raw){const trimmed=raw.trim();if(trimmed==="true")return!0;if(trimmed==="false")return!1;if(trimmed==="null")return null;const numeric=Number(trimmed);if(trimmed.length>0&&Number.isFinite(numeric))return numeric;if(trimmed.startsWith("{")&&trimmed.endsWith("}")||trimmed.startsWith("[")&&trimmed.endsWith("]"))try{return JSON.parse(trimmed)}catch{}return trimmed}function compareAssertionValues(actual,expected){return typeof actual=="object"&&actual!==null&&typeof expected=="object"&&expected!==null?stableValueEquals(actual,expected):Object.is(actual,expected)}function evaluateLinkedTestAssertions(linkedTest,stdout,stderr){const failures=[];failures.push(...evaluateContainsAssertions("stdout",stdout,linkedTest.assert_stdout_contains)),failures.push(...evaluateRegexAssertions("stdout",stdout,linkedTest.assert_stdout_regex)),failures.push(...evaluateContainsAssertions("stderr",stderr,linkedTest.assert_stderr_contains)),failures.push(...evaluateRegexAssertions("stderr",stderr,linkedTest.assert_stderr_regex)),failures.push(...evaluateStdoutLineCountAssertion(stdout,linkedTest.assert_stdout_min_lines));const jsonEqualsAssertions=linkedTest.assert_json_field_equals??{},jsonGteAssertions=linkedTest.assert_json_field_gte??{};if(!(Object.keys(jsonEqualsAssertions).length>0||Object.keys(jsonGteAssertions).length>0))return failures;let parsedJson;try{parsedJson=JSON.parse(stdout)}catch(error){return failures.push(`stdout is not valid JSON for assert_json_field_* checks: ${error instanceof Error?error.message:String(error)}`),failures}for(const[fieldPath,expectedRaw]of Object.entries(jsonEqualsAssertions)){const resolved=readJsonPathValue(parsedJson,fieldPath);if(!resolved.found){failures.push(`assert_json_field_equals missing path "${fieldPath}"`);continue}const expected=parseAssertionLiteral(expectedRaw);compareAssertionValues(resolved.value,expected)||failures.push(`assert_json_field_equals mismatch at "${fieldPath}" (expected=${JSON.stringify(expected)} actual=${JSON.stringify(resolved.value)})`)}for(const[fieldPath,expectedMinimum]of Object.entries(jsonGteAssertions)){const resolved=readJsonPathValue(parsedJson,fieldPath);if(!resolved.found){failures.push(`assert_json_field_gte missing path "${fieldPath}"`);continue}if(typeof resolved.value!="number"||!Number.isFinite(resolved.value)){failures.push(`assert_json_field_gte path "${fieldPath}" resolved to non-numeric value`);continue}resolved.value<expectedMinimum&&failures.push(`assert_json_field_gte failed at "${fieldPath}" (expected >= ${expectedMinimum}, actual ${resolved.value})`)}return failures}function evaluateContainsAssertions(streamName,output,expectedValues){const failures=[];for(const expected of expectedValues??[])output.includes(expected)||failures.push(`${streamName} missing required text: "${expected}"`);return failures}function evaluateRegexAssertions(streamName,output,patterns){const failures=[];for(const pattern of patterns??[])try{new RegExp(pattern,"m").test(output)||failures.push(`${streamName} failed regex assertion: /${pattern}/m`)}catch(error){failures.push(`${streamName} regex assertion is invalid: /${pattern}/ (${error instanceof Error?error.message:String(error)})`)}return failures}function evaluateStdoutLineCountAssertion(stdout,minimum){if(typeof minimum!="number")return[];const lineCount=stdout.split(/\r?\n/).map(line=>line.trim()).filter(line=>line.length>0).length;return lineCount<minimum?[`stdout line count ${lineCount} is below required minimum ${minimum}`]:[]}function commandUsesTestNameFilter(command){const normalized=normalizeCommandForValidation(command);return/(?:^|\s)(?:--test-name-pattern|--testnamepattern)(?:=|\s)/u.test(normalized)?!0:splitNormalizedCommandSegments(normalized).some(segment=>/(?:^|\s)-t(?:=|\s)/u.test(segment)&&segmentInvokesDirectTestRunner(segment))}function createLinkedTestSandboxLayout(sandboxRoot){return{root:sandboxRoot,schemaProjectPmPath:path.join(sandboxRoot,"schema","project",".agents","pm"),schemaGlobalPmPath:path.join(sandboxRoot,"schema","global"),trackerProjectPmPath:path.join(sandboxRoot,"tracker","project",".agents","pm"),trackerGlobalPmPath:path.join(sandboxRoot,"tracker","global"),workspaceSnapshotRoot:path.join(sandboxRoot,"workspace","project"),workspaceIsolatedRoot:path.join(sandboxRoot,"workspace","isolated")}}function linkedTestsRequireWorkspaceSnapshot(tests,runLevelMode,overrideLinkedMode){return tests.some(linkedTest=>resolveLinkedTestWorkspaceContextMode(linkedTest,runLevelMode,overrideLinkedMode)==="snapshot")}async function bindSnapshotTracker(snapshotRoot,sandboxPmPath){const agentsRoot=path.join(snapshotRoot,".agents"),target=path.join(agentsRoot,"pm");await mkdir(agentsRoot,{recursive:!0}),await rm(target,{recursive:!0,force:!0}),await symlink(sandboxPmPath,target,process.platform==="win32"?"junction":"dir")}async function initializeLinkedTestSandboxes(layout,initialize=runInit,includeTrackerData=!0){const initOptions={defaults:!0,agentGuidance:"skip"};await initialize(void 0,{path:layout.schemaProjectPmPath},initOptions),await initialize(void 0,{path:layout.schemaGlobalPmPath},initOptions),includeTrackerData&&(await initialize(void 0,{path:layout.trackerProjectPmPath},initOptions),await initialize(void 0,{path:layout.trackerGlobalPmPath},initOptions))}async function seedLinkedTestSandboxesFromSource(layout,sourceRoots,includeTrackerData){sourceRoots&&(await seedLinkedTestSandbox(layout.schemaProjectPmPath,layout.schemaGlobalPmPath,sourceRoots,!0),includeTrackerData&&(await seedLinkedTestSandbox(layout.trackerProjectPmPath,layout.trackerGlobalPmPath,sourceRoots),await seedLinkedTestTrackerData(sourceRoots.projectPmRoot,layout.trackerProjectPmPath),await seedLinkedTestTrackerData(sourceRoots.globalPmRoot,layout.trackerGlobalPmPath),await seedMissingLinkedTestSettingsHistory(sourceRoots.projectPmRoot,layout.trackerProjectPmPath),await seedMissingLinkedTestSettingsHistory(sourceRoots.globalPmRoot,layout.trackerGlobalPmPath)))}function linkedTestsRequireTrackerData(tests,runLevelPmContextMode,options){return tests.some(linkedTest=>{const command=linkedTest.command??"",isPmTrackerReadCommand=command.length>0&&commandInvokesPmTrackerReadCommand(command),requestedPmContextMode=options?.autoPmContext===!0&&isPmTrackerReadCommand?"auto":resolveLinkedTestRequestedContextMode(linkedTest,runLevelPmContextMode,options?.overrideLinkedPmContext===!0);return resolveLinkedTestEffectiveContextMode(requestedPmContextMode,isPmTrackerReadCommand)==="tracker"})}async function countLinkedTestSandboxItems(layout,sourceRoots){return{sourceProjectItemCount:sourceRoots?await countLinkedTestItemFiles(sourceRoots.projectPmRoot):0,sourceGlobalItemCount:sourceRoots?await countLinkedTestItemFiles(sourceRoots.globalPmRoot):0,schemaProjectItemCount:await countLinkedTestItemFiles(layout.schemaProjectPmPath),schemaGlobalItemCount:await countLinkedTestItemFiles(layout.schemaGlobalPmPath),trackerProjectItemCount:await countLinkedTestItemFiles(layout.trackerProjectPmPath),trackerGlobalItemCount:await countLinkedTestItemFiles(layout.trackerGlobalPmPath)}}function buildLinkedTestExecutionContext(params){const trackerMode=params.effectivePmContextMode==="tracker",selectedSandboxProjectPmPath=trackerMode?params.layout.trackerProjectPmPath:params.layout.schemaProjectPmPath,selectedSandboxGlobalPmPath=trackerMode?params.layout.trackerGlobalPmPath:params.layout.schemaGlobalPmPath,selectedSandboxProjectItemCount=trackerMode?params.counts.trackerProjectItemCount:params.counts.schemaProjectItemCount,selectedSandboxGlobalItemCount=trackerMode?params.counts.trackerGlobalItemCount:params.counts.schemaGlobalItemCount,workingDirectory=params.workspaceContextMode==="snapshot"?params.layout.workspaceSnapshotRoot:params.workspaceContextMode==="isolated"?params.layout.workspaceIsolatedRoot:params.sourceWorkspaceRoot,exposedSourceWorkspaceRoot=params.workspaceContextMode==="isolated"?"":workingDirectory;return{requested_pm_context_mode:params.requestedPmContextMode,pm_context_mode:params.effectivePmContextMode,auto_pm_context_applied:params.autoPmContextApplied,is_pm_command:params.isPmCommand,is_pm_tracker_read_command:params.isPmTrackerReadCommand,source_project_pm_path:params.sourceRoots?.projectPmRoot??"",sandbox_project_pm_path:selectedSandboxProjectPmPath,source_global_pm_path:params.sourceRoots?.globalPmRoot??"",sandbox_global_pm_path:selectedSandboxGlobalPmPath,source_project_item_count:params.counts.sourceProjectItemCount,sandbox_project_item_count:selectedSandboxProjectItemCount,source_global_item_count:params.counts.sourceGlobalItemCount,sandbox_global_item_count:selectedSandboxGlobalItemCount,mismatch_detected:params.isPmCommand&&(params.counts.sourceProjectItemCount!==selectedSandboxProjectItemCount||params.counts.sourceGlobalItemCount!==selectedSandboxGlobalItemCount),project_extensions_seeded:!!params.sourceRoots,global_extensions_seeded:!!params.sourceRoots,requested_workspace_context_mode:params.requestedWorkspaceContextMode,workspace_context_mode:params.workspaceContextMode,working_directory:workingDirectory,source_workspace_root:exposedSourceWorkspaceRoot,trust:params.trust}}async function resolveLinkedTestCommandContext(params){const linkedOverridePmContextMode=typeof params.linkedTest.pm_context_mode=="string"&¶ms.linkedTest.pm_context_mode.trim().length>0?parsePmContextMode(params.linkedTest.pm_context_mode):void 0,command=typeof params.linkedTest.command=="string"&¶ms.linkedTest.command.length>0?params.linkedTest.command:void 0,isPmCommand=command?commandInvokesPmCli(command):!1,isPmTrackerReadCommand=isPmCommand&&command?commandInvokesPmTrackerReadCommand(command):!1,autoPmContextApplied=params.options?.autoPmContext===!0&&isPmTrackerReadCommand,requestedPmContextMode=autoPmContextApplied?"auto":resolveLinkedTestRequestedContextMode(params.linkedTest,params.runLevelPmContextMode,params.options?.overrideLinkedPmContext===!0),effectivePmContextMode=resolveLinkedTestEffectiveContextMode(requestedPmContextMode,isPmTrackerReadCommand),selectedSandboxProjectPmPath=effectivePmContextMode==="tracker"?params.layout.trackerProjectPmPath:params.layout.schemaProjectPmPath;params.workspaceContextMode==="snapshot"&&await bindSnapshotTracker(params.layout.workspaceSnapshotRoot,selectedSandboxProjectPmPath);const trust=params.options?.pmRoot?await resolveLinkedTestTrust(params.options.pmRoot,params.linkedTest,params.currentSourceRef):await resolveLinkedTestTrust(params.layout.root,params.linkedTest,params.currentSourceRef);return{linkedOverridePmContextMode,executionContext:buildLinkedTestExecutionContext({layout:params.layout,counts:params.counts,sourceRoots:params.sourceRoots,isPmCommand,isPmTrackerReadCommand,requestedPmContextMode,effectivePmContextMode,autoPmContextApplied,requestedWorkspaceContextMode:params.requestedWorkspaceContextMode,workspaceContextMode:params.workspaceContextMode,sourceWorkspaceRoot:params.sourceWorkspaceRoot,trust})}}function buildLinkedTestSkippedResult(linkedTest,executionContext,error){return{command:linkedTest.command,path:linkedTest.path,status:"skipped",execution_context:executionContext,error}}function buildLinkedTestAssertionFailureResult(linkedTest,executionContext,error,output){return{command:linkedTest.command,path:linkedTest.path,status:"failed",exit_code:1,failure_category:"assertion_failure",execution_context:executionContext,...output?{stdout:output.stdout,stderr:output.stderr}:{},error}}function buildLinkedTestTrustRefusalResult(linkedTest,executionContext,error){return{command:linkedTest.command,path:linkedTest.path,status:"failed",exit_code:1,failure_category:"trust_refusal",execution_context:executionContext,error}}function resolveLinkedTestTrustPreflightResult(params){if(params.executionContext.trust.trusted)return null;const overrideRequested=params.options?.allowUntrustedLinkedTests===!0,policyEnabled=params.options?.untrustedLinkedTestsPolicyEnabled===!0;if(overrideRequested&&policyEnabled)return null;const recovery=policyEnabled?"Retry with --allow-untrusted-linked-tests for this invocation, or acknowledge the current commands with --acknowledge-linked-tests.":"Set testing.allow_untrusted_linked_tests=true, then retry with --allow-untrusted-linked-tests; alternatively acknowledge the current commands with --acknowledge-linked-tests.";return buildLinkedTestTrustRefusalResult(params.linkedTest,params.executionContext,`Linked test command is not trusted by this clone (source_ref=${params.executionContext.trust.source_ref??"unknown"}, current_ref=${params.executionContext.trust.current_source_ref??"unknown"}). ${recovery}`)}function resolveLinkedTestSafetyPreflightResult(params){if(!params.linkedTest.command)return buildLinkedTestSkippedResult(params.linkedTest,params.executionContext,"No command configured for this linked test.");const runtimeSafetySkipReason=getRuntimeSafetySkipReason(params.linkedTest.command);return runtimeSafetySkipReason?buildLinkedTestSkippedResult(params.linkedTest,params.executionContext,runtimeSafetySkipReason):null}function resolveUnboundPmContextFailure(params){return params.executionContext.pm_context_mode!=="none"?null:params.executionContext.workspace_context_mode==="source"?buildLinkedTestConfigurationRefusalResult(params.linkedTest,params.executionContext,"pm_context_mode=none requires workspace_context_mode=isolated or snapshot so implicit tracker discovery cannot reach the source workspace."):params.executionContext.is_pm_command?buildLinkedTestConfigurationRefusalResult(params.linkedTest,params.executionContext,"pm_context_mode=none is for self-isolating SDK tests; direct PM commands require schema, tracker, or auto context."):null}function buildLinkedTestConfigurationRefusalResult(linkedTest,executionContext,error){return{command:linkedTest.command,path:linkedTest.path,status:"refused",exit_code:null,failure_category:"config_refusal",execution_context:executionContext,error}}function resolvePmContextMismatchFailure(params){const failOnMismatchByDefault=params.executionContext.pm_context_mode==="schema"&¶ms.executionContext.is_pm_tracker_read_command&¶ms.executionContext.mismatch_detected,failOnMismatchByFlag=params.options?.failOnContextMismatch===!0&¶ms.executionContext.is_pm_command&¶ms.executionContext.mismatch_detected;if(!failOnMismatchByDefault&&!failOnMismatchByFlag)return null;const mismatchHint=buildPmContextMismatchHint({executionContext:params.executionContext,runLevelPmContextMode:params.runLevelPmContextMode,linkedOverridePmContextMode:params.linkedOverridePmContextMode}),mismatchPrefix=params.options?.checkContext===!0?"Linked test preflight PM context mismatch detected":"Linked test PM context mismatch detected";return buildLinkedTestConfigurationRefusalResult(params.linkedTest,params.executionContext,`${mismatchPrefix} (source_project_items=${params.executionContext.source_project_item_count}, sandbox_project_items=${params.executionContext.sandbox_project_item_count}).${mismatchHint}`)}function resolveLinkedTestPreflightResult(params){return resolveLinkedTestSafetyPreflightResult(params)||resolveLinkedTestTrustPreflightResult(params)||resolveUnboundPmContextFailure(params)||resolvePmContextMismatchFailure(params)||(params.options?.requireAssertionsForPm===!0&¶ms.executionContext.is_pm_command&&!hasLinkedTestAssertions(params.linkedTest)?buildLinkedTestConfigurationRefusalResult(params.linkedTest,params.executionContext,"Linked PM command requires assertions when --require-assertions-for-pm is enabled."):null)}function buildLinkedTestExecutionEnv(params){const effectiveDirectives=resolveEffectiveLinkedTestDirectives(params.runtimeDirectives,params.linkedTest),executionEnv={...process.env,SENTRY_ENVIRONMENT:"test"};return applyEnvDirectiveStage(executionEnv,params.runtimeDirectives),applyEnvDirectiveStage(executionEnv,{env_set:params.linkedTest.env_set??{},env_clear:params.linkedTest.env_clear??[]}),effectiveDirectives.shared_host_safe&&applySharedHostSafeDefaults(executionEnv),executionEnv.FORCE_COLOR="0",params.executionContext.pm_context_mode==="none"?delete executionEnv.PM_PATH:executionEnv.PM_PATH=params.executionContext.sandbox_project_pm_path,executionEnv.PM_GLOBAL_PATH=params.executionContext.sandbox_global_pm_path,params.executionContext.workspace_context_mode!=="source"&&(delete executionEnv.PM_BUILD_CONSUMER_LEASE,delete executionEnv.PM_BUILD_CONSUMER_LEASE_ROOT),params.executionContext.workspace_context_mode==="isolated"?(delete executionEnv.PM_SOURCE_WORKSPACE_ROOT,delete executionEnv.PM_SOURCE_PM_PATH,delete executionEnv[SOURCE_CONTEXT_ACCESS_ENV]):(executionEnv.PM_SOURCE_WORKSPACE_ROOT=params.executionContext.source_workspace_root,executionEnv.PM_SOURCE_PM_PATH=params.executionContext.workspace_context_mode==="snapshot"?params.executionContext.sandbox_project_pm_path:params.executionContext.source_project_pm_path,executionEnv[SOURCE_CONTEXT_ACCESS_ENV]="read_only"),executionEnv}function buildLinkedTestPassedResult(linkedTest,executionContext,execution,receipt){return{command:linkedTest.command,path:linkedTest.path,status:"passed",exit_code:0,execution_context:executionContext,stdout:execution.stdout,stderr:execution.stderr,...receipt?{execution_receipt:receipt}:{}}}function buildLinkedTestEmptyRunResult(params){return{command:params.linkedTest.command,path:params.linkedTest.path,status:"failed",exit_code:1,failure_category:"empty_run",execution_context:params.executionContext,stdout:params.execution.stdout,stderr:params.execution.stderr,error:`Linked test reported an empty test run (${params.emptyRunSignal.code}). Update the test selection so at least one test executes; unfiltered commands may opt out by omitting --fail-on-empty-test-run.`}}function buildLinkedTestCommandFailureResult(params){return{command:params.linkedTest.command,path:params.linkedTest.path,status:"failed",exit_code:resolveLinkedTestFailureExitCode(params.execution),failure_category:classifyLinkedTestFailure(params.execution),execution_context:params.executionContext,stdout:params.execution.stdout,stderr:params.execution.stderr,error:formatLinkedTestExecutionError(params.execution,params.timeoutMs)}}function buildLinkedTestPassedExecutionResult(params){const receipt=findLinkedTestExecutionReceipt(params.execution.stdout,params.execution.stderr);if(params.options?.failOnEmptyTestRun===!0||commandUsesTestNameFilter(params.linkedTest.command??"")){const emptyRunSignal=detectEmptyLinkedTestRun(params.execution.stdout,params.execution.stderr);if(emptyRunSignal)return buildLinkedTestEmptyRunResult({...params,emptyRunSignal});if(commandUsesTestNameFilter(params.linkedTest.command??"")&&!receipt)return buildLinkedTestEmptyRunResult({...params,emptyRunSignal:{code:"missing_positive_execution_receipt"}})}const assertionFailures=evaluateLinkedTestAssertions(params.linkedTest,params.execution.stdout,params.execution.stderr);return assertionFailures.length>0?buildLinkedTestAssertionFailureResult(params.linkedTest,params.executionContext,`Linked test assertion(s) failed: ${assertionFailures.join("; ")}`,params.execution):buildLinkedTestPassedResult(params.linkedTest,params.executionContext,params.execution,receipt)}async function runSingleLinkedTest(params){const command=params.linkedTest.command??"",timeoutMs=(params.linkedTest.timeout_seconds??params.defaultTimeoutSeconds??120)*1e3,execution=await runLinkedTestCommand(command,timeoutMs,buildLinkedTestExecutionEnv(params),{index:params.index+1,total:params.total,timeoutMs,command},params.progressMode,params.executionContext.working_directory);return execution.exitCode===0&&!execution.timedOut&&!execution.maxBufferExceeded?buildLinkedTestPassedExecutionResult({...params,execution}):buildLinkedTestCommandFailureResult({...params,execution,timeoutMs})}async function runLinkedTests(tests,defaultTimeoutSeconds,options){for(const test of tests)assertLinkedTestCommand(test.command);const results=[],sandboxRoot=await mkdtemp(path.join(tmpdir(),"pm-linked-test-")),layout=createLinkedTestSandboxLayout(sandboxRoot),runLevelPmContextMode=parsePmContextMode(options?.pmContext),runLevelWorkspaceContextMode=parseWorkspaceContextMode(options?.workspaceContext),progressMode=options?.progress===!0?"always":"auto",runtimeDirectives=resolveRuntimeDirectives(options?.envSet,options?.envClear,options?.sharedHostSafe),sourceRoots=options?.sourceRoots,sourceWorkspaceRoot=resolveLinkedTestSourceWorkspaceRoot(),includeTrackerData=linkedTestsRequireTrackerData(tests,runLevelPmContextMode,options),includeWorkspaceSnapshot=linkedTestsRequireWorkspaceSnapshot(tests,runLevelWorkspaceContextMode,options?.overrideLinkedWorkspaceContext===!0),currentSourceRef=await resolveLinkedTestSourceRef(sourceWorkspaceRoot);try{await initializeLinkedTestSandboxes(layout,runInit,includeTrackerData),await mkdir(layout.workspaceIsolatedRoot,{recursive:!0}),await seedLinkedTestSandboxesFromSource(layout,sourceRoots,includeTrackerData),includeWorkspaceSnapshot&&await seedLinkedTestWorkspaceSnapshot(sourceWorkspaceRoot,layout.workspaceSnapshotRoot,sourceRoots?.projectPmRoot,includeTrackerData);const counts=await countLinkedTestSandboxItems(layout,sourceRoots);for(let index=0;index<tests.length;index+=1){const linkedTest=tests[index],workspaceContextMode=resolveLinkedTestWorkspaceContextMode(linkedTest,runLevelWorkspaceContextMode,options?.overrideLinkedWorkspaceContext===!0),commandContext=await resolveLinkedTestCommandContext({linkedTest,layout,counts,sourceRoots,runLevelPmContextMode,options,requestedWorkspaceContextMode:runLevelWorkspaceContextMode,workspaceContextMode,currentSourceRef,sourceWorkspaceRoot}),preflightResult=resolveLinkedTestPreflightResult({linkedTest,executionContext:commandContext.executionContext,runLevelPmContextMode,linkedOverridePmContextMode:commandContext.linkedOverridePmContextMode,options});if(preflightResult){results.push(preflightResult);continue}results.push(await runSingleLinkedTest({linkedTest,index,total:tests.length,defaultTimeoutSeconds,runtimeDirectives,progressMode,executionContext:commandContext.executionContext,options}))}}finally{await rm(layout.root,{recursive:!0,force:!0,maxRetries:3,retryDelay:100})}return results}function countRemovedStoredTests(before,after){const remaining=[...after];return before.filter(entry=>{const index=remaining.findIndex(candidate=>linkedTestsHaveSameIdentity(candidate,entry));return index>=0&&remaining.splice(index,1),index<0}).length}async function readLinkedTestItem(params){const{id,pmRoot,settings,typeToFolder}=params,located=await locateItem(pmRoot,id,settings.id_prefix,settings.item_format,typeToFolder);if(!located)throw new PmCliError(`Item ${id} not found`,EXIT_CODE.NOT_FOUND);const loaded=await readLocatedItem(located,{schema:settings.schema});return{itemId:located.id,tests:loaded.document.metadata.tests??[],testRuns:loaded.document.metadata.test_runs??[],changed:!1,removed:0}}function appendMissingLinkedTests(current,additions){const next=[...current];for(const addition of additions)next.some(entry=>linkedTestsHaveSameIdentity(entry,addition))||next.push(addition);return next}function removeLinkedTestsBySelector(current,removals,removeIndexes){if(removals.length===0&&removeIndexes.length===0)return{tests:current,removed:0};const indexSet=new Set(removeIndexes),tests=current.filter((entry,index)=>indexSet.has(index+1)?!1:!removals.some(selector=>selector.kind==="command"?entry.command===selector.value:selector.kind==="path"?entry.path===selector.value:entry.command===selector.value||entry.path===selector.value));return{tests,removed:current.length-tests.length}}function applyLinkedTestMutations(previous,adds,removes,removeIndexes){return removeLinkedTestsBySelector(appendMissingLinkedTests(previous,adds),removes,removeIndexes)}function hasTestRuntimeDirectiveFlags(options){return[options.timeout!==void 0,options.progress===!0,(options.envSet?.length??0)>0,(options.envClear?.length??0)>0,options.sharedHostSafe===!0,options.pmContext!==void 0,options.overrideLinkedPmContext===!0,options.failOnContextMismatch===!0,options.failOnSkipped===!0,options.failOnEmptyTestRun===!0,options.requireAssertionsForPm===!0,options.checkContext===!0,options.autoPmContext===!0,options.workspaceContext!==void 0,options.overrideLinkedWorkspaceContext===!0,options.allowUntrustedLinkedTests===!0].some(Boolean)}function assertTestRunFlagUsage(options){if(hasTestRuntimeDirectiveFlags(options)&&options.run!==!0)throw new PmCliError("--timeout, --progress, --env-set, --env-clear, --shared-host-safe, --pm-context, --override-linked-pm-context, --workspace-context, --override-linked-workspace-context, --allow-untrusted-linked-tests, --fail-on-context-mismatch, --fail-on-skipped, --fail-on-empty-test-run, --require-assertions-for-pm, --check-context, and --auto-pm-context require --run",EXIT_CODE.USAGE);if(options.acknowledgeLinkedTests===!0&&options.run===!0)throw new PmCliError("--acknowledge-linked-tests records trust without executing commands; run it separately before --run",EXIT_CODE.USAGE);if((options.match!==void 0||options.onlyIndex!==void 0||options.onlyLast===!0)&&options.run!==!0)throw new PmCliError("--match, --only-index, and --only-last require --run",EXIT_CODE.USAGE)}async function resolveLinkedTestItem(params){const{id,options,pmRoot,settings,typeToFolder,adds,removes,removeIndexes}=params;if(adds.length===0&&removes.length===0&&removeIndexes.length===0)return readLinkedTestItem({id,pmRoot,settings,typeToFolder});let removed=0,before=[];const result=await mutateItem({pmRoot,settings,id,op:adds.length>0?"tests_add":"tests_remove",author:resolveAuthor(options.author,settings.author_default),message:options.message,force:options.force,skipNoop:!0,mutate(document){const previous=document.metadata.tests??[],mutation=applyLinkedTestMutations(previous,adds,removes,removeIndexes);if(admitLinkedTestRequest(()=>resolveTestRunOptions(options,mutation.tests)),removed=mutation.removed,(removes.length>0||removeIndexes.length>0)&&removed===0)throw new PmCliError("No linked tests matched the requested removal selector",EXIT_CODE.NOT_FOUND,{code:"linked_test_remove_no_match",unmatched:[...removes.map(entry=>`${entry.kind}=${entry.value}`),...removeIndexes.map(index=>`index=${index}`)],required:"List linked tests and retry with an exact command/path or a current 1-based --remove-index.",examples:[`pm test ${id} --list`,`pm test ${id} --remove-index 1`]});return document.metadata.tests=mutation.tests,before=previous,{changedFields:stableValueEquals(previous,mutation.tests)?[]:["tests"]}}}),tests=result.item.tests??[];return{itemId:result.item.id,tests,testRuns:result.item.test_runs??[],changed:result.changedFields.length>0,removed,written:result.changedFields.length>0?writtenLinkedEntries(before,tests):[],storedRemoved:countRemovedStoredTests(before,tests)}}function resolveTestRunOptions(options,tests){const pmContextMode=parsePmContextMode(options.pmContext);parseWorkspaceContextMode(options.workspaceContext),resolveRuntimeDirectives(options.envSet,options.envClear,options.sharedHostSafe);const selectorInput={match:options.match,onlyIndex:options.onlyIndex===void 0?void 0:parseOnlyIndexValue(options.onlyIndex),onlyLast:options.onlyLast},defaultTimeoutSeconds=options.timeout===void 0?void 0:parseOptionalNumber(options.timeout,"--timeout");if(defaultTimeoutSeconds!==void 0&&defaultTimeoutSeconds<=0)throw new PmCliError(`--timeout must be a positive number (got "${options.timeout}")`,EXIT_CODE.USAGE);assertTestRunFlagUsage(options);const runSelection=options.run===!0?resolveLinkedTestRunSelection(tests,selectorInput):void 0;if(runSelection)for(const test of runSelection.selected)assertLinkedTestCommand(test.command);return{defaultTimeoutSeconds,pmContextMode,runSelection,testsToRun:runSelection?.selected??tests}}async function executeSelectedLinkedTests(params){const{options,runOptions,pmRoot}=params;return options.run!==!0?[]:await runLinkedTests(runOptions.testsToRun,runOptions.defaultTimeoutSeconds,{progress:options.progress,envSet:options.envSet,envClear:options.envClear,sharedHostSafe:options.sharedHostSafe,pmContext:runOptions.pmContextMode,overrideLinkedPmContext:options.overrideLinkedPmContext,failOnContextMismatch:options.failOnContextMismatch,failOnEmptyTestRun:options.failOnEmptyTestRun===!0||(options.measure?.length??0)>0,requireAssertionsForPm:options.requireAssertionsForPm,checkContext:options.checkContext,autoPmContext:options.autoPmContext,workspaceContext:options.workspaceContext,overrideLinkedWorkspaceContext:options.overrideLinkedWorkspaceContext,pmRoot,allowUntrustedLinkedTests:options.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:params.untrustedLinkedTestsPolicyEnabled,sourceRoots:{projectPmRoot:pmRoot,globalPmRoot:resolveGlobalPmRoot(process.cwd())}})}function buildTestWarnings(options,runResults){const warnings=[];if(options.run===!0&&options.checkContext===!0){const preflight=summarizeContextPreflight(runResults);warnings.push(`context_preflight:checked_pm_commands=${preflight.checked_pm_commands};tracker_read_commands=${preflight.tracker_read_commands};mismatches=${preflight.mismatches};auto_remediated=${preflight.auto_remediated}`)}return warnings}function buildTrackedTestRunSummary(params){const summary=summarizeRunResultStatuses(params.runResults),parsedAttempt=Number.parseInt(process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim()??"",10),resumedFrom=process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM?.trim(),recordedAt=nowIso(),measurements=parseTestRunMeasurements(params.options.measure,recordedAt);return{run_id:resolveTrackedRunId("test"),kind:"test",status:summary.failed>0||params.failOnSkippedTriggered?"failed":"passed",started_at:params.runStartedAt,finished_at:recordedAt,recorded_at:recordedAt,attempt:Number.isFinite(parsedAttempt)&&parsedAttempt>=1?parsedAttempt:void 0,resumed_from:resumedFrom&&resumedFrom.length>0?resumedFrom:void 0,passed:summary.passed,failed:summary.failed,skipped:summary.skipped,fail_on_skipped_triggered:params.failOnSkippedTriggered?!0:void 0,measurements:measurements.length>0?measurements:void 0,executions:params.runResults.filter(result=>result.command?.trim()).slice(0,32).map(result=>({command:result.command.trim(),requested_pm_context_mode:result.execution_context?.requested_pm_context_mode,pm_context_mode:result.execution_context?.pm_context_mode,workspace_context_mode:result.execution_context?.workspace_context_mode,trust_reason:result.execution_context?.trust.reason}))}}async function recordTestRunSummary(params){const{options,pmRoot,settings,itemId,runStartedAt,runResults,failOnSkippedTriggered,warnings}=params;if(options.run!==!0||!runStartedAt)return;const entry=buildTrackedTestRunSummary({options,runStartedAt,runResults,failOnSkippedTriggered});if(settings.testing.record_results_to_items!==!0)return{entry,receipt:{recorded:!1,reason:"tracking_disabled",run_id:entry.run_id,recovery_command:"pm config project set test-result-tracking --policy enabled"}};try{return await appendTrackedTestRunSummary({pmRoot,settings,itemId,author:resolveAuthor(options.author,settings.author_default),message:`Track test run summary (${entry.run_id})`,entry}),{entry,receipt:{recorded:!0,reason:"recorded",run_id:entry.run_id}}}catch(error){if(isItemRevisionConflict(error))throw error;return warnings.push(`test_result_tracking_failed:${itemId}:${error instanceof Error?error.message:String(error)}`),{entry,receipt:{recorded:!1,reason:"write_failed",run_id:entry.run_id}}}}function buildTestMeasurementProjection(options,runs,recordedRun){let metricBelow;if(options.metricBelow!==void 0){const separator=options.metricBelow.indexOf("="),name=options.metricBelow.slice(0,separator).trim(),thresholdText=options.metricBelow.slice(separator+1).trim(),threshold=Number(thresholdText);if(separator<=0||name.length===0||thresholdText.length===0||!Number.isFinite(threshold))throw new PmCliError("--metric-below must use name=value",EXIT_CODE.USAGE);metricBelow=queryTestRunMeasurementsBelow(runs,name,threshold)}return{measurements:recordedRun?.measurements,metric_below:metricBelow,metric_diff:options.metricDiff===void 0?void 0:diffTestRunMeasurements(runs,options.metricDiff)}}async function maybeAcknowledgeLinkedTests(options,pmRoot,tests){if(options.acknowledgeLinkedTests===!0)return acknowledgeLinkedTests(pmRoot,tests,nowIso())}function projectTestResult(input){const{item,runResults,failureCategories,runSelection,failOnSkippedTriggered,warnings,recording,measurementProjection,restoreScope}=input,mutation=projectLinkedTestMutation(item,input.fullHistory),returned=selectReturnedLinkedTests(item,runSelection,mutation,restoreScope),{counts,receipts}=linkedCollectionMutationFields(mutation);return{ok:runResults.every(entry=>entry.status!=="failed"&&entry.status!=="refused")&&failOnSkippedTriggered!==!0,id:item.itemId,tests:returned.tests,...returned.omitted,run_results:runResults,...input.ran?{failure_categories:failureCategories}:{},selection:runSelection?{selector:runSelection.selector,requested:runSelection.requested,selected_indexes:runSelection.selected_indexes,selected_count:runSelection.selected_count,skipped_count:runSelection.skipped_count}:void 0,fail_on_skipped_triggered:failOnSkippedTriggered?!0:void 0,warnings:warnings.length>0?warnings:void 0,changed:item.changed||recording?.receipt.recorded===!0,...recording?{evidence_recording:recording.receipt}:{},count:returned.count,...item.removed>0?{removed:item.removed}:{},...counts,...measurementProjection,...receipts}}function selectReturnedLinkedTests(item,runSelection,mutation,restoreScope){return mutation!==void 0?{tests:mutation.entries,count:mutation.returned_count,omitted:{}}:runSelection!==void 0&&runSelection.selector!==null&&runSelection.skipped_count>0?{tests:runSelection.selected,count:item.tests.length,omitted:{tests_omitted:{count:item.tests.length-runSelection.selected.length,restore_with:renderLinkedTestRestoreCommand(item.itemId,restoreScope)}}}:{tests:item.tests,count:item.tests.length,omitted:{}}}function projectLinkedTestMutation(item,fullHistory){if(item.written!==void 0)return projectLinkedCollectionMutation({collectionKey:"tests",stored:item.tests,written:item.written,removedCount:item.storedRemoved,fullHistory})}function projectLinkedTestEdit(result,fullHistory){const edited=result.tests[result.updated_index-1],mutation=projectLinkedCollectionMutation({collectionKey:"tests",stored:result.tests,written:result.changed&&edited!==void 0?[edited]:[],removedCount:0,fullHistory}),{counts,receipts}=linkedCollectionMutationFields(mutation);return{...result,tests:mutation.entries,run_results:[],count:mutation.returned_count,...counts,...receipts}}async function runTest(id,options,global2){const edit=parseLinkedTestUpdateOptions(options);if(edit){assertLinkedTestEditUsage(options),assertTestRunFlagUsage(options),assertTestMeasurementRun(id,options,global2,resolvePmRoot(process.cwd(),global2.path));const result=await updateLinkedTest(id,{...edit,author:options.author,message:options.message,force:options.force},global2);return projectLinkedTestEdit(result,options.fullHistory===!0)}const stdinResolver=createStdinTokenResolver(),pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot);assertTestMeasurementRun(id,options,global2,pmRoot),parseTestRunMeasurements(options.measure,"validation"),buildTestMeasurementProjection(options,[],void 0);const typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()),resolvedAdds=await stdinResolver.resolveList(options.add,"--add"),resolvedAddJsons=await stdinResolver.resolveList(options.addJson,"--add-json"),resolvedRemoves=await stdinResolver.resolveList(options.remove,"--remove"),parsedAdds=[...parseAddEntries(resolvedAdds),...parseAddJsonEntries(resolvedAddJsons)],adds=await attachLinkedTestMutationProvenance(parsedAdds,resolveAuthor(options.author,settings.author_default),nowIso())??[],removes=parseRemoveEntries(resolvedRemoves),removeIndexes=parseRemoveIndexes(options.removeIndex),item=await resolveLinkedTestItem({id,options,pmRoot,settings,typeToFolder:typeRegistry.type_to_folder,adds,removes,removeIndexes}),runOptions=admitLinkedTestRequest(()=>resolveTestRunOptions(options,item.tests)),trustAcknowledgement=await maybeAcknowledgeLinkedTests(options,pmRoot,item.tests),runStartedAt=options.run===!0?nowIso():void 0,runResults=await executeSelectedLinkedTests({options,runOptions,pmRoot,untrustedLinkedTestsPolicyEnabled:settings.testing.allow_untrusted_linked_tests});assertTestMeasurementExecution(id,options,global2,pmRoot,runResults);const failureCategories=countFailureCategories(runResults),failOnSkippedTriggered=options.run===!0&&options.failOnSkipped===!0&&runResults.some(entry=>entry.status==="skipped"),warnings=buildTestWarnings(options,runResults);trustAcknowledgement&&warnings.push(`linked_test_trust_acknowledged:${trustAcknowledgement.acknowledged}`);const recording=await recordTestRunSummary({options,pmRoot,settings,itemId:item.itemId,runStartedAt,runResults,failOnSkippedTriggered,warnings}),runs=recording?.receipt.recorded?buildTrackedTestRunHistory([...item.testRuns,recording.entry]):item.testRuns,measurementProjection=buildTestMeasurementProjection(options,runs,recording?.entry);return projectTestResult({item,runResults,failureCategories,runSelection:runOptions.runSelection,failOnSkippedTriggered,warnings,recording,measurementProjection,restoreScope:resolveLinkedTestRestoreScope(global2,pmRoot),ran:options.run===!0,fullHistory:options.fullHistory===!0})}const _testOnlyTestCommand={buildLinkedTestExecutionContext,buildPmContextMismatchHint,commandInvokesPmCli,commandInvokesPmTrackerReadCommand,commandUsesTestNameFilter,copyIntoSandboxIfPresent,countLinkedTestItemFiles,ensureScope,evaluateLinkedTestAssertions,endLinkedTestProgress,extractPmInvocationArgsFromSegment,firstDirectTestRunnerSubcommand,formatLinkedTestExecutionError,hasLinkedTestAssertions,initializeLinkedTestSandboxes,linkedTestsRequireTrackerData,parseAddJsonEntries,parseLinkedTestTimeoutSeconds,parsePmContextMode,readJsonPathValue,resolveAuthor,resolveDirectRunnerSubcommand,resolveLinkedTestEffectiveContextMode,resolveLinkedTestFailureExitCode,resolveLinkedTestRequestedContextMode,resolveTestRunOptions,resolveTrackedRunId,runLinkedTestCommand,seedMissingLinkedTestSettingsHistory,seedLinkedTestSandbox,seedLinkedTestTrackerData,segmentInvokesRecursiveTestAll,splitJsonPathSegments,summarizeRunResultStatuses};export{_testOnlyTestCommand,classifyLinkedTestCommandSafety,classifyLinkedTestFailure,countFailureCategories,extractReferencedPmItemIdsFromCommand,resolveLinkedTestFailureExitCode,runLinkedTests,runTest,summarizeContextPreflight};
|
|
6
6
|
//# sourceMappingURL=execution.js.map
|
package/docs/AGENT_GUIDE.md
CHANGED
|
@@ -239,7 +239,7 @@ push tracker-only or changelog-only closeout directly to `main`: that direct
|
|
|
239
239
|
commit becomes the release candidate but has no reviewed analyzer provenance,
|
|
240
240
|
so `Release analyzer readiness (main)` must refuse it. Record external
|
|
241
241
|
post-merge observations on GitHub without changing repository state when no
|
|
242
|
-
tracked closeout update is required. See [Releasing](RELEASING.md#reviewed-delivery-closeout)
|
|
242
|
+
tracked closeout update is required. See [Releasing](https://github.com/unbraind/pm-cli/blob/main/docs/RELEASING.md#reviewed-delivery-closeout) (repository-only, excluded from npm)
|
|
243
243
|
for the release contract.
|
|
244
244
|
|
|
245
245
|
## Review and Analyzer Proof
|
|
@@ -269,7 +269,7 @@ run `inventory` once more to catch new or edited feedback, and require all
|
|
|
269
269
|
findings to have an explicit disposition. Compare each artifact's `revision`
|
|
270
270
|
and pass it as `--revision` when acknowledging feedback, so edited bodies get
|
|
271
271
|
fresh decisions and retrying a handled revision adds no duplicate reply.
|
|
272
|
-
See [Review Loop](PR_REVIEW_LOOP.md) for the revision and reply contracts.
|
|
272
|
+
See [Review Loop](https://github.com/unbraind/pm-cli/blob/main/docs/PR_REVIEW_LOOP.md) (repository-only, excluded from npm) for the revision and reply contracts.
|
|
273
273
|
|
|
274
274
|
## Documentation Rules for Agents
|
|
275
275
|
|
|
@@ -22,7 +22,13 @@ Dependency removal is lossless. `--dep-remove` rejects the same malformed
|
|
|
22
22
|
shorthand as `--dep`, and a selector that matches nothing returns the typed
|
|
23
23
|
`dependency_remove_no_match` refusal instead of a successful no-op. Exact
|
|
24
24
|
rows can be retired by selecting `id`, `kind` (or its input-only `type` alias),
|
|
25
|
-
`source_kind`, `author`, and `created_at`; omitted coordinates intentionally broaden the match.
|
|
25
|
+
`source_kind`, `author`, and `created_at`; omitted coordinates intentionally broaden the match.
|
|
26
|
+
`kind=<kind>` with no other key is the explicit kind-wide selector: it removes
|
|
27
|
+
every row of exactly that kind. An empty `id=` (an unset shell variable) and
|
|
28
|
+
any other id-less selector are refused rather than widened. Every update that removes rows names them in a
|
|
29
|
+
`dependencies_removed:<item>:<id>/<kind>,...` warning, including the rows a
|
|
30
|
+
`--unset blocked_by` scalar clear removes (only those naming the scalar's own
|
|
31
|
+
target; pm-4yxzvd). Exact
|
|
26
32
|
duplicate rows can still be normalized without delete-then-add risk by
|
|
27
33
|
re-adding the same identity; the mutation keeps one canonical row and never
|
|
28
34
|
removes the logical edge. Identity comparison includes normalized `id`, `kind`,
|
|
@@ -51,4 +51,4 @@ npm run release:verify-installed-agent -- --version "$CANDIDATE" --previous-vers
|
|
|
51
51
|
```
|
|
52
52
|
|
|
53
53
|
Set both versions. Windows `npm run` supplies npm's JavaScript entrypoint.
|
|
54
|
-
See [packed first run](PACKED_FIRST_RUN.md) and [release policy](RELEASING.md).
|
|
54
|
+
See [packed first run](PACKED_FIRST_RUN.md) and [release policy](https://github.com/unbraind/pm-cli/blob/main/docs/RELEASING.md) (repository-only, excluded from npm).
|