@unbrained/pm-cli 2026.9.27 → 2026.9.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (158) hide show
  1. package/.agents/skills/pm-developer/references/GRAPH_AND_RELATIONSHIPS.md +7 -6
  2. package/.agents/skills/pm-user/references/BACKLOG_SHAPING.md +1 -1
  3. package/.agents/skills/pm-user/references/ECOSYSTEM_PLANNING.md +26 -3
  4. package/.claude-plugin/marketplace.json +4 -6
  5. package/CHANGELOG.md +43 -0
  6. package/dist/cli/error-guidance.js +1 -1
  7. package/dist/cli/help-json-payload.js +2 -2
  8. package/dist/cli/main.js +2 -2
  9. package/dist/cli/register-operations.js +1 -1
  10. package/dist/cli/runtime/invocation-options.d.ts +3 -1
  11. package/dist/cli/runtime/invocation-options.js +1 -1
  12. package/dist/cli-bundle/bundle-manifest.json +151 -151
  13. package/dist/cli-bundle/chunks/{chunk-6OJVQ7SW.js → chunk-2AQKVJMW.js} +2 -2
  14. package/dist/cli-bundle/chunks/{chunk-TSF2LPIH.js → chunk-4DOL43PF.js} +2 -2
  15. package/dist/cli-bundle/chunks/{chunk-7TAGYNFP.js → chunk-5KEPG36D.js} +2 -2
  16. package/dist/cli-bundle/chunks/{chunk-IEP3VAT5.js → chunk-D32HVIB2.js} +2 -2
  17. package/dist/cli-bundle/chunks/{chunk-AUS6USO4.js → chunk-GP6QTYSD.js} +2 -2
  18. package/dist/cli-bundle/chunks/chunk-OTLIM22J.js +2 -0
  19. package/dist/cli-bundle/chunks/{chunk-LKGQUZ5M.js → chunk-P75SO5HO.js} +2 -2
  20. package/dist/cli-bundle/chunks/{chunk-4SLLCDFL.js → chunk-PJSQAWWQ.js} +64 -64
  21. package/dist/cli-bundle/chunks/{chunk-V5UGBYHN.js → chunk-S5A2UIRV.js} +62 -62
  22. package/dist/cli-bundle/chunks/chunk-SC6JHXFT.js +31 -0
  23. package/dist/cli-bundle/chunks/{chunk-3BTJ66CB.js → chunk-SEJ53XDN.js} +55 -55
  24. package/dist/cli-bundle/chunks/{chunk-OKVDVERQ.js → chunk-SJI55O65.js} +2 -2
  25. package/dist/cli-bundle/chunks/{chunk-JX6WCCHL.js → chunk-U3QJGJYN.js} +2 -2
  26. package/dist/cli-bundle/chunks/{register-list-query-6PAJ4PBU.js → register-list-query-R3ELWWPY.js} +2 -2
  27. package/dist/cli-bundle/chunks/{register-mutation-RZCXZXYS.js → register-mutation-WHXJXIHJ.js} +2 -2
  28. package/dist/cli-bundle/chunks/{register-operations-GK6VU2H2.js → register-operations-7ASWBYQG.js} +2 -2
  29. package/dist/cli-bundle/chunks/{register-setup-ASEMNMBF.js → register-setup-FDRTUG54.js} +2 -2
  30. package/dist/cli-bundle/focused-chunks/{chunk-QO4MTAEA.js → chunk-2O3QFI3G.js} +2 -2
  31. package/dist/cli-bundle/focused-chunks/{chunk-LBDWUHQD.js → chunk-4A4DO5ZT.js} +2 -2
  32. package/dist/cli-bundle/focused-chunks/chunk-5MC57KRC.js +2 -0
  33. package/dist/cli-bundle/focused-chunks/{chunk-NWRVNHAD.js → chunk-6OXJVE74.js} +17 -17
  34. package/dist/cli-bundle/focused-chunks/{chunk-MILJCOFJ.js → chunk-7URX7FMY.js} +2 -2
  35. package/dist/cli-bundle/focused-chunks/{chunk-OJRX6G22.js → chunk-AVP5C674.js} +2 -2
  36. package/dist/cli-bundle/focused-chunks/{chunk-SMADBUPL.js → chunk-AZE7KUHG.js} +2 -2
  37. package/dist/cli-bundle/focused-chunks/{chunk-GZD4ZYIB.js → chunk-DZVOCJFY.js} +14 -14
  38. package/dist/cli-bundle/focused-chunks/chunk-FBIRNSYP.js +75 -0
  39. package/dist/cli-bundle/focused-chunks/{chunk-NETVXIH5.js → chunk-IFBA3ZAT.js} +2 -2
  40. package/dist/cli-bundle/focused-chunks/{chunk-OJKJFDIG.js → chunk-K3AIMRIK.js} +2 -2
  41. package/dist/cli-bundle/focused-chunks/{chunk-DQ3MB7BO.js → chunk-KLKKCHWM.js} +2 -2
  42. package/dist/cli-bundle/focused-chunks/{chunk-PDVL7QYU.js → chunk-MRH4A542.js} +15 -15
  43. package/dist/cli-bundle/focused-chunks/{chunk-6UNKK3UH.js → chunk-NXQZMKW5.js} +2 -2
  44. package/dist/cli-bundle/focused-chunks/chunk-NY6FLQTN.js +2 -0
  45. package/dist/cli-bundle/focused-chunks/{chunk-NZAG7OKB.js → chunk-T4H6Q44B.js} +2 -2
  46. package/dist/cli-bundle/main.js +22 -22
  47. package/dist/cli-bundle/sdk-authoring.js +1 -1
  48. package/dist/cli-bundle/sdk-contracts.js +1 -1
  49. package/dist/cli-bundle/sdk-core.js +22 -21
  50. package/dist/cli-bundle/sdk-governance.js +1 -1
  51. package/dist/cli-bundle/sdk-graph.js +1 -1
  52. package/dist/cli-bundle/sdk-merge.js +51 -51
  53. package/dist/cli-bundle/sdk-query.js +1 -1
  54. package/dist/cli-bundle/sdk-runtime.js +1 -1
  55. package/dist/cli-bundle/sdk-testing.js +1 -1
  56. package/dist/cli-bundle/sdk.js +2 -2
  57. package/dist/core/diagnostics/remediation.js +1 -1
  58. package/dist/core/history/replay.js +1 -1
  59. package/dist/core/item/item-format.js +1 -1
  60. package/dist/core/output/mutation-projection.js +1 -1
  61. package/dist/core/store/settings.js +3 -3
  62. package/dist/core/telemetry/runtime.js +2 -2
  63. package/dist/sdk/cli-contracts/command-aliases.js +1 -1
  64. package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1
  65. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
  66. package/dist/sdk/completion/fish.js +3 -3
  67. package/dist/sdk/completion/zsh.js +3 -3
  68. package/dist/sdk/extension/copy-scope.d.ts +2 -2
  69. package/dist/sdk/extension/copy-scope.js +1 -1
  70. package/dist/sdk/extension/install-plan.js +1 -1
  71. package/dist/sdk/extension/install-runtime.js +2 -2
  72. package/dist/sdk/extension/static-inventory.js +1 -1
  73. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  74. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  75. package/dist/sdk/governance/health-merge-evidence.d.ts +18 -0
  76. package/dist/sdk/governance/health-merge-evidence.js +2 -0
  77. package/dist/sdk/governance/health.js +1 -1
  78. package/dist/sdk/index.d.ts +1 -0
  79. package/dist/sdk/index.js +1 -1
  80. package/dist/sdk/lifecycle/plan-mutation-receipt.d.ts +53 -0
  81. package/dist/sdk/lifecycle/plan-mutation-receipt.js +2 -0
  82. package/dist/sdk/lifecycle/plan.d.ts +3 -0
  83. package/dist/sdk/lifecycle/plan.js +1 -1
  84. package/dist/sdk/linked-artifacts.js +1 -1
  85. package/dist/sdk/merge/install.js +2 -2
  86. package/dist/sdk/output-projection.d.ts +1 -1
  87. package/dist/sdk/output-projection.js +1 -1
  88. package/dist/sdk/public-surface.json +1 -1
  89. package/dist/sdk/read-output-budget.d.ts +1 -1
  90. package/dist/sdk/read-output-budget.js +1 -1
  91. package/dist/sdk/read-output-contracts.js +1 -1
  92. package/dist/sdk/runtime/actions.js +1 -1
  93. package/dist/sdk/runtime-input.d.ts +2 -0
  94. package/dist/sdk/runtime-input.js +1 -1
  95. package/dist/sdk/runtime.js +1 -1
  96. package/dist/sdk/similarity-scoring.js +1 -1
  97. package/dist/sdk/telemetry.d.ts +2 -0
  98. package/dist/sdk/telemetry.js +3 -1
  99. package/dist/sdk/test/execution.d.ts +11 -0
  100. package/dist/sdk/test/execution.js +2 -2
  101. package/dist/sdk/test/parsers.d.ts +1 -1
  102. package/dist/sdk/test/parsers.js +1 -1
  103. package/dist/types.d.ts +3 -3
  104. package/dist/types.js +1 -1
  105. package/docs/AGENT_READ_AND_TEST_RECEIPTS.md +21 -0
  106. package/docs/CLAUDE_CODE_PLUGIN.md +12 -7
  107. package/docs/CLI_GRAMMAR.md +18 -1
  108. package/docs/CONFIGURATION.md +2 -0
  109. package/docs/ECOSYSTEM_PLANNING_REVIEW.md +270 -0
  110. package/docs/PACKAGE_EVIDENCE.md +18 -7
  111. package/docs/README.md +2 -0
  112. package/docs/SDK_EVIDENCE_TRACEABILITY.md +34 -0
  113. package/docs/TESTING.md +14 -3
  114. package/docs/agent-task-token-baseline.json +28 -2
  115. package/docs/agent-task-transcripts.json +137 -14
  116. package/docs/ecosystem-review-2026-09-28.json +3159 -0
  117. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +7 -3
  118. package/marketplace.json +4 -6
  119. package/package.json +5 -5
  120. package/packages/pm-beads/package.json +1 -1
  121. package/packages/pm-calendar/package.json +1 -1
  122. package/packages/pm-command-kit/package.json +1 -1
  123. package/packages/pm-digital-twin/package.json +1 -1
  124. package/packages/pm-governance-audit/package.json +1 -1
  125. package/packages/pm-guide-shell/package.json +1 -1
  126. package/packages/pm-kanban/package.json +1 -1
  127. package/packages/pm-lifecycle-hooks/package.json +1 -1
  128. package/packages/pm-linked-test-adapters/package.json +1 -1
  129. package/packages/pm-search-advanced/package.json +1 -1
  130. package/packages/pm-templates/package.json +1 -1
  131. package/packages/pm-todos/package.json +1 -1
  132. package/packages/pm-vcs/package.json +1 -1
  133. package/plugins/pm-claude/.claude-plugin/plugin.json +4 -2
  134. package/plugins/pm-claude/.mcp.json +1 -2
  135. package/plugins/pm-claude/README.md +7 -7
  136. package/plugins/pm-claude/package.json +2 -2
  137. package/plugins/pm-claude/{commands/pm-calendar.md → skills/pm-calendar/SKILL.md} +1 -0
  138. package/plugins/pm-claude/{commands/pm-close-task.md → skills/pm-close-task/SKILL.md} +1 -0
  139. package/plugins/pm-claude/{commands/pm-init.md → skills/pm-init/SKILL.md} +2 -1
  140. package/plugins/pm-claude/{commands/pm-list.md → skills/pm-list/SKILL.md} +2 -1
  141. package/plugins/pm-claude/{commands/pm-new.md → skills/pm-new/SKILL.md} +1 -0
  142. package/plugins/pm-claude/{commands/pm-search.md → skills/pm-search/SKILL.md} +1 -0
  143. package/plugins/pm-claude/{commands/pm-start-task.md → skills/pm-start-task/SKILL.md} +1 -0
  144. package/plugins/pm-claude/{commands/pm-status.md → skills/pm-status/SKILL.md} +1 -0
  145. package/plugins/pm-claude/{commands/pm-triage.md → skills/pm-triage/SKILL.md} +1 -0
  146. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  147. package/plugins/pm-codex/package.json +2 -2
  148. package/plugins/pm-codex/plugin.json +1 -1
  149. package/dist/cli-bundle/chunks/chunk-4UPZLUT2.js +0 -29
  150. package/dist/cli-bundle/chunks/chunk-LC6WEA5U.js +0 -2
  151. package/dist/cli-bundle/focused-chunks/chunk-6J2YCGSN.js +0 -75
  152. package/dist/cli-bundle/focused-chunks/chunk-E7LYK7V5.js +0 -2
  153. package/dist/cli-bundle/focused-chunks/chunk-KMPKKSA6.js +0 -2
  154. package/plugins/pm-claude/commands/pm-audit.md +0 -38
  155. package/plugins/pm-claude/commands/pm-developer.md +0 -38
  156. package/plugins/pm-claude/commands/pm-planner.md +0 -54
  157. package/plugins/pm-claude/commands/pm-release.md +0 -41
  158. package/plugins/pm-claude/commands/pm-workflow.md +0 -49
