test: enforce ADR-0001 layering with a blocking ratchet

Add spinifex/architecture/layering, a test-only package that parses the
module's import graph, maps every production package to an ADR-0001
layer and checks each dependency rule as its own subtest. Existing
violations are allow-listed against their recorded debt; a new forbidden
edge, an unmapped package, a stale allowlist entry or a new package
under a frozen legacy root fails local preflight and CI.

Record the nine edges the test found missing from the migration record
(quota -> EC2 instance types, STS/Ochre/ELBv2 -> IAM, ELBv2
cross-domain, installer UI -> admin), name the importers of the utils
residuals and gateway/ec2_idempotency.go, and correct the handlers/iam
consumer list.
This commit is contained in:
joshsiv-mulga
2026-10-09 12:01:28 +10:00
parent 903c92e260
commit 5292bd22c9
7 changed files with 993 additions and 4 deletions
+8 -4
View File
@@ -397,7 +397,7 @@ These residuals were recorded by individual slices and must be resolved once the
- ACM control-plane registration: `domains/acm/awsapi.Deps.NATS` (`registration.go`) is likewise a raw `*nats.Conn` carried by every `Handler`, for the same reason; it must not be broadened further meanwhile.
- `cmd/aws-model-coverage` imports `ingress/aws/dispatch`, `domains/ecr/awsapi`, `domains/acm/awsapi` and `gateway` to read ECR's and ACM's declared inventories. It is a non-serving tool and the only named exception to the ADR-0002 composition invariant; it must not construct a registration.
- Ingress pipeline (ADR-0002 phase 4): the request-audit record, the trace action enricher, the throttle key functions and the gateway request-context keys stay in `gateway` until the auth/IAM and request-context boundary is designed. SigV4 authentication writes the audit record and context keys from four places, so moving them now would export exactly the setters ADR-0002 says must not be exported solely to make a directory move possible.
- `utils`: `vpcd_event.go` (vpcd request/ack protocol and NAT helpers) awaits a network contract, `ec2_subject.go` awaits an EC2 contract, and `encryption.go` (the Viperblock master-key loader) awaits a Viperblock adapter owner, since `providers/ebs` is provider-neutral.
- `utils`: `vpcd_event.go` (vpcd request/ack protocol and NAT helpers) awaits a network contract, `ec2_subject.go` awaits an EC2 contract, and `encryption.go` (the Viperblock master-key loader) awaits a Viperblock adapter owner, since `providers/ebs` is provider-neutral. Importers: `domains/ec2/{eip,instance,vpc}` and `handlers/elbv2/service_impl.go` use the `vpcd_event.go` helpers (`PublishNATEvent`, `AddNAT`, `RequestEvent`), and `domains/ec2/{image,instance,volume}` use `LoadViperblockMasterKey`; each edge clears when its file moves to its owner.
- `runtime/compute/cache.New`: two construction-time panics carry a lint exemption pending a constructor that returns an error.
- `domains/ec2/systeminstance`: managed-service parent metadata is only the `ManagedBy` tag value.
- `gateway/bedrock`: holds the Ochre domain core (model catalogue, provisioned throughput, guardrail, access, credential, usage, price, logging and weights stores), the inference engine (provider, vLLM, Anthropic, embeddings, reranker, admission) and the Bedrock action layer in one package with internal cycles. `domains/ochre` imports it, which is the ADR step 7 Ochre gateway import. Splitting it needs a plan: domain core and stores to `domains/ochre/<resource>`, inference to an Ochre-owned package, and only the action layer to `domains/ochre/awsapi`. The top-level `gateway/bedrock*.go` HTTP handlers additionally wait for the ingress registration seam.
@@ -410,7 +410,7 @@ These residuals were recorded by individual slices and must be resolved once the
- `operator/cli` (known security risk): `spx admin join` contacts the formation server with `InsecureSkipVerify`, sends the join token as a bearer credential and receives the cluster CA certificate and key, master key, Viperblock key and shared credentials, so an on-path attacker during formation can capture the token and the cluster root secrets or substitute a CA. This predates the move; lint surfaced it when the tree left `cmd/`. It is accepted for now and carries a line-level gosec annotation stating it is not a false positive. Removal condition: authenticate formation TLS with a pinned key or certificate delivered with the join material, or an out-of-band CA, with tests proving a mismatched server certificate fails before credentials are sent.
- `handlers/eks` (potential security risk): `ClusterMeta.ControlPlaneTemplate` (`handlers/eks/service_impl.go`) clears the template's credentials but keeps `OIDCPrivateKeyPEM` and the k3s `JoinToken`, so both are persisted in the `eks-account-{acct}` cluster record, which the gateway also reads. Whether that record is encrypted at rest is unconfirmed; if it is not, a reader of the bucket can forge service-account tokens for the cluster's OIDC issuer and join nodes to it. This predates the refactor and is not fixed in it. Removal condition: the key and token are held by a dedicated secret store (a future KMS or Secrets Manager capability is the likely owner) and the cluster record keeps only a reference, with a test proving the persisted record contains neither secret.
- `operator/cli` (dependency): the command tree still imports domain and service implementations directly (`handlers/{iam,eks}`, `domains/admission/quota`, `gateway`, `gateway/bedrock`, `daemon`, `vpcd`, `admin`, `accountteardown`, `services/viperblockd` and runtime roles). The ADR's `cmd/spinifex` current-to-target map row requires command packages to reach domains through public capabilities; splitting supported use cases into `operator/*` packages is later work.
- `gateway/ec2.go` (registration): the EC2 dispatch map stays a `GatewayConfig` method in `gateway` and imports every `domains/ec2/awsapi/*` package. ADR-0001 makes the domain own its action registration; moving the map waits on the generic ingress registration seam and must not be done as a package move.
- `gateway/ec2.go` (registration): the EC2 dispatch map stays a `GatewayConfig` method in `gateway` and imports every `domains/ec2/awsapi/*` package; `gateway/ec2_idempotency.go` also imports `domains/ec2/awsapi/idem` (`KVBucket`, `TTL`, `TokenAndParams`) for the dispatch-time idempotency wrapper. ADR-0001 makes the domain own its action registration; moving the map waits on the generic ingress registration seam and must not be done as a package move.
- `gateway/requestaudit.go`: the outermost request-audit middleware records AWS fields and is updated from four places in the gateway's authentication flow through the gateway's own context key. Moving it would export about seven names used only by that flow, so it stays in `gateway` until the generic ingress registration seam defines how ingress middleware receives authentication results.
- `accountteardown` (dependency): its EC2 reapers call `domains/ec2/awsapi/*` action adapters directly, as they did under `gateway/ec2`. The ADR's `accountteardown` current-to-target map row replaces this with domain-owned cleanup capabilities before the package moves.
- `domains/admission/quota` (dependency, moved from `handlers/quota` unchanged): `live.go` imports `gateway/elbv2` and `handlers/rds` for its live ELBv2 and RDS counters; `records.go` imports `runtime/compute/vm` for the instance-record vCPU sweep; `live.go`, `vcpu.go` and `storage.go` call `domains/ec2/awsapi/{vpc,eip,volume}` describe adapters to count VPCs, subnets, addresses and volumes, as they did under `gateway/ec2`. The ADR's `handlers/quota` current-to-target map row replaces these with reader capabilities once their final locations exist.
@@ -428,9 +428,13 @@ Enforcement: the owner decided the layering test is blocking now, with a ratchet
- `handlers/eks` and `gateway/eks` → `domains/eks/addon` (further edges): the AWS adapter reads the persisted `Record` through `addon.Get`/`addon.List`; this clears when the owner returns a view and the add-on adapter moves to `domains/eks/awsapi`. The guest route reaches the owner through the `handlers_eks` NATS RPC (`ListStagedAddonManifests`); this clears with per-resource commands behind EKS registration. The add-on ARN is derived in both the owner and `gateway/eks/authz.go`; this clears when authorization obtains the ARN from the owner, which an incarnation suffix would require. The owner's `Manifest`/`Report` beside the `contracts/eks/v1` types is deliberate duplication, not debt.
- `agents/rds/agent` (dependency, narrowed): engine metadata now arrives through the agent-declared `EngineCatalog`, but the agent still imports `handlers/rds` for the command protocol, wire and record types (`Command*`, `Parameter`, `EngineHealth*`, `BootstrapMode*`) and API output types. This clears when those move behind a guest/controller wire contract.
- `gateway/rds` → `handlers/rds` (`InstanceSizing`): the gateway obtains its `Sizing` through the RDS handler package's adapter rather than its own composition root. This clears when the gateway's RDS composition moves to `runtime/roles/awsgw` and builds `Sizing` there.
- `domains/admission/quota` → `domains/ec2/instancetypes`: `reconcile.go`, `records.go` and `vcpu.go` read `DefaultVCPUs` to size instances without a recorded vCPU count. This clears when quota receives vCPU sizing through a consumer-owned capability or an EC2 projection.
- IAM implementation consumers in STS, Ochre and ELBv2: `handlers/sts` imports `handlers/iam` across five files (`IAMService`, `SessionRevoker`, `EncryptSecret`/`DecryptSecret`, `AccessKeyStatusActive`, `ValidateTrustPolicyDocument`, `PolicyEffectAllow`/`PolicyEffectDeny`, `IAMAccountBucketName`, `OIDCProviderARN`, `OIDCProviderKey`), not only `oidc_jwks.go`; `gateway/sts/GetCallerIdentity.go` takes `IAMService`; `gateway/bedrock/credentials.go` uses `EncryptSecret`/`DecryptSecret`; and `handlers/elbv2/{lb_role,service_impl}.go` use `EnsureSystemInstanceProfile` and `SystemInstanceRoleEnsurer`. Each clears when its consumer receives a narrow IAM capability, or a shared crypto boundary for the secret helpers, rather than importing the IAM implementation.
- `handlers/elbv2` (cross-domain): `service_impl.go` imports `domains/acm` (`Store`, `NewStore`), `domains/dns` (`ELBChanges`, `ELBName`, `Change`, `ActionUpsert`, `ResolveBaseDomain`), `domains/ec2/vpc` (`VPCServiceImpl`) and `domains/network/topology` (`Port`), and `launcher.go` re-exports `domains/ec2/systeminstance` launch types as aliases. These clear when ELBv2 is extracted and each edge becomes a consumer-owned capability, which ADR-0001 sequences after the ELBv2 data-plane boundary is settled.
- `operator/installer/ui` → `admin`: `ui.go` calls `admin.ValidateEmail` for installer input. This clears with the `admin` → `operator/admin` blocker, once `ValidateEmail` has an owner.
- `docs/service-interfaces.yaml` (coverage gap): no `ecs.*` subjects are listed and the manifest lint does not cover them, so ECS publisher/subscriber edges play no part in suite selection. Add them only after tracing the actual publishers and subscribers.
The layering test enforcing these rules is blocking, with a ratchet: the debt recorded in this section is narrowly allow-listed by owner and removal condition, and any new, unrecorded forbidden edge fails local preflight and CI. The allow-list mirrors this section.
The layering test enforcing these rules is blocking, with a ratchet: the debt recorded in this section is narrowly allow-listed by owner and removal condition, and any new, unrecorded forbidden edge fails local preflight and CI. The allow-list mirrors the edges in this section that break an import rule; same-domain legacy edges, placement residuals and security notes are not import-rule violations and have no allow-list entry.
- Merge-time follow-up in the umbrella repository: the `Makefile` `invariants-check` target, the `docs-pr.yml` clause cross-check, `.claude/hooks/architecture-traps.sh` and a `check-invariants.sh` comment hard-code `spinifex/spinifex/network/invariants`. They must change with the pointer bump that brings in this branch, or the docs-pr cross-check silently skips. Live specs and proposals citing `spinifex/network/` will report unresolved citations until updated. A read-only mulga-repository count (excluding submodules, `docs/development/archive/` and agent worktrees) confirms four items still open: `spinifex/network/` appears in 49 mulga files; `services/awsgw` appears in 19 (`.claude/rules/spinifex.md` plus 18 docs; the umbrella `.claude/CLAUDE.md` does not contain it but cites the old `network/policy/policy.go:28`); and `services/spinifexui` (including its `/frontend` subpath) appears in 20 mulga files, including `ansible/roles/build/tasks/main.yml`, the `.claude/settings.json` formatting hook, the `.claude/rules/frontend-standards.md` glob, `.claude/skills/run-spinifex/SKILL.md` and `ui-dev.sh`, `.vscode/settings.json` and `README.md`. The same `SKILL.md` also names `cmd/spinifex/cmd`, the obs-agent Ansible role's `otelsetup` path mirrors the pre-move name, and `docs/specs/guides/dependency-enforcement.md`'s "Known open edges" section carries the same pre-move paths; all four are mulga-repository updates, out of scope for a Spinifex-only commit.
@@ -483,7 +487,7 @@ series above; "needs decision" is open.
| Legacy path | What remains | What blocks it |
|---|---|---|
| `handlers/iam` | Private identity state and credential issuance; consumed by the EC2 instance and spot-instance AWS adapters, `handlers/sts/oidc_jwks.go`, the ELBv2 cert-in-use path, ECR/Ochre signing-key crypto and `operator/cli`. | Deferred: the ADR's `handlers/iam` row states a shared IAM contract is not inferred from current KV readers; each cross-domain reader needs an IAM capability first. |
| `handlers/iam` | Private identity state and credential issuance; consumed by the EC2 instance and spot-instance AWS adapters, `handlers/sts`, `gateway/sts`, `gateway/bedrock`, the ELBv2 system-instance role path, ECR/Ochre signing-key crypto and `operator/cli`. | Deferred: the ADR's `handlers/iam` row states a shared IAM contract is not inferred from current KV readers; each cross-domain reader needs an IAM capability first. |
| `handlers/sts` | Everything; not yet touched. | Deferred: Q-22 forbids the STS-to-EKS dependency in its present form; `oidc_jwks.go` still imports `handlers/eks` for `AccountBucketName`/`OIDCJWKSKey`. |
| `handlers/ecs` | Task, service and capacity resources (`taskdefinition` already extracted to `domains/ecs/taskdefinition`). | Deferred: ADR-0004 blocked-dependency list — `iam:PassRole` in the gateway adapter and EC2/ELBv2/EIP adapters called as internal APIs. |
| `handlers/eks` | Nodegroup and cluster resources (`access` and `addon` already extracted). | Deferred: ADR-0004 blocked-dependency list — IAM role/instance-profile creation, Bluebottle `auth`, the NATS CA, and EKS identity (token review, OIDC). |
@@ -0,0 +1,182 @@
package layering
// allowance is one recorded forbidden import, allowed until its debt clears.
type allowance struct {
From, To string
Debt string // subject of the migration record's debt entry or close-out row
Reason string
}
// allowlist mirrors the dependency-rule debt and close-out table in
// docs/PACKAGE_BOUNDARY_MIGRATION.md. It only shrinks: add an edge only with
// recorded debt, and delete an entry as soon as its import is gone.
var allowlist = []allowance{
{From: "accountteardown", To: "domains/ec2/awsapi/eip", Debt: "accountteardown (dependency)", Reason: "EC2 reapers call the awsapi action adapters; needs domain-owned cleanup capabilities"},
{From: "accountteardown", To: "domains/ec2/awsapi/igw", Debt: "accountteardown (dependency)", Reason: "EC2 reapers call the awsapi action adapters; needs domain-owned cleanup capabilities"},
{From: "accountteardown", To: "domains/ec2/awsapi/image", Debt: "accountteardown (dependency)", Reason: "EC2 reapers call the awsapi action adapters; needs domain-owned cleanup capabilities"},
{From: "accountteardown", To: "domains/ec2/awsapi/instance", Debt: "accountteardown (dependency)", Reason: "EC2 reapers call the awsapi action adapters; needs domain-owned cleanup capabilities"},
{From: "accountteardown", To: "domains/ec2/awsapi/key", Debt: "accountteardown (dependency)", Reason: "EC2 reapers call the awsapi action adapters; needs domain-owned cleanup capabilities"},
{From: "accountteardown", To: "domains/ec2/awsapi/launchtemplate", Debt: "accountteardown (dependency)", Reason: "EC2 reapers call the awsapi action adapters; needs domain-owned cleanup capabilities"},
{From: "accountteardown", To: "domains/ec2/awsapi/placementgroup", Debt: "accountteardown (dependency)", Reason: "EC2 reapers call the awsapi action adapters; needs domain-owned cleanup capabilities"},
{From: "accountteardown", To: "domains/ec2/awsapi/routetable", Debt: "accountteardown (dependency)", Reason: "EC2 reapers call the awsapi action adapters; needs domain-owned cleanup capabilities"},
{From: "accountteardown", To: "domains/ec2/awsapi/snapshot", Debt: "accountteardown (dependency)", Reason: "EC2 reapers call the awsapi action adapters; needs domain-owned cleanup capabilities"},
{From: "accountteardown", To: "domains/ec2/awsapi/volume", Debt: "accountteardown (dependency)", Reason: "EC2 reapers call the awsapi action adapters; needs domain-owned cleanup capabilities"},
{From: "accountteardown", To: "domains/ec2/awsapi/vpc", Debt: "accountteardown (dependency)", Reason: "EC2 reapers call the awsapi action adapters; needs domain-owned cleanup capabilities"},
{From: "agents/ecs/agent", To: "handlers/ecs", Debt: "agents/ecs/agent", Reason: "assignment/state wire types from the ECS implementation; needs a guest/controller contract"},
{From: "agents/ecs/agent", To: "handlers/ecs/bus", Debt: "agents/ecs/agent", Reason: "assignment/state wire types from the ECS implementation; needs a guest/controller contract"},
{From: "agents/eks/tokenwebhook", To: "handlers/eks", Debt: "agents/eks/tokenwebhook", Reason: "WebhookTokenReviewResult from the EKS implementation; needs an EKS contract or projection"},
{From: "agents/rds/agent", To: "handlers/rds", Debt: "agents/rds/agent (dependency, narrowed)", Reason: "command protocol, wire and record types; needs a guest/controller wire contract"},
{From: "cmd/aws-model-coverage", To: "domains/acm/awsapi", Debt: "cmd/aws-model-coverage", Reason: "reads declared ECR/ACM inventories; named exception, must not construct a registration"},
{From: "cmd/aws-model-coverage", To: "domains/ecr/awsapi", Debt: "cmd/aws-model-coverage", Reason: "reads declared ECR/ACM inventories; named exception, must not construct a registration"},
{From: "daemon", To: "domains/ec2/awsapi/instance", Debt: "Instance adapter consumers outside EC2", Reason: "daemon/eks_cp_control.go and rds_deps.go call the instance adapter; needs an EC2 capability"},
{From: "domains/acm", To: "handlers/iam", Debt: "ACM: the IAM AES-GCM helper import (ACM relocation residual)", Reason: "IAM AES-GCM helpers; needs a shared crypto boundary"},
{From: "domains/admission/quota", To: "domains/ec2/awsapi/eip", Debt: "domains/admission/quota (dependency, moved from handlers/quota unchanged)", Reason: "describe adapter used as a counter; needs a reader capability"},
{From: "domains/admission/quota", To: "domains/ec2/awsapi/instance", Debt: "domains/admission/quota (dependency, moved from handlers/quota unchanged)", Reason: "vcpu.go counts instances through the instance adapter; needs an EC2 reader capability"},
{From: "domains/admission/quota", To: "domains/ec2/awsapi/volume", Debt: "domains/admission/quota (dependency, moved from handlers/quota unchanged)", Reason: "describe adapter used as a counter; needs a reader capability"},
{From: "domains/admission/quota", To: "domains/ec2/awsapi/vpc", Debt: "domains/admission/quota (dependency, moved from handlers/quota unchanged)", Reason: "describe adapter used as a counter; needs a reader capability"},
{From: "domains/admission/quota", To: "domains/ec2/instancetypes", Debt: "domains/admission/quota → domains/ec2/instancetypes", Reason: "DefaultVCPUs sizing; needs a consumer-owned capability or EC2 projection"},
{From: "domains/admission/quota", To: "gateway/elbv2", Debt: "domains/admission/quota (dependency, moved from handlers/quota unchanged)", Reason: "live ELBv2 counter; needs a reader capability"},
{From: "domains/admission/quota", To: "handlers/rds", Debt: "domains/admission/quota (dependency, moved from handlers/quota unchanged)", Reason: "live RDS counter; needs a reader capability"},
{From: "domains/admission/quota", To: "runtime/compute/vm", Debt: "domains/admission/quota (dependency, moved from handlers/quota unchanged)", Reason: "instance-record vCPU sweep; needs a reader capability"},
{From: "domains/dns", To: "domains/network/reconcile", Debt: "domains/dns", Reason: "takes the reconcile lock from network's implementation"},
{From: "domains/dns", To: "runtime/compute/vm", Debt: "domains/dns", Reason: "domain-to-runtime import of VM state"},
{From: "domains/ec2/awsapi/instance", To: "handlers/iam", Debt: "domains/ec2/awsapi/instance (dependency)", Reason: "IAM edge needs an IAM capability"},
{From: "domains/ec2/awsapi/instance", To: "runtime/compute/cache", Debt: "domains/ec2/awsapi/instance (dependency)", Reason: "node liveness and VM state; needs an EC2-owned projection"},
{From: "domains/ec2/awsapi/instance", To: "runtime/compute/vm", Debt: "domains/ec2/awsapi/instance (dependency)", Reason: "node liveness and VM state; needs an EC2-owned projection"},
{From: "domains/ec2/awsapi/spotinstance", To: "domains/admission/quota", Debt: "domains/ec2/awsapi/spotinstance (dependency)", Reason: "RequestSpotInstances.go uses IAMService and quota.Service"},
{From: "domains/ec2/awsapi/spotinstance", To: "handlers/iam", Debt: "domains/ec2/awsapi/spotinstance (dependency)", Reason: "RequestSpotInstances.go uses IAMService and quota.Service"},
{From: "domains/ec2/eip", To: "domains/network/topology", Debt: "EC2 → network implementation", Reason: "EC2 reads network implementation; clears with the EC2-owned projection"},
{From: "domains/ec2/eip", To: "utils", Debt: "utils", Reason: "consumes a recorded utils residual file awaiting its owner"},
{From: "domains/ec2/guestmetadata", To: "domains/dns", Debt: "Guest metadata: the cross-domain and runtime imports above", Reason: "guest-metadata relocation residual; needs capabilities, projections or contracts"},
{From: "domains/ec2/guestmetadata", To: "handlers/iam", Debt: "Guest metadata: the cross-domain and runtime imports above", Reason: "guest-metadata relocation residual; needs capabilities, projections or contracts"},
{From: "domains/ec2/guestmetadata", To: "handlers/sts", Debt: "Guest metadata: the cross-domain and runtime imports above", Reason: "guest-metadata relocation residual; needs capabilities, projections or contracts"},
{From: "domains/ec2/guestmetadata", To: "runtime/compute/vm", Debt: "Guest metadata: the cross-domain and runtime imports above", Reason: "guest-metadata relocation residual; needs capabilities, projections or contracts"},
{From: "domains/ec2/image", To: "utils", Debt: "utils", Reason: "consumes a recorded utils residual file awaiting its owner"},
{From: "domains/ec2/instance", To: "domains/dns", Debt: "domains/ec2/instance", Reason: "cross-domain implementation import of DNS"},
{From: "domains/ec2/instance", To: "domains/network/topology", Debt: "EC2 → network implementation", Reason: "EC2 reads network implementation; clears with the EC2-owned projection"},
{From: "domains/ec2/instance", To: "runtime/compute/gpu", Debt: "domains/ec2/instance", Reason: "VM/GPU runtime state read directly; needs a domain-owned projection"},
{From: "domains/ec2/instance", To: "runtime/compute/vm", Debt: "domains/ec2/instance", Reason: "VM/GPU runtime state read directly; needs a domain-owned projection"},
{From: "domains/ec2/instance", To: "utils", Debt: "utils", Reason: "consumes a recorded utils residual file awaiting its owner"},
{From: "domains/ec2/volume", To: "runtime/compute/vm", Debt: "Domain → runtime", Reason: "VM runtime state read directly; needs a domain-owned projection"},
{From: "domains/ec2/volume", To: "utils", Debt: "utils", Reason: "consumes a recorded utils residual file awaiting its owner"},
{From: "domains/ec2/vpc", To: "domains/network/external", Debt: "EC2 → network implementation", Reason: "EC2 reads network implementation; clears with the EC2-owned projection"},
{From: "domains/ec2/vpc", To: "domains/network/external/dhcp", Debt: "EC2 → network implementation", Reason: "EC2 reads network implementation; clears with the EC2-owned projection"},
{From: "domains/ec2/vpc", To: "domains/network/identifiers", Debt: "EC2 → network implementation", Reason: "EC2 reads network implementation; clears with the EC2-owned projection"},
{From: "domains/ec2/vpc", To: "domains/network/topology", Debt: "EC2 → network implementation", Reason: "EC2 reads network implementation; clears with the EC2-owned projection"},
{From: "domains/ec2/vpc", To: "utils", Debt: "utils", Reason: "consumes a recorded utils residual file awaiting its owner"},
{From: "domains/ecr/auth", To: "handlers/iam", Debt: "Cross-domain", Reason: "IAM implementation import; needs an IAM capability"},
{From: "domains/network/host", To: "runtime/compute/vm", Debt: "domains/network", Reason: "domain-to-runtime import"},
{From: "domains/network/host", To: "runtime/host/command", Debt: "domains/network", Reason: "domain-to-runtime import"},
{From: "domains/network/reconcile", To: "domains/ec2/eip", Debt: "domains/network", Reason: "reconcile reads EC2 private records; clears with the EC2-owned projection"},
{From: "domains/network/reconcile", To: "domains/ec2/igw", Debt: "domains/network", Reason: "reconcile reads EC2 private records; clears with the EC2-owned projection"},
{From: "domains/network/reconcile", To: "domains/ec2/natgw", Debt: "domains/network", Reason: "reconcile reads EC2 private records; clears with the EC2-owned projection"},
{From: "domains/network/reconcile", To: "domains/ec2/routetable", Debt: "domains/network", Reason: "reconcile reads EC2 private records; clears with the EC2-owned projection"},
{From: "domains/network/reconcile", To: "domains/ec2/vpc", Debt: "domains/network", Reason: "reconcile reads EC2 private records; clears with the EC2-owned projection"},
{From: "domains/network/reconcile", To: "runtime/compute/vm", Debt: "domains/network", Reason: "domain-to-runtime import"},
{From: "domains/ochre", To: "domains/ec2/systeminstance", Debt: "Cross-domain", Reason: "consumes another domain's implementation rather than a capability"},
{From: "domains/ochre", To: "domains/network/systemvpc", Debt: "Cross-domain", Reason: "consumes another domain's implementation rather than a capability"},
{From: "domains/ochre", To: "gateway/bedrock", Debt: "gateway/bedrock", Reason: "Ochre domain core still lives in gateway/bedrock; needs the recorded split"},
{From: "domains/ochre", To: "runtime/compute/gpu", Debt: "Domain → runtime", Reason: "GPU runtime state read directly; needs a domain-owned projection"},
{From: "domains/ochre/vector", To: "handlers/iam", Debt: "Cross-domain", Reason: "consumes another domain's implementation rather than a capability"},
{From: "gateway", To: "domains/ec2/awsapi", Debt: "gateway/ec2.go (registration)", Reason: "EC2 dispatch map stays in gateway until the ingress registration seam"},
{From: "gateway", To: "domains/ec2/awsapi/account", Debt: "gateway/ec2.go (registration)", Reason: "EC2 dispatch map stays in gateway until the ingress registration seam"},
{From: "gateway", To: "domains/ec2/awsapi/capacityreservation", Debt: "gateway/ec2.go (registration)", Reason: "EC2 dispatch map stays in gateway until the ingress registration seam"},
{From: "gateway", To: "domains/ec2/awsapi/eigw", Debt: "gateway/ec2.go (registration)", Reason: "EC2 dispatch map stays in gateway until the ingress registration seam"},
{From: "gateway", To: "domains/ec2/awsapi/eip", Debt: "gateway/ec2.go (registration)", Reason: "EC2 dispatch map stays in gateway until the ingress registration seam"},
{From: "gateway", To: "domains/ec2/awsapi/idem", Debt: "gateway/ec2.go (registration; ec2_idempotency.go)", Reason: "dispatch-time idempotency wrapper; moves with the EC2 dispatch map"},
{From: "gateway", To: "domains/ec2/awsapi/igw", Debt: "gateway/ec2.go (registration)", Reason: "EC2 dispatch map stays in gateway until the ingress registration seam"},
{From: "gateway", To: "domains/ec2/awsapi/image", Debt: "gateway/ec2.go (registration)", Reason: "EC2 dispatch map stays in gateway until the ingress registration seam"},
{From: "gateway", To: "domains/ec2/awsapi/instance", Debt: "gateway/ec2.go (registration)", Reason: "EC2 dispatch map stays in gateway until the ingress registration seam"},
{From: "gateway", To: "domains/ec2/awsapi/key", Debt: "gateway/ec2.go (registration)", Reason: "EC2 dispatch map stays in gateway until the ingress registration seam"},
{From: "gateway", To: "domains/ec2/awsapi/launchtemplate", Debt: "gateway/ec2.go (registration)", Reason: "EC2 dispatch map stays in gateway until the ingress registration seam"},
{From: "gateway", To: "domains/ec2/awsapi/natgw", Debt: "gateway/ec2.go (registration)", Reason: "EC2 dispatch map stays in gateway until the ingress registration seam"},
{From: "gateway", To: "domains/ec2/awsapi/placementgroup", Debt: "gateway/ec2.go (registration)", Reason: "EC2 dispatch map stays in gateway until the ingress registration seam"},
{From: "gateway", To: "domains/ec2/awsapi/routetable", Debt: "gateway/ec2.go (registration)", Reason: "EC2 dispatch map stays in gateway until the ingress registration seam"},
{From: "gateway", To: "domains/ec2/awsapi/snapshot", Debt: "gateway/ec2.go (registration)", Reason: "EC2 dispatch map stays in gateway until the ingress registration seam"},
{From: "gateway", To: "domains/ec2/awsapi/spotinstance", Debt: "gateway/ec2.go (registration)", Reason: "EC2 dispatch map stays in gateway until the ingress registration seam"},
{From: "gateway", To: "domains/ec2/awsapi/tags", Debt: "gateway/ec2.go (registration)", Reason: "EC2 dispatch map stays in gateway until the ingress registration seam"},
{From: "gateway", To: "domains/ec2/awsapi/volume", Debt: "gateway/ec2.go (registration)", Reason: "EC2 dispatch map stays in gateway until the ingress registration seam"},
{From: "gateway", To: "domains/ec2/awsapi/vpc", Debt: "gateway/ec2.go (registration)", Reason: "EC2 dispatch map stays in gateway until the ingress registration seam"},
{From: "gateway", To: "domains/ec2/awsapi/zone", Debt: "gateway/ec2.go (registration)", Reason: "EC2 dispatch map stays in gateway until the ingress registration seam"},
{From: "gateway/bedrock", To: "handlers/iam", Debt: "IAM implementation consumers in STS, Ochre and ELBv2", Reason: "secret encrypt/decrypt helpers; needs a shared crypto boundary"},
{From: "gateway/rds", To: "domains/ec2/awsapi/instance", Debt: "Instance adapter consumers outside EC2", Reason: "enginecatalog.go calls the instance adapter; needs an EC2 capability"},
{From: "gateway/sts", To: "handlers/iam", Debt: "IAM implementation consumers in STS, Ochre and ELBv2", Reason: "GetCallerIdentity takes IAMService; needs an IAM capability"},
{From: "gateway/tagging", To: "domains/ec2/tags", Debt: "close-out: gateway/tagging", Reason: "cross-service GetResources; clears when domains/tagging aggregates through per-domain capabilities"},
{From: "gateway/tagging", To: "handlers/elbv2", Debt: "close-out: gateway/tagging", Reason: "cross-service GetResources; clears when domains/tagging aggregates through per-domain capabilities"},
{From: "handlers/ecs", To: "domains/ec2/ebs/metadata", Debt: "close-out: handlers/ecs (ADR-0004 blocked-dependency list; inventory-ecs boundary imports)", Reason: "legacy ECS calls another domain's implementation as an internal API"},
{From: "handlers/ecs", To: "domains/ec2/eip", Debt: "close-out: handlers/ecs (ADR-0004 blocked-dependency list; inventory-ecs boundary imports)", Reason: "legacy ECS calls another domain's implementation as an internal API"},
{From: "handlers/ecs", To: "domains/ec2/instancetypes", Debt: "close-out: handlers/ecs (ADR-0004 blocked-dependency list; inventory-ecs boundary imports)", Reason: "legacy ECS calls another domain's implementation as an internal API"},
{From: "handlers/ecs", To: "handlers/elbv2", Debt: "close-out: handlers/ecs (ADR-0004 blocked-dependency list; inventory-ecs boundary imports)", Reason: "legacy ECS calls another domain's implementation as an internal API"},
{From: "handlers/ecs", To: "handlers/iam", Debt: "close-out: handlers/ecs (ADR-0004 blocked-dependency list; inventory-ecs boundary imports)", Reason: "legacy ECS calls another domain's implementation as an internal API"},
{From: "handlers/eks", To: "domains/dns", Debt: "close-out: handlers/eks (ADR-0004 blocked-dependency list; inventory-eks boundary imports)", Reason: "legacy EKS calls another domain's or runtime implementation directly"},
{From: "handlers/eks", To: "domains/ec2/ebs/metadata", Debt: "close-out: handlers/eks (ADR-0004 blocked-dependency list; inventory-eks boundary imports)", Reason: "legacy EKS calls another domain's or runtime implementation directly"},
{From: "handlers/eks", To: "domains/ec2/instancetypes", Debt: "close-out: handlers/eks (ADR-0004 blocked-dependency list; inventory-eks boundary imports)", Reason: "legacy EKS calls another domain's or runtime implementation directly"},
{From: "handlers/eks", To: "domains/ec2/placementgroup", Debt: "close-out: handlers/eks (ADR-0004 blocked-dependency list; inventory-eks boundary imports)", Reason: "legacy EKS calls another domain's or runtime implementation directly"},
{From: "handlers/eks", To: "domains/ec2/systeminstance", Debt: "close-out: handlers/eks (ADR-0004 blocked-dependency list; inventory-eks boundary imports)", Reason: "legacy EKS calls another domain's or runtime implementation directly"},
{From: "handlers/eks", To: "domains/network/systemvpc", Debt: "close-out: handlers/eks (ADR-0004 blocked-dependency list; inventory-eks boundary imports)", Reason: "legacy EKS calls another domain's or runtime implementation directly"},
{From: "handlers/eks", To: "handlers/iam", Debt: "close-out: handlers/eks (ADR-0004 blocked-dependency list; inventory-eks boundary imports)", Reason: "legacy EKS calls another domain's or runtime implementation directly"},
{From: "handlers/eks", To: "runtime/compute/vm", Debt: "close-out: handlers/eks (ADR-0004 blocked-dependency list; inventory-eks boundary imports)", Reason: "legacy EKS calls another domain's or runtime implementation directly"},
{From: "handlers/elbv2", To: "domains/acm", Debt: "handlers/elbv2 (cross-domain)", Reason: "legacy ELBv2 cross-domain import; clears when ELBv2 is extracted behind consumer-owned capabilities"},
{From: "handlers/elbv2", To: "domains/dns", Debt: "handlers/elbv2 (cross-domain)", Reason: "legacy ELBv2 cross-domain import; clears when ELBv2 is extracted behind consumer-owned capabilities"},
{From: "handlers/elbv2", To: "domains/ec2/systeminstance", Debt: "handlers/elbv2 (cross-domain)", Reason: "legacy ELBv2 cross-domain import; clears when ELBv2 is extracted behind consumer-owned capabilities"},
{From: "handlers/elbv2", To: "domains/ec2/vpc", Debt: "handlers/elbv2 (cross-domain)", Reason: "legacy ELBv2 cross-domain import; clears when ELBv2 is extracted behind consumer-owned capabilities"},
{From: "handlers/elbv2", To: "domains/network/topology", Debt: "handlers/elbv2 (cross-domain)", Reason: "legacy ELBv2 cross-domain import; clears when ELBv2 is extracted behind consumer-owned capabilities"},
{From: "handlers/elbv2", To: "handlers/iam", Debt: "IAM implementation consumers in STS, Ochre and ELBv2", Reason: "system-instance role ensurer; needs an IAM capability"},
{From: "handlers/elbv2", To: "lbagent", Debt: "handlers/elbv2/{agent_types,haproxy,health_checker,nginx}.go import lbagent", Reason: "health-report and cert/PID-path vocabulary; needs a guest/controller contract"},
{From: "handlers/elbv2", To: "utils", Debt: "utils", Reason: "consumes a recorded utils residual file awaiting its owner"},
{From: "handlers/iam", To: "admin", Debt: "handlers/iam/service_impl.go:30 imports admin", Reason: "credential and account helpers; blocked with admin -> operator/admin"},
{From: "handlers/rds", To: "domains/dns", Debt: "close-out: handlers/rds (ADR-0004 blocked-dependency list; inventory-rds boundary imports)", Reason: "legacy RDS calls another domain's or runtime implementation directly"},
{From: "handlers/rds", To: "domains/ec2/instance", Debt: "close-out: handlers/rds (ADR-0004 blocked-dependency list; inventory-rds boundary imports)", Reason: "legacy RDS calls another domain's or runtime implementation directly"},
{From: "handlers/rds", To: "domains/ec2/instancetypes", Debt: "close-out: handlers/rds (ADR-0004 blocked-dependency list; inventory-rds boundary imports)", Reason: "legacy RDS calls another domain's or runtime implementation directly"},
{From: "handlers/rds", To: "domains/ec2/systeminstance", Debt: "close-out: handlers/rds (ADR-0004 blocked-dependency list; inventory-rds boundary imports)", Reason: "legacy RDS calls another domain's or runtime implementation directly"},
{From: "handlers/rds", To: "domains/network/systemvpc", Debt: "close-out: handlers/rds (ADR-0004 blocked-dependency list; inventory-rds boundary imports)", Reason: "legacy RDS calls another domain's or runtime implementation directly"},
{From: "handlers/rds", To: "handlers/iam", Debt: "close-out: handlers/rds (ADR-0004 blocked-dependency list; inventory-rds boundary imports)", Reason: "legacy RDS calls another domain's or runtime implementation directly"},
{From: "handlers/rds", To: "runtime/compute/vm", Debt: "close-out: handlers/rds (ADR-0004 blocked-dependency list; inventory-rds boundary imports)", Reason: "legacy RDS calls another domain's or runtime implementation directly"},
{From: "handlers/sts", To: "handlers/eks", Debt: "handlers/sts/oidc_jwks.go:14 imports handlers/eks (Q-22)", Reason: "needs an EKS-owned OIDC projection or identity-owned contract"},
{From: "handlers/sts", To: "handlers/iam", Debt: "IAM implementation consumers in STS, Ochre and ELBv2", Reason: "STS reads IAM service, trust-policy and OIDC-provider state; needs an IAM capability"},
{From: "operator/cli", To: "accountteardown", Debt: "operator/cli (dependency)", Reason: "command tree imports implementations; needs public capabilities"},
{From: "operator/cli", To: "admin", Debt: "operator/cli (dependency)", Reason: "command tree imports implementations; needs public capabilities"},
{From: "operator/cli", To: "daemon", Debt: "operator/cli (dependency)", Reason: "command tree imports implementations; needs public capabilities"},
{From: "operator/cli", To: "gateway", Debt: "operator/cli (dependency)", Reason: "command tree imports implementations; needs public capabilities"},
{From: "operator/cli", To: "gateway/bedrock", Debt: "operator/cli (dependency)", Reason: "command tree imports implementations; needs public capabilities"},
{From: "operator/cli", To: "handlers/eks", Debt: "operator/cli (dependency)", Reason: "command tree imports implementations; needs public capabilities"},
{From: "operator/cli", To: "handlers/iam", Debt: "operator/cli (dependency)", Reason: "command tree imports implementations; needs public capabilities"},
{From: "operator/cli", To: "services/viperblockd", Debt: "operator/cli (dependency)", Reason: "command tree imports implementations; needs public capabilities"},
{From: "operator/cli", To: "services/viperblockd/vbwire", Debt: "operator/cli (dependency)", Reason: "command tree imports implementations; needs public capabilities"},
{From: "operator/cli", To: "vpcd", Debt: "operator/cli (dependency)", Reason: "command tree imports implementations; needs public capabilities"},
{From: "operator/installer/ui", To: "admin", Debt: "operator/installer/ui → admin", Reason: "ValidateEmail; clears with the admin -> operator/admin blocker"},
}
@@ -0,0 +1,163 @@
// Package layering enforces ADR-0001's package-boundary dependency rules over
// the module's production import graph, ratcheted by a recorded-debt allowlist.
package layering
import (
"errors"
"fmt"
"go/ast"
"go/build/constraint"
"go/parser"
"go/token"
"io/fs"
"os"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
)
const modulePath = "github.com/mulgadc/spinifex"
// edge is one package-to-package import, both sides named as in the allowlist:
// application packages relative to spinifex/, module-root ones (cmd/,
// contracts/, internal/) relative to the module root.
type edge struct {
From, To string
}
func (e edge) String() string { return e.From + " -> " + e.To }
// graph is the production import graph restricted to this module.
type graph struct {
// pkgs maps a package name to its module-relative directory.
pkgs map[string]string
// imports records the first file:line at which each edge appears.
imports map[edge]string
}
func newGraph() *graph {
return &graph{pkgs: map[string]string{}, imports: map[edge]string{}}
}
// shortName drops the application-root prefix so names read like the ADR and
// the migration record; classify rejects app-root dirs that would collide.
func shortName(full string) string {
if rest, ok := strings.CutPrefix(full, "spinifex/"); ok {
return rest
}
return full
}
func moduleRoot() (string, error) {
_, file, _, ok := runtime.Caller(0)
if !ok {
return "", errors.New("cannot locate test source")
}
// spinifex/spinifex/architecture/layering/graph_test.go -> module root.
return filepath.Abs(filepath.Join(filepath.Dir(file), "..", "..", ".."))
}
// excludedTopDirs hold no production code: tests/ is test-only and docs/ only
// embeds documentation; neither is mapped to a layer.
var excludedTopDirs = map[string]bool{"tests": true, "docs": true}
// loadGraph parses the imports of every non-test Go file under root, so it
// sees every build-tag variant and needs no Go toolchain or workspace.
func loadGraph(root string) (*graph, error) {
g := newGraph()
fset := token.NewFileSet()
err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
rel, err := filepath.Rel(root, path)
if err != nil {
return err
}
rel = filepath.ToSlash(rel)
if d.IsDir() {
if rel == "." {
return nil
}
name := d.Name()
if strings.HasPrefix(name, ".") || strings.HasPrefix(name, "_") ||
name == "testdata" || name == "vendor" || name == "node_modules" || excludedTopDirs[rel] {
return filepath.SkipDir
}
if _, err := os.Stat(filepath.Join(path, "go.mod")); err == nil {
return filepath.SkipDir
}
return nil
}
if !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") {
return nil
}
f, err := parser.ParseFile(fset, path, nil, parser.ImportsOnly|parser.ParseComments)
if err != nil {
return err
}
if ignoredByBuildTag(f.Comments, f.Package) {
return nil
}
dir := filepath.ToSlash(filepath.Dir(rel))
if dir == "." {
dir = ""
}
from := shortName(dir)
g.pkgs[from] = dir
for _, imp := range f.Imports {
p, err := strconv.Unquote(imp.Path.Value)
if err != nil {
return err
}
target, ok := strings.CutPrefix(p, modulePath+"/")
if !ok {
continue
}
e := edge{From: from, To: shortName(target)}
if _, seen := g.imports[e]; !seen {
pos := fset.Position(imp.Pos())
g.imports[e] = fmt.Sprintf("%s:%d", rel, pos.Line)
}
}
return nil
})
return g, err
}
// ignoredByBuildTag reports a `//go:build ignore` file, which is a standalone
// program (a generator) rather than part of its directory's package.
func ignoredByBuildTag(groups []*ast.CommentGroup, pkgPos token.Pos) bool {
for _, cg := range groups {
if cg.Pos() >= pkgPos {
break
}
for _, c := range cg.List {
if !constraint.IsGoBuild(c.Text) {
continue
}
expr, err := constraint.Parse(c.Text)
if err == nil && expr.String() == "ignore" {
return true
}
}
}
return false
}
// sortedEdges returns the graph's edges in a stable order.
func (g *graph) sortedEdges() []edge {
out := make([]edge, 0, len(g.imports))
for e := range g.imports {
out = append(out, e)
}
sort.Slice(out, func(i, j int) bool {
if out[i].From != out[j].From {
return out[i].From < out[j].From
}
return out[i].To < out[j].To
})
return out
}
@@ -0,0 +1,193 @@
package layering
import (
"fmt"
"sort"
"strings"
"testing"
)
type violation struct {
rule string
edge edge
pos string
}
type report struct {
unmapped []string
violations []violation // every rule hit, allowlisted or not
unrecorded []violation // hits whose edge has no allowlist entry
stale []allowance // entries whose edge no rule rejects any more
malformed []string
}
// check classifies g, applies every rule and compares the result with allow.
func check(g *graph, allow []allowance) report {
var rep report
classes := map[string]class{}
for name, dir := range g.pkgs {
c, ok := classify(dir)
if !ok || c.layer == layerTests {
rep.unmapped = append(rep.unmapped, fmt.Sprintf("%s (directory %s)", name, dir))
continue
}
classes[name] = c
}
allowed := map[edge]bool{}
for _, a := range allow {
e := edge{From: a.From, To: a.To}
switch {
case allowed[e]:
rep.malformed = append(rep.malformed, "duplicate entry "+e.String())
case a.Debt == "" || a.Reason == "":
rep.malformed = append(rep.malformed, "entry "+e.String()+" needs both Debt and Reason")
}
allowed[e] = true
}
hit := map[edge]bool{}
for _, e := range g.sortedEdges() {
from, ok := classes[e.From]
if !ok {
continue
}
to, ok := classify(fullPath(e.To))
if !ok {
rep.unmapped = append(rep.unmapped, fmt.Sprintf("%s (imported by %s at %s)", e.To, e.From, g.imports[e]))
continue
}
for _, r := range rules {
if !r.subject(from, e.From) || !r.forbids(from, to, e.From) {
continue
}
v := violation{rule: r.id, edge: e, pos: g.imports[e]}
rep.violations = append(rep.violations, v)
hit[e] = true
if !allowed[e] {
rep.unrecorded = append(rep.unrecorded, v)
}
}
}
for _, a := range allow {
if !hit[edge{From: a.From, To: a.To}] {
rep.stale = append(rep.stale, a)
}
}
sort.Strings(rep.unmapped)
return rep
}
func ruleByID(id string) rule {
for _, r := range rules {
if r.id == id {
return r
}
}
panic("unknown rule " + id)
}
// TestADR0001_Layering is the blocking ratchet over the real import graph.
func TestADR0001_Layering(t *testing.T) {
root, err := moduleRoot()
if err != nil {
t.Fatal(err)
}
g, err := loadGraph(root)
if err != nil {
t.Fatal(err)
}
// Guards against a walk that silently finds nothing and passes vacuously.
if len(g.pkgs) < 100 || len(g.imports) < 500 {
t.Fatalf("scanned %d packages and %d module imports under %s; the walk has lost the tree and every rule would pass vacuously",
len(g.pkgs), len(g.imports), root)
}
rep := check(g, allowlist)
t.Run("Classification_EveryPackageMapped", func(t *testing.T) {
for _, u := range rep.unmapped {
t.Errorf("ADR-0001 current-to-target map: package %s has no layer; place it under an ADR-0001 home or classify it deliberately in layers_test.go", u)
}
})
for _, r := range rules {
t.Run(r.id, func(t *testing.T) {
subjects := 0
for name, dir := range g.pkgs {
if c, ok := classify(dir); ok && r.subject(c, name) {
subjects++
}
}
if subjects == 0 {
t.Fatalf("no scanned package is governed by %s; the rule would pass vacuously", r.id)
}
var snippets []string
for _, v := range rep.unrecorded {
if v.rule != r.id {
continue
}
t.Errorf("ADR-0001 %s: %s imports %s (%s); %s",
r.clause, v.edge.From, v.edge.To, v.pos, r.hint)
snippets = append(snippets, fmt.Sprintf("{From: %q, To: %q, Debt: \"<migration-record debt subject>\", Reason: \"<why>\"},", v.edge.From, v.edge.To))
}
if len(snippets) > 0 {
t.Logf("fix the import; only debt already recorded in docs/PACKAGE_BOUNDARY_MIGRATION.md may be allow-listed:\n%s",
strings.Join(snippets, "\n"))
}
})
}
t.Run("Allowlist_NoStaleEntries", func(t *testing.T) {
for _, a := range rep.stale {
t.Errorf("allowlist entry %s -> %s (%s) no longer matches a forbidden import; the debt is paid, so delete the entry from allowlist_test.go",
a.From, a.To, a.Debt)
}
})
t.Run("Allowlist_WellFormed", func(t *testing.T) {
for _, m := range rep.malformed {
t.Errorf("allowlist_test.go: %s", m)
}
t.Logf("%d allow-listed edges", len(allowlist))
})
}
// TestADR0001_LayeringCheckerDetectsFaults injects a forbidden edge, a stale
// allowlist entry and an unmapped package into a synthetic graph.
func TestADR0001_LayeringCheckerDetectsFaults(t *testing.T) {
g := newGraph()
for _, dir := range []string{
"spinifex/foundation/widget", "spinifex/domains/alpha/thing",
"spinifex/domains/beta/store", "spinifex/misc",
} {
g.pkgs[shortName(dir)] = dir
}
forbidden := edge{From: "foundation/widget", To: "domains/alpha/thing"}
g.imports[forbidden] = "spinifex/foundation/widget/w.go:7"
allowedEdge := edge{From: "domains/alpha/thing", To: "domains/beta/store"}
g.imports[allowedEdge] = "spinifex/domains/alpha/thing/t.go:9"
staleEntry := allowance{From: "domains/beta/store", To: "domains/alpha/thing", Debt: "synthetic", Reason: "stale"}
rep := check(g, []allowance{
{From: allowedEdge.From, To: allowedEdge.To, Debt: "synthetic", Reason: "recorded"},
staleEntry,
})
if len(rep.unrecorded) != 1 || rep.unrecorded[0].edge != forbidden ||
rep.unrecorded[0].rule != ruleByID("R1_FoundationImportsOnlyFoundation").id {
t.Errorf("want only %s reported under R1, got %+v", forbidden, rep.unrecorded)
}
if len(rep.stale) != 1 || rep.stale[0] != staleEntry {
t.Errorf("want stale entry %+v, got %+v", staleEntry, rep.stale)
}
if len(rep.unmapped) != 1 || !strings.HasPrefix(rep.unmapped[0], "misc ") {
t.Errorf("want unmapped package misc, got %v", rep.unmapped)
}
var allowedHit bool
for _, v := range rep.violations {
allowedHit = allowedHit || v.edge == allowedEdge
}
if !allowedHit {
t.Errorf("allow-listed cross-domain edge %s was not detected by R3, so the allowlist entry would read as stale", allowedEdge)
}
}
@@ -0,0 +1,164 @@
package layering
import (
"slices"
"strings"
)
type layer string
const (
layerFoundation layer = "foundation"
layerContracts layer = "contracts"
layerDomain layer = "domains"
layerIngress layer = "ingress"
layerRuntime layer = "runtime"
layerOperator layer = "operator"
layerAgents layer = "agents"
layerProviders layer = "providers"
layerBootstrap layer = "bootstrap"
layerCmd layer = "cmd"
layerInternal layer = "internal"
layerTestkit layer = "testkit"
layerLegacy layer = "legacy"
// layerTests is valid only as an import target; tests/ is never scanned.
layerTests layer = "tests"
)
// domainKind distinguishes the parts of a domain the rules treat differently.
type domainKind int
const (
notDomain domainKind = iota
domainImpl // domains/<d>/... resource implementation
domainAWSAPI // domains/<d>/awsapi/... AWS action adapters
domainProj // domains/<d>/projection/... authorised view
legacyImpl // handlers/<d>/... legacy domain implementation
legacyAdapter // gateway/<d>/... legacy AWS action adapters
)
type class struct {
layer layer
legacy string // legacy root name when layer is layerLegacy
domain string // owning domain for domain-shaped and agent packages
kind domainKind
}
func (c class) domainShaped() bool { return c.kind != notDomain }
// isLegacy reports whether c sits under one of the named legacy roots.
func (c class) isLegacy(roots ...string) bool {
if c.layer != layerLegacy {
return false
}
if len(roots) == 0 {
return true
}
return slices.Contains(roots, c.legacy)
}
// legacyRoots are pre-ADR-0001 application roots still standing.
var legacyRoots = map[string]bool{
"handlers": true, "gateway": true, "services": true, "utils": true, "daemon": true,
"vpcd": true, "admin": true, "accountteardown": true, "lbagent": true,
}
// gatewayDomains names the domain each gateway/<service> adapter belongs to;
// Bedrock is the AWS surface of the Ochre domain.
var gatewayDomains = map[string]string{
"bedrock": "ochre", "ecs": "ecs", "eks": "eks", "elbv2": "elbv2", "iam": "iam",
"rds": "rds", "sts": "sts", "tagging": "tagging",
}
// runtimeLegacy and operatorLegacy are the legacy roots whose ADR-0001 target
// is runtime/ and operator/ respectively.
var (
runtimeLegacy = []string{"daemon", "vpcd", "services"}
operatorLegacy = []string{"admin", "accountteardown"}
)
// classify maps a module-relative package directory to its layer. ok is false
// for a package that has no deliberate classification.
func classify(full string) (class, bool) {
parts := strings.Split(full, "/")
switch parts[0] {
case "cmd":
return class{layer: layerCmd}, len(parts) >= 2
case "contracts":
return class{layer: layerContracts}, len(parts) >= 2
case "internal":
if len(parts) < 2 {
return class{}, false
}
if parts[1] == "testkit" || parts[1] == "tooling" {
return class{layer: layerTestkit}, true
}
return class{layer: layerInternal}, true
case "tests":
return class{layer: layerTests}, true
case "spinifex":
return classifyApp(parts[1:])
}
return class{}, false
}
func classifyApp(app []string) (class, bool) {
if len(app) == 0 {
return class{}, false
}
switch app[0] {
case "foundation":
return class{layer: layerFoundation}, true
case "ingress":
return class{layer: layerIngress}, true
case "runtime":
return class{layer: layerRuntime}, true
case "operator":
return class{layer: layerOperator}, true
case "providers":
return class{layer: layerProviders}, true
case "bootstrap":
return class{layer: layerBootstrap}, true
case "agents":
c := class{layer: layerAgents}
if len(app) >= 2 {
c.domain = app[1]
}
return c, true
case "domains":
if len(app) < 2 {
return class{}, false
}
c := class{layer: layerDomain, domain: app[1], kind: domainImpl}
if len(app) >= 3 {
switch app[2] {
case "awsapi":
c.kind = domainAWSAPI
case "projection":
c.kind = domainProj
}
}
return c, true
}
if !legacyRoots[app[0]] {
return class{}, false
}
c := class{layer: layerLegacy, legacy: app[0]}
switch {
case app[0] == "handlers" && len(app) >= 2:
c.domain, c.kind = app[1], legacyImpl
case app[0] == "gateway" && len(app) >= 2 && gatewayDomains[app[1]] != "":
c.domain, c.kind = gatewayDomains[app[1]], legacyAdapter
}
return c, true
}
// fullPath reverses shortName for classification.
func fullPath(name string) string {
top, _, _ := strings.Cut(name, "/")
switch top {
case "cmd", "contracts", "internal", "tests", "docs":
return name
}
return "spinifex/" + name
}
@@ -0,0 +1,113 @@
package layering
import (
"os"
"path/filepath"
"sort"
"strings"
"testing"
)
// frozenLegacyPackages is every production package still under a legacy root.
// It only shrinks: a new entry is a new legacy package, a missing one is a
// completed move whose line must be deleted.
var frozenLegacyPackages = []string{
"accountteardown",
"admin",
"daemon",
"gateway",
"gateway/bedrock",
"gateway/ecs",
"gateway/eks",
"gateway/elbv2",
"gateway/iam",
"gateway/rds",
"gateway/spx",
"gateway/sts",
"gateway/tagging",
"handlers/ecs",
"handlers/ecs/bus",
"handlers/eks",
"handlers/elbv2",
"handlers/iam",
"handlers/iam/mock",
"handlers/rds",
"handlers/sts",
"lbagent",
"services/viperblockd",
"services/viperblockd/vbwire",
"utils",
"vpcd",
}
// frozenUtilsFiles are the only production files utils may hold; each awaits
// the owner named in the migration record's close-out table.
var frozenUtilsFiles = []string{"ec2_subject.go", "encryption.go", "vpcd_event.go"}
// TestADR0001_LegacyRootsFrozen: the current-to-target map gives every legacy
// root a destination, so none may gain a package and utils no new file.
func TestADR0001_LegacyRootsFrozen(t *testing.T) {
root, err := moduleRoot()
if err != nil {
t.Fatal(err)
}
g, err := loadGraph(root)
if err != nil {
t.Fatal(err)
}
present := map[string]bool{}
for name, dir := range g.pkgs {
if c, ok := classify(dir); ok && c.layer == layerLegacy {
present[name] = true
}
}
if len(present) == 0 {
t.Fatal("found no legacy packages; the freeze would pass vacuously")
}
frozen := map[string]bool{}
for _, p := range frozenLegacyPackages {
frozen[p] = true
if !present[p] {
t.Errorf("legacy package %s no longer exists; delete it from frozenLegacyPackages", p)
}
}
for p := range present {
if !frozen[p] {
t.Errorf("ADR-0001 current-to-target map: %s is a new package under a legacy root; create it at its ADR-0001 target home instead", p)
}
}
entries, err := os.ReadDir(filepath.Join(root, "spinifex", "utils"))
if err != nil {
t.Fatal(err)
}
var files []string
for _, e := range entries {
name := e.Name()
if e.IsDir() {
t.Errorf("ADR-0001 utils row \"no new utils replacement\": utils/%s is a new directory; give the code a named owner instead", name)
continue
}
if strings.HasSuffix(name, ".go") && !strings.HasSuffix(name, "_test.go") {
files = append(files, name)
}
}
sort.Strings(files)
allowedFiles := map[string]bool{}
for _, f := range frozenUtilsFiles {
allowedFiles[f] = true
}
have := map[string]bool{}
for _, f := range files {
have[f] = true
if !allowedFiles[f] {
t.Errorf("ADR-0001 utils row \"dissolve by responsibility; no new utils replacement\": utils/%s is new; move it to its owner", f)
}
}
for _, f := range frozenUtilsFiles {
if !have[f] {
t.Errorf("utils/%s has moved out; delete it from frozenUtilsFiles", f)
}
}
}
@@ -0,0 +1,170 @@
package layering
import "slices"
// rule is one ADR-0001 dependency rule over a classified import edge.
type rule struct {
id string // subtest name, led by the ADR-0001 clause it encodes
clause string // the ADR text the rule enforces, quoted in failures
hint string // one-line fix direction
// subject reports whether an importer is governed by the rule; the
// non-empty guard requires at least one governed package per rule.
subject func(from class, fromName string) bool
// forbids reports whether the rule rejects the edge.
forbids func(from, to class, fromName string) bool
}
// awsgwRole is the composition root ADR-0002 lets wire domain registrations.
const awsgwRole = "runtime/roles/awsgw"
// qualificationBinaries are the developer/qualification mains ADR-0001 lets
// keep reusable source in internal/testkit or internal/tooling.
var qualificationBinaries = map[string]bool{
"cmd/aws-model-coverage": true, "cmd/dhcptest": true, "cmd/spx-loadgen": true,
}
func isLayer(c class, layers ...layer) bool {
return slices.Contains(layers, c.layer)
}
// importsDomainImplementation is any domain-owned package other than a named
// projection, in its target or legacy home.
func importsDomainImplementation(to class) bool {
return to.domainShaped() && to.kind != domainProj
}
var rules = []rule{
{
id: "R1_FoundationImportsOnlyFoundation",
clause: "rule 1: foundation imports neither domains, ingress, runtime nor operator (enforced conservatively: foundation imports no module package above foundation)",
hint: "move the dependency's needed primitive into foundation or invert it through a parameter",
subject: func(f class, _ string) bool { return f.layer == layerFoundation },
forbids: func(_, t class, _ string) bool { return t.layer != layerFoundation },
},
{
id: "R2_IngressImportsNoImplementation",
clause: "rule 2: ingress/aws imports no domain implementation; domains supply their own action registration through the ingress registration contract",
hint: "take the capability through the registration contract wired by runtime/roles/awsgw",
subject: func(f class, _ string) bool { return f.layer == layerIngress },
forbids: func(_, t class, _ string) bool {
return !isLayer(t, layerFoundation, layerContracts, layerIngress)
},
},
{
id: "R3_DomainImportsNoOtherDomainImplementation",
clause: "rule 3: a domain does not read another domain's private records, migrations or repository; it uses a consumer-owned capability, a named projection, or a versioned contracts/<domain>/v1 contract",
hint: "declare a narrow capability in the consumer, or import the owner's projection or contracts/<domain>/v1",
subject: func(f class, _ string) bool { return f.domainShaped() },
forbids: func(f, t class, _ string) bool {
return f.domainShaped() && importsDomainImplementation(t) && t.domain != f.domain
},
},
{
id: "R4_ProviderImportsNoDomainImplementation",
clause: "rule 4: a provider adapter implements a provider contract and cannot acquire AWS-visible resource authority by reading a domain's private state",
hint: "pass the needed values into the provider contract instead of importing the domain",
subject: func(f class, _ string) bool { return f.layer == layerProviders },
forbids: func(_, t class, _ string) bool { return t.domainShaped() || t.isLegacy() },
},
{
id: "R5_DomainImportsNoRuntimeOrOperator",
clause: "rule 5: operator and runtime are composition consumers; they wire domain modules, so a domain does not import them",
hint: "expose the runtime or operator state through a domain-owned projection or a capability wired at the composition root",
subject: func(f class, _ string) bool { return f.domainShaped() },
forbids: func(f, t class, _ string) bool {
return f.domainShaped() && (isLayer(t, layerRuntime, layerOperator) ||
t.isLegacy(runtimeLegacy...) || t.isLegacy(operatorLegacy...))
},
},
{
id: "R5_AWSAPIAdaptersImportedOnlyByOwnerOrComposition",
clause: "rule 5: operator and runtime call public use cases; a domain's awsapi action adapters are owned by that domain and wired only by the composition root",
hint: "call an owner-provided capability instead of the AWS action adapter",
subject: func(_ class, _ string) bool { return true },
forbids: func(f, t class, fromName string) bool {
if t.kind != domainAWSAPI || fromName == awsgwRole {
return false
}
return !f.domainShaped() || f.domain != t.domain
},
},
{
id: "R5_OperatorImportsNoLegacyImplementation",
clause: "rule 5 and the cmd/spinifex map row: operator use cases reach domains through public capabilities and do not read domain-private state",
hint: "reach the domain through its public capability; do not import a legacy implementation root",
subject: func(f class, _ string) bool { return f.layer == layerOperator },
forbids: func(f, t class, _ string) bool { return f.layer == layerOperator && t.isLegacy() },
},
{
id: "R6_ProductionImportsNoTestkit",
clause: "rule 6: test support is under internal/testkit; production packages do not import it",
hint: "move the shared code to its production owner or keep the import in a _test.go file",
subject: func(f class, n string) bool { return f.layer != layerTestkit && !qualificationBinaries[n] },
forbids: func(f, t class, n string) bool {
return f.layer != layerTestkit && !qualificationBinaries[n] && isLayer(t, layerTestkit, layerTests)
},
},
{
id: "Contracts_ImportOnlyFoundationAndContracts",
clause: "decision item 1 and the area table: contracts own cross-process vocabulary, not application interfaces, domain persistence or transport implementation",
hint: "keep wire types self-contained; depend only on foundation or another contract",
subject: func(f class, _ string) bool { return f.layer == layerContracts },
forbids: func(_, t class, _ string) bool { return !isLayer(t, layerFoundation, layerContracts) },
},
{
id: "Domains_ImportNoAgentsIngressOrLegacy",
clause: "area table and domain module shape: a domain owns no other domain's implementation; only its awsapi adapters may use the generic ingress/aws machinery",
hint: "depend on a contract or capability; leave ingress use to the domain's awsapi package",
subject: func(f class, _ string) bool { return f.domainShaped() },
forbids: func(f, t class, _ string) bool {
if !f.domainShaped() {
return false
}
switch {
case t.layer == layerAgents || t.isLegacy("lbagent", "utils"):
return true
case t.layer == layerIngress:
return f.kind != domainAWSAPI && f.kind != legacyAdapter
case t.isLegacy("gateway") && !t.domainShaped():
return true
case t.isLegacy("handlers", "gateway"):
return f.layer == layerDomain
}
return false
},
},
{
id: "Agents_ImportNoDomainOrLegacyImplementation",
clause: "area table: agents/<domain> own in-guest and service-role behaviour, not tenant API authority or another domain's private state",
hint: "move the shared wire vocabulary behind a guest/controller contract under contracts/",
subject: func(f class, _ string) bool { return f.layer == layerAgents || f.isLegacy("lbagent") },
forbids: func(f, t class, _ string) bool {
return (f.layer == layerAgents || f.isLegacy("lbagent")) && (t.domainShaped() || t.isLegacy())
},
},
{
id: "Q22_STSImportsNoEKSImplementation",
clause: "Q-22 prohibits the STS-to-EKS dependency in its present form; cut it through an identity-owned contract or an EKS projection",
hint: "consume an EKS projection or an identity-owned contract instead of the EKS implementation",
subject: func(f class, _ string) bool { return f.domainShaped() && f.domain == "sts" },
forbids: func(f, t class, _ string) bool {
return f.domainShaped() && f.domain == "sts" && t.domain == "eks" &&
(importsDomainImplementation(t) || t.layer == layerAgents)
},
},
{
id: "Interim_DaemonGatewayHandlersDirection",
clause: "during migration the existing daemon -> gateway -> handlers rule remains the guardrail (Q-20, Q-29)",
hint: "keep the dependency pointing daemon -> gateway -> handlers; invert it through a callback or capability",
subject: func(f class, _ string) bool { return f.isLegacy("handlers", "gateway") },
forbids: func(f, t class, _ string) bool {
switch {
case f.isLegacy("handlers"):
return t.isLegacy("gateway", "daemon")
case f.isLegacy("gateway"):
return t.isLegacy("daemon")
}
return false
},
},
}