@testsprite/testsprite-cli 0.7.0 → 0.9.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 (74) hide show
  1. package/README.md +62 -45
  2. package/dist/commands/agent.d.ts +3 -0
  3. package/dist/commands/agent.js +79 -10
  4. package/dist/commands/ci.d.ts +88 -0
  5. package/dist/commands/ci.js +432 -0
  6. package/dist/commands/doctor.js +100 -1
  7. package/dist/commands/init.d.ts +45 -2
  8. package/dist/commands/init.js +198 -29
  9. package/dist/commands/project.d.ts +78 -0
  10. package/dist/commands/project.js +439 -5
  11. package/dist/commands/test.d.ts +193 -4
  12. package/dist/commands/test.js +1948 -398
  13. package/dist/commands/testlist.js +15 -9
  14. package/dist/commands/tunnel.d.ts +72 -0
  15. package/dist/commands/tunnel.js +367 -0
  16. package/dist/index.js +107 -38
  17. package/dist/lib/agent-detect.d.ts +53 -0
  18. package/dist/lib/agent-detect.js +198 -0
  19. package/dist/lib/dry-run/samples.d.ts +9 -0
  20. package/dist/lib/dry-run/samples.js +116 -0
  21. package/dist/lib/gh-output.d.ts +7 -0
  22. package/dist/lib/gh-output.js +50 -7
  23. package/dist/lib/http.d.ts +104 -0
  24. package/dist/lib/http.js +126 -7
  25. package/dist/lib/interrupt.d.ts +38 -13
  26. package/dist/lib/interrupt.js +130 -15
  27. package/dist/lib/local-target.d.ts +95 -0
  28. package/dist/lib/local-target.js +184 -0
  29. package/dist/lib/plan-poll.d.ts +171 -0
  30. package/dist/lib/plan-poll.js +442 -0
  31. package/dist/lib/plans.types.d.ts +130 -0
  32. package/dist/lib/plans.types.js +31 -0
  33. package/dist/lib/poll-support.d.ts +26 -0
  34. package/dist/lib/poll-support.js +65 -0
  35. package/dist/lib/poll.d.ts +1 -0
  36. package/dist/lib/poll.js +2 -40
  37. package/dist/lib/response-schemas.d.ts +13 -0
  38. package/dist/lib/response-schemas.js +46 -0
  39. package/dist/lib/run-progress.d.ts +41 -0
  40. package/dist/lib/run-progress.js +56 -0
  41. package/dist/lib/runs.types.d.ts +50 -0
  42. package/dist/lib/skill-nudge.d.ts +13 -5
  43. package/dist/lib/skill-nudge.js +40 -14
  44. package/dist/lib/target-url-preflight.js +3 -3
  45. package/dist/lib/target-url.d.ts +54 -8
  46. package/dist/lib/target-url.js +274 -68
  47. package/dist/lib/telemetry.d.ts +11 -0
  48. package/dist/lib/telemetry.js +1 -0
  49. package/dist/lib/ticker.d.ts +8 -0
  50. package/dist/lib/ticker.js +3 -0
  51. package/dist/lib/tunnel-session.d.ts +138 -0
  52. package/dist/lib/tunnel-session.js +249 -0
  53. package/dist/lib/tunnel.types.d.ts +54 -0
  54. package/dist/lib/tunnel.types.js +8 -0
  55. package/dist/vendor/tunnel-client/client.d.ts +82 -0
  56. package/dist/vendor/tunnel-client/client.js +924 -0
  57. package/dist/vendor/tunnel-client/config.d.ts +49 -0
  58. package/dist/vendor/tunnel-client/config.js +50 -0
  59. package/dist/vendor/tunnel-client/index.d.ts +9 -0
  60. package/dist/vendor/tunnel-client/index.js +9 -0
  61. package/dist/vendor/tunnel-client/lodash-lite.d.ts +14 -0
  62. package/dist/vendor/tunnel-client/lodash-lite.js +24 -0
  63. package/dist/vendor/tunnel-client/protocol.d.ts +60 -0
  64. package/dist/vendor/tunnel-client/protocol.js +143 -0
  65. package/dist/vendor/tunnel-client/types.d.ts +101 -0
  66. package/dist/vendor/tunnel-client/types.js +10 -0
  67. package/dist/vendor/tunnel-client/ws-compat.d.ts +206 -0
  68. package/dist/vendor/tunnel-client/ws-compat.js +316 -0
  69. package/dist/version.d.ts +1 -1
  70. package/dist/version.js +1 -1
  71. package/package.json +2 -1
  72. package/skills/testsprite-onboard.skill.md +60 -4
  73. package/skills/testsprite-verify.codex.md +22 -16
  74. package/skills/testsprite-verify.skill.md +27 -18
