@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
@@ -1,8 +1,11 @@
1
1
  import { randomUUID } from 'node:crypto';
2
- import { readFileSync } from 'node:fs';
2
+ import { createReadStream, readFileSync, statSync } from 'node:fs';
3
+ import { basename, extname } from 'node:path';
4
+ import { Readable } from 'node:stream';
3
5
  import { Command } from 'commander';
4
- import { emitDryRunBanner, makeHttpClient, parseRequestTimeoutFlag, } from '../lib/client-factory.js';
5
- import { ApiError } from '../lib/errors.js';
6
+ import { emitDryRunBanner, makeHttpClient, parseRequestTimeoutFlag, resolveRequestTimeoutMs, } from '../lib/client-factory.js';
7
+ import { ApiError, InterruptError, RequestTimeoutError } from '../lib/errors.js';
8
+ import { globalShutdown } from '../lib/interrupt.js';
6
9
  import { GLOBAL_OPTS_HINT, Output, resolveOutputMode } from '../lib/output.js';
7
10
  import { readSecretFileGuarded } from '../lib/secret-file.js';
8
11
  import { assertNotLocal } from '../lib/target-url.js';
@@ -453,6 +456,382 @@ function renderAutoAuthText(r) {
453
456
  }
454
457
  return lines.join('\n');
455
458
  }