@@ -1,7 +1,7 @@
1
- !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="cbc188f2-47f8-5e71-ab9f-feaac4ebf257")}catch(e2){}})();import{readJsonPathValue,splitJsonPathSegments}from"./json-path.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{acknowledgeLinkedTests,attachLinkedTestMutationProvenance,resolveLinkedTestSourceRef,resolveLinkedTestSourceWorkspaceRoot,resolveLinkedTestTrust}from"./trust.js";const TEST_OUTPUT_MAX_BUFFER_BYTES=20*1024*1024;const DEFAULT_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS=3e3;const DEFAULT_LINKED_TEST_HEARTBEAT_INTERVAL_MS=1e4;const DEFAULT_LINKED_TEST_PIPE_CLOSE_GRACE_MS=5e3;const MAX_LINKED_TEST_COMMAND_LABEL_LENGTH=120;const LINKED_TEST_TRACKER_DIRS_TO_SKIP=new Set(["locks","extensions","runtime"]);const LINKED_TEST_ITEM_COUNT_DIRS_TO_SKIP=new Set(["history","index","search","extensions","locks","runtime"]);const 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];const LINKED_TEST_LOCK_ACQUISITION_PATTERN=/\b(?:could not|failed to|unable to)\s+acquire\b[^\n.]*\block\b/i;const LINKED_TEST_LOCK_CONTENTION_CONTEXT_PATTERN=/\b(?:already running|timed?\s*out|timeout|held by another|lock\s+is\s+held)\b/i;const 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);if(!Number.isFinite(parsed)||parsed<=0){return fallback}return 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();if(fromEnv&&fromEnv.length>0){return fromEnv}return`${kind}-local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function summarizeRunResultStatuses(results){let passed=0;let failed=0;let skipped=0;for(const entry of results){if(entry.status==="passed"){passed+=1;continue}if(entry.status==="failed"){failed+=1;continue}skipped+=1}return{passed,failed,skipped}}function summarizeContextPreflight(runResults){let checkedPmCommands=0;let trackerReadCommands=0;let mismatches=0;let autoRemediated=0;for(const result of runResults){const context=result.execution_context;if(!context||context.is_pm_command!==true){continue}checkedPmCommands+=1;if(context.is_pm_tracker_read_command===true){trackerReadCommands+=1}if(context.mismatch_detected===true){mismatches+=1}if(context.auto_pm_context_applied===true){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){if(overrideLinkedMode){return runLevelMode}return parseLinkedTestWorkspaceContextMode(linkedTest.workspace_context_mode,"linked test")??runLevelMode}function resolveLinkedTestRequestedContextMode(linkedTest,runLevelMode,overrideLinkedPmContext){if(overrideLinkedPmContext){return runLevelMode}if(typeof linkedTest.pm_context_mode!=="string"||linkedTest.pm_context_mode.trim().length===0){return runLevelMode}return parsePmContextMode(linkedTest.pm_context_mode)}function resolveLinkedTestEffectiveContextMode(requestedMode,isPmTrackerReadCommand){if(requestedMode==="auto"){return isPmTrackerReadCommand?"tracker":"schema"}return requestedMode}function hasLinkedTestAssertions(linkedTest){return Object.entries(linkedTest).filter(([key])=>key.startsWith("assert_")).some(([,value])=>{if(value===void 0||value===null)return false;if(Array.isArray(value))return value.length>0;if(typeof value==="object")return Object.keys(value).length>0;if(typeof value==="string")return value.trim().length>0;return true})}function buildPmContextMismatchHint(params){const{executionContext,runLevelPmContextMode,linkedOverridePmContextMode}=params;if(!executionContext.is_pm_tracker_read_command||!executionContext.mismatch_detected){return""}if(runLevelPmContextMode==="tracker"&&linkedOverridePmContextMode==="schema"){return" 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."}if(executionContext.pm_context_mode==="schema"){return" 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."}return""}function mergeEnvSetDirectives(entries,optionName){const merged={};if(!entries){return merged}for(const entry of entries){const parsed=parseLinkedTestEnvSetValue(entry,optionName);if(!parsed){continue}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);if(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,firstPmSubcommand,extractPmInvocationArgsFromSegment,isPmCliPackageToken,isPmCliScriptToken,isPmExecutableToken,parseLauncherSubcommand,parseNpmExecCommand,parseNpxCommand,parsePnpmDlxCommand,resolvePmSubcommandContext,splitNormalizedCommandSegments,stripLeadingEnvAssignments}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 false}const context=resolvePmSubcommandContext(invocationArgs);if(!context){return false}return PM_TRACKER_READ_SUBCOMMANDS.has(context.subcommand)})}function resolveDirectRunnerSubcommand(parsed){if(!parsed){return void 0}if(!SCRIPT_RUN_SUBCOMMANDS.has(parsed.subcommand)){return parsed.subcommand}return parseLauncherSubcommand(parsed.args,SCRIPT_RUN_FLAGS_WITH_VALUE)?.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))}return void 0}function isDirectTestRunnerSubcommand(token){if(!token){return false}return token==="vitest"||token==="test"||token.startsWith("test:")}function parsedLauncherInvokesRecursiveTestAll(parsed){if(!parsed){return false}if(!isPmExecutableToken(parsed.command)&&!isPmCliPackageToken(parsed.command)){return false}return firstPmSubcommand(parsed.args)==="test-all"}const SHELL_COMMAND_FLAG_PATTERNS=new Map([...["sh","bash","dash","zsh"].map(executable=>[executable,/^(?:-c|-[a-z]*c[a-z]*)$/u]),...["cmd","cmd.exe"].map(executable=>[executable,/^\/[ck]$/u]),...["powershell","powershell.exe","pwsh","pwsh.exe"].map(executable=>[executable,/^-(?:c|command)$/u])]);const PACKAGE_EXEC_EXECUTABLES=new Set(["npx","bunx"]);function segmentInvokesRecursiveTestAll(segment){const rawTokens=segment.split(" ").filter(token=>token.length>0);const tokens=stripLeadingEnvAssignments(rawTokens);if(tokens.length===0){return false}const[executable,...args]=tokens;const shellCommandFlagPattern=SHELL_COMMAND_FLAG_PATTERNS.get(executable);if(shellCommandFlagPattern){const commandFlagIndex=args.findIndex(arg=>shellCommandFlagPattern.test(arg));return commandFlagIndex>=0?segmentInvokesRecursiveTestAll(args.slice(commandFlagIndex+1).join(" ")):false}if(isPmExecutableToken(executable)||isPmCliScriptToken(executable)){return firstPmSubcommand(args)==="test-all"}if(executable==="node"&&args.length>0&&isPmCliScriptToken(args[0])){return firstPmSubcommand(args.slice(1))==="test-all"}if(PACKAGE_EXEC_EXECUTABLES.has(executable)){return parsedLauncherInvokesRecursiveTestAll(parseNpxCommand(args))}if(executable==="pnpm"){return parsedLauncherInvokesRecursiveTestAll(parsePnpmDlxCommand(args))}if(executable==="npm"){return parsedLauncherInvokesRecursiveTestAll(parseNpmExecCommand(args))}return false}function invokesRecursiveTestAllCommand(command){const normalized=normalizeCommandForValidation(command);return splitNormalizedCommandSegments(normalized).some(segment=>segmentInvokesRecursiveTestAll(segment))}function assertNoRecursiveTestAllCommand(command){if(!invokesRecursiveTestAllCommand(command))return;throw new PmCliError('Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.',EXIT_CODE.USAGE)}function normalizeCommandForValidation(command){return command.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase()}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);const tokens=stripLeadingEnvAssignments(rawTokens);if(tokens.length===0){return false}const[executable,...args]=tokens;const 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(" "))}if(executable==="vitest"||executable.endsWith("/vitest")||executable.endsWith("/vitest.mjs")){return true}if(executable==="node"){return nodeArgsInvokeDirectTestRunner(args)}return 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){if(executable==="npx"||executable==="bunx"){return isDirectTestRunnerSubcommand(parseNpxCommand(args)?.command)}if(executable==="pnpm"||executable==="npm"){return isDirectTestRunnerSubcommand((executable==="pnpm"?parsePnpmDlxCommand(args):parseNpmExecCommand(args))?.command)||isDirectTestRunnerSubcommand(firstDirectTestRunnerSubcommand(executable,args))}return(executable==="yarn"||executable==="bun")&&isDirectTestRunnerSubcommand(firstDirectTestRunnerSubcommand(executable,args))}function classifyLinkedTestCommandSafety(command){const normalized=normalizeCommandForValidation(command);const segments=splitNormalizedCommandSegments(normalized);const directRunner=segments.some(segment=>!commandUsesSandboxRunner(segment)&&segmentInvokesDirectTestRunner(segment));const sandboxRunner=segments.some(commandUsesSandboxRunner);return{accepted:true,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 void 0;return'Linked test command skipped: Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.'}function parseAddEntries(raw){if(!raw)return[];return raw.map(parseAddEntry)}function parseAddEntry(entry){const trimmed=entry.trim();const kv=looksLikeStructuredLinkedTestEntry(trimmed)?normalizeStructuredLinkedTestEntry(parseCsvKv(entry,"--add"),"--add"):{command:trimmed};const 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)}assertNoRecursiveTestAllCommand(command);return{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 void 0;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){if(!raw)return[];return 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){if(!raw)return[];return 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");const kind=kv.path!==void 0?"path":"command";const 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){if(!raw)return[];return[...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," ");if(normalized.length<=MAX_LINKED_TEST_COMMAND_LABEL_LENGTH){return normalized}return`${normalized.slice(0,MAX_LINKED_TEST_COMMAND_LABEL_LENGTH-3)}...`}function shouldEmitLinkedTestProgress(mode){if(mode==="off"){return false}if(mode==="always"){return true}return process.stderr.isTTY===true}function emitLinkedTestProgress(message){try{process.stderr.write(`${message}
1
+ !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="04ea3495-92b7-5518-b06c-a1668d368d66")}catch(e2){}})();import{readJsonPathValue,splitJsonPathSegments}from"./json-path.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{acknowledgeLinkedTests,attachLinkedTestMutationProvenance,resolveLinkedTestSourceRef,resolveLinkedTestSourceWorkspaceRoot,resolveLinkedTestTrust}from"./trust.js";const TEST_OUTPUT_MAX_BUFFER_BYTES=20*1024*1024;const DEFAULT_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS=3e3;const DEFAULT_LINKED_TEST_HEARTBEAT_INTERVAL_MS=1e4;const DEFAULT_LINKED_TEST_PIPE_CLOSE_GRACE_MS=5e3;const MAX_LINKED_TEST_COMMAND_LABEL_LENGTH=120;const LINKED_TEST_TRACKER_DIRS_TO_SKIP=new Set(["locks","extensions","runtime"]);const LINKED_TEST_ITEM_COUNT_DIRS_TO_SKIP=new Set(["history","index","search","extensions","locks","runtime"]);const 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];const LINKED_TEST_LOCK_ACQUISITION_PATTERN=/\b(?:could not|failed to|unable to)\s+acquire\b[^\n.]*\block\b/i;const LINKED_TEST_LOCK_CONTENTION_CONTEXT_PATTERN=/\b(?:already running|timed?\s*out|timeout|held by another|lock\s+is\s+held)\b/i;const 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);if(!Number.isFinite(parsed)||parsed<=0){return fallback}return 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();if(fromEnv&&fromEnv.length>0){return fromEnv}return`${kind}-local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function summarizeRunResultStatuses(results){let passed=0;let failed=0;let skipped=0;for(const entry of results){if(entry.status==="passed"){passed+=1;continue}if(entry.status==="failed"){failed+=1;continue}skipped+=1}return{passed,failed,skipped}}function summarizeContextPreflight(runResults){let checkedPmCommands=0;let trackerReadCommands=0;let mismatches=0;let autoRemediated=0;for(const result of runResults){const context=result.execution_context;if(!context||context.is_pm_command!==true){continue}checkedPmCommands+=1;if(context.is_pm_tracker_read_command===true){trackerReadCommands+=1}if(context.mismatch_detected===true){mismatches+=1}if(context.auto_pm_context_applied===true){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){if(overrideLinkedMode){return runLevelMode}return parseLinkedTestWorkspaceContextMode(linkedTest.workspace_context_mode,"linked test")??runLevelMode}function resolveLinkedTestRequestedContextMode(linkedTest,runLevelMode,overrideLinkedPmContext){if(overrideLinkedPmContext){return runLevelMode}if(typeof linkedTest.pm_context_mode!=="string"||linkedTest.pm_context_mode.trim().length===0){return runLevelMode}return parsePmContextMode(linkedTest.pm_context_mode)}function resolveLinkedTestEffectiveContextMode(requestedMode,isPmTrackerReadCommand){if(requestedMode==="auto"){return isPmTrackerReadCommand?"tracker":"schema"}return requestedMode}function hasLinkedTestAssertions(linkedTest){return Object.entries(linkedTest).filter(([key])=>key.startsWith("assert_")).some(([,value])=>{if(value===void 0||value===null)return false;if(Array.isArray(value))return value.length>0;if(typeof value==="object")return Object.keys(value).length>0;if(typeof value==="string")return value.trim().length>0;return true})}function buildPmContextMismatchHint(params){const{executionContext,runLevelPmContextMode,linkedOverridePmContextMode}=params;if(!executionContext.is_pm_tracker_read_command||!executionContext.mismatch_detected){return""}if(runLevelPmContextMode==="tracker"&&linkedOverridePmContextMode==="schema"){return" 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."}if(executionContext.pm_context_mode==="schema"){return" 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."}return""}function mergeEnvSetDirectives(entries,optionName){const merged={};if(!entries){return merged}for(const entry of entries){const parsed=parseLinkedTestEnvSetValue(entry,optionName);if(!parsed){continue}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);if(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,firstPmSubcommand,extractPmInvocationArgsFromSegment,isPmCliPackageToken,isPmCliScriptToken,isPmExecutableToken,parseLauncherSubcommand,parseNpmExecCommand,parseNpxCommand,parsePnpmDlxCommand,resolvePmSubcommandContext,splitNormalizedCommandSegments,stripLeadingEnvAssignments}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 false}const context=resolvePmSubcommandContext(invocationArgs);if(!context){return false}return PM_TRACKER_READ_SUBCOMMANDS.has(context.subcommand)})}function resolveDirectRunnerSubcommand(parsed){if(!parsed){return void 0}if(!SCRIPT_RUN_SUBCOMMANDS.has(parsed.subcommand)){return parsed.subcommand}return parseLauncherSubcommand(parsed.args,SCRIPT_RUN_FLAGS_WITH_VALUE)?.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))}return void 0}function isDirectTestRunnerSubcommand(token){if(!token){return false}return token==="vitest"||token==="test"||token.startsWith("test:")}function parsedLauncherInvokesRecursiveTestAll(parsed){if(!parsed){return false}if(!isPmExecutableToken(parsed.command)&&!isPmCliPackageToken(parsed.command)){return false}return firstPmSubcommand(parsed.args)==="test-all"}const SHELL_COMMAND_FLAG_PATTERNS=new Map([...["sh","bash","dash","zsh"].map(executable=>[executable,/^(?:-c|-[a-z]*c[a-z]*)$/u]),...["cmd","cmd.exe"].map(executable=>[executable,/^\/[ck]$/u]),...["powershell","powershell.exe","pwsh","pwsh.exe"].map(executable=>[executable,/^-(?:c|command)$/u])]);const PACKAGE_EXEC_EXECUTABLES=new Set(["npx","bunx"]);function segmentInvokesRecursiveTestAll(segment){const rawTokens=segment.split(" ").filter(token=>token.length>0);const tokens=stripLeadingEnvAssignments(rawTokens);if(tokens.length===0){return false}const[executable,...args]=tokens;const shellCommandFlagPattern=SHELL_COMMAND_FLAG_PATTERNS.get(executable);if(shellCommandFlagPattern){const commandFlagIndex=args.findIndex(arg=>shellCommandFlagPattern.test(arg));return commandFlagIndex>=0?segmentInvokesRecursiveTestAll(args.slice(commandFlagIndex+1).join(" ")):false}if(isPmExecutableToken(executable)||isPmCliScriptToken(executable)){return firstPmSubcommand(args)==="test-all"}if(executable==="node"&&args.length>0&&isPmCliScriptToken(args[0])){return firstPmSubcommand(args.slice(1))==="test-all"}if(PACKAGE_EXEC_EXECUTABLES.has(executable)){return parsedLauncherInvokesRecursiveTestAll(parseNpxCommand(args))}if(executable==="pnpm"){return parsedLauncherInvokesRecursiveTestAll(parsePnpmDlxCommand(args))}if(executable==="npm"){return parsedLauncherInvokesRecursiveTestAll(parseNpmExecCommand(args))}return false}function invokesRecursiveTestAllCommand(command){const normalized=normalizeCommandForValidation(command);return splitNormalizedCommandSegments(normalized).some(segment=>segmentInvokesRecursiveTestAll(segment))}function assertNoRecursiveTestAllCommand(command){if(!invokesRecursiveTestAllCommand(command))return;throw new PmCliError('Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.',EXIT_CODE.USAGE)}function normalizeCommandForValidation(command){return command.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase()}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);const tokens=stripLeadingEnvAssignments(rawTokens);if(tokens.length===0){return false}const[executable,...args]=tokens;const 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(" "))}if(executable==="vitest"||executable.endsWith("/vitest")||executable.endsWith("/vitest.mjs")){return true}if(executable==="node"){return nodeArgsInvokeDirectTestRunner(args)}return 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){if(executable==="npx"||executable==="bunx"){return isDirectTestRunnerSubcommand(parseNpxCommand(args)?.command)}if(executable==="pnpm"||executable==="npm"){return isDirectTestRunnerSubcommand((executable==="pnpm"?parsePnpmDlxCommand(args):parseNpmExecCommand(args))?.command)||isDirectTestRunnerSubcommand(firstDirectTestRunnerSubcommand(executable,args))}return(executable==="yarn"||executable==="bun")&&isDirectTestRunnerSubcommand(firstDirectTestRunnerSubcommand(executable,args))}function classifyLinkedTestCommandSafety(command){const normalized=normalizeCommandForValidation(command);const segments=splitNormalizedCommandSegments(normalized);const directRunner=segments.some(segment=>!commandUsesSandboxRunner(segment)&&segmentInvokesDirectTestRunner(segment));const sandboxRunner=segments.some(commandUsesSandboxRunner);return{accepted:true,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 void 0;return'Linked test command skipped: Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.'}function parseAddEntries(raw){if(!raw)return[];return raw.map(parseAddEntry)}function parseAddEntry(entry){const trimmed=entry.trim();const kv=looksLikeStructuredLinkedTestEntry(trimmed)?normalizeStructuredLinkedTestEntry(parseCsvKv(entry,"--add"),"--add"):{command:trimmed};const 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)}assertNoRecursiveTestAllCommand(command);return{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 void 0;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){if(!raw)return[];return 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){if(!raw)return[];return 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");const kind=kv.path!==void 0?"path":"command";const 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){if(!raw)return[];return[...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," ");if(normalized.length<=MAX_LINKED_TEST_COMMAND_LABEL_LENGTH){return normalized}return`${normalized.slice(0,MAX_LINKED_TEST_COMMAND_LABEL_LENGTH-3)}...`}function shouldEmitLinkedTestProgress(mode){if(mode==="off"){return false}if(mode==="always"){return true}return process.stderr.isTTY===true}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);const 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());heartbeat.unref?.();return heartbeat}function endLinkedTestProgress(context,executionResult,startedAt,mode){if(!shouldEmitLinkedTestProgress(mode)){return}const commandLabel=summarizeLinkedTestCommand(context.command);const elapsedMs=Date.now()-startedAt;const failed=executionResult.timedOut||executionResult.maxBufferExceeded||executionResult.exitCode!==0;const statusLabel=failed?"failed":"passed";const reasonTokens=[];if(executionResult.timedOut){reasonTokens.push("reason=timeout")}if(executionResult.maxBufferExceeded){reasonTokens.push("reason=max_buffer")}if(executionResult.outputTruncated){reasonTokens.push("output=truncated")}if(executionResult.signal){reasonTokens.push(`signal=${executionResult.signal}`)}const exitLabel=executionResult.exitCode===null?"null":String(executionResult.exitCode);const 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){return}if(process.platform==="win32"){await new Promise(resolve=>{const killer=spawn("taskkill",["/pid",String(pid),"/T","/F"],{stdio:"ignore",windowsHide:true});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){if(timers.heartbeat){clearInterval(timers.heartbeat)}if(timers.timedOutTimer){clearTimeout(timers.timedOutTimer);timers.timedOutTimer=null}if(timers.forceKillTimer){clearTimeout(timers.forceKillTimer);timers.forceKillTimer=null}}function createLinkedTestTerminationRequester(child,timers){let terminationRequested=false;return async()=>{if(terminationRequested){return}terminationRequested=true;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(()=>{void killProcessTree(pid)},linkedTestTimeoutForceKillDelayMs());timers.forceKillTimer.unref?.()}}function waitForLinkedTestChildClose(child){return new Promise(resolve=>{let settled=false;let pipeCloseGraceTimer=null;const settle=(value,destroyPipes=false)=>{if(settled){return}settled=true;if(pipeCloseGraceTimer){clearTimeout(pipeCloseGraceTimer);pipeCloseGraceTimer=null}if(destroyPipes){child.stdin?.destroy();child.stdout?.destroy();child.stderr?.destroy()}resolve(value)};child.on("exit",(exitCode,exitSignal)=>{if(settled){return}pipeCloseGraceTimer=setTimeout(()=>{settle({code:exitCode,signal:exitSignal},true)},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:true,windowsHide:true,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;const retainedBytes=Math.min(size,TEST_OUTPUT_MAX_BUFFER_BYTES);const buffer=Buffer.alloc(retainedBytes);if(retainedBytes>0){await handle.read(buffer,0,retainedBytes,0)}return{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();const captureRoot=await mkdtemp(path.join(tmpdir(),"pm-linked-test-output-"));try{const stdoutPath=path.join(captureRoot,"stdout.log");const stderrPath=path.join(captureRoot,"stderr.log");const[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){await Promise.all([stdoutHandle.close(),stderrHandle.close()]);throw 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};const requestTermination=createLinkedTestTerminationRequester(child,timers);let timedOut=false;timers.timedOutTimer=setTimeout(()=>{timedOut=true;void requestTermination()},timeoutMs);timers.timedOutTimer.unref?.();const{code,signal}=await childClose;clearLinkedTestTimers(timers);const[stdout,stderr]=await Promise.all([readLinkedTestCapture(stdoutPath),readLinkedTestCapture(stderrPath)]);const outputTruncated=stdout.truncated||stderr.truncated;const 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
  `:"";const executionResult={stdout:`${stdout.text}${truncationNotice}`,stderr:stderr.text,exitCode:code,signal,timedOut,maxBufferExceeded:false,outputTruncated,spawnError};endLinkedTestProgress(progressContext,executionResult,startedAt,progressMode);return executionResult}finally{await rm(captureRoot,{recursive:true,force:true})}}function formatLinkedTestExecutionError(result,timeoutMs){const details=[];if(result.maxBufferExceeded){details.push(`Linked test output exceeded maxBuffer=${TEST_OUTPUT_MAX_BUFFER_BYTES} bytes. Reduce output volume or split the command.`)}if(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;const baseMessage=result.spawnError?.trim()||signalMessage||"Linked test command failed.";if(details.length===0){return baseMessage}return`${baseMessage} ${details.join(" ")}`}function hasInfraCollisionSignal(result){const combined=[result.spawnError??"",result.stderr,result.stdout].join("\n");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){if(hasInfraCollisionSignal(result)){return"infra_collision"}if(result.timedOut){return"timeout"}if(result.maxBufferExceeded){return"max_buffer"}if(result.spawnError){return"spawn_error"}if(result.signal){return"signal"}return"assertion_failure"}function createEmptyFailureCategoryCounts(){return{infra_collision:0,trust_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){if(result.status!=="failed"||!result.failure_category){continue}counts[result.failure_category]+=1}return counts}function applyEnvDirectiveStage(env,directives){for(const[key,value]of Object.entries(directives.env_set)){if(LINKED_TEST_PROTECTED_ENV_KEYS.has(key.toUpperCase())){continue}env[key]=value}for(const key of directives.env_clear){if(LINKED_TEST_PROTECTED_ENV_KEYS.has(key.toUpperCase())){continue}delete env[key]}}function applySharedHostSafeDefaults(env){if(env.PORT===void 0){env.PORT="0"}if(env.HOST===void 0){env.HOST="127.0.0.1"}if(env.PM_SHARED_HOST_SAFE===void 0){env.PM_SHARED_HOST_SAFE="1"}if(env.PLAYWRIGHT_HTML_OPEN===void 0){env.PLAYWRIGHT_HTML_OPEN="never"}if(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};const envClear=[...new Set([...runtimeDirectives.env_clear,...linkedTest.env_clear??[]])];const 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===true}}async function copyIntoSandboxIfPresent(sourcePath,targetPath,recursive=false,makeDirectory=mkdir){if(!await pathExists(sourcePath)){return}try{await withHostEnvironmentBoundary("seed_linked_test",async()=>{await makeDirectory(path.dirname(targetPath),{recursive:true});if(recursive){await cp(sourcePath,targetPath,{recursive:true,force:true});return}await cp(sourcePath,targetPath,{force:true})},{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){await copyIntoSandboxIfPresent(getSettingsPath(sourceRoots.projectPmRoot),getSettingsPath(sandboxPmPath));await copyIntoSandboxIfPresent(path.join(sourceRoots.projectPmRoot,"extensions"),path.join(sandboxPmPath,"extensions"),true);await copyIntoSandboxIfPresent(getSettingsPath(sourceRoots.globalPmRoot),getSettingsPath(sandboxGlobalPath));await copyIntoSandboxIfPresent(path.join(sourceRoots.globalPmRoot,"extensions"),path.join(sandboxGlobalPath,"extensions"),true)}async function seedLinkedTestTrackerData(sourceRoot,sandboxRoot){if(!await pathExists(sourceRoot)){return}const entries=await readdir(sourceRoot,{withFileTypes:true});for(const entry of entries){if(LINKED_TEST_TRACKER_DIRS_TO_SKIP.has(entry.name)){continue}const sourcePath=path.join(sourceRoot,entry.name);const targetPath=path.join(sandboxRoot,entry.name);if(entry.isDirectory()){await copyIntoSandboxIfPresent(sourcePath,targetPath,true);continue}if(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:true});await rm(getSettingsPath(sandboxRoot),{force:true});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:true,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:true});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:true})}catch{continue}for(const file of files){if(!file.isFile()){continue}if(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;if((execution.timedOut||execution.maxBufferExceeded)&&rawExitCode===0){return 1}return rawExitCode}function parseAssertionLiteral(raw){const trimmed=raw.trim();if(trimmed==="true"){return true}if(trimmed==="false"){return false}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){if(typeof actual==="object"&&actual!==null&&typeof expected==="object"&&expected!==null){return stableValueEquals(actual,expected)}return 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??{};const jsonGteAssertions=linkedTest.assert_json_field_gte??{};const needsJsonAssertions=Object.keys(jsonEqualsAssertions).length>0||Object.keys(jsonGteAssertions).length>0;if(!needsJsonAssertions){return failures}let parsedJson;try{parsedJson=JSON.parse(stdout)}catch(error){failures.push(`stdout is not valid JSON for assert_json_field_* checks: ${error instanceof Error?error.message:String(error)}`);return 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);if(!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}if(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??[]){if(!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{const regex=new RegExp(pattern,"m");if(!regex.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}`]:[]}const EMPTY_LINKED_TEST_RUN_PATTERNS=[{code:"no_projects_matched_filters",regex:/\bNo projects matched the filters\b/i},{code:"no_test_files_found",regex:/\bNo test files found\b/i},{code:"no_tests_found",regex:/\bNo tests found\b/i},{code:"no_matching_tests",regex:/\bNo matching tests?\b/i},{code:"collected_zero_items",regex:/\bcollected 0 items?\b/i},{code:"reported_zero_passes",regex:/(?:^\s*(?:#|ℹ)?\s*tests\s+0\s*$[\s\S]*^\s*(?:#|ℹ)?\s*pass\s+0\s*$|^\s*(?:#|ℹ)?\s*pass\s+0\s*$[\s\S]*^\s*(?:#|ℹ)?\s*tests\s+0\s*$)/imu},{code:"reported_zero_tests",regex:/^\s*(?:#|ℹ)?\s*tests\s+0\s*$/imu}];const POSITIVE_LINKED_TEST_RUN_PATTERNS=[/^\s*(?:#|ℹ)?\s*tests\s+[1-9]\d*\s*$/imu,/^\s*(?:#|ℹ)?\s*pass\s+[1-9]\d*\s*$/imu,/\bTests?\s+[1-9]\d*\s+passed\b/iu,/\b[1-9]\d*\s+passed\b/iu,/\bTests:\s+(?:.*\b)?[1-9]\d*\s+passed\b/iu];function detectEmptyLinkedTestRun(stdout,stderr){const combined=`${stdout}
5
5
  ${stderr}`;for(const pattern of EMPTY_LINKED_TEST_RUN_PATTERNS){if(pattern.regex.test(combined)){return{code:pattern.code}}}return null}function hasPositiveLinkedTestRunReceipt(stdout,stderr){const combined=`${stdout}
6
- ${stderr}`;return POSITIVE_LINKED_TEST_RUN_PATTERNS.some(pattern=>pattern.test(combined))}function commandUsesTestNameFilter(command){const normalized=normalizeCommandForValidation(command);if(/(?:^|\s)(?:--test-name-pattern|--testnamepattern)(?:=|\s)/u.test(normalized)){return true}return 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 seedLinkedTestWorkspaceSnapshot(layout,sourceWorkspaceRoot){const excludedSegments=new Set([".agents",".git",".nyc_output",".turbo","coverage","node_modules"]);await mkdir(path.dirname(layout.workspaceSnapshotRoot),{recursive:true});await cp(sourceWorkspaceRoot,layout.workspaceSnapshotRoot,{recursive:true,force:true,filter(source){const relative=path.relative(sourceWorkspaceRoot,source);if(!relative){return true}return!relative.split(path.sep).some(segment=>excludedSegments.has(segment))}});const sourceNodeModules=path.join(sourceWorkspaceRoot,"node_modules");if(await pathExists(sourceNodeModules)){await symlink(sourceNodeModules,path.join(layout.workspaceSnapshotRoot,"node_modules"),process.platform==="win32"?"junction":"dir")}}async function bindSnapshotTracker(snapshotRoot,sandboxPmPath){const agentsRoot=path.join(snapshotRoot,".agents");const target=path.join(agentsRoot,"pm");await mkdir(agentsRoot,{recursive:true});await rm(target,{recursive:true,force:true});await symlink(sandboxPmPath,target,process.platform==="win32"?"junction":"dir")}async function initializeLinkedTestSandboxes(layout,initialize=runInit,includeTrackerData=true){const initOptions={defaults:true,agentGuidance:"skip"};await initialize(void 0,{path:layout.schemaProjectPmPath},initOptions);await initialize(void 0,{path:layout.schemaGlobalPmPath},initOptions);if(!includeTrackerData){return}await initialize(void 0,{path:layout.trackerProjectPmPath},initOptions);await initialize(void 0,{path:layout.trackerGlobalPmPath},initOptions)}async function seedLinkedTestSandboxesFromSource(layout,sourceRoots,includeTrackerData){if(!sourceRoots){return}await seedLinkedTestSandbox(layout.schemaProjectPmPath,layout.schemaGlobalPmPath,sourceRoots);if(!includeTrackerData){return}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??"";const isPmTrackerReadCommand=command.length>0&&commandInvokesPmTrackerReadCommand(command);const requestedPmContextMode=options?.autoPmContext===true&&isPmTrackerReadCommand?"auto":resolveLinkedTestRequestedContextMode(linkedTest,runLevelPmContextMode,options?.overrideLinkedPmContext===true);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";const selectedSandboxProjectPmPath=trackerMode?params.layout.trackerProjectPmPath:params.layout.schemaProjectPmPath;const selectedSandboxGlobalPmPath=trackerMode?params.layout.trackerGlobalPmPath:params.layout.schemaGlobalPmPath;const selectedSandboxProjectItemCount=trackerMode?params.counts.trackerProjectItemCount:params.counts.schemaProjectItemCount;const selectedSandboxGlobalItemCount=trackerMode?params.counts.trackerGlobalItemCount:params.counts.schemaGlobalItemCount;const workingDirectory=params.workspaceContextMode==="snapshot"?params.layout.workspaceSnapshotRoot:params.workspaceContextMode==="isolated"?params.layout.workspaceIsolatedRoot:params.sourceWorkspaceRoot;const 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:Boolean(params.sourceRoots),global_extensions_seeded:Boolean(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"&&params.linkedTest.pm_context_mode.trim().length>0?parsePmContextMode(params.linkedTest.pm_context_mode):void 0;const command=typeof params.linkedTest.command==="string"&&params.linkedTest.command.length>0?params.linkedTest.command:void 0;const isPmCommand=command?commandInvokesPmCli(command):false;const isPmTrackerReadCommand=isPmCommand&&command?commandInvokesPmTrackerReadCommand(command):false;const autoPmContextApplied=params.options?.autoPmContext===true&&isPmTrackerReadCommand;const requestedPmContextMode=autoPmContextApplied?"auto":resolveLinkedTestRequestedContextMode(params.linkedTest,params.runLevelPmContextMode,params.options?.overrideLinkedPmContext===true);const effectivePmContextMode=resolveLinkedTestEffectiveContextMode(requestedPmContextMode,isPmTrackerReadCommand);const selectedSandboxProjectPmPath=effectivePmContextMode==="tracker"?params.layout.trackerProjectPmPath:params.layout.schemaProjectPmPath;if(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===true;const policyEnabled=params.options?.untrustedLinkedTestsPolicyEnabled===true;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 resolveLinkedTestPreflightResult(params){const safetyFailure=resolveLinkedTestSafetyPreflightResult(params);if(safetyFailure)return safetyFailure;const trustFailure=resolveLinkedTestTrustPreflightResult(params);if(trustFailure)return trustFailure;const failOnMismatchByDefault=params.executionContext.pm_context_mode==="schema"&&params.executionContext.is_pm_tracker_read_command&&params.executionContext.mismatch_detected;const failOnMismatchByFlag=params.options?.failOnContextMismatch===true&&params.executionContext.is_pm_command&&params.executionContext.mismatch_detected;if(failOnMismatchByDefault||failOnMismatchByFlag){const mismatchHint=buildPmContextMismatchHint({executionContext:params.executionContext,runLevelPmContextMode:params.runLevelPmContextMode,linkedOverridePmContextMode:params.linkedOverridePmContextMode});const mismatchPrefix=params.options?.checkContext===true?"Linked test preflight PM context mismatch detected":"Linked test PM context mismatch detected";return buildLinkedTestAssertionFailureResult(params.linkedTest,params.executionContext,`${mismatchPrefix} (source_project_items=${params.executionContext.source_project_item_count}, sandbox_project_items=${params.executionContext.sandbox_project_item_count}).${mismatchHint}`)}if(params.options?.requireAssertionsForPm===true&&params.executionContext.is_pm_command&&!hasLinkedTestAssertions(params.linkedTest)){return buildLinkedTestAssertionFailureResult(params.linkedTest,params.executionContext,"Linked PM command requires assertions when --require-assertions-for-pm is enabled.")}return null}function buildLinkedTestExecutionEnv(params){const effectiveDirectives=resolveEffectiveLinkedTestDirectives(params.runtimeDirectives,params.linkedTest);const executionEnv={...process.env,SENTRY_ENVIRONMENT:"test"};applyEnvDirectiveStage(executionEnv,params.runtimeDirectives);applyEnvDirectiveStage(executionEnv,{env_set:params.linkedTest.env_set??{},env_clear:params.linkedTest.env_clear??[]});if(effectiveDirectives.shared_host_safe){applySharedHostSafeDefaults(executionEnv)}executionEnv.FORCE_COLOR="0";executionEnv.PM_PATH=params.executionContext.sandbox_project_pm_path;executionEnv.PM_GLOBAL_PATH=params.executionContext.sandbox_global_pm_path;if(params.executionContext.workspace_context_mode==="isolated"){delete executionEnv.PM_SOURCE_WORKSPACE_ROOT;delete executionEnv.PM_SOURCE_PM_PATH;delete executionEnv[SOURCE_CONTEXT_ACCESS_ENV]}else{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"}return executionEnv}function buildLinkedTestPassedResult(linkedTest,executionContext,execution){return{command:linkedTest.command,path:linkedTest.path,status:"passed",exit_code:0,execution_context:executionContext,stdout:execution.stdout,stderr:execution.stderr}}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){if(params.options?.failOnEmptyTestRun===true||commandUsesTestNameFilter(params.linkedTest.command??"")){const emptyRunSignal=detectEmptyLinkedTestRun(params.execution.stdout,params.execution.stderr);if(emptyRunSignal){return buildLinkedTestEmptyRunResult({...params,emptyRunSignal})}if(commandUsesTestNameFilter(params.linkedTest.command??"")&&!hasPositiveLinkedTestRunReceipt(params.execution.stdout,params.execution.stderr)){return buildLinkedTestEmptyRunResult({...params,emptyRunSignal:{code:"missing_positive_execution_receipt"}})}}const assertionFailures=evaluateLinkedTestAssertions(params.linkedTest,params.execution.stdout,params.execution.stderr);if(assertionFailures.length>0){return buildLinkedTestAssertionFailureResult(params.linkedTest,params.executionContext,`Linked test assertion(s) failed: ${assertionFailures.join("; ")}`,params.execution)}return buildLinkedTestPassedResult(params.linkedTest,params.executionContext,params.execution)}async function runSingleLinkedTest(params){const command=params.linkedTest.command??"";const timeoutMs=(params.linkedTest.timeout_seconds??params.defaultTimeoutSeconds??120)*1e3;const execution=await runLinkedTestCommand(command,timeoutMs,buildLinkedTestExecutionEnv(params),{index:params.index+1,total:params.total,timeoutMs,command},params.progressMode,params.executionContext.working_directory);const passed=execution.exitCode===0&&!execution.timedOut&&!execution.maxBufferExceeded;return passed?buildLinkedTestPassedExecutionResult({...params,execution}):buildLinkedTestCommandFailureResult({...params,execution,timeoutMs})}async function runLinkedTests(tests,defaultTimeoutSeconds,options){const results=[];const sandboxRoot=await mkdtemp(path.join(tmpdir(),"pm-linked-test-"));const layout=createLinkedTestSandboxLayout(sandboxRoot);const runLevelPmContextMode=parsePmContextMode(options?.pmContext);const runLevelWorkspaceContextMode=parseWorkspaceContextMode(options?.workspaceContext);const progressMode=options?.progress===true?"always":"auto";const runtimeDirectives=resolveRuntimeDirectives(options?.envSet,options?.envClear,options?.sharedHostSafe);const sourceRoots=options?.sourceRoots;const sourceWorkspaceRoot=resolveLinkedTestSourceWorkspaceRoot();const includeTrackerData=linkedTestsRequireTrackerData(tests,runLevelPmContextMode,options);const includeWorkspaceSnapshot=linkedTestsRequireWorkspaceSnapshot(tests,runLevelWorkspaceContextMode,options?.overrideLinkedWorkspaceContext===true);const currentSourceRef=await resolveLinkedTestSourceRef(sourceWorkspaceRoot);try{await initializeLinkedTestSandboxes(layout,runInit,includeTrackerData);await mkdir(layout.workspaceIsolatedRoot,{recursive:true});await seedLinkedTestSandboxesFromSource(layout,sourceRoots,includeTrackerData);if(includeWorkspaceSnapshot){await seedLinkedTestWorkspaceSnapshot(layout,sourceWorkspaceRoot)}const counts=await countLinkedTestSandboxItems(layout,sourceRoots);for(let index=0;index<tests.length;index+=1){const linkedTest=tests[index];const workspaceContextMode=resolveLinkedTestWorkspaceContextMode(linkedTest,runLevelWorkspaceContextMode,options?.overrideLinkedWorkspaceContext===true);const commandContext=await resolveLinkedTestCommandContext({linkedTest,layout,counts,sourceRoots,runLevelPmContextMode,options,requestedWorkspaceContextMode:runLevelWorkspaceContextMode,workspaceContextMode,currentSourceRef,sourceWorkspaceRoot});const 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:true,force:true,maxRetries:3,retryDelay:100})}return results}async function readLinkedTestItem(params){const{id,pmRoot,settings,typeToFolder}=params;const 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:false,removed:0}}function linkedTestsHaveSameIdentity(left,right){return left.command===right.command&&left.path===right.path&&left.scope===right.scope&&left.pm_context_mode===right.pm_context_mode&&left.workspace_context_mode===right.workspace_context_mode}function appendMissingLinkedTests(current,additions){const next=[...current];for(const addition of additions){if(!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);const tests=current.filter((entry,index)=>{if(indexSet.has(index+1))return false;return!removals.some(selector=>{if(selector.kind==="command")return entry.command===selector.value;if(selector.kind==="path")return entry.path===selector.value;return 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.envSet?.length??0)>0,(options.envClear?.length??0)>0,options.sharedHostSafe===true,options.pmContext!==void 0,options.overrideLinkedPmContext===true,options.failOnContextMismatch===true,options.failOnSkipped===true,options.failOnEmptyTestRun===true,options.requireAssertionsForPm===true,options.checkContext===true,options.autoPmContext===true,options.workspaceContext!==void 0,options.overrideLinkedWorkspaceContext===true,options.allowUntrustedLinkedTests===true].some(Boolean)}function assertTestRunFlagUsage(options){if(hasTestRuntimeDirectiveFlags(options)&&options.run!==true){throw new PmCliError("--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===true&&options.run===true){throw new PmCliError("--acknowledge-linked-tests records trust without executing commands; run it separately before --run",EXIT_CODE.USAGE)}const hasSelectorFlags=options.match!==void 0||options.onlyIndex!==void 0||options.onlyLast===true;if(hasSelectorFlags&&options.run!==true){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:true,mutate(document){const previous=document.metadata.tests??[];const mutation=applyLinkedTestMutations(previous,adds,removes,removeIndexes);removed=mutation.removed;if((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`]})}document.metadata.tests=mutation.tests;return{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){assertTestRunFlagUsage(options);const selectorInput={match:options.match,onlyIndex:options.onlyIndex===void 0?void 0:parseOnlyIndexValue(options.onlyIndex),onlyLast:options.onlyLast};const runSelection=options.run===true?resolveLinkedTestRunSelection(tests,selectorInput):void 0;const defaultTimeoutSeconds=options.timeout===void 0?void 0:parseOptionalNumber(options.timeout,"timeout");if(defaultTimeoutSeconds!==void 0&&defaultTimeoutSeconds<=0){throw new PmCliError("Test timeout must be a positive number",EXIT_CODE.USAGE)}return{defaultTimeoutSeconds,pmContextMode:parsePmContextMode(options.pmContext),runSelection,testsToRun:runSelection?.selected??tests}}async function executeSelectedLinkedTests(params){const{options,runOptions,pmRoot}=params;if(options.run!==true){return[]}return 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,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,runSelection,runResults){const warnings=[];if(runSelection&&runSelection.selector!==null){warnings.push(`linked_test_selection:${runSelection.selector}=${runSelection.requested};selected=${runSelection.selected_count};skipped=${runSelection.skipped_count};indexes=${runSelection.selected_indexes.join(",")}`)}if(options.run===true&&options.checkContext===true){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);const parsedAttempt=Number.parseInt(process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim()??"",10);const resumedFrom=process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM?.trim();const recordedAt=nowIso();const 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?true: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!==true||!runStartedAt){return void 0}const entry=buildTrackedTestRunSummary({options,runStartedAt,runResults,failOnSkippedTriggered});if(settings.testing.record_results_to_items!==true){return entry}try{await appendTrackedTestRunSummary({pmRoot,settings,itemId,author:resolveAuthor(options.author,settings.author_default),message:`Track test run summary (${entry.run_id})`,entry});return entry}catch(error){warnings.push(`test_result_tracking_failed:${itemId}:${error instanceof Error?error.message:String(error)}`);return entry}}function buildTestMeasurementProjection(options,runs,recordedRun){let metricBelow;if(options.metricBelow!==void 0){const separator=options.metricBelow.indexOf("=");const name=options.metricBelow.slice(0,separator).trim();const thresholdText=options.metricBelow.slice(separator+1).trim();const 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!==true)return void 0;return acknowledgeLinkedTests(pmRoot,tests,nowIso())}async function runTest(id,options,global2){const stdinResolver=createStdinTokenResolver();const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot);if((options.measure?.length??0)>0&&options.run!==true){throw new PmCliError("--measure requires --run",EXIT_CODE.USAGE)}parseTestRunMeasurements(options.measure,"validation");buildTestMeasurementProjection(options,[],void 0);const typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations());const resolvedAdds=await stdinResolver.resolveList(options.add,"--add");const resolvedAddJsons=await stdinResolver.resolveList(options.addJson,"--add-json");const resolvedRemoves=await stdinResolver.resolveList(options.remove,"--remove");const parsedAdds=[...parseAddEntries(resolvedAdds),...parseAddJsonEntries(resolvedAddJsons)];const adds=await attachLinkedTestMutationProvenance(parsedAdds,resolveAuthor(options.author,settings.author_default),nowIso())??[];const removes=parseRemoveEntries(resolvedRemoves);const removeIndexes=parseRemoveIndexes(options.removeIndex);const item=await resolveLinkedTestItem({id,options,pmRoot,settings,typeToFolder:typeRegistry.type_to_folder,adds,removes,removeIndexes});const runOptions=resolveTestRunOptions(options,item.tests);const trustAcknowledgement=await maybeAcknowledgeLinkedTests(options,pmRoot,item.tests);const runStartedAt=options.run===true?nowIso():void 0;const runResults=await executeSelectedLinkedTests({options,runOptions,pmRoot,untrustedLinkedTestsPolicyEnabled:settings.testing.allow_untrusted_linked_tests});const failureCategories=countFailureCategories(runResults);const failOnSkippedTriggered=options.run===true&&options.failOnSkipped===true&&runResults.some(entry=>entry.status==="skipped");const warnings=buildTestWarnings(options,runOptions.runSelection,runResults);if(trustAcknowledgement){warnings.push(`linked_test_trust_acknowledged:${trustAcknowledgement.acknowledged}`)}const recordedRun=await recordTestRunSummary({options,pmRoot,settings,itemId:item.itemId,runStartedAt,runResults,failOnSkippedTriggered,warnings});const runs=recordedRun?buildTrackedTestRunHistory([...item.testRuns,recordedRun]):item.testRuns;const measurementProjection=buildTestMeasurementProjection(options,runs,recordedRun);return{ok:runResults.every(entry=>entry.status!=="failed")&&failOnSkippedTriggered!==true,id:item.itemId,tests:item.tests,run_results:runResults,failure_categories:failureCategories,selection:runOptions.runSelection?{selector:runOptions.runSelection.selector,requested:runOptions.runSelection.requested,selected_indexes:runOptions.runSelection.selected_indexes,selected_count:runOptions.runSelection.selected_count,skipped_count:runOptions.runSelection.skipped_count}:void 0,fail_on_skipped_triggered:failOnSkippedTriggered?true:void 0,warnings:warnings.length>0?warnings:void 0,changed:item.changed,count:item.tests.length,...item.removed>0?{removed:item.removed}:{},...measurementProjection}}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
+ ${stderr}`;return POSITIVE_LINKED_TEST_RUN_PATTERNS.some(pattern=>pattern.test(combined))}function commandUsesTestNameFilter(command){const normalized=normalizeCommandForValidation(command);if(/(?:^|\s)(?:--test-name-pattern|--testnamepattern)(?:=|\s)/u.test(normalized)){return true}return 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 seedLinkedTestWorkspaceSnapshot(layout,sourceWorkspaceRoot){const excludedSegments=new Set([".agents",".git",".nyc_output",".turbo","coverage","node_modules"]);await mkdir(path.dirname(layout.workspaceSnapshotRoot),{recursive:true});await cp(sourceWorkspaceRoot,layout.workspaceSnapshotRoot,{recursive:true,force:true,filter(source){const relative=path.relative(sourceWorkspaceRoot,source);if(!relative){return true}return!relative.split(path.sep).some(segment=>excludedSegments.has(segment))}});const sourceNodeModules=path.join(sourceWorkspaceRoot,"node_modules");if(await pathExists(sourceNodeModules)){await symlink(sourceNodeModules,path.join(layout.workspaceSnapshotRoot,"node_modules"),process.platform==="win32"?"junction":"dir")}}async function bindSnapshotTracker(snapshotRoot,sandboxPmPath){const agentsRoot=path.join(snapshotRoot,".agents");const target=path.join(agentsRoot,"pm");await mkdir(agentsRoot,{recursive:true});await rm(target,{recursive:true,force:true});await symlink(sandboxPmPath,target,process.platform==="win32"?"junction":"dir")}async function initializeLinkedTestSandboxes(layout,initialize=runInit,includeTrackerData=true){const initOptions={defaults:true,agentGuidance:"skip"};await initialize(void 0,{path:layout.schemaProjectPmPath},initOptions);await initialize(void 0,{path:layout.schemaGlobalPmPath},initOptions);if(!includeTrackerData){return}await initialize(void 0,{path:layout.trackerProjectPmPath},initOptions);await initialize(void 0,{path:layout.trackerGlobalPmPath},initOptions)}async function seedLinkedTestSandboxesFromSource(layout,sourceRoots,includeTrackerData){if(!sourceRoots){return}await seedLinkedTestSandbox(layout.schemaProjectPmPath,layout.schemaGlobalPmPath,sourceRoots);if(!includeTrackerData){return}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??"";const isPmTrackerReadCommand=command.length>0&&commandInvokesPmTrackerReadCommand(command);const requestedPmContextMode=options?.autoPmContext===true&&isPmTrackerReadCommand?"auto":resolveLinkedTestRequestedContextMode(linkedTest,runLevelPmContextMode,options?.overrideLinkedPmContext===true);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";const selectedSandboxProjectPmPath=trackerMode?params.layout.trackerProjectPmPath:params.layout.schemaProjectPmPath;const selectedSandboxGlobalPmPath=trackerMode?params.layout.trackerGlobalPmPath:params.layout.schemaGlobalPmPath;const selectedSandboxProjectItemCount=trackerMode?params.counts.trackerProjectItemCount:params.counts.schemaProjectItemCount;const selectedSandboxGlobalItemCount=trackerMode?params.counts.trackerGlobalItemCount:params.counts.schemaGlobalItemCount;const workingDirectory=params.workspaceContextMode==="snapshot"?params.layout.workspaceSnapshotRoot:params.workspaceContextMode==="isolated"?params.layout.workspaceIsolatedRoot:params.sourceWorkspaceRoot;const 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:Boolean(params.sourceRoots),global_extensions_seeded:Boolean(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"&&params.linkedTest.pm_context_mode.trim().length>0?parsePmContextMode(params.linkedTest.pm_context_mode):void 0;const command=typeof params.linkedTest.command==="string"&&params.linkedTest.command.length>0?params.linkedTest.command:void 0;const isPmCommand=command?commandInvokesPmCli(command):false;const isPmTrackerReadCommand=isPmCommand&&command?commandInvokesPmTrackerReadCommand(command):false;const autoPmContextApplied=params.options?.autoPmContext===true&&isPmTrackerReadCommand;const requestedPmContextMode=autoPmContextApplied?"auto":resolveLinkedTestRequestedContextMode(params.linkedTest,params.runLevelPmContextMode,params.options?.overrideLinkedPmContext===true);const effectivePmContextMode=resolveLinkedTestEffectiveContextMode(requestedPmContextMode,isPmTrackerReadCommand);const selectedSandboxProjectPmPath=effectivePmContextMode==="tracker"?params.layout.trackerProjectPmPath:params.layout.schemaProjectPmPath;if(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===true;const policyEnabled=params.options?.untrustedLinkedTestsPolicyEnabled===true;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){if(params.executionContext.pm_context_mode!=="none")return null;if(params.executionContext.workspace_context_mode==="source"){return buildLinkedTestAssertionFailureResult(params.linkedTest,params.executionContext,"pm_context_mode=none requires workspace_context_mode=isolated or snapshot so implicit tracker discovery cannot reach the source workspace.")}if(params.executionContext.is_pm_command){return buildLinkedTestAssertionFailureResult(params.linkedTest,params.executionContext,"pm_context_mode=none is for self-isolating SDK tests; direct PM commands require schema, tracker, or auto context.")}return null}function resolvePmContextMismatchFailure(params){const failOnMismatchByDefault=params.executionContext.pm_context_mode==="schema"&&params.executionContext.is_pm_tracker_read_command&&params.executionContext.mismatch_detected;const failOnMismatchByFlag=params.options?.failOnContextMismatch===true&&params.executionContext.is_pm_command&&params.executionContext.mismatch_detected;if(!failOnMismatchByDefault&&!failOnMismatchByFlag)return null;const mismatchHint=buildPmContextMismatchHint({executionContext:params.executionContext,runLevelPmContextMode:params.runLevelPmContextMode,linkedOverridePmContextMode:params.linkedOverridePmContextMode});const mismatchPrefix=params.options?.checkContext===true?"Linked test preflight PM context mismatch detected":"Linked test PM context mismatch detected";return buildLinkedTestAssertionFailureResult(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){const safetyFailure=resolveLinkedTestSafetyPreflightResult(params);if(safetyFailure)return safetyFailure;const trustFailure=resolveLinkedTestTrustPreflightResult(params);if(trustFailure)return trustFailure;const unboundContextFailure=resolveUnboundPmContextFailure(params);if(unboundContextFailure)return unboundContextFailure;const mismatchFailure=resolvePmContextMismatchFailure(params);if(mismatchFailure)return mismatchFailure;if(params.options?.requireAssertionsForPm===true&&params.executionContext.is_pm_command&&!hasLinkedTestAssertions(params.linkedTest)){return buildLinkedTestAssertionFailureResult(params.linkedTest,params.executionContext,"Linked PM command requires assertions when --require-assertions-for-pm is enabled.")}return null}function buildLinkedTestExecutionEnv(params){const effectiveDirectives=resolveEffectiveLinkedTestDirectives(params.runtimeDirectives,params.linkedTest);const executionEnv={...process.env,SENTRY_ENVIRONMENT:"test"};applyEnvDirectiveStage(executionEnv,params.runtimeDirectives);applyEnvDirectiveStage(executionEnv,{env_set:params.linkedTest.env_set??{},env_clear:params.linkedTest.env_clear??[]});if(effectiveDirectives.shared_host_safe){applySharedHostSafeDefaults(executionEnv)}executionEnv.FORCE_COLOR="0";if(params.executionContext.pm_context_mode==="none"){delete executionEnv.PM_PATH}else{executionEnv.PM_PATH=params.executionContext.sandbox_project_pm_path}executionEnv.PM_GLOBAL_PATH=params.executionContext.sandbox_global_pm_path;if(params.executionContext.workspace_context_mode==="isolated"){delete executionEnv.PM_SOURCE_WORKSPACE_ROOT;delete executionEnv.PM_SOURCE_PM_PATH;delete executionEnv[SOURCE_CONTEXT_ACCESS_ENV]}else{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"}return executionEnv}function buildLinkedTestPassedResult(linkedTest,executionContext,execution){return{command:linkedTest.command,path:linkedTest.path,status:"passed",exit_code:0,execution_context:executionContext,stdout:execution.stdout,stderr:execution.stderr}}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){if(params.options?.failOnEmptyTestRun===true||commandUsesTestNameFilter(params.linkedTest.command??"")){const emptyRunSignal=detectEmptyLinkedTestRun(params.execution.stdout,params.execution.stderr);if(emptyRunSignal){return buildLinkedTestEmptyRunResult({...params,emptyRunSignal})}if(commandUsesTestNameFilter(params.linkedTest.command??"")&&!hasPositiveLinkedTestRunReceipt(params.execution.stdout,params.execution.stderr)){return buildLinkedTestEmptyRunResult({...params,emptyRunSignal:{code:"missing_positive_execution_receipt"}})}}const assertionFailures=evaluateLinkedTestAssertions(params.linkedTest,params.execution.stdout,params.execution.stderr);if(assertionFailures.length>0){return buildLinkedTestAssertionFailureResult(params.linkedTest,params.executionContext,`Linked test assertion(s) failed: ${assertionFailures.join("; ")}`,params.execution)}return buildLinkedTestPassedResult(params.linkedTest,params.executionContext,params.execution)}async function runSingleLinkedTest(params){const command=params.linkedTest.command??"";const timeoutMs=(params.linkedTest.timeout_seconds??params.defaultTimeoutSeconds??120)*1e3;const execution=await runLinkedTestCommand(command,timeoutMs,buildLinkedTestExecutionEnv(params),{index:params.index+1,total:params.total,timeoutMs,command},params.progressMode,params.executionContext.working_directory);const passed=execution.exitCode===0&&!execution.timedOut&&!execution.maxBufferExceeded;return passed?buildLinkedTestPassedExecutionResult({...params,execution}):buildLinkedTestCommandFailureResult({...params,execution,timeoutMs})}async function runLinkedTests(tests,defaultTimeoutSeconds,options){const results=[];const sandboxRoot=await mkdtemp(path.join(tmpdir(),"pm-linked-test-"));const layout=createLinkedTestSandboxLayout(sandboxRoot);const runLevelPmContextMode=parsePmContextMode(options?.pmContext);const runLevelWorkspaceContextMode=parseWorkspaceContextMode(options?.workspaceContext);const progressMode=options?.progress===true?"always":"auto";const runtimeDirectives=resolveRuntimeDirectives(options?.envSet,options?.envClear,options?.sharedHostSafe);const sourceRoots=options?.sourceRoots;const sourceWorkspaceRoot=resolveLinkedTestSourceWorkspaceRoot();const includeTrackerData=linkedTestsRequireTrackerData(tests,runLevelPmContextMode,options);const includeWorkspaceSnapshot=linkedTestsRequireWorkspaceSnapshot(tests,runLevelWorkspaceContextMode,options?.overrideLinkedWorkspaceContext===true);const currentSourceRef=await resolveLinkedTestSourceRef(sourceWorkspaceRoot);try{await initializeLinkedTestSandboxes(layout,runInit,includeTrackerData);await mkdir(layout.workspaceIsolatedRoot,{recursive:true});await seedLinkedTestSandboxesFromSource(layout,sourceRoots,includeTrackerData);if(includeWorkspaceSnapshot){await seedLinkedTestWorkspaceSnapshot(layout,sourceWorkspaceRoot)}const counts=await countLinkedTestSandboxItems(layout,sourceRoots);for(let index=0;index<tests.length;index+=1){const linkedTest=tests[index];const workspaceContextMode=resolveLinkedTestWorkspaceContextMode(linkedTest,runLevelWorkspaceContextMode,options?.overrideLinkedWorkspaceContext===true);const commandContext=await resolveLinkedTestCommandContext({linkedTest,layout,counts,sourceRoots,runLevelPmContextMode,options,requestedWorkspaceContextMode:runLevelWorkspaceContextMode,workspaceContextMode,currentSourceRef,sourceWorkspaceRoot});const 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:true,force:true,maxRetries:3,retryDelay:100})}return results}async function readLinkedTestItem(params){const{id,pmRoot,settings,typeToFolder}=params;const 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:false,removed:0}}function linkedTestsHaveSameIdentity(left,right){return left.command===right.command&&left.path===right.path&&left.scope===right.scope&&left.pm_context_mode===right.pm_context_mode&&left.workspace_context_mode===right.workspace_context_mode}function appendMissingLinkedTests(current,additions){const next=[...current];for(const addition of additions){if(!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);const tests=current.filter((entry,index)=>{if(indexSet.has(index+1))return false;return!removals.some(selector=>{if(selector.kind==="command")return entry.command===selector.value;if(selector.kind==="path")return entry.path===selector.value;return 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.envSet?.length??0)>0,(options.envClear?.length??0)>0,options.sharedHostSafe===true,options.pmContext!==void 0,options.overrideLinkedPmContext===true,options.failOnContextMismatch===true,options.failOnSkipped===true,options.failOnEmptyTestRun===true,options.requireAssertionsForPm===true,options.checkContext===true,options.autoPmContext===true,options.workspaceContext!==void 0,options.overrideLinkedWorkspaceContext===true,options.allowUntrustedLinkedTests===true].some(Boolean)}function assertTestRunFlagUsage(options){if(hasTestRuntimeDirectiveFlags(options)&&options.run!==true){throw new PmCliError("--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===true&&options.run===true){throw new PmCliError("--acknowledge-linked-tests records trust without executing commands; run it separately before --run",EXIT_CODE.USAGE)}const hasSelectorFlags=options.match!==void 0||options.onlyIndex!==void 0||options.onlyLast===true;if(hasSelectorFlags&&options.run!==true){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:true,mutate(document){const previous=document.metadata.tests??[];const mutation=applyLinkedTestMutations(previous,adds,removes,removeIndexes);removed=mutation.removed;if((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`]})}document.metadata.tests=mutation.tests;return{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){assertTestRunFlagUsage(options);const selectorInput={match:options.match,onlyIndex:options.onlyIndex===void 0?void 0:parseOnlyIndexValue(options.onlyIndex),onlyLast:options.onlyLast};const runSelection=options.run===true?resolveLinkedTestRunSelection(tests,selectorInput):void 0;const defaultTimeoutSeconds=options.timeout===void 0?void 0:parseOptionalNumber(options.timeout,"timeout");if(defaultTimeoutSeconds!==void 0&&defaultTimeoutSeconds<=0){throw new PmCliError("Test timeout must be a positive number",EXIT_CODE.USAGE)}return{defaultTimeoutSeconds,pmContextMode:parsePmContextMode(options.pmContext),runSelection,testsToRun:runSelection?.selected??tests}}async function executeSelectedLinkedTests(params){const{options,runOptions,pmRoot}=params;if(options.run!==true){return[]}return 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,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,runSelection,runResults){const warnings=[];if(runSelection&&runSelection.selector!==null){warnings.push(`linked_test_selection:${runSelection.selector}=${runSelection.requested};selected=${runSelection.selected_count};skipped=${runSelection.skipped_count};indexes=${runSelection.selected_indexes.join(",")}`)}if(options.run===true&&options.checkContext===true){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);const parsedAttempt=Number.parseInt(process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim()??"",10);const resumedFrom=process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM?.trim();const recordedAt=nowIso();const 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?true: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!==true||!runStartedAt){return void 0}const entry=buildTrackedTestRunSummary({options,runStartedAt,runResults,failOnSkippedTriggered});if(settings.testing.record_results_to_items!==true){return{entry,receipt:{recorded:false,reason:"tracking_disabled",run_id:entry.run_id,recovery_command:"pm config project set test-result-tracking --policy enabled"}}}try{await appendTrackedTestRunSummary({pmRoot,settings,itemId,author:resolveAuthor(options.author,settings.author_default),message:`Track test run summary (${entry.run_id})`,entry});return{entry,receipt:{recorded:true,reason:"recorded",run_id:entry.run_id}}}catch(error){warnings.push(`test_result_tracking_failed:${itemId}:${error instanceof Error?error.message:String(error)}`);return{entry,receipt:{recorded:false,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("=");const name=options.metricBelow.slice(0,separator).trim();const thresholdText=options.metricBelow.slice(separator+1).trim();const 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!==true)return void 0;return acknowledgeLinkedTests(pmRoot,tests,nowIso())}function projectTestResult(input){const{item,runResults,failureCategories,runSelection,failOnSkippedTriggered,warnings,recording,measurementProjection}=input;return{ok:runResults.every(entry=>entry.status!=="failed")&&failOnSkippedTriggered!==true,id:item.itemId,tests:item.tests,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?true:void 0,warnings:warnings.length>0?warnings:void 0,changed:item.changed||recording?.receipt.recorded===true,...recording?{evidence_recording:recording.receipt}:{},count:item.tests.length,...item.removed>0?{removed:item.removed}:{},...measurementProjection}}async function runTest(id,options,global2){const stdinResolver=createStdinTokenResolver();const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot);if((options.measure?.length??0)>0&&options.run!==true){throw new PmCliError("--measure requires --run",EXIT_CODE.USAGE)}parseTestRunMeasurements(options.measure,"validation");buildTestMeasurementProjection(options,[],void 0);const typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations());const resolvedAdds=await stdinResolver.resolveList(options.add,"--add");const resolvedAddJsons=await stdinResolver.resolveList(options.addJson,"--add-json");const resolvedRemoves=await stdinResolver.resolveList(options.remove,"--remove");const parsedAdds=[...parseAddEntries(resolvedAdds),...parseAddJsonEntries(resolvedAddJsons)];const adds=await attachLinkedTestMutationProvenance(parsedAdds,resolveAuthor(options.author,settings.author_default),nowIso())??[];const removes=parseRemoveEntries(resolvedRemoves);const removeIndexes=parseRemoveIndexes(options.removeIndex);const item=await resolveLinkedTestItem({id,options,pmRoot,settings,typeToFolder:typeRegistry.type_to_folder,adds,removes,removeIndexes});const runOptions=resolveTestRunOptions(options,item.tests);const trustAcknowledgement=await maybeAcknowledgeLinkedTests(options,pmRoot,item.tests);const runStartedAt=options.run===true?nowIso():void 0;const runResults=await executeSelectedLinkedTests({options,runOptions,pmRoot,untrustedLinkedTestsPolicyEnabled:settings.testing.allow_untrusted_linked_tests});const failureCategories=countFailureCategories(runResults);const failOnSkippedTriggered=options.run===true&&options.failOnSkipped===true&&runResults.some(entry=>entry.status==="skipped");const warnings=buildTestWarnings(options,runOptions.runSelection,runResults);if(trustAcknowledgement){warnings.push(`linked_test_trust_acknowledged:${trustAcknowledgement.acknowledged}`)}const recording=await recordTestRunSummary({options,pmRoot,settings,itemId:item.itemId,runStartedAt,runResults,failOnSkippedTriggered,warnings});const runs=recording?.receipt.recorded?buildTrackedTestRunHistory([...item.testRuns,recording.entry]):item.testRuns;const measurementProjection=buildTestMeasurementProjection(options,runs,recording?.entry);return projectTestResult({item,runResults,failureCategories,runSelection:runOptions.runSelection,failOnSkippedTriggered,warnings,recording,measurementProjection})}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};
7
7
  //# sourceMappingURL=execution.js.map