package/dist/index.js CHANGED
@@ -2,11 +2,13 @@
2
2
  import { Command, CommanderError } from 'commander';
3
3
  import { createAgentCommand } from './commands/agent.js';
4
4
  import { createAuthCommand } from './commands/auth.js';
5
+ import { createCiCommand } from './commands/ci.js';
5
6
  import { createCompletionCommand } from './commands/completion.js';
6
7
  import { createDoctorCommand } from './commands/doctor.js';
7
8
  import { addSetupOptions, createDeprecatedInitCommand, createSetupCommand, runConfigureViaSetup, } from './commands/init.js';
8
9
  import { createProjectCommand } from './commands/project.js';
9
10
  import { createScheduleCommand } from './commands/schedule.js';
11
+ import { createTunnelCommand } from './commands/tunnel.js';
10
12
  import { createTestCommand } from './commands/test.js';
11
13
  import { createTestListCommand } from './commands/testlist.js';
12
14
  import { createUsageCommand } from './commands/usage.js';
@@ -68,7 +70,9 @@ program.addCommand(authCommand);
68
70
  program.addCommand(createProjectCommand({}));
69
71
  program.addCommand(createTestCommand());
70
72
  program.addCommand(createTestListCommand());
73
+ program.addCommand(createCiCommand({}));
71
74
  program.addCommand(createScheduleCommand({}));
75
+ program.addCommand(createTunnelCommand({}));
72
76
  program.addCommand(createAgentCommand({}));
73
77
  program.addCommand(createUsageCommand());
74
78
  program.addCommand(createDoctorCommand());
@@ -111,6 +115,13 @@ let telemetryEmit = false;
111
115
  // Auth resolved in the preAction hook, before the command's action runs, so
112
116
  // `auth remove` (which deletes the profile) is still reported on the key it used.
113
117
  let telemetryAuth;
118
+ // True when the leaf command that is about to run carries a `--local` option
119
+ // value — i.e. `test run --local <port>` (no other command declares `--local`).
120
+ // Set by the preAction hook, BEFORE the command's own validation runs, so a
121
+ // zero-network `--local` refusal (dead port, an incompatible flag combo) is
122
+ // still reported: the whole point of this field is to see the attempts a
123
+ // backend-side mint/attach event never observes.
124
+ let telemetryLocal = false;
114
125
  // Propagate exitOverride AND the buffered outputError config to every
115
126
  // subcommand in the tree. Commander's addCommand() does NOT inherit either
116
127
  // from the parent, so commands built externally (createTestCommand, etc.) and
@@ -130,6 +141,36 @@ function applyExitOverrideDeep(cmd) {
130
141
  }
131
142
  }
132
143
  applyExitOverrideDeep(program);
