@kirrosh/zond 0.22.0 → 0.26.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 (282) hide show
  1. package/CHANGELOG.md +811 -0
  2. package/README.md +59 -6
  3. package/package.json +9 -7
  4. package/src/CLAUDE.md +112 -0
  5. package/src/cli/argv.ts +122 -0
  6. package/src/cli/commands/add-api.ts +146 -0
  7. package/src/cli/commands/api/annotate/idempotency.ts +59 -0
  8. package/src/cli/commands/api/annotate/index.ts +880 -0
  9. package/src/cli/commands/api/annotate/lifecycle.ts +74 -0
  10. package/src/cli/commands/api/annotate/overlay.ts +206 -0
  11. package/src/cli/commands/api/annotate/pagination.ts +64 -0
  12. package/src/cli/commands/api/annotate/prompts.ts +220 -0
  13. package/src/cli/commands/api/annotate/readback.ts +58 -0
  14. package/src/cli/commands/api/annotate/resources.ts +91 -0
  15. package/src/cli/commands/api/annotate/seed-bodies.ts +61 -0
  16. package/src/cli/commands/audit.ts +786 -0
  17. package/src/cli/commands/catalog.ts +35 -0
  18. package/src/cli/commands/check.ts +361 -0
  19. package/src/cli/commands/checks.ts +1072 -0
  20. package/src/cli/commands/ci-init.ts +43 -0
  21. package/src/cli/commands/clean.ts +212 -0
  22. package/src/cli/commands/cleanup.ts +236 -0
  23. package/src/cli/commands/completions.ts +16 -0
  24. package/src/cli/commands/coverage.ts +823 -132
  25. package/src/cli/commands/db.ts +486 -12
  26. package/src/cli/commands/describe.ts +37 -2
  27. package/src/cli/commands/discover.ts +1356 -0
  28. package/src/cli/commands/doctor.ts +661 -0
  29. package/src/cli/commands/fixtures.ts +402 -0
  30. package/src/cli/commands/generate.ts +438 -47
  31. package/src/cli/commands/init/bootstrap.ts +34 -2
  32. package/src/cli/commands/{init.ts → init/index.ts} +99 -5
  33. package/src/cli/commands/init/skills.ts +99 -3
  34. package/src/cli/commands/init/templates/agents.md +77 -64
  35. package/src/cli/commands/init/templates/skills/warm-up-target.md +122 -0
  36. package/src/cli/commands/init/templates/skills/zond-checks.md +621 -0
  37. package/src/cli/commands/init/templates/skills/zond-seed.md +114 -0
  38. package/src/cli/commands/init/templates/skills/zond-triage.md +272 -0
  39. package/src/cli/commands/init/templates/skills/zond.md +802 -125
  40. package/src/cli/commands/init/templates/zond-config.yml +8 -9
  41. package/src/cli/commands/prepare-fixtures.ts +97 -0
  42. package/src/cli/commands/probe/_seed-bodies.ts +52 -0
  43. package/src/cli/commands/probe/mass-assignment.ts +594 -0
  44. package/src/cli/commands/probe/security.ts +537 -0
  45. package/src/cli/commands/probe/static.ts +255 -0
  46. package/src/cli/commands/probe/webhooks.ts +163 -0
  47. package/src/cli/commands/probe.ts +535 -0
  48. package/src/cli/commands/reference.ts +87 -0
  49. package/src/cli/commands/refresh-api.ts +227 -0
  50. package/src/cli/commands/remove-api.ts +150 -0
  51. package/src/cli/commands/report-bundle.ts +310 -0
  52. package/src/cli/commands/report.ts +241 -0
  53. package/src/cli/commands/request.ts +495 -4
  54. package/src/cli/commands/run.ts +870 -53
  55. package/src/cli/commands/schema-from-runs.ts +128 -0
  56. package/src/cli/commands/secrets.ts +133 -0
  57. package/src/cli/commands/session.ts +244 -0
  58. package/src/cli/commands/use.ts +18 -1
  59. package/src/cli/index.ts +20 -3
  60. package/src/cli/json-envelope.ts +92 -3
  61. package/src/cli/json-schemas.ts +314 -0
  62. package/src/cli/output.ts +17 -1
  63. package/src/cli/program.ts +199 -635
  64. package/src/cli/resolve.ts +105 -0
  65. package/src/cli/safe-live.ts +24 -0
  66. package/src/cli/status-filter.ts +114 -0
  67. package/src/cli/util/api-context.ts +85 -0
  68. package/src/cli/version.ts +5 -0
  69. package/src/core/audit/persist.ts +183 -0
  70. package/src/core/checks/budget.ts +59 -0
  71. package/src/core/checks/checks/_crud-helpers.ts +133 -0
  72. package/src/core/checks/checks/_negative_mutator.ts +133 -0
  73. package/src/core/checks/checks/_readback-helpers.ts +133 -0
  74. package/src/core/checks/checks/content_type_conformance.ts +39 -0
  75. package/src/core/checks/checks/cross_call_references.ts +147 -0
  76. package/src/core/checks/checks/cursor_boundary_fuzzing.ts +219 -0
  77. package/src/core/checks/checks/ensure_resource_availability.ts +62 -0
  78. package/src/core/checks/checks/idempotency_replay.ts +242 -0
  79. package/src/core/checks/checks/ignored_auth.ts +254 -0
  80. package/src/core/checks/checks/index.ts +68 -0
  81. package/src/core/checks/checks/lifecycle_transitions.ts +416 -0
  82. package/src/core/checks/checks/missing_required_header.ts +40 -0
  83. package/src/core/checks/checks/negative_data_rejection.ts +148 -0
  84. package/src/core/checks/checks/not_a_server_error.ts +35 -0
  85. package/src/core/checks/checks/open_cors_on_sensitive.ts +160 -0
  86. package/src/core/checks/checks/pagination_invariants.ts +419 -0
  87. package/src/core/checks/checks/positive_data_acceptance.ts +33 -0
  88. package/src/core/checks/checks/rate_limit_headers_absent.ts +77 -0
  89. package/src/core/checks/checks/response_headers_conformance.ts +74 -0
  90. package/src/core/checks/checks/response_schema_conformance.ts +30 -0
  91. package/src/core/checks/checks/status_code_conformance.ts +132 -0
  92. package/src/core/checks/checks/unsupported_method.ts +63 -0
  93. package/src/core/checks/checks/use_after_free.ts +78 -0
  94. package/src/core/checks/index.ts +30 -0
  95. package/src/core/checks/mode.ts +82 -0
  96. package/src/core/checks/recommended-action.ts +68 -0
  97. package/src/core/checks/registry.ts +78 -0
  98. package/src/core/checks/runner.ts +1461 -0
  99. package/src/core/checks/sarif.ts +230 -0
  100. package/src/core/checks/spec-findings.ts +308 -0
  101. package/src/core/checks/stateful.ts +121 -0
  102. package/src/core/checks/types.ts +305 -0
  103. package/src/core/checks/zond-extensions.ts +73 -0
  104. package/src/core/classifier/recommended-action.ts +251 -0
  105. package/src/core/context/current.ts +22 -6
  106. package/src/core/context/session.ts +78 -0
  107. package/src/core/coverage/loader.ts +216 -0
  108. package/src/core/coverage/reasons.ts +300 -0
  109. package/src/core/diagnostics/db-analysis.ts +293 -59
  110. package/src/core/diagnostics/failure-class.ts +140 -0
  111. package/src/core/diagnostics/failure-hints.ts +88 -89
  112. package/src/core/diagnostics/spec-pointer.ts +99 -0
  113. package/src/core/diagnostics/suggested-fixes.ts +155 -0
  114. package/src/core/exporter/case-study/index.ts +270 -0
  115. package/src/core/exporter/curl.ts +40 -0
  116. package/src/core/exporter/exporter.ts +48 -0
  117. package/src/core/exporter/html-report/escape.ts +24 -0
  118. package/src/core/exporter/html-report/index.ts +479 -0
  119. package/src/core/exporter/html-report/script.ts +100 -0
  120. package/src/core/exporter/html-report/styles.ts +408 -0
  121. package/src/core/generator/chunker.ts +38 -19
  122. package/src/core/generator/coverage-phase.ts +0 -0
  123. package/src/core/generator/data-factory.ts +586 -22
  124. package/src/core/generator/describe.ts +1 -1
  125. package/src/core/generator/fixtures-builder.ts +332 -0
  126. package/src/core/generator/index.ts +5 -5
  127. package/src/core/generator/openapi-reader.ts +135 -7
  128. package/src/core/generator/path-param-disambig.ts +140 -0
  129. package/src/core/generator/resources-builder.ts +898 -0
  130. package/src/core/generator/schema-utils.ts +33 -3
  131. package/src/core/generator/serializer.ts +103 -13
  132. package/src/core/generator/suite-generator.ts +583 -122
  133. package/src/core/generator/types.ts +14 -0
  134. package/src/core/identity/identity-file.ts +0 -0
  135. package/src/core/lint/affects.ts +28 -0
  136. package/src/core/lint/config.ts +96 -0
  137. package/src/core/lint/format.ts +42 -0
  138. package/src/core/lint/index.ts +94 -0
  139. package/src/core/lint/reporter.ts +128 -0
  140. package/src/core/lint/rules/consistency.ts +158 -0
  141. package/src/core/lint/rules/heuristics.ts +97 -0
  142. package/src/core/lint/rules/strictness.ts +109 -0
  143. package/src/core/lint/types.ts +96 -0
  144. package/src/core/lint/walker.ts +248 -0
  145. package/src/core/meta/meta-store.ts +6 -73
  146. package/src/core/output/README.md +73 -0
  147. package/src/core/output/index.ts +13 -0
  148. package/src/core/output/run.ts +91 -0
  149. package/src/core/output/types.ts +122 -0
  150. package/src/core/parser/dynamic-values.ts +160 -0
  151. package/src/core/parser/env-interpolation.ts +104 -0
  152. package/src/core/parser/filter.ts +57 -0
  153. package/src/core/parser/schema.ts +129 -4
  154. package/src/core/parser/types.ts +19 -1
  155. package/src/core/parser/variables.ts +0 -0
  156. package/src/core/parser/yaml-parser.ts +58 -12
  157. package/src/core/probe/bootstrap.ts +34 -0
  158. package/src/core/probe/dry-run-envelope.ts +61 -0
  159. package/src/core/probe/mass-assignment/classify.ts +175 -0
  160. package/src/core/probe/mass-assignment/cleanup.ts +52 -0
  161. package/src/core/probe/mass-assignment/digest.ts +114 -0
  162. package/src/core/probe/mass-assignment/orchestrator.ts +459 -0
  163. package/src/core/probe/mass-assignment/regression.ts +141 -0
  164. package/src/core/probe/mass-assignment/suspects.ts +92 -0
  165. package/src/core/probe/mass-assignment/types.ts +135 -0
  166. package/src/core/probe/mass-assignment-probe-class.ts +198 -0
  167. package/src/core/probe/mass-assignment-probe.ts +27 -0
  168. package/src/core/probe/mass-assignment-template.ts +240 -0
  169. package/src/core/probe/method-probe.ts +43 -76
  170. package/src/core/probe/method-shared.ts +69 -0
  171. package/src/core/probe/negative-probe.ts +183 -149
  172. package/src/core/probe/orphan-tracker.ts +188 -0
  173. package/src/core/probe/path-discovery.ts +439 -0
  174. package/src/core/probe/probe-harness.ts +119 -0
  175. package/src/core/probe/registry.ts +89 -0
  176. package/src/core/probe/runner.ts +136 -0
  177. package/src/core/probe/security/baseline.ts +174 -0
  178. package/src/core/probe/security/classify.ts +341 -0
  179. package/src/core/probe/security/cleanup.ts +125 -0
  180. package/src/core/probe/security/detectors.ts +71 -0
  181. package/src/core/probe/security/digest.ts +104 -0
  182. package/src/core/probe/security/orchestrator.ts +398 -0
  183. package/src/core/probe/security/regression.ts +103 -0
  184. package/src/core/probe/security/types.ts +151 -0
  185. package/src/core/probe/security-probe-class.ts +207 -0
  186. package/src/core/probe/security-probe.ts +32 -0
  187. package/src/core/probe/shared.ts +531 -0
  188. package/src/core/probe/static-probe-class.ts +125 -0
  189. package/src/core/probe/types.ts +165 -0
  190. package/src/core/probe/verdict-aggregator.ts +33 -0
  191. package/src/core/probe/webhooks-probe.ts +282 -0
  192. package/src/core/reporter/console.ts +41 -2
  193. package/src/core/reporter/index.ts +2 -3
  194. package/src/core/reporter/json.ts +11 -1
  195. package/src/core/reporter/junit.ts +27 -12
  196. package/src/core/reporter/ndjson.ts +37 -0
  197. package/src/core/reporter/types.ts +3 -0
  198. package/src/core/runner/assertions.ts +59 -2
  199. package/src/core/runner/async-pool.ts +108 -0
  200. package/src/core/runner/auth-path.ts +8 -0
  201. package/src/core/runner/ci-context.ts +72 -0
  202. package/src/core/runner/executor.ts +265 -36
  203. package/src/core/runner/form-encode.ts +41 -0
  204. package/src/core/runner/http-client.ts +112 -2
  205. package/src/core/runner/learn-drift.ts +293 -0
  206. package/src/core/runner/preflight-vars.ts +153 -0
  207. package/src/core/runner/progress-tracker.ts +73 -0
  208. package/src/core/runner/rate-limiter.ts +87 -33
  209. package/src/core/runner/run-kind.ts +45 -0
  210. package/src/core/runner/schema-validator.ts +308 -0
  211. package/src/core/runner/send-request.ts +158 -20
  212. package/src/core/runner/types.ts +44 -0
  213. package/src/core/secrets/registry.ts +164 -0
  214. package/src/core/secrets/secrets-file.ts +115 -0
  215. package/src/core/selectors/operation-filter.ts +144 -0
  216. package/src/core/setup-api.ts +457 -20
  217. package/src/core/severity/category.ts +94 -0
  218. package/src/core/severity/index.ts +58 -0
  219. package/src/core/spec/infer-schema.ts +102 -0
  220. package/src/core/spec/layers.ts +154 -0
  221. package/src/core/spec/merge-specs.ts +156 -0
  222. package/src/core/spec/schema-from-runs.ts +117 -0
  223. package/src/core/spec/schema-overlay.ts +130 -0
  224. package/src/core/util/ajv.ts +13 -0
  225. package/src/core/util/format-eta.ts +21 -0
  226. package/src/core/util/headers.ts +9 -0
  227. package/src/core/util/url.ts +24 -0
  228. package/src/core/utils.ts +5 -1
  229. package/src/core/workspace/config.ts +129 -0
  230. package/src/core/workspace/fixture-gap-report.ts +84 -0
  231. package/src/core/workspace/fixture-gaps.ts +71 -0
  232. package/src/core/workspace/manifest.ts +283 -0
  233. package/src/core/workspace/output-rotation.ts +62 -0
  234. package/src/core/workspace/root.ts +13 -11
  235. package/src/core/workspace/triage-path.ts +87 -0
  236. package/src/db/lint-runs.ts +47 -0
  237. package/src/db/migrate.ts +128 -0
  238. package/src/db/migrations/0001_run_kind.sql +25 -0
  239. package/src/db/migrations/0002_run_kind_request.sql +59 -0
  240. package/src/db/migrations/sql.d.ts +4 -0
  241. package/src/db/queries/collections.ts +133 -0
  242. package/src/db/queries/coverage.ts +9 -0
  243. package/src/db/queries/dashboard.ts +59 -0
  244. package/src/db/queries/results.ts +216 -0
  245. package/src/db/queries/runs.ts +289 -0
  246. package/src/db/queries/sessions.ts +42 -0
  247. package/src/db/queries/settings.ts +28 -0
  248. package/src/db/queries/types.ts +172 -0
  249. package/src/db/queries.ts +75 -802
  250. package/src/db/schema.ts +178 -50
  251. package/src/cli/commands/export.ts +0 -144
  252. package/src/cli/commands/guide.ts +0 -127
  253. package/src/cli/commands/init/templates/skills/scenarios.md +0 -97
  254. package/src/cli/commands/probe-methods.ts +0 -108
  255. package/src/cli/commands/probe-validation.ts +0 -124
  256. package/src/cli/commands/serve.ts +0 -114
  257. package/src/cli/commands/sync.ts +0 -268
  258. package/src/cli/commands/update.ts +0 -189
  259. package/src/cli/commands/validate.ts +0 -34
  260. package/src/core/diagnostics/render-md.ts +0 -112
  261. package/src/core/exporter/postman.ts +0 -963
  262. package/src/core/generator/guide-builder.ts +0 -253
  263. package/src/core/meta/types.ts +0 -19
  264. package/src/core/parser/index.ts +0 -21
  265. package/src/core/runner/execute-run.ts +0 -132
  266. package/src/core/runner/index.ts +0 -12
  267. package/src/core/sync/spec-differ.ts +0 -38
  268. package/src/web/data/collection-state.ts +0 -362
  269. package/src/web/routes/api.ts +0 -314
  270. package/src/web/routes/dashboard.ts +0 -350
  271. package/src/web/routes/runs.ts +0 -64
  272. package/src/web/schemas.ts +0 -121
  273. package/src/web/server.ts +0 -134
  274. package/src/web/static/htmx.min.cjs +0 -1
  275. package/src/web/static/style.css +0 -1148
  276. package/src/web/views/endpoints-tab.ts +0 -174
  277. package/src/web/views/explorer-tab.ts +0 -402
  278. package/src/web/views/health-strip.ts +0 -92
  279. package/src/web/views/layout.ts +0 -48
  280. package/src/web/views/results.ts +0 -210
  281. package/src/web/views/runs-tab.ts +0 -126
  282. package/src/web/views/suites-tab.ts +0 -181
