@testsprite/testsprite-cli 0.7.0 → 0.8.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 (68) hide show
  1. package/README.md +51 -38
  2. package/dist/commands/agent.js +47 -3
  3. package/dist/commands/ci.d.ts +88 -0
  4. package/dist/commands/ci.js +429 -0
  5. package/dist/commands/doctor.js +100 -1
  6. package/dist/commands/init.js +8 -0
  7. package/dist/commands/project.d.ts +78 -0
  8. package/dist/commands/project.js +426 -3
  9. package/dist/commands/test.d.ts +162 -2
  10. package/dist/commands/test.js +1814 -392
  11. package/dist/commands/testlist.js +15 -9
  12. package/dist/commands/tunnel.d.ts +72 -0
  13. package/dist/commands/tunnel.js +367 -0
  14. package/dist/index.js +107 -38
  15. package/dist/lib/dry-run/samples.d.ts +9 -0
  16. package/dist/lib/dry-run/samples.js +116 -0
  17. package/dist/lib/gh-output.d.ts +7 -0
  18. package/dist/lib/gh-output.js +50 -7
  19. package/dist/lib/http.d.ts +94 -0
  20. package/dist/lib/http.js +120 -5
  21. package/dist/lib/interrupt.d.ts +38 -13
  22. package/dist/lib/interrupt.js +130 -15
  23. package/dist/lib/local-target.d.ts +95 -0
  24. package/dist/lib/local-target.js +184 -0
  25. package/dist/lib/plan-poll.d.ts +171 -0
  26. package/dist/lib/plan-poll.js +442 -0
  27. package/dist/lib/plans.types.d.ts +130 -0
  28. package/dist/lib/plans.types.js +31 -0
  29. package/dist/lib/poll-support.d.ts +26 -0
  30. package/dist/lib/poll-support.js +65 -0
  31. package/dist/lib/poll.d.ts +1 -0
  32. package/dist/lib/poll.js +2 -40
  33. package/dist/lib/response-schemas.d.ts +13 -0
  34. package/dist/lib/response-schemas.js +32 -0
  35. package/dist/lib/run-progress.d.ts +41 -0
  36. package/dist/lib/run-progress.js +56 -0
  37. package/dist/lib/runs.types.d.ts +24 -0
  38. package/dist/lib/target-url-preflight.js +3 -3
  39. package/dist/lib/target-url.d.ts +44 -7
  40. package/dist/lib/target-url.js +250 -61
  41. package/dist/lib/telemetry.d.ts +11 -0
  42. package/dist/lib/telemetry.js +1 -0
  43. package/dist/lib/ticker.d.ts +8 -0
  44. package/dist/lib/ticker.js +3 -0
  45. package/dist/lib/tunnel-session.d.ts +129 -0
  46. package/dist/lib/tunnel-session.js +232 -0
  47. package/dist/lib/tunnel.types.d.ts +54 -0
  48. package/dist/lib/tunnel.types.js +8 -0
  49. package/dist/vendor/tunnel-client/client.d.ts +83 -0
  50. package/dist/vendor/tunnel-client/client.js +871 -0
  51. package/dist/vendor/tunnel-client/config.d.ts +41 -0
  52. package/dist/vendor/tunnel-client/config.js +42 -0
  53. package/dist/vendor/tunnel-client/index.d.ts +9 -0
  54. package/dist/vendor/tunnel-client/index.js +9 -0
  55. package/dist/vendor/tunnel-client/lodash-lite.d.ts +14 -0
  56. package/dist/vendor/tunnel-client/lodash-lite.js +24 -0
  57. package/dist/vendor/tunnel-client/protocol.d.ts +60 -0
  58. package/dist/vendor/tunnel-client/protocol.js +143 -0
  59. package/dist/vendor/tunnel-client/types.d.ts +96 -0
  60. package/dist/vendor/tunnel-client/types.js +10 -0
  61. package/dist/vendor/tunnel-client/ws-compat.d.ts +206 -0
  62. package/dist/vendor/tunnel-client/ws-compat.js +316 -0
  63. package/dist/version.d.ts +1 -1
  64. package/dist/version.js +1 -1
  65. package/package.json +2 -1
  66. package/skills/testsprite-onboard.skill.md +60 -4
  67. package/skills/testsprite-verify.codex.md +22 -16
  68. package/skills/testsprite-verify.skill.md +27 -18
