@muggleai/works 5.24.0 → 5.25.0-staging.184

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 (66) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/README.md +1 -0
  3. package/dist/{chunk-FEHTWWVH.js → chunk-BJGZAKBB.js} +234 -5
  4. package/dist/{chunk-GLTZIZVT.js → chunk-CE5HUVNQ.js} +26 -2
  5. package/dist/cli.js +2 -2
  6. package/dist/index.js +2 -2
  7. package/dist/plugin/.claude-plugin/plugin.json +1 -1
  8. package/dist/plugin/.codex-mcp.json +1 -1
  9. package/dist/plugin/.codex-plugin/plugin.json +1 -1
  10. package/dist/plugin/.cursor-plugin/plugin.json +1 -1
  11. package/dist/plugin/.mcp.json +1 -1
  12. package/dist/plugin/agents/test-prepare-runner.md +3 -3
  13. package/dist/plugin/skills/_shared/dev-loop/run.md +4 -1
  14. package/dist/plugin/skills/_shared/post-merge-cleanup.md +7 -6
  15. package/dist/plugin/skills/_shared/pr-branch-worktree.md +7 -6
  16. package/dist/plugin/skills/_shared/sync-branch-with-base.md +39 -4
  17. package/dist/plugin/skills/_shared/use-worktrees.md +12 -6
  18. package/dist/plugin/skills/do/e2e-acceptance.md +1 -1
  19. package/dist/plugin/skills/do/pre-flight.md +1 -1
  20. package/dist/plugin/skills/do/wave-e2e.md +2 -2
  21. package/dist/plugin/skills/muggle-preferences/preference-gates/autoRebase.md +3 -3
  22. package/dist/plugin/skills/muggle-test/execute-local.md +2 -2
  23. package/dist/plugin/skills/muggle-test-feature-local/SKILL.md +3 -8
  24. package/dist/plugin/skills/muggle-test-prepare/SKILL.md +42 -29
  25. package/dist/plugin/skills/muggle-test-prepare/steps/check-running.md +25 -10
  26. package/dist/plugin/skills/muggle-test-prepare/steps/e2e-instructions.md +1 -1
  27. package/dist/plugin/skills/muggle-test-prepare/steps/env-file.md +8 -5
  28. package/dist/plugin/skills/muggle-test-prepare/steps/readiness-report.md +22 -18
  29. package/dist/plugin/skills/muggle-test-prepare/steps/rebase-check.md +13 -1
  30. package/dist/plugin/skills/muggle-test-prepare/steps/replay-or-learn.md +2 -2
  31. package/dist/plugin/skills/muggle-test-prepare/steps/resolve-sources.md +39 -0
  32. package/dist/plugin/skills/muggle-test-prepare/steps/reuse-plan.md +7 -5
  33. package/dist/plugin/skills/muggle-test-prepare/steps/smoke-test.md +2 -2
  34. package/dist/plugin/skills/muggle-test-prepare/steps/start-services.md +4 -4
  35. package/dist/release-manifest.json +3 -3
  36. package/dist/src-BYDDPSF6.js +1 -0
  37. package/package.json +2 -2
  38. package/plugin/.claude-plugin/plugin.json +1 -1
  39. package/plugin/.codex-mcp.json +1 -1
  40. package/plugin/.codex-plugin/plugin.json +1 -1
  41. package/plugin/.cursor-plugin/plugin.json +1 -1
  42. package/plugin/.mcp.json +1 -1
  43. package/plugin/agents/test-prepare-runner.md +3 -3
  44. package/plugin/skills/_shared/dev-loop/run.md +4 -1
  45. package/plugin/skills/_shared/post-merge-cleanup.md +7 -6
  46. package/plugin/skills/_shared/pr-branch-worktree.md +7 -6
  47. package/plugin/skills/_shared/sync-branch-with-base.md +39 -4
  48. package/plugin/skills/_shared/use-worktrees.md +12 -6
  49. package/plugin/skills/do/e2e-acceptance.md +1 -1
  50. package/plugin/skills/do/pre-flight.md +1 -1
  51. package/plugin/skills/do/wave-e2e.md +2 -2
  52. package/plugin/skills/muggle-preferences/preference-gates/autoRebase.md +3 -3
  53. package/plugin/skills/muggle-test/execute-local.md +2 -2
  54. package/plugin/skills/muggle-test-feature-local/SKILL.md +3 -8
  55. package/plugin/skills/muggle-test-prepare/SKILL.md +42 -29
  56. package/plugin/skills/muggle-test-prepare/steps/check-running.md +25 -10
  57. package/plugin/skills/muggle-test-prepare/steps/e2e-instructions.md +1 -1
  58. package/plugin/skills/muggle-test-prepare/steps/env-file.md +8 -5
  59. package/plugin/skills/muggle-test-prepare/steps/readiness-report.md +22 -18
  60. package/plugin/skills/muggle-test-prepare/steps/rebase-check.md +13 -1
  61. package/plugin/skills/muggle-test-prepare/steps/replay-or-learn.md +2 -2
  62. package/plugin/skills/muggle-test-prepare/steps/resolve-sources.md +39 -0
  63. package/plugin/skills/muggle-test-prepare/steps/reuse-plan.md +7 -5
  64. package/plugin/skills/muggle-test-prepare/steps/smoke-test.md +2 -2
  65. package/plugin/skills/muggle-test-prepare/steps/start-services.md +4 -4
  66. package/dist/src-3MQ2UWSP.js +0 -1
@@ -9,7 +9,7 @@
9
9
  "name": "muggleai",
10
10
  "source": "./plugin",
11
11
  "description": "Real-browser E2E acceptance for your coding agent: test the flows you changed and open the PR with screenshots. Built for flows other tools can't reach: managed test identities with live inboxes (magic links, email OTP and 2FA, verification mail, password resets), an encrypted secret store for login and test credentials, and a test graph that runs prerequisite flows first. Plain-English tests become replayable scripts on localhost or preview URLs.",
12
- "version": "5.24.0"
12
+ "version": "5.25.0-staging.184"
13
13
  }
14
14
  ]
15
15
  }
package/README.md CHANGED
@@ -352,6 +352,7 @@ muggle doctor # Diagnose installation problems
352
352
  muggle run-view [runId] # A run's steps beside the frames they produced (newest run by default)
353
353
  muggle run-view --html # Render those frames as a self-contained page
354
354
  muggle run-view --open # Render it and open it in the browser
355
+ muggle checkout-freshness # Fetch the base and check this checkout is built on its latest commit
355
356
 
356
357
  # Authentication
357
358
  muggle login [--key-expiry 90d]
@@ -8,7 +8,7 @@ import { randomUUID } from 'crypto';
8
8
  import * as os4 from 'os';
9
9
  import { platform } from 'os';
10
10
  import winston from 'winston';
11
- import { exec, spawn } from 'child_process';
11
+ import { execFile, exec, spawn } from 'child_process';
12
12
  import axios, { AxiosError } from 'axios';
13
13
  import * as fs13 from 'fs/promises';
14
14
  import { z } from 'zod';
