ai-powered-conversational-intelligence

PROMPT 49 — ENTERPRISE WORKFLOW AUTOMATION

Role

Act as a Principal AI Architect, Enterprise Data Platform Architect and Senior Product Engineer.

Mission

Turn recommendations into governed workflows. Inspect recommendation lifecycle, RBAC, audit and available connectors. Implement proposed→approval-required→approved→assigned→in-progress→completed/rejected/expired. Support owners, due dates, comments, external task references and outcome measurement. Require approval for consequential actions and never permit uncontrolled autonomous execution. Test authorization, retries, duplicate events and audit.

Mandatory workflow

INSPECT → PLAN → IMPLEMENT → TEST → REVIEW → FIX → DOCUMENT → REPORT

Mandatory controls

§0. Concurrent-work note

This prompt was executed in the same shared working tree as a concurrent session building kpi_monitoring/ (new top-level package) plus edits to config/settings.py and semantic/intelligence/risk.py. Confirmed via git diff --stat on every file this prompt also touched (api/main.py, identity/models.py, identity/rbac.py, pyproject.toml) that the two sessions’ hunks never overlap – each diff is cleanly attributable to one session or the other, byte for byte. Nothing in kpi_monitoring/ was read, edited, or committed by this prompt; nothing in config/settings.py/semantic/intelligence /risk.py was touched. The commit for this prompt stages only the files this prompt’s own work produced.

§1. INSPECT — what already existed

The governed recommendation lifecycle (Prompt 18, extended by Prompt 31) was the mission’s own named starting point: recommendation/governance.py (the pure RecommendationStatus enum + VALID_STATUS_TRANSITIONS), recommendation/governance_policy.py (the pure RBAC+ABAC authorize_recommendation_action), identity.models .RecommendationRecord/RecommendationFeedbackEvent (one mutable “current state” row + an append-only audit-event table), identity/repositories/recommendation_governance.py (the race-safe conditional-UPDATE transition functions, owner assignment with independent permission re-checking, notes that never touch status), and api/recommendation_governance.py (9 routes, one authorization dance per route, structured audit logging, per-IP rate limiting on every mutation). This is the exact shape the mission asks for – “inspect recommendation lifecycle, RBAC, audit” – and it is reused by import, never copied: identity/repositories/workflow.py:: create_workflow takes a real identity.models.RecommendationRecord argument and reads recommendation.governance.RecommendationStatus directly to enforce that only an already-ACCEPTED/PARTIALLY_USEFUL recommendation may become a workflow.

RBAC (identity/rbac.py): the *_MANAGE/*_REVIEW two-tier split (ONBOARDING_*/CATALOG_*/RECOMMENDATION_*/GOVERNANCE_*/EVAL_*) is the established pattern for “operational action” vs. “domain judgment” permissions, each seeded onto the analyst/admin base roles via _ANALYST/_ADMIN frozensets. BI_INTEGRATION_MANAGE was inspected as the one exception (a single permission, no review tier) – not applicable here, since the mission explicitly names “require approval for consequential actions” as a mandatory control, which does need a distinct review-tier permission.

Audit: security.audit_log.log_security_event is the one shared structured-logging chokepoint every governed-lifecycle route already calls (event=<feature>_action, ids/action/status-transition only, never content) – reused verbatim, new event name workflow_action.

Available connectors (the mission’s own explicit inspection item): bi_integration/push.py (Prompt 48) is the one real outbound-push precedent in this codebase – push_power_bi/push_looker_webhook, both SSRF-hardened via bi_integration/outbound_safety.py. Inspected in full and found not reusable for “external task references”: it targets a BI dataset/webhook shape (rows of a query result pushed to a reporting tool), not a task-tracking system’s create/update/close API (Jira/ServiceNow/Trello/etc.), and this codebase has no existing connector of that second kind at all. Building one from scratch would mean a new, live, unauthenticated, unverified integration with a specific external vendor – exactly the kind of speculative, unreviewed connector the mission’s own “never permit uncontrolled autonomous execution” control argues against adding casually. Decision: external_system/external_reference_id/external_reference_url are plain, caller-supplied metadata (a label and a link a human opens themselves) – disclosed explicitly, not silently narrowed.

Race/retry-safety precedent: identity/repositories /semantic_catalog.py::_apply_transition (Prompt 27) and identity /repositories/recommendation_governance.py::_apply_conditional_status _update (Prompt 18/31) both independently arrived at the same fix for the same bug class – a plain Python status check followed by an unconditioned UPDATE lets two concurrent callers (or one retried request) both “succeed.” Reused verbatim for workflow_events’s own column shape.

