@testsprite/testsprite-cli 0.3.0 → 0.5.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 (63) hide show
  1. package/README.md +55 -29
  2. package/dist/commands/agent.js +17 -6
  3. package/dist/commands/auth.d.ts +51 -0
  4. package/dist/commands/auth.js +46 -2
  5. package/dist/commands/completion.d.ts +36 -0
  6. package/dist/commands/completion.js +111 -0
  7. package/dist/commands/doctor.js +56 -16
  8. package/dist/commands/init.d.ts +32 -1
  9. package/dist/commands/init.js +40 -10
  10. package/dist/commands/project.d.ts +102 -4
  11. package/dist/commands/project.js +250 -47
  12. package/dist/commands/test.d.ts +253 -11
  13. package/dist/commands/test.js +1822 -390
  14. package/dist/commands/usage.d.ts +56 -17
  15. package/dist/commands/usage.js +144 -29
  16. package/dist/index.js +172 -29
  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 +144 -84
  21. package/dist/lib/client-factory.d.ts +29 -0
  22. package/dist/lib/client-factory.js +49 -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 +51 -1
  27. package/dist/lib/errors.d.ts +33 -1
  28. package/dist/lib/errors.js +110 -19
  29. package/dist/lib/failing-fe-resolver.d.ts +15 -0
  30. package/dist/lib/failing-fe-resolver.js +49 -1
  31. package/dist/lib/flaky.d.ts +12 -1
  32. package/dist/lib/flaky.js +7 -12
  33. package/dist/lib/gh-output.d.ts +62 -0
  34. package/dist/lib/gh-output.js +99 -0
  35. package/dist/lib/http.d.ts +86 -16
  36. package/dist/lib/http.js +181 -11
  37. package/dist/lib/interrupt.d.ts +65 -10
  38. package/dist/lib/interrupt.js +94 -9
  39. package/dist/lib/org-render.d.ts +52 -0
  40. package/dist/lib/org-render.js +59 -0
  41. package/dist/lib/poll.d.ts +11 -0
  42. package/dist/lib/poll.js +71 -6
  43. package/dist/lib/render-error.d.ts +14 -0
  44. package/dist/lib/render-error.js +30 -0
  45. package/dist/lib/response-schemas.d.ts +83 -0
  46. package/dist/lib/response-schemas.js +272 -0
  47. package/dist/lib/runs.types.d.ts +62 -8
  48. package/dist/lib/skill-nudge.d.ts +17 -0
  49. package/dist/lib/skill-nudge.js +19 -0
  50. package/dist/lib/telemetry.d.ts +90 -0
  51. package/dist/lib/telemetry.js +171 -0
  52. package/dist/lib/text-table.d.ts +14 -0
  53. package/dist/lib/text-table.js +45 -0
  54. package/dist/lib/v3-advisory.d.ts +22 -0
  55. package/dist/lib/v3-advisory.js +32 -0
  56. package/dist/lib/version-notice.d.ts +37 -0
  57. package/dist/lib/version-notice.js +87 -0
  58. package/dist/version.d.ts +1 -1
  59. package/dist/version.js +1 -1
  60. package/package.json +16 -5
  61. package/schemas/plan.schema.json +61 -0
  62. package/skills/testsprite-verify.codex.md +8 -2
  63. package/skills/testsprite-verify.skill.md +18 -7
@@ -1,4 +1,6 @@
1
- import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync, } from 'node:fs';
1
+ import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync, } from 'node:fs';
2
+ import { spawnSync } from 'node:child_process';
3
+ import { randomUUID } from 'node:crypto';
2
4
  import { homedir } from 'node:os';
3
5
  import { dirname, join } from 'node:path';
4
6
  import { localValidationError } from './errors.js';
@@ -40,6 +42,9 @@ const FIELD_TO_FILE_KEY = {
40
42
  apiKey: 'api_key',
41
43
  apiUrl: 'api_url',
42
44
  };
