@kirrosh/zond 0.26.1 → 0.27.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 (261) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/README.md +22 -21
  3. package/bin/zond.mjs +23 -0
  4. package/package.json +13 -16
  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,548 +0,0 @@
1
- import { sendAdHocRequest } from "../../core/runner/send-request.ts";
2
- import { printError, printSuccess, printWarning } from "../output.ts";
3
- import { jsonOk, jsonError, printJson, zerr } from "../json-envelope.ts";
4
- import { existsSync, readdirSync } from "node:fs";
5
- import { join } from "node:path";
6
- import { createSchemaValidator } from "../../core/runner/schema-validator.ts";
7
- import { readOpenApiSpec, extractEndpoints } from "../../core/generator/openapi-reader.ts";
8
- import { resolveCollectionSpec } from "../../core/setup-api.ts";
9
- import { findCollectionByNameOrId } from "../../db/queries.ts";
10
- import { getDb } from "../../db/schema.ts";
11
- import type { AssertionResult } from "../../core/runner/types.ts";
12
- import { applyEnvWrites } from "./fixtures.ts";
13
-
14
- // TASK-272: when the request fails authentication (401/403) and the user
15
- // did NOT pass `--api <name>`, surface a one-liner pointing at auto-auth via
16
- // `apis/<name>/.secrets.yaml`. Only fires if an apis/ workspace exists in cwd
17
- // (otherwise the hint is irrelevant). Also triggered when the headers contain a
18
- // literal unexpanded shell-substitution shape ($(…) or `…`) — a tell-tale of a
19
- // blocked-by-sandbox manual auth attempt.
20
- function detectApisWorkspace(cwd: string): string[] {
21
- const apisDir = join(cwd, "apis");
22
- if (!existsSync(apisDir)) return [];
23
- try {
24
- return readdirSync(apisDir, { withFileTypes: true })
25
- .filter((d) => d.isDirectory())
26
- .map((d) => d.name);
27
- } catch {
28
- return [];
29
- }
30
- }
31
-
32
- function looksLikeBlockedShellSubstitution(s: string | undefined): boolean {
33
- if (!s) return false;
34
- // unexpanded `$(...)` or backtick `...` with a likely secret-fetching command
35
- return /\$\([^)]+\)|`[^`]+`/.test(s) && /yq|cat|jq|grep|awk|sed|sh /.test(s);
36
- }
37
-
38
- /** ARV-110 / ARV-144: pretty-print --json-path failure to stderr.
39
- * Two distinct hints depending on the failure:
40
- * - top-level array (reason starts with "expected an array index"):
41
- * user wrote `data[0].id` against a body that's already an array →
42
- * suggest `[0].id` / `0.id`.
43
- * - envelope confusion (firstSeg in body/data, resolved is empty):
44
- * user came from `--json | jq .data.body.id` and forgot that --json-path
45
- * addresses the response body, not the envelope. */
46
- function printJsonPathDiagnostic(
47
- jsonPath: string | undefined,
48
- diag: { resolved: string[]; failedAt?: string; reason?: string } | undefined,
49
- ): void {
50
- if (!jsonPath || !diag?.failedAt) return;
51
- const resolved = diag.resolved.length > 0 ? diag.resolved.join(".") : "(root)";
52
- process.stderr.write(
53
- `zond: --json-path '${jsonPath}' did not resolve — stopped at segment "${diag.failedAt}" after ${resolved}: ${diag.reason ?? "unknown"}\n`,
54
- );
55
- const firstSeg = jsonPath.replace(/\[\d+\]/g, "").split(".")[0];
56
- const isArrayMismatch = diag.resolved.length === 0 && /^expected an array index/.test(diag.reason ?? "");
57
- if (isArrayMismatch) {
58
- const tail = jsonPath.replace(/^[^.[]+/, "");
59
- const suggestion = tail ? `[0]${tail.startsWith(".") || tail.startsWith("[") ? tail : "." + tail}` : "[0]";
60
- process.stderr.write(
61
- ` Hint: response body is a top-level array — use \`--json-path '${suggestion}'\` or \`--json-path '0${tail}'\` to index it.\n`,
62
- );
63
- return;
64
- }
65
- if ((firstSeg === "body" || firstSeg === "data") && diag.resolved.length === 0) {
66
- process.stderr.write(
67
- ` Hint: --json-path extracts from the response body, not the zond envelope. ` +
68
- `To address the envelope's data.body.id, use \`--json\` and pipe to jq.\n`,
69
- );
70
- }
71
- }
72
-
73
- function authHintLines(apis: string[]): string[] {
74
- const example = apis[0] ?? "<name>";
75
- return [
76
- `Hint: pass \`--api ${example}\` to auto-load Authorization from apis/${example}/.secrets.yaml`,
77
- ` (avoids manual "$(yq ...)" shell substitution and keeps secrets out of shell history).`,
78
- ];
79
- }
80
-
81
- export interface RequestOptions {
82
- method: string;
83
- url: string;
84
- headers?: string[];
85
- body?: string;
86
- timeout?: number;
87
- env?: string;
88
- api?: string;
89
- jsonPath?: string;
90
- /** ARV-355: write the --json-path scalar into apis/<api>/.env.yaml as this
91
- * var, so a POST-create's returned id lands in a fixture in one command
92
- * (the "execute create+capture" primitive of the agent seed loop). */
93
- capture?: string;
94
- dbPath?: string;
95
- json?: boolean;
96
- /** TASK-142: validate the response body against the OpenAPI response schema. */
97
- validateSchema?: boolean;
98
- /** TASK-142: explicit "METHOD:/path" override when path-templating heuristics
99
- * fail or the user wants to validate against a different endpoint. */
100
- validateAgainst?: string;
101
- /** ARV-149: send the body as `application/x-www-form-urlencoded` (Stripe v1
102
- * style). When omitted but `--api` is set, zond auto-detects from the
103
- * spec's requestBody.content. */
104
- form?: boolean;
105
- }
106
-
107
- interface SchemaValidationOutcome {
108
- status: "PASS" | "FAIL" | "no-spec" | "no-endpoint" | "no-schema";
109
- matchedEndpoint: { method: string; path: string } | null;
110
- matchedResponseStatus: string | null;
111
- errors: AssertionResult[];
112
- message?: string;
113
- }
114
-
115
- export async function requestCommand(options: RequestOptions): Promise<number> {
116
- try {
117
- // ARV-355: --capture needs a value to extract (--json-path) and a target
118
- // .env.yaml (--api). Fail fast with an actionable message rather than
119
- // silently no-op'ing mid-seed-loop.
120
- if (options.capture && (!options.jsonPath || !options.api)) {
121
- printError(
122
- "--capture requires --json-path <path> (the field to extract) and --api <name> " +
123
- "(the .env.yaml to write). E.g. `zond request POST /v1/accounts --api stripe " +
124
- "--json-path id --capture account`.",
125
- );
126
- return 2;
127
- }
128
-
129
- const headers: Record<string, string> = {};
130
- if (options.headers) {
131
- for (const h of options.headers) {
132
- const colonIdx = h.indexOf(":");
133
- if (colonIdx > 0) {
134
- headers[h.slice(0, colonIdx).trim()] = h.slice(colonIdx + 1).trim();
135
- }
136
- }
137
- }
138
-
139
- // ARV-149: when --form is not set but --api is, peek at the spec to see
140
- // whether the matching endpoint declares only application/x-www-form-urlencoded
141
- // (Stripe v1 pattern). If so, default to form encoding so users don't get
142
- // a 400 "wrong content type" on every POST against form-only APIs.
143
- let useForm = options.form === true;
144
- if (!useForm && options.api) {
145
- useForm = await detectFormFromSpec(options).catch(() => false);
146
- }
147
-
148
- const result = await sendAdHocRequest({
149
- method: options.method.toUpperCase(),
150
- url: options.url,
151
- headers: Object.keys(headers).length > 0 ? headers : undefined,
152
- body: options.body,
153
- timeout: options.timeout,
154
- envName: options.env,
155
- collectionName: options.api,
156
- jsonPath: options.jsonPath,
157
- dbPath: options.dbPath,
158
- form: useForm,
159
- });
160
-
161
- // ARV-265 (B3): persist this ad-hoc call into runs/results when a
162
- // session is active, so `zond coverage --scope audit` attributes it.
163
- // No session → no DB write (mirrors `curl`-replacement intent).
164
- await maybePersistAuditedRequest({
165
- options,
166
- method: options.method.toUpperCase(),
167
- url: options.url,
168
- headers,
169
- body: options.body,
170
- result,
171
- }).catch((err) => {
172
- process.stderr.write(`zond: audit persistence failed (${(err as Error).message}).\n`);
173
- });
174
-
175
- let validation: SchemaValidationOutcome | null = null;
176
- if (options.validateSchema || options.validateAgainst) {
177
- validation = await runSchemaValidation(options, result);
178
- }
179
-
180
- if (options.json) {
181
- printJson(jsonOk("request", validation ? { ...result, schema_validation: validation } : result));
182
- // ARV-110: surface jsonPath diagnostic on stderr in --json mode too, so
183
- // pipelines that read envelope from stdout still see *why* `body` came
184
- // back null. Without this, the only signal was a silent null inside the
185
- // envelope — easy to misread as "envelope shape differs between modes".
186
- printJsonPathDiagnostic(options.jsonPath, result.jsonPathDiagnostic);
187
- } else if (options.jsonPath) {
188
- // TASK-133: pipe-friendly mode — print only the extracted value.
189
- // Scalars (string/number/bool) emit verbatim with no JSON quoting so
190
- // shells can use the output directly (e.g. `id=$(zond request … --json-path data.id)`).
191
- // null/undefined → empty line. Objects/arrays → compact JSON.
192
- const v = result.body;
193
- if (v === null || v === undefined) {
194
- console.log("");
195
- printJsonPathDiagnostic(options.jsonPath, result.jsonPathDiagnostic);
196
- } else if (typeof v === "string" || typeof v === "number" || typeof v === "boolean") {
197
- console.log(String(v));
198
- } else {
199
- console.log(JSON.stringify(v));
200
- }
201
- if (validation) printSchemaValidation(validation);
202
- } else {
203
- console.log(JSON.stringify(result, null, 2));
204
- if (validation) printSchemaValidation(validation);
205
- }
206
-
207
- // ARV-355: create+capture. Write the extracted json-path scalar into the
208
- // api's .env.yaml so the agent seed loop can chain a created id into
209
- // dependent fixtures with one command. Deterministic plumbing only — the
210
- // agent decides the body/endpoint/var; zond just POSTs and captures.
211
- // Gated to a 2xx response (capturing an id from an error body is a bug —
212
- // the agent reads the note, revises the body, and retries).
213
- if (options.capture) {
214
- const v = result.body;
215
- const ok2xx = result.status >= 200 && result.status < 300;
216
- const scalar =
217
- typeof v === "string" || typeof v === "number" || typeof v === "boolean" ? String(v) : null;
218
- if (!ok2xx || scalar === null || scalar.length === 0) {
219
- process.stderr.write(
220
- `zond: --capture ${options.capture} skipped — need a non-empty scalar from a 2xx response ` +
221
- `(status=${result.status}, --json-path '${options.jsonPath}' → ${scalar === null ? "non-scalar/null" : "empty"}). ` +
222
- `Revise the request and retry.\n`,
223
- );
224
- } else {
225
- const envPath = join(`apis/${options.api}`, ".env.yaml");
226
- const { backup } = await applyEnvWrites(envPath, { [options.capture]: scalar });
227
- process.stderr.write(
228
- `zond: captured ${options.capture}=${scalar} → ${envPath}` +
229
- (backup ? ` (backup: ${backup})` : "") + "\n",
230
- );
231
- }
232
- }
233
-
234
- // TASK-272: post-response auto-auth hint on 401/403 without --api
235
- if (
236
- !options.json
237
- && (result.status === 401 || result.status === 403)
238
- && !options.api
239
- ) {
240
- const apis = detectApisWorkspace(process.cwd());
241
- if (apis.length > 0) {
242
- for (const line of authHintLines(apis)) console.error(line);
243
- }
244
- }
245
- if (validation && validation.status === "FAIL") return 1;
246
- return 0;
247
- } catch (err) {
248
- const message = err instanceof Error ? err.message : String(err);
249
- if (options.json) {
250
- const code = /not registered/.test(message) ? "api_not_registered" : "unknown_error";
251
- printJson(jsonError("request", [zerr(code, message)]));
252
- } else {
253
- printError(message);
254
- // TASK-272: if the failure is shaped like blocked shell-substitution in
255
- // body/header (sandbox refused to expand `$(yq ...)`), point users at
256
- // `--api <name>` auto-auth instead.
257
- const headerBlob = (options.headers ?? []).join("\n");
258
- if (
259
- !options.api
260
- && (looksLikeBlockedShellSubstitution(options.body) || looksLikeBlockedShellSubstitution(headerBlob))
261
- ) {
262
- const apis = detectApisWorkspace(process.cwd());
263
- if (apis.length > 0) {
264
- for (const line of authHintLines(apis)) console.error(line);
265
- }
266
- }
267
- }
268
- return 1;
269
- }
270
- }
271
-
272
- // ──────────────────────────────────────────────
273
- // ARV-265 (B3): persist an ad-hoc `zond request` call into runs/results
274
- // so `zond coverage --scope audit` sees the HTTP touch. Only fires when
275
- // a session is active — outside a session, the command stays a pure
276
- // curl-replacement and the DB doesn't grow with one-off requests.
277
- // ──────────────────────────────────────────────
278
-
279
- async function maybePersistAuditedRequest(args: {
280
- options: RequestOptions;
281
- method: string;
282
- url: string;
283
- headers: Record<string, string>;
284
- body: string | undefined;
285
- result: { status: number; headers: Record<string, string>; body: unknown; duration_ms: number };
286
- }): Promise<void> {
287
- const { readCurrentSession } = await import("../../core/context/session.ts");
288
- const session = readCurrentSession();
289
- if (!session) return; // B3: outside-session calls leave no trace.
290
-
291
- const { checksPersistEnabled, beginAuditRun, finalizeAuditRun } =
292
- await import("../../core/audit/persist.ts");
293
- if (!checksPersistEnabled()) return;
294
-
295
- getDb(args.options.dbPath);
296
- const collectionId = args.options.api ? findCollectionByNameOrId(args.options.api)?.id : undefined;
297
- const runId = beginAuditRun({
298
- runKind: "request",
299
- ...(collectionId != null ? { collectionId } : {}),
300
- sessionId: session.id,
301
- tags: ["request", "ad-hoc"],
302
- });
303
- const status = args.result.status >= 200 && args.result.status < 400 ? "pass" : "fail";
304
- finalizeAuditRun(runId, [
305
- {
306
- suiteName: "request/ad-hoc",
307
- suiteFile: `apis/${args.options.api ?? "_"}/request.yaml`,
308
- testName: `request::${args.method} ${args.url}`,
309
- status,
310
- request: { method: args.method, url: args.url, headers: args.headers, body: args.body },
311
- response: {
312
- status: args.result.status,
313
- headers: args.result.headers,
314
- body: typeof args.result.body === "string" ? args.result.body : JSON.stringify(args.result.body ?? ""),
315
- duration_ms: args.result.duration_ms,
316
- },
317
- durationMs: args.result.duration_ms,
318
- },
319
- ]);
320
- }
321
-
322
- // ──────────────────────────────────────────────
323
- // TASK-142: --validate-schema / --validate-against
324
- // ──────────────────────────────────────────────
325
-
326
- async function runSchemaValidation(
327
- options: RequestOptions,
328
- result: { status: number; body: unknown },
329
- ): Promise<SchemaValidationOutcome> {
330
- if (!options.api) {
331
- return {
332
- status: "no-spec",
333
- matchedEndpoint: null,
334
- matchedResponseStatus: null,
335
- errors: [],
336
- message: "schema validation requires --api <name> (the spec is loaded from the registered collection)",
337
- };
338
- }
339
-
340
- getDb(options.dbPath);
341
- const col = findCollectionByNameOrId(options.api);
342
- if (!col?.openapi_spec) {
343
- return {
344
- status: "no-spec",
345
- matchedEndpoint: null,
346
- matchedResponseStatus: null,
347
- errors: [],
348
- message: `collection '${options.api}' has no openapi_spec — register one with \`zond add api ${options.api} --spec <path>\``,
349
- };
350
- }
351
-
352
- let doc;
353
- try {
354
- doc = await readOpenApiSpec(resolveCollectionSpec(col.openapi_spec));
355
- } catch (err) {
356
- return {
357
- status: "no-spec",
358
- matchedEndpoint: null,
359
- matchedResponseStatus: null,
360
- errors: [],
361
- message: `failed to load OpenAPI spec: ${(err as Error).message}`,
362
- };
363
- }
364
-
365
- let method: string;
366
- let path: string;
367
- if (options.validateAgainst) {
368
- const parsed = parseMethodPathArg(options.validateAgainst);
369
- if (!parsed) {
370
- return {
371
- status: "no-endpoint",
372
- matchedEndpoint: null,
373
- matchedResponseStatus: null,
374
- errors: [],
375
- message: `--validate-against expects "METHOD:/path" (e.g. "GET:/users/{id}"), got: ${options.validateAgainst}`,
376
- };
377
- }
378
- method = parsed.method;
379
- path = parsed.path;
380
- } else {
381
- method = options.method.toUpperCase();
382
- path = extractPath(options.url);
383
- }
384
-
385
- const validator = createSchemaValidator(doc);
386
- const inspect = validator.inspect(method, path, result.status);
387
-
388
- if (!inspect.matchedEndpoint) {
389
- return {
390
- status: "no-endpoint",
391
- matchedEndpoint: null,
392
- matchedResponseStatus: null,
393
- errors: [],
394
- message: `no spec endpoint matches ${method} ${path}. Pass \`--validate-against "METHOD:/path"\` (use spec template form, e.g. "GET:/users/{id}") to override.`,
395
- };
396
- }
397
- if (!inspect.hasJsonSchema) {
398
- return {
399
- status: "no-schema",
400
- matchedEndpoint: inspect.matchedEndpoint,
401
- matchedResponseStatus: inspect.matchedResponseStatus,
402
- errors: [],
403
- message: `endpoint ${inspect.matchedEndpoint.method} ${inspect.matchedEndpoint.path} has no application/json schema for status ${result.status} (matched branch: ${inspect.matchedResponseStatus ?? "none"})`,
404
- };
405
- }
406
-
407
- const errors = validator.validate(method, path, result.status, result.body);
408
- return {
409
- status: errors.length === 0 ? "PASS" : "FAIL",
410
- matchedEndpoint: inspect.matchedEndpoint,
411
- matchedResponseStatus: inspect.matchedResponseStatus,
412
- errors,
413
- };
414
- }
415
-
416
- function printSchemaValidation(v: SchemaValidationOutcome): void {
417
- const ep = v.matchedEndpoint ? `${v.matchedEndpoint.method} ${v.matchedEndpoint.path}` : "—";
418
- const branch = v.matchedResponseStatus ?? "—";
419
- console.log("");
420
- console.log(`Schema validation: ${v.status}`);
421
- console.log(` endpoint: ${ep}`);
422
- console.log(` response branch: ${branch}`);
423
- if (v.message) console.log(` ${v.message}`);
424
- if (v.status === "FAIL") {
425
- for (const e of v.errors) {
426
- console.log(` • ${e.field} — ${e.rule}: ${e.expected}`);
427
- }
428
- }
429
- if (v.status === "no-endpoint" || v.status === "no-spec" || v.status === "no-schema") {
430
- printWarning(v.message ?? `validation skipped: ${v.status}`);
431
- } else if (v.status === "PASS") {
432
- printSuccess("response body matches the response schema");
433
- }
434
- }
435
-
436
- function parseMethodPathArg(raw: string): { method: string; path: string } | null {
437
- const m = raw.match(/^\s*([A-Za-z]+)\s*[: ]\s*(\/.*?)\s*$/);
438
- if (!m) return null;
439
- return { method: m[1]!.toUpperCase(), path: m[2]! };
440
- }
441
-
442
- /** ARV-149: peek at the OpenAPI spec for the matching endpoint and return
443
- * true when its requestBody declares only application/x-www-form-urlencoded
444
- * (no JSON variant). Cheap-failing — any spec/db error returns false so the
445
- * caller falls back to the JSON default. */
446
- async function detectFormFromSpec(options: RequestOptions): Promise<boolean> {
447
- if (!options.api || !options.body) return false;
448
- getDb(options.dbPath);
449
- const col = findCollectionByNameOrId(options.api);
450
- if (!col?.openapi_spec) return false;
451
- const doc = await readOpenApiSpec(resolveCollectionSpec(col.openapi_spec));
452
- const endpoints = extractEndpoints(doc);
453
- const method = options.method.toUpperCase();
454
- const path = extractPath(options.url);
455
- // The OpenAPI reader normalises requestBodyContentType (prefers JSON when
456
- // present, otherwise records the first declared content type). For a true
457
- // form-only endpoint that field is "application/x-www-form-urlencoded".
458
- const exact = endpoints.find(e => e.method.toUpperCase() === method && e.path === path);
459
- const matched = exact ?? endpoints.find(e => {
460
- if (e.method.toUpperCase() !== method) return false;
461
- const re = new RegExp(
462
- "^" + e.path.replace(/\{[^}]+\}/g, "[^/]+").replace(/\//g, "\\/") + "$",
463
- );
464
- return re.test(path);
465
- });
466
- return matched?.requestBodyContentType === "application/x-www-form-urlencoded";
467
- }
468
-
469
- function extractPath(url: string): string {
470
- // Absolute URL → use URL parser. Relative URL ("/users/1") → use as-is.
471
- if (/^https?:\/\//i.test(url)) {
472
- try {
473
- return new URL(url).pathname;
474
- } catch {
475
- return url;
476
- }
477
- }
478
- // Strip query string from relative paths.
479
- const q = url.indexOf("?");
480
- return q >= 0 ? url.slice(0, q) : url;
481
- }
482
-
483
- import type { Command } from "commander";
484
- import { globalJson } from "../resolve.ts";
485
- import { collect, parsePositiveInt } from "../argv.ts";
486
- import { getApi } from "../util/api-context.ts";
487
- import { loadEnvMeta } from "../../core/parser/variables.ts";
488
- import { resolveTimeoutMs } from "../../core/workspace/config.ts";
489
-
490
- export function registerRequest(program: Command): void {
491
- program
492
- .command("request <method> <url>")
493
- .description("Send an ad-hoc HTTP request")
494
- .option("--header <H>", `Request header "Name: Value" (repeatable)`, collect, [])
495
- .option("--body <json>", "Request body (JSON string)")
496
- .option("--timeout <ms>", "Request timeout (overrides apis/<name>/.env.yaml `timeoutMs` and zond.config.yml `defaults.timeout_ms`; default 30000)", parsePositiveInt("--timeout"))
497
- .option("--env <name>", "Environment for variable interpolation")
498
- .option("--api <name>", "Collection name; auto-loads env + Authorization from apis/<name>/.secrets.yaml")
499
- .option(
500
- "--json-path <path>",
501
- "Extract one field from the RESPONSE BODY (not the zond envelope; " +
502
- "to address envelope.data.body.id pipe `--json` through jq instead). " +
503
- "Dot notation, e.g. 'data.id', 'items[0].name'. For top-level array " +
504
- "responses use '[0].id' or '0.id'. Without --json, prints " +
505
- "the value verbatim — scalars without quotes for shell use " +
506
- "(`id=$(zond request --json-path data.id ...)`), objects/arrays as compact JSON. " +
507
- "With --json, embeds the extracted value as the envelope's `body` field.",
508
- )
509
- .option(
510
- "--capture <var>",
511
- "ARV-355: write the --json-path scalar into apis/<api>/.env.yaml as <var> " +
512
- "(requires --json-path and --api). Captures a POST-create's returned id into " +
513
- "a fixture in one command, so the agent seed loop can chain dependent creates. " +
514
- "Only writes on a 2xx response; a .env.yaml.bak backup is made.",
515
- )
516
- .option("--db <path>", "Path to SQLite database file")
517
- .option("--validate-schema", "TASK-142: validate the response body against the OpenAPI response schema (requires --api). Endpoint is auto-resolved from the request method + URL.path; templated paths like /users/{id} are matched via regex. Falls back gracefully if no endpoint matches — pass --validate-against to override.")
518
- .option("--validate-against <method:path>", "TASK-142: explicit endpoint override for --validate-schema, e.g. \"GET:/users/{id}\". Use the spec template form (with \"{...}\" placeholders).")
519
- .option("--form", "ARV-149: send --body as application/x-www-form-urlencoded (Stripe v1, Rails/PHP-style APIs). Parses --body as JSON to lift fields, re-encodes with bracket notation. Auto-detected when --api is set and the spec endpoint declares only the form content type.")
520
- .action(async (method: string, url: string, opts, cmd: Command) => {
521
- const headers = (opts.header as string[] | undefined)?.length ? (opts.header as string[]) : undefined;
522
- // ARV-53.
523
- const api = getApi(cmd, opts);
524
- let envTimeout: number | undefined;
525
- if (api) {
526
- try {
527
- envTimeout = (await loadEnvMeta(opts.env, `apis/${api}`)).timeoutMs;
528
- } catch { /* meta is best-effort */ }
529
- }
530
- const timeout = resolveTimeoutMs(opts.timeout, envTimeout);
531
- process.exitCode = await requestCommand({
532
- method,
533
- url,
534
- headers,
535
- body: opts.body,
536
- timeout,
537
- env: opts.env,
538
- api,
539
- jsonPath: opts.jsonPath,
540
- capture: opts.capture,
541
- dbPath: opts.db,
542
- json: globalJson(cmd),
543
- validateSchema: opts.validateSchema === true || typeof opts.validateAgainst === "string",
544
- validateAgainst: opts.validateAgainst,
545
- form: opts.form === true,
546
- });
547
- });
548
- }