@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
@@ -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>;
@@ -0,0 +1,442 @@
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, InterruptError } from './errors.js';
63
+ import { defaultSleep, isAbortError, sleepUnlessInterrupted } from './poll-support.js';
64
+ import { isActiveGenerationStatus, PLAN_GENERATION_STAGES } from './plans.types.js';
65
+ /**
66
+ * Thrown when the ladder's deadline elapses. NOT a typed CLI error — the
67
+ * command layer converts it to the exit-7 `UNSUPPORTED` envelope (see the
68
+ * module doc). Carries the last observed plans read so the caller can print
69
+ * an honest partial before exiting.
70
+ */
71
+ export class PlanGenerationTimeoutError extends Error {
72
+ projectId;
73
+ timeoutSeconds;
74
+ lastPlans;
75
+ constructor(projectId, timeoutSeconds, lastPlans) {
76
+ super(`Timed out after ${timeoutSeconds}s waiting for plan generation on ${projectId}`);
77
+ this.name = 'PlanGenerationTimeoutError';
78
+ this.projectId = projectId;
79
+ this.timeoutSeconds = timeoutSeconds;
80
+ this.lastPlans = lastPlans;
81
+ }
82
+ }
83
+ const LONG_POLL_WAIT_SECONDS = 25;
84
+ /** Client-side pacing between reads whenever the server can't long-poll for
85
+ * us: settled (idle) reads return immediately, and so does every read in
86
+ * the no-`waitSeconds` fallback mode. */
87
+ const SETTLED_POLL_DELAY_MS = 2_000;
88
+ /** Extra time the per-iteration abort allows past the deadline for
89
+ * in-flight transport before the fetch is cut (mirrors poll.ts). */
90
+ const TRANSPORT_CUSHION_MS = 2_000;
91
+ /**
92
+ * Hard cap on accepted trigger POSTs per invocation. The ladder has one rung
93
+ * per pipeline stage, so one more accepted POST than stages means the server
94
+ * keeps reporting "idle and nothing staged" after every stage was started — a
95
+ * contract violation worth failing loudly on instead of re-POSTing forever.
96
+ */
97
+ export const MAX_ACCEPTED_TRIGGER_POSTS = PLAN_GENERATION_STAGES.length;
98
+ /**
99
+ * Companion cap on TOTAL trigger POSTs (attaches included), so an
100
+ * attach-dominated pathological sequence also fails fast instead of
101
+ * silently burning the whole `--timeout` (DEV-384 review): the accepted
102
+ * rungs + headroom for an attach per rung.
103
+ */
104
+ export const MAX_TRIGGER_POSTS_TOTAL = PLAN_GENERATION_STAGES.length * 2;
105
+ /**
106
+ * Drive the generate ladder to a settled state: trigger the next missing
107
+ * stage, poll, re-trigger between stages, and return the settled plans read.
108
+ *
109
+ * @returns the settled read — the caller maps it to exit codes (staged
110
+ * proposals → 0, `failed` → 1) and renders it.
111
+ * @throws `PlanGenerationTimeoutError` when `timeoutSeconds` elapses (the
112
+ * caller converts to the typed exit-7 envelope).
113
+ * @throws `InterruptError` on SIGINT/SIGTERM while armed (the caller renders
114
+ * the honest detach and index.ts exits 128+signum).
115
+ * @throws `ApiError` for trigger/read failures (412 preconditions, 402
116
+ * credits, 404, 429 — already typed with their exit codes).
117
+ */
118
+ export async function runGenerationLadder(client, projectId, options) {
119
+ // Arm the graceful-detach scope for the WHOLE ladder — trigger POSTs
120
+ // included, not just the polling: a Ctrl-C during the first POST must
121
+ // detach honestly too (charges may already be committed server-side).
122
+ const disarm = options.shutdown?.arm();
123
+ try {
124
+ return await ladderLoop(client, projectId, options);
125
+ }
126
+ finally {
127
+ disarm?.();
128
+ }
129
+ }
130
+ async function ladderLoop(client, projectId, options) {
131
+ const shutdownSignal = options.shutdown?.signal;
132
+ const rawSleep = options.sleep ?? defaultSleep;
133
+ const sleep = (ms) => sleepUnlessInterrupted(rawSleep, ms, shutdownSignal);
134
+ const startMs = Date.now();
135
+ const deadlineMs = startMs + options.timeoutSeconds * 1000;
136
+ let lastPlans = null;
137
+ const timedOut = () => new PlanGenerationTimeoutError(projectId, options.timeoutSeconds, lastPlans);
138
+ // Hoisted ONCE per ladder *session*, not per request (mirrors poll.ts):
139
+ // the abort target — deadlineMs + a transport cushion — is a fixed
140
+ // absolute instant, identical for every trigger POST and plans read, so a
141
+ // per-request controller + `AbortSignal.any` composite was pure churn.
142
+ // Worse, every `AbortSignal.any` registered a never-removed dependent on
143
+ // the long-lived shutdown signal — the FinalizationRegistry backlog that
144
+ // poll.ts contains by hoisting one `.any()` per session and http.ts
145
+ // eliminated outright — the composition below uses explicit listeners,
146
+ // removed in the session's finally.
147
+ const deadlineController = new AbortController();
148
+ const deadlineTimer = setTimeout(() => deadlineController.abort(), deadlineMs - startMs + TRANSPORT_CUSHION_MS);
149
+ const session = composeSessionSignal(deadlineController.signal, shutdownSignal);
150
+ // Long-poll works until the server says otherwise (VALIDATION_ERROR on
151
+ // `waitSeconds` → plain GETs paced by SETTLED_POLL_DELAY_MS).
152
+ let useLongPoll = true;
153
+ /**
154
+ * Mutable ladder state, grouped in one object because `doTrigger` (a
155
+ * closure) writes it — plain `let` captures would freeze TypeScript's
156
+ * control-flow narrowing at the initial values.
157
+ *
158
+ * `expectedRemaining` is `stagesRemaining` from the last ACCEPTED
159
+ * trigger; `null` = unknown (this invocation attached to a stage started
160
+ * elsewhere). `[]` is the proposals rung — the never-re-POST billing
161
+ * guard keys off it. `proposalsObserved` arms the same guard when the
162
+ * proposals stage is seen RUNNING (covers the 409-attach path, where no
163
+ * trigger response names the stage); sticky — stages are ordered, so
164
+ * nothing legal follows proposals. `triggerPosts` counts every POST that
165
+ * reached the server (attaches included) — drives idempotency-key
166
+ * freshness and the total-POST fuse. `observedActiveSinceTrigger` /
167
+ * `consecutiveIdleGaps` implement the between-stages gap dwell.
168
+ */
169
+ const state = {
170
+ acceptedPosts: 0,
171
+ triggerPosts: 0,
172
+ firstTrigger: null,
173
+ skippedCategories: null,
174
+ expectedRemaining: null,
175
+ proposalsObserved: false,
176
+ observedActiveSinceTrigger: false,
177
+ consecutiveIdleGaps: 0,
178
+ };
179
+ /** Interrupt outranks everything, deadline second (mirrors poll.ts). */
180
+ const checkInterruptAndDeadline = () => {
181
+ if (shutdownSignal?.aborted)
182
+ throw shutdownSignal.reason;
183
+ if (Date.now() >= deadlineMs)
184
+ throw timedOut();
185
+ };
186
+ /**
187
+ * Run one bounded request on the session-scoped signal (deadline +
188
+ * transport cushion, composed with the interrupt), classifying errors
189
+ * the shared way (interrupt > deadline-abort > passthrough).
190
+ */
191
+ const bounded = async (fn) => {
192
+ checkInterruptAndDeadline();
193
+ try {
194
+ return await fn(session.signal);
195
+ }
196
+ catch (err) {
197
+ // Interrupt classification precedes the timeout mapping — a Ctrl-C
198
+ // that aborted the in-flight fetch must never read as a timeout.
199
+ if (err instanceof InterruptError)
200
+ throw err;
201
+ if (shutdownSignal?.aborted)
202
+ throw shutdownSignal.reason;
203
+ if (isAbortError(err))
204
+ throw timedOut();
205
+ throw err;
206
+ }
207
+ };
208
+ const doTrigger = async () => {
209
+ // Fresh idempotency namespace per POST attempt — ATTACHES INCLUDED
210
+ // (DEV-384 review): a 409's key is never committed server-side, but
211
+ // reusing it would silently depend on that; a fresh key never can.
212
+ // Transport-level retries inside one POST still share the header.
213
+ const key = state.triggerPosts === 0
214
+ ? options.idempotencyKey
215
+ : `${options.idempotencyKey}:post${state.triggerPosts + 1}`;
216
+ try {
217
+ const response = await bounded(signal => client.generatePlans(projectId, { idempotencyKey: key, signal }));
218
+ state.triggerPosts += 1;
219
+ if (response.status === 'nothing_to_start') {
220
+ options.onTrigger?.(response, state.acceptedPosts);
221
+ return 'nothing_to_start';
222
+ }
223
+ state.acceptedPosts += 1;
224
+ if (state.firstTrigger === null)
225
+ state.firstTrigger = response;
226
+ if (typeof response.skippedCategories === 'number') {
227
+ state.skippedCategories = response.skippedCategories;
228
+ }
229
+ state.expectedRemaining = response.stagesRemaining;
230
+ state.observedActiveSinceTrigger = false;
231
+ state.consecutiveIdleGaps = 0;
232
+ options.onTrigger?.(response, state.acceptedPosts);
233
+ return 'accepted';
234
+ }
235
+ catch (err) {
236
+ if (err instanceof ApiError &&
237
+ err.code === 'CONFLICT' &&
238
+ err.getDetail('reason') === 'stage_in_flight') {
239
+ // A stage is already running (Portal-triggered counts): attach and
240
+ // poll. We don't know what remains after it → re-POSTs allowed,
241
+ // guarded by the dwell and by `proposalsObserved` (billing guard #1
242
+ // arms off the OBSERVED status on this path).
243
+ state.triggerPosts += 1;
244
+ options.onAttach?.(err);
245
+ state.expectedRemaining = null;
246
+ state.observedActiveSinceTrigger = false;
247
+ state.consecutiveIdleGaps = 0;
248
+ return 'attached';
249
+ }
250
+ throw err;
251
+ }
252
+ };
253
+ const readPlans = async () => {
254
+ const attempt = async (withWait) => bounded(signal => {
255
+ if (!withWait)
256
+ return client.getPlans(projectId, { signal });
257
+ const remainingSeconds = Math.ceil((deadlineMs - Date.now()) / 1000);
258
+ const waitSeconds = Math.max(1, Math.min(remainingSeconds, LONG_POLL_WAIT_SECONDS));
259
+ return client.getPlans(projectId, { waitSeconds, signal });
260
+ });
261
+ try {
262
+ return await attempt(useLongPoll);
263
+ }
264
+ catch (err) {
265
+ // Older deployment without ?waitSeconds → downgrade once, permanently
266
+ // for this invocation, and retry immediately without it.
267
+ if (useLongPoll && err instanceof ApiError && err.code === 'VALIDATION_ERROR') {
268
+ useLongPoll = false;
269
+ options.onTransition?.('Server does not support long-poll (?waitSeconds) — switching to plain polling');
270
+ return attempt(false);
271
+ }
272
+ throw err;
273
+ }
274
+ };
275
+ /** Clamped pacing sleep for reads the server answered immediately. */
276
+ const paceBeforeNextRead = async () => {
277
+ const remaining = deadlineMs - Date.now();
278
+ if (remaining <= 0)
279
+ throw timedOut();
280
+ await sleep(Math.min(SETTLED_POLL_DELAY_MS, remaining));
281
+ };
282
+ try {
283
+ // ── initial trigger ──
284
+ const initial = await doTrigger();
285
+ if (initial === 'nothing_to_start') {
286
+ // Proposals already staged — one bounded read, render, done.
287
+ const plans = await readPlans();
288
+ lastPlans = plans;
289
+ options.onTick?.(plans, Date.now() - startMs);
290
+ return {
291
+ plans,
292
+ firstTrigger: state.firstTrigger,
293
+ acceptedPosts: state.acceptedPosts,
294
+ skippedCategories: state.skippedCategories,
295
+ };
296
+ }
297
+ // ── poll / re-trigger loop ──
298
+ while (true) {
299
+ checkInterruptAndDeadline();
300
+ const plans = await readPlans();
301
+ lastPlans = plans;
302
+ options.onTick?.(plans, Date.now() - startMs);
303
+ const status = plans.generation.status;
304
+ if (status === 'failed') {
305
+ return {
306
+ plans,
307
+ firstTrigger: state.firstTrigger,
308
+ acceptedPosts: state.acceptedPosts,
309
+ skippedCategories: state.skippedCategories,
310
+ };
311
+ }
312
+ if (isActiveGenerationStatus(status)) {
313
+ state.observedActiveSinceTrigger = true;
314
+ // Seeing the proposals stage RUN arms billing guard #1 regardless of
315
+ // who started it (DEV-384 review — the 409-attach path has no trigger
316
+ // response to arm it from).
317
+ if (status === 'proposing')
318
+ state.proposalsObserved = true;
319
+ state.consecutiveIdleGaps = 0;
320
+ // Long-poll mode: the server already waited for us — loop immediately.
321
+ // Fallback mode: pace client-side.
322
+ if (!useLongPoll)
323
+ await paceBeforeNextRead();
324
+ continue;
325
+ }
326
+ // status === 'idle'
327
+ if (plans.proposals.length > 0) {
328
+ // Staged batch present — success.
329
+ return {
330
+ plans,
331
+ firstTrigger: state.firstTrigger,
332
+ acceptedPosts: state.acceptedPosts,
333
+ skippedCategories: state.skippedCategories,
334
+ };
335
+ }
336
+ // Idle and nothing staged: the between-stages gap.
337
+ //
338
+ // Both idle branches below pace UNCONDITIONALLY — even in long-poll
339
+ // mode. This asymmetry with the active branch (which skips pacing under
340
+ // long-poll) is deliberate, not a bug: the server only enters its
341
+ // waitSeconds hold for an ACTIVE generation status (`getPlans` guards
342
+ // its wait loop with `waitSeconds && isActiveGenerationStatus(...)`),
343
+ // so an idle read returns immediately and an unpaced loop here would
344
+ // hammer the facade (DEV-384 review F13).
345
+ //
346
+ // Billing guard #1: once the proposals rung is known to have started —
347
+ // our own trigger said so (`stagesRemaining: []`) OR we watched it run
348
+ // (`proposing`, incl. after a 409-attach) — there is NO later stage;
349
+ // never re-POST (a duplicate append would wipe + re-bill). Keep polling
350
+ // until staged/failed/timeout.
351
+ if ((state.expectedRemaining !== null && state.expectedRemaining.length === 0) ||
352
+ state.proposalsObserved) {
353
+ options.onTransition?.('Proposals stage triggered — waiting for the staged batch to appear');
354
+ await paceBeforeNextRead();
355
+ continue;
356
+ }
357
+ // Billing guard #2 (dwell): re-POST only when the started stage was
358
+ // observed running (it has genuinely finished), or after two
359
+ // consecutive idle reads (stage finished before our first poll).
360
+ state.consecutiveIdleGaps += 1;
361
+ if (!state.observedActiveSinceTrigger && state.consecutiveIdleGaps < 2) {
362
+ await paceBeforeNextRead();
363
+ continue;
364
+ }
365
+ if (state.acceptedPosts >= MAX_ACCEPTED_TRIGGER_POSTS ||
366
+ state.triggerPosts >= MAX_TRIGGER_POSTS_TOTAL) {
367
+ // Every rung started (or the total-POST budget is spent on attaches)
368
+ // yet the server still reports idle+empty — a facade contract
369
+ // violation; fail loudly instead of looping.
370
+ throw ApiError.fromEnvelope({
371
+ error: {
372
+ code: 'INTERNAL',
373
+ message: `Plan generation appears stuck: ${state.triggerPosts} trigger request(s) ` +
374
+ `(${state.acceptedPosts} accepted) but the server still reports no staged ` +
375
+ `proposals and nothing running.`,
376
+ nextAction: 'Retry later or check the project in the Portal. If this persists, report the requestId to support@testsprite.com.',
377
+ requestId: 'local',
378
+ details: {
379
+ projectId,
380
+ acceptedPosts: state.acceptedPosts,
381
+ triggerPosts: state.triggerPosts,
382
+ },
383
+ },
384
+ });
385
+ }
386
+ const outcome = await doTrigger();
387
+ if (outcome === 'nothing_to_start') {
388
+ // Proposals got staged between our read and the POST (or another
389
+ // client staged them) — settle on a final read.
390
+ const finalPlans = await readPlans();
391
+ lastPlans = finalPlans;
392
+ options.onTick?.(finalPlans, Date.now() - startMs);
393
+ return {
394
+ plans: finalPlans,
395
+ firstTrigger: state.firstTrigger,
396
+ acceptedPosts: state.acceptedPosts,
397
+ skippedCategories: state.skippedCategories,
398
+ };
399
+ }
400
+ // 'accepted' or 'attached' → back to polling.
401
+ }
402
+ }
403
+ finally {
404
+ clearTimeout(deadlineTimer);
405
+ session.cleanup();
406
+ }
407
+ }
408
+ /**
409
+ * Compose the session deadline signal with the (optional, long-lived)
410
+ * shutdown signal WITHOUT `AbortSignal.any` — same rationale as http.ts's
411
+ * `composeAbortSignals`: `.any()` tracks its result as a dependent of every
412
+ * source via WeakRef + FinalizationRegistry, and dependents registered
413
+ * against the process-lifetime shutdown signal are reclaimed only when V8
414
+ * runs a (deferrable) cleanup pass. Explicit listeners, removed by
415
+ * `cleanup()` in the session's finally, leave nothing behind.
416
+ */
417
+ function composeSessionSignal(deadlineSignal, shutdownSignal) {
418
+ if (shutdownSignal == null) {
419
+ return { signal: deadlineSignal, cleanup: () => { } };
420
+ }
421
+ const controller = new AbortController();
422
+ // Mirror AbortSignal.any's already-aborted short-circuit.
423
+ const alreadyAborted = [deadlineSignal, shutdownSignal].find(s => s.aborted);
424
+ if (alreadyAborted) {
425
+ controller.abort(alreadyAborted.reason);
426
+ return { signal: controller.signal, cleanup: () => { } };
427
+ }
428
+ const removers = [];
429
+ for (const source of [deadlineSignal, shutdownSignal]) {
430
+ const onAbort = () => controller.abort(source.reason);
431
+ source.addEventListener('abort', onAbort, { once: true });
432
+ removers.push(() => source.removeEventListener('abort', onAbort));
433
+ }
434
+ return {
435
+ signal: controller.signal,
436
+ cleanup: () => {
437
+ for (const remove of removers)
438
+ remove();
439
+ },
440
+ };
441
+ }
442
+ //# sourceMappingURL=plan-poll.js.map