@@ -17,7 +17,7 @@ export declare const LINKED_TEST_PROTECTED_ENV_KEYS: Set<string>;
17
17
  /** Public contract for linked test env name pattern, shared by SDK and presentation-layer consumers. */
18
18
  export declare const LINKED_TEST_ENV_NAME_PATTERN: RegExp;
19
19
  /** Supported values accepted by the linked test pm context mode contract. */
20
- export declare const LINKED_TEST_PM_CONTEXT_MODE_VALUES: readonly ["schema", "tracker", "auto"];
20
+ export declare const LINKED_TEST_PM_CONTEXT_MODE_VALUES: readonly ["schema", "tracker", "auto", "none"];
21
21
  /** Restricts linked test pm context mode values accepted by command, SDK, and storage contracts. */
22
22
  export type LinkedTestPmContextMode = (typeof LINKED_TEST_PM_CONTEXT_MODE_VALUES)[number];
23
23
  /** Supported values accepted by the linked test workspace context contract. */
@@ -1,2 +1,2 @@
1
- !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="800bdce7-d4d2-5702-9ceb-d83ac4a95fb0")}catch(e2){}})();import{parseOptionalNumber}from"../../core/item/parse.js";import{EXIT_CODE}from"../../core/shared/constants.js";import{PmCliError}from"../../core/shared/errors.js";import{splitCommaList}from"../../core/shared/split-comma-list.js";import{STRUCTURED_LINKED_TEST_KEYS}from"./entry.js";import{SCOPE_VALUES}from"../../types/index.js";import{SOURCE_CONTEXT_ACCESS_ENV,SOURCE_CONTEXT_WRITE_OVERRIDE_ENV}from"../environment/source-context.js";const LINKED_TEST_PROTECTED_ENV_KEYS=new Set(["PM_PATH","PM_GLOBAL_PATH","PM_SOURCE_PM_PATH","PM_SOURCE_WORKSPACE_ROOT",SOURCE_CONTEXT_ACCESS_ENV,SOURCE_CONTEXT_WRITE_OVERRIDE_ENV,"FORCE_COLOR"]);const LINKED_TEST_ENV_NAME_PATTERN=/^[A-Za-z_][A-Za-z0-9_]*$/;const LINKED_TEST_PM_CONTEXT_MODE_VALUES=["schema","tracker","auto"];const LINKED_TEST_WORKSPACE_CONTEXT_MODE_VALUES=["source","isolated","snapshot"];function parseLinkedTestEnvSet(raw,optionName){if(!raw){return void 0}const assignments=raw.split(/[;\n]/).map(entry=>entry.trim()).filter(entry=>entry.length>0);if(assignments.length===0){throw new PmCliError(`${optionName} env_set must include at least one KEY=VALUE assignment`,EXIT_CODE.USAGE)}const envSet=Object.create(null);for(const assignment of assignments){const separatorIndex=assignment.indexOf("=");if(separatorIndex<=0){throw new PmCliError(`${optionName} env_set entries must use KEY=VALUE and be separated by semicolons. Example: env_set=PORT=0;PLAYWRIGHT_BASE_URL=http://127.0.0.1:4173`,EXIT_CODE.USAGE)}const key=assignment.slice(0,separatorIndex).trim();const value=assignment.slice(separatorIndex+1);if(!LINKED_TEST_ENV_NAME_PATTERN.test(key)){throw new PmCliError(`${optionName} env_set key "${key}" is invalid`,EXIT_CODE.USAGE)}if(LINKED_TEST_PROTECTED_ENV_KEYS.has(key.toUpperCase())){throw new PmCliError(`${optionName} env_set key "${key}" is reserved for sandbox safety`,EXIT_CODE.USAGE)}envSet[key]=value}return Object.keys(envSet).length>0?envSet:void 0}function parseLinkedTestEnvClear(raw,optionName){if(!raw){return void 0}const keys=splitCommaList(raw,{separators:/[;,\n]/});if(keys.length===0){throw new PmCliError(`${optionName} env_clear must include at least one environment variable name`,EXIT_CODE.USAGE)}for(const key of keys){if(!LINKED_TEST_ENV_NAME_PATTERN.test(key)){throw new PmCliError(`${optionName} env_clear key "${key}" is invalid`,EXIT_CODE.USAGE)}if(LINKED_TEST_PROTECTED_ENV_KEYS.has(key.toUpperCase())){throw new PmCliError(`${optionName} env_clear key "${key}" is reserved for sandbox safety`,EXIT_CODE.USAGE)}}return keys}function parseLinkedTestBoolean(raw,optionName,fieldLabel){if(!raw){return void 0}const value=raw.trim().toLowerCase();if(value==="true"||value==="1"||value==="yes"){return true}if(value==="false"||value==="0"||value==="no"){return false}throw new PmCliError(`${optionName} ${fieldLabel} must be one of true|false|1|0|yes|no`,EXIT_CODE.USAGE)}function parseLinkedTestContextMode(raw,optionName){if(!raw){return void 0}const value=raw.trim().toLowerCase();if(LINKED_TEST_PM_CONTEXT_MODE_VALUES.includes(value)){return value}throw new PmCliError(`${optionName} pm_context_mode must be one of: ${LINKED_TEST_PM_CONTEXT_MODE_VALUES.join(", ")}`,EXIT_CODE.USAGE)}function parseLinkedTestWorkspaceContextMode(raw,optionName){if(!raw){return void 0}const value=raw.trim().toLowerCase();if(LINKED_TEST_WORKSPACE_CONTEXT_MODE_VALUES.includes(value)){return value}throw new PmCliError(`${optionName} workspace_context_mode must be one of: ${LINKED_TEST_WORKSPACE_CONTEXT_MODE_VALUES.join(", ")}`,EXIT_CODE.USAGE)}function parseLinkedTestStringList(raw){if(!raw){return void 0}const values=splitCommaList(raw,{separators:/[;\n]/});return values.length>0?values:void 0}function parseLinkedTestRegexList(raw,optionName,fieldLabel){const values=parseLinkedTestStringList(raw);if(!values||values.length===0){return void 0}for(const pattern of values){try{new RegExp(pattern,"m")}catch(error){throw new PmCliError(`${optionName} ${fieldLabel} includes invalid regex "${pattern}": ${error instanceof Error?error.message:String(error)}`,EXIT_CODE.USAGE)}}return values}function parseLinkedTestMinLines(raw,optionName){if(!raw){return void 0}const parsed=parseOptionalNumber(raw,"assert_stdout_min_lines");if(!Number.isInteger(parsed)||parsed<0){throw new PmCliError(`${optionName} assert_stdout_min_lines must be an integer >= 0`,EXIT_CODE.USAGE)}return parsed}function parseLinkedTestAssertionEqualsMap(raw,optionName){if(!raw){return void 0}const assignments=raw.split(/[;\n]/).map(entry=>entry.trim()).filter(entry=>entry.length>0);if(assignments.length===0){throw new PmCliError(`${optionName} assert_json_field_equals must include at least one path=value assignment`,EXIT_CODE.USAGE)}const values=Object.create(null);for(const assignment of assignments){const separatorIndex=assignment.indexOf("=");if(separatorIndex<=0){throw new PmCliError(`${optionName} assert_json_field_equals entries must use path=value and be separated by semicolons`,EXIT_CODE.USAGE)}const key=assignment.slice(0,separatorIndex).trim();const value=assignment.slice(separatorIndex+1).trim();if(key.length===0||value.length===0){throw new PmCliError(`${optionName} assert_json_field_equals entries must include non-empty path and value`,EXIT_CODE.USAGE)}values[key]=value}return Object.keys(values).length>0?values:void 0}function parseLinkedTestAssertionGteMap(raw,optionName){if(!raw){return void 0}const assignments=raw.split(/[;\n]/).map(entry=>entry.trim()).filter(entry=>entry.length>0);if(assignments.length===0){throw new PmCliError(`${optionName} assert_json_field_gte must include at least one path=value assignment`,EXIT_CODE.USAGE)}const values=Object.create(null);for(const assignment of assignments){const separatorIndex=assignment.indexOf("=");if(separatorIndex<=0){throw new PmCliError(`${optionName} assert_json_field_gte entries must use path=value and be separated by semicolons`,EXIT_CODE.USAGE)}const key=assignment.slice(0,separatorIndex).trim();const valueRaw=assignment.slice(separatorIndex+1).trim();if(key.length===0||valueRaw.length===0){throw new PmCliError(`${optionName} assert_json_field_gte entries must include non-empty path and value`,EXIT_CODE.USAGE)}const value=Number(valueRaw);if(!Number.isFinite(value)){throw new PmCliError(`${optionName} assert_json_field_gte value for "${key}" must be numeric`,EXIT_CODE.USAGE)}values[key]=value}return Object.keys(values).length>0?values:void 0}const LINKED_TEST_JSON_KEY_SET=new Set(STRUCTURED_LINKED_TEST_KEYS);function isPlainObject(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function normalizeJsonEntryKeys(entry,fail){const normalized={};const unknownKeys=[];for(const[key,value]of Object.entries(entry)){const normalizedKey=key.toLowerCase();if(!LINKED_TEST_JSON_KEY_SET.has(normalizedKey)){unknownKeys.push(key);continue}if(Object.hasOwn(normalized,normalizedKey)){throw fail(`provides key "${key}" more than once after case normalization`)}normalized[normalizedKey]=value}if(unknownKeys.length>0){throw fail(`does not recognize key${unknownKeys.length>1?"s":""} ${unknownKeys.map(key=>`"${key}"`).join(", ")}. Allowed keys: ${STRUCTURED_LINKED_TEST_KEYS.join(", ")}.`)}return normalized}function readJsonEntryString(entry,key,fail){if(!Object.hasOwn(entry,key)){return void 0}const value=entry[key];if(value===void 0){return void 0}if(typeof value!=="string"){throw fail(`field "${key}" must be a JSON string`)}return value}function readJsonEntryStringList(entry,key,fail){if(!Object.hasOwn(entry,key)){return void 0}const value=entry[key];if(value===void 0){return void 0}const list=typeof value==="string"?[value]:value;if(!Array.isArray(list)||list.some(item=>typeof item!=="string")){throw fail(`field "${key}" must be a string or an array of strings`)}const values=list.filter(item=>item.length>0);return values.length>0?values:void 0}function readJsonEntryRegexList(entry,key,fail){const values=readJsonEntryStringList(entry,key,fail);if(!values){return void 0}for(const pattern of values){try{new RegExp(pattern,"m")}catch(error){throw fail(`field "${key}" includes invalid regex "${pattern}": ${error instanceof Error?error.message:String(error)}`)}}return values}function readJsonEntryNumber(value,key,fail){const parsed=typeof value==="number"?value:typeof value==="string"&&value.trim().length>0?Number(value.trim()):Number.NaN;if(typeof value==="boolean"||!Number.isFinite(parsed)){throw fail(`field "${key}" must be a finite number (or numeric string)`)}return parsed}function readJsonEntryTimeoutSeconds(entry,fail){const timeoutSecondsRaw=entry.timeout_seconds;const timeoutAliasRaw=entry.timeout;if(timeoutSecondsRaw===void 0&&timeoutAliasRaw===void 0){return void 0}const timeoutSeconds=timeoutSecondsRaw===void 0?void 0:readJsonEntryNumber(timeoutSecondsRaw,"timeout_seconds",fail);const timeoutAlias=timeoutAliasRaw===void 0?void 0:readJsonEntryNumber(timeoutAliasRaw,"timeout",fail);if(timeoutSeconds!==void 0&&timeoutAlias!==void 0&&timeoutSeconds!==timeoutAlias){throw fail("timeout and timeout_seconds must match when both are provided")}const timeout=timeoutSeconds??timeoutAlias;if(!Number.isInteger(timeout)||timeout<=0){throw fail("timeout_seconds must be a positive integer")}return timeout}function readJsonEntryScope(entry,fail){const value=readJsonEntryString(entry,"scope",fail);if(value===void 0){return"project"}if(!SCOPE_VALUES.includes(value)){throw fail(`field "scope" must be one of: ${SCOPE_VALUES.join(", ")}`)}return value}function readJsonEntryEnvSet(entry,fail){if(!Object.hasOwn(entry,"env_set")){return void 0}const value=entry.env_set;if(value===void 0){return void 0}if(!isPlainObject(value)){throw fail('field "env_set" must be a JSON object mapping environment names to string values')}const envSet=Object.create(null);for(const[key,entryValue]of Object.entries(value)){if(typeof entryValue!=="string"){throw fail(`field "env_set" value for "${key}" must be a string`)}if(!LINKED_TEST_ENV_NAME_PATTERN.test(key)){throw fail(`field "env_set" key "${key}" is invalid`)}if(LINKED_TEST_PROTECTED_ENV_KEYS.has(key.toUpperCase())){throw fail(`field "env_set" key "${key}" is reserved for sandbox safety`)}envSet[key]=entryValue}return Object.keys(envSet).length>0?envSet:void 0}function readJsonEntryEnvClear(entry,fail){const keys=readJsonEntryStringList(entry,"env_clear",fail);if(!keys){return void 0}for(const key of keys){if(!LINKED_TEST_ENV_NAME_PATTERN.test(key)){throw fail(`field "env_clear" key "${key}" is invalid`)}if(LINKED_TEST_PROTECTED_ENV_KEYS.has(key.toUpperCase())){throw fail(`field "env_clear" key "${key}" is reserved for sandbox safety`)}}return keys}function readJsonEntryBoolean(entry,key,fail){if(!Object.hasOwn(entry,key)){return void 0}const value=entry[key];if(value===void 0){return void 0}if(typeof value!=="boolean"){throw fail(`field "${key}" must be a JSON boolean (true or false)`)}return value}function readJsonEntryMinLines(entry,fail){if(!Object.hasOwn(entry,"assert_stdout_min_lines")){return void 0}const value=entry.assert_stdout_min_lines;if(value===void 0){return void 0}const parsed=readJsonEntryNumber(value,"assert_stdout_min_lines",fail);if(!Number.isInteger(parsed)||parsed<0){throw fail('field "assert_stdout_min_lines" must be an integer >= 0')}return parsed}function readJsonEntryEqualsMap(entry,fail){if(!Object.hasOwn(entry,"assert_json_field_equals")){return void 0}const value=entry.assert_json_field_equals;if(value===void 0){return void 0}if(!isPlainObject(value)){throw fail('field "assert_json_field_equals" must be a JSON object mapping field paths to expected values')}const values=Object.create(null);for(const[key,entryValue]of Object.entries(value)){if(key.trim().length===0){throw fail('field "assert_json_field_equals" keys must be non-empty field paths')}if(typeof entryValue!=="string"&&typeof entryValue!=="number"&&typeof entryValue!=="boolean"){throw fail(`field "assert_json_field_equals" value for "${key}" must be a string, number, or boolean`)}values[key]=String(entryValue)}return Object.keys(values).length>0?values:void 0}function readJsonEntryGteMap(entry,fail){if(!Object.hasOwn(entry,"assert_json_field_gte")){return void 0}const value=entry.assert_json_field_gte;if(value===void 0){return void 0}if(!isPlainObject(value)){throw fail('field "assert_json_field_gte" must be a JSON object mapping field paths to numeric minimums')}const values=Object.create(null);for(const[key,entryValue]of Object.entries(value)){if(key.trim().length===0){throw fail('field "assert_json_field_gte" keys must be non-empty field paths')}values[key]=readJsonEntryNumber(entryValue,`assert_json_field_gte.${key}`,fail)}return Object.keys(values).length>0?values:void 0}function parseLinkedTestJsonEntry(rawEntry,label,optionName){const fail=message=>new PmCliError(`${optionName} ${label} ${message}`,EXIT_CODE.USAGE);if(!isPlainObject(rawEntry)){throw fail(`must be a JSON object with linked-test fields. Allowed keys: ${STRUCTURED_LINKED_TEST_KEYS.join(", ")}.`)}const entry=normalizeJsonEntryKeys(rawEntry,fail);const commandValue=readJsonEntryString(entry,"command",fail);const cmdAlias=readJsonEntryString(entry,"cmd",fail);if(commandValue!==void 0&&cmdAlias!==void 0&&commandValue!==cmdAlias){throw fail("command and cmd must match when both are provided")}const command=commandValue??cmdAlias;if(command===void 0||command.trim().length===0){throw fail('requires a non-empty "command" string')}const pathValue=readJsonEntryString(entry,"path",fail);const pmContextModeValue=readJsonEntryString(entry,"pm_context_mode",fail);if(pmContextModeValue!==void 0&&!LINKED_TEST_PM_CONTEXT_MODE_VALUES.includes(pmContextModeValue)){throw fail(`field "pm_context_mode" must be one of: ${LINKED_TEST_PM_CONTEXT_MODE_VALUES.join(", ")}`)}const workspaceContextModeValue=parseLinkedTestWorkspaceContextMode(readJsonEntryString(entry,"workspace_context_mode",fail),`${optionName} ${label}`);const noteValue=readJsonEntryString(entry,"note",fail);return{command,path:pathValue!==void 0&&pathValue.length>0?pathValue:void 0,scope:readJsonEntryScope(entry,fail),timeout_seconds:readJsonEntryTimeoutSeconds(entry,fail),pm_context_mode:pmContextModeValue,workspace_context_mode:workspaceContextModeValue,env_set:readJsonEntryEnvSet(entry,fail),env_clear:readJsonEntryEnvClear(entry,fail),shared_host_safe:readJsonEntryBoolean(entry,"shared_host_safe",fail),assert_stdout_contains:readJsonEntryStringList(entry,"assert_stdout_contains",fail),assert_stdout_regex:readJsonEntryRegexList(entry,"assert_stdout_regex",fail),assert_stderr_contains:readJsonEntryStringList(entry,"assert_stderr_contains",fail),assert_stderr_regex:readJsonEntryRegexList(entry,"assert_stderr_regex",fail),assert_stdout_min_lines:readJsonEntryMinLines(entry,fail),assert_json_field_equals:readJsonEntryEqualsMap(entry,fail),assert_json_field_gte:readJsonEntryGteMap(entry,fail),note:noteValue!==void 0&&noteValue.trim().length>0?noteValue.trim():void 0}}function parseLinkedTestJsonEntries(raw,optionName){const trimmed=raw.trim();if(trimmed.length===0){throw new PmCliError(`${optionName} requires a JSON object or array of objects describing linked-test entries`,EXIT_CODE.USAGE)}let parsed;try{parsed=JSON.parse(trimmed)}catch(error){throw new PmCliError(`${optionName} value is not valid JSON: ${error instanceof Error?error.message:String(error)}. Provide a JSON object or array of objects, e.g. '{"command":"node scripts/check.js --flag value, with commas","timeout_seconds":120}'.`,EXIT_CODE.USAGE)}const entries=Array.isArray(parsed)?parsed:[parsed];if(entries.length===0){throw new PmCliError(`${optionName} array must include at least one linked-test entry object`,EXIT_CODE.USAGE)}return entries.map((entry,index)=>parseLinkedTestJsonEntry(entry,entries.length>1?`entry ${index+1}`:"entry",optionName))}const _testOnlyLinkedTestParsers={parseLinkedTestJsonEntry};export{LINKED_TEST_ENV_NAME_PATTERN,LINKED_TEST_PM_CONTEXT_MODE_VALUES,LINKED_TEST_PROTECTED_ENV_KEYS,LINKED_TEST_WORKSPACE_CONTEXT_MODE_VALUES,_testOnlyLinkedTestParsers,parseLinkedTestAssertionEqualsMap,parseLinkedTestAssertionGteMap,parseLinkedTestBoolean,parseLinkedTestContextMode,parseLinkedTestEnvClear,parseLinkedTestEnvSet,parseLinkedTestJsonEntries,parseLinkedTestMinLines,parseLinkedTestRegexList,parseLinkedTestStringList,parseLinkedTestWorkspaceContextMode};
1
+ !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="7ea4de2f-42e2-5ef3-89b2-d15ba6eb252a")}catch(e2){}})();import{parseOptionalNumber}from"../../core/item/parse.js";import{EXIT_CODE}from"../../core/shared/constants.js";import{PmCliError}from"../../core/shared/errors.js";import{splitCommaList}from"../../core/shared/split-comma-list.js";import{STRUCTURED_LINKED_TEST_KEYS}from"./entry.js";import{SCOPE_VALUES}from"../../types/index.js";import{SOURCE_CONTEXT_ACCESS_ENV,SOURCE_CONTEXT_WRITE_OVERRIDE_ENV}from"../environment/source-context.js";const LINKED_TEST_PROTECTED_ENV_KEYS=new Set(["PM_PATH","PM_GLOBAL_PATH","PM_SOURCE_PM_PATH","PM_SOURCE_WORKSPACE_ROOT",SOURCE_CONTEXT_ACCESS_ENV,SOURCE_CONTEXT_WRITE_OVERRIDE_ENV,"FORCE_COLOR"]);const LINKED_TEST_ENV_NAME_PATTERN=/^[A-Za-z_][A-Za-z0-9_]*$/;const LINKED_TEST_PM_CONTEXT_MODE_VALUES=["schema","tracker","auto","none"];const LINKED_TEST_WORKSPACE_CONTEXT_MODE_VALUES=["source","isolated","snapshot"];function parseLinkedTestEnvSet(raw,optionName){if(!raw){return void 0}const assignments=raw.split(/[;\n]/).map(entry=>entry.trim()).filter(entry=>entry.length>0);if(assignments.length===0){throw new PmCliError(`${optionName} env_set must include at least one KEY=VALUE assignment`,EXIT_CODE.USAGE)}const envSet=Object.create(null);for(const assignment of assignments){const separatorIndex=assignment.indexOf("=");if(separatorIndex<=0){throw new PmCliError(`${optionName} env_set entries must use KEY=VALUE and be separated by semicolons. Example: env_set=PORT=0;PLAYWRIGHT_BASE_URL=http://127.0.0.1:4173`,EXIT_CODE.USAGE)}const key=assignment.slice(0,separatorIndex).trim();const value=assignment.slice(separatorIndex+1);if(!LINKED_TEST_ENV_NAME_PATTERN.test(key)){throw new PmCliError(`${optionName} env_set key "${key}" is invalid`,EXIT_CODE.USAGE)}if(LINKED_TEST_PROTECTED_ENV_KEYS.has(key.toUpperCase())){throw new PmCliError(`${optionName} env_set key "${key}" is reserved for sandbox safety`,EXIT_CODE.USAGE)}envSet[key]=value}return Object.keys(envSet).length>0?envSet:void 0}function parseLinkedTestEnvClear(raw,optionName){if(!raw){return void 0}const keys=splitCommaList(raw,{separators:/[;,\n]/});if(keys.length===0){throw new PmCliError(`${optionName} env_clear must include at least one environment variable name`,EXIT_CODE.USAGE)}for(const key of keys){if(!LINKED_TEST_ENV_NAME_PATTERN.test(key)){throw new PmCliError(`${optionName} env_clear key "${key}" is invalid`,EXIT_CODE.USAGE)}if(LINKED_TEST_PROTECTED_ENV_KEYS.has(key.toUpperCase())){throw new PmCliError(`${optionName} env_clear key "${key}" is reserved for sandbox safety`,EXIT_CODE.USAGE)}}return keys}function parseLinkedTestBoolean(raw,optionName,fieldLabel){if(!raw){return void 0}const value=raw.trim().toLowerCase();if(value==="true"||value==="1"||value==="yes"){return true}if(value==="false"||value==="0"||value==="no"){return false}throw new PmCliError(`${optionName} ${fieldLabel} must be one of true|false|1|0|yes|no`,EXIT_CODE.USAGE)}function parseLinkedTestContextMode(raw,optionName){if(!raw){return void 0}const value=raw.trim().toLowerCase();if(LINKED_TEST_PM_CONTEXT_MODE_VALUES.includes(value)){return value}throw new PmCliError(`${optionName} pm_context_mode must be one of: ${LINKED_TEST_PM_CONTEXT_MODE_VALUES.join(", ")}`,EXIT_CODE.USAGE)}function parseLinkedTestWorkspaceContextMode(raw,optionName){if(!raw){return void 0}const value=raw.trim().toLowerCase();if(LINKED_TEST_WORKSPACE_CONTEXT_MODE_VALUES.includes(value)){return value}throw new PmCliError(`${optionName} workspace_context_mode must be one of: ${LINKED_TEST_WORKSPACE_CONTEXT_MODE_VALUES.join(", ")}`,EXIT_CODE.USAGE)}function parseLinkedTestStringList(raw){if(!raw){return void 0}const values=splitCommaList(raw,{separators:/[;\n]/});return values.length>0?values:void 0}function parseLinkedTestRegexList(raw,optionName,fieldLabel){const values=parseLinkedTestStringList(raw);if(!values||values.length===0){return void 0}for(const pattern of values){try{new RegExp(pattern,"m")}catch(error){throw new PmCliError(`${optionName} ${fieldLabel} includes invalid regex "${pattern}": ${error instanceof Error?error.message:String(error)}`,EXIT_CODE.USAGE)}}return values}function parseLinkedTestMinLines(raw,optionName){if(!raw){return void 0}const parsed=parseOptionalNumber(raw,"assert_stdout_min_lines");if(!Number.isInteger(parsed)||parsed<0){throw new PmCliError(`${optionName} assert_stdout_min_lines must be an integer >= 0`,EXIT_CODE.USAGE)}return parsed}function parseLinkedTestAssertionEqualsMap(raw,optionName){if(!raw){return void 0}const assignments=raw.split(/[;\n]/).map(entry=>entry.trim()).filter(entry=>entry.length>0);if(assignments.length===0){throw new PmCliError(`${optionName} assert_json_field_equals must include at least one path=value assignment`,EXIT_CODE.USAGE)}const values=Object.create(null);for(const assignment of assignments){const separatorIndex=assignment.indexOf("=");if(separatorIndex<=0){throw new PmCliError(`${optionName} assert_json_field_equals entries must use path=value and be separated by semicolons`,EXIT_CODE.USAGE)}const key=assignment.slice(0,separatorIndex).trim();const value=assignment.slice(separatorIndex+1).trim();if(key.length===0||value.length===0){throw new PmCliError(`${optionName} assert_json_field_equals entries must include non-empty path and value`,EXIT_CODE.USAGE)}values[key]=value}return Object.keys(values).length>0?values:void 0}function parseLinkedTestAssertionGteMap(raw,optionName){if(!raw){return void 0}const assignments=raw.split(/[;\n]/).map(entry=>entry.trim()).filter(entry=>entry.length>0);if(assignments.length===0){throw new PmCliError(`${optionName} assert_json_field_gte must include at least one path=value assignment`,EXIT_CODE.USAGE)}const values=Object.create(null);for(const assignment of assignments){const separatorIndex=assignment.indexOf("=");if(separatorIndex<=0){throw new PmCliError(`${optionName} assert_json_field_gte entries must use path=value and be separated by semicolons`,EXIT_CODE.USAGE)}const key=assignment.slice(0,separatorIndex).trim();const valueRaw=assignment.slice(separatorIndex+1).trim();if(key.length===0||valueRaw.length===0){throw new PmCliError(`${optionName} assert_json_field_gte entries must include non-empty path and value`,EXIT_CODE.USAGE)}const value=Number(valueRaw);if(!Number.isFinite(value)){throw new PmCliError(`${optionName} assert_json_field_gte value for "${key}" must be numeric`,EXIT_CODE.USAGE)}values[key]=value}return Object.keys(values).length>0?values:void 0}const LINKED_TEST_JSON_KEY_SET=new Set(STRUCTURED_LINKED_TEST_KEYS);function isPlainObject(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function normalizeJsonEntryKeys(entry,fail){const normalized={};const unknownKeys=[];for(const[key,value]of Object.entries(entry)){const normalizedKey=key.toLowerCase();if(!LINKED_TEST_JSON_KEY_SET.has(normalizedKey)){unknownKeys.push(key);continue}if(Object.hasOwn(normalized,normalizedKey)){throw fail(`provides key "${key}" more than once after case normalization`)}normalized[normalizedKey]=value}if(unknownKeys.length>0){throw fail(`does not recognize key${unknownKeys.length>1?"s":""} ${unknownKeys.map(key=>`"${key}"`).join(", ")}. Allowed keys: ${STRUCTURED_LINKED_TEST_KEYS.join(", ")}.`)}return normalized}function readJsonEntryString(entry,key,fail){if(!Object.hasOwn(entry,key)){return void 0}const value=entry[key];if(value===void 0){return void 0}if(typeof value!=="string"){throw fail(`field "${key}" must be a JSON string`)}return value}function readJsonEntryStringList(entry,key,fail){if(!Object.hasOwn(entry,key)){return void 0}const value=entry[key];if(value===void 0){return void 0}const list=typeof value==="string"?[value]:value;if(!Array.isArray(list)||list.some(item=>typeof item!=="string")){throw fail(`field "${key}" must be a string or an array of strings`)}const values=list.filter(item=>item.length>0);return values.length>0?values:void 0}function readJsonEntryRegexList(entry,key,fail){const values=readJsonEntryStringList(entry,key,fail);if(!values){return void 0}for(const pattern of values){try{new RegExp(pattern,"m")}catch(error){throw fail(`field "${key}" includes invalid regex "${pattern}": ${error instanceof Error?error.message:String(error)}`)}}return values}function readJsonEntryNumber(value,key,fail){const parsed=typeof value==="number"?value:typeof value==="string"&&value.trim().length>0?Number(value.trim()):Number.NaN;if(typeof value==="boolean"||!Number.isFinite(parsed)){throw fail(`field "${key}" must be a finite number (or numeric string)`)}return parsed}function readJsonEntryTimeoutSeconds(entry,fail){const timeoutSecondsRaw=entry.timeout_seconds;const timeoutAliasRaw=entry.timeout;if(timeoutSecondsRaw===void 0&&timeoutAliasRaw===void 0){return void 0}const timeoutSeconds=timeoutSecondsRaw===void 0?void 0:readJsonEntryNumber(timeoutSecondsRaw,"timeout_seconds",fail);const timeoutAlias=timeoutAliasRaw===void 0?void 0:readJsonEntryNumber(timeoutAliasRaw,"timeout",fail);if(timeoutSeconds!==void 0&&timeoutAlias!==void 0&&timeoutSeconds!==timeoutAlias){throw fail("timeout and timeout_seconds must match when both are provided")}const timeout=timeoutSeconds??timeoutAlias;if(!Number.isInteger(timeout)||timeout<=0){throw fail("timeout_seconds must be a positive integer")}return timeout}function readJsonEntryScope(entry,fail){const value=readJsonEntryString(entry,"scope",fail);if(value===void 0){return"project"}if(!SCOPE_VALUES.includes(value)){throw fail(`field "scope" must be one of: ${SCOPE_VALUES.join(", ")}`)}return value}function readJsonEntryEnvSet(entry,fail){if(!Object.hasOwn(entry,"env_set")){return void 0}const value=entry.env_set;if(value===void 0){return void 0}if(!isPlainObject(value)){throw fail('field "env_set" must be a JSON object mapping environment names to string values')}const envSet=Object.create(null);for(const[key,entryValue]of Object.entries(value)){if(typeof entryValue!=="string"){throw fail(`field "env_set" value for "${key}" must be a string`)}if(!LINKED_TEST_ENV_NAME_PATTERN.test(key)){throw fail(`field "env_set" key "${key}" is invalid`)}if(LINKED_TEST_PROTECTED_ENV_KEYS.has(key.toUpperCase())){throw fail(`field "env_set" key "${key}" is reserved for sandbox safety`)}envSet[key]=entryValue}return Object.keys(envSet).length>0?envSet:void 0}function readJsonEntryEnvClear(entry,fail){const keys=readJsonEntryStringList(entry,"env_clear",fail);if(!keys){return void 0}for(const key of keys){if(!LINKED_TEST_ENV_NAME_PATTERN.test(key)){throw fail(`field "env_clear" key "${key}" is invalid`)}if(LINKED_TEST_PROTECTED_ENV_KEYS.has(key.toUpperCase())){throw fail(`field "env_clear" key "${key}" is reserved for sandbox safety`)}}return keys}function readJsonEntryBoolean(entry,key,fail){if(!Object.hasOwn(entry,key)){return void 0}const value=entry[key];if(value===void 0){return void 0}if(typeof value!=="boolean"){throw fail(`field "${key}" must be a JSON boolean (true or false)`)}return value}function readJsonEntryMinLines(entry,fail){if(!Object.hasOwn(entry,"assert_stdout_min_lines")){return void 0}const value=entry.assert_stdout_min_lines;if(value===void 0){return void 0}const parsed=readJsonEntryNumber(value,"assert_stdout_min_lines",fail);if(!Number.isInteger(parsed)||parsed<0){throw fail('field "assert_stdout_min_lines" must be an integer >= 0')}return parsed}function readJsonEntryEqualsMap(entry,fail){if(!Object.hasOwn(entry,"assert_json_field_equals")){return void 0}const value=entry.assert_json_field_equals;if(value===void 0){return void 0}if(!isPlainObject(value)){throw fail('field "assert_json_field_equals" must be a JSON object mapping field paths to expected values')}const values=Object.create(null);for(const[key,entryValue]of Object.entries(value)){if(key.trim().length===0){throw fail('field "assert_json_field_equals" keys must be non-empty field paths')}if(typeof entryValue!=="string"&&typeof entryValue!=="number"&&typeof entryValue!=="boolean"){throw fail(`field "assert_json_field_equals" value for "${key}" must be a string, number, or boolean`)}values[key]=String(entryValue)}return Object.keys(values).length>0?values:void 0}function readJsonEntryGteMap(entry,fail){if(!Object.hasOwn(entry,"assert_json_field_gte")){return void 0}const value=entry.assert_json_field_gte;if(value===void 0){return void 0}if(!isPlainObject(value)){throw fail('field "assert_json_field_gte" must be a JSON object mapping field paths to numeric minimums')}const values=Object.create(null);for(const[key,entryValue]of Object.entries(value)){if(key.trim().length===0){throw fail('field "assert_json_field_gte" keys must be non-empty field paths')}values[key]=readJsonEntryNumber(entryValue,`assert_json_field_gte.${key}`,fail)}return Object.keys(values).length>0?values:void 0}function parseLinkedTestJsonEntry(rawEntry,label,optionName){const fail=message=>new PmCliError(`${optionName} ${label} ${message}`,EXIT_CODE.USAGE);if(!isPlainObject(rawEntry)){throw fail(`must be a JSON object with linked-test fields. Allowed keys: ${STRUCTURED_LINKED_TEST_KEYS.join(", ")}.`)}const entry=normalizeJsonEntryKeys(rawEntry,fail);const commandValue=readJsonEntryString(entry,"command",fail);const cmdAlias=readJsonEntryString(entry,"cmd",fail);if(commandValue!==void 0&&cmdAlias!==void 0&&commandValue!==cmdAlias){throw fail("command and cmd must match when both are provided")}const command=commandValue??cmdAlias;if(command===void 0||command.trim().length===0){throw fail('requires a non-empty "command" string')}const pathValue=readJsonEntryString(entry,"path",fail);const pmContextModeValue=readJsonEntryString(entry,"pm_context_mode",fail);if(pmContextModeValue!==void 0&&!LINKED_TEST_PM_CONTEXT_MODE_VALUES.includes(pmContextModeValue)){throw fail(`field "pm_context_mode" must be one of: ${LINKED_TEST_PM_CONTEXT_MODE_VALUES.join(", ")}`)}const workspaceContextModeValue=parseLinkedTestWorkspaceContextMode(readJsonEntryString(entry,"workspace_context_mode",fail),`${optionName} ${label}`);const noteValue=readJsonEntryString(entry,"note",fail);return{command,path:pathValue!==void 0&&pathValue.length>0?pathValue:void 0,scope:readJsonEntryScope(entry,fail),timeout_seconds:readJsonEntryTimeoutSeconds(entry,fail),pm_context_mode:pmContextModeValue,workspace_context_mode:workspaceContextModeValue,env_set:readJsonEntryEnvSet(entry,fail),env_clear:readJsonEntryEnvClear(entry,fail),shared_host_safe:readJsonEntryBoolean(entry,"shared_host_safe",fail),assert_stdout_contains:readJsonEntryStringList(entry,"assert_stdout_contains",fail),assert_stdout_regex:readJsonEntryRegexList(entry,"assert_stdout_regex",fail),assert_stderr_contains:readJsonEntryStringList(entry,"assert_stderr_contains",fail),assert_stderr_regex:readJsonEntryRegexList(entry,"assert_stderr_regex",fail),assert_stdout_min_lines:readJsonEntryMinLines(entry,fail),assert_json_field_equals:readJsonEntryEqualsMap(entry,fail),assert_json_field_gte:readJsonEntryGteMap(entry,fail),note:noteValue!==void 0&&noteValue.trim().length>0?noteValue.trim():void 0}}function parseLinkedTestJsonEntries(raw,optionName){const trimmed=raw.trim();if(trimmed.length===0){throw new PmCliError(`${optionName} requires a JSON object or array of objects describing linked-test entries`,EXIT_CODE.USAGE)}let parsed;try{parsed=JSON.parse(trimmed)}catch(error){throw new PmCliError(`${optionName} value is not valid JSON: ${error instanceof Error?error.message:String(error)}. Provide a JSON object or array of objects, e.g. '{"command":"node scripts/check.js --flag value, with commas","timeout_seconds":120}'.`,EXIT_CODE.USAGE)}const entries=Array.isArray(parsed)?parsed:[parsed];if(entries.length===0){throw new PmCliError(`${optionName} array must include at least one linked-test entry object`,EXIT_CODE.USAGE)}return entries.map((entry,index)=>parseLinkedTestJsonEntry(entry,entries.length>1?`entry ${index+1}`:"entry",optionName))}const _testOnlyLinkedTestParsers={parseLinkedTestJsonEntry};export{LINKED_TEST_ENV_NAME_PATTERN,LINKED_TEST_PM_CONTEXT_MODE_VALUES,LINKED_TEST_PROTECTED_ENV_KEYS,LINKED_TEST_WORKSPACE_CONTEXT_MODE_VALUES,_testOnlyLinkedTestParsers,parseLinkedTestAssertionEqualsMap,parseLinkedTestAssertionGteMap,parseLinkedTestBoolean,parseLinkedTestContextMode,parseLinkedTestEnvClear,parseLinkedTestEnvSet,parseLinkedTestJsonEntries,parseLinkedTestMinLines,parseLinkedTestRegexList,parseLinkedTestStringList,parseLinkedTestWorkspaceContextMode};
2
2
  //# sourceMappingURL=parsers.js.map
package/dist/types.d.ts CHANGED
@@ -188,7 +188,7 @@ export interface LinkedTest {
188
188
  /** Value that configures or reports timeout seconds for this contract. */
189
189
  timeout_seconds?: number;
190
190
  /** Strategy used to control pm context behavior. */
191
- pm_context_mode?: "schema" | "tracker" | "auto";
191
+ pm_context_mode?: "schema" | "tracker" | "auto" | "none";
192
192
  /** Strategy used for source-workspace visibility and command working directory. */
193
193
  workspace_context_mode?: "source" | "isolated" | "snapshot";
194
194
  /** Immutable provenance captured when the linked command enters tracker data. */
@@ -582,9 +582,9 @@ export interface ItemTestRunExecution {
582
582
  /** Exact linked command selected for execution. */
583
583
  command: string;
584
584
  /** Context mode requested before linked-test overrides or auto-remediation. */
585
- requested_pm_context_mode?: "schema" | "tracker" | "auto";
585
+ requested_pm_context_mode?: "schema" | "tracker" | "auto" | "none";
586
586
  /** Effective context mode used by the linked command. */
587
- pm_context_mode?: "schema" | "tracker" | "auto";
587
+ pm_context_mode?: "schema" | "tracker" | "auto" | "none";
588
588
  /** Effective source-workspace mode used by the linked command. */
589
589
  workspace_context_mode?: "source" | "isolated" | "snapshot";
590
590
  /** Trust classification applied before execution. */
package/dist/types.js CHANGED
@@ -1,2 +1,2 @@
1
- !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="a966bb77-c4be-593b-93f5-b6277072160e")}catch(e2){}})();const BUILTIN_ITEM_TYPE_VALUES=["Epic","Feature","Task","Chore","Issue","Decision","Event","Reminder","Milestone","Meeting","Plan"];const ITEM_TYPE_VALUES=BUILTIN_ITEM_TYPE_VALUES;const STATUS_VALUES=["draft","open","in_progress","blocked","closed","canceled"];const RUNTIME_STATUS_ROLE_VALUES=["draft","active","blocked","terminal","terminal_done","terminal_canceled","default_open","default_close","default_cancel"];const RUNTIME_FIELD_TYPE_VALUES=["string","number","boolean","string_array","array","object"];const RUNTIME_FIELD_COMMAND_VALUES=["create","update","update_many","list","search","calendar","context"];const RUNTIME_UNKNOWN_FIELD_POLICY_VALUES=["allow","warn","reject"];const DEPENDENCY_KIND_VALUES=["blocks","parent","child","parent_child","child_of","related","related_to","discovered_from","blocked_by","incident_from","epic","implements","recurs_from","supersedes","task","verifies"];const SCOPE_VALUES=["project","global"];const RISK_VALUES=["low","medium","high","critical"];const ISSUE_SEVERITY_VALUES=["low","medium","high","critical"];const CONFIDENCE_TEXT_VALUES=["low","medium","high"];const ITEM_FORMAT_VALUES=["toon","json_markdown"];const SPRINT_RELEASE_FORMAT_POLICY_VALUES=["warn","strict_error"];const PARENT_REFERENCE_POLICY_VALUES=["warn","strict_error"];const VALIDATE_METADATA_PROFILE_VALUES=["core","strict","custom"];const GOVERNANCE_PRESET_VALUES=["minimal","default","strict","custom"];const GOVERNANCE_OWNERSHIP_ENFORCEMENT_VALUES=["none","warn","strict"];const GOVERNANCE_CREATE_MODE_DEFAULT_VALUES=["progressive","strict"];const GOVERNANCE_CLOSE_VALIDATION_DEFAULT_VALUES=["off","warn","strict"];const GOVERNANCE_WORKFLOW_ENFORCEMENT_VALUES=["off","warn","strict"];const GOVERNANCE_DUPLICATE_DETECTION_MODE_VALUES=["off","advisory","strict"];const VALIDATE_METADATA_REQUIRED_FIELD_VALUES=["author","acceptance_criteria","estimated_minutes","close_reason","reviewer","risk","confidence","sprint","release"];const RECURRENCE_FREQUENCY_VALUES=["daily","weekly","monthly","yearly"];const RECURRENCE_WEEKDAY_VALUES=["mon","tue","wed","thu","fri","sat","sun"];function weekdayOrderIndex(value){return RECURRENCE_WEEKDAY_VALUES.indexOf(value)}const PLAN_MODE_VALUES=["draft","research","review","approved","executing","paused","completed","superseded"];const PLAN_STEP_STATUS_VALUES=["pending","in_progress","completed","blocked","skipped","superseded"];const PLAN_HARNESS_VALUES=["codex","claude-code","cursor","generic"];const PLAN_STEP_LINK_KIND_VALUES=["related","blocks","blocked_by","depends_on","discovered_from","implements","recurs_from","verifies","supersedes"];const CONTEXT_DEPTH_VALUES=["brief","standard","deep","full"];const CONTEXT_SECTION_VALUES=["hierarchy","activity","progress","recently_created","unparented","blockers","files","workload","staleness","tests"];export{BUILTIN_ITEM_TYPE_VALUES,CONFIDENCE_TEXT_VALUES,CONTEXT_DEPTH_VALUES,CONTEXT_SECTION_VALUES,DEPENDENCY_KIND_VALUES,GOVERNANCE_CLOSE_VALIDATION_DEFAULT_VALUES,GOVERNANCE_CREATE_MODE_DEFAULT_VALUES,GOVERNANCE_DUPLICATE_DETECTION_MODE_VALUES,GOVERNANCE_OWNERSHIP_ENFORCEMENT_VALUES,GOVERNANCE_PRESET_VALUES,GOVERNANCE_WORKFLOW_ENFORCEMENT_VALUES,ISSUE_SEVERITY_VALUES,ITEM_FORMAT_VALUES,ITEM_TYPE_VALUES,PARENT_REFERENCE_POLICY_VALUES,PLAN_HARNESS_VALUES,PLAN_MODE_VALUES,PLAN_STEP_LINK_KIND_VALUES,PLAN_STEP_STATUS_VALUES,RECURRENCE_FREQUENCY_VALUES,RECURRENCE_WEEKDAY_VALUES,RISK_VALUES,RUNTIME_FIELD_COMMAND_VALUES,RUNTIME_FIELD_TYPE_VALUES,RUNTIME_STATUS_ROLE_VALUES,RUNTIME_UNKNOWN_FIELD_POLICY_VALUES,SCOPE_VALUES,SPRINT_RELEASE_FORMAT_POLICY_VALUES,STATUS_VALUES,VALIDATE_METADATA_PROFILE_VALUES,VALIDATE_METADATA_REQUIRED_FIELD_VALUES,weekdayOrderIndex};
1
+ !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="e33ee377-aae0-5158-9af6-e6081287a85b")}catch(e2){}})();const BUILTIN_ITEM_TYPE_VALUES=["Epic","Feature","Task","Chore","Issue","Decision","Event","Reminder","Milestone","Meeting","Plan"];const ITEM_TYPE_VALUES=BUILTIN_ITEM_TYPE_VALUES;const STATUS_VALUES=["draft","open","in_progress","blocked","closed","canceled"];const RUNTIME_STATUS_ROLE_VALUES=["draft","active","blocked","terminal","terminal_done","terminal_canceled","default_open","default_close","default_cancel"];const RUNTIME_FIELD_TYPE_VALUES=["string","number","boolean","string_array","array","object"];const RUNTIME_FIELD_COMMAND_VALUES=["create","update","update_many","list","search","calendar","context"];const RUNTIME_UNKNOWN_FIELD_POLICY_VALUES=["allow","warn","reject"];const DEPENDENCY_KIND_VALUES=["blocks","parent","child","parent_child","child_of","related","related_to","discovered_from","blocked_by","incident_from","epic","implements","recurs_from","supersedes","task","verifies"];const SCOPE_VALUES=["project","global"];const RISK_VALUES=["low","medium","high","critical"];const ISSUE_SEVERITY_VALUES=["low","medium","high","critical"];const CONFIDENCE_TEXT_VALUES=["low","medium","high"];const ITEM_FORMAT_VALUES=["toon","json_markdown"];const SPRINT_RELEASE_FORMAT_POLICY_VALUES=["warn","strict_error"];const PARENT_REFERENCE_POLICY_VALUES=["warn","strict_error"];const VALIDATE_METADATA_PROFILE_VALUES=["core","strict","custom"];const GOVERNANCE_PRESET_VALUES=["minimal","default","strict","custom"];const GOVERNANCE_OWNERSHIP_ENFORCEMENT_VALUES=["none","warn","strict"];const GOVERNANCE_CREATE_MODE_DEFAULT_VALUES=["progressive","strict"];const GOVERNANCE_CLOSE_VALIDATION_DEFAULT_VALUES=["off","warn","strict"];const GOVERNANCE_WORKFLOW_ENFORCEMENT_VALUES=["off","warn","strict"];const GOVERNANCE_DUPLICATE_DETECTION_MODE_VALUES=["off","advisory","strict"];const VALIDATE_METADATA_REQUIRED_FIELD_VALUES=["author","acceptance_criteria","estimated_minutes","close_reason","reviewer","risk","confidence","sprint","release"];const RECURRENCE_FREQUENCY_VALUES=["daily","weekly","monthly","yearly"];const RECURRENCE_WEEKDAY_VALUES=["mon","tue","wed","thu","fri","sat","sun"];function weekdayOrderIndex(value){return RECURRENCE_WEEKDAY_VALUES.indexOf(value)}const PLAN_MODE_VALUES=["draft","research","review","approved","executing","paused","completed","superseded"];const PLAN_STEP_STATUS_VALUES=["pending","in_progress","completed","blocked","skipped","superseded"];const PLAN_HARNESS_VALUES=["codex","claude-code","cursor","generic"];const PLAN_STEP_LINK_KIND_VALUES=["related","blocks","blocked_by","depends_on","discovered_from","implements","recurs_from","verifies","supersedes"];const CONTEXT_DEPTH_VALUES=["brief","standard","deep","full"];const CONTEXT_SECTION_VALUES=["hierarchy","activity","progress","recently_created","unparented","blockers","files","workload","staleness","tests"];export{BUILTIN_ITEM_TYPE_VALUES,CONFIDENCE_TEXT_VALUES,CONTEXT_DEPTH_VALUES,CONTEXT_SECTION_VALUES,DEPENDENCY_KIND_VALUES,GOVERNANCE_CLOSE_VALIDATION_DEFAULT_VALUES,GOVERNANCE_CREATE_MODE_DEFAULT_VALUES,GOVERNANCE_DUPLICATE_DETECTION_MODE_VALUES,GOVERNANCE_OWNERSHIP_ENFORCEMENT_VALUES,GOVERNANCE_PRESET_VALUES,GOVERNANCE_WORKFLOW_ENFORCEMENT_VALUES,ISSUE_SEVERITY_VALUES,ITEM_FORMAT_VALUES,ITEM_TYPE_VALUES,PARENT_REFERENCE_POLICY_VALUES,PLAN_HARNESS_VALUES,PLAN_MODE_VALUES,PLAN_STEP_LINK_KIND_VALUES,PLAN_STEP_STATUS_VALUES,RECURRENCE_FREQUENCY_VALUES,RECURRENCE_WEEKDAY_VALUES,RISK_VALUES,RUNTIME_FIELD_COMMAND_VALUES,RUNTIME_FIELD_TYPE_VALUES,RUNTIME_STATUS_ROLE_VALUES,RUNTIME_UNKNOWN_FIELD_POLICY_VALUES,SCOPE_VALUES,SPRINT_RELEASE_FORMAT_POLICY_VALUES,STATUS_VALUES,VALIDATE_METADATA_PROFILE_VALUES,VALIDATE_METADATA_REQUIRED_FIELD_VALUES,weekdayOrderIndex};
2
2
  //# sourceMappingURL=types.js.map
