@testsprite/testsprite-cli 0.16.0 → 0.18.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 (206) hide show
  1. package/README.md +52 -147
  2. package/dist/commands/agent.d.ts +12 -4
  3. package/dist/commands/agent.js +48 -63
  4. package/dist/commands/auth.d.ts +6 -10
  5. package/dist/commands/auth.js +40 -56
  6. package/dist/commands/ci.d.ts +23 -100
  7. package/dist/commands/ci.js +293 -487
  8. package/dist/commands/conversation.d.ts +27 -0
  9. package/dist/commands/conversation.js +741 -0
  10. package/dist/commands/doctor.d.ts +5 -1
  11. package/dist/commands/doctor.js +129 -34
  12. package/dist/commands/init.d.ts +4 -45
  13. package/dist/commands/init.js +108 -66
  14. package/dist/commands/project-env.d.ts +62 -2
  15. package/dist/commands/project-env.js +434 -43
  16. package/dist/commands/project-sign-in.d.ts +0 -48
  17. package/dist/commands/project-sign-in.js +1 -229
  18. package/dist/commands/project.d.ts +19 -186
  19. package/dist/commands/project.js +108 -926
  20. package/dist/commands/result.d.ts +10 -0
  21. package/dist/commands/result.js +216 -0
  22. package/dist/commands/schedule.d.ts +0 -29
  23. package/dist/commands/schedule.js +28 -87
  24. package/dist/commands/test.d.ts +301 -1838
  25. package/dist/commands/test.js +1880 -13917
  26. package/dist/commands/testlist.d.ts +130 -5
  27. package/dist/commands/testlist.js +300 -342
  28. package/dist/commands/tunnel.d.ts +3 -3
  29. package/dist/commands/tunnel.js +23 -20
  30. package/dist/commands/usage.d.ts +12 -45
  31. package/dist/commands/usage.js +50 -131
  32. package/dist/index.js +191 -110
  33. package/dist/lib/agent-detect.js +9 -5
  34. package/dist/lib/agent-targets.d.ts +21 -2
  35. package/dist/lib/agent-targets.js +88 -11
  36. package/dist/lib/args.d.ts +13 -0
  37. package/dist/lib/args.js +49 -0
  38. package/dist/lib/basic-auth.d.ts +3 -0
  39. package/dist/lib/basic-auth.js +15 -0
  40. package/dist/lib/billing-refusal.js +4 -3
  41. package/dist/lib/ci-linkage.d.ts +4 -82
  42. package/dist/lib/ci-linkage.js +4 -157
  43. package/dist/lib/ci-run.js +1 -1
  44. package/dist/lib/client-factory.d.ts +12 -4
  45. package/dist/lib/client-factory.js +41 -30
  46. package/dist/lib/commit-signal.d.ts +65 -0
  47. package/dist/lib/commit-signal.js +305 -0
  48. package/dist/lib/concurrency-limiter.d.ts +6 -0
  49. package/dist/lib/concurrency-limiter.js +29 -0
  50. package/dist/lib/config.js +10 -5
  51. package/dist/lib/conflict-reason.d.ts +9 -3
  52. package/dist/lib/conflict-reason.js +6 -3
  53. package/dist/lib/conversation/answers.d.ts +9 -0
  54. package/dist/lib/conversation/answers.js +49 -0
  55. package/dist/lib/conversation/api.d.ts +75 -0
  56. package/dist/lib/conversation/api.js +151 -0
  57. package/dist/lib/conversation/change.d.ts +31 -0
  58. package/dist/lib/conversation/change.js +124 -0
  59. package/dist/lib/conversation/context.d.ts +29 -0
  60. package/dist/lib/conversation/context.js +82 -0
  61. package/dist/lib/conversation/environment.d.ts +16 -0
  62. package/dist/lib/conversation/environment.js +21 -0
  63. package/dist/lib/conversation/follow.d.ts +24 -0
  64. package/dist/lib/conversation/follow.js +42 -0
  65. package/dist/lib/conversation/render.d.ts +33 -0
  66. package/dist/lib/conversation/render.js +318 -0
  67. package/dist/lib/conversation/title.d.ts +2 -0
  68. package/dist/lib/conversation/title.js +18 -0
  69. package/dist/lib/conversation/types.d.ts +158 -0
  70. package/dist/lib/conversation/types.js +6 -0
  71. package/dist/lib/credentials.js +67 -11
  72. package/dist/lib/cron.d.ts +1 -1
  73. package/dist/lib/cron.js +2 -2
  74. package/dist/lib/dispatch-stop.d.ts +20 -0
  75. package/dist/lib/dispatch-stop.js +30 -0
  76. package/dist/lib/download.d.ts +100 -0
  77. package/dist/lib/download.js +408 -0
  78. package/dist/lib/dry-run/fetch.d.ts +10 -0
  79. package/dist/lib/dry-run/fetch.js +20 -0
  80. package/dist/lib/dry-run/samples.d.ts +6 -34
  81. package/dist/lib/dry-run/samples.js +375 -747
  82. package/dist/lib/environment-tunnel.d.ts +19 -30
  83. package/dist/lib/environment-tunnel.js +168 -202
  84. package/dist/lib/errors.d.ts +20 -4
  85. package/dist/lib/errors.js +36 -16
  86. package/dist/lib/facade.d.ts +7 -29
  87. package/dist/lib/facade.js +7 -36
  88. package/dist/lib/failing-fe-resolver.d.ts +13 -58
  89. package/dist/lib/failing-fe-resolver.js +47 -132
  90. package/dist/lib/first-suite-hint.d.ts +20 -30
  91. package/dist/lib/first-suite-hint.js +57 -72
  92. package/dist/lib/gh-output.d.ts +76 -21
  93. package/dist/lib/gh-output.js +171 -90
  94. package/dist/lib/git-utils.d.ts +56 -0
  95. package/dist/lib/git-utils.js +212 -0
  96. package/dist/lib/github-context.d.ts +2 -0
  97. package/dist/lib/github-context.js +40 -8
  98. package/dist/lib/history-retention.d.ts +6 -2
  99. package/dist/lib/history-retention.js +10 -7
  100. package/dist/lib/http.d.ts +58 -134
  101. package/dist/lib/http.js +354 -291
  102. package/dist/lib/interrupt.d.ts +14 -8
  103. package/dist/lib/interrupt.js +28 -10
  104. package/dist/lib/junit-report.d.ts +57 -4
  105. package/dist/lib/junit-report.js +202 -32
  106. package/dist/lib/local-target.d.ts +8 -7
  107. package/dist/lib/local-target.js +14 -13
  108. package/dist/lib/output.d.ts +2 -41
  109. package/dist/lib/output.js +13 -51
  110. package/dist/lib/pagination.d.ts +2 -5
  111. package/dist/lib/pagination.js +2 -5
  112. package/dist/lib/presigned-url.d.ts +22 -0
  113. package/dist/lib/presigned-url.js +90 -0
  114. package/dist/lib/prompt.js +36 -2
  115. package/dist/lib/proxy.js +2 -1
  116. package/dist/lib/redact.d.ts +2 -2
  117. package/dist/lib/redact.js +3 -4
  118. package/dist/lib/removed-commands.d.ts +18 -0
  119. package/dist/lib/removed-commands.js +170 -0
  120. package/dist/lib/render-error.d.ts +31 -6
  121. package/dist/lib/render-error.js +88 -25
  122. package/dist/lib/response-schemas.d.ts +38 -30
  123. package/dist/lib/response-schemas.js +207 -207
  124. package/dist/lib/result/api.d.ts +24 -0
  125. package/dist/lib/result/api.js +28 -0
  126. package/dist/lib/result/evidence.d.ts +73 -0
  127. package/dist/lib/result/evidence.js +422 -0
  128. package/dist/lib/result/render.d.ts +20 -0
  129. package/dist/lib/result/render.js +194 -0
  130. package/dist/lib/result/types.d.ts +122 -0
  131. package/dist/lib/result/types.js +19 -0
  132. package/dist/lib/run-output.d.ts +275 -0
  133. package/dist/lib/run-output.js +227 -0
  134. package/dist/lib/run-render.d.ts +101 -0
  135. package/dist/lib/run-render.js +183 -0
  136. package/dist/lib/run-wait.d.ts +192 -0
  137. package/dist/lib/run-wait.js +452 -0
  138. package/dist/lib/runs.types.d.ts +118 -367
  139. package/dist/lib/runs.types.js +0 -14
  140. package/dist/lib/secret-file.d.ts +1 -1
  141. package/dist/lib/secret-file.js +11 -2
  142. package/dist/lib/skill-nudge.d.ts +7 -27
  143. package/dist/lib/skill-nudge.js +9 -37
  144. package/dist/lib/target-path.d.ts +15 -0
  145. package/dist/lib/target-path.js +35 -0
  146. package/dist/lib/target-url-advisory.d.ts +19 -0
  147. package/dist/lib/target-url-advisory.js +31 -0
  148. package/dist/lib/target-url-preflight.d.ts +9 -0
  149. package/dist/lib/target-url-preflight.js +214 -106
  150. package/dist/lib/target-url.d.ts +8 -8
  151. package/dist/lib/target-url.js +14 -24
  152. package/dist/lib/telemetry.d.ts +35 -15
  153. package/dist/lib/telemetry.js +38 -9
  154. package/dist/lib/terminal-text.d.ts +41 -0
  155. package/dist/lib/terminal-text.js +127 -0
  156. package/dist/lib/testlist.types.d.ts +16 -8
  157. package/dist/lib/testlist.types.js +1 -1
  158. package/dist/lib/text-equality.d.ts +2 -0
  159. package/dist/lib/text-equality.js +5 -0
  160. package/dist/lib/text-file.d.ts +16 -0
  161. package/dist/lib/text-file.js +41 -0
  162. package/dist/lib/text-table.d.ts +46 -0
  163. package/dist/lib/text-table.js +72 -4
  164. package/dist/lib/ticker.d.ts +9 -2
  165. package/dist/lib/ticker.js +16 -3
  166. package/dist/lib/transport-failure.d.ts +22 -0
  167. package/dist/lib/transport-failure.js +126 -0
  168. package/dist/lib/tunnel-session.d.ts +8 -2
  169. package/dist/lib/tunnel-session.js +24 -11
  170. package/dist/lib/update-check.js +3 -2
  171. package/dist/lib/url-template.d.ts +43 -0
  172. package/dist/lib/url-template.js +151 -0
  173. package/dist/lib/validate.d.ts +0 -64
  174. package/dist/lib/validate.js +2 -131
  175. package/dist/lib/version-notice.js +4 -3
  176. package/dist/lib/wait-exit.d.ts +37 -2
  177. package/dist/lib/wait-exit.js +88 -30
  178. package/dist/lib/workspace-status.js +10 -2
  179. package/dist/version.d.ts +1 -1
  180. package/dist/version.js +1 -1
  181. package/package.json +2 -3
  182. package/skills/testsprite-ci.skill.md +52 -23
  183. package/skills/testsprite-onboard.skill.md +70 -153
  184. package/skills/testsprite-verify.codex.md +54 -58
  185. package/skills/testsprite-verify.skill.md +189 -358
  186. package/dist/lib/browser.d.ts +0 -6
  187. package/dist/lib/browser.js +0 -54
  188. package/dist/lib/bundle.d.ts +0 -234
  189. package/dist/lib/bundle.js +0 -781
  190. package/dist/lib/deprecate.d.ts +0 -32
  191. package/dist/lib/deprecate.js +0 -39
  192. package/dist/lib/flaky.d.ts +0 -91
  193. package/dist/lib/flaky.js +0 -71
  194. package/dist/lib/plan-poll.d.ts +0 -171
  195. package/dist/lib/plan-poll.js +0 -441
  196. package/dist/lib/plans.types.d.ts +0 -130
  197. package/dist/lib/plans.types.js +0 -31
  198. package/dist/lib/poll.d.ts +0 -100
  199. package/dist/lib/poll.js +0 -290
  200. package/dist/lib/rate-throttle.d.ts +0 -49
  201. package/dist/lib/rate-throttle.js +0 -75
  202. package/dist/lib/run-progress.d.ts +0 -41
  203. package/dist/lib/run-progress.js +0 -56
  204. package/dist/lib/v3-advisory.d.ts +0 -55
  205. package/dist/lib/v3-advisory.js +0 -74
  206. package/schemas/plan.schema.json +0 -61
