diff --git a/example/app/google/DiscoveryDemo.cpp b/example/app/google/DiscoveryDemo.cpp
index 64a6bbc..a975ba4 100644
--- a/example/app/google/DiscoveryDemo.cpp
+++ b/example/app/google/DiscoveryDemo.cpp
@@ -1,13 +1,287 @@
#include "../GoogleDemos.hpp"
#include "../../fw/Router.hpp"
+#include "../../fw/Templates.hpp"
+#include "google/discovery/caps.h"
+#include "google/discovery/engine.h"
namespace molo::example::app {
-// every Google API generically (all 316 Discovery documents). Stub: the package agent fills this in.
+// Every Google API generically: the Discovery engine over src/google/discovery.
+// GET routes need no credential. Every route that reaches Google (documents
+// and the API itself) is a POST: 422 on bad input first, then 503
+// google_not_configured without a credential. A call runs at once when the
+// method is a GET; any other verb is a dry run (the validated request) unless
+// the body says "confirm":true.
+
+namespace {
+
+namespace dc = google::discovery;
+using Json = clients::body::Json;
+
+constexpr std::size_t kMaxBody = 512 * 1024;
+constexpr std::size_t kMaxText = 200;
+
+const char kPage[] = R"DISCOVERY({% extends "base.html" %}
+{% block content %}
+
Google Discovery
+Find any Google API (the whole Discovery directory) and call any
+method by id. Requests are validated against the real Discovery document before
+any traffic. Only GET methods run at once; other verbs are dry runs until you
+tick confirm.
+Checking Google credentials...
+
+
+
+{% endblock %}
+)DISCOVERY";
+
+fw::Response json_out(const Json& j, int status = 200) {
+ fw::Response res = fw::JsonResponse(j.dump(), status);
+ res.headers.set("Cache-Control", "no-store");
+ return res;
+}
+
+[[noreturn]] void bad(const std::string& why) {
+ throw fw::HttpError(422, "validation_error", why);
+}
+
+[[noreturn]] void rethrow(const google::GoogleError& e) {
+ if (e.http_status() == 503 && e.status() == "NOT_CONFIGURED")
+ throw fw::HttpError(503, "google_not_configured", e.message());
+ if (e.service().empty() && e.status() == "INVALID_ARGUMENT")
+ throw fw::HttpError(422, "validation_error", e.message());
+ if (e.service() == "discovery" && e.status() == "NOT_FOUND")
+ throw fw::HttpError(404, "not_found", e.message());
+ throw fw::HttpError(502, "google_error", e.status() + ": " + e.message());
+}
+
+template
+auto guarded(F&& f) -> decltype(f()) {
+ try {
+ return f();
+ } catch (const google::GoogleError& e) {
+ rethrow(e);
+ }
+}
+
+Json parse_body(const fw::Request& req) {
+ if (req.body.size() > kMaxBody) throw fw::HttpError(413, "payload_too_large", "body too large");
+ if (req.body.empty()) return Json::object();
+ try {
+ Json j = Json::parse(req.body);
+ if (!j.is_object()) bad("body must be a JSON object");
+ return j;
+ } catch (const clients::body::JsonError&) {
+ bad("body is not valid JSON");
+ }
+}
+
+std::string text(const Json& body, const char* key, bool required = false) {
+ const Json* v = body.find(key);
+ if (!v || v->is_null()) {
+ if (required) bad(std::string(key) + " is required");
+ return "";
+ }
+ if (!v->is_string()) bad(std::string(key) + " must be a string");
+ if (v->as_string().size() > kMaxText) bad(std::string(key) + " is too long");
+ return v->as_string();
+}
+
+bool flag(const Json& body, const char* key) {
+ const Json* v = body.find(key);
+ if (!v || v->is_null()) return false;
+ if (!v->is_bool()) bad(std::string(key) + " must be true or false");
+ return v->as_bool();
+}
+
+std::size_t bounded(const Json& body, const char* key, std::size_t lo, std::size_t hi,
+ std::size_t fallback) {
+ const Json* v = body.find(key);
+ if (!v || v->is_null()) return fallback;
+ if (!v->is_number()) bad(std::string(key) + " must be a number");
+ long n = v->as_int();
+ if (n < static_cast(lo) || n > static_cast(hi))
+ bad(std::string(key) + " must be " + std::to_string(lo) + ".." + std::to_string(hi));
+ return static_cast(n);
+}
+
+// "name" or "name:version", letters digits _ - . and one colon.
+std::string api_ref(const Json& body) {
+ std::string api = text(body, "api", true);
+ std::size_t colons = 0;
+ for (char c : api) {
+ if (c == ':') ++colons;
+ else if (!(std::isalnum(static_cast(c)) || c == '_' || c == '-' || c == '.'))
+ bad("api must be name or name:version");
+ }
+ if (colons > 1) bad("api must be name or name:version");
+ return api;
+}
+
+std::string method_id(const Json& body) {
+ std::string id = text(body, "method", true);
+ for (char c : id)
+ if (!(std::isalnum(static_cast(c)) || c == '_' || c == '-' || c == '.'))
+ bad("method must be a Discovery method id such as serviceusage.services.list");
+ return id;
+}
+
+dc::CallArgs args_from(const Json& body) {
+ dc::CallArgs a;
+ if (const Json* p = body.find("params"); p && !p->is_null()) {
+ if (!p->is_object()) bad("params must be a JSON object");
+ a.params = *p;
+ }
+ if (const Json* b = body.find("body"); b && !b->is_null()) {
+ if (!b->is_object()) bad("body must be a JSON object");
+ a.body = *b;
+ }
+ a.location = text(body, "location");
+ try {
+ a.auth = dc::auth_mode_from(text(body, "auth"));
+ } catch (const google::GoogleError& e) {
+ bad(e.message());
+ }
+ a.max_pages = bounded(body, "maxPages", 1, dc::DiscoveryCaps::kMaxPages, 1);
+ a.items_key = text(body, "itemsKey");
+ a.wait = flag(body, "wait");
+ return a;
+}
+
+} // namespace
+
void register_google_discovery_demo(fw::Router& router, Services& services) {
- (void)router;
- (void)services;
+ if (!services.google) services.google = google::GoogleClient::from_env();
+ auto client = services.google;
+ auto catalog = std::make_shared(std::make_shared());
+ auto engine = std::make_shared(client, catalog);
+ fw::Environment* env = services.templates.get();
+ services.templates->add_template("google_discovery.html", kPage);
+ services.add_feature("google-discovery", "/google/discovery");
+
+ // Shape checks come first (422); then the credential (503).
+ auto need_credential = [client]() {
+ if (!client->configured()) throw google::NotConfiguredError("discovery");
+ };
+
+ router.get("/google/discovery", "google-discovery-page", [env](fw::Request req) {
+ (void)req;
+ fw::TemplateCtx ctx;
+ ctx["title"] = std::string("Google Discovery");
+ return fw::Response(200, env->render("google_discovery.html", ctx), "text/html; charset=utf-8");
+ });
+
+ router.get("/google/discovery/status", "google-discovery-status", [client, catalog](fw::Request req) {
+ (void)req;
+ dc::CatalogStats s = catalog->stats();
+ Json caps = Json::object();
+ caps.set("max_pages", Json(static_cast(dc::DiscoveryCaps::kMaxPages)));
+ caps.set("max_items", Json(static_cast(dc::DiscoveryCaps::kMaxItems)));
+ caps.set("max_doc_bytes", Json(static_cast(dc::DiscoveryCaps::kMaxDocBytes)));
+ caps.set("max_body_bytes", Json(static_cast(dc::DiscoveryCaps::kMaxBodyBytes)));
+ caps.set("max_cached_apis", Json(static_cast(dc::DiscoveryCaps::kMaxCachedApis)));
+ caps.set("max_age_seconds", Json(static_cast(dc::DiscoveryCaps::kMaxAge.count())));
+ caps.set("min_refetch_seconds", Json(static_cast(dc::DiscoveryCaps::kMinRefetch.count())));
+ Json o = Json::object();
+ o.set("configured", Json(client->configured()));
+ o.set("directory", Json(std::string(dc::kDirectoryUrl)));
+ o.set("cached_apis", Json(static_cast(s.cached)));
+ o.set("cached_bytes", Json(static_cast(s.cached_bytes)));
+ o.set("fetches", Json(static_cast(s.fetches)));
+ o.set("caps", caps);
+ return json_out(o);
+ });
+
+ router.post("/google/discovery/apis", "google-discovery-apis", [engine, need_credential](fw::Request req) {
+ Json b = parse_body(req);
+ std::string filter = text(b, "filter");
+ std::size_t limit = bounded(b, "limit", 1, dc::DiscoveryCaps::kMaxListed, 50);
+ bool all = flag(b, "all");
+ return guarded([&] {
+ need_credential();
+ Json o = Json::object();
+ o.set("apis", engine->list_apis(filter, limit, !all));
+ return json_out(o);
+ });
+ });
+
+ router.post("/google/discovery/methods", "google-discovery-methods", [engine, need_credential](fw::Request req) {
+ Json b = parse_body(req);
+ std::string api = api_ref(b);
+ std::string filter = text(b, "filter");
+ std::size_t limit = bounded(b, "limit", 1, dc::DiscoveryCaps::kMaxListed, 100);
+ return guarded([&] {
+ need_credential();
+ return json_out(engine->list_methods(api, filter, limit));
+ });
+ });
+
+ router.post("/google/discovery/describe", "google-discovery-describe", [engine, need_credential](fw::Request req) {
+ Json b = parse_body(req);
+ std::string api = api_ref(b);
+ std::string method = method_id(b);
+ return guarded([&] {
+ need_credential();
+ return json_out(engine->describe(api, method));
+ });
+ });
+
+ router.post("/google/discovery/plan", "google-discovery-plan", [engine, need_credential](fw::Request req) {
+ Json b = parse_body(req);
+ std::string api = api_ref(b);
+ std::string method = method_id(b);
+ dc::CallArgs args = args_from(b);
+ return guarded([&] {
+ need_credential();
+ return json_out(engine->plan(api, method, args).to_json());
+ });
+ });
+
+ router.post("/google/discovery/call", "google-discovery-call", [engine, need_credential](fw::Request req) {
+ Json b = parse_body(req);
+ std::string api = api_ref(b);
+ std::string method = method_id(b);
+ dc::CallArgs args = args_from(b);
+ bool confirm = flag(b, "confirm");
+ return guarded([&] {
+ need_credential();
+ dc::PreparedCall plan = engine->plan(api, method, args); // validates, no API traffic
+ if (plan.http != clients::Method::kGet && !confirm) {
+ Json o = plan.to_json();
+ o.set("dry_run", Json(true));
+ o.set("hint", Json("send confirm:true to run it"));
+ return json_out(o);
+ }
+ return json_out(engine->call(api, method, args).to_json());
+ });
+ });
}
} // namespace molo::example::app
diff --git a/example/assets/google_discovery.js b/example/assets/google_discovery.js
new file mode 100644
index 0000000..97d46bd
--- /dev/null
+++ b/example/assets/google_discovery.js
@@ -0,0 +1,68 @@
+// Google Discovery page: thin client over /google/discovery/* (all limits server side).
+(function () {
+ "use strict";
+ var $ = function (id) { return document.getElementById(id); };
+ var out = $("dc-out"), err = $("dc-error");
+
+ function post(path, body) {
+ err.textContent = "";
+ out.textContent = "...";
+ return fetch(path, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body)
+ }).then(function (res) {
+ return res.text().then(function (t) {
+ var j;
+ try { j = JSON.parse(t); } catch (e) { j = { message: t }; }
+ if (!res.ok) {
+ err.textContent = j.message || ("HTTP " + res.status);
+ out.textContent = "";
+ } else {
+ out.textContent = JSON.stringify(j, null, 2);
+ }
+ });
+ }).catch(function (e) { err.textContent = String(e); out.textContent = ""; });
+ }
+
+ function json(id) {
+ var raw = $(id).value.trim();
+ if (!raw) return undefined;
+ try { return JSON.parse(raw); } catch (e) { err.textContent = id + " is not valid JSON"; return null; }
+ }
+
+ function callBody() {
+ var params = json("dc-params"), body = json("dc-body");
+ if (params === null || body === null) return null;
+ var b = {
+ api: $("dc-api").value.trim(),
+ method: $("dc-method").value.trim(),
+ location: $("dc-location").value.trim(),
+ auth: $("dc-auth").value,
+ maxPages: parseInt($("dc-pages").value, 10) || 1,
+ wait: $("dc-wait").checked,
+ confirm: $("dc-confirm").checked
+ };
+ if (params !== undefined) b.params = params;
+ if (body !== undefined) b.body = body;
+ return b;
+ }
+
+ fetch("/google/discovery/status").then(function (r) { return r.json(); }).then(function (s) {
+ $("dc-config").textContent = s.configured
+ ? "Google credential found. Documents cached: " + s.cached_apis + "."
+ : "No Google credential: every action answers 503 until one is configured.";
+ });
+
+ $("dc-apis").onclick = function () {
+ post("/google/discovery/apis", { filter: $("dc-filter").value.trim(), limit: 50 });
+ };
+ $("dc-methods").onclick = function () {
+ post("/google/discovery/methods", { api: $("dc-api").value.trim(), filter: $("dc-method").value.trim(), limit: 100 });
+ };
+ $("dc-describe").onclick = function () {
+ post("/google/discovery/describe", { api: $("dc-api").value.trim(), method: $("dc-method").value.trim() });
+ };
+ $("dc-plan").onclick = function () { var b = callBody(); if (b) post("/google/discovery/plan", b); };
+ $("dc-call").onclick = function () { var b = callBody(); if (b) post("/google/discovery/call", b); };
+})();
diff --git a/src/google/discovery/SPEC.md b/src/google/discovery/SPEC.md
new file mode 100644
index 0000000..fa27da7
--- /dev/null
+++ b/src/google/discovery/SPEC.md
@@ -0,0 +1,213 @@
+# Google Discovery Engine - Specification
+
+Owned directory: `src/google/discovery/`. Namespace `molo::google::discovery`.
+Depends on the `src/google` foundation (`GoogleClient`, `GoogleError`,
+`ServiceEndpoint`, `Operation`) and `clients::Client` for document fetches.
+No other google package depends on it and it depends on none. Plan:
+`plans/18-breadth.md` section 1.
+
+## 1. Scope
+
+One generic engine that reaches every API in Google's Discovery directory
+(`https://discovery.googleapis.com/discovery/v1/apis`: 538 entries, 316
+preferred, 2026-10-25) and calls any method by its Discovery id
+(`serviceusage.services.list`). It fetches and caches a Discovery document,
+lists APIs and methods, validates parameters and body against the document
+before any traffic, builds the URL (path templates, query, repeated values,
+regional host), chooses key or OAuth, walks `nextPageToken`, and polls
+long-running operations. Typed classes in other packages are better for the
+APIs they cover; this engine is the breadth.
+
+Not here (each is classified Limited or Rejected, see section 5): media
+upload and download bodies, resumable upload, bidirectional or client
+streaming, non-JSON replies, the global batch endpoint (`batchPath`, shut
+down by Google in 2020), and object-typed query parameters.
+
+## 2. Module map (one concern per file)
+
+| File | Concern |
+|---|---|
+| `caps.h` | Static ceilings (`DiscoveryCaps`) |
+| `model.h/.cpp` | `Api`, `Method`, `Param`: parse a document, classify every method (`Support` Full / Limited / Rejected with notes), pagination and operation detection, host allowlist |
+| `validate.h/.cpp` | `ParamValidator` (type, format, enum, pattern, range, repeated, path safety) and `BodyValidator` (schema walk: `$ref`, objects, maps, arrays, enums, int64 strings, free-form) |
+| `planner.h/.cpp` | `Planner::plan`: `(Api, Method, CallArgs)` to `PreparedCall` (endpoint, encoded path and query, body, credential choice). No traffic |
+| `catalog.h/.cpp` | `Directory`, `DocumentSource` (`HttpDocumentSource`, `FileDocumentSource`), `Catalog` (bounded LRU cache with age and refetch floor) |
+| `engine.h/.cpp` | `Engine`: `list_apis`, `list_methods`, `describe`, `plan`, `call` (paging, long-running wait) |
+| `tools/check_discovery_directory.py` | Fetches the whole directory and every preferred document, runs the engine's own classification over them, reports what it cannot handle |
+| `tools/audit_main.cc` | The C++ half of that checker (built by the script; not globbed by `google.mk`) |
+
+## 3. Static caps (see caps.h)
+
+| Knob | Value |
+|---|---|
+| Document size | 8 MiB (largest real: compute v1, 6.4 MB) |
+| Directory size / items | 2 MiB / 1000 |
+| Cached documents / cached bytes | 32 / 96 MiB, least recently used evicted |
+| Document max age | 24 h |
+| Refetch floor | 60 s per document, even after `forget` |
+| Methods per document | 10000 (largest real: compute v1, 1018; aiplatform v1, 1137) |
+| Resource nesting | 16 |
+| Parameter value | 2048 chars, no control characters |
+| Repeated values / query values | 100 / 64 |
+| Request target | 6000 chars |
+| Request body | 4 MiB, schema depth 32, 200000 visited nodes |
+| Pages per call / items per call | 50 / 10000 (default 1 page) |
+| Listing | 500 rows |
+| Operation wait | foundation `OperationCaps`: 400 polls, 2 s interval, 600 s |
+
+## 4. Contracts
+
+- Documents are fetched without a credential, over HTTPS, from hosts that
+ are `googleapis.com` or a subdomain only (`is_google_host_url`). A document
+ whose `rootUrl` or regional `endpointUrl` fails that test is rejected
+ (`BAD_DOCUMENT`), as is a document that is not the one the directory
+ listed, a wrong `kind` or `protocol`, a duplicate method id, or anything
+ over a cap.
+- API reference: `name` (preferred version) or `name:version`. The method id
+ prefix is not always the API name (`admin` serves `reports.activities.list`),
+ so the API is always given explicitly.
+- Validation order, all before traffic: API and method exist (404), method
+ not Rejected, `params` is an object, regional `location` exists in the
+ document, every param is declared (global params: only `fields`,
+ `quotaUser`, `prettyPrint`; `key`, `access_token`, `oauth_token`, `alt`,
+ `callback`, `uploadType`, `upload_protocol`, `$.xgafv` are refused by name),
+ values fit type / format / enum / pattern / range, required params are
+ present, path values have no dot segment, the body fits the request schema.
+ Failures are `GoogleError` 400 `INVALID_ARGUMENT` naming the parameter or
+ JSON path. After validation, no credential is `NotConfiguredError` (503).
+- Path templates are `{x}` (value fully percent-encoded, `/` included) or
+ `{+x}` (reserved expansion: each `/` segment encoded, slashes kept).
+ Query parameters are sorted by name, repeated parameters repeat the key.
+- Body: methods with no request schema take none; POST / PUT / PATCH without
+ a request schema or without a body send `{}`. Unknown properties are
+ rejected when the schema lists properties; free-form objects and `any`
+ pass; `null` passes (proto JSON unset); int64 / uint64 are digit strings
+ (an integral JSON number is accepted and converted).
+- Credential: `AuthMode::kAuto` sends the API key for methods that declare no
+ OAuth scope (205 of 13194) and OAuth for the rest; `kKey` / `kOAuth` force
+ it through `ServiceEndpoint::prefer_key`. `GoogleClient` falls back to the
+ other credential only when the forced one is not configured.
+- Regional hosts: `location` selects the `endpoints[]` row of the document
+ (69 documents have rows, e.g. `workflows.us-central1.rep.googleapis.com`).
+ An unknown location is rejected with examples; a document without rows
+ rejects any location. Nothing is guessed from the location string.
+- Pagination: `max_pages > 1` needs a `pageToken` query param and a reply
+ schema with `nextPageToken`. The array to collect is the single array
+ property of the reply (`items_key` otherwise). The merged reply has the
+ collected array; `truncated` is true when a page or item cap stopped the
+ walk while a token remained (the token stays in the body).
+- Long-running: a reply whose schema has `name` and boolean `done` is an
+ operation. With `wait`, the engine finds the API's `operations.get` method
+ whose `name` pattern matches, polls it with the foundation caps, throws
+ `OPERATION_FAILED` on an error result and `DEADLINE_EXCEEDED` at the cap.
+ APIs without an `operations.get` (111 methods) reject `wait` loudly.
+ Operations that use another shape (Compute `status` / `selfLink`) are
+ plain resources to this engine.
+- Destructive or sending methods are ordinary methods here; the caller (the
+ demo) decides. The demo runs GET at once and dry-runs every other verb
+ unless `confirm:true`.
+
+## 5. Shapes seen
+
+Read from the 310 reachable preferred documents (13194 methods, 27285
+schemas), 2026-10-25, and how each is handled:
+
+| Shape | Seen | Handling |
+|---|---|---|
+| `path` templates `{x}` / `{+x}` only; every variable declared as a path param | 4712 / 10563 variables, no exception | Substituted and encoded; anything else Rejected |
+| `flatPath` | 13034 methods | Ignored: `path` is authoritative and equivalent |
+| `rootUrl` + `servicePath`; 12 documents have a non-empty `servicePath` | 310 | `base_url` = root (or regional root) + servicePath; `path` is relative to it |
+| Param `location` | `path`, `query` only | Anything else Rejected |
+| Param types | string, integer, boolean, number; `object` once (`discoveryengine ...dataConnector.mcp` `extensions`) | Object params Rejected (1 method) |
+| Param `format` | int32, uint32, int64, uint64, double, float, byte, date-time, google-datetime, google-duration, google-fieldmask | Checked for integers and the 64-bit strings, date and duration shape; others are strings |
+| `repeated` | 509 params | Array or scalar; cap 100 |
+| `enum` | 710 params | Checked |
+| `pattern` | 12636 params | `std::regex` ECMAScript; a pattern it cannot parse is left to Google |
+| `minimum` / `maximum` (strings) | 306 / 61 | Checked |
+| `$ref` request/response, nested `$ref`, `items`, `additionalProperties` (map types), `any`, readOnly | all | Body validator follows `$ref` (chain cap 16), maps, arrays; readOnly is not enforced |
+| `mediaUpload` (simple, resumable) | 53 methods | Limited: the metadata call is made, no media bytes |
+| `supportsMediaDownload` | 20 methods | Limited: JSON reply only, `alt=media` is refused |
+| Reply `HttpBody` | 81 methods | Limited: the reply may not be JSON; a parse failure is `BAD_RESPONSE` |
+| `streamingType` | `NONE` 4, `SERVER_SIDE` 2 (admob) | NONE ignored; SERVER_SIDE Limited (read whole); anything else Rejected |
+| `batchPath` | 310 documents | Not used (Google removed the global batch endpoint) |
+| `endpoints[]` | 69 documents | Regional hosts, see section 4 |
+| `mtlsRootUrl`, `canonicalName`, `version_module`, `icons`, `auth` | many | Ignored |
+| Operation-shaped replies (`name` + `done`) | 2359 methods | `wait`; 111 are in documents with no `operations.get` |
+| `pageToken` + `nextPageToken` | 2386 methods | Paging |
+| Other paging schemes (`start-index`, `nextLink`) | not counted | Not paged; one call per request |
+
+## Required APIs
+
+Enable these on the project (placeholder project `example-214512124`; full
+list in `src/google/APIS.md`). The engine itself needs none: Discovery
+documents are public. Calling an API needs that API enabled; a disabled one
+answers 403 `SERVICE_DISABLED`. The live checks use:
+
+- `serviceusage.googleapis.com`: https://console.developers.google.com/apis/api/serviceusage.googleapis.com/overview?project=example-214512124
+
+Scopes: `cloud-platform` covers the Cloud APIs. Workspace and other APIs
+need the scopes named in each method's `scopes` (`describe` shows them); the
+service-account credential in this repository supplies `cloud-platform` only.
+
+## Sources
+
+- `https://discovery.googleapis.com/discovery/v1/apis` (directory, 538
+ entries, 316 preferred) and every preferred `discoveryRestUrl`, fetched
+ 2026-10-25.
+- Discovery format reference: `https://developers.google.com/discovery/v1/reference/apis`
+ and `.../v1/using` (parameter and method fields).
+
+## Verified against discovery
+
+`python3 src/google/discovery/tools/check_discovery_directory.py`,
+2026-10-25: 316 preferred APIs listed, 310 documents served and loaded by the
+engine, 0 rejected documents. Six listed APIs are not served by Google
+(`area120tables:v1alpha1`, `datalabeling:v1beta1`, `mybusinessqanda:v1` 404;
+`contentwarehouse:v1`, `poly:v1`, `rapidmigrationassessment:v1` 502): not an
+engine fault, listed by the script as UNREACHABLE. Of 13194 methods: 13037
+Full, 156 Limited (81 HttpBody replies, 53 media upload, 20 media download,
+2 server streaming), 1 Rejected (object query parameter). Dry plan of every
+callable method with synthesized required parameters: 13185 planned, 8
+skipped (synthetic value does not fit an exotic pattern), 0 failed.
+
+## Verified live
+
+`make google-live` as the service account on project `lisa-448004`,
+2026-10-25 (read-only):
+
+- Real directory over HTTPS: 538 items, 316 preferred; documents of
+ serviceusage, cloudresourcemanager, tasks, workflows parsed.
+- Largest documents fit the caps: compute v1 (1018 methods, 6419010 bytes),
+ aiplatform v1 (1137 methods, 4027902 bytes).
+- `serviceusage.services.get` for `serviceusage.googleapis.com` answered 200.
+- `serviceusage.services.list` with `pageSize=3`, 3 pages: 9 items,
+ `truncated` true (the page cap, the token left in the body).
+- `serviceusage.operations.get` with a missing name: 400 INVALID_ARGUMENT
+ (Google validates the name shape); the reply is recognised as an operation.
+- Cloud Resource Manager answers `PERMISSION_DENIED` (API not enabled on the
+ project): reported by Google, not exercised.
+
+## Unverified
+
+- Long-running `wait` polling to completion: no safe read-only operation
+ exists on this project, so only detection and the `operations.get` lookup
+ are exercised live. The loop is the foundation's `wait_operation` logic
+ re-implemented over the planner.
+- Key credential on a no-scope method live: no API key with a keyless-capable
+ API was used; the choice is verified at the request level (header).
+- Regional endpoints are verified for URL construction only, not by a call.
+- Methods Limited or Rejected are never called by design.
+- Behaviour for the 8 methods whose required-parameter patterns the audit
+ could not synthesize is only the validation path.
+
+## Gaps
+
+- Media upload (simple, resumable), media download and non-JSON replies:
+ `Method::support` says Limited; the foundation `GoogleClient` is JSON only
+ (`src/google/client.h`).
+- Batch (`batchPath`) is not offered.
+- Paging schemes other than `pageToken` / `nextPageToken`.
+- `AuthMode::kOAuth` falls back to the key when no OAuth credential exists
+ (foundation `GoogleClient::pick_auth`).
+- Documents are cached in memory only; there is no on-disk cache.
+- Test and audit coverage of `wait` against a real running operation.
diff --git a/src/google/discovery/caps.h b/src/google/discovery/caps.h
new file mode 100644
index 0000000..d59e8d6
--- /dev/null
+++ b/src/google/discovery/caps.h
@@ -0,0 +1,44 @@
+#pragma once
+
+// Static ceilings for the Discovery engine. Never autotuned. Measured
+// against the 310 reachable preferred documents on 2026-10-25: largest
+// document 6.4 MB (compute v1), most methods in one document is below
+// kMaxMethods, directory 538 entries.
+
+#include
+#include
+
+namespace molo::google::discovery {
+
+struct DiscoveryCaps {
+ // Documents and cache.
+ static constexpr std::size_t kMaxDocBytes = 8u * 1024u * 1024u;
+ static constexpr std::size_t kMaxDirectoryBytes = 2u * 1024u * 1024u;
+ static constexpr std::size_t kMaxDirectoryItems = 1000;
+ static constexpr std::size_t kMaxCachedApis = 32;
+ static constexpr std::size_t kMaxCachedBytes = 96u * 1024u * 1024u;
+ static constexpr std::chrono::seconds kMaxAge{24 * 3600};
+ // Floor: a document is never refetched more often than this, even when
+ // the caller forces a refresh.
+ static constexpr std::chrono::seconds kMinRefetch{60};
+ // Document structure.
+ static constexpr std::size_t kMaxMethods = 10000;
+ static constexpr std::size_t kMaxResourceDepth = 16;
+ static constexpr std::size_t kMaxSchemas = 20000;
+ // Listing.
+ static constexpr std::size_t kMaxListed = 500;
+ // Request validation.
+ static constexpr std::size_t kMaxParamChars = 2048;
+ static constexpr std::size_t kMaxRepeated = 100;
+ static constexpr std::size_t kMaxQueryParams = 64;
+ static constexpr std::size_t kMaxPathChars = 6000;
+ static constexpr std::size_t kMaxBodyBytes = 4u * 1024u * 1024u;
+ static constexpr std::size_t kMaxSchemaDepth = 32;
+ static constexpr std::size_t kMaxSchemaVisits = 200000;
+ // Pagination.
+ static constexpr std::size_t kDefaultPages = 1;
+ static constexpr std::size_t kMaxPages = 50;
+ static constexpr std::size_t kMaxItems = 10000;
+};
+
+} // namespace molo::google::discovery
diff --git a/src/google/discovery/catalog.cpp b/src/google/discovery/catalog.cpp
new file mode 100644
index 0000000..855ff9b
--- /dev/null
+++ b/src/google/discovery/catalog.cpp
@@ -0,0 +1,285 @@
+#include "google/discovery/catalog.h"
+
+#include
+#include
+#include
+#include
+
+#include "clients/transports/http_transport.h"
+#include "google/discovery/caps.h"
+#include "google/errors.h"
+
+namespace molo::google::discovery {
+
+using clients::body::Json;
+
+const char* const kDirectoryUrl = "https://discovery.googleapis.com/discovery/v1/apis";
+
+namespace {
+
+std::string str(const Json& o, const char* key) {
+ const Json* v = o.find(key);
+ return v && v->is_string() ? v->as_string() : "";
+}
+
+std::string lower(std::string s) {
+ for (char& c : s) c = static_cast(std::tolower(static_cast(c)));
+ return s;
+}
+
+bool valid_name(const std::string& s) {
+ if (s.empty() || s.size() > 64) return false;
+ for (char c : s)
+ if (!(std::isalnum(static_cast(c)) || c == '_' || c == '-' || c == '.')) return false;
+ return true;
+}
+
+} // namespace
+
+Json DirectoryItem::to_json() const {
+ Json o = Json::object();
+ o.set("id", Json(id));
+ o.set("name", Json(name));
+ o.set("version", Json(version));
+ o.set("title", Json(title));
+ o.set("description", Json(description));
+ o.set("discoveryRestUrl", Json(rest_url));
+ o.set("documentationLink", Json(documentation));
+ o.set("preferred", Json(preferred));
+ return o;
+}
+
+Directory Directory::parse(const std::string& text) {
+ if (text.size() > DiscoveryCaps::kMaxDirectoryBytes)
+ throw GoogleError(502, "BAD_DOCUMENT", "discovery directory is larger than the cap");
+ Json doc;
+ try {
+ doc = Json::parse(text);
+ } catch (const std::exception& e) {
+ throw GoogleError(502, "BAD_DOCUMENT", std::string("discovery directory: ") + e.what());
+ }
+ const Json* items = doc.is_object() ? doc.find("items") : nullptr;
+ if (!items || !items->is_array() || str(doc, "kind") != "discovery#directoryList")
+ throw GoogleError(502, "BAD_DOCUMENT", "discovery directory: not a directoryList");
+ if (items->as_array().size() > DiscoveryCaps::kMaxDirectoryItems)
+ throw GoogleError(502, "BAD_DOCUMENT", "discovery directory: more items than the cap");
+ Directory dir;
+ for (const Json& it : items->as_array()) {
+ DirectoryItem row;
+ row.id = str(it, "id");
+ row.name = str(it, "name");
+ row.version = str(it, "version");
+ row.title = str(it, "title");
+ row.description = str(it, "description");
+ row.rest_url = str(it, "discoveryRestUrl");
+ row.documentation = str(it, "documentationLink");
+ const Json* p = it.find("preferred");
+ row.preferred = p && p->is_bool() && p->as_bool();
+ if (row.id.empty() || row.name.empty() || row.version.empty() ||
+ !is_google_host_url(row.rest_url))
+ throw GoogleError(502, "BAD_DOCUMENT", "discovery directory: bad item " + row.id);
+ dir.items_.push_back(std::move(row));
+ }
+ return dir;
+}
+
+std::size_t Directory::preferred_count() const {
+ return static_cast(std::count_if(items_.begin(), items_.end(),
+ [](const DirectoryItem& i) { return i.preferred; }));
+}
+
+const DirectoryItem* Directory::find(const std::string& name, const std::string& version) const {
+ const DirectoryItem* fallback = nullptr;
+ for (const DirectoryItem& i : items_) {
+ if (i.name != name) continue;
+ if (!version.empty()) {
+ if (i.version == version) return &i;
+ } else if (i.preferred) {
+ return &i;
+ } else if (!fallback) {
+ fallback = &i;
+ }
+ }
+ return version.empty() ? fallback : nullptr;
+}
+
+std::vector Directory::search(const std::string& needle, std::size_t limit,
+ bool preferred_only) const {
+ std::vector out;
+ std::string n = lower(needle);
+ limit = std::min(limit, DiscoveryCaps::kMaxListed);
+ for (const DirectoryItem& i : items_) {
+ if (out.size() >= limit) break;
+ if (preferred_only && !i.preferred) continue;
+ if (n.empty() || lower(i.name).find(n) != std::string::npos ||
+ lower(i.title).find(n) != std::string::npos)
+ out.push_back(&i);
+ }
+ return out;
+}
+
+namespace {
+clients::ClientConfig source_config() {
+ clients::ClientConfig c;
+ c.auth = nullptr;
+ c.persist_cookies = false;
+ return c;
+}
+} // namespace
+
+HttpDocumentSource::HttpDocumentSource()
+ : client_(std::make_unique(), source_config()) {}
+
+HttpDocumentSource::HttpDocumentSource(std::unique_ptr transport)
+ : client_(std::move(transport), source_config()) {}
+
+std::string HttpDocumentSource::fetch(const std::string& url, std::size_t max_bytes) {
+ if (!is_google_host_url(url))
+ throw GoogleError::invalid("discovery url is not an https googleapis.com url: " + url);
+ try {
+ clients::ClientResponse res = client_.get_blocking(url);
+ if (!res.is_success())
+ throw GoogleError(res.status(), res.status() == 404 ? "NOT_FOUND" : "UNAVAILABLE",
+ "discovery fetch failed with HTTP " + std::to_string(res.status()), "discovery");
+ if (res.body().size() > max_bytes)
+ throw GoogleError(502, "BAD_DOCUMENT", "discovery document is larger than the cap", "discovery");
+ return res.body();
+ } catch (const GoogleError&) {
+ throw;
+ } catch (const std::exception& e) {
+ throw GoogleError(502, "UNAVAILABLE", e.what(), "discovery");
+ }
+}
+
+std::string FileDocumentSource::fetch(const std::string& url, std::size_t max_bytes) {
+ std::string file;
+ if (url.rfind(kDirectoryUrl, 0) == 0) {
+ file = "directory.json";
+ } else {
+ if (index_.empty()) {
+ std::ifstream din(dir_ + "/directory.json", std::ios::binary);
+ if (!din) throw GoogleError(404, "NOT_FOUND", "saved directory.json missing", "discovery");
+ std::ostringstream dss;
+ dss << din.rdbuf();
+ for (const DirectoryItem& i : Directory::parse(dss.str()).items())
+ index_[i.rest_url] = i.name + "_" + i.version + ".json";
+ }
+ auto hit = index_.find(url);
+ if (hit == index_.end()) throw GoogleError::invalid("no saved document for url: " + url);
+ file = hit->second;
+ }
+ std::ifstream in(dir_ + "/" + file, std::ios::binary);
+ if (!in) throw GoogleError(404, "NOT_FOUND", "saved discovery document missing: " + file, "discovery");
+ std::ostringstream ss;
+ ss << in.rdbuf();
+ std::string text = ss.str();
+ if (text.size() > max_bytes)
+ throw GoogleError(502, "BAD_DOCUMENT", "discovery document is larger than the cap", "discovery");
+ return text;
+}
+
+Catalog::Catalog(std::shared_ptr source, Clock clock)
+ : source_(std::move(source)), clock_(std::move(clock)) {}
+
+std::chrono::steady_clock::time_point Catalog::now() const {
+ return clock_ ? clock_() : std::chrono::steady_clock::now();
+}
+
+std::shared_ptr Catalog::directory() {
+ std::lock_guard lock(mu_);
+ auto t = now();
+ if (directory_ && t - directory_at_ < DiscoveryCaps::kMaxAge) {
+ ++stats_.hits;
+ return directory_;
+ }
+ ++stats_.fetches;
+ std::string text = source_->fetch(kDirectoryUrl, DiscoveryCaps::kMaxDirectoryBytes);
+ directory_ = std::make_shared(Directory::parse(text));
+ directory_at_ = t;
+ return directory_;
+}
+
+std::shared_ptr Catalog::api(const std::string& ref) {
+ std::string name = ref, version;
+ if (std::size_t c = ref.find(':'); c != std::string::npos) {
+ name = ref.substr(0, c);
+ version = ref.substr(c + 1);
+ }
+ if (!valid_name(name) || (!version.empty() && !valid_name(version)))
+ throw GoogleError::invalid("api must be name or name:version, got '" + ref + "'");
+ std::shared_ptr dir = directory();
+ const DirectoryItem* item = dir->find(name, version);
+ if (!item) throw GoogleError(404, "NOT_FOUND", "no such API in the Discovery directory: " + ref, "discovery");
+ std::lock_guard lock(mu_);
+ auto t = now();
+ auto it = entries_.find(item->id);
+ if (it != entries_.end()) {
+ bool stale = t - it->second.fetched >= DiscoveryCaps::kMaxAge;
+ auto lf = last_fetch_.find(item->id);
+ bool floor = lf != last_fetch_.end() && t - lf->second < DiscoveryCaps::kMinRefetch;
+ if (!stale || floor) {
+ lru_.remove(item->id);
+ lru_.push_front(item->id);
+ ++stats_.hits;
+ return it->second.api;
+ }
+ }
+ ++stats_.fetches;
+ std::string text = source_->fetch(item->rest_url, DiscoveryCaps::kMaxDocBytes);
+ Json doc;
+ try {
+ doc = Json::parse(text);
+ } catch (const std::exception& e) {
+ throw GoogleError(502, "BAD_DOCUMENT", std::string("discovery document ") + item->id + ": " + e.what());
+ }
+ Api parsed = Api::parse(doc);
+ parsed.raw_bytes = text.size();
+ if (parsed.name() != item->name || parsed.version() != item->version)
+ throw GoogleError(502, "BAD_DOCUMENT", "document " + parsed.id() + " is not the one requested: " + item->id);
+ Entry e;
+ e.api = std::make_shared(std::move(parsed));
+ e.fetched = t;
+ e.bytes = text.size();
+ entries_[item->id] = e;
+ last_fetch_[item->id] = t;
+ lru_.remove(item->id);
+ lru_.push_front(item->id);
+ evict_locked();
+ return e.api;
+}
+
+void Catalog::evict_locked() {
+ auto total = [&] {
+ std::size_t b = 0;
+ for (const auto& [k, v] : entries_) b += v.bytes;
+ return b;
+ };
+ while (entries_.size() > 1 &&
+ (entries_.size() > DiscoveryCaps::kMaxCachedApis || total() > DiscoveryCaps::kMaxCachedBytes)) {
+ entries_.erase(lru_.back());
+ lru_.pop_back();
+ ++stats_.evictions;
+ }
+}
+
+void Catalog::forget(const std::string& ref) {
+ std::lock_guard lock(mu_);
+ std::string name = ref, version;
+ if (std::size_t c = ref.find(':'); c != std::string::npos) {
+ name = ref.substr(0, c);
+ version = ref.substr(c + 1);
+ }
+ for (auto& [id, e] : entries_)
+ if (e.api->name() == name && (version.empty() || e.api->version() == version))
+ e.fetched = std::chrono::steady_clock::time_point{};
+}
+
+CatalogStats Catalog::stats() const {
+ std::lock_guard lock(mu_);
+ CatalogStats s = stats_;
+ s.cached = entries_.size();
+ for (const auto& [k, v] : entries_) s.cached_bytes += v.bytes;
+ return s;
+}
+
+} // namespace molo::google::discovery
diff --git a/src/google/discovery/catalog.h b/src/google/discovery/catalog.h
new file mode 100644
index 0000000..5c3e23d
--- /dev/null
+++ b/src/google/discovery/catalog.h
@@ -0,0 +1,125 @@
+#pragma once
+
+// Directory of Google APIs plus a bounded cache of parsed Discovery
+// documents. Documents come from a DocumentSource: HTTPS in production
+// (no credential, googleapis.com hosts only), a directory of saved real
+// documents for offline audits.
+
+#include
+#include
+#include
+#include