@@ -0,0 +1,21 @@
1
+ # Agent Read and Test Receipts
2
+
3
+ Tracked by [pm-s8ztcl](../.agents/pm/issues/pm-s8ztcl.toon), [pm-aao1hy](../.agents/pm/issues/pm-aao1hy.toon), and [pm-c3aiik](../.agents/pm/issues/pm-c3aiik.toon).
4
+
5
+ ## Agent Quick Context
6
+
7
+ The SDK owns the authoritative read and test results. CLI JSON preserves the same receipts so an agent can distinguish a completed action from recorded evidence, and can continue a bounded history read without silently losing rows.
8
+
9
+ ## Command Help
10
+
11
+ `pm help <command> --json` reports `intent_source`. A named help bundle supplies `help_bundle`; when a command has no named bundle, the command description supplies `command_description`. Root help applies only to the root request. An unbundled command shows a command-specific help invocation and empty `tips` rather than unrelated root examples.
12
+
13
+ ## Linked Test Runs
14
+
15
+ `pm test <id> --run --json` returns `evidence_recording` on an executed run. `recorded: true` means the test summary was appended to tracker history. `recorded: false` includes a reason such as `tracking_disabled` or `write_failed`; the disabled case also includes a recovery command. The command's `changed` field is true when the run was recorded even if no test definition changed. The receipt does not claim that a passing process exit was persisted when tracking is disabled.
16
+
17
+ Enable recording with `pm config project set test-result-tracking --policy enabled`, then rerun the linked test. The history `test_run_track` event is the durable evidence to inspect. Use a temporary tracker for experiments; repository linked tests must keep real `.agents/pm` data isolated.
18
+
19
+ ## History Diff Continuation
20
+
21
+ `pm history <id> --diff --json` can return separate `compact_history` and `diff` continuation cursors under a bounded output budget. Continue the `diff` cursor to retrieve subsequent diff rows. Its `projection.row_key` identifies the active collection and `count` counts that collection. A budget cursor is available only when `next_cursor` is present. When `applied_bound.kind` is `output_limit`, `has_more: true` can instead mean the explicit row limit withheld rows; raise `--output-limit` to retrieve them. If `truncated` remains true without a cursor, increase `--output-budget` or select a smaller history range. A single diff entry larger than the chosen budget requires a larger budget.
@@ -17,8 +17,8 @@ pm-cli/ (repo root)
17
17
  │ │ ├── pm-developer/ # Developer execution loop with evidence requirements
