ai-powered-conversational-intelligence

18 — Recommendation Governance & Feedback

Prompt 18 of the 32-prompt Enterprise AI Analytics & Recommendation Platform initiative (00_MASTER_IMPLEMENTATION_CONTRACT.md), following 17_RECOMMENDATION_ENGINE_CONTRACT.md. Two new pure modules (recommendation/governance.py, recommendation/governance_policy.py), two new identity-DB tables (RecommendationRecord/ RecommendationFeedbackEvent, migration f3a6b9c2d8e1), a new repository (identity/repositories/recommendation_governance.py), a new REST surface (api/recommendation_governance.py), and additive /ask-pipeline wiring (api/recommendation_persistence.py) that persists Prompt 17’s already-computed recommendations for a locally- authenticated caller. No existing route, node, or response field changed shape; AskResponse is unchanged, and every existing caller of recommendation.models.Recommendation keeps working unmodified.

1. Inspection: what already existed vs. the real gap

Prompt 17’s recommendation.engine.generate_recommendations is a pure, per-request function — its output (AskResponse.recommendations) is computed, validated, and returned, then gone; nothing in this codebase persisted a recommendation anywhere, so there was no way for a human to give feedback on a specific recommendation instance across requests, nor any way to measure recommendation quality over time. The closest existing precedents, inspected directly:

The one real design decision, made explicitly rather than assumed: master rule (“feedback must not automatically alter production rules from a single event”) requires that RecommendationFeedbackEvent rows never feed back into recommendation.engine’s own rules/thresholds. Resolved structurally, not by convention: the only read path over that table is quality_metrics_for_tenant (plain counts), and no code anywhere in this codebase reads a feedback event and writes to config.settings.Settings or a recommendation.engine rule constant. Any future auto-tuning feature would have to be built as its own new, reviewed decision — nothing here wires it, even implicitly.

2. What was built

recommendation/governance.py (new, pure)

RecommendationStatus — the exact eight values: GENERATED, REVIEWED, ACCEPTED, REJECTED, PARTIALLY_USEFUL, INCORRECT, RESOLVED, EXPIRED. VALID_STATUS_TRANSITIONS:

GENERATED        -> {REVIEWED, ACCEPTED, REJECTED, PARTIALLY_USEFUL, INCORRECT, EXPIRED}
REVIEWED         -> {ACCEPTED, REJECTED, PARTIALLY_USEFUL, INCORRECT, EXPIRED}
ACCEPTED         -> {RESOLVED, EXPIRED}
PARTIALLY_USEFUL -> {RESOLVED, EXPIRED}
REJECTED / INCORRECT / RESOLVED / EXPIRED -> {}  (terminal)

FEEDBACK_VERDICT_STATUSES (the five POST .../feedback accepts) and TERMINAL_STATUSES/is_terminal_status are derived, named subsets — RESOLVED/EXPIRED are deliberately excluded from the general feedback endpoint and given their own dedicated routes (.../resolve, .../expire) instead, since “the fix was actually carried out” and “this is stale/administratively retired” are different kinds of claims than a quality verdict, worth their own request shape and permission check.

recommendation/governance_policy.py (new, pure RBAC+ABAC)

authorize_recommendation_action — deny-by-default, mirrors semantic.catalog_policy.authorize_catalog_action exactly. Two new permissions in identity/rbac.py: Permission.RECOMMENDATION_REVIEW (analyst+: view, submit feedback, mark resolved — domain judgment) and Permission.RECOMMENDATION_MANAGE (admin-only: force-expire — an administrative override). Both seed automatically via the existing idempotent identity.bootstrap.seed_rbac on next app startup (verified live — see §3). Every action beyond none requires security.tenancy.resolve_actor_tenant_id to match RecommendationRecord.tenant_id; a cross-tenant or nonexistent record is denied identically ("cross_tenant"/"record_not_found" → the route layer maps both to a 404, anti-enumeration, matching api/semantic_ catalog.py’s own precedent).

identity/models.py (two new tables) + migration f3a6b9c2d8e1

identity/repositories/recommendation_governance.py (new)

create_record (the only creation path — see §2’s API section for why), submit_feedback/mark_resolved/expire_record (each enforces VALID_STATUS_TRANSITIONS via _assert_transition_valid, raising InvalidRecommendationStatusTransitionError on an illegal move — defense in depth behind the API layer’s own pre-flight check, mirroring identity/repositories/semantic_catalog.py’s identical posture), list_records/get_record_by_id/list_feedback_events (plain, tenant- scoped reads), and quality_metrics_for_tenant — a read-only aggregate (counts by status, counts by (category, status), an acceptance_rate that is None, never 0.0, when nothing has been judged yet) that is the one and only consumer of RecommendationFeedbackEvent rows in this codebase, structurally proving the “never alters production rules” requirement (see §1).