459
+ // ---------------------------------------------------------------------------
460
+ // project docs upload — DEV-384 piece V3-D
461
+ // ---------------------------------------------------------------------------
462
+ /**
463
+ * CLI-facing role flags → wire enum. Default is `api-doc` (stated in help);
464
+ * no inference from project type in v1 (design §3.4).
465
+ */
466
+ const DOC_ROLES = { 'api-doc': 'API_DOC', prd: 'PRD' };
467
+ /**
468
+ * MIME type sent in step 1 and echoed on the step-2 PUT. The backend signs
469
+ * `ContentType` into the presigned URL when supplied, so the PUT's
470
+ * `Content-Type` header must be byte-identical to what step 1 declared —
471
+ * both come from this one lookup, so they cannot drift.
472
+ */
473
+ const DOC_CONTENT_TYPES = {
474
+ '.json': 'application/json',
475
+ '.yaml': 'application/yaml',
476
+ '.yml': 'application/yaml',
477
+ '.md': 'text/markdown',
478
+ '.markdown': 'text/markdown',
479
+ '.txt': 'text/plain',
480
+ '.pdf': 'application/pdf',
481
+ };
482
+ const DEFAULT_DOC_CONTENT_TYPE = 'application/octet-stream';
483
+ /**
484
+ * `project docs upload <file>` — upload an API spec or PRD as a project
485
+ * source so plan generation has inputs to feed on (closes the API-project
486
+ * cold start at `no_processed_inputs`).
487
+ *
488
+ * Three-step flow against the V3-A facade routes:
489
+ *
490
+ * 1. `POST /projects/{id}/docs/upload-url` — mints a one-hour presigned
491
+ * S3 PUT URL plus the S3 key to register afterwards.
492
+ * 2. HTTP PUT of the file bytes to the presigned URL — **streamed**
493
+ * (`createReadStream` → web stream), never buffering the whole file.
494
+ * This request goes straight to S3: no facade base URL, no API key.
495
+ * 3. `POST /projects/{id}/docs` — registers the S3 object with its role
496
+ * and display name, which starts processing + embedding.
497
+ *
498
+ * Reading the local file as INPUT is allowed by DR-21 (the no-local-OUTPUTS
499
+ * rule); nothing is ever written back to disk.
500
+ *
501
+ * Failure modes are deliberately distinguished (design non-negotiable): a
502
+ * step-2 failure names the presigned PUT and the fix (re-running mints a
503
+ * fresh URL — they expire); a step-3 failure preserves the server envelope
504
+ * and says the upload already succeeded (re-running is safe: the server
505
+ * upserts the document by S3 key, so no duplicate is created).
506
+ */
507
+ export async function runDocsUpload(opts, deps = {}) {
508
+ const out = makeOutput(opts.output, deps);
509
+ const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
510
+ assertIdempotencyKey(opts.idempotencyKey);
511
+ const projectId = requireDocsProjectId(opts.projectId, deps);
512
+ const roleFlag = opts.role ?? 'api-doc';
513
+ if (!(roleFlag in DOC_ROLES)) {
514
+ throw localValidationError('--role must be api-doc (API spec, the default) or prd (product requirements document)');
515
+ }
516
+ const role = DOC_ROLES[roleFlag];
517
+ if (opts.name !== undefined && opts.name.trim().length === 0) {
518
+ throw localValidationError('--name must not be empty or whitespace-only');
519
+ }
520
+ if (opts.name !== undefined && opts.name.length > 255) {
521
+ throw localValidationError('--name must be at most 255 characters');
522
+ }
523
+ if (opts.file === undefined || opts.file.trim().length === 0) {
524
+ throw localValidationError('<file> is required');
525
+ }
526
+ // Size + existence sanity via stat only — the dry-run contract is "nothing
527
+ // read beyond a stat", and the real path opens the file exactly once, in
528
+ // the streamed PUT below.
529
+ let stat;
530
+ try {
531
+ stat = statSync(opts.file);
532
+ }
533
+ catch (cause) {
534
+ const code = cause.code;
535
+ if (code === 'ENOENT') {
536
+ throw localValidationError(`file does not exist: ${opts.file}`);
537
+ }
538
+ throw localValidationError(`cannot stat file ${opts.file}: ${cause.message ?? String(cause)}`);
539
+ }
540
+ if (!stat.isFile()) {
541
+ throw localValidationError(`${opts.file} is not a regular file (is it a directory?)`);
542
+ }
543
+ if (stat.size === 0) {
544
+ throw localValidationError(`file is empty (0 bytes), nothing to upload: ${opts.file}`);
545
+ }
546
+ const fileName = basename(opts.file);
547
+ if (fileName.length > 255) {
548
+ throw localValidationError('the file name (basename) must be at most 255 characters — rename the file ' +
549
+ '(--name only changes the display name, not the stored file name)');
550
+ }
551
+ const displayName = opts.name ?? fileName;
552
+ const contentType = DOC_CONTENT_TYPES[extname(fileName).toLowerCase()] ?? DEFAULT_DOC_CONTENT_TYPE;
553
+ const projectPath = encodeURIComponent(projectId);
554
+ if (opts.dryRun) {
555
+ // Same inline early-exit family as `test delete-batch --dry-run`: the
556
+ // command's dry-run contract (zero network, stat only, print the plan)
557
+ // cannot be expressed through canned fetch samples — step 2 would have
558
+ // to PUT somewhere. The `docsUploadUrl`/`docsRegister` entries in
559
+ // `samples.ts` are shape-guards/documentation, not consumed here.
560
+ emitDryRunBanner(stderr);
561
+ const plan = {
562
+ dryRun: true,
563
+ projectId,
564
+ file: opts.file,
565
+ fileName,
566
+ displayName,
567
+ role,
568
+ contentType,
569
+ size: stat.size,
570
+ steps: [
571
+ `POST /projects/${projectId}/docs/upload-url — mint a presigned S3 PUT URL for ${fileName} (${contentType})`,
572
+ `PUT ${stat.size} bytes to the presigned URL (streamed from disk, never buffered)`,
573
+ `POST /projects/${projectId}/docs — register ${displayName} as ${role}; starts processing + embedding`,
574
+ ],
575
+ };
576
+ out.print(plan, data => renderDocsUploadPlanText(data));
577
+ return plan;
578
+ }
579
+ const idempotencyKey = opts.idempotencyKey ?? `cli-docs-upload-${randomUUID()}`;
580
+ if (opts.idempotencyKey === undefined && (opts.output === 'json' || opts.verbose || opts.debug)) {
581
+ stderr(`idempotency-key: ${idempotencyKey}`);
582
+ }
583
+ const client = makeClient(opts, deps);
584
+ // ── Step 1 of 3: mint the presigned upload URL ────────────────────────────
585
+ const minted = await client.post(`/projects/${projectPath}/docs/upload-url`, { body: { fileName, contentType } });
586
+ // ── Step 2 of 3: stream the file bytes to S3 ──────────────────────────────
587
+ // Straight to the presigned host with the raw fetch impl — NOT through
588
+ // HttpClient, which would attach the facade base URL and leak the API key
589
+ // to S3. Content-Length comes from the stat: S3 rejects chunked
590
+ // transfer-encoding on presigned PUTs, and Node's fetch uses the explicit
591
+ // header to keep identity framing with a streamed body.
592
+ const fetchImpl = deps.fetchImpl ?? globalThis.fetch.bind(globalThis);
593
+ // DEV-384 review F3: a remote facade must mint a non-local https URL.
594
+ assertSafePresignedUploadUrl(minted.uploadUrl, client.resolvedBaseUrl);
595
+ // Same flag > TESTSPRITE_REQUEST_TIMEOUT_MS > default resolution (and 1-600s
596
+ // clamp) as makeHttpClient — this leg bypasses HttpClient, so resolve here.
597
+ const requestTimeoutMs = resolveRequestTimeoutMs(opts, deps.env ?? process.env);
598
+ const controller = new AbortController();
599
+ const timer = setTimeout(() => controller.abort(), requestTimeoutMs);
600
+ // DEV-384 review F14b: compose the shutdown signal into the PUT abort
601
+ // (manual listeners, house style — no AbortSignal.any) and arm the
602
+ // graceful scope for the upload's duration, so Ctrl-C during a long PUT
603
+ // takes the honest DEV-331 detach path instead of being unabortable.
604
+ const shutdown = deps.shutdown ?? globalShutdown;
605
+ const shutdownSignal = shutdown.signal;
606
+ const onShutdownAbort = () => controller.abort(shutdownSignal.reason);
607
+ const disarm = shutdown.arm();
608
+ if (shutdownSignal.aborted)
609
+ onShutdownAbort();
610
+ else
611
+ shutdownSignal.addEventListener('abort', onShutdownAbort, { once: true });
612
+ let putResponse;
613
+ try {
614
+ putResponse = await fetchImpl(minted.uploadUrl, {
615
+ method: 'PUT',
616
+ headers: { 'content-type': contentType, 'content-length': String(stat.size) },
617
+ body: Readable.toWeb(createReadStream(opts.file)),
618
+ duplex: 'half',
619
+ // #342 review: assertSafePresignedUploadUrl vets the MINTED url, but a
620
+ // default `redirect: 'follow'` would let a 3xx from that host resend
621
+ // the request to an unvetted Location (e.g. a 303 → 169.254.169.254) —
622
+ // an SSRF-shaped hop the guard never sees. A real S3 presigned PUT never
623
+ // redirects, so refuse: the thrown TypeError falls through to the catch
624
+ // below as a normal `presigned_put_failed` (no new error reason).
625
+ redirect: 'error',
626
+ signal: controller.signal,
627
+ });
628
+ }
629
+ catch (cause) {
630
+ // Interrupt outranks the timeout mapping: a Ctrl-C-aborted fetch must
631
+ // surface as InterruptError (exit 130/143), never as a timeout.
632
+ if (cause instanceof InterruptError)
633
+ throw cause;
634
+ if (shutdownSignal.aborted)
635
+ throw shutdownSignal.reason;
636
+ // Any other abort here is ours (the per-request timer): map to the CLI's
637
+ // typed exit-7 timeout, same contract as HttpClient's per-request timeout.
638
+ if (isAbortError(cause)) {
639
+ throw new RequestTimeoutError(requestTimeoutMs);
640
+ }
641
+ throw presignedPutError(`network error before S3 responded: ${describeCause(cause)}`, minted.expiresInSeconds);
642
+ }
643
+ finally {
644
+ clearTimeout(timer);
645
+ shutdownSignal.removeEventListener('abort', onShutdownAbort);
646
+ disarm();
647
+ }
648
+ if (!putResponse.ok) {
649
+ const snippet = (await putResponse.text().catch(() => '')).slice(0, 300);
650
+ throw presignedPutError(`S3 returned HTTP ${putResponse.status}${snippet ? ` — ${snippet}` : ''}`, minted.expiresInSeconds);
651
+ }
652
+ // ── Step 3 of 3: register the uploaded object ─────────────────────────────
653
+ let registered;
654
+ try {
655
+ registered = await client.post(`/projects/${projectPath}/docs`, {
656
+ body: { s3Key: minted.s3Key, displayName, docRole: role },
657
+ headers: { 'idempotency-key': idempotencyKey },
658
+ });
659
+ }
660
+ catch (cause) {
661
+ if (cause instanceof ApiError)
662
+ throw registerStepError(cause);
663
+ // DEV-384 review F4: a register timeout needs the same step-3 context —
664
+ // it is precisely the case where the caller can't tell whether the
665
+ // register landed. Class and exit 7 are preserved; only the text gains
666
+ // the upload-succeeded / safe-to-re-run explanation.
667
+ if (cause instanceof RequestTimeoutError) {
668
+ cause.message =
669
+ `Document register timed out (step 3 of 3) — the S3 upload succeeded, and the ` +
670
+ `register may or may not have landed. ${cause.message} Re-running the whole command ` +
671
+ `is safe: the server upserts the document by its S3 key (no duplicate is created; a PRD re-register re-runs the embedding compute, but the embedding charge is idempotent per document — never billed twice).`;
672
+ throw cause;
673
+ }
674
+ throw cause;
675
+ }
676
+ const result = {
677
+ resourceId: registered.resourceId,
678
+ displayName: registered.displayName ?? displayName,
679
+ role: registered.docRole ?? role,
680
+ size: stat.size,
681
+ processStatus: registered.processStatus,
682
+ };
683
+ out.print(result, data => renderDocsUploadText(data));
684
+ return result;
685
+ }
686
+ function isAbortError(cause) {
687
+ return cause instanceof Error && cause.name === 'AbortError';
688
+ }
689
+ function describeCause(cause) {
690
+ if (!(cause instanceof Error))
691
+ return String(cause);
692
+ // undici wraps network failures as `TypeError: fetch failed` with the
693
+ // useful detail on `.cause` — surface both.
694
+ const nested = cause.cause;
695
+ const nestedMsg = nested instanceof Error ? ` (${nested.message})` : '';
696
+ return `${cause.message}${nestedMsg}`;
697
+ }
698
+ /**
699
+ * DEV-384 review F3 — defense-in-depth on the server-minted presigned URL.
700
+ *
701
+ * A REMOTE facade must mint a non-local `https:` URL; a localhost/private or
702
+ * plain-http mint from a remote facade is exactly the anomaly to reject
703
+ * (compromised/misconfigured facade or an active MITM) — the PUT would
704
+ * otherwise send the user's file wherever that URL points, before any bytes
705
+ * leave the machine. A facade that is ITSELF loopback (dev rig, localhost
706
+ * e2e) is a deliberate operator configuration and is trusted to mint local
707
+ * URLs — and ONLY loopback qualifies (#342 review): the gate is a positive,
708
+ * fail-closed check, because gating on "anything `assertNotLocal` dislikes"
709
+ * would silently disable the guard for an unparsable base URL or a
710
+ * user-settable private-range endpoint (`--endpoint-url https://10.1.2.3`).
711
+ * Literal checks only (same scope as `assertNotLocal`); no host
712
+ * allow-listing by design.
713
+ *
714
+ * Known residual (#342 review): a loopback facade that is really a TUNNEL to a
715
+ * remote backend (`ssh -L`, a localhost corporate proxy) is trusted here even
716
+ * though the real conversation is remote and MITM-able upstream. This is
717
+ * inherent to "loopback facade = trusted dev rig" and accepted — the CLI
718
+ * cannot tell a dev rig from a tunnel by the base URL alone.
719
+ */
720
+ function assertSafePresignedUploadUrl(uploadUrl, facadeBaseUrl) {
721
+ if (isLoopbackFacade(facadeBaseUrl))
722
+ return;
723
+ const reject = (reason) => {
724
+ throw ApiError.fromEnvelope({
725
+ error: {
726
+ code: 'VALIDATION_ERROR',
727
+ message: `Refusing the presigned upload URL the server returned: ${reason}.`,
728
+ nextAction: 'No bytes were uploaded. This can indicate a misconfigured or intercepted API ' +
729
+ 'endpoint — verify --endpoint-url / TESTSPRITE_API_URL and retry.',
730
+ requestId: 'local',
731
+ details: { field: 'uploadUrl', reason: 'unsafe_presigned_url' },
732
+ },
733
+ });
734
+ };
735
+ let parsed;
736
+ try {
737
+ parsed = new URL(uploadUrl);
738
+ }
739
+ catch {
740
+ return reject('it is not a valid URL');
741
+ }
742
+ if (parsed.protocol !== 'https:')
743
+ return reject('it is not https');
744
+ if (isLocalUrl(uploadUrl))
745
+ return reject('it points at a local/private address');
746
+ }
747
+ /** True when `assertNotLocal` rejects the URL (localhost, RFC1918, link-local,
748
+ * metadata, non-http(s), unparsable). Fail-closed in the REJECTION direction
749
+ * only — used to refuse a suspicious mint, never to grant trust (that side
750
+ * is `isLoopbackFacade`). */
751
+ function isLocalUrl(url) {
752
+ try {
753
+ assertNotLocal(url);
754
+ return false;
755
+ }
756
+ catch {
757
+ return true;
758
+ }
759
+ }
760
+ /**
761
+ * #342 review: the facade-trust gate for `assertSafePresignedUploadUrl`.
762
+ * Positive and narrow — only an explicitly-loopback facade (`localhost`,
763
+ * a `127.0.0.0/8` literal, or `[::1]`) is trusted to mint local upload URLs.
764
+ * Anything else — including an unparsable base URL or a private-range
765
+ * endpoint — leaves the guard ON.
766
+ */
767
+ function isLoopbackFacade(url) {
768
+ let parsed;
769
+ try {
770
+ parsed = new URL(url);
771
+ }
772
+ catch {
773
+ return false;
774
+ }
775
+ // `localhost.` is the fully-qualified form of `localhost` (RFC 6761).
776
+ const host = parsed.hostname.toLowerCase().replace(/\.$/, '');
777
+ if (host === 'localhost')
778
+ return true;
779
+ if (/^127\.\d+\.\d+\.\d+$/.test(host))
780
+ return true;
781
+ return host === '[::1]';
782
+ }
783
+ /**
784
+ * Step-2 failure: the presigned PUT to S3. Distinguished from a register
785
+ * failure per the design non-negotiable — the fix is different (re-running
786
+ * re-mints the URL; nothing was registered, so nothing is half-done).
787
+ */
788
+ function presignedPutError(detail, expiresInSeconds) {
789
+ return new ApiError({
790
+ code: 'UNAVAILABLE',
791
+ message: `Presigned S3 upload failed (step 2 of 3): ${detail}`,
792
+ nextAction: 'The document was NOT registered. Re-run the command — each run mints a fresh ' +
793
+ `upload URL (presigned URLs expire, this one after ${Math.round(expiresInSeconds / 60)} minutes).`,
794
+ requestId: 'local',
795
+ details: { reason: 'presigned_put_failed' },
796
+ });
797
+ }
798
+ /**
799
+ * Step-3 failure: register. The server envelope (code, exit, requestId,
800
+ * details) passes through unchanged; only the text gains step context so
801
+ * the caller knows the upload itself already landed and a re-run is safe
802
+ * (the server upserts the document by S3 key — no duplicate).
803
+ */
804
+ function registerStepError(cause) {
805
+ return new ApiError({
806
+ code: cause.code,
807
+ message: `Document register failed (step 3 of 3) — the S3 upload succeeded, but the document is not registered yet. ${cause.message}`,
808
+ nextAction: `${cause.nextAction ? `${cause.nextAction} ` : ''}` +
809
+ 'Re-running the whole command is safe: the same file re-uploads and the server ' +
810
+ 'upserts the document by its S3 key (no duplicate is created; a PRD re-register re-runs the embedding compute, but the embedding charge is idempotent per document — never billed twice).',
811
+ requestId: cause.requestId,
812
+ details: cause.details,
813
+ }, cause.httpStatus, cause.retryAfterMs);
814
+ }
815
+ function formatDocSize(bytes) {
816
+ if (bytes < 1024)
817
+ return `${bytes} B`;
818
+ if (bytes < 1024 * 1024)
819
+ return `${Math.round(bytes / 1024)} KB`;
820
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
821
+ }
822
+ function renderDocsUploadText(r) {
823
+ return [
824
+ `uploaded ${r.displayName} (${formatDocSize(r.size)}) — processing started`,
825
+ 'note: generation can use this source once processing and embedding finish',
826
+ ' (check with `testsprite test plan generate` — it says if inputs are still processing)',
827
+ ].join('\n');
828
+ }
829
+ function renderDocsUploadPlanText(p) {
830
+ return [
831
+ `would upload ${p.file} (${formatDocSize(p.size)}) to project ${p.projectId} as ${p.role}:`,
832
+ ...p.steps.map((step, i) => ` ${i + 1}. ${step}`),
833
+ ].join('\n');
834
+ }
456
835
  export function createProjectCommand(deps = {}) {
457
836
  const project = new Command('project').description('Manage TestSprite projects');
458
837
  project
@@ -649,6 +1028,36 @@ export function createProjectCommand(deps = {}) {
649
1028
  idempotencyKey: cmdOpts.idempotencyKey,
650
1029
  }, deps);