@@ -1,6 +1,82 @@
1
1
  import { sendAdHocRequest } from "../../core/runner/send-request.ts";
2
- import { printError } from "../output.ts";
3
- import { jsonOk, jsonError, printJson } from "../json-envelope.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
+ }
4
80
 
5
81
  export interface RequestOptions {
6
82
  method: string;
@@ -11,12 +87,45 @@ export interface RequestOptions {
11
87
  env?: string;
12
88
  api?: string;
13
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;
14
94
  dbPath?: string;
15
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;
16
113
  }
17
114
 
18
115
  export async function requestCommand(options: RequestOptions): Promise<number> {
19
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
+
20
129
  const headers: Record<string, string> = {};
21
130
  if (options.headers) {
22
131
  for (const h of options.headers) {
@@ -27,6 +136,15 @@ export async function requestCommand(options: RequestOptions): Promise<number> {
27
136
  }
28
137
  }
29
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
+
30
148
  const result = await sendAdHocRequest({
31
149
  method: options.method.toUpperCase(),
32
150
  url: options.url,
@@ -37,21 +155,394 @@ export async function requestCommand(options: RequestOptions): Promise<number> {
37
155
  collectionName: options.api,
38
156
  jsonPath: options.jsonPath,
39
157
  dbPath: options.dbPath,
158
+ form: useForm,
40
159
  });
41
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
+
42
180
  if (options.json) {
43
- printJson(jsonOk("request", result));
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);
44
202
  } else {
45
203
  console.log(JSON.stringify(result, null, 2));
204
+ if (validation) printSchemaValidation(validation);
46
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;
47
246
  return 0;
48
247
  } catch (err) {
49
248
  const message = err instanceof Error ? err.message : String(err);
50
249
  if (options.json) {
51
- printJson(jsonError("request", [message]));
250
+ const code = /not registered/.test(message) ? "api_not_registered" : "unknown_error";
251
+ printJson(jsonError("request", [zerr(code, message)]));
52
252
  } else {
53
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
+ }
54
267
  }
55
268
  return 1;
56
269
  }
57
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
+ }