Skip to content

Commit ed4e1d7

Browse files
committed
docs: lift cross-subtree rules to their common parent
Move the frontend/backend mirrored-contract and backend-authoritative value rules to the root AGENTS.md, the retention coverage owner and the pi.dev/models.dev binding independence to backend/AGENTS.md, and the proxy-key scope and session isolation facts to ARCHITECTURE.md. Remove the restated clauses from the sub guides and link the shutdown and startup gate order to ARCHITECTURE.md.
1 parent 6fb4930 commit ed4e1d7

19 files changed

Lines changed: 22 additions & 20 deletions

File tree

‎AGENTS.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,8 @@ Prism has no automated deployment: operators update the instances by hand, and a
7474
- OpenAI text modes require strict equality across authored model/target relations and runtime gates; operation-coverage diagnostics do not relax this rule. Image capability uses its independent containment rule. See [the native operation contract](docs/runtime-api.md#openai-native-mode-equality-strict).
7575
- `start.sh` owns local PostgreSQL on `15432` and frontend on `5173`, preserves valid selected bootstrap files, and follows their backend port. Full mode unsets `VITE_API_BASE` and enables same-origin Vite proxying; keep launcher changes and docs aligned.
7676
- The root Compose file is the only checked-in local/self-hosted bundle. The root Dockerfile builds one app image with Go, React assets, and Nginx; PostgreSQL remains separate. Container changes must preserve or explicitly update the non-root `1000:1000` and `/app/config/config.json` contract, its docs, and `backend/tests/integration/dockerfile_contract_test.go`.
77+
- Backend contracts mirrored in the frontend change on both sides in one change: the `safediag` fixed credential matcher and the frontend browser matcher; typed auth errors in `backend/internal/httpapi/management/auth/problems.go` and the frontend known-code decoder, recovery classifier, and locale entries, aligned with route, details, retry, and recovery contracts; `managementRouteSpecs` with its generated `management_route_contract.json` and the frontend profile matcher, where artifact changes belong to the backend generator; backend structs and contract tests and the types under `frontend/src/lib/types/`, never repairing a mismatch by inventing frontend aliases.
78+
- Backend-derived pricing, usage, output-rate, and latency values are authoritative. The frontend must not recompute aggregate math or replace missing evidence with zero.
7779
- `release.sh` owns all four version surfaces. `.github/workflows/docker-images.yml` publishes one ARM64 GHCR image; tag releases require green CI. Do not invent separate frontend/backend releases or images.
7880

7981
## Project Documentation Navigation

‎ARCHITECTURE.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,8 +55,8 @@ On shutdown Prism runs these phases in order: HTTP server shutdown, side-effect
5555
## Trust Boundaries
5656

5757
- **Operator Authentication**: Optional cookie-backed authentication for management APIs (`/api/*`). Supports username/password.
58-
- **Proxy API Keys**: Optional API key enforcement for supported runtime operations mounted under `/v1` and `/v1beta`. Keys are issued and managed through the dashboard.
59-
- **Auth Bifurcation**: Management auth (session cookies) and runtime auth (proxy API keys) are separate enforcement paths.
58+
- **Proxy API Keys**: Optional API key enforcement for supported runtime operations mounted under `/v1` and `/v1beta`. Keys are issued and managed through the dashboard. They are global instance credentials, separate from the Default management profile scope.
59+
- **Auth Bifurcation**: Management auth (session cookies) and runtime auth (proxy API keys) are separate enforcement paths. A runtime proxy-key failure, including a `401` on `/v1` or `/v1beta`, never expires or invalidates the management session.
6060
- **Data at Rest**: API keys and secrets are stored in PostgreSQL. Endpoint secrets are encrypted at rest.
6161
- **CORS**: Local browser traffic stays same-origin through the launcher-local Vite proxy in `full` mode; standalone frontend workflows can still target an explicit backend base URL.
6262
- **Safe failure diagnostics**: Failed attempts persist a scrubbed, 4 KiB-bounded error summary through the fixed `safediag` bottom line (Bearer/Basic/JWT/API-key-like/key=value/URL-secret redaction, control-character and whitespace normalization, metadata field scrubbing with provenance arrays) plus request-time Header Blocklist additions; stream failures keep an independent scrubbed `stream_error_detail`. Raw provider bodies are never stored in `error_detail`. The raw upstream error sample the summary is derived from is itself bounded at 32 KiB per attempt (`safediag.MaxUpstreamErrorSampleBytes`, applied as the attempt-lifecycle failed-response sample cap) and stays in memory for that derivation only: it never enters the telemetry outbox or any table. Both caps are code-fixed constants, not settings.

‎backend/AGENTS.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,5 +3,7 @@
33
- Do not move HTTP parsing or profile resolution into domain packages, provider behavior into platform assembly, or feature policy into shared transaction helpers. `pgxutil/tx.go` owns transaction mechanics only; keep `endpointdomain/`, `profiledomain/`, and `providerauth/` narrow shared contracts. `openaimodecheck/` is the read-only native text-mode equality check shared by startup and upgrade preflight.
44
- Keep SQL schema changes under `migrations/` and apply them through `internal/platform/migrate/`. Baseline/history and migration-specific guards protect retained data; an error asking for a rebuild does not authorize a reset.
55
- Keep bootstrap settings separate from PostgreSQL-backed product settings.
6+
- `internal/domain/stats/retention_source.go` is the single cutoff/floor/epoch/purge and actual-coverage owner for Observe, Requests, Audit, Events, Settings, and management jobs. Resolve bounds and coverage through it; policy days, row minima, `MIN(created_at)`, page size, or browser time never prove coverage or reconstruct a floor.
7+
- Keep pi.dev export bindings independent from models.dev metadata and pricing bindings in both domain and management code.
68
- Use `internal/providerauth/` for API-family and native capability rules; external catalog metadata must not decide runtime compatibility.
79
- Changes to upstream request/response behavior need both package-local runtime/provider checks and the operation-shaped external runtime suite, including streaming and non-streaming paths.

‎backend/internal/domain/AGENTS.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ Keep these packages HTTP-neutral: handlers, authentication, profile selection, a
55
- `modelrouting/` owns graph diagnostics and route witnesses. Keep all configured nodes available for recursive Model Targets; `direct_request_enabled` gates client-entry roots and representative witnesses only.
66
- `terminaltarget/upstream_model_id.go` is the shared trim/non-blank/200-rune wire-identity validator. `custom_request_parameters.go` is the shared parser, validator, and shallow overlay; consumers must not fork its protected keys, limits, or canonicalization rules.
77
- `terminaltarget/routing_schedule.go` owns eligibility through `DecideAt`; no windows means unrestricted. Keep compiled schedules immutable and methods on value receivers because runtime snapshots share their backing slices. Pricing windows in `pricing_schedule.go` reuse geometry but belong to pricing revisions and the frozen ingress clock.
8-
- `pidev/` owns catalog transport, revision/schema checks, exact candidates, and bounded same-API model-ID search. `modelexport/` owns deterministic Pi and OpenCode renderers with independent clock-free fact digests. Keep pi.dev bindings independent from models.dev metadata/pricing bindings.
8+
- `pidev/` owns catalog transport, revision/schema checks, exact candidates, and bounded same-API model-ID search. `modelexport/` owns deterministic Pi and OpenCode renderers with independent clock-free fact digests.
99
- Render from the persisted effective Pi template plus caller-supplied Prism origin/provider/credential and current pricing facts. Do not read stored endpoint keys, infer client URLs from upstream endpoints, fetch the live catalog, or trust a request coordinate as anything beyond an assertion against the binding.
1010
- Validate source and override Pi leaves with the pinned schema in `pidev/compat.go` and `modelexport/render_pi_schema.go`. Sanitize catalog compatibility fields through the per-API allowlist, preserve sorted dropped paths, and reject invalid manual overrides. Preserve explicit null versus omitted fields and thinking-level keys.
1111
- Export cost only for one representable USD/PER_1M five-component shape across all reachable targets with reasoning price equal to output price. Missing components omit the entire cost group with a warning; explicit zero stays free. Pi supports at most one strict positive-threshold tier.

‎backend/internal/domain/safediag/AGENTS.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
`matcher.go`, `scrub.go`, `extract.go`, `urls.go`, `metadata.go`, and `limits.go` own the shared credential-redaction boundary for runtime diagnostics, audit capture, and legacy backfill.
44

5-
- Header Blocklist rules may add exact/prefix sensitive names but cannot weaken the fixed matcher. Preserve the non-secret exception and keep the frontend browser matcher aligned.
5+
- Header Blocklist rules may add exact/prefix sensitive names but cannot weaken the fixed matcher. Preserve the non-secret exception.
66
- Scrub before writing metadata, outbox/staging rows, PostgreSQL, logs, traces, or management diagnostics. Provider errors contribute only allowlisted scrubbed scalars, never raw error bodies.
77
- Truncate on UTF-8 code-point boundaries and retain the fixed byte/codepoint limits.
88
- Diagnostic redaction uses `[REDACTED]`; do not substitute secret hashes, prefixes, or lengths. The separate `CustomHeaderRedactedValue` sentinel is the write-only management header contract: submitting it preserves the stored header value.

‎backend/internal/domain/stats/AGENTS.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,12 @@
44
- Canonical money requires `pricing_status=priced` and trusted pricing evidence; ingress/final groupings are non-additive projections of one served-final fact and attempts make no cost claim. Trusted zero has a sample and a non-null zero; no trusted sample is null.
55
- Preserve row-scoped status and duration through `request_log_scope.go`; never coalesce upstream/gateway/legacy statuses. Preserve the separate stream completion and response-header duration evidence. Final-execution latency joins the finalized attempt by profile, ingress ID, and attempt number, with missing samples when request history has expired.
66
- `request_logs.go` and `request_logs_chain_cohort.go` own retained filters: same-key lists are OR, different keys are AND, `__null__` means unattributed, and caller `client_rule_id` remains separate from targets. Keep ingress, attempt-target, and finalized-target model filters distinct; reject retired ambiguous model keys and the `priced` alias at the HTTP boundary.
7-
- `retention_source.go` is the shared cutoff/floor/epoch/purge owner for Observe, Requests, Audit, Events, and Settings. Never reconstruct floors from policy days or `MIN(created_at)`; reads fail closed while purge is running or recovery is required.
7+
- Retention reads through `retention_source.go` fail closed while purge is running or recovery is required.
88
- `RefreshActualCoverageProjection` and `RecordActualCoverageAppend` in `retention_source.go` own bounded refresh and the same-transaction append handoff. Preserve source/coverage revisions, hash, generation/fence, materialization cut, freshness, and gaps; consumers must not synthesize intervals or zero counts.
99
- `observe_query_context.go` owns opaque query-context signing. Fragments use resolved bounds instead of re-parsing presets; retention final publication revokes stale tokens with the dataset snapshot error.
1010
- `request_logs_chain*.go` owns whole-ingress outer pages, bounded retained-row inner pages, and finalized summaries from usage events. Bind cursors to the complete normalized cohort/window, profile, order, page size, and retention generation; items, totals, and CSV apply the same cohort selectors and must select the same complete chains. The `created_at` outer page is ordered by the finalized event and merges retained-only chains; its totals and CSV stay keyed by retained rows, so a chain finalizing across the window's upper edge can differ. Metric ranking uses the same retained cohort for page, totals, availability counts and CSV; it never sums parent and attempt cost, and cost groups retain currency/epoch identity. Cursor versions bind the applicable ordering.
1111
- `request_logs_export.go` requires one read-only repeatable-read snapshot for bounds, count, and spool. Finish typed rejection and spool verification before file bytes; the 31-day limit is export-specific and exact-ingress reads use the retained-history boundary.
1212
- `cost_segments.go` and `classifier.go` must classify epochs and null/non-canonical currency identically in Go and SQL. Retained cost-segment/card-role/selection-state filters reuse canonical predicates; cost-segment selection alone does not change the ingress source.
1313
- `observe_usage_summary_segments.go` derives selected-card-role cost breakdown in the same aggregate statement from trusted usage evidence. Attempt errors/series preserve replay filters and calculate Top-N/Other from the full denominator.
14-
- Keep backend-derived pricing, usage, output-rate, and latency values authoritative. Preserve measured-sample counts and null gaps; frontend presentation must not recompute aggregate math or replace missing evidence with zero.
14+
- Preserve measured-sample counts and null gaps.
1515
- Dashboard aggregate snapshots and recent activity remain separate read models. Activity uses finalized ingress events, not a reconstruction from attempt rows.

‎backend/internal/httpapi/management/audit/AGENTS.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
Job execution belongs to `../../../platform/managementjobs/`.
44

5-
- Keep list query parsing bounded and descending-only, rejecting unsupported filters. Resolve the SQL interval and coverage from the shared actual-coverage owner in the same repeatable-read transaction; a retention floor alone does not prove actual history coverage.
5+
- Keep list query parsing bounded and descending-only, rejecting unsupported filters. Resolve the SQL interval and coverage from the shared actual-coverage owner in the same repeatable-read transaction.
66
- Preserve the request-time audit-capture check when a lookup is tied to a request log. Missing capture is distinct from an empty audit result.
77
- Raw-body downloads serve the exact stored byte prefix with safe attachment and private/no-store headers; do not reinterpret or reconstruct the payload.
88
- Global retention-job queries require `scope=global` and `type=log_retention` together. Keep their signed evidence paging distinct from ordinary profile job reads.

‎backend/internal/httpapi/management/auth/AGENTS.md‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,10 @@
22

33
Keep management session enforcement in `management_auth_middleware.go` and runtime proxy-key enforcement/attribution in `runtime_middleware.go`. Use `runtime_cache.go` for published runtime decisions rather than querying management state from runtime handlers.
44

5-
- `problems.go` owns typed auth errors. Keep the frontend known-code decoder, recovery classifier, and locale entries aligned with route, details, retry, and recovery contracts.
65
- Public auth status is the tagged `enabled|disabled|transition_fail_closed` union. Authenticated session responses carry the server-authored `subject_key`; public and anonymous responses do not.
76
- `enabling_fail_closed` and `rollback_required` block ordinary management while auth control, status, and operation recovery remain reachable. `disabling_enforced` retains the old enabled gate.
87
- Preserve the transaction in `auth_settings_transaction.go`: affected Requests/Audit writer admission, Proxy readiness fence, replay check, immutable staging/session changes, operation recording, and final pointer publication. Transaction commit is the linearization point; cache and cookie publication occurs afterward in `auth_settings_publish.go`.
98
- Readiness comes from `proxy_key_readiness_fence.go`, using one server-clock count and the 30-second safe-active horizon. Key mutations acquire the same fence before the auth-control singleton; do not invent another activation predicate.
109
- Proxy-key rotation updates the same row so retained attribution keeps a stable logical key id. Preserve serialized capacity, presence-aware expiry (omitted preserves, null clears), and private/no-store one-time create/rotate responses.
11-
- Auth-off runtime traffic still carries honest `identified|none|unknown` attribution with per-request `AuthEnforced`. Optional lookup failure permits execution with unknown identity; enforcement failure rejects. A proxy-key 401 is never management session expiry.
10+
- Auth-off runtime traffic still carries honest `identified|none|unknown` attribution with per-request `AuthEnforced`. Optional lookup failure permits execution with unknown identity; enforcement failure rejects.
1211
- Keep cookies, tokens, request tokens, and key helpers here. Return only metadata or newly generated one-time values.

‎backend/internal/httpapi/management/models/AGENTS.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ Keep model CRUD and graph authoring here; private Terminal Target writes stay in
77
- Preserve strict OpenAI text-mode equality across direct, inbound, and disabled relations. `graph_integrity.go` blocks mode changes that break existing relations; image-operation containment is an independent gate.
88
- Composite create includes the initial Terminal Target in the same transaction and uses the connections package's presence-aware validation. Warnings describe the final proposed graph and remain structured, non-persisted codes.
99
- Routing diagnostics and readiness consume `../../../domain/modelrouting/` and the runtime registry's read-only route-witness projection. Do not create a second operation catalog or make a diagnostic read invalidate runtime planning.
10-
- Keep models.dev `catalog_*.go` / `model_catalog_bindings` independent from pi.dev `export_pi_binding_*.go` / `model_pi_catalog_bindings`. Both are management metadata; their writes remain planning-neutral and their responses private/no-store.
10+
- models.dev (`catalog_*.go`, `model_catalog_bindings`) and pi.dev (`export_pi_binding_*.go`, `model_pi_catalog_bindings`) bindings are both management metadata; their writes remain planning-neutral and their responses private/no-store.
1111
- Fetch remote catalogs outside transactions. models.dev writes lock model then binding and recheck confirmed identity, coordinate, catalog revision, and binding token as applicable; refresh changes source fields without overwriting concurrent overrides.
1212
- Pi bind verifies trusted catalog revision plus current Prism id/final Pi API under lock. Default discovery matches full id case-sensitively and requires a unique candidate; explicit coordinates may cross directory model ids only when the final Pi API matches. Search is bounded discovery and never selects or binds.
1313
- Pi refresh replaces source fields only after the full preview CAS. Sparse overrides survive refresh, null restores a source field, coordinate changes clear overrides, and same-coordinate identity reconfirmation does not refresh frozen source data.

0 commit comments

Comments
 (0)