@testsprite/testsprite-cli 0.15.0 → 0.17.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 (207) hide show
  1. package/README.md +53 -141
  2. package/dist/commands/agent.d.ts +12 -4
  3. package/dist/commands/agent.js +55 -65
  4. package/dist/commands/auth.d.ts +6 -10
  5. package/dist/commands/auth.js +44 -56
  6. package/dist/commands/ci.d.ts +23 -100
  7. package/dist/commands/ci.js +297 -489
  8. package/dist/commands/completion.js +2 -1
  9. package/dist/commands/conversation.d.ts +27 -0
  10. package/dist/commands/conversation.js +702 -0
  11. package/dist/commands/doctor.d.ts +5 -1
  12. package/dist/commands/doctor.js +130 -34
  13. package/dist/commands/init.d.ts +4 -45
  14. package/dist/commands/init.js +116 -68
  15. package/dist/commands/project-env.d.ts +62 -2
  16. package/dist/commands/project-env.js +426 -53
  17. package/dist/commands/project-sign-in.d.ts +0 -48
  18. package/dist/commands/project-sign-in.js +1 -224
  19. package/dist/commands/project.d.ts +15 -186
  20. package/dist/commands/project.js +93 -921
  21. package/dist/commands/result.d.ts +10 -0
  22. package/dist/commands/result.js +215 -0
  23. package/dist/commands/schedule.d.ts +0 -29
  24. package/dist/commands/schedule.js +47 -97
  25. package/dist/commands/test.d.ts +315 -1824
  26. package/dist/commands/test.js +1962 -13733
  27. package/dist/commands/testlist.d.ts +128 -5
  28. package/dist/commands/testlist.js +269 -329
  29. package/dist/commands/tunnel.d.ts +2 -2
  30. package/dist/commands/tunnel.js +43 -41
  31. package/dist/commands/usage.d.ts +12 -45
  32. package/dist/commands/usage.js +51 -131
  33. package/dist/index.js +189 -108
  34. package/dist/lib/agent-detect.js +9 -5
  35. package/dist/lib/agent-targets.d.ts +21 -2
  36. package/dist/lib/agent-targets.js +88 -11
  37. package/dist/lib/args.d.ts +13 -0
  38. package/dist/lib/args.js +49 -0
  39. package/dist/lib/basic-auth.d.ts +3 -0
  40. package/dist/lib/basic-auth.js +15 -0
  41. package/dist/lib/billing-refusal.js +4 -3
  42. package/dist/lib/ci-linkage.d.ts +4 -82
  43. package/dist/lib/ci-linkage.js +4 -157
  44. package/dist/lib/ci-run.js +1 -1
  45. package/dist/lib/client-factory.d.ts +10 -2
  46. package/dist/lib/client-factory.js +38 -26
  47. package/dist/lib/commit-signal.d.ts +65 -0
  48. package/dist/lib/commit-signal.js +305 -0
  49. package/dist/lib/concurrency-limiter.d.ts +6 -0
  50. package/dist/lib/concurrency-limiter.js +29 -0
  51. package/dist/lib/config.js +10 -5
  52. package/dist/lib/conflict-reason.d.ts +31 -4
  53. package/dist/lib/conflict-reason.js +38 -4
  54. package/dist/lib/conversation/answers.d.ts +9 -0
  55. package/dist/lib/conversation/answers.js +49 -0
  56. package/dist/lib/conversation/api.d.ts +71 -0
  57. package/dist/lib/conversation/api.js +150 -0
  58. package/dist/lib/conversation/change.d.ts +31 -0
  59. package/dist/lib/conversation/change.js +124 -0
  60. package/dist/lib/conversation/context.d.ts +19 -0
  61. package/dist/lib/conversation/context.js +70 -0
  62. package/dist/lib/conversation/environment.d.ts +15 -0
  63. package/dist/lib/conversation/environment.js +33 -0
  64. package/dist/lib/conversation/follow.d.ts +24 -0
  65. package/dist/lib/conversation/follow.js +42 -0
  66. package/dist/lib/conversation/render.d.ts +33 -0
  67. package/dist/lib/conversation/render.js +315 -0
  68. package/dist/lib/conversation/title.d.ts +2 -0
  69. package/dist/lib/conversation/title.js +18 -0
  70. package/dist/lib/conversation/types.d.ts +156 -0
  71. package/dist/lib/conversation/types.js +6 -0
  72. package/dist/lib/credentials.js +67 -11
  73. package/dist/lib/cron.d.ts +1 -1
  74. package/dist/lib/cron.js +2 -2
  75. package/dist/lib/dispatch-stop.d.ts +20 -0
  76. package/dist/lib/dispatch-stop.js +30 -0
  77. package/dist/lib/download.d.ts +71 -0
  78. package/dist/lib/download.js +274 -0
  79. package/dist/lib/dry-run/fetch.d.ts +10 -0
  80. package/dist/lib/dry-run/fetch.js +20 -0
  81. package/dist/lib/dry-run/samples.d.ts +6 -34
  82. package/dist/lib/dry-run/samples.js +389 -751
  83. package/dist/lib/environment-tunnel.d.ts +16 -26
  84. package/dist/lib/environment-tunnel.js +161 -157
  85. package/dist/lib/errors.d.ts +20 -4
  86. package/dist/lib/errors.js +36 -16
  87. package/dist/lib/facade.d.ts +7 -29
  88. package/dist/lib/facade.js +7 -36
  89. package/dist/lib/failing-fe-resolver.d.ts +13 -58
  90. package/dist/lib/failing-fe-resolver.js +47 -132
  91. package/dist/lib/first-suite-hint.d.ts +16 -22
  92. package/dist/lib/first-suite-hint.js +38 -47
  93. package/dist/lib/gh-output.d.ts +76 -21
  94. package/dist/lib/gh-output.js +171 -90
  95. package/dist/lib/git-utils.d.ts +56 -0
  96. package/dist/lib/git-utils.js +212 -0
  97. package/dist/lib/github-context.d.ts +2 -0
  98. package/dist/lib/github-context.js +40 -8
  99. package/dist/lib/history-retention.d.ts +6 -2
  100. package/dist/lib/history-retention.js +10 -7
  101. package/dist/lib/http.d.ts +58 -134
  102. package/dist/lib/http.js +352 -271
  103. package/dist/lib/interrupt.d.ts +14 -8
  104. package/dist/lib/interrupt.js +28 -10
  105. package/dist/lib/junit-report.d.ts +60 -4
  106. package/dist/lib/junit-report.js +209 -32
  107. package/dist/lib/local-target.d.ts +3 -3
  108. package/dist/lib/local-target.js +3 -3
  109. package/dist/lib/output.d.ts +0 -29
  110. package/dist/lib/output.js +10 -33
  111. package/dist/lib/pagination.d.ts +2 -5
  112. package/dist/lib/pagination.js +2 -5
  113. package/dist/lib/presigned-url.d.ts +22 -0
  114. package/dist/lib/presigned-url.js +90 -0
  115. package/dist/lib/prompt.js +36 -2
  116. package/dist/lib/proxy.js +2 -1
  117. package/dist/lib/redact.d.ts +2 -2
  118. package/dist/lib/redact.js +3 -4
  119. package/dist/lib/removed-commands.d.ts +18 -0
  120. package/dist/lib/removed-commands.js +154 -0
  121. package/dist/lib/render-error.d.ts +31 -6
  122. package/dist/lib/render-error.js +88 -25
  123. package/dist/lib/response-schemas.d.ts +38 -30
  124. package/dist/lib/response-schemas.js +210 -207
  125. package/dist/lib/result/api.d.ts +24 -0
  126. package/dist/lib/result/api.js +28 -0
  127. package/dist/lib/result/evidence.d.ts +71 -0
  128. package/dist/lib/result/evidence.js +420 -0
  129. package/dist/lib/result/render.d.ts +20 -0
  130. package/dist/lib/result/render.js +194 -0
  131. package/dist/lib/result/types.d.ts +122 -0
  132. package/dist/lib/result/types.js +19 -0
  133. package/dist/lib/run-output.d.ts +275 -0
  134. package/dist/lib/run-output.js +227 -0
  135. package/dist/lib/run-render.d.ts +101 -0
  136. package/dist/lib/run-render.js +183 -0
  137. package/dist/lib/run-wait.d.ts +192 -0
  138. package/dist/lib/run-wait.js +452 -0
  139. package/dist/lib/runs.types.d.ts +134 -367
  140. package/dist/lib/runs.types.js +0 -14
  141. package/dist/lib/secret-file.d.ts +1 -1
  142. package/dist/lib/secret-file.js +11 -2
  143. package/dist/lib/skill-nudge.d.ts +7 -27
  144. package/dist/lib/skill-nudge.js +9 -37
  145. package/dist/lib/target-path.d.ts +15 -0
  146. package/dist/lib/target-path.js +35 -0
  147. package/dist/lib/target-url-advisory.d.ts +19 -0
  148. package/dist/lib/target-url-advisory.js +31 -0
  149. package/dist/lib/target-url-preflight.d.ts +9 -0
  150. package/dist/lib/target-url-preflight.js +214 -106
  151. package/dist/lib/target-url.d.ts +1 -1
  152. package/dist/lib/target-url.js +6 -16
  153. package/dist/lib/telemetry.d.ts +32 -12
  154. package/dist/lib/telemetry.js +39 -8
  155. package/dist/lib/terminal-text.d.ts +41 -0
  156. package/dist/lib/terminal-text.js +127 -0
  157. package/dist/lib/testlist.types.d.ts +16 -8
  158. package/dist/lib/testlist.types.js +1 -1
  159. package/dist/lib/text-equality.d.ts +2 -0
  160. package/dist/lib/text-equality.js +5 -0
  161. package/dist/lib/text-file.d.ts +16 -0
  162. package/dist/lib/text-file.js +41 -0
  163. package/dist/lib/text-table.d.ts +46 -0
  164. package/dist/lib/text-table.js +72 -4
  165. package/dist/lib/ticker.d.ts +9 -2
  166. package/dist/lib/ticker.js +16 -3
  167. package/dist/lib/transport-failure.d.ts +22 -0
  168. package/dist/lib/transport-failure.js +126 -0
  169. package/dist/lib/tunnel-session.d.ts +7 -1
  170. package/dist/lib/tunnel-session.js +22 -9
  171. package/dist/lib/update-check.js +3 -2
  172. package/dist/lib/url-template.d.ts +43 -0
  173. package/dist/lib/url-template.js +151 -0
  174. package/dist/lib/validate.d.ts +0 -64
  175. package/dist/lib/validate.js +2 -131
  176. package/dist/lib/version-notice.js +4 -3
  177. package/dist/lib/wait-exit.d.ts +37 -2
  178. package/dist/lib/wait-exit.js +88 -30
  179. package/dist/lib/workspace-status.js +10 -2
  180. package/dist/version.d.ts +1 -1
  181. package/dist/version.js +1 -1
  182. package/package.json +3 -4
  183. package/skills/testsprite-ci.skill.md +48 -18
  184. package/skills/testsprite-onboard.skill.md +66 -151
  185. package/skills/testsprite-verify.codex.md +54 -56
  186. package/skills/testsprite-verify.skill.md +194 -358
  187. package/dist/lib/browser.d.ts +0 -6
  188. package/dist/lib/browser.js +0 -54
  189. package/dist/lib/bundle.d.ts +0 -234
  190. package/dist/lib/bundle.js +0 -781
  191. package/dist/lib/deprecate.d.ts +0 -10
  192. package/dist/lib/deprecate.js +0 -13
  193. package/dist/lib/flaky.d.ts +0 -91
  194. package/dist/lib/flaky.js +0 -71
  195. package/dist/lib/plan-poll.d.ts +0 -171
  196. package/dist/lib/plan-poll.js +0 -441
  197. package/dist/lib/plans.types.d.ts +0 -130
  198. package/dist/lib/plans.types.js +0 -31
  199. package/dist/lib/poll.d.ts +0 -100
  200. package/dist/lib/poll.js +0 -290
  201. package/dist/lib/rate-throttle.d.ts +0 -49
  202. package/dist/lib/rate-throttle.js +0 -75
  203. package/dist/lib/run-progress.d.ts +0 -41
  204. package/dist/lib/run-progress.js +0 -56
  205. package/dist/lib/v3-advisory.d.ts +0 -55
  206. package/dist/lib/v3-advisory.js +0 -74
  207. package/schemas/plan.schema.json +0 -61