144
+ function isRegisteredRootCommand(name) {
145
+ return (name === 'help' ||
146
+ program.commands.some(command => command.name() === name || command.aliases().includes(name)));
147
+ }
148
+ /**
149
+ * Commander checks its implicit help option before reporting an unknown root
150
+ * command. It also falls back to root help when `help <command>` names a
151
+ * missing command. Detect both cases while help is being rendered so the
152
+ * normal unknown-command error wins before any misleading help is written.
153
+ */
154
+ function unknownRootCommandMaskedByHelp(args) {
155
+ const [first, second] = args;
156
+ if (first === 'help') {
157
+ return second && !isRegisteredRootCommand(second) ? second : undefined;
158
+ }
159
+ if (!first || first.startsWith('-') || isRegisteredRootCommand(first))
160
+ return undefined;
161
+ return args.slice(1).some(arg => arg === '--help' || arg === '-h') ? first : undefined;
162
+ }
163
+ program.addHelpText('beforeAll', context => {
164
+ if (context.command !== program)
165
+ return '';
166
+ const unknownCommand = unknownRootCommandMaskedByHelp(program.args);
167
+ if (unknownCommand) {
168
+ program.error(`error: unknown command '${unknownCommand}'`, {
169
+ code: 'commander.unknownCommand',
170
+ });
171
+ }
172
+ return '';
173
+ });
133
174
  /**
134
175
  * Render a leaf command's full path (group + leaf), e.g. `test run` /
135
176
  * `auth whoami`, by walking parents up to (but not including) the root program.
@@ -158,6 +199,10 @@ program.hook('preAction', (_thisCommand, actionCommand) => {
158
199
  const commandPath = commandPathOf(actionCommand);
159
200
  // Record which leaf command ran, for the telemetry emit around parseAsync.
160
201
  ranCommandPath = commandPath;
202
+ // `--local` is only declared on `test run`, so this is false for every
203
+ // other command. The raw opt is a port string; only its presence is
204
+ // recorded (see `telemetryLocal`'s own comment — never the value).
205
+ telemetryLocal = globals.local !== undefined;
161
206
  // See `isPlanTemplateInvocation` for why this one case is
162
207
  // filtered here rather than in skill-nudge.ts / update-check.ts.
163
208
  const isPlanTemplate = isPlanTemplateInvocation(commandPath, globals.planTemplate);
@@ -223,15 +268,26 @@ try {
223
268
  exitCode: 0,
224
269
  durationMs: Date.now() - telemetryStartedAt,
225
270
  ...telemetryGlobals(),
271
+ local: telemetryLocal,
226
272
  }, { resolvedAuth: telemetryAuth });
227
273
  }
228
274
  }
229
275
  catch (err) {
230
276
  const telemetryOutcome = classifyCliError(err);
231
277
  // Flush the outcome AFTER the error is rendered to stderr below (via each
232
- // branch's `flushThenExit`), so a slow backend never delays the user's error.
233
- // The classification mirrors the exit-code mapping the branches apply.
234
- const flushThenExit = async (code) => {
278
+ // branch's `flushThenSetExitCode`), so a slow backend never delays the
279
+ // user's error. The classification mirrors the exit-code mapping the
280
+ // branches apply.
281
+ //
282
+ // DEV-673: SET `process.exitCode` and let the event loop drain instead of
283
+ // forcing `process.exit()`. A forced exit tears the process down while the
284
+ // just-completed HTTPS request's TLS socket is still mid-close; on Windows
285
+ // libuv asserts on the half-closed handle (src/win/async.c) and the process
286
+ // dies with 0xC0000409 (-1073740791) — overwriting the mapped exit code
287
+ // with a crash code and voiding the documented exit-code contract for every
288
+ // script/CI/agent that branches on it. Draining takes milliseconds and is
289
+ // exactly how the success path above already exits.
290
+ const flushThenSetExitCode = async (code) => {
235
291
  if (telemetryEmit) {
236
292
  await recordOutcome({
237
293
  command: ranCommandPath,
@@ -240,12 +296,14 @@ catch (err) {
240
296
  errorCode: telemetryOutcome.errorCode,
241
297
  durationMs: Date.now() - telemetryStartedAt,
242
298
  ...telemetryGlobals(),
299
+ local: telemetryLocal,
243
300
  }, { resolvedAuth: telemetryAuth });
244
301
  }
245
- process.exit(code);
302
+ process.exitCode = code;
246
303
  };
247
304
  const rawMode = program.opts().output;
248
305
  const mode = isOutputMode(rawMode) ? rawMode : 'text';
306
+ const output = new Output(mode);
249
307
  if (err instanceof ApiError) {
250
308
  if (mode === 'json') {
251
309
  const envelope = {
@@ -295,24 +353,31 @@ catch (err) {
295
353
  }
296
354
  }
297
355
  }
298
- await flushThenExit(err.exitCode);
356
+ await flushThenSetExitCode(err.exitCode);
299
357
  }
300
- const output = new Output(mode);
301
- if (err instanceof InterruptError) {
358
+ else if (err instanceof InterruptError) {
302
359
  // Graceful detach (DEV-331 piece 1, errors.md §8.1): the wait-path catch
303
360
  // block already printed the honest partial + re-attach hint. Exit with
304
361
  // the conventional 128+signum code; `INTERRUPTED` is deliberately outside
305
362
  // the error catalog. Note: Ctrl-C does NOT cancel the server-side run.
306
363
  if (mode === 'json') {
364
+ const tunnelDetach = err
365
+ .tunnelDetach;
307
366
  const envelope = {
308
367
  error: {
309
368
  code: 'INTERRUPTED',
310
369
  message: err.message,
311
- nextAction: 'The server-side run (if any) keeps executing and billing. ' +
312
- 'Re-attach with: testsprite test wait <runId>, or stop it with: testsprite test cancel <runId> ' +
313
- '(runId is in the partial JSON on stdout).',
370
+ nextAction: tunnelDetach?.nextAction ??
371
+ 'The server-side run (if any) keeps executing and billing. ' +
372
+ 'Re-attach with: testsprite test wait <runId>, or stop it with: testsprite test cancel <runId> ' +
373
+ '(runId is in the partial JSON on stdout).',
314
374
  requestId: 'local',
315
- details: { signal: err.signal },
375
+ details: {
376
+ signal: err.signal,
377
+ ...(tunnelDetach
378
+ ? { runId: tunnelDetach.runId, cancelOutcome: tunnelDetach.cancel }
379
+ : {}),
380
+ },
316
381
  },
317
382
  };
318
383
  process.stderr.write(`${JSON.stringify(envelope, null, 2)}\n`);
@@ -320,9 +385,9 @@ catch (err) {
320
385
  else {
321
386
  process.stderr.write(`Error: ${err.message}\n`);
322
387
  }
323
- await flushThenExit(err.exitCode);
388
+ await flushThenSetExitCode(err.exitCode);
324
389
  }
325
- if (err instanceof RequestTimeoutError) {
390
+ else if (err instanceof RequestTimeoutError) {
326
391
  // Structured rendering for per-request timeouts: JSON mode emits a
327
392
  // machine-readable envelope; text mode emits the message with a hint.
328
393
  if (mode === 'json') {
@@ -341,9 +406,9 @@ catch (err) {
341
406
  else {
342
407
  process.stderr.write(`Error: ${err.message}\n`);
343
408
  }
344
- await flushThenExit(err.exitCode);
409
+ await flushThenSetExitCode(err.exitCode);
345
410
  }
346
- if (err instanceof CommanderError) {
411
+ else if (err instanceof CommanderError) {
347
412
  // Map exit codes per the CLI taxonomy:
348
413
  // help / version → 0 (user asked for it; Commander already wrote the text)
349
414
  // parse errors → 5 (VALIDATION_ERROR family: missing arg, invalid
@@ -360,33 +425,37 @@ catch (err) {
360
425
  if (err.code === 'commander.helpDisplayed' ||
361
426
  err.code === 'commander.help' ||
362
427
  err.code === 'commander.version') {
363
- await flushThenExit(0);
428
+ await flushThenSetExitCode(0);
364
429
  }
365
- // For parse errors, write the buffered message in the correct format.
366
- // rawMode from program.opts() is reliable when --output was parsed before
367
- // the error. When the error occurs first (e.g. `testsprite badcmd --output
368
- // json`), rawMode is the default 'text'; scan argv as a best-effort
369
- // fallback so machine consumers still receive a JSON envelope.
370
- const commanderMode = (() => {
371
- if (rawMode === 'json')
372
- return 'json';
373
- for (let i = 2; i < process.argv.length; i++) {
374
- const arg = process.argv[i];
375
- if (arg === '--output' && process.argv[i + 1] === 'json')
376
- return 'json';
377
- if (arg === '--output=json')
430
+ else {
431
+ // For parse errors, write the buffered message in the correct format.
432
+ // rawMode from program.opts() is reliable when --output was parsed before
433
+ // the error. When the error occurs first (e.g. `testsprite badcmd --output
434
+ // json`), rawMode is the default 'text'; scan argv as a best-effort
435
+ // fallback so machine consumers still receive a JSON envelope.
436
+ const commanderMode = (() => {
437
+ if (rawMode === 'json')
378
438
  return 'json';
379
- }
380
- return mode;
381
- })();
382
- process.stderr.write(renderCommanderError(pendingCommanderErrorMsg, err.message, commanderMode));
383
- await flushThenExit(5);
439
+ for (let i = 2; i < process.argv.length; i++) {
440
+ const arg = process.argv[i];
441
+ if (arg === '--output' && process.argv[i + 1] === 'json')
442
+ return 'json';
443
+ if (arg === '--output=json')
444
+ return 'json';
445
+ }
446
+ return mode;
447
+ })();
448
+ process.stderr.write(renderCommanderError(pendingCommanderErrorMsg, err.message, commanderMode));
449
+ await flushThenSetExitCode(5);
450
+ }
384
451
  }
385
- if (err instanceof CLIError) {
452
+ else if (err instanceof CLIError) {
386
453
  output.error(err.message);
387
- await flushThenExit(err.exitCode);
454
+ await flushThenSetExitCode(err.exitCode);
455
+ }
456
+ else {
457
+ output.error(err instanceof Error ? err.message : String(err));
458
+ await flushThenSetExitCode(1);
388
459
  }
389
- output.error(err instanceof Error ? err.message : String(err));
390
- await flushThenExit(1);
391
460
  }
392
461
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Which coding agents does this repo use?
3
+ *
4
+ * Two signal classes, kept apart because they answer different questions: `env`
5
+ * is who is invoking the CLI now, `trace` is who has been used here. Only two
6
+ * targets publish a usable env var, so traces cover the rest.
7
+ */
8
+ import { type AgentTarget } from './agent-targets.js';
9
+ export type DetectionSource = 'env' | 'trace';
10
+ export interface AgentDetection {
11
+ target: AgentTarget;
12
+ source: DetectionSource;
13
+ /** What matched — an env var name or a repo path. Named in the stderr summary. */
14
+ signal: string;
15
+ }
16
+ export interface DetectDeps {
17
+ env?: NodeJS.ProcessEnv;
18
+ existsSync?: (path: string) => boolean;
19
+ readdirSync?: (path: string) => string[];
20
+ isDirectory?: (path: string) => boolean;
21
+ }
22
+ export interface DetectAgentDeps extends DetectDeps {
23
+ readFileSync?: (path: string) => string;
24
+ }
25
+ /**
26
+ * Who is invoking the CLI right now, from the environment alone — no fs, no
27
+ * repo history. This is the only signal that identifies the CALLER; a repo
28
+ * trace only shows an agent was used here at some point.
29
+ */
30
+ export declare function detectCallerFromEnv(env?: NodeJS.ProcessEnv): AgentDetection[];
31
+ /**
32
+ * Targets detected in `dir`, env signals first.
33
+ *
34
+ * Order is significant: `setup` reports these in order, so the strongest
35
+ * evidence is named first. A target found by both appears once, as `env`.
36
+ */
37
+ export declare function detectAgentTargets(dir: string, deps?: DetectAgentDeps): AgentDetection[];
38
+ /** Just the targets, for callers that do not report the evidence. */
39
+ export declare function detectedTargets(dir: string, deps?: DetectAgentDeps): AgentTarget[];
40
+ /** Installed when nothing is detected and the caller named no target. */
41
+ export declare const FALLBACK_TARGET: AgentTarget;
42
+ export interface AgentResolution {
43
+ targets: AgentTarget[];
44
+ /** How `targets` was chosen — `flag` means the caller named it. */
45
+ source: 'flag' | DetectionSource | 'fallback';
46
+ /** Evidence behind a detected result; empty for `flag` and `fallback`. */
47
+ detections: AgentDetection[];
48
+ }
49
+ /**
50
+ * Which targets an install should cover: an explicit choice, else every agent
51
+ * detected in `dir`, else {@link FALLBACK_TARGET}.
52
+ */
53
+ export declare function resolveAgentTargets(explicit: AgentTarget | undefined, dir: string, deps?: DetectAgentDeps): AgentResolution;
@@ -0,0 +1,198 @@
1
+ /**
2
+ * Which coding agents does this repo use?
3
+ *
4
+ * Two signal classes, kept apart because they answer different questions: `env`
5
+ * is who is invoking the CLI now, `trace` is who has been used here. Only two
6
+ * targets publish a usable env var, so traces cover the rest.
7
+ */
8
+ import { join } from 'node:path';
9
+ import { existsSync as nodeExistsSync, readFileSync as nodeReadFileSync, readdirSync as nodeReaddirSync, statSync as nodeStatSync, } from 'node:fs';
10
+ import { DEFAULT_SKILLS, TARGETS, pathFor } from './agent-targets.js';
11
+ /**
12
+ * Environment variables that identify the invoking agent.
13
+ *
14
+ * Only add a variable that is observed or vendor-documented: a guessed name
15
+ * never matches, so it degrades to the fallback instead of failing loudly.
16
+ * The other six targets publish nothing usable — VSCODE_* and TERM_PROGRAM
17
+ * name the editor, not the agent, and cannot separate cursor from windsurf.
18
+ *
19
+ * Presence is the signal, so a CI job that exports one of these is read as that
20
+ * agent calling. The cost is bounded and one-directional: an extra skill file
21
+ * installed, and `detected` rather than `fallback` in the summary. Pass
22
+ * `--agent` to decide it explicitly, or `--no-agent` to install nothing.
23
+ */
24
+ const ENV_SIGNALS = {
25
+ claude: ['CLAUDECODE'],
26
+ cursor: ['CURSOR_AGENT'],
27
+ };
28
+ /**
29
+ * Repo paths that show an agent has been used here.
30
+ *
31
+ * Each is the config root the agent itself owns, which is also where our skill
32
+ * lands — so presence alone is not enough (see `hasForeignContent`).
33
+ */
34
+ const TRACE_PATHS = {
35
+ claude: '.claude',
36
+ antigravity: '.agents',
37
+ cursor: '.cursor',
38
+ cline: '.clinerules',
39
+ kiro: '.kiro',
40
+ windsurf: '.windsurf',
41
+ copilot: '.github/instructions',
42
+ codex: 'AGENTS.md',
43
+ };
44
+ const MAX_TRACE_DEPTH = 4;
45
+ function truthy(value) {
46
+ if (value === undefined)
47
+ return false;
48
+ const v = value.trim().toLowerCase();
49
+ return v !== '' && v !== '0' && v !== 'false';
50
+ }
51
+ /**
52
+ * Every relative path this CLI writes for a target, across all default skills.
53
+ *
54
+ * Includes the `.bak` sibling `agent install --force` leaves behind. Without
55
+ * it one forced reinstall makes that target permanently "detected" from its
56
+ * own backup — the self-reinforcement `hasForeignContent` exists to prevent,
57
+ * just one file over.
58
+ */
59
+ function ownPaths(target) {
60
+ return DEFAULT_SKILLS.flatMap(skill => {
61
+ const p = pathFor(target, skill).replace(/\\/g, '/');
62
+ return [p, `${p}.bak`];
63
+ });
64
+ }
65
+ /**
66
+ * True when the trace holds something this CLI did not put there.
67
+ *
68
+ * Without this the fallback is self-reinforcing: a repo where nothing was
69
+ * detected gets our own skill files written, and the next run reads those back
70
+ * as evidence of the agent we guessed.
71
+ */
72
+ function hasForeignContent(dir, target, relRoot, deps) {
73
+ const mine = new Set(ownPaths(target));
74
+ const walk = (rel, depth) => {
75
+ if (depth > MAX_TRACE_DEPTH)
76
+ return true; // too deep to be only ours
77
+ let entries;
78
+ try {
79
+ entries = deps.readdirSync(join(dir, rel));
80
+ }
81
+ catch {
82
+ return false; // unreadable → claim nothing
83
+ }
84
+ for (const entry of entries) {
85
+ const childRel = `${rel}/${entry}`;
86
+ if (mine.has(childRel))
87
+ continue;
88
+ // A directory on the way to one of our files is not itself evidence.
89
+ const isPrefix = [...mine].some(p => p.startsWith(`${childRel}/`));
90
+ if (!isPrefix)
91
+ return true;
92
+ if (deps.isDirectory(join(dir, childRel)) && walk(childRel, depth + 1))
93
+ return true;
94
+ }
95
+ return false;
96
+ };
97
+ return walk(relRoot, 1);
98
+ }
99
+ /**
100
+ * `AGENTS.md` is a cross-agent convention file, and this CLI creates it when
101
+ * absent — so it counts as a codex trace only when it carries content beyond
102
+ * our own managed section.
103
+ */
104
+ function agentsFileHasForeignContent(content) {
105
+ const withoutSection = content.replace(/<!--\s*BEGIN TESTSPRITE AGENT SECTION[\s\S]*?END TESTSPRITE AGENT SECTION\s*-->/g, '');
106
+ return withoutSection.trim().length > 0;
107
+ }
108
+ /**
109
+ * Who is invoking the CLI right now, from the environment alone — no fs, no
110
+ * repo history. This is the only signal that identifies the CALLER; a repo
111
+ * trace only shows an agent was used here at some point.
112
+ */
113
+ export function detectCallerFromEnv(env = process.env) {
114
+ const out = [];
115
+ for (const [target, vars] of Object.entries(ENV_SIGNALS)) {
116
+ const hit = vars.find(name => truthy(env[name]));
117
+ if (hit)
118
+ out.push({ target, source: 'env', signal: hit });
119
+ }
120
+ return out;
121
+ }
122
+ /**
123
+ * Targets detected in `dir`, env signals first.
124
+ *
125
+ * Order is significant: `setup` reports these in order, so the strongest
126
+ * evidence is named first. A target found by both appears once, as `env`.
127
+ */
128
+ export function detectAgentTargets(dir, deps = {}) {
129
+ const env = deps.env ?? process.env;
130
+ const exists = deps.existsSync ?? nodeExistsSync;
131
+ const readdir = deps.readdirSync ??
132
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- path comes from this module's own TRACE_PATHS table joined to the caller's dir, never from user input.
133
+ ((p) => nodeReaddirSync(p));
134
+ const isDir = deps.isDirectory ??
135
+ ((p) => {
136
+ try {
137
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- as above.
138
+ return nodeStatSync(p).isDirectory();
139
+ }
140
+ catch {
141
+ return false;
142
+ }
143
+ });
144
+ const readFile = deps.readFileSync ??
145
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- as above.
146
+ ((p) => nodeReadFileSync(p, 'utf8'));
147
+ const out = detectCallerFromEnv(env);
148
+ const seen = new Set(out.map(d => d.target));
149
+ for (const target of Object.keys(TARGETS)) {
150
+ if (seen.has(target))
151
+ continue;
152
+ const rel = TRACE_PATHS[target];
153
+ const full = join(dir, rel);
154
+ if (!exists(full))
155
+ continue;
156
+ if (TARGETS[target].mode === 'managed-section') {
157
+ let content;
158
+ try {
159
+ content = readFile(full);
160
+ }
161
+ catch {
162
+ continue; // unreadable → claim nothing
163
+ }
164
+ if (!agentsFileHasForeignContent(content))
165
+ continue;
166
+ }
167
+ else if (!hasForeignContent(dir, target, rel, { readdirSync: readdir, isDirectory: isDir })) {
168
+ continue;
169
+ }
170
+ out.push({ target, source: 'trace', signal: rel });
171
+ seen.add(target);
172
+ }
173
+ return out;
174
+ }
175
+ /** Just the targets, for callers that do not report the evidence. */
176
+ export function detectedTargets(dir, deps = {}) {
177
+ return detectAgentTargets(dir, deps).map(d => d.target);
178
+ }
179
+ /** Installed when nothing is detected and the caller named no target. */
180
+ export const FALLBACK_TARGET = 'claude';
181
+ /**
182
+ * Which targets an install should cover: an explicit choice, else every agent
183
+ * detected in `dir`, else {@link FALLBACK_TARGET}.
184
+ */
185
+ export function resolveAgentTargets(explicit, dir, deps = {}) {
186
+ if (explicit)
187
+ return { targets: [explicit], source: 'flag', detections: [] };
188
+ const detections = detectAgentTargets(dir, deps);
189
+ if (detections.length === 0) {
190
+ return { targets: [FALLBACK_TARGET], source: 'fallback', detections };
191
+ }
192
+ return {
193
+ targets: detections.map(d => d.target),
194
+ source: detections.some(d => d.source === 'env') ? 'env' : 'trace',
195
+ detections,
196
+ };
197
+ }
198
+ //# sourceMappingURL=agent-detect.js.map
@@ -50,6 +50,15 @@ export interface DryRunSampleEntry {
50
50
  * `putPlanSteps`, `createTestBatch`) so their responses reflect the
