@testsprite/testsprite-cli 0.4.0 → 0.6.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.
Files changed (56) hide show
  1. package/README.md +27 -1
  2. package/dist/commands/agent.js +17 -6
  3. package/dist/commands/auth.d.ts +46 -0
  4. package/dist/commands/auth.js +37 -2
  5. package/dist/commands/completion.d.ts +36 -0
  6. package/dist/commands/completion.js +111 -0
  7. package/dist/commands/doctor.js +20 -2
  8. package/dist/commands/init.d.ts +32 -1
  9. package/dist/commands/init.js +40 -10
  10. package/dist/commands/project.d.ts +77 -3
  11. package/dist/commands/project.js +176 -43
  12. package/dist/commands/test.d.ts +200 -10
  13. package/dist/commands/test.js +1636 -351
  14. package/dist/commands/usage.d.ts +56 -17
  15. package/dist/commands/usage.js +144 -29
  16. package/dist/index.js +132 -26
  17. package/dist/lib/browser.d.ts +6 -0
  18. package/dist/lib/browser.js +54 -0
  19. package/dist/lib/bundle.d.ts +32 -31
  20. package/dist/lib/bundle.js +125 -83
  21. package/dist/lib/client-factory.d.ts +23 -0
  22. package/dist/lib/client-factory.js +33 -1
  23. package/dist/lib/config.js +7 -3
  24. package/dist/lib/credentials.d.ts +17 -1
  25. package/dist/lib/credentials.js +175 -16
  26. package/dist/lib/dry-run/samples.js +15 -1
  27. package/dist/lib/errors.d.ts +6 -1
  28. package/dist/lib/errors.js +70 -19
  29. package/dist/lib/flaky.d.ts +12 -1
  30. package/dist/lib/flaky.js +7 -12
  31. package/dist/lib/gh-output.d.ts +84 -0
  32. package/dist/lib/gh-output.js +202 -0
  33. package/dist/lib/http.d.ts +33 -15
  34. package/dist/lib/http.js +141 -7
  35. package/dist/lib/org-render.d.ts +52 -0
  36. package/dist/lib/org-render.js +59 -0
  37. package/dist/lib/poll.js +72 -36
  38. package/dist/lib/render-error.d.ts +14 -0
  39. package/dist/lib/render-error.js +30 -0
  40. package/dist/lib/response-schemas.d.ts +83 -0
  41. package/dist/lib/response-schemas.js +282 -0
  42. package/dist/lib/runs.types.d.ts +53 -8
  43. package/dist/lib/skill-nudge.d.ts +17 -0
  44. package/dist/lib/skill-nudge.js +19 -0
  45. package/dist/lib/telemetry.d.ts +90 -0
  46. package/dist/lib/telemetry.js +171 -0
  47. package/dist/lib/text-table.d.ts +14 -0
  48. package/dist/lib/text-table.js +45 -0
  49. package/dist/lib/v3-advisory.d.ts +30 -1
  50. package/dist/lib/v3-advisory.js +35 -4
  51. package/dist/version.d.ts +1 -1
  52. package/dist/version.js +1 -1
  53. package/package.json +17 -5
  54. package/schemas/plan.schema.json +61 -0
  55. package/skills/testsprite-verify.codex.md +2 -2
  56. package/skills/testsprite-verify.skill.md +3 -3
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Cross-platform "open this URL in the default browser" helper for
3
+ * `test open` (issue #121). Spawns the platform opener with an argv array
4
+ * (never a shell string) so a URL can never be shell-injected, and refuses
5
+ * anything that is not http(s) before any process is spawned.
6
+ *
7
+ * Platform openers:
8
+ * darwin open <url>
9
+ * win32 rundll32 url.dll,FileProtocolHandler <url> (avoids `cmd /c start`,
10
+ * whose re-parsing would mangle `&` and other metachars in the URL)
11
+ * other xdg-open <url>
12
+ *
13
+ * The child is detached and unref'd so the CLI exits immediately; failures
14
+ * are the caller's to surface (it already printed the URL as the fallback).
15
+ */
16
+ import { spawn } from 'node:child_process';
17
+ import { localValidationError } from './errors.js';
18
+ export function openInBrowser(url, deps = {}) {
19
+ let parsed;
20
+ try {
21
+ parsed = new URL(url);
22
+ }
23
+ catch {
24
+ throw localValidationError('url', 'must be a valid http(s) URL', undefined, 'field');
25
+ }
26
+ if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
27
+ // User-input error, not an internal failure: classify as VALIDATION_ERROR
28
+ // so it maps to exit 5 (like every other bad-argument path), not exit 1.
29
+ throw localValidationError('url', `must be an http(s) URL (got ${parsed.protocol})`, undefined, 'field');
30
+ }
31
+ const platform = deps.platform ?? process.platform;
32
+ const exec = deps.exec ??
33
+ ((command, args) => {
34
+ const child = spawn(command, [...args], { detached: true, stdio: 'ignore' });
35
+ // spawn() reports a missing binary (ENOENT) ASYNCHRONOUSLY on the child,
36
+ // so the caller's try/catch cannot see it — and an unhandled 'error'
37
+ // event would crash the whole CLI. The URL is already on stdout, so
38
+ // degrade to the same manual-open hint the sync failure path prints.
39
+ child.on('error', () => {
40
+ process.stderr.write('could not launch a browser; open the URL above manually (or use --no-browser)\n');
41
+ });
42
+ child.unref();
43
+ });
44
+ if (platform === 'darwin') {
45
+ exec('open', [url]);
46
+ return;
47
+ }
48
+ if (platform === 'win32') {
49
+ exec('rundll32', ['url.dll,FileProtocolHandler', url]);
50
+ return;
51
+ }
52
+ exec('xdg-open', [url]);
53
+ }
54
+ //# sourceMappingURL=browser.js.map
@@ -137,6 +137,15 @@ export declare function resolveBundleDir(rawPath: string): string;
137
137
  * language, not the user-app code under test.