§2. PLAN

  1. workflow/models.py – pure WorkflowStatus/VALID_STATUS_TRANSITIONS/ ACTIVE_STATUSES/WorkflowEventType, mirroring recommendation .governance exactly.
  2. workflow/policy.py – pure WorkflowAction/authorize_workflow_action, mirroring governance_center.policy exactly (including its own Prompt-44-found LIST-vs-VIEW fix, applied from the start here rather than rediscovered).
  3. identity/rbac.py – Permission.WORKFLOW_MANAGE/WORKFLOW_REVIEW, seeded onto _ADMIN/_ANALYST the same two-tier way every sibling pair already is.
  4. identity/models.py – Workflow/WorkflowEvent ORM classes, one mutable “current state” row + one append-only audit table, mirroring RecommendationRecord/RecommendationFeedbackEvent.
  5. A new Alembic migration (k5n8p1q4r7s0, down_revision=j4k7l0m3n6p9) for workflows/workflow_events.
  6. identity/repositories/workflow.py – create_workflow (the eligibility + duplicate-active-workflow checks), the named transition functions (submit_for_approval/approve_workflow/reject_workflow/ start_workflow/complete_workflow/expire_workflow), plus the non-status-changing mutations (add_comment/assign_workflow/ set_due_date/set_external_reference).
  7. api/workflow_schemas.py + api/workflow.py – 12 routes under /workflows, one authorization dance per route, structured audit logging, per-IP rate limiting on every mutation.
  8. api/main.py – register the router.
  9. Tests: pure model/policy unit tests, a real-SQLite repository test file (including the two-Session race/retry proof), a full-HTTP test file, and a cross-cutting tests/security/ regression proving “never permits uncontrolled autonomous execution” by parsing this package’s own source.
  10. CLAUDE.md + this contract document.

Design decisions made explicit before implementing, not discovered mid-build:

§3. IMPLEMENT

workflow/models.py – WorkflowStatus (8 values, the mission’s own exact chain), VALID_STATUS_TRANSITIONS, ACTIVE_STATUSES/ TERMINAL_STATUSES (a clean partition of every status), WorkflowEventType (status_change/comment/owner_assigned/due_date_set/ external_reference_set). Carries the full “never permit uncontrolled autonomous execution” rationale in its own module docstring.

workflow/policy.py – WorkflowAction (CREATE/LIST/VIEW/ SUBMIT_FOR_APPROVAL/APPROVE/REJECT/ASSIGN/START/COMPLETE/ SET_EXTERNAL_REFERENCE/ADD_COMMENT/EXPIRE), authorize_workflow _action – CREATE/LIST authorized by permission alone (no resource yet); every other action requires a tenant match against the resolved workflow’s own tenant_id, denied identically ("cross_tenant") to a genuinely nonexistent one ("workflow_not_found") for anti-enumeration. APPROVE/REJECT are allowed by either WORKFLOW_MANAGE or WORKFLOW_REVIEW (mirrors governance_center.policy ._VIEW_OR_REVIEW_ACTIONS’s own shape) – the module’s own docstring is explicit that this is not a loophole given this codebase’s real role hierarchy (_ADMIN = _ANALYST | {...}), not an overclaimed guarantee.

identity.models.Workflow – id, tenant_id, recommendation_id (FK, ondelete=CASCADE), title/description (immutable), status (8-value enum), owner_user_id (FK, SET NULL), due_date, external_system/external_reference_id/external_reference_url, outcome_summary/outcome_measured_impact (free-form JSON, explicitly caller-reported, never computed), created_by_user_id, timestamps. identity.models.WorkflowEvent – workflow_id (FK, CASCADE), from_status/to_status, event_type, actor_user_id/actor_label, reason, detail (JSON), created_at.

Migration k5n8p1q4r7s0_workflow_automation.py – workflows + workflow_events tables, 5 + 1 indexes, full downgrade().

identity/repositories/workflow.py – create_workflow (eligibility check against RecommendationStatus, duplicate-active-workflow check via ACTIVE_STATUSES, title/description defaulting from the recommendation); _apply_conditional_status_update (the atomic UPDATE ... WHERE id=:id AND status=:expected, generalized with an extra_values dict so complete_workflow can set outcome_summary/ outcome_measured_impact in the same atomic statement as the status change); _transition (the shared per-call-one-event implementation every named transition function delegates to); assign_workflow (handles both the approved -> assigned first-assignment transition and a plain, status-preserving reassignment from assigned/ in_progress, with the owner’s own tenant/active/permission checks re-verified independently of the caller); set_due_date/ set_external_reference/add_comment (all status-preserving).

