@muggleai/works 5.34.0-staging.308 → 5.34.0-staging.310

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 (47) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/{chunk-C4L5SKOX.js → chunk-SMUHQITB.js} +27 -14
  3. package/dist/{chunk-L4ZDHFEJ.js → chunk-TVA5J73U.js} +294 -73
  4. package/dist/cli.js +2 -2
  5. package/dist/index.js +2 -2
  6. package/dist/plugin/.claude-plugin/plugin.json +1 -1
  7. package/dist/plugin/.codex-mcp.json +1 -1
  8. package/dist/plugin/.codex-plugin/plugin.json +1 -1
  9. package/dist/plugin/.cursor-plugin/plugin.json +1 -1
  10. package/dist/plugin/.mcp.json +1 -1
  11. package/dist/plugin/skills/_shared/dev-loop/fresh-session.md +1 -1
  12. package/dist/plugin/skills/_shared/dev-loop/run.md +2 -1
  13. package/dist/plugin/skills/_shared/test-case-design.md +8 -0
  14. package/dist/plugin/skills/do/e2e-acceptance.md +1 -1
  15. package/dist/plugin/skills/muggle-browser-task/SKILL.md +3 -0
  16. package/dist/plugin/skills/muggle-test/SKILL.md +1 -1
  17. package/dist/plugin/skills/muggle-test/execute-remote.md +1 -1
  18. package/dist/plugin/skills/muggle-test-feature-local/SKILL.md +1 -0
  19. package/dist/plugin/skills/muggle-test-import/SKILL.md +2 -0
  20. package/dist/plugin/skills/muggle-test-regenerate-missing/SKILL.md +1 -1
  21. package/dist/release-manifest.json +4 -4
  22. package/dist/{src-Z5YREWY6.js → src-5M2MYBRC.js} +1 -1
  23. package/package.json +1 -1
  24. package/plugin/.claude-plugin/plugin.json +1 -1
  25. package/plugin/.codex-mcp.json +1 -1
  26. package/plugin/.codex-plugin/plugin.json +1 -1
  27. package/plugin/.cursor-plugin/plugin.json +1 -1
  28. package/plugin/.mcp.json +1 -1
  29. package/plugin/skills/_shared/dev-loop/fresh-session.md +1 -1
  30. package/plugin/skills/_shared/dev-loop/run.md +2 -1
  31. package/plugin/skills/_shared/test-case-design.md +8 -0
  32. package/plugin/skills/do/e2e-acceptance.md +1 -1
  33. package/plugin/skills/muggle-browser-task/SKILL.md +3 -0
  34. package/plugin/skills/muggle-test/SKILL.md +1 -1
  35. package/plugin/skills/muggle-test/execute-remote.md +1 -1
  36. package/plugin/skills/muggle-test-feature-local/SKILL.md +1 -0
  37. package/plugin/skills/muggle-test-import/SKILL.md +2 -0
  38. package/plugin/skills/muggle-test-regenerate-missing/SKILL.md +1 -1
  39. package/scripts/postinstall.mjs +12 -13
  40. package/scripts/release-integrity/classifyTrustRootFailure.mjs +67 -0
  41. package/scripts/release-integrity/constants.mjs +55 -0
  42. package/scripts/release-integrity/enforceReleaseSignature.mjs +62 -0
  43. package/scripts/release-integrity/findBundleMismatch.mjs +58 -0
  44. package/scripts/release-integrity/index.d.mts +10 -1
  45. package/scripts/release-integrity/index.mjs +1 -0
  46. package/scripts/release-integrity/resolveIntegrityPolicy.mjs +11 -2
  47. package/scripts/release-integrity/verifyReleaseSignature.mjs +60 -8
@@ -1,24 +1,25 @@
1
- import { __export, getLogger, TelemetryEnvironment, getConfig, createChildLogger, buildElectronAppReleaseAssetUrl, getActiveRuntimeTarget, getAuthService, hasApiKey, getElectronAppVersion, getElectronAppDir, getPlatformKey, reconcileProjectPreferences, getDataDir2, 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, buildToolInputJsonSchema, toolRequiresAuth, getCallerCredentials, parseElectronAppDirName, getElectronAppReleaseTagPrefix, hasShownDisclosure, markDisclosureShown, getBundledElectronAppVersion, getElectronAppVersionSource, getCredentialsFilePath, ElectronAppReleaseStream, buildElectronAppChecksumsUrl, __require, getDisclosureCopy, buildOnboardingPlan, applyOnboardingAnswers, needsOnboarding, buildLlmSourcePlan, describeLlmSourceStatus, resolveLlmSourceStatus, readRunView, RunViewError, renderRunViewText, writeRunViewHtml, openBrowserUrl, evaluateCheckoutFreshness, runGitCommand, BLOCKING_FRESHNESS_VERDICTS, claimServiceStack, BUSY_EXIT_CODE, checkServiceStack, releaseServiceStack, readServiceStackStatus, resolvePreferences, OnboardingBlanketChoice, PreferenceKey, LlmSource, applyLlmSourceSelection, describeStackMismatch, getDataDir, DEFAULT_LOCAL_LLM_BASE_URL, isValidLocalBaseUrl, local_exports } from './chunk-C4L5SKOX.js';
1
+ import { __export, getLogger, TelemetryEnvironment, getConfig, createChildLogger, buildElectronAppReleaseAssetUrl, getActiveRuntimeTarget, getAuthService, hasApiKey, getElectronAppVersion, getElectronAppDir, getPlatformKey, reconcileProjectPreferences, getDataDir2, 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, buildToolInputJsonSchema, toolRequiresAuth, getCallerCredentials, parseElectronAppDirName, getElectronAppReleaseTagPrefix, hasShownDisclosure, markDisclosureShown, getBundledElectronAppVersion, getElectronAppVersionSource, getCredentialsFilePath, ElectronAppReleaseStream, __require, getDisclosureCopy, buildOnboardingPlan, applyOnboardingAnswers, needsOnboarding, buildLlmSourcePlan, describeLlmSourceStatus, resolveLlmSourceStatus, readRunView, RunViewError, renderRunViewText, writeRunViewHtml, openBrowserUrl, evaluateCheckoutFreshness, runGitCommand, BLOCKING_FRESHNESS_VERDICTS, claimServiceStack, BUSY_EXIT_CODE, checkServiceStack, releaseServiceStack, readServiceStackStatus, resolvePreferences, buildElectronAppChecksumsUrl, OnboardingBlanketChoice, PreferenceKey, LlmSource, applyLlmSourceSelection, describeStackMismatch, getDataDir, DEFAULT_LOCAL_LLM_BASE_URL, isValidLocalBaseUrl, local_exports } from './chunk-SMUHQITB.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';
5
5
  import { z, ZodError } from 'zod';
