@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,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
@@ -0,0 +1,130 @@
1
+ /**
2
+ * Wire types for the DEV-384 plan-generation surface:
3
+ *
4
+ * `POST /api/cli/v1/projects/{id}/plans/generate` — start the next missing
5
+ * pipeline stage (202)
6
+ * `GET /api/cli/v1/projects/{id}/plans` — synthesized generation
7
+ * status + staged proposals + best-effort credits (long-polls via
8
+ * `?waitSeconds=1..25`)
9
+ * `POST /api/cli/v1/projects/{id}/plans/accept` — staged proposals → real
10
+ * test cases
11
+ *
12
+ * These mirror the backend facade's `cli-plans.types.ts` (V3-A) shape-for-
13
+ * shape. The generation `status` is FACADE-SYNTHESIZED — no such enum exists
14
+ * on the V3 pipeline itself (design-doc v3.1 §7, DR-31) — so the CLI treats
15
+ * it as the complete truth and never tries to derive state from anything
16
+ * else.
17
+ */
18
+ /** Pipeline stages the trigger can start, in ladder order. */
19
+ export declare const PLAN_GENERATION_STAGES: readonly ["exploration", "strategy", "proposals"];
20
+ export type CliGenerationStage = (typeof PLAN_GENERATION_STAGES)[number];
21
+ /**
22
+ * Facade-synthesized generation status. `exploring`/`strategizing`/
23
+ * `proposing` are the active (keep-polling) states; `idle` means nothing is
24
+ * running (proposals present = staged batch ready, proposals empty = nothing
25
+ * staged yet); `failed` carries `errorCode`/`errorMessage`.
26
+ */
27
+ export type CliGenerationStatus = 'exploring' | 'strategizing' | 'proposing' | 'idle' | 'failed';
28
+ /**
29
+ * `generation.errorCode` values a `failed` status can carry. Kept as an open
30
+ * string union on the wire (`string | null` in {@link CliGenerationBlock})
31
+ * so a future backend adding a code is non-breaking — the CLI renders the
32
+ * message text and never switches on codes outside this set.
33
+ */
34
+ export type CliGenerationErrorCode = 'exploration_failed' | 'strategy_generation_stale' | 'proposal_generation_aborted';
35
+ /** Exploration progress: resources SETTLED (process AND embedding terminal). */
36
+ export interface CliGenerationProgress {
37
+ resourcesReady: number;
38
+ resourcesTotal: number;
39
+ }
40
+ export interface CliGenerationBlock {
41
+ status: CliGenerationStatus;
42
+ /** Present only while `exploring`. */
43
+ progress?: CliGenerationProgress;
44
+ errorCode: string | null;
45
+ errorMessage: string | null;
46
+ }
47
+ /** One FE plan step inside a staged proposal. */
48
+ export interface CliPlanProposalStep {
49
+ type: 'action' | 'assertion';
50
+ description: string;
51
+ }
52
+ /**
53
+ * One staged proposal. `proposalId` is the stable id `accept --only`
54
+ * consumes — every listed proposal carries it, which is why the CLI table
55
+ * prints it.
56
+ */
57
+ export interface CliPlanProposal {
58
+ proposalId: string;
59
+ title: string;
60
+ description: string;
61
+ /** CLI priority vocabulary (`p1`..`p3`, mapped from V3 High/Medium/Low). */
62
+ priority: string;
63
+ category: string;
64
+ feature: string;
65
+ type: 'frontend' | 'backend';
66
+ /** Frontend proposals: action/assertion steps. */
67
+ steps?: CliPlanProposalStep[];
68
+ /** Backend proposals: the endpoint under test (when resolvable). */
69
+ endpointPath?: string | null;
70
+ /** Backend proposals: variable names this test captures for consumers. */
71
+ captures?: string[];
72
+ /** Backend proposals: variable names this test consumes from producers. */
73
+ consumes?: string[];
74
+ }
75
+ export interface CliPlanCreditsCharged {
76
+ action: string;
77
+ amount: number;
78
+ }
79
+ /**
80
+ * Best-effort billing summary — the facade degrades this to an empty block
81
+ * on any billing-read failure, so the CLI must render fine without it
82
+ * (design-doc §5: "filled in best-effort and never able to fail the
83
+ * command").
84
+ */
85
+ export interface CliPlanCreditsBlock {
86
+ charged: CliPlanCreditsCharged[];
87
+ balance: number | null;
88
+ }
89
+ /** `GET /projects/{id}/plans` response. */
90
+ export interface CliGetPlansResponse {
91
+ generation: CliGenerationBlock;
92
+ proposals: CliPlanProposal[];
93
+ /** Optional-safe on the wire: treat an absent block like an empty one. */
94
+ credits?: CliPlanCreditsBlock;
95
+ }
96
+ /** `POST /projects/{id}/plans/generate` response (HTTP 202 both ways). */
97
+ export interface CliGeneratePlansResponse {
98
+ /**
99
+ * `accepted` — one stage was started; poll `GET /plans`.
100
+ * `nothing_to_start` — proposals are already staged (the facade's
101
+ * no-restart guard: a duplicate append would wipe the staged batch and
102
+ * re-bill 2 credits, so the trigger refuses and points at the batch).
103
+ */
104
+ status: 'accepted' | 'nothing_to_start';
105
+ /** The resolved V3 project id (the id `GET /plans` should be polled with). */
106
+ projectId: string;
107
+ stage: CliGenerationStage | null;
108
+ stagesRemaining: CliGenerationStage[];
109
+ enqueuedAt: string;
110
+ /**
111
+ * DEV-1008 — `stage: proposals` on a backend project only. Strategy
112
+ * categories the proposals stage was NOT asked for because they carry no
113
+ * endpoint to attach a test case to (cross-cutting themes such as
114
+ * authorization or pagination). Absent when nothing was skipped and on
115
+ * every other stage. The stage is charged flat, so this is the only
116
+ * signal that the plan covers fewer categories than the strategy lists.
117
+ */
118
+ skippedCategories?: number;
119
+ }
120
+ /**
121
+ * `POST /projects/{id}/plans/accept` response — the server's real shape.
122
+ * No code-generation field: accept does not generate code (API test code
123
+ * generates at first run — DR-29).
124
+ */
125
+ export interface CliAcceptPlansResponse {
126
+ acceptedCount: number;
127
+ caseKeys: string[];
128
+ }
129
+ /** The active (keep-polling) statuses. `idle`/`failed` are settled. */
130
+ export declare function isActiveGenerationStatus(status: CliGenerationStatus): boolean;
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Wire types for the DEV-384 plan-generation surface:
3
+ *
4
+ * `POST /api/cli/v1/projects/{id}/plans/generate` — start the next missing
5
+ * pipeline stage (202)
6
+ * `GET /api/cli/v1/projects/{id}/plans` — synthesized generation
7
+ * status + staged proposals + best-effort credits (long-polls via
8
+ * `?waitSeconds=1..25`)
9
+ * `POST /api/cli/v1/projects/{id}/plans/accept` — staged proposals → real
10
+ * test cases
11
+ *
12
+ * These mirror the backend facade's `cli-plans.types.ts` (V3-A) shape-for-
13
+ * shape. The generation `status` is FACADE-SYNTHESIZED — no such enum exists
14
+ * on the V3 pipeline itself (design-doc v3.1 §7, DR-31) — so the CLI treats
15
+ * it as the complete truth and never tries to derive state from anything
16
+ * else.
17
+ */
18
+ /** Pipeline stages the trigger can start, in ladder order. */
19
+ export const PLAN_GENERATION_STAGES = ['exploration', 'strategy', 'proposals'];
20
+ // A local `PLAN_STAGE_COSTS` price table used to live here, feeding the
21
+ // `--help` credits block and the pre-run hint. Both were removed: the command
22
+ // no longer quotes a price up front (matching `test run`), and actual spend is
23
+ // reported after the fact from `credits.charged` / `credits.balance` on the
24
+ // wire. Deliberately NOT kept as an unused constant — a hardcoded copy of the
25
+ // backend's rate card that nothing reads is a silent drift risk against
26
+ // `billing-pricing.ts`, which is the only billing authority.
27
+ /** The active (keep-polling) statuses. `idle`/`failed` are settled. */
28
+ export function isActiveGenerationStatus(status) {
29
+ return status === 'exploring' || status === 'strategizing' || status === 'proposing';
30
+ }
31
+ //# sourceMappingURL=plans.types.js.map
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Shared low-level helpers for the two polling loops (`poll.ts` for run
3
+ * polling, `plan-poll.ts` for the plan-generation ladder). These three were
4
+ * byte-identical copies in both files (#341 review); extracted here so a fix
5
+ * to the interrupt/abort contract lands in one place. Signal COMPOSITION is
6
+ * deliberately NOT here — each loop composes its own session signal with a
7
+ * shape specific to its lifetime (`poll.ts` inline, `plan-poll.ts` via
8
+ * `composeSessionSignal`), and folding those together would couple two
9
+ * unrelated lifetimes.
10
+ */
11
+ /** Resolve after `ms`. The default injectable sleep; tests substitute a fake. */
12
+ export declare function defaultSleep(ms: number, signal?: AbortSignal): Promise<void>;
13
+ /**
14
+ * Race a sleep against the shutdown signal: rejects with the signal's
15
+ * `InterruptError` reason the moment it fires, so no backoff/retry/pacing wait
16
+ * can delay the honest-detach UX. The default sleep receives the signal and
17
+ * clears its pending timer when interrupted; the outer race remains necessary
18
+ * for injected sleeps that do not implement cancellation themselves.
19
+ */
20
+ export declare function sleepUnlessInterrupted(sleep: (ms: number, signal?: AbortSignal) => Promise<void>, ms: number, signal: AbortSignal | undefined): Promise<void>;
21
+ /**
22
+ * Detects an AbortError thrown when an AbortSignal fires. Works for native
23
+ * fetch AbortErrors as well as `AbortController.abort()` from Node 18+ stdlib
24
+ * (both set `name === 'AbortError'`).
25
+ */
26
+ export declare function isAbortError(err: unknown): boolean;