651
1030
  });
1031
+ const docs = new Command('docs').description('Manage project documents — the sources plan generation feeds on');
1032
+ docs
1033
+ .command('upload <file>')
1034
+ .description('Upload an API spec or PRD as a project source (DEV-384). Three steps:\n' +
1035
+ 'mint a presigned S3 URL, stream the file bytes to it, register the\n' +
1036
+ 'document — which starts processing + embedding. The local file is\n' +
1037
+ 'only read; nothing is written back to disk.\n' +
1038
+ '\nExit codes:\n' +
1039
+ ' 0 upload registered (processing started)\n' +
1040
+ ' 3 auth error\n' +
1041
+ ' 4 project not found (or not accessible in this workspace)\n' +
1042
+ ' 5 validation error (missing/empty file, bad --role)\n' +
1043
+ ' 7 request timeout (also: backend predates the docs routes)\n' +
1044
+ ' 10 presigned S3 PUT failed — re-run to mint a fresh URL')
1045
+ .option('--project <id>', 'project id the document belongs to (required)')
1046
+ .option('--role <role>', 'document role: api-doc (API spec, default) | prd')
1047
+ .option('--name <display-name>', 'display name for the document (default: file basename)')
1048
+ .option('--idempotency-key <token>', 'opaque idempotency token. Defaults to a UUIDv4 minted per invocation.')
1049
+ .addHelpText('after', GLOBAL_OPTS_HINT)
1050
+ .action(async (file, cmdOpts, command) => {
1051
+ await runDocsUpload({
1052
+ ...resolveCommonOptions(command),
1053
+ file,
1054
+ projectId: cmdOpts.project,
1055
+ role: cmdOpts.role,
1056
+ name: cmdOpts.name,
1057
+ idempotencyKey: cmdOpts.idempotencyKey,
1058
+ }, deps);
1059
+ });
1060
+ project.addCommand(docs);
652
1061
  return project;