6
6
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
7
7
  import * as fs from 'fs';
8
- import { readFileSync, existsSync, rmSync, mkdirSync, readdirSync, createWriteStream, writeFileSync, statSync, readlinkSync, realpathSync, openSync, closeSync, writeSync, unlinkSync, copyFileSync, renameSync, appendFileSync, readSync, fstatSync } from 'fs';
8
+ import { readFileSync, existsSync, rmSync, readdirSync, mkdirSync, writeFileSync, renameSync, createWriteStream, statSync, readlinkSync, realpathSync, openSync, closeSync, writeSync, unlinkSync, copyFileSync, appendFileSync, readSync, fstatSync } from 'fs';
9
9
  import * as path from 'path';
10
10
  import { join, dirname, resolve, win32, basename } from 'path';
11
11
  import { fileURLToPath, pathToFileURL } from 'url';
12
12
  import { Command } from 'commander';
13
13
  import axios from 'axios';
14
- import { createHash } from 'crypto';
14
+ import { createHash, X509Certificate, verify } from 'crypto';
15
15
  import { platform, homedir, arch, tmpdir, hostname } from 'os';
16
16
  import { execFile, execFileSync, spawnSync, spawn } from 'child_process';
17
17
  import { createInterface } from 'readline/promises';
18
18
  import { Writable } from 'stream';
19
19
  import { pipeline } from 'stream/promises';
20
20
  import { readFile } from 'fs/promises';
21
- import { verify } from 'sigstore';
21
+ import { createVerifier, TUFError } from 'sigstore';
22
+ import { setTimeout as setTimeout$1 } from 'timers/promises';
22
23
 
23
24
  var registeredTools = [];
24
25
  function registerTools(tools) {
@@ -254,8 +255,8 @@ function createUnifiedMcpServer(options) {
254
255
  errors: error.issues
255
256
  });
256
257
  const issueMessages = error.issues.slice(0, 3).map((issue) => {
257
- const path6 = issue.path.join(".");
258
- return path6 ? `'${path6}': ${issue.message}` : issue.message;
258
+ const path7 = issue.path.join(".");
259
+ return path7 ? `'${path7}': ${issue.message}` : issue.message;
259
260
  });
