@testsprite/testsprite-cli 0.1.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 (63) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +190 -0
  3. package/dist/assets/agent-skill/testsprite-verify.codex.md +119 -0
  4. package/dist/assets/agent-skill/testsprite-verify.skill.md +423 -0
  5. package/dist/commands/agent.d.ts +51 -0
  6. package/dist/commands/agent.js +552 -0
  7. package/dist/commands/auth.d.ts +38 -0
  8. package/dist/commands/auth.js +247 -0
  9. package/dist/commands/init.d.ts +63 -0
  10. package/dist/commands/init.js +350 -0
  11. package/dist/commands/project.d.ts +72 -0
  12. package/dist/commands/project.js +400 -0
  13. package/dist/commands/test.d.ts +1245 -0
  14. package/dist/commands/test.js +6214 -0
  15. package/dist/commands/usage.d.ts +63 -0
  16. package/dist/commands/usage.js +156 -0
  17. package/dist/index.d.ts +2 -0
  18. package/dist/index.js +146 -0
  19. package/dist/lib/agent-targets.d.ts +50 -0
  20. package/dist/lib/agent-targets.js +99 -0
  21. package/dist/lib/bundle.d.ts +178 -0
  22. package/dist/lib/bundle.js +600 -0
  23. package/dist/lib/client-factory.d.ts +72 -0
  24. package/dist/lib/client-factory.js +120 -0
  25. package/dist/lib/config.d.ts +24 -0
  26. package/dist/lib/config.js +30 -0
  27. package/dist/lib/credentials.d.ts +17 -0
  28. package/dist/lib/credentials.js +122 -0
  29. package/dist/lib/dry-run/fetch.d.ts +18 -0
  30. package/dist/lib/dry-run/fetch.js +52 -0
  31. package/dist/lib/dry-run/samples.d.ts +50 -0
  32. package/dist/lib/dry-run/samples.js +676 -0
  33. package/dist/lib/errors.d.ts +118 -0
  34. package/dist/lib/errors.js +388 -0
  35. package/dist/lib/facade.d.ts +48 -0
  36. package/dist/lib/facade.js +104 -0
  37. package/dist/lib/failing-fe-resolver.d.ts +60 -0
  38. package/dist/lib/failing-fe-resolver.js +103 -0
  39. package/dist/lib/http.d.ts +255 -0
  40. package/dist/lib/http.js +608 -0
  41. package/dist/lib/output.d.ts +55 -0
  42. package/dist/lib/output.js +70 -0
  43. package/dist/lib/pagination.d.ts +56 -0
  44. package/dist/lib/pagination.js +81 -0
  45. package/dist/lib/poll.d.ts +88 -0
  46. package/dist/lib/poll.js +221 -0
  47. package/dist/lib/prompt.d.ts +8 -0
  48. package/dist/lib/prompt.js +97 -0
  49. package/dist/lib/rate-throttle.d.ts +49 -0
  50. package/dist/lib/rate-throttle.js +75 -0
  51. package/dist/lib/render-error.d.ts +15 -0
  52. package/dist/lib/render-error.js +44 -0
  53. package/dist/lib/runs.types.d.ts +344 -0
  54. package/dist/lib/runs.types.js +25 -0
  55. package/dist/lib/target-url.d.ts +25 -0
  56. package/dist/lib/target-url.js +127 -0
  57. package/dist/lib/ticker.d.ts +37 -0
  58. package/dist/lib/ticker.js +63 -0
  59. package/dist/lib/validate.d.ts +82 -0
  60. package/dist/lib/validate.js +165 -0
  61. package/dist/version.d.ts +1 -0
  62. package/dist/version.js +2 -0
  63. package/package.json +65 -0