package/dist/index.js CHANGED
@@ -3,26 +3,30 @@ import { Command, CommanderError } from 'commander';
3
3
  import { createAgentCommand } from './commands/agent.js';
4
4
  import { createAuthCommand } from './commands/auth.js';
5
5
  import { createCiCommand } from './commands/ci.js';
6
+ import { createConversationCommands } from './commands/conversation.js';
6
7
  import { createCompletionCommand } from './commands/completion.js';
7
8
  import { createDoctorCommand } from './commands/doctor.js';
8
- import { addSetupOptions, createDeprecatedInitCommand, createSetupCommand, runConfigureViaSetup, } from './commands/init.js';
9
+ import { createSetupCommand } from './commands/init.js';
9
10
  import { createProjectCommand } from './commands/project.js';
11
+ import { createResultCommand } from './commands/result.js';
10
12
  import { createScheduleCommand } from './commands/schedule.js';
11
13
  import { createTunnelCommand } from './commands/tunnel.js';
12
- import { createTestCommand } from './commands/test.js';
14
+ import { createTestCommand, createRunCommand } from './commands/test.js';
13
15
  import { createTestListCommand } from './commands/testlist.js';
14
16
  import { createUsageCommand } from './commands/usage.js';
15
17
  import { resolveProfileName } from './lib/config.js';