138
138
  */
139
139
  export declare function pickCodeExtension(language: string, framework: string): string;
140
+ /**
141
+ * Pick the on-disk extension for `<dir>/video.<ext>` from the actual
142
+ * `result.videoUrl`, instead of hardcoding `mp4` (the
143
+ * recording is sometimes a `.webm` container; saving it under a `video.mp4`
144
+ * name misleads strict-extension consumers). Falls back to `mp4` when the
145
+ * URL is malformed or its extension isn't a recognized container, so a
146
+ * response-controlled field can never smuggle an arbitrary suffix onto disk.
147
+ */
148
+ export declare function pickVideoExtension(url: string): string;
140
149
  /**
141
150
  * Step filename per §7.2 — 1-based index, zero-padded to two digits
142
151
  * for indices ≤ 99, three digits for ≥ 100. `${stepIndex}-snapshot.html`
@@ -163,8 +172,9 @@ export declare function buildMeta(ctx: CliFailureContext, fetchedAt?: Date): Bun
163
172
  * 2. `applyFailedOnly` — narrow before download (saves bytes).
164
173
  * 3. `mkdir <dir>/.tmp/` — fresh; clean any stale temp.
165
174
  * 4. `writeFile result.json / failure.json / code.<ext>` — local data.
166
- * 5. `fetch + stream` for `video.mp4` (when set) and per-step
167
- * snapshot/screenshot/evidence-json files.
175
+ * 5. `fetch + stream` for `video.<ext>` (when set; extension matches the
176
+ * actual recording container) and per-step snapshot/screenshot/
177
+ * evidence-json files.
168
178
  * 6. `writeFile meta.json` LAST — its presence means "bundle complete".
169
179
  * 7. `rename .tmp/<file> -> <file>` for every file. Last rename
170
180
  * makes meta.json visible.
@@ -174,40 +184,31 @@ export declare function buildMeta(ctx: CliFailureContext, fetchedAt?: Date): Bun
174
184
  * → 10 by default; the original ApiError is preserved when applicable).
175
185
  */
176
186
  export declare function writeBundle(ctx: CliFailureContext, options: WriteBundleOptions): Promise<WriteBundleResult>;
