@testsprite/testsprite-cli 0.12.0 → 0.14.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 (113) hide show
  1. package/README.md +59 -49
  2. package/dist/commands/agent.js +16 -13
  3. package/dist/commands/auth.d.ts +19 -0
  4. package/dist/commands/auth.js +60 -24
  5. package/dist/commands/ci.d.ts +86 -1
  6. package/dist/commands/ci.js +436 -5
  7. package/dist/commands/doctor.d.ts +2 -0
  8. package/dist/commands/doctor.js +34 -20
  9. package/dist/commands/init.js +14 -11
  10. package/dist/commands/project-env.d.ts +11 -1
  11. package/dist/commands/project-env.js +408 -70
  12. package/dist/commands/project-sign-in.d.ts +60 -0
  13. package/dist/commands/project-sign-in.js +289 -0
  14. package/dist/commands/project.d.ts +14 -5
  15. package/dist/commands/project.js +110 -70
  16. package/dist/commands/schedule.d.ts +14 -0
  17. package/dist/commands/schedule.js +193 -15
  18. package/dist/commands/test.d.ts +123 -44
  19. package/dist/commands/test.js +2993 -636
  20. package/dist/commands/testlist.d.ts +10 -5
  21. package/dist/commands/testlist.js +217 -47
  22. package/dist/commands/tunnel.d.ts +26 -3
  23. package/dist/commands/tunnel.js +221 -18
  24. package/dist/commands/usage.d.ts +3 -0
  25. package/dist/commands/usage.js +12 -5
  26. package/dist/index.js +39 -50
  27. package/dist/lib/agent-targets.d.ts +3 -3
  28. package/dist/lib/agent-targets.js +2 -2
  29. package/dist/lib/billing-refusal.d.ts +43 -0
  30. package/dist/lib/billing-refusal.js +171 -0
  31. package/dist/lib/bundle.d.ts +5 -0
  32. package/dist/lib/bundle.js +43 -13
  33. package/dist/lib/ci-linkage.d.ts +90 -0
  34. package/dist/lib/ci-linkage.js +181 -0
  35. package/dist/lib/client-factory.d.ts +16 -2
  36. package/dist/lib/client-factory.js +37 -6
  37. package/dist/lib/config.d.ts +17 -0
  38. package/dist/lib/config.js +20 -1
  39. package/dist/lib/conflict-reason.d.ts +27 -3
  40. package/dist/lib/conflict-reason.js +53 -4
  41. package/dist/lib/credentials.js +56 -14
  42. package/dist/lib/dry-run/samples.d.ts +13 -1
  43. package/dist/lib/dry-run/samples.js +104 -7
  44. package/dist/lib/environment-tunnel.d.ts +109 -0
  45. package/dist/lib/environment-tunnel.js +465 -0
  46. package/dist/lib/errors.d.ts +18 -11
  47. package/dist/lib/errors.js +123 -14
  48. package/dist/lib/failing-fe-resolver.d.ts +1 -1
  49. package/dist/lib/failing-fe-resolver.js +3 -3
  50. package/dist/lib/gh-output.d.ts +1 -0
  51. package/dist/lib/gh-output.js +16 -4
  52. package/dist/lib/history-retention.d.ts +8 -0
  53. package/dist/lib/history-retention.js +24 -0
  54. package/dist/lib/http.d.ts +39 -19
  55. package/dist/lib/http.js +46 -24
  56. package/dist/lib/interrupt.d.ts +21 -13
  57. package/dist/lib/interrupt.js +32 -21
  58. package/dist/lib/junit-report.d.ts +18 -4
  59. package/dist/lib/junit-report.js +23 -5
  60. package/dist/lib/local-target.d.ts +14 -4
  61. package/dist/lib/local-target.js +48 -13
  62. package/dist/lib/output.js +15 -1
  63. package/dist/lib/plan-poll.d.ts +11 -11
  64. package/dist/lib/plan-poll.js +15 -16
  65. package/dist/lib/plans.types.d.ts +9 -9
  66. package/dist/lib/plans.types.js +3 -3
  67. package/dist/lib/poll.d.ts +2 -2
  68. package/dist/lib/poll.js +9 -3
  69. package/dist/lib/redact.d.ts +38 -0
  70. package/dist/lib/redact.js +140 -0
  71. package/dist/lib/render-error.d.ts +21 -5
  72. package/dist/lib/render-error.js +44 -0
  73. package/dist/lib/response-schemas.d.ts +54 -12
  74. package/dist/lib/response-schemas.js +88 -7
  75. package/dist/lib/runs.types.d.ts +68 -11
  76. package/dist/lib/secret-file.js +72 -14
  77. package/dist/lib/skill-nudge.d.ts +6 -1
  78. package/dist/lib/skill-nudge.js +32 -5
  79. package/dist/lib/target-url-preflight.d.ts +6 -4
  80. package/dist/lib/target-url-preflight.js +64 -51
  81. package/dist/lib/target-url.js +11 -11
  82. package/dist/lib/telemetry.d.ts +10 -8
  83. package/dist/lib/telemetry.js +24 -17
  84. package/dist/lib/testlist.types.d.ts +1 -0
  85. package/dist/lib/ticker.d.ts +9 -0
  86. package/dist/lib/ticker.js +111 -4
  87. package/dist/lib/tunnel-session.d.ts +16 -4
  88. package/dist/lib/tunnel-session.js +7 -5
  89. package/dist/lib/tunnel.types.d.ts +12 -2
  90. package/dist/lib/tunnel.types.js +2 -2
  91. package/dist/lib/v3-advisory.js +0 -1
  92. package/dist/lib/wait-exit.d.ts +8 -0
  93. package/dist/lib/wait-exit.js +76 -4
  94. package/dist/lib/workspace-status.d.ts +23 -0
  95. package/dist/lib/workspace-status.js +15 -0
  96. package/dist/vendor/tunnel-client/client.d.ts +15 -8
  97. package/dist/vendor/tunnel-client/client.js +477 -407
  98. package/dist/vendor/tunnel-client/config.d.ts +5 -5
  99. package/dist/vendor/tunnel-client/config.js +5 -5
  100. package/dist/vendor/tunnel-client/index.d.ts +4 -4
  101. package/dist/vendor/tunnel-client/index.js +4 -4
  102. package/dist/vendor/tunnel-client/types.d.ts +19 -34
  103. package/dist/vendor/tunnel-client/types.js +1 -0
  104. package/dist/vendor/tunnel-client/ws-compat.d.ts +13 -3
  105. package/dist/vendor/tunnel-client/ws-compat.js +70 -12
  106. package/dist/version-guard.d.ts +7 -1
  107. package/dist/version-guard.js +19 -1
  108. package/dist/version.d.ts +1 -1
  109. package/dist/version.js +1 -1
  110. package/package.json +4 -4
  111. package/skills/testsprite-onboard.skill.md +8 -8
  112. package/skills/testsprite-verify.codex.md +59 -57
  113. package/skills/testsprite-verify.skill.md +53 -38
