diff --git a/docs/agent/specs/2026-10-29-2038-guardian-package/meta.yml b/docs/agent/specs/2026-10-29-2038-guardian-package/meta.yml index d57ab80..3a074dc 100644 --- a/docs/agent/specs/2026-10-29-2038-guardian-package/meta.yml +++ b/docs/agent/specs/2026-10-29-2038-guardian-package/meta.yml @@ -1,6 +1,6 @@ id: 2026-10-29-2038-guardian-package title: 'Guardian package' -status: in-review +status: closed created: '2026-10-29 20:38' standards: refactor-circus/standards: diff --git a/docs/agent/specs/2026-10-29-2038-guardian-package/post-mortem.md b/docs/agent/specs/2026-10-29-2038-guardian-package/post-mortem.md new file mode 100644 index 0000000..878e87a --- /dev/null +++ b/docs/agent/specs/2026-10-29-2038-guardian-package/post-mortem.md @@ -0,0 +1,58 @@ +# Post-mortem: Guardian package (2026-10-29-2038-guardian-package) + +## Summary + +Guardian is a new package that takes SSO and SCIM out of Roster, with the same behaviour apart from the accepted renames. The factory run `wf_e98c383c-d71` was approved in round 2 on 2026-10-30. PR: Refactor-Circus/Guardian#1. The build ran as seven task groups, then one review round, then a "Group 7" follow-up. The final gate was 546 Pest tests, PHPStan clean, Pint clean and 100% type coverage. + +Most of the cost came from groups that needed retries or salvage, and from one Roster-boundary violation (criterion 9) that review round 1 found. No human PR comments or ticket comments exist for this job. + +## Metrics + +- Rounds: 2 (the run history records `approved` at round 2). +- Task groups: 7. Groups 1 to 4 were retried or salvaged, and group 5 and group 6 each started from earlier attempts' commits. +- Review round 1 findings that were fixed: 1 major (architecture/dependencies, criterion 9) and 2 minor (architecture/service-providers). The re-run of all four reviewers (code, compat, security, standards) passed with nits only. +- Nits that did not start a round: 4 from the standards reviewer, 1 from the security reviewer. +- Decisions: 22 recorded in `decisions.md` (D-020 to D-041; earlier ids are in `shape.md`). Spec review accepted all recommendations. Five came up during build or review: D-037 and D-038 (build, group 2), D-039 (security review), D-040 (code review) and D-041 (standards review). +- Deviations recorded in `build.md`: about 12. They include the `rosterPresent()` public method, `ScimException::$status` visibility, the HandoverPending suite using a stand-in Roster, and `Permissions::forgetCache()` in place of the spec's `forget()`. +- Final test count: 546 passed, 2043 assertions. Type coverage: 100%. +- Not run locally: the `standalone`, `without-atrium`, `mysql` and browser CI jobs. + +## What went well + +- The spec review (`spec-review.md` round 1) closed many testability gaps early. These included a pinned Roster SHA (`6b1833d`), a moved-tests manifest (`tests/moved-tests.json`) with a case-count test, and literal config defaults. Later groups moved Roster's tests by diffing against that SHA. +- Cross-spec decisions (D-020 to D-022) fixed the Atrium `conflict`, the config-malformation rule and the Roster handover gate before the build started. +- Each group's retry re-checked its work against Roster's sources and did not rewrite it. Group 4's retry caught the Keen symlink that someone had re-linked by hand to an unmerged job branch. +- The gate mapped all 31 criteria to test files. Four reviewers passed on the re-run. +- Security review checked SCIM bearer auth, OIDC verification, injection and bulk limits. It also drove the real behaviour change D-039 (OIDC requires `email_verified`). D-039 shipped with tests (`OidcEmailVerifiedTest`) and a "Changed from Roster" note in the docs, held there by `DocsTest`. + +## What cost rounds + +- **Boundary violation (round 1 major).** After groups 1 to 6, the implementation still named Roster classes that criterion 9 denies: `ManagesMemberships`, `Support\CaseInsensitive` and `Domains\User\Resources\UserSummaryResource`. The fix added `Domains\Sso\Concerns\JoinsOrganizations`, `ScimQuery::equals()` and Guardian's own `UserSummaryResource`, and widened `RosterBoundaryTest` to cover Roster's `Concerns`, `Resources` and `Support` classes. Until then the arch rule and grep test had missed these classes. +- **Salvage and retry churn.** Groups 1 to 4 were recorded as "already committed, retry changed no code" or "salvaged". Earlier agents left uncommitted work (group 2) or committed it unverified (groups 3 and 4). Group 4 then needed five fixes: a fatal readonly redeclare of `ScimException::$status`, the wrong audit surface (`http` instead of `scim`), a ten-tool test that read the wrong entry points, a stale route-name lookup, and a test asserting an entry Roster never wrote. +- **Roster moving underneath the build.** The linked Roster (`remove-sso-and-scim`) no longer ships SSO and SCIM. Group 5's run showed 26 failures and 18 skips, so group 6 rebuilt fixtures (`tests/Fixtures/roster-sso-scim/`, `tests/Fixtures/roster-6b1833d/`) and changed Group 2 to 4 tests. The spec said to run Roster's own migrations and models, which stopped being possible. Criteria 22 and 28 were met with stand-ins. +- **Late decisions.** D-038 (the `guardian.ui.enabled` key Keystone requires), D-039 and D-040 were each found after the code was written. D-040 changed migration `down()` semantics and four tests. +- **Environment drift.** The Keen symlink was hand-edited, so `PackageWiringTest` failed in group 4's retry. Group 5 could not run the browser suite because `composer update` was off limits. + +## Root causes + +1. `spec_gap` (criteria 9 and 22, D-024/D-036): The spec said "deny Roster's internal bases and its Atrium/HTTP/MCP layers" but did not list `Concerns`, `Resources` or `Support\*` classes. The first arch test covered only some of the denied namespaces, so three violations got through six groups. Evidence: `build.md` "Review round 1 fixes", `RosterBoundaryTest` widened. +2. `spec_gap` (criteria 22 and 28): The spec assumed the linked Roster would still ship SSO and SCIM for the real-migration and real-`Handover` tests. It did not, and the build recorded two deviations. Evidence: `build.md` Group 6 "Deviations". +3. `spec_gap` (criterion 6, D-038): Keystone's `registerAtriumPlugin()` needs `guardian.ui.enabled`, which criterion 6's key list omitted. Evidence: `build.md` Group 2 "Left" and D-038. +4. `spec_gap` (D-039, D-040): The OIDC `email_verified` gap and the `down()` check scope were not settled in the spec. Both surfaced only in review. +5. `implementer_error`: Group 4's five defects (readonly redeclare, surface registration, test wiring) and group 3's missing organization scope on the connection-created audit entry and unrun Pint. All were fixed within the build, but they came from unverified salvaged commits. +6. `tooling`: Interrupted agents left uncommitted or unverified work in groups 2 to 4 (salvaged and retried). The hand-relinked `vendor/refactor-circus/keen` symlink broke `PackageWiringTest`. The browser dependency could not be installed in the worktree. The salvage and gate steps did not catch either. +7. `standards_gap`: `actions-events.md` says read actions have no events, while Keystone's `Arch::actionEventGaps()` requires a pair on every action (D-041). The standards disagree with each other. Standards-feedback rows were also needed for `booting()` provider registration, the `JoinsOrganizations` departure and the second user summary serializer. +8. `reviewer_noise`: None significant. The four standards nits did not start a round. The gate noted scaffold leftovers as non-blocking, although the code review said they were deleted. That note looks stale, not an actual problem. + +## What human review caught + +Nothing. The record has no PR review comments and no ticket comments, so no human-found gap can be shown. See `human_review_delta`. + +## Proposed follow-ups + +- Standards: align `actions-events.md` with `Arch::actionEventGaps()` on read actions (D-041). +- Spec template: when a spec limits another package's API, require a full denied-namespace list (including `Concerns`, `Resources`, `Support\*`) and write the arch test in group 1. +- Spec template: when a spec depends on a sibling branch that another job is changing, such as Roster `remove-sso-and-scim`, pin its fixtures from the start. Do not rely on the live checkout. +- Factory: commit or discard partial work when a group's agent is interrupted. Run the group's tests plus Pint before a salvaged commit counts as done. +- Gate: add a check that `vendor/` sibling symlinks match `composer.local.lock`. Run the browser, `standalone`, `without-atrium` and `mysql` jobs, or record that they are unverified. +- Small items: make `Sso` final, cast `max_payload_bytes`, and give `SsoLoginRefused` a `forX()` named constructor. Re-check the Roster-comparison fixtures once Roster `remove-sso-and-scim` is tagged. Then add the Roster `conflict` entry (D-027) and remove `Handover` and the coexistence tests. diff --git a/docs/agent/specs/2026-10-29-2038-guardian-package/spec.md b/docs/agent/specs/2026-10-29-2038-guardian-package/spec.md index 185769d..53c046d 100644 --- a/docs/agent/specs/2026-10-29-2038-guardian-package/spec.md +++ b/docs/agent/specs/2026-10-29-2038-guardian-package/spec.md @@ -348,3 +348,8 @@ Both are recorded in `docs/agent/standards-feedback.md` (workspace root) by the - D-038: `config/guardian.php` gains `ui.enabled` (default `true`); `GuardianPlugin` registers through Keystone's `registerAtriumPlugin()` behind `atriumInstalled()` (amends criterion 6 and group 5). - D-039: OIDC sign-in refuses to link an existing account by email or create one just-in-time unless the id_token's `email_verified` claim is `true`; the refusal is a `SsoLoginRefused` with its own reason, documented in README and CHANGELOG as a change from Roster. SAML is unchanged. - D-040: each create migration's `down()` checks only the tables it drops (amends criterion 21). + +## Addendum 2026-10-30 (v0.1.0 release) + +- Criterion 1: with the suite's first tagged release, Guardian requires `refactor-circus/keystone: ^0.1`, and develops against Roster, Atrium and Keen `^0.1` (Ringside and Standards stay `dev-main`). `laravel/mcp` is `^1.1` in `require-dev`, because the tool snapshots carry the title annotation 1.1 added. +- Criterion 28: Roster's seams branch merged, and Roster `remove-sso-and-scim` shipped with Roster v0.1.0, so Roster `^0.1` no longer carries its own SSO and SCIM. Coexistence was proven against the seams branch before merge; from v0.1.0 on, Guardian's suite runs with handover complete against Roster `^0.1`. diff --git a/docs/agent/standards-proposals/global/actions/actions-events.md b/docs/agent/standards-proposals/global/actions/actions-events.md new file mode 100644 index 0000000..61847ad --- /dev/null +++ b/docs/agent/standards-proposals/global/actions/actions-events.md @@ -0,0 +1,98 @@ +--- +key: actions/actions-events +action: amend +kind: architectural +package: refactor-circus/standards +from_spec: 2026-10-29-2038-guardian-package +status: queued +evidence: + - "/Users/jay/Projects/packages/Guardian--2026-10-29-2038-guardian-package-record/docs/agent/specs/2026-10-29-2038-guardian-package/decisions.md D-041" + - "/Users/jay/Projects/packages/Guardian--2026-10-29-2038-guardian-package-record/docs/agent/standards-feedback.md row actions/actions-events (read actions dispatch starting/finished events)" + - "/Users/jay/Projects/packages/Guardian--2026-10-29-2038-guardian-package-record/docs/agent/specs/2026-10-29-2038-guardian-package/round-1/review-standards.md: 'Decision for the user: read actions ... dispatch event pairs, which actions-events.md says they should not' and the nit 'SsoWebController dispatches SsoLoginFailedActionEvent itself ... outside the action'" + - "/Users/jay/Projects/packages/Keystone/src/Testing/Arch.php actionEventGaps() requires starting and finished events on every scanned file" + - "post-mortem root cause standards_gap (D-041)" +--- + +## Rationale + +The standard contradicts the tool that enforces it. It says read actions have no events, but Keystone's Arch::actionEventGaps() scans every action file and requires a starting and a finished event, with no exception for reads. Roster's actions and Guardian's moved List*/Show* actions already dispatch the pair. The user decided to keep the events (D-041), which left a standards-feedback row and a review decision. This amendment makes the standard match the code and the arch rule. A review nit found a controller dispatching an action's failed event outside the action, so the amendment also says only the action dispatches its events. + +## Proposed text + +# Actions & Events + +Actions hold business logic. Each one announces itself with an event pair: one event when it starts and, after the data is committed, one when it finishes. Read actions do this too. + +## Entry point: `execute()` calls a protected `handle()` + +- Actions live in their domain's `Actions/` and are named `{Verb}{Entity}Action`; see [[domain-modules]] and [[naming]]. +- Callers call `execute()`. The action implements a **`protected handle(...)`** that `execute()` delegates to. Never make `handle()` public: a single entry point leaves a place to add cross-cutting behavior later. +- No static constructors (`::run()`/`::make()`). Resolve through the container: `app(XAction::class)->execute(...)`. +- Input is an `{Action}Data` object, never an array; see [[data-objects]]. Bound models arrive as further `handle()` parameters. + +```php +final class Create{Entity}Action extends Action +{ + protected function handle(Create{Entity}Data $data, ?Model $owner = null): {Entity}Model + { + {Entity}CreatingActionEvent::dispatch($data, $owner); + + ${entity} = $this->perform($data, $owner); + + {Entity}CreatedActionEvent::dispatch(${entity}); + + return ${entity}; + } + + private function perform(Create{Entity}Data $data, ?Model $owner): {Entity}Model + { + return DB::transaction(fn (): {Entity}Model => {Entity}Model::query()->create([...])); + } +} +``` + +## Signatures + +- **Always a concrete return type, never `mixed`.** Create and update return the model, delete returns `void`, and list returns a paginator or collection. + +## Read actions + +- Read actions (`List{Entities}Action`, `Show{Entity}Action`) open no transaction, but they still dispatch the pair: `{Entities}ListingActionEvent` with the input and `{Entities}ListedActionEvent` with the result. Audit trails and listeners see every action the same way, and one arch rule covers them all. + +```php +protected function handle(List{Entities}Data $data): LengthAwarePaginator +{ + {Entities}ListingActionEvent::dispatch($data); + + $page = {Entity}Model::query()->paginate($data->perPage); + + {Entities}ListedActionEvent::dispatch($page); + + return $page; +} +``` + +## Transactions & events + +- `handle()` dispatches the **starting** event with the input, calls a private `perform()`, dispatches the **finished** event with the result, and returns that result. +- Every write in a mutating `perform()` goes inside `DB::transaction()`, even a single write. +- Finished events dispatch after commit (`ShouldDispatchAfterCommit`). They wait for the outermost transaction and never fire on rollback. An action that throws fires its starting event and no finished event. +- Only the action dispatches its events. Controllers, requests and tools never dispatch an action's event themselves. +- When a caller needs column values after the commit, `return $model->refresh();` **outside** the transaction. + +## Dependency injection + +- **Do not constructor-inject the model**: pass it through `handle()`. Constructor promotion is only for injected services. + +## Events + +- Events are `final` classes in the domain's `Events/`, using `Dispatchable` and `SerializesModels`, with no base class. Each is a plain data carrier with promoted constructor properties and may carry more than one value. +- Every action, read or write, has exactly one pair: a starting `{Entity}{Verb-ing}ActionEvent` that carries the input and a finished `{Entity}{Verb-ed}ActionEvent` that carries the result, for example `{Entity}SavingActionEvent` / `{Entity}SavedActionEvent`. +- Action events are distinct from model lifecycle events. Use action events for business logic by default; see [[lifecycle-events]]. + +## Reference implementation (Refactor Circus) + +- Actions extend `RefactorCircus\Keystone\Actions\Action`, whose `execute(mixed ...$args)` forwards to `handle()`. +- Starting events implement `Keystone\Contracts\ActionStartingEvent`. Finished events implement `Keystone\Contracts\ActionFinishedEvent`, which extends `ShouldDispatchAfterCommit`. +- `tests/ArchTest.php` enforces the pairing on every action file, read actions included (`Arch::actionEventGaps()`). It also enforces that writes happen only inside a transaction (`Arch::writesOutsideTransactions()`) and that `handle()` takes no array parameter; see [[arch-tests]]. + diff --git a/docs/agent/standards-proposals/global/architecture/dependencies.md b/docs/agent/standards-proposals/global/architecture/dependencies.md new file mode 100644 index 0000000..67e0485 --- /dev/null +++ b/docs/agent/standards-proposals/global/architecture/dependencies.md @@ -0,0 +1,86 @@ +--- +key: architecture/dependencies +action: amend +kind: architectural +package: refactor-circus/standards +from_spec: 2026-10-29-2038-guardian-package +status: queued +evidence: + - "/Users/jay/Projects/packages/Guardian--2026-10-29-2038-guardian-package-record/docs/agent/specs/2026-10-29-2038-guardian-package/build.md Review round 1 fixes (architecture/dependencies major, criterion 9: ManagesMemberships, CaseInsensitive, UserSummaryResource; RosterBoundaryTest dataset)" + - "/Users/jay/Projects/packages/Guardian--2026-10-29-2038-guardian-package-record/docs/agent/standards-feedback.md rows architecture/dependencies (src/Upgrade names Roster tables as strings; JoinsOrganizations writes Roster models directly)" + - "/Users/jay/Projects/packages/Guardian--2026-10-29-2038-guardian-package-record/docs/agent/specs/2026-10-29-2038-guardian-package/decisions.md D-024, D-036" + - "/Users/jay/Projects/packages/Guardian--2026-10-29-2038-guardian-package-record/docs/agent/specs/2026-10-29-2038-guardian-package/round-1/review-standards.md ('the Roster-boundary classes were replaced or recorded')" + - "post-mortem root cause spec_gap: 'Criterion 9 did not list all denied Roster namespaces (Concerns, Resources, Support)'" +--- + +## Rationale + +The post-mortem's only major finding came from here. Criterion 9 named the denied Roster layers (Atrium/HTTP/MCP and internal bases) but not Concerns, Resources or non-public Support, and the standard only covers boundaries between domains, not packages. Guardian used ManagesMemberships, Support\CaseInsensitive and Roster's UserSummaryResource for six task groups, until standards review round 1 caught them, and RosterBoundaryTest had to be widened with a pinned dataset. The fix also left two architecture/dependencies feedback rows: a direct model write where Roster has no action that joins with a source (JoinsOrganizations), and Upgrade code naming Roster's tables and keys as strings. This amendment turns all of that into a rule specs can copy. + +## Proposed text + +# Dependencies + +A package requires only what its core needs. Shared runtime comes from the base package, other domains and packages are reached only through their public seams and public domain API, and every optional integration is guarded so the package installs and runs without it. + +## Between domains + +- Change another domain's data only by calling its action (`app({Verb}{Entity}Action::class)->execute(...)`), never by writing its models directly. The action owns the transaction and the event pair; see [[actions-events]]. +- React to another domain by listening to its action or lifecycle events, not by reaching into its services' internals. +- Depend on another domain's `Contracts/`, `Data/` and models (for reading). Keep its `Support/`, `Concerns/` and private helpers out of reach. +- Framework-free core domains never import an integration domain. Integrations depend on the core, not the reverse. +- Package-wide code at the top level ([[domain-modules]]) may be used by every domain. + +## Between packages + +When a package builds on another suite package, the same rules apply, with the boundary written down as an explicit allowlist: + +- **Allowed:** the other package's documented seams (contracts, registries, `Data`), its models, its actions with their `Data`, its entry-point class, and the `Support` classes it names as public. +- **Denied:** members marked `@internal`; any domain's `Concerns/`, `Resources/`, `Http/` and `Mcp/`; the package's top-level `Http`, `Mcp` and UI (`Atrium`) layers; and every `Support` class not on the allowlist. A resource belongs to the HTTP layer even though it sits beside the model. +- The spec that sets the boundary lists both sides by namespace. An arch test enforces it with a dataset that pins each denied and allowed reference, so a missed namespace fails the test instead of review. +- If no public action does the write you need, ask the owning package for one. Until it lands, copy the rule into your own `Concerns/` and record the direct write in `standards-feedback.md`, with a test that pins the behaviour. +- An upgrade path that moves the other package's data (`src/Upgrade`) is the one place that may name its tables, config keys and classes as strings. Keep all of that in one namespace. + +```php +dataset('denied', [ + 'Roster\\Domains\\Organization\\Concerns\\ManagesMemberships', + 'Roster\\Domains\\User\\Resources\\UserSummaryResource', + 'Roster\\Support\\CaseInsensitive', +]); + +dataset('allowed', [ + 'Roster\\Support\\Users', + 'Roster\\Domains\\Organization\\Actions\\AddMemberAction', +]); +``` + +## Composer `require` + +- Shared runtime (base actions, request bases, event contracts, provider bases) comes only from the base package, which every package in the suite requires. Don't copy it into a package. +- Add a dependency only when the package's core behavior needs it, and only with approval. +- An optional integration is never in `require`. Keep it in `require-dev`, or leave it unlisted when listing it would be circular (the integration itself requires this package). + +## Optional integrations + +- Reference an optional package's classes only behind a check that it is installed and enabled: `class_exists()` at the wiring point, or a single `active()` method that also checks its provider is loaded and that the package's config allows it. +- Keep all those references in one integration class or an `Integration` domain, so static analysis ignores exactly one place. + +```php +public function active(): bool +{ + return class_exists(OtherServiceProvider::class) + && $this->app->getProvider(OtherServiceProvider::class) !== null + && $this->config->get('{package}.other.enabled', true) === true; +} +``` + +## Feature flags + +- Never require consumers to install a feature-flag package (such as Pennant); gating is the host application's concern. +- A package may ship a feature class for hosts that use one, with the flag package as a dev dependency only. +- Surfaces the package itself can switch off are config flags, checked strictly; see [[service-providers]]. + +## Reference implementation (Refactor Circus) + +The base package is `refactor-circus/keystone`: `Actions\Action`, `Data\Data`, the `Contracts\Action*Event` contracts, `Models\Concerns\DispatchesModelEvents` and `Support\{ServiceProvider,PackageServiceProvider}`. `Keystone\Cortex\CortexIntegration::active()` is the guard for Cortex, which cannot be a dev dependency because it requires Keystone; `phpstan.neon.dist` ignores Cortex classes in that one file. Feature-flag management lives in `refactor-circus/pennantplus`, which plugs in like any other package. Guardian's `tests/Feature/RosterBoundaryTest.php` is the reference boundary test. + diff --git a/docs/agent/standards-proposals/global/architecture/service-providers.md b/docs/agent/standards-proposals/global/architecture/service-providers.md new file mode 100644 index 0000000..ad57387 --- /dev/null +++ b/docs/agent/standards-proposals/global/architecture/service-providers.md @@ -0,0 +1,88 @@ +--- +key: architecture/service-providers +action: amend +kind: architectural +package: refactor-circus/standards +from_spec: 2026-10-29-2038-guardian-package +status: queued +evidence: + - "/Users/jay/Projects/packages/Guardian--2026-10-29-2038-guardian-package-record/docs/agent/standards-feedback.md row architecture/service-providers (booting() callback)" + - "/Users/jay/Projects/packages/Guardian--2026-10-29-2038-guardian-package-record/docs/agent/specs/2026-10-29-2038-guardian-package/decisions.md D-023, D-032, D-038" + - "/Users/jay/Projects/packages/Guardian--2026-10-29-2038-guardian-package-record/docs/agent/specs/2026-10-29-2038-guardian-package/build.md Review round 1 fixes: 'architecture/service-providers (minor) ... booting() callback'" + - "/Users/jay/Projects/packages/Keystone/src/Support/PackageServiceProvider.php:113-122 registerAtriumPlugin() returns early unless configKey('ui.enabled') === true" + - "post-mortem root cause spec_gap: 'the guardian.ui.enabled key (D-038)'" +--- + +## Rationale + +This job hit two gaps. First, Guardian must stay inert without Roster (D-023, D-032), but the standard says to register DomainServiceProvider in register() and also never to read host state there. Guardian solved this with a booting() callback, which a review flagged as a minor finding and which needed a standards-feedback row. Second, Keystone's registerAtriumPlugin() silently does nothing unless {package}.ui.enabled is true, and no standard says so. guardian.ui.enabled was found only during the build (D-038), after group 5's code depended on it. The post-mortem lists this as a spec gap. + +## Proposed text + +# Service Providers + +`register()` binds and merges config. `boot()` loads resources and registers surfaces: console-only wiring goes behind `runningInConsole()`, and optional surfaces go behind a strict config flag. + +## register() + +- Container bindings and `mergeConfigFrom()` go here, so the host app's published config overrides the package defaults. +- Register `Domains\DomainServiceProvider` here; see [[domain-modules]]. +- Never read host app state (resolved services, request, auth) during registration, because other providers may not have registered yet. + +## A package that is inert without a peer + +Some packages register their domains only when a peer package is present (for example, an add-on that needs the package it extends). Asking the gate inside `register()` would resolve it before a host or test can rebind it. Instead: + +- Register `DomainServiceProvider` from a `$this->app->booting()` callback that asks one integration gate (`Support\Integration`). `booting()` runs before any provider boots, so the domain providers still boot with the rest. +- When the gate is closed, register nothing but the `about` line that says why (`Inactive: install {vendor}/{peer}`). + +```php +public function register(): void +{ + $this->registerPackage(); + + $this->app->booting(function (): void { + if ($this->app->make(Integration::class)->peerInstalled()) { + $this->app->register(DomainServiceProvider::class); + } + }); +} +``` + +## boot() + +- Load resources with Laravel's native APIs: `loadRoutesFrom`, `loadViewsFrom`, `loadTranslationsFrom`, `loadMigrationsFrom`. +- Read settings with `config()` after the merge. Never call `env()` outside config files. +- Keep wiring in `register()`/`boot()` as explicit Laravel calls. Extract a private method only for a real repeated concern or for one optional surface. Don't swap in `spatie/laravel-package-tools` by default. + +## Console-only wiring + +- `publishes()`, `publishesMigrations()` and `commands()` sit behind `$this->app->runningInConsole()`. Web-only concerns are never registered unconditionally. +- Every publishable group carries the umbrella tag plus its own: `{package}` plus `{package}-config`, `{package}-views`, `{package}-lang` or `{package}-migrations`, so consumers can publish one group or all of them. +- Migrations publish with `publishesMigrations()`, which re-dates the files. + +```php +if ($this->app->runningInConsole()) { + $this->publishes([ + __DIR__.'/../config/{package}.php' => config_path('{package}.php'), + ], ['{package}', '{package}-config']); + + $this->commands([InstallCommand::class]); +} +``` + +## Optional surfaces + +- A surface consumers can switch off (UI, API routes, a transport) registers from `boot()` in its own private `register{Surface}()` method and is driven entirely by config. +- Gate it with `config('{package}.{surface}.enabled') === true`. Comparing against literal `true` fails closed, so `'1'`, `'yes'` or a typo never exposes an endpoint. +- Every surface the provider gates has its `{surface}.enabled` key in the shipped config file, so the flag exists before the surface is written. +- Path, domain, middleware and gate come from config. Nothing is hardcoded in the provider. + +## Tests + +Cover the observable wiring: merged config, loaded routes, publish tags, registered commands, and each optional surface both on and off. A package that is inert without a peer also tests the inert boot. + +## Reference implementation (Refactor Circus) + +`{Package}ServiceProvider` extends `RefactorCircus\Keystone\Support\PackageServiceProvider`. It returns the package from `definition()`, calls `registerPackage()`, and uses the base helpers (`registerPolicies()`, `registerMcpServer()`, `registerAtriumPlugin()`, `loadHistoryRoutes()`). `registerAtriumPlugin()` does nothing unless Atrium is installed and `{package}.ui.enabled` is `true`, so any package with an Atrium plugin ships `'ui' => ['enabled' => true]` in its config. Domain providers extend `Keystone\Support\ServiceProvider`, whose `loadApiRoutesFrom()` skips routes unless `{package}.routes.enabled` is `true`. + diff --git a/docs/agent/standards-proposals/global/errors/exceptions.md b/docs/agent/standards-proposals/global/errors/exceptions.md new file mode 100644 index 0000000..aaf616a --- /dev/null +++ b/docs/agent/standards-proposals/global/errors/exceptions.md @@ -0,0 +1,86 @@ +--- +key: errors/exceptions +action: amend +kind: architectural +package: refactor-circus/standards +from_spec: 2026-10-29-2038-guardian-package +status: queued +evidence: + - "/Users/jay/Projects/packages/Guardian--2026-10-29-2038-guardian-package-record/docs/agent/specs/2026-10-29-2038-guardian-package/build.md Group 4 What I found: 'ScimException promoted public readonly int $status over Keystone PackageException's protected int $status, which is a fatal redeclare'" + - "/Users/jay/Projects/packages/Guardian--2026-10-29-2038-guardian-package-record/docs/agent/specs/2026-10-29-2038-guardian-package/build.md Group 4 Deviations: 'ScimException::$status is public protected(set), not public readonly as in Roster'" + - "/Users/jay/Projects/packages/Keystone/src/Exceptions/PackageException.php:23 protected int $status = 409" + - "post-mortem root cause implementer_error: 'a readonly redeclare of ScimException::$status'" +--- + +## Rationale + +A salvaged group 4 commit moved Roster's ScimException with `public readonly int $status`. That is a fatal redeclare of Keystone PackageException's `protected int $status`, and PHPStan flagged it as property.readOnly. The post-mortem lists it as an implementer error that went unverified. The standard mentions overriding $status without saying how, so other packages that move exceptions onto Keystone's base will hit the same thing. The fix Guardian used (`public protected(set)`) is now the documented way. + +## Proposed text + +# Exceptions + +Every exception a package throws descends from one package base, so callers can catch it broadly or narrowly and never see a raw SPL or vendor exception. + +## Hierarchy + +``` +{Package}Exception (extends RuntimeException) src/Exceptions/ +├── {Entity}NotFoundException src/Domains/{Domain}/Exceptions/ +└── {Domain}FailedException + └── {Domain}TimeoutException +``` + +- `{Package}Exception` lives in the top-level `src/Exceptions/` and is shared by every domain. Each subclass lives in its domain's `Exceptions/`; see [[domain-modules]]. +- Catch `{Package}Exception` for anything from the package, and narrow to a subclass for a specific condition. A specialised case extends the general one, so either catch works. +- Throw a package subclass, not a bare `\RuntimeException` or `\InvalidArgumentException`. + +## Runtime failures + +A runtime failure is system state discovered partway through: a record with no published version, a circular reference, an unregistered key. There is no input field to attach an error to, so it gets a typed exception that callers, including host apps embedding the package, can catch. + +```php +final class {Entity}NotPublishedException extends {Package}Exception +{ + public static function forModel({Entity}Model $model): self + { + return new self("{Entity} [{$model->slug}] has no published version."); + } +} +``` + +- Make it `final`, with a static `forX()` named constructor. The message names the stable identifier (a slug or key, not an id) wrapped in `[…]`. +- Carry the context a caller needs to locate the failure as a readonly property (a line number, a key). + +## Wrapping third-party exceptions + +- The adapter around a vendor client ([[container-bindings]]) wraps every call in `try`/`catch` and rethrows as a package exception. That adapter is the only place vendor exceptions surface. +- The message states the operation and its context (`"Failed to create index [{$name}]: ..."`). Pass `(int) $e->getCode()` and the original exception as `previous` to keep the chain. +- Map only the exact vendor condition you mean. If "does not exist" is only a 404, every other error (auth, connectivity, server) rethrows; reporting those as absence is a bug. + +## Not for business rules + +Rejected input and broken business rules are not exceptions. Action guards throw a field-keyed `ValidationException` so the response can attach the error to a field; see [[domain-guards]]. + +## Reference implementation (Refactor Circus) + +`{Package}Exception` is `abstract` and extends Keystone's `Exceptions\PackageException` (itself a `RuntimeException`). Its `render()` returns `{"message": ...}` with status `409` by default, so the JSON API and the MCP tools pass the message through as written. Write the message for whoever made the call. + +- The base declares `protected int $status = 409`. A subclass changes it by redeclaring the default (`protected int $status = 422;`), or by setting it in its named constructor when the status varies per instance. +- When callers need to read the status, widen it to `public protected(set) int $status`. Never promote it as `public readonly int $status`: redeclaring an inherited mutable property as readonly is a fatal error. + +```php +final class ScimException extends GuardianException +{ + public protected(set) int $status; + + public static function forStatus(int $status, string $detail): self + { + $e = new self($detail); + $e->status = $status; + + return $e; + } +} +``` + diff --git a/docs/agent/standards-proposals/global/http/resources.md b/docs/agent/standards-proposals/global/http/resources.md new file mode 100644 index 0000000..cb42147 --- /dev/null +++ b/docs/agent/standards-proposals/global/http/resources.md @@ -0,0 +1,78 @@ +--- +key: http/resources +action: amend +kind: architectural +package: refactor-circus/standards +from_spec: 2026-10-29-2038-guardian-package +status: queued +evidence: + - "/Users/jay/Projects/packages/Guardian--2026-10-29-2038-guardian-package-record/docs/agent/standards-feedback.md row http/resources (second UserSummaryResource serializer)" + - "/Users/jay/Projects/packages/Guardian--2026-10-29-2038-guardian-package-record/docs/agent/specs/2026-10-29-2038-guardian-package/build.md Review round 1 fixes: 'SsoIdentityResource nests Guardian's own Domains\\Sso\\Resources\\UserSummaryResource, with the same schema and payload' and UserSummaryResourceTest" + - "post-mortem root cause spec_gap (criterion 9 denied namespaces included Resources)" +--- + +## Rationale + +Under the package boundary (criterion 9), Guardian could not use Roster's UserSummaryResource but had to nest a user in SsoIdentityResource. The standard forbids a second serializer outright, so the fix needed an http/resources feedback row. Guardian's answer, a mirror held equal by a schema and payload parity test, is the safe pattern. Writing it down settles the conflict between http/resources and the dependencies boundary for every add-on package. + +## Proposed text + +# Resources + +Every payload a package returns serializes through a JSON resource, and every surface uses the same resource, so a payload is identical wherever it is served. + +## Placement + +- A model's resource sits beside the model, in `src/Domains/{Domain}/Resources/` next to `Models/` ([[domain-modules]]). +- A payload with no model behind it lives in `src/Domains/{Domain}/Http/Resources/`, or in `src/Http/Resources/` when several domains share it. +- Name it `{Entity}Resource` ([[naming]]). + +## Shape + +```php +/** + * @mixin ProjectModel + */ +final class ProjectResource extends JsonResource +{ + public function toArray(Request $request): array + { + return [ + 'name' => $this->name, + 'slug' => $this->slug, + 'owner' => new OwnerResource($this->whenLoaded('owner')), + 'created_at' => $this->created_at?->toIso8601String(), + ]; + } +} +``` + +- Make it `final`, with a `@mixin` docblock naming the model for static analysis. +- Expose the public identity (slug or route key). Leave internal ids out unless there is a concrete need. +- Nest relations only through `whenLoaded()`. The action or request eager-loads what the resource needs, so a resource never triggers queries. +- Write timestamps as `?->toIso8601String()`. +- No conditionals on request context: the same model always yields the same payload. + +## One resource, every surface + +- HTTP responses, console output and any other surface (a tool server, a UI's data endpoint) return the same resource, never a hand-built array. A second serializer for the same model is drift waiting to happen. +- Lists use the resource's collection, with paging metadata beside the data. + +## Another package's model + +- A resource belongs to its package's HTTP layer, so another package may not use it; see [[dependencies]]. +- When you must nest another package's model, mirror its resource in your own domain's `Resources/` and read the model only through that package's public API. Add a test that holds the mirror's `schema()` and payload equal to the original, so the two cannot drift unnoticed. Record the mirror in `standards-feedback.md`. + +```php +it('serializes a user exactly as {Peer} does', function (): void { + $user = {Peer}UserFactory::new()->create(); + + expect((new UserSummaryResource($user))->resolve()) + ->toBe((new {Peer}UserSummaryResource($user))->resolve()); +}); +``` + +## Reference implementation (Refactor Circus) + +Resources extend `RefactorCircus\Keystone\Http\Resources\JsonResource`, whose collections are `Keystone\Http\Resources\ResourceCollection`. The base answers HTTP through Laravel's `toResponse()` and other surfaces through `toStructuredResponse()` with the same payload, and declares the payload's fields through `schema()`. Guardian's `Domains\Sso\Resources\UserSummaryResource` and `tests/Feature/Sso/UserSummaryResourceTest.php` are the reference mirror. + diff --git a/docs/agent/standards-proposals/global/models/migrations.md b/docs/agent/standards-proposals/global/models/migrations.md new file mode 100644 index 0000000..a4b3f1c --- /dev/null +++ b/docs/agent/standards-proposals/global/models/migrations.md @@ -0,0 +1,89 @@ +--- +key: models/migrations +action: amend +kind: architectural +package: refactor-circus/standards +from_spec: 2026-10-29-2038-guardian-package +status: queued +evidence: + - "/Users/jay/Projects/packages/Guardian--2026-10-29-2038-guardian-package-record/docs/agent/standards-feedback.md row models/migrations" + - "/Users/jay/Projects/packages/Guardian--2026-10-29-2038-guardian-package-record/docs/agent/specs/2026-10-29-2038-guardian-package/decisions.md D-031, D-034, D-040" + - "/Users/jay/Projects/packages/Guardian--2026-10-29-2038-guardian-package-record/docs/agent/specs/2026-10-29-2038-guardian-package/build.md Group 7 (7.3, D-040: each down() checks only its own tables; MigrationsTest)" + - "post-mortem root cause spec_gap: 'migration down() scope (D-040)' decided only after code was written" +--- + +## Rationale + +Guardian's create migrations had to break the plain create/drop rule. The Roster upgrade renames existing tables into place, so a plain create would fail and a plain down() would delete a customer's SSO connections and SCIM tokens. The user settled the behaviour in two decisions: refuse to drop tables with rows unless forced (D-031) and check only the tables each migration drops (D-040). D-040 surfaced only in code review after the code was written, which the post-mortem lists as a spec gap. Writing the pattern down means the next package that takes over tables (the suite is splitting features out of Roster) gets it right from the spec. + +## Proposed text + +# Migrations + +Package migrations use a fixed date plus a sequence number and one file per feature's tables. They take table names from the package's configurable tables map and are publishable. A migration whose tables may already hold another package's data never overwrites that data and never silently drops it. + +## Naming and order + +``` +2026_01_01_000001_create_{package}_{feature}_tables.php +2026_01_01_000002_create_{package}_{other_feature}_tables.php +``` + +- Use a fixed date with an incrementing sequence, so package migrations run in a stable, reviewable order in any host app, whenever they were written. The next migration takes the next sequence number. +- One migration creates all of a feature's tables (parent, children, pivots). `down()` drops them in reverse dependency order. +- Write anonymous class migrations with `declare(strict_types=1)`. + +## Table names + +- `Schema::create()`, `constrained()` and `Schema::dropIfExists()` take the table name from the same tables class and keys the models use, never a literal `{package}_*` string. A host renames a table with one config change made before the migrations run. See [[models]] and [[configuration]]. +- Foreign keys go through `constrained()` with an explicit cascade rule. Add the compound uniques and indexes the domain needs. + +```php +Schema::create(Tables::name('{entity}_items'), function (Blueprint $table): void { + $table->id(); + $table->foreignId('{entity}_id') + ->constrained(Tables::name('{entities}')) + ->cascadeOnDelete(); + $table->timestamps(); +}); +``` + +## Tables taken over from another package + +Sometimes a package inherits tables that another package created, for example when a feature moves between packages and an upgrade step renames the old tables into place before the create migrations run. + +- The upgrade step (a migration with an earlier date plus an artisan command) renames the old tables. It runs only once the old owner no longer uses them. +- Each create migration skips a `Schema::create()` whose table already exists, so it never fails on, or recreates, a table that was renamed into place. +- `down()` refuses to drop a table that holds rows. It throws a package exception and drops nothing, unless a `{package}.migrations.force_rollback` config flag is on. +- Each `down()` checks only the tables that migration drops. Rows in another feature's tables never block its rollback. +- Test both drivers the rename runs on (SQLite plus a MySQL CI lane), so foreign keys are proven to survive the rename. + +```php +public function down(): void +{ + $tables = [Tables::name('{feature}_identities'), Tables::name('{feature}_connections')]; + + if (config('{package}.migrations.force_rollback') !== true) { + foreach ($tables as $table) { + if (Schema::hasTable($table) && DB::table($table)->exists()) { + throw RollbackRefusedException::forTable($table); + } + } + } + + foreach ($tables as $table) { + Schema::dropIfExists($table); + } +} +``` + +## Loading and publishing + +- The package service provider loads migrations from `database/migrations` and registers them with `publishesMigrations()` under the package tag and a `{package}-migrations` tag, so a host can publish and edit them. See [[service-providers]]. + +## Reference implementation (Refactor Circus) + +- Migrations call the package's `Support\Tables::name($key)` (on `RefactorCircus\Keystone\Database\Tables`). +- `tests/ArchTest.php` runs `Arch::literalTableNames()` over the migrations as well as `src/`. +- Guardian's `2026_11_01_000001` / `000002` create migrations and its `Upgrade\RosterUpgrade` (`2026_11_01_000000`, `guardian:upgrade-from-roster`) follow the takeover rules. + diff --git a/docs/agent/standards-proposals/global/testing/arch-tests.md b/docs/agent/standards-proposals/global/testing/arch-tests.md new file mode 100644 index 0000000..67d79cb --- /dev/null +++ b/docs/agent/standards-proposals/global/testing/arch-tests.md @@ -0,0 +1,75 @@ +--- +key: testing/arch-tests +action: amend +kind: architectural +package: refactor-circus/standards +from_spec: 2026-10-29-2038-guardian-package +status: queued +evidence: + - "/Users/jay/Projects/packages/Guardian--2026-10-29-2038-guardian-package-record/docs/agent/specs/2026-10-29-2038-guardian-package/build.md Review round 1 fixes: 'RosterBoundaryTest.php now also denies a Roster domain's Concerns and Resources and every Roster\\Support class except ... A dataset pins which references are denied and which are allowed.'" + - "/Users/jay/Projects/packages/Guardian--2026-10-29-2038-guardian-package-record/docs/agent/specs/2026-10-29-2038-guardian-package/round-1/gate.md criterion 9 proven by tests/ArchTest.php and tests/Feature/RosterBoundaryTest.php" + - "/Users/jay/Projects/packages/Guardian--2026-10-29-2038-guardian-package-record/docs/agent/specs/2026-10-29-2038-guardian-package/decisions.md D-041" + - "post-mortem root cause spec_gap (criterion 9 boundary test missed three classes)" +--- + +## Rationale + +arch-tests says a new architectural standard is not done until it has a rule here, but the list had no rule for package boundaries. Guardian's first boundary test did not deny Concerns, Resources or Support, so three violations went unnoticed for six task groups. The fix was a dataset that pins every denied and allowed reference. This amendment adds that rule to the list, so the boundary in the dependencies proposal is enforced the same way in every package. It also says the action-event rule covers read actions, matching what Arch::actionEventGaps() actually checks (D-041). + +## Proposed text + +# Arch Tests + +Architectural rules are executable: every package has a `tests/ArchTest.php` that enforces them, instead of leaving them to review. + +## Baseline + +Every package runs the PHP and security presets, the shared suite preset, and the global bans: + +```php +arch()->preset()->php(); +arch()->preset()->security(); +arch()->preset()->{suitePreset}(); + +arch('it will not use dd(), ddd(), env(), or exit()') + ->expect(['dd', 'ddd', 'env', 'exit']) + ->each->not->toBeUsed(); + +arch('the package source declares strict types') + ->expect('{Vendor}\{Package}') + ->toUseStrictTypes(); +``` + +- Every PHP file declares `strict_types=1`. `env()` is read only in config; code reads `config()` ([[configuration]]). +- An exception to a preset is scoped to the one class that needs it (`->ignoring(Foo::class)`), with a comment saying why. Never use a blanket opt-out. +- The shared preset is registered from `tests/Pest.php`, never from an autoloaded file, because Composer may load it before Pest's functions exist. + +## Package rules + +Each package adds the rules that enforce the standards it follows. Each rule collects violations and expects the list to be empty, so a failure names the offending class: + +- Models extend Eloquent's `Model` and end in `Model` ([[models]], [[naming]]). +- Actions take Data objects, not arrays, and every Data input declares its rules ([[data-objects]]). +- Every action, read actions included, dispatches its starting and finished event pair and writes only inside a transaction ([[actions-events]]). +- Every model fires an event for every lifecycle hook ([[lifecycle-events]]). +- Tables are named through the package's table-name map, never as literals in `src` or migrations ([[migrations]]). +- Every model has a policy in the config ([[authorization]]). +- Requests validate with the Data rules and never call `Data::from()`. Every request declares its own `persist()`, and controllers make no database calls ([[request-persist]]). +- A package that builds on another suite package scans every reference to that package against the boundary's allow and deny lists. A dataset pins each denied namespace (`Concerns`, `Resources`, `Http`, `Mcp`, UI, non-public `Support`) and each allowed one ([[dependencies]]). + +```php +arch('every action dispatches a starting and a finished event') + ->expect(fn (): array => actionEventGaps($actionFiles)) + ->toBeEmpty(); + +it('names no denied {Peer} class', function (string $reference): void { + expect(boundaryViolations('src', '{Vendor}\\{Peer}'))->not->toContain($reference); +})->with('denied'); +``` + +A new architectural standard is not done until it has a rule here. + +## Reference implementation (Refactor Circus) + +`RefactorCircus\Standards\Pest\ArchPreset::register()` (in `tests/Pest.php`) adds `arch()->preset()->refactorCircus()`: strict types and no `env()` across the package's `RefactorCircus\` namespaces. `RefactorCircus\Keystone\Testing\Arch` supplies the violation finders: `domainClasses()`, `dataWithoutRules()`, `actionEventGaps()`, `writesOutsideTransactions()`, `modelEventGaps()`, `modelsWithoutPolicies()` and `literalTableNames()`. Guardian's `tests/Feature/RosterBoundaryTest.php` is the reference for a boundary rule. +