loadam 0.2.0 → 0.2.1

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.
package/dist/bin.js CHANGED
@@ -271,6 +271,257 @@ function readStdin() {
271
271
  });
272
272
  }
273
273
 
274
+ // src/commands/clean.ts
275
+ import { resolve as resolve2 } from "path";
276
+
277
+ // src/session/session.ts
278
+ import { createHash } from "crypto";
279
+ import { mkdir, readFile as readFile2, readdir, rm, stat, writeFile } from "fs/promises";
280
+ import { join, resolve } from "path";
281
+ var SESSION_SCHEMA_VERSION = 1;
282
+ var SESSIONS_DIR = "sessions";
283
+ async function createSession(input) {
284
+ const startedAt = /* @__PURE__ */ new Date();
285
+ const slug = input.slug ? sanitizeSlug(input.slug) : input.command;
286
+ const id = `${formatTimestamp(startedAt)}-${slug}`;
287
+ const root = resolve(input.outRoot, SESSIONS_DIR);
288
+ const dir = resolve(root, id);
289
+ await mkdir(dir, { recursive: true });
290
+ await ensureGitignore(root);
291
+ const specHash = sha256(input.specSource);
292
+ const irDigest = sha256(input.irJson);
293
+ const meta = {
294
+ schemaVersion: SESSION_SCHEMA_VERSION,
295
+ id,
296
+ command: input.command,
297
+ flags: sanitizeFlags(input.flags ?? {}),
298
+ spec: {
299
+ path: input.specPath,
300
+ sha256: specHash,
301
+ title: input.ir.meta.title,
302
+ version: input.ir.meta.version
303
+ },
304
+ irDigest,
305
+ target: input.target ?? null,
306
+ envVars: input.envVars ?? [],
307
+ startedAt: startedAt.toISOString(),
308
+ artefacts: ["ir.json", "meta.json"]
309
+ };
310
+ await writeFile(join(dir, "ir.json"), input.irJson, "utf8");
311
+ await writeFile(join(dir, "meta.json"), JSON.stringify(meta, null, 2), "utf8");
312
+ return {
313
+ id,
314
+ dir,
315
+ meta,
316
+ async addArtefact(relPath, contents) {
317
+ const full = join(dir, relPath);
318
+ await mkdir(join(full, "..").replace(/\/+$/, ""), { recursive: true });
319
+ await writeFile(full, contents);
320
+ if (!meta.artefacts.includes(relPath)) meta.artefacts.push(relPath);
321
+ },
322
+ async finalize({ exitCode, thresholds, summary }) {
323
+ const endedAt = /* @__PURE__ */ new Date();
324
+ meta.endedAt = endedAt.toISOString();
325
+ meta.durationMs = endedAt.getTime() - startedAt.getTime();
326
+ meta.exitCode = exitCode;
327
+ if (thresholds) meta.thresholds = thresholds;
328
+ if (summary) meta.summary = summary;
329
+ await writeFile(join(dir, "meta.json"), JSON.stringify(meta, null, 2), "utf8");
330
+ return meta;
331
+ }
332
+ };
333
+ }
334
+ async function listSessions(outRoot) {
335
+ const root = resolve(outRoot, SESSIONS_DIR);
336
+ let entries;
337
+ try {
338
+ entries = await readdir(root);
339
+ } catch {
340
+ return [];
341
+ }
342
+ const metas = [];
343
+ for (const entry of entries) {
344
+ const meta = await loadMeta(join(root, entry));
345
+ if (meta) metas.push(meta);
346
+ }
347
+ return metas.sort((a, b) => a.startedAt < b.startedAt ? 1 : -1);
348
+ }
349
+ async function resolveSessionId(outRoot, idOrPrefix) {
350
+ const all = await listSessions(outRoot);
351
+ if (all.length === 0) {
352
+ throw new Error("No sessions found. Run `loadam test`/`contract`/`diff` first.");
353
+ }
354
+ if (idOrPrefix === "latest") return all[0];
355
+ const exact = all.find((m) => m.id === idOrPrefix);
356
+ if (exact) return exact;
357
+ const prefix = all.filter((m) => m.id.startsWith(idOrPrefix));
358
+ if (prefix.length === 0) throw new Error(`No session matched "${idOrPrefix}".`);
359
+ if (prefix.length > 1) {
360
+ const ids = prefix.map((m) => m.id).join("\n ");
361
+ throw new Error(`Ambiguous session prefix "${idOrPrefix}", matches:
362
+ ${ids}`);
363
+ }
364
+ return prefix[0];
365
+ }
366
+ async function cleanSessions(outRoot, opts) {
367
+ const all = await listSessions(outRoot);
368
+ const root = resolve(outRoot, SESSIONS_DIR);
369
+ const now = Date.now();
370
+ const hasAge = typeof opts.olderThanMs === "number";
371
+ const hasKeep = typeof opts.keep === "number";
372
+ const ageCut = opts.olderThanMs ?? Number.POSITIVE_INFINITY;
373
+ const keep = opts.keep ?? 0;
374
+ if (!hasAge && !hasKeep) {
375
+ return { deleted: [], kept: all.map((m) => m.id) };
376
+ }
377
+ const deleted = [];
378
+ const kept = [];
379
+ all.forEach((m, index) => {
380
+ if (hasKeep && index < keep) {
381
+ kept.push(m.id);
382
+ return;
383
+ }
384
+ const age = now - new Date(m.startedAt).getTime();
385
+ const expired = hasAge && age >= ageCut;
386
+ const excess = hasKeep && index >= keep;
387
+ if (expired || excess) deleted.push(m.id);
388
+ else kept.push(m.id);
389
+ });
390
+ if (opts.apply) {
391
+ for (const id of deleted) {
392
+ await rm(join(root, id), { recursive: true, force: true });
393
+ }
394
+ }
395
+ return { deleted, kept };
396
+ }
397
+ async function loadMeta(dir) {
398
+ try {
399
+ const stats = await stat(dir);
400
+ if (!stats.isDirectory()) return null;
401
+ const text = await readFile2(join(dir, "meta.json"), "utf8");
402
+ const parsed = JSON.parse(text);
403
+ if (parsed?.schemaVersion === SESSION_SCHEMA_VERSION && typeof parsed.id === "string") {
404
+ return parsed;
405
+ }
406
+ } catch {
407
+ }
408
+ return null;
409
+ }
410
+ function sha256(text) {
411
+ return createHash("sha256").update(text).digest("hex");
412
+ }
413
+ function formatTimestamp(d) {
414
+ return d.toISOString().replace(/[:.]/g, "-").slice(0, 19);
415
+ }
416
+ async function ensureGitignore(root) {
417
+ const path = join(root, ".gitignore");
418
+ try {
419
+ await readFile2(path, "utf8");
420
+ } catch {
421
+ await writeFile(
422
+ path,
423
+ "# Auto-generated by loadam \u2014 sessions can contain secrets, do not commit.\n*\n!.gitignore\n",
424
+ "utf8"
425
+ );
426
+ }
427
+ }
428
+ function sanitizeSlug(s) {
429
+ return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40);
430
+ }
431
+ var SECRET_LIKE = /(token|secret|password|pass|key|credential|auth)/i;
432
+ function sanitizeFlags(flags) {
433
+ const out = {};
434
+ for (const [k, v] of Object.entries(flags)) {
435
+ if (SECRET_LIKE.test(k)) {
436
+ out[k] = "[redacted]";
437
+ continue;
438
+ }
439
+ if (v === null || typeof v === "boolean" || typeof v === "number") {
440
+ out[k] = v;
441
+ } else if (typeof v === "string") {
442
+ out[k] = v;
443
+ }
444
+ }
445
+ return out;
446
+ }
447
+
448
+ // src/util/output.ts
449
+ import { consola as consola3 } from "consola";
450
+ function makeOutput(jsonMode) {
451
+ if (jsonMode) {
452
+ return {
453
+ json: true,
454
+ start: () => void 0,
455
+ info: () => void 0,
456
+ success: () => void 0,
457
+ step: () => void 0,
458
+ result(payload) {
459
+ process.stdout.write(`${JSON.stringify(payload, null, 2)}
460
+ `);
461
+ }
462
+ };
463
+ }
464
+ return {
465
+ json: false,
466
+ start: (m) => consola3.start(m),
467
+ info: (m) => consola3.info(m),
468
+ success: (m) => consola3.success(m),
469
+ step: (m) => consola3.log(m),
470
+ result: () => void 0
471
+ };
472
+ }
473
+
474
+ // src/commands/clean.ts
475
+ var DURATION_RE = /^(\d+)([smhd])$/;
476
+ function parseDuration(raw) {
477
+ const m = DURATION_RE.exec(raw.trim());
478
+ if (!m) {
479
+ throw new Error(`Invalid --older-than "${raw}". Use 30d, 12h, 45m, 90s.`);
480
+ }
481
+ const n = Number.parseInt(m[1], 10);
482
+ const unit = m[2];
483
+ const factor = unit === "s" ? 1e3 : unit === "m" ? 6e4 : unit === "h" ? 36e5 : 864e5;
484
+ return n * factor;
485
+ }
486
+ function registerCleanCommand(program) {
487
+ program.command("clean").description("Delete archived sessions older than a threshold or beyond a keep count.").option("--root <dir>", "session archive root", "./loadam-out").option("--keep <n>", "always keep at most N most-recent sessions").option("--older-than <duration>", "delete sessions older than this (e.g. 30d, 12h)", "30d").option("-y, --yes", "actually delete (default: dry-run)", false).option("--json", "emit a JSON summary on stdout", false).action(withFriendlyErrors(runClean));
488
+ }
489
+ async function runClean(opts) {
490
+ const out = makeOutput(!!opts.json);
491
+ const root = resolve2(opts.root);
492
+ const olderThanMs = opts.olderThan ? parseDuration(opts.olderThan) : void 0;
493
+ const keep = opts.keep ? Number.parseInt(opts.keep, 10) : void 0;
494
+ const result = await cleanSessions(root, {
495
+ olderThanMs,
496
+ keep: Number.isFinite(keep) ? keep : void 0,
497
+ apply: !!opts.yes
498
+ });
499
+ if (out.json) {
500
+ out.result({
501
+ command: "clean",
502
+ root,
503
+ apply: !!opts.yes,
504
+ kept: result.kept.length,
505
+ deleted: result.deleted.length,
506
+ deletedIds: result.deleted
507
+ });
508
+ return;
509
+ }
510
+ if (result.deleted.length === 0) {
511
+ out.info(`Nothing to clean. ${result.kept.length} session(s) kept.`);
512
+ return;
513
+ }
514
+ if (opts.yes) {
515
+ out.success(`Deleted ${result.deleted.length} session(s); ${result.kept.length} kept.`);
516
+ } else {
517
+ out.info(
518
+ `Dry-run: would delete ${result.deleted.length} session(s); ${result.kept.length} kept.`
519
+ );
520
+ out.info("Pass --yes to actually delete.");
521
+ }
522
+ for (const id of result.deleted) out.info(` - ${id}`);
523
+ }
524
+
274
525
  // src/commands/completion.ts
