@kirrosh/zond 0.26.1 → 0.27.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.
Files changed (261) hide show
  1. package/CHANGELOG.md +65 -0
  2. package/README.md +39 -22
  3. package/bin/zond.mjs +23 -0
  4. package/package.json +36 -23
  5. package/scripts/npm/postinstall.mjs +76 -0
  6. package/src/CLAUDE.md +0 -112
  7. package/src/bun-types.d.ts +0 -5
  8. package/src/cli/argv.ts +0 -122
  9. package/src/cli/commands/add-api.ts +0 -146
  10. package/src/cli/commands/api/annotate/idempotency.ts +0 -59
  11. package/src/cli/commands/api/annotate/index.ts +0 -880
  12. package/src/cli/commands/api/annotate/lifecycle.ts +0 -74
  13. package/src/cli/commands/api/annotate/overlay.ts +0 -206
  14. package/src/cli/commands/api/annotate/pagination.ts +0 -64
  15. package/src/cli/commands/api/annotate/prompts.ts +0 -220
  16. package/src/cli/commands/api/annotate/readback.ts +0 -58
  17. package/src/cli/commands/api/annotate/resources.ts +0 -91
  18. package/src/cli/commands/api/annotate/seed-bodies.ts +0 -61
  19. package/src/cli/commands/audit.ts +0 -786
  20. package/src/cli/commands/catalog.ts +0 -97
  21. package/src/cli/commands/check.ts +0 -361
  22. package/src/cli/commands/checks.ts +0 -1072
  23. package/src/cli/commands/ci-init.ts +0 -223
  24. package/src/cli/commands/clean.ts +0 -212
  25. package/src/cli/commands/cleanup.ts +0 -236
  26. package/src/cli/commands/completions.ts +0 -192
  27. package/src/cli/commands/coverage.ts +0 -872
  28. package/src/cli/commands/db.ts +0 -611
  29. package/src/cli/commands/describe.ts +0 -120
  30. package/src/cli/commands/discover.ts +0 -1356
  31. package/src/cli/commands/doctor.ts +0 -661
  32. package/src/cli/commands/fixtures.ts +0 -402
  33. package/src/cli/commands/generate.ts +0 -577
  34. package/src/cli/commands/init/agents-md.ts +0 -61
  35. package/src/cli/commands/init/bootstrap.ts +0 -111
  36. package/src/cli/commands/init/index.ts +0 -244
  37. package/src/cli/commands/init/skills.ts +0 -141
  38. package/src/cli/commands/init/templates/agents.md +0 -86
  39. package/src/cli/commands/init/templates/markdown.d.ts +0 -4
  40. package/src/cli/commands/init/templates/skills/warm-up-target.md +0 -122
  41. package/src/cli/commands/init/templates/skills/zond-checks.md +0 -621
  42. package/src/cli/commands/init/templates/skills/zond-seed.md +0 -114
  43. package/src/cli/commands/init/templates/skills/zond-triage.md +0 -272
  44. package/src/cli/commands/init/templates/skills/zond.md +0 -861
  45. package/src/cli/commands/init/templates/zond-config.yml +0 -14
  46. package/src/cli/commands/prepare-fixtures.ts +0 -97
  47. package/src/cli/commands/probe/_seed-bodies.ts +0 -52
  48. package/src/cli/commands/probe/mass-assignment.ts +0 -594
  49. package/src/cli/commands/probe/security.ts +0 -537
  50. package/src/cli/commands/probe/static.ts +0 -255
  51. package/src/cli/commands/probe/webhooks.ts +0 -163
  52. package/src/cli/commands/probe.ts +0 -535
  53. package/src/cli/commands/reference.ts +0 -87
  54. package/src/cli/commands/refresh-api.ts +0 -227
  55. package/src/cli/commands/remove-api.ts +0 -150
  56. package/src/cli/commands/report-bundle.ts +0 -310
  57. package/src/cli/commands/report.ts +0 -241
  58. package/src/cli/commands/request.ts +0 -548
  59. package/src/cli/commands/run.ts +0 -1162
  60. package/src/cli/commands/schema-from-runs.ts +0 -128
  61. package/src/cli/commands/secrets.ts +0 -133
  62. package/src/cli/commands/session.ts +0 -244
  63. package/src/cli/commands/use.ts +0 -74
  64. package/src/cli/index.ts +0 -55
  65. package/src/cli/json-envelope.ts +0 -108
  66. package/src/cli/json-schemas.ts +0 -314
  67. package/src/cli/output.ts +0 -40
  68. package/src/cli/program.ts +0 -219
  69. package/src/cli/resolve.ts +0 -105
  70. package/src/cli/runtime.ts +0 -7
  71. package/src/cli/safe-live.ts +0 -24
  72. package/src/cli/status-filter.ts +0 -114
  73. package/src/cli/util/api-context.ts +0 -85
  74. package/src/cli/version.ts +0 -8
  75. package/src/core/audit/persist.ts +0 -183
  76. package/src/core/checks/budget.ts +0 -59
  77. package/src/core/checks/checks/_crud-helpers.ts +0 -133
  78. package/src/core/checks/checks/_negative_mutator.ts +0 -133
  79. package/src/core/checks/checks/_readback-helpers.ts +0 -133
  80. package/src/core/checks/checks/content_type_conformance.ts +0 -39
  81. package/src/core/checks/checks/cross_call_references.ts +0 -147
  82. package/src/core/checks/checks/cursor_boundary_fuzzing.ts +0 -219
  83. package/src/core/checks/checks/ensure_resource_availability.ts +0 -62
  84. package/src/core/checks/checks/idempotency_replay.ts +0 -242
  85. package/src/core/checks/checks/ignored_auth.ts +0 -254
  86. package/src/core/checks/checks/index.ts +0 -68
  87. package/src/core/checks/checks/lifecycle_transitions.ts +0 -416
  88. package/src/core/checks/checks/missing_required_header.ts +0 -40
  89. package/src/core/checks/checks/negative_data_rejection.ts +0 -148
  90. package/src/core/checks/checks/not_a_server_error.ts +0 -35
  91. package/src/core/checks/checks/open_cors_on_sensitive.ts +0 -160
  92. package/src/core/checks/checks/pagination_invariants.ts +0 -419
  93. package/src/core/checks/checks/positive_data_acceptance.ts +0 -33
  94. package/src/core/checks/checks/rate_limit_headers_absent.ts +0 -77
  95. package/src/core/checks/checks/response_headers_conformance.ts +0 -74
  96. package/src/core/checks/checks/response_schema_conformance.ts +0 -30
  97. package/src/core/checks/checks/status_code_conformance.ts +0 -132
  98. package/src/core/checks/checks/unsupported_method.ts +0 -63
  99. package/src/core/checks/checks/use_after_free.ts +0 -78
  100. package/src/core/checks/index.ts +0 -30
  101. package/src/core/checks/mode.ts +0 -82
  102. package/src/core/checks/recommended-action.ts +0 -68
  103. package/src/core/checks/registry.ts +0 -78
  104. package/src/core/checks/runner.ts +0 -1461
  105. package/src/core/checks/sarif.ts +0 -230
  106. package/src/core/checks/spec-findings.ts +0 -308
  107. package/src/core/checks/stateful.ts +0 -121
  108. package/src/core/checks/types.ts +0 -305
  109. package/src/core/checks/zond-extensions.ts +0 -73
  110. package/src/core/classifier/recommended-action.ts +0 -251
  111. package/src/core/context/current.ts +0 -51
  112. package/src/core/context/session.ts +0 -78
  113. package/src/core/coverage/loader.ts +0 -216
  114. package/src/core/coverage/reasons.ts +0 -300
  115. package/src/core/diagnostics/db-analysis.ts +0 -666
  116. package/src/core/diagnostics/failure-class.ts +0 -140
  117. package/src/core/diagnostics/failure-hints.ts +0 -112
  118. package/src/core/diagnostics/spec-pointer.ts +0 -99
  119. package/src/core/diagnostics/suggested-fixes.ts +0 -155
  120. package/src/core/exporter/case-study/index.ts +0 -270
  121. package/src/core/exporter/curl.ts +0 -40
  122. package/src/core/exporter/exporter.ts +0 -48
  123. package/src/core/exporter/html-report/escape.ts +0 -24
  124. package/src/core/exporter/html-report/index.ts +0 -479
  125. package/src/core/exporter/html-report/script.ts +0 -100
  126. package/src/core/exporter/html-report/styles.ts +0 -408
  127. package/src/core/generator/catalog-builder.ts +0 -179
  128. package/src/core/generator/chunker.ts +0 -78
  129. package/src/core/generator/coverage-phase.ts +0 -0
  130. package/src/core/generator/coverage-scanner.ts +0 -87
  131. package/src/core/generator/data-factory.ts +0 -759
  132. package/src/core/generator/describe.ts +0 -302
  133. package/src/core/generator/endpoint-warnings.ts +0 -52
  134. package/src/core/generator/fixtures-builder.ts +0 -332
  135. package/src/core/generator/index.ts +0 -14
  136. package/src/core/generator/openapi-reader.ts +0 -297
  137. package/src/core/generator/path-param-disambig.ts +0 -140
  138. package/src/core/generator/resources-builder.ts +0 -898
  139. package/src/core/generator/schema-utils.ts +0 -112
  140. package/src/core/generator/serializer.ts +0 -343
  141. package/src/core/generator/suite-generator.ts +0 -1301
  142. package/src/core/generator/types.ts +0 -63
  143. package/src/core/identity/identity-file.ts +0 -0
  144. package/src/core/lint/affects.ts +0 -28
  145. package/src/core/lint/config.ts +0 -96
  146. package/src/core/lint/format.ts +0 -42
  147. package/src/core/lint/index.ts +0 -94
  148. package/src/core/lint/reporter.ts +0 -128
  149. package/src/core/lint/rules/consistency.ts +0 -158
  150. package/src/core/lint/rules/heuristics.ts +0 -97
  151. package/src/core/lint/rules/strictness.ts +0 -109
  152. package/src/core/lint/types.ts +0 -96
  153. package/src/core/lint/walker.ts +0 -248
  154. package/src/core/meta/meta-store.ts +0 -11
  155. package/src/core/output/README.md +0 -73
  156. package/src/core/output/index.ts +0 -13
  157. package/src/core/output/run.ts +0 -91
  158. package/src/core/output/types.ts +0 -122
  159. package/src/core/parser/dynamic-values.ts +0 -160
  160. package/src/core/parser/env-interpolation.ts +0 -104
  161. package/src/core/parser/filter.ts +0 -97
  162. package/src/core/parser/schema.ts +0 -359
  163. package/src/core/parser/types.ts +0 -117
  164. package/src/core/parser/variables.ts +0 -0
  165. package/src/core/parser/yaml-parser.ts +0 -181
  166. package/src/core/probe/bootstrap.ts +0 -34
  167. package/src/core/probe/dry-run-envelope.ts +0 -61
  168. package/src/core/probe/mass-assignment/classify.ts +0 -175
  169. package/src/core/probe/mass-assignment/cleanup.ts +0 -52
  170. package/src/core/probe/mass-assignment/digest.ts +0 -114
  171. package/src/core/probe/mass-assignment/orchestrator.ts +0 -459
  172. package/src/core/probe/mass-assignment/regression.ts +0 -141
  173. package/src/core/probe/mass-assignment/suspects.ts +0 -92
  174. package/src/core/probe/mass-assignment/types.ts +0 -135
  175. package/src/core/probe/mass-assignment-probe-class.ts +0 -198
  176. package/src/core/probe/mass-assignment-probe.ts +0 -27
  177. package/src/core/probe/mass-assignment-template.ts +0 -240
  178. package/src/core/probe/method-probe.ts +0 -164
  179. package/src/core/probe/method-shared.ts +0 -69
  180. package/src/core/probe/negative-probe.ts +0 -691
  181. package/src/core/probe/orphan-tracker.ts +0 -188
  182. package/src/core/probe/path-discovery.ts +0 -439
  183. package/src/core/probe/probe-harness.ts +0 -119
  184. package/src/core/probe/registry.ts +0 -89
  185. package/src/core/probe/runner.ts +0 -136
  186. package/src/core/probe/security/baseline.ts +0 -174
  187. package/src/core/probe/security/classify.ts +0 -341
  188. package/src/core/probe/security/cleanup.ts +0 -125
  189. package/src/core/probe/security/detectors.ts +0 -71
  190. package/src/core/probe/security/digest.ts +0 -104
  191. package/src/core/probe/security/orchestrator.ts +0 -398
  192. package/src/core/probe/security/regression.ts +0 -103
  193. package/src/core/probe/security/types.ts +0 -151
  194. package/src/core/probe/security-probe-class.ts +0 -207
  195. package/src/core/probe/security-probe.ts +0 -32
  196. package/src/core/probe/shared.ts +0 -531
  197. package/src/core/probe/static-probe-class.ts +0 -125
  198. package/src/core/probe/types.ts +0 -165
  199. package/src/core/probe/verdict-aggregator.ts +0 -33
  200. package/src/core/probe/webhooks-probe.ts +0 -282
  201. package/src/core/reporter/console.ts +0 -240
  202. package/src/core/reporter/index.ts +0 -22
  203. package/src/core/reporter/json.ts +0 -22
  204. package/src/core/reporter/junit.ts +0 -93
  205. package/src/core/reporter/ndjson.ts +0 -37
  206. package/src/core/reporter/types.ts +0 -15
  207. package/src/core/runner/assertions.ts +0 -383
  208. package/src/core/runner/async-pool.ts +0 -108
  209. package/src/core/runner/auth-path.ts +0 -8
  210. package/src/core/runner/ci-context.ts +0 -72
  211. package/src/core/runner/executor.ts +0 -652
  212. package/src/core/runner/expr-eval.ts +0 -41
  213. package/src/core/runner/form-encode.ts +0 -41
  214. package/src/core/runner/http-client.ts +0 -224
  215. package/src/core/runner/learn-drift.ts +0 -293
  216. package/src/core/runner/preflight-vars.ts +0 -153
  217. package/src/core/runner/progress-tracker.ts +0 -73
  218. package/src/core/runner/rate-limiter.ts +0 -185
  219. package/src/core/runner/run-kind.ts +0 -45
  220. package/src/core/runner/schema-validator.ts +0 -308
  221. package/src/core/runner/send-request.ts +0 -232
  222. package/src/core/runner/transforms.ts +0 -65
  223. package/src/core/runner/types.ts +0 -94
  224. package/src/core/secrets/registry.ts +0 -164
  225. package/src/core/secrets/secrets-file.ts +0 -115
  226. package/src/core/selectors/operation-filter.ts +0 -144
  227. package/src/core/setup-api.ts +0 -590
  228. package/src/core/severity/category.ts +0 -94
  229. package/src/core/severity/index.ts +0 -58
  230. package/src/core/spec/infer-schema.ts +0 -102
  231. package/src/core/spec/layers.ts +0 -154
  232. package/src/core/spec/merge-specs.ts +0 -156
  233. package/src/core/spec/schema-from-runs.ts +0 -117
  234. package/src/core/spec/schema-overlay.ts +0 -130
  235. package/src/core/util/ajv.ts +0 -13
  236. package/src/core/util/format-eta.ts +0 -21
  237. package/src/core/util/headers.ts +0 -9
  238. package/src/core/util/url.ts +0 -24
  239. package/src/core/utils.ts +0 -13
  240. package/src/core/workspace/config.ts +0 -129
  241. package/src/core/workspace/fixture-gap-report.ts +0 -84
  242. package/src/core/workspace/fixture-gaps.ts +0 -71
  243. package/src/core/workspace/manifest.ts +0 -283
  244. package/src/core/workspace/output-rotation.ts +0 -62
  245. package/src/core/workspace/root.ts +0 -96
  246. package/src/core/workspace/triage-path.ts +0 -87
  247. package/src/db/lint-runs.ts +0 -47
  248. package/src/db/migrate.ts +0 -128
  249. package/src/db/migrations/0001_run_kind.sql +0 -25
  250. package/src/db/migrations/0002_run_kind_request.sql +0 -59
  251. package/src/db/migrations/sql.d.ts +0 -4
  252. package/src/db/queries/collections.ts +0 -133
  253. package/src/db/queries/coverage.ts +0 -9
  254. package/src/db/queries/dashboard.ts +0 -59
  255. package/src/db/queries/results.ts +0 -216
  256. package/src/db/queries/runs.ts +0 -289
  257. package/src/db/queries/sessions.ts +0 -42
  258. package/src/db/queries/settings.ts +0 -28
  259. package/src/db/queries/types.ts +0 -172
  260. package/src/db/queries.ts +0 -75
  261. package/src/db/schema.ts +0 -298
