@testsprite/testsprite-cli 0.1.1 → 0.2.0

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.
@@ -1,6 +1,6 @@
1
1
  import { createWriteStream, readFileSync, readdirSync, statSync } from 'node:fs';
2
- import { stat } from 'node:fs/promises';
3
- import { dirname, extname, isAbsolute, join, resolve } from 'node:path';
2
+ import { rename, stat, unlink } from 'node:fs/promises';
3
+ import { basename, dirname, extname, isAbsolute, join, resolve } from 'node:path';
4
4
  import { randomUUID } from 'node:crypto';
5
5
  import { Command } from 'commander';
6
6
  import { emitDryRunBanner, makeHttpClient, } from '../lib/client-factory.js';
@@ -223,6 +223,7 @@ export async function runCreate(opts, deps = {}) {
223
223
  },
224
224
  });
225
225
  }
226
+ assertPythonCodeFile(opts.codeFile);
226
227
  if (!['frontend', 'backend'].includes(opts.type)) {
227
228
  throw localValidationError('type', 'must be one of: frontend, backend', [
228
229
  'frontend',
@@ -367,6 +368,12 @@ export async function runCreate(opts, deps = {}) {
367
368
  * — kept readable for debug-event captures.
368
369
  */
369
370
  const DRY_RUN_PLACEHOLDER_CODE = '// dry-run placeholder code body';
371
+ function assertPythonCodeFile(path) {
372
+ if (!path.toLowerCase().endsWith('.py')) {
373
+ throw localValidationError('code-file', 'must be a Python (.py) file — TestSprite runs all test code as Python ' +
374
+ '(frontend: Playwright for Python; backend: requests + pytest).');
375
+ }
376
+ }
370
377
  /**
371
378
  * Read the code body with a `stat`-first size guard so an oversize
372
379
  * artifact is rejected BEFORE we load + decode the whole thing into
@@ -920,6 +927,58 @@ const MAX_BATCH_BODY_BYTES = 5 * 1024 * 1024;
920
927
  * than this, the CLI splits into chunks and aggregates the results.
921
928
  */
922
929
  const MAX_BATCH_RERUN_IDS = 50;
930
+ /**
931
+ * Drop duplicate `testId` entries from a chunked batch-rerun's aggregated
932
+ * `accepted[]`, keeping the first occurrence. BE producer/teardown closure
933
+ * dedup happens per-request server-side, not across the separate requests
934
+ * one chunk per `MAX_BATCH_RERUN_IDS` window produces, so the same producer
935
+ * can come back accepted (with a different runId) from more than one
936
+ * chunk. Returns the deduped list plus how many entries were dropped, so
937
+ * the caller can warn the operator that a shared BE producer/teardown was
938
+ * triggered more than once.
939
+ */
940
+ function dedupeBatchRerunAccepted(entries) {
941
+ const seen = new Map();
942
+ let droppedCount = 0;
943
+ for (const entry of entries) {
944
+ if (seen.has(entry.testId)) {
945
+ droppedCount++;
946
+ continue;
947
+ }
948
+ seen.set(entry.testId, entry);
949
+ }
950
+ return { deduped: [...seen.values()], droppedCount };
951
+ }
952
+ /**
953
+ * Merge per-project closure summaries from multiple batch-rerun chunk
954
+ * responses, combining entries that share a `projectId` rather than
955
+ * leaving one entry per chunk. `testIds` / `addedProducers` /
956
+ * `addedTeardowns` are unioned (a producer present in two chunks' entries
957
+ * for the same project, the closure-dedup race this fixes, must not be
958
+ * counted twice); `clearedCaptured` is summed, each chunk's expansion is a
959
+ * disjoint operation so its count is additive.
960
+ */
961
+ function mergeBatchRerunClosureByProject(entries) {
962
+ const byProject = new Map();
963
+ for (const entry of entries) {
964
+ const existing = byProject.get(entry.projectId);
965
+ if (!existing) {
966
+ byProject.set(entry.projectId, {
967
+ projectId: entry.projectId,
968
+ testIds: [...new Set(entry.testIds)],
969
+ addedProducers: [...new Set(entry.addedProducers)],
970
+ addedTeardowns: [...new Set(entry.addedTeardowns)],
971
+ clearedCaptured: entry.clearedCaptured,
972
+ });
973
+ continue;
974
+ }
975
+ existing.testIds = [...new Set([...existing.testIds, ...entry.testIds])];
976
+ existing.addedProducers = [...new Set([...existing.addedProducers, ...entry.addedProducers])];
977
+ existing.addedTeardowns = [...new Set([...existing.addedTeardowns, ...entry.addedTeardowns])];
978
+ existing.clearedCaptured += entry.clearedCaptured;
979
+ }
980
+ return [...byProject.values()];
981
+ }
923
982
  /**
924
983
  * Default max in-flight run-triggers for `create-batch --run`.
925
984
  *
@@ -1796,42 +1855,31 @@ apiUrlForDashboard) {
1796
1855
  failureKind: finalRun.failureKind,
1797
1856
  };
1798
1857
  }
1799
- // Bounded concurrency fan-out using a semaphore pattern.
1800
- // We process testIds one slot at a time up to the concurrency limit.
1801
- // This avoids pulling in p-limit; the logic is simple enough inline.
1802
- const remaining = [...testIds];
1803
- const inFlight = new Set();
1804
- async function drainOne() {
1805
- const testId = remaining.shift();
1806
- if (testId === undefined)
1807
- return;
1808
- const p = triggerOne(testId).then(result => {
1809
- batchRunResults.push(result);
1810
- inFlight.delete(p);
1811
- return result;
1812
- });
1813
- inFlight.add(p);
1814
- await p;
1815
- }
1816
- // Fill up to concurrencyLimit slots, then drain one before adding
1817
- // each new testId so we never exceed the limit.
1818
- const initial = Math.min(concurrencyLimit, testIds.length);
1819
- const startPromises = [];
1820
- for (let i = 0; i < initial; i++) {
1821
- startPromises.push(drainOne());
1822
- }
1823
- // Process remaining items as slots free up.
1824
- while (remaining.length > 0) {
1825
- // Wait for any in-flight slot to free up.
1826
- if (inFlight.size > 0) {
1827
- await Promise.race(inFlight);
1828
- }
1829
- if (remaining.length > 0 && inFlight.size < concurrencyLimit) {
1830
- await drainOne();
1858
+ // Bounded concurrency fan-out: launch up to concurrencyLimit jobs, then
1859
+ // launch the next one as each finishes. Mirrors the startNext() pattern
1860
+ // used by the other fan-outs in this file (e.g. pollFreshAccepted below).
1861
+ let nextIdx = 0;
1862
+ let inFlight = 0;
1863
+ await new Promise((resolve, reject) => {
1864
+ function startNext() {
1865
+ while (inFlight < concurrencyLimit && nextIdx < testIds.length) {
1866
+ const testId = testIds[nextIdx++];
1867
+ inFlight++;
1868
+ triggerOne(testId)
1869
+ .then(result => {
1870
+ batchRunResults.push(result);
1871
+ inFlight--;
1872
+ startNext();
1873
+ if (inFlight === 0 && nextIdx >= testIds.length)
1874
+ resolve();
1875
+ })
1876
+ .catch(reject);
1877
+ }
1831
1878
  }
1832
- }
1833
- // Wait for all in-flight to finish.
1834
- await Promise.all([...inFlight, ...startPromises]);
1879
+ startNext();
1880
+ if (testIds.length === 0)
1881
+ resolve();
1882
+ });
1835
1883
  // Sort by testId order (same as input order for stable output).
1836
1884
  batchRunResults.sort((a, b) => testIds.indexOf(a.testId) - testIds.indexOf(b.testId));
1837
1885
  // Emit output.
@@ -2159,11 +2207,14 @@ export async function runGet(opts, deps = {}) {
2159
2207
  * directly; presigned URLs are dereferenced via the same fetch impl
2160
2208
  * (without API-key headers — the URL is the bearer of authority).
2161
2209
  *
2162
- * `--out <path>` redirects the same bytes into a file. We open the file
2163
- * before issuing the network request so a permission/dir error fails
2164
- * fast (exit 5 / VALIDATION_ERROR) without spending an API call. On
2165
- * any error after open we tear down the sink so we don't leak a
2166
- * half-written artifact.
2210
+ * `--out <path>` redirects the same bytes into a file. We validate the
2211
+ * path and open a sibling temp file before issuing the network request
2212
+ * so a permission/dir error fails fast (exit 5 / VALIDATION_ERROR)
2213
+ * without spending an API call. The temp file is renamed onto the real
2214
+ * `--out` path only after a successful, complete write; on any error
2215
+ * (or the "no code generated yet" branch, which writes nothing) the
2216
+ * temp file is discarded and the user's pre-existing `--out` file, if
2217
+ * any, is left untouched.
2167
2218
  */
2168
2219
  export async function runCodeGet(opts, deps = {}) {
2169
2220
  // Dry-run: no fetch, no fs. Print the canned shape to stdout and, if
@@ -2193,8 +2244,10 @@ export async function runCodeGet(opts, deps = {}) {
2193
2244
  const client = makeClient(opts, deps);
2194
2245
  try {
2195
2246
  const code = await client.get(`/tests/${encodeURIComponent(opts.testId)}/code`);
2247
+ let wroteContent = false;
2196
2248
  if (opts.output === 'json') {
2197
2249
  out.print(code);
2250
+ wroteContent = true;
2198
2251
  }
2199
2252
  else if (isPresignedCodeUrl(code.code)) {
2200
2253
  // Text mode: dump the source body. JSON consumers want the wire
@@ -2206,28 +2259,37 @@ export async function runCodeGet(opts, deps = {}) {
2206
2259
  // or a piped `gzip`) pauses the upstream reader rather than
2207
2260
  // letting chunks accumulate in V8's heap.
2208
2261
  await streamPresignedBody(code.code, out, deps);
2262
+ wroteContent = true;
2209
2263
  }
2210
2264
  else if (code.code === '' || code.code === null) {
2211
2265
  // P2-10: draft test with no code yet — empty body would produce
2212
2266
  // silent empty stdout. Print a friendly hint to stderr instead so
2213
- // the operator knows what happened, and keep exit 0.
2267
+ // the operator knows what happened, and keep exit 0. Nothing was
2268
+ // written, so the temp file is discarded below without touching
2269
+ // a pre-existing `--out` file.
2214
2270
  const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
2215
2271
  stderrFn('(no code generated yet — run the test first)');
2216
2272
  }
2217
2273
  else {
2218
2274
  await out.writeChunk(code.code);
2275
+ wroteContent = true;
2219
2276
  }
2220
2277
  if (fileSink)
2221
- await closeOutputFile(fileSink);
2278
+ await closeOutputFile(fileSink, wroteContent);
2222
2279
  return code;
2223
2280
  }
2224
2281
  catch (err) {
2225
2282
  if (fileSink)
2226
- await closeOutputFile(fileSink).catch(() => undefined);
2283
+ await closeOutputFile(fileSink, false).catch(() => undefined);
2227
2284
  throw err;
2228
2285
  }
2229
2286
  }
2230
- const CODE_PUT_LANGUAGES = ['typescript', 'javascript', 'python'];
2287
+ // Only `python` is accepted as a `--language` INPUT: TestSprite executes
2288
+ // stored test code as Python (FE Playwright `playwright.async_api`, BE
2289
+ // `requests`/pytest), so accepting `typescript`/`javascript` would be a
2290
+ // false promise. The read-side `CliTestCode['language']` union keeps ts/js
2291
+ // for wire fidelity with legacy rows the server may still return.
2292
+ const CODE_PUT_LANGUAGES = ['python'];
2231
2293
  /**
2232
2294
  * `test code put <test-id> --code-file <path>` — M3.2 piece-4.
2233
2295
  *
@@ -2269,6 +2331,7 @@ export async function runCodePut(opts, deps = {}) {
2269
2331
  assertIdempotencyKey(opts.idempotencyKey);
2270
2332
  requireNonEmpty('test-id', opts.testId);
2271
2333
  requireNonEmpty('code-file', opts.codeFile);
2334
+ assertPythonCodeFile(opts.codeFile);
2272
2335
  if (opts.expectedVersion !== undefined && opts.force === true) {
2273
2336
  throw localValidationError('expected-version', 'is mutually exclusive with --force; pass one or the other (or neither for auto-fetch)');
2274
2337
  }
@@ -2759,11 +2822,15 @@ export async function runFailureSummary(opts, deps = {}) {
2759
2822
  export async function runFailureGet(opts, deps = {}) {
2760
2823
  const out = makeOutput(opts.output, deps);
2761
2824
  const client = makeClient(opts, deps);
2762
- // We resolve the output dir BEFORE the network call so a missing /
2825
+ // Resolve and validate --out BEFORE the network call so a missing /
2763
2826
  // empty path surfaces as VALIDATION_ERROR (exit 5) without spending
2764
- // an API call. `writeBundle` re-validates internally; this is the
2765
- // fast-fail.
2766
- const requestedDir = opts.out;
2827
+ // an API call. Mirrors `runArtifactGet`; `writeBundle` re-validates
2828
+ // internally as defense-in-depth.
2829
+ let resolvedDir;
2830
+ if (opts.out !== undefined) {
2831
+ resolvedDir = resolveBundleDir(opts.out);
2832
+ await assertOutDirParentExists(resolvedDir);
2833
+ }
2767
2834
  const context = await client.get(`/tests/${encodeURIComponent(opts.testId)}/failure`);
2768
2835
  // Run the §3 atomicity invariants on every path — even when --out is
2769
2836
  // absent. An agent piping the JSON envelope into a vision-LLM
@@ -2771,7 +2838,7 @@ export async function runFailureGet(opts, deps = {}) {
2771
2838
  // guarantees never reaches it. The bundle writer re-runs the check
2772
2839
  // internally; this call is the cheap upfront trap.
2773
2840
  assertContextIntegrity(context, 'local');
2774
- if (requestedDir !== undefined) {
2841
+ if (resolvedDir !== undefined) {
2775
2842
  // Dry-run: do NOT call writeBundle (which would mkdir, fetch
2776
2843
  // presigned URLs, and write files). Print the would-be bundle layout
2777
2844
  // to stderr and emit the wire envelope to stdout so the agent sees
@@ -2779,23 +2846,23 @@ export async function runFailureGet(opts, deps = {}) {
2779
2846
  if (opts.dryRun) {
2780
2847
  const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
2781
2848
  const fileNames = plannedBundleFiles(context, opts.failedOnly);
2782
- stderr(`[dry-run] would write bundle to ${requestedDir} (${fileNames.length} files; meta.json renames last)`);
2849
+ stderr(`[dry-run] would write bundle to ${resolvedDir} (${fileNames.length} files; meta.json renames last)`);
2783
2850
  for (const f of fileNames)
2784
2851
  stderr(`[dry-run] ${f}`);
2785
2852
  if (opts.output === 'json') {
2786
- out.print({ ok: true, dir: requestedDir, dryRun: true, context });
2853
+ out.print({ ok: true, dir: resolvedDir, dryRun: true, context });
2787
2854
  }
2788
2855
  else {
2789
2856
  // Use a dry-run-specific renderer: the real success renderer
2790
2857
  // says "Bundle written to ..." which would be a lie here. Stdout
2791
2858
  // is the success contract automation may parse, so it must not
2792
2859
  // imply the bundle was created.
2793
- out.print({ dir: requestedDir, files: fileNames.length, snapshotId: context.snapshotId }, data => renderBundleDryRunText(data));
2860
+ out.print({ dir: resolvedDir, files: fileNames.length, snapshotId: context.snapshotId }, data => renderBundleDryRunText(data));
2794
2861
  }
2795
2862
  return { context };
2796
2863
  }
2797
2864
  const bundle = await writeBundle(context, {
2798
- dir: requestedDir,
2865
+ dir: resolvedDir,
2799
2866
  failedOnly: opts.failedOnly,
2800
2867
  fetchImpl: deps.fetchImpl,
2801
2868
  });
@@ -2864,7 +2931,12 @@ function isTerminalPublicStatus(status) {
2864
2931
  * round-2: don't fabricate blank correlation fields).
2865
2932
  */
2866
2933
  function backendResultToRunResponse(result, run) {
2867
- const total = result.summary.passed + result.summary.failed + result.summary.skipped;
2934
+ // `result.summary` is now a semantic string, not a count object.
2935
+ // Reconstruct the synthetic 1-test stepSummary from the verdict (byte-identical
2936
+ // to the prior status-derived counts: passed→1/0, failed→0/1, else→0/0).
2937
+ const passedCount = result.status === 'passed' ? 1 : 0;
2938
+ const failedCount = result.status === 'failed' ? 1 : 0;
2939
+ const total = passedCount + failedCount;
2868
2940
  return {
2869
2941
  ...run,
2870
2942
  status: result.status,
@@ -2882,9 +2954,9 @@ function backendResultToRunResponse(result, run) {
2882
2954
  videoUrl: result.videoUrl,
2883
2955
  stepSummary: {
2884
2956
  total,
2885
- completed: result.summary.passed + result.summary.failed,
2886
- passedCount: result.summary.passed,
2887
- failedCount: result.summary.failed,
2957
+ completed: total,
2958
+ passedCount,
2959
+ failedCount,
2888
2960
  },
2889
2961
  };
2890
2962
  }
@@ -3485,6 +3557,9 @@ export async function runTestRunAll(opts, deps = {}) {
3485
3557
  const out = makeOutput(opts.output, deps);
3486
3558
  // --- Dry-run path ---
3487
3559
  if (opts.dryRun) {
3560
+ // DEV-247: this path returns before makeClient() fires the banner, so emit it
3561
+ // here — otherwise the canned sample can be mistaken for a live response.
3562
+ emitDryRunBanner(stderrFn);
3488
3563
  const idempotencyKey = opts.idempotencyKey ?? `dry-run-${randomUUID()}`;
3489
3564
  const batchRunSample = findSample('POST', '/api/cli/v1/tests/batch/run')?.body();
3490
3565
  const envelope = {
@@ -4430,15 +4505,25 @@ export async function runTestRerun(opts, deps = {}) {
4430
4505
  chunks.push([]); // defensive: empty list handled above
4431
4506
  let chunkResponses;
4432
4507
  try {
4433
- chunkResponses = await Promise.all(chunks.map((chunk, idx) => {
4508
+ // Dispatch chunks one at a time, NOT via Promise.all. BE producer/
4509
+ // teardown closure dedup happens per-request, server-side. Two chunks
4510
+ // that share a project's producer fired concurrently can each decide
4511
+ // independently "this producer hasn't been added yet" and both trigger
4512
+ // it, double-running the producer. Sequential dispatch closes that
4513
+ // race: by the time chunk N is sent, chunk N-1's trigger has already
4514
+ // landed server-side for it to dedup against.
4515
+ chunkResponses = [];
4516
+ for (let idx = 0; idx < chunks.length; idx++) {
4517
+ const chunk = chunks[idx];
4434
4518
  const chunkKey = chunks.length === 1 ? idempotencyKey : `${idempotencyKey}:chunk${idx}`;
4435
- return client.triggerBatchRerun({
4519
+ const chunkResp = await client.triggerBatchRerun({
4436
4520
  source: 'cli',
4437
4521
  testIds: chunk,
4438
4522
  ...(effectiveAutoHeal ? { autoHeal: true } : {}),
4439
4523
  ...(opts.skipDependencies ? { skipDependencies: true } : {}),
4440
4524
  }, { idempotencyKey: chunkKey });
4441
- }));
4525
+ chunkResponses.push(chunkResp);
4526
+ }
4442
4527
  }
4443
4528
  catch (err) {
4444
4529
  // D2 (dogfood): the batch endpoint rejects the WHOLE request when any id is
@@ -4461,12 +4546,21 @@ export async function runTestRerun(opts, deps = {}) {
4461
4546
  throw err;
4462
4547
  }
4463
4548
  // Aggregate chunk responses into a single synthetic BatchRerunResponse.
4549
+ // `accepted` is deduped by testId (defense in depth: even with sequential
4550
+ // dispatch above, a shared producer/teardown should never be reported, or
4551
+ // polled under --wait, more than once) and `closure.byProject` entries
4552
+ // sharing a projectId are merged rather than left as separate per-chunk
4553
+ // entries.
4554
+ const { deduped: dedupedAccepted, droppedCount: duplicateAcceptedCount } = dedupeBatchRerunAccepted(chunkResponses.flatMap(r => r.accepted));
4555
+ if (duplicateAcceptedCount > 0) {
4556
+ stderrFn(`[warn] ${duplicateAcceptedCount} test${duplicateAcceptedCount !== 1 ? 's were' : ' was'} triggered more than once across chunked batch-rerun requests (shared BE producer/teardown); kept the first run, ignored the rest.`);
4557
+ }
4464
4558
  const batchResp = {
4465
- accepted: chunkResponses.flatMap(r => r.accepted),
4559
+ accepted: dedupedAccepted,
4466
4560
  deferred: chunkResponses.flatMap(r => r.deferred),
4467
4561
  conflicts: chunkResponses.flatMap(r => r.conflicts),
4468
4562
  closure: {
4469
- byProject: chunkResponses.flatMap(r => r.closure.byProject),
4563
+ byProject: mergeBatchRerunClosureByProject(chunkResponses.flatMap(r => r.closure.byProject)),
4470
4564
  },
4471
4565
  notFound: chunkResponses.flatMap(r => r.notFound ?? []),
4472
4566
  };
@@ -4545,7 +4639,12 @@ export async function runTestRerun(opts, deps = {}) {
4545
4639
  }
4546
4640
  let retryChunkResponses;
4547
4641
  try {
4548
- retryChunkResponses = await Promise.all(retryChunks.map((chunk, idx) => {
4642
+ // Sequential, same reason as the initial dispatch above: concurrent
4643
+ // chunks racing on per-request server-side closure dedup can
4644
+ // double-trigger a shared BE producer/teardown.
4645
+ retryChunkResponses = [];
4646
+ for (let idx = 0; idx < retryChunks.length; idx++) {
4647
+ const chunk = retryChunks[idx];
4549
4648
  // [P2] Bound the derived key to ≤256 chars. Caller-supplied keys may
4550
4649
  // be up to 256 chars; appending the suffix could exceed the server
4551
4650
  // limit and cause every retry to be rejected. Truncate the base key
@@ -4557,19 +4656,20 @@ export async function runTestRerun(opts, deps = {}) {
4557
4656
  ? idempotencyKey.slice(0, 256 - retrySuffix.length)
4558
4657
  : idempotencyKey;
4559
4658
  const retryKey = `${retryBase}${retrySuffix}`;
4560
- return client.triggerBatchRerun({
4659
+ const retryChunkResp = await client.triggerBatchRerun({
4561
4660
  source: 'cli',
4562
4661
  testIds: chunk,
4563
4662
  ...(effectiveAutoHeal ? { autoHeal: true } : {}),
4564
4663
  ...(opts.skipDependencies ? { skipDependencies: true } : {}),
4565
4664
  }, { idempotencyKey: retryKey });
4566
- }));
4665
+ retryChunkResponses.push(retryChunkResp);
4666
+ }
4567
4667
  }
4568
4668
  catch (err) {
4569
4669
  stderrFn(`[deferred-retry] attempt ${attempt} failed with error: ${err instanceof Error ? err.message : String(err)}`);
4570
4670
  break;
4571
4671
  }
4572
- const newlyAccepted = retryChunkResponses.flatMap(r => r.accepted);
4672
+ const { deduped: newlyAccepted, droppedCount: newlyDuplicateCount } = dedupeBatchRerunAccepted(retryChunkResponses.flatMap(r => r.accepted));
4573
4673
  const newlyDeferred = retryChunkResponses.flatMap(r => r.deferred);
4574
4674
  const newlyConflicted = retryChunkResponses.flatMap(r => r.conflicts);
4575
4675
  // [P2] Collect notFound[] from the retry response. A deferred test may be
@@ -4577,9 +4677,12 @@ export async function runTestRerun(opts, deps = {}) {
4577
4677
  // into the running notFound set and remove from deferred so it isn't
4578
4678
  // reported as "resolved" in the final output.
4579
4679
  const newlyNotFound = retryChunkResponses.flatMap(r => r.notFound ?? []);
4680
+ if (newlyDuplicateCount > 0) {
4681
+ stderrFn(`[warn] ${newlyDuplicateCount} test${newlyDuplicateCount !== 1 ? 's were' : ' was'} triggered more than once across deferred-retry chunked requests (shared BE producer/teardown); kept the first run, ignored the rest.`);
4682
+ }
4580
4683
  if (newlyAccepted.length > 0) {
4581
4684
  stderrFn(`[deferred-retry] attempt ${attempt}: ${newlyAccepted.length} test${newlyAccepted.length !== 1 ? 's' : ''} now accepted.`);
4582
- accepted = accepted.concat(newlyAccepted);
4685
+ accepted = dedupeBatchRerunAccepted(accepted.concat(newlyAccepted)).deduped;
4583
4686
  }
4584
4687
  if (newlyConflicted.length > 0) {
4585
4688
  // [P1] Merge retry-returned conflicts into the running conflicts collection
@@ -5544,13 +5647,16 @@ function makeOutput(mode, deps) {
5544
5647
  });
5545
5648
  }
5546
5649
  /**
5547
- * Open the `--out` target before any network I/O so a permission/dir
5548
- * error fails fast. Synchronous open via `createWriteStream` doesn't
5549
- * actually open the descriptor until first write, so we don't surface
5550
- * EACCES/ENOENT here — instead the stream emits `'error'`, which we
5551
- * remember on the sink and re-throw at close time. The benefit of
5552
- * opening early is still real: invalid path strings (empty, `/dev/null`
5553
- * on a sandboxed fs, etc.) are caught before the API request goes out.
5650
+ * Open a temp file next to the `--out` target before any network I/O so
5651
+ * a permission/dir error fails fast. Synchronous open via
5652
+ * `createWriteStream` doesn't actually open the descriptor until first
5653
+ * write, so we don't surface EACCES/ENOENT here, instead the stream
5654
+ * emits `'error'`, which we remember on the sink and re-throw at close
5655
+ * time. The benefit of opening early is still real: invalid path
5656
+ * strings (empty, `/dev/null` on a sandboxed fs, etc.) are caught
5657
+ * before the API request goes out. Writing to a temp path rather than
5658
+ * `resolved` directly means the real `--out` file is never truncated
5659
+ * up front, see `closeOutputFile` for the commit step.
5554
5660
  */
5555
5661
  function openOutputFile(rawPath) {
5556
5662
  if (typeof rawPath !== 'string' || rawPath.length === 0) {
@@ -5580,8 +5686,9 @@ function openOutputFile(rawPath) {
5580
5686
  if (!parentStat.isDirectory()) {
5581
5687
  throw localValidationError('out', `parent path is not a directory: ${parent}`);
5582
5688
  }
5583
- const stream = createWriteStream(resolved, { encoding: 'utf8' });
5584
- const sink = { stream, path: resolved, error: null };
5689
+ const tmpPath = join(parent, `.${basename(resolved)}.tmp-${randomUUID()}`);
5690
+ const stream = createWriteStream(tmpPath, { encoding: 'utf8' });
5691
+ const sink = { stream, path: resolved, tmpPath, error: null };
5585
5692
  stream.on('error', err => {
5586
5693
  sink.error = err instanceof Error ? err : new Error(String(err));
5587
5694
  });
@@ -5611,25 +5718,37 @@ function makeFileOutput(mode, sink) {
5611
5718
  });
5612
5719
  }
5613
5720
  /**
5614
- * Flush + close the file sink. Called on the success path after the
5615
- * last write and on the error path inside a `.catch(() => undefined)`
5616
- * so the original error isn't masked by a teardown failure.
5721
+ * Flush + close the file sink, then either commit or discard the temp
5722
+ * file. Called on the success path after the last write (`commit:
5723
+ * true` when content was actually written) and on the error / "no code
5724
+ * yet" paths (`commit: false`) inside a `.catch(() => undefined)` so a
5725
+ * teardown failure doesn't mask the original error.
5726
+ *
5727
+ * `commit: true` renames `tmpPath` onto the real `--out` path, the
5728
+ * only point at which the operator's file is touched. `commit: false`
5729
+ * discards the temp file and leaves any pre-existing `--out` file
5730
+ * exactly as it was, this is what prevents a failed/empty response
5731
+ * from silently truncating the operator's filesystem (mirrors the
5732
+ * atomic-rename contract `bundle.ts` uses for multi-file bundles).
5617
5733
  *
5618
5734
  * Re-raises any async stream error captured by the `'error'` listener.
5619
5735
  * Without this re-raise, an EACCES on first write would leave a
5620
- * zero-byte file behind and exit 0 — a false-success surface that is
5621
- * exactly the failure mode `--out` exists to avoid.
5736
+ * zero-byte temp file behind and exit 0, a false-success surface that
5737
+ * is exactly the failure mode `--out` exists to avoid.
5622
5738
  */
5623
- function closeOutputFile(sink) {
5624
- return new Promise((resolve, reject) => {
5625
- sink.stream.end(() => {
5626
- if (sink.error) {
5627
- reject(new TransportError(`Failed to write --out ${sink.path}: ${sink.error.message}`));
5628
- return;
5629
- }
5630
- resolve();
5631
- });
5739
+ async function closeOutputFile(sink, commit) {
5740
+ await new Promise(resolveStream => {
5741
+ sink.stream.end(() => resolveStream());
5632
5742
  });
5743
+ if (sink.error) {
5744
+ await unlink(sink.tmpPath).catch(() => undefined);
5745
+ throw new TransportError(`Failed to write --out ${sink.path}: ${sink.error.message}`);
5746
+ }
5747
+ if (!commit) {
5748
+ await unlink(sink.tmpPath).catch(() => undefined);
5749
+ return;
5750
+ }
5751
+ await rename(sink.tmpPath, sink.path);
5633
5752
  }
5634
5753
  /** A presigned `code` body is any `https://` URL — never anything else. */
5635
5754
  export function isPresignedCodeUrl(code) {
@@ -5988,7 +6107,10 @@ function renderResultText(r) {
5988
6107
  // when the run failed; passing/running runs render in chronological
5989
6108
  // order so a glance reads like a timeline.
5990
6109
  const lines = [];
5991
- lines.push(`status: ${r.status}`);
6110
+ // surface verdict (outcome) and executionStatus (lifecycle) instead
6111
+ // of the legacy conflated `status` (still present on the JSON wire shape).
6112
+ lines.push(`verdict: ${r.verdict ?? '— (no verdict yet)'}`);
6113
+ lines.push(`executionStatus: ${r.executionStatus}`);
5992
6114
  lines.push(`testId: ${r.testId}`);
5993
6115
  if (r.failureKind !== null)
5994
6116
  lines.push(`failureKind: ${r.failureKind}`);
@@ -6005,7 +6127,7 @@ function renderResultText(r) {
6005
6127
  lines.push(`codeVersion: ${r.codeVersion}`);
6006
6128
  if (r.targetUrl !== null)
6007
6129
  lines.push(`targetUrl: ${r.targetUrl}`);
6008
- lines.push(`summary: passed=${r.summary.passed} failed=${r.summary.failed} skipped=${r.summary.skipped}`);
6130
+ lines.push(`summary: ${r.summary}`);
6009
6131
  if (r.videoUrl !== null)
6010
6132
  lines.push(`videoUrl: ${r.videoUrl}`);
6011
6133
  if (r.failureAnalysisUrl !== null)
@@ -6099,7 +6221,7 @@ function createTestCodeCommand(deps) {
6099
6221
  .option('--code-file <path>', 'file containing the new test code (≤ 350 KB)')
6100
6222
  .option('--expected-version <v>', 'expected current codeVersion (e.g. v3); sent as `If-Match`. Mutually exclusive with --force.')
6101
6223
  .option('--force', 'send `If-Match: *` to skip the etag check (audit-logged with force: true). Mutually exclusive with --expected-version.', false)
6102
- .option('--language <lang>', 'override the stored language (typescript|javascript|python). Defaults to the existing language.')
6224
+ .option('--language <lang>', 'set the stored code language; only "python" is supported (TestSprite executes test code as Python). Defaults to the existing language.')
6103
6225
  .option('--idempotency-key <token>', 'opaque idempotency token (1-256 ASCII chars). Defaults to a UUIDv4 minted per invocation; pin one yourself for safe retries.')
6104
6226
  .option('--dry-run-simulate-error <code>', 'With --dry-run: synthesise an error envelope to preview the error path. Supported: PRECONDITION_FAILED (412).')
6105
6227
  .addHelpText('after', '\nDry-run note: --dry-run always returns the happy response shape.\n' +
@@ -6156,7 +6278,11 @@ function createTestPlanCommand(deps) {
6156
6278
  export function createTestArtifactCommand(deps) {
6157
6279
  const artifact = new Command('artifact').description('Download run-scoped artifact bundles (M3.3 piece-4)');
6158
6280
  artifact
6159
- .command('get <run-id>')
6281
+ // `isDefault: true` makes `test artifact <run-id>` a pass-through alias for
6282
+ // `test artifact get <run-id>` (DEV-230 grammar consistency — bare-noun reads
6283
+ // mirror the flat `test result/steps/get <id>` forms). Run-id semantics are
6284
+ // preserved: the positional is still a run-id, not a test-id.
6285
+ .command('get <run-id>', { isDefault: true })
6160
6286
  .description([
6161
6287
  'Download the §7 failure-context bundle for a specific run.',
6162
6288
  '',
@@ -6189,7 +6315,10 @@ export function createTestArtifactCommand(deps) {
6189
6315
  function createTestFailureCommand(deps) {
6190
6316
  const failure = new Command('failure').description('Export the latest-failure agent bundle');
6191
6317
  failure
6192
- .command('get <test-id>')
6318
+ // `isDefault: true` makes `test failure <test-id>` a pass-through alias for
6319
+ // `test failure get <test-id>` (DEV-230 grammar consistency). `failure summary`
6320
+ // still routes explicitly; only the bare-noun form falls through to `get`.
6321
+ .command('get <test-id>', { isDefault: true })
6193
6322
  .description("Write a self-contained failure-context bundle for a test's latest failing run")
6194
6323
  .option('--out <dir>', 'Directory to write the §7 disk layout into (default: print wire envelope to stdout)')
6195
6324
  .option('--failed-only', 'Keep only the failed step plus its immediate neighbors (±1)')