275
526
  var BASH = `# loadam bash completion. Install:
276
527
  # loadam completion bash > ~/.loadam-completion.bash
@@ -343,13 +594,13 @@ function registerCompletionCommand(program) {
343
594
  }
344
595
 
345
596
  // src/commands/contract.ts
346
- import { mkdir, readFile as readFile3, writeFile } from "fs/promises";
347
- import { dirname, resolve as resolve2 } from "path";
597
+ import { mkdir as mkdir2, readFile as readFile4, writeFile as writeFile2 } from "fs/promises";
598
+ import { dirname, resolve as resolve4 } from "path";
348
599
 
349
600
  // ../core/dist/index.js
350
601
  import { z } from "zod";
351
- import { readFile as readFile2 } from "fs/promises";
352
- import { resolve } from "path";
602
+ import { readFile as readFile3 } from "fs/promises";
603
+ import { resolve as resolve3 } from "path";
353
604
  import SwaggerParser from "@apidevtools/swagger-parser";
354
605
  import { parse as parseYaml } from "yaml";
355
606
  var IR_VERSION = "1";
@@ -607,8 +858,8 @@ var HTTP_METHODS = [
607
858
  "OPTIONS"
608
859
  ];
609
860
  async function fromOpenApiFile(path, opts = {}) {
610
- const absolute = resolve(path);
611
- const raw = await readFile2(absolute, "utf8");
861
+ const absolute = resolve3(path);
862
+ const raw = await readFile3(absolute, "utf8");
612
863
  const doc = parseDocument(raw);
613
864
  const bundled = await SwaggerParser.bundle(doc);
614
865
  return fromOpenApi(bundled, { sourceUri: opts.sourceUri ?? absolute });
@@ -1355,32 +1606,6 @@ function slugify(s) {
1355
1606
  return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
1356
1607
  }
1357
1608
 
1358
- // src/util/output.ts
1359
- import { consola as consola3 } from "consola";
1360
- function makeOutput(jsonMode) {
1361
- if (jsonMode) {
1362
- return {
1363
- json: true,
1364
- start: () => void 0,
1365
- info: () => void 0,
1366
- success: () => void 0,
1367
- step: () => void 0,
1368
- result(payload) {
1369
- process.stdout.write(`${JSON.stringify(payload, null, 2)}
1370
- `);
1371
- }
1372
- };
1373
- }
1374
- return {
1375
- json: false,
1376
- start: (m) => consola3.start(m),
1377
- info: (m) => consola3.info(m),
1378
- success: (m) => consola3.success(m),
1379
- step: (m) => consola3.log(m),
1380
- result: () => void 0
1381
- };
1382
- }
1383
-
1384
1609
  // src/commands/contract.ts
1385
1610
  function registerContractCommand(program) {
1386
1611
  program.command("contract").description("Compile an OpenAPI spec into a Schemathesis property-based contract suite.").argument("<spec>", "path to OpenAPI 3.x spec (YAML or JSON)").option(
@@ -1391,28 +1616,52 @@ function registerContractCommand(program) {
1391
1616
  }
1392
1617
  async function runContract(spec, opts) {
1393
1618
  const out = makeOutput(!!opts.json);
1394
- const specPath = resolve2(spec);
1619
+ const specPath = resolve4(spec);
1395
1620
  out.start(`Parsing OpenAPI spec: ${specPath}`);
1396
1621
  const ir = await fromOpenApiFile(specPath);
1397
1622
  inferResourceGraph(ir);
1398
1623
  parseIR(ir);
1399
- const specSource = await readFile3(specPath, "utf8");
1624
+ const specSource = await readFile4(specPath, "utf8");
1400
1625
  const examples = Number.parseInt(opts.examples ?? "25", 10);
1401
1626
  const result = compileContract(ir, specSource, {
1402
1627
  baseUrl: opts.target,
1403
1628
  examples: Number.isFinite(examples) ? examples : 25
1404
1629
  });
1405
- const outDir = resolve2(opts.output);
1406
- await mkdir(outDir, { recursive: true });
1630
+ const outDir = resolve4(opts.output);
1631
+ await mkdir2(outDir, { recursive: true });
1407
1632
  for (const [rel, contents] of Object.entries(result.files)) {
1408
- const full = resolve2(outDir, rel);
1409
- await mkdir(dirname(full), { recursive: true });
1410
- await writeFile(full, contents, "utf8");
1633
+ const full = resolve4(outDir, rel);
1634
+ await mkdir2(dirname(full), { recursive: true });
1635
+ await writeFile2(full, contents, "utf8");
1411
1636
  }
1412
1637
  const fileCount = Object.keys(result.files).length;
1413
1638
  out.success(`Wrote ${fileCount} files to ${outDir}`);
1414
1639
  out.info(` ${ir.operations.length} operations to fuzz`);
1640
+ const session = await createSession({
1641
+ command: "contract",
1642
+ outRoot: resolve4(outDir, ".."),
1643
+ specPath,
1644
+ specSource,
1645
+ ir,
1646
+ irJson: JSON.stringify(ir, null, 2),
1647
+ target: opts.target ?? null,
1648
+ envVars: result.envVars ?? [],
1649
+ flags: {
1650
+ target: opts.target ?? null,
1651
+ examples
1652
+ },
1653
+ slug: `contract-${ir.meta.title ?? "run"}`
1654
+ });
1655
+ await session.finalize({
1656
+ exitCode: 0,
1657
+ thresholds: { passed: [], failed: [] },
1658
+ summary: {
1659
+ files: fileCount,
1660
+ operations: ir.operations.length
1661
+ }
1662
+ });
1415
1663
  if (!out.json) {
1664
+ out.info(` Session: ${session.id}`);
1416
1665
  out.step("");
1417
1666
  out.step("Next steps:");
1418
1667
  out.step(` cd ${opts.output}`);
@@ -1425,13 +1674,14 @@ async function runContract(spec, opts) {
1425
1674
  outputDir: outDir,
1426
1675
  files: fileCount,
1427
1676
  operations: ir.operations.length,
1428
- envVars: result.envVars
1677
+ envVars: result.envVars,
1678
+ sessionId: session.id
1429
1679
  });
1430
1680
  }
1431
1681
 
1432
1682
  // src/commands/diff.ts
1433
- import { writeFile as writeFile2 } from "fs/promises";
1434
- import { resolve as resolve3 } from "path";
1683
+ import { readFile as readFile5, writeFile as writeFile3 } from "fs/promises";
1684
+ import { resolve as resolve5 } from "path";
1435
1685
 
1436
1686
  // ../test-drift/dist/index.js
1437
1687
  import Ajv from "ajv";
@@ -1686,8 +1936,9 @@ function registerDiffCommand(program) {
1686
1936
  }
1687
1937
  async function runDiff(spec, opts) {
1688
1938
  const out = makeOutput(!!opts.json);
1689
- const specPath = resolve3(spec);
1939
+ const specPath = resolve5(spec);
1690
1940
  out.start(`Parsing OpenAPI spec: ${specPath}`);
1941
+ const specSource = await readFile5(specPath, "utf8");
1691
1942
  const ir = await fromOpenApiFile(specPath);
1692
1943
  inferResourceGraph(ir);
1693
1944
  parseIR(ir);
@@ -1704,16 +1955,40 @@ async function runDiff(spec, opts) {
1704
1955
  });
1705
1956
  const findings = compareProbes({ ir, probes });
1706
1957
  const counts = countBySeverity(findings);
1958
+ const session = await createSession({
1959
+ command: "diff",
1960
+ outRoot: resolve5("./loadam-out"),
1961
+ specPath,
1962
+ specSource,
1963
+ ir,
1964
+ irJson: JSON.stringify(ir, null, 2),
1965
+ target: opts.target,
1966
+ envVars: [],
1967
+ flags: {
1968
+ target: opts.target,
1969
+ timeoutMs,
1970
+ mutating: !!opts.mutating,
1971
+ failOn: opts.failOn ?? "error",
1972
+ headers: Object.keys(headers),
1973
+ pathParams: Object.keys(pathParams)
1974
+ },
1975
+ slug: `diff-${ir.meta.title ?? "run"}`
1976
+ });
1977
+ const report = renderMarkdownReport({
1978
+ ir,
1979
+ baseUrl: opts.target,
1980
+ findings,
1981
+ skipped
1982
+ });
1983
+ await session.addArtefact("drift.md", report);
1984
+ await session.addArtefact(
1985
+ "findings.json",
1986
+ JSON.stringify({ findings, skipped, counts }, null, 2)
1987
+ );
1707
1988
  if (!out.json) {
1708
- const report = renderMarkdownReport({
1709
- ir,
1710
- baseUrl: opts.target,
1711
- findings,
1712
- skipped
1713
- });
1714
1989
  if (opts.output) {
1715
- const outFile = resolve3(opts.output);
1716
- await writeFile2(outFile, report, "utf8");
1990
+ const outFile = resolve5(opts.output);
1991
+ await writeFile3(outFile, report, "utf8");
1717
1992
  out.success(`Wrote drift report to ${outFile}`);
1718
1993
  } else {
1719
1994
  process.stdout.write(report);
@@ -1721,17 +1996,24 @@ async function runDiff(spec, opts) {
1721
1996
  out.info(
1722
1997
  ` ${probes.length} probed \xB7 ${skipped.length} skipped \xB7 ${counts.error} error \xB7 ${counts.warning} warning \xB7 ${counts.info} info`
1723
1998
  );
1999
+ out.info(` Session: ${session.id}`);
1724
2000
  } else if (opts.output) {
1725
- const report = renderMarkdownReport({
1726
- ir,
1727
- baseUrl: opts.target,
1728
- findings,
1729
- skipped
1730
- });
1731
- await writeFile2(resolve3(opts.output), report, "utf8");
2001
+ await writeFile3(resolve5(opts.output), report, "utf8");
1732
2002
  }
1733
2003
  const failOn = opts.failOn ?? "error";
1734
2004
  const failed = failOn === "error" && counts.error > 0 || failOn === "warning" && counts.error + counts.warning > 0;
2005
+ await session.finalize({
2006
+ exitCode: failed ? 1 : 0,
2007
+ thresholds: { passed: [], failed: [] },
2008
+ summary: {
2009
+ probed: probes.length,
2010
+ skipped: skipped.length,
2011
+ findings: findings.length,
2012
+ error: counts.error,
2013
+ warning: counts.warning,
2014
+ info: counts.info
2015
+ }
2016
+ });
1735
2017
  out.result({
1736
2018
  command: "diff",
1737
2019
  target: opts.target,
@@ -1739,9 +2021,10 @@ async function runDiff(spec, opts) {
1739
2021
  skipped: skipped.length,
1740
2022
  findings: findings.length,
1741
2023
  counts,
1742
- reportPath: opts.output ? resolve3(opts.output) : null,
2024
+ reportPath: opts.output ? resolve5(opts.output) : null,
1743
2025
  failOn,
1744
- failed
2026
+ failed,
2027
+ sessionId: session.id
1745
2028
  });
1746
2029
  if (failOn !== "never" && failed) process.exit(1);
1747
2030
  }
@@ -1757,21 +2040,54 @@ function parseKvPairs(values, sep) {
1757
2040
  return out;
1758
2041
  }
1759
2042
 
2043
+ // src/commands/history.ts
2044
+ import { resolve as resolve6 } from "path";
2045
+ function registerHistoryCommand(program) {
2046
+ program.command("history").description("List archived loadam sessions (newest first).").option("--root <dir>", "session archive root", "./loadam-out").option("--limit <n>", "show at most N sessions", "20").option("--command <cmd>", "filter by command (test|contract|diff)").option("--json", "emit a JSON array on stdout", false).action(withFriendlyErrors(runHistory));
2047
+ }
2048
+ async function runHistory(opts) {
2049
+ const out = makeOutput(!!opts.json);
2050
+ const root = resolve6(opts.root);
2051
+ const limit = Number.parseInt(opts.limit ?? "20", 10);
2052
+ const all = await listSessions(root);
2053
+ const filtered = opts.command ? all.filter((s) => s.command === opts.command) : all;
2054
+ const shown = filtered.slice(0, Number.isFinite(limit) ? limit : 20);
2055
+ if (out.json) {
2056
+ out.result({ command: "history", root, total: filtered.length, sessions: shown });
2057
+ return;
2058
+ }
2059
+ if (shown.length === 0) {
2060
+ out.info("No sessions found. Run `loadam test`/`contract`/`diff` first.");
2061
+ return;
2062
+ }
2063
+ out.info(" ID CMD EXIT WHEN");
2064
+ for (const s of shown) {
2065
+ const idCol = s.id.padEnd(60).slice(0, 60);
2066
+ const cmdCol = s.command.padEnd(8);
2067
+ const exitCol = (s.exitCode ?? "\u2014").toString().padEnd(6);
2068
+ const when = s.startedAt;
2069
+ out.info(` ${idCol} ${cmdCol} ${exitCol} ${when}`);
2070
+ }
2071
+ if (filtered.length > shown.length) {
2072
+ out.info(` \u2026 ${filtered.length - shown.length} more (raise --limit to see them)`);
2073
+ }
2074
+ }
2075
+
1760
2076
  // src/commands/init.ts
1761
- import { writeFile as writeFile3 } from "fs/promises";
1762
- import { resolve as resolve4 } from "path";
2077
+ import { writeFile as writeFile4 } from "fs/promises";
2078
+ import { resolve as resolve7 } from "path";
1763
2079
  function registerInitCommand(program) {
1764
2080
  program.command("init").description("Parse a spec and emit loadam.ir.json with inferred resource graph").argument("<spec>", "path to OpenAPI 3.x spec (YAML or JSON)").option("-o, --output <path>", "output path for IR JSON", "./loadam.ir.json").option("--no-tree", "skip printing the resource-graph tree").option("--json", "emit a single JSON summary on stdout (CI mode)", false).action(withFriendlyErrors(runInit));
1765
2081
  }
1766
2082
  async function runInit(spec, opts) {
1767
2083
  const out = makeOutput(!!opts.json);
1768
- const specPath = resolve4(spec);
2084
+ const specPath = resolve7(spec);
1769
2085
  out.start(`Parsing OpenAPI spec: ${specPath}`);
1770
2086
  const ir = await fromOpenApiFile(specPath);
1771
2087
  inferResourceGraph(ir);
1772
2088
  parseIR(ir);
1773
- const outPath = resolve4(opts.output);
1774
- await writeFile3(outPath, `${JSON.stringify(ir, null, 2)}
2089
+ const outPath = resolve7(opts.output);
2090
+ await writeFile4(outPath, `${JSON.stringify(ir, null, 2)}
1775
2091
  `, "utf8");