api/workflow.py – 12 routes: POST /workflows (create), GET /workflows (list, tenant-scoped), GET /workflows/{id}, GET /workflows/{id}/events, POST /workflows/{id}/submit-for-approval, .../approve, .../reject, .../assign, .../due-date, .../start, .../complete, .../expire, .../comments, .../external-reference. Every optional-body route uses the module-level-singleton-default pattern (_DEFAULT_SUBMIT_REQUEST etc.) api/governance.py already established fixing the exact FastAPI-422-on-omitted-body bug Prompt 44 found – applied here from the start.

§4. TEST

Full results: 133/133 new tests passing. Full backend regression (tests/test_identity_bootstrap.py/tests/test_identity_rbac.py, both fully dynamic over SEED_PERMISSIONS/SEED_ROLES) confirmed unaffected by the two new permission codes. ruff/black/mypy/bandit all clean on every new/changed file.

§5. REVIEW / FIX

§6. DOCUMENT

§7. REPORT

Inspected areas: the governed recommendation lifecycle (models, policy, repository, API — Prompts 18/31), identity/rbac.py’s *_MANAGE/*_REVIEW permission-tier convention, security.audit_log’s shared structured-logging chokepoint, and every existing outbound- connector precedent in this codebase (bi_integration/push.py — found not reusable for task-tracking, disclosed rather than forced).

Reused components: recommendation.governance.RecommendationStatus (the eligibility gate), the race-safe conditional-UPDATE pattern from identity/repositories/recommendation_governance.py/semantic_catalog.py, governance_center.policy’s LIST-vs-VIEW action split, security .audit_log.log_security_event, api.rate_limit.enforce_api_action _rate_limit, and the module-level-singleton-default pattern for optional-body routes.

Files changed: workflow/__init__.py, workflow/models.py, workflow/policy.py (new package); identity/models.py (+Workflow/ WorkflowEvent); identity/rbac.py (+2 permissions); identity/migrations/versions/k5n8p1q4r7s0_workflow_automation.py (new); identity/repositories/workflow.py (new); api/workflow_schemas.py, api/workflow.py (new); api/main.py (router registration); pyproject.toml (one ruff config fix); CLAUDE.md; this contract document; 5 new test files (one in tests/security/).

API/DB/config changes: 12 new routes under /workflows; 2 new tables (workflows, workflow_events); 2 new RBAC permission codes (workflow.manage, workflow.review); no new Settings field, no feature flag (an administrative surface gated purely by RBAC, matching api/governance.py/api/semantic_catalog.py/api/recommendation _governance.py’s own precedent).

Tests and results: 133 new tests across 5 files, all passing; ruff/black/mypy/bandit clean; the real local identity Postgres database migrated to the new head (k5n8p1q4r7s0) and RBAC re-seeded, confirmed via a live alembic heads check.

Security/tenant review: every resource-scoped action requires a tenant match, denied identically to a nonexistent resource (anti-enumeration); approval requires a distinct permission from operating; nothing in this feature executes SQL, calls an LLM, or reaches an external system — proven structurally via source-parsing, not just asserted; every mutation is audit-logged without claim/comment/ outcome content and rate-limited per-IP (a disclosed limitation, not a gap unique to this feature — Prompt 31 already named it for its own sibling routes).

Performance/cost impact: negligible — plain CRUD over two new, indexed tables; no new LLM call, no new outbound HTTP call, no change to the /ask//execute request path at all.

Limitations: no live ticketing-system connector (disclosed, not silently narrowed); owner reassignment is last-writer-wins; no scheduled/automated expiry sweep exists anywhere in this codebase (every EXPIRED transition is human-initiated); no frontend surface in this pass.

Remaining risks: none identified beyond the disclosed limitations above — every mandatory control the mission names (reuse-first, RBAC/tenant isolation, untrusted-data framing — not applicable here, since this feature ingests no external documents, evidence/provenance preservation, no inference presented as fact, no secrets, tests, docs) was independently inspected and found satisfied.

Recommended next prompt: a frontend dashboard for this workflow lifecycle (mirroring frontend/src/pages/Recommendations.tsx’s own shape), or wiring the kpi_monitoring/ package currently being built in this same working tree by a concurrent session into this one’s own external_reference/outcome-measurement fields once that work lands.