177
- /**
178
- * Rename `<tmp>/<file>` → `<dir>/<file>` for every file in `files`.
179
- *
180
- * Critical ordering for atomicity (the §3 "agent-safe" contract):
181
- *
182
- * 1. **Remove the OLD `meta.json` first.** The bundle's completion
183
- * signal is `meta.json`'s presence; an agent reading `<dir>` while
184
- * we're mutating it must see "no meta → bundle absent or
185
- * mid-write" rather than "meta points at a snapshot that's already
186
- * been partially overwritten." Removing the old meta is what
187
- * makes the rest of the swap safe to do in place.
188
- * 2. Wipe stale top-level files (e.g. an old `video.mp4` when the new
189
- * bundle has no video). Without this, a fresh bundle could ship
190
- * with a stale video lingering at the top level.
191
- * 3. Replace `<dir>/steps/` wholesale.
192
- * 4. Rename top-level files into place.
193
- * 5. **Rename `meta.json` LAST.** Its visible presence is the atomic
194
- * completion signal; until step 5 lands, agents see "incomplete."
195
- *
196
- * The window between (1) and (5) is bounded by a handful of `rename`
197
- * syscalls — small enough that a SIGKILL there is rare, and any agent
198
- * caught reading the dir during it sees no meta and refuses to consume
199
- * (per §7.3). That's what we want.
200
- */
201
187
  /**
202
188
  * Whether a top-level directory entry belongs to the bundle format —
203
189
  * i.e. something a prior `writeBundle` could have produced and this
204
- * commit is therefore allowed to clean up. `code.<ext>` is matched by
205
- * pattern (not the current run's extension) so a stale `code.py` is
206
- * still swept when the new bundle writes `code.ts`. Everything else in
207
- * the directory is the user's and must never be deleted (`--out` can
208
- * point at a pre-existing, populated directory).
190
+ * commit is therefore allowed to clean up. `code.<ext>` and `video.<ext>`
191
+ * are matched by pattern (not the current run's extension) so a stale
192
+ * `code.py` or `video.webm` is still swept when the new bundle writes
193
+ * `code.ts` / `video.mp4` (or no video at all). Everything else in the
194
+ * directory is the user's and must never be deleted (`--out` can point at
195
+ * a pre-existing, populated directory).
209
196
  */
210
197
  export declare function isBundleOwnedEntry(entry: string): boolean;
198
+ /**
199
+ * Atomically install the complete bundle staged in `tmpDir` into `dir`.
200
+ *
201
+ * Compatible with the #162 data-loss guard: only `isBundleOwnedEntry`
202
+ * names are moved aside or replaced — foreign files in `--out` survive.
203
+ *
204
+ * Re-commit safety: bundle-owned entries are renamed to a sibling
205
+ * aside directory before the new artifacts land. The prior `meta.json`
206
+ * is moved aside first (§3/§7.3 — no meta ⇒ refuse to consume) so a
207
+ * concurrent reader never sees meta pointing at steps already gone.
208
+ * The new `meta.json` is installed last. On failure, aside entries are
209
+ * restored so a failed re-commit never leaves the directory unusable.
210
+ */
211
+ export declare function commitBundle(tmpDir: string, dir: string, files: ReadonlyArray<string>): Promise<void>;
211
212
  /**
212
213
  * Stream a presigned URL into a file with bounded retry on transport
213
214
  * failures. 4xx (presigned URL expired or unauthorized) is NOT
@@ -32,10 +32,11 @@
32
32
  * - Resume after a partial bundle. M2 always re-fetches from scratch
33
33
  * when the agent re-runs. M3 may add resume.
34
34
  */
35
+ import { randomUUID } from 'node:crypto';
35
36
  import { mkdir, mkdtemp, readdir, rename, rm, stat, unlink, writeFile } from 'node:fs/promises';
36
37
  import { pipeline } from 'node:stream/promises';
37
38
  import { createWriteStream } from 'node:fs';
38
- import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
39
+ import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
39
40
  import { ApiError, TransportError, localValidationError } from './errors.js';
40
41
  import { requireEnum } from './validate.js';
41
42
  /** Schema version stamped into `meta.json`. Bumps with the contract. */
@@ -229,6 +230,28 @@ export function pickCodeExtension(language, framework) {
229
230
  return 'py';
230
231
  return 'py';
231
232
  }