@@ -1,22 +1,19 @@
1
1
  import { randomUUID } from 'node:crypto';
2
- import { createReadStream, readFileSync, statSync } from 'node:fs';
3
- import { basename, extname } from 'node:path';
4
- import { Readable } from 'node:stream';
5
- import { Command, Option } from 'commander';
6
- import { emitDryRunBanner, makeHttpClient, parseRequestTimeoutFlag, resolveRequestTimeoutMs, } from '../lib/client-factory.js';
2
+ import { Command } from 'commander';
3
+ import { emitDryRunBanner, makeHttpClient, parseRequestTimeoutFlag, } from '../lib/client-factory.js';
7
4
  import { resolveProfileName } from '../lib/config.js';
8
- import { ApiError, InterruptError, RequestTimeoutError } from '../lib/errors.js';
5
+ import { readRepository, runGit } from '../lib/conversation/change.js';
6
+ import { rememberProject } from '../lib/conversation/context.js';
7
+ import { ApiError } from '../lib/errors.js';
9
8
  import { firstSuiteNextSteps } from '../lib/first-suite-hint.js';
10
- import { globalShutdown } from '../lib/interrupt.js';
11
- import { assertStoredLocalTargetListening, buildLocalTargetUrl, parseStoredLocalTarget, } from '../lib/local-target.js';
12
9
  import { GLOBAL_OPTS_HINT, Output, resolveOutputMode } from '../lib/output.js';
13
- import { readSecretFileGuarded } from '../lib/secret-file.js';
14
- import { assertNotLocal } from '../lib/target-url.js';
10
+ import { CLI_PROJECT_LIST_SCHEMA, CLI_PROJECT_SCHEMA } from '../lib/response-schemas.js';
11
+ import { terminalWidth } from '../lib/ticker.js';
15
12
  import { renderTextTable, resolveTextColumns } from '../lib/text-table.js';
16
13
  import { assertIdempotencyKey } from '../lib/validate.js';
17
14
  import { fetchSinglePage, paginate, validatePaginationFlags, } from '../lib/pagination.js';
18
15
  import { createProjectEnvCommand } from './project-env.js';
19
- import { createProjectSignInCommand } from './project-sign-in.js';
16
+ import { terminalSafe, terminalSafeLine, terminalSafeWriter } from '../lib/terminal-text.js';
20
17
  /** Attribute names are interpolated into CSS selectors by the engine — keep them plain. */
21
18
  const TEST_ID_ATTRIBUTE_NAME = /^[A-Za-z_][\w.:-]*$/;
22
19
  const TEST_ID_ATTRIBUTES_MAX = 10;