18
18
  │ │ ├── pm-release/ # Release gate sequence and evidence linking
19
19
  │ │ ├── pm-audit/ # Comprehensive audit suite
20
- │ │ └── pm-planner/ # Planning: decompose, prioritize, triage
21
- │ ├── commands/ # Slash-command definitions (one .md per /pm-* command)
20
+ │ │ ├── pm-planner/ # Planning: decompose, prioritize, triage
21
+ │ │ └── pm-*/ # Nine focused skill invocations (all /pm-* names retained)
22
22
  │ ├── hooks/
23
23
  │ │ ├── hooks.json # SessionStart hook definition
24
24
  │ │ └── session-start.mjs # Injects pm context at session start
@@ -34,9 +34,14 @@ pm-cli/ (repo root)
34
34
 
35
35
  The MCP server itself lives at `src/mcp/server.ts` (compiled to `dist/mcp/server.js`) and is bundled with the npm package as the `pm-mcp` binary.
36
36
 
37
+ `.claude-plugin/marketplace.json` is the current Claude marketplace entrypoint.
38
+ The root `marketplace.json` remains for older marketplace consumers. Both files
39
+ must contain identical bytes after version stamping; the plugin contract test
40
+ checks this so the compatibility copy cannot silently drift.
41
+
37
42
  ## Capability Inventory