653
1062
  }
654
1063
  function parseFlag(raw, flagName) {
@@ -804,6 +1213,20 @@ function renderUpdateText(r) {
804
1213
  function renderDeleteText(r) {
805
1214
  return [`projectId ${r.projectId}`, `deletedAt ${r.deletedAt}`].join('\n');
806
1215
  }
1216
+ /**
1217
+ * `--project` resolution for `project docs upload` — mirrors test.ts's
1218
+ * resolveProjectId/requireProjectId so `TESTSPRITE_PROJECT_ID` works here the
1219
+ * same as on every other command (DEV-384 review F5). Flag wins over env.
1220
+ */
1221
+ function requireDocsProjectId(projectId, deps) {
1222
+ const explicit = projectId?.trim();
1223
+ if (explicit && explicit.length > 0)
1224
+ return explicit;
1225
+ const envValue = (deps.env ?? process.env).TESTSPRITE_PROJECT_ID?.trim();
1226
+ if (envValue && envValue.length > 0)
1227
+ return envValue;
1228
+ throw localValidationError('--project <id> is required; pass --project <id> or set TESTSPRITE_PROJECT_ID');
1229
+ }
807
1230
  function localValidationError(message) {
808
1231
  return ApiError.fromEnvelope({
809
1232
  error: {