16
18
  import { classifyBillingRefusal } from './lib/billing-refusal.js';
17
- import { TARGETS } from './lib/agent-targets.js';
19
+ import { validatePositionalArgs } from './lib/args.js';
18
20
  import { ApiError, CLIError, InterruptError, RequestTimeoutError, extractNodeErrorCode, } from './lib/errors.js';
19
21
  import { armInterruptExitBackstop, installBrokenPipeGuard, installSignalHandlers, } from './lib/interrupt.js';
20
22
  import { Output, isOutputMode } from './lib/output.js';
21
23
  import { maybeInstallProxyAgent } from './lib/proxy.js';
22
24
  import { redactDeep } from './lib/redact.js';
23
- import { buildInterruptEnvelope, renderAmbiguousOrgCandidates, renderTunnelBindingLimitIds, renderCommanderError, rephraseUnknownOption, } from './lib/render-error.js';
24
- import { isPlanTemplateInvocation, maybeEmitSkillNudge } from './lib/skill-nudge.js';
25
- import { classifyCliError, isTelemetryOptedOut, recordOutcome, recordTelemetryExtras, resolveTelemetryAuth, } from './lib/telemetry.js';
25
+ import { removedCommandPointer, removedOptionPointer } from './lib/removed-commands.js';
26
+ import { jsonForTerminal, terminalSafe, terminalSafeLine } from './lib/terminal-text.js';
27
+ import { buildInterruptEnvelope, renderAmbiguousOrgCandidates, renderTunnelBindingLimitIds, redactUnknownOptionValue, renderCommanderError, rephraseUnknownOption, } from './lib/render-error.js';
28
+ import { maybeEmitSkillNudge } from './lib/skill-nudge.js';
29
+ import { classifyCliError, isTelemetryOptedOut, recordOutcome, recordTelemetryExtras, tryResolveTelemetryAuth, } from './lib/telemetry.js';
26
30
  import { maybeNotifyUpdate } from './lib/update-check.js';
27
31
  import { VERSION } from './version.js';
28
32
  import { rejectUnsupportedNodeVersion } from './version-guard.js';
@@ -40,40 +44,28 @@ program
40
44
  .version(VERSION)
41
45
  .option('--output <mode>', 'Output format (json|text)', 'text')
42
46
  .option('--profile <name>', 'Configuration profile to use')
43
- .option('--endpoint-url <url>', 'Override the API endpoint host')
44
- .option('--verbose', 'Emit human-readable HTTP retry / backoff / polling-mode transitions to stderr. Less noisy than --debug; useful for diagnosing hangs without the full trace.')
47
+ .option('--endpoint-url <url>', 'API base URL (a full http(s) URL)')
48
+ .option('--verbose', 'Log HTTP retry / backoff / polling transitions to stderr (lighter than --debug)')
45
49
  .option('--debug', 'Print HTTP method/path, request id, latency, retry decisions to stderr')