233
+ /** Recording container extensions the bundle writer will trust from `videoUrl`. */
234
+ const KNOWN_VIDEO_EXTENSIONS = new Set(['mp4', 'webm', 'mov', 'mkv', 'avi']);
235
+ /**
236
+ * Pick the on-disk extension for `<dir>/video.<ext>` from the actual
237
+ * `result.videoUrl`, instead of hardcoding `mp4` (the
238
+ * recording is sometimes a `.webm` container; saving it under a `video.mp4`
239
+ * name misleads strict-extension consumers). Falls back to `mp4` when the
240
+ * URL is malformed or its extension isn't a recognized container, so a
241
+ * response-controlled field can never smuggle an arbitrary suffix onto disk.
242
+ */
243
+ export function pickVideoExtension(url) {
244
+ try {
245
+ const match = /\.([A-Za-z0-9]+)$/.exec(new URL(url).pathname);
246
+ const ext = match?.[1]?.toLowerCase();
247
+ if (ext !== undefined && KNOWN_VIDEO_EXTENSIONS.has(ext))
248
+ return ext;
249
+ }
250
+ catch {
251
+ // Malformed URL — fall through to the default below.
252
+ }
253
+ return 'mp4';
254
+ }
232
255
  /**
233
256
  * Step filename per §7.2 — 1-based index, zero-padded to two digits
234
257
  * for indices ≤ 99, three digits for ≥ 100. `${stepIndex}-snapshot.html`
@@ -278,8 +301,9 @@ export function buildMeta(ctx, fetchedAt = new Date()) {
278
301
  * 2. `applyFailedOnly` — narrow before download (saves bytes).
279
302
  * 3. `mkdir <dir>/.tmp/` — fresh; clean any stale temp.
280
303
  * 4. `writeFile result.json / failure.json / code.<ext>` — local data.
281
- * 5. `fetch + stream` for `video.mp4` (when set) and per-step
282
- * snapshot/screenshot/evidence-json files.
304
+ * 5. `fetch + stream` for `video.<ext>` (when set; extension matches the
305
+ * actual recording container) and per-step snapshot/screenshot/
306
+ * evidence-json files.
283
307
  * 6. `writeFile meta.json` LAST — its presence means "bundle complete".
284
308
  * 7. `rename .tmp/<file> -> <file>` for every file. Last rename
285
309
  * makes meta.json visible.
@@ -328,10 +352,12 @@ export async function writeBundle(ctx, options) {
328
352
  // Optional video. Wire field is `result.videoUrl` (not in `failure`),
329
353
  // and the CLI surfaces it as a top-level on-disk artifact for agent
330
354
  // ergonomics — the agent doesn't have to know which sub-object held
331
- // it on the wire.
355
+ // it on the wire. Extension matches the actual recording container
356
+ // (some runs ship `.webm`, not `.mp4`).
332
357
  if (filtered.result.videoUrl) {
333
- await streamUrlToFile(filtered.result.videoUrl, join(tmpDir, 'video.mp4'), fetchImpl);
334
- filesWritten.push('video.mp4');
358
+ const videoFile = `video.${pickVideoExtension(filtered.result.videoUrl)}`;
359
+ await streamUrlToFile(filtered.result.videoUrl, join(tmpDir, videoFile), fetchImpl);
360
+ filesWritten.push(videoFile);
335
361
  }
336
362
  for (const step of filtered.steps) {
337
363
  await writeStepArtifacts(step, filtered.failure.evidence, stepsTmpDir, fetchImpl, filesWritten);
@@ -365,101 +391,117 @@ async function freshTmpDir(dir) {
365
391
  await mkdir(tmpDir, { recursive: true });
366
392
  return tmpDir;
367
393
  }
368
- /**
369
- * Rename `<tmp>/<file>` → `<dir>/<file>` for every file in `files`.
370
- *
371
- * Critical ordering for atomicity (the §3 "agent-safe" contract):
372
- *
373
- * 1. **Remove the OLD `meta.json` first.** The bundle's completion
374
- * signal is `meta.json`'s presence; an agent reading `<dir>` while
375
- * we're mutating it must see "no meta → bundle absent or
376
- * mid-write" rather than "meta points at a snapshot that's already
377
- * been partially overwritten." Removing the old meta is what
378
- * makes the rest of the swap safe to do in place.
379
- * 2. Wipe stale top-level files (e.g. an old `video.mp4` when the new
380
- * bundle has no video). Without this, a fresh bundle could ship
381
- * with a stale video lingering at the top level.
382
- * 3. Replace `<dir>/steps/` wholesale.
383
- * 4. Rename top-level files into place.
384
- * 5. **Rename `meta.json` LAST.** Its visible presence is the atomic
385
- * completion signal; until step 5 lands, agents see "incomplete."
386
- *
387
- * The window between (1) and (5) is bounded by a handful of `rename`
388
- * syscalls — small enough that a SIGKILL there is rare, and any agent
389
- * caught reading the dir during it sees no meta and refuses to consume
390
- * (per §7.3). That's what we want.
391
- */
392
394
  /**
393
395
  * Whether a top-level directory entry belongs to the bundle format —
394
396
  * i.e. something a prior `writeBundle` could have produced and this
395
- * commit is therefore allowed to clean up. `code.<ext>` is matched by
396
- * pattern (not the current run's extension) so a stale `code.py` is
397
- * still swept when the new bundle writes `code.ts`. Everything else in
398
- * the directory is the user's and must never be deleted (`--out` can
399
- * point at a pre-existing, populated directory).
397
+ * commit is therefore allowed to clean up. `code.<ext>` and `video.<ext>`
398
+ * are matched by pattern (not the current run's extension) so a stale
399
+ * `code.py` or `video.webm` is still swept when the new bundle writes
400
+ * `code.ts` / `video.mp4` (or no video at all). Everything else in the
401
+ * directory is the user's and must never be deleted (`--out` can point at
402
+ * a pre-existing, populated directory).
400
403
  */