@@ -0,0 +1,552 @@
1
+ import path from 'node:path';
2
+ import fs from 'node:fs/promises';
3
+ import { Command } from 'commander';
4
+ import { CLIError, localValidationError } from '../lib/errors.js';
5
+ import { GLOBAL_OPTS_HINT, Output } from '../lib/output.js';
6
+ import { promptText } from '../lib/prompt.js';
7
+ import { TARGETS, loadSkillBody, loadCodexSkillBody, renderForTarget, MANAGED_SECTION_BEGIN, MANAGED_SECTION_END, } from '../lib/agent-targets.js';
8
+ // ---------------------------------------------------------------------------
9
+ // Constants
10
+ // ---------------------------------------------------------------------------
11
+ /**
12
+ * Codex loads AGENTS.md files lazily and has a documented 32 KiB load budget
13
+ * per file. Content beyond that offset is silently truncated. We warn (but do
14
+ * not refuse to write) when a managed-section write would produce a file larger
15
+ * than this threshold so operators have early visibility.
16
+ */
17
+ export const AGENTS_MD_CODEX_BUDGET_BYTES = 32768; // 32 KiB
18
+ const defaultAgentFs = {
19
+ async lstat(p) {
20
+ try {
21
+ const s = await fs.lstat(p);
22
+ return { isFile: s.isFile(), isSymbolicLink: s.isSymbolicLink() };
23
+ }
24
+ catch (err) {
25
+ if (err instanceof Error && err.code === 'ENOENT') {
26
+ return null;
27
+ }
28
+ throw err;
29
+ }
30
+ },
31
+ async readFile(p) {
32
+ return fs.readFile(p, 'utf8');
33
+ },
34
+ async writeFile(p, data, opts) {
35
+ await fs.writeFile(p, data, { encoding: 'utf8', flag: opts?.exclusive ? 'wx' : 'w' });
36
+ },
37
+ async mkdir(p) {
38
+ await fs.mkdir(p, { recursive: true });
39
+ },
40
+ };
41
+ // ---------------------------------------------------------------------------
42
+ // Path safety
43
+ // ---------------------------------------------------------------------------
44
+ /**
45
+ * Walk each component of `relPath` beneath `root`, refusing to traverse or
46
+ * write through a symlink. `fs.mkdir`/`writeFile` follow symlinks, so a planted
47
+ * symlink at any existing path component (e.g. `.claude` -> /etc, or the final
48
+ * `SKILL.md` -> ~/.bashrc) could place or clobber files outside `--dir`. The
49
+ * lexical containment guard in `runInstall` is a string compare and cannot see
50
+ * this; only an `lstat`-per-component walk can. Fail-closed: any symlink is
51
+ * rejected (exit 5).
52
+ *
53
+ * Returns the target's `{ isFile }` when it already exists, or `null` when it
54
+ * (or any ancestor) does not yet exist — in which case the missing tail is
55
+ * created fresh and cannot be a pre-planted symlink. A small TOCTOU window
56
+ * remains between this check and the write; that is acceptable for a local,
57
+ * single-user CLI and avoids non-portable O_NOFOLLOW / rename gymnastics.
58
+ */
59
+ async function inspectTargetPath(agentFs, root, relPath) {
60
+ const segments = relPath.split(/[/\\]+/).filter(Boolean);
61
+ let current = root;
62
+ let finalIsFile = false;
63
+ for (const [i, seg] of segments.entries()) {
64
+ current = path.join(current, seg);
65
+ const ls = await agentFs.lstat(current);
66
+ if (ls === null) {
67
+ // This component and everything below it does not exist yet.
68
+ return null;
69
+ }
70
+ if (ls.isSymbolicLink) {
71
+ const shown = segments.slice(0, i + 1).join('/');
72
+ throw new CLIError(`refusing to write through a symlink: "${shown}" — installing here could place files outside --dir. Remove the symlink or choose a different --dir.`, 5);
73
+ }
74
+ if (i < segments.length - 1 && ls.isFile) {
75
+ const shown = segments.slice(0, i + 1).join('/');
76
+ throw new CLIError(`cannot create ${relPath}: "${shown}" exists and is not a directory.`, 5);
77
+ }
78
+ finalIsFile = ls.isFile;
79
+ }
80
+ return { isFile: finalIsFile };
81
+ }
82
+ /**
83
+ * Back up the current bytes at `abs` next to it without clobbering any existing
84
+ * backup or writing through a symlink. Exclusive create (`wx`) fails with
85
+ * EEXIST on an existing regular file OR symlink, so we walk `.bak`, `.bak.1`,
86
+ * `.bak.2`, … until a free slot is found. Returns the absolute path used.
87
+ */
88
+ async function writeBackup(agentFs, abs, existing) {
89
+ for (let n = 0; n < 100; n++) {
90
+ const candidate = n === 0 ? `${abs}.bak` : `${abs}.bak.${n}`;
91
+ try {
92
+ await agentFs.writeFile(candidate, existing, { exclusive: true });
93
+ return candidate;
94
+ }
95
+ catch (err) {
96
+ if (err instanceof Error && err.code === 'EEXIST') {
97
+ continue;
98
+ }
99
+ throw err;
100
+ }
101
+ }
102
+ throw new CLIError(`refusing to back up ${path.basename(abs)}: too many existing .bak files — clean them up and re-run.`, 6);
103
+ }
104
+ // ---------------------------------------------------------------------------
105
+ // Managed-section helpers (codex target)
106
+ // ---------------------------------------------------------------------------
107
+ /**
108
+ * Build the section block to inject (sentinels + body + trailing newline).
109
+ * Uses \n throughout; the caller handles CRLF normalisation.
110
+ */
111
+ function buildSection(body) {
112
+ return `${MANAGED_SECTION_BEGIN}\n${body.trimEnd()}\n${MANAGED_SECTION_END}\n`;
113
+ }
114
+ /**
115
+ * Inspect an existing AGENTS.md and classify the managed-section state.
116
+ *
117
+ * Sentinel-matching rules (P2 hardening):
118
+ * - Only STANDALONE sentinel lines count (a line that consists solely of the
119
+ * marker, optionally followed by whitespace/CR before the LF). This prevents
120
+ * inline mentions in prose (e.g. documentation quoting the markers) from
121
+ * being mis-classified as a managed block.
122
+ * - Multiple standalone BEGIN or END lines → ambiguous → corrupt (exit 5).
123
+ * - CRLF files are handled by stripping trailing \r from each line before
124
+ * comparison.
125
+ */
126
+ function classifySection(existing, section) {
127
+ // Split on LF; strip trailing CR so CRLF files normalise correctly.
128
+ const lines = existing.split('\n');
129
+ // Collect line INDICES (0-based) where the sentinel appears as the whole line
130
+ // (trimEnd removes trailing CR and spaces).
131
+ const beginLines = [];
132
+ const endLines = [];
133
+ for (let i = 0; i < lines.length; i++) {
134
+ const stripped = (lines[i] ?? '').trimEnd();
135
+ if (stripped === MANAGED_SECTION_BEGIN)
136
+ beginLines.push(i);
137
+ else if (stripped === MANAGED_SECTION_END)
138
+ endLines.push(i);
139
+ }
140
+ const hasBegin = beginLines.length > 0;
141
+ const hasEnd = endLines.length > 0;
142
+ if (!hasBegin && !hasEnd) {
143
+ // No standalone sentinels — append path.
144
+ return { kind: 'append', existing };
145
+ }
146
+ // Duplicate standalone sentinels are ambiguous — treat as corrupt.
147
+ if (beginLines.length > 1) {
148
+ return { kind: 'corrupt' };
149
+ }
150
+ if (endLines.length > 1) {
151
+ return { kind: 'corrupt' };
152
+ }
153
+ if (hasBegin && !hasEnd) {
154
+ // BEGIN present but no standalone END — corrupt.
155
+ return { kind: 'corrupt' };
156
+ }
157
+ if (!hasBegin && hasEnd) {
158
+ // END present but no standalone BEGIN — corrupt.
159
+ return { kind: 'corrupt' };
160
+ }
161
+ const beginLineIdx = beginLines[0];
162
+ const endLineIdx = endLines[0];
163
+ if (endLineIdx < beginLineIdx) {
164
+ // END appears before BEGIN — corrupt.
165
+ return { kind: 'corrupt' };
166
+ }
167
+ // Both sentinels present, in the right order, with no duplicates.
168
+ // Reconstruct byte offsets from line positions so we can slice the original
169
+ // string (preserving its exact byte content for the before/after split).
170
+ //
171
+ // lineStart[i] = byte offset of the first character of line i.
172
+ let byteOffset = 0;
173
+ const lineStart = [];
174
+ for (const line of lines) {
175
+ lineStart.push(byteOffset);
176
+ byteOffset += line.length + 1; // +1 for the '\n' that split() removed
177
+ }
178
+ const beginByteIdx = lineStart[beginLineIdx];
179
+ // The END sentinel line ends at: lineStart[endLineIdx] + raw line length.
180
+ // We want to include the trailing '\n' after END when present.
181
+ const endLineRawLength = (lines[endLineIdx] ?? '').length;
182
+ const endOfEndByte = lineStart[endLineIdx] + endLineRawLength;
183
+ // Include one trailing newline after END if present.
184
+ const charAfterEnd = existing[endOfEndByte];
185
+ const trailingNewline = charAfterEnd === '\n' ? 1 : charAfterEnd === '\r' ? 2 : 0;
186
+ const before = existing.slice(0, beginByteIdx);
187
+ const after = existing.slice(endOfEndByte + trailingNewline);
188
+ const currentSection = existing.slice(beginByteIdx, endOfEndByte + trailingNewline);
189
+ if (currentSection === section) {
190
+ return { kind: 'unchanged' };
191
+ }
192
+ return { kind: 'replace', existing, before, after };
193
+ }
194
+ /**
195
+ * Compose the new AGENTS.md content for the 'append' and 'replace' paths.
196
+ *
197
+ * 'append': ensure a single blank line separator between existing content
198
+ * and the section (but don't add two blank lines if the file already ends
199
+ * with one).
200
+ * 'replace': splice the new section between `before` and `after`.
201
+ */
202
+ function composeManagedFile(state, section) {
203
+ if (state.kind === 'append') {
204
+ const existing = state.existing;
205
+ const sep = existing.length === 0 || existing.endsWith('\n\n') ? '' : '\n';
206
+ return `${existing}${sep}${section}`;
207
+ }
208
+ // replace
209
+ return `${state.before}${section}${state.after}`;
210
+ }
211
+ // ---------------------------------------------------------------------------
212
+ // runInstall
213
+ // ---------------------------------------------------------------------------
214
+ export async function runInstall(opts, deps = {}) {
215
+ const agentFs = deps.fs ?? defaultAgentFs;
216
+ const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
217
+ const out = makeOutput(opts.output, deps);
218
+ // 1. Parse targets
219
+ const rawTargets = opts.target
220
+ .flatMap(s => s.split(','))
221
+ .map(s => s.trim())
222
+ .filter(Boolean);
223
+ let resolvedTargetStrings;
224
+ if (rawTargets.length === 0) {
225
+ const isTTY = deps.isTTY ?? Boolean(process.stdin.isTTY);
226
+ if (!isTTY) {
227
+ throw localValidationError('target', `required; pass --target=claude (comma-separated or repeated for several). Supported: ${Object.keys(TARGETS).join(', ')}`);
228
+ }
229
+ const promptFn = deps.prompt ?? ((q) => promptText(q));
230
+ const answer = (await promptFn('Targets to install (comma-separated) [claude]: ')).trim();
231
+ const defaulted = answer || 'claude';
232
+ resolvedTargetStrings = defaulted
233
+ .split(',')
234
+ .map(s => s.trim())
235
+ .filter(Boolean);
236
+ }
237
+ else {
238
+ resolvedTargetStrings = rawTargets;
239
+ }
240
+ // 2. Validate targets
241
+ const validTargets = Object.keys(TARGETS);
242
+ for (const t of resolvedTargetStrings) {
243
+ if (!validTargets.includes(t)) {
244
+ throw localValidationError('target', `unknown target "${t}"; supported: ${validTargets.join(', ')}`);
245
+ }
246
+ }
247
+ // De-duplicate while preserving first-seen order
248
+ const seen = new Set();
249
+ const targets = resolvedTargetStrings.filter(t => {
250
+ if (seen.has(t))
251
+ return false;
252
+ seen.add(t);
253
+ return true;
254
+ });
255
+ // 3. Resolve dir
256
+ const dir = opts.dir ?? deps.cwd ?? process.cwd();
257
+ const root = path.resolve(dir);
258
+ // 4. Load skill bodies (lazy — only touch disk if a target actually needs it)
259
+ let ownFileBody;
260
+ let codexBody;
261
+ const results = [];
262
+ // Track bytes for dry-run output
263
+ const dryRunLines = [];
264
+ // 5. Process each target
265
+ for (const t of targets) {
266
+ const spec = TARGETS[t];
267
+ const relPath = spec.path;
268
+ const abs = path.resolve(root, relPath);
269
+ // Path safety: ensure abs is inside root (defense against .. in relPath or dir)
270
+ if (abs !== root && !abs.startsWith(root + path.sep)) {
271
+ throw new CLIError(`refusing to write outside --dir: ${relPath}`, 5);
272
+ }
273
+ // -----------------------------------------------------------------------
274
+ // managed-section mode (codex target)
275
+ // -----------------------------------------------------------------------
276
+ if (spec.mode === 'managed-section') {
277
+ if (codexBody === undefined)
278
+ codexBody = loadCodexSkillBody();
279
+ const section = buildSection(codexBody);
280
+ if (opts.dryRun) {
281
+ // Dry-run: report what would happen without writing disk.
282
+ //
283
+ // [P2] Apply the SAME symlink fail-close guard as the real install path.
284
+ // Without this, a symlinked AGENTS.md gets followed in dry-run even
285
+ // though the real install would refuse (exit 5). Run inspectTargetPath
286
+ // first; only lstat-check the final file (not write) after that.
287
+ const dryRunSt = await inspectTargetPath(agentFs, root, relPath);
288
+ if (dryRunSt !== null && !dryRunSt.isFile) {
289
+ throw new CLIError(`${relPath} exists but is not a regular file — remove it and re-run.`, 5);
290
+ }
291
+ // We DO read the existing file (if present) to compute the
292
+ // would-be byte count and emit the 32 KiB budget warning — without
293
+ // this the warning was silently absent on --dry-run runs (Fix 4).
294
+ //
295
+ // [P3 round-2] Measure the ACTUAL composed result via the same
296
+ // classifySection + composeManagedFile pipeline the real install
297
+ // uses — `existing + section` double-counts the old block on the
298
+ // replace path and misses the append separator. Read failures other
299
+ // than ENOENT are surfaced (EACCES/EIO must not read as "absent" —
300
+ // absence is already represented by dryRunSt === null).
301
+ const bytes = Buffer.byteLength(section, 'utf8');
302
+ let wouldBeContent = section;
303
+ if (dryRunSt !== null) {
304
+ let existing = null;
305
+ try {
306
+ existing = await agentFs.readFile(abs);
307
+ }
308
+ catch (err) {
309
+ if (err instanceof Error && err.code === 'ENOENT') {
310
+ existing = null; // raced away between lstat and read → would-be = create
311
+ }
312
+ else {
313
+ throw new CLIError(`cannot read ${relPath} for dry-run: ${err instanceof Error ? err.message : String(err)}`, 5);
314
+ }
315
+ }
316
+ if (existing !== null) {
317
+ const state = classifySection(existing, section);
318
+ if (state.kind === 'corrupt') {
319
+ // The real install would refuse with exit 5 — dry-run reports
320
+ // the same outcome rather than a misleading success.
321
+ throw new CLIError(`${relPath} contains a malformed TestSprite sentinel (BEGIN without END or vice-versa). ` +
322
+ `Manually remove the partial sentinel block and re-run.`, 5);
323
+ }
324
+ wouldBeContent =
325
+ state.kind === 'unchanged'
326
+ ? existing
327
+ : state.kind === 'create'
328
+ ? section
329
+ : composeManagedFile(state, section);
330
+ }
331
+ }
332
+ const wouldBeBytes = Buffer.byteLength(wouldBeContent, 'utf8');
333
+ if (wouldBeBytes > AGENTS_MD_CODEX_BUDGET_BYTES) {
334
+ stderrFn(`[warn] ${relPath} will be ${wouldBeBytes} bytes after this write — Codex may not load content beyond its 32 KiB (${AGENTS_MD_CODEX_BUDGET_BYTES} byte) budget. Trim AGENTS.md to stay within the limit.`);
335
+ }
336
+ dryRunLines.push({ abs, bytes, note: 'managed section' });
337
+ results.push({ target: t, path: relPath, action: 'dry-run' });
338
+ continue;
339
+ }
340
+ // Inspect the target path via lstat walk (symlink-safe, same as own-file).
341
+ const st = await inspectTargetPath(agentFs, root, relPath);
342
+ if (st !== null && !st.isFile) {
343
+ throw new CLIError(`${relPath} exists but is not a regular file — remove it and re-run.`, 5);
344
+ }
345
+ /**
346
+ * [P2] Emit a stderr warn when the would-be file content exceeds Codex's
347
+ * 32 KiB load budget. We still write — this is a warn, not a refusal —
348
+ * but the operator needs early visibility so they can trim AGENTS.md.
349
+ */
350
+ function warnIfOverBudget(wouldBeContent) {
351
+ const byteLen = Buffer.byteLength(wouldBeContent, 'utf8');
352
+ if (byteLen > AGENTS_MD_CODEX_BUDGET_BYTES) {
353
+ stderrFn(`[warn] ${relPath} will be ${byteLen} bytes after this write — Codex may not load content beyond its 32 KiB (${AGENTS_MD_CODEX_BUDGET_BYTES} byte) budget. Trim AGENTS.md to stay within the limit.`);
354
+ }
355
+ }
356
+ if (st === null) {
357
+ // File absent → create AGENTS.md containing just the section.
358
+ warnIfOverBudget(section);
359
+ await agentFs.mkdir(path.dirname(abs));
360
+ try {
361
+ await agentFs.writeFile(abs, section, { exclusive: true });
362
+ }
363
+ catch (err) {
364
+ if (err instanceof Error && err.code === 'EEXIST') {
365
+ throw new CLIError(`${relPath} appeared after the path check — re-run, or pass --force to overwrite.`, 6);
366
+ }
367
+ throw err;
368
+ }
369
+ results.push({ target: t, path: relPath, action: 'section-installed' });
370
+ }
371
+ else {
372
+ const existing = await agentFs.readFile(abs);
373
+ const state = classifySection(existing, section);
374
+ if (state.kind === 'corrupt') {
375
+ // BEGIN without matching END (or vice-versa) — never destroy user content.
376
+ throw new CLIError(`${relPath} contains a malformed TestSprite sentinel (BEGIN without END or vice-versa). ` +
377
+ `Manually remove the partial sentinel block and re-run.`, 5);
378
+ }
379
+ if (state.kind === 'unchanged') {
380
+ results.push({ target: t, path: relPath, action: 'section-unchanged' });
381
+ }
382
+ else if (state.kind === 'create') {
383
+ // Shouldn't happen (st !== null means file exists), but guard anyway.
384
+ warnIfOverBudget(section);
385
+ await agentFs.writeFile(abs, section);
386
+ results.push({ target: t, path: relPath, action: 'section-installed' });
387
+ }
388
+ else {
389
+ // 'append' or 'replace' — write the new content.
390
+ // --force has no special meaning for managed-section: we always merge
391
+ // rather than replacing the whole file, so force is effectively always
392
+ // on for the section (user content is never at risk).
393
+ const newContent = composeManagedFile(state, section);
394
+ warnIfOverBudget(newContent);
395
+ await agentFs.writeFile(abs, newContent);
396
+ const action = state.kind === 'append' ? 'section-installed' : 'section-updated';
397
+ results.push({ target: t, path: relPath, action });
398
+ }
399
+ }
400
+ continue;
401
+ }
402
+ // -----------------------------------------------------------------------
403
+ // own-file mode (all other targets)
404
+ // -----------------------------------------------------------------------
405
+ if (ownFileBody === undefined)
406
+ ownFileBody = loadSkillBody();
407
+ const content = renderForTarget(t, ownFileBody).content;
408
+ if (opts.dryRun) {
409
+ const bytes = Buffer.byteLength(content, 'utf8');
410
+ dryRunLines.push({ abs, bytes, note: '' });
411
+ results.push({ target: t, path: relPath, action: 'dry-run' });
412
+ continue;
413
+ }
414
+ // Inspect the target path: refuse to traverse or write through a symlink
415
+ // (fs writes follow symlinks, which would let a planted symlink escape
416
+ // --dir), and reject a non-regular-file landing path. The lexical guard
417
+ // above is necessary but not sufficient — it cannot see symlinks.
418
+ const st = await inspectTargetPath(agentFs, root, relPath);
419
+ if (st !== null && !st.isFile) {
420
+ throw new CLIError(`${relPath} exists but is not a regular file — remove it and re-run.`, 5);
421
+ }
422
+ if (st === null) {
423
+ // Path does not exist — create it. inspectTargetPath verified every
424
+ // existing ancestor is a real directory; exclusive create (wx) then
425
+ // ensures a file or symlink that races in after the check is not followed
426
+ // or silently overwritten.
427
+ await agentFs.mkdir(path.dirname(abs));
428
+ try {
429
+ await agentFs.writeFile(abs, content, { exclusive: true });
430
+ }
431
+ catch (err) {
432
+ if (err instanceof Error && err.code === 'EEXIST') {
433
+ throw new CLIError(`${relPath} appeared after the path check — re-run, or pass --force to overwrite.`, 6);
434
+ }
435
+ throw err;
436
+ }
437
+ results.push({ target: t, path: relPath, action: 'written' });
438
+ }
439
+ else {
440
+ const existing = await agentFs.readFile(abs);
441
+ if (existing === content) {
442
+ // Byte-identical — skip
443
+ results.push({ target: t, path: relPath, action: 'skipped' });
444
+ }
445
+ else if (!opts.force) {
446
+ // Differs and no --force → blocked
447
+ results.push({ target: t, path: relPath, action: 'blocked' });
448
+ }
449
+ else {
450
+ // Differs and --force → back up the current bytes to a fresh slot
451
+ // (never clobbering an existing backup or following a symlink), then
452
+ // overwrite. The overwrite itself can follow a symlink swapped in after
453
+ // the check — an accepted TOCTOU residual for a local, single-user CLI.
454
+ const backupPath = await writeBackup(agentFs, abs, existing);
455
+ await agentFs.writeFile(abs, content);
456
+ if (opts.output === 'text') {
457
+ stderrFn(`backed up ${relPath} to ${path.relative(root, backupPath)}`);
458
+ }
459
+ results.push({ target: t, path: relPath, action: 'updated' });
460
+ }
461
+ }
462
+ }
463
+ // 6. Dry-run output
464
+ if (opts.dryRun) {
465
+ stderrFn('[dry-run] no files written — preview only');
466
+ for (const { abs, bytes, note } of dryRunLines) {
467
+ const suffix = note ? ` (${note}, ${bytes} bytes)` : ` (${bytes} bytes)`;
468
+ stderrFn(`[dry-run] would write ${abs}${suffix}`);
469
+ }
470
+ }
471
+ // 7. Blocked hints
472
+ for (const r of results) {
473
+ if (r.action === 'blocked') {
474
+ stderrFn(`${r.path} exists and differs from the canonical skill — re-run with --force to overwrite (the existing file is backed up to .bak).`);
475
+ }
476
+ }
477
+ // 8. Print results
478
+ out.print(results, data => {
479
+ const items = data;
480
+ return items.map(r => `${r.target.padEnd(12)} ${r.action.padEnd(12)} ${r.path}`).join('\n');
481
+ });
482
+ // 9. Exit with 6 if any blocked
483
+ if (results.some(r => r.action === 'blocked')) {
484
+ throw new CLIError('one or more targets already exist and differ; re-run with --force to overwrite (a .bak is kept).', 6);
485
+ }
486
+ }
487
+ export async function runList(opts, deps = {}) {
488
+ const out = makeOutput(opts.output, deps);
489
+ const results = Object.entries(TARGETS).map(([t, spec]) => ({
490
+ target: t,
491
+ status: spec.status,
492
+ mode: spec.mode,
493
+ path: spec.path,
494
+ }));
495
+ out.print(results, data => {
496
+ const items = data;
497
+ const header = `${'TARGET'.padEnd(14)} ${'STATUS'.padEnd(12)} ${'MODE'.padEnd(18)} PATH`;
498
+ const rows = items.map(r => `${r.target.padEnd(14)} ${r.status.padEnd(12)} ${r.mode.padEnd(18)} ${r.path}`);
499
+ return [header, ...rows].join('\n');
500
+ });
501
+ }
502
+ // ---------------------------------------------------------------------------
503
+ // Command factory
504
+ // ---------------------------------------------------------------------------
505
+ function collect(v, prev) {
506
+ return prev.concat(v);
507
+ }
508
+ export function createAgentCommand(deps = {}) {
509
+ const agent = new Command('agent').description('Install TestSprite guidance into coding-agent config (Claude Code, Cursor, Cline, Antigravity, Codex)');
510
+ agent
511
+ .command('install')
512
+ .description('Write the TestSprite verification-loop skill file into a project for a coding agent')
513
+ .option('--target <t>', 'Agent target(s): claude, cursor, cline, antigravity, codex (comma-separated or repeated)', collect, [])
514
+ .option('--dir <path>', 'Project root to write into (default: cwd)')
515
+ .option('--force', 'For own-file targets: overwrite existing file (a .bak backup is kept). ' +
516
+ 'For codex (managed-section): replaces the section unconditionally; user content outside the section is never destroyed.')
517
+ .addHelpText('after', GLOBAL_OPTS_HINT)
518
+ .action(async (cmdOpts, command) => {
519
+ await runInstall({
520
+ ...resolveCommonOptions(command),
521
+ target: cmdOpts.target,
522
+ dir: cmdOpts.dir,
523
+ force: Boolean(cmdOpts.force),
524
+ }, deps);
525
+ });
526
+ agent
527
+ .command('list')
528
+ .description('List supported agent targets, their status, and landing paths')
529
+ .addHelpText('after', GLOBAL_OPTS_HINT)
530
+ .action(async (_o, command) => {
531
+ await runList(resolveCommonOptions(command), deps);
532
+ });
533
+ return agent;
534
+ }
535
+ // ---------------------------------------------------------------------------
536
+ // Per-file helpers (per convention: copy from auth.ts)
537
+ // ---------------------------------------------------------------------------
538
+ function resolveCommonOptions(command) {
539
+ const globals = command.optsWithGlobals();
540
+ return {
541
+ profile: globals.profile ?? 'default',
542
+ output: globals.output ?? 'text',
543
+ endpointUrl: globals.endpointUrl,
544
+ debug: globals.debug ?? false,
545
+ verbose: globals.verbose ?? false,
546
+ dryRun: globals.dryRun ?? false,
547
+ };
548
+ }
549
+ function makeOutput(mode, deps) {
550
+ return new Output(mode, { stdout: deps.stdout, stderr: deps.stderr });
551
+ }
552
+ //# sourceMappingURL=agent.js.map
@@ -0,0 +1,38 @@
1
+ import { Command } from 'commander';
2
+ import { type CommonOptions as FactoryCommonOptions } from '../lib/client-factory.js';
3
+ import type { FetchImpl } from '../lib/http.js';
4
+ export interface MeResponse {
5
+ userId: string;
6
+ keyId: string;
7
+ scopes: string[];
8
+ env: 'development' | 'staging' | 'production';
9
+ /**
10
+ * Human-readable email for the bound account. Forward-compat: the
11
+ * backend `/me` projection does not surface it yet, so it is optional
12
+ * and absent-safe — rendered only when present (dogfood L1866). Keep
13
+ * `userId` as the machine-stable join key regardless.
14
+ */
15
+ email?: string;
16
+ /** Human-readable display name for the bound account. Absent-safe (dogfood L1866). */
17
+ displayName?: string;
18
+ }
19
+ export interface AuthDeps {
20
+ env?: NodeJS.ProcessEnv;
21
+ credentialsPath?: string;
22
+ fetchImpl?: FetchImpl;
23
+ prompt?: {
24
+ secret: (question: string) => Promise<string>;
25
+ };
26
+ stdout?: (line: string) => void;
27
+ stderr?: (line: string) => void;
28
+ preludeWrite?: (chunk: string) => void;
29
+ }
30
+ type CommonOptions = FactoryCommonOptions;
31
+ interface ConfigureOptions extends CommonOptions {
32
+ fromEnv: boolean;
33
+ }
34
+ export declare function runConfigure(opts: ConfigureOptions, deps?: AuthDeps): Promise<void>;
35
+ export declare function runWhoami(opts: CommonOptions, deps?: AuthDeps): Promise<MeResponse>;
36
+ export declare function runLogout(opts: CommonOptions, deps?: AuthDeps): Promise<void>;
37
+ export declare function createAuthCommand(deps?: AuthDeps): Command;
38
+ export {};