@@ -1,3 +1,34 @@
1
+ /**
2
+ * Build the `INTERRUPTED` envelope from whatever the interrupted command
3
+ * attached to the error. A tunnel run attaches `tunnelDetach` and
4
+ * `test plan generate` attaches `planDetach`; each carries its own
5
+ * `nextAction` so the envelope never contradicts the text line the catch
6
+ * block already printed. Otherwise a run wait gets the run-detach story
7
+ * (`test wait`) and any other request gets the generic check-state hint.
8
+ */
9
+ export function buildInterruptEnvelope(err) {
10
+ const { tunnelDetach, planDetach } = err;
11
+ const nextAction = tunnelDetach?.nextAction ??
12
+ planDetach?.nextAction ??
13
+ (err.runWaitContext
14
+ ? 'The server-side run (if any) keeps executing and billing. ' +
15
+ 'Re-attach with: testsprite test wait <runId>, or stop it with: testsprite test cancel <runId> ' +
16
+ '(runId is in the partial JSON on stdout).'
17
+ : 'The request was interrupted. Check the current state before retrying; ' +
18
+ 'a multi-item command may have processed some items.');
19
+ const details = { signal: err.signal };
20
+ if (tunnelDetach) {
21
+ details.runId = tunnelDetach.runId;
22
+ details.cancelOutcome = tunnelDetach.cancel;
23
+ }
24
+ else if (planDetach) {
25
+ details.projectId = planDetach.projectId;
26
+ details.stagesRemaining = planDetach.stagesRemaining;
27
+ }
28
+ return {
29
+ error: { code: 'INTERRUPTED', message: err.message, nextAction, requestId: 'local', details },
30
+ };
31
+ }
1
32
  /**
2
33
  * Global flags that belong before the subcommand, not after it.
3
34
  *
@@ -80,6 +111,19 @@ export function renderAmbiguousOrgCandidates(candidates) {
80
111
  lines.push(' hint: re-run with --project <id> to disambiguate.');
81
112
  return lines;
82
113
  }
114
+ /** Text-mode recovery handles for the account's tunnel binding limit. */
115
+ export function renderTunnelBindingLimitIds(details) {
116
+ if (!Array.isArray(details))
117
+ return [];
118
+ const ids = details.filter((value) => typeof value === 'string');
119
+ if (ids.length === 0)
120
+ return [];
121
+ const lines = ids.slice(0, 20).map(id => ` tunnel: ${id}`);
122
+ if (ids.length > 20)
123
+ lines.push(` … and ${ids.length - 20} more`);
124
+ lines.push(' hint: testsprite tunnel list · testsprite tunnel stop <client-id> · testsprite tunnel stop --all --confirm');
125
+ return lines;
126
+ }
83
127
  export function rephraseUnknownOption(raw) {
84
128
  // Commander emits: "error: unknown option '--foo'"
85
129
  const match = /unknown option\s+'--([^']+)'/.exec(raw);
@@ -1,14 +1,15 @@
1
1
  /**
2
- * Valibot schemas for the run-path wire shapes (issue #102).
2
+ * Valibot schemas for the API wire shapes (issue #102, extended by #277).
3
3
  *
4
4
  * `requestWithMeta` used to return `(await response.json()) as T` with zero
5
5
  * runtime validation, so a drifted or partial server response surfaced as
6
6
  * `undefined` output or an opaque TypeError deep inside a command. These
7
7
  * schemas are wired (opt-in, via `RequestOptions.schema`) into the typed
8
- * HttpClient helpers only: `triggerRun`, `triggerRunWithMeta`, `triggerRerun`,
8
+ * HttpClient helpers `triggerRun`, `triggerRunWithMeta`, `triggerRerun`,
9
9
  * `triggerBatchRerun`, `triggerBatchRunFresh`, `getRun`, `listTestRuns`,
10
- * `cancelRun`.
11
- * The generic `get`/`post`/`put`/`patch`/`delete` paths stay schema-free.
10
+ * `cancelRun`, and — for the account surfaces below — the `client.get` call
11
+ * sites that own a `/me` or usage read. Every other generic
12
+ * `get`/`post`/`put`/`patch`/`delete` caller stays schema-free and opt-in.
12
13
  *
13
14
  * Resilience rules (additive server changes must never hard-fail the CLI):
14
15
  *
@@ -33,9 +34,11 @@
33
34
  * interface it mirrors, so schema/interface drift fails `tsc` in this file.
34
35
  */