api/recommendation_governance.py + api/recommendation_governance_schemas.py (new)

Seven routes under /recommendations, each doing exactly one authorization dance (resolve by id → authorize_recommendation_action → act only on allowed=True):

Route Permission Purpose
GET /recommendations REVIEW or MANAGE List the caller’s tenant’s records
GET /recommendations/metrics REVIEW or MANAGE Quality rollup (registered before /{record_id} so the literal path segment is never swallowed as a malformed UUID)
GET /recommendations/{id} REVIEW or MANAGE (ABAC) One record
GET /recommendations/{id}/events REVIEW or MANAGE (ABAC) Full audit trail
POST /recommendations/{id}/feedback REVIEW or MANAGE (ABAC) A reviewed/accepted/rejected/partially_useful/incorrect verdict
POST /recommendations/{id}/resolve REVIEW or MANAGE (ABAC) accepted/partially_useful → resolved
POST /recommendations/{id}/expire MANAGE only (ABAC) Any non-terminal → expired

There is deliberately no create/ingest route — a RecommendationRecord is only ever created by the live /ask pipeline’s own already- Permission.ASK-gated call (below), never by a caller hitting this surface directly; authorize_recommendation_action has no CREATE action to recognize at all.

api/recommendation_persistence.py + /ask wiring (new, additive)

persist_ask_recommendations — called from POST /ask immediately after the existing persist_ask_turn (chat-history) call, wrapped in the identical try/except-log-and-continue shape. Reconstructs recommendation.models.Recommendation objects from AskResponse.recommendations’s own dicts and calls create_record once per recommendation, for a locally-authenticated caller only (AuthIdentity.mode == "local" and Settings.local_auth_enabled) — identical scoping to persist_ask_turn, for the identical reason (no identity.users row, no resolved tenant, for any other caller mode). A malformed recommendation dict is logged and skipped, never fatal to the rest. New Settings.enable_recommendation_persistence (default True) is the operator escape hatch.

3. Testing

tests/test_recommendation_governance_model.py (28 tests) — every required status exists; every allowed/disallowed transition pair; terminal-status set; feedback-verdict subset.

tests/test_recommendation_governance_policy.py (18 tests) — RBAC (review vs. manage vs. neither, per action), ABAC (missing/mismatched/ None tenant, all denied with the correct reason code), unrecognized action.

tests/test_identity_repositories_recommendation_governance.py (25 tests, real in-memory SQLite) — creation + initial audit event + system- actor labeling, evidence-version determinism, list/get/filter, every legal transition, illegal-transition/terminal-status rejection, resolve/expire (including a None-user-id system actor), and the quality-metrics aggregate (counts, acceptance rate, None when unjudged, tenant/database scoping, and a direct proof that reading metrics never mutates a record).

tests/test_api_recommendation_governance.py (20 tests, real TestClient

tests/test_recommendation_persistence.py (9 tests, real in-memory SQLite) — successful persistence, zero-recommendations no-op, OIDC identity skipped, local_auth_enabled=False skipped, the feature flag off, a malformed recommendation dict skipped without blocking the rest, an unreachable identity DB failing open, a non-UUID subject failing open, and the database=None → "default" fallback.

Live-verified against the real, configured PostgreSQL identity database (AUTH_DATABASE_URL), not only SQLite: alembic -c identity/ alembic.ini upgrade head ran the full pending chain — this also revealed and applied three prior prompts’ migrations (c4d8e1f6a9b3/onboarding, d5e9f2a7b4c1/semantic-catalog, e8f1c3a6d9b2/catalog-metric-fields) that had never actually been applied to this real database before, in addition to this prompt’s own f3a6b9c2d8e1 — confirmed at head afterward, with both new tables present in information_schema.tables. identity.bootstrap.seed_rbac was then run directly against that same real database and confirmed both new permission codes (recommendation.review/recommendation .manage) now exist in permissions.

Full regression suite reran clean after every change: 3272/3272 backend tests passing (up from 3172 before this prompt — 100 new tests), 0 new mypy errors outside test files, 0 ruff findings, 0 bandit findings, black --check clean.

4. Known, disclosed limitations (not oversights)