46
- .option('--dry-run', 'Skip the network and credentials; emit a canned sample matching the OpenAPI contract. Useful for learning the CLI surface without an API key. Note: file inputs you pass (--plan-from/--plans/--steps) are still read and validated locally; only --code-file uses a placeholder.')
47
- .option('--request-timeout <seconds>', 'Client-side per-request timeout in seconds (default: 120). Aborts any single fetch that does not complete within this deadline. ' +
48
- 'Override via TESTSPRITE_REQUEST_TIMEOUT_MS env var (milliseconds). ' +
49
- 'Range: 1–600. Does not affect the --timeout polling ceiling for `test run/wait`.');
50
+ .option('--dry-run', 'Skip the network and credentials; emit a canned sample matching the OpenAPI contract. Exception: run launches (`run --project`, `run <test-id...>`, `run --testlist`) with credentials and no explicit target may make read-only GETs to preview an automatic tunnel target; nothing is created or started.')
51
+ .option('--request-timeout <seconds>', 'Per-request timeout in seconds (default 120; range 1–600, values outside are clamped). ' +
52
+ 'Does not affect the --timeout polling ceiling for `run` or `run wait`.');
50
53
  // `setup` is the primary onboarding command, listed FIRST in --help so a coding
51
- // agent reaches it before anything else. `init` is kept as a hidden, deprecated
52
- // alias (invisible to --help; still works for existing scripts/agents).
54
+ // agent reaches it before anything else.
53
55
  program.addCommand(createSetupCommand({}));
54
- program.addCommand(createDeprecatedInitCommand({}), { hidden: true });
55
- // `auth configure` is a hidden, deprecated alias that runs FULL `setup`
56
- // (configure + skill install), so an agent reaching for the old command still
57
- // ends up with the skill. `setup` remains the ONLY path that writes credentials.
58
- // Attach the SAME flag set `setup` has (previously only
59
- // `--from-env` was wired up, so README's "runs the full setup" claim didn't
60
- // hold — `--yes`/`--agent`/`--api-key`/`--force`/`--dir`/`--no-agent` were all
61
- // rejected as `unknown option`).
62
- const authCommand = createAuthCommand();
63
- const authConfigureValidTargets = Object.keys(TARGETS);
64
- addSetupOptions(authCommand.command('configure', { hidden: true }), authConfigureValidTargets, 'claude').action(async (cmdOpts, command) => {
65
- process.stderr.write('[deprecated] `testsprite auth configure` now runs full setup (configure + skill install) — ' +
66
- 'use `testsprite setup` (add --no-agent to skip the skill).\n');
67
- await runConfigureViaSetup(command, {}, cmdOpts);
68
- });
69
- program.addCommand(authCommand);
56
+ // The project's agent: the same conversations, cards and memory the portal has.
57
+ for (const command of createConversationCommands())
58
+ program.addCommand(command);
59
+ program.addCommand(createAuthCommand());
70
60
  program.addCommand(createProjectCommand({}));
71
61
  let waitTimeoutTelemetry = {};