35
36
  import * as v from 'valibot';
37
+ import type { MeResponse } from '../commands/auth.js';
38
+ import type { UsageResponse } from '../commands/usage.js';
36
39
  import type { BatchRerunResponse, BatchRunFreshResponse, CancelRunResponse, ListRunsResponse, RerunResponse, RunResponse, TriggerRunResponse } from './runs.types.js';
37
40
  import type { CliTestListRunResponse } from './testlist.types.js';
38
- import type { TunnelMintResponse, TunnelStatusResponse } from './tunnel.types.js';
41
+ import type { TunnelListResponse, TunnelMintResponse, TunnelStatusResponse } from './tunnel.types.js';
39
42
  /** Mirrors `RunResponse` (runs.types.ts): `GET /api/cli/v1/runs/{runId}`. */
40
43
  export declare const RUN_RESPONSE_SCHEMA: v.GenericSchema<unknown, RunResponse>;
41
44
  /** Mirrors `CancelRunResponse` (runs.types.ts): the run envelope plus cancel metadata. */
@@ -57,17 +60,23 @@ export declare const TESTLIST_RUN_RESPONSE_SCHEMA: v.GenericSchema<unknown, CliT
57
60
  /** Mirrors `ListRunsResponse` (runs.types.ts): `GET /tests/{testId}/runs`. */
58
61
  export declare const LIST_RUNS_RESPONSE_SCHEMA: v.GenericSchema<unknown, ListRunsResponse>;
59
62
  /**
60
- * Minimal `/me` identity core shared by its consumers. `doctor` reads a
61
- * two-field optional projection (`MeIdentity` in commands/doctor.ts) while
62
- * `auth whoami` reads the full `MeResponse` (commands/auth.ts); this schema
63
- * validates the common identity core so it can guard either caller, and
64
- * `looseObject` lets the full projection (scopes, env, email, ...) pass
65
- * through untouched. Not wired into any typed helper yet: `/me` callers use
66
- * the generic `get`, which stays schema-free in this change.
63
+ * Minimal `/me` identity core, as read by `doctor`'s connectivity check.
64
+ *
65
+ * `doctor` deliberately treats every field as optional: the check only needs
66
+ * "the key was accepted", and it decorates the detail line with the userId
67
+ * *when present* (`me.userId ? ...`). Fixture evidence for keeping it fully
68
+ * optional rather than reusing {@link ME_RESPONSE_SCHEMA}: `OK_ME` in
69
+ * `commands/doctor.test.ts` is `{ userId, keyId }` with no `scopes`/`env`, and
70
+ * a connectivity probe must not fail on a partial identity projection.
71
+ *
72
+ * `commands/doctor.ts` aliases its `MeIdentity` to this type so the two cannot
73
+ * drift (they already had: `v3Enabled` existed on the command side only).
67
74
  */