@@ -1,227 +0,0 @@
1
- /**
2
- * `zond refresh-api <name>` — re-fetch the OpenAPI spec and regenerate
3
- * the four artifacts (spec.json, .api-catalog.yaml, .api-resources.yaml,
4
- * .api-fixtures.yaml).
5
- *
6
- * Without --spec, refresh re-reads from the source recorded at register
7
- * time (treating workspace-relative paths as the local snapshot — which
8
- * is a no-op refresh useful only for re-emitting derived artifacts after
9
- * a builder change). With --spec, the new source is fetched, dereferenced,
10
- * and replaces the local snapshot.
11
- */
12
-
13
- import { readFileSync, existsSync } from "node:fs";
14
- import { join } from "node:path";
15
- import { getDb } from "../../db/schema.ts";
16
- import { findCollectionByNameOrId, updateCollection } from "../../db/queries.ts";
17
- import { findWorkspaceRoot } from "../../core/workspace/root.ts";
18
- import { readOpenApiSpec } from "../../core/generator/openapi-reader.ts";
19
- import {
20
- resolveCollectionSpec,
21
- writeArtifactsFromDoc,
22
- SPEC_SNAPSHOT_FILENAME,
23
- } from "../../core/setup-api.ts";
24
- import { jsonOk, jsonError, printJson } from "../json-envelope.ts";
25
- import { printError, printSuccess, printWarning } from "../output.ts";
26
- import { readFileSync as readFileSyncNode } from "node:fs";
27
- import {
28
- loadSchemaOverlay,
29
- mergePatch,
30
- saveSchemaOverlay,
31
- applySchemaOverlay,
32
- type ResponseSchemaPatch,
33
- } from "../../core/spec/schema-overlay.ts";
34
-
35
- export interface RefreshApiOptions {
36
- api: string;
37
- /** When provided, fetch this source and replace spec.json. Otherwise
38
- * re-read the existing local snapshot and just rebuild artifacts. */
39
- spec?: string;
40
- insecure?: boolean;
41
- json?: boolean;
42
- dbPath?: string;
43
- /** ARV-176: path to a patch.schema.json (from `schema-from-runs`) to fold
44
- * into the response-schema overlay before rebuilding spec.json. */
45
- mergeSchema?: string;
46
- /** ARV-176: overwrite response schemas already declared upstream. */
47
- force?: boolean;
48
- }
49
-
50
- export async function refreshApiCommand(opts: RefreshApiOptions): Promise<number> {
51
- try {
52
- getDb(opts.dbPath);
53
- } catch (err) {
54
- const m = `DB unavailable: ${(err as Error).message}`;
55
- if (opts.json) printJson(jsonError("refresh-api", [m])); else printError(m);
56
- return 2;
57
- }
58
-
59
- const collection = findCollectionByNameOrId(opts.api);
60
- if (!collection) {
61
- const m = `API '${opts.api}' not found.`;
62
- if (opts.json) printJson(jsonError("refresh-api", [m])); else printError(m);
63
- return 2;
64
- }
65
-
66
- if (!collection.base_dir) {
67
- const m = `API '${opts.api}' has no base_dir recorded — cannot refresh artifacts.`;
68
- if (opts.json) printJson(jsonError("refresh-api", [m])); else printError(m);
69
- return 2;
70
- }
71
-
72
- const workspaceRoot = findWorkspaceRoot().root;
73
- const baseDir = collection.base_dir;
74
-
75
- // 1. Pick spec source
76
- let specSource: string;
77
- let usedExternal: boolean;
78
- if (opts.spec) {
79
- specSource = opts.spec;
80
- usedExternal = true;
81
- } else if (collection.openapi_spec) {
82
- specSource = resolveCollectionSpec(collection.openapi_spec);
83
- usedExternal = false;
84
- if (!existsSync(specSource) && !/^https?:\/\//i.test(specSource)) {
85
- const m = `Local spec snapshot missing at ${specSource}. Pass --spec <path|url> to re-pull from upstream.`;
86
- if (opts.json) printJson(jsonError("refresh-api", [m])); else printError(m);
87
- return 2;
88
- }
89
- } else {
90
- const m = `API '${opts.api}' has no spec recorded. Pass --spec <path|url>.`;
91
- if (opts.json) printJson(jsonError("refresh-api", [m])); else printError(m);
92
- return 2;
93
- }
94
-
95
- // 2. Dereference (fetch if URL)
96
- let doc: unknown;
97
- try {
98
- doc = await readOpenApiSpec(specSource, { insecure: opts.insecure });
99
- } catch (err) {
100
- const m = `Failed to read spec ${specSource}: ${(err as Error).message}`;
101
- if (opts.json) printJson(jsonError("refresh-api", [m])); else printError(m);
102
- return 2;
103
- }
104
-
105
- // 3. Determine baseUrl from the doc
106
- const baseUrl = ((doc as any).servers?.[0]?.url as string | undefined) ?? "";
107
-
108
- // ARV-176: response-schema overlay. Fold a --merge-schema patch into the
109
- // persistent overlay first, then apply the (possibly-updated) overlay onto
110
- // the freshly-pulled doc *before* it's serialised to spec.json. Applying on
111
- // every refresh (not only when --merge-schema is passed) is what makes the
112
- // overlay survive an upstream re-pull (AC#2).
113
- let schemaReport: {
114
- merged_from?: string;
115
- applied: string[];
116
- preserved: string[];
117
- conflicts: string[];
118
- } | undefined;
119
- if (opts.mergeSchema) {
120
- let incoming: ResponseSchemaPatch;
121
- try {
122
- incoming = JSON.parse(readFileSyncNode(opts.mergeSchema, "utf-8")) as ResponseSchemaPatch;
123
- } catch (err) {
124
- const m = `Failed to read --merge-schema "${opts.mergeSchema}": ${(err as Error).message}`;
125
- if (opts.json) printJson(jsonError("refresh-api", [m])); else printError(m);
126
- return 2;
127
- }
128
- const merged = mergePatch(loadSchemaOverlay(baseDir), incoming);
129
- saveSchemaOverlay(baseDir, merged);
130
- }
131
- const overlay = loadSchemaOverlay(baseDir);
132
- if (overlay) {
133
- const r = applySchemaOverlay(doc, overlay, { force: opts.force === true });
134
- schemaReport = {
135
- ...(opts.mergeSchema ? { merged_from: opts.mergeSchema } : {}),
136
- applied: r.applied,
137
- preserved: r.preserved,
138
- conflicts: r.conflicts,
139
- };
140
- }
141
-
142
- // 4. Write spec.json + 3 artifacts
143
- writeArtifactsFromDoc({
144
- doc,
145
- baseDir,
146
- apiName: collection.name,
147
- baseUrl,
148
- workspaceRoot,
149
- });
150
-
151
- // 5. If we pulled fresh from external, ensure the DB points to the local snapshot
152
- const expectedDbSpec = `apis/${collection.name}/${SPEC_SNAPSHOT_FILENAME}`;
153
- if (collection.openapi_spec !== expectedDbSpec) {
154
- updateCollection(collection.id, { openapi_spec: expectedDbSpec });
155
- }
156
-
157
- // 6. Surface result
158
- const localSpec = join(baseDir, SPEC_SNAPSHOT_FILENAME);
159
- const endpointCount = readEndpointCount(localSpec);
160
- const result = {
161
- api: collection.name,
162
- baseDir,
163
- spec: localSpec,
164
- pulledFrom: usedExternal ? specSource : null,
165
- endpointCount,
166
- artifacts: [".api-catalog.yaml", ".api-resources.yaml", ".api-fixtures.yaml"],
167
- ...(schemaReport ? { schema_overlay: schemaReport } : {}),
168
- };
169
-
170
- if (opts.json) {
171
- printJson(jsonOk("refresh-api", result));
172
- } else {
173
- printSuccess(`Refreshed '${collection.name}' (${endpointCount} endpoints)${usedExternal ? ` from ${specSource}` : ""}`);
174
- process.stdout.write(` spec: ${localSpec}\n`);
175
- process.stdout.write(` artifacts: ${result.artifacts.join(", ")}\n`);
176
- if (schemaReport) {
177
- process.stdout.write(` schema overlay: ${schemaReport.applied.length} applied, ${schemaReport.preserved.length} preserved, ${schemaReport.conflicts.length} conflict(s)\n`);
178
- for (const c of schemaReport.conflicts) {
179
- printWarning(`schema overlay conflict (endpoint not in upstream, skipped): ${c}`);
180
- }
181
- }
182
- process.stdout.write(` Run \`zond doctor --api ${collection.name}\` to verify fixtures.\n`);
183
- }
184
- return 0;
185
- }
186
-
187
- function readEndpointCount(specPath: string): number {
188
- try {
189
- const doc = JSON.parse(readFileSync(specPath, "utf-8")) as any;
190
- let count = 0;
191
- for (const item of Object.values(doc.paths ?? {})) {
192
- if (item && typeof item === "object") {
193
- for (const k of Object.keys(item as object)) {
194
- if (["get", "post", "put", "patch", "delete", "head", "options"].includes(k.toLowerCase())) count++;
195
- }
196
- }
197
- }
198
- return count;
199
- } catch {
200
- return 0;
201
- }
202
- }
203
-
204
- import type { Command } from "commander";
205
- import { globalJson } from "../resolve.ts";
206
-
207
- export function registerRefreshApi(program: Command): void {
208
- program
209
- .command("refresh-api <name>")
210
- .description("Re-snapshot the OpenAPI spec into apis/<name>/spec.json and regenerate the 3 artifacts (catalog/resources/fixtures)")
211
- .option("--spec <path>", "Pull fresh from this path or URL (overrides registered source)")
212
- .option("--insecure", "Allow self-signed TLS when --spec is an https URL")
213
- .option("--merge-schema <path>", "ARV-176: fold a patch.schema.json (from `zond schema-from-runs`) into the persistent response-schema overlay (.api-schema.local.yaml) and apply it to spec.json. The overlay survives future refreshes.")
214
- .option("--force", "ARV-176: overwrite response schemas already declared upstream (default: only fill gaps).")
215
- .option("--db <path>", "Path to SQLite database file")
216
- .action(async (name: string, opts, cmd: Command) => {
217
- process.exitCode = await refreshApiCommand({
218
- api: name,
219
- spec: opts.spec,
220
- insecure: opts.insecure === true,
221
- mergeSchema: typeof opts.mergeSchema === "string" ? opts.mergeSchema : undefined,
222
- force: opts.force === true,
223
- dbPath: typeof opts.db === "string" ? opts.db : undefined,
224
- json: globalJson(cmd),
225
- });
226
- });
227
- }
@@ -1,150 +0,0 @@
1
- /**
2
- * `zond remove api <name>` — unregister an API from the workspace.
3
- *
4
- * Mirrors `zond add api`. Removes the `collections` row, optionally the
5
- * associated `runs`/`results`, and (by default) the `apis/<name>/`
6
- * directory on disk. If the removed API was the active one
7
- * (`.zond/current-api`), the marker is cleared.
8
- *
9
- * Without `--purge`, runs that referenced the collection are detached
10
- * (`collection_id = NULL`) so historical run data survives the removal.
11
- * `--purge` deletes them outright. `--keep-files` leaves the directory
12
- * on disk and only drops the DB row, useful when the user wants to
13
- * snapshot the artifacts elsewhere first.
14
- */
15
-
16
- import { existsSync, rmSync } from "node:fs";
17
- import { relative, resolve } from "node:path";
18
- import { getDb } from "../../db/schema.ts";
19
- import {
20
- deleteCollection,
21
- findCollectionByNameOrId,
22
- } from "../../db/queries.ts";
23
- import { findWorkspaceRoot } from "../../core/workspace/root.ts";
24
- import { clearCurrentApi, readCurrentApi } from "../../core/context/current.ts";
25
- import { jsonOk, jsonError, printJson } from "../json-envelope.ts";
26
- import { printError, printSuccess } from "../output.ts";
27
-
28
- export interface RemoveApiOptions {
29
- api: string;
30
- purge?: boolean;
31
- keepFiles?: boolean;
32
- yes?: boolean;
33
- dbPath?: string;
34
- json?: boolean;
35
- }
36
-
37
- export interface RemoveApiResult {
38
- api: string;
39
- collectionId: number;
40
- removedDir: string | null;
41
- detachedRuns: number;
42
- deletedRuns: number;
43
- clearedCurrent: boolean;
44
- }
45
-
46
- export async function removeApiCommand(opts: RemoveApiOptions): Promise<number> {
47
- try {
48
- getDb(opts.dbPath);
49
- } catch (err) {
50
- const m = `DB unavailable: ${(err as Error).message}`;
51
- if (opts.json) printJson(jsonError("remove-api", [m])); else printError(m);
52
- return 2;
53
- }
54
-
55
- const collection = findCollectionByNameOrId(opts.api);
56
- if (!collection) {
57
- const m = `API '${opts.api}' not found.`;
58
- if (opts.json) printJson(jsonError("remove-api", [m])); else printError(m);
59
- return 2;
60
- }
61
-
62
- const db = getDb();
63
- const runsCount = (db
64
- .query("SELECT COUNT(*) AS c FROM runs WHERE collection_id = ?")
65
- .get(collection.id) as { c: number }).c;
66
-
67
- const workspaceRoot = findWorkspaceRoot().root;
68
- const dirAbs = collection.base_dir
69
- ? resolve(workspaceRoot, collection.base_dir)
70
- : null;
71
- const willRemoveDir = !opts.keepFiles && dirAbs !== null && existsSync(dirAbs);
72
- const dirRel = dirAbs ? relative(workspaceRoot, dirAbs).replace(/\\/g, "/") : null;
73
-
74
- if (!opts.yes && !opts.json) {
75
- const parts = [
76
- `Removing API '${collection.name}' (id=${collection.id})`,
77
- willRemoveDir ? ` • directory: ${dirRel}` : ` • directory: kept`,
78
- opts.purge
79
- ? ` • runs: ${runsCount} runs + their results will be DELETED`
80
- : ` • runs: ${runsCount} runs will be detached (collection_id=NULL)`,
81
- ];
82
- process.stderr.write(parts.join("\n") + "\nPass --yes to confirm.\n");
83
- return 1;
84
- }
85
-
86
- const detachedRuns = opts.purge ? 0 : runsCount;
87
- const deletedRuns = opts.purge ? runsCount : 0;
88
- deleteCollection(collection.id, opts.purge === true);
89
-
90
- let removedDir: string | null = null;
91
- if (willRemoveDir && dirAbs) {
92
- rmSync(dirAbs, { recursive: true, force: true });
93
- removedDir = relative(workspaceRoot, dirAbs).replace(/\\/g, "/");
94
- }
95
-
96
- let clearedCurrent = false;
97
- const current = readCurrentApi(workspaceRoot);
98
- if (current === collection.name) {
99
- clearedCurrent = clearCurrentApi(workspaceRoot);
100
- }
101
-
102
- const result: RemoveApiResult = {
103
- api: collection.name,
104
- collectionId: collection.id,
105
- removedDir,
106
- detachedRuns,
107
- deletedRuns,
108
- clearedCurrent,
109
- };
110
-
111
- if (opts.json) {
112
- printJson(jsonOk("remove-api", result));
113
- } else {
114
- printSuccess(`Removed API '${collection.name}' (id=${collection.id})`);
115
- if (removedDir) process.stdout.write(` Directory: ${removedDir} (deleted)\n`);
116
- else if (opts.keepFiles) process.stdout.write(` Directory: ${dirRel ?? "<unknown>"} (kept by --keep-files)\n`);
117
- if (opts.purge) process.stdout.write(` Runs: ${deletedRuns} deleted (--purge)\n`);
118
- else if (detachedRuns > 0) process.stdout.write(` Runs: ${detachedRuns} detached (collection_id=NULL)\n`);
119
- if (clearedCurrent) process.stdout.write(` Cleared .zond/current-api marker (was '${collection.name}')\n`);
120
- }
121
- return 0;
122
- }
123
-
124
- import type { Command } from "commander";
125
- import { globalJson } from "../resolve.ts";
126
-
127
- export function registerRemove(program: Command): void {
128
- const remove = program
129
- .command("remove")
130
- .alias("rm")
131
- .description("Unregister objects from the workspace");
132
- remove
133
- .command("api <name>")
134
- .description("Unregister an API: drops collections row, removes apis/<name>/, optionally purges run history")
135
- .option("--purge", "Also delete the runs+results that referenced this API (default: detach to NULL)")
136
- .option("--keep-files", "Leave apis/<name>/ on disk; only remove the DB record")
137
- .option("--yes", "Skip the interactive confirmation prompt")
138
- .option("--db <path>", "Path to SQLite database file")
139
- .action(async (name: string, opts, cmd: Command) => {
140
- const json = globalJson(cmd);
141
- process.exitCode = await removeApiCommand({
142
- api: name,
143
- purge: opts.purge === true,
144
- keepFiles: opts.keepFiles === true,
145
- yes: opts.yes === true || json,
146
- dbPath: typeof opts.db === "string" ? opts.db : undefined,
147
- json,
148
- });
149
- });
150
- }
@@ -1,310 +0,0 @@
1
- /**
2
- * TASK-143: `zond report bundle <range> [--output <dir>] [--include ...]`.
3
- *
4
- * Batch triage exporter — collects case-study + HTML report + diagnose JSON
5
- * for a range of run-ids in one command, plus a top-level index.md with a
6
- * table of run-id, totals, and links.
7
- *
8
- * Range forms:
9
- * A..B inclusive numeric range, e.g. "135..142"
10
- * A,B,C comma-separated list
11
- * --session <id> all runs for a CLI session (DB column `session_id`)
12
- */
13
- import { join } from "path";
14
- import { mkdir } from "fs/promises";
15
- import { getDb } from "../../db/schema.ts";
16
- import { getRunById, getResultsByRunId, getCollectionById } from "../../db/queries.ts";
17
- import type { RunRecord, StoredStepResult } from "../../db/queries/types.ts";
18
- import { renderHtmlReport } from "../../core/exporter/html-report/index.ts";
19
- import { renderCaseStudy } from "../../core/exporter/case-study/index.ts";
20
- import { diagnoseRun } from "../../core/diagnostics/db-analysis.ts";
21
- import { applySanitizer } from "../../core/exporter/exporter.ts";
22
- import { resolveCollectionSpec } from "../../core/setup-api.ts";
23
- import { readOpenApiSpec } from "../../core/generator/openapi-reader.ts";
24
- import { printError, printWarning } from "../output.ts";
25
- import { jsonOk, jsonError, printJson } from "../json-envelope.ts";
26
- import { VERSION } from "../version.ts";
27
-
28
- export type BundleArtifact = "case-study" | "export" | "diagnose";
29
-
30
- export interface ReportBundleOptions {
31
- /** "A..B" range, "A,B,C" list, or unused when sessionId is set. */
32
- range?: string;
33
- /** Resolve runs by session_id instead of explicit ids. */
34
- sessionId?: string;
35
- output?: string;
36
- include?: BundleArtifact[];
37
- bodyCapBytes?: number;
38
- dbPath?: string;
39
- json?: boolean;
40
- }
41
-
42
- const DEFAULT_BODY_CAP_BYTES = 8192;
43
- const ALL_ARTIFACTS: BundleArtifact[] = ["case-study", "export", "diagnose"];
44
-
45
- interface BundleEntry {
46
- runId: number;
47
- spec: string | null;
48
- totals: { total: number; passed: number; failed: number; skipped: number };
49
- caseStudy?: string;
50
- htmlReport?: string;
51
- diagnose?: string;
52
- }
53
-
54
- export function parseBundleRange(input: string): number[] | { error: string } {
55
- const trimmed = input.trim();
56
- if (!trimmed) return { error: "empty range" };
57
-
58
- const rangeMatch = trimmed.match(/^(\d+)\.\.(\d+)$/);
59
- if (rangeMatch) {
60
- const a = parseInt(rangeMatch[1]!, 10);
61
- const b = parseInt(rangeMatch[2]!, 10);
62
- if (a > b) return { error: `range start ${a} is greater than end ${b}` };
63
- const out: number[] = [];
64
- for (let i = a; i <= b; i++) out.push(i);
65
- return out;
66
- }
67
-
68
- if (trimmed.includes(",")) {
69
- const parts = trimmed.split(",").map(s => s.trim()).filter(Boolean);
70
- const ids: number[] = [];
71
- for (const p of parts) {
72
- const n = parseInt(p, 10);
73
- if (!Number.isFinite(n) || n <= 0) return { error: `not a positive integer: ${p}` };
74
- ids.push(n);
75
- }
76
- return Array.from(new Set(ids)).sort((a, b) => a - b);
77
- }
78
-
79
- const n = parseInt(trimmed, 10);
80
- if (!Number.isFinite(n) || n <= 0) return { error: `not a recognised range: ${trimmed}` };
81
- return [n];
82
- }
83
-
84
- export async function reportBundleCommand(options: ReportBundleOptions): Promise<number> {
85
- try {
86
- getDb(options.dbPath);
87
- } catch (err) {
88
- const msg = `Failed to open database: ${(err as Error).message}`;
89
- if (options.json) printJson(jsonError("report bundle", [msg]));
90
- else printError(msg);
91
- return 2;
92
- }
93
-
94
- let runIds: number[];
95
- if (options.sessionId) {
96
- runIds = listRunIdsBySession(options.sessionId);
97
- if (runIds.length === 0) {
98
- const msg = `No runs found for --session ${options.sessionId}`;
99
- if (options.json) printJson(jsonError("report bundle", [msg]));
100
- else printError(msg);
101
- return 1;
102
- }
103
- } else {
104
- if (!options.range) {
105
- const msg = "report bundle requires <range> (A..B / A,B,C) or --session <id>";
106
- if (options.json) printJson(jsonError("report bundle", [msg]));
107
- else printError(msg);
108
- return 2;
109
- }
110
- const parsed = parseBundleRange(options.range);
111
- if (!Array.isArray(parsed)) {
112
- const msg = `Invalid range: ${parsed.error}. Examples: 135..142, 135,137,141`;
113
- if (options.json) printJson(jsonError("report bundle", [msg]));
114
- else printError(msg);
115
- return 2;
116
- }
117
- runIds = parsed;
118
- }
119
-
120
- const include = options.include && options.include.length > 0 ? options.include : ALL_ARTIFACTS;
121
- const outDir = options.output ?? join("triage", "bundle", new Date().toISOString().replace(/[:.]/g, "-"));
122
- await mkdir(outDir, { recursive: true });
123
-
124
- const entries: BundleEntry[] = [];
125
- const skipped: Array<{ runId: number; reason: string }> = [];
126
- const bodyCap = options.bodyCapBytes ?? DEFAULT_BODY_CAP_BYTES;
127
-
128
- for (const runId of runIds) {
129
- const run = getRunById(runId);
130
- if (!run) {
131
- skipped.push({ runId, reason: "not found" });
132
- continue;
133
- }
134
- const results = getResultsByRunId(runId);
135
- const runDir = join(outDir, String(runId));
136
- await mkdir(runDir, { recursive: true });
137
-
138
- const entry: BundleEntry = {
139
- runId,
140
- spec: await loadSpecTitle(run),
141
- totals: {
142
- total: run.total ?? 0,
143
- passed: run.passed ?? 0,
144
- failed: run.failed ?? 0,
145
- skipped: run.skipped ?? 0,
146
- },
147
- };
148
-
149
- if (include.includes("export")) {
150
- const html = renderHtmlReport({
151
- run,
152
- results,
153
- zondVersion: VERSION,
154
- generatedAt: new Date(),
155
- collectionName: run.collection_id != null ? getCollectionById(run.collection_id)?.name ?? null : null,
156
- bodyCapBytes: bodyCap,
157
- });
158
- const file = join(runDir, "report.html");
159
- await Bun.write(file, html);
160
- entry.htmlReport = file;
161
- }
162
-
163
- if (include.includes("case-study")) {
164
- const failure = pickPrimaryFailure(results);
165
- if (failure) {
166
- const specDoc = await loadSpecDoc(run);
167
- const md = applySanitizer(renderCaseStudy({
168
- result: failure,
169
- run,
170
- specTitle: entry.spec,
171
- specVersion: null,
172
- zondVersion: VERSION,
173
- bodyCapBytes: bodyCap,
174
- apiName: collectionApiName(run),
175
- specDoc: specDoc as Parameters<typeof renderCaseStudy>[0]["specDoc"],
176
- }));
177
- const file = join(runDir, "case-study.md");
178
- await Bun.write(file, md);
179
- entry.caseStudy = file;
180
- }
181
- }
182
-
183
- if (include.includes("diagnose")) {
184
- const diag = diagnoseRun(runId, false, options.dbPath, 5);
185
- const file = join(runDir, "diagnose.json");
186
- await Bun.write(file, JSON.stringify(diag, null, 2));
187
- entry.diagnose = file;
188
- }
189
-
190
- entries.push(entry);
191
- }
192
-
193
- if (entries.length === 0) {
194
- const msg = `No runs in [${runIds.join(", ")}] resolved to existing rows`;
195
- if (options.json) printJson(jsonError("report bundle", [msg]));
196
- else printError(msg);
197
- return 1;
198
- }
199
-
200
- const indexPath = join(outDir, "index.md");
201
- await Bun.write(indexPath, renderIndex(entries, skipped));
202
-
203
- if (options.json) {
204
- printJson(
205
- jsonOk("report bundle", {
206
- outputDir: outDir,
207
- index: indexPath,
208
- entries: entries.map(e => ({
209
- runId: e.runId,
210
- spec: e.spec,
211
- totals: e.totals,
212
- caseStudy: e.caseStudy ?? null,
213
- htmlReport: e.htmlReport ?? null,
214
- diagnose: e.diagnose ?? null,
215
- })),
216
- skipped,
217
- }),
218
- );
219
- } else {
220
- if (skipped.length > 0) {
221
- for (const s of skipped) printWarning(`Run #${s.runId} skipped: ${s.reason}`);
222
- }
223
- // TASK-241: status → stderr; stdout carries only the bundle dir path.
224
- process.stderr.write(`zond: bundle written (${entries.length} run(s), index: ${indexPath})\n`,);
225
- process.stdout.write(`${outDir}\n`);
226
- }
227
- return 0;
228
- }
229
-
230
- function listRunIdsBySession(sessionId: string): number[] {
231
- const db = getDb();
232
- const rows = db.query("SELECT id FROM runs WHERE session_id = ? ORDER BY started_at ASC")
233
- .all(sessionId) as Array<{ id: number }>;
234
- return rows.map(r => r.id);
235
- }
236
-
237
- async function loadSpecTitle(run: RunRecord): Promise<string | null> {
238
- if (run.collection_id == null) return null;
239
- const collection = getCollectionById(run.collection_id);
240
- if (!collection?.openapi_spec) return collection?.name ?? null;
241
- try {
242
- const doc = await readOpenApiSpec(resolveCollectionSpec(collection.openapi_spec));
243
- return doc.info?.title ?? collection.name ?? null;
244
- } catch {
245
- return collection.name ?? null;
246
- }
247
- }
248
-
249
- /** ARV-107: load the parsed spec document for the run's collection so the
250
- * case-study renderer can auto-extract the operation slice. */
251
- async function loadSpecDoc(run: RunRecord): Promise<unknown | null> {
252
- if (run.collection_id == null) return null;
253
- const collection = getCollectionById(run.collection_id);
254
- if (!collection?.openapi_spec) return null;
255
- try {
256
- return await readOpenApiSpec(resolveCollectionSpec(collection.openapi_spec));
257
- } catch {
258
- return null;
259
- }
260
- }
261
-
262
- /** ARV-106/107: short registry slug (`--api <name>` form) for the run's
263
- * collection, used to fill the case-study `apiName` option. */
264
- function collectionApiName(run: RunRecord): string | null {
265
- if (run.collection_id == null) return null;
266
- return getCollectionById(run.collection_id)?.name ?? null;
267
- }
268
-
269
- function pickPrimaryFailure(results: StoredStepResult[]): StoredStepResult | null {
270
- // Prefer a result classified as a real bug.
271
- const bugFirst = results.find(
272
- r => r.status !== "pass" && (r.failure_class === "definitely_bug" || r.failure_class === "likely_bug"),
273
- );
274
- if (bugFirst) return bugFirst;
275
- return results.find(r => r.status === "fail" || r.status === "5xx") ?? null;
276
- }
277
-
278
- function renderIndex(entries: BundleEntry[], skipped: Array<{ runId: number; reason: string }>): string {
279
- const lines: string[] = [];
280
- lines.push("# Bundle index", "");
281
- lines.push(`Generated: ${new Date().toISOString()}`);
282
- lines.push(`Runs: ${entries.length}` + (skipped.length > 0 ? ` (skipped: ${skipped.length})` : ""));
283
- lines.push("");
284
- lines.push("| Run | Spec | Total | Pass | Fail | Skip | Artefacts |");
285
- lines.push("|----:|------|------:|-----:|-----:|-----:|-----------|");
286
-
287
- for (const e of entries) {
288
- const links: string[] = [];
289
- if (e.caseStudy) links.push(`[case-study](${rel(e.caseStudy)})`);
290
- if (e.htmlReport) links.push(`[html](${rel(e.htmlReport)})`);
291
- if (e.diagnose) links.push(`[diagnose](${rel(e.diagnose)})`);
292
- lines.push(
293
- `| ${e.runId} | ${e.spec ?? "—"} | ${e.totals.total} | ${e.totals.passed} | ${e.totals.failed} | ${e.totals.skipped} | ${links.join(" · ") || "—"} |`,
294
- );
295
- }
296
-
297
- if (skipped.length > 0) {
298
- lines.push("", "## Skipped", "");
299
- for (const s of skipped) lines.push(`- run #${s.runId} — ${s.reason}`);
300
- }
301
- return lines.join("\n") + "\n";
302
- }
303
-
304
- function rel(p: string): string {
305
- // Index lives at <dir>/index.md, run files at <dir>/<id>/<file> — strip the
306
- // shared parent so relative links still work after the dir is moved.
307
- const seg = p.split(/[/\\]/);
308
- const tail = seg.slice(-2);
309
- return tail.join("/");
310
- }