@@ -63,14 +60,16 @@ export async function runList(opts, deps = {}) {
63
60
  // for --max-items, treat that as a "give me one page and the cursor"
64
61
  // request — same shape AWS CLI ships. Otherwise auto-page.
65
62
  const useSinglePage = opts.pageSize !== undefined && opts.maxItems === undefined;
63
+ const fetchPage = async ({ pageSize, cursor }) => client.get('/projects', {
64
+ query: { pageSize, cursor },
65
+ schema: CLI_PROJECT_LIST_SCHEMA,
66
+ });
66
67
  let page;
67
68
  if (useSinglePage) {
68
- page = await fetchSinglePage(client, '/projects', paginationFlags.pageSize, opts.startingToken);
69
+ page = await fetchSinglePage(client, '/projects', paginationFlags.pageSize, opts.startingToken, {}, CLI_PROJECT_LIST_SCHEMA);
69
70
  }
70
71
  else {
71
- page = await paginate(async ({ pageSize, cursor }) => client.get('/projects', {
72
- query: { pageSize, cursor },
73
- }), paginationFlags);
72
+ page = await paginate(fetchPage, paginationFlags);
74
73
  }
75
74
  out.print(page, data => {
76
75
  const p = data;
@@ -81,7 +80,9 @@ export async function runList(opts, deps = {}) {
81
80
  export async function runGet(opts, deps = {}) {
82
81
  const out = makeOutput(opts.output, deps);
83
82
  const client = makeClient(opts, deps);
84
- const project = await client.get(`/projects/${encodeURIComponent(opts.projectId)}`);
83
+ const project = await client.get(`/projects/${encodeURIComponent(opts.projectId)}`, {
84
+ schema: CLI_PROJECT_SCHEMA,
85
+ });
85
86
  out.print(project, data => renderProjectText(data));
86
87
  return project;
87
88
  }
@@ -91,66 +92,29 @@ export function resolveCreatedProjectId(r) {
91
92
  }
92
93
  export async function runCreate(opts, deps = {}) {
93
94
  const out = makeOutput(opts.output, deps);
94
- const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
95
+ const stderr = terminalSafeWriter(deps.stderr);
95
96
  // P1-2: validate idempotency key before sending as an HTTP header.
96
97
  // Non-ASCII chars cause a ByteString TypeError at the transport layer
97
98
  // (exit 10 UNAVAILABLE) — fail fast with a clear exit 5 instead.
98
99
  assertIdempotencyKey(opts.idempotencyKey);
99
100
  // P1-3: client-side length checks matching server limits.
100
- // Whitespace-only / empty rejection (parity with `test create`'s requireString;
101
- // a truthy `--name " "` otherwise creates a blank-named project on the backend).
101
+ // Whitespace-only / empty rejection: a truthy `--name " "` otherwise
102
+ // creates a blank-named project on the backend.
102
103
  if (opts.name === undefined || opts.name.trim().length === 0) {
103
104
  throw localValidationError('--name is required and must not be empty or whitespace-only');
104
105
  }
105
- if (opts.password !== undefined && opts.password.trim().length === 0) {
106
- throw localValidationError('--password must not be empty or whitespace-only');
107
- }
108
- if (opts.password !== undefined && opts.passwordFile !== undefined) {
109
- stderr('Warning: --password takes precedence; --password-file was ignored.');
110
- }
111
106
  if (opts.name.length > 200) {
112
107
  throw localValidationError('--name must be at most 200 characters');
113
108
  }
114
- // `--description` is not supported on projects — no project entity stores a
115
- // description, and the backend rejects it with a 422. Fail fast client-side
116
- // with an actionable message instead of a wasted round trip.
117
- if (opts.description !== undefined) {
118
- throw localValidationError('--description is not supported for projects; omit it (test-level descriptions are set on `test create`)');
119
- }
120
- if (opts.local !== undefined && opts.type !== 'frontend') {
121
- throw localValidationError('--local projects are frontend-only');
122
- }
123
- const localTarget = parseStoredLocalTarget({
124
- local: opts.local,
125
- localHost: opts.localHost,
126
- url: opts.targetUrl,
127
- });
128
- // A loopback --url is the same stored target as --local, so it gets the same
129
- // refusal before anything is sent.
130
- if (localTarget && opts.type !== 'frontend') {
131
- throw localValidationError('a --url on this machine (localhost, 127.0.0.1, [::1]) is frontend-only; give a backend project a public URL');
132
- }
133
- const targetUrl = opts.targetUrl ??
134
- (localTarget ? buildLocalTargetUrl(localTarget.host, localTarget.port) : undefined);
135
- // Keep the existing public-address guard for targets a loopback tunnel cannot reach.
136
- if (opts.targetUrl !== undefined && !localTarget) {
137
- assertNotLocal(opts.targetUrl, {
138
- field: 'url',
139
- helpCommand: 'testsprite project create',
140
- hintContext: 'local-project-create',
141
- });
142
- }
143
- if (opts.type === 'frontend' && !targetUrl) {
144
- throw localValidationError('--url is required for --type frontend');
145
- }
146
109
  if (opts.dryRun) {
147
- // This path returns before makeClient() fires the banner, so emit it here
148
- // — otherwise the canned sample can be mistaken for a live response.
110
+ // This path returns without making any dry-run request, so emit the
111
+ // banner here — otherwise the canned sample can be mistaken for a live
112
+ // response.
149
113
  emitDryRunBanner(stderr);
150
114
  const idempotencyKey = opts.idempotencyKey ?? `cli-proj-create-${randomUUID()}`;
151
- // P2-6: gate idempotency-key output behind --verbose/--debug/json (matches
152
- // test create convention). Suppress in plain text interactive mode to reduce
153
- // noise; still available for automation and retry flows.
115
+ // P2-6: gate idempotency-key output behind --verbose/--debug/json. Suppress
116
+ // in plain text interactive mode to reduce noise; still available for
117
+ // automation and retry flows.
154
118
  if (opts.idempotencyKey === undefined &&
155
119
  (opts.output === 'json' || opts.verbose || opts.debug)) {
156
120
  stderr(`idempotency-key: ${idempotencyKey}`);
@@ -163,8 +127,6 @@ export async function runCreate(opts, deps = {}) {
163
127
  id: 'p_dryrun_2026',
164
128
  type: opts.type,
165
129
  name: opts.name,
166
- targetUrl: targetUrl ?? '',
167
- ...(localTarget ? { originMode: 'local' } : {}),
168
130
  createdFrom: 'cli',
169
131
  createdAt: '2026-05-16T00:00:00.000Z',
170
132
  updatedAt: '2026-05-16T00:00:00.000Z',
@@ -172,14 +134,6 @@ export async function runCreate(opts, deps = {}) {
172
134
  out.print(sample, data => renderCreateProjectText(data));
173
135
  return sample;
174
136
  }
175
- if (localTarget) {
176
- await assertStoredLocalTargetListening(localTarget, opts, deps.localPortProbeDeps);
177
- }
178
- // Resolve password: flag > file > none
179
- let password = opts.password;
180
- if (password === undefined && opts.passwordFile !== undefined) {
181
- password = readSecretFileGuarded('password-file', opts.passwordFile);
182
- }
183
137
  const idempotencyKey = opts.idempotencyKey ?? `cli-proj-create-${randomUUID()}`;
184
138
  if (opts.idempotencyKey === undefined && (opts.output === 'json' || opts.verbose || opts.debug)) {
185
139
  stderr(`idempotency-key: ${idempotencyKey}`);
@@ -187,10 +141,6 @@ export async function runCreate(opts, deps = {}) {
187
141
  const body = {
188
142
  type: opts.type,
189
143
  name: opts.name,
190
- ...(targetUrl !== undefined ? { targetUrl } : {}),
191
- ...(localTarget ? { originMode: 'local' } : {}),
192
- ...(opts.username !== undefined ? { username: opts.username } : {}),
193
- ...(password !== undefined ? { password } : {}),
194
144
  ...(opts.instruction !== undefined ? { instruction: opts.instruction } : {}),
195
145
  ...(opts.testIdAttributes !== undefined ? { testIdAttributes: opts.testIdAttributes } : {}),
196
146
  };
@@ -213,53 +163,11 @@ export async function runCreate(opts, deps = {}) {
213
163
  ...rawCreated,
214
164
  ...(resolvedId !== undefined ? { projectId: resolvedId, id: resolvedId } : {}),
215
165
  };
216
- out.print(created, data => renderCreateProjectText(data, localTarget));
217
- // A backend project created without --url has no default environment URL.
218
- // On the V3 execution path, the shared admission guard (`runProjectGuarded`
219
- // -> `assertProjectEnvNotLocal`, called by every V3 run/rerun/batch entry
220
- // point, including `backendRun`) rejects the FIRST run of any test in the
221
- // project with 400 no-target-resolvable. On the V2 path (`cli-run.service.ts`
222
- // -> `resolveRunPrereqsFE`), this URL resolution is frontend-only and is
223
- // never applied to a backend run, so a V2-routed backend project without a
224
- // URL runs fine — V2 is the only execution path live in production today
225
- // (V3 is dev-only pending its own GA release), so the wording below is
226
- // conditioned on V3 rather than stated as a universal consequence.
227
- // `--url` is intentionally NOT made mandatory here (that would break the
228
- // published --help contract: npm 0.4.0 already ships text saying the URL
229
- // is frontend-only), so this stays advisory-only. The CLI does not call
230
- // GET /me here to check the caller's actual v3Enabled routing before
231
- // deciding whether to print this — an extra round-trip on every create is
232
- // not worth it just to gate a hint — so it points the reader at `auth
233
- // status` (which already renders the routing: v2|v3 line) instead.
234
- // Emitted in EVERY output mode, including --output json: this goes to
235
- // stderr, which never touches JSON stdout, so there is nothing to protect
236
- // by suppressing it (unlike `emitV3RoutingAdvisory`, which withholds
237
- // account-context advisory in JSON mode because a JSON caller can read
238
- // `v3Enabled` directly instead — there is no equivalent structured signal
239
- // for this one). And --output json is precisely the case that needs it
240
- // most: a script or agent creating a project non-interactively has no one
241
- // watching a terminal, so a silent dead-on-arrival project only surfaces
242
- // later as an unexplained 400 on the first run. Same family as the C1
243
- // `--target-url` advisory above (a flag/setup the caller just made has a
244
- // structural consequence) rather than the routing-advisory family.
245
- // Real path only — NOT duplicated into the dry-run branch above, because
246
- // the remedy command below embeds the created project id, and under
247
- // --dry-run that id is the canned `p_dryrun_2026` sample: emitting a
248
- // live-looking fix-it command against a fake resource is exactly what the
249
- // `dashboardUrl` convention (see CLAUDE.md) already decided to suppress.
250
- if (opts.type === 'backend' && !opts.targetUrl) {
251
- stderr(`[advisory] this backend project has no default environment URL. On the V3 execution ` +
252
- `path (check with \`testsprite auth status\`), test runs are rejected with ` +
253
- `no-target-resolvable until one is set. Fix: testsprite project update ` +
254
- `${resolvedId ?? '<project-id>'} --url <url>`);
255
- }
256
- // A new project with no tests is where activation stalls. Point at
257
- // the generate -> accept path (text mode only: a JSON caller already holds
258
- // the id; --dry-run returned above, its id is the canned sample). Printed
259
- // after the URL advisory so a fix-first warning is never buried below it.
260
- // A --local project is skipped: its record above already ends with the
261
- // hand-written-plan next steps.
262
- if (opts.output !== 'json' && resolvedId !== undefined && !localTarget) {
166
+ out.print(created, data => renderCreateProjectText(data));
167
+ // A new project has no environment and no tests yet; one hint names both
168
+ // steps. Text mode only: a JSON caller already holds the id, and --dry-run
169
+ // returned above with a canned one.
170
+ if (opts.output !== 'json' && resolvedId !== undefined) {
263
171
  stderr(firstSuiteNextSteps(resolvedId, opts.type));
264
172
  }
265
173
  return created;
@@ -270,7 +178,7 @@ export function resolveUpdatedProjectId(r) {
270
178
  }
271
179
  export async function runUpdate(opts, deps = {}) {
272
180
  const out = makeOutput(opts.output, deps);
273
- const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
181
+ const stderr = terminalSafeWriter(deps.stderr);
274
182
  // P1-2: validate idempotency key before sending as an HTTP header.
275
183
  assertIdempotencyKey(opts.idempotencyKey);
276
184
  // P1-3: client-side length checks matching server limits.
@@ -279,40 +187,14 @@ export async function runUpdate(opts, deps = {}) {
279
187
  if (opts.name !== undefined && opts.name.trim().length === 0) {
280
188
  throw localValidationError('--name must not be empty or whitespace-only');
281
189
  }
282
- if (opts.password !== undefined && opts.password.trim().length === 0) {
283
- throw localValidationError('--password must not be empty or whitespace-only');
284
- }
285
- if (opts.password !== undefined && opts.passwordFile !== undefined) {
286
- stderr('Warning: --password takes precedence; --password-file was ignored.');
287
- }
288
190
  if (opts.name !== undefined && opts.name.length > 200) {
289
191
  throw localValidationError('--name must be at most 200 characters');
290
192
  }
291
- // A loopback URL and --local shorthand use the same stored-target wire shape.
292
- // The server owns project-type validation on update.
293
- const localTarget = parseStoredLocalTarget({
294
- local: opts.local,
295
- localHost: opts.localHost,
296
- url: opts.targetUrl,
297
- });
298
- const targetUrl = opts.targetUrl ??
299
- (localTarget ? buildLocalTargetUrl(localTarget.host, localTarget.port) : undefined);
300
- if (opts.targetUrl !== undefined && !localTarget) {
301
- assertNotLocal(opts.targetUrl, {
302
- field: 'url',
303
- helpCommand: 'testsprite project update',
304
- hintContext: 'local-project-create',
305
- });
306
- }
307
193
  if (opts.testIdAttributes !== undefined && opts.clearTestIdAttributes) {
308
194
  throw localValidationError('--test-id-attributes and --clear-test-id-attributes are mutually exclusive.');
309
195
  }
310
- const passwordSupplied = opts.password !== undefined || opts.passwordFile !== undefined;
311
196
  const mutableFields = {
312
197
  name: opts.name !== undefined,
313
- targetUrl: targetUrl !== undefined,
314
- username: opts.username !== undefined,
315
- password: passwordSupplied,
316
198
  instruction: opts.instruction !== undefined,
317
199
  testIdAttributes: opts.testIdAttributes !== undefined || opts.clearTestIdAttributes === true,
318
200
  };
@@ -320,8 +202,8 @@ export async function runUpdate(opts, deps = {}) {
320
202
  .filter(([, present]) => present)
321
203
  .map(([field]) => field);
322
204
  if (presentFieldNames.length === 0) {
323
- throw localValidationError('At least one mutable flag is required: --name, --url, --username, --password/--password-file, ' +
324
- '--instruction, --test-id-attributes, or --clear-test-id-attributes.');
205
+ throw localValidationError('At least one mutable flag is required: --name, --instruction, --test-id-attributes, or ' +
206
+ '--clear-test-id-attributes.');
325
207
  }
326
208
  if (opts.dryRun) {
327
209
  // Emit the banner here (this path returns before makeClient() does).
@@ -340,28 +222,15 @@ export async function runUpdate(opts, deps = {}) {
340
222
  updatedFields: presentFieldNames,
341
223
  updatedAt: '2026-05-16T00:00:00.000Z',
342
224
  };
343
- out.print(sample, data => renderUpdateText(data, localTarget));
225
+ out.print(sample, data => renderUpdateText(data));
344
226
  return sample;
345
227
  }
346
- if (localTarget) {
347
- await assertStoredLocalTargetListening(localTarget, opts, deps.localPortProbeDeps);
348
- }
349
- // Resolve password only on the real path. Dry-run must not touch the
350
- // filesystem, even when --password-file is present.
351
- let password = opts.password;
352
- if (password === undefined && opts.passwordFile !== undefined) {
353
- password = readSecretFileGuarded('password-file', opts.passwordFile);
354
- }
355
228
  const idempotencyKey = opts.idempotencyKey ?? `cli-proj-update-${randomUUID()}`;
356
229
  if (opts.idempotencyKey === undefined && (opts.output === 'json' || opts.verbose || opts.debug)) {
357
230
  stderr(`idempotency-key: ${idempotencyKey}`);
358
231
  }
359
232
  const bodyFields = {
360
233
  name: opts.name,
361
- targetUrl,
362
- originMode: localTarget ? 'local' : undefined,
363
- username: opts.username,
364
- password,
365
234
  instruction: opts.instruction,
366
235
  // `null` clears the list server-side (same convention as `test update --clear-step-timeout`).
367
236
  testIdAttributes: opts.clearTestIdAttributes ? null : opts.testIdAttributes,
@@ -388,7 +257,7 @@ export async function runUpdate(opts, deps = {}) {
388
257
  ? { projectId: resolvedUpdatedId, id: resolvedUpdatedId }
389
258
  : {}),
390
259
  };
391
- out.print(updated, data => renderUpdateText(data, localTarget));
260
+ out.print(updated, data => renderUpdateText(data));
392
261
  return updated;
393
262
  }
394
263
  /**
@@ -406,9 +275,6 @@ export async function runUpdate(opts, deps = {}) {
406
275
  */
407
276
  export async function runDelete(opts, deps = {}) {
408
277
  assertIdempotencyKey(opts.idempotencyKey);
409
- if (opts.projectId === undefined || opts.projectId.trim().length === 0) {
410
- throw localValidationError('<project-id> is required');
411
- }
412
278
  if (!opts.confirm && !opts.dryRun) {
413
279
  throw ApiError.fromEnvelope({
414
280
  error: {
@@ -425,7 +291,7 @@ export async function runDelete(opts, deps = {}) {
425
291
  }
426
292
  const idempotencyKey = opts.idempotencyKey ?? `cli-delete-${randomUUID()}`;
427
293
  if (opts.idempotencyKey === undefined && (opts.output === 'json' || opts.verbose || opts.debug)) {
428
- const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
294
+ const stderr = terminalSafeWriter(deps.stderr);
429
295
  stderr(`idempotency-key: ${idempotencyKey}`);
430
296
  }
431
297
  const client = makeClient(opts, deps);
@@ -436,514 +302,6 @@ export async function runDelete(opts, deps = {}) {
436
302
  out.print(response, data => renderDeleteText(data));
437
303
  return response;
438
304
  }
439
- // ---------------------------------------------------------------------------
440
- // project credential — set the static backend credential
441
- // ---------------------------------------------------------------------------
442
- const CLI_AUTH_TYPES = ['public', 'Bearer token', 'API key', 'basic token'];
443
- export async function runCredential(opts, deps = {}) {
444
- const out = makeOutput(opts.output, deps);
445
- const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
446
- assertIdempotencyKey(opts.idempotencyKey);
447
- if (!CLI_AUTH_TYPES.includes(opts.authType)) {
448
- throw localValidationError(`--type must be one of: ${CLI_AUTH_TYPES.join(', ')}`);
449
- }
450
- // Resolve the credential value (flag or file). Required for every type
451
- // except `public` (which clears it).
452
- let credential = opts.credential;
453
- if (credential === undefined && opts.credentialFile !== undefined) {
454
- credential = readFileSync(opts.credentialFile, 'utf8').trim();
455
- }
456
- if (opts.authType !== 'public' && (credential === undefined || credential === '')) {
457
- throw localValidationError('--credential (or --credential-file) is required unless --type is "public"');
458
- }
459
- const body = { authType: opts.authType };
460
- if (opts.authType !== 'public' && credential !== undefined)
461
- body.credential = credential;
462
- const idempotencyKey = opts.idempotencyKey ?? `cli-proj-cred-${randomUUID()}`;
463
- if (opts.idempotencyKey === undefined && (opts.output === 'json' || opts.verbose || opts.debug)) {
464
- stderr(`idempotency-key: ${idempotencyKey}`);
465
- }
466
- if (opts.dryRun) {
467
- const sample = {
468
- projectId: opts.projectId,
469
- authType: opts.authType,
470
- rewroteCount: 0,
471
- };
472
- out.print(sample, data => renderCredentialText(data));
473
- return sample;
474
- }
475
- const client = makeClient(opts, deps);
476
- const res = await client.put(`/projects/${encodeURIComponent(opts.projectId)}/credential`, { body, headers: { 'idempotency-key': idempotencyKey } });
477
- out.print(res, data => renderCredentialText(data));
478
- return res;
479
- }
480
- function renderCredentialText(r) {
481
- return [
482
- `projectId ${r.projectId}`,
483
- `authType ${r.authType}`,
484
- `rewroteCount ${r.rewroteCount}`,
485
- ].join('\n');
486
- }
487
- // ---------------------------------------------------------------------------
488
- // project auto-auth — configure the recurring-token (auto-refresh) login
489
- // ---------------------------------------------------------------------------
490
- const AUTO_AUTH_METHODS = ['password', 'refresh_token', 'aws_cognito_refresh'];
491
- const AUTO_AUTH_INJECTS = ['bearer', 'header', 'cookie'];
492
- export async function runAutoAuth(opts, deps = {}) {
493
- const out = makeOutput(opts.output, deps);
494
- const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
495
- assertIdempotencyKey(opts.idempotencyKey);
496
- if (!AUTO_AUTH_METHODS.includes(opts.method)) {
497
- throw localValidationError(`--method must be one of: ${AUTO_AUTH_METHODS.join(', ')}`);
498
- }
499
- if (!AUTO_AUTH_INJECTS.includes(opts.inject)) {
500
- throw localValidationError(`--inject must be one of: ${AUTO_AUTH_INJECTS.join(', ')}`);
501
- }
502
- // Resolve secrets from --*-file variants so they stay out of shell history.
503
- const password = opts.password ??
504
- (opts.passwordFile !== undefined ? readFileSync(opts.passwordFile, 'utf8').trim() : undefined);
505
- const clientSecret = opts.clientSecret ??
506
- (opts.clientSecretFile !== undefined
507
- ? readFileSync(opts.clientSecretFile, 'utf8').trim()
508
- : undefined);
509
- const refreshToken = opts.refreshToken ??
510
- (opts.refreshTokenFile !== undefined
511
- ? readFileSync(opts.refreshTokenFile, 'utf8').trim()
512
- : undefined);
513
- const enabled = opts.disable !== true;
514
- const body = { enabled, method: opts.method, inject: opts.inject };
515
- const maybe = (k, v) => {
516
- if (v !== undefined)
517
- body[k] = v;
518
- };
519
- maybe('injectKey', opts.injectKey);
520
- maybe('loginUrl', opts.loginUrl);
521
- maybe('loginMethod', opts.loginMethod);
522
- maybe('loginContentType', opts.loginContentType);
523
- maybe('loginBodyTemplate', opts.loginBodyTemplate);
524
- maybe('username', opts.username);
525
- maybe('password', password);
526
- maybe('tokenPath', opts.tokenPath);
527
- maybe('tokenEndpoint', opts.tokenEndpoint);
528
- maybe('clientId', opts.clientId);
529
- maybe('clientSecret', clientSecret);
530
- maybe('refreshToken', refreshToken);
531
- maybe('scope', opts.scope);
532
- maybe('region', opts.region);
533
- const idempotencyKey = opts.idempotencyKey ?? `cli-proj-autoauth-${randomUUID()}`;
534
- if (opts.idempotencyKey === undefined && (opts.output === 'json' || opts.verbose || opts.debug)) {
535
- stderr(`idempotency-key: ${idempotencyKey}`);
536
- }
537
- if (opts.dryRun) {
538
- const sample = {
539
- projectId: opts.projectId,
540
- enabled,
541
- method: opts.method,
542
- inject: opts.inject,
543
- };
544
- out.print(sample, data => renderAutoAuthText(data));
545
- return sample;
546
- }
547
- const client = makeClient(opts, deps);
548
- const res = await client.put(`/projects/${encodeURIComponent(opts.projectId)}/auto-auth`, { body, headers: { 'idempotency-key': idempotencyKey } });
549
- out.print(res, data => renderAutoAuthText(data));
550
- return res;
551
- }
552
- function renderAutoAuthText(r) {
553
- const lines = [
554
- `projectId ${r.projectId}`,
555
- `enabled ${r.enabled}`,
556
- `method ${r.method}`,
557
- `inject ${r.inject}`,
558
- ];
559
- if (r.lastRefreshError) {
560
- lines.push(`lastRefreshError ${r.lastRefreshError}`);
561
- }
562
- // A disabled result after a write means the trial login failed — call it out
563
- // so the user doesn't assume auto-auth is live.
564
- if (!r.enabled) {
565
- lines.push('note auto-auth was stored but is DISABLED — the trial login failed. Fix the credentials (e.g. a valid refresh token) and re-run.');
566
- }
567
- return lines.join('\n');
568
- }
569
- // ---------------------------------------------------------------------------
570
- // project docs upload
571
- // ---------------------------------------------------------------------------
572
- /**
573
- * CLI-facing role flags → wire enum. Default is `api-doc` (stated in help);
574
- * no inference from project type in v1 (design §3.4).
575
- */
576
- const DOC_ROLES = { 'api-doc': 'API_DOC', prd: 'PRD' };
577
- /**
578
- * MIME type sent in step 1 and echoed on the step-2 PUT. The backend signs
579
- * `ContentType` into the presigned URL when supplied, so the PUT's
580
- * `Content-Type` header must be byte-identical to what step 1 declared —
581
- * both come from this one lookup, so they cannot drift.
582
- */
583
- const DOC_CONTENT_TYPES = {
584
- '.json': 'application/json',
585
- '.yaml': 'application/yaml',
586
- '.yml': 'application/yaml',
587
- '.md': 'text/markdown',
588
- '.markdown': 'text/markdown',
589
- '.txt': 'text/plain',
590
- '.pdf': 'application/pdf',
591
- };
592
- const DEFAULT_DOC_CONTENT_TYPE = 'application/octet-stream';
593
- /**
594
- * `project docs upload <file>` — upload an API spec or PRD as a project
595
- * source so plan generation has inputs to feed on (closes the API-project
596
- * cold start at `no_processed_inputs`).
597
- *
598
- * Three-step flow against the docs facade routes:
599
- *
600
- * 1. `POST /projects/{id}/docs/upload-url` — mints a one-hour presigned
601
- * S3 PUT URL plus the S3 key to register afterwards.
602
- * 2. HTTP PUT of the file bytes to the presigned URL — **streamed**
603
- * (`createReadStream` → web stream), never buffering the whole file.
604
- * This request goes straight to S3: no facade base URL, no API key.
605
- * 3. `POST /projects/{id}/docs` — registers the S3 object with its role
606
- * and display name, which starts processing + embedding.
607
- *
608
- * Reading the local file as INPUT is allowed by DR-21 (the no-local-OUTPUTS
609
- * rule); nothing is ever written back to disk.
610
- *
611
- * Failure modes are deliberately distinguished (design non-negotiable): a
612
- * step-2 failure names the presigned PUT and the fix (re-running mints a
613
- * fresh URL — they expire); a step-3 failure preserves the server envelope
614
- * and says the upload already succeeded (re-running is safe: the server
615
- * upserts the document by S3 key, so no duplicate is created).
616
- */
617
- export async function runDocsUpload(opts, deps = {}) {
618
- const out = makeOutput(opts.output, deps);
619
- const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
620
- assertIdempotencyKey(opts.idempotencyKey);
621
- const projectId = requireDocsProjectId(opts.projectId, deps);
622
- const roleFlag = opts.role ?? 'api-doc';
623
- if (!(roleFlag in DOC_ROLES)) {
624
- throw localValidationError('--role must be api-doc (API spec, the default) or prd (product requirements document)');
625
- }
626
- const role = DOC_ROLES[roleFlag];
627
- if (opts.name !== undefined && opts.name.trim().length === 0) {
628
- throw localValidationError('--name must not be empty or whitespace-only');
629
- }
630
- if (opts.name !== undefined && opts.name.length > 255) {
631
- throw localValidationError('--name must be at most 255 characters');
632
- }
633
- if (opts.file === undefined || opts.file.trim().length === 0) {
634
- throw localValidationError('<file> is required');
635
- }
636
- // Size + existence sanity via stat only — the dry-run contract is "nothing
637
- // read beyond a stat", and the real path opens the file exactly once, in
638
- // the streamed PUT below.
639
- let stat;
640
- try {
641
- stat = statSync(opts.file);
642
- }
643
- catch (cause) {
644
- const code = cause.code;
645
- if (code === 'ENOENT') {
646
- throw localValidationError(`file does not exist: ${opts.file}`);
647
- }
648
- throw localValidationError(`cannot stat file ${opts.file}: ${cause.message ?? String(cause)}`);
649
- }
650
- if (!stat.isFile()) {
651
- throw localValidationError(`${opts.file} is not a regular file (is it a directory?)`);
652
- }
653
- if (stat.size === 0) {
654
- throw localValidationError(`file is empty (0 bytes), nothing to upload: ${opts.file}`);
655
- }
656
- const fileName = basename(opts.file);
657
- if (fileName.length > 255) {
658
- throw localValidationError('the file name (basename) must be at most 255 characters — rename the file ' +
659
- '(--name only changes the display name, not the stored file name)');
660
- }
661
- const displayName = opts.name ?? fileName;
662
- const contentType = DOC_CONTENT_TYPES[extname(fileName).toLowerCase()] ?? DEFAULT_DOC_CONTENT_TYPE;
663
- const projectPath = encodeURIComponent(projectId);
664
- if (opts.dryRun) {
665
- // Same inline early-exit family as `test delete-batch --dry-run`: the
666
- // command's dry-run contract (zero network, stat only, print the plan)
667
- // cannot be expressed through canned fetch samples — step 2 would have
668
- // to PUT somewhere. The `docsUploadUrl`/`docsRegister` entries in
669
- // `samples.ts` are shape-guards/documentation, not consumed here.
670
- emitDryRunBanner(stderr);
671
- const plan = {
672
- dryRun: true,
673
- projectId,
674
- file: opts.file,
675
- fileName,
676
- displayName,
677
- role,
678
- contentType,
679
- size: stat.size,
680
- steps: [
681
- `POST /projects/${projectId}/docs/upload-url — mint a presigned S3 PUT URL for ${fileName} (${contentType})`,
682
- `PUT ${stat.size} bytes to the presigned URL (streamed from disk, never buffered)`,
683
- `POST /projects/${projectId}/docs — register ${displayName} as ${role}; starts processing + embedding`,
684
- ],
685
- };
686
- out.print(plan, data => renderDocsUploadPlanText(data));
687
- return plan;
688
- }
689
- const idempotencyKey = opts.idempotencyKey ?? `cli-docs-upload-${randomUUID()}`;
690
- if (opts.idempotencyKey === undefined && (opts.output === 'json' || opts.verbose || opts.debug)) {
691
- stderr(`idempotency-key: ${idempotencyKey}`);
692
- }
693
- const client = makeClient(opts, deps);
694
- // ── Step 1 of 3: mint the presigned upload URL ────────────────────────────
695
- const minted = await client.post(`/projects/${projectPath}/docs/upload-url`, { body: { fileName, contentType } });
696
- // ── Step 2 of 3: stream the file bytes to S3 ──────────────────────────────
697
- // Straight to the presigned host with the raw fetch impl — NOT through
698
- // HttpClient, which would attach the facade base URL and leak the API key
699
- // to S3. Content-Length comes from the stat: S3 rejects chunked
700
- // transfer-encoding on presigned PUTs, and Node's fetch uses the explicit
701
- // header to keep identity framing with a streamed body.
702
- const fetchImpl = deps.fetchImpl ?? globalThis.fetch.bind(globalThis);
703
- // A remote facade must mint a non-local https URL.
704
- assertSafePresignedUploadUrl(minted.uploadUrl, client.resolvedBaseUrl);
705
- // Same flag > TESTSPRITE_REQUEST_TIMEOUT_MS > default resolution (and 1-600s
706
- // clamp) as makeHttpClient — this leg bypasses HttpClient, so resolve here.
707
- const requestTimeoutMs = resolveRequestTimeoutMs(opts, deps.env ?? process.env);
708
- const controller = new AbortController();
709
- const timer = setTimeout(() => controller.abort(), requestTimeoutMs);
710
- // Compose the shutdown signal into the PUT abort (manual listeners, house
711
- // style — no AbortSignal.any) and arm the graceful scope for the upload's
712
- // duration, so Ctrl-C during a long PUT takes the honest detach path
713
- // instead of being unabortable.
714
- const shutdown = deps.shutdown ?? globalShutdown;
715
- const shutdownSignal = shutdown.signal;
716
- const onShutdownAbort = () => controller.abort(shutdownSignal.reason);
717
- const disarm = shutdown.arm();
718
- if (shutdownSignal.aborted)
719
- onShutdownAbort();
720
- else
721
- shutdownSignal.addEventListener('abort', onShutdownAbort, { once: true });
722
- let putResponse;
723
- try {
724
- putResponse = await fetchImpl(minted.uploadUrl, {
725
- method: 'PUT',
726
- headers: { 'content-type': contentType, 'content-length': String(stat.size) },
727
- body: Readable.toWeb(createReadStream(opts.file)),
728
- duplex: 'half',
729
- // assertSafePresignedUploadUrl vets the MINTED url, but a
730
- // default `redirect: 'follow'` would let a 3xx from that host resend
731
- // the request to an unvetted Location (e.g. a 303 → 169.254.169.254) —
732
- // an SSRF-shaped hop the guard never sees. A real S3 presigned PUT never
733
- // redirects, so refuse: the thrown TypeError falls through to the catch
734
- // below as a normal `presigned_put_failed` (no new error reason).
735
- redirect: 'error',
736
- signal: controller.signal,
737
- });
738
- }
739
- catch (cause) {
740
- // Interrupt outranks the timeout mapping: a Ctrl-C-aborted fetch must
741
- // surface as InterruptError (exit 130/143), never as a timeout.
742
- if (cause instanceof InterruptError)
743
- throw cause;
744
- if (shutdownSignal.aborted)
745
- throw shutdownSignal.reason;
746
- // Any other abort here is ours (the per-request timer): map to the CLI's
747
- // typed exit-7 timeout, same contract as HttpClient's per-request timeout.
748
- if (isAbortError(cause)) {
749
- throw new RequestTimeoutError(requestTimeoutMs);
750
- }
751
- throw presignedPutError(`network error before S3 responded: ${describeCause(cause)}`, minted.expiresInSeconds);
752
- }
753
- finally {
754
- clearTimeout(timer);
755
- shutdownSignal.removeEventListener('abort', onShutdownAbort);
756
- disarm();
757
- }
758
- if (!putResponse.ok) {
759
- const snippet = (await putResponse.text().catch(() => '')).slice(0, 300);
760
- throw presignedPutError(`S3 returned HTTP ${putResponse.status}${snippet ? ` — ${snippet}` : ''}`, minted.expiresInSeconds);
761
- }
762
- // ── Step 3 of 3: register the uploaded object ─────────────────────────────
763
- let registered;
764
- try {
765
- registered = await client.post(`/projects/${projectPath}/docs`, {
766
- body: { s3Key: minted.s3Key, displayName, docRole: role },
767
- headers: { 'idempotency-key': idempotencyKey },
768
- });
769
- }
770
- catch (cause) {
771
- if (cause instanceof ApiError)
772
- throw registerStepError(cause);
773
- // A register timeout needs the same step-3 context — it is precisely the
774
- // case where the caller can't tell whether the register landed. Class and
775
- // exit 7 are preserved; only the text gains the upload-succeeded /
776
- // safe-to-re-run explanation.
777
- if (cause instanceof RequestTimeoutError) {
778
- cause.message =
779
- `Document register timed out (step 3 of 3) — the S3 upload succeeded, and the ` +
780
- `register may or may not have landed. ${cause.message} Re-running the whole command ` +
781
- `is safe: the server upserts the document by its S3 key (no duplicate is created; a PRD re-register re-runs the embedding compute, but the embedding charge is idempotent per document — never billed twice).`;
782
- throw cause;
783
- }
784
- throw cause;
785
- }
786
- const result = {
787
- resourceId: registered.resourceId,
788
- displayName: registered.displayName ?? displayName,
789
- role: registered.docRole ?? role,
790
- size: stat.size,
791
- processStatus: registered.processStatus,
792
- };
793
- out.print(result, data => renderDocsUploadText(data));
794
- return result;
795
- }
796
- function isAbortError(cause) {
797
- return cause instanceof Error && cause.name === 'AbortError';
798
- }
799
- function describeCause(cause) {
800
- if (!(cause instanceof Error))
801
- return String(cause);
802
- // undici wraps network failures as `TypeError: fetch failed` with the
803
- // useful detail on `.cause` — surface both.
804
- const nested = cause.cause;
805
- const nestedMsg = nested instanceof Error ? ` (${nested.message})` : '';
806
- return `${cause.message}${nestedMsg}`;
807
- }
808
- /**
809
- * Defense-in-depth on the server-minted presigned URL.
810
- *
811
- * A REMOTE facade must mint a non-local `https:` URL; a localhost/private or
812
- * plain-http mint from a remote facade is exactly the anomaly to reject
813
- * (compromised/misconfigured facade or an active MITM) — the PUT would
814
- * otherwise send the user's file wherever that URL points, before any bytes
815
- * leave the machine. A facade that is ITSELF loopback (dev rig, localhost
816
- * e2e) is a deliberate operator configuration and is trusted to mint local
817
- * URLs — and ONLY loopback qualifies: the gate is a positive, fail-closed
818
- * check, because gating on "anything `assertNotLocal` dislikes" would
819
- * silently disable the guard for an unparsable base URL or a user-settable
820
- * private-range endpoint (`--endpoint-url https://10.1.2.3`). Literal checks
821
- * only (same scope as `assertNotLocal`); no host allow-listing by design.
822
- *
823
- * Known residual: a loopback facade that is really a TUNNEL to a remote
824
- * backend (`ssh -L`, a localhost corporate proxy) is trusted here even though
825
- * the real conversation is remote and MITM-able upstream. This is inherent to
826
- * "loopback facade = trusted dev rig" and accepted — the CLI cannot tell a
827
- * dev rig from a tunnel by the base URL alone.
828
- */
829
- function assertSafePresignedUploadUrl(uploadUrl, facadeBaseUrl) {
830
- if (isLoopbackFacade(facadeBaseUrl))
831
- return;
832
- const reject = (reason) => {
833
- throw ApiError.fromEnvelope({
834
- error: {
835
- code: 'VALIDATION_ERROR',
836
- message: `Refusing the presigned upload URL the server returned: ${reason}.`,
837
- nextAction: 'No bytes were uploaded. This can indicate a misconfigured or intercepted API ' +
838
- 'endpoint — verify --endpoint-url / TESTSPRITE_API_URL and retry.',
839
- requestId: 'local',
840
- details: { field: 'uploadUrl', reason: 'unsafe_presigned_url' },
841
- },
842
- });
843
- };
844
- let parsed;
845
- try {
846
- parsed = new URL(uploadUrl);
847
- }
848
- catch {
849
- return reject('it is not a valid URL');
850
- }
851
- if (parsed.protocol !== 'https:')
852
- return reject('it is not https');
853
- if (isLocalUrl(uploadUrl))
854
- return reject('it points at a local/private address');
855
- }
856
- /** True when `assertNotLocal` rejects the URL (localhost, RFC1918, link-local,
857
- * metadata, non-http(s), unparsable). Fail-closed in the REJECTION direction
858
- * only — used to refuse a suspicious mint, never to grant trust (that side
859
- * is `isLoopbackFacade`). */
860
- function isLocalUrl(url) {
861
- try {
862
- assertNotLocal(url, {
863
- field: 'upload-url',
864
- helpCommand: 'testsprite project docs upload',
865
- });
866
- return false;
867
- }
868
- catch {
869
- return true;
870
- }
871
- }
872
- /**
873
- * The facade-trust gate for `assertSafePresignedUploadUrl`.
874
- * Positive and narrow — only an explicitly-loopback facade (`localhost`,
875
- * a `127.0.0.0/8` literal, or `[::1]`) is trusted to mint local upload URLs.
876
- * Anything else — including an unparsable base URL or a private-range
877
- * endpoint — leaves the guard ON.
878
- */
879
- function isLoopbackFacade(url) {
880
- let parsed;
881
- try {
882
- parsed = new URL(url);
883
- }
884
- catch {
885
- return false;
886
- }
887
- // `localhost.` is the fully-qualified form of `localhost` (RFC 6761).
888
- const host = parsed.hostname.toLowerCase().replace(/\.$/, '');
889
- if (host === 'localhost')
890
- return true;
891
- if (/^127\.\d+\.\d+\.\d+$/.test(host))
892
- return true;
893
- return host === '[::1]';
894
- }
895
- /**
896
- * Step-2 failure: the presigned PUT to S3. Distinguished from a register
897
- * failure per the design non-negotiable — the fix is different (re-running
898
- * re-mints the URL; nothing was registered, so nothing is half-done).
899
- */
900
- function presignedPutError(detail, expiresInSeconds) {
901
- return new ApiError({
902
- code: 'UNAVAILABLE',
903
- message: `Presigned S3 upload failed (step 2 of 3): ${detail}`,
904
- nextAction: 'The document was NOT registered. Re-run the command — each run mints a fresh ' +
905
- `upload URL (presigned URLs expire, this one after ${Math.round(expiresInSeconds / 60)} minutes).`,
906
- requestId: 'local',
907
- details: { reason: 'presigned_put_failed' },
908
- });
909
- }
910
- /**
911
- * Step-3 failure: register. The server envelope (code, exit, requestId,
912
- * details) passes through unchanged; only the text gains step context so
913
- * the caller knows the upload itself already landed and a re-run is safe
914
- * (the server upserts the document by S3 key — no duplicate).
915
- */
916
- function registerStepError(cause) {
917
- return new ApiError({
918
- code: cause.code,
919
- message: `Document register failed (step 3 of 3) — the S3 upload succeeded, but the document is not registered yet. ${cause.message}`,
920
- nextAction: `${cause.nextAction ? `${cause.nextAction} ` : ''}` +
921
- 'Re-running the whole command is safe: the same file re-uploads and the server ' +
922
- 'upserts the document by its S3 key (no duplicate is created; a PRD re-register re-runs the embedding compute, but the embedding charge is idempotent per document — never billed twice).',
923
- requestId: cause.requestId,
924
- details: cause.details,
925
- }, cause.httpStatus, cause.retryAfterMs);
926
- }
927
- function formatDocSize(bytes) {
928
- if (bytes < 1024)
929
- return `${bytes} B`;
930
- if (bytes < 1024 * 1024)
931
- return `${Math.round(bytes / 1024)} KB`;
932
- return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
933
- }
934
- function renderDocsUploadText(r) {
935
- return [
936
- `uploaded ${r.displayName} (${formatDocSize(r.size)}) — processing started`,
937
- 'note: generation can use this source once processing and embedding finish',
938
- ' (check with `testsprite test plan generate` — it says if inputs are still processing)',
939
- ].join('\n');
940
- }
941
- function renderDocsUploadPlanText(p) {
942
- return [
943
- `would upload ${p.file} (${formatDocSize(p.size)}) to project ${p.projectId} as ${p.role}:`,
944
- ...p.steps.map((step, i) => ` ${i + 1}. ${step}`),
945
- ].join('\n');
946
- }
947
305
  export function createProjectCommand(deps = {}) {
948
306
  const project = new Command('project').description('Manage TestSprite projects');
949
307
  project
@@ -985,18 +343,10 @@ export function createProjectCommand(deps = {}) {
985
343
  });
986
344
  project
987
345
  .command('create')
988
- .description('Create a new project')
346
+ .description('Create a project; add where it runs with `project env create`')
989
347
  .option('--type <frontend|backend>', 'project type (required)')
990
348
  .option('--name <name>', 'project name (required)')
991
- .option('--url <url>', 'target URL (public http/https; a loopback http origin with an explicit port is frontend only; required for frontend unless --local; also required for backend on the V3 path, see `auth status`)')
992
- .option('--local <port>', 'shorthand for --url http://localhost:<port> (1-65535; excludes --url; frontend only; runs open a tunnel automatically)')
993
- .addOption(new Option('--local-host <host>', 'deprecated loopback host override; requires --local').hideHelp())
994
- .option('--skip-preflight', 'skip the local TCP listener check before project creation')
995
- .option('--description <text>', 'not supported — projects have no description (test-level descriptions are set on `test create`)')
996
- .option('--username <user>', 'optional auth username (give with --password)')
997
- .option('--password <pw>', 'optional auth password, with --username (--password-file for non-interactive)')
998
- .option('--password-file <path>', 'read password from file (if both are given, --password wins with a warning)')
999
- .option('--instruction <text>', 'optional FE plan-gen instruction hint')
349
+ .option('--instruction <text>', 'extra instructions: facts and rules the agent keeps in mind when it explores the app, writes tests or runs them')
1000
350
  .option('--test-id-attributes <list>', 'comma-separated DOM attributes the engine should prefer as locators, highest priority first ' +
1001
351
  '(e.g. data-element,data-testid). Unique values are exported as page.locator(\'[attr="…"]\').')
1002
352
  .option('--idempotency-key <token>', 'opaque idempotency token. Defaults to a UUIDv4 minted per invocation.')
@@ -1010,37 +360,28 @@ export function createProjectCommand(deps = {}) {
1010
360
  if (type !== 'frontend' && type !== 'backend') {
1011
361
  throw localValidationError('--type must be frontend or backend');
1012
362
  }
1013
- await runCreate({
1014
- ...resolveCommonOptions(command, deps.env),
363
+ const common = resolveCommonOptions(command, deps.env);
364
+ const created = await runCreate({
365
+ ...common,
1015
366
  type,
1016
367
  name: cmdOpts.name,
1017
- targetUrl: cmdOpts.url,
1018
- local: cmdOpts.local,
1019
- localHost: cmdOpts.localHost,
1020
- skipPreflight: cmdOpts.skipPreflight,
1021
- description: cmdOpts.description,
1022
- username: cmdOpts.username,
1023
- password: cmdOpts.password,
1024
- passwordFile: cmdOpts.passwordFile,
1025
368
  instruction: cmdOpts.instruction,
1026
369
  testIdAttributes: cmdOpts.testIdAttributes !== undefined
1027
370
  ? parseTestIdAttributesFlag(cmdOpts.testIdAttributes, 'test-id-attributes')
1028
371
  : undefined,
1029
372
  idempotencyKey: cmdOpts.idempotencyKey,
1030
373
  }, deps);
374
+ // The project just made is the one the next agent command here works on
375
+ // (`plan` without --project), as a plan started here makes its project
376
+ // this folder's. --dry-run made none.
377
+ if (!common.dryRun && created.projectId)
378
+ rememberCreated(created.projectId, deps);
1031
379
  });
1032
380
  project
1033
381
  .command('update <project-id>')
1034
- .description('Update project metadata')
382
+ .description("Update a project's name, extra instructions or test-id attributes")
1035
383
  .option('--name <name>', 'new project name')
1036
- .option('--url <url>', 'new target URL (public http/https, or a loopback http origin with an explicit port)')
1037
- .option('--local <port>', 'shorthand for --url http://localhost:<port> (1-65535; excludes --url; frontend only)')
1038
- .addOption(new Option('--local-host <host>', 'deprecated loopback host override; requires --local').hideHelp())
1039
- .option('--skip-preflight', 'skip the local TCP listener check before the update')
1040
- .option('--username <user>', 'new auth username')
1041
- .option('--password <pw>', 'new auth password')
1042
- .option('--password-file <path>', 'read new password from file (if both are given, --password wins with a warning)')
1043
- .option('--instruction <text>', 'new FE plan-gen instruction hint')
384
+ .option('--instruction <text>', 'replace the current instructions (read them with project get)')
1044
385
  .option('--test-id-attributes <list>', 'comma-separated DOM attributes the engine should prefer as locators, highest priority first ' +
1045
386
  '(e.g. data-element,data-testid); replaces the current list')
1046
387
  .option('--clear-test-id-attributes', 'remove the test-id attribute list (engine falls back to data-testid)', false)
@@ -1051,13 +392,6 @@ export function createProjectCommand(deps = {}) {
1051
392
  ...resolveCommonOptions(command, deps.env),
1052
393
  projectId,
1053
394
  name: cmdOpts.name,
1054
- targetUrl: cmdOpts.url,
1055
- local: cmdOpts.local,
1056
- localHost: cmdOpts.localHost,
1057
- skipPreflight: cmdOpts.skipPreflight,
1058
- username: cmdOpts.username,
1059
- password: cmdOpts.password,
1060
- passwordFile: cmdOpts.passwordFile,
1061
395
  instruction: cmdOpts.instruction,
1062
396
  testIdAttributes: cmdOpts.testIdAttributes !== undefined
1063
397
  ? parseTestIdAttributesFlag(cmdOpts.testIdAttributes, 'test-id-attributes')
@@ -1087,121 +421,9 @@ export function createProjectCommand(deps = {}) {
1087
421
  idempotencyKey: cmdOpts.idempotencyKey,
1088
422
  }, deps);
1089
423
  });
1090
- project
1091
- .command('credential <project-id>')
1092
- .summary('Set the static credential injected into backend tests')
1093
- .description('Set the static backend credential injected into every backend test. Free tier.\n' +
1094
- "On V3 accounts it is stored on the project's default environment.")
1095
- .requiredOption('--type <type>', 'required: public | "Bearer token" | "API key" | "basic token" (exact, lowercase)')
1096
- .option('--credential <value>', 'credential value (required unless --type public)')
1097
- .option('--credential-file <path>', 'read the credential value from a file')
1098
- .option('--idempotency-key <token>', 'opaque idempotency token. Defaults to a UUIDv4 minted per invocation.')
1099
- .addHelpText('after', GLOBAL_OPTS_HINT)
1100
- .action(async (projectId, cmdOpts, command) => {
1101
- await runCredential({
1102
- ...resolveCommonOptions(command, deps.env),
1103
- projectId,
1104
- authType: cmdOpts.type,
1105
- credential: cmdOpts.credential,
1106
- credentialFile: cmdOpts.credentialFile,
1107
- idempotencyKey: cmdOpts.idempotencyKey,
1108
- }, deps);
1109
- });
1110
- project
1111
- .command('auto-auth <project-id>')
1112
- .summary('Configure auto-refresh login for backend tests (paid)')
1113
- .description('Configure the recurring-token (auto-refresh login) for backend tests (paid plans):\n' +
1114
- 'a fresh token is fetched on each run and injected into every backend test.\n' +
1115
- 'Each method needs its own flags (password: --login-url, --token-path, ...;\n' +
1116
- 'refresh_token: --token-endpoint, --client-id, ...; aws_cognito_refresh: --region, ...).')
1117
- .requiredOption('--method <method>', 'password | refresh_token | aws_cognito_refresh')
1118
- .requiredOption('--inject <where>', 'bearer | header | cookie')
1119
- .option('--disable', 'turn auto-auth off, keeping stored config (--method and --inject are still required)')
1120
- .option('--inject-key <name>', 'header/cookie name when --inject is header/cookie')
1121
- // password method
1122
- .option('--login-url <url>', 'login endpoint (method=password)')
1123
- .option('--login-method <verb>', 'POST | PUT (method=password)')
1124
- .option('--login-content-type <ct>', 'application/json | application/x-www-form-urlencoded')
1125
- .option('--login-body-template <tpl>', 'login body template with {{username}}/{{password}}')
1126
- .option('--username <user>', 'login username (method=password)')
1127
- .option('--password <pw>', 'login password (method=password)')
1128
- .option('--password-file <path>', 'read login password from a file')
1129
- .option('--token-path <jsonpath>', 'JSONPath to the token in the login response')
1130
- // refresh_token method
1131
- .option('--token-endpoint <url>', 'OAuth token endpoint (method=refresh_token)')
1132
- .option('--client-id <id>', 'OAuth client id')
1133
- .option('--client-secret <secret>', 'OAuth client secret')
1134
- .option('--client-secret-file <path>', 'read OAuth client secret from a file')
1135
- .option('--refresh-token <token>', 'OAuth/Cognito refresh token')
1136
- .option('--refresh-token-file <path>', 'read the refresh token from a file')
1137
- .option('--scope <scope>', 'OAuth scope')
1138
- // aws_cognito_refresh method
1139
- .option('--region <region>', "AWS region (method=aws_cognito_refresh, e.g. 'us-east-1')")
1140
- .option('--idempotency-key <token>', 'opaque idempotency token. Defaults to a UUIDv4 minted per invocation.')
1141
- .addHelpText('after', GLOBAL_OPTS_HINT)
1142
- .action(async (projectId, cmdOpts, command) => {
1143
- await runAutoAuth({
1144
- ...resolveCommonOptions(command, deps.env),
1145
- projectId,
1146
- disable: cmdOpts.disable,
1147
- method: cmdOpts.method,
1148
- inject: cmdOpts.inject,
1149
- injectKey: cmdOpts.injectKey,
1150
- loginUrl: cmdOpts.loginUrl,
1151
- loginMethod: cmdOpts.loginMethod,
1152
- loginContentType: cmdOpts.loginContentType,
1153
- loginBodyTemplate: cmdOpts.loginBodyTemplate,
1154
- username: cmdOpts.username,
1155
- password: cmdOpts.password,
1156
- passwordFile: cmdOpts.passwordFile,
1157
- tokenPath: cmdOpts.tokenPath,
1158
- tokenEndpoint: cmdOpts.tokenEndpoint,
1159
- clientId: cmdOpts.clientId,
1160
- clientSecret: cmdOpts.clientSecret,
1161
- clientSecretFile: cmdOpts.clientSecretFile,
1162
- refreshToken: cmdOpts.refreshToken,
1163
- refreshTokenFile: cmdOpts.refreshTokenFile,
1164
- scope: cmdOpts.scope,
1165
- region: cmdOpts.region,
1166
- idempotencyKey: cmdOpts.idempotencyKey,
1167
- }, deps);
1168
- });
1169
- const docs = new Command('docs')
1170
- .summary('Manage project documents (plan-generation sources)')
1171
- .description('Manage project documents — the sources plan generation feeds on');
1172
- docs
1173
- .command('upload <file>')
1174
- .summary('Upload an API spec or PRD as a project source')
1175
- .description('Upload an API spec or PRD as a project source: mint a presigned S3 URL, stream the file\n' +
1176
- 'to it, register the document — which starts processing + embedding and spends credits\n' +
1177
- '(see `testsprite usage`). The local file is only read.\n' +
1178
- '\nExit codes:\n' +
1179
- ' 0 upload registered (processing started)\n' +
1180
- ' 3 auth error\n' +
1181
- ' 4 project not found (or not accessible in this workspace)\n' +
1182
- ' 5 validation error (missing/empty file, bad --role)\n' +
1183
- ' 7 request timeout (also: backend predates the docs routes)\n' +
1184
- ' 10 presigned S3 PUT failed — re-run to mint a fresh URL')
1185
- .option('--project <id>', 'project id (required unless TESTSPRITE_PROJECT_ID is set)')
1186
- .option('--role <role>', 'document role: api-doc (API spec, default) | prd')
1187
- .option('--name <display-name>', 'display name for the document (default: file basename)')
1188
- .option('--idempotency-key <token>', 'opaque idempotency token. Defaults to a UUIDv4 minted per invocation.')
1189
- .addHelpText('after', GLOBAL_OPTS_HINT)
1190
- .action(async (file, cmdOpts, command) => {
1191
- await runDocsUpload({
1192
- ...resolveCommonOptions(command, deps.env),
1193
- file,
1194
- projectId: cmdOpts.project,
1195
- role: cmdOpts.role,
1196
- name: cmdOpts.name,
1197
- idempotencyKey: cmdOpts.idempotencyKey,
1198
- }, deps);
1199
- });
1200
- project.addCommand(docs);
1201
- // `project env <verb>` — the per-project environment surface (credentials,
1202
- // URL, default). Own module; `deps` threaded so tests inject.
424
+ // `project env <verb>` — the per-project environment surface (URL, sign-in,
425
+ // backend credentials, default). Own module; `deps` threaded so tests inject.
1203
426
  project.addCommand(createProjectEnvCommand(deps));
1204
- project.addCommand(createProjectSignInCommand(deps));
1205
427
  return project;
1206
428
  }
1207
429
  function parseFlag(raw, flagName) {
@@ -1221,6 +443,15 @@ function parseFlag(raw, flagName) {
1221
443
  }
1222
444
  return n;
1223
445
  }
446
+ function rememberCreated(projectId, deps) {
447
+ const cwd = deps.cwd ?? process.cwd();
448
+ try {
449
+ rememberProject(readRepository(cwd, deps.git ?? runGit)?.root ?? cwd, projectId);
450
+ }
451
+ catch {
452
+ // A folder the CLI can't write to keeps no state; the next command then needs --project.
453
+ }
454
+ }
1224
455
  function resolveCommonOptions(command, env) {
1225
456
  const globals = command.optsWithGlobals();
1226
457
  // P2-8: validate --output before allowing silent fallback to 'text'.
@@ -1256,34 +487,29 @@ function makeOutput(mode, deps) {
1256
487
  const PROJECT_LIST_COLUMNS = [
1257
488
  {
1258
489
  header: 'ID',
1259
- width: rows => Math.max(2, ...rows.map(project => project.id.length)),
490
+ width: rows => Math.max(2, ...rows.map(project => terminalWidth(project.id))),
1260
491
  render: project => project.id,
1261
492
  },
1262
493
  {
1263
494
  header: 'NAME',
1264
- width: rows => Math.max(4, ...rows.map(project => project.name.length)),
495
+ width: rows => Math.max(4, ...rows.map(project => terminalWidth(project.name))),
1265
496
  render: project => project.name,
1266
497
  },
1267
498
  { header: 'TYPE', width: 8, render: project => project.type },
1268
499
  { header: 'FROM', width: 6, render: project => project.createdFrom },
1269
500
  {
1270
501
  header: 'ORG',
1271
- width: rows => Math.max(3, ...rows.map(project => (project.orgName ?? project.orgId ?? '').length)),
502
+ width: rows => Math.max(3, ...rows.map(project => terminalWidth(project.orgName ?? project.orgId ?? ''))),
1272
503
  render: project => project.orgName ?? project.orgId ?? '',
1273
504
  },
1274
- {
1275
- header: 'URL',
1276
- width: rows => Math.max(3, ...rows.map(project => renderProjectUrl(project).length)),
1277
- render: renderProjectUrl,
1278
- },
1279
505
  {
1280
506
  header: 'CREATED',
1281
- width: rows => Math.max(7, ...rows.map(project => project.createdAt.length)),
507
+ width: rows => Math.max(7, ...rows.map(project => terminalWidth(project.createdAt))),
1282
508
  render: project => project.createdAt,
1283
509
  },
1284
510
  {
1285
511
  header: 'DEFAULT ENV',
1286
- width: rows => Math.max(11, ...rows.map(project => (project.defaultEnvironment ?? '-').length)),
512
+ width: rows => Math.max(11, ...rows.map(project => terminalWidth(project.defaultEnvironment ?? '-'))),
1287
513
  render: project => project.defaultEnvironment ?? '-',
1288
514
  },
1289
515
  {
@@ -1292,24 +518,24 @@ const PROJECT_LIST_COLUMNS = [
1292
518
  render: project => project.environmentCount?.toString() ?? '-',
1293
519
  },
1294
520
  ];
1295
- function renderProjectUrl(project) {
1296
- const url = project.targetUrl ?? '';
1297
- return project.originMode === 'local' ? `${url ? `${url} ` : ''}(Local)` : url;
1298
- }
1299
521
  /**
1300
522
  * Default (no explicit `--columns`) column set. ORG is included only when
1301
- * at least one row carries `orgId`; URL is included when a row is local.
1302
- * Older responses retain the existing default table columns.
523
+ * at least one row carries `orgId`.
1303
524
  */
1304
525
  function defaultProjectListColumns(rows) {
1305
526
  const hasOrgInfo = rows.some(project => project.orgId !== undefined);
1306
- const hasLocalProject = rows.some(project => project.originMode === 'local');
1307
- return PROJECT_LIST_COLUMNS.filter(column => (column.header !== 'ORG' || hasOrgInfo) && (column.header !== 'URL' || hasLocalProject));
527
+ return PROJECT_LIST_COLUMNS.filter(column => column.header !== 'ORG' || hasOrgInfo);
1308
528
  }
1309
- function renderProjectListText(page, options = {}) {
529
+ /**
530
+ * Render `project list`'s text table over a fetched page. Falls back to the
531
+ * default column set (ORG/URL included only when the data carries them).
532
+ * Exported for direct unit coverage of the CJK display-width regression
533
+ * (#369): later columns must not shift when a project name is full-width.
534
+ */
535
+ export function renderProjectListText(page, options = {}) {
1310
536
  if (page.items.length === 0) {
1311
537
  return page.nextToken
1312
- ? `No projects on this page.\nnextToken: ${page.nextToken}`
538
+ ? `No projects on this page.\nnextToken: ${terminalSafeLine(page.nextToken)}`
1313
539
  : 'No projects.';
1314
540
  }
1315
541
  // Explicit --columns: resolve against the FULL master set (so `org` can be
@@ -1323,44 +549,38 @@ function renderProjectListText(page, options = {}) {
1323
549
  }),
1324
550
  ];
1325
551
  if (page.nextToken)
1326
- lines.push('', `nextToken: ${page.nextToken}`);
552
+ lines.push('', `nextToken: ${terminalSafeLine(page.nextToken)}`);
1327
553
  return lines.join('\n');
1328
554
  }
1329
555
  function renderProjectText(p) {
1330
556
  const lines = [
1331
- `id: ${p.id}`,
1332
- `name: ${p.name}`,
1333
- `type: ${p.type}`,
1334
- `createdFrom: ${p.createdFrom}`,
1335
- `createdAt: ${p.createdAt}`,
1336
- `updatedAt: ${p.updatedAt}`,
557
+ `id: ${terminalSafeLine(p.id)}`,
558
+ `name: ${terminalSafeLine(p.name)}`,
559
+ `type: ${terminalSafeLine(p.type)}`,
560
+ `createdFrom: ${terminalSafeLine(p.createdFrom)}`,
561
+ `createdAt: ${terminalSafeLine(p.createdAt)}`,
562
+ `updatedAt: ${terminalSafeLine(p.updatedAt)}`,
1337
563
  ];
1338
564
  if (p.orgId !== undefined) {
1339
- lines.push(`org: ${p.orgName ?? '(name unknown)'} (${p.orgId})`);
565
+ lines.push(`org: ${terminalSafeLine(p.orgName ?? '(name unknown)')} (${terminalSafeLine(p.orgId)})`);
566
+ }
567
+ if (p.instruction !== undefined) {
568
+ lines.push(p.instruction
569
+ ? `instruction:\n ${terminalSafe(p.instruction).replaceAll('\n', '\n ')}`
570
+ : 'instruction: (not set)');
1340
571
  }
1341
572
  if ('defaultEnvironment' in p) {
1342
- lines.push(`defaultEnv: ${p.defaultEnvironment ?? '-'}`);
573
+ lines.push(`defaultEnv: ${terminalSafeLine(p.defaultEnvironment ?? '-')}`);
1343
574
  }
1344
575
  if ('environmentCount' in p) {
1345
576
  const count = p.environmentCount;
1346
- lines.push(`envs: ${count}${count !== undefined && count > 0 ? ` (list with: testsprite project env list ${p.id})` : ''}`);
1347
- }
1348
- // Presence, not truthiness — see the `targetUrl` docstring on `CliProject`.
1349
- // `'targetUrl' in p` distinguishes "the backend answered 'no URL'" (render the
1350
- // hint) from "this endpoint doesn't report it" (say nothing).
1351
- if ('targetUrl' in p) {
1352
- lines.push(p.targetUrl
1353
- ? `targetUrl: ${renderProjectUrl(p)}`
1354
- : `targetUrl: (not set — set one with: testsprite project update ${p.id} --url <url>)`);
577
+ lines.push(`envs: ${count}${count !== undefined && count > 0 ? ` (list with: testsprite project env list ${terminalSafeLine(p.id)})` : ''}`);
1355
578
  }
1356
- if (p.originMode === 'local' && !p.targetUrl) {
1357
- lines.push('originMode: local (Local)');
1358
- }
1359
- // Presence-keyed like targetUrl: older backends don't report the field at all.
579
+ // Presence-keyed: older backends don't report the field at all.
1360
580
  if ('testIdAttributes' in p) {
1361
581
  lines.push(p.testIdAttributes && p.testIdAttributes.length > 0
1362
- ? `testIdAttrs: ${p.testIdAttributes.join(', ')} (locator priority, highest first)`
1363
- : `testIdAttrs: (not set — engine default data-testid; set with: testsprite project update ${p.id} --test-id-attributes <list>)`);
582
+ ? `testIdAttrs: ${terminalSafeLine(p.testIdAttributes.join(', '))} (locator priority, highest first)`
583
+ : `testIdAttrs: (not set — engine default data-testid; set with: testsprite project update ${terminalSafeLine(p.id)} --test-id-attributes <list>)`);
1364
584
  }
1365
585
  return lines.join('\n');
1366
586
  }
@@ -1370,70 +590,32 @@ function renderProjectText(p) {
1370
590
  * field is proven reliable) because the create response's id field name and
1371
591
  * `updatedAt` presence are not guaranteed — see `CliCreateProjectResponse`.
1372
592
  */
1373
- function renderCreateProjectText(p, localTarget) {
593
+ function renderCreateProjectText(p) {
1374
594
  const lines = [
1375
- `id: ${resolveCreatedProjectId(p) ?? '(unknown)'}`,
1376
- `name: ${p.name}`,
1377
- `type: ${p.type}`,
1378
- `createdFrom: ${p.createdFrom}`,
1379
- `createdAt: ${p.createdAt}`,
595
+ `id: ${terminalSafeLine(resolveCreatedProjectId(p) ?? '(unknown)')}`,
596
+ `name: ${terminalSafeLine(p.name)}`,
597
+ `type: ${terminalSafeLine(p.type)}`,
598
+ `createdFrom: ${terminalSafeLine(p.createdFrom)}`,
599
+ `createdAt: ${terminalSafeLine(p.createdAt)}`,
1380
600
  ];
1381
601
  if (p.updatedAt !== undefined)
1382
- lines.push(`updatedAt: ${p.updatedAt}`);
1383
- if (localTarget) {
1384
- const projectId = resolveCreatedProjectId(p) ?? '<project-id>';
1385
- const url = buildLocalTargetUrl(localTarget.host, localTarget.port);
1386
- lines.push(`Local project: TestSprite will reach ${url} only through a tunnel from this machine.`, 'Next: write a plan and run it locally:',
1387
- // The only next step a --local project gets (it has no first-suite hint),
1388
- // so it names how to get a plan file. `--plan-from` takes the project from
1389
- // the file and ignores `--project`, hence "set projectId" and no flag.
1390
- ' testsprite test create --plan-template > plan.json', ` In plan.json, set projectId to ${projectId} and edit the steps.`, ' testsprite test create --plan-from plan.json', ' testsprite test run <test-id>', `Portal runs of this project stay blocked (free) until you set a public URL with: testsprite project update ${projectId} --url https://...`);
1391
- }
602
+ lines.push(`updatedAt: ${terminalSafeLine(p.updatedAt)}`);
1392
603
  return lines.join('\n');
1393
604
  }
1394
- function renderUpdateText(r, localTarget) {
605
+ function renderUpdateText(r) {
1395
606
  const lines = [
1396
- `id: ${resolveUpdatedProjectId(r) ?? '(unknown)'}`,
1397
- `updatedFields: ${r.updatedFields?.join(', ') ?? '(none)'}`,
607
+ `id: ${terminalSafeLine(resolveUpdatedProjectId(r) ?? '(unknown)')}`,
608
+ `updatedFields: ${terminalSafeLine(r.updatedFields?.join(', ') ?? '(none)')}`,
1398
609
  ];
1399
610
  if (r.updatedAt !== undefined)
1400
- lines.push(`updatedAt: ${r.updatedAt}`);
1401
- if (r.environment !== undefined) {
1402
- lines.push(`environment: ${r.environment.name} (default)`);
1403
- const labels = {
1404
- 'environment.url': 'Environment URL updated',
1405
- 'environment.credentials': 'Environment credentials updated',
1406
- 'project.name': 'Project name updated',
1407
- 'project.instruction': 'Project instruction updated',
1408
- 'project.testIdAttributes': 'Project test ID attributes updated',
1409
- };
1410
- for (const effect of r.effects ?? []) {
1411
- if (labels[effect])
1412
- lines.push(`effect: ${labels[effect]}`);
1413
- }
1414
- }
1415
- if (localTarget) {
1416
- const url = buildLocalTargetUrl(localTarget.host, localTarget.port);
1417
- lines.push(`Local project: TestSprite will reach ${url} only through a tunnel from this machine.`, 'Run its tests with: testsprite test run <test-id> (the CLI opens a tunnel automatically).');
1418
- }
611
+ lines.push(`updatedAt: ${terminalSafeLine(r.updatedAt)}`);
1419
612
  return lines.join('\n');
1420
613
  }
1421
614
  function renderDeleteText(r) {
1422
- return [`projectId ${r.projectId}`, `deletedAt ${r.deletedAt}`].join('\n');
1423
- }
1424
- /**
1425
- * `--project` resolution for `project docs upload` — mirrors test.ts's
1426
- * resolveProjectId/requireProjectId so `TESTSPRITE_PROJECT_ID` works here the
1427
- * same as on every other command. Flag wins over env.
1428
- */
1429
- function requireDocsProjectId(projectId, deps) {
1430
- const explicit = projectId?.trim();
1431
- if (explicit && explicit.length > 0)
1432
- return explicit;
1433
- const envValue = (deps.env ?? process.env).TESTSPRITE_PROJECT_ID?.trim();
1434
- if (envValue && envValue.length > 0)
1435
- return envValue;
1436
- throw localValidationError('--project <id> is required; pass --project <id> or set TESTSPRITE_PROJECT_ID');
615
+ return [
616
+ `projectId ${terminalSafeLine(r.projectId)}`,
617
+ `deletedAt ${terminalSafeLine(r.deletedAt)}`,
618
+ ].join('\n');
1437
619
  }
1438
620
  /**
1439
621
  * A backend that predates the testIdAttributes field answers a PATCH/POST that