@@ -30,11 +30,16 @@ var __export = (target, all) => {
30
30
  var src_exports = {};
31
31
  __export(src_exports, {
32
32
  ACTION_SCRIPT_FILE_NAME: () => ACTION_SCRIPT_FILE_NAME,
33
+ BASE_REMOTE_NAME: () => BASE_REMOTE_NAME,
34
+ BLOCKING_FRESHNESS_VERDICTS: () => BLOCKING_FRESHNESS_VERDICTS,
35
+ BRANCH_CREATION_REFLOG_PREFIX: () => BRANCH_CREATION_REFLOG_PREFIX,
36
+ CheckoutFreshnessVerdict: () => CheckoutFreshnessVerdict,
33
37
  DEFAULT_PREFERENCES: () => DEFAULT_PREFERENCES,
34
38
  ELECTRON_APP_EXECUTABLE_PATH_SEGMENTS: () => ELECTRON_APP_EXECUTABLE_PATH_SEGMENTS,
35
39
  ElectronAppPlatform: () => ElectronAppPlatform,
36
40
  ElectronAppReleaseStream: () => ElectronAppReleaseStream,
37
41
  HTML_VIEW_OFFER_LINE: () => HTML_VIEW_OFFER_LINE,
42
+ MAX_LISTED_INHERITED_COMMITS: () => MAX_LISTED_INHERITED_COMMITS,
38
43
  ONBOARDING_BLANKET_OPTIONS: () => ONBOARDING_BLANKET_OPTIONS,
39
44
  ONBOARDING_CHOICE_GROUPS: () => ONBOARDING_CHOICE_GROUPS,
40
45
  ONBOARDING_MAX_OFFERS: () => ONBOARDING_MAX_OFFERS,
@@ -75,6 +80,7 @@ __export(src_exports, {
75
80
  deleteApiKeyData: () => deleteApiKeyData,
76
81
  deleteCredentials: () => deleteCredentials,
77
82
  e2e: () => e2e_exports2,
83
+ evaluateCheckoutFreshness: () => evaluateCheckoutFreshness,
78
84
  formatPreferencesOneLiner: () => formatPreferencesOneLiner,
79
85
  getActiveElectronAppReleaseStream: () => getActiveElectronAppReleaseStream,
80
86
  getActiveRuntimeTarget: () => getActiveRuntimeTarget,
@@ -141,10 +147,12 @@ __export(src_exports, {
141
147
  resolveRunSessionPath: () => resolveRunSessionPath,
142
148
  resolveRuntimeTarget: () => resolveRuntimeTarget,
143
149
  resolveTogglePreferences: () => resolveTogglePreferences,
150
+ runGitCommand: () => runGitCommand,
144
151
  saveApiKey: () => saveApiKey,
145
152
  saveApiKeyData: () => saveApiKeyData,
146
153
  saveCredentials: () => saveCredentials,
147
154
  startDeviceCodeFlow: () => startDeviceCodeFlow,
155
+ toDisplayRef: () => toDisplayRef,
148
156
  toolRequiresAuth: () => toolRequiresAuth,
149
157
  validatePreference: () => validatePreference,
150
158
  verifyFileChecksum: () => verifyFileChecksum,
@@ -3945,6 +3953,183 @@ function listActiveExecutions() {
3945
3953
  }));
3946
3954
  }
3947
3955
 
3956
+ // packages/mcps/src/shared/checkout-freshness-types.ts
3957
+ var CheckoutFreshnessVerdict = /* @__PURE__ */ ((CheckoutFreshnessVerdict2) => {
3958
+ CheckoutFreshnessVerdict2["Fresh"] = "FRESH";
3959
+ CheckoutFreshnessVerdict2["BehindBase"] = "BEHIND_BASE";
3960
+ CheckoutFreshnessVerdict2["ForeignBase"] = "FOREIGN_BASE";
3961
+ CheckoutFreshnessVerdict2["NotApplicable"] = "NOT_APPLICABLE";
3962
+ return CheckoutFreshnessVerdict2;
3963
+ })(CheckoutFreshnessVerdict || {});
3964
+
3965
+ // packages/mcps/src/shared/checkout-freshness-constants.ts
3966
+ var BLOCKING_FRESHNESS_VERDICTS = /* @__PURE__ */ new Set([
3967
+ "BEHIND_BASE" /* BehindBase */,
3968
+ "FOREIGN_BASE" /* ForeignBase */
3969
+ ]);
3970
+ var BASE_REMOTE_NAME = "origin";
3971
+ var BRANCH_CREATION_REFLOG_PREFIX = "branch: Created from ";
3972
+ var SHORT_SHA_LENGTH = 7;
3973
+ var MAX_LISTED_INHERITED_COMMITS = 20;
3974
+ var GIT_COMMAND_TIMEOUT_MS = 3e4;
3975
+ var runGitCommand = (args, cwd) => new Promise((resolve6) => {
3976
+ execFile(
3977
+ "git",
3978
+ args,
3979
+ { cwd, timeout: GIT_COMMAND_TIMEOUT_MS, windowsHide: true, encoding: "utf-8" },
3980
+ (error, stdout) => {
3981
+ resolve6(error ? null : stdout.trim());
3982
+ }
3983
+ );
3984
+ });
3985
+
3986
+ // packages/mcps/src/shared/checkout-freshness.ts
3987
+ var shortSha = (sha) => sha.slice(0, SHORT_SHA_LENGTH);
3988
+ var pluralCommits = (count) => count === 1 ? "1 commit" : `${count} commits`;
3989
+ var isAncestorAsync = async (runGit, cwd, ancestorSha, descendantSha) => await runGit(["merge-base", "--is-ancestor", ancestorSha, descendantSha], cwd) !== null;
3990
+ var resolveMainWorktreeRootAsync = async (runGit, cwd) => {
3991
+ const porcelain = await runGit(["worktree", "list", "--porcelain"], cwd);
3992
+ const firstLine = porcelain?.split("\n")[0] ?? "";
3993
+ return firstLine.startsWith("worktree ") ? firstLine.slice("worktree ".length) : null;
3994
+ };
3995
+ var resolveDefaultBranchAsync = async (runGit, cwd) => {
3996
+ const remoteHead = await runGit(["symbolic-ref", "--short", `refs/remotes/${BASE_REMOTE_NAME}/HEAD`], cwd);
3997
+ const prefix = `${BASE_REMOTE_NAME}/`;
3998
+ return remoteHead?.startsWith(prefix) ? remoteHead.slice(prefix.length) : null;
3999
+ };
4000
+ var resolveBaseAsync = async (runGit, cwd, baseBranch) => {
4001
+ for (const ref of [`refs/remotes/${BASE_REMOTE_NAME}/${baseBranch}`, `refs/heads/${baseBranch}`]) {
4002
+ const sha = await runGit(["rev-parse", "--verify", "--quiet", `${ref}^{commit}`], cwd);
4003
+ if (sha) return { ref, sha };
4004
+ }
4005
+ return null;
4006
+ };
4007
+ var toDisplayRef = (ref) => ref.replace(/^refs\/(remotes|heads)\//, "");
4008
+ var isOwnRemoteBranch = (startPoint, branch) => startPoint === `${BASE_REMOTE_NAME}/${branch}` || startPoint === `refs/remotes/${BASE_REMOTE_NAME}/${branch}`;
4009
+ var readBranchCreationAsync = async (runGit, cwd, branch) => {
4010
+ const reflog = await runGit(["reflog", "show", "--format=%H%x09%gs", `refs/heads/${branch}`], cwd);
4011
+ const oldestEntry = reflog?.split("\n").at(-1) ?? "";
4012
+ const [sha, subject] = oldestEntry.split(" ");
4013
+ if (!sha || !subject?.startsWith(BRANCH_CREATION_REFLOG_PREFIX)) return null;
4014
+ const startPoint = subject.slice(BRANCH_CREATION_REFLOG_PREFIX.length);
4015
+ if (isOwnRemoteBranch(startPoint, branch)) return null;
4016
+ return { sha, startPoint };
4017
+ };
4018
+ var withVerdict = (report, verdict, reason) => ({ ...report, verdict, reason });
4019
+ async function evaluateCheckoutFreshness(request) {
4020
+ const { cwd, runGit } = request;
4021
+ let report = {
4022
+ verdict: "NOT_APPLICABLE" /* NotApplicable */,
4023
+ reason: "",
4024
+ checkoutRoot: null,
4025
+ mainWorktreeRoot: null,
4026
+ branch: null,
4027
+ headSha: null,
4028
+ baseRef: null,
4029
+ baseSha: null,
4030
+ behindBy: 0,
4031
+ creationSha: null,
4032
+ inheritedCommitCount: 0,
4033
+ inheritedCommits: [],
4034
+ hasFetchFailed: false
4035
+ };
4036
+ const checkoutRoot = await runGit(["rev-parse", "--show-toplevel"], cwd);
4037
+ if (!checkoutRoot) return withVerdict(report, "NOT_APPLICABLE" /* NotApplicable */, "not inside a git checkout");
4038
+ report.checkoutRoot = checkoutRoot;
4039
+ report.mainWorktreeRoot = await resolveMainWorktreeRootAsync(runGit, cwd);
4040
+ if (await runGit(["remote", "get-url", BASE_REMOTE_NAME], cwd) === null) {
4041
+ return withVerdict(report, "NOT_APPLICABLE" /* NotApplicable */, `the checkout has no ${BASE_REMOTE_NAME} remote`);
4042
+ }
4043
+ const baseBranch = request.baseBranch ?? await resolveDefaultBranchAsync(runGit, cwd);
4044
+ if (!baseBranch) {
4045
+ return withVerdict(
4046
+ report,
4047
+ "NOT_APPLICABLE" /* NotApplicable */,
4048
+ `${BASE_REMOTE_NAME}'s default branch is unknown \u2014 name the base branch explicitly`
4049
+ );
4050
+ }
4051
+ if (request.shouldFetchBase) {
4052
+ const refspec = `+refs/heads/${baseBranch}:refs/remotes/${BASE_REMOTE_NAME}/${baseBranch}`;
4053
+ report.hasFetchFailed = await runGit(["fetch", "--no-tags", BASE_REMOTE_NAME, refspec], cwd) === null;
4054
+ }
4055
+ const base = await resolveBaseAsync(runGit, cwd, baseBranch);
4056
+ if (!base) {
4057
+ return withVerdict(
4058
+ report,
4059
+ "NOT_APPLICABLE" /* NotApplicable */,
4060
+ `base branch ${baseBranch} exists neither on ${BASE_REMOTE_NAME} nor locally`
4061
+ );
4062
+ }
4063
+ const headSha = await runGit(["rev-parse", "--verify", "--quiet", "HEAD^{commit}"], cwd);
4064
+ if (!headSha) return withVerdict(report, "NOT_APPLICABLE" /* NotApplicable */, "the checkout has no commits");
4065
+ const baseName = toDisplayRef(base.ref);
4066
+ report = {
4067
+ ...report,
4068
+ baseRef: base.ref,
4069
+ baseSha: base.sha,
4070
+ headSha,
4071
+ branch: await runGit(["symbolic-ref", "--quiet", "--short", "HEAD"], cwd)
4072
+ };
4073
+ if (!await isAncestorAsync(runGit, cwd, base.sha, headSha)) {
4074
+ const behindCount = await runGit(["rev-list", "--count", `${headSha}..${base.sha}`], cwd);
4075
+ report.behindBy = Number(behindCount ?? "0");
4076
+ }
4077
+ const creation = report.branch ? await readBranchCreationAsync(runGit, cwd, report.branch) : null;
4078
+ if (creation) {
4079
+ report.creationSha = creation.sha;
4080
+ const isCreatedOnBase = await isAncestorAsync(runGit, cwd, creation.sha, base.sha);
4081
+ const isCreationStillCarried = !isCreatedOnBase && await isAncestorAsync(runGit, cwd, creation.sha, headSha);
4082
+ if (isCreationStillCarried) {
4083
+ const inheritedRange = `${base.sha}..${creation.sha}`;
4084
+ report.inheritedCommitCount = Number(await runGit(["rev-list", "--count", inheritedRange], cwd) ?? "0");
4085
+ const inheritedLog = await runGit(
4086
+ ["log", "--format=%h %s", `-n${MAX_LISTED_INHERITED_COMMITS}`, inheritedRange],
4087
+ cwd
4088
+ );
4089
+ report.inheritedCommits = inheritedLog ? inheritedLog.split("\n") : [];
4090
+ return withVerdict(
4091
+ report,
4092
+ "FOREIGN_BASE" /* ForeignBase */,
4093
+ `${report.branch} was created from ${creation.startPoint} at ${shortSha(creation.sha)}, which ${baseName} does not contain \u2014 it carries ${pluralCommits(report.inheritedCommitCount)} from that branch`
4094
+ );
4095
+ }
4096
+ }
4097
+ if (report.behindBy > 0) {
4098
+ return withVerdict(
4099
+ report,
4100
+ "BEHIND_BASE" /* BehindBase */,
4101
+ `HEAD is ${pluralCommits(report.behindBy)} behind ${baseName} (${shortSha(base.sha)})`
4102
+ );
4103
+ }
4104
+ return withVerdict(report, "FRESH" /* Fresh */, `HEAD contains ${baseName} (${shortSha(base.sha)})`);
4105
+ }
4106
+
4107
+ // packages/mcps/src/mcp/local/services/run-checkout-gate-constants.ts
4108
+ var LOOPBACK_HOSTNAMES = ["localhost", "127.0.0.1", "[::1]", "0.0.0.0"];
4109
+ var LOCALHOST_DOMAIN_SUFFIX = ".localhost";
4110
+ var IPV4_LOOPBACK_PREFIX = "127.";
4111
+
4112
+ // packages/mcps/src/mcp/local/services/run-checkout-gate.ts
4113
+ function isLoopbackUrl(url) {
4114
+ let hostname2;
4115
+ try {
4116
+ hostname2 = new URL(url).hostname.toLowerCase();
4117
+ } catch {
4118
+ return false;
4119
+ }
4120
+ return LOOPBACK_HOSTNAMES.includes(hostname2) || hostname2.startsWith(IPV4_LOOPBACK_PREFIX) || hostname2.endsWith(LOCALHOST_DOMAIN_SUFFIX);
4121
+ }
4122
+ async function findRunCheckoutRefusal(params) {
4123
+ if (!isLoopbackUrl(params.localUrl)) return null;
4124
+ const report = await evaluateCheckoutFreshness({
4125
+ cwd: params.cwd,
4126
+ baseBranch: params.baseBranch,
4127
+ shouldFetchBase: false,
4128
+ runGit: params.runGit ?? runGitCommand
4129
+ });
4130
+ return BLOCKING_FRESHNESS_VERDICTS.has(report.verdict) ? report : null;
4131
+ }
4132
+
3948
4133
  // packages/mcps/src/shared/auth.ts
3949
4134
  var logger6 = getLogger();
3950
4135
  async function startDeviceCodeFlow(config, options) {
@@ -7648,7 +7833,9 @@ var ExecuteTestGenerationInputSchema = z.object({
7648
7833
  /** Local URL to test against. */
7649
7834
  localUrl: z.string().url().describe("Local URL to test against (e.g., http://localhost:3000)"),
7650
7835
  /** Absolute path identifying the caller's worktree. Drives the cross-worktree single-flight lock — same path = parallel allowed (intra-change), different path = waits its turn. Required: ambiguity here causes the lock to mis-key, splitting one logical change into two competing holders. */
7651
- cwd: z.string().min(1).describe("Absolute path of the caller's worktree. Required \u2014 this keys the cross-worktree single-flight lock so concurrent muggle-test runs from different branches serialize."),
7836
+ cwd: z.string().min(1).describe("Absolute path of the caller's worktree; keys the single-flight lock. A loopback run is refused unless it holds its base's latest commit."),
7837
+ /** Base of a stacked change; the run is refused unless `cwd` contains its latest commit. */
7838
+ baseBranch: z.string().min(1).optional().describe("Base branch if not origin's default (e.g. a stacked parent)."),
7652
7839
  /** Optional timeout. */
7653
7840
  timeoutMs: z.number().int().positive().optional().describe("Timeout in milliseconds (default: 300000 = 5 min)"),
7654
7841
  /** Show the electron-app UI during execution. Default: visible window. Pass false to run headless. */
@@ -7674,13 +7861,15 @@ var ExecuteReplayInputSchema = z.object({
7674
7861
  /** Local URL to test against. */
7675
7862
  localUrl: z.string().url().describe("Local URL to test against (e.g., http://localhost:3000)"),
7676
7863
  /** Absolute path identifying the caller's worktree. Drives the cross-worktree single-flight lock — same path = parallel allowed (intra-change), different path = waits its turn. Required: ambiguity here causes the lock to mis-key, splitting one logical change into two competing holders. */
7677
- cwd: z.string().min(1).describe("Absolute path of the caller's worktree. Required \u2014 this keys the cross-worktree single-flight lock so concurrent muggle-test runs from different branches serialize."),
7864
+ cwd: z.string().min(1).describe("Absolute path of the caller's worktree; keys the single-flight lock. A loopback run is refused unless it holds its base's latest commit."),
7865
+ /** Base of a stacked change; the run is refused unless `cwd` contains its latest commit. */
7866
+ baseBranch: z.string().min(1).optional().describe("Base branch if not origin's default (e.g. a stacked parent)."),
7678
7867
  /** Optional timeout. */
7679
7868
  timeoutMs: z.number().int().positive().optional().describe("Timeout in milliseconds (default: 180000 = 3 min)"),
7680
7869
  /** Show the electron-app UI during execution. Default: visible window. Pass false to run headless. */
7681
7870
  showUi: z.boolean().optional().describe("Show the electron-app UI during replay. Defaults to visible; pass false to run headless."),
7682
7871
  /** Whether the replay starts from an emptied browser session, copied from the recording. */
7683
- freshSession: z.boolean().optional().describe("Copy from actionParams.freshSession of the muggle-remote-action-script-get result, so the replay starts the way the script was recorded: true clears all session storage (cookies, localStorage, etc.) before execution. A recording without it may predate run identities; pass true then only for a test that needs clean browser state (registration, login, cookie consent). Default: false."),
7872
+ freshSession: z.boolean().optional().describe("Copy actionParams.freshSession from muggle-remote-action-script-get so the replay starts as recorded: true clears all session storage (cookies, localStorage) first. Absent there (an older recording): true only for clean-state tests (registration, login, cookie consent). Default: false."),
7684
7873
  /** Mutation parameters passed to the LLM step predictor — a string[] where each element is an instruction describing what varies this run. Supports plain-English instructions (e.g. "The post content should be 'Hello world'") and local file paths for uploads (e.g. "Attach the image at C:\\Users\\user\\photo.jpg"). Matches the electron-app's string[] mutation file format. When provided, the electron app uses LLM-driven step prediction instead of deterministic replay. */
7685
7874
  mutations: z.array(z.string()).optional().describe(`Mutation parameters: string[] where each element is a plain-English instruction or a local file path (e.g. ["The post content should be 'Hello'", "Attach the image at C:\\\\Users\\\\user\\\\photo.jpg"]).`),
7686
7875
  /** Pinned account the script was recorded with, copied from the recording. */
@@ -8071,6 +8260,26 @@ function clearLastHost(cwd) {
8071
8260
  clearCwdEntry(LAST_HOST_CACHE, cwd);
8072
8261
  }
8073
8262
 
8263
+ // packages/mcps/src/mcp/tools/local/run-checkout-refusal.ts
8264
+ function formatRunCheckoutRefusal(report, cwd) {
8265
+ const baseName = report.baseRef ? toDisplayRef(report.baseRef) : "";
8266
+ const remedy = report.verdict === "FOREIGN_BASE" /* ForeignBase */ ? `Recreate the branch from \`${baseName}\` and carry over only this change's own commits \u2014 or, when the change deliberately stacks on that branch, pass it as \`baseBranch\`.` : `Rebase this checkout onto \`${baseName}\`.`;
8267
+ const inherited = report.inheritedCommits.length > 0 ? ["", "Inherited commits:", ...report.inheritedCommits.map((commit) => `- ${commit}`)] : [];
8268
+ return [
8269
+ `## Run refused \u2014 checkout is not on the latest ${baseName || "base"}`,
8270
+ "",
8271
+ `**Verdict:** ${report.verdict}`,
8272
+ `**Checkout:** ${report.checkoutRoot ?? cwd}`,
8273
+ `**Why:** ${report.reason}`,
8274
+ ...inherited,
8275
+ "",
8276
+ "Nothing was launched. To clear it:",
8277
+ `1. \`muggle checkout-freshness --cwd "${cwd}"\` \u2014 fetches the base and re-checks.`,
8278
+ `2. ${remedy}`,
8279
+ "3. Restart the dev server from this checkout, then run again."
8280
+ ].join("\n");
8281
+ }
8282
+
8074
8283
  // packages/mcps/src/mcp/tools/local/tool-registry.ts
8075
8284
  function createChildLogger2(correlationId) {
8076
8285
  const logger7 = getLogger();
@@ -8326,6 +8535,15 @@ var executeTestGenerationTool = {
8326
8535
  logger7.info("Executing muggle-local-execute-test-generation");
8327
8536
  const input = ExecuteTestGenerationInputSchema.parse(ctx.input);
8328
8537
  const showUi = input.showUi !== false;
8538
+ const checkoutRefusal = await findRunCheckoutRefusal({
8539
+ cwd: input.cwd,
8540
+ localUrl: input.localUrl,
8541
+ baseBranch: input.baseBranch
8542
+ });
8543
+ if (checkoutRefusal) {
8544
+ logger7.warn("Test generation refused: stale checkout", { verdict: checkoutRefusal.verdict, cwd: input.cwd });
8545
+ return { content: formatRunCheckoutRefusal(checkoutRefusal, input.cwd), isError: true, data: checkoutRefusal };
8546
+ }
8329
8547
  try {
8330
8548
  const generationRun = await executeTestGeneration({
8331
8549
  testCase: input.testCase,
@@ -8369,6 +8587,15 @@ var executeReplayTool = {
8369
8587
  logger7.info("Executing muggle-local-execute-replay");
8370
8588
  const input = ExecuteReplayInputSchema.parse(ctx.input);
8371
8589
  const showUi = input.showUi !== false;
8590
+ const checkoutRefusal = await findRunCheckoutRefusal({
8591
+ cwd: input.cwd,
8592
+ localUrl: input.localUrl,
8593
+ baseBranch: input.baseBranch
8594
+ });
8595
+ if (checkoutRefusal) {
8596
+ logger7.warn("Test replay refused: stale checkout", { verdict: checkoutRefusal.verdict, cwd: input.cwd });
8597
+ return { content: formatRunCheckoutRefusal(checkoutRefusal, input.cwd), isError: true, data: checkoutRefusal };
8598
+ }
8372
8599
  try {
8373
8600
  const replayRun = await executeReplay({
8374
8601
  testScript: input.testScript,
@@ -8852,11 +9079,13 @@ __export(local_exports2, {
8852
9079
  executeReplay: () => executeReplay,
8853
9080
  executeTestGeneration: () => executeTestGeneration,
8854
9081
  executeTool: () => executeTool,
9082
+ findRunCheckoutRefusal: () => findRunCheckoutRefusal,
8855
9083
  getAuthService: () => getAuthService,
8856
9084
  getLocalQaTools: () => getLocalQaTools,
8857
9085
  getRunResultStorageService: () => getRunResultStorageService,
8858
9086
  getStorageService: () => getStorageService,
8859
9087
  getTool: () => getTool,
9088
+ isLoopbackUrl: () => isLoopbackUrl,
8860
9089
  listActiveExecutions: () => listActiveExecutions,
8861
9090
  readLocalExecutionLockState: () => readLocalExecutionLockState,
8862
9091
  resetAuthService: () => resetAuthService,
@@ -9171,4 +9400,4 @@ function applyOnboardingAnswers(answers, dataDirOverride2, now = /* @__PURE__ */
9171
9400
  return { isCompleted: true, preferences: prefs };
9172
9401
  }
9173
9402
 
9174
- export { ACTION_SCRIPT_FILE_NAME, DEFAULT_PREFERENCES, ELECTRON_APP_EXECUTABLE_PATH_SEGMENTS, ElectronAppPlatform, ElectronAppReleaseStream, EventName, HTML_VIEW_OFFER_LINE, ONBOARDING_BLANKET_OPTIONS, ONBOARDING_CHOICE_GROUPS, ONBOARDING_MAX_OFFERS, ONBOARDING_PRIMER_BULLETS, ONBOARDING_PRIMER_HEADLINE, ONBOARDING_TOGGLE_GROUPS, ONBOARDING_TOGGLE_PROMPT, ONBOARDING_UNSELECTED_TOGGLE_VALUE, OnboardingBlanketChoice, OnboardingGroupKind, PREFERENCES_FILE_NAME, PREFERENCES_PROJECT_DIR_NAME, PREFERENCES_SCHEMA, PREFERENCES_VERSION, PREFERENCE_ALLOWED_VALUES, PreferenceKey, PreferenceValue, ProjectPreferencesReconcileOutcome, RUN_SESSIONS_DIR_NAME, RUN_VIEW_DASHBOARD_LINK_LABEL, RunViewError, RuntimeTarget, SCREENSHOT_DIR_RELATIVE_PATH, SCREENSHOT_FILE_EXTENSION, ServiceName, Surface, WATCHER_LIFETIME_SECONDS, WATCHER_LIFETIME_UNBOUNDED_SECONDS, __export, __require, applyOnboardingAnswers, assertDeviceCodeClientProvisioned, buildElectronAppChecksumsUrl, buildElectronAppDirName, buildElectronAppReleaseAssetUrl, buildElectronAppReleaseTag, buildOnboardingPlan, calculateFileChecksum, completeOnboarding, createApiKeyWithToken, createChildLogger, deleteApiKeyData, deleteCredentials, e2e_exports2 as e2e_exports, formatPreferencesOneLiner, getActiveElectronAppReleaseStream, getActiveRuntimeTarget, getApiKey, getApiKeyFilePath, getAuthService, getBundledElectronAppVersion, getCallerCredentials, getCallerCredentialsAsync, getChecksumForPlatform, getConfig, getCredentialsFilePath, getDashboardBaseUrl, getDataDir2 as getDataDir, getDisclosureCopy, getDownloadBaseUrl, getElectronAppChecksums, getElectronAppDir, getElectronAppReleaseTagPrefix, getElectronAppSignedFromVersion, getElectronAppVersion, getElectronAppVersionSource, getLocalQaTools, getLogger, getOnboardingToggleKeys, getPlatformKey, getQaTools, getReleaseSignerIdentityUri, getRunSessionsDir, getValidApiKeyData, getValidCredentials, hasApiKey, hasShownDisclosure, initTelemetry, isElectronAppInstalled, isElectronAppPlatform, isFirstRun, loadApiKeyData, loadCredentials, local_exports2 as local_exports, markDisclosureShown, markOnboardingCompleted, mcp_exports, needsOnboarding, openBrowserUrl, parseElectronAppDirName, performLogin, performLogout, pollDeviceCode, readPreferencesMetadata, readRunView, reconcileProjectPreferences, recordOnboardingSkip, renderRunViewHtml, renderRunViewText, resetConfig, resetLogger, resetPreference, resolveActiveProfile, resolveActiveReleaseStream, resolveActiveReleaseTagPrefix, resolveBlanketPreferences, resolveElectronAppExecutablePath, resolveElectronAppPathOrNull, resolveOnboardingAnswers, resolvePreferences, resolveRunSessionPath, resolveRuntimeTarget, resolveTogglePreferences, saveApiKey, saveApiKeyData, saveCredentials, src_exports, startDeviceCodeFlow, toolRequiresAuth, track, validatePreference, verifyFileChecksum, writePreferences2 as writePreferences, writePreferencesWithMetadata, writeRunViewHtml };
9403
+ export { ACTION_SCRIPT_FILE_NAME, BASE_REMOTE_NAME, BLOCKING_FRESHNESS_VERDICTS, BRANCH_CREATION_REFLOG_PREFIX, CheckoutFreshnessVerdict, DEFAULT_PREFERENCES, ELECTRON_APP_EXECUTABLE_PATH_SEGMENTS, ElectronAppPlatform, ElectronAppReleaseStream, EventName, HTML_VIEW_OFFER_LINE, MAX_LISTED_INHERITED_COMMITS, ONBOARDING_BLANKET_OPTIONS, ONBOARDING_CHOICE_GROUPS, ONBOARDING_MAX_OFFERS, ONBOARDING_PRIMER_BULLETS, ONBOARDING_PRIMER_HEADLINE, ONBOARDING_TOGGLE_GROUPS, ONBOARDING_TOGGLE_PROMPT, ONBOARDING_UNSELECTED_TOGGLE_VALUE, OnboardingBlanketChoice, OnboardingGroupKind, PREFERENCES_FILE_NAME, PREFERENCES_PROJECT_DIR_NAME, PREFERENCES_SCHEMA, PREFERENCES_VERSION, PREFERENCE_ALLOWED_VALUES, PreferenceKey, PreferenceValue, ProjectPreferencesReconcileOutcome, RUN_SESSIONS_DIR_NAME, RUN_VIEW_DASHBOARD_LINK_LABEL, RunViewError, RuntimeTarget, SCREENSHOT_DIR_RELATIVE_PATH, SCREENSHOT_FILE_EXTENSION, ServiceName, Surface, WATCHER_LIFETIME_SECONDS, WATCHER_LIFETIME_UNBOUNDED_SECONDS, __export, __require, applyOnboardingAnswers, assertDeviceCodeClientProvisioned, buildElectronAppChecksumsUrl, buildElectronAppDirName, buildElectronAppReleaseAssetUrl, buildElectronAppReleaseTag, buildOnboardingPlan, calculateFileChecksum, completeOnboarding, createApiKeyWithToken, createChildLogger, deleteApiKeyData, deleteCredentials, e2e_exports2 as e2e_exports, evaluateCheckoutFreshness, formatPreferencesOneLiner, getActiveElectronAppReleaseStream, getActiveRuntimeTarget, getApiKey, getApiKeyFilePath, getAuthService, getBundledElectronAppVersion, getCallerCredentials, getCallerCredentialsAsync, getChecksumForPlatform, getConfig, getCredentialsFilePath, getDashboardBaseUrl, getDataDir2 as getDataDir, getDisclosureCopy, getDownloadBaseUrl, getElectronAppChecksums, getElectronAppDir, getElectronAppReleaseTagPrefix, getElectronAppSignedFromVersion, getElectronAppVersion, getElectronAppVersionSource, getLocalQaTools, getLogger, getOnboardingToggleKeys, getPlatformKey, getQaTools, getReleaseSignerIdentityUri, getRunSessionsDir, getValidApiKeyData, getValidCredentials, hasApiKey, hasShownDisclosure, initTelemetry, isElectronAppInstalled, isElectronAppPlatform, isFirstRun, loadApiKeyData, loadCredentials, local_exports2 as local_exports, markDisclosureShown, markOnboardingCompleted, mcp_exports, needsOnboarding, openBrowserUrl, parseElectronAppDirName, performLogin, performLogout, pollDeviceCode, readPreferencesMetadata, readRunView, reconcileProjectPreferences, recordOnboardingSkip, renderRunViewHtml, renderRunViewText, resetConfig, resetLogger, resetPreference, resolveActiveProfile, resolveActiveReleaseStream, resolveActiveReleaseTagPrefix, resolveBlanketPreferences, resolveElectronAppExecutablePath, resolveElectronAppPathOrNull, resolveOnboardingAnswers, resolvePreferences, resolveRunSessionPath, resolveRuntimeTarget, resolveTogglePreferences, runGitCommand, saveApiKey, saveApiKeyData, saveCredentials, src_exports, startDeviceCodeFlow, toDisplayRef, toolRequiresAuth, track, validatePreference, verifyFileChecksum, writePreferences2 as writePreferences, writePreferencesWithMetadata, writeRunViewHtml };
@@ -1,4 +1,4 @@
1
- import { __export, getLogger, getConfig, createChildLogger, buildElectronAppReleaseAssetUrl, getActiveRuntimeTarget, getAuthService, hasApiKey, getElectronAppVersion, getElectronAppDir, getPlatformKey, reconcileProjectPreferences, getDataDir, PREFERENCES_FILE_NAME, isFirstRun, writePreferences, DEFAULT_PREFERENCES, isElectronAppInstalled, getElectronAppChecksums, getChecksumForPlatform, getElectronAppSignedFromVersion, getReleaseSignerIdentityUri, verifyFileChecksum, resolveElectronAppExecutablePath, calculateFileChecksum, initTelemetry, Surface, ServiceName, track, EventName, getQaTools, getLocalQaTools, performLogout, assertDeviceCodeClientProvisioned, performLogin, getActiveElectronAppReleaseStream, toolRequiresAuth, getCallerCredentials, parseElectronAppDirName, getElectronAppReleaseTagPrefix, hasShownDisclosure, markDisclosureShown, getBundledElectronAppVersion, getElectronAppVersionSource, getCredentialsFilePath, ElectronAppReleaseStream, buildElectronAppChecksumsUrl, __require, getDisclosureCopy, buildOnboardingPlan, applyOnboardingAnswers, needsOnboarding, readRunView, RunViewError, renderRunViewText, writeRunViewHtml, openBrowserUrl, OnboardingBlanketChoice, PreferenceKey, resolvePreferences } from './chunk-FEHTWWVH.js';
1
+ import { __export, getLogger, getConfig, createChildLogger, buildElectronAppReleaseAssetUrl, getActiveRuntimeTarget, getAuthService, hasApiKey, getElectronAppVersion, getElectronAppDir, getPlatformKey, reconcileProjectPreferences, getDataDir, PREFERENCES_FILE_NAME, isFirstRun, writePreferences, DEFAULT_PREFERENCES, isElectronAppInstalled, getElectronAppChecksums, getChecksumForPlatform, getElectronAppSignedFromVersion, getReleaseSignerIdentityUri, verifyFileChecksum, resolveElectronAppExecutablePath, calculateFileChecksum, initTelemetry, Surface, ServiceName, track, EventName, getQaTools, getLocalQaTools, performLogout, assertDeviceCodeClientProvisioned, performLogin, getActiveElectronAppReleaseStream, toolRequiresAuth, getCallerCredentials, parseElectronAppDirName, getElectronAppReleaseTagPrefix, hasShownDisclosure, markDisclosureShown, getBundledElectronAppVersion, getElectronAppVersionSource, getCredentialsFilePath, ElectronAppReleaseStream, buildElectronAppChecksumsUrl, __require, getDisclosureCopy, buildOnboardingPlan, applyOnboardingAnswers, needsOnboarding, readRunView, RunViewError, renderRunViewText, writeRunViewHtml, openBrowserUrl, evaluateCheckoutFreshness, runGitCommand, BLOCKING_FRESHNESS_VERDICTS, OnboardingBlanketChoice, PreferenceKey, resolvePreferences } from './chunk-BJGZAKBB.js';
2
2
  import { Server } from '@modelcontextprotocol/sdk/server/index.js';
3
3
  import { ListToolsRequestSchema, CallToolRequestSchema, ListResourcesRequestSchema, ReadResourceRequestSchema } from '@modelcontextprotocol/sdk/types.js';
4
4
  import { v4 } from 'uuid';
@@ -1042,7 +1042,7 @@ async function resolveGsScreenshotUrls(report, opts) {
1042
1042
  if (gsUrls.length === 0) {
1043
1043
  return report;
1044
1044
  }
1045
- const mcps = await import('./src-3MQ2UWSP.js');
1045
+ const mcps = await import('./src-BYDDPSF6.js');
1046
1046
  const credentials = await mcps.getCallerCredentialsAsync();
1047
1047
  if (!credentials.bearerToken && !credentials.apiKey) {
1048
1048
  stderrWrite(
@@ -1169,6 +1169,29 @@ async function buildPrSectionCommand(options) {
1169
1169
  }
1170
1170
  }
1171
1171
 
1172
+ // src/cli/checkout-freshness.ts
1173
+ function renderCheckoutFreshnessSummary(report) {
1174
+ const lines = [`${report.verdict}: ${report.reason}`];
1175
+ if (report.checkoutRoot) lines.push(`checkout: ${report.checkoutRoot}`);
1176
+ if (report.headSha) lines.push(`head: ${report.headSha}${report.branch ? ` (${report.branch})` : " (detached)"}`);
1177
+ if (report.baseRef && report.baseSha) lines.push(`base: ${report.baseRef} @ ${report.baseSha}`);
1178
+ if (report.hasFetchFailed) lines.push("warning: fetching the base failed \u2014 checked against the last fetched base");
1179
+ for (const commit of report.inheritedCommits) lines.push(`inherited: ${commit}`);
1180
+ return lines.join("\n");
1181
+ }
1182
+ async function checkoutFreshnessCommand(flags) {
1183
+ const report = await evaluateCheckoutFreshness({
1184
+ cwd: flags.cwd ?? process.cwd(),
1185
+ baseBranch: flags.base,
1186
+ shouldFetchBase: flags.fetch !== false,
1187
+ runGit: runGitCommand
1188
+ });
1189
+ const output = flags.json ? JSON.stringify(report, null, 2) : renderCheckoutFreshnessSummary(report);
1190
+ process.stdout.write(`${output}
1191
+ `);
1192
+ if (BLOCKING_FRESHNESS_VERDICTS.has(report.verdict)) process.exitCode = 1;
1193
+ }
1194
+
1172
1195
  // src/ci-workflow/constants.ts
1173
1196
  var USER_WORKFLOW_PATH = ".github/workflows/muggle-walkthrough.yml";
1174
1197
  var USER_WORKFLOW_COMMAND = "npx -y -p @muggleai/works muggle pr-walkthrough-check --check-run";
@@ -3443,6 +3466,7 @@ function createProgram() {
3443
3466
  program.command("build-pr-section").description("Render a muggle-do PR body evidence block from an e2e report on stdin").option("--max-body-bytes <n>", "Max UTF-8 byte budget for the PR body (default 60000)").action(buildPrSectionCommand);
3444
3467
  program.command("run-view").argument("[runId]", "Run id, or a unique prefix of one (default: the newest run)").description("Show a local run's steps beside the frames they produced").option("--html", "Render a self-contained HTML page instead of terminal text").option("--open", "Open the rendered page in the default browser (implies --html)").option("--out-dir <dir>", "Directory to write the page into (default: current directory)").action(runViewCommand);
3445
3468
  program.command("pr-walkthrough-check").description("Check that a PR's Muggle AI walkthrough comment carries a result or a stated skip").option("--repo <owner/repo>", "Repository (default: $GITHUB_REPOSITORY)").option("--pr <number>", "Pull request number (default: the Actions event payload)").option("--head-sha <sha>", "Commit the check run attaches to (default: the PR head)").option("--check-run", "Publish the verdict as a check run instead of failing the process").action(prWalkthroughCheckCommand);
3469
+ program.command("checkout-freshness").description("Fetch the base branch and check that a checkout is built on its latest commit").option("--cwd <dir>", "Directory inside the checkout (default: the current directory)").option("--base <branch>", "Branch the change merges into (default: origin's default branch)").option("--no-fetch", "Check against the last fetched base instead of fetching").option("--json", "Print the full report as JSON").action(checkoutFreshnessCommand);
3446
3470
  program.command("ci-install").description("Add the Muggle walkthrough check to this repository's GitHub Actions").option("--force", "Replace an existing workflow file").action(ciInstallCommand);
3447
3471
  program.action(() => {
3448
3472
  helpCommand();
package/dist/cli.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { runCli } from './chunk-GLTZIZVT.js';
3
- import './chunk-FEHTWWVH.js';
2
+ import { runCli } from './chunk-CE5HUVNQ.js';
3
+ import './chunk-BJGZAKBB.js';
4
4
 
5
5
  // src/cli/main.ts
6
6
  runCli().catch((error) => {
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- export { src_exports as commands, createUnifiedMcpServer, server_exports as server } from './chunk-GLTZIZVT.js';
2
- export { createChildLogger, e2e_exports as e2e, getConfig, getLocalQaTools, getLogger, getQaTools, local_exports as localQa, mcp_exports as mcp, e2e_exports as qa, src_exports as shared } from './chunk-FEHTWWVH.js';
1
+ export { src_exports as commands, createUnifiedMcpServer, server_exports as server } from './chunk-CE5HUVNQ.js';
2
+ export { createChildLogger, e2e_exports as e2e, getConfig, getLocalQaTools, getLogger, getQaTools, local_exports as localQa, mcp_exports as mcp, e2e_exports as qa, src_exports as shared } from './chunk-BJGZAKBB.js';
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "muggle",
3
3
  "description": "Real-browser E2E acceptance for your coding agent: test the flows you changed and open the PR with screenshots. Built for flows other tools can't reach: managed test identities with live inboxes (magic links, email OTP and 2FA, verification mail, password resets), an encrypted secret store for login and test credentials, and a test graph that runs prerequisite flows first. Plain-English tests become replayable scripts on localhost or preview URLs.",
4
- "version": "5.24.0",
4
+ "version": "5.25.0-staging.184",
5
5
  "author": {
6
6
  "name": "Muggle AI",
7
7
  "email": "support@muggle-ai.com"
@@ -4,7 +4,7 @@
4
4
  "command": "npx",
5
5
  "args": [
6
6
  "-y",
7
- "@muggleai/works@5.24.0",
7
+ "@muggleai/works@5.25.0-staging.184",
8
8
  "serve"
9
9
  ],
10
10
  "env": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "muggle",
3
- "version": "5.24.0",
3
+ "version": "5.25.0-staging.184",
4
4
  "description": "Real-browser E2E acceptance for your coding agent: test the flows you changed and open the PR with screenshots. Built for flows other tools can't reach: managed test identities with live inboxes (magic links, email OTP and 2FA, verification mail, password resets), an encrypted secret store for login and test credentials, and a test graph that runs prerequisite flows first. Plain-English tests become replayable scripts on localhost or preview URLs.",
5
5
  "author": {
6
6
  "name": "Muggle AI",
@@ -2,7 +2,7 @@
2
2
  "name": "muggle",
3
3
  "displayName": "Muggle AI",
4
4
  "description": "Real-browser E2E acceptance for your coding agent: test the flows you changed and open the PR with screenshots. Built for flows other tools can't reach: managed test identities with live inboxes (magic links, email OTP and 2FA, verification mail, password resets), an encrypted secret store for login and test credentials, and a test graph that runs prerequisite flows first. Plain-English tests become replayable scripts on localhost or preview URLs.",
5
- "version": "5.24.0",
5
+ "version": "5.25.0-staging.184",
6
6
  "author": {
7
7
  "name": "Muggle AI",
8
8
  "email": "support@muggle-ai.com"
@@ -4,7 +4,7 @@
4
4
  "command": "npx",
5
5
  "args": [
6
6
  "-y",
7
- "@muggleai/works@5.24.0",
7
+ "@muggleai/works@5.25.0-staging.184",
8
8
  "serve"
9
9
  ]
10
10
  }
@@ -12,10 +12,10 @@ You bring a local dev stack to verified readiness for E2E testing: detect what's
12
12
 
13
13
  The dispatch prompt carries the resolved prepare plan:
14
14
 
15
- - `services[]` — name, dir, start command, expected port, `external` flag, approval already granted.
15
+ - `services[]` — name, dir, start command, expected port, `external` flag, approval already granted. `dir` is the run directory the skill's resolve-sources stage chose this run — the change's own checkout, or a base checkout on the latest default branch; start and judge each service from it, never from anywhere else.
16
16
  - `testingScope` and `excludedServices[]` (with reasons).
17
17
  - The recorded dev-server URL (from the `autoSelectLocalHost` resolution) — never invent or default a host/port; a framework default like `:3000` is not a fallback.
18
- - Resolved gate values the stages read (`autoRebase` outcome already applied or explicitly skipped upstream).
18
+ - Resolved gate values the stages read (`autoRebase` outcome already applied upstream, with the checkout synced onto its base).
19
19
  - The E2E run instructions — startup order, manual steps, local gotchas — already captured from the user. Honour the recorded startup order when starting services, and write the instructions out per the readiness-report stage. Absent means the skill had nothing to record; never invent them.
20
20
 
21
21
  ## Stages
@@ -34,7 +34,7 @@ Where a stage file offers the user a choice, take the branch the plan resolved;
34
34
 
35
35
  ## PID tracking
36
36
 
37
- Track every launched process in `/tmp/muggle-test-prepare.json` exactly per the skill's schema (`session_started`, `testing_scope`, `excluded_services`, `services[]` with pid/port/log). Processes the user started independently stay `external: true` and are never killed. Prune dead PIDs silently.
37
+ Track every launched process in the tracking file of the checkout it runs from, exactly per the skill's [PID Tracking](../skills/muggle-test-prepare/SKILL.md#pid-tracking) schema (`services[]` with pid/port/headSha/log). Never write into, or kill a process recorded in, another checkout's file — that is a parallel session's server. Processes the user started independently stay `external: true` and are never killed. Prune dead PIDs silently.
38
38
 
39
39
  ## Output contract
40
40
 
@@ -10,7 +10,8 @@ The caller resolves these before the loop and supplies them per test case:
10
10
 
11
11
  - `mode` — `replay` or `regen`, already chosen (by the user, or by [`../failure-mode-handling.md`](../failure-mode-handling.md) for change-driven callers).
12
12
  - `localUrl` — local execution target. Local-only; never changes the cloud project or test definitions.
13
- - `cwd` — absolute path of the active working tree (PR-branch worktree if one exists, else repo root). Drives the cross-worktree single-flight lock so concurrent runs serialize.
13
+ - `cwd` — absolute path of the active working tree (PR-branch worktree if one exists, else repo root). Drives the cross-worktree single-flight lock so concurrent runs serialize, and names the checkout the execute tools check for freshness.
14
+ - `baseBranch` — the change's base, only when it is not the remote default (a stacked change, a PR into a release branch). Omitted, the tools check `cwd` against the remote default.
14
15
  - `testCase` / `cloudTestCaseId` — the cloud test case and its id.
15
16
  - `showUi` — from the caller's `showElectronBrowser` resolution: omit for visible, `false` for headless.
16
17
 
@@ -32,3 +33,5 @@ Per test case, branch on `mode`:
32
33
  2. `muggle-local-execute-test-generation` with `testCase`, `localUrl`, `cwd`, `showUi`, `freshSession` (omit it so the stored flag decides; pass it only to override for this run, per [`fresh-session.md`](fresh-session.md)), `timeoutMs`.
33
34
 
34
35
  Store the returned `runId`, tagged with its `mode`. If a run fails, log it and continue the batch — never abort. Read the result per [`failures.md`](failures.md), then [`publish.md`](publish.md).
36
+
37
+ **A refused run is not a failure.** A result headed `Run refused — checkout is not on the latest …` launched nothing and has no `runId`: the `cwd` checkout lacks its base's latest commit (`BEHIND_BASE`) or carries another branch's commits (`FOREIGN_BASE`). Sync it per [`../sync-branch-with-base.md`](../sync-branch-with-base.md), re-invoke [`muggle-test-prepare`](../../muggle-test-prepare/SKILL.md) so the dev server serves the synced code, and run the case again. Never route it through failure handling or count it as a result.
@@ -37,11 +37,12 @@ A worktree's dependency dir (`node_modules`, and nested workspace copies) is oft
37
37
  `git worktree remove` refuses for two unrelated reasons, and **both texts lead to the same forbidden flag** — one because it is the obvious fix, the other because git prints it as the suggestion. Clear each cause at its source; neither is a reason to reconsider the flag.
38
38
 
39
39
  1. **Never `--force`.** It is the one flag that follows links.
40
- 2. Clear the dependency and build dirs first, nested workspace ones included (`packages/*/node_modules`, `dist`). A plain `git worktree remove` fails with `Directory not empty` while they remain, and the obvious fix for that error is exactly the forbidden flag.
40
+ 2. Stop the services environment prep started from this worktree (step 6 names their tracker) — a running dev server holds files open, and on Windows the removal then fails.
41
+ 3. Clear the dependency and build dirs first, nested workspace ones included (`packages/*/node_modules`, `dist`). A plain `git worktree remove` fails with `Directory not empty` while they remain, and the obvious fix for that error is exactly the forbidden flag.
41
42
  - A **link** → unlink it first with the host OS's unlink, removing the link only and never its target.
42
43
  - A **real directory** → delete it in place.
43
44
  Check which it is before deleting; the two are indistinguishable from a listing but not from a `rm -r`.
44
- 3. Clear the worktree's own dirty state — what the merge already landed, and nothing else. While anything remains, removal fails with `contains modified or untracked files, use --force to delete it`, an error that prescribes the forbidden flag in its own text.
45
+ 4. Clear the worktree's own dirty state — what the merge already landed, and nothing else. While anything remains, removal fails with `contains modified or untracked files, use --force to delete it`, an error that prescribes the forbidden flag in its own text.
45
46
 
46
47
  Expect this on any cycle that pushed through a server-side signed commit: that mutation writes to the remote only, so the worktree keeps the edits as modifications of a commit it never made locally. The dirt is this cycle's own landed work, not something the user left behind.
47
48
 
@@ -50,8 +51,8 @@ A worktree's dependency dir (`node_modules`, and nested workspace copies) is oft
50
51
  - **Untracked files** — never on the base, so no diff can clear them. Delete only the paths this procedure itself created: the dependency and build dirs cleared above. Anything else stops the sequence and is reported by name; an untracked file is the one thing in the worktree with no copy anywhere.
51
52
 
52
53
  **Never `git clean -x`.** `-x` is what reaches the ignored dependency dir, and clean recurses through a link exactly as a forced remove does — it undoes the unlink above under a different name.
53
- 4. Then plain `git worktree remove {worktreePath}`.
54
- 5. `git worktree prune` to drop the administrative entry when the directory went away out from under git.
54
+ 5. Then plain `git worktree remove {worktreePath}`.
55
+ 6. `git worktree prune` to drop the administrative entry when the directory went away out from under git.
55
56
 
56
57
  **Verify:** the path is gone, it no longer appears in `git worktree list`, the removal ran without `--force`, **and** the shared dependency tree the links pointed at still exists. That last check is the one that catches a link-follow.
57
58
 
@@ -87,9 +88,9 @@ Clear it only when `prs.json` records a terminal state. A slot for a still-open
87
88
 
88
89
  ## 6. Clear this run's prepare artifacts
89
90
 
90
- The PID tracker and per-service logs written during environment prep — `/tmp/muggle-test-prepare.json` and `/tmp/muggle-prepare-*.log`.
91
+ The services environment prep started from the merged change's worktree, with their tracker and logs — that worktree's tracking file and log directory, per [`muggle-test-prepare`'s PID Tracking](../muggle-test-prepare/SKILL.md#pid-tracking). Stop any tracked PID still alive (step 2 normally already has), then delete both.
91
92
 
92
- **Only this run's.** Artifacts belonging to another session are not yours to delete; it may be mid-prepare with services running. When the tracker is absent no services are tracked, so any remaining logs are orphaned — report them rather than removing them.
93
+ **Only this run's worktree.** Another checkout's tracker belongs to another session, which may be mid-prepare with services running; a base checkout's services are shared by every session. Neither is yours to stop or delete.
93
94
 
94
95
  Cloud results always stay.
95
96
 
@@ -8,10 +8,10 @@ A skill receives a GitHub PR URL of the form `github.com/<org>/<repo>/pull/<n>`
8
8
 
9
9
  ## Steps
10
10
 
11
- 1. **Resolve the PR's head branch:**
12
- `gh pr view <n> --repo <org>/<repo> --json headRefName -q .headRefName`
11
+ 1. **Resolve the PR's head and base branches:**
12
+ `gh pr view <n> --repo <org>/<repo> --json headRefName,baseRefName`
13
13
  2. **Sanitize the branch name** for filesystem use — replace `/` and other path separators with `-`. Example: `claude/regen-test-replay-flow-ZSScQ` → `claude-regen-test-replay-flow-ZSScQ`.
14
- 3. **Build the target worktree path:** `<repo>/.claude/worktrees/<sanitized-branch>`.
14
+ 3. **Build the target worktree path:** `<repo>/.claude/worktrees/<sanitized-branch>`, where `<repo>` is the clone's main working tree (the first `worktree` line of `git worktree list --porcelain`) even when the session stands in another worktree.
15
15
  4. **Materialize the worktree:**
16
16
  - If the target path does NOT exist:
17
17
  - `git -C <repo> fetch origin <branch>`
@@ -19,10 +19,11 @@ A skill receives a GitHub PR URL of the form `github.com/<org>/<repo>/pull/<n>`
19
19
  - If the target path EXISTS (reused from a prior run):
20
20
  - `git -C <target-path> fetch`
21
21
  - `git -C <target-path> reset --hard origin/<branch>` — picks up new pushes, drops any local cruft.
22
- 5. **Use the worktree path as the working directory** for the rest of the run, including:
23
- - Passing it as the **`cwd` parameter** to `muggle-local-execute-test-generation` and `muggle-local-execute-replay`. This is required, not optional — see `_shared/failure-mode-handling.md` and the lock identity discussion in those tools' MCP source.
22
+ 5. **Bring it onto the latest base.** A PR branch opened days ago lacks everything merged since; testing it as-is tests code that will never ship. Sync the worktree onto `origin/<baseRefName>` per [`sync-branch-with-base.md`](sync-branch-with-base.md), passing `baseRefName` as the base. This rebase is local and test-only — **never push it**; the next run's `reset --hard` discards it. A rebase that conflicts means the PR cannot merge as it stands: report the conflicted files and stop rather than testing either side alone.
23
+ 6. **Use the worktree path as the working directory** for the rest of the run, including:
24
+ - Passing it as the **`cwd` parameter** to `muggle-local-execute-test-generation` and `muggle-local-execute-replay`. This is required, not optional — see `_shared/failure-mode-handling.md` and the lock identity discussion in those tools' MCP source. When `baseRefName` is not the remote default, pass it as `baseBranch` too: the tools refuse a loopback run whose `cwd` lacks its base's latest commit.
24
25
  - Resolving any `npm install` / dev-server start commands inside the worktree (it has its own `node_modules/` and `.env*` files).
25
- 6. **Tell the user** where the worktree lives so they can clean it up later with `git -C <repo> worktree remove <target-path>`.
26
+ 7. **Tell the user** where the worktree lives so they can clean it up later with `git -C <repo> worktree remove <target-path>`.
26
27
 
27
28
  ## Invariants
28
29