260
261
  return {
261
262
  content: [
@@ -1255,7 +1256,7 @@ async function resolveGsScreenshotUrls(report, opts) {
1255
1256
  if (gsUrls.length === 0) {
1256
1257
  return report;
1257
1258
  }
1258
- const mcps = await import('./src-Z5YREWY6.js');
1259
+ const mcps = await import('./src-5M2MYBRC.js');
1259
1260
  const credentials = await mcps.getCallerCredentialsAsync();
1260
1261
  if (!credentials.bearerToken && !credentials.apiKey) {
1261
1262
  stderrWrite(
@@ -1492,12 +1493,12 @@ var WORKFLOW_WRITING_OUTCOMES = /* @__PURE__ */ new Set([
1492
1493
  "replaced" /* Replaced */
1493
1494
  ]);
1494
1495
  var CI_INSTALL_MESSAGES = {
1495
- ["installed" /* Installed */]: (path6) => `Wrote ${path6}
1496
+ ["installed" /* Installed */]: (path7) => `Wrote ${path7}
1496
1497
  Commit it, and every pull request here will owe a settled Muggle AI walkthrough comment.`,
1497
- ["updated" /* Updated */]: (path6) => `Updated ${path6} from an earlier Muggle release to the current workflow. Commit it.`,
1498
- ["already-current" /* AlreadyCurrent */]: (path6) => `${path6} is already the current workflow \u2014 nothing to do.`,
1499
- ["kept-customized" /* KeptCustomized */]: (path6) => `${path6} has been edited since Muggle wrote it \u2014 left untouched. Re-run with --force to replace it.`,
1500
- ["replaced" /* Replaced */]: (path6) => `Replaced ${path6} with the current workflow. Commit it.`,
1498
+ ["updated" /* Updated */]: (path7) => `Updated ${path7} from an earlier Muggle release to the current workflow. Commit it.`,
1499
+ ["already-current" /* AlreadyCurrent */]: (path7) => `${path7} is already the current workflow \u2014 nothing to do.`,
1500
+ ["kept-customized" /* KeptCustomized */]: (path7) => `${path7} has been edited since Muggle wrote it \u2014 left untouched. Re-run with --force to replace it.`,
1501
+ ["replaced" /* Replaced */]: (path7) => `Replaced ${path7} with the current workflow. Commit it.`,
1501
1502
  ["not-a-repository" /* NotARepository */]: () => "Not a git repository \u2014 run this from the repo that should carry the check."
1502
1503
  };
1503
1504
 
@@ -2753,8 +2754,8 @@ ${title}`, COLORS.bold + COLORS.cyan);
2753
2754
  function cmd(cmd2) {
2754
2755
  return colorize(cmd2, COLORS.green);
2755
2756
  }
2756
- function path3(path6) {
2757
- return colorize(path6, COLORS.yellow);
2757
+ function path3(path7) {
2758
+ return colorize(path7, COLORS.yellow);
2758
2759
  }
2759
2760
  function getHelpGuidance() {
2760
2761
  const lines = [
@@ -4153,6 +4154,32 @@ async function serveCommand(options) {
4153
4154
  var SIGNATURE_BUNDLE_SUFFIX = ".sigstore.json";
4154
4155
  var SIGNER_CERTIFICATE_ISSUER = "https://token.actions.githubusercontent.com";
4155
4156
  var SIGNATURE_FETCH_TIMEOUT_MS = 3e4;
4157
+ var SIGNATURE_TRUST_ROOT_HOST = "tuf-repo-cdn.sigstore.dev";
4158
+ var SIGNATURE_VERIFIED_MESSAGE = "Signature verified successfully.";
4159
+ var SIGNATURE_REFUSAL_PREFIX = "Signature verification failed, refusing to install: ";
4160
+ var BUNDLE_DIGEST_ALGORITHM = "SHA2_256";
4161
+ var BUNDLE_HASH_ALGORITHM = "sha256";
4162
+ var CERTIFICATE_URI_SAN_PREFIX = "URI:";
4163
+ var CERTIFICATE_SAN_SEPARATOR = ", ";
4164
+ var TRUST_ROOT_FETCH_ERROR_CODES = /* @__PURE__ */ new Set([
4165
+ "TUF_REFRESH_METADATA_ERROR",
4166
+ "TUF_DOWNLOAD_TARGET_ERROR"
4167
+ ]);
4168
+ var HOST_UNREACHABLE_ERROR_CODES = /* @__PURE__ */ new Set([
4169
+ "ENOTFOUND",
4170
+ "EAI_AGAIN",
4171
+ "ECONNREFUSED",
4172
+ "ECONNRESET",
4173
+ "ETIMEDOUT",
4174
+ "ENETUNREACH",
4175
+ "EHOSTUNREACH",
4176
+ "ENETDOWN",
4177
+ "UND_ERR_CONNECT_TIMEOUT",
4178
+ "UND_ERR_SOCKET"
4179
+ ]);
4180
+ var FETCH_TIMEOUT_ERROR_NAME = "TimeoutError";
4181
+ var FLATTENED_TRUST_ROOT_TIMEOUT_PATTERN = /^Unable to load (?:snapshot metadata|targets) error TimeoutError: The operation was aborted due to timeout$/;
4182
+ var MAX_ERROR_CAUSE_DEPTH = 5;
4156
4183
 
4157
4184
  // scripts/release-integrity/compareVersions.mjs
4158
4185
  function compareVersions2(a, b) {
@@ -4172,10 +4199,12 @@ function compareVersions2(a, b) {
4172
4199
  }
4173
4200
 
4174
4201
  // scripts/release-integrity/resolveIntegrityPolicy.mjs
4202
+ function hasExpectedChecksum(expectedChecksum) {
4203
+ return Boolean(expectedChecksum && expectedChecksum.trim());
4204
+ }
4175
4205
  function resolveIntegrityPolicy({ version, signedFromVersion, expectedChecksum }) {
4176
4206
  const requiresSignature = Boolean(signedFromVersion) && compareVersions2(version, signedFromVersion) >= 0;
4177
- const hasChecksum = Boolean(expectedChecksum && expectedChecksum.trim());
4178
- if (!requiresSignature && !hasChecksum) {
4207
+ if (!requiresSignature && !hasExpectedChecksum(expectedChecksum)) {
4179
4208
  return {
4180
4209
  requiresSignature: false,
4181
4210
  requiresChecksum: false,
@@ -4188,9 +4217,66 @@ function resolveIntegrityPolicy({ version, signedFromVersion, expectedChecksum }
4188
4217
  unverifiableReason: ""
4189
4218
  };
4190
4219
  }
4220
+ function listErrorChain(error) {
4221
+ const chain = [];
4222
+ let current = error;
4223
+ while (current && chain.length < MAX_ERROR_CAUSE_DEPTH) {
4224
+ chain.push(current);
4225
+ current = current.cause;
4226
+ }
4227
+ return chain;
4228
+ }
4229
+ function isTrustRootUnreachable(trustRootError) {
4230
+ if (!(trustRootError instanceof TUFError) || !TRUST_ROOT_FETCH_ERROR_CODES.has(trustRootError.code)) {
4231
+ return false;
4232
+ }
4233
+ return listErrorChain(trustRootError.cause).some(
4234
+ (chainedError) => chainedError.name === FETCH_TIMEOUT_ERROR_NAME || HOST_UNREACHABLE_ERROR_CODES.has(chainedError.code) || FLATTENED_TRUST_ROOT_TIMEOUT_PATTERN.test(chainedError.message ?? "")
4235
+ );
4236
+ }
4237
+ function describeErrorChain(error) {
4238
+ return listErrorChain(error).map((chainedError) => chainedError.message).filter(Boolean).join(": ");
4239
+ }
4240
+ function findBundleMismatch({ bundle, artifactBytes, signerIdentityUri }) {
4241
+ const messageSignature = bundle?.messageSignature;
4242
+ const messageDigest = messageSignature?.messageDigest;
4243
+ const certificateRawBytes = bundle?.verificationMaterial?.certificate?.rawBytes;
4244
+ if (!messageDigest?.digest || !messageSignature?.signature || !certificateRawBytes) {
4245
+ return "the signature bundle is missing its digest, signature or signing certificate";
4246
+ }
4247
+ if (messageDigest.algorithm !== BUNDLE_DIGEST_ALGORITHM) {
4248
+ return `the signature bundle uses an unexpected digest algorithm: ${messageDigest.algorithm}`;
4249
+ }
4250
+ const artifactDigest = createHash(BUNDLE_HASH_ALGORITHM).update(artifactBytes).digest();
4251
+ if (!artifactDigest.equals(Buffer.from(messageDigest.digest, "base64"))) {
4252
+ return "the download does not match the digest recorded in its signature bundle";
4253
+ }
4254
+ try {
4255
+ const signingCertificate = new X509Certificate(Buffer.from(certificateRawBytes, "base64"));
4256
+ const certificateNames = (signingCertificate.subjectAltName ?? "").split(CERTIFICATE_SAN_SEPARATOR);
4257
+ if (!certificateNames.includes(`${CERTIFICATE_URI_SAN_PREFIX}${signerIdentityUri}`)) {
4258
+ return `the signing certificate was not issued to ${signerIdentityUri}`;
4259
+ }
4260
+ const isSignatureMatching = verify(
4261
+ BUNDLE_HASH_ALGORITHM,
4262
+ artifactBytes,
4263
+ signingCertificate.publicKey,
4264
+ Buffer.from(messageSignature.signature, "base64")
4265
+ );
4266
+ return isSignatureMatching ? "" : "the signature in the bundle does not match the download";
4267
+ } catch (error) {
4268
+ return `the signature bundle could not be read: ${error.message}`;
4269
+ }
4270
+ }
4271
+
4272
+ // scripts/release-integrity/verifyReleaseSignature.mjs
4191
4273
  async function verifyReleaseSignature({ artifactPath, bundleUrl, signerIdentityUri }) {
4192
4274
  if (!signerIdentityUri) {
4193
- return { valid: false, reason: "no signer identity is configured to verify against" };
4275
+ return {
4276
+ valid: false,
4277
+ reason: "no signer identity is configured to verify against",
4278
+ isTrustRootUnreachable: false
4279
+ };
4194
4280
  }
4195
4281
  const controller = new AbortController();
4196
4282
  const timer = setTimeout(() => controller.abort(), SIGNATURE_FETCH_TIMEOUT_MS);
@@ -4200,23 +4286,161 @@ async function verifyReleaseSignature({ artifactPath, bundleUrl, signerIdentityU
4200
4286
  if (!response.ok) {
4201
4287
  return {
4202
4288
  valid: false,
4203
- reason: `signature bundle unavailable (HTTP ${response.status}) at ${bundleUrl}`
4289
+ reason: `signature bundle unavailable (HTTP ${response.status}) at ${bundleUrl}`,
4290
+ isTrustRootUnreachable: false
4204
4291
  };
4205
4292
  }
4206
4293
  bundle = await response.json();
4207
4294
  } catch (error) {
4208
- return { valid: false, reason: `could not fetch signature bundle: ${error.message}` };
4295
+ return {
4296
+ valid: false,
4297
+ reason: `could not fetch signature bundle: ${error.message}`,
4298
+ isTrustRootUnreachable: false
4299
+ };
4209
4300
  } finally {
4210
4301
  clearTimeout(timer);
4211
4302
  }
4303
+ let artifactBytes;
4304
+ try {
4305
+ artifactBytes = await readFile(artifactPath);
4306
+ } catch (error) {
4307
+ return { valid: false, reason: error.message, isTrustRootUnreachable: false };
4308
+ }
4309
+ let bundleVerifier;
4212
4310
  try {
4213
- await verify(bundle, await readFile(artifactPath), {
4311
+ bundleVerifier = await createVerifier({
4214
4312
  certificateIssuer: SIGNER_CERTIFICATE_ISSUER,
4215
4313
  certificateIdentityURI: signerIdentityUri
4216
4314
  });
4217
- return { valid: true, reason: "" };
4218
4315
  } catch (error) {
4219
- return { valid: false, reason: error.message };
4316
+ const failureDescription = describeErrorChain(error);
4317
+ if (!isTrustRootUnreachable(error)) {
4318
+ return {
4319
+ valid: false,
4320
+ reason: `could not load the trust root from ${SIGNATURE_TRUST_ROOT_HOST}: ${failureDescription}`,
4321
+ isTrustRootUnreachable: false
4322
+ };
4323
+ }
4324
+ const bundleMismatch = findBundleMismatch({
4325
+ bundle,
4326
+ artifactBytes,
4327
+ signerIdentityUri
4328
+ });
4329
+ return {
4330
+ valid: false,
4331
+ reason: bundleMismatch || failureDescription,
4332
+ isTrustRootUnreachable: !bundleMismatch
4333
+ };
4334
+ }
4335
+ try {
4336
+ bundleVerifier.verify(bundle, artifactBytes);
4337
+ return { valid: true, reason: "", isTrustRootUnreachable: false };
4338
+ } catch (error) {
4339
+ return { valid: false, reason: error.message, isTrustRootUnreachable: false };
4340
+ }
4341
+ }
4342
+
4343
+ // scripts/release-integrity/enforceReleaseSignature.mjs
4344
+ async function enforceReleaseSignature({
4345
+ artifactPath,
4346
+ bundleUrl,
4347
+ signerIdentityUri,
4348
+ expectedChecksum,
4349
+ logInfo,
4350
+ logWarning
4351
+ }) {
4352
+ const signatureOutcome = await verifyReleaseSignature({
4353
+ artifactPath,
4354
+ bundleUrl,
4355
+ signerIdentityUri
4356
+ });
4357
+ if (signatureOutcome.valid) {
4358
+ logInfo(SIGNATURE_VERIFIED_MESSAGE);
4359
+ return { isSignatureVerified: true };
4360
+ }
4361
+ if (!signatureOutcome.isTrustRootUnreachable) {
4362
+ throw new Error(SIGNATURE_REFUSAL_PREFIX + signatureOutcome.reason);
4363
+ }
4364
+ const networkFailure = `a network failure kept ${SIGNATURE_TRUST_ROOT_HOST} out of reach (${signatureOutcome.reason})`;
4365
+ if (!hasExpectedChecksum(expectedChecksum)) {
4366
+ throw new Error(`${SIGNATURE_REFUSAL_PREFIX}${networkFailure}, and no checksum is available to check instead.`);
4367
+ }
4368
+ logWarning(
4369
+ `WARNING: The signature was NOT verified: ${networkFailure}. Falling back to the checksum check only.`
4370
+ );
4371
+ return { isSignatureVerified: false };
4372
+ }
4373
+
4374
+ // src/cli/studio-install-staging-constants.ts
4375
+ var STUDIO_STAGING_DIR_NAME = "studio-stage";
4376
+ var RETIRED_INSTALL_SUFFIX = ".retired";
4377
+ var INSTALL_MOVE_MAX_ATTEMPTS = 10;
4378
+ var INSTALL_MOVE_RETRY_DELAY_MS = 500;
4379
+ var INSTALL_MOVE_RETRYABLE_ERROR_CODES = /* @__PURE__ */ new Set(["EPERM", "EACCES", "EBUSY"]);
4380
+
4381
+ // src/cli/studio-install-staging.ts
4382
+ function getStudioStagingDir(versionDir) {
4383
+ return path.join(getDataDir2(), STUDIO_STAGING_DIR_NAME, path.basename(versionDir));
4384
+ }
4385
+ function getRetiredInstallDir(stagingDir) {
4386
+ return `${stagingDir}${RETIRED_INSTALL_SUFFIX}`;
4387
+ }
4388
+ function prepareStudioStagingDir(params) {
4389
+ const { stagingDir, versionDir } = params;
4390
+ const retiredDir = getRetiredInstallDir(stagingDir);
4391
+ if (existsSync(retiredDir) && !existsSync(versionDir)) {
4392
+ renameSync(retiredDir, versionDir);
4393
+ }
4394
+ rmSync(stagingDir, { recursive: true, force: true });
4395
+ rmSync(retiredDir, { recursive: true, force: true });
4396
+ mkdirSync(stagingDir, { recursive: true });
4397
+ }
4398
+ function discardStudioStagingDir(stagingDir) {
4399
+ try {
4400
+ rmSync(stagingDir, { recursive: true, force: true });
4401
+ } catch {
4402
+ }
4403
+ }
4404
+ async function moveDirectory(fromDir, toDir) {
4405
+ for (let attempt = 1; ; attempt++) {
4406
+ try {
4407
+ renameSync(fromDir, toDir);
4408
+ return;
4409
+ } catch (error) {
4410
+ const errorCode = error.code ?? "";
4411
+ if (attempt >= INSTALL_MOVE_MAX_ATTEMPTS || !INSTALL_MOVE_RETRYABLE_ERROR_CODES.has(errorCode)) {
4412
+ throw error;
4413
+ }
4414
+ await setTimeout$1(INSTALL_MOVE_RETRY_DELAY_MS);
4415
+ }
4416
+ }
4417
+ }
4418
+ async function replaceStudioInstall(params) {
4419
+ const { stagingDir, versionDir } = params;
4420
+ mkdirSync(path.dirname(versionDir), { recursive: true });
4421
+ if (!existsSync(versionDir)) {
4422
+ await moveDirectory(stagingDir, versionDir);
4423
+ return;
4424
+ }
4425
+ const retiredDir = getRetiredInstallDir(stagingDir);
4426
+ try {
4427
+ await moveDirectory(versionDir, retiredDir);
4428
+ } catch (error) {
4429
+ const errorMessage = error instanceof Error ? error.message : String(error);
4430
+ throw new Error(
4431
+ `Could not replace the install at ${versionDir}, which may be in use. It was left as it was: ${errorMessage}`,
4432
+ { cause: error }
4433
+ );
4434
+ }
4435
+ try {
4436
+ await moveDirectory(stagingDir, versionDir);
4437
+ } catch (error) {
4438
+ await moveDirectory(retiredDir, versionDir);
4439
+ throw error;
4440
+ }
4441
+ try {
4442
+ rmSync(retiredDir, { recursive: true, force: true });
4443
+ } catch {
4220
4444
  }
4221
4445
  }
4222
4446
 
@@ -4324,14 +4548,6 @@ function writeInstallMetadata(params) {
4324
4548
  writeFileSync(params.metadataPath, `${JSON.stringify(metadata, null, 2)}
4325
4549
  `, "utf-8");
4326
4550
  }
4327
- function cleanupFailedInstall(versionDir) {
4328
- if (existsSync(versionDir)) {
4329
- try {
4330
- rmSync(versionDir, { recursive: true, force: true });
4331
- } catch {
4332
- }
4333
- }
4334
- }
4335
4551
  function upsertCursorMcpConfig() {
4336
4552
  const cursorMcpConfigPath = path.join(homedir(), ".cursor", "mcp.json");
4337
4553
  const cursorDir = path.join(homedir(), ".cursor");
@@ -4392,12 +4608,10 @@ async function setupCommand(options) {
4392
4608
  });
4393
4609
  console.log(`Downloading Muggle Test Electron app v${version}...`);
4394
4610
  console.log(`URL: ${downloadUrl}`);
4611
+ const stagingDir = getStudioStagingDir(versionDir);
4395
4612
  try {
4396
- if (existsSync(versionDir)) {
4397
- rmSync(versionDir, { recursive: true, force: true });
4398
- }
4399
- mkdirSync(versionDir, { recursive: true });
4400
- const tempFile = path.join(versionDir, binaryName);
4613
+ prepareStudioStagingDir({ stagingDir, versionDir });
4614
+ const tempFile = path.join(stagingDir, binaryName);
4401
4615
  await downloadWithRetry(downloadUrl, tempFile);
4402
4616
  console.log("Download complete, verifying integrity...");
4403
4617
  const checksums = getElectronAppChecksums();
@@ -4408,24 +4622,23 @@ async function setupCommand(options) {
4408
4622
  expectedChecksum: expectedChecksum ?? ""
4409
4623
  });
4410
4624
  if (integrityPolicy.unverifiableReason) {
4411
- cleanupFailedInstall(versionDir);
4412
4625
  throw new Error("Refusing to install an unverifiable download: " + integrityPolicy.unverifiableReason);
4413
4626
  }
4627
+ let isSignatureVerified = false;
4414
4628
  if (integrityPolicy.requiresSignature) {
4415
- const signatureResult = await verifyReleaseSignature({
4629
+ const signatureEnforcement = await enforceReleaseSignature({
4416
4630
  artifactPath: tempFile,
4417
4631
  bundleUrl: downloadUrl + SIGNATURE_BUNDLE_SUFFIX,
4418
- signerIdentityUri: getReleaseSignerIdentityUri()
4632
+ signerIdentityUri: getReleaseSignerIdentityUri(),
4633
+ expectedChecksum: expectedChecksum ?? "",
4634
+ logInfo: console.log,
4635
+ logWarning: console.warn
4419
4636
  });
4420
- if (!signatureResult.valid) {
4421
- cleanupFailedInstall(versionDir);
4422
- throw new Error("Signature verification failed, refusing to install: " + signatureResult.reason);
4423
- }
4424
- console.log("Signature verified successfully.");
4637
+ isSignatureVerified = signatureEnforcement.isSignatureVerified;
4425
4638
  }
4426
4639
  const checksumResult = await verifyFileChecksum(tempFile, expectedChecksum);
4427
4640
  if (!checksumResult.valid && expectedChecksum) {
4428
- if (!integrityPolicy.requiresChecksum) {
4641
+ if (isSignatureVerified) {
4429
4642
  console.warn(
4430
4643
  `Pinned checksum does not match this download, but its signature verified.
4431
4644
  Expected: ${checksumResult.expected}
@@ -4433,7 +4646,6 @@ Actual: ${checksumResult.actual}
4433
4646
  The pin in package.json muggleConfig.checksumsByStream is stale for this release; continuing on the signature.`
4434
4647
  );
4435
4648
  } else {
4436
- cleanupFailedInstall(versionDir);
4437
4649
  throw new Error(
4438
4650
  `Checksum verification failed!
4439
4651
  Expected: ${checksumResult.expected}
@@ -4447,13 +4659,12 @@ The downloaded file may be corrupted or tampered with.`
4447
4659
  }
4448
4660
  console.log("Extracting...");
4449
4661
  if (binaryName.endsWith(".zip")) {
4450
- await extractZip(tempFile, versionDir);
4662
+ await extractZip(tempFile, stagingDir);
4451
4663
  } else if (binaryName.endsWith(".tar.gz")) {
4452
- await extractTarGz(tempFile, versionDir);
4664
+ await extractTarGz(tempFile, stagingDir);
4453
4665
  }
4454
- const executablePath = resolveElectronAppExecutablePath({ installDir: versionDir, platformName: platform() });
4666
+ const executablePath = resolveElectronAppExecutablePath({ installDir: stagingDir, platformName: platform() });
4455
4667
  if (!existsSync(executablePath)) {
4456
- cleanupFailedInstall(versionDir);
4457
4668
  throw new Error(
4458
4669
  `Extraction failed: executable not found at expected path.
4459
4670
  Expected: ${executablePath}
@@ -4461,7 +4672,7 @@ The archive may be corrupted or in an unexpected format.`
4461
4672
  );
4462
4673
  }
4463
4674
  const executableChecksum = await calculateFileChecksum(executablePath);
4464
- const metadataPath = path.join(versionDir, INSTALL_METADATA_FILE_NAME);
4675
+ const metadataPath = path.join(stagingDir, INSTALL_METADATA_FILE_NAME);
4465
4676
  writeInstallMetadata({
4466
4677
  metadataPath,
4467
4678
  version,
@@ -4471,9 +4682,11 @@ The archive may be corrupted or in an unexpected format.`
4471
4682
  expectedArchiveChecksum: expectedChecksum
4472
4683
  });
4473
4684
  rmSync(tempFile, { force: true });
4685
+ await replaceStudioInstall({ stagingDir, versionDir });
4474
4686
  console.log(`Electron app installed to ${versionDir}`);
4475
4687
  logger6.info("Setup complete", { version, path: versionDir });
4476
4688
  } catch (error) {
4689
+ discardStudioStagingDir(stagingDir);
4477
4690
  const errorMessage = error instanceof Error ? error.message : String(error);
4478
4691
  console.error(`Failed to download Electron app: ${errorMessage}`);
4479
4692
  logger6.error("Setup failed", { error: errorMessage });
@@ -4773,21 +4986,15 @@ async function fetchChecksumFromRelease(version) {
4773
4986
  return "";
4774
4987
  }
4775
4988
  }
4776
- async function downloadAndInstall(version, downloadUrl, checksum) {
4777
- const versionDir = getElectronAppDir(version);
4989
+ async function stageVerifiedDownload(params) {
4990
+ const { version, downloadUrl, checksum, stagingDir } = params;
4778
4991
  const binaryName = getBinaryName2();
4779
4992
  const platformKey = getPlatformKey();
4780
- console.log(`Downloading Muggle Test Electron app v${version}...`);
4781
- console.log(`URL: ${downloadUrl}`);
4782
- if (existsSync(versionDir)) {
4783
- rmSync(versionDir, { recursive: true, force: true });
4784
- }
4785
- mkdirSync(versionDir, { recursive: true });
4786
4993
  const response = await fetch(downloadUrl);
4787
4994
  if (!response.ok) {
4788
4995
  throw new Error(`Download failed: ${response.status} ${response.statusText}`);
4789
4996
  }
4790
- const tempFile = path.join(versionDir, binaryName);
4997
+ const tempFile = path.join(stagingDir, binaryName);
4791
4998
  const fileStream = createWriteStream(tempFile);
4792
4999
  if (!response.body) {
4793
5000
  throw new Error("No response body");
@@ -4804,24 +5011,20 @@ async function downloadAndInstall(version, downloadUrl, checksum) {
4804
5011
  expectedChecksum: expectedChecksum ?? ""
4805
5012
  });
4806
5013
  if (integrityPolicy.unverifiableReason) {
4807
- rmSync(versionDir, { recursive: true, force: true });
4808
5014
  throw new Error("Refusing to install an unverifiable download: " + integrityPolicy.unverifiableReason);
4809
5015
  }
4810
5016
  if (integrityPolicy.requiresSignature) {
4811
- const signatureResult = await verifyReleaseSignature({
5017
+ await enforceReleaseSignature({
4812
5018
  artifactPath: tempFile,
4813
5019
  bundleUrl: downloadUrl + SIGNATURE_BUNDLE_SUFFIX,
4814
- signerIdentityUri: getReleaseSignerIdentityUri()
5020
+ signerIdentityUri: getReleaseSignerIdentityUri(),
5021
+ expectedChecksum: expectedChecksum ?? "",
5022
+ logInfo: console.log,
5023
+ logWarning: console.warn
4815
5024
  });
4816
- if (!signatureResult.valid) {
4817
- rmSync(versionDir, { recursive: true, force: true });
4818
- throw new Error("Signature verification failed, refusing to install: " + signatureResult.reason);
4819
- }
4820
- console.log("Signature verified successfully.");
4821
5025
  }
4822
5026
  const checksumResult = await verifyFileChecksum(tempFile, expectedChecksum || "");
4823
5027
  if (!checksumResult.valid && expectedChecksum) {
4824
- rmSync(versionDir, { recursive: true, force: true });
4825
5028
  throw new Error(
4826
5029
  `Checksum verification failed!
4827
5030
  Expected: ${checksumResult.expected}
@@ -4834,13 +5037,12 @@ The downloaded file may be corrupted or tampered with.`
4834
5037
  }
4835
5038
  console.log("Extracting...");
4836
5039
  if (binaryName.endsWith(".zip")) {
4837
- await extractZip2(tempFile, versionDir);
5040
+ await extractZip2(tempFile, stagingDir);
4838
5041
  } else if (binaryName.endsWith(".tar.gz")) {
4839
- await extractTarGz2(tempFile, versionDir);
5042
+ await extractTarGz2(tempFile, stagingDir);
4840
5043
  }
4841
- const executablePath = resolveElectronAppExecutablePath({ installDir: versionDir, platformName: platform() });
5044
+ const executablePath = resolveElectronAppExecutablePath({ installDir: stagingDir, platformName: platform() });
4842
5045
  if (!existsSync(executablePath)) {
4843
- rmSync(versionDir, { recursive: true, force: true });
4844
5046
  throw new Error(
4845
5047
  `Extraction failed: executable not found at expected path.
4846
5048
  Expected: ${executablePath}
@@ -4848,7 +5050,7 @@ The archive may be corrupted or in an unexpected format.`
4848
5050
  );
4849
5051
  }
4850
5052
  const executableChecksum = await calculateFileChecksum(executablePath);
4851
- const metadataPath = path.join(versionDir, INSTALL_METADATA_FILE_NAME2);
5053
+ const metadataPath = path.join(stagingDir, INSTALL_METADATA_FILE_NAME2);
4852
5054
  writeInstallMetadata2({
4853
5055
  metadataPath,
4854
5056
  version,
@@ -4858,6 +5060,25 @@ The archive may be corrupted or in an unexpected format.`
4858
5060
  expectedArchiveChecksum: expectedChecksum || ""
4859
5061
  });
4860
5062
  rmSync(tempFile, { force: true });
5063
+ }
5064
+ async function downloadAndInstall(version, downloadUrl, checksum) {
5065
+ const versionDir = getElectronAppDir(version);
5066
+ const stagingDir = getStudioStagingDir(versionDir);
5067
+ console.log(`Downloading Muggle Test Electron app v${version}...`);
5068
+ console.log(`URL: ${downloadUrl}`);
5069
+ try {
5070
+ prepareStudioStagingDir({ stagingDir, versionDir });
5071
+ await stageVerifiedDownload({
5072
+ version,
5073
+ downloadUrl,
5074
+ checksum,
5075
+ stagingDir
5076
+ });
5077
+ await replaceStudioInstall({ stagingDir, versionDir });
5078
+ } catch (error) {
5079
+ discardStudioStagingDir(stagingDir);
5080
+ throw error;
5081
+ }
4861
5082
  saveVersionOverride(version);
4862
5083
  console.log(`Electron app v${version} installed to ${versionDir}`);
4863
5084
  logger7.info("Upgrade complete", { version, path: versionDir });
package/dist/cli.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { runCli } from './chunk-L4ZDHFEJ.js';
3
- import './chunk-C4L5SKOX.js';
2
+ import { runCli } from './chunk-TVA5J73U.js';
3
+ import './chunk-SMUHQITB.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-L4ZDHFEJ.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-C4L5SKOX.js';
1
+ export { src_exports as commands, createUnifiedMcpServer, server_exports as server } from './chunk-TVA5J73U.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-SMUHQITB.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.34.0-staging.308",
4
+ "version": "5.34.0-staging.310",
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.34.0-staging.308",
7
+ "@muggleai/works@5.34.0-staging.310",
8
8
  "serve"
9
9
  ],
10
10
  "env": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "muggle",
3
- "version": "5.34.0-staging.308",
3
+ "version": "5.34.0-staging.310",
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.34.0-staging.308",
5
+ "version": "5.34.0-staging.310",
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.34.0-staging.308",
7
+ "@muggleai/works@5.34.0-staging.310",
8
8
  "serve"
9
9
  ]
10
10
  }
@@ -15,7 +15,7 @@ For an older test case with no stored flag, pass `freshSession: true` when it ne
15
15
 
16
16
  ## Replay
17
17
 
18
- Replay runs as the script was recorded, never as the test case is now. Copy `pinnedAccount` and `freshSession` from the `actionParams` of the `muggle-remote-action-script-get` result onto `muggle-local-execute-replay` when present. A recording that carries neither may predate run identities, so decide its `freshSession` by the list above, as before.
18
+ A replay's account and session are the ones the script was recorded with, never the test case's current ones. Copy `pinnedAccount` and `freshSession` from the `actionParams` of the `muggle-remote-action-script-get` result onto `muggle-local-execute-replay` when present. A recording that carries neither may predate run identities, so decide its `freshSession` by the list above, as before.
19
19
 
20
20
  ## Changing the stored value
21
21