38
43
 
39
- The canonical user-facing inventory for MCP tools, slash commands, skills, subagents, and `pm_run` actions lives in [`plugins/pm-claude/README.md`](../plugins/pm-claude/README.md). This page focuses on architecture, launcher behavior, and smoke-test expectations so capability counts do not drift between docs.
44
+ The canonical user-facing inventory for MCP tools, skills, slash invocations, subagents, and `pm_run` actions lives in [`plugins/pm-claude/README.md`](../plugins/pm-claude/README.md). This page focuses on architecture, launcher behavior, and smoke-test expectations so capability counts do not drift between docs.
40
45
 
41
46
  ## Installation Methods
42
47
 
@@ -49,7 +54,7 @@ Add the pm-cli GitHub repo as a marketplace source, then install:
49
54
  /plugin install pm-claude@pm
50
55
  ```
51
56
 
52
- This clones the repo, reads `.claude-plugin/marketplace.json` at the root, installs the plugin from `./plugins/pm-claude/`, and configures the MCP server, skills, slash commands, subagents, and the session hook automatically.
57
+ This clones the repo, reads `.claude-plugin/marketplace.json` at the root, installs the plugin from `./plugins/pm-claude/`, and configures the MCP server, skills with the same `/pm-*` names, subagents, and the session hook automatically.
53
58
 
54
59
  ### 2. Global MCP via Claude Code CLI (MCP tools only)
55
60
 
@@ -57,7 +62,7 @@ This clones the repo, reads `.claude-plugin/marketplace.json` at the root, insta
57
62
  claude mcp add --transport stdio pm-mcp -- npx -y --package=@unbrained/pm-cli@latest pm-mcp
58
63
  ```