72
- program.addCommand(createTestCommand({
62
+ program.addCommand(createRunCommand({
73
63
  onWaitTimeout: context => {
74
64
  waitTimeoutTelemetry = context;
75
65
  },
76
66
  }));
67
+ program.addCommand(createTestCommand());
68
+ program.addCommand(createResultCommand());
77
69
  program.addCommand(createTestListCommand());
78
70
  program.addCommand(createCiCommand({
79
71
  onWaitTimeout: context => {
@@ -86,6 +78,35 @@ program.addCommand(createAgentCommand({}));
86
78
  program.addCommand(createUsageCommand());
87
79
  program.addCommand(createDoctorCommand());
88
80
  program.addCommand(createCompletionCommand(() => buildCompletionSpec()));
81
+ // The root accepts global flags anywhere. Its ordinary parser also collects
82
+ // child operands before the first unknown option. Feed the whole run tail to
83
+ // the hybrid parser together, so it can stop at wait/cancel before consuming
84
+ // their flags. Other groups retain Commander's existing parsing behavior.
85
+ const parseRootOptions = program.parseOptions.bind(program);
86
+ program.parseOptions = args => {
87
+ const parsed = parseRootOptions(args);
88
+ if (parsed.operands[0] !== 'run')
89
+ return parsed;
90
+ const tail = [...parsed.operands.slice(1), ...parsed.unknown];
91
+ // Commander consumes a terminator encountered before any unknown option.
92
+ // Reinsert it before reprocessing operands, so literal IDs cannot turn into
93
+ // project/list launch flags. A required global option may itself take `--`
94
+ // as its value; that occurrence is not an option terminator.
95
+ for (let index = 0; index < args.length; index++) {
96
+ const arg = args[index];
97
+ if (arg === '--') {
98
+ if (parsed.unknown.length === 0) {
99
+ const literalCount = args.length - index - 1;
100
+ tail.splice(Math.max(0, parsed.operands.length - 1 - literalCount), 0, '--');
101
+ }
102
+ break;
103
+ }
104
+ const option = program.options.find(option => option.long === arg || option.short === arg);
105
+ if (option?.required)
106
+ index++;
107
+ }
108
+ return { operands: ['run'], unknown: tail };
109
+ };
89
110
  // Derive the shell-completion spec from the fully-assembled command tree at call
90
111
  // time (not module-load), so `testsprite completion` can never drift from the
91
112
  // real commands, subcommands, and global flags.
@@ -118,8 +139,8 @@ let pendingCommanderErrorMsg = null;
118
139
  // skips those. Read by the success + error telemetry emits around parseAsync.
119
140
  let ranCommandPath = '';
120
141
  // Whether the command that ran should emit telemetry. `completion` (its stdout
121
- // is eval'd by shells) and `--plan-template` (pure-local) are kept off the
122
- // beacon, same as the update notice. Set by the preAction hook.
142
+ // is eval'd by shells) is kept off the beacon, same as the update notice. Set by
143
+ // the preAction hook.
123
144
  let telemetryEmit = false;
124
145
  // Auth resolved in the preAction hook, before the command's action runs, so
125
146
  // `auth remove` (which deletes the profile) is still reported on the key it used.
@@ -137,8 +158,9 @@ function applyExitOverrideDeep(cmd) {
137
158
  cmd.exitOverride();
138
159
  cmd.configureOutput({
139
160
  outputError(str, _write) {
140
- const rephrased = rephraseUnknownOption(str);
141
- pendingCommanderErrorMsg = rephrased !== null ? `${rephrased}\n` : str;
161
+ const safe = redactUnknownOptionValue(str);
162
+ const rephrased = rephraseUnknownOption(safe);
163
+ pendingCommanderErrorMsg = rephrased !== null ? `${rephrased}\n` : safe;
142
164
  },
143
165
  });
144
166
  for (const child of cmd.commands) {
@@ -146,29 +168,74 @@ function applyExitOverrideDeep(cmd) {
146
168
  }
147
169
  }
148
170
  applyExitOverrideDeep(program);
149
- function isRegisteredRootCommand(name) {
150
- return (name === 'help' ||
151
- program.commands.some(command => command.name() === name || command.aliases().includes(name)));
171
+ /** The subcommand of `group` that `name` names, by name or alias. */
172
+ function subcommandNamed(group, name) {
173
+ return group.commands.find(command => command.name() === name || command.aliases().includes(name));
152
174
  }
153
175
  /**
154
- * Commander checks its implicit help option before reporting an unknown root
155
- * command. It also falls back to root help when `help <command>` names a
156
- * missing command. Detect both cases while help is being rendered so the
157
- * normal unknown-command error wins before any misleading help is written.
176
+ * Commander checks its implicit help option before reporting an unknown
177
+ * command, at every level: `<group> <unknown> --help` prints the group's
178
+ * help, and `help <group> <unknown>` or `<group> help <unknown>` fall back to
179
+ * it too.
180
+ * Walk the command names the program was given, from the root down, while
181
+ * help is being rendered: the first name that is not a subcommand of the
182
+ * group before it is the unknown command, and that error wins before any
183
+ * misleading help is written. Only groups are walked; a leaf's arguments
184
+ * are its own. `-h` / `--help` is skipped wherever it stands, so the order of
185
+ * the words does not matter; the walk stops at any other option, so a flag's
186
+ * value is never read as a command. Returns the unknown name and the group it
187
+ * was looked up in; the error handler walks the same way to name where a
188
+ * removed command went.
158
189
  */
159
- function unknownRootCommandMaskedByHelp(args) {
160
- const [first, second] = args;
161
- if (first === 'help') {
162
- return second && !isRegisteredRootCommand(second) ? second : undefined;
190
+ function unknownCommandIn(args) {
191
+ let group = program;
192
+ // `help <name>…` at the root names the path to describe.
193
+ let explicitHelpPath = args[0] === 'help';
194
+ for (const name of explicitHelpPath ? args.slice(1) : args) {
195
+ if (group.commands.length === 0)
196
+ return undefined;
197
+ // The help flag asks for help wherever it stands; the names after it still
198
+ // have to exist (`test --help result`).
199
+ if (name === '-h' || name === '--help')
200
+ continue;
201
+ if (name.startsWith('-'))
202
+ return undefined;
203
+ // A group's own `help` subcommand: the name after it is its subcommand.
204
+ if (name === 'help') {
205
+ explicitHelpPath = true;
206
+ continue;
207
+ }
208
+ const next = subcommandNamed(group, name);
209
+ if (next === undefined) {
210
+ if (group.name() === 'run' && group.parent === program && !explicitHelpPath)
211
+ return undefined;
212
+ return { group, name };
213
+ }
214
+ group = next;
163
215
  }
164
- if (!first || first.startsWith('-') || isRegisteredRootCommand(first))
165
- return undefined;
166
- return args.slice(1).some(arg => arg === '--help' || arg === '-h') ? first : undefined;
216
+ return undefined;
167
217
  }
168
- program.addHelpText('beforeAll', context => {
169
- if (context.command !== program)
170
- return '';
171
- const unknownCommand = unknownRootCommandMaskedByHelp(program.args);
218
+ /**
219
+ * The command the leading names reach, which is the one that parses the
220
+ * options after them. The walk stops at the first option or the first word
221
+ * that is not a subcommand (an argument), like the walk above.
222
+ */
223
+ function commandNamedBy(args) {
224
+ let command = program;
225
+ for (const name of args) {
226
+ const next = name.startsWith('-') ? undefined : subcommandNamed(command, name);
227
+ if (next === undefined)
228
+ break;
229
+ command = next;
230
+ }
231
+ return command;
232
+ }
233
+ program.addHelpText('after', '\nEnvironment:\n' +
234
+ ' TESTSPRITE_API_KEY (overrides stored credentials), TESTSPRITE_NO_UPDATE_NOTIFIER (disables\n' +
235
+ ' the version check); TESTSPRITE_API_URL, TESTSPRITE_PROFILE and TESTSPRITE_REQUEST_TIMEOUT_MS\n' +
236
+ ' (milliseconds) mirror --endpoint-url, --profile and --request-timeout.');
237
+ program.addHelpText('beforeAll', () => {
238
+ const unknownCommand = unknownCommandIn(program.args)?.name;
172
239
  if (unknownCommand) {
173
240
  program.error(`error: unknown command '${unknownCommand}'`, {
174
241
  code: 'commander.unknownCommand',
@@ -177,8 +244,8 @@ program.addHelpText('beforeAll', context => {
177
244
  return '';
178
245
  });
179
246
  /**
180
- * Render a leaf command's full path (group + leaf), e.g. `test run` /
181
- * `auth whoami`, by walking parents up to (but not including) the root program.
247
+ * Render a leaf command's full path (group + leaf), e.g. `run` /
248
+ * `auth status`, by walking parents up to (but not including) the root program.
182
249
  */
183
250
  function commandPathOf(cmd) {
184
251
  const names = [];
@@ -200,10 +267,10 @@ function telemetryGlobals() {
200
267
  // action; the helper self-gates (text-only, non-dry-run, a small command
201
268
  // allowlist, opt-out via TESTSPRITE_NO_SKILL_WARNING) and never throws.
202
269
  program.hook('preAction', (_thisCommand, actionCommand) => {
203
- const globals = actionCommand.optsWithGlobals();
204
270
  const commandPath = commandPathOf(actionCommand);
205
271
  // Record which leaf command ran, for the telemetry emit around parseAsync.
206
272
  ranCommandPath = commandPath;
273
+ const globals = actionCommand.optsWithGlobals();
207
274
  // Preserve explicit --local attempts, including refusals and borrowed tunnels;
208
275
  // only flag presence is recorded. Automatic tunnel paths record the same fact.
209
276
  if (globals.local !== undefined)
@@ -211,43 +278,45 @@ program.hook('preAction', (_thisCommand, actionCommand) => {
211
278
  telemetryLocalProject =
212
279
  commandPath === 'project create' &&
213
280
  (globals.local !== undefined || globals.localHost !== undefined);
214
- // See `isPlanTemplateInvocation` for why this one case is
215
- // filtered here rather than in skill-nudge.ts / update-check.ts.
216
- const isPlanTemplate = isPlanTemplateInvocation(commandPath, globals.planTemplate);
217
- // Telemetry gate, same reasons as the update notice below: skip `completion`
218
- // (its stdout is eval'd by shells) and `--plan-template` (pure-local). Resolve
219
- // auth now, before the command's action runs, so `auth remove` still reports
220
- // on the key it used; skip the read for opt-out / dry-run.
221
- telemetryEmit = commandPath !== 'completion' && !isPlanTemplate;
281
+ // Telemetry gate, same reason as the update notice below: skip `completion`
282
+ // (its stdout is eval'd by shells). Resolve auth now, before the command's
283
+ // action runs, so `auth remove` still reports on the key it used; skip the
284
+ // read for opt-out / dry-run.
285
+ telemetryEmit = commandPath !== 'completion';
286
+ // Refuse an empty or whitespace-only positional before the action runs.
287
+ // This sits below the telemetry gate so the refusal is still reported as a
288
+ // VALIDATION_ERROR outcome, as it was when each command checked for itself,
289
+ // and above the auth read so a bad profile cannot replace this error.
290
+ validatePositionalArgs(actionCommand);
291
+ // The auth read is best-effort: an unreadable credentials file must not end
292
+ // the process here, before the command could run — `doctor` exists to
293
+ // diagnose exactly that, and offline commands never need the key. On failure
294
+ // the command runs as if telemetry were off (no event, and no fallback read
295
+ // at exit either).
222
296
  if (telemetryEmit && !isTelemetryOptedOut(process.env) && globals.dryRun !== true) {
223
- telemetryAuth = resolveTelemetryAuth({
224
- profile: globals.profile,
225
- endpointUrl: globals.endpointUrl,
226
- });
227
- }
228
- if (!isPlanTemplate) {
229
- maybeEmitSkillNudge({
230
- commandPath,
231
- output: isOutputMode(globals.output) ? globals.output : 'text',
232
- dryRun: globals.dryRun ?? false,
233
- profile: resolveProfileName(globals.profile),
234
- cwd: process.cwd(),
235
- env: process.env,
236
- debug: globals.debug ?? false,
297
+ telemetryAuth = tryResolveTelemetryAuth({ profile: globals.profile, endpointUrl: globals.endpointUrl }, {
298
+ onError: globals.debug
299
+ ? error => process.stderr.write(`[debug] telemetry skipped: ${error instanceof Error ? error.message : String(error)}\n`)
300
+ : undefined,
237
301
  });
302
+ if (telemetryAuth === undefined)
303
+ telemetryEmit = false;
238
304
  }
305
+ maybeEmitSkillNudge({
306
+ commandPath,
307
+ output: isOutputMode(globals.output) ? globals.output : 'text',
308
+ dryRun: globals.dryRun ?? false,
309
+ profile: resolveProfileName(globals.profile),
310
+ cwd: process.cwd(),
311
+ env: process.env,
312
+ debug: globals.debug ?? false,
313
+ });
239
314
  // Best-effort update notice (see lib/update-check.ts): self-gates on the
240
315
  // opt-out env, CI, TTY, and a 24h cache; the wiring adds the flag-level
241
316
  // gates the lib cannot see. Skipped for `completion` (its stdout is eval'd
242
- // by shells), under --output json, under --dry-run, and for
243
- // `--plan-template` (pure-local — this check hits the npm registry over
244
- // the network and writes ~/.testsprite/update-check.json, both of which
245
- // contradict "no network" for this flag). Deliberately not awaited: an
246
- // advisory must never delay the real command.
247
- if (globals.output !== 'json' &&
248
- globals.dryRun !== true &&
249
- commandPath !== 'completion' &&
250
- !isPlanTemplate) {
317
+ // by shells), under --output json and under --dry-run. Deliberately not
318
+ // awaited: an advisory must never delay the real command.
319
+ if (globals.output !== 'json' && globals.dryRun !== true && commandPath !== 'completion') {
251
320
  void maybeNotifyUpdate();
252
321
  }
253
322
  });
@@ -320,45 +389,46 @@ catch (err) {
320
389
  const output = new Output(mode);
321
390
  if (err instanceof ApiError) {
322
391
  const billingRefusal = classifyBillingRefusal(err);
323
- const message = err.code === 'UNSUPPORTED' &&
324
- err.getDetail('reason') === 'tunnel-unsupported-for-backend-test'
325
- ? '--local only supports frontend tests today. Re-run without --local, or point the test at a reachable base URL.'
326
- : err.message;
392
+ const { message, nextAction, details } = err;
327
393
  if (mode === 'json') {
328
394
  const envelope = {
329
395
  error: {
330
396
  code: err.code,
331
397
  message,
332
- nextAction: err.nextAction,
398
+ nextAction,
333
399
  requestId: err.requestId,
334
400
  // `err.details` is already redacted at ApiError construction (see
335
401
  // `errors.ts`); redacting again here is defence in depth for this
336
402
  // hand-built envelope specifically, independent of that.
337
- details: redactDeep(err.details),
403
+ details: redactDeep(details),
338
404
  ...(billingRefusal ? { links: billingRefusal.links } : {}),
339
405
  },
340
406
  };
341
- process.stderr.write(`${JSON.stringify(envelope, null, 2)}\n`);
407
+ process.stderr.write(`${jsonForTerminal(envelope, 2)}\n`);
342
408
  }
343
409
  else {
344
- process.stderr.write(`Error: ${message}\n`);
345
- if (err.nextAction)
346
- process.stderr.write(`${err.nextAction}\n`);
410
+ // Server text on a terminal: escape sequences and other control
411
+ // characters are removed, and the message and request id stay on their
412
+ // own line, so the server cannot write a line of its own beneath them.
413
+ // The JSON envelope above keeps what the server sent.
414
+ process.stderr.write(`Error: ${terminalSafeLine(message)}\n`);
415
+ if (nextAction)
416
+ process.stderr.write(`${terminalSafe(nextAction)}\n`);
347
417
  if (billingRefusal) {
348
418
  for (const line of billingRefusal.lines)
349
419
  process.stderr.write(`${line}\n`);
350
420
  }
351
421
  if (err.requestId && err.requestId !== 'local')
352
- process.stderr.write(`requestId: ${err.requestId}\n`);
422
+ process.stderr.write(`requestId: ${terminalSafeLine(err.requestId)}\n`);
353
423
  // C1: surface requiredScopes / grantedScopes on AUTH_FORBIDDEN
354
424
  if (err.code === 'AUTH_FORBIDDEN') {
355
425
  const required = err.getDetail('requiredScopes');
356
426
  const granted = err.getDetail('grantedScopes');
357
427
  if (Array.isArray(required) && required.length > 0) {
358
- process.stderr.write(` required: ${required.join(', ')}\n`);
428
+ process.stderr.write(` required: ${terminalSafeLine(required.join(', '))}\n`);
359
429
  }
360
430
  if (Array.isArray(granted)) {
361
- process.stderr.write(` granted: ${granted.join(', ')}\n`);
431
+ process.stderr.write(` granted: ${terminalSafeLine(granted.join(', '))}\n`);
362
432
  }
363
433
  }
364
434
  // Surface the version gap on CLIENT_TOO_OLD so the user sees exactly what
@@ -368,7 +438,7 @@ catch (err) {
368
438
  const your = err.getDetail('yourVersion');
369
439
  const min = err.getDetail('minVersion');
370
440
  if (typeof your === 'string' && typeof min === 'string') {
371
- process.stderr.write(` your version: ${your}, minimum supported: ${min}\n`);
441
+ process.stderr.write(` your version: ${terminalSafeLine(your)}, minimum supported: ${terminalSafeLine(min)}\n`);
372
442
  }
373
443
  }
374
444
  // AMBIGUOUS_ORG: the same testId resolved inside more than one of the
@@ -392,10 +462,10 @@ catch (err) {
392
462
  // A disarmed request has no run ID, so its JSON hint describes checking
393
463
  // current state before retrying. Both use the conventional 128+signum code.
394
464
  if (mode === 'json') {
395
- process.stderr.write(`${JSON.stringify(buildInterruptEnvelope(err), null, 2)}\n`);
465
+ process.stderr.write(`${jsonForTerminal(buildInterruptEnvelope(err), 2)}\n`);
396
466
  }
397
467
  else {
398
- process.stderr.write(`Error: ${err.message}\n`);
468
+ process.stderr.write(`Error: ${terminalSafeLine(err.message)}\n`);
399
469
  }
400
470
  await flushThenSetExitCode(err.exitCode);
401
471
  armInterruptExitBackstop(err.exitCode);
@@ -408,16 +478,17 @@ catch (err) {
408
478
  error: {
409
479
  code: 'REQUEST_TIMEOUT',
410
480
  message: err.message,
411
- nextAction: 'Increase --request-timeout <seconds> or set TESTSPRITE_REQUEST_TIMEOUT_MS. ' +
412
- 'Check that the backend is reachable and not overloaded.',
481
+ nextAction: err.nextAction ??
482
+ 'Increase --request-timeout <seconds> or set TESTSPRITE_REQUEST_TIMEOUT_MS. ' +
483
+ 'Check that the backend is reachable and not overloaded.',
413
484
  requestId: err.requestId,
414
485
  details: { timeoutMs: err.timeoutMs },
415
486
  },
416
487
  };
417
- process.stderr.write(`${JSON.stringify(envelope, null, 2)}\n`);
488
+ process.stderr.write(`${jsonForTerminal(envelope, 2)}\n`);
418
489
  }
419
490
  else {
420
- process.stderr.write(`Error: ${err.message}\n`);
491
+ process.stderr.write(`Error: ${terminalSafeLine(err.message)}\n`);
421
492
  }
422
493
  await flushThenSetExitCode(err.exitCode);
423
494
  }
@@ -458,7 +529,17 @@ catch (err) {
458
529
  }
459
530
  return mode;
460
531
  })();
461
- process.stderr.write(renderCommanderError(pendingCommanderErrorMsg, err.message, commanderMode));
532
+ // A removed command also says where it went, by the
533
+ // same walk that found the unknown name (Commander's own error and the
534
+ // one raised before a group's help both arrive here). A removed option
535
+ // does too, from the command the arguments name and the message it wrote.
536
+ const unknown = err.code === 'commander.unknownCommand' ? unknownCommandIn(program.args) : undefined;
537
+ const removedPointer = unknown !== undefined
538
+ ? removedCommandPointer(commandPathOf(unknown.group), unknown.name)
539
+ : err.code === 'commander.unknownOption'
540
+ ? removedOptionPointer(commandPathOf(commandNamedBy(program.args)), err.message)
541
+ : undefined;
542
+ process.stderr.write(renderCommanderError(pendingCommanderErrorMsg, err.message, commanderMode, removedPointer));
462
543
  await flushThenSetExitCode(5);
463
544
  }
464
545
  }
@@ -51,15 +51,19 @@ function truthy(value) {
51
51
  /**
52
52
  * Every relative path this CLI writes for a target, across all default skills.
53
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.
54
+ * Includes the backup siblings `agent install --force` leaves behind —
55
+ * `writeBackup` walks `.bak`, `.bak.1`, … `.bak.99` before giving up. Without
56
+ * them a repeated forced reinstall makes that target permanently "detected"
57
+ * from its own backups — the self-reinforcement `hasForeignContent` exists to
58
+ * prevent, just one file over.
58
59
  */
59
60
  function ownPaths(target) {
60
61
  return DEFAULT_SKILLS.flatMap(skill => {
61
62
  const p = pathFor(target, skill).replace(/\\/g, '/');
62
- return [p, `${p}.bak`];
63
+ const backups = [`${p}.bak`];
64
+ for (let n = 1; n <= 99; n++)
65
+ backups.push(`${p}.bak.${n}`);
66
+ return [p, ...backups];
63
67
  });
64
68
  }
65
69
  /**
@@ -30,7 +30,7 @@ export interface TargetSpec {
30
30
  * No-op for cline (body verbatim) and codex (managed-section authors plain
31
31
  * Markdown with no frontmatter).
32
32
  */
33
- wrap(name: string, description: string, body: string): string;
33
+ wrap(name: string, description: string, body: string, quote?: boolean): string;
34
34
  }
35
35
  /**
36
36
  * How a skill contributes to the codex target's always-on `AGENTS.md` section.
@@ -65,7 +65,7 @@ export interface SkillSpec {
65
65
  * `testsprite-onboard` codex contribution — a single always-on line. Kept here
66
66
  * (not in a `*.codex.md` asset) because it is one line; see {@link CodexContribution}.
67
67
  */
68
- export declare const ONBOARD_CODEX_LINE = "**First-time setup:** if this repo has no TestSprite tests yet, seed a *broad* first suite across its main user flows \u2014 not just one test \u2014 each with a concrete, observable assertion, before reporting setup as done. Try `testsprite test plan generate --project <id>` then `test plan accept` first; author plans by hand only if generation is unavailable.";
68
+ export declare const ONBOARD_CODEX_LINE = "**First-time setup:** if this repo has no TestSprite tests yet, seed a *broad* first suite across its main user flows \u2014 not just one test \u2014 each with a concrete, observable assertion, before reporting setup as done. Ask the project's agent with `testsprite plan --project <id> \"<the main user flows>\"`, review what it proposes, then `testsprite apply`.";
69
69
  /**
70
70
  * `testsprite-ci` codex contribution — one always-on line; the full onboarding
71
71
  * flow lives in the own-file body and the docs.
@@ -93,6 +93,12 @@ export declare const SKILL_NAME = "testsprite-verify";
93
93
  * byte-identity unit test keep working.
94
94
  */
95
95
  export declare const SKILL_DESCRIPTION: string;
96
+ /**
97
+ * Emit a frontmatter scalar: unchanged when a plain scalar is safe, otherwise a
98
+ * double-quoted YAML string (JSON escapes are a subset of YAML's). Keeps the
99
+ * verify/onboard renders byte-identical while making any description safe.
100
+ */
101
+ export declare function yamlScalar(value: string): string;
96
102
  /**
97
103
  * Repo-relative landing path for a given skill on a given target (POSIX
98
104
  * separators). Own-file targets embed the skill name in the path so multiple
@@ -193,6 +199,19 @@ export declare function loadCodexSkillBody(read?: ReadFn): string;
193
199
  * string lags but the body is unchanged, the artifact still compares pristine.
194
200
  */
195
201
  export declare function renderOwnFileWithMarker(target: AgentTarget, skill: string, markerLine: string, body?: string): string;
202
+ /**
203
+ * Render an own-file artifact the way v0.15.0 did: the description interpolated
204
+ * as an unquoted plain scalar. Kept only so install/status can recognise those
205
+ * files as pristine-but-outdated instead of user edits — never written.
206
+ */
207
+ export declare function renderLegacyOwnFileWithMarker(target: AgentTarget, skill: string, markerLine: string, body?: string): string;
208
+ /**
209
+ * True when `content` is exactly what v0.15.0 wrote for this (target, skill):
210
+ * the marker's hash still matches the canonical body, but the bytes only match
211
+ * the legacy unquoted render. Such files are stale installs, not user edits, so
212
+ * a plain `agent install` may repair them without `--force`.
213
+ */
214
+ export declare function isLegacyOwnFileRender(target: AgentTarget, skill: string, content: string, body?: string): boolean;
196
215
  /**
197
216
  * The exact bytes to write for one skill on one target.
198
217
  *