1776
2092
  const stats = graphStats(ir.resources);
1777
2093
  out.success(`Wrote ${outPath}`);
@@ -1795,8 +2111,8 @@ async function runInit(spec, opts) {
1795
2111
  }
1796
2112
 
1797
2113
  // src/commands/mcp.ts
1798
- import { mkdir as mkdir2, writeFile as writeFile4 } from "fs/promises";
1799
- import { dirname as dirname2, resolve as resolve5 } from "path";
2114
+ import { mkdir as mkdir3, writeFile as writeFile5 } from "fs/promises";
2115
+ import { dirname as dirname2, resolve as resolve8 } from "path";
1800
2116
 
1801
2117
  // ../mcp/dist/index.js
1802
2118
  function emitAuth(ir) {
@@ -2304,7 +2620,7 @@ function registerMcpCommand(program) {
2304
2620
  }
2305
2621
  async function runMcp(spec, opts) {
2306
2622
  const out = makeOutput(!!opts.json);
2307
- const specPath = resolve5(spec);
2623
+ const specPath = resolve8(spec);
2308
2624
  out.start(`Parsing OpenAPI spec: ${specPath}`);
2309
2625
  const ir = await fromOpenApiFile(specPath);
2310
2626
  inferResourceGraph(ir);
@@ -2314,12 +2630,12 @@ async function runMcp(spec, opts) {
2314
2630
  includeWrites: !!opts.writes,
2315
2631
  exclude: opts.exclude
2316
2632
  });
2317
- const outDir = resolve5(opts.output);
2318
- await mkdir2(outDir, { recursive: true });
2633
+ const outDir = resolve8(opts.output);
2634
+ await mkdir3(outDir, { recursive: true });
2319
2635
  for (const [rel, contents] of Object.entries(result.files)) {
2320
- const full = resolve5(outDir, rel);
2321
- await mkdir2(dirname2(full), { recursive: true });
2322
- await writeFile4(full, contents, "utf8");
2636
+ const full = resolve8(outDir, rel);
2637
+ await mkdir3(dirname2(full), { recursive: true });
2638
+ await writeFile5(full, contents, "utf8");
2323
2639
  }
2324
2640
  const fileCount = Object.keys(result.files).length;
2325
2641
  out.success(`Wrote ${fileCount} files to ${outDir}`);
@@ -2345,9 +2661,66 @@ async function runMcp(spec, opts) {
2345
2661
  });