68
75
  export interface MeIdentityWire {
69
76
  userId?: string;
70
77
  keyId?: string;
78
+ /** Authoritative per-user V3 routing bit; older backends omit it. */
79
+ v3Enabled?: boolean;
71
80
  /**
72
81
  * Account-wide organization membership list (mirrors `CliOrgSummary` in
73
82
  * `lib/org-render.ts`). Optional/absent-safe: omitted on a server-side
@@ -92,6 +101,37 @@ export interface MeIdentityWire {
92
101
  }
93
102
  /** Mirrors `MeIdentity` (commands/doctor.ts): `GET /api/cli/v1/me` core. */
94
103
  export declare const ME_IDENTITY_SCHEMA: v.GenericSchema<unknown, MeIdentityWire>;
104
+ /**
105
+ * Mirrors `MeResponse` (commands/auth.ts): the full `GET /me` projection read
106
+ * by `auth whoami` (and, through it, `init`).
107
+ *
108
+ * `scopes` is required and array-typed on purpose — this is the shape drift
109
+ * that actually bites today. `runWhoami` renders `m.scopes.join(', ')` and
110
+ * computes `missingScopes` via `m.scopes.includes(...)` with no guard, so a
111
+ * `/me` body without `scopes` crashes with a raw `TypeError` (exit 1) instead
112
+ * of a typed envelope. Every `/me` fixture in the suite supplies it
113
+ * (`auth.test.ts`, `init.test.ts`, `usage.test.ts`, `cli.subprocess.test.ts`,
114
+ * `test/mock-backend/fixtures.ts`), so requiring it matches observed wire
115
+ * reality; `email` / `displayName` / `v3Enabled` are the genuinely absent-safe
116
+ * ones and stay `v.optional` with no default (rule 3, optional branch).
117
+ *
118
+ * `init` calls this through `runWhoami` inside a try/catch that falls back to
119
+ * a placeholder identity, so a drifted `/me` degrades the setup summary
120
+ * instead of failing the whole `init`.
121
+ */
122
+ export declare const ME_RESPONSE_SCHEMA: v.GenericSchema<unknown, MeResponse>;
123
+ /**
124
+ * Mirrors `UsageResponse` (commands/usage.ts): the credits/plan projection the
125
+ * `usage` command reads off the same `GET /me` body.
126
+ *
127
+ * `renderUsage` prints `userId`/`keyId`/`env` unconditionally as its "identity
128
+ * block", so those three are required; `credits`, `subPlan` and
129
+ * `creditsPerRun` are forward-compat fields the backend does not send today
130
+ * (see the BACKEND FOLLOW-UP note in usage.ts) and every renderer branch is
131
+ * gated on `!== undefined`, so they stay optional with no default. `scopes`
132
+ * rides along as an unknown extra key and is preserved by `looseObject`.
133
+ */
134
+ export declare const USAGE_RESPONSE_SCHEMA: v.GenericSchema<unknown, UsageResponse>;
95
135
  /**
96
136
  * Mirrors `TunnelMintResponse` (tunnel.types.ts): `POST /tunnel`.
97
137
  *
@@ -104,3 +144,5 @@ export declare const ME_IDENTITY_SCHEMA: v.GenericSchema<unknown, MeIdentityWire
104
144
  export declare const TUNNEL_MINT_RESPONSE_SCHEMA: v.GenericSchema<unknown, TunnelMintResponse>;
105
145
  /** Mirrors `TunnelStatusResponse` (tunnel.types.ts): `GET /tunnel/{clientId}`. */
106
146
  export declare const TUNNEL_STATUS_RESPONSE_SCHEMA: v.GenericSchema<unknown, TunnelStatusResponse>;
147
+ /** Mirrors `TunnelListResponse`: a server may add status values or omit creation time. */
148
+ export declare const TUNNEL_LIST_RESPONSE_SCHEMA: v.GenericSchema<unknown, TunnelListResponse>;
@@ -1,14 +1,15 @@
1
1
  /**
2
- * Valibot schemas for the run-path wire shapes (issue #102).
2
+ * Valibot schemas for the API wire shapes (issue #102, extended by #277).
3
3
  *
4
4
  * `requestWithMeta` used to return `(await response.json()) as T` with zero
5
5
  * runtime validation, so a drifted or partial server response surfaced as
6
6
  * `undefined` output or an opaque TypeError deep inside a command. These
7
7
  * schemas are wired (opt-in, via `RequestOptions.schema`) into the typed
8
- * HttpClient helpers only: `triggerRun`, `triggerRunWithMeta`, `triggerRerun`,
8
+ * HttpClient helpers `triggerRun`, `triggerRunWithMeta`, `triggerRerun`,
9
9
  * `triggerBatchRerun`, `triggerBatchRunFresh`, `getRun`, `listTestRuns`,
10
- * `cancelRun`.
11
- * The generic `get`/`post`/`put`/`patch`/`delete` paths stay schema-free.
10
+ * `cancelRun`, and — for the account surfaces below — the `client.get` call
11
+ * sites that own a `/me` or usage read. Every other generic
12
+ * `get`/`post`/`put`/`patch`/`delete` caller stays schema-free and opt-in.
12
13
  *
13
14
  * Resilience rules (additive server changes must never hard-fail the CLI):
14
15
  *
@@ -175,6 +176,12 @@ export const TRIGGER_RUN_RESPONSE_SCHEMA = v.looseObject({
175
176
  enqueuedAt: v.string(),
176
177
  codeVersion: v.string(),
177
178
  targetUrl: v.string(),
179
+ // Optional with NO default (rule 3). The default must stay
180
+ // absent: `undefined` here means "this backend predates the field and
181
+ // stripped what we sent", which is precisely what the opt-out advisory
182
+ // keys on. Defaulting it to `false` would make an old backend look like
183
+ // it had honoured `--no-auto-heal`.
184
+ autoHeal: v.optional(v.boolean()),
178
185
  // The run's environment — optional with no default (rule 3, optional branch).
179
186
  environment: OPTIONAL_ENVIRONMENT_SCHEMA,
180
187
  // Server-built portal links (backend ≥ the run-links change). Optional
@@ -239,8 +246,15 @@ export const BATCH_RERUN_RESPONSE_SCHEMA = v.looseObject({
239
246
  accepted: v.array(v.looseObject({ testId: v.string(), runId: v.string(), enqueuedAt: v.string() })),
240
247
  // Mirrors BatchRerunDeferred (runs.types.ts).
241
248
  deferred: v.array(v.looseObject({ testId: v.string(), reason: v.string() })),
242
- // Mirrors BatchRerunConflict (runs.types.ts).
243
- conflicts: v.array(v.looseObject({ testId: v.string(), currentRunId: v.string() })),
249
+ // Mirrors BatchRerunConflict (runs.types.ts). `currentRunId` is optional,
250
+ // as in the two schemas below: a refusal only carries a run id when there
251
+ // is a run to point at.
252
+ conflicts: v.array(v.looseObject({
253
+ testId: v.string(),
254
+ currentRunId: v.optional(v.string()),
255
+ reason: v.optional(v.string()),
256
+ message: v.optional(v.string()),
257
+ })),
244
258
  // Mirrors BatchRerunClosure / BatchRerunClosureByProject (runs.types.ts).
245
259
  closure: v.looseObject({
246
260
  byProject: v.array(v.looseObject({
@@ -263,6 +277,8 @@ export const BATCH_RERUN_RESPONSE_SCHEMA = v.looseObject({
263
277
  // ---------------------------------------------------------------------------
264
278
  /** Mirrors `BatchRunFreshResponse` (runs.types.ts): `POST /tests/batch/run`. */
265
279
  export const BATCH_RUN_FRESH_RESPONSE_SCHEMA = v.looseObject({
280
+ // See TRIGGER_RUN_RESPONSE_SCHEMA; absence carries the same meaning.
281
+ autoHeal: v.optional(v.boolean()),
266
282
  // Mirrors BatchRunFreshAccepted (runs.types.ts); dashboardUrl is
267
283
  // client-synthesized, tolerated as optional.
268
284
  accepted: v.array(v.looseObject({
@@ -285,6 +301,8 @@ export const BATCH_RUN_FRESH_RESPONSE_SCHEMA = v.looseObject({
285
301
  // keeps computing its legacy template for an older backend / the V2 engine;
286
302
  // `null` passes through as a present key meaning "no correct page".
287
303
  dashboardUrl: v.nullish(v.string(), undefined),
304
+ // An exact echo confirms that the backend read the target URL override.
305
+ targetUrl: v.optional(v.string()),
288
306
  });
289
307
  /**
290
308
  * `POST /api/cli/v1/testlist/{listId}/run`. Mirrors the batch-run-fresh shape so
@@ -337,6 +355,10 @@ export const LIST_RUNS_RESPONSE_SCHEMA = v.looseObject({
337
355
  historyStartsAt: v.optional(v.string()),
338
356
  note: v.optional(v.string()),
339
357
  portalUrl: v.optional(v.string()),
358
+ tier: v.optional(v.string()),
359
+ retentionDays: v.optional(v.nullable(v.number())),
360
+ hiddenCount: v.optional(v.number()),
361
+ billingUrl: v.optional(v.string()),
340
362
  }),
341
363
  });
342
364
  /** Mirrors `CliOrgSummary` (lib/org-render.ts): one `Me.organizations[]` entry. */
@@ -356,11 +378,61 @@ const ORG_BINDING_SCHEMA = v.looseObject({
356
378
  export const ME_IDENTITY_SCHEMA = v.looseObject({
357
379
  userId: v.optional(v.string()),
358
380
  keyId: v.optional(v.string()),
381
+ v3Enabled: v.optional(v.boolean()),
359
382
  organizations: v.optional(v.array(ORG_SUMMARY_SCHEMA)),
360
383
  org: v.optional(ORG_BINDING_SCHEMA),
361
384
  });
385
+ /**
386
+ * Mirrors `MeResponse` (commands/auth.ts): the full `GET /me` projection read
387
+ * by `auth whoami` (and, through it, `init`).
388
+ *
389
+ * `scopes` is required and array-typed on purpose — this is the shape drift
390
+ * that actually bites today. `runWhoami` renders `m.scopes.join(', ')` and
391
+ * computes `missingScopes` via `m.scopes.includes(...)` with no guard, so a
392
+ * `/me` body without `scopes` crashes with a raw `TypeError` (exit 1) instead
393
+ * of a typed envelope. Every `/me` fixture in the suite supplies it
394
+ * (`auth.test.ts`, `init.test.ts`, `usage.test.ts`, `cli.subprocess.test.ts`,
395
+ * `test/mock-backend/fixtures.ts`), so requiring it matches observed wire
396
+ * reality; `email` / `displayName` / `v3Enabled` are the genuinely absent-safe
397
+ * ones and stay `v.optional` with no default (rule 3, optional branch).
398
+ *
399
+ * `init` calls this through `runWhoami` inside a try/catch that falls back to
400
+ * a placeholder identity, so a drifted `/me` degrades the setup summary
401
+ * instead of failing the whole `init`.
402
+ */
403
+ export const ME_RESPONSE_SCHEMA = v.looseObject({
404
+ userId: v.string(),
405
+ keyId: v.string(),
406
+ scopes: v.array(v.string()),
407
+ env: openWireLiteral(),
408
+ email: v.optional(v.string()),
409
+ displayName: v.optional(v.string()),
410
+ v3Enabled: v.optional(v.boolean()),
411
+ });
412
+ // ---------------------------------------------------------------------------
413
+ // GET /me (usage projection)
414
+ // ---------------------------------------------------------------------------
415
+ /**
416
+ * Mirrors `UsageResponse` (commands/usage.ts): the credits/plan projection the
417
+ * `usage` command reads off the same `GET /me` body.
418
+ *
419
+ * `renderUsage` prints `userId`/`keyId`/`env` unconditionally as its "identity
420
+ * block", so those three are required; `credits`, `subPlan` and
421
+ * `creditsPerRun` are forward-compat fields the backend does not send today
422
+ * (see the BACKEND FOLLOW-UP note in usage.ts) and every renderer branch is
423
+ * gated on `!== undefined`, so they stay optional with no default. `scopes`
424
+ * rides along as an unknown extra key and is preserved by `looseObject`.
425
+ */
426
+ export const USAGE_RESPONSE_SCHEMA = v.looseObject({
427
+ userId: v.string(),
428
+ keyId: v.string(),
429
+ env: openWireLiteral(),
430
+ credits: v.optional(v.number()),
431
+ subPlan: v.optional(v.string()),
432
+ creditsPerRun: v.optional(v.number()),
433
+ });
362
434
  // ---------------------------------------------------------------------------
363
- // /tunnel — DEV-747 piece 1 facade
435
+ // /tunnel facade
364
436
  // ---------------------------------------------------------------------------
365
437
  /**
366
438
  * Mirrors `TunnelMintResponse` (tunnel.types.ts): `POST /tunnel`.
@@ -385,4 +457,13 @@ export const TUNNEL_STATUS_RESPONSE_SCHEMA = v.looseObject({
385
457
  status: openWireLiteral(),
386
458
  expiresAt: v.string(),
387
459
  });
460
+ /** Mirrors `TunnelListResponse`: a server may add status values or omit creation time. */
461
+ export const TUNNEL_LIST_RESPONSE_SCHEMA = v.looseObject({
462
+ tunnels: v.array(v.looseObject({
463
+ clientId: v.string(),
464
+ status: openWireLiteral(),
465
+ expiresAt: v.string(),
466
+ createdAt: v.optional(v.nullable(v.string())),
467
+ })),
468
+ });
388
469
  //# sourceMappingURL=response-schemas.js.map
@@ -4,7 +4,7 @@
4
4
  * Extended by M3.4 piece-5 — `test result --history` command.
5
5
 
6
6
  */
7
- import type { RunConflict } from './conflict-reason.js';
7
+ import type { ConflictReason, RunConflict } from './conflict-reason.js';
8
8
  /** Literal body sent to `POST /api/cli/v1/tests/{testId}/runs`. */
9
9
  export interface TriggerRunBody {
10
10
  /** Fixed source literal for CLI-triggered runs. */
@@ -12,7 +12,7 @@ export interface TriggerRunBody {
12
12
  /** Optional override for the project's configured target URL. */
13
13
  targetUrl?: string;
14
14
  /**
15
- * DEV-747: id of a tunnel client minted through `POST /api/cli/v1/tunnel`.
15
+ * Id of a tunnel client minted through `POST /api/cli/v1/tunnel`.
16
16
  *
17
17
  * An ID, never a proxy string — the caller does not choose the proxy host.
18
18
  * The server loads the binding, checks it belongs to the calling principal
@@ -23,11 +23,26 @@ export interface TriggerRunBody {
23
23
  */
24
24
  tunnelClientId?: string;
25
25
  /**
26
- * DEV-1305: the NAME of the project environment whose credentials, auto-auth
27
- * and OTP settings this run should use (`unique(project_id, name)` server
28
- * side). Absent → the project's default environment, exactly as before.
29
- * Composes with `targetUrl`/`tunnelClientId`: those pick WHERE the browser
30
- * goes, this picks WHOSE credentials it logs in with.
26
+ * May the agent re-author this test when its stored code no longer
27
+ * executes?
28
+ *
29
+ * OMITTED on purpose whenever auto-heal is on. The field is tri-state on the
30
+ * wire and the CLI only ever sends one of its three states: `false`, for
31
+ * `--no-auto-heal`. Absent means "heal, but replay a user-authored body
32
+ * rather than rewriting it" — the server-side default — and sending an
33
+ * explicit `true` would mean something DIFFERENT and worse here: an
34
+ * unconditional heal that re-authors code the user wrote. So the default is
35
+ * expressed by saying nothing, which also means an older backend (the field
36
+ * is stripped by `whitelist: true`, never 400'd) behaves exactly as it does
37
+ * today for the default case.
38
+ */
39
+ autoHeal?: false;
40
+ /**
41
+ * The NAME of the project environment whose credentials, auto-auth and OTP
42
+ * settings this run should use (`unique(project_id, name)` server side).
43
+ * Absent → the project's default environment, exactly as before. Composes
44
+ * with `targetUrl`/`tunnelClientId`: those pick WHERE the browser goes,
45
+ * this picks WHOSE credentials it logs in with.
31
46
  */
32
47
  environment?: string;
33
48
  }
@@ -40,10 +55,13 @@ export interface RunEnvironmentRef {
40
55
  }
41
56
  /**
42
57
  * Body sent to `POST /api/cli/v1/tests/{testId}/runs/rerun`.
43
- * No `targetUrl` — rerun replays against the project's configured URL.
58
+ * Tunnel replay includes the saved environment URL verbatim; ordinary replay
59
+ * uses the configured URL.
44
60
  * `source` must be "cli" (not "cli-rerun" — that is not a valid RUN_SOURCES value).
45
61
  */
46
62
  export interface RerunRequest {
63
+ tunnelClientId?: string;
64
+ targetUrl?: string;
47
65
  source: 'cli';
48
66
  /** Opt into AI heal-on-drift. Paid + FE only. Server tier-gates and echoes effective value. */
49
67
  autoHeal?: boolean;
@@ -86,6 +104,7 @@ export interface RerunAdvisory {
86
104
  * `runId` is always non-null (minted synchronously before async invoke).
87
105
  */
88
106
  export interface RerunResponse {
107
+ tunnelClientId?: string;
89
108
  /** The named test's runId (minted synchronously before async Lambda invoke). */
90
109
  runId: string;
91
110
  status: 'queued';
@@ -116,6 +135,8 @@ export interface RerunResponse {
116
135
  * Mixed FE/BE testIds allowed; BE closure deduped server-side per project.
117
136
  */
118
137
  export interface BatchRerunRequest {
138
+ tunnelClientId?: string;
139
+ targetUrl?: string;
119
140
  source: 'cli';
120
141
  testIds: string[];
121
142
  autoHeal?: boolean;
@@ -135,10 +156,17 @@ export interface BatchRerunDeferred {
135
156
  testId: string;
136
157
  reason: string;
137
158
  }
138
- /** One conflicted (already in-flight) testId in the batch rerun response. */
159
+ /**
160
+ * One testId in the batch rerun response that did not dispatch.
161
+ *
162
+ * `currentRunId` is present only when the refusal points at a run already in
163
+ * flight; otherwise `reason` says why it did not start.
164
+ */
139
165
  export interface BatchRerunConflict {
140
166
  testId: string;
141
- currentRunId: string;
167
+ currentRunId?: string;
168
+ reason?: ConflictReason;
169
+ message?: string;
142
170
  }
143
171
  /** Per-project closure summary in the batch rerun response. */
144
172
  export interface BatchRerunClosureByProject {
@@ -166,6 +194,7 @@ export interface BatchRerunClosure {
166
194
  * chunked dispatch requests (see `dedupeRerunAdvisories` in `commands/test.ts`).
167
195
  */
168
196
  export interface BatchRerunResponse {
197
+ tunnelClientId?: string;
169
198
  accepted: BatchRerunAccepted[];
170
199
  deferred: BatchRerunDeferred[];
171
200
  conflicts: BatchRerunConflict[];
@@ -178,9 +207,20 @@ export interface BatchRerunResponse {
178
207
  * All fields are stamped at trigger time and cannot change for this runId.
179
208
  */
180
209
  export interface TriggerRunResponse {
210
+ tunnelClientId?: string;
181
211
  runId: string;
182
212
  status: 'queued';
183
213
  enqueuedAt: string;
214
+ /**
215
+ * The EFFECTIVE heal decision the server made for this run.
216
+ *
217
+ * OPTIONAL on purpose, and the absence is the load-bearing case: the backend
218
+ * runs `whitelist: true`, so a CLI sending `autoHeal` to a server that
219
+ * predates the field has it silently STRIPPED and the run heals anyway. An
220
+ * absent echo is how the CLI learns it is talking to such a server and that
221
+ * `--no-auto-heal` did nothing — without it the opt-out is unfalsifiable.
222
+ */
223
+ autoHeal?: boolean;
184
224
  /** codeVersion resolved at trigger time from the test row. */
185
225
  codeVersion: string;
186
226
  /** Resolved target URL (project default when --target-url absent). */
@@ -409,6 +449,11 @@ export interface RunHistoryMeta {
409
449
  note?: string;
410
450
  /** Portal URL where older run history can be viewed. */
411
451
  portalUrl?: string;
452
+ /** Plan-limited history details; absent on older backends and V2. */
453
+ tier?: string;
454
+ retentionDays?: number | null;
455
+ hiddenCount?: number;
456
+ billingUrl?: string;
412
457
  }
413
458
  /**
414
459
  * Response from `GET /api/cli/v1/tests/{testId}/runs`.
@@ -429,7 +474,7 @@ export interface ListRunsQuery {
429
474
  source?: RunSource;
430
475
  /** ISO timestamp (after client-side duration parsing). */
431
476
  since?: string;
432
- /** DEV-1306: only runs whose credentials came from this environment (by name). */
477
+ /** Only runs whose credentials came from this environment (by name). */
433
478
  environment?: string;
434
479
  }
435
480
  /**
@@ -441,8 +486,12 @@ export interface BatchRunFreshRequest {
441
486
  projectId: string;
442
487
  testIds?: string[];
443
488
  source: 'cli';
489
+ /** See `TriggerRunBody.autoHeal`, including why `true` is never sent. */
490
+ autoHeal?: false;
444
491
  /** See `TriggerRunBody.environment` — applied to every test in the batch. */
445
492
  environment?: string;
493
+ /** Per-run URL override for the batch; echoed when the backend honors it. */
494
+ targetUrl?: string;
446
495
  }
447
496
  /** One accepted run in the batch fresh-run response. */
448
497
  export interface BatchRunFreshAccepted {
@@ -474,6 +523,8 @@ export interface BatchRunFreshAccepted {
474
523
  */
475
524
  export interface BatchRunFreshResponse {
476
525
  accepted: BatchRunFreshAccepted[];
526
+ /** See `TriggerRunResponse.autoHeal`; absence means the same thing. */
527
+ autoHeal?: boolean;
477
528
  /**
478
529
  * A run-slot conflict. `currentRunId`, when present, is the id of the run
479
530
  * ALREADY in flight for this test — under `--wait` the CLI polls it to a
@@ -498,4 +549,10 @@ export interface BatchRunFreshResponse {
498
549
  * nothing rather than a dead link.
499
550
  */
500
551
  dashboardUrl?: string | null;
552
+ /**
553
+ * Exact echo of the request's `targetUrl` when the backend read the override.
554
+ * A missing or different echo makes the CLI refuse the batch rather than
555
+ * report a verdict for an unconfirmed target.
556
+ */
557
+ targetUrl?: string;
501
558
  }
@@ -18,8 +18,13 @@
18
18
  * Callers pass the flag name so the envelope names the flag the user actually
19
19
  * typed — one helper serves `--password-file` today and the remaining
20
20
  * credential/auto-auth file flags once they are migrated.
21
+ *
22
+ * The check (is this a regular file?) and the use (read its bytes) happen
23
+ * against a single open file descriptor rather than against the path twice,
24
+ * so nothing can be swapped in between: whatever `openSync` resolved is
25
+ * exactly what `fstatSync` classifies and `readFileSync` reads.
21
26
  */
22
- import { readFileSync, statSync } from 'node:fs';
27
+ import { closeSync, constants, fstatSync, openSync, readFileSync, statSync } from 'node:fs';
23
28
  import { isAbsolute, resolve } from 'node:path';
24
29
  import { localValidationError } from './errors.js';
25
30
  /**
@@ -38,26 +43,67 @@ import { localValidationError } from './errors.js';
38
43
  */
39
44
  export function readSecretFileGuarded(flag, path) {
40
45
  const absolute = isAbsolute(path) ? path : resolve(process.cwd(), path);
41
- let stat;
46
+ let fd;
42
47
  try {
43
- // eslint-disable-next-line security/detect-non-literal-fs-filename -- this is the guard itself: `absolute` is the user-supplied `--*-file` path after isAbsolute()/resolve() normalization, and this statSync().isFile() check (below) plus the try/catch mapping every errno to a typed VALIDATION_ERROR is exactly the mitigation for a non-literal fs path here.
44
- stat = statSync(absolute);
48
+ // O_NONBLOCK matters here specifically because this is a *-file flag:
49
+ // a plain `open(path, O_RDONLY)` on a FIFO with no writer blocks the
50
+ // calling thread until one connects (POSIX fifo(7)), and since this is
51
+ // a synchronous fs call on Node's single main thread, that blocks the
52
+ // entire CLI process -- including its SIGINT handler, since delivering
53
+ // that signal to JS requires the (blocked) event loop to run. The old
54
+ // statSync()-first code rejected a FIFO instantly via `isFile()` before
55
+ // ever opening it; O_NONBLOCK restores that instant-fail behavior by
56
+ // making the open itself return right away instead of waiting for a
57
+ // writer, so the existing fstatSync().isFile() check below still does
58
+ // the rejecting. It has no effect on a regular file's read semantics.
59
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- this is the guard itself: `absolute` is the user-supplied --*-file path after isAbsolute()/resolve(); everything after (fstat, then read) uses the fd this open() returns, not the path string, which is the mitigation for a non-literal fs path here.
60
+ fd = openSync(absolute, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0));
45
61
  }
46
62
  catch (err) {
63
+ // Opening a directory succeeds on POSIX (the fstat().isFile() check
64
+ // below is the gate for that case) but can fail right here on other
65
+ // platforms, and not always with the same errno a directory produces
66
+ // elsewhere. Classify the failure by re-stat'ing the path once,
67
+ // diagnostically, before falling back to errno-based mapping: nothing is
68
+ // read as a result, so this cannot reintroduce a check-then-use race —
69
+ // it only decides which message to throw for an open() that already
70
+ // failed.
71
+ let isDir = false;
72
+ try {
73
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- diagnostic only, to pick an error message for the open() failure above; no data is read from `absolute` here or afterward.
74
+ isDir = statSync(absolute).isDirectory();
75
+ }
76
+ catch {
77
+ // Path vanished or became inaccessible between the failed open() and
78
+ // this diagnostic stat — fall through to the errno-based mapping,
79
+ // which still accurately reports that the open() failed.
80
+ }
81
+ if (isDir) {
82
+ throw localValidationError(flag, `not a regular file: ${path}`);
83
+ }
47
84
  throw secretFileError(flag, path, err, 'stat');
48
85
  }
49
- // A directory would otherwise reach readFileSync and throw EISDIR on Linux
50
- // while resolving to an empty read on some platforms — reject it up front so
51
- // the contract is the same everywhere.
52
- if (!stat.isFile()) {
53
- throw localValidationError(flag, `not a regular file: ${path}`);
54
- }
55
86
  try {
56
- // eslint-disable-next-line security/detect-non-literal-fs-filename -- same guarded path as the statSync() above: `absolute` already passed the isFile() regular-file check, so this read is the guard's intended purpose (reading a user-supplied secret path), not an unvalidated pass-through.
57
- return readFileSync(absolute, 'utf8').trim();
87
+ let stat;
88
+ try {
89
+ stat = fstatSync(fd);
90
+ }
91
+ catch (err) {
92
+ throw secretFileError(flag, path, err, 'stat');
93
+ }
94
+ if (!stat.isFile()) {
95
+ throw localValidationError(flag, `not a regular file: ${path}`);
96
+ }
97
+ try {
98
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- `fd` is the open file descriptor from openSync() above, not a path string; the rule's non-literal-argument check does not distinguish the two, but there is no path re-resolution here for anything to race against.
99
+ return readFileSync(fd, 'utf8').trim();
100
+ }
101
+ catch (err) {
102
+ throw secretFileError(flag, path, err, 'read');
103
+ }
58
104
  }
59
- catch (err) {
60
- throw secretFileError(flag, path, err, 'read');
105
+ finally {
106
+ closeSync(fd);
61
107
  }
62
108
  }
63
109
  /**
@@ -76,6 +122,18 @@ function secretFileError(flag, path, err, verb) {
76
122
  if (code === 'EISDIR') {
77
123
  return localValidationError(flag, `not a regular file: ${path}`);
78
124
  }
125
+ if (code === 'EMFILE' || code === 'ENFILE') {
126
+ // The old stat-then-read code's statSync() opens no file descriptor, so
127
+ // it always succeeded even with the process's fd table exhausted; only
128
+ // the later readFileSync (which does open one) could hit EMFILE/ENFILE,
129
+ // landing in the generic "cannot read" wording. The fd-based guard's
130
+ // openSync is the first fs call here, so the same exhaustion now surfaces
131
+ // at what looks like the "stat" step; route it to the same "cannot read"
132
+ // wording regardless of `verb` so fd-table exhaustion always reads the
133
+ // same as it did before, no matter which syscall actually hit the ceiling.
134
+ const reason = err instanceof Error ? err.message : 'unknown error';
135
+ return localValidationError(flag, `cannot read ${path}: ${reason}`);
136
+ }
79
137
  const reason = err instanceof Error ? err.message : 'unknown error';
80
138
  return localValidationError(flag, `cannot ${verb} ${path}: ${reason}`);
81
139
  }
@@ -42,6 +42,8 @@ export declare function isPlanTemplateInvocation(commandPath: string, planTempla
42
42
  export interface SkillPresenceDeps {
43
43
  existsSync?: (p: string) => boolean;
44
44
  readFileSync?: (p: string) => string;
45
+ /** Best-effort diagnostic hook for an unreadable managed-section target. */
46
+ onReadError?: (path: string, error: unknown) => void;
45
47
  /**
46
48
  * Narrow the check to specific agents. Pass the agents actually calling: a
47
49
  * skill installed for some OTHER agent is not one this caller can read, and
@@ -80,6 +82,8 @@ export interface SkillNudgeContext {
80
82
  } | undefined;
81
83
  /** Sink for the hint line; defaults to `process.stderr`. */
82
84
  stderr?: (line: string) => void;
85
+ /** Emit best-effort diagnostics for swallowed nudge errors. */
86
+ debug?: boolean;
83
87
  existsSync?: (p: string) => boolean;
84
88
  readFileSync?: (p: string) => string;
85
89
  }
@@ -93,6 +97,7 @@ export interface SkillNudgeContext {
93
97
  * not `--dry-run`, the command is in {@link SKILL_NUDGE_COMMANDS}, the opt-out
94
98
  * env is unset, the active profile has an api key (un-configured callers hit an
95
99
  * auth error that already points at setup), and the skill is not already
96
- * installed. Never throws and never blocks the command — any error is swallowed.
100
+ * installed. Never throws and never blocks the command — any error is swallowed;
101
+ * `--debug` callers receive the swallowed reason on stderr.
97
102
  */
98
103
  export declare function maybeEmitSkillNudge(ctx: SkillNudgeContext): void;