51
51
  * user's actual flags rather than static canned values.
52
52
  */
53
+ /**
54
+ * Like {@link findSample}, but a missing sample throws instead of returning
55
+ * `undefined`. For dry-run paths that resolve samples DIRECTLY (bypassing the
56
+ * dry-run fetch impl, which has its own loud INTERNAL envelope for this):
57
+ * without the throw, a lost registry entry surfaces as a raw TypeError deep
58
+ * in a renderer (DEV-384 review F6 — `samples.ts` is a real merge-conflict
59
+ * hotspot, so a silently dropped entry is a live hazard, not a hypothetical).
60
+ */
61
+ export declare function findSampleOrThrow(method: string, url: string, requestBody?: unknown): DryRunSampleEntry;
53
62
  export declare function findSample(method: string, url: string, requestBody?: unknown): DryRunSampleEntry | undefined;
54
63
  /** Test-only export so `samples.test.ts` can iterate the catalog. */
55
64
  export declare const DRY_RUN_SAMPLE_ENTRIES: ReadonlyArray<DryRunSampleEntry>;
@@ -1,3 +1,4 @@
1
+ import { ApiError } from '../errors.js';
1
2
  import { buildJUnitReport } from '../junit-report.js';
2
3
  const SAMPLE_USER_ID = '11111111-1111-4111-8111-111111111111';