2346
2662
  }
2347
2663
 
2664
+ // src/commands/show.ts
2665
+ import { readFile as readFile6, readdir as readdir2 } from "fs/promises";
2666
+ import { join as join2, resolve as resolve9 } from "path";
2667
+ function registerShowCommand(program) {
2668
+ program.command("show").description("Show details of an archived session.").argument("<id>", 'session ID, prefix, or "latest"').option("--root <dir>", "session archive root", "./loadam-out").option("--json", "emit the meta.json payload on stdout", false).action(withFriendlyErrors(runShow));
2669
+ }
2670
+ async function runShow(id, opts) {
2671
+ const out = makeOutput(!!opts.json);
2672
+ const root = resolve9(opts.root);
2673
+ const meta = await resolveSessionId(root, id);
2674
+ const dir = join2(root, "sessions", meta.id);
2675
+ if (out.json) {
2676
+ out.result({ ...meta });
2677
+ return;
2678
+ }
2679
+ out.info(`Session ${meta.id}`);
2680
+ out.info(` Command: ${meta.command}`);
2681
+ out.info(` Started: ${meta.startedAt}`);
2682
+ if (meta.endedAt) out.info(` Ended: ${meta.endedAt}`);
2683
+ if (typeof meta.durationMs === "number") {
2684
+ out.info(` Duration: ${(meta.durationMs / 1e3).toFixed(2)}s`);
2685
+ }
2686
+ out.info(` Exit code: ${meta.exitCode ?? "\u2014"}`);
2687
+ out.info(` Spec: ${meta.spec.path} (${meta.spec.title ?? "?"} ${meta.spec.version ?? ""})`);
2688
+ out.info(` Spec sha: ${meta.spec.sha256.slice(0, 12)}\u2026`);
2689
+ out.info(` IR digest: ${meta.irDigest.slice(0, 12)}\u2026`);
2690
+ if (meta.target) out.info(` Target: ${meta.target}`);
2691
+ if (meta.envVars.length > 0) out.info(` Env vars: ${meta.envVars.join(", ")}`);
2692
+ if (meta.thresholds && (meta.thresholds.passed.length || meta.thresholds.failed.length)) {
2693
+ out.info(
2694
+ ` Thresholds: ${meta.thresholds.passed.length} passed \xB7 ${meta.thresholds.failed.length} failed`
2695
+ );
2696
+ for (const t of meta.thresholds.failed) out.info(` \u2717 ${t}`);
2697
+ }
2698
+ if (meta.summary && Object.keys(meta.summary).length > 0) {
2699
+ out.info(" Summary:");
2700
+ for (const [k, v] of Object.entries(meta.summary)) {
2701
+ out.info(` ${k}: ${v}`);
2702
+ }
2703
+ }
2704
+ try {
2705
+ const entries = await readdir2(dir);
2706
+ out.info(` Artefacts (${entries.length}):`);
2707
+ for (const e of entries.sort()) out.info(` ${e}`);
2708
+ } catch {
2709
+ }
2710
+ if (meta.command === "diff") {
2711
+ try {
2712
+ const drift = await readFile6(join2(dir, "drift.md"), "utf8");
2713
+ out.info("");
2714
+ out.info("\u2500\u2500\u2500\u2500 drift.md \u2500\u2500\u2500\u2500");
2715
+ process.stdout.write(drift);
2716
+ } catch {
2717
+ }
2718
+ }
2719
+ }
2720
+
2348
2721
  // src/commands/test.ts