59
64
 
60
- Gives you the 32 MCP tools without skills or slash commands.
65
+ Gives you the 32 MCP tools without skills.
61
66
 
62
67
  ### 3. Direct project `.mcp.json` (project-scoped MCP only)
63
68
 
@@ -171,8 +176,8 @@ For migration details and automation expectations, see:
171
176
  ### Validate manifests
172
177
 
173
178
  ```bash
174
- claude plugin validate .claude-plugin/marketplace.json
175
- claude plugin validate plugins/pm-claude/.claude-plugin/plugin.json
179
+ claude plugin validate . --strict
180
+ claude plugin validate plugins/pm-claude --strict
176
181
  ```
177
182
 
178
183
  ### Manual verification
@@ -1,6 +1,6 @@
1
1
  # Noun–Verb CLI Grammar and Compatibility Policy
2
2
 
3
- Tracked by [pm-pbyu](../.agents/pm/decisions/pm-pbyu.toon), implemented through [pm-0z7n](../.agents/pm/features/pm-0z7n.toon), [pm-pfqi](../.agents/pm/tasks/pm-pfqi.toon), [pm-yy8rmx](../.agents/pm/tasks/pm-yy8rmx.toon), [pm-wt43zj](../.agents/pm/tasks/pm-wt43zj.toon), [pm-e2bq](../.agents/pm/features/pm-e2bq.toon), and [pm-yql1](../.agents/pm/tasks/pm-yql1.toon).
3
+ Tracked by [pm-pbyu](../.agents/pm/decisions/pm-pbyu.toon), implemented through [pm-0z7n](../.agents/pm/features/pm-0z7n.toon), [pm-0mox](../.agents/pm/tasks/pm-0mox.toon), [pm-pfqi](../.agents/pm/tasks/pm-pfqi.toon), [pm-yy8rmx](../.agents/pm/tasks/pm-yy8rmx.toon), [pm-wt43zj](../.agents/pm/tasks/pm-wt43zj.toon), [pm-e2bq](../.agents/pm/features/pm-e2bq.toon), and [pm-yql1](../.agents/pm/tasks/pm-yql1.toon).
4
4
 