401
404
  export function isBundleOwnedEntry(entry) {
402
405
  if (entry === 'result.json' ||
403
406
  entry === 'failure.json' ||
404
- entry === 'video.mp4' ||
405
407
  entry === 'meta.json' ||
406
408
  entry === 'steps' ||
407
409
  entry === '.tmp' ||
408
410
  entry === '.partial') {
409
411
  return true;
410
412
  }
411
- return /^code\.[A-Za-z0-9]+$/.test(entry);
413
+ // Videos: only the extensions the bundle itself can write (see
414
+ // KNOWN_VIDEO_EXTENSIONS / pickVideoExtension). A broader `video.*`
415
+ // pattern would claim user files like `video.txt` sitting in a
416
+ // pre-existing `--out` directory and delete them in the sweep.
417
+ return (/^code\.[A-Za-z0-9]+$/.test(entry) ||
418
+ (entry.startsWith('video.') && KNOWN_VIDEO_EXTENSIONS.has(entry.slice('video.'.length))));
412
419
  }
413
- async function commitBundle(tmpDir, dir, files) {
414
- // (1) Remove the prior bundle's completion signal FIRST.
415
- await unlink(join(dir, 'meta.json')).catch(() => undefined);
416
- // (2) Sweep stale top-level files that the new bundle won't write.
417
- // If the prior run wrote `video.mp4` and the new run has no video,
418
- // an in-place rename leaves the old video lingering. Only entries the
419
- // bundle format OWNS are candidates: `--out` may point at a directory
420
- // that also holds the user's unrelated files, and those must survive
421
- // the commit (deleting them would be silent data loss).
422
- const topLevel = files.filter(f => !f.startsWith('steps/'));
423
- const newTopLevelSet = new Set(topLevel);
424
- newTopLevelSet.add('meta.json'); // about to land last, do not delete
425
- const existing = await readdir(dir).catch(() => []);
426
- for (const entry of existing) {
427
- // Preserve the writer's own scratch dir + the .partial marker
428
- // (we'll re-evaluate .partial at the end of commit). Any other
429
- // bundle-owned entry not-listed in the new bundle is stale.
430
- if (entry === '.tmp' || entry === '.partial')
431
- continue;
432
- if (newTopLevelSet.has(entry))
433
- continue;
434
- if (entry === 'steps')
435
- continue; // handled below
436
- if (!isBundleOwnedEntry(entry))
437
- continue; // foreign file — never touch
438
- await rm(join(dir, entry), { recursive: true, force: true });
420
+ /**
421
+ * Atomically install the complete bundle staged in `tmpDir` into `dir`.
422
+ *
423
+ * Compatible with the #162 data-loss guard: only `isBundleOwnedEntry`
424
+ * names are moved aside or replaced — foreign files in `--out` survive.
425
+ *
426
+ * Re-commit safety: bundle-owned entries are renamed to a sibling
427
+ * aside directory before the new artifacts land. The prior `meta.json`
428
+ * is moved aside first (§3/§7.3 — no meta ⇒ refuse to consume) so a
429
+ * concurrent reader never sees meta pointing at steps already gone.
430
+ * The new `meta.json` is installed last. On failure, aside entries are
431
+ * restored so a failed re-commit never leaves the directory unusable.
432
+ */
433
+ export async function commitBundle(tmpDir, dir, files) {
434
+ const parent = dirname(dir);
435
+ const base = basename(dir);
436
+ const asideDir = join(parent, `.${base}.aside.${randomUUID()}`);
437
+ const asideLog = [];
438
+ const asideIfPresent = async (entry) => {
439
+ const restorePath = join(dir, entry);
440
+ if (!(await pathExists(restorePath)))
441
+ return;
442
+ const asidePath = join(asideDir, entry);
443
+ await mkdir(dirname(asidePath), { recursive: true });
444
+ await rename(restorePath, asidePath);
445
+ asideLog.push({ asidePath, restorePath });
446
+ };
447
+ const rollback = async () => {
448
+ for (const { asidePath, restorePath } of [...asideLog].reverse()) {
449
+ await rm(restorePath, { recursive: true, force: true }).catch(() => undefined);
450
+ await rename(asidePath, restorePath).catch(() => undefined);
451
+ }
452
+ await rm(asideDir, { recursive: true, force: true }).catch(() => undefined);
453
+ };
454
+ try {
455
+ const topLevel = files.filter(f => !f.startsWith('steps/'));
456
+ const newTopLevelSet = new Set(topLevel);
457
+ newTopLevelSet.add('meta.json');
458
+ // meta.json first — its presence is the completion signal; do not
459
+ // move steps (or anything else) aside while a stale meta is still visible.
460
+ await asideIfPresent('meta.json');
461
+ const existing = await readdir(dir).catch(() => []);
462
+ for (const entry of existing) {
463
+ if (entry === '.tmp' || entry === 'meta.json')
464
+ continue;
465
+ if (!isBundleOwnedEntry(entry))
466
+ continue;
467
+ const isStale = entry !== 'steps' && entry !== '.partial' && !newTopLevelSet.has(entry);
468
+ const willReplace = entry === 'steps' || newTopLevelSet.has(entry);
469
+ if (isStale || willReplace) {
470
+ await asideIfPresent(entry);
471
+ }
472
+ }
473
+ const stepsTmp = join(tmpDir, 'steps');
474
+ const stepsDir = join(dir, 'steps');
475
+ if (await dirExists(stepsTmp)) {
476
+ await rename(stepsTmp, stepsDir);
477
+ }
478
+ const metaIdx = topLevel.indexOf('meta.json');
479
+ const beforeMeta = metaIdx >= 0 ? topLevel.filter((_, i) => i !== metaIdx) : topLevel;
480
+ for (const file of beforeMeta) {
481
+ await rename(join(tmpDir, file), join(dir, file));
482
+ }
483
+ if (metaIdx >= 0) {
484
+ await rename(join(tmpDir, 'meta.json'), join(dir, 'meta.json'));
485
+ }
486
+ await unlink(join(dir, '.partial')).catch(() => undefined);
487
+ await rm(tmpDir, { recursive: true, force: true });
488
+ // Best-effort aside cleanup — failures must not roll back a committed bundle.
489
+ await rm(asideDir, { recursive: true, force: true }).catch(() => undefined);
439
490
  }
440
- // (3) Replace `<dir>/steps/` with `<tmp>/steps/`.
441
- const stepsTmp = join(tmpDir, 'steps');
442
- const stepsDir = join(dir, 'steps');
443
- await rm(stepsDir, { recursive: true, force: true });
444
- if (await dirExists(stepsTmp)) {
445
- await rename(stepsTmp, stepsDir);
491
+ catch (err) {
492
+ await rollback();
493
+ await rm(tmpDir, { recursive: true, force: true }).catch(() => undefined);
494
+ throw err;
446
495
  }
447
- // (4) Top-level files (result/failure/code/video). meta.json renames
448
- // LAST; track it separately.
449
- const metaIdx = topLevel.indexOf('meta.json');
450
- const beforeMeta = metaIdx >= 0 ? topLevel.filter((_, i) => i !== metaIdx) : topLevel;
451
- for (const file of beforeMeta) {
452
- await rename(join(tmpDir, file), join(dir, file));
496
+ }
497
+ async function pathExists(path) {
498
+ try {
499
+ await stat(path);
500
+ return true;
453
501
  }
454
- // (5) meta.json LAST → atomic completion signal.
455
- if (metaIdx >= 0) {
456
- await rename(join(tmpDir, 'meta.json'), join(dir, 'meta.json'));
502
+ catch {
503
+ return false;
457
504
  }
458
- // .partial from a prior aborted run is now stale. Remove it so an
459
- // agent inspecting the dir sees only the fresh bundle.
460
- await unlink(join(dir, '.partial')).catch(() => undefined);
461
- // Clean up the now-empty tmp dir.
462
- await rm(tmpDir, { recursive: true, force: true });
463
505
  }
464
506
  async function dirExists(path) {
465
507
  try {
@@ -48,6 +48,20 @@ export interface ClientFactoryDeps {
48
48
  */
49
49
  shutdownSignal?: AbortSignal;
50
50
  }
51
+ /**
52
+ * Accepted TestSprite API-key prefixes, in the order they are reported to the
53
+ * user. Three families exist today and all three authenticate:
54
+ *
55
+ * - `sk-user-…` legacy encrypted-envelope key — acts as the human
56
+ * - `sk-member-…` membership key — acts as ONE org membership of that human
57
+ * - `tsp_…` the pre-rename spelling of a membership key (`sk-member-…`);
58
+ * still issued to nobody, still valid for everyone holding one
59
+ *
60
+ * `sk-member-` is deliberately NOT shortened to `sk-` here: this list is only
61
+ * a fail-fast format check, but keeping the full prefixes means the message
62
+ * below can name exactly what the server will accept.
63
+ */
64
+ export declare const API_KEY_PREFIXES: readonly ["sk-user-", "sk-member-", "tsp_"];
51
65
  /**
52
66
  * The fake API key used in dry-run. Never sent — the dry-run fetch
53
67
  * impl ignores headers and returns a canned sample. Documented in the
@@ -93,6 +107,15 @@ export declare function resolveRequestTimeoutMs(opts: Pick<CommonOptions, 'reque
93
107
  * assuming the flag.
94
108
  */
95
109
  export declare function assertValidEndpointUrl(rawUrl: string): void;
110
+ /**
111
+ * Reject a key that isn't a TestSprite key, up front — so a malformed key
112
+ * fails fast instead of a slow live `fetch failed`. Checks only the prefix +
113
+ * non-empty body against {@link API_KEY_PREFIXES}, so it can never reject a
114
+ * real key of any issued family.
115
+ */
116
+ export declare function assertValidApiKeyFormat(apiKey: string): void;
117
+ /** Up-front key validation: TestSprite format + legal HTTP header value. */
118
+ export declare function assertValidApiKey(apiKey: string): void;
96
119
  export declare function assertValidApiKeyHeaderValue(apiKey: string): void;
97
120
  /**
98
121
  * Parse the `--request-timeout <seconds>` flag value into milliseconds.
@@ -22,6 +22,20 @@ import { globalShutdown } from './interrupt.js';
22
22
  import { createDryRunFetch } from './dry-run/fetch.js';
23
23
  import { noteServerVersion } from './version-notice.js';
24
24
  import { VERSION } from '../version.js';
25
+ /**
26
+ * Accepted TestSprite API-key prefixes, in the order they are reported to the
27
+ * user. Three families exist today and all three authenticate:
28
+ *
29
+ * - `sk-user-…` legacy encrypted-envelope key — acts as the human
30
+ * - `sk-member-…` membership key — acts as ONE org membership of that human
31
+ * - `tsp_…` the pre-rename spelling of a membership key (`sk-member-…`);
32
+ * still issued to nobody, still valid for everyone holding one
33
+ *
34
+ * `sk-member-` is deliberately NOT shortened to `sk-` here: this list is only
35
+ * a fail-fast format check, but keeping the full prefixes means the message
36
+ * below can name exactly what the server will accept.
37
+ */
38
+ export const API_KEY_PREFIXES = ['sk-user-', 'sk-member-', 'tsp_'];
25
39
  /**
26
40
  * The fake API key used in dry-run. Never sent — the dry-run fetch
27
41
  * impl ignores headers and returns a canned sample. Documented in the
@@ -112,6 +126,24 @@ export function assertValidEndpointUrl(rawUrl) {
112
126
  `(e.g. https://api.testsprite.com)`, undefined, 'field');
113
127
  }
114
128
  }
129
+ /**
130
+ * Reject a key that isn't a TestSprite key, up front — so a malformed key
131
+ * fails fast instead of a slow live `fetch failed`. Checks only the prefix +
132
+ * non-empty body against {@link API_KEY_PREFIXES}, so it can never reject a
133
+ * real key of any issued family.
134
+ */
135
+ export function assertValidApiKeyFormat(apiKey) {
136
+ const matchesPrefix = (prefix) => apiKey.startsWith(prefix) && apiKey.length > prefix.length;
137
+ if (!API_KEY_PREFIXES.some(matchesPrefix)) {
138
+ const shown = API_KEY_PREFIXES.map(p => `\`${p}\``).join(', ');
139
+ throw localValidationError('api-key', `must be a TestSprite API key beginning with one of ${shown} (create one in the dashboard, then run \`testsprite setup\`)`, undefined, 'field');
140
+ }
141
+ }
142
+ /** Up-front key validation: TestSprite format + legal HTTP header value. */
143
+ export function assertValidApiKey(apiKey) {
144
+ assertValidApiKeyFormat(apiKey);
145
+ assertValidApiKeyHeaderValue(apiKey);
146
+ }
115
147
  export function assertValidApiKeyHeaderValue(apiKey) {
116
148
  const reason = 'must be a non-empty HTTP header value; paste the raw key without smart punctuation, emoji, or line breaks';
117
149
  if (apiKey.trim().length === 0) {
@@ -192,7 +224,7 @@ export function makeHttpClient(opts, deps = {}) {
192
224
  assertValidEndpointUrl(config.apiUrl);
193
225
  if (!config.apiKey)
194
226
  throw ApiError.authRequired();
195
- assertValidApiKeyHeaderValue(config.apiKey);
227
+ assertValidApiKey(config.apiKey);
196
228
  return new HttpClient({
197
229
  baseUrl: facadeBaseUrl(config.apiUrl),
198
230
  apiKey: config.apiKey,
@@ -22,12 +22,16 @@ export function defaultConfigPath() {
22
22
  */
23
23
  export function loadConfig(options = {}) {
24
24
  const env = options.env ?? process.env;
25
- const profile = options.profile ?? env.TESTSPRITE_PROFILE ?? DEFAULT_PROFILE;
25
+ const profile = options.profile ?? normalizeEnvVar(env.TESTSPRITE_PROFILE) ?? DEFAULT_PROFILE;
26
26
  const credentialsPath = options.credentialsPath ?? defaultCredentialsPath();
27
27
  const fileEntry = readProfile(profile, { path: credentialsPath });
28
28
  // Empty / whitespace-only env vars are treated as unset so they do not
29
- // short-circuit the `??` chain (e.g. `export TESTSPRITE_API_URL=` in a shell
30
- // profile). Matches the normalization in auth configure and init/setup.
29
+ // short-circuit the `??` chain (e.g. `export TESTSPRITE_API_URL=` or
30
+ // `export TESTSPRITE_PROFILE=` in a shell profile). For the profile this
31
+ // also avoids a confusing VALIDATION_ERROR: an empty name fails the INI
32
+ // section-name guard, so without normalization a blank env var would break
33
+ // every command instead of falling back to the default profile. Matches the
34
+ // normalization in auth configure and init/setup.
31
35
  const envApiUrl = normalizeEnvVar(env.TESTSPRITE_API_URL);
32
36
  const envApiKey = normalizeEnvVar(env.TESTSPRITE_API_KEY);
33
37
  return {
@@ -1,3 +1,4 @@
1
+ import { type SpawnSyncReturns } from 'node:child_process';
1
2
  export declare const DEFAULT_PROFILE = "default";
2
3
  /**
3
4
  * Throw a typed VALIDATION_ERROR (exit 5) when `profile` is not a safe INI
@@ -15,10 +16,25 @@ export type CredentialsFile = Record<string, ProfileEntry>;
15
16
  export interface CredentialsOptions {
16
17
  path?: string;
17
18
  }
19
+ interface RestrictiveModeOptions {
20
+ platform?: NodeJS.Platform;
21
+ env?: NodeJS.ProcessEnv;
22
+ spawnSync?: (command: string, args: readonly string[], options: {
23
+ shell: false;
24
+ stdio: 'ignore';
25
+ windowsHide: true;
26
+ }) => SpawnSyncReturns<Buffer>;
27
+ warn?: (line: string) => void;
28
+ }
18
29
  export declare function parseCredentials(content: string): CredentialsFile;
19
30
  export declare function serializeCredentials(file: CredentialsFile): string;
20
31
  export declare function readCredentialsFile(options?: CredentialsOptions): CredentialsFile;
21
32
  export declare function readProfile(profile: string, options?: CredentialsOptions): ProfileEntry | undefined;
22
33
  export declare function writeProfile(profile: string, entry: ProfileEntry, options?: CredentialsOptions): void;
23
34
  export declare function deleteProfile(profile: string, options?: CredentialsOptions): boolean;
24
- export declare function ensureRestrictiveMode(path: string): void;
35
+ /**
36
+ * Enforce restrictive access on the credentials file after atomic writes.
37
+ * POSIX hosts use chmod(0600); Windows hosts use ACL tightening via icacls.
38
+ */
39
+ export declare function ensureRestrictiveMode(path: string, options?: RestrictiveModeOptions): void;
40
+ export {};