@@ -0,0 +1,184 @@
1
+ /**
2
+ * `--local <port>` argument handling and the pre-charge port probe.
3
+ *
4
+ * Separate from `target-url-preflight.ts` on purpose, even though both answer
5
+ * "is the thing I am about to bill a run against actually there". They probe
6
+ * two different mechanisms and must not share one:
7
+ *
8
+ * - `--target-url` is fetched by a browser inside a Lambda, so probing it
9
+ * with `fetch()` (proxy dispatcher and all) is the closest local analogue,
10
+ * and an ambiguous result downgrades to a warning because the CLI is not
11
+ * the machine that will do the fetching.
12
+ * - `--local <port>` is dialled by the vendored tunnel client running *in
13
+ * this very process*, with `net.connect`, against the candidate set
14
+ * {@link resolveDialCandidates} produces. So the probe uses that same
15
+ * function and the same kind of socket. A pass means at least one TCP
16
+ * connection actually completed; every other result refuses. In
17
+ * particular, `ETIMEDOUT` can be a dropped SYN with no listener at all,
18
+ * so it is not evidence that something is bound. That is why this one is
19
+ * allowed to be the gate that runs BEFORE the mint and therefore before
20
+ * any run row or credit spend exists.
21
+ */
22
+ import * as net from 'node:net';
23
+ import { ApiError, localValidationError } from './errors.js';
24
+ import { resolveDialCandidates } from '../vendor/tunnel-client/index.js';
25
+ /**
26
+ * The loopback spellings a tunnel target may use.
27
+ *
28
+ * This is a MIRROR of the server's `isLoopbackString`
29
+ * (backend-v2.0 `libs/net/private-address.ts`), which accepts exactly
30
+ * `localhost`, `127.0.0.1` and `::1` — not "anything in 127.0.0.0/8". Keeping
31
+ * the two identical is the whole point of validating client-side at all: a
32
+ * value this accepts and the server rejects would fail with
33
+ * `tunnel-target-not-local` AFTER a tunnel had already been minted, and a
34
+ * value this rejects but the server accepts is a capability silently withheld.
35
+ */
36
+ export const LOOPBACK_HOSTS = ['localhost', '127.0.0.1', '::1'];
37
+ /** Default `--local-host`. An IP literal, so no resolver is involved at all. */
38
+ export const DEFAULT_LOCAL_HOST = '127.0.0.1';
39
+ /**
40
+ * Per-candidate dial budget. Deliberately short: this is a loopback connect on
41
+ * the caller's own machine, where a live listener answers in microseconds. A
42
+ * long budget would only lengthen the wait before an honest refusal.
43
+ */
44
+ export const LOCAL_PORT_PROBE_TIMEOUT_MS = 2_000;
45
+ /** Parse `--local <port>`. Strict: this becomes part of a URL a run is billed against. */
46
+ export function parseLocalPort(raw) {
47
+ const port = Number(raw);
48
+ if (raw.trim() !== raw ||
49
+ raw.length === 0 ||
50
+ !Number.isInteger(port) ||
51
+ port < 1 ||
52
+ port > 65535) {
53
+ throw localValidationError('local', 'must be a port number between 1 and 65535');
54
+ }
55
+ return port;
56
+ }
57
+ /**
58
+ * Normalise and validate `--local-host`. Rejects everything outside
59
+ * {@link LOOPBACK_HOSTS} with zero network calls — a tunnel reaches the
60
+ * caller's own machine and nothing else, so a non-loopback value here is a
61
+ * misunderstanding to correct immediately, not a request to forward.
62
+ */
63
+ export function normalizeLocalHost(raw) {
64
+ if (raw === undefined)
65
+ return DEFAULT_LOCAL_HOST;
66
+ const unbracketed = raw.startsWith('[') && raw.endsWith(']') ? raw.slice(1, -1) : raw;
67
+ const candidate = unbracketed.trim().toLowerCase();
68
+ const match = LOOPBACK_HOSTS.find(host => host === candidate);
69
+ if (match === undefined) {
70
+ throw localValidationError('local-host', `must name your own machine — one of ${LOOPBACK_HOSTS.join(', ')}. ` +
71
+ 'A tunnel only reaches the machine running this CLI; to test a reachable ' +
72
+ 'address use --target-url instead', [...LOOPBACK_HOSTS]);
73
+ }
74
+ return match;
75
+ }
76
+ /** `http://<host>:<port>`, with IPv6 bracketed as the URL grammar requires. */
77
+ export function buildLocalTargetUrl(host, port) {
78
+ const authority = host.includes(':') ? `[${host}]` : host;
79
+ return `http://${authority}:${port}`;
80
+ }
81
+ function dialOnce(host, port, timeoutMs) {
82
+ return new Promise((resolve, reject) => {
83
+ const socket = net.connect({ host, port });
84
+ const cleanup = () => {
85
+ clearTimeout(timer);
86
+ socket.removeAllListeners();
87
+ socket.destroy();
88
+ };
89
+ const timer = setTimeout(() => {
90
+ cleanup();
91
+ const err = new Error(`connect timeout ${timeoutMs}ms`);
92
+ err.code = 'ETIMEDOUT';
93
+ reject(err);
94
+ }, timeoutMs);
95
+ socket.once('connect', () => {
96
+ cleanup();
97
+ resolve();
98
+ });
99
+ socket.once('error', err => {
100
+ cleanup();
101
+ reject(err);
102
+ });
103
+ });
104
+ }
105
+ function formatDialTarget(host, port) {
106
+ const authority = host.includes(':') ? `[${host}]` : host;
107
+ return `${authority}:${port}`;
108
+ }
109
+ function describeDialFailure(err) {
110
+ const code = err?.code;
111
+ const message = err instanceof Error ? err.message : String(err);
112
+ if (code === undefined || code === message)
113
+ return message;
114
+ return `${code} (${message})`;
115
+ }
116
+ /**
117
+ * Dial every candidate {@link resolveDialCandidates} produces for
118
+ * `host:port`. ANY successful connect is a pass — `localhost` resolves to both
119
+ * `127.0.0.1` and `::1`, and a dev server bound to one family must never be
120
+ * reported dead because the other refused.
121
+ */
122
+ export async function probeLocalPort(host, port, deps = {}) {
123
+ const resolveCandidates = deps.resolveCandidates ?? resolveDialCandidates;
124
+ const connect = deps.connect ?? dialOnce;
125
+ const candidates = await resolveCandidates(host, port);
126
+ if (candidates.length === 0) {
127
+ return {
128
+ verdict: 'refuse',
129
+ reason: `tried resolving ${formatDialTarget(host, port)}; resolver returned no dial candidates`,
130
+ };
131
+ }
132
+ const failures = [];
133
+ for (const candidate of candidates) {
134
+ try {
135
+ await connect(candidate.host, candidate.port, LOCAL_PORT_PROBE_TIMEOUT_MS);
136
+ return { verdict: 'ok' };
137
+ }
138
+ catch (err) {
139
+ failures.push(`${formatDialTarget(candidate.host, candidate.port)} -> ${describeDialFailure(err)}`);
140
+ }
141
+ }
142
+ return {
143
+ verdict: 'refuse',
144
+ reason: `no candidate connected to ${formatDialTarget(host, port)}; attempts: ` + failures.join('; '),
145
+ };
146
+ }
147
+ /** Shared refusal wording that names the one explicit bypass exactly once. */
148
+ const SKIP_HINT = 'Skip this check with --skip-preflight.';
149
+ /**
150
+ * Run {@link probeLocalPort} and either throw (refuse) or no-op (ok / skipped).
151
+ *
152
+ * Call this BEFORE minting a tunnel. That ordering is the feature: DEV-243
153
+ * measured 1,003 blocked-with-URL CLI runs, 55.5% of the third-party-tunnel
154
+ * ones blocked, every one of them charged, because the run row and its credit
155
+ * spend happen before the Lambda ever discovers the target is dead. A dev
156
+ * server that is not running is the single most likely `--local` mistake, and
157
+ * this is the only place it can be caught for free.
158
+ *
159
+ * `skipPreflight: true` is a pure no-op with ZERO connection attempts.
160
+ */
161
+ export async function assertLocalPortListening(host, port, opts, _stderrFn, deps = {}) {
162
+ if (opts.skipPreflight === true)
163
+ return;
164
+ const outcome = await probeLocalPort(host, port, deps);
165
+ if (outcome.verdict === 'refuse') {
166
+ throw ApiError.fromEnvelope({
167
+ error: {
168
+ code: 'VALIDATION_ERROR',
169
+ message: `Nothing is listening on ${host}:${port}, so a tunnel run would fail after being billed.`,
170
+ nextAction: `Start your app on port ${port} first, or point --local at the port it is actually ` +
171
+ `serving. ${SKIP_HINT}`,
172
+ requestId: 'local',
173
+ details: {
174
+ field: 'local',
175
+ reason: 'local-port-not-listening',
176
+ host,
177
+ port,
178
+ probeReason: outcome.reason,
179
+ },
180
+ },
181
+ });
182
+ }
183
+ }
184
+ //# sourceMappingURL=local-target.js.map
@@ -0,0 +1,171 @@
1
+ /**
2
+ * Generation-ladder driver for `test plan generate` (DEV-384 V3-B).
3
+ *
4
+ * This is a NEW loop, deliberately not a reuse of `poll.ts`: the run poller
5
+ * is hard-typed to runs (its `RunClient` contract, `isTerminalStatus` check,
6
+ * and `TimeoutError.runId` are all run-specific), while generation settles on
7
+ * a completely different state machine — the facade-synthesized
8
+ * `CliGenerationStatus` — and additionally has to RE-TRIGGER between stages
9
+ * (writes happen on POST; the read stays pure, so when a stage finishes while
10
+ * a later one is still missing the client must POST again to start it).
11
+ *
12
+ * What it shares with the run poller, by design:
13
+ *
14
+ * - **The shutdown handle is armed here** for the whole ladder (first POST
15
+ * included). Arm/disarm lives inside the run poller, not for free in the
16
+ * harness — without arming, Ctrl-C during a generate wait would hard-kill
17
+ * the process instead of running the honest-detach UX (DEV-331).
18
+ * - Long-poll preferred (`?waitSeconds = min(remaining, 25)`), with a
19
+ * plain-GET + fixed-sleep fallback when the server rejects `waitSeconds`
20
+ * with VALIDATION_ERROR (older deployment).
21
+ * - ONE session-scoped `AbortController` firing at the deadline plus a 2s
22
+ * transport cushion (a fixed absolute instant, so per-request minting
23
+ * would be pure churn), composed with the shutdown signal via explicit
24
+ * add/removeEventListener — NOT `AbortSignal.any`, whose dependent-signal
25
+ * tracking against the long-lived shutdown signal is the known
26
+ * FinalizationRegistry backlog. poll.ts CONTAINS that backlog by hoisting
27
+ * a single `.any()` per session (it still calls it); only http.ts
28
+ * eliminated it outright (`composeAbortSignals`). This module composes
29
+ * explicitly, like http.ts — don't go hunting for a poll.ts replacement
30
+ * that isn't there (DEV-384 review F12).
31
+ * A hung fetch can never overrun `--timeout` and an interrupt aborts the
32
+ * in-flight request instantly.
33
+ * - Every sleep is clamped to the remaining deadline and bails on interrupt.
34
+ *
35
+ * The deadline throws {@link PlanGenerationTimeoutError} — which, exactly
36
+ * like poll.ts's `TimeoutError`, is NOT a typed CLI error. The command layer
37
+ * must convert it into the typed exit-7 envelope (`code: 'UNSUPPORTED'`) the
38
+ * way every existing wait site does; letting it propagate raw would surface
39
+ * as a generic exit 1.
40
+ *
41
+ * ── Billing safety (why re-POSTs are guarded) ──────────────────────────────
42
+ *
43
+ * The proposals stage has NO server-side duplicate guard: a second append
44
+ * request wipes the staged batch, regenerates, and bills another 2 credits.
45
+ * The facade refuses to restart when it can SEE the stage (staged proposals,
46
+ * or in-flight per-feature flags) — but those flags are set asynchronously
47
+ * by the append listener, so a client that re-POSTs in the gap between
48
+ * "append accepted" and "flags visible" would still double-bill. Two ladder
49
+ * rules make that structurally impossible:
50
+ *
51
+ * 1. **Never re-POST after the proposals rung.** The trigger response names
52
+ * the remaining stages; when the last accepted trigger reported
53
+ * `stagesRemaining: []` there is no later stage a re-POST could start,
54
+ * so an idle-and-empty read just keeps polling.
55
+ * 2. **Dwell before any other re-POST.** A re-POST fires only once the
56
+ * started stage was actually observed running (it has genuinely
57
+ * finished), or after two consecutive idle reads (covering a stage that
58
+ * finished faster than our first poll). Exploration and strategy are
59
+ * server-idempotent (per-project ledger key / row lock), so a duplicate
60
+ * POST there wastes nothing even if the dwell heuristic misjudges.
61
+ */
62
+ import { ApiError } from './errors.js';
63
+ import type { ShutdownHandle } from './interrupt.js';
64
+ import type { CliGeneratePlansResponse, CliGetPlansResponse } from './plans.types.js';
65
+ /**
66
+ * Minimal structural interface the ladder needs from the HTTP client —
67
+ * mirrors `RunClient` in poll.ts so tests supply a lightweight fake instead
68
+ * of the full `HttpClient`.
69
+ */
70
+ export interface PlanLadderClient {
71
+ generatePlans(projectId: string, options: {
72
+ idempotencyKey: string;
73
+ signal?: AbortSignal;
74
+ }): Promise<CliGeneratePlansResponse>;
75
+ getPlans(projectId: string, options?: {
76
+ waitSeconds?: number;
77
+ signal?: AbortSignal;
78
+ }): Promise<CliGetPlansResponse>;
79
+ }
80
+ /**
81
+ * Thrown when the ladder's deadline elapses. NOT a typed CLI error — the
82
+ * command layer converts it to the exit-7 `UNSUPPORTED` envelope (see the
83
+ * module doc). Carries the last observed plans read so the caller can print
84
+ * an honest partial before exiting.
85
+ */
86
+ export declare class PlanGenerationTimeoutError extends Error {
87
+ readonly projectId: string;
88
+ readonly timeoutSeconds: number;
89
+ readonly lastPlans: CliGetPlansResponse | null;
90
+ constructor(projectId: string, timeoutSeconds: number, lastPlans: CliGetPlansResponse | null);
91
+ }
92
+ export interface PlanLadderOptions {
93
+ /** Total wall-clock budget for the WHOLE ladder (all stages), in seconds. */
94
+ timeoutSeconds: number;
95
+ /**
96
+ * Idempotency key for the first trigger POST. Every later POST attempt —
97
+ * 409-attaches included — suffixes it (`<key>:post2`, `<key>:post3`, …):
98
+ * each POST is fresh work, so replaying an earlier POST's cached 202
99
+ * would silently never start the next stage.
100
+ */
101
+ idempotencyKey: string;
102
+ /** Injectable sleep (tests use an instant fake). */
103
+ sleep?: (ms: number) => Promise<void>;
104
+ /**
105
+ * Graceful-detach coordinator (DEV-331). The ladder arms it for its whole
106
+ * duration; a SIGINT/SIGTERM surfaces as `InterruptError` out of this
107
+ * function and the caller renders the honest detach.
108
+ */
109
+ shutdown?: ShutdownHandle;
110
+ /**
111
+ * Fired after every trigger POST outcome: an accepted stage start
112
+ * (`acceptedPosts` counts it) or the `nothing_to_start` answer. The
113
+ * command layer prints the first-run hint / credentials warning from the
114
+ * FIRST accepted response.
115
+ */
116
+ onTrigger?: (response: CliGeneratePlansResponse, acceptedPosts: number) => void;
117
+ /** Fired when a trigger answered 409 `stage_in_flight` (attach + poll). */
118
+ onAttach?: (err: ApiError) => void;
119
+ /** Fired after every successful plans read (ticker updates). */
120
+ onTick?: (plans: CliGetPlansResponse, elapsedMs: number) => void;
121
+ /** Low-volume mode-switch messages (wired to stderr at `--verbose`). */
122
+ onTransition?: (msg: string) => void;
123
+ }
124
+ export interface PlanLadderResult {
125
+ /** The settled read: staged proposals (success), empty-idle, or `failed`. */
126
+ plans: CliGetPlansResponse;
127
+ /**
128
+ * The first ACCEPTED trigger response, or `null` when the ladder only ever
129
+ * attached to stages started elsewhere (409) or found the batch already
130
+ * staged (`nothing_to_start`).
131
+ */
132
+ firstTrigger: CliGeneratePlansResponse | null;
133
+ /** How many trigger POSTs were accepted (stages this invocation started). */
134
+ acceptedPosts: number;
135
+ /**
136
+ * DEV-1008 — `skippedCategories` from the accepted trigger that carried it
137
+ * (the proposals rung), or `null` when no accepted trigger did. Read from
138
+ * the LAST such trigger, not `firstTrigger`: on a fresh backend project
139
+ * the first accepted POST starts strategy, and the field rides only on
140
+ * the proposals POST that follows.
141
+ */
142
+ skippedCategories: number | null;
143
+ }
144
+ /**
145
+ * Hard cap on accepted trigger POSTs per invocation. The ladder has one rung
146
+ * per pipeline stage, so one more accepted POST than stages means the server
147
+ * keeps reporting "idle and nothing staged" after every stage was started — a
148
+ * contract violation worth failing loudly on instead of re-POSTing forever.
149
+ */
150
+ export declare const MAX_ACCEPTED_TRIGGER_POSTS: 3;
151
+ /**
152
+ * Companion cap on TOTAL trigger POSTs (attaches included), so an
153
+ * attach-dominated pathological sequence also fails fast instead of
154
+ * silently burning the whole `--timeout` (DEV-384 review): the accepted
155
+ * rungs + headroom for an attach per rung.
156
+ */
157
+ export declare const MAX_TRIGGER_POSTS_TOTAL: number;
158
+ /**
159
+ * Drive the generate ladder to a settled state: trigger the next missing
160
+ * stage, poll, re-trigger between stages, and return the settled plans read.
161
+ *
162
+ * @returns the settled read — the caller maps it to exit codes (staged
163
+ * proposals → 0, `failed` → 1) and renders it.
164
+ * @throws `PlanGenerationTimeoutError` when `timeoutSeconds` elapses (the
165
+ * caller converts to the typed exit-7 envelope).
166
+ * @throws `InterruptError` on SIGINT/SIGTERM while armed (the caller renders
167
+ * the honest detach and index.ts exits 128+signum).
168
+ * @throws `ApiError` for trigger/read failures (412 preconditions, 402
169
+ * credits, 404, 429 — already typed with their exit codes).
170
+ */
171
+ export declare function runGenerationLadder(client: PlanLadderClient, projectId: string, options: PlanLadderOptions): Promise<PlanLadderResult>;