5
5
  ## Agent Quick Context
6
6
 
@@ -98,6 +98,23 @@ pm config project set ux_deprecation_hints false
98
98
 
99
99
  This setting changes presentation only. It does not disable aliases or change command results. The uniform machine result-envelope receipt is intentionally deferred to its separately tracked cross-command contract so this implementation does not create a list-only shape.
100
100
 
101
+ ### Removal evidence
102
+
103
+ `pm telemetry stats --json` reports `alias_usage` (declared deprecated spelling,
104
+ canonical target, retained hit count, and last seen time), `zero_use_aliases`,
105
+ and `alias_usage_retention_days`. These counts are held only in the local
106
+ telemetry runtime state when telemetry consent is enabled. The same process
107
+ opt-outs used by telemetry suppress recording. Diagnostics reads and new alias
108
+ hits prune expired observations from disk; `pm telemetry clear` removes them
109
+ immediately. Canonical spellings do
110
+ not write an alias counter.
111
+
112
+ An empty local counter is not evidence that an alias is unused across all
113
+ workspaces. The open GA stability decision [pm-agou](../.agents/pm/decisions/pm-agou.toon)
114
+ must set the number of releases with zero observed use across reporting
115
+ workspaces before any removal at a major version boundary. Until that decision
116
+ and cross-workspace evidence exist, published aliases remain executable.
117
+
101
118
  ## Enforcement
102
119
 
103
120
  `pnpm quality:command-grammar` builds the SDK, reads the live runtime command contracts, and compares them with the checked-in destination and alias tables. Package-owned destination rows are conditional because installed packages vary by workspace; every activated package command still requires a declared row, while an inactive package does not make its row stale. The gate also proves parity between discoverable SDK actions, the MCP `pm_run` action enum, and narrow MCP tools. The same gate runs inside `quality:static`, alongside contract drift checks. Its negative controls prove that unknown commands, stale core rows, broken alias targets, MCP drift, and surface-ceiling growth fail upward.
@@ -67,6 +67,8 @@ Precedence:
67
67
 
68
68
  When `settings.json` cannot be loaded, `pm` falls back to built-in defaults and prints a one-time `settings_read_fs_error`, `settings_read_invalid_json`, or `settings_read_invalid_schema` warning to stderr (stdout output is unchanged); run `pm health` for remediation.
69
69
 
70
+ If the existing project `settings.json` has invalid JSON, a configuration write refuses with `settings_write_invalid_existing_json`. It leaves the file and workspace history untouched. Repair the syntax in `.agents/pm/settings.json`, run `pm health`, then retry the configuration command. The read fallback to defaults does not authorize replacing malformed settings.
71
+
70
72
  ## Common Settings
71
73
 
72
74
  | Setting | Purpose |