2349
- import { mkdir as mkdir3, writeFile as writeFile6 } from "fs/promises";
2350
- import { dirname as dirname3, resolve as resolve7 } from "path";
2722
+ import { mkdir as mkdir4, readFile as readFile8, writeFile as writeFile7 } from "fs/promises";
2723
+ import { dirname as dirname3, join as join4, resolve as resolve11 } from "path";
2351
2724
 
2352
2725
  // ../data/dist/index.js
2353
2726
  import { faker } from "@faker-js/faker";
@@ -2400,20 +2773,20 @@ function inferKindFromFieldName(field) {
2400
2773
  const root = m[1];
2401
2774
  return root.charAt(0).toUpperCase() + root.slice(1);
2402
2775
  }
2403
- function expandRefs(node, resolve8, seen) {
2404
- if (Array.isArray(node)) return node.map((n) => expandRefs(n, resolve8, seen));
2776
+ function expandRefs(node, resolve12, seen) {
2777
+ if (Array.isArray(node)) return node.map((n) => expandRefs(n, resolve12, seen));
2405
2778
  if (!node || typeof node !== "object") return node;
2406
2779
  const obj = node;
2407
2780
  if (typeof obj.$ref === "string") {
2408
2781
  if (seen.has(obj.$ref)) return {};
2409
- const target = resolve8(obj.$ref);
2782
+ const target = resolve12(obj.$ref);
2410
2783
  if (target === void 0) return obj;
2411
2784
  const next = new Set(seen);
2412
2785
  next.add(obj.$ref);
2413
- return expandRefs(target, resolve8, next);
2786
+ return expandRefs(target, resolve12, next);
2414
2787
  }
2415
2788
  const out = {};
2416
- for (const [k, v] of Object.entries(obj)) out[k] = expandRefs(v, resolve8, seen);
2789
+ for (const [k, v] of Object.entries(obj)) out[k] = expandRefs(v, resolve12, seen);
2417
2790
  return out;
2418
2791
  }
2419
2792
 
@@ -2909,8 +3282,8 @@ function compileK6(ir, opts = {}) {
2909
3282
  }
2910
3283
 
2911
3284
  // src/util/interactive.ts
2912
- import { chmod, readFile as readFile4, writeFile as writeFile5 } from "fs/promises";
2913
- import { resolve as resolve6 } from "path";
3285
+ import { chmod, readFile as readFile7, writeFile as writeFile6 } from "fs/promises";
3286
+ import { resolve as resolve10 } from "path";
2914
3287
  import { confirm, password, select } from "@inquirer/prompts";
2915
3288
  function isInteractive(noInteractiveFlag) {
2916
3289
  if (noInteractiveFlag) return false;
@@ -2947,7 +3320,7 @@ async function confirmContinue(message) {
2947
3320
  return await confirm({ message, default: true });
2948
3321
  }
2949
3322
  async function writeEnvFile(dir, baseUrl, vars, opts = {}) {
2950
- const path = resolve6(dir, ".env");
3323
+ const path = resolve10(dir, ".env");
2951
3324
  const existing = await readEnvFile(path);
2952
3325
  const written = [];
2953
3326
  const preserved = [];
@@ -2967,14 +3340,14 @@ async function writeEnvFile(dir, baseUrl, vars, opts = {}) {
2967
3340
  }
2968
3341
  const body = `${Object.entries(existing).map(([k, v]) => `${k}=${v}`).join("\n")}
2969
3342
  `;
2970
- await writeFile5(path, body, "utf8");
3343
+ await writeFile6(path, body, "utf8");
2971
3344
  await chmod(path, 384).catch(() => {
2972
3345
  });
2973
3346
  return { path, written, preserved };
2974
3347
  }
2975
3348
  async function readEnvFile(path) {
2976
3349
  try {
2977
- const text = await readFile4(path, "utf8");
3350
+ const text = await readFile7(path, "utf8");
2978
3351
  const out = {};
2979
3352
  for (const raw of text.split(/\r?\n/)) {
2980
3353
  const line = raw.trim();
@@ -2994,14 +3367,14 @@ async function readEnvFile(path) {
2994
3367
  // src/util/k6.ts
2995
3368
  import { spawn } from "child_process";
2996
3369
  import { constants, access } from "fs/promises";
2997
- import { delimiter, join } from "path";
3370
+ import { delimiter, join as join3 } from "path";
2998
3371
  async function findK6Binary() {
2999
3372
  const path = process.env.PATH ?? "";
3000
3373
  const exts = process.platform === "win32" ? [".exe", ".cmd", ".bat", ""] : [""];
3001
3374
  for (const dir of path.split(delimiter)) {
3002
3375
  if (!dir) continue;
3003
3376
  for (const ext of exts) {
3004
- const candidate = join(dir, `k6${ext}`);
3377
+ const candidate = join3(dir, `k6${ext}`);
3005
3378
  try {
3006
3379
  await access(candidate, constants.X_OK);
3007
3380
  return candidate;
@@ -3018,8 +3391,11 @@ async function runK6(opts) {
3018
3391
  "k6 not found on PATH. Install it from https://grafana.com/docs/k6/latest/set-up/install-k6/ and try again."
3019
3392
  );
3020
3393
  }
3394
+ const args = ["run"];
3395
+ if (opts.summaryPath) args.push(`--summary-export=${opts.summaryPath}`);
3396
+ args.push(...opts.args ?? [], opts.script);
3021
3397
  return await new Promise((resolveExit, reject) => {
3022
- const child = spawn(bin, ["run", ...opts.args ?? [], opts.script], {
3398
+ const child = spawn(bin, args, {
3023
3399
  cwd: opts.cwd,
3024
3400
  env: { ...process.env, ...opts.env },
3025
3401
  stdio: "inherit"
@@ -3028,6 +3404,32 @@ async function runK6(opts) {
3028
3404
  child.on("close", (code) => resolveExit(code ?? 0));
3029
3405
  });
3030
3406
  }
3407
+ async function digestK6Summary(path) {
3408
+ try {
3409
+ const { readFile: readFile9 } = await import("fs/promises");
3410
+ const text = await readFile9(path, "utf8");
3411
+ const data = JSON.parse(text);
3412
+ const passed = [];
3413
+ const failed = [];
3414
+ const metrics = {};
3415
+ for (const [name, m] of Object.entries(data.metrics ?? {})) {
3416
+ if (m.thresholds) {
3417
+ for (const [expr, info] of Object.entries(m.thresholds)) {
3418
+ (info.ok ? passed : failed).push(`${name}: ${expr}`);
3419
+ }
3420
+ }
3421
+ if (m.values) {
3422
+ if (typeof m.values["p(95)"] === "number") metrics[`${name}.p95`] = m.values["p(95)"];
3423
+ if (typeof m.values.rate === "number") metrics[`${name}.rate`] = m.values.rate;
3424
+ if (typeof m.values.count === "number") metrics[`${name}.count`] = m.values.count;
3425
+ if (typeof m.values.avg === "number") metrics[`${name}.avg`] = m.values.avg;
3426
+ }
3427
+ }
3428
+ return { passed, failed, metrics };
3429
+ } catch {
3430
+ return null;
3431
+ }
3432
+ }
3031
3433
 
3032
3434
  // src/commands/test.ts
3033
3435
  var VALID_MODES = ["smoke", "load", "both", "skip"];
@@ -3042,8 +3444,9 @@ function registerTestCommand(program) {
3042
3444
  }
3043
3445
  async function runTest(spec, opts) {
3044
3446
  const out = makeOutput(!!opts.json);
3045
- const specPath = resolve7(spec);
3447
+ const specPath = resolve11(spec);
3046
3448
  out.start(`Parsing OpenAPI spec: ${specPath}`);
3449
+ const specSource = await readFile8(specPath, "utf8");
3047
3450
  const ir = await fromOpenApiFile(specPath);
3048
3451
  inferResourceGraph(ir);
3049
3452
  parseIR(ir);
@@ -3054,12 +3457,12 @@ async function runTest(spec, opts) {
3054
3457
  fixtureSize: Number.isFinite(fixtureSize) ? fixtureSize : 10,
3055
3458
  seed: Number.isFinite(seed) ? seed : 1
3056
3459
  });
3057
- const outDir = resolve7(opts.output);
3058
- await mkdir3(outDir, { recursive: true });
3460
+ const outDir = resolve11(opts.output);
3461
+ await mkdir4(outDir, { recursive: true });
3059
3462
  for (const [rel, contents] of Object.entries(result.files)) {
3060
- const full = resolve7(outDir, rel);
3061
- await mkdir3(dirname3(full), { recursive: true });
3062
- await writeFile6(full, contents, "utf8");
3463
+ const full = resolve11(outDir, rel);
3464
+ await mkdir4(dirname3(full), { recursive: true });
3465
+ await writeFile7(full, contents, "utf8");
3063
3466
  }
3064
3467
  const fileCount = Object.keys(result.files).length;
3065
3468
  const fixtureCount = Object.keys(result.fixtures.byOperationId).length;
@@ -3071,6 +3474,7 @@ async function runTest(spec, opts) {
3071
3474
  const requestedMode = parseModeFlag(opts.mode);
3072
3475
  let envAction = "not-needed";
3073
3476
  let runResult = null;
3477
+ let mode;
3074
3478
  if (interactive) {
3075
3479
  if (result.auth.envVars.length > 0) {
3076
3480
  out.step("");
@@ -3094,19 +3498,49 @@ async function runTest(spec, opts) {
3094
3498
  out.success(`Wrote ${written.path}`);
3095
3499
  envAction = "wrote";
3096
3500
  }
3097
- const mode = requestedMode ?? await promptForMode();
3098
- runResult = await maybeRun(mode, outDir, out);
3501
+ mode = requestedMode ?? await promptForMode();
3099
3502
  } else {
3100
- const mode = requestedMode ?? "skip";
3101
- if (mode !== "skip") {
3102
- runResult = await maybeRun(mode, outDir, out);
3103
- } else if (!out.json) {
3104
- out.step("");
3105
- out.step("Next steps:");
3106
- out.step(` cd ${opts.output}`);
3107
- out.step(" cp .env.example .env # fill in credentials");
3108
- out.step(" k6 run smoke.js");
3109
- }
3503
+ mode = requestedMode ?? "skip";
3504
+ }
3505
+ const session = await createSession({
3506
+ command: "test",
3507
+ outRoot: getSessionRoot(outDir),
3508
+ specPath,
3509
+ specSource,
3510
+ ir,
3511
+ irJson: JSON.stringify(ir, null, 2),
3512
+ target: opts.target ?? result.baseUrl,
3513
+ envVars: result.auth.envVars,
3514
+ flags: {
3515
+ mode,
3516
+ target: opts.target ?? null,
3517
+ fixtureSize,
3518
+ seed,
3519
+ noInteractive: !!opts.noInteractive,
3520
+ json: !!opts.json
3521
+ },
3522
+ slug: `${mode}-${ir.meta.title ?? "run"}`
3523
+ });
3524
+ if (!out.json) out.info(` Session: ${session.id}`);
3525
+ if (mode !== "skip") {
3526
+ runResult = await maybeRunWithSession({ mode, cwd: outDir, out, session });
3527
+ } else if (!interactive && !out.json) {
3528
+ out.step("");
3529
+ out.step("Next steps:");
3530
+ out.step(` cd ${opts.output}`);
3531
+ out.step(" cp .env.example .env # fill in credentials");
3532
+ out.step(" k6 run smoke.js");
3533
+ }
3534
+ if (mode === "skip") {
3535
+ await session.finalize({
3536
+ exitCode: 0,
3537
+ thresholds: { passed: [], failed: [] },
3538
+ summary: {
3539
+ operations: ir.operations.length,
3540
+ fixtureOps: fixtureCount,
3541
+ files: fileCount
3542
+ }
3543
+ });
3110
3544
  }
3111
3545
  out.result({
3112
3546
  command: "test",
@@ -3118,7 +3552,8 @@ async function runTest(spec, opts) {
3118
3552
  envVars: result.auth.envVars,
3119
3553
  envAction,
3120
3554
  interactive,
3121
- run: runResult
3555
+ run: runResult,
3556
+ sessionId: session.id
3122
3557
  });
3123
3558
  if (runResult) {
3124
3559
  if (runResult.smokeExit && runResult.smokeExit !== 0 || runResult.loadExit && runResult.loadExit !== 0) {
@@ -3133,34 +3568,83 @@ function parseModeFlag(raw) {
3133
3568
  }
3134
3569
  return raw;
3135
3570
  }
3136
- async function maybeRun(mode, cwd, out) {
3571
+ function getSessionRoot(outDir) {
3572
+ return resolve11(outDir, "..");
3573
+ }
3574
+ async function maybeRunWithSession(input) {
3575
+ const { mode, cwd, out, session } = input;
3137
3576
  if (mode === "skip") return { mode };
3138
3577
  const bin = await findK6Binary();
3139
3578
  if (!bin) {
3140
3579
  out.info("");
3141
3580
  out.info("k6 binary not found on PATH. Skipping run.");
3142
3581
  out.info("Install: https://grafana.com/docs/k6/latest/set-up/install-k6/");
3582
+ await session.finalize({
3583
+ exitCode: 0,
3584
+ thresholds: { passed: [], failed: [] },
3585
+ summary: { skipped: "k6 not installed" }
3586
+ });
3143
3587
  return { mode: "skip" };
3144
3588
  }
3145
3589
  const result = { mode };
3590
+ const allPassed = [];
3591
+ const allFailed = [];
3592
+ const summary = {};
3146
3593
  if (mode === "smoke" || mode === "both") {
3147
3594
  if (!out.json) {
3148
3595
  out.step("");
3149
3596
  out.step("Running k6 smoke test...");
3150
3597
  }
3151
- result.smokeExit = await runK6({ cwd, script: "smoke.js" });
3598
+ const summaryPath = join4(session.dir, "k6-smoke-summary.json");
3599
+ result.smokeExit = await runK6({ cwd, script: "smoke.js", summaryPath });
3600
+ const digest = await digestK6Summary(summaryPath);
3601
+ if (digest) {
3602
+ allPassed.push(...digest.passed.map((t) => `smoke: ${t}`));
3603
+ allFailed.push(...digest.failed.map((t) => `smoke: ${t}`));
3604
+ if (typeof digest.metrics["http_req_duration.p95"] === "number") {
3605
+ summary.smokeP95 = Math.round(digest.metrics["http_req_duration.p95"]);
3606
+ }
3607
+ if (typeof digest.metrics["http_reqs.count"] === "number") {
3608
+ summary.smokeReqs = digest.metrics["http_reqs.count"];
3609
+ }
3610
+ }
3152
3611
  }
3153
3612
  if (mode === "load" || mode === "both") {
3154
3613
  if (mode === "both") {
3155
3614
  const cont = await confirmContinue("Smoke complete. Continue with load test?");
3156
- if (!cont) return result;
3615
+ if (!cont) {
3616
+ await session.finalize({
3617
+ exitCode: result.smokeExit ?? 0,
3618
+ thresholds: { passed: allPassed, failed: allFailed },
3619
+ summary
3620
+ });
3621
+ return result;
3622
+ }
3157
3623
  }
3158
3624
  if (!out.json) {
3159
3625
  out.step("");
3160
3626
  out.step("Running k6 load test...");
3161
3627
  }
3162
- result.loadExit = await runK6({ cwd, script: "load.js" });
3628
+ const summaryPath = join4(session.dir, "k6-load-summary.json");
3629
+ result.loadExit = await runK6({ cwd, script: "load.js", summaryPath });
3630
+ const digest = await digestK6Summary(summaryPath);
3631
+ if (digest) {
3632
+ allPassed.push(...digest.passed.map((t) => `load: ${t}`));
3633
+ allFailed.push(...digest.failed.map((t) => `load: ${t}`));
3634
+ if (typeof digest.metrics["http_req_duration.p95"] === "number") {
3635
+ summary.loadP95 = Math.round(digest.metrics["http_req_duration.p95"]);
3636
+ }
3637
+ if (typeof digest.metrics["http_reqs.count"] === "number") {
3638
+ summary.loadReqs = digest.metrics["http_reqs.count"];
3639
+ }
3640
+ }
3163
3641
  }
3642
+ const finalExit = result.loadExit ?? result.smokeExit ?? 0;
3643
+ await session.finalize({
3644
+ exitCode: finalExit,
3645
+ thresholds: { passed: allPassed, failed: allFailed },
3646
+ summary
3647
+ });
3164
3648
  return result;
3165
3649
  }
3166
3650
 
@@ -3255,7 +3739,7 @@ ${dim}${TAGLINE}${reset}
3255
3739
  }
3256
3740
 
3257
3741
  // src/program.ts
3258
- var VERSION = true ? "0.2.0" : "0.0.0";
3742
+ var VERSION = true ? "0.2.1" : "0.0.0";
3259
3743
  function buildProgram() {
3260
3744
  const program = new Command();
3261
3745
  program.name("loadam").description(
@@ -3267,6 +3751,9 @@ function buildProgram() {
3267
3751
  registerContractCommand(program);
3268
3752
  registerDiffCommand(program);
3269
3753
  registerMcpCommand(program);
3754
+ registerHistoryCommand(program);
3755
+ registerShowCommand(program);
3756
+ registerCleanCommand(program);
3270
3757
  registerCompletionCommand(program);
3271
3758
  registerUpdateCommand(program, VERSION);
3272
3759
  return program;