From 96366ee0a915b353fc2f73117516021daf808401 Mon Sep 17 00:00:00 2001 From: Jay Fletcher <5743488+jayjfletcher@users.noreply.github.com> Date: Tue, 27 Oct 2026 00:06:00 -0400 Subject: [PATCH] Switch from agent-os to Ringside Drop the agent-os commands and standards (now in refactor-circus/standards), add ring-master.yml, the docs/agent/ skeleton, the Ringside hooks and the AGENTS.md Ring Master block, ignore the files Ringside generates, and require refactor-circus/ringside and refactor-circus/standards for dev. Co-Authored-By: Claude Opus 5.5 (1M context) --- .gitignore | 6 +++ CLAUDE.md | 8 +++ .../backend/callback-sub-builders.md | 22 -------- .../standards/backend/config-safe-defaults.md | 21 -------- .../standards/backend/contract-first-di.md | 20 -------- .../standards/backend/empty-clause-skip.md | 17 ------- .../standards/backend/facade-method-sync.md | 23 --------- agent-os/standards/backend/fluent-builder.md | 22 -------- .../backend/guard-builder-options.md | 21 -------- .../backend/immutable-connection-switch.md | 26 ---------- .../backend/lazy-cached-connections.md | 16 ------ agent-os/standards/backend/named-msearch.md | 24 --------- .../backend/per-query-config-fallback.md | 17 ------- .../standards/backend/raw-escape-hatch.md | 12 ----- .../backend/shared-trait-duck-typing.md | 19 ------- .../backend/structural-cache-keys.md | 24 --------- .../backend/tolerate-response-shapes.md | 20 -------- .../backend/wrap-client-exceptions.md | 24 --------- agent-os/standards/index.yml | 44 ---------------- .../standards/testing/mock-client-contract.md | 27 ---------- agent-os/standards/testing/pest-style.md | 16 ------ .../standards/testing/test-build-output.md | 20 -------- .../standards/testing/testbench-harness.md | 28 ---------- docs/agent/product/.gitkeep | 0 docs/agent/specs/.gitkeep | 0 docs/agent/standards-feedback.md | 8 +++ .../stretch/callback-sub-builders.md | 32 ++++++++++++ .../standards/stretch/connection-config.md | 26 ++++++++++ .../standards/stretch/connection-purge.md | 14 +++++ .../standards/stretch/empty-clause-skip.md | 28 ++++++++++ .../agent/standards/stretch/fluent-builder.md | 30 +++++++++++ .../stretch/guard-builder-options.md | 35 +++++++++++++ .../stretch/immutable-connection-switch.md | 29 +++++++++++ docs/agent/standards/stretch/named-msearch.md | 35 +++++++++++++ .../stretch/per-query-config-fallback.md | 25 +++++++++ .../standards/stretch/raw-escape-hatch.md | 21 ++++++++ .../stretch/shared-trait-duck-typing.md | 29 +++++++++++ .../stretch/structural-cache-keys.md | 30 +++++++++++ .../standards/stretch/testbench-harness.md | 24 +++++++++ .../stretch/tolerate-response-shapes.md | 30 +++++++++++ .../standards/testing/mock-client-contract.md | 32 ++++++++++++ docs/agent/standards/testing/pest-style.md | 24 +++++++++ .../standards/testing/test-build-output.md | 28 ++++++++++ docs/agent/standards/testing/test-layers.md | 51 +++++++++++++++++++ ring-master.yml | 14 +++++ 45 files changed, 559 insertions(+), 463 deletions(-) delete mode 100644 agent-os/standards/backend/callback-sub-builders.md delete mode 100644 agent-os/standards/backend/config-safe-defaults.md delete mode 100644 agent-os/standards/backend/contract-first-di.md delete mode 100644 agent-os/standards/backend/empty-clause-skip.md delete mode 100644 agent-os/standards/backend/facade-method-sync.md delete mode 100644 agent-os/standards/backend/fluent-builder.md delete mode 100644 agent-os/standards/backend/guard-builder-options.md delete mode 100644 agent-os/standards/backend/immutable-connection-switch.md delete mode 100644 agent-os/standards/backend/lazy-cached-connections.md delete mode 100644 agent-os/standards/backend/named-msearch.md delete mode 100644 agent-os/standards/backend/per-query-config-fallback.md delete mode 100644 agent-os/standards/backend/raw-escape-hatch.md delete mode 100644 agent-os/standards/backend/shared-trait-duck-typing.md delete mode 100644 agent-os/standards/backend/structural-cache-keys.md delete mode 100644 agent-os/standards/backend/tolerate-response-shapes.md delete mode 100644 agent-os/standards/backend/wrap-client-exceptions.md delete mode 100644 agent-os/standards/index.yml delete mode 100644 agent-os/standards/testing/mock-client-contract.md delete mode 100644 agent-os/standards/testing/pest-style.md delete mode 100644 agent-os/standards/testing/test-build-output.md delete mode 100644 agent-os/standards/testing/testbench-harness.md create mode 100644 docs/agent/product/.gitkeep create mode 100644 docs/agent/specs/.gitkeep create mode 100644 docs/agent/standards-feedback.md create mode 100644 docs/agent/standards/stretch/callback-sub-builders.md create mode 100644 docs/agent/standards/stretch/connection-config.md create mode 100644 docs/agent/standards/stretch/connection-purge.md create mode 100644 docs/agent/standards/stretch/empty-clause-skip.md create mode 100644 docs/agent/standards/stretch/fluent-builder.md create mode 100644 docs/agent/standards/stretch/guard-builder-options.md create mode 100644 docs/agent/standards/stretch/immutable-connection-switch.md create mode 100644 docs/agent/standards/stretch/named-msearch.md create mode 100644 docs/agent/standards/stretch/per-query-config-fallback.md create mode 100644 docs/agent/standards/stretch/raw-escape-hatch.md create mode 100644 docs/agent/standards/stretch/shared-trait-duck-typing.md create mode 100644 docs/agent/standards/stretch/structural-cache-keys.md create mode 100644 docs/agent/standards/stretch/testbench-harness.md create mode 100644 docs/agent/standards/stretch/tolerate-response-shapes.md create mode 100644 docs/agent/standards/testing/mock-client-contract.md create mode 100644 docs/agent/standards/testing/pest-style.md create mode 100644 docs/agent/standards/testing/test-build-output.md create mode 100644 docs/agent/standards/testing/test-layers.md create mode 100644 ring-master.yml diff --git a/.gitignore b/.gitignore index 99c9e65..df9bde8 100644 --- a/.gitignore +++ b/.gitignore @@ -34,3 +34,9 @@ auth.json .DS_Store composer.local.json composer.local.lock + +# ringside generated files +/docs/agent/standards.index.yml +/docs/agent/standards.summary.md +/.claude/skills/ring-master-*/ +/.claude/agents/ring-master-*.md diff --git a/CLAUDE.md b/CLAUDE.md index de28a7a..254f120 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -253,3 +253,11 @@ The `config/stretch.php` file includes: - `aggregations` - Max buckets, default size - `logging` - Enabled flag, log channel, query logging, slow query threshold - `cache` - Enabled-by-default flag, TTL, prefix, store settings + + +## Ring Master + +- Specs, product docs and local standards live in `docs/agent/`. Shared standards come from `vendor/` through `docs/agent/standards.index.yml`; read the matching standards before changing code. +- Workflow: `/ring-master-shape-spec` → `/ring-master-write-spec` → `/ring-master-create-tasks` → `/ring-master-implement` → `/ring-master-verify-spec`. +- Done means `composer test` passes. When work must break a standard, add a row to `docs/agent/standards-feedback.md`. + diff --git a/agent-os/standards/backend/callback-sub-builders.md b/agent-os/standards/backend/callback-sub-builders.md deleted file mode 100644 index bea8952..0000000 --- a/agent-os/standards/backend/callback-sub-builders.md +++ /dev/null @@ -1,22 +0,0 @@ -# Callback Sub-Builders - -Composite clauses take a callback receiving a FRESH builder; the parent extracts the built result. - -Keeps sub-query state isolated from the parent — nothing leaks across clause boundaries. - -```php -public function nested(string $path, callable $callback): static -{ - $sub = new ElasticsearchQueryBuilder($this->client, $this->manager); - $callback($sub); - $query = $sub->build()['query'] ?? null; - // ...attach (see empty-clause-skip) -} -``` - -- Query-context clauses (`nested`, `filter`, `postFilter`) pass `$this->client, $this->manager` so connection context carries into the sub-builder. -- Pure structural sub-builders build without executing, so they need no client: `BoolQueryBuilder` (`new ElasticsearchQueryBuilder`), `AggregationBuilder`, `RetrieverBuilder`. -- Parent reads `$sub->build()['query']` (or `->build()` for aggs/retrievers) — never reaches into sub-builder internals. -- New composite clause → new dedicated builder class implementing its contract; don't inline clause assembly in the main builder. - -See [[empty-clause-skip]] for the null-skip rule on the extracted query. diff --git a/agent-os/standards/backend/config-safe-defaults.md b/agent-os/standards/backend/config-safe-defaults.md deleted file mode 100644 index 4a03b9a..0000000 --- a/agent-os/standards/backend/config-safe-defaults.md +++ /dev/null @@ -1,21 +0,0 @@ -# Fail-Loud, Safe-Default Config - -Misconfigured connections throw immediately; security defaults stay ON unless explicitly disabled. - -```php -if (! isset($connections[$name])) { - throw new \InvalidArgumentException("Elasticsearch connection [{$name}] not configured."); -} -if (empty($connections[$name]['hosts'])) { - throw new \InvalidArgumentException("Elasticsearch connection [{$name}] is missing hosts."); -} - -// SSL verification stays enabled unless explicitly turned off -if (! ($config['ssl_verification'] ?? true)) { - $clientBuilder->setSSLVerification(false); -} -``` - -- No silent fallback for a missing/empty connection — throw `InvalidArgumentException` with the connection name. -- Security-relevant defaults default to the SAFE value: `?? true` for SSL verification; opt OUT explicitly, never opt in. -- Optional hardening (connect_timeout, timeout) applied only when the connection declares it — `array_filter` out nulls so absent keys don't override client defaults. diff --git a/agent-os/standards/backend/contract-first-di.md b/agent-os/standards/backend/contract-first-di.md deleted file mode 100644 index 038b6fd..0000000 --- a/agent-os/standards/backend/contract-first-di.md +++ /dev/null @@ -1,20 +0,0 @@ -# Contract-First DI - -Consumers depend on contracts, never concrete implementations. The native ES client is wrapped behind `ClientContract`. - -Enables clean mocking/swapping in tests and insulates the package from vendor client API drift — only `ElasticsearchClient` adapts, consumers don't. - -```php -// StretchServiceProvider -$this->app->singleton(ClientContract::class, fn ($app) => - new ElasticsearchClient($app[Client::class])); // wrap native client - -$this->app->bind(QueryBuilderContract::class, ElasticsearchQueryBuilder::class); -$this->app->bind(MultiQueryBuilderContract::class, MultiQueryBuilder::class); -``` - -- Builders/Stretch type-hint `ClientContract`, `QueryBuilderContract`, etc. — never the native `Elastic\...\Client` directly. -- Singletons for stateful/shared services (client, manager, `stretch`); `bind()` for per-resolution builders. -- New ES-touching operation → add it to `ClientContract` + `ElasticsearchClient`, don't reach around the wrapper. - -See [[mock-client-contract]] — this is what makes client mocking clean. diff --git a/agent-os/standards/backend/empty-clause-skip.md b/agent-os/standards/backend/empty-clause-skip.md deleted file mode 100644 index 22ab485..0000000 --- a/agent-os/standards/backend/empty-clause-skip.md +++ /dev/null @@ -1,17 +0,0 @@ -# Empty-Clause Skip - -Composite clauses that receive a callback MUST skip attachment when the callback adds no query. - -An empty `bool`/`nested`/`filter` clause makes Elasticsearch reject the whole request. Skipping keeps requests valid when callbacks conditionally add nothing. - -- Build the sub-query, read `build()['query'] ?? null`, skip on null: - ```php - $sub = new ElasticsearchQueryBuilder; - $callback($sub); - $query = $sub->build()['query'] ?? null; - if ($query === null) { - return $this; // never attach an empty clause - } - ``` -- Applies to: `nested()`, `filter()`, `postFilter()`, and `BoolQueryBuilder` must/should/filter/mustNot (via `buildSubQuery()`). -- Any new composite/callback clause MUST follow this — never emit `{"bool": {}}`, `{"nested": {...}}` with no query, etc. diff --git a/agent-os/standards/backend/facade-method-sync.md b/agent-os/standards/backend/facade-method-sync.md deleted file mode 100644 index 1da057a..0000000 --- a/agent-os/standards/backend/facade-method-sync.md +++ /dev/null @@ -1,23 +0,0 @@ -# Facade @method Sync - -Every public `Stretch` method MUST have a matching `@method static` tag on the `Stretch` facade. - -The facade proxies dynamically via `getFacadeAccessor()`, so the `@method` docblock is the only source of truth for the static API — IDE autocomplete and PHPStan see nothing without it. - -```php -/** - * @method static QueryBuilderContract index(string|array $index) ... - * @method static array putPipeline(string $id, array $body) ... - */ -class Stretch extends Facade -{ - protected static function getFacadeAccessor(): string - { - return 'stretch'; - } -} -``` - -- Add a public method to `Stretch` → add/update the `@method static` line. Match signature and return type exactly. -- Keep `@see \RefactorCircus\Stretch\Stretch` on the facade so the two stay discoverable together. -- Removing/renaming a `Stretch` method → update the tag in the same change. diff --git a/agent-os/standards/backend/fluent-builder.md b/agent-os/standards/backend/fluent-builder.md deleted file mode 100644 index f59095c..0000000 --- a/agent-os/standards/backend/fluent-builder.md +++ /dev/null @@ -1,22 +0,0 @@ -# Fluent Builder: build() / execute() - -Builder methods mutate internal state and return `static`. `build()` assembles the body; `execute()` sends it. - -- Every clause/option method returns `$this` (typed `static`) for chaining. Sub-builder entry points (`range()`, `bool()` no-callback) return the sub-builder instead. -- State lives in typed protected arrays/scalars (`$query`, `$aggregations`, `$sort`, `$size`, ...). Methods append; nothing hits ES until `execute()`. -- `build()` is pure — assembles and returns the array body, no side effects. `toArray()` is its alias for inspection. -- `execute()` calls `build()`, wraps in `['index' => ..., 'body' => ...]`, stores `$lastQuery`, dispatches via the client. - -## Single-clause unwrap - -`build()` emits a lone clause bare; only multiple clauses auto-wrap in `bool.must`: - -```php -count($this->query) === 1 - ? $body['query'] = $this->query[0] // { "match": {...} } - : $body['query'] = ['bool' => ['must' => $this->query]]; -``` - -Keeps output idiomatic — a single `match` matches hand-written ES DSL, not `bool.must`. - -- Precedence in `build()`: `retriever` replaces query+knn entirely (early return); else top-level `knn`; else query (with `filters` → `bool.filter` wrap). diff --git a/agent-os/standards/backend/guard-builder-options.md b/agent-os/standards/backend/guard-builder-options.md deleted file mode 100644 index 3924b71..0000000 --- a/agent-os/standards/backend/guard-builder-options.md +++ /dev/null @@ -1,21 +0,0 @@ -# Guard Builder Options by Type - -When a builder option only applies to certain shapes, `build()` throws `LogicException` on misuse — never silently drops it. - -Silently ignoring an unsupported option hides a coding mistake. A `LogicException` (programmer error) surfaces it at build time with an actionable message, beating a cryptic downstream ES parse error. - -```php -if (isset($agg['terms'])) { - $agg['terms']['size'] = min($this->size ?? config('stretch.aggregations.default_size'), - config('stretch.aggregations.max_buckets')); -} elseif ($this->size !== null) { - throw new LogicException( - sprintf('size() is only supported on terms aggregations, [%s] given.', $this->aggregationType()) - ); -} -``` - -- Validate at `build()`, not in the setter — the setter doesn't yet know the final aggregation type. -- Message names the offending option AND the actual type (`$this->aggregationType()`). -- `orderBy()` follows the same guard (allowed on terms/histogram/date_histogram only). -- Terms aggregations always get a config-clamped `size` (`min(size ?? default, max_buckets)`) — bucket explosion is capped by default. diff --git a/agent-os/standards/backend/immutable-connection-switch.md b/agent-os/standards/backend/immutable-connection-switch.md deleted file mode 100644 index e034d9f..0000000 --- a/agent-os/standards/backend/immutable-connection-switch.md +++ /dev/null @@ -1,26 +0,0 @@ -# Immutable Connection Switch - -`connection()` CLONES the instance and swaps the client — it does NOT mutate in place. - -Exception to the mutate-and-return-`$this` norm. Cloning lets one configured base builder branch to multiple connections without a switch clobbering earlier references, and avoids retroactively mutating shared state mid-chain. - -```php -public function connection(string $name): static -{ - if (! $this->manager) { - throw new \RuntimeException('Elasticsearch manager not available. Cannot switch connections.'); - } - - $clone = clone $this; - $clone->client = new ElasticsearchClient($this->manager->connection($name)); - $clone->connectionName = $name; - - return $clone; -} -``` - -- All accumulated state (query clauses, cache settings) survives the clone, so `connection()` is valid at any point in the chain. -- Requires `$this->manager`; throw if absent. -- `getConnectionName()` falls back: `$connectionName ?? manager default ?? 'default'`. The name feeds the cache key so per-connection results don't collide. - -See [[structural-cache-keys]] for how the connection name scopes the cache key. diff --git a/agent-os/standards/backend/lazy-cached-connections.md b/agent-os/standards/backend/lazy-cached-connections.md deleted file mode 100644 index be16868..0000000 --- a/agent-os/standards/backend/lazy-cached-connections.md +++ /dev/null @@ -1,16 +0,0 @@ -# Lazy Cached Connections - -`ElasticsearchManager` builds clients on first use and caches them by name. Purging forgets container singletons too. - -```php -public function connection(?string $name = null): Client -{ - $name = $name ?: $this->getDefaultConnection(); - return $this->connections[$name] ??= $this->makeConnection($name); -} -``` - -- Connections are lazy: never built until requested; cached in `$connections[$name]` thereafter. -- `purge($name)` / `disconnect()` clear the cache AND call `forgetInstance()` on `Client::class`, `ClientContract::class`, `'stretch'`. - - Long-running runtimes (Octane, workers) resolve those singletons once; without forgetting they'd hold a stale connection after a purge. Forgetting forces a rebuild against a fresh connection and releases the old one. - - `forgetInstance()` is guarded by `method_exists($this->app, ...)` — no-op outside a full Laravel container (see [[shared-trait-duck-typing]]). diff --git a/agent-os/standards/backend/named-msearch.md b/agent-os/standards/backend/named-msearch.md deleted file mode 100644 index 8cd46ea..0000000 --- a/agent-os/standards/backend/named-msearch.md +++ /dev/null @@ -1,24 +0,0 @@ -# Named msearch by Key - -`MultiQueryBuilder` pairs named queries to positional msearch responses by sorting keys identically at build AND remap. - -Elasticsearch `_msearch` returns a positional `responses[]` array. Sorting the queries the same way in both places guarantees each name lines up with its own result, and makes the cache key order-independent. - -```php -// build(): sortKeys() before emitting header/body pairs -$queries = collect($this->queries)->sortKeys()->toArray(); - -// execute(): remap positional responses back onto the sorted names -$key = -1; -$results['responses'] = collect($this->queries)->sortKeys()->map(function () use (&$results, &$key) { - $key++; - return Arr::get($results, "responses.{$key}"); -})->toArray(); -``` - -- `add($name, ...)` uses `$name` as the index fallback when the sub-query sets none (`getIndex() ?? $name`). -- Callers read results by name: `$results['responses']['posts']`. -- Empty builder short-circuits: `execute()` returns `['responses' => []]` without hitting ES. -- Any change to build ordering MUST be mirrored in the remap, or names and results desync silently. - -See [[structural-cache-keys]] — sorted build() is what makes the multi cache key order-stable. diff --git a/agent-os/standards/backend/per-query-config-fallback.md b/agent-os/standards/backend/per-query-config-fallback.md deleted file mode 100644 index 289cf51..0000000 --- a/agent-os/standards/backend/per-query-config-fallback.md +++ /dev/null @@ -1,17 +0,0 @@ -# Per-Query Override, Config Fallback - -Configurable settings are stored nullable and resolved in the getter as `per-query ?? config default`. - -- `null` = untouched → use config. An explicit value is a deliberate per-query choice that MUST win over config. -- Resolve lazily in the getter, never eager-default in the constructor — the builder may exist before/outside a booted app, so config is read only when needed: - ```php - protected ?bool $cacheEnabled = null; - - public function getCacheEnabled(): bool - { - return $this->cacheEnabled ?? (bool) config('stretch.cache.enabled', false); - } - ``` -- Pattern repeats for every setting: enabled, ttl, prefix, store. Setter stores the raw value; getter applies the fallback. -- Provide a bare-verb alias where it reads well (`cache()` → `setCacheEnabled()`, `clearCache()` → `setCacheClear()`). -- config() calls always pass a hard-coded default as the 2nd arg — never assume the config key is published. diff --git a/agent-os/standards/backend/raw-escape-hatch.md b/agent-os/standards/backend/raw-escape-hatch.md deleted file mode 100644 index f524d82..0000000 --- a/agent-os/standards/backend/raw-escape-hatch.md +++ /dev/null @@ -1,12 +0,0 @@ -# raw() Escape Hatches - -Every builder area pairs typed helpers with a raw escape hatch. No ES feature is ever unreachable. - -- Typed helpers cover common DSL (`terms()`, `dateHistogram()`, `match()`, ...). -- `raw()` / `rawAggregation()` is the permanent fallback for long-tail or uncovered structures — pass the ES array through verbatim: - ```php - $agg->raw('my_agg', ['filter' => [...], 'aggs' => [...]]); - $builder->rawAggregation('price_stats', ['stats' => ['field' => 'price']]); - ``` -- Add a typed helper when a pattern is used often; leave rare/one-off structures on raw() to keep the API surface small. -- Never block a feature behind "not implemented" — raw() must always accept it. diff --git a/agent-os/standards/backend/shared-trait-duck-typing.md b/agent-os/standards/backend/shared-trait-duck-typing.md deleted file mode 100644 index 1b1651b..0000000 --- a/agent-os/standards/backend/shared-trait-duck-typing.md +++ /dev/null @@ -1,19 +0,0 @@ -# Shared Trait Duck-Typing - -Shared traits detect host capabilities at runtime (`method_exists`/`property_exists`), not via a required interface. - -`IsCacheable` serves two differently-shaped hosts — `ElasticsearchQueryBuilder` (single `getIndex()`) and `MultiQueryBuilder` (a `queries` array) — without forcing a common contract or abstract methods on either. - -```php -if (method_exists($this, 'getIndex')) { - $indexes = $indexes->push($this->getIndex()); -} - -if (property_exists($this, 'queries')) { - $indexes = collect($this->queries)->pluck('index'); -} -``` - -- Use when one trait must adapt to hosts with divergent shapes. Each branch handles one host's structure. -- PHPStan narrows these as always-true per host; suppress with `@phpstan-ignore function.alreadyNarrowedType` on the check — expected, not a smell. -- Don't reach for this when hosts share a real contract — prefer an interface/abstract method then. Duck-typing is for genuinely divergent shapes only. diff --git a/agent-os/standards/backend/structural-cache-keys.md b/agent-os/standards/backend/structural-cache-keys.md deleted file mode 100644 index f464797..0000000 --- a/agent-os/standards/backend/structural-cache-keys.md +++ /dev/null @@ -1,24 +0,0 @@ -# Structural Cache Keys - -Cache key = prefix + connection + indexes + `sha1(serialize(Arr::sortRecursive(build())))`. - -The key is derived from the built query STRUCTURE, not a manual string. `sortRecursive` normalizes clause/key order so the same logical query always yields the same key regardless of build order — order variations don't fragment the cache. - -```php -public function getCacheKey(): string -{ - $sorted = Arr::sortRecursive($this->build()); - $hash = sha1(serialize($sorted)); - $indexes = $this->getIndexes()->implode(':'); - - return '{'.$this->getCachePrefix().$this->getConnectionName().':'.$indexes.$hash.'}'; -} -``` - -- The whole key is wrapped in a Redis cluster hash tag (`{...}`) so `flexible()` can MGET the key and its `illuminate:cache:flexible:created:` twin from one cluster slot. Don't drop the braces — clustered Redis rejects the cross-slot read. - -- Scoped by connection AND index: identical queries on different connections/indexes get distinct keys — no cross-connection collisions. -- `build()` must stay pure (no side effects) so key generation is safe to call independently of `execute()`. -- Any new state that changes query semantics MUST flow through `build()`, or it won't affect the key and will serve stale cache. - -See [[fluent-builder]] (build() purity) and [[immutable-connection-switch]] (connection scoping). diff --git a/agent-os/standards/backend/tolerate-response-shapes.md b/agent-os/standards/backend/tolerate-response-shapes.md deleted file mode 100644 index 2f229d0..0000000 --- a/agent-os/standards/backend/tolerate-response-shapes.md +++ /dev/null @@ -1,20 +0,0 @@ -# Tolerate Varied ES Response Shapes - -Parse responses defensively: `data_get` with defaults, and handle both `hits.total` forms. - -ES returns `hits.total` as an object (`{value, relation}`) by default, but as a bare int under `rest_total_hits_as_int`. The parser must accept either so pagination works under both — and never crash on a missing key. - -```php -$total = data_get($response, 'hits.total', 0); - -return new ElasticPaginator( - items: data_get($response, 'hits.hits', []), - total: is_array($total) ? ($total['value'] ?? 0) : (int) $total, - perPage: $size ?: config('stretch.query.default_size'), - currentPage: $size ? (int) floor($request->getFrom() / $size) + 1 : 1, -); -``` - -- Reach into response nesting with `data_get($response, 'a.b.c', $default)`, never raw `$response['a']['b']` — missing keys must degrade, not fatal. -- Normalize both total shapes: `is_array($total) ? $total['value'] ?? 0 : (int) $total`. -- Derive the current page from the builder's `from`/`size` (`floor(from/size)+1`), guarding division when size is 0/null. diff --git a/agent-os/standards/backend/wrap-client-exceptions.md b/agent-os/standards/backend/wrap-client-exceptions.md deleted file mode 100644 index 5f57bea..0000000 --- a/agent-os/standards/backend/wrap-client-exceptions.md +++ /dev/null @@ -1,24 +0,0 @@ -# Wrap All Client Calls in StretchException - -Every `ElasticsearchClient` method wraps the native call in try/catch and rethrows as `StretchException`. Consumers catch one exception type. - -```php -public function search(array $params): array -{ - try { - $this->logQuery($params); - $response = $this->client->search($params)->asArray(); - $this->logSlowQuery($params, $response); - return $response; - } catch (Exception $exception) { - throw new StretchException("Search failed: {$exception->getMessage()}", (int) $exception->getCode(), $exception); - } -} -``` - -- Message states the operation + context (`"Failed to create index '{$index}': ..."`). -- Preserve the chain: pass `(int) $exception->getCode()` and the original as `previous`. -- Always `->asArray()` the native response — the contract returns plain arrays, never native response objects. -- **404-only carve-out**: `indexExists()` treats only a `ClientResponseException` with code 404 as `false`; every other error rethrows. `false` must mean exactly "does not exist" — masking auth/connectivity/server errors as absence is a correctness bug. - -See [[contract-first-di]] — this wrapper is the only place native-client exceptions surface. diff --git a/agent-os/standards/index.yml b/agent-os/standards/index.yml deleted file mode 100644 index 1318e97..0000000 --- a/agent-os/standards/index.yml +++ /dev/null @@ -1,44 +0,0 @@ -# Agent OS Standards Index - -backend: - callback-sub-builders: - description: Composite clauses use a fresh sub-builder; parent extracts build() result. - config-safe-defaults: - description: Throw on missing/empty connection; SSL verify defaults ON unless opted out. - contract-first-di: - description: Depend on contracts; native ES client wrapped behind ClientContract. - empty-clause-skip: - description: Skip attaching callback clauses that add no query, avoiding invalid ES DSL. - facade-method-sync: - description: Mirror every public Stretch method as an @method static tag on the facade. - fluent-builder: - description: Chainable static-returning methods; build() assembles, execute() sends; single-clause unwrap. - guard-builder-options: - description: build() throws LogicException when an option is used on an unsupported type. - immutable-connection-switch: - description: connection() clones and swaps client instead of mutating in place. - lazy-cached-connections: - description: Manager lazy-builds/caches clients by name; purge forgets container singletons. - named-msearch: - description: MultiQueryBuilder sorts keys at build and remap so names pair to positional responses. - per-query-config-fallback: - description: Nullable settings resolved as per-query value ?? config default, lazily in getters. - raw-escape-hatch: - description: Typed helpers for common DSL, raw()/rawAggregation() as guaranteed fallback. - shared-trait-duck-typing: - description: Shared traits detect host shape via method_exists/property_exists, not an interface. - structural-cache-keys: - description: Cache key from sha1 of sorted build(), scoped by connection and index. - tolerate-response-shapes: - description: Parse ES responses with data_get defaults; handle both hits.total int and object forms. - wrap-client-exceptions: - description: Every client call wraps native errors in StretchException; indexExists 404-only false. -testing: - mock-client-contract: - description: Mock ClientContract with Mockery; assert payload via m::on or literal ->with. - pest-style: - description: Pest it() behavior phrases with fluent expect()->and() chains; ->throws for exceptions. - test-build-output: - description: Query-shape tests use a bare builder and assert build() output, no client. - testbench-harness: - description: Orchestra Testbench + Workbench; inline config() in beforeEach; array cache store. diff --git a/agent-os/standards/testing/mock-client-contract.md b/agent-os/standards/testing/mock-client-contract.md deleted file mode 100644 index 0aab825..0000000 --- a/agent-os/standards/testing/mock-client-contract.md +++ /dev/null @@ -1,27 +0,0 @@ -# Mock ClientContract for Dispatch Tests - -Mock `ClientContract` with Mockery to test dispatch; assert the outgoing payload. - -```php -use Mockery as m; - -$mockClient = m::mock(ClientContract::class); -$mockClient->shouldReceive('search') - ->once() - ->with(m::on(fn ($params) => - $params['index'] === 'posts' - && isset($params['body']['query']['bool']['filter']) - )) - ->andReturn(['hits' => ['total' => ['value' => 0], 'hits' => []]]); - -(new ElasticsearchQueryBuilder($mockClient))->index('posts')->/* ... */->execute(); -``` - -- Mock the `ClientContract` interface, never the native ES client. -- `->once()` (or `->twice()`) to pin call count. -- Payload assertion, pick by shape: - - `m::on(fn ($params) => ...)` for search/delete bodies — check only the keys that matter, tolerant of default noise (`size`, `from`). - - literal `->with([...])` for small exact payloads (index/update/delete doc ops). -- `andReturn()` a realistic ES response shape (`['hits' => ['total' => ..., 'hits' => []]]`, `['result' => 'created']`, `['deleted' => N]`). - -See [[test-build-output]] — use this ONLY when dispatch is under test, not DSL shape. diff --git a/agent-os/standards/testing/pest-style.md b/agent-os/standards/testing/pest-style.md deleted file mode 100644 index b4bb607..0000000 --- a/agent-os/standards/testing/pest-style.md +++ /dev/null @@ -1,16 +0,0 @@ -# Pest Test Style - -Tests use Pest `it()` with a behavior phrase and fluent `expect()` chains. No class methods, no `describe` blocks. - -```php -it('wraps query in body when executing', function () { - // ... - expect($query['query']['multi_match']['query'])->toBe('laptop for work') - ->and($query['query']['multi_match']['fields'])->toBe(['title^3']); -}); -``` - -- `it('', fn)` — phrasing is free (describe the behavior); no PHPUnit test-method style. -- Chain related assertions with `->and(...)` off a single `expect()`; separate `expect()` calls are fine for unrelated ones. -- Assert exact values with `->toBe()`; use `->toHaveKey()` / `->not->toHaveKey()` for presence/absence. -- Expected-exception tests use the trailing modifier: `it('throws when ...', fn () => ...)->throws(RuntimeException::class);` diff --git a/agent-os/standards/testing/test-build-output.md b/agent-os/standards/testing/test-build-output.md deleted file mode 100644 index ce3381e..0000000 --- a/agent-os/standards/testing/test-build-output.md +++ /dev/null @@ -1,20 +0,0 @@ -# Test build() Output, Not execute() - -Query-shape tests construct a bare builder (no client) and assert on `build()` — never mock ES. - -`build()` is pure, so DSL-structure assertions need no Elasticsearch or mock: fast, deterministic, and they test the array mapping directly. Keeps structure tests isolated from dispatch tests. - -```php -it('can create a match query', function () { - $builder = new ElasticsearchQueryBuilder; // no client - $builder->match('title', 'Laravel'); - $query = $builder->build(); - expect($query['query']['match']['title']['query'])->toBe('Laravel'); -}); -``` - -- Mock the client ONLY when the thing under test is dispatch/wrapping/facade behavior (see [[mock-client-contract]]). -- Assert the exact DSL path, not just presence — `$query['query']['range']['created_at']['gte']`. -- Assert absence too where it matters: `expect($query)->not->toHaveKey('track_total_hits')`. - -See [[fluent-builder]] for why build() is pure. diff --git a/agent-os/standards/testing/testbench-harness.md b/agent-os/standards/testing/testbench-harness.md deleted file mode 100644 index f09d642..0000000 --- a/agent-os/standards/testing/testbench-harness.md +++ /dev/null @@ -1,28 +0,0 @@ -# Testbench Harness - -Tests run on Orchestra Testbench + Workbench. Set config inline; bind TestCase in Pest.php. - -```php -// tests/TestCase.php -class TestCase extends Orchestra -{ - use WithWorkbench; -} - -// tests/Pest.php -uses(TestCase::class)->in('Feature'); -uses(TestCase::class)->in('Unit'); -``` - -- `TestCase extends Orchestra\Testbench\TestCase` with `WithWorkbench`. Both `Feature` and `Unit` dirs bind it via `Pest.php`. -- No real published config under Testbench — set config the code reads in `beforeEach`, giving each test deterministic, isolated values: - ```php - beforeEach(function () { - config(['stretch.cache.enabled' => false]); - config(['stretch.cache.store' => 'array']); - }); - ``` -- Use the `array` cache store in tests — no filesystem, no cross-test leakage. -- Split: `Unit/` = builders with no app boot needed (bare `new Builder`); `Feature/` = Stretch facade / service-wired behavior. - -Relates to [[per-query-config-fallback]] — the getters these tests exercise fall back to this config. diff --git a/docs/agent/product/.gitkeep b/docs/agent/product/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/docs/agent/specs/.gitkeep b/docs/agent/specs/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/docs/agent/standards-feedback.md b/docs/agent/standards-feedback.md new file mode 100644 index 0000000..aae7fe6 --- /dev/null +++ b/docs/agent/standards-feedback.md @@ -0,0 +1,8 @@ +# Standards Feedback + +Every time work has to break a standard, add a row. + +| Date | Spec | Standard | Deviation | Why | +| --- | --- | --- | --- | --- | +| 2026-10-23 | standards cleanup | errors/exceptions | `ElasticsearchManager::getConnectionConfig()` (`src/Domains/Connection/Services/ElasticsearchManager.php`) throws raw `\InvalidArgumentException` for a connection that is not configured or has no hosts (was agent-os `backend/config-safe-defaults`). | follow-up: add StretchException and throw subclasses (a `StretchException` already exists in `src/Exceptions/` but extends `Exception`, not `RuntimeException`, and has no subclasses) | +| 2026-10-23 | standards cleanup | errors/exceptions | `AggregationBuilder::build()` (`src/Domains/Aggregation/Builders/AggregationBuilder.php`) throws raw `LogicException` when `size()` is used on a non-terms aggregation or `orderBy()` on a type other than terms/histogram/date_histogram (was agent-os `backend/guard-builder-options`). | follow-up: add StretchException and throw subclasses (a `StretchException` already exists in `src/Exceptions/` but extends `Exception`, not `RuntimeException`, and has no subclasses) | diff --git a/docs/agent/standards/stretch/callback-sub-builders.md b/docs/agent/standards/stretch/callback-sub-builders.md new file mode 100644 index 0000000..511d685 --- /dev/null +++ b/docs/agent/standards/stretch/callback-sub-builders.md @@ -0,0 +1,32 @@ +--- +description: "Composite clauses use a fresh sub-builder; parent extracts build() result." +tags: [stretch, query-builder, sub-builders] +kind: convention +--- + +# Callback Sub-Builders + +Composite clauses take a callback that receives a fresh builder, and the parent reads only that builder's built result. + +## Why + +- Sub-query state stays isolated from the parent; nothing leaks across clause boundaries. + +## Rules + +- Query-context clauses (`nested`, `filter`, `postFilter`) pass `$this->client, $this->manager`, so connection context carries into the sub-builder. +- Pure structural sub-builders build without executing and need no client: `BoolQueryBuilder` (`new ElasticsearchQueryBuilder`), `AggregationBuilder`, `RetrieverBuilder`. +- The parent reads `$sub->build()['query']` (or `->build()` for aggregations and retrievers), never the sub-builder's internals. +- A new composite clause gets its own builder class implementing its contract; clause assembly is never inlined in the main builder. + +```php +public function nested(string $path, callable $callback): static +{ + $sub = new ElasticsearchQueryBuilder($this->client, $this->manager); + $callback($sub); + $query = $sub->build()['query'] ?? null; + // ...attach (see empty-clause-skip) +} +``` + +See [[empty-clause-skip]] for the null-skip rule on the extracted query. diff --git a/docs/agent/standards/stretch/connection-config.md b/docs/agent/standards/stretch/connection-config.md new file mode 100644 index 0000000..b5ab69a --- /dev/null +++ b/docs/agent/standards/stretch/connection-config.md @@ -0,0 +1,26 @@ +--- +description: "Connection config: missing/empty connection throws a StretchException subclass; ssl_verification ?? true; timeouts only when declared." +tags: [stretch, config, connections, security] +kind: convention +--- + +# Connection Config + +Complements [[configuration]] for the `stretch.connections` entries that `ElasticsearchManager` turns into clients. + +## Rules + +- A missing connection, or one with empty `hosts`, throws right away with the connection name in `[…]`. It throws a `StretchException` subclass per [[exceptions]], not `InvalidArgumentException`. +- SSL verification defaults on: read `$config['ssl_verification'] ?? true` and only call `setSSLVerification(false)` when a connection turns it off explicitly. +- Optional HTTP hardening (`connect_timeout`, `timeout`) is passed only when the connection declares it. `array_filter` the nulls out, so an absent key never overrides the client's own default. + +```php +if (! ($config['ssl_verification'] ?? true)) { + $clientBuilder->setSSLVerification(false); +} + +$httpOptions = array_filter([ + 'connect_timeout' => $config['connect_timeout'] ?? null, + 'timeout' => $config['timeout'] ?? null, +]); +``` diff --git a/docs/agent/standards/stretch/connection-purge.md b/docs/agent/standards/stretch/connection-purge.md new file mode 100644 index 0000000..51993fb --- /dev/null +++ b/docs/agent/standards/stretch/connection-purge.md @@ -0,0 +1,14 @@ +--- +description: "Manager lazy-builds/caches clients by name; purge forgets container singletons." +tags: [stretch, connections, container, octane] +kind: convention +--- + +# Connection Purge + +Complements [[container-bindings]]: `ElasticsearchManager` names exactly which singletons a purge forgets. + +## Rules + +- `purge($name)` and `disconnect()` clear `$connections[$name]` and call `forgetInstance()` on `Client::class`, `ClientContract::class` and `'stretch'`. +- `forgetInstance()` is guarded by `method_exists($this->app, ...)`, so it is a no-op outside a full Laravel container (see [[shared-trait-duck-typing]]). diff --git a/docs/agent/standards/stretch/empty-clause-skip.md b/docs/agent/standards/stretch/empty-clause-skip.md new file mode 100644 index 0000000..9d86d08 --- /dev/null +++ b/docs/agent/standards/stretch/empty-clause-skip.md @@ -0,0 +1,28 @@ +--- +description: "Skip attaching callback clauses that add no query, avoiding invalid ES DSL." +tags: [stretch, query-builder, elasticsearch, dsl] +kind: convention +--- + +# Empty-Clause Skip + +A composite clause that receives a callback skips attachment when the callback adds no query. + +## Why + +- An empty `bool`, `nested` or `filter` clause makes Elasticsearch reject the whole request. Skipping keeps requests valid when a callback conditionally adds nothing. + +## Rules + +- Build the sub-query, read `build()['query'] ?? null`, and return early on `null`. +- Applies to `nested()`, `filter()`, `postFilter()`, and `BoolQueryBuilder` must/should/filter/mustNot (through `buildSubQuery()`). +- Every new composite or callback clause follows this. Never emit `{"bool": {}}` or a `nested` with no query. + +```php +$sub = new ElasticsearchQueryBuilder; +$callback($sub); +$query = $sub->build()['query'] ?? null; +if ($query === null) { + return $this; // never attach an empty clause +} +``` diff --git a/docs/agent/standards/stretch/fluent-builder.md b/docs/agent/standards/stretch/fluent-builder.md new file mode 100644 index 0000000..174b0f8 --- /dev/null +++ b/docs/agent/standards/stretch/fluent-builder.md @@ -0,0 +1,30 @@ +--- +description: "Chainable static-returning methods; build() assembles, execute() sends; single-clause unwrap." +tags: [stretch, query-builder, fluent] +kind: convention +--- + +# Fluent Builder + +Builder methods record state and return `static`; `build()` assembles the body and `execute()` sends it. + +## Chaining + +- Every clause or option method returns `$this` (typed `static`). Sub-builder entry points (`range()`, `bool()` without a callback) return the sub-builder instead. +- State lives in typed protected arrays and scalars (`$query`, `$aggregations`, `$sort`, `$size`, ...). Methods append; nothing reaches Elasticsearch until `execute()`. + +## build() and execute() + +- `build()` is pure: it assembles and returns the array body with no side effects. `toArray()` is its alias for inspection. +- `execute()` calls `build()`, wraps it in `['index' => ..., 'body' => ...]`, stores `$lastQuery` and dispatches through the client. +- Precedence in `build()`: `retriever` replaces query and knn entirely (early return); else top-level `knn`; else the query (with `filters` wrapped in `bool.filter`). + +## Single-clause unwrap + +- A lone clause is emitted bare; only multiple clauses wrap in `bool.must`, so a single `match` reads like hand-written DSL. + +```php +count($this->query) === 1 + ? $body['query'] = $this->query[0] // { "match": {...} } + : $body['query'] = ['bool' => ['must' => $this->query]]; +``` diff --git a/docs/agent/standards/stretch/guard-builder-options.md b/docs/agent/standards/stretch/guard-builder-options.md new file mode 100644 index 0000000..66e0ea4 --- /dev/null +++ b/docs/agent/standards/stretch/guard-builder-options.md @@ -0,0 +1,35 @@ +--- +description: "AggregationBuilder::build() throws a StretchException subclass when size()/orderBy() hit an unsupported type; terms size clamped to max_buckets." +tags: [stretch, aggregations, builders, errors] +kind: convention +--- + +# Guard Builder Options + +When a builder option only applies to certain aggregation types, `build()` rejects misuse instead of silently dropping it. + +## Why + +- A silently ignored option hides a coding mistake. Failing at build time with a clear message beats a cryptic Elasticsearch parse error later. + +## Rules + +- An option used on an unsupported type throws a `StretchException` subclass per [[exceptions]], never a raw `LogicException`. +- Validate in `build()`, not in the setter: the setter does not yet know the final aggregation type. +- The message names the offending option and the actual type, from `$this->aggregationType()`, wrapped in `[…]`. +- `size()` is supported on `terms` only. +- `orderBy()` is supported on `terms`, `histogram` and `date_histogram` only. +- A `terms` aggregation always gets a clamped size: `min(size ?? stretch.aggregations.default_size, stretch.aggregations.max_buckets)`, so bucket explosion is capped by default, even when `size()` was never called. + +```php +if (isset($agg['terms'])) { + $agg['terms']['size'] = min( + $this->size ?? config('stretch.aggregations.default_size'), + config('stretch.aggregations.max_buckets'), + ); +} elseif ($this->size !== null) { + throw UnsupportedAggregationOptionException::forOption('size()', $this->aggregationType()); +} +``` + +The exception class name above is illustrative until the follow-up in `docs/agent/standards-feedback.md` lands. diff --git a/docs/agent/standards/stretch/immutable-connection-switch.md b/docs/agent/standards/stretch/immutable-connection-switch.md new file mode 100644 index 0000000..a547748 --- /dev/null +++ b/docs/agent/standards/stretch/immutable-connection-switch.md @@ -0,0 +1,29 @@ +--- +description: "connection() clones and swaps client instead of mutating in place." +tags: [stretch, query-builder, connections] +kind: convention +--- + +# Immutable Connection Switch + +`connection()` clones the builder and swaps the client on the clone; it never mutates in place. + +## Why + +- It is the one exception to the mutate-and-return-`$this` rule of [[fluent-builder]]. Cloning lets one configured base builder branch to several connections without a switch clobbering earlier references or changing shared state mid-chain. + +## Rules + +- All accumulated state (query clauses, cache settings) survives the clone, so `connection()` is valid at any point in the chain. +- It requires `$this->manager` and throws when the manager is absent. +- `getConnectionName()` falls back as `$connectionName ?? manager default ?? 'default'`. The name feeds the cache key, so per-connection results never collide. + +```php +$clone = clone $this; +$clone->client = new ElasticsearchClient($this->manager->connection($name)); +$clone->connectionName = $name; + +return $clone; +``` + +See [[structural-cache-keys]] for how the connection name scopes the cache key. diff --git a/docs/agent/standards/stretch/named-msearch.md b/docs/agent/standards/stretch/named-msearch.md new file mode 100644 index 0000000..1e940e8 --- /dev/null +++ b/docs/agent/standards/stretch/named-msearch.md @@ -0,0 +1,35 @@ +--- +description: "MultiQueryBuilder sorts keys at build and remap so names pair to positional responses." +tags: [stretch, multi-search, msearch, elasticsearch] +kind: convention +--- + +# Named msearch + +`MultiQueryBuilder` sorts query names the same way at build and at remap, so each name pairs with its positional `_msearch` response. + +## Why + +- `_msearch` returns a positional `responses[]` array. Identical sorting in both places lines each name up with its own result and makes the cache key order-independent. + +## Rules + +- `build()` calls `sortKeys()` before emitting header/body pairs; `execute()` remaps the positional responses onto the same sorted names. +- `add($name, ...)` uses `$name` as the index when the sub-query sets none (`getIndex() ?? $name`). +- Callers read results by name: `$results['responses']['posts']`. +- An empty builder short-circuits: `execute()` returns `['responses' => []]` without calling Elasticsearch. +- Any change to build ordering is mirrored in the remap, or names and results desync silently. + +```php +// build() +$queries = collect($this->queries)->sortKeys()->toArray(); + +// execute() +$key = -1; +$results['responses'] = collect($this->queries)->sortKeys()->map(function () use (&$results, &$key) { + $key++; + return Arr::get($results, "responses.{$key}"); +})->toArray(); +``` + +See [[structural-cache-keys]]: the sorted `build()` keeps the multi-query cache key stable. diff --git a/docs/agent/standards/stretch/per-query-config-fallback.md b/docs/agent/standards/stretch/per-query-config-fallback.md new file mode 100644 index 0000000..92ef2ea --- /dev/null +++ b/docs/agent/standards/stretch/per-query-config-fallback.md @@ -0,0 +1,25 @@ +--- +description: "Nullable settings resolved as per-query value ?? config default, lazily in getters." +tags: [stretch, config, query-builder, caching] +kind: convention +--- + +# Per-Query Config Fallback + +Complements [[configuration]]: builder settings are stored nullable and resolved lazily in their getters. + +## Rules + +- A setting property is nullable; `null` means untouched and falls back to config. +- The setter stores the raw value; the getter applies `per-query ?? config(...)`. Never default eagerly in the constructor: the builder may exist before or outside a booted app. +- The pattern covers every cache setting: enabled, ttl, prefix, store. +- Provide a bare-verb alias where it reads well: `cache()` for `setCacheEnabled()`, `clearCache()` for `setCacheClear()`. + +```php +protected ?bool $cacheEnabled = null; + +public function getCacheEnabled(): bool +{ + return $this->cacheEnabled ?? (bool) config('stretch.cache.enabled', false); +} +``` diff --git a/docs/agent/standards/stretch/raw-escape-hatch.md b/docs/agent/standards/stretch/raw-escape-hatch.md new file mode 100644 index 0000000..b432d14 --- /dev/null +++ b/docs/agent/standards/stretch/raw-escape-hatch.md @@ -0,0 +1,21 @@ +--- +description: "Typed helpers for common DSL, raw()/rawAggregation() as guaranteed fallback." +tags: [stretch, query-builder, aggregations, dsl] +kind: convention +--- + +# raw() Escape Hatches + +Every builder area pairs typed helpers with a raw escape hatch, so no Elasticsearch feature is ever unreachable. + +## Rules + +- Typed helpers cover common DSL (`terms()`, `dateHistogram()`, `match()`, ...). +- `raw()` / `rawAggregation()` is the permanent fallback for long-tail structures and passes the array through verbatim. +- Add a typed helper when a pattern is used often; leave rare structures on `raw()` to keep the API small. +- Never block a feature behind "not implemented"; `raw()` always accepts it. + +```php +$agg->raw('my_agg', ['filter' => [...], 'aggs' => [...]]); +$builder->rawAggregation('price_stats', ['stats' => ['field' => 'price']]); +``` diff --git a/docs/agent/standards/stretch/shared-trait-duck-typing.md b/docs/agent/standards/stretch/shared-trait-duck-typing.md new file mode 100644 index 0000000..1e01c76 --- /dev/null +++ b/docs/agent/standards/stretch/shared-trait-duck-typing.md @@ -0,0 +1,29 @@ +--- +description: "Shared traits detect host shape via method_exists/property_exists, not an interface." +tags: [stretch, traits, caching] +kind: convention +--- + +# Shared Trait Duck-Typing + +A shared trait detects its host's shape at runtime with `method_exists`/`property_exists` instead of requiring an interface. + +## Where + +- `IsCacheable` serves two differently shaped hosts: `ElasticsearchQueryBuilder` (a single `getIndex()`) and `MultiQueryBuilder` (a `queries` array), without forcing a common contract on either. + +## Rules + +- Use it only when one trait must adapt to hosts with genuinely divergent shapes; each branch handles one host's structure. +- When hosts share a real contract, use an interface or abstract method instead. +- PHPStan narrows these checks as always-true per host; suppress with `@phpstan-ignore function.alreadyNarrowedType` on the check. + +```php +if (method_exists($this, 'getIndex')) { + $indexes = $indexes->push($this->getIndex()); +} + +if (property_exists($this, 'queries')) { + $indexes = collect($this->queries)->pluck('index'); +} +``` diff --git a/docs/agent/standards/stretch/structural-cache-keys.md b/docs/agent/standards/stretch/structural-cache-keys.md new file mode 100644 index 0000000..559595e --- /dev/null +++ b/docs/agent/standards/stretch/structural-cache-keys.md @@ -0,0 +1,30 @@ +--- +description: "Cache key from sha1 of sorted build(), scoped by connection and index." +tags: [stretch, caching, redis, query-builder] +kind: convention +--- + +# Structural Cache Keys + +The cache key is prefix + connection + indexes + `sha1(serialize(Arr::sortRecursive(build())))`, derived from the query's structure rather than a hand-written string. + +## Rules + +- `sortRecursive` normalizes clause and key order, so the same logical query always yields the same key. +- Keys are scoped by connection and index; identical queries on different connections or indexes never collide. +- The whole key is wrapped in a Redis cluster hash tag (`{...}`) so `flexible()` can MGET the key and its `illuminate:cache:flexible:created:` twin from one slot. Never drop the braces; clustered Redis rejects the cross-slot read. +- `build()` stays pure so the key can be computed independently of `execute()`. +- Any new state that changes query semantics flows through `build()`, or it will not affect the key and stale cache is served. + +```php +public function getCacheKey(): string +{ + $sorted = Arr::sortRecursive($this->build()); + $hash = sha1(serialize($sorted)); + $indexes = $this->getIndexes()->implode(':'); + + return '{'.$this->getCachePrefix().$this->getConnectionName().':'.$indexes.$hash.'}'; +} +``` + +See [[fluent-builder]] and [[immutable-connection-switch]]. diff --git a/docs/agent/standards/stretch/testbench-harness.md b/docs/agent/standards/stretch/testbench-harness.md new file mode 100644 index 0000000..f1ffa3a --- /dev/null +++ b/docs/agent/standards/stretch/testbench-harness.md @@ -0,0 +1,24 @@ +--- +description: "TestCase extends Orchestra with WithWorkbench; config set inline in beforeEach; array cache store." +tags: [stretch, testing, testbench] +kind: convention +--- + +# Testbench Harness + +How the Testbench `TestCase` is set up and fed config. Which tests may boot it is in [[test-layers]]. + +## Rules + +- `tests/TestCase.php` extends `Orchestra\Testbench\TestCase` and uses `WithWorkbench`. +- There is no published config under Testbench. Set every key the code under test reads in `beforeEach`, so each test gets deterministic, isolated values. +- Use the `array` cache store in tests: no filesystem, no leakage between tests. + +```php +beforeEach(function () { + config(['stretch.cache.enabled' => false]); + config(['stretch.cache.store' => 'array']); +}); +``` + +Relates to [[per-query-config-fallback]]: the getters these tests exercise fall back to this config. diff --git a/docs/agent/standards/stretch/tolerate-response-shapes.md b/docs/agent/standards/stretch/tolerate-response-shapes.md new file mode 100644 index 0000000..804585c --- /dev/null +++ b/docs/agent/standards/stretch/tolerate-response-shapes.md @@ -0,0 +1,30 @@ +--- +description: "Parse ES responses with data_get defaults; handle both hits.total int and object forms." +tags: [stretch, elasticsearch, pagination, responses] +kind: convention +--- + +# Tolerate Response Shapes + +Parse Elasticsearch responses defensively with `data_get` defaults, accepting both forms of `hits.total`. + +## Why + +- `hits.total` is an object (`{value, relation}`) by default but a bare int under `rest_total_hits_as_int`; pagination works under both and never crashes on a missing key. + +## Rules + +- Read nested values with `data_get($response, 'a.b.c', $default)`, never `$response['a']['b']`. +- Normalize the total: `is_array($total) ? $total['value'] ?? 0 : (int) $total`. +- Derive the current page from the builder's `from`/`size` (`floor(from / size) + 1`), guarding a `0` or `null` size. + +```php +$total = data_get($response, 'hits.total', 0); + +return new ElasticPaginator( + items: data_get($response, 'hits.hits', []), + total: is_array($total) ? ($total['value'] ?? 0) : (int) $total, + perPage: $size ?: config('stretch.query.default_size'), + currentPage: $size ? (int) floor($request->getFrom() / $size) + 1 : 1, +); +``` diff --git a/docs/agent/standards/testing/mock-client-contract.md b/docs/agent/standards/testing/mock-client-contract.md new file mode 100644 index 0000000..6c0f41f --- /dev/null +++ b/docs/agent/standards/testing/mock-client-contract.md @@ -0,0 +1,32 @@ +--- +description: "Mock ClientContract with Mockery; assert payload via m::on or literal ->with." +tags: [stretch, testing, mockery, client] +kind: convention +--- + +# Mock ClientContract + +Dispatch tests mock `ClientContract` with Mockery and assert the outgoing payload. + +## Rules + +- Mock the `ClientContract` interface, never the native Elasticsearch client. +- Pin the call count with `->once()` (or `->twice()`). +- Pick the payload assertion by shape: + - `m::on(fn ($params) => ...)` for search and delete bodies, checking only the keys that matter (tolerant of default `size`, `from`). + - Literal `->with([...])` for small exact payloads (index, update, delete document operations). +- `andReturn()` a realistic response shape: `['hits' => ['total' => ..., 'hits' => []]]`, `['result' => 'created']`, `['deleted' => N]`. +- Use this only when dispatch is under test; for DSL shape see [[test-build-output]]. + +```php +$mockClient = m::mock(ClientContract::class); +$mockClient->shouldReceive('search') + ->once() + ->with(m::on(fn ($params) => + $params['index'] === 'posts' + && isset($params['body']['query']['bool']['filter']) + )) + ->andReturn(['hits' => ['total' => ['value' => 0], 'hits' => []]]); + +(new ElasticsearchQueryBuilder($mockClient))->index('posts')->/* ... */->execute(); +``` diff --git a/docs/agent/standards/testing/pest-style.md b/docs/agent/standards/testing/pest-style.md new file mode 100644 index 0000000..c5aa913 --- /dev/null +++ b/docs/agent/standards/testing/pest-style.md @@ -0,0 +1,24 @@ +--- +description: "Pest it() behavior phrases with fluent expect()->and() chains; ->throws for exceptions." +tags: [stretch, testing, pest] +kind: convention +--- + +# Pest Style + +Tests are Pest `it()` closures named with a behavior phrase and asserted through fluent `expect()` chains. + +## Rules + +- `it('', fn)`; no PHPUnit test classes or methods, no `describe` blocks. +- Chain related assertions with `->and(...)` off one `expect()`; separate `expect()` calls are fine for unrelated ones. +- Assert exact values with `->toBe()`; presence and absence with `->toHaveKey()` / `->not->toHaveKey()`. +- Expected exceptions use the trailing modifier: `it('throws when ...', fn () => ...)->throws(RuntimeException::class);` + +```php +it('wraps query in body when executing', function () { + // ... + expect($query['query']['multi_match']['query'])->toBe('laptop for work') + ->and($query['query']['multi_match']['fields'])->toBe(['title^3']); +}); +``` diff --git a/docs/agent/standards/testing/test-build-output.md b/docs/agent/standards/testing/test-build-output.md new file mode 100644 index 0000000..3480da3 --- /dev/null +++ b/docs/agent/standards/testing/test-build-output.md @@ -0,0 +1,28 @@ +--- +description: "Query-shape tests use a bare builder and assert build() output, no client." +tags: [stretch, testing, query-builder] +kind: convention +--- + +# Test build() Output + +Query-shape tests construct a bare builder with no client and assert on `build()`, never on a mocked dispatch. + +## Why + +- `build()` is pure ([[fluent-builder]]), so DSL-structure tests need neither Elasticsearch nor a mock: fast, deterministic, and isolated from dispatch tests. + +## Rules + +- Mock the client only when dispatch, wrapping or facade behavior is under test; see [[mock-client-contract]]. +- Assert the exact DSL path, not just presence: `$query['query']['range']['created_at']['gte']`. +- Assert absence where it matters: `expect($query)->not->toHaveKey('track_total_hits')`. + +```php +it('can create a match query', function () { + $builder = new ElasticsearchQueryBuilder; // no client + $builder->match('title', 'Laravel'); + $query = $builder->build(); + expect($query['query']['match']['title']['query'])->toBe('Laravel'); +}); +``` diff --git a/docs/agent/standards/testing/test-layers.md b/docs/agent/standards/testing/test-layers.md new file mode 100644 index 0000000..33cba78 --- /dev/null +++ b/docs/agent/standards/testing/test-layers.md @@ -0,0 +1,51 @@ +--- +description: 'Stretch override of the global test-layers standard: behavior tested once at the action, surfaces test only their own wiring, route names not URLs, layer table; TestCase bound in both Unit and Feature because unit tests of classes that read config, cache or the container need Testbench; Feature for facade/provider/service-wired behavior.' +tags: + - testing + - architecture + - layers + - testbench +kind: architectural +overrides: refactor-circus/standards +reviewed_hash: 1cf688063fa0 +--- +# Test Layers + +Behavior is tested once, at the action; each surface tests only its own wiring. + +## Layers + +| Layer | Location | Invokes via | Covers | +|---|---|---|---| +| Unit | `tests/Unit/` | the class directly | One class's logic: builders and their `build()` output, value objects, client wrapping, the connection manager, caching | +| Actions | `tests/Feature/*ActionsTest.php` | `app({Action}::class)->execute(...)` | Business rules, edge cases, guards, events | +| HTTP | `tests/Feature/Http/` | `$this->postJson(route('{package}.…'))` | Status codes, validation mapping, authorization, JSON paths | +| Console | `tests/Feature/Console/` | `$this->artisan('{package}:…')` | Arguments, prompts, output, exit codes | +| Other surfaces | `tests/Feature/{Surface}/` | the surface's own entry point | Its envelope, errors, parity with HTTP | +| Architecture | `tests/ArchTest.php` | `arch()` | Structural rules ([[arch-tests]]) | + +## Rules + +- Do not repeat a business case per surface. A "cannot delete while in use" rule is one action test, not one per surface; the HTTP test only checks that the refusal maps to the right status. +- A surface test proves the surface reaches the action and shapes its result: routing, validation, authorization ([[authorization]]), status, and the resource payload ([[resources]]). +- HTTP tests refer to routes by name, never by literal URL ([[routes]]). +- Set up data with model factories. Shared fixtures (fake implementations, test policies, extra servers) live in `tests/Fixtures/`. + +## Unit vs feature + +Stretch differs from the global rule here: `tests/Unit/` is not framework-free. + +- `TestCase` (Testbench; see [[testbench-harness]]) is bound in both `Unit` and `Feature`, because Stretch classes read config lazily ([[per-query-config-fallback]]), so many unit tests need a booted config repository even for a bare builder. +- A unit test may use what the boot provides only for the class under test's own dependencies: `config()` read by builder getters or `build()`, the cache store behind `Cacheable`, the container that `ElasticsearchManager` resolves and purges. It still instantiates the class directly (`new ElasticsearchQueryBuilder(...)`, a mocked `ClientContract`) and never goes through the `Stretch` facade or the service provider. +- `tests/Feature/` is for behavior wired by the package boot: the `Stretch` facade and root, `StretchServiceProvider` bindings and publishing, multiple configured connections. +- A test that needs no config, cache or container still belongs in `Unit`; it just does not use the boot. + +```php +// tests/Pest.php +uses(TestCase::class)->in('Feature'); +uses(TestCase::class)->in('Unit'); // Stretch unit tests read config, cache and the container +``` + +## Reference implementation (Refactor Circus) + +`RefactorCircus\Keystone\Testing\Parity::gaps()` lists actions a surface cannot reach, so a parity test can assert every action is offered on each surface the package has. diff --git a/ring-master.yml b/ring-master.yml new file mode 100644 index 0000000..d0f6115 --- /dev/null +++ b/ring-master.yml @@ -0,0 +1,14 @@ +# Ring Master configuration. Every key is optional; only detected settings are written here. +# Full schema and defaults: vendor/refactor-circus/ringside/README.md + +commands: + verify: 'composer test' +standards: + global: + - + package: refactor-circus/standards + strict: true + +# No pint.json in this package; keep its own formatting. +pint: + allow_diff: true