45
+ const CREDENTIALS_LOCK_RETRY_MS = 25;
46
+ const CREDENTIALS_LOCK_WAIT_MS = 5_000;
47
+ const CREDENTIALS_LOCK_STALE_MS = 30_000;
43
48
  export function parseCredentials(content) {
44
49
  const result = {};
45
50
  let currentEntry = null;
@@ -122,40 +127,194 @@ export function readProfile(profile, options = {}) {
122
127
  export function writeProfile(profile, entry, options = {}) {
123
128
  assertValidProfileName(profile);
124
129
  const path = resolvePath(options);
125
- const file = readCredentialsFile(options);
126
- file[profile] = { ...file[profile], ...entry };
127
- writeCredentialsAtomic(path, file);
130
+ mutateCredentialsFile(path, file => {
131
+ file[profile] = { ...file[profile], ...entry };
132
+ return file;
133
+ });
128
134
  }
129
135
  export function deleteProfile(profile, options = {}) {
130
136
  assertValidProfileName(profile);
131
137
  const path = resolvePath(options);
132
- const file = readCredentialsFile(options);
133
- if (!(profile in file))
138
+ if (!existsSync(path))
134
139
  return false;
135
- delete file[profile];
136
- if (Object.keys(file).length === 0) {
137
- writeCredentialsAtomic(path, {});
138
- }
139
- else {
140
- writeCredentialsAtomic(path, file);
141
- }
142
- return true;
140
+ let removed = false;
141
+ mutateCredentialsFile(path, file => {
142
+ if (!(profile in file))
143
+ return undefined;
144
+ removed = true;
145
+ delete file[profile];
146
+ return file;
147
+ });
148
+ return removed;
143
149
  }
144
- export function ensureRestrictiveMode(path) {
150
+ /**
151
+ * Enforce restrictive access on the credentials file after atomic writes.
152
+ * POSIX hosts use chmod(0600); Windows hosts use ACL tightening via icacls.
153
+ */
154
+ export function ensureRestrictiveMode(path, options = {}) {
145
155
  if (!existsSync(path))
146
156
  return;
157
+ if ((options.platform ?? process.platform) === 'win32') {
158
+ ensureWindowsRestrictiveAcl(path, options);
159
+ return;
160
+ }
147
161
  const overpermissive = (statSync(path).mode & 0o077) !== 0;
148
162
  if (overpermissive)
149
163
  chmodSync(path, 0o600);
150
164
  }
165
+ /**
166
+ * Restrict a Windows credentials file to the current user using icacls.
167
+ * The command is invoked with an args array so credential paths are never shell-interpreted.
168
+ */
169
+ function ensureWindowsRestrictiveAcl(path, options) {
170
+ const username = (options.env ?? process.env).USERNAME?.trim();
171
+ if (!username) {
172
+ warnWindowsAcl('could not determine the Windows username; credentials file permissions were not tightened', options);
173
+ return;
174
+ }
175
+ const run = options.spawnSync ?? spawnSync;
176
+ const result = run('icacls', [path, '/inheritance:r', '/grant:r', `${username}:F`], {
177
+ shell: false,
178
+ stdio: 'ignore',
179
+ windowsHide: true,
180
+ });
181
+ if (result.error) {
182
+ warnWindowsAcl(`icacls failed while tightening credentials file permissions: ${result.error.message}`, options);
183
+ return;
184
+ }
185
+ if (result.status !== 0) {
186
+ warnWindowsAcl(`icacls exited with status ${result.status ?? 'unknown'}; credentials file permissions may be too broad`, options);
187
+ }
188
+ }
189
+ /** Emit an explicit warning when Windows ACL tightening cannot be completed. */
190
+ function warnWindowsAcl(message, options) {
191
+ const warn = options.warn ?? ((line) => process.stderr.write(`${line}\n`));
192
+ warn(`[warning] ${message}`);
193
+ }
151
194
  function resolvePath(options) {
152
195
  return options.path ?? defaultCredentialsPath();
153
196
  }
154
- function writeCredentialsAtomic(path, file) {
197
+ function mutateCredentialsFile(path, mutate) {
155
198
  mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
199
+ const lock = acquireCredentialsLock(path);
200
+ try {
201
+ const file = readCredentialsFile({ path });
202
+ const nextFile = mutate(file);
203
+ if (nextFile === undefined)
204
+ return;
205
+ lock.assertHeld();
206
+ writeCredentialsAtomic(path, nextFile);
207
+ }
208
+ finally {
209
+ lock.release();
210
+ }
211
+ }
212
+ function writeCredentialsAtomic(path, file) {
156
213
  const tmp = `${path}.tmp.${process.pid}`;
157
214
  writeFileSync(tmp, serializeCredentials(file), { mode: 0o600, encoding: 'utf8' });
158
215
  renameSync(tmp, path);
159
216
  ensureRestrictiveMode(path);
160
217
  }
218
+ function acquireCredentialsLock(path) {
219
+ const lockPath = `${path}.lock`;
220
+ const deadline = Date.now() + CREDENTIALS_LOCK_WAIT_MS;
221
+ const token = `${process.pid}:${Date.now()}:${randomUUID()}`;
222
+ const lockInfo = {
223
+ pid: process.pid,
224
+ createdAt: Date.now(),
225
+ token,
226
+ };
227
+ while (true) {
228
+ try {
229
+ writeFileSync(lockPath, `${JSON.stringify(lockInfo)}\n`, {
230
+ encoding: 'utf8',
231
+ flag: 'wx',
232
+ mode: 0o600,
233
+ });
234
+ return {
235
+ assertHeld: () => assertCredentialsLockHeld(lockPath, token),
236
+ release: () => releaseCredentialsLock(lockPath, token),
237
+ };
238
+ }
239
+ catch (error) {
240
+ if (!isErrnoException(error) || error.code !== 'EEXIST') {
241
+ throw error;
242
+ }
243
+ reclaimStaleCredentialsLock(lockPath);
244
+ if (Date.now() >= deadline) {
245
+ throw localValidationError('credentialsLock', 'timed out waiting for another credential update to finish; retry the command', undefined, 'field');
246
+ }
247
+ sleepSync(CREDENTIALS_LOCK_RETRY_MS);
248
+ }
249
+ }
250
+ }
251
+ function reclaimStaleCredentialsLock(lockPath) {
252
+ let lockInfo;
253
+ try {
254
+ lockInfo = JSON.parse(readFileSync(lockPath, 'utf-8'));
255
+ }
256
+ catch {
257
+ lockInfo = undefined;
258
+ }
259
+ const createdAt = typeof lockInfo?.createdAt === 'number' ? lockInfo.createdAt : undefined;
260
+ const ageMs = createdAt === undefined ? Number.POSITIVE_INFINITY : Date.now() - createdAt;
261
+ const pid = typeof lockInfo?.pid === 'number' ? lockInfo.pid : undefined;
262
+ if (ageMs <= CREDENTIALS_LOCK_STALE_MS && (pid === undefined || isProcessAlive(pid))) {
263
+ return;
264
+ }
265
+ try {
266
+ unlinkSync(lockPath);
267
+ }
268
+ catch (error) {
269
+ if (!isErrnoException(error) || error.code !== 'ENOENT') {
270
+ throw error;
271
+ }
272
+ }
273
+ }
274
+ function assertCredentialsLockHeld(lockPath, token) {
275
+ const lockInfo = readCredentialsLockInfo(lockPath);
276
+ if (lockInfo?.token === token)
277
+ return;
278
+ throw localValidationError('credentialsLock', 'lost ownership of the credential update lock; retry the command', undefined, 'field');
279
+ }
280
+ function releaseCredentialsLock(lockPath, token) {
281
+ const lockInfo = readCredentialsLockInfo(lockPath);
282
+ if (lockInfo?.token !== token)
283
+ return;
284
+ try {
285
+ unlinkSync(lockPath);
286
+ }
287
+ catch (error) {
288
+ if (!isErrnoException(error) || error.code !== 'ENOENT') {
289
+ throw error;
290
+ }
291
+ }
292
+ }
293
+ function readCredentialsLockInfo(lockPath) {
294
+ try {
295
+ return JSON.parse(readFileSync(lockPath, 'utf-8'));
296
+ }
297
+ catch {
298
+ return undefined;
299
+ }
300
+ }
301
+ function isProcessAlive(pid) {
302
+ if (pid === process.pid)
303
+ return true;
304
+ try {
305
+ process.kill(pid, 0);
306
+ return true;
307
+ }
308
+ catch (error) {
309
+ if (isErrnoException(error) && error.code === 'ESRCH')
310
+ return false;
311
+ return true;
312
+ }
313
+ }
314
+ function isErrnoException(error) {
315
+ return error instanceof Error && 'code' in error;
316
+ }
317
+ function sleepSync(ms) {
318
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
319
+ }
161
320
  //# sourceMappingURL=credentials.js.map
@@ -58,6 +58,16 @@ const me = {
58
58
  keyId: SAMPLE_KEY_ID,
59
59
  scopes: ['read:projects', 'read:tests', 'write:tests', 'run:tests'],
60
60
  env: 'development',
61
+ v3Enabled: true,
62
+ activeOrg: {
63
+ id: '22222222-2222-4222-8222-222222222222',
64
+ name: 'Dry Run Workspace',
65
+ plan: 'Standard',
66
+ role: 'owner',
67
+ remaining: 1650,
68
+ includedCredits: 1600,
69
+ seats: 1,
70
+ },
61
71
  };
62
72
  const projects = [
63
73
  {
@@ -290,7 +300,10 @@ const ENTRIES = [
290
300
  entry('getProject', 'GET', '/projects/{projectId}', projects[0]),
291
301
  // P6 — POST /projects (create project). The id uses a stable dry-run
292
302
  // sentinel so agents can see a coherent field shape without a real key.
303
+ // Both `projectId` (the live field) and `id` (legacy/
304
+ // fallback) are shown — see `CliCreateProjectResponse`.
293
305
  entry('createProject', 'POST', '/projects', {
306
+ projectId: 'p_dryrun_create_2026',
294
307
  id: 'p_dryrun_create_2026',
295
308
  type: 'frontend',
296
309
  name: 'Dry-run project',
@@ -298,12 +311,19 @@ const ENTRIES = [
298
311
  createdAt: '2026-05-16T00:00:00.000Z',
299
312
  updatedAt: '2026-05-16T00:00:00.000Z',
300
313
  }),
301
- // P7 — PATCH /projects/{id} (update project).
314
+ // P7 — PATCH /projects/{id} (update project). Both id
315
+ // field names shown — see `CliUpdateProjectResponse`.
302
316
  entry('updateProject', 'PATCH', '/projects/{projectId}', {
317
+ projectId: SAMPLE_PROJECT_ID,
303
318
  id: SAMPLE_PROJECT_ID,
304
319
  updatedFields: ['name'],
305
320
  updatedAt: '2026-05-16T00:00:00.000Z',
306
321
  }),
322
+ // DELETE /projects/{id} (cascade delete project + tests + fixtures).
323
+ entry('deleteProject', 'DELETE', '/projects/{projectId}', {
324
+ projectId: SAMPLE_PROJECT_ID,
325
+ deletedAt: '2026-05-16T00:00:00.000Z',
326
+ }),
307
327
  entry('listTests', 'GET', '/tests', pageOf(tests)),
308
328
  entry('getTestCode', 'GET', '/tests/{testId}/code', testCode),
309
329
  entry('listTestSteps', 'GET', '/tests/{testId}/steps', pageOf(testSteps)),
@@ -654,6 +674,36 @@ const ENTRIES = [
654
674
  },
655
675
  ],
656
676
  }),
677
+ // DEV-331 piece 3 — POST /runs/{runId}/cancel. Method-guarded in
678
+ // `findSample` (POST vs `getRun`'s GET), so this can't be shadowed by the
679
+ // broader `/runs/{runId}` pattern above despite sharing its path prefix.
680
+ // `alreadyCancelled: false` — a fresh cancel is the more instructive shape
681
+ // for a dry-run learner than the idempotent no-op.
682
+ entry('cancelRun', 'POST', '/runs/{runId}/cancel', {
683
+ runId: SAMPLE_RUN_ID,
684
+ testId: SAMPLE_TEST_ID_PASSED,
685
+ projectId: SAMPLE_PROJECT_ID,
686
+ userId: SAMPLE_USER_ID,
687
+ status: 'cancelled',
688
+ source: 'cli',
689
+ createdAt: '2026-05-15T19:32:00.000Z',
690
+ startedAt: '2026-05-15T19:32:05.000Z',
691
+ finishedAt: '2026-05-15T19:33:12.000Z',
692
+ codeVersion: 'v1',
693
+ targetUrl: SAMPLE_TARGET_URL,
694
+ createdFrom: null,
695
+ failedStepIndex: null,
696
+ failureKind: null,
697
+ error: null,
698
+ videoUrl: null,
699
+ stepSummary: {
700
+ total: 8,
701
+ completed: 3,
702
+ passedCount: 3,
703
+ failedCount: 0,
704
+ },
705
+ alreadyCancelled: false,
706
+ }),
657
707
  ];
658
708
  function entry(operationId, method, pathTemplate, body) {
659
709
  // Convert `/tests/{testId}/code` → /^\/tests\/[^/]+\/code$/
@@ -2,7 +2,7 @@
2
2
  * Error codes shared with the backend facade and the MCP plugin.
3
3
  * Must stay in sync across all three.
4
4
  */
5
- export declare const ERROR_CODES: readonly ["AUTH_REQUIRED", "AUTH_INVALID", "AUTH_FORBIDDEN", "NOT_FOUND", "VALIDATION_ERROR", "PAYLOAD_TOO_LARGE", "CONFLICT", "PRECONDITION_FAILED", "IDEMPOTENCY_BODY_MISMATCH", "RATE_LIMITED", "INSUFFICIENT_CREDITS", "FEATURE_GATED", "UNSUPPORTED", "INTERNAL", "UNAVAILABLE"];
5
+ export declare const ERROR_CODES: readonly ["AUTH_REQUIRED", "AUTH_INVALID", "AUTH_FORBIDDEN", "NOT_FOUND", "VALIDATION_ERROR", "PAYLOAD_TOO_LARGE", "CONFLICT", "PRECONDITION_FAILED", "IDEMPOTENCY_BODY_MISMATCH", "RATE_LIMITED", "INSUFFICIENT_CREDITS", "FEATURE_GATED", "AMBIGUOUS_ORG", "UNSUPPORTED", "CLIENT_TOO_OLD", "INTERNAL", "UNAVAILABLE"];
6
6
  export type ErrorCode = (typeof ERROR_CODES)[number];
7
7
  export declare function isErrorCode(value: unknown): value is ErrorCode;
8
8
  /**
@@ -15,6 +15,33 @@ export declare class CLIError extends Error {
15
15
  readonly exitCode: number;
16
16
  constructor(message: string, exitCode?: number);
17
17
  }
18
+ /**
19
+ * Termination signals with graceful handling, mapped to their conventional
20
+ * `128 + signum` exit code. sourceRef: POSIX signal numbers (SIGHUP=1,
21
+ * SIGINT=2, SIGTERM=15). Lives here (not interrupt.ts) so `InterruptError`
22
+ * needs no import cycle; `interrupt.ts` re-exports for back-compat.
23
+ */
24
+ export declare const TERMINATION_EXIT_CODES: {
25
+ readonly SIGINT: 130;
26
+ readonly SIGTERM: 143;
27
+ readonly SIGHUP: 129;
28
+ };
29
+ export type TerminationSignal = keyof typeof TERMINATION_EXIT_CODES;
30
+ /**
31
+ * User-initiated interrupt (SIGINT/SIGTERM/SIGHUP) observed while a
32
+ * graceful-detach scope (the `--wait` polling window) was armed — see
33
+ * `interrupt.ts::ShutdownController`. The `--wait` catch blocks render the
34
+ * honest partial envelope + re-attach hint, then rethrow to `index.ts`.
35
+ *
36
+ * Deliberately NOT in `ERROR_CODES` — on a signal the CLI
37
+ * exits 130/143 without consulting the error catalog. The JSON-mode stderr
38
+ * envelope uses the out-of-catalog code `"INTERRUPTED"`. Same client-local
39
+ * synthetic category as `RequestTimeoutError`.
40
+ */
41
+ export declare class InterruptError extends CLIError {
42
+ readonly signal: TerminationSignal;
43
+ constructor(signal: TerminationSignal);
44
+ }
18
45
  export declare class NotImplementedError extends CLIError {
19
46
  constructor(commandPath: string);
20
47
  }
@@ -93,6 +120,11 @@ export declare class ApiError extends CLIError {
93
120
  *
94
121
  * Use `'field'` for JSON-body paths to avoid fabricating a `--fieldName`
95
122
  * flag that doesn't exist in the CLI surface.
123
+ *
124
+ * `reason` is trailed with a period UNLESS it already ends with one — some
125
+ * call sites compose `reason` from multiple already-punctuated sentences
126
+ * (e.g. `'... Remove --target-url.'`), and unconditionally appending a
127
+ * second period produced a doubled `..` at the end of the rendered message.
96
128
  */
97
129
  export declare function localValidationError(field: string, reason: string, accepted?: unknown, kind?: 'flag' | 'field'): ApiError;
98
130
  /**
@@ -25,25 +25,40 @@ export const ERROR_CODES = [
25
25
  // "a Portal write is in flight."
26
26
  'IDEMPOTENCY_BODY_MISMATCH',
27
27
  'RATE_LIMITED',
28
- // Client-side re-map of the credits sub-case of a RATE_LIMITED envelope.
29
- // Detected when the backend returns RATE_LIMITED (HTTP 429) with a
30
- // message matching /insufficient credits/i or details.required present.
31
- // Exit 12: non-retriable — out-of-credits cannot self-heal with retries.
32
- // The genuine per-minute throttle, 60/min/key ("Run trigger rate limit exceeded")
33
- // retains code RATE_LIMITED / exit 11 / retriable.
34
- // Note: backend will emit a distinct code in a future release; this is
35
- // CLI-side detection only, bridging the gap.
28
+ // Emitted natively by the backend as HTTP 402 with `details.required` (the
29
+ // shortfall) — non-retriable, exit 12: out-of-credits cannot self-heal with
30
+ // retries. The CLI additionally re-maps the legacy credits sub-case of a
31
+ // RATE_LIMITED envelope (message matching /insufficient credits/i or
32
+ // details.required present) for older backends. The genuine per-minute
33
+ // throttle, 60/min/key ("Run trigger rate limit exceeded") retains code
34
+ // RATE_LIMITED / exit 11 / retriable.
36
35
  'INSUFFICIENT_CREDITS',
37
- // Client-side code for plan-gated features that the server silently downgrades
38
- // rather than emitting a 4xx. Used when the CLI detects a paid-tier feature was
39
- // requested but the response shows it was not applied (e.g. autoHeal: false when
40
- // autoHeal: true was sent on a Free key). This is NOT thrown as an error by
41
- // default (the command still succeeds with verbatim replay) — it is used by
42
- // callers that want to programmatically detect plan-downgrade events.
43
- // Exit code: 13 (non-retriable). Backend follow-up: emit natively from the server
44
- // so the CLI can drop the client-side detection heuristic.
36
+ // Emitted natively by the backend as a fatal HTTP 403 when a plan-gated
37
+ // feature is requested by a tier that doesn't include it (e.g. auto-auth on
38
+ // a Free-plan org). `details` carries `{feature, plan, reason: 'plan'}`;
39
+ // exit code 13 (non-retriable) — the fix is an upgrade, not a retry.
40
+ // Distinct from silent tier DOWNGRADES (a request that still succeeds with
41
+ // the feature dropped): those are surfaced via the response's advisory
42
+ // fields, not this error.
45
43
  'FEATURE_GATED',
44
+ // Client-side re-map of the org-ambiguity sub-case of a CONFLICT (409)
45
+ // envelope. Raised when a membership-key caller's testId resolves to
46
+ // projects in more than one of their organizations (uuid-derived ids
47
+ // should not normally collide, so this is pathological — a shared-id
48
+ // union-resolution edge case, not a transient snapshot race). Detected
49
+ // when the backend returns `code: "CONFLICT"` with
50
+ // `details.reason === "ambiguous_org"`. Same exit-code family as CONFLICT
51
+ // (exit 6) but kept as a distinct code — unlike a generic CONFLICT this is
52
+ // never retried (retrying resolves the same ambiguity again) and
53
+ // `details.candidates[]` needs its own rendering.
54
+ 'AMBIGUOUS_ORG',
46
55
  'UNSUPPORTED',
56
+ // The running CLI is older than the backend's minimum supported version.
57
+ // Backend emits this as HTTP 426 when version enforcement is enabled. Exit
58
+ // 14, non-retriable — a too-old client cannot self-heal by retrying; the
59
+ // user must upgrade. `nextAction` carries the upgrade instruction and
60
+ // `details` echoes { minVersion, latestVersion, yourVersion }.
61
+ 'CLIENT_TOO_OLD',
47
62
  'INTERNAL',
48
63
  'UNAVAILABLE',
49
64
  ];
@@ -69,9 +84,12 @@ export function exitCodeFor(code) {
69
84
  case 'CONFLICT':
70
85
  case 'PRECONDITION_FAILED':
71
86
  case 'IDEMPOTENCY_BODY_MISMATCH':
87
+ case 'AMBIGUOUS_ORG':
72
88
  return 6;
73
89
  case 'UNSUPPORTED':
74
90
  return 7;
91
+ case 'CLIENT_TOO_OLD':
92
+ return 14;
75
93
  case 'UNAVAILABLE':
76
94
  return 10;
77
95
  case 'RATE_LIMITED':
@@ -92,6 +110,36 @@ export class CLIError extends Error {
92
110
  this.exitCode = exitCode;
93
111
  }
94
112
  }
113
+ /**
114
+ * Termination signals with graceful handling, mapped to their conventional
115
+ * `128 + signum` exit code. sourceRef: POSIX signal numbers (SIGHUP=1,
116
+ * SIGINT=2, SIGTERM=15). Lives here (not interrupt.ts) so `InterruptError`
117
+ * needs no import cycle; `interrupt.ts` re-exports for back-compat.
118
+ */
119
+ export const TERMINATION_EXIT_CODES = {
120
+ SIGINT: 130, // 128 + 2
121
+ SIGTERM: 143, // 128 + 15
122
+ SIGHUP: 129, // 128 + 1
123
+ };
124
+ /**
125
+ * User-initiated interrupt (SIGINT/SIGTERM/SIGHUP) observed while a
126
+ * graceful-detach scope (the `--wait` polling window) was armed — see
127
+ * `interrupt.ts::ShutdownController`. The `--wait` catch blocks render the
128
+ * honest partial envelope + re-attach hint, then rethrow to `index.ts`.
129
+ *
130
+ * Deliberately NOT in `ERROR_CODES` — on a signal the CLI
131
+ * exits 130/143 without consulting the error catalog. The JSON-mode stderr
132
+ * envelope uses the out-of-catalog code `"INTERRUPTED"`. Same client-local
133
+ * synthetic category as `RequestTimeoutError`.
134
+ */
135
+ export class InterruptError extends CLIError {
136
+ signal;
137
+ constructor(signal) {
138
+ super(`Interrupted by ${signal}.`, TERMINATION_EXIT_CODES[signal]);
139
+ this.name = 'InterruptError';
140
+ this.signal = signal;
141
+ }
142
+ }
95
143
  export class NotImplementedError extends CLIError {
96
144
  constructor(commandPath) {
97
145
  super(`Command not yet implemented: ${commandPath}`, 2);
@@ -195,16 +243,22 @@ export class ApiError extends CLIError {
195
243
  *
196
244
  * Use `'field'` for JSON-body paths to avoid fabricating a `--fieldName`
197
245
  * flag that doesn't exist in the CLI surface.
246
+ *
247
+ * `reason` is trailed with a period UNLESS it already ends with one — some
248
+ * call sites compose `reason` from multiple already-punctuated sentences
249
+ * (e.g. `'... Remove --target-url.'`), and unconditionally appending a
250
+ * second period produced a doubled `..` at the end of the rendered message.
198
251
  */
199
252
  export function localValidationError(field, reason, accepted, kind = 'flag') {
200
253
  const subject = kind === 'flag'
201
254
  ? `Flag \`--${field.replace(/[A-Z]/g, ch => `-${ch.toLowerCase()}`)}\``
202
255
  : `Field \`${field}\``;
256
+ const punctuatedReason = reason.endsWith('.') ? reason : `${reason}.`;
203
257
  return ApiError.fromEnvelope({
204
258
  error: {
205
259
  code: 'VALIDATION_ERROR',
206
260
  message: 'Invalid request.',
207
- nextAction: `${subject} is invalid: ${reason}.`,
261
+ nextAction: `${subject} is invalid: ${punctuatedReason}`,
208
262
  requestId: 'local',
209
263
  details: accepted === undefined ? { field, reason } : { field, reason, accepted },
210
264
  },
@@ -260,6 +314,8 @@ function codeFromHttpStatus(status) {
260
314
  return 'VALIDATION_ERROR';
261
315
  case 401:
262
316
  return 'AUTH_INVALID';
317
+ case 402:
318
+ return 'INSUFFICIENT_CREDITS';
263
319
  case 403:
264
320
  return 'AUTH_FORBIDDEN';
265
321
  case 404:
@@ -270,6 +326,8 @@ function codeFromHttpStatus(status) {
270
326
  return 'PRECONDITION_FAILED';
271
327
  case 413:
272
328
  return 'PAYLOAD_TOO_LARGE';
329
+ case 426:
330
+ return 'CLIENT_TOO_OLD';
273
331
  case 429:
274
332
  return 'RATE_LIMITED';
275
333
  case 501:
@@ -303,6 +361,16 @@ function isInsufficientCredits(rawCode, message, details) {
303
361
  const hasCreditsMessage = /insufficient credits/i.test(message);
304
362
  return hasRequiredField || hasCreditsMessage;
305
363
  }
364
+ /**
365
+ * Detect the "ambiguous org" sub-case of a CONFLICT (409) envelope: a
366
+ * membership-key caller's testId resolved to projects in more than one of
367
+ * their organizations. `details.reason === "ambiguous_org"` is the backend's
368
+ * stable discriminator (see `CliAmbiguousTestError` server-side) — distinct
369
+ * from the default CONFLICT meaning (snapshot in flight).
370
+ */
371
+ function isAmbiguousOrgConflict(rawCode, details) {
372
+ return rawCode === 'CONFLICT' && details.reason === 'ambiguous_org';
373
+ }
306
374
  function parseEnvelopeBody(raw, httpStatus, apiUrl) {
307
375
  if (typeof raw !== 'object' || raw === null) {
308
376
  const fallbackCode = codeFromHttpStatus(httpStatus);
@@ -362,12 +430,21 @@ function parseEnvelopeBody(raw, httpStatus, apiUrl) {
362
430
  // Portal links resolve per environment from the API endpoint (dev and
363
431
  // prod portals live on different domains); unknown hosts get the route
364
432
  // only — a hardcoded domain would point at the wrong environment.
433
+ //
434
+ // V3 API keys are membership-bound: a key minted for a team org spends
435
+ // THAT org's wallet, not the holder's personal one, and there is no
436
+ // request-scoped signal here (this branch fires client-side, purely
437
+ // from the HTTP status/body) to tell which kind of key just failed. So
438
+ // this synthesized hint deliberately does NOT assert "top up your
439
+ // (personal) credits" as the only path — it offers the personal-key
440
+ // link (still correct for the common case) alongside an honest
441
+ // org-bound alternative, rather than guessing.
365
442
  const portalBase = apiUrl === undefined ? undefined : resolvePortalBase(apiUrl);
366
443
  const billingNextAction = nextAction !== ''
367
444
  ? nextAction
368
445
  : (portalBase !== undefined
369
- ? `Top up your credits at ${portalBase}/dashboard/settings/billing or upgrade your plan at ${portalBase}/pricing.`
370
- : 'Top up your credits on the portal Billing page (/dashboard/settings/billing) or upgrade your plan (/pricing).') +
446
+ ? `Top up credits at ${portalBase}/dashboard/settings/billing (personal keys) — ask an org admin if this key is organization-bound — or upgrade your plan at ${portalBase}/pricing.`
447
+ : 'Top up credits on the portal Billing page (/dashboard/settings/billing) if this is a personal key — ask an org admin if it is organization-bound — or upgrade your plan (/pricing).') +
371
448
  ' Run `testsprite usage` to check your current balance before the next run.';
372
449
  return {
373
450
  code: 'INSUFFICIENT_CREDITS',
@@ -377,6 +454,20 @@ function parseEnvelopeBody(raw, httpStatus, apiUrl) {
377
454
  details,
378
455
  };
379
456
  }
457
+ // Client-side re-map: CONFLICT with the ambiguous-org discriminator ->
458
+ // AMBIGUOUS_ORG. Same message/nextAction as the backend supplied — the
459
+ // server already writes an actionable template — but a distinct `code`
460
+ // so the retry decision (http.ts) and the candidates rendering (index.ts)
461
+ // can key off it directly instead of re-parsing `details.reason`.
462
+ if (isAmbiguousOrgConflict(rawCode, details)) {
463
+ return {
464
+ code: 'AMBIGUOUS_ORG',
465
+ message,
466
+ nextAction,
467
+ requestId,
468
+ details,
469
+ };
470
+ }
380
471
  return {
381
472
  code: rawCode,
382
473
  message,
@@ -43,6 +43,21 @@ export interface ResolverOptions {
43
43
  * Each page uses pageSize=50, so 5 pages = 250 tests scanned.
44
44
  */
45
45
  maxPages?: number;
46
+ /**
47
+ * DEV-393: the operator's pinned `failingFrontendTestId` (the static value
48
+ * from fixtures.local.json). "Freshest failed" alone is fragile in a shared
49
+ * project: any OTHER FE test that fails more recently than a dedicated,
50
+ * permanently-red fixture silently steals the slot (live-reproduced
51
+ * 2026-07-16 — a `passingFrontendTestId` fresh-run flip immediately
52
+ * outranked the dedicated fixture on `updatedAt`). When set, the pinned id
53
+ * is probed directly first (one GET /tests/{id} — immune to the maxPages
54
+ * list-scan cap); if it is currently `status:failed` it wins outright,
55
+ * regardless of timestamp. If the probe errors, the list scan below still
56
+ * prefers the pinned id when it appears among the candidates. Falls through
57
+ * to the existing freshest-wins behavior when unset or no longer failing —
58
+ * fully backward compatible.
59
+ */
60
+ preferredId?: string;
46
61
  }
47
62
  export interface ResolverResult {
48
63
  /** The resolved failing frontend test id, or null if none found. */
@@ -24,8 +24,44 @@
24
24
  * when no Failed test exists — never throws.
25
25
  */
26
26
  export async function resolveFailingFrontendTestId(opts) {
27
- const { baseUrl, apiKey, projectId, maxPages = 5 } = opts;
27
+ const { baseUrl, apiKey, projectId, maxPages = 5, preferredId } = opts;
28
28
  const fetchImpl = opts.fetchImpl ?? fetch;
29
+ // DEV-393 (codex F3): probe the pinned fixture directly first, so the
30
+ // preference cannot be defeated by the maxPages list-scan cap (a pinned
31
+ // fixture beyond page `maxPages` would otherwise silently lose the slot to
32
+ // an incidental fresher failure). Any probe error or non-failed status
33
+ // falls through to the list scan; the in-candidates preference there
34
+ // remains as a second chance after a transient probe failure.
35
+ if (preferredId) {
36
+ try {
37
+ const resp = await fetchImpl(`${baseUrl}/tests/${encodeURIComponent(preferredId)}`, {
38
+ headers: {
39
+ 'x-api-key': apiKey,
40
+ 'x-request-id': `dev-e2e-resolver-preferred-${Date.now()}`,
41
+ accept: 'application/json',
42
+ },
43
+ signal: AbortSignal.timeout(10_000),
44
+ });
45
+ if (resp.ok) {
46
+ const test = (await resp.json());
47
+ // The probe must honor the resolver's project scope (codex round 2):
48
+ // the list path filters by projectId server-side, so a pin that
49
+ // points at a failed FE test in a DIFFERENT project must not win
50
+ // here either. A response without a matching projectId (absent or
51
+ // mismatched) falls through to the project-scoped list scan.
52
+ if (test.type === 'frontend' && test.status === 'failed' && test.projectId === projectId) {
53
+ return {
54
+ testId: preferredId,
55
+ reason: `Preferred pinned failingFrontendTestId (${preferredId}) confirmed status:failed ` +
56
+ `via direct GET (updatedAt=${test.updatedAt ?? 'unknown'}); list scan skipped`,
57
+ };
58
+ }
59
+ }
60
+ }
61
+ catch {
62
+ // Transient probe failure — fall through to the list scan below.
63
+ }
64
+ }
29
65
  const candidates = [];
30
66
  let cursor;
31
67
  let pagesFetched = 0;
@@ -82,6 +118,18 @@ export async function resolveFailingFrontendTestId(opts) {
82
118
  reason: 'No frontend tests with status=failed found in project; falling back to static fixture',
83
119
  };
84
120
  }
121
+ // DEV-393: a pinned, dedicated "always red" fixture wins over freshest
122
+ // whenever it is still in the failed set — see the doc comment on
123
+ // ResolverOptions.preferredId for why "freshest" alone is not enough.
124
+ if (preferredId) {
125
+ const pinned = candidates.find(c => c.id === preferredId);
126
+ if (pinned) {
127
+ return {
128
+ testId: pinned.id,
129
+ reason: `Preferred pinned failingFrontendTestId (${pinned.id}) is still status:failed (updatedAt=${pinned.updatedAt}); took priority over freshest-updatedAt candidate`,
130
+ };
131
+ }
132
+ }
85
133
  // Pick the most recently updated candidate — freshest failure is the
86
134
  // most likely to have a valid failure bundle attached.
87
135
  candidates.sort((a, b) => {