3
4
  const SAMPLE_KEY_ID = 'key_dryrun_2026';
@@ -441,6 +442,97 @@ const PATH_PREFIX = '/api/cli/v1';
441
442
  const ENTRIES = [
442
443
  entry('whoami', 'GET', '/me', me),
443
444
  entry('listProjects', 'GET', '/projects', pageOf(projects)),
445
+ // DEV-384 V3-B — plan-generation surface. All three MUST be registered
446
+ // BEFORE `getProject`: findSample is first-match-wins and the projects/*
447
+ // family shares the `/projects/…` prefix, so the more specific plans
448
+ // paths are listed first (same defensive convention as `/tests/{id}/runs`
449
+ // before the `/tests/{id}` catch-all; `samples.test.ts` proves the
450
+ // ordering with shadowing tests).
451
+ //
452
+ // The trigger sample reports the PROPOSALS rung starting
453
+ // (`stagesRemaining: []`) and the plans sample shows the settled result
454
+ // (idle + two staged proposals), so a dry-run learner sees a coherent
455
+ // story: trigger → stage runs → staged batch with stable proposalIds.
456
+ entry('generatePlans', 'POST', '/projects/{projectId}/plans/generate', {
457
+ status: 'accepted',
458
+ projectId: SAMPLE_PROJECT_ID,
459
+ stage: 'proposals',
460
+ stagesRemaining: [],
461
+ enqueuedAt: '2026-07-28T09:00:00.000Z',
462
+ }),
463
+ // One frontend proposal (with action/assertion steps) and one backend
464
+ // proposal (with endpointPath/captures/consumes) so both wire shapes are
465
+ // learnable offline. `credits` shows the charged-actions breakdown the
466
+ // real facade fills best-effort.
467
+ entry('getPlans', 'GET', '/projects/{projectId}/plans', {
468
+ generation: { status: 'idle', errorCode: null, errorMessage: null },
469
+ proposals: [
470
+ {
471
+ proposalId: 'prop_1',
472
+ title: 'Login happy path',
473
+ description: 'Sign in with valid credentials and land on the dashboard.',
474
+ priority: 'p1',
475
+ category: 'auth',
476
+ feature: 'login',
477
+ type: 'frontend',
478
+ steps: [
479
+ { type: 'action', description: 'Enter valid credentials and submit the login form' },
480
+ { type: 'assertion', description: 'Dashboard heading is visible' },
481
+ ],
482
+ },
483
+ {
484
+ proposalId: 'prop_2',
485
+ title: 'Create order — success',
486
+ description: 'POST a valid order and capture its id for downstream tests.',
487
+ priority: 'p2',
488
+ category: 'orders',
489
+ feature: 'create-order',
490
+ type: 'backend',
491
+ endpointPath: '/v1/orders',
492
+ captures: ['orderId'],
493
+ consumes: ['authToken'],
494
+ },
495
+ ],
496
+ credits: {
497
+ charged: [
498
+ { action: 'strategy', amount: 1 },
499
+ { action: 'proposals', amount: 2 },
500
+ ],
501
+ balance: 147,
502
+ },
503
+ }),
504
+ // Input-derived: echoes the explicit id list the CLI always sends (never
505
+ // the omitted or empty forms — §3.3 safety rules), so `accept --only
506
+ // prop_2 --dry-run` shows acceptedCount: 1 rather than a canned 2.
507
+ entry('acceptPlans', 'POST', '/projects/{projectId}/plans/accept', (req) => {
508
+ const body = req != null && typeof req === 'object' ? req : {};
509
+ const only = Array.isArray(body.only)
510
+ ? body.only.filter((id) => typeof id === 'string')
511
+ : null;
512
+ const ids = only !== null && only.length > 0 ? only : ['prop_1', 'prop_2'];
513
+ return {
514
+ acceptedCount: ids.length,
515
+ caseKeys: ids.map(id => `case_dryrun_${id}`),
516
+ };
517
+ }),
518
+ // DEV-384 piece V3-D — `project docs upload` two-step facade routes.
519
+ // Registered BEFORE the broader project patterns (design doc §7 ordering
520
+ // rule; findSample is first-match-wins) and with `/docs/upload-url` before
521
+ // `/docs`. NOT consumed by the command's dry-run path: `project docs
522
+ // upload --dry-run` is an inline early-exit (zero network, stat only —
523
+ // the presigned S3 PUT leg cannot be expressed as a canned fetch sample).
524
+ // These are documentation/shape-guards, same family as `deleteBatch`.
525
+ entry('docsUploadUrl', 'POST', '/projects/{projectId}/docs/upload-url', {
526
+ uploadUrl: 'https://s3.dry-run.invalid/testsprite-usercontent/u_dryrun/p_dryrun_2026/openapi.yaml?X-Amz-Signature=dryrun',
527
+ s3Key: 'u_dryrun/p_dryrun_2026/openapi.yaml',
528
+ expiresInSeconds: 3600,
529
+ }),
530
+ entry('docsRegister', 'POST', '/projects/{projectId}/docs', {
531
+ resourceId: 'res_dryrun_2026',
532
+ displayName: 'openapi.yaml',
533
+ docRole: 'API_DOC',
534
+ processStatus: 'Pending',
535
+ }),
444
536
  entry('getProject', 'GET', '/projects/{projectId}', projects[0]),
445
537
  // P6 — POST /projects (create project). The id uses a stable dry-run
446
538
  // sentinel so agents can see a coherent field shape without a real key.
@@ -861,6 +953,30 @@ function pageOf(items) {
861
953
  * `putPlanSteps`, `createTestBatch`) so their responses reflect the
862
954
  * user's actual flags rather than static canned values.
863
955
  */
956
+ /**
957
+ * Like {@link findSample}, but a missing sample throws instead of returning
958
+ * `undefined`. For dry-run paths that resolve samples DIRECTLY (bypassing the
959
+ * dry-run fetch impl, which has its own loud INTERNAL envelope for this):
960
+ * without the throw, a lost registry entry surfaces as a raw TypeError deep
961
+ * in a renderer (DEV-384 review F6 — `samples.ts` is a real merge-conflict
962
+ * hotspot, so a silently dropped entry is a live hazard, not a hypothetical).
963
+ */
964
+ export function findSampleOrThrow(method, url, requestBody) {
965
+ const entry = findSample(method, url, requestBody);
966
+ if (entry === undefined) {
967
+ throw ApiError.fromEnvelope({
968
+ error: {
969
+ code: 'INTERNAL',
970
+ message: `dry-run sample registry has no entry for ${method.toUpperCase()} ${extractPath(url)} — ` +
971
+ 'a sample was removed or shadowed in src/lib/dry-run/samples.ts (internal CLI bug).',
972
+ nextAction: 'Please report this to support@testsprite.com.',
973
+ requestId: SAMPLE_DRY_RUN_REQUEST_ID,
974
+ details: { method: method.toUpperCase(), path: extractPath(url) },
975
+ },
976
+ });
977
+ }
978
+ return entry;
979
+ }
864
980
  export function findSample(method, url, requestBody) {
865
981
  const upper = method.toUpperCase();
866
982
  const pathOnly = extractPath(url);